ANTLR4-如何获得令牌类型作为ANTLR中的令牌文本? [英] ANTLR4 - How do I get the token TYPE as the token text in ANTLR?

查看:214
本文介绍了ANTLR4-如何获得令牌类型作为ANTLR中的令牌文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个带有这样的标记的语法:

Say I have a grammar that has tokens like this:

AND        : 'AND' | 'and' | '&&' | '&';
OR         : 'OR' | 'or' | '||' | '|' ;
NOT        : 'NOT' | 'not' | '~' | '!';

当我使用TreeViewer可视化ParseTree或使用tree.toStringTree()打印树时,每个节点的文本与匹配的文本相同.

When I visualize the ParseTree using TreeViewer or print the tree using tree.toStringTree(), each node's text is the same as what was matched.

因此,如果我解析"A和B或C",则两个二进制运算符将为和"/或". 如果我解析"A& B || C",它们将是&&"/"||".

So if I parse "A and B or C", the two binary operators will be "and" / "or". If I parse "A && B || C", they'll be "&&" / "||".

我想让他们始终为"AND"/"OR/"或"NOT",而不管匹配什么文字符号.这可能吗?

What I would LIKE is for them to always be "AND" / "OR / "NOT", regardless of what literal symbol was matched. Is this possible?

推荐答案

这是该词汇表的目的.使用yourLexer.getVocabulary()yourParser.getVocabulary(),然后使用vocabulary.getSymbolicName(tokenType)作为令牌类型的文本表示.如果返回空字符串,请尝试第二步vocabulary.getLiteralName(tokenType),它返回用于定义令牌的文本.

This is what the vocabulary is for. Use yourLexer.getVocabulary() or yourParser.getVocabulary() and then vocabulary.getSymbolicName(tokenType) for the text representation of the token type. If that returns an empty string try as second step vocabulary.getLiteralName(tokenType), which returns the text used to define the token.

这篇关于ANTLR4-如何获得令牌类型作为ANTLR中的令牌文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