【问题标题】:ANTLR4 - Change token textANTLR4 - 更改令牌文本
【发布时间】:2020-10-19 16:34:10
【问题描述】:

考虑以下词法分析器规则:

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

我希望将所有 TRUE 标记转换为“真”。

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

【问题讨论】:

    标签: typescript antlr4


    【解决方案1】:

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

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

    并不是说1 看起来很可疑:如果您有一个匹配数字(或整数)的规则并放在此 TRUE 规则之前,那么输入 1 将永远不会被标记为 TRUE令牌(参见:Why does the order of ANTLR4 tokens matter?)。

    编辑

    它在 JavaScript 中的外观如何?我正在使用antlr4ts,但似乎没有像setText 这样的东西。

    setText(...) 是 Java 运行时中的 Lexer 方法。如果我查看the antlr4ts code,看起来您可以设置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";}
     ;
    

    【讨论】:

    • 它在 JavaScript 中的外观如何?我正在使用antlr4ts,似乎没有像setText 这样的东西。
    • 试试我的 EDIT @JohnSmith
    猜你喜欢
    • 1970-01-01
    • 2013-08-12
    • 2017-03-12
    • 2023-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多