-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson.y
More file actions
108 lines (108 loc) · 1.7 KB
/
Copy pathjson.y
File metadata and controls
108 lines (108 loc) · 1.7 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
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
%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern int yylex();
extern int yyparse();
extern FILE *yyin;
extern char* yytext;
int errorPrinted = 0;
void yyerror(const char *detail);
%}
%union
{
int num;
4
char *str;
}
%token TRUE FALSE NULL_TOKEN
%token STRING NUMBER
%token OPEN_BRACE CLOSE_BRACE OPEN_BRACKET CLOSE_BRACKET COLON
COMMA
%type <num> NUMBER
%type <str> STRING
%start json
%%
json:
value { printf("\n\t\t\tJSON is valid!\n"); }
;
value:
STRING
| NUMBER
| TRUE
| FALSE
| NULL_TOKEN
| object
| array
;
object:
OPEN_BRACE members CLOSE_BRACE
;
members:
pair
| pair COMMA members
;
pair:
STRING COLON value
;
array:
OPEN_BRACKET elements CLOSE_BRACKET
;
elements:
value
| value COMMA elements
;
%%
void yyerror(const char *detail) {
if (!errorPrinted) {
printf("\n\t\t\tJSON is invalid\n\t\t\tError: %s\n", detail);
fprintf(stderr,"\t\t\tUnexpected or missing character near: %s\n", yytext);
errorPrinted = 1;
}
}
int main(int argc, char *argv[])
{
if (argc < 2)
{
fprintf(stderr, "Usage: %s <input_file>\n", argv[0]);
return 1;
}
yyin = fopen(argv[1], "r");
if (!yyin)
{
perror(argv[1]);
return 1;
}
printf("\n\n\t\t\t+
+\n");
printf("\t\t\t|\t\t\t\t\t\t\t\t\tJSON Parser\t\t\t\t\t\t\t\t\t|");
printf("\n\t\t\t+
+\n\n");
printf("\t\t\t**Input file content:**\n\n");
int ch;
int indentation = 28;
6
int isFirstCharacter = 1;
while ((ch = fgetc(yyin)) != EOF) {
if (isFirstCharacter) {
for (int i = 0; i < indentation; ++i) {
putchar(' ');
}
isFirstCharacter = 0;
}
putchar(ch);
if (ch == '\n') {
isFirstCharacter = 1;
}
}
rewind(yyin);
printf("\n\t\t\t+
+\n");
printf("\t\t\t|\t\t\t\t\t\t\t\t\tParsed Output\t\t\t\t\t\t\t\t\t|\n");
printf("\t\t\t+
+\n\n");
yyparse();
fclose(yyin);
printf("\n\n\n");
return 0;
}