Chinaunix首页 | 论坛 | 博客
  • 博客访问: 395532
  • 博文数量: 53
  • 博客积分: 1910
  • 博客等级: 中尉
  • 技术积分: 1130
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-10 14:56
文章分类

全部博文(53)

文章存档

2013年(1)

2012年(17)

2011年(33)

2010年(2)

分类: Python/Ruby

2011-05-11 18:41:52

promote 样例代码的python code:
VariableSymbol.py
  1. from Symbol import Symbol
  2. class VariableSymbol( Symbol ):
  3.     def __init__( self,name, type) :
  4.         super(VariableSymbol,self).__init__(name, type)

 

Type.py

 

  1. from Scope import abstract

  2. class Type(object) :
  3.     
  4.     #def __init__(self):
  5.     #    if self.__class__ is Scope:
  6.     # abstract()
  7.                 
  8.     #public String getName();
  9.     def getName(self):
  10.         abstract()
  11.     
  12.     #public int getTypeIndex();
  13.     def getTypeIndex(self):
  14.         abstract()

SymbolTable.py

 

  1. from CymbolListener import CymbolListener

  2. from BuiltInTypeSymbol import BuiltInTypeSymbol

  3. from GlobalScope import GlobalScope

  4. class SymbolTable(object):
  5.     # arithmetic types defined in order from narrowest to widest
  6.     #public static final int tUSER = 0; // user-defined type (struct)
  7.     tUSER = 0
  8.     #public static final int tBOOLEAN = 1;
  9.     tBOOLEAN = 1
  10.     tCHAR = 2
  11.     tINT = 3
  12.     tFLOAT = 4
  13.     tVOID = 5

  14.     #public static final BuiltInTypeSymbol _boolean =
  15.     # new BuiltInTypeSymbol("boolean", tBOOLEAN);
  16.     print 'liu: now init buildin type'
  17.     _boolean = BuiltInTypeSymbol("boolean", tBOOLEAN)
  18.     _char = BuiltInTypeSymbol("char", tCHAR)
  19.     _int = BuiltInTypeSymbol("int", tINT)
  20.     _float = BuiltInTypeSymbol("float", tFLOAT)
  21.     _void = BuiltInTypeSymbol("void", tVOID)

  22.     #public CymbolListener listener =
  23.     # new CymbolListener() {
  24.     # public void info(String msg) { System.out.println(msg); }
  25.     # public void error(String msg) { System.err.println(msg); }
  26.     # };
  27.     
  28.     #listener = CymbolListener() # liunote move to __init__

  29.     #/** arithmetic types defined in order from narrowest to widest */
  30.     #public static final Type[] indexToType = {
  31.     # // 0, 1, 2, 3, 4, 5
  32.     indexToType = [ None, _boolean, _char, _int, _float, _void ]
  33.     

  34.     #/** Map t1 op t2 to result type (_void implies illegal) */
  35.     #public static final Type[][] arithmeticResultType = new Type[][] {
  36.     # /* struct boolean char int float, void */
  37.     # /*struct*/ {_void, _void, _void, _void, _void, _void},
  38.     # /*boolean*/ {_void, _void, _void, _void, _void, _void},
  39.     # /*char*/ {_void, _void, _char, _int, _float, _void},
  40.     # /*int*/ {_void, _void, _int, _int, _float, _void},
  41.     # /*float*/ {_void, _void, _float, _float, _float, _void},
  42.     # /*void*/ {_void, _void, _void, _void, _void, _void}
  43.     #};
  44.     
  45.     # liunote math calc type change !!!
  46.     arithmeticResultType = [
  47.               [_void, _void, _void, _void, _void, _void ],
  48.               [_void, _void, _void, _void, _void, _void ],
  49.               [_void, _void, _char, _int, _float, _void ],
  50.               [_void, _void, _int, _int, _float, _void ],
  51.               [_void, _void, _float, _float, _float, _void ],
  52.               [_void, _void, _void, _void, _void, _void ]
  53.                            ]


  54.     #public static final Type[][] relationalResultType = new Type[][] {
  55.     # /* struct boolean char int float, void */
  56.     # /*struct*/ {_void, _void, _void, _void, _void, _void},
  57.     # /*boolean*/ {_void, _void, _void, _void, _void, _void},
  58.     # /*char*/ {_void, _void, _boolean, _boolean, _boolean, _void},
  59.     # /*int*/ {_void, _void, _boolean, _boolean, _boolean, _void},
  60.     # /*float*/ {_void, _void, _boolean, _boolean, _boolean, _void},
  61.     # /*void*/ {_void, _void, _void, _void, _void, _void}
  62.     #};
  63.     
  64.     # liunote relation calc type change !!!
  65.     relationalResultType = [
  66.          [ _void, _void, _void, _void, _void, _void ],
  67.          [ _void, _void, _void, _void, _void, _void ],
  68.          [ _void, _void, _boolean, _boolean, _boolean, _void ],
  69.          [ _void, _void, _boolean, _boolean, _boolean, _void ],
  70.          [ _void, _void, _boolean, _boolean, _boolean, _void ],
  71.          [ _void, _void, _void, _void, _void, _void ]
  72.                            ]

  73.     #public static final Type[][] equalityResultType = new Type[][] {
  74.     # /* struct boolean char int float, void */
  75.     # /*struct*/ {_void, _void, _void, _void, _void, _void},
  76.     # /*boolean*/ {_void, _boolean, _void, _void, _void, _void},
  77.     # /*char*/ {_void, _void, _boolean, _boolean, _boolean, _void},
  78.     # /*int*/ {_void, _void, _boolean, _boolean, _boolean, _void},
  79.     # /*float*/ {_void, _void, _boolean, _boolean, _boolean, _void},
  80.     # /*void*/ {_void, _void, _void, _void, _void, _void}
  81.     #};

  82.     equalityResultType = [
  83.         [ _void, _void, _void, _void, _void, _void ],
  84.         [ _void, _boolean, _void, _void, _void, _void ],
  85.         [ _void, _void, _boolean, _boolean, _boolean, _void ],
  86.         [ _void, _void, _boolean, _boolean, _boolean, _void ],
  87.         [ _void, _void, _boolean, _boolean, _boolean, _void ],
  88.         [ _void, _void, _void, _void, _void, _void ]
  89.                          ]
  90.     
  91.     #/** Indicate whether a type needs a promotion to a wider type.
  92.     # * If not null, implies promotion required. Null does NOT imply
  93.     # * error--it implies no promotion. This works for
  94.     # * arithmetic, equality, and relational operators in Cymbol.
  95.     # */
  96.     #public static final Type[][] promoteFromTo = new Type[][] {
  97.     # /* struct boolean char int float, void (liunote formal is colum)*/
  98.     # /*struct*/ {null, null, null, null, null, null},
  99.     # /*boolean*/ {null, null, null, null, null, null},
  100.     # /*char*/ {null, null, null, _int, _float, null},
  101.     # /*int*/ {null, null, null, null, _float, null},
  102.     # /*float*/ {null, null, null, null, null, null},
  103.     # /*void*/ {null, null, null, null, null, null}
  104.     #};
  105.     
  106.     promoteFromTo = [
  107.         [ None, None, None, None, None, None ],
  108.         [ None, None, None, None, None, None ],
  109.         [ None, None, None, _int, _float, None ],
  110.         [ None, None, None, None, _float, None ],
  111.         [ None, None, None, None, None, None ],
  112.         [ None, None, None, None, None, None ]
  113.                    ]

  114.     #GlobalScope globals = new GlobalScope();
  115.     #public SymbolTable() { initTypeSystem(); }
  116.     
  117.     #protected void initTypeSystem() {
  118.     # for (Type t : indexToType) {
  119.     # if ( t!=null ) globals.define((BuiltInTypeSymbol)t);
  120.     # }
  121.     #}
  122.     def initTypeSystem(self):
  123.         for t in SymbolTable.indexToType:
  124.             if t != None : self.globals.define(t)

  125.     def __init__(self):
  126.         self.listener = CymbolListener()
  127.         self.globals = GlobalScope()
  128.         self.initTypeSystem()

  129.     #public Type getResultType(Type[][] typeTable, CymbolAST a, CymbolAST b) {
  130.     # int ta = a.evalType.getTypeIndex(); // type index of left operand
  131.     # int tb = b.evalType.getTypeIndex(); // type index of right operand
  132.     # Type result = typeTable[ta][tb]; // operation result type
  133.     # // promote left to right or right to left?
  134.     # a.promoteToType = promoteFromTo[ta][result.getTypeIndex()];
  135.     # b.promoteToType = promoteFromTo[tb][result.getTypeIndex()];
  136.     # return result;
  137.     #}
  138.     
  139.     def getResultType(self,typeTable, a, b) :
  140.         ta = a.evalType.getTypeIndex() # type index of left operand liunote evalType => int a (a+1.1)'evalType is float!!!
  141.         tb = b.evalType.getTypeIndex() # type index of right operand
  142.         result = typeTable[ta][tb] # operation result type
  143.         
  144.         # promote left to right or right to left?
  145.         a.promoteToType = SymbolTable.promoteFromTo[ta][result.getTypeIndex()]
  146.         b.promoteToType = SymbolTable.promoteFromTo[tb][result.getTypeIndex()]
  147.         return result


  148.     #public Type bop(CymbolAST a, CymbolAST b) {
  149.     # return getResultType(arithmeticResultType, a, b);
  150.     #}
  151.     def bop( self,a, b) :
  152.         return self.getResultType(SymbolTable.arithmeticResultType, a, b) # liunote call myslef method ,param need't self
  153.     
  154.     #public Type relop(CymbolAST a, CymbolAST b) {
  155.     # return getResultType(relationalResultType, a, b);
  156.     #}
  157.     def relop(self, a, b) :
  158.         return self.getResultType(SymbolTable.relationalResultType, a, b)
  159.     
  160.     #public Type eqop(CymbolAST a, CymbolAST b) {
  161.     # return getResultType(equalityResultType, a, b);
  162.     #}
  163.     def eqop(self, a, b) :
  164.         return getResultType(SymbolTable.equalityResultType, a, b)
  165.     

  166.     #public Type uminus(CymbolAST a) { return a.evalType; }
  167.     def uminus(self,a): return a.evalType
  168.     #public Type unot(CymbolAST a) { return _boolean; }
  169.     def unot(self, a): return _boolean

  170.     #public Type arrayIndex(CymbolAST id, CymbolAST index) {
  171.     # Symbol s = id.scope.resolve(id.getText()); // resolve variable
  172.     # VariableSymbol vs = (VariableSymbol)s;
  173.     # id.symbol = vs; // annotate AST
  174.     # Type t = ((ArrayType)vs.type).elementType; // get element type
  175.     # int texpr = index.evalType.getTypeIndex();
  176.     # index.promoteToType = promoteFromTo[texpr][tINT]; // promote index?
  177.     # return t;
  178.     #}
  179.     #arrayRef returns [type] //[Type type]
  180.     #: ^(INDEX ID expr)
  181.     # {
  182.     # $type = self.symtab.arrayIndex($ID, $expr.start);
  183.     # $start.evalType = $type;
  184.     # }
  185.     #;
  186.     def arrayIndex(self,id, index) :
  187.         s = id.scope.resolve(id.getText()) # resolve variable # liunote return self.token.text
  188.         vs = s; # liunote VariableSymbol ???
  189.         id.symbol = vs; # annotate AST
  190.         #t = ((ArrayType)vs.type).elementType # get element type
  191.         #type ID '[]' ('=' expression)? ';' -> ^(VAR_DECL ^('[]' type) ID expression?)
  192.         t = (vs.type).elementType # liunote vs.type dont cast to (ArrayType) ???
  193.         
  194.         texpr = index.evalType.getTypeIndex() # liunote index node get it's evalType [2-1] => _int type
  195.         index.promoteToType = SymbolTable.promoteFromTo[texpr][SymbolTable.tINT]; # promote index?
  196.         return t;

  197.     #/** For g('q',10), promote 'q' to int, 10 to float
  198.     # * Given int g(int x, float y) {...} */
  199.     #public Type call(CymbolAST id, List args) {
  200.     # Symbol s = id.scope.resolve(id.getText());
  201.     # MethodSymbol ms = (MethodSymbol)s;
  202.     # id.symbol = ms;
  203.     # int i=0;
  204.     # for (Symbol a : ms.orderedArgs.values() ) { // for each arg
  205.     # CymbolAST argAST = (CymbolAST)args.get(i++);
  206.     # // get argument expression type and expected type
  207.     # Type actualArgType = argAST.evalType;
  208.     # Type formalArgType = ((VariableSymbol)a).type;
  209.     # int targ = actualArgType.getTypeIndex();
  210.     # int tformal = formalArgType.getTypeIndex();
  211.     # // do we need to promote argument type to defined type?
  212.     # argAST.promoteToType = promoteFromTo[targ][tformal];
  213.     # }
  214.     # return ms.type;
  215.     #}
  216.     #call returns [type] //[Type type]
  217.     #@init {List args = new ArrayList();}
  218.     #: ^(CALL ID ^(ELIST (expr {args.add($expr.start);})*))
  219.     # {
  220.     # $type = symtab.call($ID, args);
  221.     # $start.evalType = $type;
  222.     # }
  223.     #;
  224.     def call( self,id,args):
  225.         s = id.scope.resolve(id.getText())
  226.         ms = s #(MethodSymbol)
  227.         id.symbol = ms
  228.         i = 0
  229.         #for (Symbol a : ms.orderedArgs.values() ) { // for each arg
  230.         for a in [item[1] for item in ms.orderedArgs]:
  231.             #CymbolAST argAST = (CymbolAST)args.get(i++);
  232.             argAST = args[i]
  233.             
  234.             # get argument expression type and expected type
  235.             #Type actualArgType = argAST.evalType;
  236.             actualArgType = argAST.evalType # liunote only CymbolAST has evalType ???
  237.             
  238.             #Type formalArgType = ((VariableSymbol)a).type; # liunote formaltype => int func (int j) ,but call is func (5+1.2)!!!
  239.             formalArgType = a.type # formal is int index 3, actualArg is float index 4
  240.                                                               # promote[4][3]= None , int func(float) ,func(5) =>promote[3][4]= _float
  241.             #int targ = actualArgType.getTypeIndex();
  242.             #int tformal = formalArgType.getTypeIndex();
  243.             targ = actualArgType.getTypeIndex()
  244.             tformal = formalArgType.getTypeIndex()
  245.             
  246.             #// do we need to promote argument type to defined type?
  247.             argAST.promoteToType = SymbolTable.promoteFromTo[targ][tformal]
  248.             
  249.             i += 1
  250.         
  251.         return ms.type
  252.     

  253.     #public Type member(CymbolAST expr, CymbolAST field) {
  254.     # StructSymbol scope=(StructSymbol)expr.evalType;// get scope of left
  255.     # Symbol s = scope.resolveMember(field.getText());// resolve ID in scope
  256.     # field.symbol = s;
  257.     # return s.type; // return ID's type
  258.     #}
  259.     #member returns [type] //[Type type]
  260.     #: ^('.' expr ID)
  261.     # {
  262.     # $type = self.symtab.member($expr.start, $ID); // liunote struct a{ int b,...}[] => a[i].b ??? $expr.start what is ???
  263.     # $start.evalType = $type; // liunote $expr => class expr_return (see below ), it derive TreeRuleReturnScope
  264.     # } // $expr'start TreeRuleReturnScope 's start ()
  265.     # // This is identical to the ParserRuleReturnScope except that
  266.     # // the start property is a tree nodes not Token object
  267.     # // when you are parsing trees. To be generic the tree node types
  268.     # // have to be Object.

  269.     #public static class expr_return extends TreeRuleReturnScope {
  270.     # public Type type;
  271.     #};

  272.     #// $ANTLR start "expr"
  273.     #// /Users/parrt/research/book/TPDSL/Book/code/semantics/promote/Types.g:39:1: expr returns [Type type] : ( 'true' | 'false' | CHAR | INT | FLOAT | ID | ^( UNARY_MINUS a= expr ) | ^( UNARY_NOT a= expr ) | member | arrayRef | call | binaryOps );
  274.     #public final Types.expr_return expr() throws RecognitionException {
  275.     # Types.expr_return retval = new Types.expr_return();
  276.     
  277.     def member(self, expr, field) :
  278.         scope = expr.evalType # (StructSymbol) get scope of left
  279.         s = scope.resolveMember(field.getText()) # resolve ID in scope
  280.         field.symbol = s
  281.         return s.type # return ID's type
  282.     

  283.     # assignnment stuff (arg assignment in call())

  284.     #public void declinit(CymbolAST id, CymbolAST init) {
  285.     # int te = init.evalType.getTypeIndex(); //promote expr to decl type?
  286.     # int tdecl = id.symbol.type.getTypeIndex();
  287.     # init.promoteToType = promoteFromTo[te][tdecl];
  288.     #}
  289.     #// START: datatransfer
  290.     #decl: ^(VAR_DECL . ID (init=.)?) // call declinit if we have init expr
  291.     # /*{if ( $init!=null && $init.evalType!=null )
  292.     # symtab.declinit($ID, $init);}
  293.     # *//* liunote $init=>CymbolAST */
  294.     # {if $init!=None and $init.evalType!=None:
  295.     # self.symtab.declinit($ID, $init);}
  296.     #;
  297.     def declinit(self, id, init) :
  298.         te = init.evalType.getTypeIndex() # promote expr to decl type?
  299.         tdecl = id.symbol.type.getTypeIndex()
  300.         init.promoteToType = SymbolTable.promoteFromTo[te][tdecl]

  301.     #ret : ^('return' v=.) {self.symtab.ret($start.symbol, $v);} //{symtab.ret((MethodSymbol)$start.symbol, $v);}
  302.     #;
  303.     def ret( self,ms, expr) :
  304.         retType = ms.type; # promote return expr to function decl type? int m1(...) {return a;} a:expr, ms:int 's switch
  305.         exprType = expr.evalType
  306.         texpr = exprType.getTypeIndex()
  307.         tret = retType.getTypeIndex()
  308.         expr.promoteToType = SymbolTable.promoteFromTo[texpr][tret] # liunote at return get promote type

  309.     #assignment // don't walk exprs, just examine types; '.' is wildcard
  310.     #: ^('=

 

