Re: In lex, how do I begin in a state?? (Jonathan Eifrig)
Sun, 22 Nov 1992 22:25:44 GMT

          From comp.compilers

Related articles
In lex, how do I begin in a state?? (James A. Cadwell) (1992-11-21)
Re: In lex, how do I begin in a state?? (1992-11-22)
Re: In lex, how do I begin in a state??! (1992-11-25)
| List of all articles for this month |

Newsgroups: comp.compilers
From: (Jonathan Eifrig)
Organization: The Johns Hopkins University CS Department
Date: Sun, 22 Nov 1992 22:25:44 GMT
References: 92-11-122
Keywords: lex

James A. Cadwell <> writes:
>In lex, one uses BEGIN STATE-NAME in an action to place lex in a
>state. My question is: how do I begin in a state?? That is, have
>a state in effect before any input is read.

The Moderator adds:
>[In short, you have to execute a BEGIN before the lexer starts scanning.
>Code put at the front of the rules section is run whenever you call yylex(),
>so you could do something like this:
> static int first_time = 1;
> if(first_time) {
> first_time = 0;
> }
>The new version of O'Reilly's lex&yacc, much of which I wrote, explains this
>in more detail. -John]

This is, of course, the right way to do things. However, if
you're in a hurry, or are writing a lex-only program (using the _main in
the lex library), one can use the undocumented start state INITIAL. This
is probably a Bad Idea as far as portability goes, but if you're doing
something simple like stripping comments with a two-line lexer, it's
probably sufficient.

As far as the Moderator's suggestion goes, it's probably better to
put the lexer into a state by hand before calling yylex() by adding a
special initialization routine in the "user subroutines" section of the
lex file, after the rules:

kick_start_lexer() { BEGIN FOOSTATE; }

and then manually initialize the lexer before calling yylex():

extern int kick_start_lexer();

      if (yyparse())) ...

This way, the test to see if the lexer is being called for the
first time is eliminated. Hey, it's only one instruction, but that's one
comparison _per_token_. These things start to add up after a while! :-)
Jack Eifrig ( The Johns Hopkins University, C.S. Dept.

Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.