码迷,mamicode.com
首页 > 其他好文 > 详细

词法分析实战

时间:2014-12-17 00:18:57      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:编译   词法分析   token   

题目:

在这部分中,你将使用图转移算法手工实现一个小型的词法分析器。
* 分析器的输入:存储在文本文件中的字符序列,字符取自ASCII字符集。文件中可能包括四种记号:关键字if、符合C语言标准的标识符、空格符、回车符\n。
* 分析器的输出:打印出所识别的标识符的种类、及行号、列号信息。

根据题目的要求,定义如下的Token类:

enum TokenType{
TT_ID,
TT_IF
};

class Token {
public:
Token(){}
Token(TokenType _t, string _n, int _l, int _c) { mType = _t; mName = _n; mLine = _l; mColumn = _c; }
~Token(){}
string toString();
TokenType mType;
string mName;
int mLine;
int mColumn;
};

重点实现获取Token的方法:

Token* nextToken(string& input)
{
if (input.empty()) {
return NULL;
}
string name;
int i = 0;
if (input[i] == ‘ ‘) {
input = input.substr(1);
gColumn += 1;
return nextToken(input);
}
else if (input[i] == ‘\n‘) {
input = input.substr(1);
gLine += 1;
gColumn = 1;
return nextToken(input);
}
else if (input[i] == ‘i‘) {
i++;
name.append("i");
if (input[i] == ‘f‘) {
i++;
name.append("f");
while ((input[i] >= ‘a‘ && input[i] <= ‘z‘) ||
(input[i] >= ‘A‘ && input[i] <= ‘Z‘) ||
(input[i] >= ‘0‘ && input[i] <= ‘9‘) || input[i] == ‘_‘) {
name.append(input.substr(i, 1));
i++;
}
if (name.compare("if") == 0) {
input = input.substr(i);
Token *token = new Token(TT_IF, "", gLine, gColumn);
gColumn += i;
return token;
}
else {
input = input.substr(i);
Token *token = new Token(TT_ID, name, gLine, gColumn);
gColumn += i;
return token;
}
}
else {
while ((input[i] >= ‘a‘ && input[i] <= ‘z‘) ||
(input[i] >= ‘A‘ && input[i] <= ‘Z‘) ||
(input[i] >= ‘0‘ && input[i] <= ‘9‘) || input[i] == ‘_‘) {
name.append(input.substr(i, 1));
i++;
}
input = input.substr(i);
Token *token = new Token(TT_ID, name, gLine, gColumn);
gColumn += i;
return token;
}
}
else if ((input[i] >= ‘a‘ && input[i] <= ‘z‘) ||
(input[i] >= ‘A‘ && input[i] <= ‘Z‘) || input[i] == ‘_‘) {
i++;
name.append(input.substr(0, 1));
while ((input[i] >= ‘a‘ && input[i] <= ‘z‘) ||
(input[i] >= ‘A‘ && input[i] <= ‘Z‘) ||
(input[i] >= ‘0‘ && input[i] <= ‘9‘) || input[i] == ‘_‘) {
name.append(input.substr(i, 1));
i++;
}
input = input.substr(i);
Token *token = new Token(TT_ID, name, gLine, gColumn);
gColumn += i;
return token;
}
else {
input = input.substr(1);
gColumn += 1;
return nextToken(input);
}
}

代码比较挫,不多说了,感兴趣的自己看吧。


词法分析实战

标签:编译   词法分析   token   

原文地址:http://blog.csdn.net/booirror/article/details/41972211

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!