Symbol.py

 

  1. class Symbol(object): # A generic programming language symbol

  2.     #public Symbol(String name) { this.name = name; }
  3.     #public Symbol(String name, Type type) { this(name); this.type = type; }
  4.     def __init__(self,name,type=None):
  5.         self.name = '' # liunote use None ???
  6.         self.scope = None
  7.         self.type = None
  8.         self.cymbolast_def = None # Location in AST of ID node liunote where use???
  9.         
  10.         self.name = name
  11.         
  12.         if type != None:
  13.             self.type = type

  14.     #public String getName() { return name; } # liunote getName must define ,for derive Type interface
  15.     def getName(self):
  16.         return self.name
  17.     #name = property(getName) # liunote for sub get parent's member var !

  18.     #def getType(self):
  19.     #    return self.type
  20.     #type = property(getType) # liunote for sub class instance get parent's member var !

  21.     #public String toString() {
  22.     def toString(self):
  23.         s = "";
  24.         if self.scope != None : s = self.scope.getScopeName()+".";
  25.         if self.type != None : return '<' + s + self.getName() + ":" + type + '>'
  26.         return s + self.getName();


  27.     #public static String stripBrackets(String s) {
  28.     def stripBrackets(s):
  29.         return s[1:len(s)-1] #s.substring(1,s.length()-1)
  30.     
  31.     stripBrackets = staticmethod(stripBrackets)

