[comp.sources.amiga] v02i054: cdecl - C & C++ declaration composer/decoder, Part01/03

page@swan.ulowell.edu (Bob Page) (11/05/88)

Submitted-by: finkel@taurus.bitnet (Udi Finkelstein)
Posting-number: Volume 2, Issue 54
Archive-name: languages/cdecl.1

Cdecl is a program for encoding and decoding ANSI C (C++) type-declarations.

#	This is a shell archive.
#	Remove everything above and including the cut line.
#	Then run the rest of the file through sh.
#----cut here-----cut here-----cut here-----cut here----#
#!/bin/sh
# shar:    Shell Archiver
#	Run the following text with /bin/sh to create:
#	cdecl.c
#	cdgram.y
#	cdecl.1
# This archive created: Fri Nov  4 18:00:14 1988
cat << \SHAR_EOF > cdecl.c
/*
 * cdecl - ANSI C and C++ declaration composer & decoder
 *
 *	originally written
 *		Graham Ross
 *		once at tektronix!tekmdp!grahamr
 *		now at Context, Inc.
 *
 *	modified to provide hints for unsupported types
 *	added argument lists for functions
 *	added 'explain cast' grammar
 *	added #ifdef for 'create program' feature
 *		???? (sorry, I lost your name and login)
 *
 *	conversion to ANSI C
 *		David Wolverton
 *		ihnp4!houxs!daw
 *
 *	merged D. Wolverton's ANSI C version w/ ????'s version
 *	added function prototypes
 *	added C++ declarations
 *	made type combination checking table driven
 *	added checks for void variable combinations
 *	made 'create program' feature a runtime option
 *	added file parsing as well as just stdin
 *	added help message at beginning
 *	added prompts when on a TTY or in interactive mode
 *	added getopt() usage
 *	added -a, -r, -p, -c, -d, -D, -V, -i and -+ options
 *	delinted
 *	added #defines for those without getopt or void
 *	added 'set options' command
 *	added 'quit/exit' command
 *	added synonyms
 *		Tony Hansen
 *		attmail!tony, ihnp4!pegasus!hansen
 *
 *	added extern, register, static
 *	added links to explain, cast, declare
 *	separately developed ANSI C support
 *		Merlyn LeRoy
 *		merlyn@rose3.rosemount.com
 *
 *	merged versions from LeRoy
 *	added tmpfile() support
 *	allow more parts to be missing during explanations
 *		Tony Hansen
 *		attmail!tony, ihnp4!pegasus!hansen
 */

char cdeclsccsid[] = "@(#)cdecl.c	2.4 3/31/88";

#include <stdio.h>
#include <ctype.h>
#ifdef AMIGA

char *strcat(), *strncat(), *strcpy(), *strncpy(), index(), rindex();
char *strchr(), *strrchr(), *strpbrk(), *strtok();
int strcmp(), strncmp(), strlen(), strspn(), strcspn();

char *malloc();
extern free(), exit(), perror();

#include <errno.h>
#else /* AMIGA not defined */
#if __STDC__ || defined(DOS)
# include <stdlib.h>
# include <stddef.h>
# include <string.h>
# include <stdarg.h>
#else
# ifndef NOVARARGS
#  include <varargs.h>
# endif /* ndef NOVARARGS */
char *malloc();
void free(), exit(), perror();
# ifdef BSD
#  include <strings.h>
   extern int errno;
#  define strrchr rindex
#  define NOTMPFILE
# else
#  include <string.h>
#  include <errno.h>
# endif /* BSD */
# ifdef NOVOID
#  define void int
# endif /* NOVOID */
#endif /* __STDC__ || DOS */

#endif /* AMIGA */

#define	MB_SHORT	0001
#define	MB_LONG		0002
#define	MB_UNSIGNED	0004
#define MB_INT		0010
#define MB_CHAR		0020
#define MB_FLOAT	0040
#define MB_DOUBLE	0100
#define MB_VOID		0200
#define	MB_SIGNED	0400

#define NullCP ((char*)NULL)
#ifdef dodebug
# define Debug(x) do { if (DebugFlag) (void) fprintf x; } while (0)
#else
# define Debug(x) /* nothing */
#endif

#if __STDC__
  char *ds(char *), *cat(char *, ...), *visible(int);
  int getopt(int,char **,char *);
  int main(int, char **);
  int yywrap(void);
  int dostdin(void);
  void mbcheck(void), dohelp(void), usage(void);
  void prompt(void), doprompt(void), noprompt(void);
  void unsupp(char *, char *);
  void notsupported(char *, char *, char *);
  void yyerror(char *);
  void doset(char *);
  void dodeclare(char*, char*, char*, char*, char*);
  void docast(char*, char*, char*, char*);
  void dodexplain(char*, char*, char*, char*);
  void docexplain(char*, char*, char*, char*);
  void setprogname(char *);
  int dotmpfile(int, char**), dofileargs(int, char**);
#else
  char *ds(), *cat(), *visible();
  int getopt();
  void mbcheck(), dohelp(), usage();
  void prompt(), doprompt(), noprompt();
  void unsupp(), notsupported();
  void yyerror();
  void doset(), dodeclare(), docast(), dodexplain(), docexplain();
  void setprogname();
  int dotmpfile(), dofileargs();
#endif /* __STDC__ */
  FILE *tmpfile();

/* variables used during parsing */
unsigned modbits = 0;
int arbdims = 1;
char *savedname = 0;
char unknown_name[] = "unknown_name";
char prev = 0;		/* the current type of the variable being examined */
			/*    values	type				   */
			/*	p	pointer				   */
			/*	r	reference			   */
			/*	f	function			   */
			/*	a	array (of arbitrary dimensions)    */
			/*	A	array with dimensions		   */
			/*	n	name				   */
			/*	v	void				   */
			/*	s	struct | class			   */
			/*	t	simple type (int, long, etc.)	   */

/* options */
int RitchieFlag = 0;		/* -r, assume Ritchie PDP C language */
int MkProgramFlag = 0;		/* -c, output {} and ; after declarations */
int PreANSIFlag = 0;		/* -p, assume pre-ANSI C language */
int CplusplusFlag = 0;		/* -+, assume C++ language */
int OnATty = 0;			/* stdin is coming from a terminal */
int Interactive = 0;		/* -i, overrides OnATty */
int KeywordName = 0;		/* $0 is a keyword (declare, explain, cast) */
char *progname = "cdecl";	/* $0 */

#if dodebug
int DebugFlag = 0;		/* -d, output debugging trace info */
#endif

#ifdef doyydebug		/* compile in yacc trace statements */
#define YYDEBUG 1
#endif /* doyydebug */

#include "cdgram.c"
#include "cdlex.c"

/* definitions (and abbreviations) for type combinations cross check table */
#define ALWAYS	0	/* combo always okay */
#define _	ALWAYS
#define NEVER	1	/* combo never allowed */
#define X	NEVER
#define RITCHIE	2	/* combo not allowed in Ritchie compiler */
#define R	RITCHIE
#define PREANSI	3	/* combo not allowed in Pre-ANSI compiler */
#define P	PREANSI
#define ANSI	4	/* combo not allowed anymore in ANSI compiler */
#define A	ANSI

/* This is an lower left triangular array. If we needed */
/* to save 9 bytes, the "long" row can be removed. */
char crosscheck[9][9] = {
    /*			L, I, S, C, V, U, S, F, D, */
    /* long */		_, _, _, _, _, _, _, _, _,
    /* int */		_, _, _, _, _, _, _, _, _,
    /* short */		X, _, _, _, _, _, _, _, _,
    /* char */		X, X, X, _, _, _, _, _, _,
    /* void */		X, X, X, X, _, _, _, _, _,
    /* unsigned */	R, _, R, R, X, _, _, _, _,
    /* signed */	P, P, P, P, X, X, _, _, _,
    /* float */		A, X, X, X, X, X, X, _, _,
    /* double */	P, X, X, X, X, X, X, X, _
};

/* the names and bits checked for each row in the above array */
struct
    {
    char *name;
    int bit;
    } crosstypes[9] =
	{
	    { "long",		MB_LONG		},
	    { "int",		MB_INT		},
	    { "short",		MB_SHORT	},
	    { "char",		MB_CHAR		},
	    { "void",		MB_VOID		},
	    { "unsigned",	MB_UNSIGNED	},
	    { "signed",		MB_SIGNED	},
	    { "float",		MB_FLOAT	},
	    { "double",		MB_DOUBLE	}
	};

