ANTLR4-更改令牌文本



考虑以下lexer规则:

TRUE : 'true' | 'TRUE' | '1';

我希望所有TRUE令牌都转换为"true"。

我正在使用antlr4ts。我该怎么做?

这只能通过使用特定于目标的代码来完成。例如,在Java中,它看起来像这样:

TRUE
: ( 'true' | 'TRUE' | '1' ) {setText("true");}
;

并不是说1看起来可疑:如果您有一个与数字(或整数(匹配的规则,并且该规则位于TRUE规则之前,那么输入1将永远不会被标记为TRUE令牌(请参阅:为什么ANTLR4令牌的顺序很重要?(。

编辑

在JavaScript中会是什么样子?我使用的是antlr4ts,但似乎没有setText

setText(...)是Java运行时中的Lexer方法。如果我看一下antlr4ts代码,看起来你只需要设置public _text字段:

/** You can set the text for the current token to override what is in
*  the input char buffer.  Set `text` or can set this instance var.
*/
public _text: string | undefined;

换句话说,试试这个:

TRUE
: ( 'true' | 'TRUE' | '1' ) {this._text = "true";}
;

最新更新