2011-12-21 94 views
2

我想創建簡單的翻譯翻譯是這樣的:ANTLR如何獲取重寫的代碼源? (使用TokenRewriteStream)

aaa | bbb | ccc 

1 : aaa 
2 : bbb 
c : ccc 

這裏是語法test01.g:

grammar test01; 

options { 
    output=AST; 
} 

@members{ 
    int N; 
} 

test 
@init{ 
    N = 0; 
}: 
    id ('|' id)* -> id (BR id)*; 

id : {N++;} ID -> {new CommonTree(new CommonToken(ID, Integer.toString(N) + " : " + $ID.text))}; 
ID : ('a'..'z')+; 
BR : '\n'; 
WS : ' '{$channel=HIDDEN;}; 

翻譯源FooTest。 java:

import org.antlr.runtime.*; 

class FooTest { 
    public static void main(String[] args) throws Exception {  
    String text = "aaa | bbb | ccc";   
    System.out.println("parsing: "+text);   
    ANTLRStringStream in = new ANTLRStringStream(text); 
    test01Lexer lexer = new test01Lexer(in); 
    CommonTokenStream tokens = new TokenRewriteStream(lexer); 
    test01Parser parser = new test01Parser(tokens); 
    parser.test(); 
    System.out.println("Result: "+tokens.toString());  
    } 
} 

當我運行它,我excpect得到的東西,如:

parsing: aaa | bbb | ccc 
Result: 
1 : aaa 
2 : bbb 
3 : ccc 

,但我得到:

parsing: aaa | bbb | ccc 
    Result: aaa | bbb | ccc 

文字似乎是不變。

如何獲取修改後的源代碼?

回答

1

你只需做印刷令牌的列表:

CommonTokenStream tokens = new TokenRewriteStream(lexer); 
// ... 
System.out.println("Result: "+tokens.toString()); 

如果您調整FooTest類:

import org.antlr.runtime.*; 
import org.antlr.runtime.tree.*; 

class FooTest { 
    public static void main(String[] args) throws Exception {  
    String text = "aaa | bbb | ccc";   
    System.out.println("parsing: "+text);   
    ANTLRStringStream in = new ANTLRStringStream(text); 
    test01Lexer lexer = new test01Lexer(in); 
    CommonTokenStream tokens = new TokenRewriteStream(lexer); 
    test01Parser parser = new test01Parser(tokens); 
    CommonTree root = (CommonTree)parser.test().getTree(); 
    for(int i = 0; i < root.getChildCount(); i++) { 
     CommonTree child = (CommonTree)root.getChild(i); 
     System.out.println("root.children[" + i + "] = " + child); 
    } 
    } 
} 

被打印到控制檯如下:

parsing: aaa | bbb | ccc 
root.children[0] = 1 : aaa 
root.children[1] = BR 
root.children[2] = 2 : bbb 
root.children[3] = BR 
root.children[4] = 3 : ccc 

並注意t您不需要在解析器類中放置全局變量。規則也處理變量(局部於它們)。這是首選:

grammar test01; 

options { 
    output=AST; 
} 

test: 
    id ('|' id)* -> id (BR id)*; 

id 
@init{ 
    int N = 0; 
} 
    : {N++;} ID -> {new CommonTree(new CommonToken(ID, Integer.toString(N) + " : " + $ID.text))} 
    ; 

// other rules