/
JSON.SyntaxValidator.cs
470 lines (422 loc) · 18.7 KB
/
JSON.SyntaxValidator.cs
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
/*
JSON Syntax Validator
(C) Torres Frederic 2013
Based on code from: How do I write my own parser? (for JSON) By Patrick van Bergen http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
My library heavily change Patrick van Bergen's code.
The library is release under the Mit Style License
*/
using System;
using System.Collections;
using System.Globalization;
using System.Text;
using DynamicSugar;
using System.Collections.Generic;
namespace JSON.SyntaxValidator
{
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes ArrayList and Hashtable.
/// All numbers are parsed to doubles.
/// </summary>
public class Compiler : Tokenizer
{
public const string SYNTAX_ERROR_001 = @"Trailing coma not supported";
public const string SYNTAX_ERROR_002 = @"Missing ']'";
public const string SYNTAX_ERROR_003 = @"Missing '}'";
public const string SYNTAX_ERROR_004 = @"Missing ':'";
public const string SYNTAX_ERROR_005 = @"Missing ','";
public const string SYNTAX_ERROR_006 = @"Missing '""'";
public const string SYNTAX_ERROR_007 = @"String expected instead of ID";
public const string SYNTAX_ERROR_008 = @"Invalid value:";
public const string SYNTAX_ERROR_009 = @"Expected ',' or ']'";
public const string SYNTAX_ERROR_010 = @"Expected ',' or '}'";
public const string SYNTAX_ERROR_011 = @"Missing '}' or '""' expected";
public const string SYNTAX_ERROR_012 = @"Missing value ',,' is invalid";
public const string SYNTAX_ERROR_013 = @"',' unexpected";
public const string SYNTAX_ERROR_014 = @"'{0}' unexpected";
public const string SYNTAX_ERROR_015 = @"']' unexpected";
public const string SYNTAX_ERROR_016 = @"'}' unexpected";
public const string SYNTAX_ERROR_017 = @"'""' missing";
public const string SYNTAX_ERROR_018 = @"Expected end of file";
public const string SYNTAX_ERROR_019 = @"// Comment are not allowed in JSON strict mode";
public const string SYNTAX_ERROR_020 = @"Invalid JSON date:""{0}""";
private char[] _charArray;
private int _index;
private bool _supportIDWithNoQuote;
private bool _supportTrailingComa;
private bool _supportStartComment;
private bool _supportSlashComment;
private const int BUILDER_CAPACITY = 2000;
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An ArrayList, a Hashtable, a double, a string, null, true, or false</returns>
public object Validate(string json, bool supportStartComment = false, bool relaxMode = false, CommentInfos commentInfos = null)
{
bool success = true;
this._supportStartComment = supportStartComment;
if (commentInfos == null) // Optimization for the TextHighlighter extension
{ // So we do not have parse the comment twice if possible
commentInfos = new CommentParser().Parse(json);
}
_supportIDWithNoQuote = (relaxMode) || (commentInfos.IsRelax);
_supportTrailingComa = _supportIDWithNoQuote;
_supportSlashComment = _supportIDWithNoQuote;
return Compile(json, ref success);
}
/// <summary>
/// Parses the string json into a value; and fills 'success' with the successfullness of the parse.
/// </summary>
/// <param name="json">A JSON string.</param>
/// <param name="success">Successful parse?</param>
/// <returns>An ArrayList, a Hashtable, a double, a string, null, true, or false</returns>
public object Compile(string json, ref bool success)
{
success = true;
if (json != null)
{
this._charArray = json.ToCharArray();
this._index = 0;
object value = ParseValue(ref success);
var tokenAHead = LookAhead(this._charArray, this._index, this._supportStartComment, this._supportSlashComment);
if (tokenAHead != TOKENS.NONE)
{
this.ThrowError(SYNTAX_ERROR_014.format(TOKEN_STRING[tokenAHead]), this._index);
}
// Make sure there is nothing at the end of the file once we parsed
// the object or array
EatWhitespace(this._charArray, ref this._index, this._supportStartComment, this._supportSlashComment);
if(this._index < this._charArray.Length)
{
this.ThrowError(SYNTAX_ERROR_018, this._index);
}
return value;
}
else
{
return null;
}
}
private int GetLine(int index)
{
return Tokenizer.GetLine(this._charArray, index);
}
private int GetColumn(int index)
{
return Tokenizer.GetColumn(this._charArray, index);
}
private void ThrowError(string message, int index)
{
var ex = new ParserException(message, GetLine(index), GetColumn(index), index);
throw ex;
}
private Hashtable ParseObject(ref bool success)
{
var table = new Hashtable();
var done = false;
TOKENS token;
// {
NextToken(_charArray, ref _index, this._supportStartComment, this._supportSlashComment);
var tokenAHead = LookAhead(_charArray, _index, this._supportStartComment , this._supportSlashComment);
// Check for [{]
// Check for {,
if (tokenAHead.In(TOKENS.SQUARED_CLOSE, TOKENS.COMA, TOKENS.COLON))
{
NextToken(_charArray, ref _index, this._supportStartComment , this._supportSlashComment);
this.ThrowError(SYNTAX_ERROR_014.format(TOKEN_STRING[tokenAHead]), _index);
}
while (!done)
{
token = LookAhead(_charArray, _index, this._supportStartComment , this._supportSlashComment);
if (token == TOKENS.NONE)
{
this.ThrowError(SYNTAX_ERROR_011, this._index);
}
else if (token == TOKENS.COMA)
{
NextToken(_charArray, ref _index, this._supportStartComment, this._supportSlashComment);
if (LookAhead(_charArray, _index, this._supportStartComment, this._supportSlashComment).In(TOKENS.CURLY_CLOSE))
{
if (!this._supportTrailingComa)
this.ThrowError(SYNTAX_ERROR_001, this._index);
}
}
else if (token == TOKENS.CURLY_CLOSE)
{
NextToken(_charArray, ref _index, this._supportStartComment, this._supportSlashComment);
return table;
}
else
{
// name with or without id
string name = "";
if (token == TOKENS.ID && this._supportIDWithNoQuote)
{
name = ParseID(this._charArray, ref _index, ref success, this._supportStartComment, this._supportSlashComment).ToString();
}
else if (token == TOKENS.STRING)
{
var s = ParseString(ref _index, ref success);
if (s == null)
{
this.ThrowError(SYNTAX_ERROR_017, this._index);
}
else
{
name = s.ToString();
}
}
else
{
success = false;
}
if (!success)
{
var tmpTok = NextToken(_charArray, ref _index, this._supportStartComment , this._supportSlashComment);
this.ThrowError(SYNTAX_ERROR_007, this._index);
}
// :
token = NextToken(_charArray, ref _index, this._supportStartComment , this._supportSlashComment);
if (token != TOKENS.COLON)
{
this.ThrowError(SYNTAX_ERROR_004, this._index);
}
// value
object value = ParseValue(ref success);
if (!success)
{
this.ThrowError(SYNTAX_ERROR_008, this._index);
}
var next2Tokens = GetNext2TokensAHead();
if (next2Tokens.Count >= 1 && (!next2Tokens[0].In(TOKENS.COMA, TOKENS.CURLY_CLOSE)))
{
this.ThrowError(SYNTAX_ERROR_010, this._index);
} // Check for ,, after an value
else if (next2Tokens.Count == 2 && next2Tokens[0] == TOKENS.COMA && next2Tokens[1] == TOKENS.COMA)
{
this.ThrowError(SYNTAX_ERROR_012, this._index);
}
else if (next2Tokens.Count == 2 && next2Tokens[0] == TOKENS.COMA && next2Tokens[1] == TOKENS.SQUARED_CLOSE)
{
if (!this._supportTrailingComa)
this.ThrowError(SYNTAX_ERROR_001, this._index);
}
else if (next2Tokens.Count == 2 && next2Tokens[0] == TOKENS.NONE && next2Tokens[1] == TOKENS.NONE)
{ // If we are missing a } but are at the eof
this.ThrowError(SYNTAX_ERROR_003, this._index);
}
table[name] = value;
}
}
return table;
}
private List<TOKENS> GetNext2TokensAHead()
{
var l = new List<TOKENS>();
int index2 = _index;
l.Add(NextToken(this._charArray, ref _index, this._supportStartComment , this._supportSlashComment));
l.Add(NextToken(_charArray, ref _index, this._supportStartComment , this._supportSlashComment));
_index = index2;
return l;
}
private ArrayList ParseArray(ref bool success)
{
var array = new ArrayList();
// [
NextToken(_charArray, ref _index, this._supportStartComment, this._supportSlashComment);
bool done = false;
var tokenAHead = LookAhead(_charArray, _index, this._supportStartComment, this._supportSlashComment);
// Check for [,
// Check for [}
if (tokenAHead.In(TOKENS.COMA, TOKENS.CURLY_CLOSE))
{
NextToken(_charArray, ref _index, this._supportStartComment, this._supportSlashComment);
this.ThrowError(SYNTAX_ERROR_014.format(TOKEN_STRING[tokenAHead]), this._index);
}
while (!done)
{
var token = LookAhead(_charArray, _index, this._supportStartComment, this._supportSlashComment);
if (token == TOKENS.NONE)
{
this.ThrowError(SYNTAX_ERROR_002, this._index);
}
else if (token == TOKENS.COMA)
{
NextToken(_charArray, ref _index, this._supportStartComment , this._supportSlashComment);
if (LookAhead(_charArray, _index, this._supportStartComment , this._supportSlashComment).In(TOKENS.CURLY_CLOSE))
{
if (!this._supportTrailingComa)
this.ThrowError(SYNTAX_ERROR_001, this._index);
}
}
else if (token == TOKENS.SQUARED_CLOSE)
{
NextToken(_charArray, ref _index, this._supportStartComment , this._supportSlashComment);
break;
}
else
{
object value = ParseValue(ref success);
if (!success)
{
this.ThrowError(SYNTAX_ERROR_008, this._index);
}
array.Add(value);
var nextToken = LookAhead(_charArray, _index, this._supportStartComment, this._supportSlashComment);
if (nextToken != TOKENS.SQUARED_CLOSE && nextToken != TOKENS.COMA)
{
this.ThrowError(SYNTAX_ERROR_009, this._index);
}
// Check for ,, after an value
var next2Tokens = GetNext2TokensAHead();
if (next2Tokens.Count == 2 && next2Tokens[0] == TOKENS.COMA && next2Tokens[1] == TOKENS.COMA)
{
this.ThrowError(SYNTAX_ERROR_012, this._index);
}
if (next2Tokens.Count == 2 && next2Tokens[0] == TOKENS.COMA && next2Tokens[1] == TOKENS.SQUARED_CLOSE)
{
if (!this._supportTrailingComa)
this.ThrowError(SYNTAX_ERROR_001, this._index);
}
}
}
return array;
}
private object ParseValue(ref bool success)
{
var token = LookAhead(_charArray, _index, this._supportStartComment, this._supportSlashComment);
switch (token)
{
case TOKENS.STRING:
return ParseString(ref _index, ref success);
case TOKENS.NUMBER:
return ParseNumber(this._charArray, ref _index, ref success, this._supportStartComment, this._supportSlashComment);
case TOKENS.CURLY_OPEN:
return ParseObject(ref success);
case TOKENS.SQUARED_OPEN:
return ParseArray(ref success);
case TOKENS.TRUE:
NextToken(this._charArray, ref _index, this._supportStartComment , this._supportSlashComment);
return true;
case TOKENS.FALSE:
NextToken(this._charArray, ref _index, this._supportStartComment , this._supportSlashComment);
return false;
case TOKENS.NULL:
NextToken(this._charArray, ref _index, this._supportStartComment , this._supportSlashComment);
return null;
case TOKENS.NONE:
break;
}
this.ThrowError(SYNTAX_ERROR_014.format(TOKEN_STRING[token]), this._index);
return null; // will never be executed
}
private object ParseString(ref int index, ref bool success)
{
var indexSaved = index;
StringBuilder s = new StringBuilder(BUILDER_CAPACITY);
char c;
EatWhitespace(_charArray, ref index, this._supportStartComment, this._supportSlashComment);
c = _charArray[index++];
bool complete = false;
while (!complete)
{
if (index == _charArray.Length)
{
break;
}
c = _charArray[index++];
if (c == '"')
{
complete = true;
break;
}
else if (c == '\\')
{
if (index == _charArray.Length)
{
break;
}
c = _charArray[index++];
if (c == '"')
{
s.Append('"');
}
else if (c == '\\')
{
s.Append('\\');
}
else if (c == '/')
{
s.Append('/');
}
else if (c == 'b')
{
s.Append('\b');
}
else if (c == 'f')
{
s.Append('\f');
}
else if (c == 'n')
{
s.Append('\n');
}
else if (c == 'r')
{
s.Append('\r');
}
else if (c == 't')
{
s.Append('\t');
}
else if (c == 'u')
{
int remainingLength = _charArray.Length - index;
if (remainingLength >= 4)
{
// parse the 32 bit hex into an integer codepoint
uint codePoint;
if (!(success = UInt32.TryParse(new string(_charArray, index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out codePoint)))
{
return "";
}
// convert the integer codepoint to a unicode char and add to string
s.Append(Char.ConvertFromUtf32((int)codePoint));
// skip 4 chars
index += 4;
}
else
{
break;
}
}
}
else
{
s.Append(c);
}
}
if (!complete)
{
index = indexSaved; // Restore the position where we started parsing the string, this give a better error message
success = false;
return null;
}
var val = s.ToString();
if (IsJsonDate(val)) {
try {
return ParseJsonDateTime(val);
}
catch(System.ArgumentException aex) {
this.ThrowError(SYNTAX_ERROR_020.format(val), this._index);
return null;
}
}
else
return val;
}
}
}