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