Source

BrainMachine / NameSpace.py

Full commit
#!/usr/bin/env python

import string
import OpcodeDef
import RunState
import VarDefine
import NameSpace

class BaseNameSpace():
    def __init__(self):
        self.tem_s = ''
        self.sIden = ''
        self.oplist = []
        self.vars = []

    def tem_char_in(self, c):
        self.tem_s += c

    def Output(self):
        for op in self.oplist:
            for s in op.Output():
                yield s

    def Run(self, rs):
        result = None
        for op in self.oplist:
            result = op.Run(rs)
            if op is OpcodeDef.Opcode_Return:
                break
        return result
    def RegisterVar(self, v):
        self.vars.append(v)

class ClassNS(BaseNameSpace):
    def __init__(self, name):
        BaseNameSpace.__init__(self)
        self.name = name
    def Output(self):
        yield 'class ' + self.name + '():'
        for op in self.oplist:
            for s in op.Output():
                yield '    ' + s
    def CreateClassInstance(self, params, rs):
        classInstance = RunState.ClassInstance(self, rs)
        value = VarDefine.Value("classinstance", classInstance)
        self.Run(classInstance)
        initfunc = [k for k in classInstance.funcs if k.name == '__init__']
        if initfunc:
            assert len(initfunc) == 1
            thefunc = initfunc[0]
            assert thefunc.__class__ is NameSpace.FuncNS
            assert len(thefunc.params) > 0 # the first should be 'self'
            assert len(thefunc.params) == len(params) +1 # +1 is self, not support default param
            funcInstance = RunState.FuncInstance(thefunc, thefunc.params, classInstance)
            wordself = thefunc.params[0]
            funcInstance.DeclareParameter(wordself, value)
            for i in range(len(params)):
                wd = params[i]
                v = rs.GetVarRunState(wd)
                funcInstance.DeclareParameter(thefunc.params[i+1], v)
            thefunc.Run(funcInstance)
        else:
            assert not params #no param, it must be no __init__
        return value

class FuncNS(BaseNameSpace):
    def __init__(self, name, params):
        BaseNameSpace.__init__(self)
        self.name = name
        self.params = params
    def Output(self):
        s = string.join(self.params, ',')
        yield 'def ' + self.name + '(%s):' % s
        for op in self.oplist:
            for s in op.Output():
                yield '    ' + s

class BranchNS(BaseNameSpace):
    def __init__(self, name):
        BaseNameSpace.__init__(self)
        self.name = name