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