/* Run through the crosscheck array looking */
/* for unsupported combinations of types. */
void mbcheck()
{
    register int i, j, restrict;
    char *t1, *t2;

    /* Loop through the types */
    /* (skip the "long" row) */
    for (i = 1; i < 9; i++)
	{
	/* if this type is in use */
	if ((modbits & crosstypes[i].bit) != 0)
	    {
	    /* check for other types also in use */
	    for (j = 0; j < i; j++)
		{
		/* this type is not in use */
		if (!(modbits & crosstypes[j].bit))
		    continue;
		/* check the type of restriction */
		restrict = crosscheck[i][j];
		if (restrict == ALWAYS)
		    continue;
		t1 = crosstypes[i].name;
		t2 = crosstypes[j].name;
		if (restrict == NEVER)
		    {
		    notsupported("", t1, t2);
		    }
		else if (restrict == RITCHIE)
		    {
		    if (RitchieFlag)
			notsupported(" (Ritchie Compiler)", t1, t2);
		    }
		else if (restrict == PREANSI)
		    {
		    if (PreANSIFlag || RitchieFlag)
			notsupported(" (Pre-ANSI Compiler)", t1, t2);
		    }
		else if (restrict == ANSI)
		    {
		    if (!RitchieFlag && !PreANSIFlag)
			notsupported(" (ANSI Compiler)", t1, t2);
		    }
		else
		    {
		    (void) fprintf (stderr,
			"%s: Internal error in crosscheck[%d,%d]=%d!\n",
			progname, i, j, restrict);
		    exit(1); /* NOTREACHED */
		    }
		}
	    }
	}
}

/* undefine these as they are no longer needed */
#undef _
#undef ALWAYS
#undef X
#undef NEVER
#undef R
#undef RITCHIE
#undef P
#undef PREANSI
#undef A
#undef ANSI

/* Write out a message about something */
/* being unsupported, possibly with a hint. */
void unsupp(s,hint)
char *s,*hint;
{
    notsupported("", s, NullCP);
    if (hint)
	(void) fprintf(stderr, "\t(maybe you mean \"%s\")\n", hint);
}

/* Write out a message about something */
/* being unsupported on a particular compiler. */
void notsupported(compiler, type1, type2)
char *compiler, *type1, *type2;
{
    if (type2)
	(void) fprintf(stderr,
	    "Warning: Unsupported in%s C%s -- '%s' with '%s'\n",
	    compiler, CplusplusFlag ? "++" : "", type1, type2);
    else
	(void) fprintf(stderr,
	    "Warning: Unsupported in%s C%s -- '%s'\n",
	    compiler, CplusplusFlag ? "++" : "", type1);
}

/* Called by the yacc grammar */
void yyerror(s)
char *s;
{
    (void) printf("%s\n",s);
    Debug((stdout, "yychar=%d\n", yychar));
}

/* Called by the yacc grammar */
int yywrap()
{
    return 1;
}

/*
 * Support for dynamic strings:
 * cat() creates a string from the concatenation
 * of a null terminated list of input strings.
 * The input strings are free()'d by cat()
 * (so they better have been malloc()'d).
 *
 * the different methods of <stdarg.h> and
 * <vararg.h> are handled within these macros
 */
#ifdef AMIGA
# define VA_DCL(type,var)		(var) type var;
# define VA_START(list,var,type)	(list = (va_list)&(var) , (var))
# define va_arg(list,type)		((type *)(list += sizeof(type)))[0]
# define va_end(p)			/* nothing */
typedef char *va_list;
#else
#if __STDC__
#  define VA_DCL(type,var)		(type var,...)
#  define VA_START(list,var,type)	((va_start(list,var)) , (var))
#else
#if defined(DOS)
#  define VA_DCL(type,var)		(var,...) type var;
#  define VA_START(list,var,type)	((va_start(list,var)) , (var))
#else
#ifndef NOVARARGS
# define VA_DCL(type,var)		(va_alist) va_dcl
# define VA_START(list,var,type)	((va_start(list)) , va_arg(list,type))
#else
   /*
    *	it is assumed here that machines which don't have either
    *	<varargs.h> or <stdarg.h> will put its arguments on
    *	the stack in the "usual" way and consequently can grab
    *	the arguments using the "take the address of the first
    *	parameter and increment by sizeof" trick.
    */
# define VA_DCL(type,var)		(var) type var;
# define VA_START(list,var,type)	(list = (va_list)&(var) , (var))
# define va_arg(list,type)		((type *)(list += sizeof(type)))[-1]
# define va_end(p)			/* nothing */
typedef char *va_list;
#endif /* NOVARARGS */
#endif /* DOS */
#endif /* __STDC__ */
#endif /* AMIGA */

/* VARARGS */
char *cat
VA_DCL(char*, s1)
{
    register char *newstr;
    register unsigned len = 1;
    char *str;
    va_list args;

    /* find the length which needs to be allocated */
    str = VA_START(args, s1, char*);
    for ( ; str; str = va_arg(args, char*))
	len += strlen(str);
    va_end(args);

    /* allocate it */
    newstr = malloc(len);
    if (newstr == 0)
	{
	(void) fprintf (stderr, "%s: out of malloc space within cat()!\n",
	    progname);
	exit(1);
	}
    newstr[0] = '\0';

    /* copy in the strings */
    str = VA_START(args, s1, char*);
    for ( ; str; str = va_arg(args, char*))
	{
	(void) strcat(newstr,str);
	free(str);
	}
    va_end(args);

    Debug((stderr, "\tcat created '%s'\n", newstr));
    return newstr;
}

/*
 * ds() makes a malloc()'d string from one that's not.
 */
char *ds(s)
char *s;
{
    register char *p = malloc((unsigned)(strlen(s)+1));

    if (p)
	(void) strcpy(p,s);
    else
	{
	(void) fprintf (stderr, "%s: malloc() failed!\n", progname);
	exit(1);
	}
    return p;
}

/* return a visible representation of a character */
char *visible(c)
int c;
{
    static char buf[5];

    c &= 0377;
    if (isprint(c))
	{
	buf[0] = c;
	buf[1] = '\0';
	}
    else
	(void) sprintf(buf,"\\%03o",c);
    return buf;
}

#ifdef NOTMPFILE
/* provide a conservative version of tmpfile() */
/* for those systems without it. */
/* tmpfile() returns a FILE* of a file opened */
/* for read&write. It is supposed to be */
/* automatically removed when it gets closed, */
/* but here we provide a separate rmtmpfile() */
/* function to perform that function. */
/* Also provide several possible file names to */
/* try for opening. */
static char *file4tmpfile = 0;

FILE *tmpfile()
{

#ifdef AMIGA
    static char *listtmpfiles[] =
	{
	":T/cdeclXXXXXX",
	"ram:cdeclXXXXXX",
	"ram:cdeclXXXXXX",
	"ram:cdeclXXXXXX",
	0
	};
#else
    static char *listtmpfiles[] =
	{
	"/usr/tmp/cdeclXXXXXX",
	"/tmp/cdeclXXXXXX",
	"/cdeclXXXXXX",
	"cdeclXXXXXX",
	0
	};
#endif

    char **listp = listtmpfiles;
    for ( ; *listp; listp++)
	{
	FILE *retfp;
	(void) mktemp(*listp);
	retfp = fopen(*listp, "w+");
	if (!retfp)
	    continue;
	file4tmpfile = *listp;
	return retfp;
	}

    return 0;
}

void rmtmpfile()
{
    if (file4tmpfile)
	(void) unlink(file4tmpfile);
}
#else
/* provide a mock rmtmpfile() for normal systems */
# define rmtmpfile()	/* nothing */
#endif /* NOTMPFILE */

#ifndef NOGETOPT
extern int optind;
#else
/* This is a miniature version of getopt() which will */
/* do just barely enough for us to get by below. */
/* Options are not allowed to be bunched up together. */
/* Option arguments are not supported. */
int optind = 1;

int getopt(argc,argv,optstring)
char **argv;
char *optstring;
{
    int ret;
    char *p;

    if ((argv[optind][0] != '-')
#ifdef DOS
	&& (argv[optind][0] != '/')
#endif /* DOS */
	)
	return EOF;

    ret = argv[optind][1];
    optind++;

    for (p = optstring; *p; p++)
	if (*p == ret)
	    return ret;

    (void) fprintf (stderr, "%s: illegal option -- %s\n",
	progname, visible(ret));

    return '?';
}
#endif

/* the help messages */
struct helpstruct
    {
	char *text;	/* generic text */
	char *cpptext;	/* C++ specific text */
    } helptext[] =
    {	/* up-to 23 lines of help text so it fits on (24x80) screens */
/*  1 */{ "[] means optional; {} means 1 or more; <> means defined elsewhere", 0 },
/*  2 */{ "  commands are separated by ';' and newlines", 0 },
/*  3 */{ "command:", 0 },
/*  4 */{ "  declare <name> as <english>", 0 },
/*  5 */{ "  cast <name> into <english>", 0 },
/*  6 */{ "  explain <gibberish>", 0 },
/*  7 */{ "  set or set options", 0 },
/*  8 */{ "  help, ?", 0 },
/*  9 */{ "  quit or exit", 0 },
/* 10 */{ "english:", 0 },
/* 11 */{ "  function [( <decl-list> )] returning <english>", 0 },
/* 12 */{ "  array [<number>] of <english>", 0 },
/* 13 */{ "  [{ const | volatile | noalias }] pointer to <english>",
	  "  [{const|volatile}] {pointer|reference} to [member of class <name>] <english>" },
/* 14 */{ "  <type>", 0 },
/* 15 */{ "type:", 0 },
/* 16 */{ "  {[<storage-class>] [{<modifier>}] [<C-type>]}", 0 },
/* 17 */{ "  { struct | union | enum } <name>",
	  "  {struct|class|union|enum} <name>" },
/* 18 */{ "decllist: a comma separated list of <name>, <english> or <name> as <english>", 0 },
/* 19 */{ "name: a C identifier", 0 },
/* 20 */{ "gibberish: a C declaration, like 'int *x', or cast, like '(int *)x'", 0 },
/* 21 */{ "storage-class: extern, static, auto, register", 0 },
/* 22 */{ "C-type: int, char, float, double, or void", 0 },
/* 23 */{ "modifier: short, long, signed, unsigned, const, volatile, or noalias",
	  "modifier: short, long, signed, unsigned, const, or volatile" },
	{ 0, 0 }
    };

