Re: In lex, how do I begin in a state??

eifrig@beanworld.cs.jhu.edu (Jonathan Eifrig)
Sun, 22 Nov 1992 22:25:44 GMT

          From comp.compilers

Related articles
In lex, how do I begin in a state?? cadwell@seattleu.edu (James A. Cadwell) (1992-11-21)
Re: In lex, how do I begin in a state?? eifrig@beanworld.cs.jhu.edu (1992-11-22)
Re: In lex, how do I begin in a state?? tamdhu.ohm.york.ac.uk!rog@ohm.york.ac.uk (1992-11-25)
| List of all articles for this month |
Newsgroups: comp.compilers
From: eifrig@beanworld.cs.jhu.edu (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 <cadwell@seattleu.edu> 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) {
> BEGIN FOOSTATE;
> 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:


<START>.....
...
%%
int
kick_start_lexer() { BEGIN FOOSTATE; }


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


extern int kick_start_lexer();


int
main()
{
      ...
      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 (eifrig@cs.jhu.edu) 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.