1 #!/usr/bin/env python 2 3 """ 4 Import logic. 5 6 Copyright (C) 2006, 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 errors import ProgramError 24 from os.path import exists, extsep, getmtime, join 25 from os import listdir, makedirs, remove 26 from common import init_item, readfile, writefile 27 from modules import CachedModule 28 from referencing import Reference 29 import inspector 30 import sys 31 32 class Importer: 33 34 "An import machine, searching for and loading modules." 35 36 def __init__(self, path, cache=None, verbose=False): 37 38 """ 39 Initialise the importer with the given search 'path' - a list of 40 directories to search for Python modules. 41 42 The optional 'cache' should be the name of a directory used to store 43 cached module information. 44 45 The optional 'verbose' parameter causes output concerning the activities 46 of the object to be produced if set to a true value (not the default). 47 """ 48 49 self.path = path 50 self.cache = cache 51 self.verbose = verbose 52 53 # Module importing queue, required modules, removed modules and active 54 # modules in the final program. 55 56 self.to_import = set() 57 self.required = set(["__main__"]) 58 self.removed = {} 59 self.modules = {} 60 61 # Module relationships and invalidated cached modules. 62 63 self.accessing_modules = {} 64 self.invalidated = set() 65 66 # Basic program information. 67 68 self.objects = {} 69 self.classes = {} 70 self.function_parameters = {} 71 self.function_defaults = {} 72 self.function_locals = {} 73 self.function_targets = {} 74 self.function_arguments = {} 75 76 # Unresolved names. 77 78 self.missing = set() 79 80 # Derived information. 81 82 self.subclasses = {} 83 84 # Attributes of different object types. 85 86 self.all_class_attrs = {} 87 self.all_instance_attrs = {} 88 self.all_instance_attr_constants = {} 89 self.all_combined_attrs = {} 90 self.all_module_attrs = {} 91 self.all_shadowed_attrs = {} 92 93 # References to external names and aliases within program units. 94 95 self.all_name_references = {} 96 self.all_initialised_names = {} 97 self.all_aliased_names = {} 98 99 # General attribute accesses. 100 101 self.all_attr_accesses = {} 102 self.all_const_accesses = {} 103 self.all_attr_access_modifiers = {} 104 105 # Constant literals and values. 106 107 self.all_constants = {} 108 self.all_constant_values = {} 109 110 self.make_cache() 111 112 def make_cache(self): 113 if self.cache and not exists(self.cache): 114 makedirs(self.cache) 115 116 def check_cache(self, details): 117 118 """ 119 Check whether the cache applies for the given 'details', invalidating it 120 if it does not. 121 """ 122 123 recorded_details = self.get_cache_details() 124 125 if recorded_details != details: 126 self.remove_cache() 127 128 writefile(self.get_cache_details_filename(), details) 129 130 def get_cache_details_filename(self): 131 132 "Return the filename for the cache details." 133 134 return join(self.cache, "$details") 135 136 def get_cache_details(self): 137 138 "Return details of the cache." 139 140 details_filename = self.get_cache_details_filename() 141 142 if not exists(details_filename): 143 return None 144 else: 145 return readfile(details_filename) 146 147 def remove_cache(self): 148 149 "Remove the contents of the cache." 150 151 for filename in listdir(self.cache): 152 remove(join(self.cache, filename)) 153 154 def to_cache(self): 155 156 "Write modules to the cache." 157 158 if self.cache: 159 for module_name, module in self.modules.items(): 160 module.to_cache(join(self.cache, module_name)) 161 162 # Object retrieval and storage. 163 164 def get_object(self, name): 165 166 """ 167 Return a reference for the given 'name' or None if no such object 168 exists. 169 """ 170 171 return self.objects.get(name) 172 173 def set_object(self, name, value=None): 174 175 "Set the object with the given 'name' and the given 'value'." 176 177 if isinstance(value, Reference): 178 ref = value.alias(name) 179 else: 180 ref = Reference(value, name) 181 182 self.objects[name] = ref 183 184 # Identification of both stored object names and name references. 185 186 def identify(self, name): 187 188 "Identify 'name' using stored object and external name records." 189 190 return self.objects.get(name) or self.all_name_references.get(name) 191 192 # Indirect object retrieval. 193 194 def get_attributes(self, ref, attrname): 195 196 """ 197 Return attributes provided by 'ref' for 'attrname'. Class attributes 198 may be provided by instances. 199 """ 200 201 kind = ref.get_kind() 202 if kind == "<class>": 203 ref = self.get_class_attribute(ref.get_origin(), attrname) 204 return ref and set([ref]) or set() 205 elif kind == "<instance>": 206 return self.get_combined_attributes(ref.get_origin(), attrname) 207 elif kind == "<module>": 208 ref = self.get_module_attribute(ref.get_origin(), attrname) 209 return ref and set([ref]) or set() 210 else: 211 return set() 212 213 def get_class_attribute(self, object_type, attrname): 214 215 "Return from 'object_type' the details of class attribute 'attrname'." 216 217 attr = self.all_class_attrs[object_type].get(attrname) 218 return attr and self.get_object(attr) 219 220 def get_instance_attributes(self, object_type, attrname): 221 222 """ 223 Return from 'object_type' the details of instance attribute 'attrname'. 224 """ 225 226 consts = self.all_instance_attr_constants.get(object_type) 227 attrs = set() 228 for attr in self.all_instance_attrs[object_type].get(attrname, []): 229 attrs.add(consts and consts.get(attrname) or Reference("<var>", attr)) 230 return attrs 231 232 def get_combined_attributes(self, object_type, attrname): 233 234 """ 235 Return from 'object_type' the details of class or instance attribute 236 'attrname'. 237 """ 238 239 ref = self.get_class_attribute(object_type, attrname) 240 refs = ref and set([ref]) or set() 241 refs.update(self.get_instance_attributes(object_type, attrname)) 242 return refs 243 244 def get_module_attribute(self, object_type, attrname): 245 246 "Return from 'object_type' the details of module attribute 'attrname'." 247 248 if attrname in self.all_module_attrs[object_type]: 249 return self.get_object("%s.%s" % (object_type, attrname)) 250 else: 251 return None 252 253 # Convenience methods for deducing which kind of object provided an 254 # attribute. 255 256 def get_attribute_provider(self, ref, attrname): 257 258 """ 259 Return the kind of provider of the attribute accessed via 'ref' using 260 'attrname'. 261 """ 262 263 kind = ref.get_kind() 264 265 if kind in ["<class>", "<module>"]: 266 return kind 267 else: 268 return self.get_instance_attribute_provider(ref.get_origin(), attrname) 269 270 def get_instance_attribute_provider(self, object_type, attrname): 271 272 """ 273 Return the kind of provider of the attribute accessed via an instance of 274 'object_type' using 'attrname'. 275 """ 276 277 if self.get_class_attribute(object_type, attrname): 278 return "<class>" 279 else: 280 return "<instance>" 281 282 # Module management. 283 284 def queue_module(self, name, accessor, required=False): 285 286 """ 287 Queue the module with the given 'name' for import from the given 288 'accessor' module. If 'required' is true (it is false by default), the 289 module will be required in the final program. 290 """ 291 292 if not self.modules.has_key(name): 293 self.to_import.add(name) 294 295 if required: 296 self.required.add(name) 297 298 init_item(self.accessing_modules, name, set) 299 self.accessing_modules[name].add(accessor.name) 300 301 def get_modules(self): 302 303 "Return all modules known to the importer." 304 305 return self.modules.values() 306 307 def get_module(self, name): 308 309 "Return the module with the given 'name'." 310 311 if not self.modules.has_key(name): 312 return None 313 314 return self.modules[name] 315 316 # Program operations. 317 318 def initialise(self, filename, reset=False): 319 320 """ 321 Initialise a program whose main module is 'filename', resetting the 322 cache if 'reset' is true. Return the main module. 323 """ 324 325 if reset: 326 self.remove_cache() 327 self.check_cache(filename) 328 329 # Load the program itself. 330 331 m = self.load_from_file(filename) 332 333 # Load any queued modules. 334 335 while self.to_import: 336 for name in list(self.to_import): # avoid mutation issue 337 self.load(name) 338 339 # Resolve dependencies between modules. 340 341 self.resolve() 342 343 # Record the type of all classes. 344 345 self.type_ref = self.get_object("__builtins__.type") 346 347 # Resolve dependencies within the program. 348 349 for module in self.modules.values(): 350 module.complete() 351 352 # Remove unneeded modules. 353 354 all_modules = self.modules.items() 355 356 for name, module in all_modules: 357 if name not in self.required: 358 module.unpropagate() 359 del self.modules[name] 360 self.removed[name] = module 361 362 # Collect redundant objects. 363 364 for module in self.removed.values(): 365 module.collect() 366 367 # Assert module objects where aliases have been removed. 368 369 for name in self.required: 370 if not self.objects.has_key(name): 371 self.objects[name] = Reference("<module>", name) 372 373 return m 374 375 def finalise(self): 376 377 """ 378 Finalise the inspected program, returning whether the program could be 379 finalised. 380 """ 381 382 if self.missing: 383 return False 384 385 self.finalise_classes() 386 self.to_cache() 387 self.set_class_types() 388 self.define_instantiators() 389 self.collect_constants() 390 391 return True 392 393 # Supporting operations. 394 395 def resolve(self): 396 397 "Resolve dependencies between modules." 398 399 self.waiting = {} 400 401 for module in self.modules.values(): 402 403 # Resolve all deferred references in each module. 404 405 for ref in module.deferred: 406 found = self.find_dependency(ref) 407 if not found: 408 self.missing.add((module.name, ref.get_origin())) 409 410 # Record the resolved names and identify required modules. 411 412 else: 413 # Find the providing module of this reference. 414 # Where definitive details of the origin cannot be found, 415 # identify the provider using the deferred reference. 416 # NOTE: This may need to test for static origins. 417 418 provider = self.get_module_provider(found.unresolved() and ref or found) 419 ref.mutate(found) 420 421 if provider: 422 423 module.required.add(provider) 424 self.accessing_modules[provider].add(module.name) 425 426 # Postpone any inclusion of the provider until this 427 # module becomes required. 428 429 if module.name not in self.required: 430 init_item(self.waiting, module.name, set) 431 self.waiting[module.name].add(provider) 432 433 # Make this module required in the accessing module. 434 435 elif provider not in self.required: 436 self.required.add(provider) 437 if self.verbose: 438 print >>sys.stderr, "Requiring", provider, "for", ref 439 440 # Check modules again to see if they are now required and should now 441 # cause the inclusion of other modules providing objects to the program. 442 443 for module_name in self.waiting.keys(): 444 self.require_providers(module_name) 445 446 def require_providers(self, module_name): 447 448 """ 449 Test if 'module_name' is itself required and, if so, require modules 450 containing objects provided to the module. 451 """ 452 453 if module_name in self.required and self.waiting.has_key(module_name): 454 for provider in self.waiting[module_name]: 455 if provider not in self.required: 456 self.required.add(provider) 457 if self.verbose: 458 print >>sys.stderr, "Requiring", provider 459 self.require_providers(provider) 460 461 def find_dependency(self, ref): 462 463 "Find the ultimate dependency for 'ref'." 464 465 found = set() 466 while ref and ref.has_kind("<depends>") and not ref in found: 467 found.add(ref) 468 ref = self.identify(ref.get_origin()) 469 return ref 470 471 def get_module_provider(self, ref): 472 473 "Identify the provider of the given 'ref'." 474 475 for ancestor in ref.ancestors(): 476 if self.modules.has_key(ancestor): 477 return ancestor 478 return None 479 480 def finalise_classes(self): 481 482 "Finalise the class relationships and attributes." 483 484 self.derive_inherited_attrs() 485 self.derive_subclasses() 486 self.derive_shadowed_attrs() 487 488 def derive_inherited_attrs(self): 489 490 "Derive inherited attributes for classes throughout the program." 491 492 for name in self.classes.keys(): 493 self.propagate_attrs_for_class(name) 494 495 def propagate_attrs_for_class(self, name, visited=None): 496 497 "Propagate inherited attributes for class 'name'." 498 499 # Visit classes only once. 500 501 if self.all_combined_attrs.has_key(name): 502 return 503 504 visited = visited or [] 505 506 if name in visited: 507 raise ProgramError, "Class %s may not inherit from itself: %s -> %s." % (name, " -> ".join(visited), name) 508 509 visited.append(name) 510 511 class_attrs = {} 512 instance_attrs = {} 513 514 # Aggregate the attributes from base classes, recording the origins of 515 # applicable attributes. 516 517 for base in self.classes[name][::-1]: 518 519 # Get the identity of the class from the reference. 520 521 base = base.get_origin() 522 523 # Define the base class completely before continuing with this 524 # class. 525 526 self.propagate_attrs_for_class(base, visited) 527 class_attrs.update(self.all_class_attrs[base]) 528 529 # Instance attribute origins are combined if different. 530 531 for key, values in self.all_instance_attrs[base].items(): 532 init_item(instance_attrs, key, set) 533 instance_attrs[key].update(values) 534 535 # Class attributes override those defined earlier in the hierarchy. 536 537 class_attrs.update(self.all_class_attrs.get(name, {})) 538 539 # Instance attributes are merely added if not already defined. 540 541 for key in self.all_instance_attrs.get(name, []): 542 if not instance_attrs.has_key(key): 543 instance_attrs[key] = set(["%s.%s" % (name, key)]) 544 545 self.all_class_attrs[name] = class_attrs 546 self.all_instance_attrs[name] = instance_attrs 547 self.all_combined_attrs[name] = set(class_attrs.keys()).union(instance_attrs.keys()) 548 549 def derive_subclasses(self): 550 551 "Derive subclass details for classes." 552 553 for name, bases in self.classes.items(): 554 for base in bases: 555 556 # Get the identity of the class from the reference. 557 558 base = base.get_origin() 559 self.subclasses[base].add(name) 560 561 def derive_shadowed_attrs(self): 562 563 "Derive shadowed attributes for classes." 564 565 for name, attrs in self.all_instance_attrs.items(): 566 attrs = set(attrs.keys()).intersection(self.all_class_attrs[name].keys()) 567 if attrs: 568 self.all_shadowed_attrs[name] = attrs 569 570 def set_class_types(self): 571 572 "Set the type of each class." 573 574 for attrs in self.all_class_attrs.values(): 575 attrs["__class__"] = self.type_ref.get_origin() 576 577 def define_instantiators(self): 578 579 """ 580 Consolidate parameter and default details, incorporating initialiser 581 details to define instantiator signatures. 582 """ 583 584 for cls, attrs in self.all_class_attrs.items(): 585 initialiser = attrs["__init__"] 586 self.function_parameters[cls] = self.function_parameters[initialiser] 587 self.function_defaults[cls] = self.function_defaults[initialiser] 588 589 def collect_constants(self): 590 591 "Get constants from all active modules." 592 593 for module in self.modules.values(): 594 self.all_constants.update(module.constants) 595 596 # Import methods. 597 598 def find_in_path(self, name): 599 600 """ 601 Find the given module 'name' in the search path, returning None where no 602 such module could be found, or a 2-tuple from the 'find' method 603 otherwise. 604 """ 605 606 for d in self.path: 607 m = self.find(d, name) 608 if m: return m 609 return None 610 611 def find(self, d, name): 612 613 """ 614 In the directory 'd', find the given module 'name', where 'name' can 615 either refer to a single file module or to a package. Return None if the 616 'name' cannot be associated with either a file or a package directory, 617 or a 2-tuple from '_find_package' or '_find_module' otherwise. 618 """ 619 620 m = self._find_package(d, name) 621 if m: return m 622 m = self._find_module(d, name) 623 if m: return m 624 return None 625 626 def _find_module(self, d, name): 627 628 """ 629 In the directory 'd', find the given module 'name', returning None where 630 no suitable file exists in the directory, or a 2-tuple consisting of 631 None (indicating that no package directory is involved) and a filename 632 indicating the location of the module. 633 """ 634 635 name_py = name + extsep + "py" 636 filename = self._find_file(d, name_py) 637 if filename: 638 return None, filename 639 return None 640 641 def _find_package(self, d, name): 642 643 """ 644 In the directory 'd', find the given package 'name', returning None 645 where no suitable package directory exists, or a 2-tuple consisting of 646 a directory (indicating the location of the package directory itself) 647 and a filename indicating the location of the __init__.py module which 648 declares the package's top-level contents. 649 """ 650 651 filename = self._find_file(d, name) 652 if filename: 653 init_py = "__init__" + extsep + "py" 654 init_py_filename = self._find_file(filename, init_py) 655 if init_py_filename: 656 return filename, init_py_filename 657 return None 658 659 def _find_file(self, d, filename): 660 661 """ 662 Return the filename obtained when searching the directory 'd' for the 663 given 'filename', or None if no actual file exists for the filename. 664 """ 665 666 filename = join(d, filename) 667 if exists(filename): 668 return filename 669 else: 670 return None 671 672 def load(self, name): 673 674 """ 675 Load the module or package with the given 'name'. Return an object 676 referencing the loaded module or package, or None if no such module or 677 package exists. 678 """ 679 680 # Loaded modules are returned immediately. 681 # Modules may be known but not yet loading (having been registered as 682 # submodules), loading, loaded, or completely unknown. 683 684 module = self.get_module(name) 685 686 if module: 687 return self.modules[name] 688 689 # Otherwise, modules are loaded. 690 691 # Split the name into path components, and try to find the uppermost in 692 # the search path. 693 694 path = name.split(".") 695 path_so_far = [] 696 module = None 697 698 for p in path: 699 700 # Get the module's filesystem details. 701 702 if not path_so_far: 703 m = self.find_in_path(p) 704 elif d: 705 m = self.find(d, p) 706 else: 707 m = None 708 709 path_so_far.append(p) 710 module_name = ".".join(path_so_far) 711 712 if not m: 713 if self.verbose: 714 print >>sys.stderr, "Not found (%s)" % name 715 716 return None # NOTE: Import error. 717 718 # Get the module itself. 719 720 d, filename = m 721 module = self.load_from_file(filename, module_name) 722 723 return module 724 725 def load_from_file(self, filename, module_name=None): 726 727 "Load the module from the given 'filename'." 728 729 if module_name is None: 730 module_name = "__main__" 731 732 module = self.modules.get(module_name) 733 734 if not module: 735 736 # Try to load from cache. 737 738 module = self.load_from_cache(filename, module_name) 739 if module: 740 return module 741 742 # If no cache entry exists, load from file. 743 744 module = inspector.InspectedModule(module_name, self) 745 self.add_module(module_name, module) 746 self.update_cache_validity(module) 747 748 self._load(module, module_name, lambda m: m.parse, filename) 749 750 return module 751 752 def update_cache_validity(self, module): 753 754 "Make 'module' valid in the cache, but invalidate accessing modules." 755 756 accessing = self.accessing_modules.get(module.name) 757 if accessing: 758 self.invalidated.update(accessing) 759 if module.name in self.invalidated: 760 self.invalidated.remove(module.name) 761 762 def source_is_new(self, filename, module_name): 763 764 "Return whether 'filename' is newer than the cached 'module_name'." 765 766 if self.cache: 767 cache_filename = join(self.cache, module_name) 768 return not exists(cache_filename) or \ 769 getmtime(filename) > getmtime(cache_filename) or \ 770 module_name in self.invalidated 771 else: 772 return True 773 774 def load_from_cache(self, filename, module_name): 775 776 "Return a module residing in the cache." 777 778 module = self.modules.get(module_name) 779 780 if not module and not self.source_is_new(filename, module_name): 781 module = CachedModule(module_name, self) 782 self.add_module(module_name, module) 783 784 filename = join(self.cache, module_name) 785 self._load(module, module_name, lambda m: m.from_cache, filename) 786 787 return module 788 789 def _load(self, module, module_name, fn, filename): 790 791 """ 792 Load 'module' for the given 'module_name', and with 'fn' performing an 793 invocation on the module with the given 'filename'. 794 """ 795 796 # Load the module. 797 798 if self.verbose: 799 print >>sys.stderr, module_name in self.required and "Required" or "Loading", module_name, "from", filename 800 fn(module)(filename) 801 802 # Add the module object if not already defined. 803 804 if not self.objects.has_key(module_name): 805 self.objects[module_name] = Reference("<module>", module_name) 806 807 def add_module(self, module_name, module): 808 809 """ 810 Return the module with the given 'module_name', adding a new module 811 object if one does not already exist. 812 """ 813 814 self.modules[module_name] = module 815 if module_name in self.to_import: 816 self.to_import.remove(module_name) 817 818 # vim: tabstop=4 expandtab shiftwidth=4