/* Print out the help text */
void dohelp()
{
    register struct helpstruct *p;
    register char *fmt = CplusplusFlag ? " %s\n" : "\t%s\n";

    for (p = helptext; p->text; p++)
	if (CplusplusFlag && p->cpptext)
	    (void) printf(fmt, p->cpptext);
	else
	    (void) printf(fmt, p->text);
}

/* Tell how to invoke cdecl. */
void usage()
{
    (void) fprintf (stderr, "Usage: %s [-r|-p|-a|-+] [-ci%s%s] [files...]\n",
	progname,
#ifdef dodebug
	"d",
#else
	"",
#endif /* dodebug */
#ifdef doyydebug
	"D"
#else
	""
#endif /* doyydebug */
	);
    (void) fprintf (stderr, "\t-r Check against Ritchie PDP C Compiler\n");
    (void) fprintf (stderr, "\t-p Check against Pre-ANSI C Compiler\n");
    (void) fprintf (stderr, "\t-a Check against ANSI C Compiler%s\n",
	CplusplusFlag ? "" : " (the default)");
    (void) fprintf (stderr, "\t-+ Check against C++ Compiler%s\n",
	CplusplusFlag ? " (the default)" : "");
    (void) fprintf (stderr, "\t-c Create compilable output (include ; and {})\n");
    (void) fprintf (stderr, "\t-i Force interactive mode\n");
#ifdef dodebug
    (void) fprintf (stderr, "\t-d Turn on debugging mode\n");
#endif /* dodebug */
#ifdef doyydebug
    (void) fprintf (stderr, "\t-D Turn on YACC debugging mode\n");
#endif /* doyydebug */
    exit(1);
    /* NOTREACHED */
}

/* Manage the prompts. */
static int prompting = 1;

void doprompt() { prompting = 1; }
void noprompt() { prompting = 0; }

void prompt()
{
    if ((OnATty || Interactive) && prompting) {
	(void) printf("%s> ", progname);
	(void) fflush(stdout);
    }
}

/* Save away the name of the program from argv[0] */
void setprogname(argv0)
char *argv0;
{
#ifdef DOS
    char *dot;
#endif /* DOS */

    progname = strrchr(argv0, '/');

#ifdef DOS
    if (!progname)
	progname = strrchr(argv0, '\\');
#endif /* DOS */

    if (progname)
	progname++;
    else
	progname = argv0;

#ifdef DOS
    dot = strchr(progname, '.');
    if (dot)
	*dot = '\0';
    for (dot = progname; *dot; dot++)
	*dot = tolower(*dot);
#endif /* DOS */
}

/* Run down the list of keywords to see if the */
/* program is being called named as one of them */
/* or the first argument is one of them. */
int namedkeyword(argn)
char *argn;
{
    static char *cmdlist[] =
	{
	"explain", "declare", "cast", "help", "?", "set", 0
	};

    /* first check the program name */
    char **cmdptr = cmdlist;
    for ( ; *cmdptr; cmdptr++)
	if (strcmp(*cmdptr, progname) == 0)
	    {
	    KeywordName = 1;
	    return 1;
	    }

    /* now check $1 */
    for (cmdptr = cmdlist; *cmdptr; cmdptr++)
	if (strcmp(*cmdptr, argn) == 0)
	    return 1;

    /* nope, must be file name arguments */
    return 0;
}

/* Read from standard input, turning */
/* on prompting if necessary. */
int dostdin()
{
    int ret;
    OnATty = isatty(0);
    if (OnATty || Interactive)
	{
	(void) printf("Type `help' or `?' for help\n");
	prompt();
	}

    yyin = stdin;
    ret = yyparse();
    OnATty = 0;
    return ret;
}

/* Write the arguments into a file */
/* and treat that file as the input. */
int dotmpfile(argc, argv)
int argc;
char **argv;
{
    int ret = 0;
    FILE *tmpfp = tmpfile();
    if (!tmpfp)
	{
	int sverrno = errno;
	(void) fprintf (stderr, "%s: cannot open temp file\n",
	    progname);
	errno = sverrno;
	perror(progname);
	return 1;
	}

    if (KeywordName)
	if (fputs(progname, tmpfp) == EOF)
	    {
	    int sverrno;
	errwrite:
	    sverrno = errno;
	    (void) fprintf (stderr, "%s: error writing to temp file\n",
		progname);
	    errno = sverrno;
	    perror(progname);
	    (void) fclose(tmpfp);
	    rmtmpfile();
	    return 1;
	    }

    for ( ; optind < argc; optind++)
	if (fprintf(tmpfp, " %s", argv[optind]) == EOF)
	    goto errwrite;

    if (putc('\n', tmpfp) == EOF)
	goto errwrite;

    rewind(tmpfp);
    yyin = tmpfp;
    ret += yyparse();
    (void) fclose(tmpfp);
    rmtmpfile();

    return ret;
}

/* Read each of the named files for input. */
int dofileargs(argc, argv)
int argc;
char **argv;
{
    FILE *ifp;
    int ret = 0;

    for ( ; optind < argc; optind++)
	if (strcmp(argv[optind], "-") == 0)
	    ret += dostdin();

	else if ((ifp = fopen(argv[optind], "r")) == NULL)
	    {
	    int sverrno = errno;
	    (void) fprintf (stderr, "%s: cannot open %s\n",
		progname, argv[optind]);
	    errno = sverrno;
	    perror(argv[optind]);
	    ret++;
	    }

	else
	    {
	    yyin = ifp;
	    ret += yyparse();
	    }

    return ret;
}

/* print out a cast */
void docast(name, left, right, type)
char *name, *left, *right, *type;
{
    int lenl = strlen(left), lenr = strlen(right);

    if (prev == 'f')
	    unsupp("Cast into function",
		    "cast into pointer to function");
    else if (prev=='A' || prev=='a')
	    unsupp("Cast into array","cast into pointer");
    (void) printf("(%s%*s%s)%s\n",
	    type, lenl+lenr?lenl+1:0,
	    left, right, name ? name : "expression");
    free(left);
    free(right);
    free(type);
    if (name)
        free(name);
}

/* print out a declaration */
void dodeclare(name, storage, left, right, type)
char *name, *storage, *left, *right, *type;
{
    if (prev == 'v')
	    unsupp("Variable of type void",
		    "variable of type pointer to void");

    if (*storage == 'r')
	switch (prev)
	    {
	    case 'f': unsupp("Register function", NullCP); break;
	    case 'A':
	    case 'a': unsupp("Register array", NullCP); break;
	    case 's': unsupp("Register struct/class", NullCP); break;
	    }

    if (*storage)
        (void) printf("%s ", storage);
    (void) printf("%s %s%s%s",
        type, left,
	name ? name : (prev == 'f') ? "f" : "var", right);
    if (MkProgramFlag) {
	    if ((prev == 'f') && (*storage != 'e'))
		    (void) printf(" { }\n");
	    else
		    (void) printf(";\n");
    } else {
	    (void) printf("\n");
    }
    free(storage);
    free(left);
    free(right);
    free(type);
    if (name)
        free(name);
}

void dodexplain(storage, constvol, type, decl)
char *storage, *constvol, *type, *decl;
{
    if (type && (strcmp(type, "void") == 0))
	if (prev == 'n')
	    unsupp("Variable of type void",
		   "variable of type pointer to void");
	else if (prev == 'a')
	    unsupp("array of type void",
		   "array of type pointer to void");
	else if (prev == 'r')
	    unsupp("reference to type void",
		   "pointer to void");

    if (*storage == 'r')
	switch (prev)
	    {
	    case 'f': unsupp("Register function", NullCP); break;
	    case 'A':
	    case 'a': unsupp("Register array", NullCP); break;
	    case 's': unsupp("Register struct/union/enum/class", NullCP); break;
	    }

    (void) printf("declare %s as ", savedname);
    if (*storage)
        (void) printf("%s ", storage);
    (void) printf("%s", decl);
    if (*constvol)
	    (void) printf("%s ", constvol);
    (void) printf("%s\n", type ? type : "int");
}

void docexplain(constvol, type, cast, name)
char *constvol, *type, *cast, *name;
{
    if (strcmp(type, "void") == 0)
	if (prev == 'a')
	    unsupp("array of type void",
		   "array of type pointer to void");
	else if (prev == 'r')
	    unsupp("reference to type void",
		   "pointer to void");
    (void) printf("cast %s into %s", name, cast);
    if (strlen(constvol) > 0)
	    (void) printf("%s ", constvol);
    (void) printf("%s\n",type);
}

