Flex start conditions
Posted Fri, 28 Nov 2008
I finally (after a bit of searching and thinking) figured how to properly match
comments with flex/bison. Horray :)
Some tutorials use this in flex:
#.*$But since flex chooses longest-match-first for the next token, any line with a # in it might have the remainder of the line accidentally cut as a comment. The right way to do this appears to be:
/* in your .lex file */
%x LEX_COMMENT
%%
"#" { BEGIN(LEX_COMMENT); }
<LEX_COMMENT>[^\n]* /* ignore comments. */
<LEX_COMMENT>\n { yylineno++; BEGIN(INITIAL); } /* end comment */
There's a mini state-machine going on here. When it matches a "#" it moves into
the 'LEX_COMMENT' (name chosen by me, could be anything) state where only
tokens in this state are accepted. Now my config files can ignore comments
properly: only when outside the presence of any other token (like a quoted
string).