|
| 1 | +#include <stdio.h> |
| 2 | +#include <string.h> |
| 3 | +#include <ctype.h> |
| 4 | +#include "buffer.h" |
| 5 | + |
| 6 | +#define MAXTOKEN 100 |
| 7 | + |
| 8 | +enum { NAME, PARENS, BRACKETS }; |
| 9 | + |
| 10 | +void dcl(void); |
| 11 | +void dirdcl(void); |
| 12 | + |
| 13 | +int gettoken(void); |
| 14 | +int tokentype; /* type of last token */ |
| 15 | +char token[MAXTOKEN]; /* last token string */ |
| 16 | +char name[MAXTOKEN]; /* indetifier name */ |
| 17 | +char datatype[MAXTOKEN]; /* data type = char, int, etc. */ |
| 18 | +char out[1024]; /* output string */ |
| 19 | + |
| 20 | +int main() { |
| 21 | + while (gettoken() != EOF) { /* 1st token on line */ |
| 22 | + strcpy(datatype, token); /* is the datatype */ |
| 23 | + out[0] = '\0'; |
| 24 | + dcl(); /* parse rest of the line */ |
| 25 | + if (tokentype != '\n') |
| 26 | + printf("syntax error\n"); |
| 27 | + printf("%s: %s %s\n", name, out, datatype); |
| 28 | + } |
| 29 | + return 0; |
| 30 | +} |
| 31 | + |
| 32 | +/* dcl: parse a declarator */ |
| 33 | +void dcl(void) { |
| 34 | + int ns; |
| 35 | + |
| 36 | + for (ns = 0; gettoken() == '*'; ) /* count *'s */ |
| 37 | + ns++; |
| 38 | + dirdcl(); |
| 39 | + while (ns-- > 0) |
| 40 | + strcat(out, " pointer to"); |
| 41 | +} |
| 42 | + |
| 43 | +/* dirdcl: parse a direct declarator */ |
| 44 | +void dirdcl(void) { |
| 45 | + int type; |
| 46 | + |
| 47 | + if (tokentype == '(') { /* ( dcl ) */ |
| 48 | + dcl(); |
| 49 | + if (tokentype != ')') |
| 50 | + printf("error: missing )\n"); |
| 51 | + } else if (tokentype == NAME) /* variable name */ |
| 52 | + strcpy(name, token); |
| 53 | + else |
| 54 | + printf("error: expected name or (dcl)\n"); |
| 55 | + while ((type = gettoken()) == PARENS || type == BRACKETS) |
| 56 | + if (type == PARENS) |
| 57 | + strcat(out, " function returning"); |
| 58 | + else { |
| 59 | + strcat(out, " array"); |
| 60 | + strcat(out, token); |
| 61 | + strcat(out, " of"); |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +int gettoken(void) /* return next token */ { |
| 66 | + int c, getch(void); |
| 67 | + void ungetch(int); |
| 68 | + char *p = token; |
| 69 | + |
| 70 | + while((c = getch()) == ' ' || c == '\t') |
| 71 | + ; |
| 72 | + if (c == '(') { |
| 73 | + if ((c = getch()) == ')') { |
| 74 | + strcpy(token, "()"); |
| 75 | + return tokentype = PARENS; |
| 76 | + } else { |
| 77 | + ungetch(c); |
| 78 | + return tokentype = '('; |
| 79 | + } |
| 80 | + } else if (c == '[') { |
| 81 | + for (*p++ = c; (*p++ = getch()) != ']'; ) |
| 82 | + ; |
| 83 | + *p = '\0'; |
| 84 | + return tokentype = BRACKETS; |
| 85 | + } else if (isalpha(c)) { |
| 86 | + for (*p++ = c; isalnum(c = getch()); ) |
| 87 | + *p++ = c; |
| 88 | + *p = '\0'; |
| 89 | + ungetch(c); |
| 90 | + return tokentype = NAME; |
| 91 | + } else |
| 92 | + return tokentype = c; |
| 93 | +} |
0 commit comments