/* Do the appropriate things for the "set" command. */
void doset(opt)
char *opt;
{
    if (strcmp(opt, "create") == 0)
	{ MkProgramFlag = 1; }
    else if (strcmp(opt, "nocreate") == 0)
	{ MkProgramFlag = 0; }
    else if (strcmp(opt, "interactive") == 0)
	{ Interactive = 1; }
    else if (strcmp(opt, "nointeractive") == 0)
	{ Interactive = 0; OnATty = 0; }
    else if (strcmp(opt, "ritchie") == 0)
	{ CplusplusFlag=0; RitchieFlag=1; PreANSIFlag=0; }
    else if (strcmp(opt, "preansi") == 0)
	{ CplusplusFlag=0; RitchieFlag=0; PreANSIFlag=1; }
    else if (strcmp(opt, "ansi") == 0)
	{ CplusplusFlag=0; RitchieFlag=0; PreANSIFlag=0; }
    else if (strcmp(opt, "cplusplus") == 0)
	{ CplusplusFlag=1; RitchieFlag=0; PreANSIFlag=0; }
#ifdef dodebug
    else if (strcmp(opt, "debug") == 0)
	{ DebugFlag = 1; }
    else if (strcmp(opt, "nodebug") == 0)
	{ DebugFlag = 0; }
#endif /* dodebug */
#ifdef doyydebug
    else if (strcmp(opt, "yydebug") == 0)
	{ yydebug = 1; }
    else if (strcmp(opt, "noyydebug") == 0)
	{ yydebug = 0; }
#endif /* doyydebug */
    else
	{
	if ((strcmp(opt, unknown_name) != 0) &&
	    (strcmp(opt, "options") != 0))
	    (void) printf("Unknown set option: '%s'\n", opt);

	(void) printf("Valid set options (and command line equivalents) are:\n");
	(void) printf("\toptions\n");
	(void) printf("\tcreate (-c), nocreate\n");
	(void) printf("\tinteractive (-i), nointeractive\n");
	(void) printf("\tritchie (-r), preansi (-p), ansi (-a) or cplusplus (-+)\n");
#ifdef dodebug
	(void) printf("\tdebug (-d), nodebug\n");
#endif /* dodebug */
#ifdef doyydebug
	(void) printf("\tyydebug (-D), noyydebug\n");
#endif /* doyydebug */

	(void) printf("\nCurrent set values are:\n");
	(void) printf("\t%screate\n", MkProgramFlag ? "   " : " no");
	(void) printf("\t%sinteractive\n",
	    (OnATty || Interactive) ? "   " : " no");
	if (RitchieFlag)
	    (void) printf("\t   ritchie\n");
	else
	    (void) printf("\t(noritchie)\n");
	if (PreANSIFlag)
	    (void) printf("\t   preansi\n");
	else
	    (void) printf("\t(nopreansi)\n");
	if (!RitchieFlag && !PreANSIFlag && !CplusplusFlag)
	    (void) printf("\t   ansi\n");
	else
	    (void) printf("\t(noansi)\n");
	if (CplusplusFlag)
	    (void) printf("\t   cplusplus\n");
	else
	    (void) printf("\t(nocplusplus)\n");
#ifdef dodebug
	(void) printf("\t%sdebug\n", DebugFlag ? "   " : " no");
#endif /* dodebug */
#ifdef doyydebug
	(void) printf("\t%syydebug\n", yydebug ? "   " : " no");
#endif /* doyydebug */
	}
}

void versions()
{
    (void) printf("Version:\n\t%s\n\t%s\n\t%s\n",
	cdeclsccsid, cdgramsccsid, cdlexsccsid);
    exit(0);
}

int main(argc, argv)
char **argv;
{
    int c, ret = 0;

    setprogname(argv[0]);
#ifdef DOS
    if (strcmp(progname, "cppdecl") == 0)
#else
    if (strcmp(progname, "c++decl") == 0)
#endif /* DOS */
	CplusplusFlag = 1;

    while ((c = getopt(argc, argv, "cirpa+dDV")) != EOF)
	switch (c)
	    {
	    case 'c': MkProgramFlag=1; break;
	    case 'i': Interactive=1; break;

	    /* The following are mutually exclusive. */
	    /* Only the last one set prevails. */
	    case 'r': CplusplusFlag=0; RitchieFlag=1; PreANSIFlag=0; break;
	    case 'p': CplusplusFlag=0; RitchieFlag=0; PreANSIFlag=1; break;
	    case 'a': CplusplusFlag=0; RitchieFlag=0; PreANSIFlag=0; break;
	    case '+': CplusplusFlag=1; RitchieFlag=0; PreANSIFlag=0; break;

#ifdef dodebug
	    case 'd': DebugFlag=1; break;
#endif /* dodebug */
#ifdef doyydebug
	    case 'D': yydebug=1; break;
#endif /* doyydebug */
	    case 'V': versions(); break;
	    case '?': usage(); break;
	    }

    /* Run down the list of arguments, parsing each one. */

    /* Use standard input if no file names or "-" is found. */
    if (optind == argc)
	ret += dostdin();

    /* If called as explain, declare or cast, or first */
    /* argument is one of those, use the command line */
    /* as the input. */
    else if (namedkeyword(argv[optind]))
	ret += dotmpfile(argc, argv);

    else
	ret += dofileargs(argc, argv);

    exit(ret);
    /* NOTREACHED */
}
SHAR_EOF
cat << \SHAR_EOF > cdgram.y
%{
/* Yacc grammar for ANSI and C++ cdecl. */
/* The output of this file is included */
/* into the C file cdecl.c. */
char cdgramsccsid[] = "@(#)cdgram.y	2.2 3/30/88";
%}

%union {
	char *dynstr;
	struct {
		char *left;
		char *right;
		char *type;
	} halves;
}

%token ARRAY AS CAST COMMA DECLARE DOUBLECOLON EXPLAIN FUNCTION
%token HELP INTO OF MEMBER POINTER REFERENCE RETURNING SET TO
%token <dynstr> CHAR CLASS CONSTVOLATILE DOUBLE ENUM FLOAT INT LONG NAME
%token <dynstr> NUMBER SHORT SIGNED STRUCT UNION UNSIGNED VOID
%token <dynstr> AUTO EXTERN REGISTER STATIC
%type <dynstr> adecllist adims c_type cast castlist cdecl cdecl1 cdims
%type <dynstr> constvol_list ClassStruct mod_list mod_list1 modifier
%type <dynstr> opt_constvol_list optNAME opt_storage storage StrClaUniEnum
%type <dynstr> tname type
%type <halves> adecl

%start prog

%%
prog		: /* empty */
		| prog stmt
			{
			prompt();
			prev = 0;
			}
		;

stmt		: HELP NL
			{
			Debug((stderr, "stmt: help\n"));
			dohelp();
			}

		| DECLARE NAME AS opt_storage adecl NL
			{
			Debug((stderr, "stmt: DECLARE NAME AS opt_storage adecl\n"));
			Debug((stderr, "\tNAME='%s'\n", $2));
			Debug((stderr, "\topt_storage='%s'\n", $4));
			Debug((stderr, "\tacdecl.left='%s'\n", $5.left));
			Debug((stderr, "\tacdecl.right='%s'\n", $5.right));
			Debug((stderr, "\tacdecl.type='%s'\n", $5.type));
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			dodeclare($2, $4, $5.left, $5.right, $5.type);
			}

		| DECLARE opt_storage adecl NL
			{
			Debug((stderr, "stmt: DECLARE opt_storage adecl\n"));
			Debug((stderr, "\topt_storage='%s'\n", $2));
			Debug((stderr, "\tacdecl.left='%s'\n", $3.left));
			Debug((stderr, "\tacdecl.right='%s'\n", $3.right));
			Debug((stderr, "\tacdecl.type='%s'\n", $3.type));
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			dodeclare(NullCP, $2, $3.left, $3.right, $3.type);
			}

		| CAST NAME INTO adecl NL
			{
			Debug((stderr, "stmt: CAST NAME AS adecl\n"));
			Debug((stderr, "\tNAME='%s'\n", $2));
			Debug((stderr, "\tacdecl.left='%s'\n", $4.left));
			Debug((stderr, "\tacdecl.right='%s'\n", $4.right));
			Debug((stderr, "\tacdecl.type='%s'\n", $4.type));
			docast($2, $4.left, $4.right, $4.type);
			}

		| CAST adecl NL
			{
			Debug((stderr, "stmt: CAST adecl\n"));
			Debug((stderr, "\tacdecl.left='%s'\n", $2.left));
			Debug((stderr, "\tacdecl.right='%s'\n", $2.right));
			Debug((stderr, "\tacdecl.type='%s'\n", $2.type));
			docast(NullCP, $2.left, $2.right, $2.type);
			}

		| EXPLAIN opt_storage opt_constvol_list type cdecl NL
			{
			Debug((stderr, "stmt: EXPLAIN opt_storage opt_constvol_list type cdecl\n"));
			Debug((stderr, "\topt_storage='%s'\n", $2));
			Debug((stderr, "\topt_constvol_list='%s'\n", $3));
			Debug((stderr, "\ttype='%s'\n", $4));
			Debug((stderr, "\tcdecl='%s'\n", $5));
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			dodexplain($2, $3, $4, $5);
			}

		| EXPLAIN storage opt_constvol_list cdecl NL
			{
			Debug((stderr, "stmt: EXPLAIN storage opt_constvol_list cdecl\n"));
			Debug((stderr, "\tstorage='%s'\n", $2));
			Debug((stderr, "\topt_constvol_list='%s'\n", $3));
			Debug((stderr, "\tcdecl='%s'\n", $4));
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			dodexplain($2, $3, NullCP, $4);
			}

		| EXPLAIN opt_storage constvol_list cdecl NL
			{
			Debug((stderr, "stmt: EXPLAIN opt_storage constvol_list cdecl\n"));
			Debug((stderr, "\topt_storage='%s'\n", $2));
			Debug((stderr, "\tconstvol_list='%s'\n", $3));
			Debug((stderr, "\tcdecl='%s'\n", $4));
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			dodexplain($2, $3, NullCP, $4);
			}

		| EXPLAIN '(' opt_constvol_list type cast ')' optNAME NL
			{
			Debug((stderr, "stmt: EXPLAIN ( opt_constvol_list type cast ) optNAME\n"));
			Debug((stderr, "\topt_constvol_list='%s'\n", $3));
			Debug((stderr, "\ttype='%s'\n", $4));
			Debug((stderr, "\tcast='%s'\n", $5));
			Debug((stderr, "\tNAME='%s'\n", $7));
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			docexplain($3, $4, $5, $7);
			}

		| SET optNAME NL
			{
			Debug((stderr, "stmt: SET optNAME\n"));
			Debug((stderr, "\toptNAME='%s'\n", $2));
			doset($2);
			}

		| NL
		| error NL
			{
			yyerrok;
			}
		;

