-1

Is there any way to match a token in antlr except a specific one?

I have a rule which states that a '_' can be an ID. Now I have a specific situation in which I want to match an ID, but in this particular case I want it to ignore the '_' alternative. Is it possible?

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
halfwarp
  • 1,780
  • 5
  • 24
  • 41
  • 3
    I browsed through your questions a bit and many of them seem to have decent answers, yet most of them are not accepted. You _do_ seem to favor your own answers you provide to your questions... :) – Bart Kiers Aug 17 '11 at 17:16
  • @halfwarp Does the answer qualify as acceptable? If yes please accept it. – Th 00 mÄ s Dec 07 '12 at 11:06

1 Answers1

1

I think something like

(ID {!$ID.text.equals("_")}?)

should do it (if you are using Java as target language). Otherwise you will have to write that semantic predicate in a way that your language understands it.

In short, this will check whether the text does not equal "_" and only then will the subrule match.

Another possible way to do this:

id: ID
  | '_'
  ;

ID: // lexer rule to match every valid identifier EXCEPT '_' ;

That way, whenever you mean "either '_' or any other ID", you use id to match this, if you disallow "_", you can use _.

Community
  • 1
  • 1
Egon
  • 4,757
  • 1
  • 23
  • 38