C语言子集的词法分析器实现
1 实习目标
这次将使用C++ 实现C语言子集的词法分析器,该词法分析器能够识别:
-各种关键字,包括while,for,switch,case,if,else
-标识符:由下划线或字母开头,跟着字母,数字或下划线
-各种分界符:包括分号; 括号()以及花括号{}
-运算符:包括< ,<=, >,>= , ==,= , +,-,*,/
下面为产生所涉及单词符号的文法的产生式:
-1) 标识符文法
Id→letter rid | _rid
rid→letter rid | _rid | digit rid| ε
-2) 无符号整数文法
digits→digit rdigit
rdigit→digit rdigit | ε
-3) 关系运算符和算术运算符的文法
Op→* | + | -|
2 代码设计思路
2.1 输入输出格式和预处理
输入: 从文件中读取字符,以字符数组保存源代码。用两个索引,分别指向当前单词的开头和搜索到的末尾。
输出: 输出一个Pair结构体,存储的是单词的种别编码和单词自身值
`预处理:我们需要定义单词的种别编码以及缓冲区的大小等,具体如下:
/*单词符号的种别编码*/
const int _while = 1;
const int _for = 2;
const int _if = 3;
const int _else = 4;
const int _switch = 5;
const int _case = 6;
const int _id = 7;
const int _int = 8;
const int _digital = 9;
const int _star = 10; // *
const int _div = 11; // /
const int _plus = 12; // +
const int _minus = 13; // -
const int _assign = 14; // =
const int _relop_lt = 15; // <
const int _relop_le = 16; // <=
const int _relop_rt = 17; // >
const int _relop_re = 18; // >=
const int _relop_eq = 19;