-
Notifications
You must be signed in to change notification settings - Fork 13
/
lexer.d
2066 lines (1830 loc) · 64.1 KB
/
lexer.d
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Provides JSON lexing facilities.
*
* Synopsis:
* ---
* // Lex a JSON string into a lazy range of tokens
* auto tokens = lexJSON(`{"name": "Peter", "age": 42}`);
*
* with (JSONToken) {
* assert(tokens.map!(t => t.kind).equal(
* [Kind.objectStart, Kind.string, Kind.colon, Kind.string, Kind.comma,
* Kind.string, Kind.colon, Kind.number, Kind.objectEnd]));
* }
*
* // Get detailed information
* tokens.popFront(); // skip the '{'
* assert(tokens.front.string == "name");
* tokens.popFront(); // skip "name"
* tokens.popFront(); // skip the ':'
* assert(tokens.front.string == "Peter");
* assert(tokens.front.location.line == 0);
* assert(tokens.front.location.column == 9);
* ---
*
* Credits:
* Support for escaped UTF-16 surrogates was contributed to the original
* vibe.d JSON module by Etienne Cimon. The number parsing code is based
* on the version contained in Andrei Alexandrescu's "std.jgrandson"
* module draft.
*
* Copyright: Copyright 2012 - 2014, Sönke Ludwig.
* License: $(WEB www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
* Authors: Sönke Ludwig
* Source: $(PHOBOSSRC std/data/json/lexer.d)
*/
module stdx.data.json.lexer;
@safe:
import std.range;
import std.array : appender;
import std.traits : isIntegral, isSomeChar, isSomeString;
import stdx.data.json.foundation;
/**
* Returns a lazy range of tokens corresponding to the given JSON input string.
*
* The input must be a valid JSON string, given as an input range of either
* characters, or of integral values. In case of integral types, the input
* ecoding is assumed to be a superset of ASCII that is parsed unit by unit.
*
* For inputs of type $(D string) and of type $(D immutable(ubyte)[]), all
* string literals will be stored as slices into the original string. String
* literals containung escape sequences will be unescaped on demand when
* $(D JSONString.value) is accessed.
*
* Throws:
* Without $(D LexOptions.noThrow), a $(D JSONException) is thrown as soon as
* an invalid token is encountered.
*
* If $(D LexOptions.noThrow) is given, lexJSON does not throw any exceptions,
* apart from letting through any exceptins thrown by the input range.
* Instead, a token with kind $(D JSONToken.Kind.error) is generated as the
* last token in the range.
*/
JSONLexerRange!(Input, options, appenderFactory) lexJSON
(LexOptions options = LexOptions.init, alias appenderFactory = () => appender!string(), Input)
(Input input, string filename = null)
if (isStringInputRange!Input || isIntegralInputRange!Input)
{
return JSONLexerRange!(Input, options, appenderFactory)(input, filename);
}
///
unittest
{
import std.algorithm : equal, map;
auto rng = lexJSON(`{ "hello": 1.2, "world":[1, true, null]}`);
with (JSONToken)
{
assert(rng.map!(t => t.kind).equal(
[Kind.objectStart, Kind.string, Kind.colon, Kind.number, Kind.comma,
Kind.string, Kind.colon, Kind.arrayStart, Kind.number, Kind.comma,
Kind.boolean, Kind.comma, Kind.null_, Kind.arrayEnd,
Kind.objectEnd]));
}
}
///
unittest
{
auto rng = lexJSON("true\n false null\r\n 1.0\r \"test\"");
rng.popFront();
assert(rng.front.boolean == false);
assert(rng.front.location.line == 1 && rng.front.location.column == 3);
rng.popFront();
assert(rng.front.kind == JSONToken.Kind.null_);
assert(rng.front.location.line == 1 && rng.front.location.column == 9);
rng.popFront();
assert(rng.front.number == 1.0);
assert(rng.front.location.line == 2 && rng.front.location.column == 2);
rng.popFront();
assert(rng.front.string == "test");
assert(rng.front.location.line == 3 && rng.front.location.column == 1);
rng.popFront();
assert(rng.empty);
}
unittest
{
import std.exception;
assertThrown(lexJSON(`trui`).front); // invalid token
assertThrown(lexJSON(`fal`).front); // invalid token
assertThrown(lexJSON(`falsi`).front); // invalid token
assertThrown(lexJSON(`nul`).front); // invalid token
assertThrown(lexJSON(`nulX`).front); // invalid token
assertThrown(lexJSON(`0.e`).front); // invalid number
assertThrown(lexJSON(`xyz`).front); // invalid token
}
unittest { // test built-in UTF validation
import std.exception;
static void test_invalid(immutable(ubyte)[] str)
{
assertThrown(lexJSON(str).front);
assertNotThrown(lexJSON(cast(string)str).front);
}
test_invalid(['"', 0xFF, '"']);
test_invalid(['"', 0xFF, 'x', '"']);
test_invalid(['"', 0xFF, 'x', '\\', 't','"']);
test_invalid(['"', '\\', 't', 0xFF,'"']);
test_invalid(['"', '\\', 't', 0xFF,'x','"']);
static void testw_invalid(immutable(ushort)[] str)
{
import std.conv;
assertThrown(lexJSON(str).front, str.to!string);
// Invalid UTF sequences can still throw in the non-validating case,
// because UTF-16 is converted to UTF-8 internally, so we don't test
// this case:
// assertNotThrown(lexJSON(cast(wstring)str).front);
}
static void testw_valid(immutable(ushort)[] str)
{
import std.conv;
assertNotThrown(lexJSON(str).front, str.to!string);
assertNotThrown(lexJSON(cast(wstring)str).front);
}
testw_invalid(['"', 0xD800, 0xFFFF, '"']);
testw_invalid(['"', 0xD800, 0xFFFF, 'x', '"']);
testw_invalid(['"', 0xD800, 0xFFFF, 'x', '\\', 't','"']);
testw_invalid(['"', '\\', 't', 0xD800, 0xFFFF,'"']);
testw_invalid(['"', '\\', 't', 0xD800, 0xFFFF,'x','"']);
testw_valid(['"', 0xE000, '"']);
testw_valid(['"', 0xE000, 'x', '"']);
testw_valid(['"', 0xE000, 'x', '\\', 't','"']);
testw_valid(['"', '\\', 't', 0xE000,'"']);
testw_valid(['"', '\\', 't', 0xE000,'x','"']);
}
static if (__VERSION__ >= 2067)
unittest { // test for @nogc interface
static struct MyAppender {
@nogc:
void put(string s) { }
void put(dchar ch) {}
void put(char ch) {}
@property string data() { return null; }
}
static MyAppender createAppender() @nogc { return MyAppender.init; }
@nogc void test(T)()
{
T text;
auto rng = lexJSON!(LexOptions.noThrow, createAppender)(text);
while (!rng.empty) {
auto f = rng.front;
rng.popFront();
cast(void)f.boolean;
static if (__VERSION__ >= 2067)
f.number.longValue;
cast(void)f.string;
cast(void)f.string.anyValue;
}
}
// just instantiate, don't run
auto t1 = &test!string;
auto t2 = &test!wstring;
auto t3 = &test!dstring;
}
/**
* A lazy input range of JSON tokens.
*
* This range type takes an input string range and converts it into a range of
* $(D JSONToken) values.
*
* See $(D lexJSON) for more information.
*/
struct JSONLexerRange(Input, LexOptions options = LexOptions.init, alias appenderFactory = () => appender!string())
if (isStringInputRange!Input || isIntegralInputRange!Input)
{
import std.string : representation;
static if (isSomeString!Input)
alias InternalInput = typeof(Input.init.representation);
else
alias InternalInput = Input;
static if (typeof(InternalInput.init.front).sizeof > 1)
alias CharType = dchar;
else
alias CharType = char;
private
{
InternalInput _input;
JSONToken _front;
Location _loc;
string _error;
}
/**
* Constructs a new token stream.
*/
this(Input input, string filename = null)
{
_input = cast(InternalInput)input;
_front.location.file = filename;
skipWhitespace();
}
/**
* Returns a copy of the underlying input range.
*/
@property Input input() { return cast(Input)_input; }
/**
* The current location of the lexer.
*/
@property Location location() const { return _loc; }
/**
* Determines if the token stream has been exhausted.
*/
@property bool empty()
{
if (_front.kind != JSONToken.Kind.none) return false;
return _input.empty;
}
/**
* Returns the current token in the stream.
*/
@property ref const(JSONToken) front()
{
ensureFrontValid();
return _front;
}
/**
* Skips to the next token.
*/
void popFront()
{
ensureFrontValid();
// make sure an error token is the last token in the range
if (_front.kind == JSONToken.Kind.error && !_input.empty)
{
// clear the input
_input = InternalInput.init;
assert(_input.empty);
}
_front.kind = JSONToken.Kind.none;
}
private void ensureFrontValid()
{
assert(!empty, "Reading from an empty JSONLexerRange.");
if (_front.kind == JSONToken.Kind.none)
{
readToken();
assert(_front.kind != JSONToken.Kind.none);
static if (!(options & LexOptions.noThrow))
enforceJson(_front.kind != JSONToken.Kind.error, _error, _loc);
}
}
private void readToken()
{
assert(!_input.empty, "Reading JSON token from empty input stream.");
static if (!(options & LexOptions.noTrackLocation))
_front.location = _loc;
switch (_input.front)
{
default: setError("Malformed token"); break;
case 'f': _front.boolean = false; skipKeyword("false"); break;
case 't': _front.boolean = true; skipKeyword("true"); break;
case 'n': _front.kind = JSONToken.Kind.null_; skipKeyword("null"); break;
case '"': parseString(); break;
case '0': .. case '9': case '-': parseNumber(); break;
case '[': skipChar(); _front.kind = JSONToken.Kind.arrayStart; break;
case ']': skipChar(); _front.kind = JSONToken.Kind.arrayEnd; break;
case '{': skipChar(); _front.kind = JSONToken.Kind.objectStart; break;
case '}': skipChar(); _front.kind = JSONToken.Kind.objectEnd; break;
case ':': skipChar(); _front.kind = JSONToken.Kind.colon; break;
case ',': skipChar(); _front.kind = JSONToken.Kind.comma; break;
static if (options & LexOptions.specialFloatLiterals)
{
case 'N', 'I': parseNumber(); break;
}
}
skipWhitespace();
}
private void skipChar()
{
_input.popFront();
static if (!(options & LexOptions.noTrackLocation)) _loc.column++;
}
private void skipKeyword(string kw)
{
import std.algorithm : skipOver;
if (!_input.skipOver(kw)) setError("Invalid keyord");
else static if (!(options & LexOptions.noTrackLocation)) _loc.column += kw.length;
}
private void skipWhitespace()
{
import std.traits;
static if (!(options & LexOptions.noTrackLocation))
{
while (!_input.empty)
{
switch (_input.front)
{
default: return;
case '\r': // Mac and Windows line breaks
_loc.line++;
_loc.column = 0;
_input.popFront();
if (!_input.empty && _input.front == '\n')
_input.popFront();
break;
case '\n': // Linux line breaks
_loc.line++;
_loc.column = 0;
_input.popFront();
break;
case ' ', '\t':
_loc.column++;
_input.popFront();
break;
}
}
}
else static if (isDynamicArray!InternalInput && is(Unqual!(ElementType!InternalInput) == ubyte))
{
() @trusted {
while (true) {
auto idx = skip!(true, '\r', '\n', ' ', '\t')(_input.ptr);
if (idx == 0) break;
_input.popFrontN(idx);
}
} ();
}
else
{
while (!_input.empty)
{
switch (_input.front)
{
default: return;
case '\r', '\n', ' ', '\t':
_input.popFront();
break;
}
}
}
}
private void parseString()
{
static if (is(Input == string) || is(Input == immutable(ubyte)[]))
{
InternalInput lit;
bool has_escapes = false;
if (skipStringLiteral!(!(options & LexOptions.noTrackLocation))(_input, lit, _error, _loc.column, has_escapes))
{
auto litstr = cast(string)lit;
static if (!isSomeChar!(typeof(Input.init.front))) {
import std.encoding;
if (!()@trusted{ return isValid(litstr); }()) {
setError("Invalid UTF sequence in string literal.");
return;
}
}
JSONString js;
if (has_escapes) js.rawValue = litstr;
else js.value = litstr[1 .. $-1];
_front.string = js;
}
else _front.kind = JSONToken.Kind.error;
}
else
{
bool appender_init = false;
typeof(appenderFactory()) dst;
string slice;
void initAppender()
@safe {
dst = appenderFactory();
appender_init = true;
}
if (unescapeStringLiteral!(!(options & LexOptions.noTrackLocation), isSomeChar!(typeof(Input.init.front)))(
_input, dst, slice, &initAppender, _error, _loc.column
))
{
if (!appender_init) _front.string = slice;
else _front.string = dst.data;
}
else _front.kind = JSONToken.Kind.error;
}
}
private void parseNumber()
{
import std.algorithm : among;
import std.ascii;
import std.bigint;
import std.math;
import std.string;
import std.traits;
assert(!_input.empty, "Passed empty range to parseNumber");
static if (options & (LexOptions.useBigInt/*|LexOptions.useDecimal*/))
BigInt int_part = 0;
else
long int_part = 0;
bool neg = false;
void setInt()
{
if (neg) int_part = -int_part;
static if (options & LexOptions.useBigInt)
{
static if (options & LexOptions.useLong)
{
if (int_part >= long.min && int_part <= long.max) _front.number = int_part.toLong();
else _front.number = int_part;
}
else _front.number = int_part;
}
//else static if (options & LexOptions.useDecimal) _front.number = Decimal(int_part, 0);
else _front.number = int_part;
}
// negative sign
if (_input.front == '-')
{
skipChar();
neg = true;
}
// support non-standard float special values
static if (options & LexOptions.specialFloatLiterals)
{
import std.algorithm : skipOver;
if (!_input.empty) {
if (_input.front == 'I') {
if (_input.skipOver("Infinity".representation))
{
static if (!(options & LexOptions.noTrackLocation)) _loc.column += 8;
_front.number = neg ? -double.infinity : double.infinity;
}
else setError("Invalid number, expected 'Infinity'");
return;
}
if (!neg && _input.front == 'N')
{
if (_input.skipOver("NaN".representation))
{
static if (!(options & LexOptions.noTrackLocation)) _loc.column += 3;
_front.number = double.nan;
}
else setError("Invalid number, expected 'NaN'");
return;
}
}
}
// integer part of the number
if (_input.empty || !_input.front.isDigit())
{
setError("Invalid number, expected digit");
return;
}
if (_input.front == '0')
{
skipChar();
if (_input.empty) // return 0
{
setInt();
return;
}
if (_input.front.isDigit)
{
setError("Invalid number, 0 must not be followed by another digit");
return;
}
}
else do
{
int_part = int_part * 10 + (_input.front - '0');
skipChar();
if (_input.empty) // return integer
{
setInt();
return;
}
}
while (isDigit(_input.front));
int exponent = 0;
void setFloat()
{
if (neg) int_part = -int_part;
/*static if (options & LexOptions.useDecimal) _front.number = Decimal(int_part, exponent);
else*/ if (exponent == 0) _front.number = int_part;
else _front.number = exp10(exponent) * int_part;
}
// post decimal point part
assert(!_input.empty);
if (_input.front == '.')
{
skipChar();
if (_input.empty)
{
setError("Missing fractional number part");
return;
}
while (true)
{
uint digit = _input.front - '0';
if (digit > 9) break;
int_part = int_part * 10 + digit;
exponent--;
skipChar();
if (_input.empty)
{
setFloat();
return;
}
}
}
// exponent
assert(!_input.empty);
if (_input.front.among!('e', 'E'))
{
skipChar();
if (_input.empty)
{
setError("Missing exponent");
return;
}
bool negexp = void;
if (_input.front == '-')
{
negexp = true;
skipChar();
}
else
{
negexp = false;
if (_input.front == '+') skipChar();
}
if (_input.empty || !_input.front.isDigit)
{
setError("Missing exponent");
return;
}
uint exp = 0;
while (true)
{
exp = exp * 10 + (_input.front - '0');
skipChar();
if (_input.empty || !_input.front.isDigit) break;
}
if (negexp) exponent -= exp;
else exponent += exp;
}
setFloat();
}
private void setError(string err)
{
_front.kind = JSONToken.Kind.error;
_error = err;
}
}
unittest
{
import std.conv;
import std.exception;
import std.string : format, representation;
static JSONString parseStringHelper(R)(ref R input, ref Location loc)
{
auto rng = JSONLexerRange!R(input);
rng.parseString();
input = cast(R)rng._input;
loc = rng._loc;
return rng._front.string;
}
void testResult(string str, string expected, string remaining, bool slice_expected = false)
{
{ // test with string (possibly sliced result)
Location loc;
string scopy = str;
auto ret = parseStringHelper(scopy, loc);
assert(ret == expected, ret);
assert(scopy == remaining);
auto sval = ret.anyValue;
// string[] must always slice string literals
assert(sval[1] && sval[0].ptr is &str[1] || !sval[1] && sval[0].ptr is &str[0]);
if (slice_expected) assert(&ret[0] is &str[1]);
assert(loc.line == 0);
assert(loc.column == str.length - remaining.length, format("%s col %s", str, loc.column));
}
{ // test with string representation (possibly sliced result)
Location loc;
immutable(ubyte)[] scopy = str.representation;
auto ret = parseStringHelper(scopy, loc);
assert(ret == expected, ret);
assert(scopy == remaining);
auto sval = ret.anyValue;
// immutable(ubyte)[] must always slice string literals
assert(sval[1] && sval[0].ptr is &str[1] || !sval[1] && sval[0].ptr is &str[0]);
if (slice_expected) assert(&ret[0] is &str[1]);
assert(loc.line == 0);
assert(loc.column == str.length - remaining.length, format("%s col %s", str, loc.column));
}
{ // test with dstring (fully duplicated result)
Location loc;
dstring scopy = str.to!dstring;
auto ret = parseStringHelper(scopy, loc);
assert(ret == expected);
assert(scopy == remaining.to!dstring);
assert(loc.line == 0);
assert(loc.column == str.to!dstring.length - remaining.to!dstring.length, format("%s col %s", str, loc.column));
}
}
testResult(`"test"`, "test", "", true);
testResult(`"test"...`, "test", "...", true);
testResult(`"test\n"`, "test\n", "");
testResult(`"test\n"...`, "test\n", "...");
testResult(`"test\""...`, "test\"", "...");
testResult(`"ä"`, "ä", "", true);
testResult(`"\r\n\\\"\b\f\t\/"`, "\r\n\\\"\b\f\t/", "");
testResult(`"\u1234"`, "\u1234", "");
testResult(`"\uD800\udc00"`, "\U00010000", "");
}
unittest
{
import std.exception;
void testFail(string str)
{
Location loc;
auto rng1 = JSONLexerRange!(string, LexOptions.init)(str);
assertThrown(rng1.front);
auto rng2 = JSONLexerRange!(string, LexOptions.noThrow)(str);
assertNotThrown(rng2.front);
assert(rng2.front.kind == JSONToken.Kind.error);
}
testFail(`"`); // unterminated string
testFail(`"\`); // unterminated string escape sequence
testFail(`"test\"`); // unterminated string
testFail(`"test'`); // unterminated string
testFail("\"test\n\""); // illegal control character
testFail(`"\x"`); // invalid escape sequence
testFail(`"\u123`); // unterminated unicode escape sequence
testFail(`"\u123"`); // too short unicode escape sequence
testFail(`"\u123G"`); // invalid unicode escape sequence
testFail(`"\u123g"`); // invalid unicode escape sequence
testFail(`"\uD800"`); // missing surrogate
testFail(`"\uD800\u"`); // too short second surrogate
testFail(`"\uD800\u1234"`); // invalid surrogate pair
}
unittest
{
import std.exception;
import std.math : approxEqual, isNaN;
static double parseNumberHelper(LexOptions options, R)(ref R input, ref Location loc)
{
auto rng = JSONLexerRange!(R, options & ~LexOptions.noTrackLocation)(input);
rng.parseNumber();
input = cast(R)rng._input;
loc = rng._loc;
assert(rng._front.kind != JSONToken.Kind.error, rng._error);
return rng._front.number;
}
static void test(LexOptions options = LexOptions.init)(string str, double expected, string remainder)
{
import std.conv;
Location loc;
auto strcopy = str;
auto res = parseNumberHelper!options(strcopy, loc);
assert((res.isNaN && expected.isNaN) || approxEqual(res, expected), () @trusted {return res.to!string;}());
assert(strcopy == remainder);
assert(loc.line == 0);
assert(loc.column == str.length - remainder.length, text(loc.column));
}
test("0", 0.0, "");
test("0 ", 0.0, " ");
test("-0", 0.0, "");
test("-0 ", 0.0, " ");
test("-0e+10 ", 0.0, " ");
test("123", 123.0, "");
test("123 ", 123.0, " ");
test("123.0", 123.0, "");
test("123.0 ", 123.0, " ");
test("123.456", 123.456, "");
test("123.456 ", 123.456, " ");
test("123.456e1", 1234.56, "");
test("123.456e1 ", 1234.56, " ");
test("123.456e+1", 1234.56, "");
test("123.456e+1 ", 1234.56, " ");
test("123.456e-1", 12.3456, "");
test("123.456e-1 ", 12.3456, " ");
test("123.456e-01", 12.3456, "");
test("123.456e-01 ", 12.3456, " ");
test("0.123e-12", 0.123e-12, "");
test("0.123e-12 ", 0.123e-12, " ");
test!(LexOptions.specialFloatLiterals)("NaN", double.nan, "");
test!(LexOptions.specialFloatLiterals)("NaN ", double.nan, " ");
test!(LexOptions.specialFloatLiterals)("Infinity", double.infinity, "");
test!(LexOptions.specialFloatLiterals)("Infinity ", double.infinity, " ");
test!(LexOptions.specialFloatLiterals)("-Infinity", -double.infinity, "");
test!(LexOptions.specialFloatLiterals)("-Infinity ", -double.infinity, " ");
}
unittest
{
import std.exception;
static void testFail(LexOptions options = LexOptions.init)(string str)
{
Location loc;
auto rng1 = JSONLexerRange!(string, options)(str);
assertThrown(rng1.front);
auto rng2 = JSONLexerRange!(string, options|LexOptions.noThrow)(str);
assertNotThrown(rng2.front);
assert(rng2.front.kind == JSONToken.Kind.error);
}
testFail("+");
testFail("-");
testFail("+1");
testFail("1.");
testFail(".1");
testFail("01");
testFail("1e");
testFail("1e+");
testFail("1e-");
testFail("1.e");
testFail("1.e-");
testFail("1.ee");
testFail("1.e-e");
testFail("1.e+e");
testFail("NaN");
testFail("Infinity");
testFail("-Infinity");
testFail!(LexOptions.specialFloatLiterals)("NaX");
testFail!(LexOptions.specialFloatLiterals)("InfinitX");
testFail!(LexOptions.specialFloatLiterals)("-InfinitX");
}
/**
* A low-level JSON token as returned by $(D JSONLexer).
*/
struct JSONToken
{
import std.algorithm : among;
/**
* The kind of token represented.
*/
enum Kind
{
none, /// Used internally, never returned from the lexer
error, /// Malformed token
null_, /// The "null" token
boolean, /// "true" or "false" token
number, /// Numeric token
string, /// String token, stored in escaped form
objectStart, /// The "{" token
objectEnd, /// The "}" token
arrayStart, /// The "[" token
arrayEnd, /// The "]" token
colon, /// The ":" token
comma /// The "," token
}
private
{
union
{
JSONString _string;
bool _boolean;
JSONNumber _number;
}
Kind _kind = Kind.none;
}
/// The location of the token in the input.
Location location;
ref JSONToken opAssign(ref JSONToken other) nothrow @trusted @nogc
{
_kind = other._kind;
switch (_kind) with (Kind) {
default: break;
case boolean: _boolean = other._boolean; break;
case number: _number = other._number; break;
case string: _string = other._string; break;
}
this.location = other.location;
return this;
}
/**
* Gets/sets the kind of the represented token.
*
* Setting the token kind is not allowed for any of the kinds that have
* additional data associated (boolean, number and string).
*/
@property Kind kind() const pure nothrow @nogc { return _kind; }
/// ditto
@property Kind kind(Kind value) nothrow @nogc
in { assert(!value.among!(Kind.boolean, Kind.number, Kind.string)); }
body { return _kind = value; }
/// Gets/sets the boolean value of the token.
@property bool boolean() const pure nothrow @trusted @nogc
in { assert(_kind == Kind.boolean, "Token is not a boolean."); }
body { return _boolean; }
/// ditto
@property bool boolean(bool value) pure nothrow @nogc
{
_kind = Kind.boolean;
_boolean = value;
return value;
}
/// Gets/sets the numeric value of the token.
@property JSONNumber number() const pure nothrow @trusted @nogc
in { assert(_kind == Kind.number, "Token is not a number."); }
body { return _number; }
/// ditto
@property JSONNumber number(JSONNumber value) nothrow @nogc
{
_kind = Kind.number;
_number = value;
return value;
}
/// ditto
@property JSONNumber number(double value) nothrow @nogc { return this.number = JSONNumber(value); }
/// Gets/sets the string value of the token.
@property JSONString string() const pure nothrow @trusted @nogc
in { assert(_kind == Kind.string, "Token is not a string."); }
body { return _kind == Kind.string ? _string : JSONString.init; }
/// ditto
@property JSONString string(JSONString value) pure nothrow @nogc
{
_kind = Kind.string;
_string = value;
return value;
}
/// ditto
@property JSONString string(.string value) pure nothrow @nogc { return this.string = JSONString(value); }
/**
* Enables equality comparisons.
*
* Note that the location is considered token meta data and thus does not
* affect the comparison.
*/
bool opEquals(in ref JSONToken other) const nothrow @trusted
{
if (this.kind != other.kind) return false;
switch (this.kind)
{
default: return true;
case Kind.boolean: return this.boolean == other.boolean;
case Kind.number: return this.number == other.number;
case Kind.string: return this.string == other.string;
}
}
/// ditto
bool opEquals(JSONToken other) const nothrow { return opEquals(other); }
/**
* Enables usage of $(D JSONToken) as an associative array key.
*/
size_t toHash() const @trusted nothrow
{
hash_t ret = 3781249591u + cast(uint)_kind * 2721371;
switch (_kind)
{
default: return ret;
case Kind.boolean: return ret + _boolean;
case Kind.number: return ret + typeid(double).getHash(&_number);
case Kind.string: return ret + typeid(.string).getHash(&_string);
}
}
/**
* Converts the token to a string representation.
*
* Note that this representation is NOT the JSON representation, but rather
* a representation suitable for printing out a token including its
* location.
*/
.string toString() const @trusted
{
import std.string;
switch (this.kind)
{
default: return format("[%s %s]", location, this.kind);
case Kind.boolean: return format("[%s %s]", location, this.boolean);
case Kind.number: return format("[%s %s]", location, this.number);
case Kind.string: return format("[%s \"%s\"]", location, this.string);
}
}
}
unittest
{
JSONToken tok;
assert((tok.boolean = true) == true);
assert(tok.kind == JSONToken.Kind.boolean);
assert(tok.boolean == true);
assert((tok.number = 1.0) == 1.0);
assert(tok.kind == JSONToken.Kind.number);