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