-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathccjsonparser.js
More file actions
301 lines (269 loc) · 8.84 KB
/
Copy pathccjsonparser.js
File metadata and controls
301 lines (269 loc) · 8.84 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
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
const fs = require("fs");
// It returns an array of tokens or an error if it encounters an unexpected character
// Tokens are objects with a type property, e.g., {type: "LBRACE
function lex(input){
const tokens = [];
let i = 0;
const isWhitespace = (char) => /\s/.test(char);
const isDigit = (char) => /[0-9]/.test(char);
while (i < input.length) {
const ch = input[i];
if(isWhitespace(ch)){
i++;
continue;
}
if (ch === '{'){
tokens.push({ type: "LBRACE"});
i++;
continue;
}
if (ch === '}'){
tokens.push({ type: "RBRACE"});
i++;
continue;
}
if (ch === ':'){
tokens.push({ type: "COLON"});
i++;
continue;
}
if (ch === ','){
tokens.push({ type: "COMMA"});
i++;
continue;
}
if (ch === '"'){
// Parse a string
let str = "";
i++;
while (i < input.length && input[i] !== '"'){
if (input[i] === "\\" ) {
i++;
if(i >= input.length){
return {tokens, error: "Unterminated escape sequence"};
}
const escapeChar = input[i++];
switch (escapeChar) {
case '"': str += '"'; break;
case "\\": str += "\\"; break;
case "/": str += "/"; break;
case "b": str += "\b"; break;
case "f": str += "\f"; break;
case "n": str += "\n"; break;
case "r": str += "\r"; break;
case "t": str += "\t"; break;
case "u":
if (i+4 > input.length){
return {tokens, error: "Invalid unicode escape sequence"};
}
const hex = input.slice(i, i + 4);
if (!/^[0-9a-fA-F]{4}$/.test(hex)){
return {tokens, error: "Invalid unicode escape sequence"};
}
str += String.fromCharCode(parseInt(hex, 16));
i += 4;
break;
default:
return {tokens, error: `Invalid escape character: \\${escapeChar}`};
}
} else {
if (input.charCodeAt(i) < 0x20){
return {tokens, error: "Invalid string: control characters must be escaped"};
}
str += input[i++];
}
}
if(i >= input.length){
return {tokens, error: "Unterminated string"};
}
i++; // Skip closing quote
tokens.push({ type: "STRING", value: str});
continue;
}
if(input.startsWith("true", i)){
tokens.push({ type: "TRUE", value: true});
i += 4;
continue;
}
if(input.startsWith("false", i)){
tokens.push({ type: "FALSE", value: false});
i += 5;
continue;
}
if (input.startsWith("null", i)){
tokens.push({ type: "NULL", value: null});
i += 4;
continue;
}
if( ch ==='['){
tokens.push({type: "LBRACKET"});
i++;
continue;
}
if( ch ===']'){
tokens.push({type: "RBRACKET"});
i++;
continue;
}
if( ch === '-' || isDigit(ch)){
let numStr = "";
if (ch === "-"){
numStr += ch;
i++;
}
if (ch === "0"){
numStr += ch;
i++;
if(i <input.length && isDigit(input[i])){
return {tokens, error: "Invalid number: leading zeros are not allowed"};
}
}
while (i < input.length && isDigit(input[i])){
numStr += input[i++];
}
if( i < input.length && input[i] === '.' ){
numStr += input[i++];
const decimalStart = i;
while (i < input.length && isDigit(input[i])){
numStr += input[i++];
}
if (decimalStart === i){
return{tokens, error: "Invalid decimal missing digits"};
}
}
if ( i < input.length && (input[i] === 'e' || input[i] === 'E')){
numStr += input[i++];
if( input[i] === '+' || input[i] === '-'){
numStr += input[i++];
}
const expStart = i;
while (i < input.length && isDigit(input[i])){
numStr += input[i++];
}
if (expStart === i){
return {tokens, error: "Invalid exponent missing digits"};
}
}
tokens.push({ type: "NUMBER", value: Number(numStr)});
continue;
}
// If we reach here, it's an unexpected character
return {tokens, error: `Unexpected character: '${ch}' at position ${i}`};
}
tokens.push({ type: "EOF"});
return {tokens, error: null};
}
// A simple parser that checks for balanced braces in the token stream
// It returns true if the braces are balanced, false otherwise
function parse(tokens){
let pos = 0;
const peek = () => tokens[pos];
const consume = (type) => {
if (peek()?.type === type) return tokens[pos++];
throw new Error(`Expected ${type} but found ${peek()?.type || "EOF"}`);
};
function parseValue(){
switch (peek().type) {
case "STRING":
return consume("STRING").value;
case "NUMBER":
return consume("NUMBER").value;
case "TRUE":
return consume("TRUE").value;
case "FALSE":
return consume("FALSE").value;
case "NULL":
return consume("NULL").value;
case "LBRACE":
return parseObject();
case "LBRACKET":
return parseArray();
default:
throw new Error(`Expected value but found ${peek()?.type || "EOF"}`);
}
}
function parseObject(){
consume("LBRACE");
const obj = {};
if (peek().type === 'RBRACE'){
consume("RBRACE");
return obj;
}
while (true){
// parse one or more key-value pairs
if (peek().type !== "STRING"){
throw new Error(`Expected STRING but found ${peek()?.type || "EOF"}`);
}
const key = consume("STRING").value;
consume("COLON");
obj[key] = parseValue();
if (peek().type === "COMMA"){
consume("COMMA");
continue;
}
if (peek().type === "RBRACE"){
consume("RBRACE");
break;
}
throw new Error(`Expected COMMA or RBRACE but found ${peek()?.type || "EOF"}`);
}
return obj;
}
function parseArray(){
consume("LBRACKET");
const arr = [];
if (peek().type === "RBRACKET"){
consume("RBRACKET");
return arr;
}
while (true){
arr.push(parseValue());
if (peek().type === "COMMA"){
consume("COMMA");
continue;
}
if (peek().type === "RBRACKET"){
consume("RBRACKET");
break;
}
throw new Error(`Expected COMMA or RBRACKET but found ${peek()?.type || "EOF"}`);
}
return arr;
}
const result = parseValue();
consume("EOF");
return result;
}
// Main function to read a file, lex and parse its contents, and report validity
function main() {
const args = process.argv.slice(2);
if (args.length !==1){
console.error("Usage: node ccjsonparser.js <json-string>");
process.exit(1);
}
const path = args[0];
let contents;
try {
contents = fs.readFileSync(path, "utf8");
} catch (e) {
console.error(`Error: could not read file "${path}": ${e.message}`);
process.exit(1);
}
const {tokens, error: lexError} = lex(contents);
if (lexError) {
console.error(`Invalid JSON in ${path}: ${lexError}`);
process.exit(1);
}
try{
const result = parse(tokens);
console.log(`Valid JSON in ${path}:`);
console.log(JSON.stringify(result, null, 2));
process.exit(0);
} catch (e) {
console.error(`Invalid JSON in ${path}: ${e.message}`);
process.exit(1);
}
}
if (require.main === module){
main();
}