开发者

ANTLR AST building problem

开发者 https://www.devze.com 2023-01-26 18:19 出处:网络
I am unable to get AST of \" risk & factors | concise\" | item 503 using following grammar grammar BoolExpRep;

I am unable to get AST of

" risk & factors | concise" | item 503

using following grammar

grammar BoolExpRep;

options {
  output=AST;
}

tokens {
  MultiWordNode;
}

start
  :  exp EOF!
  ;

exp
  :  atom (expRest^)? 
  |  '('! exp ')'! (expRest^)?
  ;

expRest 
  :  OPER exp -> ^(OPER exp)
  |  '~' WORD exp -> ^('~' WORD exp)
  ;

OPER
  :  '&' | '|' | '!' | '&!' | '|!'
  ;

atom
  :  WORD WORD+ -> ^(MultiWordNode WORD+) 
  |  WORD
  |  '"' WORD (OPER? WORD)+ '"' -> ^(MultiWordNode '"' (OPER? WORD)+ '"')
  |  '"' WORD '"' 
  ;

WORD
  :  ('a'..'z' | 'A'..'Z' | '0'..'9' | '.' | '*' | '{' | '}' | '_' | '?' | ':' 
             | ',' | '/' | '\\')+ ('0'..'9')* 
  ;

I want to make an AST which should show words and operators in order for

" risk & factors | concise "

i.e. my requirement is something like:

" risk & factors | concise "

instead what i get i开发者_JAVA百科s :

" & risk & factors & concise "

actually, i am referring to AST under MultiwordNode (or generated at 'atom' level)

it should work something like

        M u l t i W o r d N o d e 
        /   / /  |    \  \      \
       /   / /   |     \  \      \
      " risk & factors | concise  "

(sorry for my bad drawing :) )

the problem is that if operator occurs without quotes, it should be the kind of head of its siblings (as it refers in AST). but when it occurs in some text with quotes, it should be captures just like other words...


Using this as atom should do the trick:

atom
  :  WORD WORD+ -> ^(MultiWordNode WORD+) 
  |  WORD
  |  '"' WORD (OPER WORD)+ '"' -> ^(MultiWordNode '"' WORD (OPER WORD)+ '"')
  |  '"' WORD '"' 
  ;
0

精彩评论

暂无评论...
验证码 换一张
取 消