注:
课程:《编译技术》上机
实验一:词法语法分析器的设计与实现,生成抽象语法树。
建议使用词法语法分析程序生成工具如:LEX/FLEX , YACC/BISON等专业工具完成。
此处完成补充 for循环 的操作
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 I 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)
- Insert recognition of the string for in line 37
- Insert recognition of the string break in line 38
- Line 39 inserts the recognition of the string continue
Second step
Modify the parser.y file (parser.y is the C language grammar)
- Line 36 inserts the word Fame FOR BREAK CONTINUE
- Modify the stmt line 92 and insert the for statement to
explain that Stmt refers to a statement. The for loop as a whole is counted as a statement. Define FOR LP Def Exp SEMI Exp RP Stmt here
(对照着for(int a=0;a<10;a++){
printf(" %d ",a);}来看)
LP是左括号,
Def是变量定义语句,因为Def包含分号;,所以下一个直接接上了Exp
Exp是复合表达式/语句(不带分号;)
SEMI是分号
又来一个EXP,a++可以看做是一个复合表达式的
Rp是右括号
Stmt,我想用的是Stmt:Compst这个文法,
Compst是函数体,有大括号包起来的变量定义列表+语句列表
{
$$=mknode(4,FOR,yylineno,$3,$4,$6,$8);}的含义
mknode是创建子节点的函数,
4表示创建4个节点
FOR是该文法的标识(type)
yylineno是当前行数
$3,$4,$6,$8分别对应Def Exp Exp Stmt(几个非终结符)
- Insert break and continue grammar in lines 125-126. The
terminator does not need to create child nodes, so the first parameter of mknode is 0
third step
Modify the ast.c file (ast.c defines the generation and output of the tree)
- The output of inserting for in line 83
does not need to be explained. Each sentence is to go with the flow.
First output the For loop name, which is the parent node, and then there are four child nodes, each of which is indent+3
and indent+6 Is the internal definition of the child node, is the child node of the child node
- Insert the output of break and contiue on line 93
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 16-19 are testing the for loop
- Line 18 is the test break
- The 25th is the test continue
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
I found garbled characters, use chcp 65001 to switch to the UTF-8 encoding interface
for loop output is complete!
Break output is complete!
continute output is complete!
 for循环补充完成啦!有没有感觉自己又会了hhhhhh
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!