2012-12-20 52 views
2

我在重寫規則時將解析樹轉換爲antlr中的AST樹時遇到了麻煩。AST重寫規則,在antlr中帶「* +」

這裏是我的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名1 ADJ2」 解析樹像這樣的結果:

parse tree

AST樹在重寫規則看起來不完全像分析樹之後,adj是雙倍的,而不是像這樣:

AST tree

所以我的問題是我怎麼能重寫規則有一個像上面的解析樹的結果?

回答

2

您的名詞短語規則會收集所有形容詞,並將它們複製到名詞的兩側,因爲ANTLR無法自動區分一組匹配的adj s與另一組。

這裏是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知道哪些adj年代以前寫出來和n年代後。

+0

它的工作,非常感謝你:) –

+0

我喜歡你的帽子。 –

+0

@TrungL我很高興能幫上忙。 :) – user1201210