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, %r)" % (self.s, self.refs, self.accessor_kinds) 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 target_structure = None 1081 function = None 1082 instantiation = False 1083 literal_instantiation = False 1084 context_required = True 1085 1086 # Obtain details of the callable. 1087 1088 # Literals may be instantiated specially. 1089 1090 if expr.is_name() and expr.name.startswith("$L") and objpath: 1091 instantiation = literal_instantiation = objpath 1092 parameters = None 1093 target = encode_literal_instantiator(objpath) 1094 context_required = False 1095 1096 # Identified targets employ function pointers directly. 1097 1098 elif objpath: 1099 parameters = self.importer.function_parameters.get(objpath) 1100 1101 # Class invocation involves instantiators. 1102 1103 if expr.has_kind("<class>"): 1104 instantiation = objpath 1105 target = encode_instantiator_pointer(objpath) 1106 target_structure = "&%s" % encode_bound_reference("%s.__init__" % objpath) 1107 context_required = False 1108 1109 # Only plain functions and bound methods employ function pointers. 1110 1111 elif expr.has_kind("<function>"): 1112 function = objpath 1113 1114 # Test for functions and methods. 1115 1116 context_required = self.is_method(objpath) 1117 accessor_kinds = expr.get_accessor_kinds() 1118 instance_accessor = accessor_kinds and \ 1119 len(accessor_kinds) == 1 and \ 1120 first(accessor_kinds) == "<instance>" 1121 1122 # Only identify certain bound methods or functions. 1123 1124 if not context_required or instance_accessor: 1125 target = encode_function_pointer(objpath) 1126 1127 # Access bound method defaults even if it is not clear whether 1128 # the accessor is appropriate. 1129 1130 target_structure = self.is_method(objpath) and \ 1131 "&%s" % encode_bound_reference(objpath) or \ 1132 "&%s" % encode_path(objpath) 1133 1134 # Other targets are retrieved at run-time. 1135 1136 else: 1137 parameters = None 1138 1139 # Arguments are presented in a temporary frame array with any context 1140 # always being the first argument. Where it would be unused, it may be 1141 # set to null. 1142 1143 if context_required: 1144 args = ["__CONTEXT_AS_VALUE(__tmp_targets[%d])" % self.function_target] 1145 else: 1146 args = ["(__attr) {0, 0}"] 1147 1148 args += [None] * (not parameters and len(n.args) or parameters and len(parameters) or 0) 1149 kwcodes = [] 1150 kwargs = [] 1151 1152 # Any invocations in the arguments will store target details in a 1153 # different location. 1154 1155 self.function_target += 1 1156 1157 for i, arg in enumerate(n.args): 1158 argexpr = self.process_structure_node(arg) 1159 1160 # Store a keyword argument, either in the argument list or 1161 # in a separate keyword argument list for subsequent lookup. 1162 1163 if isinstance(arg, compiler.ast.Keyword): 1164 1165 # With knowledge of the target, store the keyword 1166 # argument directly. 1167 1168 if parameters: 1169 try: 1170 argnum = parameters.index(arg.name) 1171 except ValueError: 1172 raise TranslateError("Argument %s is not recognised." % arg.name, 1173 self.get_namespace_path(), n) 1174 args[argnum+1] = str(argexpr) 1175 1176 # Otherwise, store the details in a separate collection. 1177 1178 else: 1179 kwargs.append(str(argexpr)) 1180 kwcodes.append("{%s, %s}" % ( 1181 encode_symbol("ppos", arg.name), 1182 encode_symbol("pcode", arg.name))) 1183 1184 # Store non-keyword arguments in the argument list, rejecting 1185 # superfluous arguments. 1186 1187 else: 1188 try: 1189 args[i+1] = str(argexpr) 1190 except IndexError: 1191 raise TranslateError("Too many arguments specified.", 1192 self.get_namespace_path(), n) 1193 1194 # Reference the current target again. 1195 1196 self.function_target -= 1 1197 1198 # Defaults are added to the frame where arguments are missing. 1199 1200 if parameters: 1201 function_defaults = self.importer.function_defaults.get(objpath) 1202 if function_defaults: 1203 1204 # Visit each default and set any missing arguments. 1205 # Use the target structure to obtain defaults, as opposed to the 1206 # actual function involved. 1207 1208 for i, (argname, default) in enumerate(function_defaults): 1209 argnum = parameters.index(argname) 1210 if not args[argnum+1]: 1211 args[argnum+1] = "__GETDEFAULT(%s, %d)" % (target_structure, i) 1212 1213 # Test for missing arguments. 1214 1215 if None in args: 1216 raise TranslateError("Not all arguments supplied.", 1217 self.get_namespace_path(), n) 1218 1219 # Encode the arguments. 1220 1221 argstr = "__ARGS(%s)" % ", ".join(args) 1222 kwargstr = kwargs and ("__ARGS(%s)" % ", ".join(kwargs)) or "0" 1223 kwcodestr = kwcodes and ("__KWARGS(%s)" % ", ".join(kwcodes)) or "0" 1224 1225 # Where literal instantiation is occurring, add an argument indicating 1226 # the number of values. 1227 1228 if literal_instantiation: 1229 argstr += ", %d" % (len(args) - 1) 1230 1231 # First, the invocation expression is presented. 1232 1233 stages = [] 1234 1235 # Without a known specific callable, the expression provides the target. 1236 1237 if not target or context_required: 1238 stages.append("__tmp_targets[%d] = %s" % (self.function_target, expr)) 1239 1240 # Any specific callable is then obtained. 1241 1242 if target: 1243 stages.append(target) 1244 elif function: 1245 stages.append("__load_via_object(__tmp_targets[%d].value, %s).fn" % ( 1246 self.function_target, encode_symbol("pos", "__fn__"))) 1247 1248 # With a known target, the function is obtained directly and called. 1249 1250 if target or function: 1251 output = "(\n%s\n)(%s)" % (",\n".join(stages), argstr) 1252 1253 # With unknown targets, the generic invocation function is applied to 1254 # the callable and argument collections. 1255 1256 else: 1257 output = "(%s, __invoke(\n__tmp_targets[%d],\n%d, %d, %s, %s,\n%d, %s\n))" % ( 1258 ",\n".join(stages), 1259 self.function_target, 1260 self.always_callable and 1 or 0, 1261 len(kwargs), kwcodestr, kwargstr, 1262 len(args), argstr) 1263 1264 if instantiation: 1265 return TrInstanceRef(instantiation, output) 1266 else: 1267 return make_expression(output) 1268 1269 def always_callable(self, refs): 1270 1271 "Determine whether all 'refs' are callable." 1272 1273 for ref in refs: 1274 if not ref.static(): 1275 return False 1276 else: 1277 origin = ref.final() 1278 if not self.importer.get_attribute(origin, "__fn__"): 1279 return False 1280 return True 1281 1282 def need_default_arguments(self, objpath, nargs): 1283 1284 """ 1285 Return whether any default arguments are needed when invoking the object 1286 given by 'objpath'. 1287 """ 1288 1289 parameters = self.importer.function_parameters.get(objpath) 1290 return nargs < len(parameters) 1291 1292 def process_lambda_node(self, n): 1293 1294 "Process the given lambda node 'n'." 1295 1296 name = self.get_lambda_name() 1297 function_name = self.get_object_path(name) 1298 1299 defaults = self.process_function_defaults(n, name, function_name, "__tmp_value") 1300 1301 # Without defaults, produce an attribute referring to the function. 1302 1303 if not defaults: 1304 return make_expression("((__attr) {0, &%s})" % encode_path(function_name)) 1305 1306 # With defaults, copy the function structure and set the defaults on the 1307 # copy. 1308 1309 else: 1310 return make_expression("(__tmp_value = __COPY(&%s, sizeof(%s)), %s, (__attr) {0, __tmp_value})" % ( 1311 encode_path(function_name), 1312 encode_symbol("obj", function_name), 1313 ", ".join(defaults))) 1314 1315 def process_logical_node(self, n): 1316 1317 """ 1318 Process the given operator node 'n'. 1319 1320 Convert ... to ... 1321 1322 <a> and <b> 1323 (__tmp_result = <a>, !__BOOL(__tmp_result)) ? __tmp_result : <b> 1324 1325 <a> or <b> 1326 (__tmp_result = <a>, __BOOL(__tmp_result)) ? __tmp_result : <b> 1327 """ 1328 1329 if isinstance(n, compiler.ast.And): 1330 op = "!" 1331 else: 1332 op = "" 1333 1334 results = [] 1335 1336 for node in n.nodes[:-1]: 1337 expr = self.process_structure_node(node) 1338 results.append("(__tmp_result = %s, %s__BOOL(__tmp_result)) ? __tmp_result : " % (expr, op)) 1339 1340 expr = self.process_structure_node(n.nodes[-1]) 1341 results.append(str(expr)) 1342 1343 return make_expression("(%s)" % "".join(results)) 1344 1345 def process_name_node(self, n, expr=None): 1346 1347 "Process the given name node 'n' with the optional assignment 'expr'." 1348 1349 # Determine whether the name refers to a static external entity. 1350 1351 if n.name in predefined_constants: 1352 return PredefinedConstantRef(n.name, expr) 1353 1354 # Convert literal references, operator function names, and print 1355 # function names to references. 1356 1357 elif n.name.startswith("$L") or n.name.startswith("$op") or \ 1358 n.name.startswith("$print"): 1359 1360 ref, paths = self.importer.get_module(self.name).special[n.name] 1361 return TrResolvedNameRef(n.name, ref) 1362 1363 # Get the appropriate name for the name reference, using the same method 1364 # as in the inspector. 1365 1366 path = self.get_namespace_path() 1367 objpath = self.get_object_path(n.name) 1368 1369 # Determine any assigned globals. 1370 1371 globals = self.importer.get_module(self.name).scope_globals.get(path) 1372 if globals and n.name in globals: 1373 objpath = self.get_global_path(n.name) 1374 1375 # Get the static identity of the name. 1376 1377 ref = self.importer.identify(objpath) 1378 if ref and not ref.get_name(): 1379 ref = ref.alias(objpath) 1380 1381 # Obtain any resolved names for non-assignment names. 1382 1383 if not expr and not ref and self.in_function: 1384 locals = self.importer.function_locals.get(path) 1385 ref = locals and locals.get(n.name) 1386 1387 # Determine whether the name refers to a parameter. The generation of 1388 # parameter references is different from other names. 1389 1390 parameters = self.importer.function_parameters.get(path) 1391 parameter = n.name == "self" and self.in_method() or \ 1392 parameters and n.name in parameters 1393 1394 # Qualified names are used for resolved static references or for 1395 # static namespace members. The reference should be configured to return 1396 # such names. 1397 1398 return TrResolvedNameRef(n.name, ref, expr=expr, parameter=parameter) 1399 1400 def process_not_node(self, n): 1401 1402 "Process the given operator node 'n'." 1403 1404 return make_expression("(__BOOL(%s) ? %s : %s)" % 1405 (self.process_structure_node(n.expr), PredefinedConstantRef("False"), 1406 PredefinedConstantRef("True"))) 1407 1408 def process_raise_node(self, n): 1409 1410 "Process the given raise node 'n'." 1411 1412 # NOTE: Determine which raise statement variants should be permitted. 1413 1414 if n.expr1: 1415 exc = self.process_structure_node(n.expr1) 1416 1417 # Raise instances, testing the kind at run-time if necessary and 1418 # instantiating any non-instance. 1419 1420 if isinstance(exc, TrInstanceRef): 1421 self.writestmt("__Raise(%s);" % exc) 1422 else: 1423 self.writestmt("__Raise(__ensure_instance(%s));" % exc) 1424 else: 1425 self.writestmt("__Throw(__tmp_exc);") 1426 1427 def process_return_node(self, n): 1428 1429 "Process the given return node 'n'." 1430 1431 expr = self.process_structure_node(n.value) or PredefinedConstantRef("None") 1432 if self.in_try_finally or self.in_try_except: 1433 self.writestmt("__Return(%s);" % expr) 1434 else: 1435 self.writestmt("return %s;" % expr) 1436 1437 return ReturnRef() 1438 1439 def process_try_node(self, n): 1440 1441 """ 1442 Process the given "try...except" node 'n'. 1443 """ 1444 1445 in_try_except = self.in_try_except 1446 self.in_try_except = True 1447 1448 # Use macros to implement exception handling. 1449 1450 self.writestmt("__Try") 1451 self.writeline("{") 1452 self.indent += 1 1453 self.process_structure_node(n.body) 1454 1455 # Put the else statement in another try block that handles any raised 1456 # exceptions and converts them to exceptions that will not be handled by 1457 # the main handling block. 1458 1459 if n.else_: 1460 self.writestmt("__Try") 1461 self.writeline("{") 1462 self.indent += 1 1463 self.process_structure_node(n.else_) 1464 self.indent -= 1 1465 self.writeline("}") 1466 self.writeline("__Catch (__tmp_exc)") 1467 self.writeline("{") 1468 self.indent += 1 1469 self.writeline("if (__tmp_exc.raising) __RaiseElse(__tmp_exc.arg);") 1470 self.writeline("else if (__tmp_exc.completing) __Throw(__tmp_exc);") 1471 self.indent -= 1 1472 self.writeline("}") 1473 1474 # Complete the try block and enter the finally block, if appropriate. 1475 1476 if self.in_try_finally: 1477 self.writestmt("__Complete;") 1478 1479 self.indent -= 1 1480 self.writeline("}") 1481 1482 self.in_try_except = in_try_except 1483 1484 # Handlers are tests within a common handler block. 1485 1486 self.writeline("__Catch (__tmp_exc)") 1487 self.writeline("{") 1488 self.indent += 1 1489 1490 # Introduce an if statement to handle the completion of a try block. 1491 1492 self.process_try_completion() 1493 1494 # Handle exceptions in else blocks converted to __RaiseElse, converting 1495 # them back to normal exceptions. 1496 1497 if n.else_: 1498 self.writeline("else if (__tmp_exc.raising_else) __Raise(__tmp_exc.arg);") 1499 1500 # Exception handling. 1501 1502 for name, var, handler in n.handlers: 1503 1504 # Test for specific exceptions. 1505 1506 if name is not None: 1507 name_ref = self.process_structure_node(name) 1508 self.writeline("else if (__BOOL(__fn_native_introspection_isinstance((__attr[]) {{0, 0}, __tmp_exc.arg, %s})))" % name_ref) 1509 else: 1510 self.writeline("else if (1)") 1511 1512 self.writeline("{") 1513 self.indent += 1 1514 1515 # Establish the local for the handler. 1516 1517 if var is not None: 1518 self.writestmt("%s;" % self.process_name_node(var, make_expression("__tmp_exc.arg"))) 1519 1520 if handler is not None: 1521 self.process_structure_node(handler) 1522 1523 self.indent -= 1 1524 self.writeline("}") 1525 1526 # Re-raise unhandled exceptions. 1527 1528 self.writeline("else __Throw(__tmp_exc);") 1529 1530 # End the handler block. 1531 1532 self.indent -= 1 1533 self.writeline("}") 1534 1535 def process_try_finally_node(self, n): 1536 1537 """ 1538 Process the given "try...finally" node 'n'. 1539 """ 1540 1541 in_try_finally = self.in_try_finally 1542 self.in_try_finally = True 1543 1544 # Use macros to implement exception handling. 1545 1546 self.writestmt("__Try") 1547 self.writeline("{") 1548 self.indent += 1 1549 self.process_structure_node(n.body) 1550 self.indent -= 1 1551 self.writeline("}") 1552 1553 self.in_try_finally = in_try_finally 1554 1555 # Finally clauses handle special exceptions. 1556 1557 self.writeline("__Catch (__tmp_exc)") 1558 self.writeline("{") 1559 self.indent += 1 1560 self.process_structure_node(n.final) 1561 1562 # Introduce an if statement to handle the completion of a try block. 1563 1564 self.process_try_completion() 1565 self.writeline("else __Throw(__tmp_exc);") 1566 1567 self.indent -= 1 1568 self.writeline("}") 1569 1570 def process_try_completion(self): 1571 1572 "Generate a test for the completion of a try block." 1573 1574 self.writestmt("if (__tmp_exc.completing)") 1575 self.writeline("{") 1576 self.indent += 1 1577 1578 # Do not return anything at the module level. 1579 1580 if self.get_namespace_path() != self.name: 1581 1582 # Only use the normal return statement if no surrounding try blocks 1583 # apply. 1584 1585 if not self.in_try_finally and not self.in_try_except: 1586 self.writeline("if (!__ISNULL(__tmp_exc.arg)) return __tmp_exc.arg;") 1587 else: 1588 self.writeline("if (!__ISNULL(__tmp_exc.arg)) __Throw(__tmp_exc);") 1589 1590 self.indent -= 1 1591 self.writeline("}") 1592 1593 def process_while_node(self, n): 1594 1595 "Process the given while node 'n'." 1596 1597 self.writeline("while (1)") 1598 self.writeline("{") 1599 self.indent += 1 1600 test = self.process_structure_node(n.test) 1601 1602 # Emit the loop termination condition unless "while <true value>" is 1603 # indicated. 1604 1605 if not (isinstance(test, PredefinedConstantRef) and test.value): 1606 1607 # NOTE: This needs to evaluate whether the operand is true or false 1608 # NOTE: according to Python rules. 1609 1610 self.writeline("if (!__BOOL(%s))" % test) 1611 self.writeline("{") 1612 self.indent += 1 1613 if n.else_: 1614 self.process_structure_node(n.else_) 1615 self.writestmt("break;") 1616 self.indent -= 1 1617 self.writeline("}") 1618 1619 in_conditional = self.in_conditional 1620 self.in_conditional = True 1621 self.process_structure_node(n.body) 1622 self.in_conditional = in_conditional 1623 1624 self.indent -= 1 1625 self.writeline("}") 1626 1627 # Output generation. 1628 1629 def start_output(self): 1630 1631 "Write the declarations at the top of each source file." 1632 1633 print >>self.out, """\ 1634 #include "types.h" 1635 #include "exceptions.h" 1636 #include "ops.h" 1637 #include "progconsts.h" 1638 #include "progops.h" 1639 #include "progtypes.h" 1640 #include "main.h" 1641 """ 1642 1643 def start_module(self): 1644 1645 "Write the start of each module's main function." 1646 1647 print >>self.out, "void __main_%s()" % encode_path(self.name) 1648 print >>self.out, "{" 1649 self.indent += 1 1650 self.write_temporaries(self.importer.function_targets.get(self.name)) 1651 1652 def end_module(self): 1653 1654 "End each module by closing its main function." 1655 1656 self.indent -= 1 1657 print >>self.out, "}" 1658 1659 def start_function(self, name): 1660 1661 "Start the function having the given 'name'." 1662 1663 print >>self.out, "__attr %s(__attr __args[])" % encode_function_pointer(name) 1664 print >>self.out, "{" 1665 self.indent += 1 1666 self.write_temporaries(self.importer.function_targets.get(name)) 1667 1668 # Obtain local names from parameters. 1669 1670 parameters = self.importer.function_parameters[name] 1671 locals = self.importer.function_locals[name].keys() 1672 names = [] 1673 1674 for n in locals: 1675 1676 # Filter out special names and parameters. Note that self is a local 1677 # regardless of whether it originally appeared in the parameters or 1678 # not. 1679 1680 if n.startswith("$l") or n in parameters or n == "self": 1681 continue 1682 names.append(encode_path(n)) 1683 1684 # Emit required local names. 1685 1686 if names: 1687 names.sort() 1688 self.writeline("__attr %s;" % ", ".join(names)) 1689 1690 self.write_parameters(name) 1691 1692 def end_function(self, name): 1693 1694 "End the function having the given 'name'." 1695 1696 self.indent -= 1 1697 print >>self.out, "}" 1698 print >>self.out 1699 1700 def write_temporaries(self, targets): 1701 1702 """ 1703 Write temporary storage employed by functions, providing space for the 1704 given number of 'targets'. 1705 """ 1706 1707 targets = targets is not None and "__tmp_targets[%d], " % targets or "" 1708 1709 self.writeline("__ref __tmp_context, __tmp_value, __tmp_target_value;") 1710 self.writeline("__attr %s__tmp_result;" % targets) 1711 self.writeline("__exc __tmp_exc;") 1712 1713 def write_parameters(self, name): 1714 1715 """ 1716 For the function having the given 'name', write definitions of 1717 parameters found in the arguments array. 1718 """ 1719 1720 parameters = self.importer.function_parameters[name] 1721 1722 # Generate any self reference. 1723 1724 if self.is_method(name): 1725 self.writeline("__attr * const self = &__args[0];") 1726 1727 # Generate aliases for the parameters. 1728 1729 for i, parameter in enumerate(parameters): 1730 self.writeline("__attr * const %s = &__args[%d];" % (encode_path(parameter), i+1)) 1731 1732 def start_if(self, first, test_ref): 1733 self.writestmt("%sif (__BOOL(%s))" % (not first and "else " or "", test_ref)) 1734 self.writeline("{") 1735 self.indent += 1 1736 1737 def end_if(self): 1738 self.indent -= 1 1739 self.writeline("}") 1740 1741 def start_else(self): 1742 self.writeline("else") 1743 self.writeline("{") 1744 self.indent += 1 1745 1746 def end_else(self): 1747 self.indent -= 1 1748 self.writeline("}") 1749 1750 def statement(self, expr): 1751 # NOTE: Should never be None. 1752 if not expr: 1753 self.writestmt("...;") 1754 s = str(expr) 1755 if s: 1756 self.writestmt("%s;" % s) 1757 1758 def statements(self, results): 1759 for result in results: 1760 self.statement(result) 1761 1762 def writeline(self, s): 1763 print >>self.out, "%s%s" % (self.pad(), self.indenttext(s, self.indent + 1)) 1764 1765 def writestmt(self, s): 1766 print >>self.out 1767 self.writeline(s) 1768 1769 def write_comment(self, s): 1770 self.writestmt("/* %s */" % s) 1771 1772 def pad(self, extra=0): 1773 return (self.indent + extra) * self.tabstop 1774 1775 def indenttext(self, s, levels): 1776 lines = s.split("\n") 1777 out = [lines[0]] 1778 for line in lines[1:]: 1779 out.append(levels * self.tabstop + line) 1780 if line.endswith("("): 1781 levels += 1 1782 elif line.startswith(")"): 1783 levels -= 1 1784 return "\n".join(out) 1785 1786 # vim: tabstop=4 expandtab shiftwidth=4