1

我试图理解 ANTLR 谓词。为此,我有一个简单的词法分析器和解析器,如下所示。

我想做的是使用谓词在每次看到“foo”时插入单词“fubar”,然后是一些空格,然后是“bar”。我想在保持相同基本结构的同时做到这一点。在词法分析器中执行此操作的奖励积分。如果我可以在完全不提及基础语言的情况下做到这一点,则可以获得更多奖励积分。但如果有必要,它是 C#。

例如,如果输入字符串是:

programmers use the words foo bar and bar foo class

输出将是

programmers use the words foo fubar bar and bar foo class

词法分析器:

lexer grammar TextLexer;

@members
{
    protected const int EOF = Eof;
    protected const int HIDDEN = Hidden;
}

FOO: 'foo';
BAR: 'bar';
TEXT: [a-z]+ ;

WS
    :   ' ' -> channel(HIDDEN)
    ;

解析器:

parser grammar TextParser;

options { tokenVocab=TextLexer; }

@members
{
    protected const int EOF = Eof;
}

file: words EOF;

word:FOO
|BAR
|TEXT;

words: word
| word words
;

compileUnit
    :   EOF
    ;
4

1 回答 1

1

在这种情况下,ANTLR3 的词法分析器可能需要一个谓词,但 ANTLR4 的词法分析器要“更智能”得多。您可以在单个词法分析器规则中匹配“foo bar”,并使用以下内容更改其内部文本setText(...)

FOO_BAR
 : 'foo' [ \t]+ 'bar' {setText("fubar");}
 ;

TEXT
 : [a-z]+ 
 ;

WS
 : ' ' -> channel(HIDDEN)
 ;
于 2013-12-16T20:14:20.927 回答