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