1 """Interface to the compiler's internal symbol tables"""
4 from _symtable
import (USE
, DEF_GLOBAL
, DEF_LOCAL
, DEF_PARAM
,
5 DEF_IMPORT
, DEF_BOUND
, OPT_IMPORT_STAR
, OPT_EXEC
, OPT_BARE_EXEC
,
6 SCOPE_OFF
, SCOPE_MASK
, FREE
, GLOBAL_IMPLICIT
, GLOBAL_EXPLICIT
)
11 __all__
= ["symtable", "SymbolTable", "Class", "Function", "Symbol"]
13 def symtable(code
, filename
, compile_type
):
14 raw
= _symtable
.symtable(code
, filename
, compile_type
)
15 for top
in raw
.itervalues():
18 return _newSymbolTable(top
, filename
)
20 class SymbolTableFactory
:
22 self
.__memo
= weakref
.WeakValueDictionary()
24 def new(self
, table
, filename
):
25 if table
.type == _symtable
.TYPE_FUNCTION
:
26 return Function(table
, filename
)
27 if table
.type == _symtable
.TYPE_CLASS
:
28 return Class(table
, filename
)
29 return SymbolTable(table
, filename
)
31 def __call__(self
, table
, filename
):
33 obj
= self
.__memo
.get(key
, None)
35 obj
= self
.__memo
[key
] = self
.new(table
, filename
)
38 _newSymbolTable
= SymbolTableFactory()
41 class SymbolTable(object):
43 def __init__(self
, raw_table
, filename
):
44 self
._table
= raw_table
45 self
._filename
= filename
49 if self
.__class
__ == SymbolTable
:
52 kind
= "%s " % self
.__class
__.__name
__
54 if self
._table
.name
== "global":
55 return "<{0}SymbolTable for module {1}>".format(kind
, self
._filename
)
57 return "<{0}SymbolTable for {1} in {2}>".format(kind
,
62 if self
._table
.type == _symtable
.TYPE_MODULE
:
64 if self
._table
.type == _symtable
.TYPE_FUNCTION
:
66 if self
._table
.type == _symtable
.TYPE_CLASS
:
68 assert self
._table
.type in (1, 2, 3), \
69 "unexpected type: {0}".format(self
._table
.type)
75 return self
._table
.name
78 return self
._table
.lineno
80 def is_optimized(self
):
81 return bool(self
._table
.type == _symtable
.TYPE_FUNCTION
82 and not self
._table
.optimized
)
85 return bool(self
._table
.nested
)
87 def has_children(self
):
88 return bool(self
._table
.children
)
91 """Return true if the scope uses exec"""
92 return bool(self
._table
.optimized
& (OPT_EXEC | OPT_BARE_EXEC
))
94 def has_import_star(self
):
95 """Return true if the scope uses import *"""
96 return bool(self
._table
.optimized
& OPT_IMPORT_STAR
)
98 def get_identifiers(self
):
99 return self
._table
.symbols
.keys()
101 def lookup(self
, name
):
102 sym
= self
._symbols
.get(name
)
104 flags
= self
._table
.symbols
[name
]
105 namespaces
= self
.__check
_children
(name
)
106 sym
= self
._symbols
[name
] = Symbol(name
, flags
, namespaces
)
109 def get_symbols(self
):
110 return [self
.lookup(ident
) for ident
in self
.get_identifiers()]
112 def __check_children(self
, name
):
113 return [_newSymbolTable(st
, self
._filename
)
114 for st
in self
._table
.children
117 def get_children(self
):
118 return [_newSymbolTable(st
, self
._filename
)
119 for st
in self
._table
.children
]
122 class Function(SymbolTable
):
124 # Default values for instance variables
130 def __idents_matching(self
, test_func
):
131 return tuple([ident
for ident
in self
.get_identifiers()
132 if test_func(self
._table
.symbols
[ident
])])
134 def get_parameters(self
):
135 if self
.__params
is None:
136 self
.__params
= self
.__idents
_matching
(lambda x
:x
& DEF_PARAM
)
139 def get_locals(self
):
140 if self
.__locals
is None:
141 self
.__locals
= self
.__idents
_matching
(lambda x
:x
& DEF_BOUND
)
144 def get_globals(self
):
145 if self
.__globals
is None:
146 glob
= (GLOBAL_IMPLICIT
, GLOBAL_EXPLICIT
)
147 test
= lambda x
:((x
>> SCOPE_OFF
) & SCOPE_MASK
) in glob
148 self
.__globals
= self
.__idents
_matching
(test
)
149 return self
.__globals
152 if self
.__frees
is None:
153 is_free
= lambda x
:((x
>> SCOPE_OFF
) & SCOPE_MASK
) == FREE
154 self
.__frees
= self
.__idents
_matching
(is_free
)
158 class Class(SymbolTable
):
162 def get_methods(self
):
163 if self
.__methods
is None:
165 for st
in self
._table
.children
:
167 self
.__methods
= tuple(d
)
168 return self
.__methods
171 class Symbol(object):
173 def __init__(self
, name
, flags
, namespaces
=None):
176 self
.__scope
= (flags
>> SCOPE_OFF
) & SCOPE_MASK
# like PyST_GetScope()
177 self
.__namespaces
= namespaces
or ()
180 return "<symbol {0!r}>".format(self
.__name
)
185 def is_referenced(self
):
186 return bool(self
.__flags
& _symtable
.USE
)
188 def is_parameter(self
):
189 return bool(self
.__flags
& DEF_PARAM
)
192 return bool(self
.__scope
in (GLOBAL_IMPLICIT
, GLOBAL_EXPLICIT
))
195 warnings
.warn("is_vararg() is obsolete and will be removed",
196 DeprecationWarning, 2)
199 def is_keywordarg(self
):
200 warnings
.warn("is_keywordarg() is obsolete and will be removed",
201 DeprecationWarning, 2)
205 return bool(self
.__flags
& DEF_BOUND
)
208 return bool(self
.__scope
== FREE
)
210 def is_imported(self
):
211 return bool(self
.__flags
& DEF_IMPORT
)
213 def is_assigned(self
):
214 return bool(self
.__flags
& DEF_LOCAL
)
216 def is_in_tuple(self
):
217 warnings
.warn("is_in_tuple() is obsolete and will be removed",
218 DeprecationWarning, 2)
220 def is_namespace(self
):
221 """Returns true if name binding introduces new namespace.
223 If the name is used as the target of a function or class
224 statement, this will be true.
226 Note that a single name can be bound to multiple objects. If
227 is_namespace() is true, the name may also be bound to other
228 objects, like an int or list, that does not introduce a new
231 return bool(self
.__namespaces
)
233 def get_namespaces(self
):
234 """Return a list of namespaces bound to this name"""
235 return self
.__namespaces
237 def get_namespace(self
):
238 """Returns the single namespace bound to this name.
240 Raises ValueError if the name is bound to multiple namespaces.
242 if len(self
.__namespaces
) != 1:
243 raise ValueError, "name is bound to multiple namespaces"
244 return self
.__namespaces
[0]
246 if __name__
== "__main__":
248 src
= open(sys
.argv
[0]).read()
249 mod
= symtable(src
, os
.path
.split(sys
.argv
[0])[1], "exec")
250 for ident
in mod
.get_identifiers():
251 info
= mod
.lookup(ident
)
252 print info
, info
.is_local(), info
.is_namespace()