如何在终端中打印类似于”-tokens”的标记?

huangapple go评论41阅读模式
英文:

How to print the tokens like with "-tokens" in the terminal?

问题

在终端(或控制台)中,我可以使用以下命令grun Exp eval -tokens,但我如何从Java中执行这个操作呢?我发现可以使用如下方式来实现类似于-tree的功能:

ParseTree tree = parser.eval();
System.out.println(tree.toStringTree(parser));

但我找不到类似于-tokens的功能。

编辑 1:我找到了使用lexer.reset()的方式:

lexer.reset();
for (Token token: lexer.getAllTokens()) {
    System.out.println(token);
}

但是这些标记只是像<4>这样的数字,我想要获取它们的实际名称。

编辑 2:我明白了:

Vocabulary vocabulary = lexer.getVocabulary();
lexer.reset();
for (Token token: lexer.getAllTokens()) {
    System.out.println(token.getLine() + ":" + token.getCharPositionInLine() + " '" + token.getText() + "' " + vocabulary.getSymbolicName(token.getType()));
}

虽然这不是完全相同的功能,但仍然提供了主要信息!

英文:

In the terminal (or console), I can just do grun Exp eval -tokens, but how do I do that from Java? I found that, that do like -tree:

ParseTree tree = parser.eval();
System.out.println(tree.toStringTree(parser));

But I can't find anything similar for -tokens.

Edit 1: I found something with lexer.reset():

lexer.reset();
for (Token token: lexer.getAllTokens()) {
	System.out.println(token);
}

But the token are only numbers like <4>, I would like to get the real name from it.

Edit 2: I got it:

Vocabulary vocabulary = lexer.getVocabulary();
lexer.reset();
for (Token token: lexer.getAllTokens()) {
	System.out.println(token.getLine() + ":" + token.getCharPositionInLine() + " '" + token.getText() + "' " + vocabulary.getSymbolicName(token.getType()));
}

This isn't the exact same thing but the main infos still!

答案1

得分: 1

答案是:

Vocabulary vocabulary = lexer.getVocabulary();
lexer.reset();
for (Token token: lexer.getAllTokens()) {
    System.out.println(token.getLine() + ":" + token.getCharPositionInLine() + " '" + token.getText() + "' " + vocabulary.getSymbolicName(token.getType()));
}
英文:

The answer is:

Vocabulary vocabulary = lexer.getVocabulary();
lexer.reset();
for (Token token: lexer.getAllTokens()) {
    System.out.println(token.getLine() + ":" + token.getCharPositionInLine() + " '" + token.getText() + "' " + vocabulary.getSymbolicName(token.getType()));
}

huangapple
  • 本文由 发表于 2020年7月28日 15:37:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63129158.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定