1 #!/usr/bin/env python 2 3 """ 4 Translate programs. 5 6 Copyright (C) 2015, 2016 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 from common import * 23 from encoders import * 24 from os.path import exists, join 25 from os import makedirs 26 from referencing import Reference 27 import compiler 28 import results 29 30 class Translator(CommonOutput): 31 32 "A program translator." 33 34 def __init__(self, importer, deducer, optimiser, output): 35 self.importer = importer 36 self.deducer = deducer 37 self.optimiser = optimiser 38 self.output = output 39 40 def to_output(self): 41 output = join(self.output, "src") 42 43 if not exists(output): 44 makedirs(output) 45 46 self.check_output() 47 48 for module in self.importer.modules.values(): 49 parts = module.name.split(".") 50 if parts[0] != "native": 51 tm = TranslatedModule(module.name, self.importer, self.deducer, self.optimiser) 52 tm.translate(module.filename, join(output, "%s.c" % module.name)) 53 54 # Classes representing intermediate translation results. 55 56 class TranslationResult: 57 58 "An abstract translation result mix-in." 59 60 def get_accessor_kinds(self): 61 return None 62 63 class ReturnRef(TranslationResult): 64 65 "Indicates usage of a return statement." 66 67 pass 68 69 class Expression(results.Result, TranslationResult): 70 71 "A general expression." 72 73 def __init__(self, s): 74 self.s = s 75 def __str__(self): 76 return self.s 77 def __repr__(self): 78 return "Expression(%r)" % self.s 79 80 class TrResolvedNameRef(results.ResolvedNameRef, TranslationResult): 81 82 "A reference to a name in the translation." 83 84 def __init__(self, name, ref, expr=None, parameter=None): 85 results.ResolvedNameRef.__init__(self, name, ref, expr) 86 self.parameter = parameter 87 88 def __str__(self): 89 90 "Return an output representation of the referenced name." 91 92 # For sources, any identified static origin will be constant and thus 93 # usable directly. For targets, no constant should be assigned and thus 94 # the alias (or any plain name) will be used. 95 96 ref = self.static() 97 origin = ref and self.get_origin() 98 static_name = origin and encode_path(origin) 99 100 # Determine whether a qualified name is involved. 101 102 t = (not self.is_constant_alias() and self.get_name() or self.name).rsplit(".", 1) 103 parent = len(t) > 1 and t[0] or None 104 attrname = t[-1] and encode_path(t[-1]) 105 106 # Assignments. 107 108 if self.expr: 109 110 # Eliminate assignments between constants. 111 112 if ref and isinstance(self.expr, results.ResolvedNameRef) and self.expr.static(): 113 return "" 114 115 # Qualified names must be converted into parent-relative assignments. 116 117 elif parent: 118 return "__store_via_object(&%s, %s, %s)" % ( 119 encode_path(parent), encode_symbol("pos", attrname), self.expr) 120 121 # All other assignments involve the names as they were given. 122 123 else: 124 return "(%s%s) = %s" % (self.parameter and "*" or "", attrname, self.expr) 125 126 # Expressions. 127 128 elif static_name: 129 parent = ref.parent() 130 context = ref.has_kind("<function>") and encode_path(parent) or None 131 return "((__attr) {%s, &%s})" % (context and "&%s" % context or "0", static_name) 132 133 # Qualified names must be converted into parent-relative accesses. 134 135 elif parent: 136 return "__load_via_object(&%s, %s)" % ( 137 encode_path(parent), encode_symbol("pos", attrname)) 138 139 # All other accesses involve the names as they were given. 140 141 else: 142 return "(%s%s)" % (self.parameter and "*" or "", attrname) 143 144 class TrConstantValueRef(results.ConstantValueRef, TranslationResult): 145 146 "A constant value reference in the translation." 147 148 def __str__(self): 149 return encode_literal_constant(self.number) 150 151 class TrLiteralSequenceRef(results.LiteralSequenceRef, TranslationResult): 152 153 "A reference representing a sequence of values." 154 155 def __str__(self): 156 return str(self.node) 157 158 class TrInstanceRef(results.InstanceRef, TranslationResult): 159 160 "A reference representing instantiation of a class." 161 162 def __init__(self, ref, expr): 163 164 """ 165 Initialise the reference with 'ref' indicating the nature of the 166 reference and 'expr' being an expression used to create the instance. 167 """ 168 169 results.InstanceRef.__init__(self, ref) 170 self.expr = expr 171 172 def __str__(self): 173 return self.expr 174 175 def __repr__(self): 176 return "TrResolvedInstanceRef(%r, %r)" % (self.ref, self.expr) 177 178 class AttrResult(Expression, TranslationResult): 179 180 "A translation result for an attribute access." 181 182 def __init__(self, s, refs, accessor_kinds): 183 Expression.__init__(self, s) 184 self.refs = refs 185 self.accessor_kinds = accessor_kinds 186 187 def get_origin(self): 188 return self.refs and len(self.refs) == 1 and first(self.refs).get_origin() 189 190 def has_kind(self, kinds): 191 if not self.refs: 192 return False 193 for ref in self.refs: 194 if ref.has_kind(kinds): 195 return True 196 return False 197 198 def get_accessor_kinds(self): 199 return self.accessor_kinds 200 201 def __repr__(self): 202 return "AttrResult(%r, %r)" % (self.s, self.get_origin()) 203 204 class PredefinedConstantRef(AttrResult): 205 206 "A predefined constant reference." 207 208 def __init__(self, value): 209 self.value = value 210 211 def __str__(self): 212 if self.value in ("False", "True"): 213 return encode_path("__builtins__.boolean.%s" % self.value) 214 elif self.value == "None": 215 return encode_path("__builtins__.none.%s" % self.value) 216 elif self.value == "NotImplemented": 217 return encode_path("__builtins__.notimplemented.%s" % self.value) 218 else: 219 return self.value 220 221 def __repr__(self): 222 return "PredefinedConstantRef(%r)" % self.value 223 224 class BooleanResult(Expression, TranslationResult): 225 226 "A expression producing a boolean result." 227 228 def __str__(self): 229 return "__builtins___bool_bool(%s)" % self.s 230 231 def __repr__(self): 232 return "BooleanResult(%r)" % self.s 233 234 def make_expression(expr): 235 236 "Make a new expression from the existing 'expr'." 237 238 if isinstance(expr, results.Result): 239 return expr 240 else: 241 return Expression(str(expr)) 242 243 # The actual translation process itself. 244 245 class TranslatedModule(CommonModule): 246 247 "A module translator." 248 249 def __init__(self, name, importer, deducer, optimiser): 250 CommonModule.__init__(self, name, importer) 251 self.deducer = deducer 252 self.optimiser = optimiser 253 254 # Output stream. 255 256 self.out = None 257 self.indent = 0 258 self.tabstop = " " 259 260 # Recorded namespaces. 261 262 self.namespaces = [] 263 self.in_conditional = False 264 265 # Exception raising adjustments. 266 267 self.in_try_finally = False 268 self.in_try_except = False 269 270 # Attribute access and accessor counting. 271 272 self.attr_accesses = {} 273 self.attr_accessors = {} 274 275 def __repr__(self): 276 return "TranslatedModule(%r, %r)" % (self.name, self.importer) 277 278 def translate(self, filename, output_filename): 279 280 """ 281 Parse the file having the given 'filename', writing the translation to 282 the given 'output_filename'. 283 """ 284 285 self.parse_file(filename) 286 287 # Collect function namespaces for separate processing. 288 289 self.record_namespaces(self.astnode) 290 291 # Reset the lambda naming (in order to obtain the same names again) and 292 # translate the program. 293 294 self.reset_lambdas() 295 296 self.out = open(output_filename, "w") 297 try: 298 self.start_output() 299 300 # Process namespaces, writing the translation. 301 302 for path, node in self.namespaces: 303 self.process_namespace(path, node) 304 305 # Process the module namespace including class namespaces. 306 307 self.process_namespace([], self.astnode) 308 309 finally: 310 self.out.close() 311 312 def have_object(self): 313 314 "Return whether a namespace is a recorded object." 315 316 return self.importer.objects.get(self.get_namespace_path()) 317 318 def get_builtin_class(self, name): 319 320 "Return a reference to the actual object providing 'name'." 321 322 # NOTE: This makes assumptions about the __builtins__ structure. 323 324 modname = get_builtin_module(name) 325 return self.importer.get_object("__builtins__.%s.%s" % (modname, name)) 326 327 def is_method(self, path): 328 329 "Return whether 'path' is a method." 330 331 class_name, method_name = path.rsplit(".", 1) 332 return self.importer.classes.has_key(class_name) and class_name or None 333 334 def in_method(self): 335 336 "Return whether the current namespace provides a method." 337 338 return self.in_function and self.is_method(self.get_namespace_path()) 339 340 # Namespace recording. 341 342 def record_namespaces(self, node): 343 344 "Process the program structure 'node', recording namespaces." 345 346 for n in node.getChildNodes(): 347 self.record_namespaces_in_node(n) 348 349 def record_namespaces_in_node(self, node): 350 351 "Process the program structure 'node', recording namespaces." 352 353 # Function namespaces within modules, classes and other functions. 354 # Functions appearing within conditional statements are given arbitrary 355 # names. 356 357 if isinstance(node, compiler.ast.Function): 358 self.record_function_node(node, (self.in_conditional or self.in_function) and self.get_lambda_name() or node.name) 359 360 elif isinstance(node, compiler.ast.Lambda): 361 self.record_function_node(node, self.get_lambda_name()) 362 363 # Classes are visited, but may be ignored if inside functions. 364 365 elif isinstance(node, compiler.ast.Class): 366 self.enter_namespace(node.name) 367 if self.have_object(): 368 self.record_namespaces(node) 369 self.exit_namespace() 370 371 # Conditional nodes are tracked so that function definitions may be 372 # handled. Since "for" loops are converted to "while" loops, they are 373 # included here. 374 375 elif isinstance(node, (compiler.ast.For, compiler.ast.If, compiler.ast.While)): 376 in_conditional = self.in_conditional 377 self.in_conditional = True 378 self.record_namespaces(node) 379 self.in_conditional = in_conditional 380 381 # All other nodes are processed depth-first. 382 383 else: 384 self.record_namespaces(node) 385 386 def record_function_node(self, n, name): 387 388 """ 389 Record the given function, lambda, if expression or list comprehension 390 node 'n' with the given 'name'. 391 """ 392 393 self.in_function = True 394 self.enter_namespace(name) 395 396 if self.have_object(): 397 398 # Record the namespace path and the node itself. 399 400 self.namespaces.append((self.namespace_path[:], n)) 401 self.record_namespaces_in_node(n.code) 402 403 self.exit_namespace() 404 self.in_function = False 405 406 # Constant referencing. 407 408 def get_literal_instance(self, n, name): 409 410 """ 411 For node 'n', return a reference for the type of the given 'name'. 412 """ 413 414 # Handle stray None constants (Sliceobj seems to produce them). 415 416 if name == "NoneType": 417 return self.process_name_node(compiler.ast.Name("None")) 418 419 ref = self.get_builtin_class(name) 420 421 if name in ("dict", "list", "tuple"): 422 return self.process_literal_sequence_node(n, name, ref, TrLiteralSequenceRef) 423 else: 424 path = self.get_namespace_path() 425 local_number = self.importer.all_constants[path][n.value] 426 constant_name = "$c%d" % local_number 427 objpath = self.get_object_path(constant_name) 428 number = self.optimiser.constant_numbers[objpath] 429 return TrConstantValueRef(constant_name, ref.instance_of(), n.value, number) 430 431 # Namespace translation. 432 433 def process_namespace(self, path, node): 434 435 """ 436 Process the namespace for the given 'path' defined by the given 'node'. 437 """ 438 439 self.namespace_path = path 440 441 if isinstance(node, (compiler.ast.Function, compiler.ast.Lambda)): 442 self.in_function = True 443 self.process_function_body_node(node) 444 else: 445 self.in_function = False 446 self.function_target = 0 447 self.start_module() 448 self.process_structure(node) 449 self.end_module() 450 451 def process_structure(self, node): 452 453 "Process the given 'node' or result." 454 455 # Handle processing requests on results. 456 457 if isinstance(node, results.Result): 458 return node 459 460 # Handle processing requests on nodes. 461 462 else: 463 l = CommonModule.process_structure(self, node) 464 465 # Return indications of return statement usage. 466 467 if l and isinstance(l[-1], ReturnRef): 468 return l[-1] 469 else: 470 return None 471 472 def process_structure_node(self, n): 473 474 "Process the individual node 'n'." 475 476 # Plain statements emit their expressions. 477 478 if isinstance(n, compiler.ast.Discard): 479 expr = self.process_structure_node(n.expr) 480 self.statement(expr) 481 482 # Module import declarations. 483 484 elif isinstance(n, compiler.ast.From): 485 self.process_from_node(n) 486 487 # Nodes using operator module functions. 488 489 elif isinstance(n, compiler.ast.Operator): 490 return self.process_operator_node(n) 491 492 elif isinstance(n, compiler.ast.AugAssign): 493 self.process_augassign_node(n) 494 495 elif isinstance(n, compiler.ast.Compare): 496 return self.process_compare_node(n) 497 498 elif isinstance(n, compiler.ast.Slice): 499 return self.process_slice_node(n) 500 501 elif isinstance(n, compiler.ast.Sliceobj): 502 return self.process_sliceobj_node(n) 503 504 elif isinstance(n, compiler.ast.Subscript): 505 return self.process_subscript_node(n) 506 507 # Classes are visited, but may be ignored if inside functions. 508 509 elif isinstance(n, compiler.ast.Class): 510 self.process_class_node(n) 511 512 # Functions within namespaces have any dynamic defaults initialised. 513 514 elif isinstance(n, compiler.ast.Function): 515 self.process_function_node(n) 516 517 # Lambdas are replaced with references to separately-generated 518 # functions. 519 520 elif isinstance(n, compiler.ast.Lambda): 521 return self.process_lambda_node(n) 522 523 # Assignments. 524 525 elif isinstance(n, compiler.ast.Assign): 526 527 # Handle each assignment node. 528 529 for node in n.nodes: 530 self.process_assignment_node(node, n.expr) 531 532 # Accesses. 533 534 elif isinstance(n, compiler.ast.Getattr): 535 return self.process_attribute_access(n) 536 537 # Names. 538 539 elif isinstance(n, compiler.ast.Name): 540 return self.process_name_node(n) 541 542 # Loops and conditionals. 543 544 elif isinstance(n, compiler.ast.For): 545 self.process_for_node(n) 546 547 elif isinstance(n, compiler.ast.While): 548 self.process_while_node(n) 549 550 elif isinstance(n, compiler.ast.If): 551 self.process_if_node(n) 552 553 elif isinstance(n, (compiler.ast.And, compiler.ast.Or)): 554 return self.process_logical_node(n) 555 556 elif isinstance(n, compiler.ast.Not): 557 return self.process_not_node(n) 558 559 # Exception control-flow tracking. 560 561 elif isinstance(n, compiler.ast.TryExcept): 562 self.process_try_node(n) 563 564 elif isinstance(n, compiler.ast.TryFinally): 565 self.process_try_finally_node(n) 566 567 # Control-flow modification statements. 568 569 elif isinstance(n, compiler.ast.Break): 570 self.writestmt("break;") 571 572 elif isinstance(n, compiler.ast.Continue): 573 self.writestmt("continue;") 574 575 elif isinstance(n, compiler.ast.Raise): 576 self.process_raise_node(n) 577 578 elif isinstance(n, compiler.ast.Return): 579 return self.process_return_node(n) 580 581 # Print statements. 582 583 elif isinstance(n, (compiler.ast.Print, compiler.ast.Printnl)): 584 self.statement(self.process_print_node(n)) 585 586 # Invocations. 587 588 elif isinstance(n, compiler.ast.CallFunc): 589 return self.process_invocation_node(n) 590 591 elif isinstance(n, compiler.ast.Keyword): 592 return self.process_structure_node(n.expr) 593 594 # Constant usage. 595 596 elif isinstance(n, compiler.ast.Const): 597 return self.get_literal_instance(n, n.value.__class__.__name__) 598 599 elif isinstance(n, compiler.ast.Dict): 600 return self.get_literal_instance(n, "dict") 601 602 elif isinstance(n, compiler.ast.List): 603 return self.get_literal_instance(n, "list") 604 605 elif isinstance(n, compiler.ast.Tuple): 606 return self.get_literal_instance(n, "tuple") 607 608 # All other nodes are processed depth-first. 609 610 else: 611 return self.process_structure(n) 612 613 def process_assignment_node(self, n, expr): 614 615 "Process the individual node 'n' to be assigned the contents of 'expr'." 616 617 # Names and attributes are assigned the entire expression. 618 619 if isinstance(n, compiler.ast.AssName): 620 name_ref = self.process_name_node(n, self.process_structure_node(expr)) 621 self.statement(name_ref) 622 623 # Employ guards after assignments if required. 624 625 if expr and name_ref.is_name(): 626 self.generate_guard(name_ref.name) 627 628 elif isinstance(n, compiler.ast.AssAttr): 629 in_assignment = self.in_assignment 630 self.in_assignment = self.process_structure_node(expr) 631 self.statement(self.process_attribute_access(n)) 632 self.in_assignment = in_assignment 633 634 # Lists and tuples are matched against the expression and their 635 # items assigned to expression items. 636 637 elif isinstance(n, (compiler.ast.AssList, compiler.ast.AssTuple)): 638 self.process_assignment_node_items(n, expr) 639 640 # Slices and subscripts are permitted within assignment nodes. 641 642 elif isinstance(n, compiler.ast.Slice): 643 self.statement(self.process_slice_node(n, expr)) 644 645 elif isinstance(n, compiler.ast.Subscript): 646 self.statement(self.process_subscript_node(n, expr)) 647 648 def process_attribute_access(self, n): 649 650 """ 651 Process the given attribute access node 'n'. 652 653 Where a name is provided, a single access should be recorded 654 involving potentially many attributes, thus providing a path to an 655 object. The remaining attributes are then accessed dynamically. 656 The remaining accesses could be deduced and computed, but they would 657 also need to be tested. 658 659 Where no name is provided, potentially many accesses should be 660 recorded, one per attribute name. These could be used to provide 661 computed accesses, but the accessors would need to be tested in each 662 case. 663 """ 664 665 # Obtain any completed chain and return the reference to it. 666 667 attr_expr = self.process_attribute_chain(n) 668 if self.have_access_expression(n): 669 return attr_expr 670 671 # Where the start of the chain of attributes has been reached, process 672 # the complete access. 673 674 name_ref = attr_expr and attr_expr.is_name() and attr_expr 675 name = name_ref and self.get_name_for_tracking(name_ref.name, name_ref and name_ref.final()) or None 676 677 location = self.get_access_location(name) 678 refs = self.get_referenced_attributes(location) 679 680 # Generate access instructions. 681 682 subs = { 683 "<expr>" : str(attr_expr), 684 "<assexpr>" : str(self.in_assignment), 685 "<context>" : "__tmp_context", 686 "<accessor>" : "__tmp_value", 687 } 688 689 output = [] 690 691 for instruction in self.optimiser.access_instructions[location]: 692 output.append(encode_access_instruction(instruction, subs)) 693 694 if len(output) == 1: 695 out = output[0] 696 else: 697 out = "(\n%s\n)" % ",\n".join(output) 698 699 del self.attrs[0] 700 return AttrResult(out, refs, self.get_accessor_kinds(location)) 701 702 def get_referenced_attributes(self, location): 703 704 """ 705 Convert 'location' to the form used by the deducer and retrieve any 706 identified attribute. 707 """ 708 709 access_location = self.deducer.const_accesses.get(location) 710 refs = [] 711 for attrtype, objpath, attr in self.deducer.referenced_attrs[access_location or location]: 712 refs.append(attr) 713 return refs 714 715 def get_accessor_kinds(self, location): 716 717 "Return the accessor kinds for 'location'." 718 719 return self.optimiser.accessor_kinds[location] 720 721 def get_access_location(self, name): 722 723 """ 724 Using the current namespace and the given 'name', return the access 725 location. 726 """ 727 728 path = self.get_path_for_access() 729 730 # Get the location used by the deducer and optimiser and find any 731 # recorded access. 732 733 attrnames = ".".join(self.attrs) 734 access_number = self.get_access_number(path, name, attrnames) 735 self.update_access_number(path, name, attrnames) 736 return (path, name, attrnames, access_number) 737 738 def get_access_number(self, path, name, attrnames): 739 access = name, attrnames 740 if self.attr_accesses.has_key(path) and self.attr_accesses[path].has_key(access): 741 return self.attr_accesses[path][access] 742 else: 743 return 0 744 745 def update_access_number(self, path, name, attrnames): 746 access = name, attrnames 747 if name: 748 init_item(self.attr_accesses, path, dict) 749 init_item(self.attr_accesses[path], access, lambda: 0) 750 self.attr_accesses[path][access] += 1 751 752 def get_accessor_location(self, name): 753 754 """ 755 Using the current namespace and the given 'name', return the accessor 756 location. 757 """ 758 759 path = self.get_path_for_access() 760 761 # Get the location used by the deducer and optimiser and find any 762 # recorded accessor. 763 764 access_number = self.get_accessor_number(path, name) 765 self.update_accessor_number(path, name) 766 return (path, name, None, access_number) 767 768 def get_accessor_number(self, path, name): 769 if self.attr_accessors.has_key(path) and self.attr_accessors[path].has_key(name): 770 return self.attr_accessors[path][name] 771 else: 772 return 0 773 774 def update_accessor_number(self, path, name): 775 if name: 776 init_item(self.attr_accessors, path, dict) 777 init_item(self.attr_accessors[path], name, lambda: 0) 778 self.attr_accessors[path][name] += 1 779 780 def process_class_node(self, n): 781 782 "Process the given class node 'n'." 783 784 class_name = self.get_object_path(n.name) 785 786 # Where a class is set conditionally or where the name may refer to 787 # different values, assign the name. 788 789 ref = self.importer.identify(class_name) 790 791 if not ref.static(): 792 self.process_assignment_for_object( 793 n.name, make_expression("((__attr) {0, &%s})" % 794 encode_path(class_name))) 795 796 self.enter_namespace(n.name) 797 798 if self.have_object(): 799 self.write_comment("Class: %s" % class_name) 800 801 self.initialise_inherited_members(class_name) 802 803 self.process_structure(n) 804 self.write_comment("End class: %s" % class_name) 805 806 self.exit_namespace() 807 808 def initialise_inherited_members(self, class_name): 809 810 "Initialise members of 'class_name' inherited from its ancestors." 811 812 for name, path in self.importer.all_class_attrs[class_name].items(): 813 target = "%s.%s" % (class_name, name) 814 815 # Ignore attributes with definitions. 816 817 ref = self.importer.identify(target) 818 if ref: 819 continue 820 821 # Ignore special type attributes. 822 823 if is_type_attribute(name): 824 continue 825 826 # Reference inherited attributes. 827 828 ref = self.importer.identify(path) 829 if ref and not ref.static(): 830 parent, attrname = path.rsplit(".", 1) 831 832 self.writestmt("__store_via_object(&%s, %s, __load_via_object(&%s, %s));" % ( 833 encode_path(class_name), encode_symbol("pos", name), 834 encode_path(parent), encode_symbol("pos", attrname) 835 )) 836 837 def process_from_node(self, n): 838 839 "Process the given node 'n', importing from another module." 840 841 path = self.get_namespace_path() 842 843 # Attempt to obtain the referenced objects. 844 845 for name, alias in n.names: 846 if name == "*": 847 raise InspectError("Only explicitly specified names can be imported from modules.", path, n) 848 849 # Obtain the path of the assigned name. 850 851 objpath = self.get_object_path(alias or name) 852 853 # Obtain the identity of the name. 854 855 ref = self.importer.identify(objpath) 856 857 # Where the name is not static, assign the value. 858 859 if ref and not ref.static() and ref.get_name(): 860 self.writestmt("%s;" % 861 TrResolvedNameRef(alias or name, Reference("<var>", None, objpath), 862 expr=TrResolvedNameRef(name, ref))) 863 864 def process_function_body_node(self, n): 865 866 """ 867 Process the given function, lambda, if expression or list comprehension 868 node 'n', generating the body. 869 """ 870 871 function_name = self.get_namespace_path() 872 self.start_function(function_name) 873 874 # Process the function body. 875 876 in_conditional = self.in_conditional 877 self.in_conditional = False 878 self.function_target = 0 879 880 # Process any guards defined for the parameters. 881 882 for name in self.importer.function_parameters.get(function_name): 883 self.generate_guard(name) 884 885 # Produce the body and any additional return statement. 886 887 expr = self.process_structure_node(n.code) or PredefinedConstantRef("None") 888 if not isinstance(expr, ReturnRef): 889 self.writestmt("return %s;" % expr) 890 891 self.in_conditional = in_conditional 892 893 self.end_function(function_name) 894 895 def generate_guard(self, name): 896 897 """ 898 Get the accessor details for 'name', found in the current namespace, and 899 generate any guards defined for it. 900 """ 901 902 # Obtain the location, keeping track of assignment versions. 903 904 location = self.get_accessor_location(name) 905 test = self.deducer.accessor_guard_tests.get(location) 906 907 # Generate any guard from the deduced information. 908 909 if test: 910 guard, guard_type = test 911 912 if guard == "specific": 913 ref = first(self.deducer.accessor_all_types[location]) 914 argstr = "&%s" % encode_path(ref.get_origin()) 915 elif guard == "common": 916 ref = first(self.deducer.accessor_all_general_types[location]) 917 typeattr = encode_type_attribute(ref.get_origin()) 918 argstr = "%s, %s" % (encode_symbol("pos", typeattr), encode_symbol("code", typeattr)) 919 else: 920 return 921 922 # Produce an appropriate access to an attribute's value. 923 924 parameters = self.importer.function_parameters.get(self.get_namespace_path()) 925 if parameters and name in parameters: 926 name_to_value = "%s->value" % name 927 else: 928 name_to_value = "%s.value" % name 929 930 # Write a test that raises a TypeError upon failure. 931 932 self.writestmt("if (!__test_%s_%s(%s, %s)) __raise_type_error();" % ( 933 guard, guard_type, name_to_value, argstr)) 934 935 def process_function_node(self, n): 936 937 """ 938 Process the given function, lambda, if expression or list comprehension 939 node 'n', generating any initialisation statements. 940 """ 941 942 # Where a function is declared conditionally, use a separate name for 943 # the definition, and assign the definition to the stated name. 944 945 original_name = n.name 946 947 if self.in_conditional or self.in_function: 948 name = self.get_lambda_name() 949 else: 950 name = n.name 951 952 objpath = self.get_object_path(name) 953 954 # Obtain details of the defaults. 955 956 defaults = self.process_function_defaults(n, name, objpath) 957 if defaults: 958 for default in defaults: 959 self.writeline("%s;" % default) 960 961 # Where a function is set conditionally or where the name may refer to 962 # different values, assign the name. 963 964 ref = self.importer.identify(objpath) 965 966 if self.in_conditional or self.in_function: 967 self.process_assignment_for_object(original_name, compiler.ast.Name(name)) 968 elif not ref.static(): 969 context = self.is_method(objpath) 970 971 self.process_assignment_for_object(original_name, 972 make_expression("((__attr) {%s, &%s})" % ( 973 context and "&%s" % encode_path(context) or "0", 974 encode_path(objpath)))) 975 976 def process_function_defaults(self, n, name, objpath, instance_name=None): 977 978 """ 979 Process the given function or lambda node 'n', initialising defaults 980 that are dynamically set. The given 'name' indicates the name of the 981 function. The given 'objpath' indicates the origin of the function. 982 The given 'instance_name' indicates the name of any separate instance 983 of the function created to hold the defaults. 984 985 Return a list of operations setting defaults on a function instance. 986 """ 987 988 function_name = self.get_object_path(name) 989 function_defaults = self.importer.function_defaults.get(function_name) 990 if not function_defaults: 991 return None 992 993 # Determine whether any unidentified defaults are involved. 994 995 for argname, default in function_defaults: 996 if not default.static(): 997 break 998 else: 999 return None 1000 1001 # Handle bound methods. 1002 1003 if not instance_name: 1004 if self.is_method(objpath): 1005 instance_name = "&%s" % encode_bound_reference(objpath) 1006 else: 1007 instance_name = "&%s" % encode_path(objpath) 1008 1009 # Where defaults are involved but cannot be identified, obtain a new 1010 # instance of the lambda and populate the defaults. 1011 1012 defaults = [] 1013 1014 # Join the original defaults with the inspected defaults. 1015 1016 original_defaults = [(argname, default) for (argname, default) in compiler.ast.get_defaults(n) if default] 1017 1018 for i, (original, inspected) in enumerate(map(None, original_defaults, function_defaults)): 1019 1020 # Obtain any reference for the default. 1021 1022 if original: 1023 argname, default = original 1024 name_ref = self.process_structure_node(default) 1025 elif inspected: 1026 argname, default = inspected 1027 name_ref = TrResolvedNameRef(argname, default) 1028 else: 1029 continue 1030 1031 # Generate default initialisers except when constants are employed. 1032 # Constants should be used when populating the function structures. 1033 1034 if name_ref and not isinstance(name_ref, TrConstantValueRef): 1035 defaults.append("__SETDEFAULT(%s, %s, %s)" % (instance_name, i, name_ref)) 1036 1037 return defaults 1038 1039 def process_if_node(self, n): 1040 1041 """ 1042 Process the given "if" node 'n'. 1043 """ 1044 1045 first = True 1046 for test, body in n.tests: 1047 test_ref = self.process_structure_node(test) 1048 self.start_if(first, test_ref) 1049 1050 in_conditional = self.in_conditional 1051 self.in_conditional = True 1052 self.process_structure_node(body) 1053 self.in_conditional = in_conditional 1054 1055 self.end_if() 1056 first = False 1057 1058 if n.else_: 1059 self.start_else() 1060 self.process_structure_node(n.else_) 1061 self.end_else() 1062 1063 def process_invocation_node(self, n): 1064 1065 "Process the given invocation node 'n'." 1066 1067 expr = self.process_structure_node(n.node) 1068 objpath = expr.get_origin() 1069 target = None 1070 function = None 1071 instantiation = False 1072 literal_instantiation = False 1073 context_required = True 1074 1075 # Obtain details of the callable. 1076 1077 # Literals may be instantiated specially. 1078 1079 if expr.is_name() and expr.name.startswith("$L") and objpath: 1080 instantiation = literal_instantiation = objpath 1081 parameters = None 1082 target = encode_literal_instantiator(objpath) 1083 context_required = False 1084 1085 # Identified targets employ function pointers directly. 1086 1087 elif objpath: 1088 parameters = self.importer.function_parameters.get(objpath) 1089 1090 # Class invocation involves instantiators. 1091 1092 if expr.has_kind("<class>"): 1093 instantiation = objpath 1094 target = encode_instantiator_pointer(objpath) 1095 target_structure = "&%s" % encode_bound_reference("%s.__init__" % objpath) 1096 context_required = False 1097 1098 # Only plain functions and bound methods employ function pointers. 1099 1100 elif expr.has_kind("<function>"): 1101 function = objpath 1102 1103 # Test for functions and methods. 1104 1105 method_class = self.is_method(objpath) 1106 accessor_kinds = expr.get_accessor_kinds() 1107 instance_accessor = accessor_kinds and \ 1108 len(accessor_kinds) == 1 and \ 1109 first(accessor_kinds) == "<instance>" 1110 1111 if not method_class or instance_accessor: 1112 target = encode_function_pointer(objpath) 1113 target_structure = self.is_method(objpath) and \ 1114 "&%s" % encode_bound_reference(objpath) or \ 1115 "&%s" % encode_path(objpath) 1116 1117 if not method_class: 1118 context_required = False 1119 1120 # Other targets are retrieved at run-time. 1121 1122 else: 1123 parameters = None 1124 1125 # Arguments are presented in a temporary frame array with any context 1126 # always being the first argument. Where it would be unused, it may be 1127 # set to null. 1128 1129 if context_required: 1130 args = ["__CONTEXT_AS_VALUE(__tmp_targets[%d])" % self.function_target] 1131 else: 1132 args = ["(__attr) {0, 0}"] 1133 1134 args += [None] * (not parameters and len(n.args) or parameters and len(parameters) or 0) 1135 kwcodes = [] 1136 kwargs = [] 1137 1138 # Any invocations in the arguments will store target details in a 1139 # different location. 1140 1141 self.function_target += 1 1142 1143 for i, arg in enumerate(n.args): 1144 argexpr = self.process_structure_node(arg) 1145 1146 # Store a keyword argument, either in the argument list or 1147 # in a separate keyword argument list for subsequent lookup. 1148 1149 if isinstance(arg, compiler.ast.Keyword): 1150 1151 # With knowledge of the target, store the keyword 1152 # argument directly. 1153 1154 if parameters: 1155 argnum = parameters.index(arg.name) 1156 args[argnum+1] = str(argexpr) 1157 1158 # Otherwise, store the details in a separate collection. 1159 1160 else: 1161 kwargs.append(str(argexpr)) 1162 kwcodes.append("{%s, %s}" % ( 1163 encode_symbol("ppos", arg.name), 1164 encode_symbol("pcode", arg.name))) 1165 1166 # Store non-keyword arguments in the argument list, rejecting 1167 # superfluous arguments. 1168 1169 else: 1170 try: 1171 args[i+1] = str(argexpr) 1172 except IndexError: 1173 raise TranslateError("Too many arguments specified.", 1174 self.get_namespace_path(), n) 1175 1176 # Reference the current target again. 1177 1178 self.function_target -= 1 1179 1180 # Defaults are added to the frame where arguments are missing. 1181 1182 if parameters: 1183 function_defaults = self.importer.function_defaults.get(objpath) 1184 if function_defaults: 1185 1186 # Visit each default and set any missing arguments. 1187 # Use the target structure to obtain defaults, as opposed to the 1188 # actual function involved. 1189 1190 for i, (argname, default) in enumerate(function_defaults): 1191 argnum = parameters.index(argname) 1192 if not args[argnum+1]: 1193 args[argnum+1] = "__GETDEFAULT(%s, %d)" % (target_structure, i) 1194 1195 # Test for missing arguments. 1196 1197 if None in args: 1198 raise TranslateError("Not all arguments supplied.", 1199 self.get_namespace_path(), n) 1200 1201 # Encode the arguments. 1202 1203 argstr = "__ARGS(%s)" % ", ".join(args) 1204 kwargstr = kwargs and ("__ARGS(%s)" % ", ".join(kwargs)) or "0" 1205 kwcodestr = kwcodes and ("__KWARGS(%s)" % ", ".join(kwcodes)) or "0" 1206 1207 # Where literal instantiation is occurring, add an argument indicating 1208 # the number of values. 1209 1210 if literal_instantiation: 1211 argstr += ", %d" % (len(args) - 1) 1212 1213 # First, the invocation expression is presented. 1214 1215 stages = [] 1216 1217 # Without a known specific callable, the expression provides the target. 1218 1219 if not target or context_required: 1220 stages.append("__tmp_targets[%d] = %s" % (self.function_target, expr)) 1221 1222 # Any specific callable is then obtained. 1223 1224 if target: 1225 stages.append(target) 1226 elif function: 1227 stages.append("__load_via_object(__tmp_targets[%d].value, %s).fn" % ( 1228 self.function_target, encode_symbol("pos", "__fn__"))) 1229 1230 # With a known target, the function is obtained directly and called. 1231 1232 if target or function: 1233 output = "(\n%s\n)(%s)" % (",\n".join(stages), argstr) 1234 1235 # With unknown targets, the generic invocation function is applied to 1236 # the callable and argument collections. 1237 1238 else: 1239 output = "(%s, __invoke(\n__tmp_targets[%d],\n%d, %d, %s, %s,\n%d, %s\n))" % ( 1240 ",\n".join(stages), 1241 self.function_target, 1242 self.always_callable and 1 or 0, 1243 len(kwargs), kwcodestr, kwargstr, 1244 len(args), argstr) 1245 1246 if instantiation: 1247 return TrInstanceRef(instantiation, output) 1248 else: 1249 return make_expression(output) 1250 1251 def always_callable(self, refs): 1252 1253 "Determine whether all 'refs' are callable." 1254 1255 for ref in refs: 1256 if not ref.static(): 1257 return False 1258 else: 1259 origin = ref.final() 1260 if not self.importer.get_attribute(origin, "__fn__"): 1261 return False 1262 return True 1263 1264 def need_default_arguments(self, objpath, nargs): 1265 1266 """ 1267 Return whether any default arguments are needed when invoking the object 1268 given by 'objpath'. 1269 """ 1270 1271 parameters = self.importer.function_parameters.get(objpath) 1272 return nargs < len(parameters) 1273 1274 def process_lambda_node(self, n): 1275 1276 "Process the given lambda node 'n'." 1277 1278 name = self.get_lambda_name() 1279 function_name = self.get_object_path(name) 1280 1281 defaults = self.process_function_defaults(n, name, function_name, "__tmp_value") 1282 1283 # Without defaults, produce an attribute referring to the function. 1284 1285 if not defaults: 1286 return make_expression("((__attr) {0, &%s})" % encode_path(function_name)) 1287 1288 # With defaults, copy the function structure and set the defaults on the 1289 # copy. 1290 1291 else: 1292 return make_expression("(__tmp_value = __COPY(&%s, sizeof(%s)), %s, (__attr) {0, __tmp_value})" % ( 1293 encode_path(function_name), 1294 encode_symbol("obj", function_name), 1295 ", ".join(defaults))) 1296 1297 def process_logical_node(self, n): 1298 1299 """ 1300 Process the given operator node 'n'. 1301 1302 Convert ... to ... 1303 1304 <a> and <b> 1305 (__tmp_result = <a>, !__BOOL(__tmp_result)) ? __tmp_result : <b> 1306 1307 <a> or <b> 1308 (__tmp_result = <a>, __BOOL(__tmp_result)) ? __tmp_result : <b> 1309 """ 1310 1311 if isinstance(n, compiler.ast.And): 1312 op = "!" 1313 else: 1314 op = "" 1315 1316 results = [] 1317 1318 for node in n.nodes[:-1]: 1319 expr = self.process_structure_node(node) 1320 results.append("(__tmp_result = %s, %s__BOOL(__tmp_result)) ? __tmp_result : " % (expr, op)) 1321 1322 expr = self.process_structure_node(n.nodes[-1]) 1323 results.append(str(expr)) 1324 1325 return make_expression("(%s)" % "".join(results)) 1326 1327 def process_name_node(self, n, expr=None): 1328 1329 "Process the given name node 'n' with the optional assignment 'expr'." 1330 1331 # Determine whether the name refers to a static external entity. 1332 1333 if n.name in predefined_constants: 1334 return PredefinedConstantRef(n.name) 1335 1336 # Convert literal references, operator function names, and print 1337 # function names to references. 1338 1339 elif n.name.startswith("$L") or n.name.startswith("$op") or \ 1340 n.name.startswith("$print"): 1341 ref = self.importer.get_module(self.name).special.get(n.name) 1342 return TrResolvedNameRef(n.name, ref) 1343 1344 # Get the appropriate name for the name reference, using the same method 1345 # as in the inspector. 1346 1347 path = self.get_namespace_path() 1348 objpath = self.get_object_path(n.name) 1349 1350 # Determine any assigned globals. 1351 1352 globals = self.importer.get_module(self.name).scope_globals.get(path) 1353 if globals and n.name in globals: 1354 objpath = self.get_global_path(n.name) 1355 1356 # Get the static identity of the name. 1357 1358 ref = self.importer.identify(objpath) 1359 if ref and not ref.get_name(): 1360 ref = ref.alias(objpath) 1361 1362 # Obtain any resolved names for non-assignment names. 1363 1364 if not expr and not ref and self.in_function: 1365 locals = self.importer.function_locals.get(path) 1366 ref = locals and locals.get(n.name) 1367 1368 # Determine whether the name refers to a parameter. The generation of 1369 # parameter references is different from other names. 1370 1371 parameters = self.importer.function_parameters.get(path) 1372 parameter = n.name == "self" and self.in_method() or \ 1373 parameters and n.name in parameters 1374 1375 # Qualified names are used for resolved static references or for 1376 # static namespace members. The reference should be configured to return 1377 # such names. 1378 1379 return TrResolvedNameRef(n.name, ref, expr=expr, parameter=parameter) 1380 1381 def process_not_node(self, n): 1382 1383 "Process the given operator node 'n'." 1384 1385 return make_expression("(__BOOL(%s) ? %s : %s)" % 1386 (self.process_structure_node(n.expr), PredefinedConstantRef("False"), 1387 PredefinedConstantRef("True"))) 1388 1389 def process_raise_node(self, n): 1390 1391 "Process the given raise node 'n'." 1392 1393 # NOTE: Determine which raise statement variants should be permitted. 1394 1395 if n.expr1: 1396 exc = self.process_structure_node(n.expr1) 1397 1398 # Raise instances, testing the kind at run-time if necessary and 1399 # instantiating any non-instance. 1400 1401 if isinstance(exc, TrInstanceRef): 1402 self.writestmt("__Raise(%s);" % exc) 1403 else: 1404 self.writestmt("__Raise(__ensure_instance(%s));" % exc) 1405 else: 1406 self.writestmt("__Throw(__tmp_exc);") 1407 1408 def process_return_node(self, n): 1409 1410 "Process the given return node 'n'." 1411 1412 expr = self.process_structure_node(n.value) or PredefinedConstantRef("None") 1413 if self.in_try_finally or self.in_try_except: 1414 self.writestmt("__Return(%s);" % expr) 1415 else: 1416 self.writestmt("return %s;" % expr) 1417 1418 return ReturnRef() 1419 1420 def process_try_node(self, n): 1421 1422 """ 1423 Process the given "try...except" node 'n'. 1424 """ 1425 1426 in_try_except = self.in_try_except 1427 self.in_try_except = True 1428 1429 # Use macros to implement exception handling. 1430 1431 self.writestmt("__Try") 1432 self.writeline("{") 1433 self.indent += 1 1434 self.process_structure_node(n.body) 1435 1436 # Put the else statement in another try block that handles any raised 1437 # exceptions and converts them to exceptions that will not be handled by 1438 # the main handling block. 1439 1440 if n.else_: 1441 self.writestmt("__Try") 1442 self.writeline("{") 1443 self.indent += 1 1444 self.process_structure_node(n.else_) 1445 self.indent -= 1 1446 self.writeline("}") 1447 self.writeline("__Catch (__tmp_exc)") 1448 self.writeline("{") 1449 self.indent += 1 1450 self.writeline("if (__tmp_exc.raising) __RaiseElse(__tmp_exc.arg);") 1451 self.writeline("else if (__tmp_exc.completing) __Throw(__tmp_exc);") 1452 self.indent -= 1 1453 self.writeline("}") 1454 1455 # Complete the try block and enter the finally block, if appropriate. 1456 1457 if self.in_try_finally: 1458 self.writestmt("__Complete;") 1459 1460 self.indent -= 1 1461 self.writeline("}") 1462 1463 self.in_try_except = in_try_except 1464 1465 # Handlers are tests within a common handler block. 1466 1467 self.writeline("__Catch (__tmp_exc)") 1468 self.writeline("{") 1469 self.indent += 1 1470 1471 # Introduce an if statement to handle the completion of a try block. 1472 1473 self.process_try_completion() 1474 1475 # Handle exceptions in else blocks converted to __RaiseElse, converting 1476 # them back to normal exceptions. 1477 1478 if n.else_: 1479 self.writeline("else if (__tmp_exc.raising_else) __Raise(__tmp_exc.arg);") 1480 1481 # Exception handling. 1482 1483 for name, var, handler in n.handlers: 1484 1485 # Test for specific exceptions. 1486 1487 if name is not None: 1488 name_ref = self.process_structure_node(name) 1489 self.writeline("else if (__BOOL(__fn_native_introspection_isinstance((__attr[]) {{0, 0}, __tmp_exc.arg, %s})))" % name_ref) 1490 else: 1491 self.writeline("else if (1)") 1492 1493 self.writeline("{") 1494 self.indent += 1 1495 1496 # Establish the local for the handler. 1497 1498 if var is not None: 1499 self.writestmt("%s;" % self.process_name_node(var, make_expression("__tmp_exc.arg"))) 1500 1501 if handler is not None: 1502 self.process_structure_node(handler) 1503 1504 self.indent -= 1 1505 self.writeline("}") 1506 1507 # Re-raise unhandled exceptions. 1508 1509 self.writeline("else __Throw(__tmp_exc);") 1510 1511 # End the handler block. 1512 1513 self.indent -= 1 1514 self.writeline("}") 1515 1516 def process_try_finally_node(self, n): 1517 1518 """ 1519 Process the given "try...finally" node 'n'. 1520 """ 1521 1522 in_try_finally = self.in_try_finally 1523 self.in_try_finally = True 1524 1525 # Use macros to implement exception handling. 1526 1527 self.writestmt("__Try") 1528 self.writeline("{") 1529 self.indent += 1 1530 self.process_structure_node(n.body) 1531 self.indent -= 1 1532 self.writeline("}") 1533 1534 self.in_try_finally = in_try_finally 1535 1536 # Finally clauses handle special exceptions. 1537 1538 self.writeline("__Catch (__tmp_exc)") 1539 self.writeline("{") 1540 self.indent += 1 1541 self.process_structure_node(n.final) 1542 1543 # Introduce an if statement to handle the completion of a try block. 1544 1545 self.process_try_completion() 1546 self.writeline("else __Throw(__tmp_exc);") 1547 1548 self.indent -= 1 1549 self.writeline("}") 1550 1551 def process_try_completion(self): 1552 1553 "Generate a test for the completion of a try block." 1554 1555 self.writestmt("if (__tmp_exc.completing)") 1556 self.writeline("{") 1557 self.indent += 1 1558 1559 # Do not return anything at the module level. 1560 1561 if self.get_namespace_path() != self.name: 1562 1563 # Only use the normal return statement if no surrounding try blocks 1564 # apply. 1565 1566 if not self.in_try_finally and not self.in_try_except: 1567 self.writeline("if (!__ISNULL(__tmp_exc.arg)) return __tmp_exc.arg;") 1568 else: 1569 self.writeline("if (!__ISNULL(__tmp_exc.arg)) __Throw(__tmp_exc);") 1570 1571 self.indent -= 1 1572 self.writeline("}") 1573 1574 def process_while_node(self, n): 1575 1576 "Process the given while node 'n'." 1577 1578 self.writeline("while (1)") 1579 self.writeline("{") 1580 self.indent += 1 1581 test = self.process_structure_node(n.test) 1582 1583 # Emit the loop termination condition unless "while <true value>" is 1584 # indicated. 1585 1586 if not (isinstance(test, PredefinedConstantRef) and test.value): 1587 1588 # NOTE: This needs to evaluate whether the operand is true or false 1589 # NOTE: according to Python rules. 1590 1591 self.writeline("if (!__BOOL(%s))" % test) 1592 self.writeline("{") 1593 self.indent += 1 1594 if n.else_: 1595 self.process_structure_node(n.else_) 1596 self.writestmt("break;") 1597 self.indent -= 1 1598 self.writeline("}") 1599 1600 in_conditional = self.in_conditional 1601 self.in_conditional = True 1602 self.process_structure_node(n.body) 1603 self.in_conditional = in_conditional 1604 1605 self.indent -= 1 1606 self.writeline("}") 1607 1608 # Output generation. 1609 1610 def start_output(self): 1611 1612 "Write the declarations at the top of each source file." 1613 1614 print >>self.out, """\ 1615 #include "types.h" 1616 #include "exceptions.h" 1617 #include "ops.h" 1618 #include "progconsts.h" 1619 #include "progops.h" 1620 #include "progtypes.h" 1621 #include "main.h" 1622 """ 1623 1624 def start_module(self): 1625 1626 "Write the start of each module's main function." 1627 1628 print >>self.out, "void __main_%s()" % encode_path(self.name) 1629 print >>self.out, "{" 1630 self.indent += 1 1631 self.write_temporaries(self.importer.function_targets.get(self.name)) 1632 1633 def end_module(self): 1634 1635 "End each module by closing its main function." 1636 1637 self.indent -= 1 1638 print >>self.out, "}" 1639 1640 def start_function(self, name): 1641 1642 "Start the function having the given 'name'." 1643 1644 print >>self.out, "__attr %s(__attr __args[])" % encode_function_pointer(name) 1645 print >>self.out, "{" 1646 self.indent += 1 1647 self.write_temporaries(self.importer.function_targets.get(name)) 1648 1649 # Obtain local names from parameters. 1650 1651 parameters = self.importer.function_parameters[name] 1652 locals = self.importer.function_locals[name].keys() 1653 names = [] 1654 1655 for n in locals: 1656 1657 # Filter out special names and parameters. Note that self is a local 1658 # regardless of whether it originally appeared in the parameters or 1659 # not. 1660 1661 if n.startswith("$l") or n in parameters or n == "self": 1662 continue 1663 names.append(encode_path(n)) 1664 1665 # Emit required local names. 1666 1667 if names: 1668 names.sort() 1669 self.writeline("__attr %s;" % ", ".join(names)) 1670 1671 self.write_parameters(name) 1672 1673 def end_function(self, name): 1674 1675 "End the function having the given 'name'." 1676 1677 self.indent -= 1 1678 print >>self.out, "}" 1679 print >>self.out 1680 1681 def write_temporaries(self, targets): 1682 1683 """ 1684 Write temporary storage employed by functions, providing space for the 1685 given number of 'targets'. 1686 """ 1687 1688 targets = targets is not None and "__tmp_targets[%d], " % targets or "" 1689 1690 self.writeline("__ref __tmp_context, __tmp_value;") 1691 self.writeline("__attr %s__tmp_result;" % targets) 1692 self.writeline("__exc __tmp_exc;") 1693 1694 def write_parameters(self, name): 1695 1696 """ 1697 For the function having the given 'name', write definitions of 1698 parameters found in the arguments array. 1699 """ 1700 1701 parameters = self.importer.function_parameters[name] 1702 1703 # Generate any self reference. 1704 1705 if self.is_method(name): 1706 self.writeline("__attr * const self = &__args[0];") 1707 1708 # Generate aliases for the parameters. 1709 1710 for i, parameter in enumerate(parameters): 1711 self.writeline("__attr * const %s = &__args[%d];" % (encode_path(parameter), i+1)) 1712 1713 def start_if(self, first, test_ref): 1714 self.writestmt("%sif (__BOOL(%s))" % (not first and "else " or "", test_ref)) 1715 self.writeline("{") 1716 self.indent += 1 1717 1718 def end_if(self): 1719 self.indent -= 1 1720 self.writeline("}") 1721 1722 def start_else(self): 1723 self.writeline("else") 1724 self.writeline("{") 1725 self.indent += 1 1726 1727 def end_else(self): 1728 self.indent -= 1 1729 self.writeline("}") 1730 1731 def statement(self, expr): 1732 # NOTE: Should never be None. 1733 if not expr: 1734 self.writestmt("...;") 1735 s = str(expr) 1736 if s: 1737 self.writestmt("%s;" % s) 1738 1739 def statements(self, results): 1740 for result in results: 1741 self.statement(result) 1742 1743 def writeline(self, s): 1744 print >>self.out, "%s%s" % (self.pad(), self.indenttext(s, self.indent + 1)) 1745 1746 def writestmt(self, s): 1747 print >>self.out 1748 self.writeline(s) 1749 1750 def write_comment(self, s): 1751 self.writestmt("/* %s */" % s) 1752 1753 def pad(self, extra=0): 1754 return (self.indent + extra) * self.tabstop 1755 1756 def indenttext(self, s, levels): 1757 lines = s.split("\n") 1758 out = [lines[0]] 1759 for line in lines[1:]: 1760 out.append(levels * self.tabstop + line) 1761 if line.endswith("("): 1762 levels += 1 1763 elif line.startswith(")"): 1764 levels -= 1 1765 return "\n".join(out) 1766 1767 # vim: tabstop=4 expandtab shiftwidth=4