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 # Volatile locals for exception handling. 808 809 self.volatile_locals = set() 810 811 # Process any guards defined for the parameters. 812 813 for name in self.importer.function_parameters.get(function_name): 814 self.generate_guard(name) 815 816 # Produce the body and any additional return statement. 817 818 expr = self.process_structure_node(n.code) or PredefinedConstantRef("None") 819 if not isinstance(expr, ReturnRef): 820 self.writestmt("return %s;" % expr) 821 822 self.in_conditional = in_conditional 823 824 self.end_function(function_name) 825 826 def generate_guard(self, name): 827 828 """ 829 Get the accessor details for 'name', found in the current namespace, and 830 generate any guards defined for it. 831 """ 832 833 # Obtain the location, keeping track of assignment versions. 834 835 location = self.get_accessor_location(name) 836 test = self.deducer.accessor_guard_tests.get(location) 837 838 # Generate any guard from the deduced information. 839 840 if test: 841 guard, guard_type = test 842 843 if guard == "specific": 844 ref = first(self.deducer.accessor_all_types[location]) 845 argstr = "&%s" % encode_path(ref.get_origin()) 846 elif guard == "common": 847 ref = first(self.deducer.accessor_all_general_types[location]) 848 argstr = encode_path(encode_type_attribute(ref.get_origin())) 849 else: 850 return 851 852 # Produce an appropriate access to an attribute's value. 853 854 parameters = self.importer.function_parameters.get(self.get_namespace_path()) 855 if parameters and name in parameters: 856 name_to_value = "%s->value" % name 857 else: 858 name_to_value = "%s.value" % name 859 860 # Write a test that raises a TypeError upon failure. 861 862 self.writestmt("if (!__test_%s_%s(%s, %s)) __raise_type_error();" % ( 863 guard, guard_type, name_to_value, argstr)) 864 865 def process_function_node(self, n): 866 867 """ 868 Process the given function, lambda, if expression or list comprehension 869 node 'n', generating any initialisation statements. 870 """ 871 872 # Where a function is declared conditionally, use a separate name for 873 # the definition, and assign the definition to the stated name. 874 875 original_name = n.name 876 877 if self.in_conditional or self.in_function: 878 name = self.get_lambda_name() 879 else: 880 name = n.name 881 882 objpath = self.get_object_path(name) 883 884 # Obtain details of the defaults. 885 886 defaults = self.process_function_defaults(n, name, objpath) 887 if defaults: 888 for default in defaults: 889 self.writeline("%s;" % default) 890 891 # Where a function is set conditionally or where the name may refer to 892 # different values, assign the name. 893 894 ref = self.importer.identify(objpath) 895 896 if self.in_conditional or self.in_function: 897 self.process_assignment_for_object(original_name, compiler.ast.Name(name)) 898 elif not ref.static(): 899 context = self.is_method(objpath) 900 901 self.process_assignment_for_object(original_name, 902 make_expression("__ATTRVALUE(&%s)" % encode_path(objpath))) 903 904 def process_function_defaults(self, n, name, objpath, instance_name=None): 905 906 """ 907 Process the given function or lambda node 'n', initialising defaults 908 that are dynamically set. The given 'name' indicates the name of the 909 function. The given 'objpath' indicates the origin of the function. 910 The given 'instance_name' indicates the name of any separate instance 911 of the function created to hold the defaults. 912 913 Return a list of operations setting defaults on a function instance. 914 """ 915 916 function_name = self.get_object_path(name) 917 function_defaults = self.importer.function_defaults.get(function_name) 918 if not function_defaults: 919 return None 920 921 # Determine whether any unidentified defaults are involved. 922 923 for argname, default in function_defaults: 924 if not default.static(): 925 break 926 else: 927 return None 928 929 # Handle bound methods. 930 931 if not instance_name: 932 instance_name = "&%s" % encode_path(objpath) 933 934 # Where defaults are involved but cannot be identified, obtain a new 935 # instance of the lambda and populate the defaults. 936 937 defaults = [] 938 939 # Join the original defaults with the inspected defaults. 940 941 original_defaults = [(argname, default) for (argname, default) in compiler.ast.get_defaults(n) if default] 942 943 for i, (original, inspected) in enumerate(map(None, original_defaults, function_defaults)): 944 945 # Obtain any reference for the default. 946 947 if original: 948 argname, default = original 949 name_ref = self.process_structure_node(default) 950 elif inspected: 951 argname, default = inspected 952 name_ref = TrResolvedNameRef(argname, default) 953 else: 954 continue 955 956 # Generate default initialisers except when constants are employed. 957 # Constants should be used when populating the function structures. 958 959 if name_ref and not isinstance(name_ref, TrConstantValueRef): 960 defaults.append("__SETDEFAULT(%s, %s, %s)" % (instance_name, i, name_ref)) 961 962 return defaults 963 964 def process_if_node(self, n): 965 966 """ 967 Process the given "if" node 'n'. 968 """ 969 970 first = True 971 for test, body in n.tests: 972 test_ref = self.process_structure_node(test) 973 self.start_if(first, test_ref) 974 975 in_conditional = self.in_conditional 976 self.in_conditional = True 977 self.process_structure_node(body) 978 self.in_conditional = in_conditional 979 980 self.end_if() 981 first = False 982 983 if n.else_: 984 self.start_else() 985 self.process_structure_node(n.else_) 986 self.end_else() 987 988 print >>self.out 989 990 def process_invocation_node(self, n): 991 992 "Process the given invocation node 'n'." 993 994 # Any invocations in the expression will store target details in a 995 # different location. 996 997 self.function_target += 1 998 999 # Process the expression. 1000 1001 expr = self.process_structure_node(n.node) 1002 1003 # Reference the current target again. 1004 1005 self.function_target -= 1 1006 1007 # Obtain details of the invocation expression. 1008 1009 objpath = expr.get_origin() 1010 location = expr.access_location() 1011 1012 # Identified target details. 1013 1014 target = None 1015 target_structure = None 1016 1017 # Specific function target information. 1018 1019 function = None 1020 1021 # Instantiation involvement. 1022 1023 instantiation = False 1024 literal_instantiation = False 1025 1026 # Invocation requirements. 1027 1028 context_required = True 1029 have_access_context = isinstance(expr, AttrResult) 1030 context_identity = have_access_context and expr.context() 1031 parameters = None 1032 1033 # Obtain details of the callable and of its parameters. 1034 1035 # Literals may be instantiated specially. 1036 1037 if expr.is_name() and expr.name.startswith("$L") and objpath: 1038 instantiation = literal_instantiation = objpath 1039 target = encode_literal_instantiator(objpath) 1040 context_required = False 1041 1042 # Identified targets employ function pointers directly. 1043 1044 elif objpath: 1045 parameters = self.importer.function_parameters.get(objpath) 1046 1047 # Class invocation involves instantiators. 1048 1049 if expr.has_kind("<class>"): 1050 instantiation = objpath 1051 target = encode_instantiator_pointer(objpath) 1052 init_ref = self.importer.all_class_attrs[objpath]["__init__"] 1053 target_structure = "&%s" % encode_path(init_ref) 1054 context_required = False 1055 1056 # Only plain functions and bound methods employ function pointers. 1057 1058 elif expr.has_kind("<function>"): 1059 function = objpath 1060 1061 # Test for functions and methods. 1062 1063 context_required = self.is_method(objpath) 1064 accessor_kinds = self.get_accessor_kinds(location) 1065 instance_accessor = accessor_kinds and \ 1066 len(accessor_kinds) == 1 and \ 1067 first(accessor_kinds) == "<instance>" 1068 1069 # Only identify certain bound methods or functions. 1070 1071 if not context_required or instance_accessor: 1072 target = encode_function_pointer(objpath) 1073 1074 # Access bound method defaults even if it is not clear whether 1075 # the accessor is appropriate. 1076 1077 target_structure = "&%s" % encode_path(objpath) 1078 1079 # Other targets are retrieved at run-time. Some information about them 1080 # may be available and be used to provide warnings about argument 1081 # compatibility. 1082 1083 elif self.importer.give_warning("args"): 1084 unsuitable = self.get_referenced_attribute_invocations(location) 1085 1086 if unsuitable: 1087 for ref in unsuitable: 1088 _objpath = ref.get_origin() 1089 num_parameters = len(self.importer.function_parameters[_objpath]) 1090 print >>sys.stderr, \ 1091 "In %s, at line %d, inappropriate number of " \ 1092 "arguments given. Need %d arguments to call %s." % ( 1093 self.get_namespace_path(), n.lineno, num_parameters, 1094 _objpath) 1095 1096 # Determine any readily-accessible target identity. 1097 1098 target_identity = target or expr.is_name() and str(expr) or None 1099 target_var = target_identity or "__tmp_targets[%d]" % self.function_target 1100 1101 if not target_identity: 1102 self.record_temp("__tmp_targets") 1103 1104 if context_identity and context_identity.startswith("__tmp_contexts"): 1105 self.record_temp("__tmp_contexts") 1106 1107 # Arguments are presented in a temporary frame array with any context 1108 # always being the first argument. Where it would be unused, it may be 1109 # set to null. 1110 1111 if context_required: 1112 if have_access_context: 1113 args = ["__ATTRVALUE(%s)" % context_identity] 1114 else: 1115 args = ["__CONTEXT_AS_VALUE(%s)" % target_var] 1116 else: 1117 args = ["__NULL"] 1118 1119 # Complete the array with null values, permitting tests for a complete 1120 # set of arguments. 1121 1122 args += [None] * (parameters is None and len(n.args) or parameters is not None and len(parameters) or 0) 1123 kwcodes = [] 1124 kwargs = [] 1125 1126 # Any invocations in the arguments will store target details in a 1127 # different location. 1128 1129 self.function_target += 1 1130 1131 for i, arg in enumerate(n.args): 1132 argexpr = self.process_structure_node(arg) 1133 1134 # Store a keyword argument, either in the argument list or 1135 # in a separate keyword argument list for subsequent lookup. 1136 1137 if isinstance(arg, compiler.ast.Keyword): 1138 1139 # With knowledge of the target, store the keyword 1140 # argument directly. 1141 1142 if parameters: 1143 try: 1144 argnum = parameters.index(arg.name) 1145 except ValueError: 1146 raise TranslateError("Argument %s is not recognised." % arg.name, 1147 self.get_namespace_path(), n) 1148 args[argnum+1] = str(argexpr) 1149 1150 # Otherwise, store the details in a separate collection. 1151 1152 else: 1153 kwargs.append(str(argexpr)) 1154 kwcodes.append("{%s, %s}" % ( 1155 encode_ppos(arg.name), encode_pcode(arg.name))) 1156 1157 # Store non-keyword arguments in the argument list, rejecting 1158 # superfluous arguments. 1159 1160 else: 1161 try: 1162 args[i+1] = str(argexpr) 1163 except IndexError: 1164 raise TranslateError("Too many arguments specified.", 1165 self.get_namespace_path(), n) 1166 1167 # Reference the current target again. 1168 1169 self.function_target -= 1 1170 1171 # Defaults are added to the frame where arguments are missing. 1172 1173 if parameters: 1174 function_defaults = self.importer.function_defaults.get(objpath) 1175 if function_defaults: 1176 1177 # Visit each default and set any missing arguments. 1178 # Use the target structure to obtain defaults, as opposed to the 1179 # actual function involved. 1180 1181 for i, (argname, default) in enumerate(function_defaults): 1182 argnum = parameters.index(argname) 1183 if not args[argnum+1]: 1184 args[argnum+1] = "__GETDEFAULT(%s, %d)" % (target_structure, i) 1185 1186 # Test for missing arguments. 1187 1188 if None in args: 1189 raise TranslateError("Not all arguments supplied.", 1190 self.get_namespace_path(), n) 1191 1192 # Encode the arguments. 1193 1194 argstr = "__ARGS(%s)" % ", ".join(args) 1195 kwargstr = kwargs and ("__ARGS(%s)" % ", ".join(kwargs)) or "0" 1196 kwcodestr = kwcodes and ("__KWARGS(%s)" % ", ".join(kwcodes)) or "0" 1197 1198 # Where literal instantiation is occurring, add an argument indicating 1199 # the number of values. 1200 1201 if literal_instantiation: 1202 argstr += ", %d" % (len(args) - 1) 1203 1204 # First, the invocation expression is presented. 1205 1206 stages = [] 1207 1208 # Without a known specific callable, the expression provides the target. 1209 1210 if not target or context_required: 1211 if target: 1212 if expr: 1213 stages.append(str(expr)) 1214 elif not target_identity: 1215 stages.append("%s = %s" % (target_var, expr)) 1216 1217 # Any specific callable is then obtained. 1218 1219 if target: 1220 stages.append(target) 1221 1222 # Methods accessed via unidentified accessors are obtained. 1223 1224 elif function: 1225 if context_required: 1226 if have_access_context: 1227 stages.append("__get_function(%s, %s)" % ( 1228 context_identity, target_var)) 1229 else: 1230 stages.append("__get_function(__CONTEXT_AS_VALUE(%s).value, %s)" % ( 1231 target_var, target_var)) 1232 else: 1233 stages.append("__load_via_object(%s.value, __fn__).fn" % target_var) 1234 1235 # With a known target, the function is obtained directly and called. 1236 # By putting the invocation at the end of the final element in the 1237 # instruction sequence (the stages), the result becomes the result of 1238 # the sequence. Moreover, the parameters become part of the sequence 1239 # and thereby participate in a guaranteed evaluation order. 1240 1241 if target or function: 1242 stages[-1] += "(%s)" % argstr 1243 if instantiation: 1244 return InstantiationResult(instantiation, stages) 1245 else: 1246 return InvocationResult(stages) 1247 1248 # With unknown targets, the generic invocation function is applied to 1249 # the callable and argument collections. 1250 1251 else: 1252 stages.append("__invoke(\n%s,\n%d, %d, %s, %s,\n%d, %s\n)" % ( 1253 target_var, 1254 self.always_callable and 1 or 0, 1255 len(kwargs), kwcodestr, kwargstr, 1256 len(args), argstr)) 1257 return InvocationResult(stages) 1258 1259 def always_callable(self, refs): 1260 1261 "Determine whether all 'refs' are callable." 1262 1263 for ref in refs: 1264 if not ref.static(): 1265 return False 1266 else: 1267 origin = ref.final() 1268 if not self.importer.get_attribute(origin, "__fn__"): 1269 return False 1270 return True 1271 1272 def need_default_arguments(self, objpath, nargs): 1273 1274 """ 1275 Return whether any default arguments are needed when invoking the object 1276 given by 'objpath'. 1277 """ 1278 1279 parameters = self.importer.function_parameters.get(objpath) 1280 return nargs < len(parameters) 1281 1282 def process_lambda_node(self, n): 1283 1284 "Process the given lambda node 'n'." 1285 1286 name = self.get_lambda_name() 1287 function_name = self.get_object_path(name) 1288 1289 defaults = self.process_function_defaults(n, name, function_name, "__tmp_value") 1290 1291 # Without defaults, produce an attribute referring to the function. 1292 1293 if not defaults: 1294 return make_expression("__ATTRVALUE(&%s)" % encode_path(function_name)) 1295 1296 # With defaults, copy the function structure and set the defaults on the 1297 # copy. 1298 1299 else: 1300 self.record_temp("__tmp_value") 1301 return make_expression("(__tmp_value = __COPY(&%s, sizeof(%s)), %s, __ATTRVALUE(__tmp_value))" % ( 1302 encode_path(function_name), 1303 encode_symbol("obj", function_name), 1304 ", ".join(defaults))) 1305 1306 def process_logical_node(self, n): 1307 1308 "Process the given operator node 'n'." 1309 1310 self.record_temp("__tmp_result") 1311 1312 conjunction = isinstance(n, compiler.ast.And) 1313 results = [] 1314 1315 for node in n.nodes: 1316 results.append(self.process_structure_node(node)) 1317 1318 return LogicalOperationResult(results, conjunction) 1319 1320 def process_name_node(self, n, expr=None): 1321 1322 "Process the given name node 'n' with the optional assignment 'expr'." 1323 1324 # Determine whether the name refers to a static external entity. 1325 1326 if n.name in predefined_constants: 1327 return PredefinedConstantRef(n.name, expr) 1328 1329 # Convert literal references, operator function names, and print 1330 # function names to references. 1331 1332 elif n.name.startswith("$L") or n.name.startswith("$op") or \ 1333 n.name.startswith("$print"): 1334 1335 ref, paths = self.importer.get_module(self.name).special[n.name] 1336 return TrResolvedNameRef(n.name, ref) 1337 1338 # Temporary names are output program locals. 1339 1340 elif n.name.startswith("$t"): 1341 return TrResolvedNameRef(n.name, Reference("<var>"), expr=expr) 1342 1343 # Get the appropriate name for the name reference, using the same method 1344 # as in the inspector. 1345 1346 path = self.get_namespace_path() 1347 objpath = self.get_object_path(n.name) 1348 1349 # Determine any assigned globals. 1350 1351 globals = self.importer.get_module(self.name).scope_globals.get(path) 1352 1353 # Explicitly declared globals. 1354 1355 if globals and n.name in globals: 1356 objpath = self.get_global_path(n.name) 1357 is_global = True 1358 1359 # Implicitly referenced globals in functions. 1360 1361 elif self.in_function: 1362 is_global = n.name not in self.importer.function_locals[path] 1363 1364 # Implicitly referenced globals elsewhere. 1365 1366 else: 1367 namespace = self.importer.identify(path) 1368 is_global = not self.importer.get_attributes(namespace, n.name) 1369 1370 # Get the static identity of the name. 1371 1372 ref = self.importer.identify(objpath) 1373 if ref and not ref.get_name(): 1374 ref = ref.alias(objpath) 1375 1376 # Obtain any resolved names for non-assignment names. 1377 1378 if not expr and not ref and self.in_function: 1379 locals = self.importer.function_locals.get(path) 1380 ref = locals and locals.get(n.name) 1381 1382 # Determine whether the name refers to a parameter. The generation of 1383 # parameter references is different from other names. 1384 1385 parameters = self.importer.function_parameters.get(path) 1386 parameter = n.name == "self" and self.in_method() or \ 1387 parameters and n.name in parameters 1388 1389 # Find any invocation details. 1390 1391 location = self.get_access_location(n.name) 1392 1393 # Mark any local assignments as volatile in exception blocks. 1394 1395 if expr and self.in_function and not is_global and self.in_try_except: 1396 self.make_volatile(n.name) 1397 1398 # Qualified names are used for resolved static references or for 1399 # static namespace members. The reference should be configured to return 1400 # such names. 1401 1402 return TrResolvedNameRef(n.name, ref, expr=expr, is_global=is_global, parameter=parameter, location=location) 1403 1404 def make_volatile(self, name): 1405 1406 "Record 'name' as volatile in the current namespace." 1407 1408 self.volatile_locals.add(name) 1409 1410 def process_not_node(self, n): 1411 1412 "Process the given operator node 'n'." 1413 1414 return self.make_negation(self.process_structure_node(n.expr)) 1415 1416 def process_raise_node(self, n): 1417 1418 "Process the given raise node 'n'." 1419 1420 # NOTE: Determine which raise statement variants should be permitted. 1421 1422 if n.expr1: 1423 1424 # Names with accompanying arguments are treated like invocations. 1425 1426 if n.expr2: 1427 call = compiler.ast.CallFunc(n.expr1, [n.expr2]) 1428 exc = self.process_structure_node(call) 1429 self.writestmt("__Raise(%s);" % exc) 1430 1431 # Raise instances, testing the kind at run-time if necessary and 1432 # instantiating any non-instance. 1433 1434 else: 1435 exc = self.process_structure_node(n.expr1) 1436 1437 if isinstance(exc, TrInstanceRef): 1438 self.writestmt("__Raise(%s);" % exc) 1439 else: 1440 self.writestmt("__Raise(__ensure_instance(%s));" % exc) 1441 else: 1442 self.writestmt("__Throw(__tmp_exc);") 1443 1444 def process_return_node(self, n): 1445 1446 "Process the given return node 'n'." 1447 1448 expr = self.process_structure_node(n.value) or PredefinedConstantRef("None") 1449 if self.in_try_finally or self.in_try_except: 1450 self.writestmt("__Return(%s);" % expr) 1451 else: 1452 self.writestmt("return %s;" % expr) 1453 1454 return ReturnRef() 1455 1456 def process_try_node(self, n): 1457 1458 """ 1459 Process the given "try...except" node 'n'. 1460 """ 1461 1462 in_try_except = self.in_try_except 1463 self.in_try_except = True 1464 1465 # Use macros to implement exception handling. 1466 1467 self.writestmt("__Try") 1468 self.writeline("{") 1469 self.indent += 1 1470 self.process_structure_node(n.body) 1471 1472 # Put the else statement in another try block that handles any raised 1473 # exceptions and converts them to exceptions that will not be handled by 1474 # the main handling block. 1475 1476 if n.else_: 1477 self.writestmt("__Try") 1478 self.writeline("{") 1479 self.indent += 1 1480 self.process_structure_node(n.else_) 1481 self.indent -= 1 1482 self.writeline("}") 1483 self.writeline("__Catch (__tmp_exc)") 1484 self.writeline("{") 1485 self.indent += 1 1486 self.writeline("if (__tmp_exc.raising) __RaiseElse(__tmp_exc.arg);") 1487 self.writeline("else if (__tmp_exc.completing) __Throw(__tmp_exc);") 1488 self.indent -= 1 1489 self.writeline("}") 1490 1491 # Complete the try block and enter the finally block, if appropriate. 1492 1493 if self.in_try_finally: 1494 self.writestmt("__Complete;") 1495 1496 self.indent -= 1 1497 self.writeline("}") 1498 1499 self.in_try_except = in_try_except 1500 1501 # Handlers are tests within a common handler block. 1502 1503 self.writeline("__Catch (__tmp_exc)") 1504 self.writeline("{") 1505 self.indent += 1 1506 1507 # Introduce an if statement to handle the completion of a try block. 1508 1509 self.process_try_completion() 1510 1511 # Handle exceptions in else blocks converted to __RaiseElse, converting 1512 # them back to normal exceptions. 1513 1514 if n.else_: 1515 self.writeline("else if (__tmp_exc.raising_else) __Raise(__tmp_exc.arg);") 1516 1517 # Exception handling. 1518 1519 for name, var, handler in n.handlers: 1520 1521 # Test for specific exceptions. 1522 1523 if name is not None: 1524 name_ref = self.process_structure_node(name) 1525 self.writeline("else if (__ISINSTANCE(__tmp_exc.arg, %s))" % name_ref) 1526 else: 1527 self.writeline("else if (1)") 1528 1529 self.writeline("{") 1530 self.indent += 1 1531 1532 # Establish the local for the handler. 1533 1534 if var is not None: 1535 self.writestmt("%s;" % self.process_name_node(var, make_expression("__tmp_exc.arg"))) 1536 1537 if handler is not None: 1538 self.process_structure_node(handler) 1539 1540 self.indent -= 1 1541 self.writeline("}") 1542 1543 # Re-raise unhandled exceptions. 1544 1545 self.writeline("else __Throw(__tmp_exc);") 1546 1547 # End the handler block. 1548 1549 self.indent -= 1 1550 self.writeline("}") 1551 print >>self.out 1552 1553 def process_try_finally_node(self, n): 1554 1555 """ 1556 Process the given "try...finally" node 'n'. 1557 """ 1558 1559 in_try_finally = self.in_try_finally 1560 self.in_try_finally = True 1561 1562 # Use macros to implement exception handling. 1563 1564 self.writestmt("__Try") 1565 self.writeline("{") 1566 self.indent += 1 1567 self.process_structure_node(n.body) 1568 self.indent -= 1 1569 self.writeline("}") 1570 1571 self.in_try_finally = in_try_finally 1572 1573 # Finally clauses handle special exceptions. 1574 1575 self.writeline("__Catch (__tmp_exc)") 1576 self.writeline("{") 1577 self.indent += 1 1578 self.process_structure_node(n.final) 1579 1580 # Introduce an if statement to handle the completion of a try block. 1581 1582 self.process_try_completion() 1583 self.writeline("else __Throw(__tmp_exc);") 1584 1585 self.indent -= 1 1586 self.writeline("}") 1587 print >>self.out 1588 1589 def process_try_completion(self): 1590 1591 "Generate a test for the completion of a try block." 1592 1593 self.writestmt("if (__tmp_exc.completing)") 1594 self.writeline("{") 1595 self.indent += 1 1596 1597 # Do not return anything at the module level. 1598 1599 if self.get_namespace_path() != self.name: 1600 1601 # Only use the normal return statement if no surrounding try blocks 1602 # apply. 1603 1604 if not self.in_try_finally and not self.in_try_except: 1605 self.writeline("if (!__ISNULL(__tmp_exc.arg)) return __tmp_exc.arg;") 1606 else: 1607 self.writeline("if (!__ISNULL(__tmp_exc.arg)) __Throw(__tmp_exc);") 1608 1609 self.indent -= 1 1610 self.writeline("}") 1611 1612 def process_while_node(self, n): 1613 1614 "Process the given while node 'n'." 1615 1616 self.writeline("while (1)") 1617 self.writeline("{") 1618 self.indent += 1 1619 test = self.process_structure_node(n.test) 1620 1621 # Emit the loop termination condition unless "while <true value>" is 1622 # indicated. 1623 1624 if not (isinstance(test, PredefinedConstantRef) and test.value): 1625 1626 # Emit a negated test of the continuation condition. 1627 1628 self.start_if(True, self.make_negation(test)) 1629 if n.else_: 1630 self.process_structure_node(n.else_) 1631 self.writestmt("break;") 1632 self.end_if() 1633 1634 in_conditional = self.in_conditional 1635 self.in_conditional = True 1636 self.process_structure_node(n.body) 1637 self.in_conditional = in_conditional 1638 1639 self.indent -= 1 1640 self.writeline("}") 1641 print >>self.out 1642 1643 # Special variable usage. 1644 1645 def get_temp_path(self): 1646 1647 """ 1648 Return the appropriate namespace path for temporary names in the current 1649 namespace. 1650 """ 1651 1652 if self.in_function: 1653 return self.get_namespace_path() 1654 else: 1655 return self.name 1656 1657 def record_temp(self, name): 1658 1659 """ 1660 Record the use of the temporary 'name' in the current namespace. At the 1661 class or module level, the temporary name is associated with the module, 1662 since the variable will then be allocated in the module's own main 1663 program. 1664 """ 1665 1666 path = self.get_temp_path() 1667 1668 init_item(self.temp_usage, path, list) 1669 self.temp_usage[path].append(name) 1670 1671 def remove_temps(self, names): 1672 1673 """ 1674 Remove 'names' from temporary storage allocations, each instance 1675 removing each request for storage. 1676 """ 1677 1678 path = self.get_temp_path() 1679 1680 for name in names: 1681 if self.uses_temp(path, name): 1682 self.temp_usage[path].remove(name) 1683 1684 def uses_temp(self, path, name): 1685 1686 """ 1687 Return whether the given namespace 'path' employs a temporary variable 1688 with the given 'name'. Note that 'path' should only be a module or a 1689 function or method, not a class. 1690 """ 1691 1692 return self.temp_usage.has_key(path) and name in self.temp_usage[path] 1693 1694 def make_negation(self, expr): 1695 1696 "Return a negated form of 'expr'." 1697 1698 result = NegationResult(expr) 1699 1700 # Negation discards the temporary results of its operand. 1701 1702 temps = expr.discards_temporary() 1703 if temps: 1704 self.remove_temps(temps) 1705 1706 return result 1707 1708 # Output generation. 1709 1710 def start_output(self): 1711 1712 "Write the declarations at the top of each source file." 1713 1714 print >>self.out, """\ 1715 #include "types.h" 1716 #include "exceptions.h" 1717 #include "ops.h" 1718 #include "progconsts.h" 1719 #include "progops.h" 1720 #include "progtypes.h" 1721 #include "main.h" 1722 """ 1723 1724 def start_unit(self): 1725 1726 "Record output within a generated function for later use." 1727 1728 self.out = StringIO() 1729 1730 def end_unit(self): 1731 1732 "Restore the output stream." 1733 1734 out = self.out 1735 self.out = self.out_toplevel 1736 return out 1737 1738 def flush_unit(self, name, out): 1739 1740 "Add declarations and generated code." 1741 1742 self.write_temporaries(name) 1743 print >>self.out 1744 out.seek(0) 1745 self.out.write(out.read()) 1746 1747 def start_module(self): 1748 1749 "Write the start of each module's main function." 1750 1751 print >>self.out, "void __main_%s()" % encode_path(self.name) 1752 print >>self.out, "{" 1753 self.indent += 1 1754 1755 # Define temporary variables, excluded from the module structure itself. 1756 1757 tempnames = [] 1758 1759 for n in self.importer.all_module_attrs[self.name]: 1760 if n.startswith("$t"): 1761 tempnames.append(encode_path(n)) 1762 1763 if tempnames: 1764 tempnames.sort() 1765 self.writeline("__attr %s;" % ", ".join(tempnames)) 1766 1767 self.start_unit() 1768 1769 def end_module(self): 1770 1771 "End each module by closing its main function." 1772 1773 out = self.end_unit() 1774 self.flush_unit(self.name, out) 1775 1776 self.indent -= 1 1777 print >>self.out, "}" 1778 1779 def start_function(self, name): 1780 1781 "Start the function having the given 'name'." 1782 1783 print >>self.out, "__attr %s(__attr __args[])" % encode_function_pointer(name) 1784 print >>self.out, "{" 1785 self.indent += 1 1786 1787 self.start_unit() 1788 1789 def end_function(self, name): 1790 1791 "End the function having the given 'name'." 1792 1793 out = self.end_unit() 1794 1795 # Obtain local names from parameters. 1796 1797 parameters = self.importer.function_parameters[name] 1798 locals = self.importer.function_locals[name].keys() 1799 names = [] 1800 volatile_names = [] 1801 1802 for n in locals: 1803 1804 # Filter out special names and parameters. Note that self is a local 1805 # regardless of whether it originally appeared in the parameters or 1806 # not. 1807 1808 if n.startswith("$l") or n in parameters or n == "self": 1809 continue 1810 if n in self.volatile_locals: 1811 volatile_names.append(encode_path(n)) 1812 else: 1813 names.append(encode_path(n)) 1814 1815 # Emit required local names. 1816 1817 if names: 1818 names.sort() 1819 self.writeline("__attr %s;" % ", ".join(names)) 1820 1821 if volatile_names: 1822 volatile_names.sort() 1823 self.writeline("volatile __attr %s;" % ", ".join(volatile_names)) 1824 1825 self.write_parameters(name) 1826 1827 self.flush_unit(name, out) 1828 1829 self.indent -= 1 1830 print >>self.out, "}" 1831 print >>self.out 1832 1833 def write_temporaries(self, name): 1834 1835 "Write temporary storage employed by 'name'." 1836 1837 # Provide space for the given number of targets. 1838 1839 targets = self.importer.function_targets.get(name) 1840 1841 if self.uses_temp(name, "__tmp_targets"): 1842 self.writeline("__attr __tmp_targets[%d];" % targets) 1843 if self.uses_temp(name, "__tmp_contexts"): 1844 self.writeline("__ref __tmp_contexts[%d];" % targets) 1845 1846 # Add temporary variable usage details. 1847 1848 if self.uses_temp(name, "__tmp_private_context"): 1849 self.writeline("__ref __tmp_private_context;") 1850 if self.uses_temp(name, "__tmp_value"): 1851 self.writeline("__ref __tmp_value;") 1852 if self.uses_temp(name, "__tmp_target_value"): 1853 self.writeline("__ref __tmp_target_value;") 1854 if self.uses_temp(name, "__tmp_result"): 1855 self.writeline("__attr __tmp_result;") 1856 1857 module = self.importer.get_module(self.name) 1858 1859 if name in module.exception_namespaces: 1860 self.writeline("__exc __tmp_exc;") 1861 1862 def write_parameters(self, name): 1863 1864 """ 1865 For the function having the given 'name', write definitions of 1866 parameters found in the arguments array. 1867 """ 1868 1869 parameters = self.importer.function_parameters[name] 1870 1871 # Generate any self reference. 1872 1873 if self.is_method(name): 1874 self.writeline("__attr * const self = &__args[0];") 1875 1876 # Generate aliases for the parameters. 1877 1878 for i, parameter in enumerate(parameters): 1879 self.writeline("%s__attr * const %s = &__args[%d];" % ( 1880 parameter in self.volatile_locals and "volatile " or "", 1881 encode_path(parameter), i+1)) 1882 1883 def start_if(self, first, test_ref): 1884 statement = "%sif" % (not first and "else " or "") 1885 1886 # Consume logical results directly. 1887 1888 if isinstance(test_ref, LogicalResult): 1889 self.writeline("%s %s" % (statement, test_ref.apply_test())) 1890 temps = test_ref.discards_temporary() 1891 if temps: 1892 self.remove_temps(temps) 1893 else: 1894 self.writeline("%s (__BOOL(%s))" % (statement, test_ref)) 1895 1896 self.writeline("{") 1897 self.indent += 1 1898 1899 def end_if(self): 1900 self.indent -= 1 1901 self.writeline("}") 1902 1903 def start_else(self): 1904 self.writeline("else") 1905 self.writeline("{") 1906 self.indent += 1 1907 1908 def end_else(self): 1909 self.indent -= 1 1910 self.writeline("}") 1911 1912 def statement(self, expr): 1913 s = str(expr) 1914 if s: 1915 self.writestmt("%s;" % s) 1916 1917 def statements(self, results): 1918 for result in results: 1919 self.statement(result) 1920 1921 def writeline(self, s): 1922 print >>self.out, "%s%s" % (self.pad(), self.indenttext(s, self.indent + 1)) 1923 1924 def writestmt(self, s): 1925 self.writeline(s) 1926 1927 def write_comment(self, s): 1928 self.writestmt("/* %s */" % s) 1929 1930 def pad(self, extra=0): 1931 return (self.indent + extra) * self.tabstop 1932 1933 def indenttext(self, s, levels): 1934 lines = s.split("\n") 1935 out = [lines[0]] 1936 for line in lines[1:]: 1937 out.append(levels * self.tabstop + line) 1938 if line.endswith("("): 1939 levels += 1 1940 elif line.startswith(")"): 1941 levels -= 1 1942 return "\n".join(out) 1943 1944 # vim: tabstop=4 expandtab shiftwidth=4