paul@0 | 1 | #!/usr/bin/env python |
paul@0 | 2 | |
paul@0 | 3 | """ |
paul@0 | 4 | Inspect source files, obtaining details of classes and attributes. |
paul@0 | 5 | |
paul@31 | 6 | Copyright (C) 2007, 2008 Paul Boddie <paul@boddie.org.uk> |
paul@0 | 7 | |
paul@0 | 8 | This program is free software; you can redistribute it and/or modify it under |
paul@0 | 9 | the terms of the GNU General Public License as published by the Free Software |
paul@0 | 10 | Foundation; either version 3 of the License, or (at your option) any later |
paul@0 | 11 | version. |
paul@0 | 12 | |
paul@0 | 13 | This program is distributed in the hope that it will be useful, but WITHOUT |
paul@0 | 14 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS |
paul@0 | 15 | FOR A PARTICULAR PURPOSE. See the GNU General Public License for more |
paul@0 | 16 | details. |
paul@0 | 17 | |
paul@0 | 18 | You should have received a copy of the GNU General Public License along with |
paul@0 | 19 | this program. If not, see <http://www.gnu.org/licenses/>. |
paul@20 | 20 | |
paul@20 | 21 | -------- |
paul@20 | 22 | |
paul@20 | 23 | The central classes in this module are the following: |
paul@20 | 24 | |
paul@20 | 25 | * Class |
paul@20 | 26 | * Function |
paul@20 | 27 | * Module |
paul@20 | 28 | * InspectedModule (derived from Module) |
paul@20 | 29 | |
paul@20 | 30 | All of the above support the Naming interface either explicitly or through |
paul@20 | 31 | general conformance, meaning that all can be asked to provide their 'full_name' |
paul@20 | 32 | using the method of that name. |
paul@20 | 33 | |
paul@20 | 34 | Additionally, all of the above also support a dictionary interface in order to |
paul@20 | 35 | access names within their defined scopes. Specific methods also exist in order |
paul@20 | 36 | to distinguish between certain kinds of attributes: |
paul@20 | 37 | |
paul@20 | 38 | * Class: (class|all_class|instance|all)_attributes |
paul@31 | 39 | * Function: parameters, locals, all_locals |
paul@20 | 40 | * Module: module_attributes |
paul@20 | 41 | |
paul@20 | 42 | These specific methods are useful in certain situations. |
paul@20 | 43 | |
paul@20 | 44 | The above classes also provide a 'node' attribute, indicating the AST node where |
paul@20 | 45 | each such object is defined. |
paul@0 | 46 | """ |
paul@0 | 47 | |
paul@0 | 48 | import compiler.ast |
paul@0 | 49 | from compiler.visitor import ASTVisitor |
paul@0 | 50 | try: |
paul@0 | 51 | set |
paul@0 | 52 | except NameError: |
paul@0 | 53 | from sets import Set as set |
paul@0 | 54 | |
paul@0 | 55 | class InspectError(Exception): |
paul@0 | 56 | |
paul@0 | 57 | "An inspection error." |
paul@0 | 58 | |
paul@0 | 59 | pass |
paul@0 | 60 | |
paul@31 | 61 | class AtLeast: |
paul@31 | 62 | |
paul@31 | 63 | "A special representation for numbers of a given value or greater." |
paul@31 | 64 | |
paul@31 | 65 | def __init__(self, count): |
paul@31 | 66 | self.count = count |
paul@31 | 67 | |
paul@31 | 68 | def __eq__(self, other): |
paul@31 | 69 | return 0 |
paul@31 | 70 | |
paul@31 | 71 | __lt__ = __le__ = __eq__ |
paul@31 | 72 | |
paul@31 | 73 | def __ne__(self, other): |
paul@31 | 74 | return 1 |
paul@31 | 75 | |
paul@31 | 76 | def __gt__(self, other): |
paul@31 | 77 | if isinstance(other, AtLeast): |
paul@31 | 78 | return 0 |
paul@31 | 79 | else: |
paul@31 | 80 | return self.count > other |
paul@31 | 81 | |
paul@31 | 82 | def __ge__(self, other): |
paul@31 | 83 | if isinstance(other, AtLeast): |
paul@31 | 84 | return 0 |
paul@31 | 85 | else: |
paul@31 | 86 | return self.count >= other |
paul@31 | 87 | |
paul@31 | 88 | def __iadd__(self, other): |
paul@31 | 89 | if isinstance(other, AtLeast): |
paul@31 | 90 | self.count += other.count |
paul@31 | 91 | else: |
paul@31 | 92 | self.count += other |
paul@31 | 93 | return self |
paul@31 | 94 | |
paul@31 | 95 | def __radd__(self, other): |
paul@31 | 96 | if isinstance(other, AtLeast): |
paul@31 | 97 | return AtLeast(self.count + other.count) |
paul@31 | 98 | else: |
paul@31 | 99 | return AtLeast(self.count + other) |
paul@31 | 100 | |
paul@31 | 101 | def __repr__(self): |
paul@31 | 102 | return "AtLeast(%r)" % self.count |
paul@31 | 103 | |
paul@12 | 104 | # Mix-ins and abstract classes. |
paul@12 | 105 | |
paul@3 | 106 | class NamespaceDict: |
paul@3 | 107 | |
paul@3 | 108 | "A mix-in providing dictionary methods." |
paul@3 | 109 | |
paul@24 | 110 | def __init__(self, global_namespace=None): |
paul@12 | 111 | self.namespace = {} |
paul@12 | 112 | self.globals = set() |
paul@24 | 113 | self.global_namespace = global_namespace |
paul@36 | 114 | self.attr_position = 0 |
paul@23 | 115 | |
paul@3 | 116 | def __getitem__(self, name): |
paul@3 | 117 | return self.namespace[name] |
paul@3 | 118 | |
paul@15 | 119 | def get(self, name, default=None): |
paul@15 | 120 | return self.namespace.get(name, default) |
paul@15 | 121 | |
paul@12 | 122 | def __setitem__(self, name, value): |
paul@31 | 123 | |
paul@31 | 124 | # Use a special method to access the namespace. |
paul@31 | 125 | |
paul@14 | 126 | if name not in self.globals: |
paul@31 | 127 | self.set(name, value) |
paul@31 | 128 | else: |
paul@34 | 129 | self.global_namespace.set(name, value, 0) |
paul@31 | 130 | |
paul@34 | 131 | def set(self, name, value, single_assignment=1): |
paul@36 | 132 | attr = self._set(name, value) |
paul@12 | 133 | |
paul@31 | 134 | # NOTE: Insist on assignments with known values. |
paul@23 | 135 | |
paul@31 | 136 | if value is not None: |
paul@36 | 137 | attr.update(value, single_assignment) |
paul@32 | 138 | |
paul@32 | 139 | def set_module(self, name, value): |
paul@36 | 140 | attr = self._set(name, value) |
paul@36 | 141 | if attr.assignments is None: |
paul@36 | 142 | attr.assignments = 1 |
paul@36 | 143 | attr.assignment_values.add(value) |
paul@36 | 144 | |
paul@36 | 145 | def _set(self, name, value): |
paul@36 | 146 | if not self.namespace.has_key(name): |
paul@36 | 147 | self.namespace[name] = Attr(self.attr_position, self, name, value) |
paul@36 | 148 | self.attr_position += 1 |
paul@36 | 149 | return self.namespace[name] |
paul@23 | 150 | |
paul@12 | 151 | def __delitem__(self, name): |
paul@12 | 152 | del self.namespace[name] |
paul@12 | 153 | |
paul@13 | 154 | def has_key(self, name): |
paul@13 | 155 | return self.namespace.has_key(name) |
paul@13 | 156 | |
paul@3 | 157 | def keys(self): |
paul@3 | 158 | return self.namespace.keys() |
paul@3 | 159 | |
paul@7 | 160 | def values(self): |
paul@7 | 161 | return self.namespace.values() |
paul@7 | 162 | |
paul@7 | 163 | def items(self): |
paul@7 | 164 | return self.namespace.items() |
paul@7 | 165 | |
paul@12 | 166 | def make_global(self, name): |
paul@12 | 167 | if not self.namespace.has_key(name): |
paul@12 | 168 | self.globals.add(name) |
paul@12 | 169 | else: |
paul@12 | 170 | raise InspectError, "Name %r is global and local in %r" % (name, self) |
paul@12 | 171 | |
paul@32 | 172 | def get_assignments(self, name): |
paul@32 | 173 | if self.assignments.has_key(name): |
paul@32 | 174 | return max(self.assignments[name], len(self.assignment_values[name])) |
paul@32 | 175 | else: |
paul@32 | 176 | return None |
paul@32 | 177 | |
paul@4 | 178 | class Naming: |
paul@4 | 179 | |
paul@4 | 180 | "A mix-in providing naming conveniences." |
paul@4 | 181 | |
paul@4 | 182 | def full_name(self): |
paul@4 | 183 | if self.name is not None: |
paul@7 | 184 | return self.parent_name + "." + self.name |
paul@4 | 185 | else: |
paul@7 | 186 | return self.parent_name |
paul@4 | 187 | |
paul@12 | 188 | # Program data structures. |
paul@12 | 189 | |
paul@10 | 190 | class Attr: |
paul@10 | 191 | |
paul@10 | 192 | "An attribute entry." |
paul@10 | 193 | |
paul@36 | 194 | def __init__(self, position, parent, name, value=None, assignments=None): |
paul@10 | 195 | self.position = position |
paul@10 | 196 | self.parent = parent |
paul@36 | 197 | self.name = name |
paul@10 | 198 | self.value = value |
paul@10 | 199 | |
paul@36 | 200 | # Number of assignments per name. |
paul@36 | 201 | |
paul@36 | 202 | self.assignments = assignments |
paul@36 | 203 | self.assignment_values = set() |
paul@36 | 204 | |
paul@36 | 205 | def update(self, value, single_assignment): |
paul@36 | 206 | if self.assignments is None: |
paul@36 | 207 | if single_assignment: |
paul@36 | 208 | self.assignments = 1 |
paul@36 | 209 | else: |
paul@36 | 210 | self.assignments = AtLeast(1) |
paul@36 | 211 | else: |
paul@36 | 212 | if single_assignment: |
paul@36 | 213 | self.assignments += 1 |
paul@36 | 214 | else: |
paul@36 | 215 | self.assignments += AtLeast(1) |
paul@36 | 216 | self.assignment_values.add(value) |
paul@36 | 217 | |
paul@10 | 218 | def __repr__(self): |
paul@36 | 219 | return "Attr(%r, %r, %r, %r, %r)" % (self.position, self.parent, self.name, self.value, self.assignments) |
paul@10 | 220 | |
paul@21 | 221 | class Const: |
paul@21 | 222 | |
paul@21 | 223 | "A constant object." |
paul@21 | 224 | |
paul@21 | 225 | def __init__(self, value): |
paul@21 | 226 | self.value = value |
paul@21 | 227 | |
paul@21 | 228 | # Image generation details. |
paul@21 | 229 | |
paul@21 | 230 | self.location = None |
paul@21 | 231 | |
paul@21 | 232 | def __repr__(self): |
paul@24 | 233 | return "Const(%r, location=%r)" % (self.value, self.location) |
paul@21 | 234 | |
paul@21 | 235 | def __eq__(self, other): |
paul@21 | 236 | return self.value == other.value |
paul@21 | 237 | |
paul@21 | 238 | def __hash__(self): |
paul@21 | 239 | return hash(self.value) |
paul@21 | 240 | |
paul@4 | 241 | class Class(NamespaceDict, Naming): |
paul@0 | 242 | |
paul@0 | 243 | "An inspected class." |
paul@0 | 244 | |
paul@24 | 245 | def __init__(self, name, parent_name, global_namespace=None, node=None): |
paul@24 | 246 | NamespaceDict.__init__(self, global_namespace) |
paul@0 | 247 | self.name = name |
paul@7 | 248 | self.parent_name = parent_name |
paul@17 | 249 | self.node = node |
paul@12 | 250 | |
paul@0 | 251 | self.bases = [] |
paul@9 | 252 | self.instattr = set() # instance attributes |
paul@12 | 253 | |
paul@12 | 254 | self.all_instattr = None # cache for instance_attributes |
paul@13 | 255 | self.all_instattr_names = None # from all_instattr |
paul@12 | 256 | self.all_classattr = None # cache for all_class_attributes |
paul@12 | 257 | self.all_classattr_names = None # from all_classattr |
paul@9 | 258 | self.allattr = None # cache for all_attributes |
paul@10 | 259 | self.allattr_names = None # from allattr |
paul@9 | 260 | |
paul@9 | 261 | # Image generation details. |
paul@9 | 262 | |
paul@9 | 263 | self.location = None |
paul@19 | 264 | self.code_location = None |
paul@0 | 265 | |
paul@12 | 266 | def __repr__(self): |
paul@12 | 267 | return "Class(%r, %r, location=%r)" % (self.name, self.parent_name, self.location) |
paul@12 | 268 | |
paul@0 | 269 | def add_base(self, base): |
paul@0 | 270 | self.bases.append(base) |
paul@0 | 271 | |
paul@12 | 272 | def add_instance_attribute(self, name): |
paul@12 | 273 | self.instattr.add(name) |
paul@9 | 274 | |
paul@36 | 275 | "Return the attribute names provided by this class only." |
paul@9 | 276 | |
paul@36 | 277 | class_attribute_names = NamespaceDict.keys |
paul@4 | 278 | |
paul@4 | 279 | def class_attributes(self): |
paul@4 | 280 | |
paul@12 | 281 | "Return class attributes provided by this class only." |
paul@4 | 282 | |
paul@36 | 283 | return self |
paul@12 | 284 | |
paul@12 | 285 | def all_class_attribute_names(self): |
paul@12 | 286 | |
paul@12 | 287 | "Return the attribute names provided by classes in this hierarchy." |
paul@12 | 288 | |
paul@12 | 289 | if self.all_classattr_names is None: |
paul@12 | 290 | self.all_class_attributes() |
paul@12 | 291 | return self.all_classattr_names |
paul@12 | 292 | |
paul@12 | 293 | def all_class_attributes(self): |
paul@12 | 294 | |
paul@12 | 295 | "Return all class attributes, indicating the class which provides them." |
paul@12 | 296 | |
paul@12 | 297 | if self.all_classattr is None: |
paul@12 | 298 | self.all_classattr = {} |
paul@12 | 299 | |
paul@9 | 300 | reversed_bases = self.bases[:] |
paul@9 | 301 | reversed_bases.reverse() |
paul@9 | 302 | for cls in reversed_bases: |
paul@12 | 303 | self.all_classattr.update(cls.all_class_attributes()) |
paul@10 | 304 | |
paul@10 | 305 | # Record attributes provided by this class, along with their |
paul@10 | 306 | # positions. |
paul@10 | 307 | |
paul@12 | 308 | self.all_classattr.update(self.class_attributes()) |
paul@9 | 309 | |
paul@12 | 310 | return self.all_classattr |
paul@4 | 311 | |
paul@7 | 312 | def instance_attribute_names(self): |
paul@7 | 313 | |
paul@7 | 314 | "Return the instance attribute names provided by the class." |
paul@7 | 315 | |
paul@12 | 316 | if self.all_instattr_names is None: |
paul@12 | 317 | self.instance_attributes() |
paul@12 | 318 | return self.all_instattr_names |
paul@7 | 319 | |
paul@4 | 320 | def instance_attributes(self): |
paul@4 | 321 | |
paul@9 | 322 | "Return instance-only attributes for instances of this class." |
paul@9 | 323 | |
paul@12 | 324 | if self.all_instattr is None: |
paul@12 | 325 | self.all_instattr = {} |
paul@12 | 326 | instattr = set() |
paul@12 | 327 | |
paul@12 | 328 | reversed_bases = self.bases[:] |
paul@12 | 329 | reversed_bases.reverse() |
paul@12 | 330 | for cls in reversed_bases: |
paul@12 | 331 | instattr.update(cls.instance_attributes().keys()) |
paul@12 | 332 | |
paul@12 | 333 | # Record instance attributes provided by this class and its bases, |
paul@12 | 334 | # along with their positions. |
paul@12 | 335 | |
paul@12 | 336 | instattr.update(self.instattr) |
paul@12 | 337 | |
paul@12 | 338 | for i, name in enumerate(instattr): |
paul@36 | 339 | self.all_instattr[name] = Attr(i, None, name) |
paul@12 | 340 | |
paul@12 | 341 | self.all_instattr_names = self.all_instattr.keys() |
paul@12 | 342 | |
paul@12 | 343 | return self.all_instattr |
paul@9 | 344 | |
paul@9 | 345 | def all_attribute_names(self): |
paul@9 | 346 | |
paul@9 | 347 | """ |
paul@9 | 348 | Return the names of all attributes provided by instances of this class. |
paul@9 | 349 | """ |
paul@9 | 350 | |
paul@9 | 351 | self.allattr_names = self.allattr_names or self.all_attributes().keys() |
paul@9 | 352 | return self.allattr_names |
paul@9 | 353 | |
paul@9 | 354 | def all_attributes(self): |
paul@9 | 355 | |
paul@4 | 356 | """ |
paul@4 | 357 | Return all attributes for an instance, indicating either the class which |
paul@4 | 358 | provides them or that the instance itself provides them. |
paul@4 | 359 | """ |
paul@4 | 360 | |
paul@9 | 361 | if self.allattr is None: |
paul@9 | 362 | self.allattr = {} |
paul@12 | 363 | self.allattr.update(self.all_class_attributes()) |
paul@9 | 364 | for i, name in enumerate(self.instance_attribute_names()): |
paul@9 | 365 | if self.allattr.has_key(name): |
paul@9 | 366 | print "Instance attribute %r in %r overrides class attribute." % (name, self) |
paul@36 | 367 | self.allattr[name] = Attr(i, None, name) |
paul@9 | 368 | return self.allattr |
paul@4 | 369 | |
paul@12 | 370 | class Function(NamespaceDict, Naming): |
paul@0 | 371 | |
paul@0 | 372 | "An inspected function." |
paul@0 | 373 | |
paul@24 | 374 | def __init__(self, name, parent_name, argnames, has_star, has_dstar, global_namespace=None, node=None): |
paul@24 | 375 | NamespaceDict.__init__(self, global_namespace) |
paul@3 | 376 | self.name = name |
paul@7 | 377 | self.parent_name = parent_name |
paul@3 | 378 | self.argnames = argnames |
paul@3 | 379 | self.has_star = has_star |
paul@3 | 380 | self.has_dstar = has_dstar |
paul@17 | 381 | self.node = node |
paul@3 | 382 | |
paul@36 | 383 | # Caches. |
paul@36 | 384 | |
paul@12 | 385 | self.localnames = None # cache for locals |
paul@12 | 386 | |
paul@17 | 387 | # Add parameters to the namespace. |
paul@17 | 388 | |
paul@25 | 389 | self._add_parameters(argnames) |
paul@17 | 390 | |
paul@9 | 391 | # Image generation details. |
paul@9 | 392 | |
paul@9 | 393 | self.location = None |
paul@19 | 394 | self.code_location = None |
paul@9 | 395 | |
paul@25 | 396 | def _add_parameters(self, argnames): |
paul@25 | 397 | for name in argnames: |
paul@25 | 398 | if isinstance(name, tuple): |
paul@25 | 399 | self._add_parameters(name) |
paul@25 | 400 | else: |
paul@25 | 401 | self[name] = None |
paul@25 | 402 | |
paul@4 | 403 | def __repr__(self): |
paul@9 | 404 | return "Function(%r, %r, %r, %r, %r, location=%r)" % ( |
paul@9 | 405 | self.name, self.parent_name, self.argnames, self.has_star, self.has_dstar, self.location |
paul@4 | 406 | ) |
paul@4 | 407 | |
paul@12 | 408 | def make_global(self, name): |
paul@13 | 409 | if name not in self.argnames and not self.has_key(name): |
paul@12 | 410 | self.globals.add(name) |
paul@12 | 411 | else: |
paul@12 | 412 | raise InspectError, "Name %r is global and local in %r" % (name, self) |
paul@12 | 413 | |
paul@7 | 414 | def parameters(self): |
paul@7 | 415 | |
paul@7 | 416 | """ |
paul@7 | 417 | Return a dictionary mapping parameter names to their position in the |
paul@7 | 418 | parameter list. |
paul@7 | 419 | """ |
paul@7 | 420 | |
paul@7 | 421 | parameters = {} |
paul@7 | 422 | for i, name in enumerate(self.argnames): |
paul@7 | 423 | parameters[name] = i |
paul@7 | 424 | return parameters |
paul@7 | 425 | |
paul@36 | 426 | def all_locals(self): |
paul@36 | 427 | |
paul@36 | 428 | "Return a dictionary mapping names to local and parameter details." |
paul@36 | 429 | |
paul@36 | 430 | return self |
paul@36 | 431 | |
paul@12 | 432 | def locals(self): |
paul@12 | 433 | |
paul@12 | 434 | "Return a dictionary mapping names to local details." |
paul@12 | 435 | |
paul@12 | 436 | if self.localnames is None: |
paul@12 | 437 | self.localnames = {} |
paul@36 | 438 | self.localnames.update(self.all_locals()) |
paul@36 | 439 | for name in self.argnames: |
paul@36 | 440 | del self.localnames[name] |
paul@12 | 441 | return self.localnames |
paul@12 | 442 | |
paul@4 | 443 | class UnresolvedName(NamespaceDict, Naming): |
paul@3 | 444 | |
paul@3 | 445 | "A module, class or function which was mentioned but could not be imported." |
paul@3 | 446 | |
paul@24 | 447 | def __init__(self, name, parent_name, global_namespace=None): |
paul@24 | 448 | NamespaceDict.__init__(self, global_namespace) |
paul@0 | 449 | self.name = name |
paul@7 | 450 | self.parent_name = parent_name |
paul@0 | 451 | |
paul@12 | 452 | def all_class_attributes(self): |
paul@7 | 453 | return {} |
paul@7 | 454 | |
paul@13 | 455 | def instance_attributes(self): |
paul@13 | 456 | return {} |
paul@13 | 457 | |
paul@4 | 458 | def __repr__(self): |
paul@7 | 459 | return "UnresolvedName(%r, %r)" % (self.name, self.parent_name) |
paul@4 | 460 | |
paul@15 | 461 | class Module(NamespaceDict): |
paul@0 | 462 | |
paul@20 | 463 | "An inspected module's core details." |
paul@20 | 464 | |
paul@15 | 465 | def __init__(self, name): |
paul@24 | 466 | NamespaceDict.__init__(self, self) |
paul@1 | 467 | self.name = name |
paul@0 | 468 | |
paul@7 | 469 | # Complete lists of classes and functions. |
paul@7 | 470 | |
paul@33 | 471 | self.all_objects = set() |
paul@0 | 472 | |
paul@22 | 473 | # Constant records. |
paul@22 | 474 | |
paul@22 | 475 | self.constant_values = {} |
paul@22 | 476 | self.constant_list = None # cache for constants |
paul@22 | 477 | |
paul@15 | 478 | # Image generation details. |
paul@15 | 479 | |
paul@15 | 480 | self.location = None |
paul@19 | 481 | self.code_location = None |
paul@15 | 482 | |
paul@20 | 483 | # Original location details. |
paul@20 | 484 | |
paul@20 | 485 | self.node = None |
paul@20 | 486 | |
paul@15 | 487 | def full_name(self): |
paul@15 | 488 | return self.name |
paul@15 | 489 | |
paul@15 | 490 | def __repr__(self): |
paul@15 | 491 | return "Module(%r, location=%r)" % (self.name, self.location) |
paul@15 | 492 | |
paul@15 | 493 | # Attribute methods. |
paul@15 | 494 | |
paul@36 | 495 | "Return the module attribute names provided by the module." |
paul@15 | 496 | |
paul@36 | 497 | module_attribute_names = NamespaceDict.keys |
paul@15 | 498 | |
paul@15 | 499 | def module_attributes(self): |
paul@15 | 500 | |
paul@15 | 501 | "Return a dictionary mapping names to module attributes." |
paul@15 | 502 | |
paul@36 | 503 | return self |
paul@15 | 504 | |
paul@22 | 505 | def constants(self): |
paul@22 | 506 | |
paul@22 | 507 | "Return a list of constants." |
paul@22 | 508 | |
paul@22 | 509 | if self.constant_list is None: |
paul@22 | 510 | self.constant_list = list(self.constant_values.values()) |
paul@22 | 511 | |
paul@22 | 512 | return self.constant_list |
paul@22 | 513 | |
paul@21 | 514 | # Program visitors. |
paul@21 | 515 | |
paul@15 | 516 | class InspectedModule(ASTVisitor, Module): |
paul@15 | 517 | |
paul@20 | 518 | """ |
paul@20 | 519 | An inspected module, providing core details via the Module superclass, but |
paul@20 | 520 | capable of being used as an AST visitor. |
paul@20 | 521 | """ |
paul@15 | 522 | |
paul@15 | 523 | def __init__(self, name, importer=None): |
paul@15 | 524 | ASTVisitor.__init__(self) |
paul@15 | 525 | Module.__init__(self, name) |
paul@15 | 526 | self.visitor = self |
paul@15 | 527 | |
paul@15 | 528 | self.importer = importer |
paul@15 | 529 | self.loaded = 0 |
paul@15 | 530 | |
paul@1 | 531 | # Current expression state. |
paul@1 | 532 | |
paul@1 | 533 | self.expr = None |
paul@1 | 534 | |
paul@1 | 535 | # Namespace state. |
paul@1 | 536 | |
paul@34 | 537 | self.in_init = 0 # Find instance attributes in __init__ methods. |
paul@34 | 538 | self.in_loop = 0 # Note loop "membership", affecting assignments. |
paul@12 | 539 | self.namespaces = [] |
paul@0 | 540 | self.module = None |
paul@0 | 541 | |
paul@0 | 542 | def parse(self, filename): |
paul@9 | 543 | |
paul@9 | 544 | "Parse the file having the given 'filename'." |
paul@9 | 545 | |
paul@0 | 546 | module = compiler.parseFile(filename) |
paul@0 | 547 | self.process(module) |
paul@0 | 548 | |
paul@0 | 549 | def process(self, module): |
paul@9 | 550 | |
paul@9 | 551 | "Process the given 'module'." |
paul@9 | 552 | |
paul@20 | 553 | self.node = self.module = module |
paul@1 | 554 | processed = self.dispatch(module) |
paul@13 | 555 | if self.has_key("__all__"): |
paul@12 | 556 | all = self["__all__"] |
paul@1 | 557 | if isinstance(all, compiler.ast.List): |
paul@1 | 558 | for n in all.nodes: |
paul@12 | 559 | self[n.value] = self.importer.add_module(self.name + "." + n.value) |
paul@1 | 560 | return processed |
paul@0 | 561 | |
paul@3 | 562 | def vacuum(self): |
paul@9 | 563 | |
paul@9 | 564 | "Vacuum the module namespace, removing unloaded module references." |
paul@9 | 565 | |
paul@13 | 566 | for name, value in self.items(): |
paul@3 | 567 | if isinstance(value, Module) and not value.loaded: |
paul@12 | 568 | del self[name] |
paul@0 | 569 | |
paul@16 | 570 | # Complain about globals not initialised at the module level. |
paul@16 | 571 | |
paul@16 | 572 | if isinstance(value, Global): |
paul@16 | 573 | print "Warning: global %r in module %r not initialised at the module level." % (name, self.name) |
paul@16 | 574 | |
paul@3 | 575 | # Namespace methods. |
paul@0 | 576 | |
paul@0 | 577 | def store(self, name, obj): |
paul@12 | 578 | |
paul@12 | 579 | "Record attribute or local 'name', storing 'obj'." |
paul@12 | 580 | |
paul@12 | 581 | if not self.namespaces: |
paul@34 | 582 | self.set(name, obj, not self.in_loop) |
paul@12 | 583 | else: |
paul@34 | 584 | self.namespaces[-1].set(name, obj, not self.in_loop) |
paul@12 | 585 | |
paul@12 | 586 | # Record all non-local objects. |
paul@12 | 587 | |
paul@12 | 588 | if not (self.namespaces and isinstance(self.namespaces[-1], Function)): |
paul@33 | 589 | self.all_objects.add(obj) |
paul@0 | 590 | |
paul@34 | 591 | def store_instance_attr(self, name): |
paul@12 | 592 | |
paul@12 | 593 | "Record instance attribute 'name' in the current class." |
paul@12 | 594 | |
paul@0 | 595 | if self.in_init: |
paul@15 | 596 | |
paul@12 | 597 | # Current namespace is the function. |
paul@12 | 598 | # Previous namespace is the class. |
paul@15 | 599 | |
paul@12 | 600 | self.namespaces[-2].add_instance_attribute(name) |
paul@0 | 601 | |
paul@7 | 602 | def get_parent(self): |
paul@12 | 603 | return (self.namespaces[-1:] or [self])[0] |
paul@7 | 604 | |
paul@3 | 605 | # Visitor methods. |
paul@3 | 606 | |
paul@3 | 607 | def default(self, node, *args): |
paul@3 | 608 | raise InspectError, node.__class__ |
paul@3 | 609 | |
paul@3 | 610 | def dispatch(self, node, *args): |
paul@3 | 611 | return ASTVisitor.dispatch(self, node, *args) |
paul@3 | 612 | |
paul@0 | 613 | def NOP(self, node): |
paul@21 | 614 | for n in node.getChildNodes(): |
paul@21 | 615 | self.dispatch(n) |
paul@19 | 616 | return None |
paul@0 | 617 | |
paul@1 | 618 | visitAdd = NOP |
paul@1 | 619 | |
paul@0 | 620 | visitAnd = NOP |
paul@0 | 621 | |
paul@4 | 622 | visitAssert = NOP |
paul@4 | 623 | |
paul@0 | 624 | def visitAssign(self, node): |
paul@0 | 625 | self.expr = self.dispatch(node.expr) |
paul@0 | 626 | for n in node.nodes: |
paul@0 | 627 | self.dispatch(n) |
paul@0 | 628 | return None |
paul@0 | 629 | |
paul@0 | 630 | def visitAssAttr(self, node): |
paul@0 | 631 | expr = self.dispatch(node.expr) |
paul@36 | 632 | if isinstance(expr, Attr) and expr.name == "self": |
paul@34 | 633 | self.store_instance_attr(node.attrname) |
paul@0 | 634 | return None |
paul@0 | 635 | |
paul@0 | 636 | def visitAssList(self, node): |
paul@0 | 637 | for n in node.nodes: |
paul@0 | 638 | self.dispatch(n) |
paul@0 | 639 | return None |
paul@0 | 640 | |
paul@0 | 641 | def visitAssName(self, node): |
paul@36 | 642 | if isinstance(self.expr, Attr): |
paul@36 | 643 | self.store(node.name, self.expr.value) |
paul@36 | 644 | else: |
paul@36 | 645 | self.store(node.name, self.expr) |
paul@0 | 646 | return None |
paul@0 | 647 | |
paul@0 | 648 | visitAssTuple = visitAssList |
paul@0 | 649 | |
paul@2 | 650 | visitAugAssign = NOP |
paul@2 | 651 | |
paul@4 | 652 | visitBackquote = NOP |
paul@4 | 653 | |
paul@2 | 654 | visitBitand = NOP |
paul@2 | 655 | |
paul@2 | 656 | visitBitor = NOP |
paul@2 | 657 | |
paul@4 | 658 | visitBitxor = NOP |
paul@4 | 659 | |
paul@4 | 660 | visitBreak = NOP |
paul@4 | 661 | |
paul@0 | 662 | visitCallFunc = NOP |
paul@0 | 663 | |
paul@0 | 664 | def visitClass(self, node): |
paul@12 | 665 | if self.namespaces: |
paul@4 | 666 | print "Class %r in %r is not global: ignored." % (node.name, self) |
paul@0 | 667 | else: |
paul@24 | 668 | cls = Class(node.name, self.get_parent().full_name(), self, node) |
paul@0 | 669 | for base in node.bases: |
paul@36 | 670 | expr = self.dispatch(base) |
paul@36 | 671 | if isinstance(expr, Attr): |
paul@36 | 672 | if expr.assignments != 1: |
paul@36 | 673 | print "Base class %r for class %r in %r may not be constant." % (base, cls, self) |
paul@36 | 674 | else: |
paul@36 | 675 | cls.add_base(expr.value) |
paul@36 | 676 | else: # if expr is None: |
paul@36 | 677 | raise InspectError, "Base class %r for class %r in %r is not found: it may be hidden in some way." % (base, cls, self) |
paul@0 | 678 | |
paul@21 | 679 | # Make a back reference from the node for code generation. |
paul@21 | 680 | |
paul@21 | 681 | node.cls = cls |
paul@21 | 682 | |
paul@0 | 683 | # Make an entry for the class. |
paul@0 | 684 | |
paul@0 | 685 | self.store(node.name, cls) |
paul@0 | 686 | |
paul@12 | 687 | self.namespaces.append(cls) |
paul@0 | 688 | self.dispatch(node.code) |
paul@12 | 689 | self.namespaces.pop() |
paul@0 | 690 | |
paul@19 | 691 | return None |
paul@0 | 692 | |
paul@4 | 693 | visitCompare = NOP |
paul@4 | 694 | |
paul@21 | 695 | def visitConst(self, node): |
paul@21 | 696 | const = Const(node.value) |
paul@22 | 697 | self.constant_values[node.value] = const |
paul@24 | 698 | return const |
paul@0 | 699 | |
paul@4 | 700 | visitContinue = NOP |
paul@4 | 701 | |
paul@4 | 702 | visitDecorators = NOP |
paul@4 | 703 | |
paul@0 | 704 | visitDict = NOP |
paul@0 | 705 | |
paul@0 | 706 | visitDiscard = NOP |
paul@0 | 707 | |
paul@4 | 708 | visitDiv = NOP |
paul@4 | 709 | |
paul@4 | 710 | visitEllipsis = NOP |
paul@4 | 711 | |
paul@4 | 712 | visitExec = NOP |
paul@4 | 713 | |
paul@4 | 714 | visitExpression = NOP |
paul@4 | 715 | |
paul@4 | 716 | visitFloorDiv = NOP |
paul@4 | 717 | |
paul@34 | 718 | def visitFor(self, node): |
paul@34 | 719 | self.in_loop = 1 |
paul@34 | 720 | self.NOP(node) |
paul@34 | 721 | self.in_loop = 0 |
paul@0 | 722 | |
paul@0 | 723 | def visitFrom(self, node): |
paul@0 | 724 | if self.importer is None: |
paul@0 | 725 | raise InspectError, "Please use the micropython.Importer class for code which uses the 'from' statement." |
paul@0 | 726 | |
paul@0 | 727 | module = self.importer.load(node.modname, 1) |
paul@0 | 728 | |
paul@35 | 729 | #if module is None: |
paul@35 | 730 | # print "Warning:", node.modname, "not imported." |
paul@0 | 731 | |
paul@0 | 732 | for name, alias in node.names: |
paul@0 | 733 | if name != "*": |
paul@4 | 734 | if module is not None and module.namespace.has_key(name): |
paul@24 | 735 | attr = module[name] |
paul@36 | 736 | self.store(alias or name, attr.value) |
paul@2 | 737 | if isinstance(attr, Module) and not attr.loaded: |
paul@2 | 738 | self.importer.load(attr.name) |
paul@24 | 739 | |
paul@24 | 740 | # Support the import of names from missing modules. |
paul@24 | 741 | |
paul@3 | 742 | else: |
paul@24 | 743 | self.store(alias or name, UnresolvedName(name, node.modname, self)) |
paul@3 | 744 | else: |
paul@3 | 745 | if module is not None: |
paul@3 | 746 | for n in module.namespace.keys(): |
paul@24 | 747 | attr = module[n] |
paul@36 | 748 | self.store(n, attr.value) |
paul@3 | 749 | if isinstance(attr, Module) and not attr.loaded: |
paul@3 | 750 | self.importer.load(attr.name) |
paul@0 | 751 | |
paul@0 | 752 | return None |
paul@0 | 753 | |
paul@0 | 754 | def visitFunction(self, node): |
paul@3 | 755 | function = Function( |
paul@3 | 756 | node.name, |
paul@7 | 757 | self.get_parent().full_name(), |
paul@3 | 758 | node.argnames, |
paul@17 | 759 | (node.flags & 4 != 0), |
paul@17 | 760 | (node.flags & 8 != 0), |
paul@24 | 761 | self, |
paul@17 | 762 | node |
paul@3 | 763 | ) |
paul@0 | 764 | |
paul@21 | 765 | # Make a back reference from the node for code generation. |
paul@21 | 766 | |
paul@21 | 767 | node.function = function |
paul@21 | 768 | |
paul@12 | 769 | self.namespaces.append(function) |
paul@15 | 770 | |
paul@12 | 771 | # Current namespace is the function. |
paul@12 | 772 | # Previous namespace is the class. |
paul@15 | 773 | |
paul@12 | 774 | if node.name == "__init__" and isinstance(self.namespaces[-2], Class): |
paul@0 | 775 | self.in_init = 1 |
paul@15 | 776 | |
paul@12 | 777 | self.dispatch(node.code) |
paul@12 | 778 | self.in_init = 0 |
paul@12 | 779 | self.namespaces.pop() |
paul@3 | 780 | |
paul@3 | 781 | self.store(node.name, function) |
paul@0 | 782 | return None |
paul@0 | 783 | |
paul@4 | 784 | visitGenExpr = NOP |
paul@4 | 785 | |
paul@4 | 786 | visitGenExprFor = NOP |
paul@4 | 787 | |
paul@4 | 788 | visitGenExprIf = NOP |
paul@4 | 789 | |
paul@4 | 790 | visitGenExprInner = NOP |
paul@4 | 791 | |
paul@0 | 792 | def visitGetattr(self, node): |
paul@0 | 793 | expr = self.dispatch(node.expr) |
paul@36 | 794 | if isinstance(expr, Attr): |
paul@36 | 795 | value = expr.value |
paul@36 | 796 | if isinstance(value, Module): |
paul@36 | 797 | return value.namespace.get(node.attrname) |
paul@36 | 798 | elif isinstance(value, UnresolvedName): |
paul@36 | 799 | return UnresolvedName(node.attrname, value.full_name(), self) |
paul@15 | 800 | return builtins.get(node.attrname) |
paul@4 | 801 | |
paul@12 | 802 | def visitGlobal(self, node): |
paul@12 | 803 | if self.namespaces: |
paul@12 | 804 | for name in node.names: |
paul@12 | 805 | self.namespaces[-1].make_global(name) |
paul@15 | 806 | if not self.has_key(name): |
paul@16 | 807 | self[name] = Global() |
paul@0 | 808 | |
paul@0 | 809 | def visitIf(self, node): |
paul@0 | 810 | for test, body in node.tests: |
paul@0 | 811 | self.dispatch(body) |
paul@0 | 812 | if node.else_ is not None: |
paul@0 | 813 | self.dispatch(node.else_) |
paul@0 | 814 | return None |
paul@0 | 815 | |
paul@12 | 816 | visitIfExp = NOP |
paul@12 | 817 | |
paul@0 | 818 | def visitImport(self, node): |
paul@0 | 819 | if self.importer is None: |
paul@0 | 820 | raise InspectError, "Please use the micropython.Importer class for code which uses the 'import' statement." |
paul@0 | 821 | |
paul@0 | 822 | for name, alias in node.names: |
paul@2 | 823 | if alias is not None: |
paul@24 | 824 | self.store(alias, self.importer.load(name, 1) or UnresolvedName(None, name, self)) |
paul@2 | 825 | else: |
paul@24 | 826 | self.store(name.split(".")[0], self.importer.load(name) or UnresolvedName(None, name.split(".")[0], self)) |
paul@0 | 827 | |
paul@0 | 828 | return None |
paul@0 | 829 | |
paul@4 | 830 | visitInvert = NOP |
paul@4 | 831 | |
paul@4 | 832 | visitKeyword = NOP |
paul@4 | 833 | |
paul@4 | 834 | visitLambda = NOP |
paul@4 | 835 | |
paul@1 | 836 | visitLeftShift = NOP |
paul@1 | 837 | |
paul@0 | 838 | visitList = NOP |
paul@0 | 839 | |
paul@4 | 840 | visitListComp = NOP |
paul@4 | 841 | |
paul@4 | 842 | visitListCompFor = NOP |
paul@4 | 843 | |
paul@4 | 844 | visitListCompIf = NOP |
paul@4 | 845 | |
paul@4 | 846 | visitMod = NOP |
paul@4 | 847 | |
paul@0 | 848 | def visitModule(self, node): |
paul@0 | 849 | return self.dispatch(node.node) |
paul@0 | 850 | |
paul@2 | 851 | visitMul = NOP |
paul@2 | 852 | |
paul@0 | 853 | def visitName(self, node): |
paul@0 | 854 | name = node.name |
paul@36 | 855 | if self.namespaces and self.namespaces[-1].has_key(name): |
paul@35 | 856 | return self.namespaces[-1][name] |
paul@13 | 857 | elif self.has_key(name): |
paul@12 | 858 | return self[name] |
paul@15 | 859 | elif builtins.has_key(name): |
paul@15 | 860 | return builtins[name] |
paul@0 | 861 | else: |
paul@0 | 862 | return None |
paul@0 | 863 | |
paul@0 | 864 | visitNot = NOP |
paul@0 | 865 | |
paul@0 | 866 | visitOr = NOP |
paul@0 | 867 | |
paul@0 | 868 | visitPass = NOP |
paul@0 | 869 | |
paul@4 | 870 | visitPower = NOP |
paul@4 | 871 | |
paul@4 | 872 | visitPrint = NOP |
paul@4 | 873 | |
paul@4 | 874 | visitPrintnl = NOP |
paul@4 | 875 | |
paul@0 | 876 | visitRaise = NOP |
paul@0 | 877 | |
paul@4 | 878 | visitReturn = NOP |
paul@4 | 879 | |
paul@1 | 880 | visitRightShift = NOP |
paul@1 | 881 | |
paul@4 | 882 | visitSlice = NOP |
paul@4 | 883 | |
paul@23 | 884 | visitSliceobj = NOP |
paul@23 | 885 | |
paul@0 | 886 | def visitStmt(self, node): |
paul@0 | 887 | for n in node.nodes: |
paul@0 | 888 | self.dispatch(n) |
paul@0 | 889 | return None |
paul@0 | 890 | |
paul@4 | 891 | visitSub = NOP |
paul@4 | 892 | |
paul@0 | 893 | visitSubscript = NOP |
paul@0 | 894 | |
paul@0 | 895 | def visitTryExcept(self, node): |
paul@0 | 896 | self.dispatch(node.body) |
paul@0 | 897 | for name, var, n in node.handlers: |
paul@0 | 898 | self.dispatch(n) |
paul@0 | 899 | if node.else_ is not None: |
paul@0 | 900 | self.dispatch(node.else_) |
paul@0 | 901 | return None |
paul@0 | 902 | |
paul@4 | 903 | visitTryFinally = NOP |
paul@4 | 904 | |
paul@1 | 905 | visitTuple = NOP |
paul@1 | 906 | |
paul@4 | 907 | visitUnaryAdd = NOP |
paul@4 | 908 | |
paul@4 | 909 | visitUnarySub = NOP |
paul@4 | 910 | |
paul@34 | 911 | def visitWhile(self, node): |
paul@34 | 912 | self.in_loop = 1 |
paul@34 | 913 | self.NOP(node) |
paul@34 | 914 | self.in_loop = 0 |
paul@4 | 915 | |
paul@4 | 916 | visitWith = NOP |
paul@4 | 917 | |
paul@4 | 918 | visitYield = NOP |
paul@4 | 919 | |
paul@16 | 920 | class Global: |
paul@16 | 921 | |
paul@16 | 922 | """ |
paul@16 | 923 | A reference to an object assigned to a global from outside the module |
paul@16 | 924 | top-level. |
paul@16 | 925 | """ |
paul@16 | 926 | |
paul@16 | 927 | pass |
paul@16 | 928 | |
paul@4 | 929 | # Built-in types initialisation. |
paul@4 | 930 | |
paul@15 | 931 | class Builtins(Module): |
paul@15 | 932 | |
paul@15 | 933 | "The special built-in types module." |
paul@15 | 934 | |
paul@15 | 935 | def __init__(self): |
paul@15 | 936 | Module.__init__(self, "__builtins__") |
paul@15 | 937 | |
paul@15 | 938 | for key in ['ArithmeticError', 'AssertionError', 'AttributeError', |
paul@15 | 939 | 'BaseException', 'DeprecationWarning', 'EOFError', 'Ellipsis', |
paul@15 | 940 | 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', |
paul@15 | 941 | 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', |
paul@15 | 942 | 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', |
paul@15 | 943 | 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', |
paul@15 | 944 | 'None', 'NotImplemented', 'NotImplementedError', 'OSError', |
paul@15 | 945 | 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', |
paul@15 | 946 | 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', |
paul@15 | 947 | 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', |
paul@15 | 948 | 'TabError', 'True', 'TypeError', 'UnboundLocalError', |
paul@15 | 949 | 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', |
paul@15 | 950 | 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', |
paul@15 | 951 | 'ValueError', 'Warning', 'ZeroDivisionError', |
paul@25 | 952 | 'basestring', 'bool', 'buffer', 'complex', 'dict', 'file', 'float', |
paul@25 | 953 | 'frozenset', 'int', 'list', 'long', 'object', 'set', 'slice', 'str', |
paul@25 | 954 | 'tuple', 'type', 'unicode', 'xrange']: |
paul@24 | 955 | self[key] = Class(key, self.full_name(), self) |
paul@15 | 956 | |
paul@25 | 957 | # NOTE: Incomplete: some functions have more than one parameter. |
paul@25 | 958 | |
paul@25 | 959 | for key in ['__import__', 'abs', 'all', 'any', 'callable', 'chr', |
paul@25 | 960 | 'classmethod', 'cmp', 'compile', 'delattr', 'dir', 'divmod', |
paul@25 | 961 | 'enumerate', 'eval', 'execfile', 'filter', 'getattr', 'globals', |
paul@25 | 962 | 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'isinstance', |
paul@25 | 963 | 'issubclass', 'iter', 'len', 'locals', 'map', 'max', 'min', 'oct', |
paul@25 | 964 | 'open', 'ord', 'pow', 'property', 'range', 'raw_input', 'reduce', |
paul@25 | 965 | 'reload', 'repr', 'reversed', 'round', 'setattr', 'sorted', |
paul@25 | 966 | 'staticmethod', 'sum', 'super', 'unichr', 'vars', 'zip']: |
paul@24 | 967 | self[key] = Function(key, self.full_name(), ['arg'], 0, 0, self) |
paul@16 | 968 | |
paul@15 | 969 | builtins = Builtins() |
paul@0 | 970 | |
paul@0 | 971 | # vim: tabstop=4 expandtab shiftwidth=4 |