注:
课程:《编译技术》上机
实验一:词法语法分析器的设计与实现,生成抽象语法树。
建议使用词法语法分析程序生成工具如:LEX/FLEX , YACC/BISON等专业工具完成。
此处完成补充 自增自减 的操作
In addition: I hope that Da Karma will support my personal blog website: www.xyzsh.cn If the
article is updated, the personal website will be issued first (CSDN has a review)
I hope that children’s shoes can step on it~!
Preliminary preparation
- The supplementary char operation in the previous article has been completed
- The entire folder has been prepared for the retrospect after the magic change
Start experiment
first step
Modify the lex.l file (the lex description file gives the rules for each type of lexical unit)
- Line 47 inserts the recognition of the string ++
- Line 48 inserts the recognition of the string-
Second step
Modify the parser.y file (parser.y is the C language grammar)
- Insert the word name DPLUS DMINUS on line 35
- The 48th line defines the priority of
self-increment and self-decrement. The priority is very high, and the priority is the same as the negative sign (UMINUS) and the non-sign (NOT).
- Insert the auto-increment grammar
in lines 117-120. In order to distinguish between pre-increment and post-increment, I set two states DPLUS_BEFORE DPLUS_AFTORE
- Line 38 adds the state name
third step
Modify the ast.c file (ast.c defines the generation and output of the tree)
- Insert the output of DPLUS\DMINUS in lines 152-155.
They can share a set of output with NOT and UMINUS.
Supplement: Explain the meaning of printf("% * cCHAR:%c\n",indent,'',T->type_char);: first print indent spaces, and then print CHAR: %c
defaults to a lower level, then Move back 3 spaces
the fourth step
Modify the test.c file (test code)
- Lines 18-21 are when the test increases and decreases alone
- Line 23 is the test in the self-increasing compound statement
Result check
Run sequentially
flex lex.l
bison -d parser.y
gcc -o parser lex.yy.c parser.tab.c ast.c
parser test.c
Found garbled, use chcp 65001 to switch to UTF-8 encoding interface
Self-increment and self-decrement output is complete!
It can also be output in compound sentences!
自增自减补充完成啦!胜利就在眼前,加油呀!
Written at the end
Hope the above can help you!
If there are mistakes or different ideas, please point them out, learn from each other and make progress together!