0 Star 0 Fork 71

Samele/compiler-homework2

forked from zren/compiler-homework2 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
lexer.c 2.09 KB
一键复制 编辑 原始数据 按行查看 历史
ac 提交于 2016-04-21 20:50 . v1
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define KEY 6
char *keyword[KEY] = {"for", "if", "then", "else", "while", "do"};
char id[1024];
int num;
int token;
void lexical(FILE *fp) {
char x = getc(fp);
char temp;
FILE *f;
int i=0;
char *array=new char[20];
f=fp;
num = 0;
strcpy(id, "\0");
if(x>='a' && x<='z')
{
array[i]=x;
for(;i<5;)
{
temp=getc(f++);
i++;
array[i]=temp;
if(array=="for")
{token=1;strcpy(id, keyword[0]);}
else if(array=="if")
{token=2;strcpy(id, keyword[1]);}
else if(array=="then")
{token=3;strcpy(id, keyword[2]);}
else if(array=="else")
{token=4;strcpy(id, keyword[3]);}
else if(array=="while")
{token=5;strcpy(id, keyword[4]);}
else if(array=="do")
{token=6;strcpy(id, keyword[5]);}
else {token=10;strcpy(id, x;}
}
}
else if(x>='0' && x<='9') {token=11;num=x-48;}
else if(x=="+") {token=13;strcpy(id, x;}
else if(x=="-") {token=14;strcpy(id, x;}
else if(x=="*") {token=15;strcpy(id, x;}
else if(x=="/") {token=16;strcpy(id, x;}
else if(x==":") {token=17;strcpy(id, x;}
else if(x==":=") {token=18;strcpy(id, x;}
else if(x=="<") {token=20;strcpy(id, x;}
else if(x=="<>") {token=21;strcpy(id, x;}
else if(x=="<=") {token=22;strcpy(id, x;}
else if(x==">") {token=23;strcpy(id, x;}
else if(x==">=") {token=24;strcpy(id, x;}
else if(x=="=") {token=25;strcpy(id, x;}
else if(x==";") {token=26;strcpy(id, x;}
else if(x=="(") {token=27;strcpy(id, x;}
else if(x==")") {token=28;strcpy(id, x;}
else if(x=="#") {token=0;strcpy(id, x;}
fp=fp++;
//process x
//process each regex here
//store the result in global variables id, num, or token
//in case of backtrack, use
//ungetc(x, fp);
}
int main(int argc, const char *argv[])
{
if(argc < 2) {
printf("insufficient args\n");
return 1;
}
FILE *fp = fopen(argv[1], "r");
do {
lexical(fp);
switch(token) {
case 10: printf("(id, %s)\n", id); break;
case 11: printf("(num, %d)\n", num); break;
case -1: printf("error!\n"); break;
default: printf("(%d, %s)\n", token, id);
}
} while(token != 0);
fclose(fp);
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/samele/compiler-homework2.git
git@gitee.com:samele/compiler-homework2.git
samele
compiler-homework2
compiler-homework2
master

搜索帮助