Source

BrainMachine / OpcodeDef.py

#!/usr/bin/env python

import VarDefine

class BaseOpcode():
    def Output(self):
        raise 'not implement'
    def Run(self, ns):
        # can return None, or tuple(flag,value)
        # flag can not be 0
        # flag == 1 means meet opcode 'return'
        raise 'not implement'

class Opcode_AopB(BaseOpcode):
    def __init__(self, vleft, vright, verb):
        self.type = 'aopb'
        self.vleft = vleft
        self.vright = vright
        self.verb = verb
    def Output(self):
        yield str(self.vleft) + ' ' + self.verb + ' ' + str(self.vright)
    def Run(self, rs):
        value = self.vright.GetValue(rs)
        if self.verb == '=':
            rs.SetVarValue(self.vleft, value)
            return None
        assert False
    def __str__(self):
        return str(self.vleft) + ' ' + self.verb + ' ' + str(self.vright)


class Opcode_If(BaseOpcode):
    def __init__(self, v, ns):
        self.type = 'if'
        self.condition = v
        self.body = ns
    def Output(self):
        yield 'if ' + str(self.condition) + ':'
        for s in self.body.Output():
            yield '    ' + s
    def Run(self, rs):
        value = self.condition.GetValue(rs)
        if value.IfTrue():
            return self.body.Run(rs)
        pass

class Opcode_Return(BaseOpcode):
    def __init__(self, v):
        self.type = 'return'
        self.v = v
    def Output(self):
        yield 'return ' + str(self.v)
    def Run(self, rs):
        value = self.v.GetValue(rs)
        return 1, value

class Opcode_Print(BaseOpcode):
    def __init__(self, v):
        self.type = 'print'
        self.v = v
    def Output(self):
        yield 'print ' + str(self.v)
    def Run(self, rs):
        def PrintArgToString(v):
            if v.__class__ is VarDefine.CombineToken:
                values = v.GetValueInList(rs)
                s = ''
                for m in values:
                    if s:
                        s = s + ' ';
                    s = s + m.ToString()
                return s
            value = v.GetValue(rs)
            return value.ToString()
        s = PrintArgToString(self.v)
        print s

class Opcode_ClassDef(BaseOpcode):
    def __init__(self, classdef):
        self.type = 'classdef'
        self.classdef = classdef
    def Output(self):
        for s in self.classdef.Output():
            yield s
    def Run(self, rs):
        rs.classes.append(self.classdef)

class Opcode_FuncDef(BaseOpcode):
    def __init__(self, funcdef):
        self.type = 'funcdef'
        self.funcdef = funcdef
    def Output(self):
        for s in self.funcdef.Output():
            yield s
    def Run(self, rs):
        rs.funcs.append(self.funcdef)