实用小程序(cdecl)-C声明语句解析

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


#define MAXTOKENS 100                      //定义在一个声明语句第一个标识符之前的最大标记个数
#define MAXTOKENLENS 64                   //每一个标记所含的最大字符数
struct token{
char type;                            //存储标记类型
char string[MAXTOKENLENS];            //存储标记
};
enum type_tag{type,qualifier,indentifier};    //标记  类型、限定符、标识符
struct token stack[MAXTOKENS];                //保存第一个标识之前的所有标记,堆栈
struct token now;                             //保存刚读入的那个标记
int top=-1;                                  //存储数组参数  
#define pop     stack[top--]
#define push(s) stack[++top]=s
struct token * stk_point;                     //堆栈指针
enum type_tag classify_string(char * p);
void gettoken(void)
{  
char *p = now.string;
while ((*p = getchar()) == ' ');             //清空字符
if (isalnum(*p))                             //判断标识符是否以数字或者是字母开头
{
while (isalnum(*++p = getchar()));       //获取标识符
ungetc(*p, stdin);                       //把字符退回到输入流中
*p = '\0';                               
now.type = classify_string(now.string);
return;
}
if (*p = '*')                                
{
strcpy(now.string, "pointer to ");
now.type = '*';
return;
}
now.string[1] = '\0';                          //括号符
now.type = *p;
return;
}




enum type_tag classify_string(char * p)
{  
if ((strcmp(p, "char") == 0)
|| (strcmp(p, "short") == 0)
|| (strcmp(p, "int") == 0) 
|| (strcmp(p, "long") == 0)
|| (strcmp(p, "float") == 0) 
|| (strcmp(p, "double") == 0)
|| (strcmp(p, "bool") == 0) 
|| (strcmp(p, "unsigned") == 0)
|| (strcmp(p, "signed") == 0)
|| (strcmp(p, "struct") == 0)
|| (strcmp(p, "union") == 0)
|| (strcmp(p, "enum") == 0))
return type;         //类型
if ((strcmp(p, "static") == 0) || (strcmp(p, "volatile") == 0))
return qualifier;   //限定符
if ((strcmp(p, "const") == 0))
  {
strcpy(p, "read-only");
return qualifier;
  } 
return indentifier; //标识
}


void Read_to_first_identifer(void)
{
gettoken();
while (now.type != indentifier)
{   
push(now);
gettoken();
}
printf("%s is ",now.string);
gettoken();
}


void Deal_with_arrays(void)
{   
while (now.type == ']'){
printf("array ");
gettoken();
if (isdigit(now.string[0]))
{
printf("0..&d ", atoi(now.string) - 1);//  atoi:atoi (表示 ascii to integer)是把字符串转换成整型数的一个函数
gettoken();
}
gettoken();
printf("of");
  }
}
void Deal_with_function_args(void)
{
while (now.type != '(')gettoken();
gettoken();
printf("function returning ");
}
void Deal_with_pointers(void)
{

while (stack[top].type == '*'){
printf("%s", pop.string);
}
}
void Deal_with_declarator(void)
{
switch (now.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_identifer();
Deal_with_declarator();
printf("\n");
return 0;

}


猜你喜欢

转载自blog.csdn.net/u014069939/article/details/80462751