ยปCore Development>Code coverage>Lib/compiler/symbols.py

Python code coverage for Lib/compiler/symbols.py

#countcontent
12"""Module symbol-table generator"""
2n/a
32from compiler import ast
42from compiler.consts import SC_LOCAL, SC_GLOBAL_IMPLICIT, SC_GLOBAL_EXPLICT, \
5n/a SC_FREE, SC_CELL, SC_UNKNOWN
62from compiler.misc import mangle
72import types
8n/a
9n/a
102import sys
11n/a
122MANGLE_LEN = 256
13n/a
144class Scope:
15n/a # XXX how much information do I need about each name?
162 def __init__(self, name, module, klass=None):
171059 self.name = name
181059 self.module = module
191059 self.defs = {}
201059 self.uses = {}
211059 self.globals = {}
221059 self.params = {}
231059 self.frees = {}
241059 self.cells = {}
251059 self.children = []
26n/a # nested is true if the class could contain free variables,
27n/a # i.e. if it is nested within another function.
281059 self.nested = None
291059 self.generator = None
301059 self.klass = None
311059 if klass is not None:
32993 for i in range(len(klass)):
33993 if klass[i] != '_':
34976 self.klass = klass[i:]
35976 break
36n/a
372 def __repr__(self):
380 return "<%s: %s>" % (self.__class__.__name__, self.name)
39n/a
402 def mangle(self, name):
4110098 if self.klass is None:
42619 return name
439479 return mangle(name, self.klass)
44n/a
452 def add_def(self, name):
462327 self.defs[self.mangle(name)] = 1
47n/a
482 def add_use(self, name):
496815 self.uses[self.mangle(name)] = 1
50n/a
512 def add_global(self, name):
5211 name = self.mangle(name)
5311 if name in self.uses or name in self.defs:
540 pass # XXX warn about global following def/use
5511 if name in self.params:
560 raise SyntaxError, "%s in %s is global and parameter" % \
570 (name, self.name)
5811 self.globals[name] = 1
5911 self.module.add_def(name)
60n/a
612 def add_param(self, name):
62945 name = self.mangle(name)
63945 self.defs[name] = 1
64945 self.params[name] = 1
65n/a
662 def get_names(self):
670 d = {}
680 d.update(self.defs)
690 d.update(self.uses)
700 d.update(self.globals)
710 return d.keys()
72n/a
732 def add_child(self, child):
741028 self.children.append(child)
75n/a
762 def get_children(self):
770 return self.children
78n/a
792 def DEBUG(self):
800 print >> sys.stderr, self.name, self.nested and "nested" or ""
810 print >> sys.stderr, "\tglobals: ", self.globals
820 print >> sys.stderr, "\tcells: ", self.cells
830 print >> sys.stderr, "\tdefs: ", self.defs
840 print >> sys.stderr, "\tuses: ", self.uses
850 print >> sys.stderr, "\tfrees:", self.frees
86n/a
872 def check_name(self, name):
88n/a """Return scope of name.
89n/a
90n/a The scope of a name could be LOCAL, GLOBAL, FREE, or CELL.
91n/a """
929971 if name in self.globals:
93301 return SC_GLOBAL_EXPLICT
949670 if name in self.cells:
95385 return SC_CELL
969285 if name in self.defs:
977042 return SC_LOCAL
982243 if self.nested and (name in self.frees or name in self.uses):
99314 return SC_FREE
1001929 if self.nested:
101365 return SC_UNKNOWN
102n/a else:
1031564 return SC_GLOBAL_IMPLICIT
104n/a
1052 def get_free_vars(self):
1063010 if not self.nested:
107931 return ()
1082079 free = {}
1092079 free.update(self.frees)
1104425 for name in self.uses.keys():
1112346 if name not in self.defs and name not in self.globals:
112554 free[name] = 1
1132079 return free.keys()
114n/a
1152 def handle_children(self):
1161982 for child in self.children:
117954 frees = child.get_free_vars()
118954 globals = self.add_frees(frees)
1191136 for name in globals:
120182 child.force_global(name)
121n/a
1222 def force_global(self, name):
123n/a """Force name to be global in scope.
124n/a
125n/a Some child of the current node had a free reference to name.
126n/a When the child was processed, it was labelled a free
127n/a variable. Now that all its enclosing scope have been
128n/a processed, the name is known to be a global or builtin. So
129n/a walk back down the child chain and set the name to be global
130n/a rather than free.
131n/a
132n/a Be careful to stop if a child does not think the name is
133n/a free.
134n/a """
135322 self.globals[name] = 1
136322 if name in self.frees:
137111 del self.frees[name]
138676 for child in self.children:
139354 if child.check_name(name) == SC_FREE:
140140 child.force_global(name)
141n/a
1422 def add_frees(self, names):
143n/a """Process list of free vars from nested scope.
144n/a
145n/a Returns a list of names that are either 1) declared global in the
146n/a parent or 2) undefined in a top-level parent. In either case,
147n/a the nested scope should treat them as globals.
148n/a """
149954 child_globals = []
1501433 for name in names:
151479 sc = self.check_name(name)
152479 if self.nested:
153201 if sc == SC_UNKNOWN or sc == SC_FREE \
1541 or isinstance(self, ClassScope):
155200 self.frees[name] = 1
1561 elif sc == SC_GLOBAL_IMPLICIT:
1570 child_globals.append(name)
1581 elif isinstance(self, FunctionScope) and sc == SC_LOCAL:
1591 self.cells[name] = 1
1600 elif sc != SC_CELL:
1610 child_globals.append(name)
162n/a else:
163278 if sc == SC_LOCAL:
16483 self.cells[name] = 1
165195 elif sc != SC_CELL:
166182 child_globals.append(name)
167954 return child_globals
168n/a
1692 def get_cell_vars(self):
1701028 return self.cells.keys()
171n/a
1724class ModuleScope(Scope):
1732 __super_init = Scope.__init__
174n/a
1752 def __init__(self):
17631 self.__super_init("global", self)
177n/a
1784class FunctionScope(Scope):
1792 pass
180n/a
1814class GenExprScope(Scope):
1822 __super_init = Scope.__init__
183n/a
1842 __counter = 1
185n/a
1862 def __init__(self, module, klass=None):
1872 i = self.__counter
1882 self.__counter += 1
1892 self.__super_init("generator expression<%d>"%i, module, klass)
1902 self.add_param('.0')
191n/a
1922 def get_names(self):
1930 keys = Scope.get_names(self)
1940 return keys
195n/a
1964class LambdaScope(FunctionScope):
1972 __super_init = Scope.__init__
198n/a
1992 __counter = 1
200n/a
2012 def __init__(self, module, klass=None):
20218 i = self.__counter
20318 self.__counter += 1
20418 self.__super_init("lambda.%d" % i, module, klass)
205n/a
2064class ClassScope(Scope):
2072 __super_init = Scope.__init__
208n/a
2092 def __init__(self, name, module):
210391 self.__super_init(name, module, name)
211n/a
2124class SymbolVisitor:
2132 def __init__(self):
21431 self.scopes = {}
21531 self.klass = None
216n/a
217n/a # node that define new scopes
218n/a
2192 def visitModule(self, node):
22031 scope = self.module = self.scopes[node] = ModuleScope()
22131 self.visit(node.node, scope)
222n/a
2232 visitExpression = visitModule
224n/a
2252 def visitFunction(self, node, parent):
226617 if node.decorators:
22719 self.visit(node.decorators, parent)
228617 parent.add_def(node.name)
229660 for n in node.defaults:
23043 self.visit(n, parent)
231617 scope = FunctionScope(node.name, self.module, self.klass)
232617 if parent.nested or isinstance(parent, FunctionScope):
233306 scope.nested = 1
234617 self.scopes[node] = scope
235617 self._do_args(scope, node.argnames)
236617 self.visit(node.code, scope)
237617 self.handle_free_vars(scope, parent)
238n/a
2392 def visitGenExpr(self, node, parent):
2402 scope = GenExprScope(self.module, self.klass);
2412 if parent.nested or isinstance(parent, FunctionScope) \
2421 or isinstance(parent, GenExprScope):
2431 scope.nested = 1
244n/a
2452 self.scopes[node] = scope
2462 self.visit(node.code, scope)
247n/a
2482 self.handle_free_vars(scope, parent)
249n/a
2502 def visitGenExprInner(self, node, scope):
2515 for genfor in node.quals:
2523 self.visit(genfor, scope)
253n/a
2542 self.visit(node.expr, scope)
255n/a
2562 def visitGenExprFor(self, node, scope):
2573 self.visit(node.assign, scope, 1)
2583 self.visit(node.iter, scope)
2595 for if_ in node.ifs:
2602 self.visit(if_, scope)
261n/a
2622 def visitGenExprIf(self, node, scope):
2632 self.visit(node.test, scope)
264n/a
2652 def visitLambda(self, node, parent, assign=0):
266n/a # Lambda is an expression, so it could appear in an expression
267n/a # context where assign is passed. The transformer should catch
268n/a # any code that has a lambda on the left-hand side.
26918 assert not assign
270n/a
27118 for n in node.defaults:
2720 self.visit(n, parent)
27318 scope = LambdaScope(self.module, self.klass)
27418 if parent.nested or isinstance(parent, FunctionScope):
27518 scope.nested = 1
27618 self.scopes[node] = scope
27718 self._do_args(scope, node.argnames)
27818 self.visit(node.code, scope)
27918 self.handle_free_vars(scope, parent)
280n/a
2812 def _do_args(self, scope, args):
2821578 for name in args:
283943 if type(name) == types.TupleType:
2840 self._do_args(scope, name)
285n/a else:
286943 scope.add_param(name)
287n/a
2882 def handle_free_vars(self, scope, parent):
2891028 parent.add_child(scope)
2901028 scope.handle_children()
291n/a
2922 def visitClass(self, node, parent):
293391 parent.add_def(node.name)
294805 for n in node.bases:
295414 self.visit(n, parent)
296391 scope = ClassScope(node.name, self.module)
297391 if parent.nested or isinstance(parent, FunctionScope):
298368 scope.nested = 1
299391 if node.doc is not None:
3007 scope.add_def('__doc__')
301391 scope.add_def('__module__')
302391 self.scopes[node] = scope
303391 prev = self.klass
304391 self.klass = node.name
305391 self.visit(node.code, scope)
306391 self.klass = prev
307391 self.handle_free_vars(scope, parent)
308n/a
309n/a # name can be a def or a use
310n/a
311n/a # XXX a few calls and nodes expect a third "assign" arg that is
312n/a # true if the name is being used as an assignment. only
313n/a # expressions contained within statements may have the assign arg.
314n/a
3152 def visitName(self, node, scope, assign=0):
3166826 if assign:
31711 scope.add_def(node.name)
318n/a else:
3196815 scope.add_use(node.name)
320n/a
321n/a # operations that bind new names
322n/a
3232 def visitFor(self, node, scope):
32490 self.visit(node.assign, scope, 1)
32590 self.visit(node.list, scope)
32690 self.visit(node.body, scope)
32790 if node.else_:
3280 self.visit(node.else_, scope)
329n/a
3302 def visitFrom(self, node, scope):
33132 for name, asname in node.names:
33217 if name == "*":
3330 continue
33417 scope.add_def(asname or name)
335n/a
3362 def visitImport(self, node, scope):
337101 for name, asname in node.names:
33853 i = name.find(".")
33953 if i > -1:
3402 name = name[:i]
34153 scope.add_def(asname or name)
342n/a
3432 def visitGlobal(self, node, scope):
34418 for name in node.names:
34511 scope.add_global(name)
346n/a
3472 def visitAssign(self, node, scope):
348n/a """Propagate assignment flag down to child nodes.
349n/a
350n/a The Assign node doesn't itself contains the variables being
351n/a assigned to. Instead, the children in node.nodes are visited
352n/a with the assign flag set to true. When the names occur in
353n/a those nodes, they are marked as defs.
354n/a
355n/a Some names that occur in an assignment target are not bound by
356n/a the assignment, e.g. a name occurring inside a slice. The
357n/a visitor handles these nodes specially; they do not propagate
358n/a the assign flag to their children.
359n/a """
3601946 for n in node.nodes:
361975 self.visit(n, scope, 1)
362971 self.visit(node.expr, scope)
363n/a
3642 def visitAssName(self, node, scope, assign=1):
365829 scope.add_def(node.name)
366n/a
3672 def visitAssAttr(self, node, scope, assign=0):
368337 self.visit(node.expr, scope, 0)
369n/a
3702 def visitSubscript(self, node, scope, assign=0):
371148 self.visit(node.expr, scope, 0)
372296 for n in node.subs:
373148 self.visit(n, scope, 0)
374n/a
3752 def visitSlice(self, node, scope, assign=0):
37634 self.visit(node.expr, scope, 0)
37734 if node.lower:
37818 self.visit(node.lower, scope, 0)
37934 if node.upper:
38020 self.visit(node.upper, scope, 0)
381n/a
3822 def visitAugAssign(self, node, scope):
383n/a # If the LHS is a name, then this counts as assignment.
384n/a # Otherwise, it's just use.
38517 self.visit(node.node, scope)
38617 if isinstance(node.node, ast.Name):
38711 self.visit(node.node, scope, 1) # XXX worry about this
38817 self.visit(node.expr, scope)
389n/a
390n/a # prune if statements if tests are false
391n/a
3922 _const_types = types.StringType, types.IntType, types.FloatType
393n/a
3942 def visitIf(self, node, scope):
395234 for test, body in node.tests:
396118 if isinstance(test, ast.Const):
3970 if type(test.value) in self._const_types:
3980 if not test.value:
3990 continue
400118 self.visit(test, scope)
401118 self.visit(body, scope)
402116 if node.else_:
40326 self.visit(node.else_, scope)
404n/a
405n/a # a yield statement signals a generator
406n/a
4072 def visitYield(self, node, scope):
4082 scope.generator = 1
4092 self.visit(node.value, scope)
410n/a
4112def list_eq(l1, l2):
4120 return sorted(l1) == sorted(l2)
413n/a
4142if __name__ == "__main__":
4150 import sys
4160 from compiler import parseFile, walk
4170 import symtable
418n/a
4190 def get_names(syms):
4200 return [s for s in [s.get_name() for s in syms.get_symbols()]
4210 if not (s.startswith('_[') or s.startswith('.'))]
422n/a
4230 for file in sys.argv[1:]:
4240 print file
4250 f = open(file)
4260 buf = f.read()
4270 f.close()
4280 syms = symtable.symtable(buf, file, "exec")
4290 mod_names = get_names(syms)
4300 tree = parseFile(file)
4310 s = SymbolVisitor()
4320 walk(tree, s)
433n/a
434n/a # compare module-level symbols
4350 names2 = s.scopes[tree].get_names()
436n/a
4370 if not list_eq(mod_names, names2):
4380 print
4390 print "oops", file
4400 print sorted(mod_names)
4410 print sorted(names2)
4420 sys.exit(-1)
443n/a
4440 d = {}
4450 d.update(s.scopes)
4460 del d[tree]
4470 scopes = d.values()
4480 del d
449n/a
4500 for s in syms.get_symbols():
4510 if s.is_namespace():
4520 l = [sc for sc in scopes
4530 if sc.name == s.get_name()]
4540 if len(l) > 1:
4550 print "skipping", s.get_name()
456n/a else:
4570 if not list_eq(get_names(s.get_namespace()),
4580 l[0].get_names()):
4590 print s.get_name()
4600 print sorted(get_names(s.get_namespace()))
4610 print sorted(l[0].get_names())
4620 sys.exit(-1)