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