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