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