Compilation principle (4)-self-increase and self-decrease

注:
课程:《编译技术》上机
实验一:词法语法分析器的设计与实现,生成抽象语法树。
建议使用词法语法分析程序生成工具如: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
  1. The supplementary char operation in the previous article has been completed
  2. The entire folder has been prepared for the retrospect after the magic change
    Insert picture description here
Start experiment
first step

Modify the lex.l file (the lex description file gives the rules for each type of lexical unit)

  1. Line 47 inserts the recognition of the string ++
  2. Line 48 inserts the recognition of the string-
    Insert picture description here
Second step

Modify the parser.y file (parser.y is the C language grammar)

  1. Insert the word name DPLUS DMINUS on line 35
    Insert picture description here
  2. 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 picture description here
  3. 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
    Insert picture description here
  4. Line 38 adds the state name
    Insert picture description here
third step

Modify the ast.c file (ast.c defines the generation and output of the tree)

  1. Insert the output of DPLUS\DMINUS in lines 152-155.
     They can share a set of output with NOT and UMINUS.
    Insert picture description here

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)

  1. Lines 18-21 are when the test increases and decreases alone
  2. Line 23 is the test in the self-increasing compound statement
    Insert picture description here
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

Insert picture description here
 Found garbled, use chcp 65001 to switch to UTF-8 encoding interface
Insert picture description here

 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!

Guess you like

Origin blog.csdn.net/zsh1184528359/article/details/109635301