120 likes | 329 Views
Lex & Yacc. logoLex.h. LEX. logoLex.l. logoLex.c. logoYacc.h. YACC. logoYacc.y. logoYacc.c. Lex file (.l). %{ /* Lexical Analyzer for the Grammar: S-> aSb | Ce C-> cC | d */ #include "myYacc.h" %} %% a {return TOKENA;} b {return TOKENB;}
E N D
Lex & Yacc logoLex.h LEX logoLex.l logoLex.c logoYacc.h YACC logoYacc.y logoYacc.c
Lex file (.l) %{ /* Lexical Analyzer for the Grammar: S-> aSb | Ce C-> cC | d */ #include "myYacc.h" %} %% a {return TOKENA;} b {return TOKENB;} c {return TOKENC;} d {return TOKEND;} e {return TOKENE;} %% C header stuff
Lex file (.l) %{ /* Lexical Analyzer for the Grammar: S-> aSb | Ce C-> cC | d */ #include "myYacc.h" %} %% a {return TOKENA;} b {return TOKENB;} c {return TOKENC;} d {return TOKEND;} e {return TOKENE;} %% Section Separators
Lex Flie (.l) • Lex file has 3 sections separated by %% • Section 1: Header stuff including C header (between %{ and %} • Token definition and actions • Expressed patterns in extended Regular Expression • Decide what to do with each legal token. Most common action is to store the value and return token type to the parser. • C code stuff – could contain the main function here for testing purposes, but it’s usually in the parser. Uses default main if left blank.
Lex file (.l) %{ /* Lexical Analyzer for the Grammar: S-> aSb | Ce C-> cC | d */ #include "myYacc.h" %} %% a {return TOKENA;} b {return TOKENB;} c {return TOKENC;} d {return TOKEND;} e {return TOKENE;} %% Actions in C code Token Patterns (extended R.E.)
Yacc Flie (.y) • Yacc file also has 3 sections separated by %% • Section 1: Header stuff including C header (between %{ and %} • Syntax definition and actions • Expressed syntax in context-free grammar • Decide what to do with each legal structure. • C code stuff –Uses default main if left blank. • Must be connected to the .l file in several ways.
Lex & Yacc logoLex.h logoYacc.h logoLex.c logoYacc.c main() { yyparse(); } return TokenType; yylex()
Lex & Yacc 123 logoLex.h logoYacc.h logoLex.c logoYacc.c yylval 123 yytext main() { yyparse(); } return NUMBER; yylex()
Lex & Yacc logoYacc.y yylval logoLex.l %{ #include <string.h> #define YYTYPE char* %} %token FD %token BK %token TO %token REPEAT %token END %token '[' %token ']' %token NUMBER %token ID %{ #include "logoYacc.h“ extern char * yylval; %} FD {return FD;} BK {return BK;} 0|[1-9][0-9]* { yylval = (char *) malloc(sizeof(yytext)+1); strcpy(yylval, yytext); return NUMBER;}
Lex & Yacc 123 logoYacc.y yylval logoLex.l %% S : FD NUMBER { printf(“FD %s\n”, $2);} 0|[1-9][0-9]* { yylval = (char *) malloc(sizeof(yytext)+1); strcpy(yylval, yytext); return NUMBER;} 123 yytext
Lex & Yacc • logoYacc.y S : FD NUMBER { printf(“FD: %s\n”, $2 } S $$ $1 $2 $4 $3