StructSymbol.py

 

  1. from Type import Type
  2. from Scope import Scope
  3. from ScopedSymbol import ScopedSymbol
  4. from SymbolTable import SymbolTable



  5. class StructSymbol (ScopedSymbol, Type, Scope):
  6.     
  7.     #Map<String, Symbol> fields = new LinkedHashMap<String, Symbol>();
  8.     #public StructSymbol(String name,Scope parent) {super(name, parent);}
  9.     def __init__(self,name,parent) :
  10.         self.fields = []
  11.         super(MethodSymbol,self).__init__(name, sparent)
  12.     
  13.     #/** For a.b, only look in a only to resolve b, not up scope tree */
  14.     #public Symbol resolveMember(String name) { return fields.get(name); }
  15.     def resolveMember(self,name):
  16.         #return fields.get(name)
  17.         for item in self.fields:
  18.             if type(item) != tuple:
  19.                 raise RuntimeError('fields item is not tuple error')
  20.             else:
  21.              if item[0] == name:
  22.                  return item[1]
  23.         
  24.     
  25.     #public Map<String, Symbol> getMembers() { return fields; }
  26.     def getMembers(self):
  27.         return fields
  28.         
  29.     def get(self,name):
  30.         for item in self.fields:
  31.             if type(item) != tuple:
  32.                 raise RuntimeError('fields item is not tuple')
  33.             else:
  34.              if item[0] == name:
  35.                  return item[1]

  36.     #public String toString() {
  37.     def toString(self):
  38.         #return "struct "+name+":{"+ stripBrackets(fields.keySet().toString())+"}";
  39.         return "struct " + self.name + "(" + ScopedSymbol.stripBrackets(str([item[0] for item in self.fields])) + ")"

  40.     
  41.     #public int getTypeIndex() { return SymbolTable.tUSER; }
  42.     def getTypeIndex(self): # liunote other is buildin type ,this is user type
  43.         return SymbolTable.tUSER

