Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse comments with EBNF grammars

When defining the grammar for a language parser, how do you deal with things like comments (eg /* .... */) that can occur at any point in the text?

Building up your grammar from tags within tags seems to work great when things are structured, but comments seem to throw everything.

Do you just have to parse your text in two steps? First to remove these items, then to pick apart the actual structure of the code?

Thanks

like image 411
Jagu Avatar asked Sep 26 '11 13:09

Jagu


2 Answers

Normally, comments are treated by the lexical analyzer outside the scope of the main grammar. In effect, they are (usually) treated as if they were blanks.

like image 147
Jonathan Leffler Avatar answered Nov 28 '22 01:11

Jonathan Leffler


One approach is to use a separate lexer. Another, much more flexible way, is to amend all your token-like entries (keywords, lexical elements, etc.) with an implicit whitespace prefix, valid for the current context. This is how most of the modern Packrat parsers are dealing with whitespaces.

like image 42
SK-logic Avatar answered Nov 28 '22 03:11

SK-logic