sm13294
sm13294

Reputation: 563

Rewrite rules in ANTLR

I am doing an ANTLR specification. In my AST i need to do this one:

characters ('*'^|'+'^|'?'^)?

I need to do a rewrite rule that will present in ast instead of * ASTERISK, instead of + PLUS and instead of ? QMARK nodes?

I know that if we would have something like this:

characters '*' 

it can be rewrited as

^(ASTERISK characters)

but i dont know how to deal with | operator?

Upvotes: 0

Views: 393

Answers (1)

Bart Kiers
Bart Kiers

Reputation: 170178

Try this:

grammar T;

// options ...

tokens {
  ASTERISK;
  PLUS;
  QMARK;
}

// @header and/or @members ...

rule
 : (characters -> characters) ( '*' -> ^(ASTERISK characters)
                              | '+' -> ^(PLUS characters)
                              | '?' -> ^(QMARK characters)
                              )?
 ;

The key here is that if the optional *, + or ? are not present, the characters will just stay characters by the rewrite rule: (characters -> characters).

Upvotes: 2

Related Questions