blob: 135cd569b6ff980c181e435c393d0d97fcf4d485 [file] [log] [blame]
Jeremy Hylton816e1492001-03-22 23:32:22 +00001"""Interface to the compiler's internal symbol tables"""
2from __future__ import nested_scopes
3
4import _symtable
5from _symtable import USE, DEF_GLOBAL, DEF_LOCAL, DEF_PARAM, \
6 DEF_STAR, DEF_DOUBLESTAR, DEF_INTUPLE, DEF_FREE, \
7 DEF_FREE_GLOBAL, DEF_FREE_CLASS, DEF_IMPORT, DEF_BOUND
8
9import weakref
10
Jeremy Hylton101651c2001-03-23 15:41:14 +000011__all__ = ["symtable", "SymbolTable", "newSymbolTable", "Class",
12 "Function", "Symbol"]
Jeremy Hylton816e1492001-03-22 23:32:22 +000013
14def symtable(code, filename, compile_type):
15 raw = _symtable.symtable(code, filename, compile_type)
16 return newSymbolTable(raw[0], filename)
17
18class SymbolTableFactory:
19 def __init__(self):
20 self.__memo = weakref.WeakValueDictionary()
21
22 def new(self, table, filename):
23 if table.type == _symtable.TYPE_FUNCTION:
24 return Function(table, filename)
25 if table.type == _symtable.TYPE_CLASS:
26 return Class(table, filename)
27 return SymbolTable(table, filename)
28
29 def __call__(self, table, filename):
30 key = table, filename
31 obj = self.__memo.get(key, None)
32 if obj is None:
33 obj = self.__memo[key] = self.new(table, filename)
34 return obj
35
36newSymbolTable = SymbolTableFactory()
Tim Petersa19a1682001-03-29 04:36:09 +000037
Jeremy Hylton816e1492001-03-22 23:32:22 +000038def bool(x):
39 """Helper to force boolean result to 1 or 0"""
40 if x:
41 return 1
42 return 0
43
44def is_free(flags):
45 if (flags & (USE | DEF_FREE)) \
46 and (flags & (DEF_LOCAL | DEF_PARAM | DEF_GLOBAL)):
47 return 1
48 if flags & DEF_FREE_CLASS:
49 return 1
50 return 0
51
52class SymbolTable:
53 def __init__(self, raw_table, filename):
54 self._table = raw_table
55 self._filename = filename
56 self._symbols = {}
57
58 def __repr__(self):
59 if self.__class__ == SymbolTable:
60 kind = ""
61 else:
62 kind = "%s " % self.__class__.__name__
Tim Petersa19a1682001-03-29 04:36:09 +000063
Jeremy Hylton816e1492001-03-22 23:32:22 +000064 if self._table.name == "global":
65 return "<%sSymbolTable for module %s>" % (kind, self._filename)
66 else:
67 return "<%sSymbolTable for %s in %s>" % (kind, self._table.name,
68 self._filename)
69
70 def get_type(self):
71 if self._table.type == _symtable.TYPE_MODULE:
72 return "module"
73 if self._table.type == _symtable.TYPE_FUNCTION:
74 return "function"
75 if self._table.type == _symtable.TYPE_CLASS:
76 return "class"
77 assert self._table.type in (1, 2, 3), \
78 "unexpected type: %s" % self._table.type
79
80 def get_id(self):
81 return self._table.id
82
83 def get_name(self):
84 return self._table.name
85
86 def get_lineno(self):
87 return self._table.lineno
88
89 def is_optimized(self):
90 return bool(self._table.type == _symtable.TYPE_FUNCTION
91 and not self._table.optimized)
92
93 def is_nested(self):
94 return bool(self._table.nested)
95
96 def has_children(self):
97 return bool(self._table.children)
98
99 def has_exec(self):
100 return bool()
101
102 def get_identifiers(self):
103 return self._table.symbols.keys()
104
105 def lookup(self, name):
106 sym = self._symbols.get(name)
107 if sym is None:
108 flags = self._table.symbols[name]
109 namespaces = self.__check_children(name)
110 sym = self._symbols[name] = Symbol(name, flags, namespaces)
111 return sym
112
113 def get_symbols(self):
114 return [self.lookup(ident) for ident in self.get_identifiers()]
115
116 def __check_children(self, name):
117 return [newSymbolTable(st, self._filename)
118 for st in self._table.children
119 if st.name == name]
120
Jeremy Hylton101651c2001-03-23 15:41:14 +0000121 def get_children(self):
122 return [newSymbolTable(st, self._filename)
123 for st in self._table.children]
124
Jeremy Hylton816e1492001-03-22 23:32:22 +0000125class Function(SymbolTable):
126
127 # Default values for instance variables
128 __params = None
129 __locals = None
130 __frees = None
131 __globals = None
132
133 def __idents_matching(self, test_func):
134 return tuple([ident for ident in self.get_identifiers()
135 if test_func(self._table.symbols[ident])])
136
137 def get_parameters(self):
138 if self.__params is None:
139 self.__params = self.__idents_matching(lambda x:x & DEF_PARAM)
140 return self.__params
141
142 def get_locals(self):
143 if self.__locals is None:
144 self.__locals = self.__idents_matching(lambda x:x & DEF_BOUND)
145 return self.__locals
Tim Petersa19a1682001-03-29 04:36:09 +0000146
Jeremy Hylton816e1492001-03-22 23:32:22 +0000147 def get_globals(self):
148 if self.__globals is None:
149 glob = DEF_GLOBAL | DEF_FREE_GLOBAL
150 self.__globals = self.__idents_matching(lambda x:x & glob)
151 return self.__globals
152
153 def get_frees(self):
154 if self.__frees is None:
155 self.__frees = self.__idents_matching(is_free)
156 return self.__frees
157
158class Class(SymbolTable):
159
160 __methods = None
161
162 def get_methods(self):
163 if self.__methods is None:
164 d = {}
165 for st in self._table.children:
166 d[st.name] = 1
167 self.__methods = tuple(d.keys())
168 return self.__methods
169
170class Symbol:
171 def __init__(self, name, flags, namespaces=None):
172 self.__name = name
173 self.__flags = flags
174 self.__namespaces = namespaces or ()
175
176 def __repr__(self):
177 return "<symbol '%s'>" % self.__name
178
179 def get_name(self):
180 return self.__name
181
182 def is_referenced(self):
183 return bool(self.__flags & _symtable.USE)
184
185 def is_parameter(self):
186 return bool(self.__flags & DEF_PARAM)
187
188 def is_global(self):
Tim Petersa19a1682001-03-29 04:36:09 +0000189 return bool((self.__flags & DEF_GLOBAL)
Jeremy Hylton816e1492001-03-22 23:32:22 +0000190 or (self.__flags & DEF_FREE_GLOBAL))
191
192 def is_vararg(self):
193 return bool(self.flag & DEF_STAR)
194
195 def is_keywordarg(self):
196 return bool(self.__flags & DEF_STARSTAR)
197
198 def is_local(self):
199 return bool(self.__flags & DEF_BOUND)
200
201 def is_free(self):
202 if (self.__flags & (USE | DEF_FREE)) \
203 and (self.__flags & (DEF_LOCAL | DEF_PARAM | DEF_GLOBAL)):
204 return 1
205 if self.__flags & DEF_FREE_CLASS:
206 return 1
207 return 0
208
209 def is_imported(self):
210 return bool(self.__flags & DEF_IMPORT)
211
212 def is_assigned(self):
213 return bool(self.__flags & DEF_LOCAL)
214
215 def is_in_tuple(self):
216 return bool(self.__flags & DEF_INTUPLE)
217
218 def is_namespace(self):
219 """Returns true if name binding introduces new namespace.
220
221 If the name is used as the target of a function or class
222 statement, this will be true.
223
224 Note that a single name can be bound to multiple objects. If
225 is_namespace() is true, the name may also be bound to other
226 objects, like an int or list, that does not introduce a new
227 namespace.
228 """
229 return bool(self.__namespaces)
230
231 def get_namespaces(self):
232 """Return a list of namespaces bound to this name"""
233 return self.__namespaces
234
235 def get_namespace(self):
236 """Returns the single namespace bound to this name.
237
238 Raises ValueError if the name is bound to multiple namespaces.
239 """
240 if len(self.__namespaces) != 1:
241 raise ValueError, "name is bound to multiple namespaces"
242 return self.__namespaces[0]
243
Jeremy Hylton816e1492001-03-22 23:32:22 +0000244if __name__ == "__main__":
245 import os, sys
246 src = open(sys.argv[0]).read()
247 mod = symtable(src, os.path.split(sys.argv[0])[1], "exec")
248 for ident in mod.get_identifiers():
249 info = mod.lookup(ident)
250 print info, info.is_local(), info.is_namespace()