AST rewrite rule with “ * +” in antlr

懵懂的女人 提交于 2019-12-11 03:24:10

问题


I'm having a trouble about rewrite rule to convert from parsing tree into AST tree in antlr.

Here's my antlr code:

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';

When I input "adj1 noun1 adj2" , the result of parse tree like this:

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?


回答1:


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 adjs and another.

Here is a break-down of the np rule:

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
         )
    ;

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
         )
    ;

This way ANTLR knows which adjs to write out before and after the ns.



来源:https://stackoverflow.com/questions/13965243/ast-rewrite-rule-with-in-antlr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!