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 ref.mutate(found) 414 415 # Find the providing module of this reference. 416 417 provider = self.get_module_provider(ref) 418 if provider: 419 420 module.required.add(provider) 421 self.accessing_modules[provider].add(module.name) 422 423 # Postpone any inclusion of the provider until this 424 # module becomes required. 425 426 if module.name not in self.required: 427 init_item(self.waiting, module.name, set) 428 self.waiting[module.name].add(provider) 429 430 # Make this module required in the accessing module. 431 432 elif provider not in self.required: 433 self.required.add(provider) 434 if self.verbose: 435 print >>sys.stderr, "Requiring", provider, "for", ref 436 437 # Check modules again to see if they are now required and should now 438 # cause the inclusion of other modules providing objects to the program. 439 440 for module_name in self.waiting.keys(): 441 self.require_providers(module_name) 442 443 def require_providers(self, module_name): 444 445 """ 446 Test if 'module_name' is itself required and, if so, require modules 447 containing objects provided to the module. 448 """ 449 450 if module_name in self.required and self.waiting.has_key(module_name): 451 for provider in self.waiting[module_name]: 452 if provider not in self.required: 453 self.required.add(provider) 454 if self.verbose: 455 print >>sys.stderr, "Requiring", provider 456 self.require_providers(provider) 457 458 def find_dependency(self, ref): 459 460 "Find the ultimate dependency for 'ref'." 461 462 found = set() 463 while ref and ref.has_kind("<depends>") and not ref in found: 464 found.add(ref) 465 ref = self.identify(ref.get_origin()) 466 return ref 467 468 def get_module_provider(self, ref): 469 470 "Identify the provider of the given 'ref'." 471 472 for ancestor in ref.ancestors(): 473 if self.modules.has_key(ancestor): 474 return ancestor 475 return None 476 477 def finalise_classes(self): 478 479 "Finalise the class relationships and attributes." 480 481 self.derive_inherited_attrs() 482 self.derive_subclasses() 483 self.derive_shadowed_attrs() 484 485 def derive_inherited_attrs(self): 486 487 "Derive inherited attributes for classes throughout the program." 488 489 for name in self.classes.keys(): 490 self.propagate_attrs_for_class(name) 491 492 def propagate_attrs_for_class(self, name, visited=None): 493 494 "Propagate inherited attributes for class 'name'." 495 496 # Visit classes only once. 497 498 if self.all_combined_attrs.has_key(name): 499 return 500 501 visited = visited or [] 502 503 if name in visited: 504 raise ProgramError, "Class %s may not inherit from itself: %s -> %s." % (name, " -> ".join(visited), name) 505 506 visited.append(name) 507 508 class_attrs = {} 509 instance_attrs = {} 510 511 # Aggregate the attributes from base classes, recording the origins of 512 # applicable attributes. 513 514 for base in self.classes[name][::-1]: 515 516 # Get the identity of the class from the reference. 517 518 base = base.get_origin() 519 520 # Define the base class completely before continuing with this 521 # class. 522 523 self.propagate_attrs_for_class(base, visited) 524 class_attrs.update(self.all_class_attrs[base]) 525 526 # Instance attribute origins are combined if different. 527 528 for key, values in self.all_instance_attrs[base].items(): 529 init_item(instance_attrs, key, set) 530 instance_attrs[key].update(values) 531 532 # Class attributes override those defined earlier in the hierarchy. 533 534 class_attrs.update(self.all_class_attrs.get(name, {})) 535 536 # Instance attributes are merely added if not already defined. 537 538 for key in self.all_instance_attrs.get(name, []): 539 if not instance_attrs.has_key(key): 540 instance_attrs[key] = set(["%s.%s" % (name, key)]) 541 542 self.all_class_attrs[name] = class_attrs 543 self.all_instance_attrs[name] = instance_attrs 544 self.all_combined_attrs[name] = set(class_attrs.keys()).union(instance_attrs.keys()) 545 546 def derive_subclasses(self): 547 548 "Derive subclass details for classes." 549 550 for name, bases in self.classes.items(): 551 for base in bases: 552 553 # Get the identity of the class from the reference. 554 555 base = base.get_origin() 556 self.subclasses[base].add(name) 557 558 def derive_shadowed_attrs(self): 559 560 "Derive shadowed attributes for classes." 561 562 for name, attrs in self.all_instance_attrs.items(): 563 attrs = set(attrs.keys()).intersection(self.all_class_attrs[name].keys()) 564 if attrs: 565 self.all_shadowed_attrs[name] = attrs 566 567 def set_class_types(self): 568 569 "Set the type of each class." 570 571 for attrs in self.all_class_attrs.values(): 572 attrs["__class__"] = self.type_ref.get_origin() 573 574 def define_instantiators(self): 575 576 """ 577 Consolidate parameter and default details, incorporating initialiser 578 details to define instantiator signatures. 579 """ 580 581 for cls, attrs in self.all_class_attrs.items(): 582 initialiser = attrs["__init__"] 583 self.function_parameters[cls] = self.function_parameters[initialiser] 584 self.function_defaults[cls] = self.function_defaults[initialiser] 585 586 def collect_constants(self): 587 588 "Get constants from all active modules." 589 590 for module in self.modules.values(): 591 self.all_constants.update(module.constants) 592 593 # Import methods. 594 595 def find_in_path(self, name): 596 597 """ 598 Find the given module 'name' in the search path, returning None where no 599 such module could be found, or a 2-tuple from the 'find' method 600 otherwise. 601 """ 602 603 for d in self.path: 604 m = self.find(d, name) 605 if m: return m 606 return None 607 608 def find(self, d, name): 609 610 """ 611 In the directory 'd', find the given module 'name', where 'name' can 612 either refer to a single file module or to a package. Return None if the 613 'name' cannot be associated with either a file or a package directory, 614 or a 2-tuple from '_find_package' or '_find_module' otherwise. 615 """ 616 617 m = self._find_package(d, name) 618 if m: return m 619 m = self._find_module(d, name) 620 if m: return m 621 return None 622 623 def _find_module(self, d, name): 624 625 """ 626 In the directory 'd', find the given module 'name', returning None where 627 no suitable file exists in the directory, or a 2-tuple consisting of 628 None (indicating that no package directory is involved) and a filename 629 indicating the location of the module. 630 """ 631 632 name_py = name + extsep + "py" 633 filename = self._find_file(d, name_py) 634 if filename: 635 return None, filename 636 return None 637 638 def _find_package(self, d, name): 639 640 """ 641 In the directory 'd', find the given package 'name', returning None 642 where no suitable package directory exists, or a 2-tuple consisting of 643 a directory (indicating the location of the package directory itself) 644 and a filename indicating the location of the __init__.py module which 645 declares the package's top-level contents. 646 """ 647 648 filename = self._find_file(d, name) 649 if filename: 650 init_py = "__init__" + extsep + "py" 651 init_py_filename = self._find_file(filename, init_py) 652 if init_py_filename: 653 return filename, init_py_filename 654 return None 655 656 def _find_file(self, d, filename): 657 658 """ 659 Return the filename obtained when searching the directory 'd' for the 660 given 'filename', or None if no actual file exists for the filename. 661 """ 662 663 filename = join(d, filename) 664 if exists(filename): 665 return filename 666 else: 667 return None 668 669 def load(self, name): 670 671 """ 672 Load the module or package with the given 'name'. Return an object 673 referencing the loaded module or package, or None if no such module or 674 package exists. 675 """ 676 677 # Loaded modules are returned immediately. 678 # Modules may be known but not yet loading (having been registered as 679 # submodules), loading, loaded, or completely unknown. 680 681 module = self.get_module(name) 682 683 if module: 684 return self.modules[name] 685 686 # Otherwise, modules are loaded. 687 688 # Split the name into path components, and try to find the uppermost in 689 # the search path. 690 691 path = name.split(".") 692 path_so_far = [] 693 module = None 694 695 for p in path: 696 697 # Get the module's filesystem details. 698 699 if not path_so_far: 700 m = self.find_in_path(p) 701 elif d: 702 m = self.find(d, p) 703 else: 704 m = None 705 706 path_so_far.append(p) 707 module_name = ".".join(path_so_far) 708 709 if not m: 710 if self.verbose: 711 print >>sys.stderr, "Not found (%s)" % name 712 713 return None # NOTE: Import error. 714 715 # Get the module itself. 716 717 d, filename = m 718 module = self.load_from_file(filename, module_name) 719 720 return module 721 722 def load_from_file(self, filename, module_name=None): 723 724 "Load the module from the given 'filename'." 725 726 if module_name is None: 727 module_name = "__main__" 728 729 module = self.modules.get(module_name) 730 731 if not module: 732 733 # Try to load from cache. 734 735 module = self.load_from_cache(filename, module_name) 736 if module: 737 return module 738 739 # If no cache entry exists, load from file. 740 741 module = inspector.InspectedModule(module_name, self) 742 self.add_module(module_name, module) 743 self.update_cache_validity(module) 744 745 self._load(module, module_name, lambda m: m.parse, filename) 746 747 return module 748 749 def update_cache_validity(self, module): 750 751 "Make 'module' valid in the cache, but invalidate accessing modules." 752 753 accessing = self.accessing_modules.get(module.name) 754 if accessing: 755 self.invalidated.update(accessing) 756 if module.name in self.invalidated: 757 self.invalidated.remove(module.name) 758 759 def source_is_new(self, filename, module_name): 760 761 "Return whether 'filename' is newer than the cached 'module_name'." 762 763 if self.cache: 764 cache_filename = join(self.cache, module_name) 765 return not exists(cache_filename) or \ 766 getmtime(filename) > getmtime(cache_filename) or \ 767 module_name in self.invalidated 768 else: 769 return True 770 771 def load_from_cache(self, filename, module_name): 772 773 "Return a module residing in the cache." 774 775 module = self.modules.get(module_name) 776 777 if not module and not self.source_is_new(filename, module_name): 778 module = CachedModule(module_name, self) 779 self.add_module(module_name, module) 780 781 filename = join(self.cache, module_name) 782 self._load(module, module_name, lambda m: m.from_cache, filename) 783 784 return module 785 786 def _load(self, module, module_name, fn, filename): 787 788 """ 789 Load 'module' for the given 'module_name', and with 'fn' performing an 790 invocation on the module with the given 'filename'. 791 """ 792 793 # Load the module. 794 795 if self.verbose: 796 print >>sys.stderr, module_name in self.required and "Required" or "Loading", module_name, "from", filename 797 fn(module)(filename) 798 799 # Add the module object if not already defined. 800 801 if not self.objects.has_key(module_name): 802 self.objects[module_name] = Reference("<module>", module_name) 803 804 def add_module(self, module_name, module): 805 806 """ 807 Return the module with the given 'module_name', adding a new module 808 object if one does not already exist. 809 """ 810 811 self.modules[module_name] = module 812 if module_name in self.to_import: 813 self.to_import.remove(module_name) 814 815 # vim: tabstop=4 expandtab shiftwidth=4