Page 126

Modify undcl so that it does not add redundant parentheses to declarations.

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>

#define MAXTOKEN 100

/* The task is to 'Modify undcl so that it does not add redundant parentheses to
 * declarations'. I interpret this to mean that instead of *always* wrapping pointers
 * with parens, this should occur only when the pointer applies to a function () or an
 * array [], as these have higher precedence than *. */

enum { NAME = 1, PARENS, BRACKETS };

void dcl(void);
void dirdcl(void);

int gettoken(void);
int tokentype;
char token[MAXTOKEN];
char name[MAXTOKEN];
char datatype[MAXTOKEN];
char out[1000];
bool missing_paren = false;
int getch(void);
void ungetch(int);

int main()
{
	int type;
	int c1, c2;
	char *paren_fmt = "(*%s)", *default_fmt = "*%s";
	char temp[MAXTOKEN];

	while (gettoken() != EOF) {
		strcpy(out, token);
		while ((type = gettoken()) != '\n') {
			if (type == PARENS || type == BRACKETS) {
				strcat(out, token);
			} else if (type == '*') {
				char *selected_fmt = default_fmt;
				c1 = getch();
				c2 = getch();
				if (c1 == ' ' && (c2 == '(' || c2 == '[')) {
					selected_fmt = paren_fmt;
				}
				ungetch(c2);
				ungetch(c1);
				sprintf(temp, selected_fmt, out);
				strcpy(out, temp);
			} else if (type == NAME) {
				sprintf(temp, "%s %s", token, out);
				strcpy(out, temp);
			} else {
				printf("invalid input at %s\n", token);
			}
		}
		printf("%s\n", out);
	}
	return 0;
}

int gettoken(void)
{
	int c;
	char *p = token;

	if (missing_paren) {
		tokentype = ')';
		missing_paren = false;
		return tokentype;
	}

	while ((c = getch()) == ' ' || c == '\t')
		;
	if (c == '(') {
		if ((c = getch()) == ')') {
			strcpy(token, "()");
			return tokentype = PARENS;
		} else {
			ungetch(c);
			return tokentype = '(';
		}
	} else if (c == '[') {
		/* Support alphanum and underscore inside brackets */
		for (*p = c; isalnum(*(++p) = getch()) || *p == '_';)
			;
		/* Recover if end bracket missing */
		if (*p != ']') {
			ungetch(*p);
			*p = ']';
		}
		*(++p) = '\0';
		return tokentype = BRACKETS;
	} else if (c == ']') {
		*p++ = '[';
		*p++ = ']';
		*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;
	}
}

#define BUFSIZE 100
char buf[BUFSIZE];
int bufp = 0;

int getch(void)
{
	return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c)
{
	if (bufp >= BUFSIZE) {
		printf("ungetch: too many characters\n");
	} else {
		buf[bufp++] = c;
	}
}