Search code examples
parsingsmalltalkpetitparser

How to parse identifiers that start with a keyword with PetitParser?


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!


Solution

  • 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'.