70 likes | 302 Views
Using Scanner Generator Lex. By J. H. Wang May 10, 2011. Creating a Lexical Analyzer with Lex. Lex compiler. Lex source program lex.l. lex.yy.c. C compiler. lex.yy.c. a.out. a.out (The scanner). Input stream. Sequence of tokens. To generate the scanner:
E N D
Using Scanner Generator Lex By J. H. Wang May 10, 2011
Creating a Lexical Analyzer with Lex Lex compiler Lex source program lex.l lex.yy.c C compiler lex.yy.c a.out a.out(The scanner) Input stream Sequence of tokens
To generate the scanner: • For Lex:lex <file>.lgcc lex.yy.c -o <file> -ll • For flex:flex <file>.lgcc lex.yy.c -o <file> -lfl
An Example • Patterns for tokens in the grammar • digit [0-9]digits digit+number digits (. digits)? (E [+-]? digits )?letter [A-Za-z]id letter (letter |digit)*if ifthen thenelse elserelop < | > | <= | >= | = | <> • ws (blank | tab | newline)+
Example Lex Program • %{ LT, LE, EQ, NE, GT, GE, IF, THEN, ELSE, ID, NUMBER, RELOP%}delim [ \t\n]ws {delim}+letter [A-Za-z]digit [0-9]id {letter}({letter}|{digit})*number {digit}+(\.{digit}+)?(E[+-]?{digit}+)?%%{ws} {}if { return(IF); }then { return(THEN); }else { return(ELSE); }
{id} { yylval = (int) installID(); return (ID); }{number} { yylval = (int) installNum(); return (NUMBER); }“<“ {yylval = LT; return(RELOP); }“<=“ {yylval = LE; return(RELOP); }“=“ {yylval = EQ; return(RELOP); }“<>“ {yylval = NE; return(RELOP); }“>“ {yylval = GT; return(RELOP); }“>=“ {yylval = GE; return(RELOP); }%%int installID() {}int installNum() {}