Skip to content

Instantly share code, notes, and snippets.

@prehistoricpenguin
Created December 26, 2012 12:38
Show Gist options
  • Select an option

  • Save prehistoricpenguin/4380145 to your computer and use it in GitHub Desktop.

Select an option

Save prehistoricpenguin/4380145 to your computer and use it in GitHub Desktop.
cdecl
/*
* cdecl
*/
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#define MAXTOKEN 100
enum TokenType {NAME, PARENS, BRACKETS};
void dcl();
void dirdcl();
int gettoken();
int tokentype;
char token[MAXTOKEN];
char name[MAXTOKEN];
char datatype[MAXTOKEN];
char out[10086];
void dcl()
{
int ns;
for (ns = 0; gettoken() == '*';) /* count *'s */
++ns;
dirdcl();
while (ns-- > 0)
strcat(out, " pointer to");
}
void dirdcl()
{
int type;
if (tokentype == '(')
{
dcl();
if (tokentype != ')')
{
fprintf(stderr, "error: missing )\n");
exit(EXIT_FAILURE);
}
}
else if (tokentype == NAME)
strcpy(name, token);
else
{
fprintf(stderr, "error: expected name or (dcl)\n");
exit(EXIT_FAILURE);
}
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()
{
int c;
char* p = token;
while ((c = getchar()) == ' ' || c == '\t')
;
if (c == '(')
{
if ((c = getchar()) == ')')
{
strcpy(token, "()");
return tokentype = PARENS;
}
else
{
ungetc(c, stdin);
return tokentype = '(';
}
}
else if (c == '[')
{
for (*p++ = c; (*p++ = getchar()) != ']';)
;
*p = '\0';
return tokentype = BRACKETS;
}
else if (isalpha(c))
{
for (*p++ = c; isalnum(c = getchar());)
*p++ = c;
*p = '\0';
ungetc(c, stdin);
return tokentype = NAME;
}
else
return tokentype = c;
}
int main()
{
printf("input your declarelation statement:\n");
while (gettoken() != EOF)
{
strcpy(datatype, token);
out[0] = '\0';
dcl();
if (tokentype != '\n')
{
fprintf(stderr, "syntax error!\n");
exit(EXIT_FAILURE);
}
printf("%s: %s %s\n", name, out, datatype);
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment