symtable.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. """Interface to the compiler's internal symbol tables"""
  2. import _symtable
  3. from _symtable import (USE, DEF_GLOBAL, DEF_LOCAL, DEF_PARAM,
  4. DEF_IMPORT, DEF_BOUND, OPT_IMPORT_STAR, OPT_EXEC, OPT_BARE_EXEC,
  5. SCOPE_OFF, SCOPE_MASK, FREE, GLOBAL_IMPLICIT, GLOBAL_EXPLICIT, CELL, LOCAL)
  6. import weakref
  7. __all__ = ["symtable", "SymbolTable", "Class", "Function", "Symbol"]
  8. def symtable(code, filename, compile_type):
  9. top = _symtable.symtable(code, filename, compile_type)
  10. return _newSymbolTable(top, filename)
  11. class SymbolTableFactory:
  12. def __init__(self):
  13. self.__memo = weakref.WeakValueDictionary()
  14. def new(self, table, filename):
  15. if table.type == _symtable.TYPE_FUNCTION:
  16. return Function(table, filename)
  17. if table.type == _symtable.TYPE_CLASS:
  18. return Class(table, filename)
  19. return SymbolTable(table, filename)
  20. def __call__(self, table, filename):
  21. key = table, filename
  22. obj = self.__memo.get(key, None)
  23. if obj is None:
  24. obj = self.__memo[key] = self.new(table, filename)
  25. return obj
  26. _newSymbolTable = SymbolTableFactory()
  27. class SymbolTable(object):
  28. def __init__(self, raw_table, filename):
  29. self._table = raw_table
  30. self._filename = filename
  31. self._symbols = {}
  32. def __repr__(self):
  33. if self.__class__ == SymbolTable:
  34. kind = ""
  35. else:
  36. kind = "%s " % self.__class__.__name__
  37. if self._table.name == "global":
  38. return "<{0}SymbolTable for module {1}>".format(kind, self._filename)
  39. else:
  40. return "<{0}SymbolTable for {1} in {2}>".format(kind,
  41. self._table.name,
  42. self._filename)
  43. def get_type(self):
  44. if self._table.type == _symtable.TYPE_MODULE:
  45. return "module"
  46. if self._table.type == _symtable.TYPE_FUNCTION:
  47. return "function"
  48. if self._table.type == _symtable.TYPE_CLASS:
  49. return "class"
  50. assert self._table.type in (1, 2, 3), \
  51. "unexpected type: {0}".format(self._table.type)
  52. def get_id(self):
  53. return self._table.id
  54. def get_name(self):
  55. return self._table.name
  56. def get_lineno(self):
  57. return self._table.lineno
  58. def is_optimized(self):
  59. return bool(self._table.type == _symtable.TYPE_FUNCTION
  60. and not self._table.optimized)
  61. def is_nested(self):
  62. return bool(self._table.nested)
  63. def has_children(self):
  64. return bool(self._table.children)
  65. def has_exec(self):
  66. """Return true if the scope uses exec"""
  67. return bool(self._table.optimized & (OPT_EXEC | OPT_BARE_EXEC))
  68. def has_import_star(self):
  69. """Return true if the scope uses import *"""
  70. return bool(self._table.optimized & OPT_IMPORT_STAR)
  71. def get_identifiers(self):
  72. return self._table.symbols.keys()
  73. def lookup(self, name):
  74. sym = self._symbols.get(name)
  75. if sym is None:
  76. flags = self._table.symbols[name]
  77. namespaces = self.__check_children(name)
  78. sym = self._symbols[name] = Symbol(name, flags, namespaces)
  79. return sym
  80. def get_symbols(self):
  81. return [self.lookup(ident) for ident in self.get_identifiers()]
  82. def __check_children(self, name):
  83. return [_newSymbolTable(st, self._filename)
  84. for st in self._table.children
  85. if st.name == name]
  86. def get_children(self):
  87. return [_newSymbolTable(st, self._filename)
  88. for st in self._table.children]
  89. class Function(SymbolTable):
  90. # Default values for instance variables
  91. __params = None
  92. __locals = None
  93. __frees = None
  94. __globals = None
  95. def __idents_matching(self, test_func):
  96. return tuple([ident for ident in self.get_identifiers()
  97. if test_func(self._table.symbols[ident])])
  98. def get_parameters(self):
  99. if self.__params is None:
  100. self.__params = self.__idents_matching(lambda x:x & DEF_PARAM)
  101. return self.__params
  102. def get_locals(self):
  103. if self.__locals is None:
  104. locs = (LOCAL, CELL)
  105. test = lambda x: ((x >> SCOPE_OFF) & SCOPE_MASK) in locs
  106. self.__locals = self.__idents_matching(test)
  107. return self.__locals
  108. def get_globals(self):
  109. if self.__globals is None:
  110. glob = (GLOBAL_IMPLICIT, GLOBAL_EXPLICIT)
  111. test = lambda x:((x >> SCOPE_OFF) & SCOPE_MASK) in glob
  112. self.__globals = self.__idents_matching(test)
  113. return self.__globals
  114. def get_frees(self):
  115. if self.__frees is None:
  116. is_free = lambda x:((x >> SCOPE_OFF) & SCOPE_MASK) == FREE
  117. self.__frees = self.__idents_matching(is_free)
  118. return self.__frees
  119. class Class(SymbolTable):
  120. __methods = None
  121. def get_methods(self):
  122. if self.__methods is None:
  123. d = {}
  124. for st in self._table.children:
  125. d[st.name] = 1
  126. self.__methods = tuple(d)
  127. return self.__methods
  128. class Symbol(object):
  129. def __init__(self, name, flags, namespaces=None):
  130. self.__name = name
  131. self.__flags = flags
  132. self.__scope = (flags >> SCOPE_OFF) & SCOPE_MASK # like PyST_GetScope()
  133. self.__namespaces = namespaces or ()
  134. def __repr__(self):
  135. return "<symbol {0!r}>".format(self.__name)
  136. def get_name(self):
  137. return self.__name
  138. def is_referenced(self):
  139. return bool(self.__flags & _symtable.USE)
  140. def is_parameter(self):
  141. return bool(self.__flags & DEF_PARAM)
  142. def is_global(self):
  143. return bool(self.__scope in (GLOBAL_IMPLICIT, GLOBAL_EXPLICIT))
  144. def is_declared_global(self):
  145. return bool(self.__scope == GLOBAL_EXPLICIT)
  146. def is_local(self):
  147. return bool(self.__flags & DEF_BOUND)
  148. def is_free(self):
  149. return bool(self.__scope == FREE)
  150. def is_imported(self):
  151. return bool(self.__flags & DEF_IMPORT)
  152. def is_assigned(self):
  153. return bool(self.__flags & DEF_LOCAL)
  154. def is_namespace(self):
  155. """Returns true if name binding introduces new namespace.
  156. If the name is used as the target of a function or class
  157. statement, this will be true.
  158. Note that a single name can be bound to multiple objects. If
  159. is_namespace() is true, the name may also be bound to other
  160. objects, like an int or list, that does not introduce a new
  161. namespace.
  162. """
  163. return bool(self.__namespaces)
  164. def get_namespaces(self):
  165. """Return a list of namespaces bound to this name"""
  166. return self.__namespaces
  167. def get_namespace(self):
  168. """Returns the single namespace bound to this name.
  169. Raises ValueError if the name is bound to multiple namespaces.
  170. """
  171. if len(self.__namespaces) != 1:
  172. raise ValueError, "name is bound to multiple namespaces"
  173. return self.__namespaces[0]
  174. if __name__ == "__main__":
  175. import os, sys
  176. src = open(sys.argv[0]).read()
  177. mod = symtable(src, os.path.split(sys.argv[0])[1], "exec")
  178. for ident in mod.get_identifiers():
  179. info = mod.lookup(ident)
  180. print info, info.is_local(), info.is_namespace()