-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
538 lines (453 loc) · 13 KB
/
Copy pathscript.js
File metadata and controls
538 lines (453 loc) · 13 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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
// Sample JSON Schema
const sampleSchema = `{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Product",
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"price": {
"type": "number",
"minimum": 0
}
},
"required": ["id", "name", "price"]
}`;
// DOM elements
const jsonInput = document.getElementById("jsonInput");
const analyzeBtn = document.getElementById("analyzeBtn");
const sampleBtn = document.getElementById("sampleBtn");
const clearBtn = document.getElementById("clearBtn");
const tokensOutput = document.getElementById("tokensOutput");
const astOutput = document.getElementById("astOutput");
const validationOutput = document.getElementById("validationOutput");
// Token types
const TokenType = {
LEFT_BRACE: "LEFT_BRACE",
RIGHT_BRACE: "RIGHT_BRACE",
LEFT_BRACKET: "LEFT_BRACKET",
RIGHT_BRACKET: "RIGHT_BRACKET",
COLON: "COLON",
COMMA: "COMMA",
STRING: "STRING",
NUMBER: "NUMBER",
BOOLEAN: "BOOLEAN",
NULL: "NULL",
KEYWORD: "KEYWORD",
ERROR: "ERROR",
};
// JSON Schema keywords
const jsonSchemaKeywords = [
"$schema",
"title",
"description",
"type",
"properties",
"required",
"minimum",
"maximum",
"minLength",
"maxLength",
"items",
"additionalProperties",
"definitions",
"$ref",
];
// Button event listeners
sampleBtn.addEventListener("click", () => {
jsonInput.value = sampleSchema;
analyzeJSON();
});
clearBtn.addEventListener("click", () => {
jsonInput.value = "";
tokensOutput.textContent = "";
astOutput.textContent = "";
validationOutput.textContent = "";
});
analyzeBtn.addEventListener("click", analyzeJSON);
// Main analysis function
function analyzeJSON() {
try {
const input = jsonInput.value;
// Run lexical analysis
const tokens = lexicalAnalysis(input);
displayTokens(tokens);
// Run syntax analysis
const ast = syntaxAnalysis(tokens);
displayAST(ast);
// Run validation
const validationResults = validateSchema(ast);
displayValidation(validationResults);
} catch (error) {
tokensOutput.textContent = "Error analyzing JSON: " + error.message;
astOutput.textContent = "Error analyzing JSON: " + error.message;
validationOutput.textContent = "Error analyzing JSON: " + error.message;
}
}
// Lexical analysis function
function lexicalAnalysis(input) {
const tokens = [];
let position = 0;
function isWhitespace(char) {
return /\s/.test(char);
}
function isDigit(char) {
return /[0-9]/.test(char);
}
function scanToken() {
// Skip whitespace
while (position < input.length && isWhitespace(input[position])) {
position++;
}
if (position >= input.length) return null;
const char = input[position];
// Handle single-character tokens
if (char === "{") {
position++;
return { type: TokenType.LEFT_BRACE, value: "{" };
}
if (char === "}") {
position++;
return { type: TokenType.RIGHT_BRACE, value: "}" };
}
if (char === "[") {
position++;
return { type: TokenType.LEFT_BRACKET, value: "[" };
}
if (char === "]") {
position++;
return { type: TokenType.RIGHT_BRACKET, value: "]" };
}
if (char === ":") {
position++;
return { type: TokenType.COLON, value: ":" };
}
if (char === ",") {
position++;
return { type: TokenType.COMMA, value: "," };
}
// Handle strings
if (char === '"') {
const start = position;
position++; // Skip opening quote
while (position < input.length && input[position] !== '"') {
// Handle escaped characters
if (input[position] === "\\") {
position++; // Skip the escape character
}
position++;
}
if (position >= input.length) {
return { type: TokenType.ERROR, value: "Unterminated string" };
}
position++; // Skip closing quote
const value = input.substring(start, position);
const content = value.slice(1, -1); // Remove quotes
// Check if it's a JSON Schema keyword
if (jsonSchemaKeywords.includes(content)) {
return { type: TokenType.KEYWORD, value, content };
}
return { type: TokenType.STRING, value, content };
}
// Handle numbers
if (isDigit(char) || char === "-") {
const start = position;
// Handle negative sign
if (char === "-") {
position++;
}
// Integer part
while (position < input.length && isDigit(input[position])) {
position++;
}
// Decimal part
if (position < input.length && input[position] === ".") {
position++;
while (position < input.length && isDigit(input[position])) {
position++;
}
}
const value = input.substring(start, position);
return { type: TokenType.NUMBER, value };
}
// Handle literals
if (char === "t" && input.substr(position, 4) === "true") {
position += 4;
return { type: TokenType.BOOLEAN, value: "true" };
}
if (char === "f" && input.substr(position, 5) === "false") {
position += 5;
return { type: TokenType.BOOLEAN, value: "false" };
}
if (char === "n" && input.substr(position, 4) === "null") {
position += 4;
return { type: TokenType.NULL, value: "null" };
}
// Unrecognized token
position++;
return {
type: TokenType.ERROR,
value: `Unexpected character: ${char}`,
};
}
// Scan all tokens
let token = scanToken();
while (token !== null) {
tokens.push(token);
token = scanToken();
}
return tokens;
}
// Syntax analysis (AST building)
// this funciton creates the nodes for all the code using the tokens
function syntaxAnalysis(tokens) {
let current = 0;
function peek() {
if (current >= tokens.length) return null;
return tokens[current];
}
function advance() {
current++;
return tokens[current - 1];
}
function parseValue() {
const token = peek();
if (!token) {
return { type: "ERROR", message: "Unexpected end of input" };
}
switch (token.type) {
case TokenType.LEFT_BRACE:
return parseObject();
case TokenType.LEFT_BRACKET:
return parseArray();
case TokenType.STRING:
advance();
return { type: "STRING", value: token.content };
case TokenType.NUMBER:
advance();
return { type: "NUMBER", value: parseFloat(token.value) };
case TokenType.BOOLEAN:
advance();
return { type: "BOOLEAN", value: token.value === "true" };
case TokenType.NULL:
advance();
return { type: "NULL" };
case TokenType.KEYWORD:
advance();
return { type: "KEYWORD", value: token.content };
default:
advance();
return {
type: "ERROR",
message: `Unexpected token: ${token.type}`,
};
}
}
function parseObject() {
const obj = { type: "OBJECT", properties: [] };
advance(); // Skip left brace
// Empty object
if (peek() && peek().type === TokenType.RIGHT_BRACE) {
advance();
return obj;
}
while (true) {
// Property name must be a string
const nameToken = peek();
if (
!nameToken ||
(nameToken.type !== TokenType.STRING &&
nameToken.type !== TokenType.KEYWORD)
) {
return {
type: "ERROR",
message: "Expected property name string",
};
}
advance();
// Must be followed by a colon
const colonToken = peek();
if (!colonToken || colonToken.type !== TokenType.COLON) {
return {
type: "ERROR",
message: "Expected colon after property name",
};
}
advance();
// Parse the property value
const value = parseValue();
// Add property to object
obj.properties.push({
name: nameToken.content,
value: value,
});
// Check for comma or end of object
const nextToken = peek();
if (!nextToken) {
return {
type: "ERROR",
message: "Unexpected end of input in object",
};
}
if (nextToken.type === TokenType.RIGHT_BRACE) {
advance();
break;
}
if (nextToken.type !== TokenType.COMMA) {
return {
type: "ERROR",
message: "Expected comma or closing brace in object",
};
}
advance(); // Skip comma
}
return obj;
}
function parseArray() {
const arr = { type: "ARRAY", elements: [] };
advance(); // Skip left bracket
// Empty array
if (peek() && peek().type === TokenType.RIGHT_BRACKET) {
advance();
return arr;
}
while (true) {
// Parse array element
const element = parseValue();
arr.elements.push(element);
// Check for comma or end of array
const nextToken = peek();
if (!nextToken) {
return {
type: "ERROR",
message: "Unexpected end of input in array",
};
}
if (nextToken.type === TokenType.RIGHT_BRACKET) {
advance();
break;
}
if (nextToken.type !== TokenType.COMMA) {
return {
type: "ERROR",
message: "Expected comma or closing bracket in array",
};
}
advance(); // Skip comma
}
return arr;
}
// Start parsing from the root
return parseValue();
}
// Basic schema validation
function validateSchema(ast) {
const validationMessages = [];
function findProperty(obj, name) {
if (obj.type !== "OBJECT") return null;
for (const prop of obj.properties) {
if (prop.name === name) {
return prop.value;
}
}
return null;
}
// Basic validation
if (ast.type === "OBJECT") {
// Check for type property
const typeProperty = findProperty(ast, "type");
if (!typeProperty) {
validationMessages.push(
'Warning: Schema object is missing "type" property'
);
}
// Check required property format
const required = findProperty(ast, "required");
if (required && required.type !== "ARRAY") {
validationMessages.push(
'Error: The "required" property must be an array'
);
}
// Check properties existence
const properties = findProperty(ast, "properties");
if (typeProperty && typeProperty.value === "object" && !properties) {
validationMessages.push(
'Warning: Object schema is missing "properties" property'
);
}
// Basic checks on numeric constraints
const minimum = findProperty(ast, "minimum");
const maximum = findProperty(ast, "maximum");
if (
minimum &&
maximum &&
minimum.type === "NUMBER" &&
maximum.type === "NUMBER" &&
minimum.value > maximum.value
) {
validationMessages.push(
'Error: "minimum" value cannot be greater than "maximum"'
);
}
} else {
validationMessages.push("Error: Root element must be an object");
}
return validationMessages.length > 0
? validationMessages
: ["Schema appears valid."];
}
// Display tokens in the UI
function displayTokens(tokens) {
tokensOutput.innerHTML = "";
tokens.forEach((token) => {
const tokenElement = document.createElement("span");
let cssClass = "";
switch (token.type) {
case TokenType.KEYWORD:
cssClass = "keyword";
break;
case TokenType.STRING:
cssClass = "string";
break;
case TokenType.NUMBER:
cssClass = "number";
break;
case TokenType.BOOLEAN:
cssClass = "boolean";
break;
case TokenType.NULL:
cssClass = "null";
break;
case TokenType.LEFT_BRACE:
case TokenType.RIGHT_BRACE:
case TokenType.LEFT_BRACKET:
case TokenType.RIGHT_BRACKET:
case TokenType.COLON:
case TokenType.COMMA:
cssClass = "punctuation";
break;
case TokenType.ERROR:
cssClass = "error";
break;
}
tokenElement.classList.add("token", cssClass);
tokenElement.textContent = `${token.type}: ${token.value}`;
tokensOutput.appendChild(tokenElement);
});
}
// Display AST in the UI
function displayAST(ast) {
astOutput.textContent = JSON.stringify(ast, null, 2);
}
// Display validation results in the UI
function displayValidation(validationResults) {
validationOutput.innerHTML = validationResults.join("<br>");
}
// Auto-load the sample on page load
window.addEventListener("load", () => {
sampleBtn.click();
});