我的c\c++之旅(十一)——声明器

声明器

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

#define MAXLENGTH		100
#define MAXWORDLENGTH	50

enum Type_Tag {IDENTIFIER, QUALIFIER, TYPE};

struct Words {	
	char name[MAXWORDLENGTH];
	char type;	
};

int top = -1;
struct Words stack[MAXLENGTH];
struct Words current;
#define push(x)	stack[++top] = x
#define pop()	stack[top--]

void Dealwith_Identifier(void);
void Dealwith_Declaration(void);
void Get_Words(void);
enum Type_Tag Classify_Word(void);
void Dealwith_Array(void);
void Dealwith_Function(void);
void Dealwith_Pointer(void);

int main()
{
	Dealwith_Identifier();
	Dealwith_Declaration();
	return 0;
}

void Dealwith_Identifier(void)
{
	Get_Words();
	while(current.type != IDENTIFIER) {
		push(current);
		Get_Words();
	}
	printf("%s is ", current.name);
}

void Dealwith_Declaration(void)
{
	Get_Words();
	switch(current.type) {
	case '[':
		Dealwith_Array();
		break;
	case '(':
		Dealwith_Function();
		break;
	}

	Dealwith_Pointer();
	while(top != -1) {
		if(stack[top].type == '(') {
			pop();
			Dealwith_Declaration();
		} else
			printf("%s ", pop().name);
	}
}

void Get_Words(void)
{
	char *p = current.name;

	while((*p = getchar()) == ' ');
	if(isalnum(*p)) {
		while(isalnum(*++p = getchar()));
		ungetc(*p, stdin);
		*p = '\0';
		current.type = Classify_Word();
	} else if(*p == '*') {
		strcpy(p, "pointer to");
		current.type = '*';
	} else {		
		current.type = *p;
		*++p = '\0';
	}
	return;
}

enum Type_Tag Classify_Word(void)
{
	char *p = current.name;

	if(!strcmp(p, "const")) {
		strcpy(p, "read-only");
		return QUALIFIER;
	}
	if(!strcmp(p, "volatile")) return QUALIFIER;
	if(!strcmp(p, "char")) return TYPE;
	if(!strcmp(p, "signed")) return TYPE;
	if(!strcmp(p, "unsigned")) return TYPE;
	if(!strcmp(p, "short")) return TYPE;
	if(!strcmp(p, "int")) return TYPE;
	if(!strcmp(p, "long")) return TYPE;
	if(!strcmp(p, "float")) return TYPE;
	if(!strcmp(p, "double")) return TYPE;
	if(!strcmp(p, "struct")) return TYPE;
	if(!strcmp(p, "union")) return TYPE;
	if(!strcmp(p, "enum")) return TYPE;
	return IDENTIFIER;
}

void Dealwith_Array(void)
{
	while(current.type == '[') {
		printf("array ");
		Get_Words();
		if(isdigit(current.name[0])) {
			printf("0...%d ", atoi(current.name)-1);
			Get_Words();
		}
		printf("of ");
		Get_Words();
	}
}

void Dealwith_Function(void)
{
	while(current.type != ')')
		Get_Words();	
	printf("function return ");
	Get_Words();
}

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值