-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathjson.y
136 lines (116 loc) · 2.92 KB
/
json.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
/*
* Simple JSON parser
*
* $ lrama -d json.y -o json.c && gcc -Wall json.c -o json && ./json <<< '{"foo": 42, "bar": [1, 2, 3], "baz": {"qux": true}}'
* JSON parsed successfully!
* $ lrama -d json.y -o json.c && gcc -Wall json.c -o json && ./json <<< '{"foo": invalid }'
* Unexpected literal: invalid
*/
%{
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
%}
%code provides {
static int yylex(YYSTYPE *lval, YYLTYPE *loc);
static int yyerror(YYLTYPE *loc, const char *s);
}
%union {
char *str;
double num;
}
%token STRING NUMBER TRUE FALSE NULL_T
%locations
%%
json: object
| array
;
object: '{' members? '}'
;
members: separated_nonempty_list(',', pair)
;
pair: STRING ':' value
;
array: '[' elements? ']'
;
elements: separated_nonempty_list(',', value)
;
value: STRING | NUMBER | object | array | TRUE | FALSE | NULL_T;
%%
static int yylex(YYSTYPE *yylval, YYLTYPE *loc) {
int c;
while ((c = getchar()) != EOF && isspace(c));
if (c == EOF) return 0;
if (c == '{' || c == '}' || c == '[' || c == ']' || c == ':' || c == ',') {
return c;
}
if (c == '"') {
char buffer[1024];
int i = 0;
while ((c = getchar()) != EOF && c != '"') {
if (c == '\\') {
int next = getchar();
if (next == EOF)
break;
buffer[i++] = next;
} else {
buffer[i++] = c;
}
if (i >= 1023)
break;
}
buffer[i] = '\0';
yylval->str = strdup(buffer);
return STRING;
}
if (c == '-' || isdigit(c)) {
char num_buffer[64];
int i = 0;
num_buffer[i++] = c;
while ((c = getchar()) != EOF && (isdigit(c) || c == '.')) {
num_buffer[i++] = c;
if (i >= 63)
break;
}
num_buffer[i] = '\0';
if (c != EOF)
ungetc(c, stdin);
yylval->num = atof(num_buffer);
return NUMBER;
}
if (isalpha(c)) {
char word[16];
int i = 0;
word[i++] = c;
while ((c = getchar()) != EOF && isalpha(c)) {
word[i++] = c;
if (i >= 15)
break;
}
word[i] = '\0';
if (c != EOF)
ungetc(c, stdin);
if (strcmp(word, "true") == 0)
return TRUE;
else if (strcmp(word, "false") == 0)
return FALSE;
else if (strcmp(word, "null") == 0)
return NULL_T;
else {
fprintf(stderr, "Unexpected literal: %s\n", word);
exit(1);
}
}
fprintf(stderr, "Unexpected character: %c\n", c);
return 0;
}
static int yyerror(YYLTYPE *loc, const char *s) {
fprintf(stderr, "Error: %s\n", s);
return 0;
}
int main() {
yyparse();
printf("JSON parsed successfully!\n");
return 0;
}