regexcompiler-constructionbnfc

Is there a way to use whitespace in BNFC?


How do you use whitespace in a BNFC definition?

For example, suppose I want to produce a parser for the lambda calculus where I allow a list of variables to be abstracted:

\x y z.x z (y z)

The "obvious" thing to do is use a labeled rule like:

ListAbs . Exp ::= "\\" [Ident] "." Exp ;
separator Ident " "

However, BNFC defaults to stripping whitespace, so that does not work. What does work is using a comma separator. A bit uglier, but I could live with it... Still it would be nice to be able to separate by space.

Is there a whitespace character class in BNFC?


Solution

  • You can declare the empty string as separator:

    separator Ident ""
    

    In practice this lets you use white-spaces (or any space character) as separator:

    $ cat test.cf
    A . A ::= [Ident] ;
    separator Ident ""
    $ bnfc -haskell -m test.cf
    $ make
    $ echo 'x y z' | ./Testtest
    
    Parse Successful!
    
    [Abstract Syntax]
    
    A [Ident "x",Ident "y",Ident "z"]
    
    [Linearized tree]
    
    x y z