5

I would like to parse identifiers in a programming language, by using PetitParser.

One of the requirements is that the name of an identifier is not a keyword (such as null), so that null would not be a valid identifier.

The smallest parser I can think for this case is:

identifier := ('null' asParser not,  #word asParser plus)

However, if the input starts with a keyword it fails:

identifier end parse: 'nullable'

Do you have any suggestion to solve this? Thank you!

Alberto Bacchelli
  • 1,029
  • 1
  • 9
  • 9

1 Answers1

6
identifier := ('null' asParser, #word asParser plus) /
    ('null' asParser not, #word asParser plus).

identifier end parse: 'nullable'. "=> #('null' #($a $b $l $e))"
identifier end parse: 'null'. "=>  'at 0'"
identifier end parse: 'foo' "=> #(nil #($f $o $o))"

The at 0 is PetitParser's default 'failed to parse' error, showing that the parser will accept 'nullable', normal words, and not 'null'.

Frank Shearar
  • 17,012
  • 8
  • 67
  • 94