我在重写规则以从 antlr 中的解析树转换为 AST 树时遇到了麻烦。
这是我的 antlr 代码:
grammar MyGrammar;
options {
output= AST;
ASTLabelType=CommonTree;
backtrack = true;
}
tokens {
NP;
NOUN;
ADJ;
}
//NOUN PHRASE
np : ( (adj)* n+ (adj)* -> ^(ADJ adj)* ^(NOUN n)+ ^(ADJ adj)* )
;
adj : 'adj1'|'adj2';
n : 'noun1';
当我输入“adj1 noun1 adj2”时,解析树的结果如下:
但是重写规则后的AST树看起来并不完全像解析树,adj是双的并且不按顺序,如下所示:
所以我的问题是如何重写规则以获得像上面的解析树这样的结果?
最佳答案
您的名词短语规则会收集所有形容词并将它们复制到名词的两侧,因为 ANTLR 无法自动区分一组匹配的 adj
和另一组。
以下是 np
规则的分割:
np : (
(adj)* //collect some adjectives
n+
(adj)* //collect some more adjectives
-> ^(ADJ adj)* //all adjectives written
^(NOUN n)+ //all nouns written
^(ADJ adj)* //all adjectives written again
)
;
区分这两个组的一种方法是将它们收集到各自的列表中。下面是一个应用于规则 np
的示例:
np : (
(before+=adj)* //collect some adjectives into "before"
n+
(after+=adj)* //collect some adjectives into "after"
-> ^(ADJ $before)* //"before" adjectives written
^(NOUN n)+ //all nouns copied
^(ADJ $after)* //"after" adjectives written
)
;
这样 ANTLR 就知道在 n
之前和之后要写出哪些 adj
。
关于antlr - Antlr 中 "* +"的 AST 重写规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13965243/