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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAXTOKEN 100
#define OUTLEN 1000
#define MAXBUFF 100
enum { NAME, PARENS, BRACKETS };
enum { NO, YES };
void err(char *s);
void errmsg(char *s);
void dcl(void);
void dirdcl(void);
int gettoken(void);
int tokentype;
int prevtoken;
char token[MAXTOKEN];
char name[MAXTOKEN];
char datatype[MAXTOKEN];
char out[OUTLEN];
char buff[MAXBUFF];
static size_t top;
void errmsg(char *s)
{
printf("err: %s\n", s);
prevtoken = YES;
}
void err(char *s)
{
printf("fatal error: %s\n", s);
exit(1);
}
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();
if (tokentype != ')')
errmsg("missing )");
} else if (tokentype == NAME) {
strcpy(name, token);
} else {
errmsg("expected name or (dcl)");
}
while ((type = gettoken()) == PARENS || type == BRACKETS) {
if (type == PARENS) {
strcat(out, " function returning");
} else {
strcat(out, " array");
strcat(out, token);
strcat(out, " of");
}
}
}
int gettoken(void)
{
char c, *p = token;
char getch(void);
void ungetch(char);
if (prevtoken == YES) {
prevtoken = NO;
return tokentype;
}
while(isblank(c = getch()))
;
if (c == '/') { /* ignore comments */
if ((c = getch()) == '/') {
while ((c = getch()) != '\n')
;
} else if (c == '*') {
while (getch() != '*' || (c = getch()) != '/')
if (c == '*')
ungetch('*');
return gettoken();
} else {
ungetch(c);
c = '/';
}
}
if (c == '(') {
if ((c = getch()) == ')') {
strcpy(token, "()");
return tokentype = PARENS;
} else {
ungetch(c);
return tokentype = '(';
}
} else if (c == '[') {
for (*p++ = '['; (*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 ungetch(char c)
{
if (top < MAXBUFF)
buff[top++] = c;
else
err("stack overflow");
}
char getch(void)
{
return (top > 0) ? buff[--top] : getchar();
}
int main(void)
{
while (gettoken() != EOF) {
if (tokentype == '\n') /* skip empty lines */
continue;
strcpy(datatype, token);
out[0] = '\0';
dcl();
if (tokentype != '\n')
printf("synatx error\n");
printf("%s: %s %s\n", name, out, datatype);
}
return 0;
}
|