编译原理词法分析C语言代码
时间: 2023-11-29 11:46:15 浏览: 34
以下是一个简单的C语言词法分析器代码示例:
```c
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAXTOKENLEN 100
enum { NAME, PARENS, BRACKETS };
void dcl(void);
void dirdcl(void);
int gettoken(void);
int tokentype; // 最后一个记号的类型
char token[MAXTOKENLEN]; // 最后一个记号的字符串
char name[MAXTOKENLEN]; // 标识符名
char datatype[MAXTOKENLEN]; // 数据类型为char、int等
char out[1000]; // 输出串
int main()
{
while (gettoken() != EOF) { // 直到输入结束
strcpy(datatype, token); // 是数据类型
out[0] = '\0';
dcl(); // 分析该行剩余部分
if (tokentype != '\n') {
printf("syntax error\n");
}
printf("%s: %s %s\n", name, out, datatype);
}
return 0;
}
// 返回下一个标记
int gettoken(void)
{
int c, getch(void);
void ungetch(int);
char *p = token;
while ((c = getch()) == ' ' || c == '\t')
;
if (c == '(') {
if ((c = getch()) == ')') {
strcpy(token, "()");
return tokentype = PARENS;
} else {
ungetch(c);
return tokentype = '(';
}
} else if (c == '[') {
for (*p++ = c; (*p++ = getch()) != ']'; )
;
*p = '\0';
return tokentype = BRACKETS;
} else if (isalpha(c)) {
for (*p++ = c; isalnum(c = getch()); )
*p++ = c;
*p = '\0';
ungetch(c);
return tokentype = NAME;
} else {
return tokentype = c;
}
}
// 分析一个声明
void dcl(void)
{
int ns;
for (ns = 0; gettoken() == '*'; ) // 统计字符 * 的个数
ns++;
dirdcl();
while (ns-- > 0) {
strcat(out, " pointer to");
}
}
// 分析一个直接声明
void dirdcl(void)
{
int type;
if (tokentype == '(') { // 形式为 ( dcl )
dcl();
if (tokentype != ')') {
printf("error: missing )\n");
}
} else if (tokentype == NAME) { // 变量名
strcpy(name, token);
} else {
printf("error: expected name or (dcl)\n");
}
while ((type = gettoken()) == PARENS || type == BRACKETS) {
if (type == PARENS) {
strcat(out, " function returning");
} else {
strcat(out, " array");
strcat(out, token);
strcat(out, " of");
}
}
}
```