NL		: '\n'
			{
			doprompt();
			}
		| ';'
			{
			noprompt();
			}
		;

optNAME		: NAME
			{
			Debug((stderr, "optNAME: NAME\n"));
			Debug((stderr, "\tNAME='%s'\n", $1));
			$$ = $1;
			}

		| /* empty */
			{
			Debug((stderr, "optNAME: EMPTY\n"));
			$$ = ds(unknown_name);
			}
		;

cdecl		: cdecl1
		| '*' opt_constvol_list cdecl
			{
			Debug((stderr, "cdecl: * opt_constvol_list cdecl\n"));
			Debug((stderr, "\topt_constvol_list='%s'\n", $2));
			Debug((stderr, "\tcdecl='%s'\n", $3));
			$$ = cat($3,$2,ds(strlen($2)?" pointer to ":"pointer to "),NullCP);
			prev = 'p';
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			}

		| NAME DOUBLECOLON '*' cdecl
			{
			Debug((stderr, "cdecl: NAME DOUBLECOLON '*' cdecl\n"));
			Debug((stderr, "\tNAME='%s'\n", $1));
			Debug((stderr, "\tcdecl='%s'\n", $4));
			if (!CplusplusFlag)
				unsupp("pointer to member of class", NullCP);
			$$ = cat($4,ds("pointer to member of class "),$1,ds(" "),NullCP);
			prev = 'p';
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			}

		| '&' opt_constvol_list cdecl
			{
			Debug((stderr, "cdecl: & opt_constvol_list cdecl\n"));
			Debug((stderr, "\topt_constvol_list='%s'\n", $2));
			Debug((stderr, "\tcdecl='%s'\n", $3));
			if (!CplusplusFlag)
				unsupp("reference", NullCP);
			$$ = cat($3,$2,ds(strlen($2)?" reference to ":"reference to "),NullCP);
			prev = 'r';
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			}
		;

cdecl1		: cdecl1 '(' ')'
			{
			Debug((stderr, "cdecl1: cdecl1()\n"));
			Debug((stderr, "\tcdecl1='%s'\n", $1));
			$$ = cat($1,ds("function returning "),NullCP);
			prev = 'f';
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			}

		| cdecl1 '(' castlist ')'
			{
			Debug((stderr, "cdecl1: cdecl1(castlist)\n"));
			Debug((stderr, "\tcdecl1='%s'\n", $1));
			Debug((stderr, "\tcastlist='%s'\n", $3));
			$$ = cat($1, ds("function ("),
				  $3, ds(") returning "), NullCP);
			prev = 'f';
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			}

		| cdecl1 cdims
			{
			Debug((stderr, "cdecl1: cdecl1 cdims\n"));
			Debug((stderr, "\tcdecl1='%s'\n", $1));
			Debug((stderr, "\tcdims='%s'\n", $2));
			$$ = cat($1,ds("array "),$2,NullCP);
			prev = 'a';
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			}

		| '(' cdecl ')'
			{
			Debug((stderr, "cdecl1: (cdecl)\n"));
			Debug((stderr, "\tcdecl='%s'\n", $2));
			$$ = $2;
			/* prev = prev; */
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			}

		| NAME
			{
			Debug((stderr, "cdecl1: NAME\n"));
			Debug((stderr, "\tNAME='%s'\n", $1));
			savedname = $1;
			$$ = ds("");
			prev = 'n';
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			}
		;

castlist	: castlist COMMA castlist
			{
			Debug((stderr, "castlist: castlist1, castlist2\n"));
			Debug((stderr, "\tcastlist1='%s'\n", $1));
			Debug((stderr, "\tcastlist2='%s'\n", $3));
			$$ = cat($1, ds(", "), $3, NullCP);
			}

		| opt_constvol_list type cast
			{
			Debug((stderr, "castlist: opt_constvol_list type cast\n"));
			Debug((stderr, "\topt_constvol_list='%s'\n", $1));
			Debug((stderr, "\ttype='%s'\n", $2));
			Debug((stderr, "\tcast='%s'\n", $3));
			$$ = cat($3, $1, ds(strlen($1) ? " " : ""), $2, NullCP);
			}

		| NAME
			{
			$$ = $1;
			}
		;

adecllist	: /* empty */
			{
			Debug((stderr, "adecllist: EMPTY\n"));
			$$ = ds("");
			}

		| adecllist COMMA adecllist
			{
			Debug((stderr, "adecllist: adecllist1, adecllist2\n"));
			Debug((stderr, "\tadecllist1='%s'\n", $1));
			Debug((stderr, "\tadecllist2='%s'\n", $3));
			$$ = cat($1, ds(", "), $3, NullCP);
			}

		| NAME
			{
			Debug((stderr, "adecllist: NAME\n"));
			Debug((stderr, "\tNAME='%s'\n", $1));
			$$ = $1;
			}

		| adecl
			{
			Debug((stderr, "adecllist: adecl\n"));
			Debug((stderr, "\tadecl.left='%s'\n", $1.left));
			Debug((stderr, "\tadecl.right='%s'\n", $1.right));
			Debug((stderr, "\tadecl.type='%s'\n", $1.type));
			$$ = cat($1.type, ds(" "), $1.left, $1.right, NullCP);
			}

		| NAME AS adecl
			{
			Debug((stderr, "adecllist: NAME AS adecl\n"));
			Debug((stderr, "\tNAME='%s'\n", $1));
			Debug((stderr, "\tadecl.left='%s'\n", $3.left));
			Debug((stderr, "\tadecl.right='%s'\n", $3.right));
			Debug((stderr, "\tadecl.type='%s'\n", $3.type));
			$$ = cat($3.type, ds(" "), $3.left, $1, $3.right, NullCP);
			}
		;

cast		: /* empty */
			{
			Debug((stderr, "cast: EMPTY\n"));
			$$ = ds("");
			/* prev = prev; */
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			}

		| '(' ')'
			{
			Debug((stderr, "cast: ()\n"));
			$$ = ds("function returning ");
			prev = 'f';
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			}

		| '(' cast ')' '(' ')'
			{
			Debug((stderr, "cast: (cast)()\n"));
			Debug((stderr, "\tcast='%s'\n", $2));
			$$ = cat($2,ds("function returning "),NullCP);
			prev = 'f';
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			}

		| '(' cast ')' '(' castlist ')'
			{
			Debug((stderr, "cast: (cast)(castlist)\n"));
			Debug((stderr, "\tcast='%s'\n", $2));
			Debug((stderr, "\tcastlist='%s'\n", $5));
			$$ = cat($2,ds("function ("),$5,ds(") returning "),NullCP);
			prev = 'f';
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			}

		| '(' cast ')'
			{
			Debug((stderr, "cast: (cast)\n"));
			Debug((stderr, "\tcast='%s'\n", $2));
			$$ = $2;
			/* prev = prev; */
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			}

		| NAME DOUBLECOLON '*' cast
			{
			Debug((stderr, "cast: NAME::*cast\n"));
			Debug((stderr, "\tcast='%s'\n", $4));
			if (!CplusplusFlag)
				unsupp("pointer to member of class", NullCP);
			$$ = cat($4,ds("pointer to member of class "),$1,ds(" "),NullCP);
			prev = 'p';
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			}

		| '*' cast
			{
			Debug((stderr, "cast: *cast\n"));
			Debug((stderr, "\tcast='%s'\n", $2));
			$$ = cat($2,ds("pointer to "),NullCP);
			prev = 'p';
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			}

		| '&' cast
			{
			Debug((stderr, "cast: &cast\n"));
			Debug((stderr, "\tcast='%s'\n", $2));
			if (!CplusplusFlag)
				unsupp("reference", NullCP);
			$$ = cat($2,ds("reference to "),NullCP);
			prev = 'r';
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			}

		| cast cdims
			{
			Debug((stderr, "cast: cast cdims\n"));
			Debug((stderr, "\tcast='%s'\n", $1));
			Debug((stderr, "\tcdims='%s'\n", $2));
			$$ = cat($1,ds("array "),$2,NullCP);
			prev = 'a';
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			}
		;

