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