我试图理解 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
;