cdims		: '[' ']'
			{
			Debug((stderr, "cdims: []\n"));
			$$ = ds("of ");
			}

		| '[' NUMBER ']'
			{
			Debug((stderr, "cdims: [NUMBER]\n"));
			Debug((stderr, "\tNUMBER='%s'\n", $2));
			$$ = cat($2,ds(" of "),NullCP);
			}
		;

adecl		: FUNCTION RETURNING adecl
			{
			Debug((stderr, "adecl: FUNCTION RETURNING adecl\n"));
			Debug((stderr, "\tadecl.left='%s'\n", $3.left));
			Debug((stderr, "\tadecl.right='%s'\n", $3.right));
			Debug((stderr, "\tadecl.type='%s'\n", $3.type));
			if (prev == 'f')
				unsupp("Function returning function",
				       "function returning pointer to function");
			else if (prev=='A' || prev=='a')
				unsupp("Function returning array",
				       "function returning pointer");
			$$.left = $3.left;
			$$.right = cat(ds("()"),$3.right,NullCP);
			$$.type = $3.type;
			prev = 'f';
			Debug((stderr, "\n\tadecl now =\n"));
			Debug((stderr, "\t\tadecl.left='%s'\n", $$.left));
			Debug((stderr, "\t\tadecl.right='%s'\n", $$.right));
			Debug((stderr, "\t\tadecl.type='%s'\n", $$.type));
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			}

		| FUNCTION '(' adecllist ')' RETURNING adecl
			{
			Debug((stderr, "adecl: FUNCTION (adecllist) RETURNING adecl\n"));
			Debug((stderr, "\tadecllist='%s'\n", $3));
			Debug((stderr, "\tadecl.left='%s'\n", $6.left));
			Debug((stderr, "\tadecl.right='%s'\n", $6.right));
			Debug((stderr, "\tadecl.type='%s'\n", $6.type));
			if (prev == 'f')
				unsupp("Function returning function",
				       "function returning pointer to function");
			else if (prev=='A' || prev=='a')
				unsupp("Function returning array",
				       "function returning pointer");
			$$.left = $6.left;
			$$.right = cat(ds("("),$3,ds(")"),$6.right,NullCP);
			$$.type = $6.type;
			prev = 'f';
			Debug((stderr, "\n\tadecl now =\n"));
			Debug((stderr, "\t\tadecl.left='%s'\n", $$.left));
			Debug((stderr, "\t\tadecl.right='%s'\n", $$.right));
			Debug((stderr, "\t\tadecl.type='%s'\n", $$.type));
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			}

		| ARRAY adims OF adecl
			{
			Debug((stderr, "adecl: ARRAY adims OF adecl\n"));
			Debug((stderr, "\tadims='%s'\n", $2));
			Debug((stderr, "\tadecl.left='%s'\n", $4.left));
			Debug((stderr, "\tadecl.right='%s'\n", $4.right));
			Debug((stderr, "\tadecl.type='%s'\n", $4.type));
			if (prev == 'f')
				unsupp("Array of function",
				       "array of pointer to function");
			else if (prev == 'a')
				unsupp("Inner array of unspecified size",
				       "array of pointer");
			else if (prev == 'v')
				unsupp("Array of void",
				       "pointer to void");
			if (arbdims)
				prev = 'a';
			else
				prev = 'A';
			$$.left = $4.left;
			$$.right = cat($2,$4.right,NullCP);
			$$.type = $4.type;
			Debug((stderr, "\n\tadecl now =\n"));
			Debug((stderr, "\t\tadecl.left='%s'\n", $$.left));
			Debug((stderr, "\t\tadecl.right='%s'\n", $$.right));
			Debug((stderr, "\t\tadecl.type='%s'\n", $$.type));
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			}

		| opt_constvol_list POINTER TO adecl
			{
			char *op = "", *cp = "", *sp = "";

			Debug((stderr, "adecl: opt_constvol_list POINTER TO adecl\n"));
			Debug((stderr, "\topt_constvol_list='%s'\n", $1));
			Debug((stderr, "\tadecl.left='%s'\n", $4.left));
			Debug((stderr, "\tadecl.right='%s'\n", $4.right));
			Debug((stderr, "\tadecl.type='%s'\n", $4.type));
			if (prev == 'a')
				unsupp("Pointer to array of unspecified dimension",
				       "pointer to object");
			if (prev=='a' || prev=='A' || prev=='f') {
				op = "(";
				cp = ")";
			}
			if (strlen($1) != 0)
				sp = " ";
			$$.left = cat($4.left,ds(op),ds("*"),
				       ds(sp),$1,ds(sp),NullCP);
			$$.right = cat(ds(cp),$4.right,NullCP);
			$$.type = $4.type;
			prev = 'p';
			Debug((stderr, "\n\tadecl now =\n"));
			Debug((stderr, "\t\tadecl.left='%s'\n", $$.left));
			Debug((stderr, "\t\tadecl.right='%s'\n", $$.right));
			Debug((stderr, "\t\tadecl.type='%s'\n", $$.type));
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			}

		| opt_constvol_list POINTER TO MEMBER OF ClassStruct NAME adecl
			{
			char *op = "", *cp = "", *sp = "";

			Debug((stderr, "adecl: opt_constvol_list POINTER TO MEMBER OF ClassStruct NAME adecl\n"));
			Debug((stderr, "\topt_constvol_list='%s'\n", $1));
			Debug((stderr, "\tClassStruct='%s'\n", $6));
			Debug((stderr, "\tNAME='%s'\n", $7));
			Debug((stderr, "\tadecl.left='%s'\n", $8.left));
			Debug((stderr, "\tadecl.right='%s'\n", $8.right));
			Debug((stderr, "\tadecl.type='%s'\n", $8.type));
			if (!CplusplusFlag)
				unsupp("pointer to member of class", NullCP);
			if (prev == 'a')
				unsupp("Pointer to array of unspecified dimension",
				       "pointer to object");
			if (prev=='a' || prev=='A' || prev=='f') {
				op = "(";
				cp = ")";
			}
			if (strlen($1) != 0)
				sp = " ";
			$$.left = cat($8.left,ds(op),$7,ds("::*"),
				      ds(sp),$1,ds(sp),NullCP);
			$$.right = cat(ds(cp),$8.right,NullCP);
			$$.type = $8.type;
			prev = 'p';
			Debug((stderr, "\n\tadecl now =\n"));
			Debug((stderr, "\t\tadecl.left='%s'\n", $$.left));
			Debug((stderr, "\t\tadecl.right='%s'\n", $$.right));
			Debug((stderr, "\t\tadecl.type='%s'\n", $$.type));
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			}

		| opt_constvol_list REFERENCE TO adecl
			{
			char *op = "", *cp = "", *sp = "";

			Debug((stderr, "adecl: opt_constvol_list REFERENCE TO adecl\n"));
			Debug((stderr, "\topt_constvol_list='%s'\n", $1));
			Debug((stderr, "\tadecl.left='%s'\n", $4.left));
			Debug((stderr, "\tadecl.right='%s'\n", $4.right));
			Debug((stderr, "\tadecl.type='%s'\n", $4.type));
			if (!CplusplusFlag)
				unsupp("reference", NullCP);
			if (prev == 'v')
				unsupp("Reference to void",
				       "pointer to void");
			else if (prev == 'a')
				unsupp("Reference to array of unspecified dimension",
				       "reference to object");
			if (prev=='a' || prev=='A' || prev=='f') {
				op = "(";
				cp = ")";
			}
			if (strlen($1) != 0)
				sp = " ";
			$$.left = cat($4.left,ds(op),ds("&"),
				       ds(sp),$1,ds(sp),NullCP);
			$$.right = cat(ds(cp),$4.right,NullCP);
			$$.type = $4.type;
			prev = 'r';
			Debug((stderr, "\n\tadecl now =\n"));
			Debug((stderr, "\t\tadecl.left='%s'\n", $$.left));
			Debug((stderr, "\t\tadecl.right='%s'\n", $$.right));
			Debug((stderr, "\t\tadecl.type='%s'\n", $$.type));
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			}

		| opt_constvol_list type
			{
			Debug((stderr, "adecl: opt_constvol_list type\n"));
			Debug((stderr, "\topt_constvol_list='%s'\n", $1));
			Debug((stderr, "\ttype='%s'\n", $2));
			$$.left = ds("");
			$$.right = ds("");
			$$.type = cat($1,ds(strlen($1)?" ":""),$2,NullCP);
			if (strcmp($2, "void") == 0)
			    prev = 'v';
			else if ((strncmp($2, "struct", 6) == 0) ||
			         (strncmp($2, "class", 5) == 0))
			    prev = 's';
			else
			    prev = 't';
			Debug((stderr, "\n\tadecl now =\n"));
			Debug((stderr, "\t\tadecl.left='%s'\n", $$.left));
			Debug((stderr, "\t\tadecl.right='%s'\n", $$.right));
			Debug((stderr, "\t\tadecl.type='%s'\n", $$.type));
			Debug((stderr, "\tprev = '%s'\n", visible(prev)));
			}
		;

