1 #!/usr/bin/env python 2 3 """ 4 Inspect and obtain module structure. 5 6 Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013, 7 2014, 2015, 2016 Paul Boddie <paul@boddie.org.uk> 8 9 This program is free software; you can redistribute it and/or modify it under 10 the terms of the GNU General Public License as published by the Free Software 11 Foundation; either version 3 of the License, or (at your option) any later 12 version. 13 14 This program is distributed in the hope that it will be useful, but WITHOUT 15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 16 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 17 details. 18 19 You should have received a copy of the GNU General Public License along with 20 this program. If not, see <http://www.gnu.org/licenses/>. 21 """ 22 23 from branching import BranchTracker 24 from common import get_argnames, init_item, predefined_constants 25 from modules import BasicModule, CacheWritingModule, InspectionNaming 26 from errors import InspectError 27 from referencing import Reference 28 from resolving import NameResolving 29 from results import AccessRef, InstanceRef, InvocationRef, LiteralSequenceRef, \ 30 LocalNameRef, NameRef, ResolvedNameRef 31 import compiler 32 import sys 33 34 class InspectedModule(BasicModule, CacheWritingModule, NameResolving, InspectionNaming): 35 36 "A module inspector." 37 38 def __init__(self, name, importer): 39 40 "Initialise the module with basic details." 41 42 BasicModule.__init__(self, name, importer) 43 44 self.in_class = False 45 self.in_conditional = False 46 self.global_attr_accesses = {} 47 48 # Usage tracking. 49 50 self.trackers = [] 51 self.attr_accessor_branches = {} 52 53 def __repr__(self): 54 return "InspectedModule(%r, %r)" % (self.name, self.importer) 55 56 # Principal methods. 57 58 def parse(self, filename): 59 60 "Parse the file having the given 'filename'." 61 62 self.parse_file(filename) 63 64 # Inspect the module. 65 66 self.start_tracking_in_module() 67 68 # Detect and record imports and globals declared in the module. 69 70 self.assign_general_local("__name__", self.get_constant("str", self.name)) 71 self.assign_general_local("__file__", self.get_constant("str", filename)) 72 self.process_structure(self.astnode) 73 74 # Set the class of the module after the definition has occurred. 75 76 ref = self.get_builtin("object") 77 self.set_name("__class__", ref) 78 79 # Get module-level attribute usage details. 80 81 self.stop_tracking_in_module() 82 83 # Collect external name references. 84 85 self.collect_names() 86 87 def complete(self): 88 89 "Complete the module inspection." 90 91 # Resolve names not definitively mapped to objects. 92 93 self.resolve() 94 95 # Define the invocation requirements in each namespace. 96 97 self.set_invocation_usage() 98 99 # Propagate to the importer information needed in subsequent activities. 100 101 self.propagate() 102 103 # Accessory methods. 104 105 def collect_names(self): 106 107 "Collect the names used by each scope." 108 109 for path in self.names_used.keys(): 110 self.collect_names_for_path(path) 111 112 def collect_names_for_path(self, path): 113 114 """ 115 Collect the names used by the given 'path'. These are propagated to the 116 importer in advance of any dependency resolution. 117 """ 118 119 names = self.names_used.get(path) 120 if not names: 121 return 122 123 in_function = self.function_locals.has_key(path) 124 125 for name in names: 126 if name in predefined_constants or in_function and name in self.function_locals[path]: 127 continue 128 129 # Find local definitions (within dynamic namespaces). 130 131 key = "%s.%s" % (path, name) 132 ref = self.get_resolved_object(key) 133 if ref: 134 self.set_name_reference(key, ref) 135 continue 136 137 # Find global or known built-in definitions. 138 139 ref = self.get_resolved_global_or_builtin(name) 140 if ref: 141 self.set_name_reference(key, ref) 142 continue 143 144 # Find presumed built-in definitions. 145 146 ref = self.get_builtin(name) 147 self.set_name_reference(key, ref) 148 149 def set_name_reference(self, path, ref): 150 151 "Map the given name 'path' to 'ref'." 152 153 self.importer.all_name_references[path] = self.name_references[path] = ref 154 155 def get_resolved_global_or_builtin(self, name): 156 157 "Return the resolved global or built-in object with the given 'name'." 158 159 # In some circumstances, the name is neither global nor recognised by 160 # the importer. It is then assumed to be a general built-in. 161 162 return self.get_global(name) or \ 163 self.importer.get_object("__builtins__.%s" % name) 164 165 # Module structure traversal. 166 167 def process_structure_node(self, n): 168 169 "Process the individual node 'n'." 170 171 # Module global detection. 172 173 if isinstance(n, compiler.ast.Global): 174 self.process_global_node(n) 175 176 # Module import declarations. 177 178 elif isinstance(n, compiler.ast.From): 179 self.process_from_node(n) 180 181 elif isinstance(n, compiler.ast.Import): 182 self.process_import_node(n) 183 184 # Nodes using operator module functions. 185 186 elif isinstance(n, compiler.ast.Operator): 187 return self.process_operator_node(n) 188 189 elif isinstance(n, compiler.ast.AugAssign): 190 self.process_augassign_node(n) 191 192 elif isinstance(n, compiler.ast.Compare): 193 return self.process_compare_node(n) 194 195 elif isinstance(n, compiler.ast.Slice): 196 return self.process_slice_node(n) 197 198 elif isinstance(n, compiler.ast.Sliceobj): 199 return self.process_sliceobj_node(n) 200 201 elif isinstance(n, compiler.ast.Subscript): 202 return self.process_subscript_node(n) 203 204 # Namespaces within modules. 205 206 elif isinstance(n, compiler.ast.Class): 207 self.process_class_node(n) 208 209 elif isinstance(n, compiler.ast.Function): 210 self.process_function_node(n, n.name) 211 212 elif isinstance(n, compiler.ast.Lambda): 213 return self.process_lambda_node(n) 214 215 # Assignments. 216 217 elif isinstance(n, compiler.ast.Assign): 218 219 # Handle each assignment node. 220 221 for node in n.nodes: 222 self.process_assignment_node(node, n.expr) 223 224 # Assignments within non-Assign nodes. 225 226 elif isinstance(n, compiler.ast.AssName): 227 self.process_assignment_node(n, None) 228 229 elif isinstance(n, compiler.ast.AssAttr): 230 self.process_attribute_access(n) 231 232 # Accesses. 233 234 elif isinstance(n, compiler.ast.Getattr): 235 return self.process_attribute_access(n) 236 237 # Name recording for later testing. 238 239 elif isinstance(n, compiler.ast.Name): 240 return self.process_name_node(n) 241 242 # Conditional statement tracking. 243 244 elif isinstance(n, compiler.ast.For): 245 self.process_for_node(n) 246 247 elif isinstance(n, compiler.ast.While): 248 self.process_while_node(n) 249 250 elif isinstance(n, compiler.ast.If): 251 self.process_if_node(n) 252 253 elif isinstance(n, (compiler.ast.And, compiler.ast.Or)): 254 return self.process_logical_node(n) 255 256 # Exception control-flow tracking. 257 258 elif isinstance(n, compiler.ast.TryExcept): 259 self.process_try_node(n) 260 261 elif isinstance(n, compiler.ast.TryFinally): 262 self.process_try_finally_node(n) 263 264 # Control-flow modification statements. 265 266 elif isinstance(n, compiler.ast.Break): 267 self.trackers[-1].suspend_broken_branch() 268 269 elif isinstance(n, compiler.ast.Continue): 270 self.trackers[-1].suspend_continuing_branch() 271 272 elif isinstance(n, compiler.ast.Raise): 273 self.process_structure(n) 274 self.trackers[-1].abandon_branch() 275 276 elif isinstance(n, compiler.ast.Return): 277 self.process_structure(n) 278 self.trackers[-1].abandon_returning_branch() 279 280 # Invocations. 281 282 elif isinstance(n, compiler.ast.CallFunc): 283 return self.process_invocation_node(n) 284 285 # Constant usage. 286 287 elif isinstance(n, compiler.ast.Const): 288 return self.get_literal_instance(n, n.value.__class__.__name__) 289 290 elif isinstance(n, compiler.ast.Dict): 291 return self.get_literal_instance(n, "dict") 292 293 elif isinstance(n, compiler.ast.List): 294 return self.get_literal_instance(n, "list") 295 296 elif isinstance(n, compiler.ast.Tuple): 297 return self.get_literal_instance(n, "tuple") 298 299 # Unsupported nodes. 300 301 elif isinstance(n, compiler.ast.GenExpr): 302 raise InspectError("Generator expressions are not supported.", self.get_namespace_path(), n) 303 304 elif isinstance(n, compiler.ast.IfExp): 305 raise InspectError("If-else expressions are not supported.", self.get_namespace_path(), n) 306 307 elif isinstance(n, compiler.ast.ListComp): 308 raise InspectError("List comprehensions are not supported.", self.get_namespace_path(), n) 309 310 # All other nodes are processed depth-first. 311 312 else: 313 self.process_structure(n) 314 315 # By default, no expression details are returned. 316 317 return None 318 319 # Specific node handling. 320 321 def process_assignment_node(self, n, expr): 322 323 "Process the individual node 'n' to be assigned the contents of 'expr'." 324 325 # Names and attributes are assigned the entire expression. 326 327 if isinstance(n, compiler.ast.AssName): 328 329 name_ref = expr and self.process_structure_node(expr) 330 331 # Name assignments populate either function namespaces or the 332 # general namespace hierarchy. 333 334 self.assign_general_local(n.name, name_ref) 335 336 # Record usage of the name. 337 338 self.record_name(n.name) 339 340 elif isinstance(n, compiler.ast.AssAttr): 341 if expr: self.process_structure_node(expr) 342 self.process_attribute_access(n) 343 344 # Lists and tuples are matched against the expression and their 345 # items assigned to expression items. 346 347 elif isinstance(n, (compiler.ast.AssList, compiler.ast.AssTuple)): 348 self.process_assignment_node_items(n, expr) 349 350 # Slices and subscripts are permitted within assignment nodes. 351 352 elif isinstance(n, compiler.ast.Slice): 353 self.process_slice_node(n, expr) 354 355 elif isinstance(n, compiler.ast.Subscript): 356 self.process_subscript_node(n, expr) 357 358 def process_attribute_access(self, n): 359 360 "Process the given attribute access node 'n'." 361 362 # Obtain any completed chain and return the reference to it. 363 364 name_ref = self.process_attribute_chain(n) 365 if self.have_access_expression(n): 366 return name_ref 367 368 # Where the start of the chain of attributes has been reached, determine 369 # the complete access. 370 371 # Given a non-access node, this chain can be handled in its entirety, 372 # either being name-based and thus an access rooted on a name, or being 373 # based on some other node and thus an anonymous access of some kind. 374 375 path = self.get_namespace_path() 376 377 # Start with the the full attribute chain. 378 379 remaining = self.attrs 380 attrnames = ".".join(remaining) 381 382 # If the accessor cannot be identified, or where attributes 383 # remain in an attribute chain, record the anonymous accesses. 384 385 if not isinstance(name_ref, NameRef): # includes ResolvedNameRef 386 387 assignment = isinstance(n, compiler.ast.AssAttr) 388 389 init_item(self.attr_accesses, path, set) 390 self.attr_accesses[path].add(attrnames) 391 392 self.record_access_details(None, attrnames, assignment) 393 del self.attrs[0] 394 return 395 396 # Name-based accesses will handle the first attribute in a 397 # chain. 398 399 else: 400 attrname = remaining[0] 401 402 # Attribute assignments are used to identify instance attributes. 403 404 if isinstance(n, compiler.ast.AssAttr) and \ 405 self.in_class and self.in_function and n.expr.name == "self": 406 407 self.set_instance_attr(attrname) 408 409 # Record attribute usage using any name local to this namespace, 410 # if assigned in the namespace, or using an external name 411 # (presently just globals within classes). 412 413 name = self.get_name_for_tracking(name_ref.name, name_ref.final()) 414 tracker = self.trackers[-1] 415 416 immediate_access = len(self.attrs) == 1 417 assignment = immediate_access and isinstance(n, compiler.ast.AssAttr) 418 419 del self.attrs[0] 420 421 # Record global-based chains for subsequent resolution. 422 423 is_global = self.in_function and not self.function_locals[path].has_key(name) or \ 424 not self.in_function 425 426 if is_global: 427 self.record_global_access_details(name, attrnames) 428 429 # Make sure the name is being tracked: global names will not 430 # already be initialised in a branch and must be added 431 # explicitly. 432 433 if not tracker.have_name(name): 434 tracker.assign_names([name]) 435 if self.in_function: 436 self.scope_globals[path].add(name) 437 438 # Record attribute usage in the tracker, and record the branch 439 # information for the access. 440 441 branches = tracker.use_attribute(name, attrname) 442 443 if not branches: 444 print >>sys.stderr, "In %s, name %s is accessed using %s before an assignment." % ( 445 path, name, attrname) 446 branches = tracker.use_attribute(name, attrname) 447 448 self.record_branches_for_access(branches, name, attrnames) 449 access_number = self.record_access_details(name, attrnames, assignment) 450 return AccessRef(name, attrnames, access_number) 451 452 def process_class_node(self, n): 453 454 "Process the given class node 'n'." 455 456 path = self.get_namespace_path() 457 458 # To avoid notions of class "versions" where the same definition 459 # might be parameterised with different state and be referenced 460 # elsewhere (as base classes, for example), classes in functions or 461 # conditions are forbidden. 462 463 if self.in_function or self.in_conditional: 464 print >>sys.stderr, "In %s, class %s in function or conditional statement ignored." % ( 465 path, n.name) 466 return 467 468 # Resolve base classes. 469 470 bases = [] 471 472 for base in n.bases: 473 base_class = self.get_class(base) 474 475 if not base_class: 476 print >>sys.stderr, "In %s, class %s has unidentifiable base class: %s" % ( 477 path, n.name, base) 478 return 479 else: 480 bases.append(base_class) 481 482 # Record bases for the class and retain the class name. 483 484 class_name = self.get_object_path(n.name) 485 486 if not bases and class_name != "__builtins__.core.object": 487 ref = self.get_object("__builtins__.object") 488 bases.append(ref) 489 490 self.importer.classes[class_name] = self.classes[class_name] = bases 491 self.importer.subclasses[class_name] = set() 492 self.scope_globals[class_name] = set() 493 494 # Set the definition before entering the namespace rather than 495 # afterwards because methods may reference it. In normal Python, 496 # a class is not accessible until the definition is complete, but 497 # methods can generally reference it since upon being called the 498 # class will already exist. 499 500 self.set_definition(n.name, "<class>") 501 502 in_class = self.in_class 503 self.in_class = class_name 504 self.set_instance_attr("__class__", Reference("<class>", class_name)) 505 self.enter_namespace(n.name) 506 self.set_name("__fn__") # special instantiator attribute 507 self.set_name("__args__") # special instantiator attribute 508 self.assign_general_local("__name__", self.get_constant("str", class_name)) 509 self.process_structure_node(n.code) 510 self.exit_namespace() 511 self.in_class = in_class 512 513 def process_from_node(self, n): 514 515 "Process the given node 'n', importing from another module." 516 517 path = self.get_namespace_path() 518 519 module_name, names = self.get_module_name(n) 520 if module_name == self.name: 521 raise InspectError("Cannot import from the current module.", path, n) 522 523 self.queue_module(module_name) 524 525 # Attempt to obtain the referenced objects. 526 527 for name, alias in n.names: 528 if name == "*": 529 raise InspectError("Only explicitly specified names can be imported from modules.", path, n) 530 531 # Explicit names. 532 533 ref = self.import_name_from_module(name, module_name) 534 value = ResolvedNameRef(alias or name, ref) 535 self.set_general_local(alias or name, value) 536 537 def process_function_node(self, n, name): 538 539 """ 540 Process the given function or lambda node 'n' with the given 'name'. 541 """ 542 543 is_lambda = isinstance(n, compiler.ast.Lambda) 544 545 # Where a function is declared conditionally, use a separate name for 546 # the definition, and assign the definition to the stated name. 547 548 if (self.in_conditional or self.in_function) and not is_lambda: 549 original_name = name 550 name = self.get_lambda_name() 551 else: 552 original_name = None 553 554 # Initialise argument and local records. 555 556 function_name = self.get_object_path(name) 557 argnames = get_argnames(n.argnames) 558 is_method = self.in_class and not self.in_function 559 560 # Remove explicit "self" from method parameters. 561 562 if is_method and argnames and argnames[0] == "self": 563 del argnames[0] 564 565 # Copy and propagate the parameters. 566 567 self.importer.function_parameters[function_name] = \ 568 self.function_parameters[function_name] = argnames[:] 569 570 # Define all arguments/parameters in the local namespace. 571 572 locals = self.function_locals[function_name] = {} 573 574 # Insert "self" into method locals. 575 576 if is_method: 577 argnames.insert(0, "self") 578 579 # Define "self" in terms of the class if in a method. 580 # This does not diminish the need for type-narrowing in the deducer. 581 582 if argnames: 583 if self.in_class and not self.in_function and argnames[0] == "self": 584 locals[argnames[0]] = Reference("<instance>", self.in_class) 585 else: 586 locals[argnames[0]] = Reference("<var>") 587 588 for argname in argnames[1:]: 589 locals[argname] = Reference("<var>") 590 591 globals = self.scope_globals[function_name] = set() 592 593 # Process the defaults. 594 595 defaults = self.importer.function_defaults[function_name] = \ 596 self.function_defaults[function_name] = [] 597 598 for argname, default in compiler.ast.get_defaults(n): 599 if default: 600 601 # Obtain any reference for the default. 602 603 name_ref = self.process_structure_node(default) 604 defaults.append((argname, name_ref.is_name() and name_ref.reference() or Reference("<var>"))) 605 606 # Reset conditional tracking to focus on the function contents. 607 608 in_conditional = self.in_conditional 609 self.in_conditional = False 610 611 in_function = self.in_function 612 self.in_function = function_name 613 614 self.enter_namespace(name) 615 616 # Track attribute usage within the namespace. 617 618 path = self.get_namespace_path() 619 620 self.start_tracking(locals) 621 self.process_structure_node(n.code) 622 self.stop_tracking() 623 624 # Exit to the parent. 625 626 self.exit_namespace() 627 628 # Update flags. 629 630 self.in_function = in_function 631 self.in_conditional = in_conditional 632 633 # Define the function using the appropriate name. 634 635 self.set_definition(name, "<function>") 636 637 # Where a function is set conditionally, assign the name. 638 639 if original_name: 640 self.process_assignment_for_function(original_name, name) 641 642 def process_global_node(self, n): 643 644 """ 645 Process the given "global" node 'n'. 646 """ 647 648 path = self.get_namespace_path() 649 650 if path != self.name: 651 self.scope_globals[path].update(n.names) 652 653 def process_if_node(self, n): 654 655 """ 656 Process the given "if" node 'n'. 657 """ 658 659 tracker = self.trackers[-1] 660 tracker.new_branchpoint() 661 662 for test, body in n.tests: 663 self.process_structure_node(test) 664 665 tracker.new_branch() 666 667 in_conditional = self.in_conditional 668 self.in_conditional = True 669 self.process_structure_node(body) 670 self.in_conditional = in_conditional 671 672 tracker.shelve_branch() 673 674 # Maintain a branch for the else clause. 675 676 tracker.new_branch() 677 if n.else_: 678 self.process_structure_node(n.else_) 679 tracker.shelve_branch() 680 681 tracker.merge_branches() 682 683 def process_import_node(self, n): 684 685 "Process the given import node 'n'." 686 687 path = self.get_namespace_path() 688 689 # Load the mentioned module. 690 691 for name, alias in n.names: 692 if name == self.name: 693 raise InspectError("Cannot import the current module.", path, n) 694 695 self.set_module(alias or name.split(".")[-1], name) 696 self.queue_module(name, True) 697 698 def process_invocation_node(self, n): 699 700 "Process the given invocation node 'n'." 701 702 path = self.get_namespace_path() 703 704 self.allocate_arguments(path, n.args) 705 706 try: 707 # Process the expression, obtaining any identified reference. 708 709 name_ref = self.process_structure_node(n.node) 710 711 # Process the arguments. 712 713 for arg in n.args: 714 self.process_structure_node(arg) 715 716 # Detect class invocations. 717 718 if isinstance(name_ref, ResolvedNameRef) and name_ref.has_kind("<class>"): 719 return InstanceRef(name_ref.reference().instance_of()) 720 721 elif isinstance(name_ref, NameRef): 722 return InvocationRef(name_ref) 723 724 return None 725 726 finally: 727 self.deallocate_arguments(path, n.args) 728 729 def process_lambda_node(self, n): 730 731 "Process the given lambda node 'n'." 732 733 name = self.get_lambda_name() 734 self.process_function_node(n, name) 735 736 origin = self.get_object_path(name) 737 return ResolvedNameRef(name, Reference("<function>", origin)) 738 739 def process_logical_node(self, n): 740 741 "Process the given operator node 'n'." 742 743 self.process_operator_chain(n.nodes, self.process_structure_node) 744 745 def process_name_node(self, n): 746 747 "Process the given name node 'n'." 748 749 path = self.get_namespace_path() 750 751 # Special names. 752 753 if n.name.startswith("$"): 754 value = self.get_special(n.name) 755 if value: 756 return value 757 758 # Special case for operator functions introduced through code 759 # transformations. 760 761 if n.name.startswith("$op"): 762 763 # Obtain the location of the actual function defined in the operator 764 # package. 765 766 op = n.name[len("$op"):] 767 768 # Attempt to get a reference. 769 770 ref = self.import_name_from_module(op, "operator") 771 self.add_deferred(ref) 772 773 # Record the imported name and provide the resolved name reference. 774 775 value = ResolvedNameRef(n.name, ref) 776 self.set_special(n.name, value) 777 return value 778 779 # Test for self usage, which is only allowed in methods. 780 781 if n.name == "self" and not (self.in_function and self.in_class): 782 raise InspectError("Use of self is only allowed in methods.", path, n) 783 784 # Record usage of the name. 785 786 self.record_name(n.name) 787 788 # Search for unknown names in non-function scopes immediately. 789 # External names in functions are resolved later. 790 791 ref = self.find_name(n.name) 792 if ref: 793 return ResolvedNameRef(n.name, ref) 794 795 # Explicitly-declared global names. 796 797 elif self.in_function and n.name in self.scope_globals[path]: 798 return NameRef(n.name) 799 800 # Examine other names. 801 802 else: 803 tracker = self.trackers[-1] 804 805 # Check local names. 806 807 branches = tracker.tracking_name(n.name) 808 809 # Local name. 810 811 if branches: 812 self.record_branches_for_access(branches, n.name, None) 813 access_number = self.record_access_details(n.name, None, False) 814 return LocalNameRef(n.name, access_number) 815 816 # Possible global or built-in name. 817 818 else: 819 return NameRef(n.name) 820 821 def process_operator_chain(self, nodes, fn): 822 823 """ 824 Process the given chain of 'nodes', applying 'fn' to each node or item. 825 Each node starts a new conditional region, effectively making a deeply- 826 nested collection of if-like statements. 827 """ 828 829 tracker = self.trackers[-1] 830 831 for item in nodes: 832 tracker.new_branchpoint() 833 tracker.new_branch() 834 fn(item) 835 836 for item in nodes[:-1]: 837 tracker.shelve_branch() 838 tracker.new_branch() 839 tracker.shelve_branch() 840 tracker.merge_branches() 841 842 tracker.shelve_branch() 843 tracker.merge_branches() 844 845 def process_try_node(self, n): 846 847 """ 848 Process the given "try...except" node 'n'. 849 """ 850 851 tracker = self.trackers[-1] 852 tracker.new_branchpoint() 853 854 self.process_structure_node(n.body) 855 856 for name, var, handler in n.handlers: 857 if name is not None: 858 self.process_structure_node(name) 859 860 # Any abandoned branches from the body can now be resumed in a new 861 # branch. 862 863 tracker.resume_abandoned_branches() 864 865 # Establish the local for the handler. 866 867 if var is not None: 868 self.process_structure_node(var) 869 if handler is not None: 870 self.process_structure_node(handler) 871 872 tracker.shelve_branch() 873 874 # The else clause maintains the usage from the body but without the 875 # abandoned branches since they would never lead to the else clause 876 # being executed. 877 878 if n.else_: 879 tracker.new_branch() 880 self.process_structure_node(n.else_) 881 tracker.shelve_branch() 882 883 # Without an else clause, a null branch propagates the successful 884 # outcome. 885 886 else: 887 tracker.new_branch() 888 tracker.shelve_branch() 889 890 tracker.merge_branches() 891 892 def process_try_finally_node(self, n): 893 894 """ 895 Process the given "try...finally" node 'n'. 896 """ 897 898 tracker = self.trackers[-1] 899 self.process_structure_node(n.body) 900 901 # Any abandoned branches from the body can now be resumed. 902 903 branches = tracker.resume_all_abandoned_branches() 904 self.process_structure_node(n.final) 905 906 # At the end of the finally clause, abandoned branches are discarded. 907 908 tracker.restore_active_branches(branches) 909 910 def process_while_node(self, n): 911 912 "Process the given while node 'n'." 913 914 tracker = self.trackers[-1] 915 tracker.new_branchpoint(loop_node=True) 916 917 # Evaluate any test or iterator outside the loop. 918 919 self.process_structure_node(n.test) 920 921 # Propagate attribute usage to branches. 922 923 tracker.new_branch(loop_node=True) 924 925 # Enter the loop. 926 927 in_conditional = self.in_conditional 928 self.in_conditional = True 929 self.process_structure_node(n.body) 930 self.in_conditional = in_conditional 931 932 # Continuing branches are resumed before any test. 933 934 tracker.resume_continuing_branches() 935 936 # Evaluate any continuation test within the body. 937 938 self.process_structure_node(n.test) 939 940 tracker.shelve_branch(loop_node=True) 941 942 # Support the non-looping condition. 943 944 tracker.new_branch() 945 tracker.shelve_branch() 946 947 tracker.merge_branches() 948 949 # Evaluate any else clause outside branches. 950 951 if n.else_: 952 self.process_structure_node(n.else_) 953 954 # Connect broken branches to the code after any loop. 955 956 tracker.resume_broken_branches() 957 958 # Branch tracking methods. 959 960 def start_tracking(self, names): 961 962 """ 963 Start tracking attribute usage for names in the current namespace, 964 immediately registering the given 'names'. 965 """ 966 967 path = self.get_namespace_path() 968 parent = self.trackers[-1] 969 tracker = BranchTracker() 970 self.trackers.append(tracker) 971 972 # Record the given names established as new branches. 973 974 tracker.assign_names(names) 975 976 def assign_name(self, name, name_ref): 977 978 "Assign to 'name' the given 'name_ref' in the current namespace." 979 980 name = self.get_name_for_tracking(name) 981 self.trackers[-1].assign_names([name], [name_ref]) 982 983 def stop_tracking(self): 984 985 """ 986 Stop tracking attribute usage, recording computed usage for the current 987 namespace. 988 """ 989 990 path = self.get_namespace_path() 991 tracker = self.trackers.pop() 992 self.record_assignments_for_access(tracker) 993 994 self.attr_usage[path] = tracker.get_all_usage() 995 self.name_initialisers[path] = tracker.get_all_values() 996 997 def start_tracking_in_module(self): 998 999 "Start tracking attribute usage in the module." 1000 1001 tracker = BranchTracker() 1002 self.trackers.append(tracker) 1003 1004 def stop_tracking_in_module(self): 1005 1006 "Stop tracking attribute usage in the module." 1007 1008 tracker = self.trackers[0] 1009 self.record_assignments_for_access(tracker) 1010 self.attr_usage[self.name] = tracker.get_all_usage() 1011 self.name_initialisers[self.name] = tracker.get_all_values() 1012 1013 def record_assignments_for_access(self, tracker): 1014 1015 """ 1016 For the current path, use the given 'tracker' to record assignment 1017 version information for attribute accesses. 1018 """ 1019 1020 path = self.get_path_for_access() 1021 1022 if not self.attr_accessor_branches.has_key(path): 1023 return 1024 1025 init_item(self.attr_accessors, path, dict) 1026 attr_accessors = self.attr_accessors[path] 1027 1028 # Obtain the branches applying during each access. 1029 1030 for access, all_branches in self.attr_accessor_branches[path].items(): 1031 name, attrnames = access 1032 init_item(attr_accessors, access, list) 1033 1034 # Obtain the assignments applying to each branch. 1035 1036 for branches in all_branches: 1037 positions = tracker.get_assignment_positions_for_branches(name, branches) 1038 1039 # Detect missing name information. 1040 1041 if None in positions: 1042 globals = self.global_attr_accesses.get(path) 1043 accesses = globals and globals.get(name) 1044 if not accesses: 1045 print >>sys.stderr, "In %s, %s may not be defined when used." % ( 1046 self.get_namespace_path(), name) 1047 positions.remove(None) 1048 1049 attr_accessors[access].append(positions) 1050 1051 def record_branches_for_access(self, branches, name, attrnames): 1052 1053 """ 1054 Record the given 'branches' for an access involving the given 'name' and 1055 'attrnames'. 1056 """ 1057 1058 access = name, attrnames 1059 path = self.get_path_for_access() 1060 1061 init_item(self.attr_accessor_branches, path, dict) 1062 attr_accessor_branches = self.attr_accessor_branches[path] 1063 1064 init_item(attr_accessor_branches, access, list) 1065 attr_accessor_branches[access].append(branches) 1066 1067 def record_access_details(self, name, attrnames, assignment): 1068 1069 """ 1070 For the given 'name' and 'attrnames', record an access indicating 1071 whether 'assignment' is occurring. 1072 1073 These details correspond to accesses otherwise recorded by the attribute 1074 accessor and attribute access dictionaries. 1075 """ 1076 1077 access = name, attrnames 1078 path = self.get_path_for_access() 1079 1080 init_item(self.attr_access_modifiers, path, dict) 1081 init_item(self.attr_access_modifiers[path], access, list) 1082 1083 access_number = len(self.attr_access_modifiers[path][access]) 1084 self.attr_access_modifiers[path][access].append(assignment) 1085 return access_number 1086 1087 def record_global_access_details(self, name, attrnames): 1088 1089 """ 1090 Record details of a global access via the given 'name' involving the 1091 indicated 'attrnames'. 1092 """ 1093 1094 path = self.get_namespace_path() 1095 1096 init_item(self.global_attr_accesses, path, dict) 1097 init_item(self.global_attr_accesses[path], name, set) 1098 self.global_attr_accesses[path][name].add(attrnames) 1099 1100 # Namespace modification. 1101 1102 def record_name(self, name): 1103 1104 "Record the use of 'name' in a namespace." 1105 1106 path = self.get_namespace_path() 1107 init_item(self.names_used, path, set) 1108 self.names_used[path].add(name) 1109 1110 def set_module(self, name, module_name): 1111 1112 """ 1113 Set a module in the current namespace using the given 'name' associated 1114 with the corresponding 'module_name'. 1115 """ 1116 1117 if name: 1118 self.set_general_local(name, Reference("<module>", module_name)) 1119 1120 def set_definition(self, name, kind): 1121 1122 """ 1123 Set the definition having the given 'name' and 'kind'. 1124 1125 Definitions are set in the static namespace hierarchy, but they can also 1126 be recorded for function locals. 1127 """ 1128 1129 if self.is_global(name): 1130 print >>sys.stderr, "In %s, %s is defined as being global." % ( 1131 self.get_namespace_path(), name) 1132 1133 path = self.get_object_path(name) 1134 self.set_object(path, kind) 1135 1136 ref = self.get_object(path) 1137 if ref.get_kind() == "<var>": 1138 print >>sys.stderr, "In %s, %s is defined more than once." % ( 1139 self.get_namespace_path(), name) 1140 1141 if not self.is_global(name) and self.in_function: 1142 self.set_function_local(name, ref) 1143 1144 def set_function_local(self, name, ref=None): 1145 1146 "Set the local with the given 'name' and optional 'ref'." 1147 1148 locals = self.function_locals[self.get_namespace_path()] 1149 multiple = not ref or locals.has_key(name) and locals[name] != ref 1150 locals[name] = multiple and Reference("<var>") or ref 1151 1152 def assign_general_local(self, name, name_ref): 1153 1154 """ 1155 Set for 'name' the given 'name_ref', recording the name for attribute 1156 usage tracking. 1157 """ 1158 1159 self.set_general_local(name, name_ref) 1160 self.assign_name(name, name_ref) 1161 1162 def set_general_local(self, name, value=None): 1163 1164 """ 1165 Set the 'name' with optional 'value' in any kind of local namespace, 1166 where the 'value' should be a reference if specified. 1167 """ 1168 1169 init_value = self.get_initialising_value(value) 1170 1171 # Module global names. 1172 1173 if self.is_global(name): 1174 path = self.get_global_path(name) 1175 self.set_object(path, init_value) 1176 1177 # Function local names. 1178 1179 elif self.in_function: 1180 path = self.get_object_path(name) 1181 self.set_function_local(name, init_value) 1182 1183 # Other namespaces (classes). 1184 1185 else: 1186 path = self.get_object_path(name) 1187 self.set_name(name, init_value) 1188 1189 def set_name(self, name, ref=None): 1190 1191 "Attach the 'name' with optional 'ref' to the current namespace." 1192 1193 self.set_object(self.get_object_path(name), ref) 1194 1195 def set_instance_attr(self, name, ref=None): 1196 1197 """ 1198 Add an instance attribute of the given 'name' to the current class, 1199 using the optional 'ref'. 1200 """ 1201 1202 init_item(self.instance_attrs, self.in_class, set) 1203 self.instance_attrs[self.in_class].add(name) 1204 1205 if ref: 1206 init_item(self.instance_attr_constants, self.in_class, dict) 1207 self.instance_attr_constants[self.in_class][name] = ref 1208 1209 def get_initialising_value(self, value): 1210 1211 "Return a suitable initialiser reference for 'value'." 1212 1213 # Includes LiteralSequenceRef, ResolvedNameRef... 1214 1215 if isinstance(value, (NameRef, AccessRef, InstanceRef)): 1216 return value.reference() 1217 1218 # In general, invocations do not produce known results. However, the 1219 # name initialisers are resolved once a module has been inspected. 1220 1221 elif isinstance(value, InvocationRef): 1222 return value.reference() 1223 1224 else: 1225 return value 1226 1227 # Static, program-relative naming. 1228 1229 def find_name(self, name): 1230 1231 """ 1232 Return the qualified name for the given 'name' used in the current 1233 non-function namespace. 1234 """ 1235 1236 path = self.get_namespace_path() 1237 ref = None 1238 1239 if not self.in_function and name not in predefined_constants: 1240 if self.in_class: 1241 ref = self.get_object(self.get_object_path(name)) 1242 if not ref: 1243 ref = self.get_global_or_builtin(name) 1244 1245 return ref 1246 1247 def get_class(self, node): 1248 1249 """ 1250 Use the given 'node' to obtain the identity of a class. Return a 1251 reference for the class. Unresolved dependencies are permitted and must 1252 be resolved later. 1253 """ 1254 1255 ref = self._get_class(node) 1256 return ref.has_kind(["<class>", "<depends>"]) and ref or None 1257 1258 def _get_class(self, node): 1259 1260 """ 1261 Use the given 'node' to find a class definition. Return a reference to 1262 the class. 1263 """ 1264 1265 if isinstance(node, compiler.ast.Getattr): 1266 1267 # Obtain the identity of the access target. 1268 1269 ref = self._get_class(node.expr) 1270 1271 # Where the target is a class or module, obtain the identity of the 1272 # attribute. 1273 1274 if ref.has_kind(["<function>", "<var>"]): 1275 return None 1276 else: 1277 attrname = "%s.%s" % (ref.get_origin(), node.attrname) 1278 return self.get_object(attrname) 1279 1280 # Names can be module-level or built-in. 1281 1282 elif isinstance(node, compiler.ast.Name): 1283 1284 # Record usage of the name and attempt to identify it. 1285 1286 self.record_name(node.name) 1287 return self.get_global_or_builtin(node.name) 1288 else: 1289 return None 1290 1291 def get_constant(self, name, value): 1292 1293 "Return a constant reference for the given type 'name' and 'value'." 1294 1295 ref = self.get_builtin_class(name) 1296 return self.get_constant_reference(ref, value) 1297 1298 def get_literal_instance(self, n, name): 1299 1300 "For node 'n', return a reference to an instance of 'name'." 1301 1302 # Get a reference to the built-in class. 1303 1304 ref = self.get_builtin_class(name) 1305 1306 # Obtain the details of the literal itself. 1307 # An alias to the type is generated for sequences. 1308 1309 if name in ("dict", "list", "tuple"): 1310 self.set_special_literal(name, ref) 1311 return self.process_literal_sequence_node(n, name, ref, LiteralSequenceRef) 1312 1313 # Constant values are independently recorded. 1314 1315 else: 1316 return self.get_constant_reference(ref, n.value) 1317 1318 # Special names. 1319 1320 def get_special(self, name): 1321 1322 "Return any stored value for the given special 'name'." 1323 1324 return self.special.get(name) 1325 1326 def set_special(self, name, value): 1327 1328 """ 1329 Set a special 'name' that merely tracks the use of an implicit object 1330 'value'. 1331 """ 1332 1333 self.special[name] = value 1334 1335 def set_special_literal(self, name, ref): 1336 1337 """ 1338 Set a special name for the literal type 'name' having type 'ref'. Such 1339 special names provide a way of referring to literal object types. 1340 """ 1341 1342 literal_name = "$L%s" % name 1343 value = ResolvedNameRef(literal_name, ref) 1344 self.set_special(literal_name, value) 1345 1346 # Functions and invocations. 1347 1348 def set_invocation_usage(self): 1349 1350 """ 1351 Discard the current invocation storage figures, retaining the maximum 1352 values. 1353 """ 1354 1355 for path, (current, maximum) in self.function_targets.items(): 1356 self.importer.function_targets[path] = self.function_targets[path] = maximum 1357 1358 for path, (current, maximum) in self.function_arguments.items(): 1359 self.importer.function_arguments[path] = self.function_arguments[path] = maximum 1360 1361 def allocate_arguments(self, path, args): 1362 1363 """ 1364 Allocate temporary argument storage using current and maximum 1365 requirements for the given 'path' and 'args'. 1366 """ 1367 1368 init_item(self.function_targets, path, lambda: [0, 0]) 1369 t = self.function_targets[path] 1370 t[0] += 1 1371 t[1] = max(t[0], t[1]) 1372 1373 init_item(self.function_arguments, path, lambda: [0, 0]) 1374 t = self.function_arguments[path] 1375 t[0] += len(args) + 1 1376 t[1] = max(t[0], t[1]) 1377 1378 def deallocate_arguments(self, path, args): 1379 1380 "Deallocate temporary argument storage for the given 'path' and 'args'." 1381 1382 self.function_targets[path][0] -= 1 1383 self.function_arguments[path][0] -= len(args) + 1 1384 1385 # vim: tabstop=4 expandtab shiftwidth=4