-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.c
More file actions
executable file
·80 lines (79 loc) · 1.93 KB
/
main.c
File metadata and controls
executable file
·80 lines (79 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include"tree.h"
#include"lex.yy.c"
extern void yyrestart(FILE *input_file);
extern int yyparse(void);
extern char *yytext;
//新建一个叶子节点
struct Ast* newLeaf(char* s,int yyline)
{
struct Ast *l=(struct Ast *)malloc(sizeof(struct Ast));
l->name=s; //语法单元名字
l->line=yyline;
l->n=0;
if((!strcmp(l->name,"ID"))||(!strcmp(l->name,"TYPE")))
{
char *t;
t=(char *)malloc(sizeof(char *)*10);
strcpy(t,yytext);
l->type=t;
}
else if(!strcmp(l->name,"INT"))
l->i=atoi(yytext);
else if(!strcmp(l->name,"FLOAT"))
l->f=atof(yytext);
return l;
}
//新建一个语法树分支节点
struct Ast *newNode(char *s,int yyline,int num,struct Ast* arr[])
{
struct Ast *l=(struct Ast *)malloc(sizeof(struct Ast));
l->name=s;
l->line=yyline;
l->n=num;
for(int i=0;i<l->n;i++)
l->child[i]=arr[i];
return l;
}
//实现对空的处理
struct Ast *newNode0(char *s,int num)
{
struct Ast *l=(struct Ast *)malloc(sizeof(struct Ast));
l->name=s;
l->n=0;
l->line=-1;
return l;
}
//遍历语法树
void printTree(struct Ast* r,int layer)
{
if(r!=NULL && r->line!=-1)
{
for(int i=0;i<layer;i++)
printf(" ");
printf("%s",r->name);//语法单元名字
if((!strcmp(r->name,"ID"))||(!strcmp(r->name,"TYPE")))
printf(": %s",r->type);
else if(!strcmp(r->name,"INT"))
printf(": %d",r->i);
else if(!strcmp(r->name,"FLOAT"))
printf(": %f",r->f);
else if(r->n!=0) //语法单元输出行号
printf(" (%d)",r->line);
printf("\n");
for(int k=0;k<r->n;k++)
printTree(r->child[k],layer+1);
}
}
int main(int argc, char** argv) {
if(argc<=1)
return 1;
FILE* f=fopen(argv[1],"r");
if(!f)
{
perror(argv[1]);
return 1;
}
yyrestart(f);
yyparse();
return 0;
}