词法分析文件:
语法分析文件: parser.y
- %{
- #include <stdio.h>
- #include <stdlib.h>
- void yyerror(const char*);
- #define YYSTYPE char *
- %}
- %token T_IntConstant T_Identifier
- %left '+' '-'
- %left '*' '/'
- %right U_neg
- %%
- S : Stmt
- | S Stmt
- ;
- Stmt: T_Identifier '=' E ';' { printf("pop %s\n\n", $1); }
- E : E '+' E { printf("add\n"); }
- | E '-' E { printf("sub\n"); }
- | E '*' E { printf("mul\n"); }
- | E '/' E { printf("div\n"); }
- | '-' E %prec U_neg { printf("neg\n"); }
- | T_IntConstant { printf("push %s\n", $1); }
- | T_Identifier { printf("push %s\n", $1); }
- | '(' E ')' { /* empty */ }
- ;
- %%
- int main() {
- return yyparse();
- }
makefile 文件:
测试文件: test.c
- a = 1 + 2 * ( 2 + 2 );
- b = c + d;
- e = f + 7 * 8 / 9;
这个示例对第一个示例进行了一些扩充。
makefile 里面是编译这个程序的命令,在终端输入 make 后,将编译生成可执行文件 tcc ,然后用 test.c 文件来测试一下:
test.asm 文件中的输出内容如下:
- push 1
- push 2
- push 2
- add
- mul
- add
- pop a
- push c
- push d
- add
- pop b
- push f
- push 7
- push 8
- mul
- push 9
- div
- add
- pop e
第 13 章完