2012-10-21 62 views
0

我試圖學習將EBNF轉換爲C#代碼。將EBNF轉換爲C#編譯器

樣品:int <ident> = <expr>

我理解它的說「的可變(IDENT)這個數據類型的(INT)取入(=)整數(表達式),但我不明白的是如何將它轉換成這樣:

從阿斯特類

public class Int : Stmt 
{ 
    public string Ident; 
    public Expr Expr; 
} 

從解析器類

#region INTEGER VARIABLE 
    else if (this.tokens[this.index].Equals("int")) 
    { 
     this.index++; 
     Int Integer = new Int(); 

     if (this.index < this.tokens.Count && 
      this.tokens[this.index] is string) 
     { 
      Integer.Ident = (string)this.tokens[this.index]; 
     } 
     else 
     { 
      throw new System.Exception("expected variable name after 'int'"); 
     } 

     this.index++; 

     if (this.index == this.tokens.Count || 
      this.tokens[this.index] != Scanner.EqualSign) 
     { 
      throw new System.Exception("expected = after 'int ident'"); 
     } 

     this.index++; 

     Integer.Expr = this.ParseExpr(); 
     result = Integer; 
    } 
    #endregion 

從CodeGen將類

#region INTEGER 
    else if (stmt is Int) 
    { 
     // declare a local 
     Int integer = (Int)stmt; 
     this.symbolTable[integer.Ident] = this.il.DeclareLocal(this.TypeOfExpr(integer.Expr)); 

     // set the initial value 
     Assign assign = new Assign(); 
     assign.Ident = integer.Ident; 
     assign.Expr = integer.Expr; 
     this.GenStmt(assign); 
    } 
    #endregion 

有人點我在正確的方向上如何正確地理解如何轉換呢?

回答

0

爲什麼不使用編譯器編譯器如AntLR?它會自動執行,並且速度更快:)

+0

我剛剛檢出了這些庫,它看起來像只有2.0版本,是嗎? – SpicyWeenie

+0

可能是:在這裏有人問同樣的問題:http://stackoverflow.com/questions/1194584/what-is-a-good-c-sharp-compiler-compiler-parser-generator – LueTm

+0

我堅持與黃金。 Thx爲輸入! :) – SpicyWeenie