adims		: /* empty */
			{
			Debug((stderr, "adims: EMPTY\n"));
			arbdims = 1;
			$$ = ds("[]");
			}

		| NUMBER
			{
			Debug((stderr, "adims: NUMBER\n"));
			Debug((stderr, "\tNUMBER='%s'\n", $1));
			arbdims = 0;
			$$ = cat(ds("["),$1,ds("]"),NullCP);
			}
		;

type		: tinit c_type
			{
			Debug((stderr, "type: tinit c_type\n"));
			Debug((stderr, "\ttinit=''\n"));
			Debug((stderr, "\tc_type='%s'\n", $2));
			mbcheck();
			$$ = $2;
			}
		;

tinit		: /* empty */
			{
			Debug((stderr, "tinit: EMPTY\n"));
			modbits = 0;
			}
		;

c_type		: mod_list
			{
			Debug((stderr, "c_type: mod_list\n"));
			Debug((stderr, "\tmod_list='%s'\n", $1));
			$$ = $1;
			}

		| tname
			{
			Debug((stderr, "c_type: tname\n"));
			Debug((stderr, "\ttname='%s'\n", $1));
			$$ = $1;
			}

		| mod_list tname
			{
			Debug((stderr, "c_type: mod_list tname\n"));
			Debug((stderr, "\tmod_list='%s'\n", $1));
			Debug((stderr, "\ttname='%s'\n", $2));
			$$ = cat($1,ds(" "),$2,NullCP);
			}

		| StrClaUniEnum NAME
			{
			Debug((stderr, "c_type: StrClaUniEnum NAME\n"));
			Debug((stderr, "\tStrClaUniEnum='%s'\n", $1));
			Debug((stderr, "\tNAME='%s'\n", $2));
			$$ = cat($1,ds(" "),$2,NullCP);
			}
		;

StrClaUniEnum	: ClassStruct
		| ENUM
		| UNION
			{
			$$ = $1;
			}
		;

ClassStruct	: STRUCT
		| CLASS
			{
			$$ = $1;
			}
		;

tname		: INT
			{
			Debug((stderr, "tname: INT\n"));
			Debug((stderr, "\tINT='%s'\n", $1));
			modbits |= MB_INT; $$ = $1;
			}

		| CHAR
			{
			Debug((stderr, "tname: CHAR\n"));
			Debug((stderr, "\tCHAR='%s'\n", $1));
			modbits |= MB_CHAR; $$ = $1;
			}

		| FLOAT
			{
			Debug((stderr, "tname: FLOAT\n"));
			Debug((stderr, "\tFLOAT='%s'\n", $1));
			modbits |= MB_FLOAT; $$ = $1;
			}

		| DOUBLE
			{
			Debug((stderr, "tname: DOUBLE\n"));
			Debug((stderr, "\tDOUBLE='%s'\n", $1));
			modbits |= MB_DOUBLE; $$ = $1;
			}

		| VOID
			{
			Debug((stderr, "tname: VOID\n"));
			Debug((stderr, "\tVOID='%s'\n", $1));
			modbits |= MB_VOID; $$ = $1;
			}
		;

mod_list	: modifier mod_list1
			{
			Debug((stderr, "mod_list: modifier mod_list1\n"));
			Debug((stderr, "\tmodifier='%s'\n", $1));
			Debug((stderr, "\tmod_list1='%s'\n", $2));
			$$ = cat($1,ds(" "),$2,NullCP);
			}

		| modifier
			{
			Debug((stderr, "mod_list: modifier\n"));
			Debug((stderr, "\tmodifier='%s'\n", $1));
			$$ = $1;
			}
		;

mod_list1	: mod_list
			{
			Debug((stderr, "mod_list1: mod_list\n"));
			Debug((stderr, "\tmod_list='%s'\n", $1));
			$$ = $1;
			}

		| CONSTVOLATILE
			{
			Debug((stderr, "mod_list1: CONSTVOLATILE\n"));
			Debug((stderr, "\tCONSTVOLATILE='%s'\n", $1));
			if (PreANSIFlag)
				notsupported(" (Pre-ANSI Compiler)", $1, NullCP);
			else if (RitchieFlag)
				notsupported(" (Ritchie Compiler)", $1, NullCP);
			else if ((strcmp($1, "noalias") == 0) && CplusplusFlag)
				unsupp($1, NullCP);
			$$ = $1;
			}
		;

modifier	: UNSIGNED
			{
			Debug((stderr, "modifier: UNSIGNED\n"));
			Debug((stderr, "\tUNSIGNED='%s'\n", $1));
			modbits |= MB_UNSIGNED; $$ = $1;
			}

		| SIGNED
			{
			Debug((stderr, "modifier: SIGNED\n"));
			Debug((stderr, "\tSIGNED='%s'\n", $1));
			modbits |= MB_SIGNED; $$ = $1;
			}

		| LONG
			{
			Debug((stderr, "modifier: LONG\n"));
			Debug((stderr, "\tLONG='%s'\n", $1));
			modbits |= MB_LONG; $$ = $1;
			}

		| SHORT
			{
			Debug((stderr, "modifier: SHORT\n"));
			Debug((stderr, "\tSHORT='%s'\n", $1));
			modbits |= MB_SHORT; $$ = $1;
			}
		;

opt_constvol_list: CONSTVOLATILE opt_constvol_list
			{
			Debug((stderr, "opt_constvol_list: CONSTVOLATILE opt_constvol_list\n"));
			Debug((stderr, "\tCONSTVOLATILE='%s'\n", $1));
			Debug((stderr, "\topt_constvol_list='%s'\n", $2));
			if (PreANSIFlag)
				notsupported(" (Pre-ANSI Compiler)", $1, NullCP);
			else if (RitchieFlag)
				notsupported(" (Ritchie Compiler)", $1, NullCP);
			else if ((strcmp($1, "noalias") == 0) && CplusplusFlag)
				unsupp($1, NullCP);
			$$ = cat($1,ds(strlen($2) ? " " : ""),$2,NullCP);
			}

		| /* empty */
			{
			Debug((stderr, "opt_constvol_list: EMPTY\n"));
			$$ = ds("");
			}
		;

constvol_list: CONSTVOLATILE opt_constvol_list
			{
			Debug((stderr, "constvol_list: CONSTVOLATILE opt_constvol_list\n"));
			Debug((stderr, "\tCONSTVOLATILE='%s'\n", $1));
			Debug((stderr, "\topt_constvol_list='%s'\n", $2));
			if (PreANSIFlag)
				notsupported(" (Pre-ANSI Compiler)", $1, NullCP);
			else if (RitchieFlag)
				notsupported(" (Ritchie Compiler)", $1, NullCP);
			else if ((strcmp($1, "noalias") == 0) && CplusplusFlag)
				unsupp($1, NullCP);
			$$ = cat($1,ds(strlen($2) ? " " : ""),$2,NullCP);
			}
		;

storage		: AUTO
		| EXTERN
		| REGISTER
		| STATIC
			{
			Debug((stderr, "storage: AUTO,EXTERN,STATIC,REGISTER (%s)\n", $1));
			$$ = $1;
			}
		;

opt_storage	: storage
			{
			Debug((stderr, "opt_storage: storage=%s\n", $1));
			$$ = $1;
			}

		| /* empty */
			{
			Debug((stderr, "opt_storage: EMPTY\n"));
			$$ = ds("");
			}
		;
