Flex와 Bison을 이용한 기본적인 계산기 Program으로 Lex와 Yacc의 개념을 익히기에 가장 좋은것 같아 분석하기로 했다.
- 관련소스 download
1.1 기본소스 구성
기본소스를 이해하기 전의 File구성과 Makefile의 구성이해하고 GCC를 사용하기 전까지의
절차를 정확하게 이해하고 이를 이해해보자.
상위 소스를 보면 아래와 같이 Flex과 Bison을 위한 File 밖에 존재하지 않는다.
$ tree . ├── LICENSE ├── Makefile ├── README ├── calc.l // flex file └── calc.y // bison file
기본 Makefile의 구성을 알아보고 기본동작이 어떻게 동작이 되는 지 알아보자.
$ vi Makefile all: calc calc.tab.c calc.tab.h: calc.y bison -d calc.y lex.yy.c: calc.l calc.tab.h flex calc.l calc: lex.yy.c calc.tab.c calc.tab.h gcc -o calc calc.tab.c lex.yy.c clean: rm calc calc.tab.c lex.yy.c calc.tab.h
Make를 실행을 하면 바로 calc이라는 프로그램이 나오지만, 과정이 어떻게 되어 나오는지 정확하게 알아보자
$ flex calc.l // lex.yy.c 생성확인 $ bison -d calc.y // calc.tab.c , calc.tab.h 생성확인 $ gcc -o calc calc.tab.c lex.yy.c // GCC를 이용하여 C File을 빌드
2. Flex 기본특징
Flex의 기본구조적인 특징은 거의 유사하며 메뉴얼을 보면서를 이해를 하자
- definitions
name definition
- rules
definition action
definitions %% rules %% user code
Input Format 과 Pattern
http://dinosaur.compilertools.net/flex/flex_6.html#SEC6
http://dinosaur.compilertools.net/flex/flex_7.html
Rule의 Action
http://dinosaur.compilertools.net/flex/flex_9.html
2.1 계산기 Flex File 분석
- calc.l
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Refer to https://github.com/meyerd/flex-bison-example | |
Definitions | |
C코드 삽입시 %{, }% 기호 | |
*/ | |
%option noyywrap // flex | |
%{ | |
#include <stdio.h> | |
#define YY_DECL int yylex() | |
#include "calc.tab.h" | |
%} | |
/* | |
Rules | |
Pattern과 Action으로 표현이되어짐 | |
C코드는 {, }로 감싸서 표시함 | |
*/ | |
%% | |
[ \t] ; // ignore all whitespace | |
[0-9]+\.[0-9]+ {yylval.fval = atof(yytext); return T_FLOAT;} | |
[0-9]+ {yylval.ival = atoi(yytext); return T_INT;} | |
\n {return T_NEWLINE;} | |
"+" {return T_PLUS;} | |
"-" {return T_MINUS;} | |
"*" {return T_MULTIPLY;} | |
"/" {return T_DIVIDE;} | |
"(" {return T_LEFT;} | |
")" {return T_RIGHT;} | |
"exit" {return T_QUIT;} | |
"quit" {return T_QUIT;} | |
%% | |
댓글 없음 :
댓글 쓰기