编译原理实验词法分析器
时间: 2023-12-01 14:04:51 浏览: 75
编译原理实验词法分析器是一个用于将源代码转换为单词符号序的程序。下面是一个简单的词法分析器的实现示例:
```c
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX_TOKEN_LEN 100
typedef enum {
KEYWORD,
IDENTIFIER,
NUMBER,
OPERATOR,
DELIMITER
} TokenType;
typedef struct {
TokenType type;
char value[MAX_TOKEN_LEN];
} Token;
int is_keyword(char* token) {
char* keywords[] = {"if", "else", "while", "for", "int", "float", "char", "return"};
int num_keywords = 8;
int i;
for (i = 0; i < num_keywords; i++) {
if (strcmp(keywords[i], token) == 0) {
return 1;
}
}
return 0;
}
int is_operator(char c) {
char* operators = "+-*/=";
int num_operators = 5;
int i;
for (i = 0; i < num_operators; i++) {
if (c == operators[i]) {
return 1;
}
}
return 0;
}
int is_delimiter(char c) {
char* delimiters = "(){}[],;";
int num_delimiters = 8;
int i;
for (i = 0; i < num_delimiters; i++) {
if (c == delimiters[i]) {
return 1;
}
}
return 0;
}
Token get_next_token(FILE* fp) {
Token token;
char c = fgetc(fp);
while (isspace(c)) {
c = fgetc(fp);
}
if (isalpha(c)) {
int i = 0;
while (isalnum(c)) {
token.value[i++] = c;
c = fgetc(fp);
}
token.value[i] = '\0';
if (is_keyword(token.value)) {
token.type = KEYWORD;
} else {
token.type = IDENTIFIER;
}
ungetc(c, fp);
} else if (isdigit(c)) {
int i = 0;
while (isdigit(c)) {
token.value[i++] = c;
c = fgetc(fp);
}
token.value[i] = '\0';
token.type = NUMBER;
ungetc(c, fp);
} else if (is_operator(c)) {
token.value[0] = c;
token.value[1] = '\0';
token.type = OPERATOR;
} else if (is_delimiter(c)) {
token.value[0] = c;
token.value[1] = '\0';
token.type = DELIMITER;
} else if (c == EOF) {
token.type = EOF;
} else {
token.type = -1;
}
return token;
}
int main() {
FILE* fp = fopen("input.txt", "r");
Token token = get_next_token(fp);
while (token.type != EOF) {
printf("%s\n", token.value);
token = get_next_token(fp);
}
fclose(fp);
return 0;
}
```
该词法分析器可以识别关键字、标识符、常数、运算符和界符。它从文件中读取源代码,并将其转换为单词符号序列,然后将每个单词符号打印到控制台上。
阅读全文