C語言cdelc實現

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#define MAXTOKENLEN 64
#define MAXTOKENS 100

/*《C專家編程》:cdecl 實現 註釋見P71*/

enum type_tag {IDENTIFIER,QUALIFIER,TYPE};

struct token 
{
  char type;
  char string[MAXTOKENLEN];
};

int top = -1;
struct token stack[MAXTOKENS];
struct token This;

#define pop stack[top--]
#define push(s) stack[++top] = s

enum type_tag classify_string(void)
{
  char *s = This.string;
  if(!strcmp(s,"const"))
  {
    strcpy(s,"read_only");
	return QUALIFIER;
  }

  if(!strcmp(s,"void")) return TYPE;
  if(!strcmp(s,"char")) return TYPE;
  if(!strcmp(s,"void")) return TYPE;
  if(!strcmp(s,"signed")) return TYPE;
  if(!strcmp(s,"unsigned")) return TYPE;
  if(!strcmp(s,"short")) return TYPE;
  if(!strcmp(s,"int")) return TYPE;
  if(!strcmp(s,"long")) return TYPE;
  if(!strcmp(s,"float")) return TYPE;
  if(!strcmp(s,"double")) return TYPE;
  if(!strcmp(s,"struct")) return TYPE;
  if(!strcmp(s,"union")) return TYPE;
  if(!strcmp(s,"enum"))  return TYPE;

  return IDENTIFIER;
}

void gettoken()   
{ 
  char *p = This.string;

  while((*p = getchar()) == ' ')
	  ;

  if(isalnum(*p))
  {
    while(isalnum(*++p = getchar()))
		;
	ungetc(*p,stdin);
	*p = '\0';
	This.type = classify_string();
	return ;
  }

  if(*p == '*')
  {
	  strcpy(This.string,"pointer to");
	  This.type = '*';
	  return ;
  }

  This.string[1] = '\0';
  This.type = *p;
  return ;
}

void read_to_first_identifier()
{ 
  gettoken();
  while(This.type != IDENTIFIER)
  {
    push(This);
	gettoken();
  }

  printf("%s is ",This.string);
  gettoken();
}

void deal_with_arrays()
{
  while(This.type == '[')
  {
    printf("array ");
	gettoken();
	if(isdigit(This.string[0]))
	{
	  printf("0 ... %d ",atoi(This.string - 1));
	  gettoken();
	}
	gettoken();
	printf("of ");
  }

}

void deal_with_function_args()
{
  while(This.type != ')')
  {
    gettoken();
  }
  gettoken();
  printf("function returning ");
}

void deal_with_pointers()
{ 
  while(stack[top].type == '*')
  {
    printf("%s ",pop.string);
  }
}


void deal_with_declarator()
{ 
  switch(This.type )
  {
  case '[': deal_with_arrays();break;
  case '(': deal_with_function_args();
  }

  deal_with_pointers();

  while(top >= 0)
  {
    if(stack[top].type == '(')
	{
	  pop;
	  gettoken();
	  deal_with_declarator();
	}
	else
	{
	  printf("%s ",pop.string);
	}
  }
}

int main()
{ 
  read_to_first_identifier();
  deal_with_declarator();
  printf("\n");
  return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章