view python/c3/semantics.py @ 149:74241ca312cc

Fixes on parser and semantics
author Windel Bouwman
date Fri, 01 Mar 2013 11:43:52 +0100
parents e5263f74b287
children 4ae0e02599de
line wrap: on
line source

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):
      return iter(self.symbols.values())
   def getType(self, name):
      t = self.getSymbol(name)
      print(t)
      assert isinstance(t, astnodes.Type)
      return t
   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 createBuiltins(scope):
   scope.addSymbol(astnodes.BaseType('int'))

class Semantics:
   """ This class constructs the AST from parser input """
   def __init__(self, diag):
      self.diag = diag
   def handlePackage(self, name, loc):
      self.mod = astnodes.Package(name)
      self.mod.loc = loc
      self.mod.scope = self.curScope = Scope()
      createBuiltins(self.curScope)
   def actOnBinop(self, lhs, op, rhs, loc):
      bo = astnodes.Binop(lhs, op, rhs)
      bo.loc = loc
      return bo
   def actOnNumber(self, num, loc):
      n = astnodes.Constant(num)
      n.loc = loc
      return n
   def actOnVarDef(self, name, loc, t, ival):
      s = astnodes.Variable(name, t)
      s.loc = loc
      self.curScope.addSymbol(s)
   def actOnFuncDef1(self, name, loc):
      self.curFunc = astnodes.Procedure(name)
      self.curFunc.loc = loc
      self.curScope.addSymbol(self.curFunc)
      self.curScope = self.curFunc.scope = Scope(self.curScope)
   def actOnFuncDef2(self, parameters, returntype, body):
      self.curFunc.body = body
      self.curFunc.typ = astnodes.FunctionType(parameters, returntype)
      self.curFunc = None
      self.curScope = self.curScope.parent
   def actOnType(self, tok):
      # Try to lookup type, in case of failure return void
      pass