diff python/ppci/symboltable.py @ 96:a350055d6119

movage
author windel
date Mon, 24 Dec 2012 13:30:12 +0100
parents python/libs/compiler/symboltable.py@32078200cdd6
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/python/ppci/symboltable.py	Mon Dec 24 13:30:12 2012 +0100
@@ -0,0 +1,80 @@
+from .nodes import *
+from .errors import Error
+
+class SymbolTable:
+  """
+   Symbol table for a current scope.
+   It has functions:
+    - hasname for checking for a name in current scope or above
+    - addSymbol to add an object
+  """
+  def __init__(self, parent=None):
+    self.parent = parent
+    self.syms = {}
+
+  def __repr__(self):
+    return 'Symboltable with {0} symbols\n'.format(len(self.syms))
+
+  def printTable(self, indent=0):
+    for name in self.syms:
+      print(self.syms[name])
+
+  def getAllLocal(self, cls):
+     """ Get all local objects of a specific type """
+     r = []
+     for key in self.syms.keys():
+        sym = self.syms[key]
+        if issubclass(type(sym), cls):
+           r.append(sym)
+     return r
+
+  def getLocal(self, cls, name):
+      if name in self.syms.keys():
+         sym = self.syms[name]
+         if isinstance(sym, cls):
+            return sym
+         else:
+            Error('Wrong type found')
+      else:
+         Error('Symbol not found')
+
+  # Retrieving of specific classes of items:
+  def get(self, cls, name):
+    if self.hasSymbol(name):
+      sym = self.getSymbol(name)
+      if issubclass(type(sym), cls):
+        return sym
+    raise SymbolException('type {0} undefined'.format(typename))
+
+  def has(self, cls, name):
+    if self.hasSymbol(name):
+      sym = self.getSymbol(name)
+      if issubclass(type(sym), cls):
+        return True
+    return False
+
+  # Adding and retrieving of symbols in general:
+  def addSymbol(self, sym):
+    if sym.name in self.syms.keys():
+      raise Exception('Symbol "{0}" redefined'.format(sym.name))
+    else:
+      self.syms[sym.name] = sym
+
+  def getSymbol(self, name):
+     if name in self.syms.keys():
+      return self.syms[name]
+     else:
+      if self.parent:
+        return self.parent.getSymbol(name)
+      else:
+         Error('Symbol "{0}" undeclared!'.format(name))
+
+  def hasSymbol(self, name):
+    if name in self.syms.keys():
+      return True
+    else:
+      if self.parent:
+        return self.parent.hasSymbol(name)
+      else:
+        return False
+