-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.y
156 lines (132 loc) · 2.31 KB
/
parse.y
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
%{
#include <stdio.h>
#include <string.h>
char *new_str(const char *str);
int yylex();
void yyerror(const char *);
struct Node {
char *pre;
char *post;
struct Node *right;
struct Node *down;
};
struct Node* new_node();
struct Node* start=NULL;
%}
%define parse.error verbose
%union {
char *str;
struct Node *node;
}
%token <str> __STRING_LITERAL
%token <str> __NUMBER
%token <str> __BOOLEAN __NULL
%type <node> object members pair array elements value
%%
document: object {
start=$1;
}
;
object: '{' members '}' {
$$ = $2;
}
;
members: /*nothing*/ {
$$=NULL;
}
| pair {
$$=$1;
}
| pair ',' members {
$$=$1; $1->down=$3;
}
;
pair: __STRING_LITERAL ':' value {
$1[strlen($1)-1]='\0';
$$=new_node();
$$->pre=(char *)malloc(sizeof(char)*strlen($1)+10);
sprintf($$->pre,"<%s>",$1+1);
$$->post=(char *)malloc(sizeof(char)*strlen($1)+10);
sprintf($$->post,"</%s>",$1+1);
$$->right=$3;
}
;
elements: value {
$$=new_node();
$$->pre=new_str((const char*)"<elem>");
$$->post=new_str((const char*)"</elem>");
$$->right=$1;
}
| value ',' elements {
$$=new_node();
$$->pre=new_str((const char*)"<elem>");
$$->post=new_str((const char*)"</elem>");
$$->right=$1;
$$->down=$3;
}
;
array: '[' ']' {
$$=NULL;
}
| '[' elements ']' {
$$=$2;
}
;
value: object {
$$=$1;
}
| array {
$$=$1;
}
| __STRING_LITERAL {
$$=new_node(); $$->pre=$1;
}
| __NUMBER {
$$=new_node(); $$->pre=$1;
}
| __BOOLEAN {
$$=new_node(); $$->pre=$1;
}
| __NULL {
$$=new_node(); $$->pre=$1;
}
;
%%
const struct Node def={NULL,NULL,NULL,NULL};
struct Node* new_node()
{
struct Node *tmp=(struct Node*)malloc(sizeof(struct Node));
*tmp=def;
return tmp;
}
void pr_t(int n)
{
while(n--)
printf("\t");
}
void print_tree(struct Node *tree, int t)
{
if(tree->pre)
{
pr_t(t);
printf("%s\n",tree->pre);
}
if(tree->right)
print_tree(tree->right,t+1);
if(tree->post)
{
pr_t(t);
printf("%s\n",tree->post);
}
if(tree->down)
print_tree(tree->down,t);
}
void yyerror(const char *s) {
printf("\n%s\n",s);
}
int main(void) {
yyparse();
if(start)
print_tree(start, 0);
return 0;
}