Flex と Bison - 実習編 -
description
Transcript of Flex と Bison - 実習編 -
-
FlexBison--
-
FlexBisonHTMLPascal
-
Flex
-
Flex
%%
%%
-
Flex%{C%}%%Flex
%%C
-
FlexgccFlexProgramLex.yy.ca.exe*
-
calc
lexer.l Flex (Fastlex ) (token) C1) 2) 3)C
parser.yBisonC
-
% bison -d parser.y% flex lexer.l% gcc -o calc parser.tab.c -lfl% ./calc.exe 1: 1 + 2 3 2: (1+2)*4 12 3:
-
lexer.l%{#include"parser.tab.h"#includeinttokenValue = NONE;intlineNumber = 1;%}%%[ \t]+{ /* do nothing */ }\n{ return(ENDOFLINE); }[0-9]+{ tokenValue = strtol(yytext, NULL, 10); return(NUMBER); }"+"{ return(PLUS); }"-"{ return(MINUS); }"*"{ return(MULTIPLY); }"/"{ return(DIVIDE); }"("{ return(LPAR); }")"{ return(RPAR); }.{ tokenValue = yytext[0]; return(NONE); }%%
-
(parser.y)%{extern int tokenValue;extern int lineNumber;#define prompt printf("\n%5d : ", ++lineNumber)%}
%start lines%token PLUS MINUS MULTIPLY DIVIDE LPAR RPAR NONE ENDOFLINE NUMBER
%%lines:/* null string epsylon */|expression { printf("%d", $1); prompt; } ENDOFLINE lines;
expression:expression PLUS term { $$ = $1 + $3; }|expression MINUS term { $$ = $1 - $3; }|term { $$ = $1; };
term:term MULTIPLYfactor { $$ = $1 * $3; }|term DIVIDEfactor { $$ = $1 / $3; }|factor { $$ = $1 };
factor:LPAR expression RPAR{ $$ = $2; }|NUMBER{ $$ = tokenValue; }|MINUS NUMBER { $$ = -tokenValue; };
%%
#include"lex.yy.c"
main(){printf("%5d : ", lineNumber);yyparse();return 0;}
yyerror(char *s){printf("%s\n", s);}