修改ANTLR中的tokenizer

时间:2014-06-04 19:07:35

标签: parsing antlr token

在ANTLR中,如何像push&#34一样逐个输出标记;输入"在键盘中,我尝试像这样的名为hello.java的类

public class Hello{
    public static void main(String args[]){
        System.out.println("Hello World ...");
    }
}

现在,是时候解析令牌了

final Antlr3JavaLexer lexer = new Antlr3JavaLexer();
   try {
      lexer.setCharStream(new ANTLRReaderStream(in)); // in is a file 
    } catch (IOException e) {
       e.printStackTrace();
   }

    final CommonTokenStream tokens = new CommonTokenStream();
    tokens.setTokenSource(lexer);
    tokens.LT(10); // force load


    Antlr3JavaParser parser = new Antlr3JavaParser(tokens);
    System.out.println(tokens);

它给了我这样的输出,

publicclassHello{publicstaticvoidmain(Stringarggs[]){System.out.println("Hello World ...");}}

如何使输出看起来像这样

public
class
Hello
{
public
static ... untill the end...

我尝试使用Stringbuilder,但它无法正常工作。 谢谢4帮助..

1 个答案:

答案 0 :(得分:0)

您不必仅打印令牌,而是必须迭代令牌流以获得所需的结果。

像这样修改你的代码。

final Antlr3JavaLexer lexer = new Antlr3JavaLexer();
try {
  lexer.setCharStream(new ANTLRReaderStream(in)); // in is a file 
} catch (IOException e) {
   e.printStackTrace();
}

final CommonTokenStream tokens = new CommonTokenStream();
tokens.setTokenSource(lexer);
//tokens.LT(10); // force load - not needed


Antlr3JavaParser parser = new Antlr3JavaParser(tokens);
// Iterate over tokenstream
for (Object tk: tokens.getTokens()) 
{
 CommonToken commontk = (CommonToken) tk;
 if (commontk.getText() != null && commontk.getText().trim().isEmpty() == false) 
   {
    System.out.println(commontk.getText());             
   }
}

在此之后,你将得到这个结果。

 public
 class
 Hello
 {
 public
 static ... etc...

希望这能解决您的问题。