Flex と Bison - 実習編 -

download Flex と Bison - 実習編 -

If you can't read please download the document

description

Flex と Bison - 実習編 -. 東京工科大学 コンピュータサイエンス学部 亀田弘之. 内容. 実例紹介 基礎練習 Flex と Bison の書き方・実行手順 実習1 HTML のタグを抜き出す 実習2 電卓作成 実践的演習 Pascal パーザ作成. 1.実例紹介. 2.基礎練習. Flex の書き方・実行手順. Flex 書き方. %% %%. Flex 書き方. 各種定義 %{ C 言語のコード %} %% Flex の記述 パターン アクション の列 %% C 言語のコード. 実行手順. ライブラリ(fl). - PowerPoint PPT Presentation

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);}