home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.compilers
- Path: sparky!uunet!world!iecc!compilers-sender
- From: eifrig@beanworld.cs.jhu.edu (Jonathan Eifrig)
- Subject: Re: In lex, how do I begin in a state??
- Reply-To: eifrig@beanworld.cs.jhu.edu (Jonathan Eifrig)
- Organization: The Johns Hopkins University CS Department
- Date: Sun, 22 Nov 1992 22:25:44 GMT
- Approved: compilers@iecc.cambridge.ma.us
- Message-ID: <92-11-129@comp.compilers>
- References: <92-11-122@comp.compilers>
- Keywords: lex
- Sender: compilers-sender@iecc.cambridge.ma.us
- Lines: 62
-
- 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.
- --
- Send compilers articles to compilers@iecc.cambridge.ma.us or
- {ima | spdcc | world}!iecc!compilers. Meta-mail to compilers-request.
-