1
votes

I am trying to write a lexer rule that will match a variable name as follows.

TYPE: [a-zA-Z][a-zA-Z0-9_];

However, I also have a parser rule similar to below.

dup: TYPE 'x{' TYPE '}' 

These easily match,

HELLO x{wee}
catx x{text}

but I want to be able to match the following as well.

HELLOx{wee}
namex{text}

Where x{ would match the token in the parser rule. The problem is that x is getting put into the TYPE token so the parser doesn't know what to do with the random {.

Is there anyway to get the lexer to not match a trailing x if it is followed by a {?

1

1 Answers

2
votes

This can be solved with a lookahead, e.g.

dup
  : TYPE 'x{' TYPE '}'
  ; 

TYPE
  : [a-zA-Z]([a-wy-zA-Z0-9_]|('x' {_input.LA(1) != '{'}?))*
  ;

The definition of TYPE allows x only if the lookahead is not a {.