-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpltoken.c
More file actions
104 lines (91 loc) · 1.91 KB
/
pltoken.c
File metadata and controls
104 lines (91 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include <assert.h>
#include "pltoken.h"
#define MAX_LEN 128
PLToken *PLTokenise(FILE *file, int stopToFirstPeriod)
{
assert(file);
int stop = 0;
int ch;
PLToken *tokens = NULL;
PLToken *first = NULL;
PLToken *t;
while ((ch = fgetc(file)) != EOF) {
while (isspace(ch)) {
ch = fgetc(file);
}
if (ch == '(') {
t = PLTokenCreate(PLTokenParenthesisOpen, NULL);
} else if (ch == ')') {
t = PLTokenCreate(PLTokenParenthesisClose, NULL);
} else if (ch == ',') {
t = PLTokenCreate(PLTokenComma, NULL);
} else if (ch == '.') {
t = PLTokenCreate(PLTokenPeriod, NULL);
stop = stopToFirstPeriod;
} else if (ch == ':') {
if ((ch = fgetc(file)) != '-') {
PLTokensFree(tokens);
return NULL;
}
t = PLTokenCreate(PLTokenArrow, NULL);
} else if (ch == '%') {
while ((ch = fgetc(file)) != '\n');
continue;
} else if (ch == EOF) {
break;
} else {
if (!isalpha(ch) && !isdigit(ch)) {
PLTokensFree(tokens);
return NULL;
}
PLTokenType type = isupper(ch) ? PLTokenVariable : PLTokenConstant;
char buf[MAX_LEN];
int i = 0;
do {
buf[i++] = ch;
ch = fgetc(file);
} while (isalpha(ch) || isdigit(ch));
buf[i] = '\0';
ungetc(ch, file);
t = PLTokenCreate(type, buf);
}
if (!tokens) {
tokens = t;
first = tokens;
} else {
tokens->next = t;
tokens = tokens->next;
}
if (stop) {
break;
}
}
return first;
}
void PLTokensFree(PLToken *token)
{
if (!token) {
return;
}
PLToken *t = token->next;
free(token->value);
free(token);
while (t) {
token = t;
t = t->next;
free(token->value);
free(token);
}
}
PLToken *PLTokenCreate(PLTokenType type, const char *lexem)
{
PLToken *t = (PLToken *)malloc(sizeof(PLToken));
t->type = type;
t->next = NULL;
t->value = NULL;
if (type == PLTokenConstant || type == PLTokenVariable) {
t->value = (char *)malloc(strlen(lexem) + 1);
strcpy(t->value, lexem);
}
return t;
}