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

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

问题描述

假设我有一个包含如下标记的语法:

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 中获取令牌 TYPE 作为令牌文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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