BrainMachine /

#!/usr/bin/env python

import string
import NameSpace
import RunState

class Value():
    def __init__(self, typestr, val):
        self.typestr = typestr #can be bool, string, number, classinstance
        self.val = val
    def ToString(self):
        if self.typestr == 'number':
            return self.val
        assert False
    def IsSameValue(self, v):
        if self.typestr == v.typestr:
            if self.val == v.val:
                return True
        return False
    def IfTrue(self):
        if self.typestr == 'bool':
            return self.val
        assert False

def IsPythonNumber(s):
    # support more number format later
    import re
    k = re.match(r'\A\d+\Z', s)
    if k:
        return True
    return False

class BaseToken():
    def GetValue(self, rs):
        raise 'not implement'

class NameToken(BaseToken):
    def __init__(self, name): = name
    def __str__(self):
    def GetValue(self, rs):
        if IsPythonNumber(
            return Value("number",
        return rs._GetAttr(

class CombineToken(BaseToken):
    def __init__(self, vleft, vright, op):
        self.vleft = vleft
        self.vright = vright
        self.op = op
    def __str__(self):
        return str(self.vleft) + self.op + str(self.vright)
    def GetValue(self, rs):
        if self.op == '==':
            v1 = self.vleft.GetValue(rs)
            v2 = self.vright.GetValue(rs)
            b = v1.IsSameValue(v2)
            return Value('bool', b)
        assert False

class StringToken(BaseToken):
    def __init__(self, s):
        self.s = s
    def __str__(self):
        return self.s
    def GetValue(self, rs):
        return Value('string', self.s[1:-1])

class FuncToken(BaseToken):
    # not really function, but somethine like word(..)
    # it may be many meaning in Python
    def __init__(self, func, params):
        self.func = func
        self.params = params
    def __str__(self):
        return str(self.func)+'('+string.join(self.params, ',')+')'
    def GetValue(self, rs):
        if self.func.__class__ is NameToken:
            funcname =
            what = rs.GetNameToken(funcname)
            if what:
                if what.__class__ is NameSpace.ClassNS:
                    # create Class instance
                    return what.CreateClassInstance(self.params, rs)
        assert False