C语言子集的词法分析器

本文档介绍了使用C++实现C语言子集的词法分析器,目标是识别关键字、标识符、分界符和运算符。详细阐述了代码设计思路,包括输入输出格式的设定、预处理过程,以及利用有穷自动机进行单词分析的方法。
摘要由CSDN通过智能技术生成

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; 
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值