diff python/ppci/c3/scope.py @ 300:158068af716c

yafm
author Windel Bouwman
date Tue, 03 Dec 2013 18:00:22 +0100
parents python/c3/scope.py@a747a45dcd78
children b145f8e6050b
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/python/ppci/c3/scope.py	Tue Dec 03 18:00:22 2013 +0100
@@ -0,0 +1,70 @@
+from . import astnodes
+
+
+class Scope:
+    """ A scope contains all symbols in a scope """
+    def __init__(self, parent=None):
+        self.symbols = {}
+        self.parent = parent
+
+    def __iter__(self):
+        # Iterate in a deterministic manner:
+        return iter(self.Constants + self.Variables + self.Functions)
+
+    @property
+    def Syms(self):
+        syms = self.symbols.values()
+        return sorted(syms, key=lambda v: v.name)
+
+    @property
+    def Constants(self):
+        return [s for s in self.Syms if type(s) is astnodes.Constant]
+
+    @property
+    def Variables(self):
+        return [s for s in self.Syms if isinstance(s, astnodes.Variable)]
+
+    @property
+    def Functions(self):
+        return [s for s in self.Syms if type(s) is astnodes.Function]
+
+    def getSymbol(self, name):
+        if name in self.symbols:
+            return self.symbols[name]
+        # Look for symbol:
+        if self.parent:
+            return self.parent.getSymbol(name)
+        raise CompilerException("Symbol {0} not found".format(name), name.loc)
+
+    def hasSymbol(self, name):
+        if name in self.symbols:
+            return True
+        if self.parent:
+            return self.parent.hasSymbol(name)
+        return False
+
+    def addSymbol(self, sym):
+        self.symbols[sym.name] = sym
+
+    def __repr__(self):
+        return 'Scope with {} symbols'.format(len(self.symbols))
+
+
+def createBuiltins(scope):
+    for tn in ['u64', 'u32', 'u16', 'u8']:
+        scope.addSymbol(astnodes.BaseType(tn))
+    for t in [intType, doubleType, voidType, boolType, stringType, byteType]:
+        scope.addSymbol(t)
+
+# buildin types:
+intType = astnodes.BaseType('int')
+intType.bytesize = 4
+doubleType = astnodes.BaseType('double')
+voidType = astnodes.BaseType('void')
+boolType = astnodes.BaseType('bool')
+stringType = astnodes.BaseType('string')
+byteType = astnodes.BaseType('byte')
+
+# Create top level scope:
+topScope = Scope()
+createBuiltins(topScope)