c语言小子集,C语言小子集的词法分析程序
时间: 2023-10-05 19:08:06 浏览: 49
C语言小子集是指C语言的子集,只包含C语言的一部分语法。下面是一个简单的C语言小子集的词法分析程序示例:
```c
#include <stdio.h>
#include <ctype.h>
#define MAX_LEN 100
enum Token_Type {
TOKEN_INVALID,
TOKEN_IDENTIFIER,
TOKEN_NUMBER,
TOKEN_PLUS,
TOKEN_MINUS,
TOKEN_MULTIPLY,
TOKEN_DIVIDE,
TOKEN_ASSIGN,
TOKEN_SEMICOLON,
TOKEN_LPAREN,
TOKEN_RPAREN,
};
struct Token {
enum Token_Type type;
char value[MAX_LEN + 1];
};
int is_keyword(char *str) {
char *keywords[] = {"int", "float", "double", "char", "if", "else", "while"};
int num_keywords = sizeof(keywords) / sizeof(char *);
for (int i = 0; i < num_keywords; i++) {
if (strcmp(str, keywords[i]) == 0) {
return 1;
}
}
return 0;
}
int is_operator(char c) {
char *operators = "+-*/=";
int num_operators = strlen(operators);
for (int i = 0; i < num_operators; i++) {
if (c == operators[i]) {
return 1;
}
}
return 0;
}
int is_digit(char c) {
return isdigit(c);
}
int is_alpha(char c) {
return isalpha(c);
}
int is_alnum(char c) {
return isalnum(c);
}
int is_space(char c) {
return isspace(c);
}
struct Token get_next_token(char *input) {
struct Token token = {TOKEN_INVALID, ""};
int len = strlen(input);
int i = 0;
while (i < len) {
if (is_operator(input[i])) {
if (input[i] == '+') {
token.type = TOKEN_PLUS;
} else if (input[i] == '-') {
token.type = TOKEN_MINUS;
} else if (input[i] == '*') {
token.type = TOKEN_MULTIPLY;
} else if (input[i] == '/') {
token.type = TOKEN_DIVIDE;
} else if (input[i] == '=') {
token.type = TOKEN_ASSIGN;
}
strncpy(token.value, input + i, 1);
i++;
break;
} else if (is_digit(input[i])) {
token.type = TOKEN_NUMBER;
int j = i;
while (j < len && is_digit(input[j])) {
j++;
}
strncpy(token.value, input + i, j - i);
token.value[j - i] = '\0';
i = j;
break;
} else if (is_alpha(input[i])) {
token.type = TOKEN_IDENTIFIER;
int j = i;
while (j < len && is_alnum(input[j])) {
j++;
}
strncpy(token.value, input + i, j - i);
token.value[j - i] = '\0';
if (is_keyword(token.value)) {
token.type = TOKEN_IDENTIFIER;
}
i = j;
break;
} else if (is_space(input[i])) {
i++;
continue;
} else if (input[i] == ';') {
token.type = TOKEN_SEMICOLON;
strncpy(token.value, input + i, 1);
i++;
break;
} else if (input[i] == '(') {
token.type = TOKEN_LPAREN;
strncpy(token.value, input + i, 1);
i++;
break;
} else if (input[i] == ')') {
token.type = TOKEN_RPAREN;
strncpy(token.value, input + i, 1);
i++;
break;
} else {
token.type = TOKEN_INVALID;
strncpy(token.value, input + i, 1);
i++;
break;
}
}
return token;
}
int main() {
char input[MAX_LEN + 1];
printf("Enter input: ");
fgets(input, MAX_LEN + 1, stdin);
struct Token token;
do {
token = get_next_token(input);
printf("Type: %d, Value: %s\n", token.type, token.value);
strncpy(input, input + strlen(token.value), MAX_LEN - strlen(token.value) + 1);
} while (token.type != TOKEN_INVALID);
return 0;
}
```
这个程序可以解析简单的C语言小子集的表达式,包括标识符、数字、加减乘除运算符和赋值运算符等。它使用了一个`Token`结构体表示词法单元,以及`get_next_token`函数来解析输入字符串并返回下一个词法单元。在`main`函数中,我们可以循环调用`get_next_token`函数来逐个解析输入字符串中的词法单元,并输出它们的类型和值。