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
|
// slang-json-lexer.cpp
#include "slang-json-lexer.h"
#include "slang-json-diagnostics.h"
#include "../core/slang-char-util.h"
/*
https://www.json.org/json-en.html
*/
namespace Slang {
/* static */UnownedStringSlice JSONLexer::calcLexemeLocation(const UnownedStringSlice& text)
{
SourceManager sourceManager;
sourceManager.initialize(nullptr, nullptr);
DiagnosticSink sink;
sink.init(&sourceManager, nullptr);
String contents(text);
SourceFile* sourceFile = sourceManager.createSourceFileWithString(PathInfo::makeUnknown(), contents);
SourceView* sourceView = sourceManager.createSourceView(sourceFile, nullptr, SourceLoc());
JSONLexer lexer;
lexer.init(sourceView, &sink);
if (lexer.peekType() != JSONTokenType::Invalid)
{
// Get the start offset
auto offset = sourceView->getRange().getOffset(lexer.peekLoc());
return text.subString(offset, lexer.peekLexeme().getLength());
}
else
{
return text.head(0);
}
}
SlangResult JSONLexer::init(SourceView* sourceView, DiagnosticSink* sink)
{
m_sourceView = sourceView;
m_sink = sink;
SourceFile* sourceFile = sourceView->getSourceFile();
// Note that the content must be null terminated (because of other requirements)
SLANG_ASSERT(sourceFile && sourceFile->hasContent());
m_contentStart = sourceFile->getContent().begin();
m_startLoc = sourceView->getRange().begin;
m_lexemeStart = m_contentStart;
m_cursor = m_lexemeStart;
// We need to prime the first token
advance();
return SLANG_OK;
}
SLANG_FORCE_INLINE static const char* _handleEndOfLine(char c, const char* cursor)
{
SLANG_ASSERT(c == '\n' || c == '\r');
const char d = *cursor;
return cursor + Index((c ^ d) == ('\n' ^ '\r'));
}
JSONTokenType JSONLexer::_setInvalidToken()
{
return _setToken(JSONTokenType::Invalid, m_lexemeStart);
}
SlangResult JSONLexer::expect(JSONTokenType type)
{
if (type != peekType())
{
m_sink->diagnose(m_token.loc, JSONDiagnostics::unexpectedTokenExpectedTokenType, getJSONTokenAsText(peekType()), getJSONTokenAsText(type));
return SLANG_FAIL;
}
advance();
return SLANG_OK;
}
SlangResult JSONLexer::expect(JSONTokenType type, JSONToken& out)
{
if (type != peekType())
{
m_sink->diagnose(m_token.loc, JSONDiagnostics::unexpectedTokenExpectedTokenType, getJSONTokenAsText(peekType()), getJSONTokenAsText(type));
return SLANG_FAIL;
}
out = m_token;
advance();
return SLANG_OK;
}
bool JSONLexer::advanceIf(JSONTokenType type)
{
if (type == peekType())
{
advance();
return true;
}
return false;
}
bool JSONLexer::advanceIf(JSONTokenType type, JSONToken& out)
{
if (type == peekType())
{
out = m_token;
advance();
return true;
}
return false;
}
UnownedStringSlice JSONLexer::getLexeme(const JSONToken& tok) const
{
auto offset = m_sourceView->getRange().getOffset(tok.loc);
return UnownedStringSlice(m_sourceView->getContent().begin() + offset, tok.length);
}
JSONTokenType JSONLexer::advance()
{
const char* cursor = m_cursor;
while (true)
{
m_lexemeStart = cursor;
const char c = *cursor++;
switch (c)
{
case 0: return _setToken(JSONTokenType::EndOfFile, cursor - 1);
case '"':
{
cursor = _lexString(cursor);
if (cursor == nullptr)
{
return _setInvalidToken();
}
return _setToken(JSONTokenType::StringLiteral, cursor);
}
case '/':
{
// We allow comments
const char nextChar = *m_cursor;
if (nextChar == '/')
{
// Line comment
cursor = _lexLineComment(cursor);
}
else if (nextChar == '*')
{
cursor = _lexBlockComment(cursor);
// Can fail...
if (cursor == nullptr)
{
return _setInvalidToken();
}
}
else
{
return _setInvalidToken();
}
break;
}
case ' ':
case '\t':
case '\n':
case '\r':
{
cursor = _lexWhitespace(cursor);
break;
}
case ':': return _setToken(JSONTokenType::Colon, cursor);
case ',': return _setToken(JSONTokenType::Comma, cursor);
case '[': return _setToken(JSONTokenType::LBracket, cursor);
case ']': return _setToken(JSONTokenType::RBracket, cursor);
case '{': return _setToken(JSONTokenType::LBrace, cursor);
case '}': return _setToken(JSONTokenType::RBrace, cursor);
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
LexResult res = _lexNumber(cursor - 1);
if (res.cursor == nullptr)
{
return _setToken(JSONTokenType::Invalid, m_lexemeStart);
}
return _setToken(res.type, res.cursor);
}
case 't':
{
if (cursor[0] == 'r' && cursor[1] == 'u' && cursor[2] == 'e')
{
return _setToken(JSONTokenType::True, cursor + 3);
}
m_sink->diagnose(_getLoc(m_lexemeStart), JSONDiagnostics::expectingValueName);
return _setInvalidToken();
}
case 'f':
{
if (cursor[0] == 'a' && cursor[1] == 'l' && cursor[2] == 's' && cursor[3] == 'e')
{
return _setToken(JSONTokenType::False, cursor + 4);
}
m_sink->diagnose(_getLoc(m_lexemeStart), JSONDiagnostics::expectingValueName);
return _setInvalidToken();
}
case 'n':
{
if (cursor[0] == 'u' && cursor[1] == 'l' && cursor[2] == 'l')
{
return _setToken(JSONTokenType::Null, cursor + 3);
}
m_sink->diagnose(_getLoc(m_lexemeStart), JSONDiagnostics::expectingValueName);
return _setInvalidToken();
}
default:
{
StringBuilder buf;
if (c <= ' ' || c >= 0x7e)
{
static const char s_hex[] = "0123456789abcdef";
char hexBuf[5] = "0x";
uint32_t value = c;
hexBuf[2] = s_hex[((value >> 4) & 0xf)];
hexBuf[3] = s_hex[(value & 0xf)];
hexBuf[4] = 0;
buf << hexBuf;
}
else
{
buf << c;
}
m_sink->diagnose(_getLoc(m_lexemeStart), JSONDiagnostics::unexpectedCharacter);
return _setInvalidToken();
}
}
}
}
JSONLexer::LexResult JSONLexer::_lexNumber(const char* cursor)
{
JSONTokenType tokenType = JSONTokenType::IntegerLiteral;
if (*cursor == '-')
{
cursor++;
}
if (*cursor == '0')
{
// Can only be followed by . exponent, or nothing
cursor++;
}
else if (*cursor >= '1' && *cursor <= '9')
{
cursor++;
while (CharUtil::isDigit(*cursor))
{
cursor++;
}
}
// Theres a fraction
if (*cursor == '.')
{
tokenType = JSONTokenType::FloatLiteral;
// Skip the dot
cursor++;
// Must have at least one digit
if (!CharUtil::isDigit(*cursor))
{
m_sink->diagnose(_getLoc(cursor), JSONDiagnostics::expectingADigit);
return LexResult{ JSONTokenType::Invalid, nullptr };
}
// Skip the digit
cursor++;
// Skip any more digits
while (CharUtil::isDigit(*cursor)) cursor++;
}
// Theres an exponent
if (*cursor == 'e' || *cursor == 'E')
{
tokenType = JSONTokenType::FloatLiteral;
// Has an exponent
cursor++;
// Skip +/- if has one
if (*cursor == '+' || *cursor == '-')
{
cursor++;
}
// Must have one digit
if (!CharUtil::isDigit(*cursor))
{
m_sink->diagnose(_getLoc(cursor), JSONDiagnostics::expectingADigit);
return LexResult{ JSONTokenType::Invalid, nullptr };
}
// Skip the digit
cursor++;
// Skip any more digits
while (CharUtil::isDigit(*cursor)) cursor++;
}
return LexResult{tokenType, cursor};
}
const char* JSONLexer::_lexString(const char* cursor)
{
// We've skipped the first "
while (true)
{
const char c = *cursor++;
switch (c)
{
case 0:
{
m_sink->diagnose(_getLoc(cursor - 1), JSONDiagnostics::endOfFileInLiteral);
return nullptr;
}
case '"':
{
return cursor;
}
case '\\':
{
const char nextC = *cursor;
switch (nextC)
{
case '"':
case '\\':
case '/':
case 'b':
case 'f':
case 'n':
case 'r':
case 't':
{
++cursor;
break;
}
case 'u':
{
cursor++;
for (Index i = 0; i < 4; ++i)
{
if (!CharUtil::isHexDigit(cursor[i]))
{
m_sink->diagnose(_getLoc(cursor), JSONDiagnostics::expectingAHexDigit);
return nullptr;
}
}
cursor += 4;
break;
}
}
}
// Somewhat surprisingly it appears it's valid to have \r\n inside of quotes.
default: break;
}
}
}
const char* JSONLexer::_lexLineComment(const char* cursor)
{
for (;;)
{
const char c = *cursor++;
switch (c)
{
case '\n':
case '\r':
{
// We need to skip to the next line
return _handleEndOfLine(c, cursor);
}
case 0:
{
return cursor - 1;
}
}
}
}
const char* JSONLexer::_lexBlockComment(const char* cursor)
{
for (;;)
{
const char c = *cursor++;
switch (c)
{
case 0:
{
m_sink->diagnose(_getLoc(cursor), JSONDiagnostics::endOfFileInComment);
return nullptr;
}
case '*':
{
if (*cursor == '/')
{
return cursor + 1;
}
break;
}
default: break;
}
}
}
const char* JSONLexer::_lexWhitespace(const char* cursor)
{
while (true)
{
const char c = *cursor;
// Might want to use CharUtil::isWhitespace...
switch (c)
{
case ' ':
case '\n':
case '\r':
case '\t':
{
cursor++;
break;
}
default:
{
// Hit non white space
return cursor;
}
}
}
}
UnownedStringSlice getJSONTokenAsText(JSONTokenType type)
{
switch (type)
{
case JSONTokenType::Invalid: return UnownedStringSlice::fromLiteral("invalid");
case JSONTokenType::IntegerLiteral: return UnownedStringSlice::fromLiteral("integer literal");
case JSONTokenType::FloatLiteral: return UnownedStringSlice::fromLiteral("float literal");
case JSONTokenType::StringLiteral: return UnownedStringSlice::fromLiteral("string literal");
case JSONTokenType::LBracket: return UnownedStringSlice::fromLiteral("[");
case JSONTokenType::RBracket: return UnownedStringSlice::fromLiteral("]");
case JSONTokenType::LBrace: return UnownedStringSlice::fromLiteral("{");
case JSONTokenType::RBrace: return UnownedStringSlice::fromLiteral("}");
case JSONTokenType::Comma: return UnownedStringSlice::fromLiteral(",");
case JSONTokenType::Colon: return UnownedStringSlice::fromLiteral(":");
case JSONTokenType::True: return UnownedStringSlice::fromLiteral("true");
case JSONTokenType::False: return UnownedStringSlice::fromLiteral("false");
case JSONTokenType::Null: return UnownedStringSlice::fromLiteral("null");
case JSONTokenType::EndOfFile: return UnownedStringSlice::fromLiteral("end of file");
default: break;
}
SLANG_UNEXPECTED("JSONTokenType not known");
}
} // namespace Slang
|