ScopedSymbol.py

 

  1. from Symbol import Symbol
  2. from Scope import Scope


  3. #public abstract class ScopedSymbol extends Symbol implements Scope {
  4. class ScopedSymbol (Symbol, Scope):

  5.     #Scope enclosingScope;

  6.     #public ScopedSymbol(String name, Type type, Scope enclosingScope) {
  7.     # super(name, type);
  8.     # this.enclosingScope = enclosingScope;
  9.     #}
  10.     #public ScopedSymbol(String name, Scope enclosingScope) {
  11.     # super(name);
  12.     # this.enclosingScope = enclosingScope;
  13.     #}
  14.     
  15.     def __init__( self,name, enclosingScope,type):
  16.         
  17.         if type != None:
  18.             super(ScopedSymbol,self).__init__(name, type)
  19.         else:
  20.             super(ScopedSymbol,self).__init__(name)
  21.         
  22.         #if isinstance(enclosingScope,Scope):
  23.         # self.enclosingScope = enclosingScope # liunote use issubclass ???
  24.         #else:
  25.         # raise RuntimeError('enclosingScope is not instance of xScope')
  26.         
  27.         # liunote nouse above , when buidin type(derive smbol type) not derive from Scope !!!
  28.         #print 'liutest enclosingScope'
  29.         #print enclosingScope
  30.         self.enclosingScope = enclosingScope
  31.         
  32.     #public Symbol resolve(String name) {
  33.     def resolve(self,name):
  34.     #s = self.getMembers().get(name) # this getMembers is abstract, subclass must implement this method !
  35.     s = self.get(name)
  36.         if s != None: return s
  37.     
  38.     #if not here, check any enclosing scope
  39.     if self.getEnclosingScope() != None :
  40.         return self.getEnclosingScope().resolve(name)
  41.         
  42.     return None # not found
  43.     
  44.     #public Symbol resolveType(String name) { return resolve(name); }
  45.     def resolveType(self,name):
  46.         return self.resolve(name)
  47.     
  48.     def define(self,sym):
  49.         #self.getMembers().put(sym.name, sym)
  50.         self.getMembers().append((sym.name, sym))
  51.     sym.scope = self # track the scope in each symbol
  52.     # liutest
  53.     print self.getMembers()


  54.     def getEnclosingScope(self):
  55.         return self.enclosingScope
  56.     
  57.     def getScopeName(self):
  58.         return self.name # liunote self.name at Symbol class => property(getName)

  59.     #/** Indicate how subclasses store scope members. Allows us to
  60.     # * factor out common code in this class.
  61.     # */
  62.     #public abstract Map<String, Symbol> getMembers();
  63.     def getMembers(self): # ??? liunote if use below get,getMember can discard !
  64.         abstract()

  65.     # liunote for list get name     
  66.     def get(self,name):
  67.         abstract()

Scope.py

 

  1. def abstract():
  2.     raise NotImplementedError("abstract")

  3. class Scope(object):
  4.     
  5.     #def __init__(self):
  6.         # if self.__class__ is Scope:
  7.         # abstract()

  8.     def getScopeName(self):
  9.             abstract()
  10.                
  11.         # Where to look next for symbols
  12.         def getEnclosingScope(self):
  13.             abstract()

  14.         # Define a symbol in the current scope
  15.         def define(self,sym):
  16.             abstract()
  17.             
  18.         # Look up name in this scope or in enclosing scope if not here
  19.         def resolve(self,name):
  20.             abstract()

 

 

阅读(1160) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~