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