Umer
Umer

Reputation: 1921

ANTLR AST building problem

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 is :

" & 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...

Upvotes: 0

Views: 277

Answers (1)

MiKo
MiKo

Reputation: 2146

Using this as atom should do the trick:

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

Upvotes: 1

Related Questions