http://d.hatena.ne.jp/tanakaBox/20070507/1178537799 に記載されている内容をおさらいして電卓を作成する。
環境
flex --versionflex 2.5.35 Apple(flex-31)
bison --versionbison (GNU Bison) 2.3 Written by Robert Corbett and Richard Stallman. Copyright (C) 2006 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
字句解析
%{
#include <stdio.h>
#include <stdlib.h>
#include "calc.tab.h"
%}
NUMBER [0-9]+
SPACE  [\t ]
OP     [+-/*()]
CR     [\n]
OTHER  .
%%
{NUMBER} { yylval = atoi(yytext); return NUMBER; }
{OP}     { return yytext[0]; }
{CR}     { return yytext[0]; }
{SPACE}  {}
{OTHER}  { printf("そんなのしらない\n"); exit(1); }
%%flex src/calc.l構文解析
%{
#include <stdio.h>
#include <string.h>
void yyerror(const char *str)
{
        fprintf(stderr,"error: %s\n",str);
}
 
int yywrap()
{
        return 1;
} 
  
int main()
{
        yyparse();
} 
%}
%token NUMBER
%left '+' '-'
%left '*' '/'
%%
lines
	: line
	| lines line
	;
line
	: '\n'
	| ex '\n' { printf("%d\n", $1); }
	;
ex
	: NUMBER
	| '(' ex ')' { $$ = $2; }
	| ex '+' ex  { $$ = $1 + $3; }
	| ex '-' ex  { $$ = $1 - $3; }
	| ex '*' ex  { $$ = $1 * $3; }
	| ex '/' ex  { $$ = $1 / $3; }
	;
%%bison -d src/calc.y実行ファイル
.PHONY: all
all:
	-@# <YACC>
	bison -d src/calc.y
	-@# </YACC>
	-@# <LEX>
	flex src/calc.l
	-@# </LEX>
	-@# <EXE>
	cc lex.yy.c calc.tab.c -o calc
	-@# <EXE>
.PHONY: clean
clean:
	rm calc calc.tab.c calc.tab.h lex.yy.ccc lex.yy.c calc.tab.c -o calc