help-flex
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: flex help


From: John Millaway
Subject: Re: flex help
Date: Tue, 16 Jul 2002 08:15:49 -0700 (PDT)

Here's a working scanner/parser for your problem. Notice that the {ws} rule
will skip newlines, that we used %option case-insensitive, that the {ident}
rule will also match keywords like "select" so we must put the keywords BEFORE
the ident rule (because in flex, the longest match wins, and the first rule
listed in the .l file breaks ties). Finally, notice that we used the "-d" flag
to flex and the "-t" flag to bison to enable TONS of debugging output.

/* FILE:  "sql.l" */
%{
#include "sql.tab.h" /* generated by bison */
%}
%option case-insensitive nomain noyywrap nounput
%option warn nodefault outfile="sql.c"

ws              [[:space:]]+
ident           [[:alpha:]_][[:alnum:]_]+
%%

{ws}            /* SKIP */
select      return SELECT;
from        return FROM;
"*"             return '*';
","         return ',';
{ident}     return IDENT;
.|\n        return UNKNOWN;
%%
extern int yyparse();
int main(int c, char**v){ return yyparse(); }
/* END FILE sql.l */

/* FILE: sql.y */
%{
#include <stdio.h>
#include <stdlib.h>
extern int yylex();
void yyerror (char *s) { fprintf (stderr, "%s\n", s); }
%}

%token SELECT FROM IDENT UNKNOWN

%%

select:
        SELECT '*' FROM ident_list
    |   SELECT ident_list FROM ident_list
    ;

ident_list:
        IDENT
    |   ident_list ',' IDENT
    ;

%%
/* END FILE sql.y*/

Example run:

$ bison -d -t sql.y
$ flex sql.l
$ gcc -Wall -g -c sql.c
$ gcc -Wall -g -c sql.tab.c
$ gcc -Wall -g -o parse_sql sql.o sql.tab.o 
$ ./parse_sql
--(end of buffer or a NUL)
select first,last from users
--accepting rule at line 12 ("select")
--accepting rule at line 11 (" ")
--accepting rule at line 16 ("first")
--accepting rule at line 15 (",")
--accepting rule at line 16 ("last")
--accepting rule at line 11 (" ")
--accepting rule at line 13 ("from")
--accepting rule at line 11 (" ")
--accepting rule at line 16 ("users")
--(end of buffer or a NUL)
--accepting rule at line 11 ("
")
--(end of buffer or a NUL)
--EOF (start condition 0)
returned 0




__________________________________________________
Do You Yahoo!?
Yahoo! Autos - Get free new car price quotes
http://autos.yahoo.com



reply via email to

[Prev in Thread] Current Thread [Next in Thread]