# QT 词法语法分析
```
本学期上过编译原理的课程,课程设计要求做一个词法语法分析器,就相当于一个编译器的部分功能,正好最近也在学习QT,所以就用QT做课设,里面涉及到**sqlite数据库对种别码表信息进行增删查改,另外有修改字体,颜色,背景进行永久保存**,相关源代码在最下面,可以选择github下载链接,不需要积分。
```
[TOC]
---
## 词法分析
```
词法分析是计算机科学中将字符序列转换为单词序列的过程。进行词法分析的程序或者函数叫作词法分析器,也叫扫描器。词法分析器一般以函数的形式存在,供语法分析器调用。
词法分析是编译程序的第一个阶段且是必要阶段;词法分析的核心任务是扫描、识别单词且对识别出的单词给出定性、定长的处理;实现词法分析程序的常用途径:自动生成,手工生成。
```
**1.单词种别构成表**
| 单词符号 | 种别码 | 单词符号 | 种别码 |
| :---------------------: | :----: | :------: | :----: |
| begin | 1 | : | 17 |
| if | 2 | := | 18 |
| then | 3 | < | 20 |
| while | 4 | <> | 21 |
| do | 5 | <= | 22 |
| end | 6 | > | 23 |
| lettet(letter\|digit)* | 10 | >= | 24 |
| dight dight* | 11 | = | 25 |
| + | 13 | ; | 26 |
| — | 14 | ( | 27 |
| * | 15 | ) | 28 |
| / | 16 | # | 0 |
**2.状态转换图**
![](https://www.writebug.com/myres/static/uploads/2021/11/24/879a7b683318a4bcb614ea916bf9e208.writebug)
## 语法分析
递归下降语法分析是在每个非终结符都对应一个子程序。该子程序根据下一个输入符号来确定按照哪一个产生式进行处理,再根据该产生式的右端:
1.每遇到一个终结符,则判断当前读入的单词是否与该终结符相匹配,若匹配,再读取下一个单词继续分析;不匹配,则进行出错处理
2.每遇到一个非终结符,则调用相应的子程序语法分析器在其工作过程中,一般应完成下列的任务:
(1)给出语法分析的文法;
(2)有必要还需要将文法转成 LL(1)文法;
(3)求出 first 和 follow 集合构造预测分析表;
(4)进行语法检查,报告所发现的错误。
## 相关流程图
### **词法分析流程图**
![](https://www.writebug.com/myres/static/uploads/2021/11/24/a3133146f3f5250652d078e20433ebf2.writebug)
### **递归下降分析流程图**
![](https://www.writebug.com/myres/static/uploads/2021/11/24/534f14634459e1057598b37c9a9fb5cc.writebug)
### **语句串分析流程图**
![](https://www.writebug.com/myres/static/uploads/2021/11/24/fa11afbf5b47ec105bfcc86147cf89c3.writebug)
### **语句分析流程图**
![](https://www.writebug.com/myres/static/uploads/2021/11/24/324d0014443813cc6184a1dea80003dd.writebug)
### **表达式分析流程图**
![](https://www.writebug.com/myres/static/uploads/2021/11/24/2723e34ea4ee19bcb60aced318949269.writebug)
### **项分析流程图**
![](https://www.writebug.com/myres/static/uploads/2021/11/24/0d39584ad5011e0ed5500dbe3f7f5cd8.writebug)
### **因子分析流程图**
![](https://www.writebug.com/myres/static/uploads/2021/11/24/6439f1656c1a8ef79d86d7950c043951.writebug)
## 功能演示
### 词法分析
可识别符号对应的种别码,未识别的种别码也会显示在错误结果框中,可以将需要识别的种别码加入到种别码表中,这样词法分析就可以识别。
![](https://www.writebug.com/myres/static/uploads/2021/11/24/d5b74a6e6ae0ed0aff9809cd2f6c9e0b.writebug)
### 语法分析
可以识别语句错误,缺少括号,if 语句判断。
![](https://www.writebug.com/myres/static/uploads/2021/11/24/97c84f7117f4fb55ad6c1b8cabeb45d3.writebug)
### 字体设置
设置编辑框字体和字体大小。
![](https://www.writebug.com/myres/static/uploads/2021/11/24/52096102cef2be2e6888faf6cb72ee2f.writebug)
### 颜色设置
设置编辑框字体颜色。
![](https://www.writebug.com/myres/static/uploads/2021/11/24/157eed2a03707dedc58f2eb03d3e86e5.writebug)
### 背景设置
设置编辑框背景图片。
![](https://www.writebug.com/myres/static/uploads/2021/11/24/8e0a52366b914adb22ec8a4408e02c9d.writebug)
GitHub 下载地址:[https://github.com/ys-lucky/QtCompiler.git](https://github.com/ys-lucky/QtCompiler.git)