词法分析文件:

    语法分析文件: parser.y

    1. %{
    2. #include <stdio.h>
    3. #include <stdlib.h>
    4. void yyerror(const char*);
    5. #define YYSTYPE char *
    6. %}
    7.  
    8. %token T_IntConstant T_Identifier
    9.  
    10. %left '+' '-'
    11. %left '*' '/'
    12. %right U_neg
    13.  
    14. %%
    15.  
    16. S : Stmt
    17. | S Stmt
    18. ;
    19.  
    20. Stmt: T_Identifier '=' E ';' { printf("pop %s\n\n", $1); }
    21.  
    22. E : E '+' E { printf("add\n"); }
    23. | E '-' E { printf("sub\n"); }
    24. | E '*' E { printf("mul\n"); }
    25. | E '/' E { printf("div\n"); }
    26. | '-' E %prec U_neg { printf("neg\n"); }
    27. | T_IntConstant { printf("push %s\n", $1); }
    28. | T_Identifier { printf("push %s\n", $1); }
    29. | '(' E ')' { /* empty */ }
    30. ;
    31.  
    32. %%
    33.  
    34. int main() {
    35. return yyparse();
    36. }

    makefile 文件:

    测试文件: test.c

    1. a = 1 + 2 * ( 2 + 2 );
    2. b = c + d;
    3. e = f + 7 * 8 / 9;

    这个示例对第一个示例进行了一些扩充。

    makefile 里面是编译这个程序的命令,在终端输入 make 后,将编译生成可执行文件 tcc ,然后用 test.c 文件来测试一下:

    test.asm 文件中的输出内容如下:

    1. push 1
    2. push 2
    3. push 2
    4. add
    5. mul
    6. add
    7. pop a
    8.  
    9. push c
    10. push d
    11. add
    12. pop b
    13.  
    14. push f
    15. push 7
    16. push 8
    17. mul
    18. push 9
    19. div
    20. add
    21. pop e

    第 13 章完