c语言实现 PASCAL 子集的词法分析程序
时间: 2024-05-02 11:17:37 浏览: 132
基于C语言实现小子集程序的词法分析【100013134】
以下是用 C 语言实现 PASCAL 子集的词法分析程序的示例代码:
```c
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX_LENGTH 100
char input[MAX_LENGTH];
int pos = 0;
typedef enum {
NONE,
ID,
NUMBER,
PLUS,
MINUS,
MUL,
DIV,
LPAREN,
RPAREN,
SEMICOLON,
ASSIGN,
END
} TokenType;
typedef struct {
TokenType type;
char value[MAX_LENGTH];
} Token;
void advance() {
pos++;
}
char peek() {
return input[pos];
}
Token get_next_token() {
Token token;
token.type = NONE;
memset(token.value, 0, sizeof(token.value));
char c = peek();
while (c != '\0') {
if (isspace(c)) {
advance();
c = peek();
continue;
}
if (isalpha(c)) {
int i = 0;
while (isalnum(c)) {
token.value[i] = c;
i++;
advance();
c = peek();
}
token.type = ID;
return token;
}
if (isdigit(c)) {
int i = 0;
while (isdigit(c)) {
token.value[i] = c;
i++;
advance();
c = peek();
}
token.type = NUMBER;
return token;
}
if (c == '+') {
token.type = PLUS;
advance();
return token;
}
if (c == '-') {
token.type = MINUS;
advance();
return token;
}
if (c == '*') {
token.type = MUL;
advance();
return token;
}
if (c == '/') {
token.type = DIV;
advance();
return token;
}
if (c == '(') {
token.type = LPAREN;
advance();
return token;
}
if (c == ')') {
token.type = RPAREN;
advance();
return token;
}
if (c == ';') {
token.type = SEMICOLON;
advance();
return token;
}
if (c == ':') {
advance();
c = peek();
if (c == '=') {
token.type = ASSIGN;
token.value[0] = ':';
token.value[1] = '=';
advance();
return token;
}
}
printf("Invalid character: %c\n", c);
token.type = END;
return token;
}
token.type = END;
return token;
}
int main() {
printf("Enter Pascal code:\n");
fgets(input, MAX_LENGTH, stdin);
Token token = get_next_token();
while (token.type != END) {
printf("Token: %s\n", token.value);
token = get_next_token();
}
return 0;
}
```
该程序实现了对 Pascal 子集中的 ID、数字、运算符、括号、分号和赋值符号进行识别。在 `main` 函数中,用户可以输入 Pascal 代码,并且使用 `get_next_token` 函数来逐个获取每个词法单元的类型和值。
阅读全文