AST重写规则带有"* +"在反叛中 [英] AST rewrite rule with " * +" in antlr
问题描述
我在将规则从解析树转换为ant树的AST树时遇到麻烦.
I'm having a trouble about rewrite rule to convert from parsing tree into AST tree in 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"时,解析树的结果如下:
When I input "adj1 noun1 adj2" , the result of parse tree like this:
但是重写规则后的 AST树似乎并不完全像解析树,adj是double且顺序不正确,例如:
But the AST tree after rewrite rule seem not exactly like the parse tree, the adj is double and not in order, like this:
所以我的问题是我该如何重写规则以得到像上面的解析树这样的结果?
So my question is how can I rewrite rule to have a result like the parsing tree above?
推荐答案
您的名词短语规则会收集所有形容词并将其复制到名词的两侧,因为ANTLR无法自动区分一组匹配的adj
还有一个.
Your noun phrase rule collects all the adjectives and copies them to both sides of the nouns because ANTLR can't automatically distinguish between one group of matched adj
s and another.
这是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
的示例:
One way to separate the two groups is to collect them into their own respective lists. Here's an example, applied to rule 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
.
This way ANTLR knows which adj
s to write out before and after the n
s.
这篇关于AST重写规则带有"* +"在反叛中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!