Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 533
Alberto Bacchelli Avatar asked Dec 20 '12 11:12

Alberto Bacchelli


1 Answers

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

like image 129
Frank Shearar Avatar answered Nov 15 '22 06:11

Frank Shearar