view python/c3/semantics.py @ 207:8b2f20aae086

cleaning of files
author Windel Bouwman
date Sat, 29 Jun 2013 10:05:42 +0200
parents b01429a5d695
children 003c8a976fff
line wrap: on
line source

from . import astnodes
from .scope import Scope, topScope
from ppci import CompilerError

class Semantics:
   """ This class constructs the AST from parser input """
   def __init__(self, diag):
      self.diag = diag
   def reinit(self):
      # Set mod to empty package:
      self.mod = astnodes.Package('unnamed')
      self.mod.scope = Scope(topScope)
   def addSymbol(self, s):
      if self.curScope.hasSymbol(s.name):
         msg = 'Redefinition of {0}'.format(s.name)
         raise CompilerError(msg, s.loc)
      else:
         self.curScope.addSymbol(s)
   def handlePackage(self, name, loc):
      self.mod = astnodes.Package(name)
      self.mod.loc = loc
      self.mod.scope = self.curScope = Scope(topScope)
   def actOnVarDef(self, name, loc, t, ival):
      s = astnodes.Variable(name, t)
      s.loc = loc
      self.addSymbol(s)
   def actOnConstDef(self, name, loc, t, val):
      s = astnodes.Constant(name, t, val)
      s.loc = loc
      self.addSymbol(s)
   def actOnFuncDef1(self, name, loc):
      self.curFunc = astnodes.Function(name)
      self.curFunc.loc = loc
      self.addSymbol(self.curFunc)
      self.curScope = self.curFunc.scope = Scope(self.curScope)
   def actOnParameter(self, name, loc, t):
      p = astnodes.Variable(name, t)
      p.isParameter = True
      p.loc = loc
      self.addSymbol(p)
      return p
   def actOnFuncDef2(self, parameters, returntype, body):
      self.curFunc.body = body
      paramtypes = [p.typ for p in parameters]
      self.curFunc.typ = astnodes.FunctionType(paramtypes, returntype)
      self.curFunc = None
      self.curScope = self.curScope.parent
   def actOnType(self, tok):
      # Try to lookup type, in case of failure return void
      pass
   def actOnDesignator(self, tname, loc):
      d = astnodes.Designator(tname)
      d.scope = self.curScope
      d.loc = loc
      return d
   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.Literal(num)
      n.loc = loc
      return n
   def actOnVariableUse(self, d, loc):
      vu = astnodes.VariableUse(d)
      vu.loc = loc
      return vu
   def actOnAssignment(self, lval, rval, loc):
      a = astnodes.Assignment(lval, rval)
      a.loc = loc
      return a
   def actOnFunctionCall(self, func, args, loc):
      fc = astnodes.FunctionCall(func, args)
      fc.loc = loc
      return fc
   def actOnIfStatement(self, cond, yes, no, loc):
      i = astnodes.IfStatement(cond, yes, no)
      i.loc = loc
      return i