%%
SHAR_EOF
cat << \SHAR_EOF > cdecl.1
'\" @(#)cdecl.1	2.4 3/30/88
.TH CDECL 1
.SH NAME
cdecl, c++decl \- Compose C and C++ type declarations
.SH SYNOPSIS
.B cdecl
[\-a | \-+ | \-p | \-r]
[\-cidDV]
.br
.RS .5i
.RI [[ files
\&...] |
.B explain
\&... |
.B declare
\&... |
.B cast
\&... |
.B set
\&... |
.B help
\&... |
.B ?
\&... ]
.RE
.br
.B c++decl
[\-a | \-+ | \-p | \-r]
[\-cidDV]
.br
.RS .5i
.RI [[ files
\&...] |
.B explain
\&... |
.B declare
\&... |
.B cast
\&... |
.B set
\&... |
.B help
\&... |
.B ?
\&... ]
.RE
.br
.B explain
\&...
.br
.B declare
\&...
.br
.B cast
\&...
.SH DESCRIPTION
.I Cdecl
(and
.I c++decl )
is a program for encoding and decoding C (C++) type-declarations.
The C language (the default for 
.I cdecl ,
or with the
.B \-a
option) is based on the (draft proposed) X3J11 ANSI
Standard;
optionally, the C language may be based on the pre-ANSI definition defined by
Kernighan & Ritchie's 
.I "The C Programming Language"
book (the
.B \-p
option is used), or
the C language defined by the Ritchie PDP-11 C compiler (the
.B \-r
option is used).
The C++ language (the default for
.I c++decl ,
or with the
.B \-+
option) is based on Stroustrup's
.IR "The C++ Programming Language" ,
plus the version 2.0 additions to the language.
.PP
.I Cdecl
reads the named files for statements in the language described below.
A transformation is made from that language to C (C++) or pseudo-English.
The results of this transformation are written on standard output.
If no files are named, or a filename of ``\-'' is encountered, standard input
will be read.
If standard input is coming from a terminal, (or the
.B \-i
option is used), a prompt will be written to the terminal before each line.
If
.I cdecl
is invoked as 
.IR explain ,
.IR declare
or
.IR cast ,
or the first argument is one of the commands discussed below, the argument
list will be interpreted according to the grammar shown below instead of as
file names.
.PP
You can use
.I cdecl
as you create a C program with an editor like vi(1) or emacs(1).
You simply type in the pseudo-English version of the declaration and apply
.I cdecl
as a filter to the line.
(In vi(1), type ``!!cdecl<cr>''.)
.PP
If the 
.I "create program"
option
.B \-c
is used, the output will include semi-colons after variable declarations and
curly brace pairs after function declarations.
.PP
The
.B \-V
option will print out the version numbers of the files used to create the
process.
If the source is compiled with debugging information turned on, the
.B \-d
option will enable it to be output.
If the source is compiled with YACC debugging information turned on, the
.B \-D
option will enable it to be output.
.SH "COMMAND LANGUAGE"
There are six statements in the language.
The
.I "declare"
statement composes a C type-declaration from a verbose description.
The
.I "cast"
statement composes a C type-cast as might appear in an expression.
The
.I "explain"
statement decodes a C type-declaration or cast, producing a verbose
description.
The
.I "help"
(or
.IR ? )
statement provides a help message.
The
.I "quit"
(or
.IR "exit" )
statement (or the end of file) exits the program.
The
.I "set"
statement allows the command line options to be set interactively.
Each statement is separated by a semi-colon or a newline.
.PP
The following grammar describes the language.
In the grammar, words in "<>" are non-terminals,
bare lower-case words are terminals that stand for themselves.
Bare upper-case words are other lexical tokens:
NOTHING means the empty string;
NAME means a C identifier;
NUMBER means a string of decimal digits; and
NL means the new-line or semi-colon characters.
.PP
Some synonyms are permitted during a declaration:
character \(-> char,
constant \(-> const,
enumeration \(-> enum,
func \(-> function,
integer \(-> int,
ptr \(-> pointer,
ref \(-> reference,
ret \(-> returning,
structure \(-> struct,
and
vector \(-> array.
.PP
.nf
.ft CW
.ta .5i 1.5i
	<program>	::= NOTHING
		| <program> <stmt> NL
	<stmt>	::= NOTHING
		| declare NAME as <adecl>
		| declare <adecl>
		| cast NAME into <adecl>
		| cast <adecl>
		| explain <optstorage> <ptrmodlist> <type> <cdecl>
		| explain <storage> <ptrmodlist> <cdecl>
		| explain ( <ptrmodlist> <type> <cast> ) optional-NAME
		| set <options>
		| help | ?
		| quit
		| exit
	<adecl>	::= array of <adecl>
		| array NUMBER of <adecl>
		| function returning <adecl>
		| function ( <adecl-list> ) returning <adecl>
		| <ptrmodlist> pointer to <adecl>
		| <ptrmodlist> pointer to member of class NAME <adecl>
		| <ptrmodlist> reference to <adecl>
		| <ptrmodlist> <type>
	<cdecl>	::= <cdecl1>
		| * <ptrmodlist> <cdecl>
		| NAME :: * <cdecl>
		| & <ptrmodlist> <cdecl>
	<cdecl1>	::= <cdecl1> ( )
		| <cdecl1> ( <castlist> )
		| <cdecl1> [ ]
		| <cdecl1> [ NUMBER ]
		| ( <cdecl> )
		| NAME
	<cast>	::= NOTHING
		| ( )
		| ( <cast> ) ( )
		| ( <cast> ) ( <castlist> )
		| ( <cast> )
		| NAME :: * <cast>
		| * <cast>
		| & <cast>
		| <cast> [ ]
		| <cast> [ NUMBER ]
	<type>	::= <typename> | <modlist>
		| <modlist> <typename>
		| struct NAME | union NAME | enum NAME | class NAME
	<castlist>	::= <castlist> , <castlist>
		| <ptrmodlist> <type> <cast>
		| <name>
	<adecllist>	::= <adecllist> , <adecllist>
		| NOTHING
		| <name>
		| <adecl>
		| <name> as <adecl>
	<typename>	::= int | char | double | float | void
	<modlist>	::= <modifier> | <modlist> <modifier>
	<modifier>	::= short | long | unsigned | signed | <ptrmod>
	<ptrmodlist>	::= <ptrmod> <ptrmodlist> | NOTHING
	<ptrmod>	::= const | volatile | noalias
	<storage>	::= auto | extern | register | auto
	<optstorage>	::= NOTHING | <storage>
	<options>	::= NOTHING | <options>
		| create | nocreate
		| interactive | nointeractive
		| ritchie | preansi | ansi | cplusplus
		| debug | nodebug | yydebug | noyydebug
.ft P
.fi
.SH EXAMPLES
.de Ex
.    PP
.    RS .5i
..
.de Ee
.    RE
.    PP
..
To declare an array of pointers to functions like malloc(3), do
.Ex
declare fptab as array of pointer to function returning pointer to char
.Ee
The result of this command is
.Ex
char *(*fptab[])()
.Ee
When you see this declaration in someone else's code, you
can make sense out of it by doing
.Ex
explain char *(*fptab[])()
.Ee
The proper declaration for signal(2), ignoring function prototypes, is easily
described in
.IR cdecl 's
language:
.Ex
declare signal as function returning pointer to function returning void
.Ee
which produces
.Ex
void (*signal())()
.Ee
The function declaration that results has two sets of empty parentheses.
The author of such a function might wonder where to put the parameters:
.Ex
declare signal as function (arg1,arg2) returning pointer to function returning
void
.Ee
provides the following solution (when run with the
.I \-c
option):
.Ex
void (*signal(arg1,arg2))()
{
}
.Ee
If we want to add in the function prototypes, the function prototype for a
function such as _exit(2) would be declared with:
.Ex
declare _exit as function (retvalue as int) returning void
.Ee
giving
.Ex
void _exit(int retvalue)
{
}
.Ee
As a more complex example using function prototypes, signal(2) could be fully
defined as:
.Ex
declare signal as function(x as int, y as pointer to function(int)
returning void) returning pointer to function(int) returning void
.Ee
giving (with \-c)
.Ex
void (*signal(int x, void (*y)(int )))(int )
{
}
.Ee
.I Cdecl
can help figure out the where to put the "const" and "volatile" modifiers
in declarations, thus
.Ex
declare foo as pointer to const int
.Ee
gives
.Ex
const int *foo
.Ee
while
.Ex
declare foo as const pointer to int
.Ee
gives
.Ex
int * const foo
.Ee
.I C++decl
can help with declaring references, thus
.Ex
declare x as reference to pointer to character
.Ee
gives
.Ex
char *&x
.Ee
.I C++decl
can help with pointers to member of classes, thus
declaring a pointer to an integer member of a class X with
.Ex
declare foo as pointer to member of class X int
.Ee
gives
.Ex
int X::*foo
.Ee
and
.Ex
declare foo as pointer to member of class X function (arg1, arg2) returning
pointer to class Y
.Ee
gives
.Ex
class Y *(X::*foo)(arg1, arg2)
.Ee
.SH DIAGNOSTICS
The declare, cast and explain statements try to point out constructions that
are not supported in C.
In some cases, a guess is made as to what was really intended.
In these cases, the C result is a toy declaration whose semantics will work
only in Algol-68.
The list of unsupported C constructs is dependent on which version of the C
language is being used (see the ANSI, pre-ANSI, and Ritchie options).
The set of supported C++ constructs is a superset of the ANSI set, with the
exception of the
.B noalias
keyword.
.SH "SEE ALSO"
(draft proposed) ANSI National Standard X3J11
.sp
\(sc8.4 of the C Reference Manual within
.I "The C Programming Language"
by B. Kernighan & D. Ritchie.
.sp
\(sc8 of the C++ Reference Manual within
.I "The C++ Programming Language"
by B. Stroustrup.
.SH CAVEATS
The pseudo-English syntax is excessively verbose.
.PP
There is a wealth of semantic checking that isn't being done.
.PP
.I Cdecl's
scope is intentionally small.
It doesn't help you figure out initializations.
It expects storage classes to be at the beginning of a declaration,
followed by the the const, volatile and noalias modifiers, followed by the
type of the variable.
.I Cdecl
doesn't know anything about variable length argument lists.
(This includes the ``\f(CW,...\fP'' syntax.)
.PP
.I Cdecl
thinks all the declarations you utter are going to be used as external
definitions.
Some declaration contexts in C allow more flexibility than this.
An example of this is:
.Ex
declare argv as array of array of char
.Ee
where
.I cdecl
responds with
.Ex
.nf
Warning: Unsupported in C -- 'Inner array of unspecified size'
        (maybe you mean "array of pointer")
char argv[][]
.fi
.Ee
.PP
Tentative support for the
.I noalias
keyword has been put in because it is in the current ANSI specifications.
SHAR_EOF
#	End of shell archive
exit 0
-- 
Bob Page, U of Lowell CS Dept.  page@swan.ulowell.edu  ulowell!page
Have five nice days.