-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy pathJsonValueReader.java
More file actions
1309 lines (1145 loc) · 52.2 KB
/
JsonValueReader.java
File metadata and controls
1309 lines (1145 loc) · 52.2 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
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
/**
* Copyright (c) 2016, Jurgen J. Vinju, Centrum Wiskunde & Informatica (CWI) All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions
* and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.rascalmpl.library.lang.json.internal;
import java.io.EOFException;
import java.io.FilterReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.rascalmpl.debug.IRascalMonitor;
import org.rascalmpl.exceptions.RuntimeExceptionFactory;
import org.rascalmpl.exceptions.Throw;
import org.rascalmpl.types.ReifiedType;
import org.rascalmpl.uri.URIUtil;
import org.rascalmpl.values.IRascalValueFactory;
import org.rascalmpl.values.functions.IFunction;
import org.rascalmpl.values.maybe.UtilMaybe;
import io.usethesource.vallang.IConstructor;
import io.usethesource.vallang.IInteger;
import io.usethesource.vallang.IListWriter;
import io.usethesource.vallang.IMapWriter;
import io.usethesource.vallang.ISetWriter;
import io.usethesource.vallang.ISourceLocation;
import io.usethesource.vallang.IString;
import io.usethesource.vallang.IValue;
import io.usethesource.vallang.IValueFactory;
import io.usethesource.vallang.io.StandardTextReader;
import io.usethesource.vallang.type.ITypeVisitor;
import io.usethesource.vallang.type.Type;
import io.usethesource.vallang.type.TypeFactory;
import io.usethesource.vallang.type.TypeStore;
import com.google.gson.JsonParseException;
import com.google.gson.Strictness;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.MalformedJsonException;
/**
* This class streams a JSON stream directly to an IValue representation and validates the content
* to a given type as declared in a given type store. See the Rascal file lang::json::IO::readJson
* for documentation.
*/
public class JsonValueReader {
private static final TypeFactory TF = TypeFactory.getInstance();
private final TypeStore store;
private final IValueFactory vf;
private final IRascalMonitor monitor;
private final ISourceLocation src;
private VarHandle posHandler;
/* options */
private ThreadLocal<SimpleDateFormat> format;
private boolean trackOrigins = false;
private boolean stopTracking = false;
private boolean explicitConstructorNames;
private boolean explicitDataTypes;
private boolean lenient;
private IFunction parsers;
private Map<Type, IValue> nulls = Collections.emptyMap();
private final class ExpectedTypeDispatcher implements ITypeVisitor<IValue, IOException> {
private final JsonReader in;
private final OriginTrackingReader tracker;
/**
* In this mode we read directly from a given JsonReader, under which we can not
* encapsulate its Reader for counting offsets. This is used by the JSON-RPC bridge.
* @param in
*/
private ExpectedTypeDispatcher(JsonReader in) {
this(in, null);
}
/**
* In this mode we have created an OriginTrackingReader which feeds the JsonReader from below.
* Accurate offsets can be tracked like this, which enables accurate error locations. When
* trackOrigins=true we get accurate origin src fields for objects.
*/
public ExpectedTypeDispatcher(JsonReader in, OriginTrackingReader tracker) {
this.in = in;
this.tracker = tracker;
}
@Override
public IValue visitInteger(Type type) throws IOException {
try {
switch (in.peek()) {
case NUMBER:
// fallthrough
case STRING:
return vf.integer(in.nextString());
case NULL:
in.nextNull();
return inferNullValue(nulls, type);
default:
throw parseErrorHere("Expected integer but got " + in.peek());
}
}
catch (NumberFormatException e) {
throw parseErrorHere("Expected integer but got " + e.getMessage());
}
}
@Override
public IValue visitReal(Type type) throws IOException {
try {
switch (in.peek()) {
case NUMBER:
// fallthrough
case STRING:
return vf.real(in.nextString());
case NULL:
in.nextNull();
return inferNullValue(nulls, type);
default:
throw parseErrorHere("Expected real but got " + in.peek());
}
}
catch (NumberFormatException e) {
throw parseErrorHere("Expected real but got " + e.getMessage());
}
}
private IValue inferNullValue(Map<Type, IValue> nulls, Type expected) {
return nulls.entrySet().stream().map(Entry::getKey).sorted(Type::compareTo)
// give the most specific match:
.filter(superType -> expected.isSubtypeOf(superType)).findFirst()
// lookup the corresponding null value
.map(t -> nulls.get(t))
// the value in the table still has to fit the currently expected type
.filter(r -> r.getType().isSubtypeOf(expected))
// or we muddle on and throw NPE elsewhere. This NPE is important for fault localization. We don't want to hide it here.
.orElse(null);
}
@Override
public IValue visitExternal(Type type) throws IOException {
throw parseErrorHere("External type " + type + "is not implemented yet by the json reader:" + in.getPath());
}
@Override
public IValue visitString(Type type) throws IOException {
if (isNull()) {
return inferNullValue(nulls, type);
}
return vf.string(in.nextString());
}
@Override
public IValue visitTuple(Type type) throws IOException {
if (isNull()) {
return null;
}
List<IValue> l = new ArrayList<>();
in.beginArray();
if (type.hasFieldNames()) {
for (int i = 0; i < type.getArity(); i++) {
l.add(type.getFieldType(i).accept(this));
}
}
else {
for (int i = 0; i < type.getArity(); i++) {
l.add(type.getFieldType(i).accept(this));
}
}
in.endArray();
// filter all the null values
l.forEach(e -> {
if (e == null) {
throw parseErrorHere("Tuples can not have null elements.");
}
});
assert type.getArity() == l.size();
return vf.tuple(l.toArray(new IValue[l.size()]));
}
@Override
public IValue visitVoid(Type type) throws IOException {
throw parseErrorHere("Can not read json values of type void: " + in.getPath());
}
@Override
public IValue visitFunction(Type type) throws IOException {
throw parseErrorHere("Can not read json values of function types: " + in.getPath());
}
@Override
public IValue visitSourceLocation(Type type) throws IOException {
if (isNull()) {
return inferNullValue(nulls, type);
}
switch (in.peek()) {
case STRING:
return sourceLocationString();
case BEGIN_OBJECT:
return sourceLocationObject();
default:
throw parseErrorHere("Could not find string or source location object here: " + in.getPath());
}
}
private IValue sourceLocationObject() throws IOException {
String scheme = null;
String authority = null;
String path = null;
String fragment = "";
String query = "";
int offset = -1;
int length = -1;
int beginLine = -1;
int endLine = -1;
int beginColumn = -1;
int endColumn = -1;
in.beginObject();
while (in.hasNext()) {
String name = in.nextName();
switch (name) {
case "scheme":
scheme = in.nextString();
break;
case "authority":
authority = in.nextString();
break;
case "path":
path = in.nextString();
break;
case "fragment":
fragment = in.nextString();
break;
case "query":
query = in.nextString();
break;
case "offset":
offset = in.nextInt();
break;
case "length":
length = in.nextInt();
break;
case "start":
case "begin":
in.beginArray();
beginLine = in.nextInt();
beginColumn = in.nextInt();
in.endArray();
break;
case "end":
in.beginArray();
endLine = in.nextInt();
endColumn = in.nextInt();
in.endArray();
break;
default:
throw parseErrorHere("unexpected property name " + name + " :" + in.getPath());
}
}
in.endObject();
try {
ISourceLocation root;
if (scheme != null && authority != null && query != null && fragment != null) {
root = vf.sourceLocation(scheme, authority, path, query, fragment);
}
else if (scheme != null) {
root = vf.sourceLocation(scheme, authority == null ? "" : authority, path);
}
else if (path != null) {
root = URIUtil.createFileLocation(path);
}
else {
throw parseErrorHere("Could not parse complete source location: " + in.getPath());
}
if (offset != -1 && length != -1 && beginLine != -1 && endLine != -1 && beginColumn != -1
&& endColumn != -1) {
return vf.sourceLocation(root, offset, length, beginLine, endLine, beginColumn, endColumn);
}
if (offset != -1 && length != -1) {
return vf.sourceLocation(root, offset, length);
}
return root;
}
catch (URISyntaxException e) {
throw parseErrorHere(e.getMessage());
}
}
@Override
public IValue visitValue(Type type) throws IOException {
switch (in.peek()) {
case NUMBER:
return visitNumber(TF.numberType());
case STRING:
return visitString(TF.stringType());
case BEGIN_ARRAY:
return visitList(TF.listType(TF.valueType()));
case BEGIN_OBJECT:
return visitNode(TF.nodeType());
case BOOLEAN:
return visitBool(TF.boolType());
case NAME:
// this would be weird though. names are part of objects, not top-level values.
// this is probably unreachable given the rest of this parser.
return vf.string(in.nextName());
case NULL:
in.nextNull();
return inferNullValue(nulls, type);
default:
throw parseErrorHere(
"Did not expect end of Json value here, while looking for " + type + " + at " + in.getPath());
}
}
private IValue sourceLocationString() throws IOException {
try {
String val = in.nextString().trim();
if (val.startsWith("|") && (val.endsWith("|") || val.endsWith(")"))) {
return new StandardTextReader().read(vf, new StringReader(val));
}
else if (val.contains("://")) {
return vf.sourceLocation(URIUtil.createFromEncoded(val));
}
else {
// will be simple interpreted as an absolute file name
return URIUtil.createFileLocation(val);
}
}
catch (URISyntaxException e) {
throw parseErrorHere(e.getMessage());
}
}
@Override
public IValue visitRational(Type type) throws IOException {
if (isNull()) {
return inferNullValue(nulls, type);
}
switch (in.peek()) {
case BEGIN_ARRAY:
in.beginArray();
IInteger numA = (IInteger) TF.integerType().accept(this);
IInteger denomA = (IInteger) TF.integerType().accept(this);
in.endArray();
return vf.rational(numA, denomA);
case STRING:
return vf.rational(in.nextString());
default:
throw parseErrorHere("Expected rational but got " + in.peek());
}
}
@Override
public IValue visitMap(Type type) throws IOException {
if (isNull()) {
return inferNullValue(nulls, type);
}
IMapWriter w = vf.mapWriter();
switch (in.peek()) {
case BEGIN_OBJECT:
in.beginObject();
if (!type.getKeyType().isString() && in.peek() != JsonToken.END_OBJECT) {
throw parseErrorHere("Can not read JSon object as a map if the key type of the map (" + type
+ ") is not a string at " + in.getPath());
}
while (in.hasNext()) {
IString label = vf.string(in.nextName());
IValue value = type.getValueType().accept(this);
if (value != null) {
w.put(label, value);
}
}
in.endObject();
return w.done();
case BEGIN_ARRAY:
in.beginArray();
while (in.hasNext()) {
in.beginArray();
IValue key = type.getKeyType().accept(this);
IValue value = type.getValueType().accept(this);
if (key != null && value != null) {
w.put(key, value);
}
in.endArray();
}
in.endArray();
return w.done();
default:
throw parseErrorHere("Expected a map encoded as an object or an nested array to match " + type);
}
}
@Override
public IValue visitAlias(Type type) throws IOException {
while (type.isAliased()) {
type = type.getAliased();
}
return type.accept(this);
}
@Override
public IValue visitBool(Type type) throws IOException {
if (isNull()) {
return inferNullValue(nulls, type);
}
return vf.bool(in.nextBoolean());
}
/**
* @return the offset where the parser cursor is _right now_.
* and `this.lastPos` is set to the last internal `pos` field of the GsonReader `in`
* and `offset` is set to the current character offset in the input.
*
* This method depends on arbitraire private details of JsonReader from the gson package.
* In particular it tries to detect when its internal buffer has wrapped (probably at 1024 characters)
* The internal private field `pos` in JsonReader holds the index into the buffer, and it is
* advanced by 1 with every character. We use it to update a locale file offset field, and we
* have to watch out for the buffer reset (pos is set to 0 again) while doing this.
*
* KNOWN BUG: These tricks break when a comment or whitespace section between normal tokens is larger
* than or equal to 1024 Java chars. getPos() will not be able to detect the offset increase,
* because it has not been called in between from JsonValueReader to JsonReader and the condition
* `internalPos < lastPos` will not have had the opportunity to evaluate to `true`.
*/
private int getOffset() {
if (stopTracking) {
return 0;
}
try {
assert posHandler != null;
var internalPos = (int) posHandler.get(in);
return tracker.getOffsetAtBufferPos(internalPos);
}
catch (IllegalArgumentException | SecurityException e) {
// we stop trying to track positions if it fails so hard,
// this way we at least can get some form of DOM back.
stopTracking = true;
return 0;
}
}
private int getLine() {
if (stopTracking) {
return 1;
}
try {
var internalPos = (int) posHandler.get(in);
return tracker.getLineAtBufferPos(internalPos);
}
catch (IllegalArgumentException | SecurityException e) {
// stop trying to recover the positions
stopTracking = true;
return 1;
}
}
/**
* We try to recover the column position. This used internal private fields
* of the GsonReader class.
*
*
* @return the column position the parser is at currently.
*/
private int getCol() {
if (stopTracking) {
return 0;
}
try {
assert posHandler != null;
var internalPos = (int) posHandler.get(in);
return tracker.getColumnAtBufferPos(internalPos);
}
catch (IllegalArgumentException | SecurityException e) {
// stop trying to recover the positions
stopTracking = true;
return 0;
}
}
protected Throw parseErrorHere(String cause) {
var location = getRootLoc();
int offset = getOffset();
int line = getLine();
int col = getCol();
if (!stopTracking) {
return RuntimeExceptionFactory
.jsonParseError(vf.sourceLocation(location, offset, 1, line, line, col, col + 1), cause, in.getPath());
}
else {
// if we didn't track the offset, we can at least produce line and column information, but not as a
// default Rascal ParseError with '0' or '-1' for offset, because that can trigger assertions and
// break other assumptions clients make about the source location values.
return RuntimeExceptionFactory
.jsonParseError(location, line, col, cause, in.getPath());
}
}
/**
* Expecting an ADT we found NULL on the lookahead. This is either a Maybe or we can use the map of
* null values.
*/
private IValue visitNullAsAbstractData(Type type) {
return inferNullValue(nulls, type);
}
/**
* Expecting an ADT we found a string value instead. Now we can (try to) apply the parsers that were
* passed in. If that does not fly, we can interpret strings as nullary ADT constructors.
*/
private IValue visitStringAsAbstractData(Type type) throws IOException {
var stringInput = in.nextString();
// might be a parsable string. let's see.
if (parsers != null) {
var reified = new org.rascalmpl.types.TypeReifier(vf).typeToValue(type, new TypeStore(), vf.map());
try {
return parsers.call(Collections.emptyMap(), reified, vf.string(stringInput));
}
catch (Throw t) {
Type excType = t.getException().getType();
if (excType.isAbstractData()
&& ((IConstructor) t.getException()).getConstructorType().getName().equals("ParseError")) {
throw t; // that's a real parse error to report
}
// otherwise we fall through to enum recognition
}
}
// enum!
Set<Type> enumCons = store.lookupConstructor(type, stringInput);
for (Type candidate : enumCons) {
if (candidate.getArity() == 0) {
return vf.constructor(candidate);
}
}
if (parsers != null) {
throw parseErrorHere("parser failed to recognize \"" + stringInput
+ "\" and no nullary constructor found for " + type + "either");
}
else {
throw parseErrorHere("no nullary constructor found for " + type + ", that matches " + stringInput);
}
}
/**
* This is the main workhorse. Every object is mapped one-to-one to an ADT constructor instance. The
* field names (keyword parameters and positional) are mapped to field names of the object. The name
* of the constructor is _not_ consequential.
*
* @param type
* @return
* @throws IOException
*/
private IValue visitObjectAsAbstractData(Type type) throws IOException {
Set<Type> alternatives = null;
int startPos = Math.max(getOffset() - 1 /* pos cursor is at { */, 0);
int startLine = getLine();
int startCol = getCol() - 1;
in.beginObject();
// use explicit information in the JSON to select and filter constructors from the TypeStore
// we expect always to have the field _constructor before _type.
if (explicitConstructorNames || explicitDataTypes) {
String consName = null;
String typeName = null; // this one is optional, and the order with cons is not defined.
String consLabel = in.nextName();
// first we read either a cons name or a type name
if (explicitConstructorNames && "_constructor".equals(consLabel)) {
consName = in.nextString();
}
else if (explicitDataTypes && "_type".equals(consLabel)) {
typeName = in.nextString();
}
// optionally read the second field
if (explicitDataTypes && typeName == null) {
// we've read a constructor name, but we still need a type name
consLabel = in.nextName();
if (explicitDataTypes && "_type".equals(consLabel)) {
typeName = in.nextString();
}
}
else if (explicitDataTypes && consName == null) {
// we've read type name, but we still need a constructor name
consLabel = in.nextName();
if (explicitDataTypes && "_constructor".equals(consLabel)) {
consName = in.nextString();
}
}
if (explicitDataTypes && typeName == null) {
throw parseErrorHere("Missing a _type field: " + in.getPath());
}
else if (explicitConstructorNames && consName == null) {
throw parseErrorHere("Missing a _constructor field: " + in.getPath());
}
if (typeName != null && consName != null) {
// first focus on the given type name
var dataType = TF.abstractDataType(store, typeName);
alternatives = store.lookupConstructor(dataType, consName);
}
else {
// we only have a constructor name
// lookup over all data types by constructor name
alternatives = store.lookupConstructors(consName);
}
}
else {
alternatives = store.lookupAlternatives(type);
}
if (alternatives.size() > 1) {
monitor.warning("selecting arbitrary constructor for " + type, vf.sourceLocation(in.getPath()));
}
else if (alternatives.size() == 0) {
throw parseErrorHere("No fitting constructor found for " + in.getPath());
}
Type cons = alternatives.iterator().next();
IValue[] args = new IValue[cons.getArity()];
Map<String, IValue> kwParams = new HashMap<>();
if (!cons.hasFieldNames() && cons.getArity() != 0) {
throw parseErrorHere("For the object encoding constructors must have field names " + in.getPath());
}
while (in.hasNext()) {
String label = in.nextName();
if (cons.hasField(label)) {
IValue val = cons.getFieldType(label).accept(this);
if (val != null) {
args[cons.getFieldIndex(label)] = val;
}
else {
throw parseErrorHere("Could not parse argument " + label + ":" + in.getPath());
}
}
else if (cons.hasKeywordField(label, store)) {
if (!isNull()) { // lookahead for null to give default parameters the preference.
IValue val = store.getKeywordParameterType(cons, label).accept(this);
// null can still happen if the nulls map doesn't have a default
if (val != null) {
// if the value is null we'd use the default value of the defined field in the constructor
kwParams.put(label, val);
}
}
else {
var nullValue = inferNullValue(nulls, cons.getAbstractDataType());
if (nullValue != null) {
kwParams.put(label, nullValue);
}
}
}
else { // its a normal arg, pass its label to the child
if (!explicitConstructorNames && "_constructor".equals(label)) {
// ignore additional _constructor fields.
in.nextString(); // skip the constructor value
continue;
}
else if (!explicitDataTypes && "_type".equals(label)) {
// ignore additional _type fields.
in.nextString(); // skip the type value
continue;
}
else {
// field label does not match data type definition
throw parseErrorHere("Unknown field " + label + ":" + in.getPath());
}
}
}
int endPos = Math.max(getOffset() - 1, 0);
assert endPos > startPos : "offset tracking messed up while stopTracking is " + stopTracking + " and trackOrigins is " + trackOrigins;
int endLine = getLine();
int endCol = getCol() - 1;
in.endObject();
for (int i = 0; i < args.length; i++) {
if (args[i] == null) {
throw parseErrorHere(
"Missing argument " + cons.getFieldName(i) + " to " + cons + ":" + in.getPath());
}
}
if (trackOrigins && !stopTracking) {
kwParams.put(kwParams.containsKey("src") ? "rascal-src" : "src",
vf.sourceLocation(getRootLoc(), startPos, endPos - startPos + 1, startLine, endLine, startCol, endCol + 1));
}
return vf.constructor(cons, args, kwParams);
}
private ISourceLocation getRootLoc() {
if (src == null) {
return URIUtil.rootLocation("unknown");
}
else {
return src;
}
}
@Override
public IValue visitAbstractData(Type type) throws IOException {
if (UtilMaybe.isMaybe(type)) {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return UtilMaybe.nothing();
}
else {
// dive into the wrapped type, and wrap the result. Could be a str, int, or anything.
return UtilMaybe.just(type.getTypeParameters().getFieldType(0).accept(this));
}
}
switch (in.peek()) {
case NULL:
return visitNullAsAbstractData(type);
case STRING:
return visitStringAsAbstractData(type);
case BEGIN_OBJECT:
return visitObjectAsAbstractData(type);
default:
throw parseErrorHere("Expected ADT:" + type + ", but found " + in.peek().toString());
}
}
@Override
public IValue visitConstructor(Type type) throws IOException {
return type.getAbstractDataType().accept(this);
}
@Override
public IValue visitNode(Type type) throws IOException {
if (isNull()) {
return inferNullValue(nulls, type);
}
int startPos = Math.max(getOffset() - 1, 0);
int startLine = getLine();
int startCol = getCol() - 1;
in.beginObject();
Map<String, IValue> kws = new HashMap<>();
Map<String, IValue> args = new HashMap<>();
String name = "object";
while (in.hasNext()) {
String kwName = in.nextName();
if (kwName.equals("_name")) {
name = ((IString) TF.stringType().accept(this)).getValue();
continue;
}
boolean positioned = kwName.startsWith("__arg");
if (!isNull()) { // lookahead for null to give default parameters the preference.
IValue val = TF.valueType().accept(this);
if (val != null) {
// if the value is null we'd use the default value of the defined field in the constructor
(positioned ? args : kws).put(kwName, val);
}
}
else {
var nullValue = inferNullValue(nulls, TF.valueType());
if (nullValue != null) {
(positioned ? args : kws).put(kwName, nullValue);
}
}
}
int endPos = Math.max(getOffset() - 1, 0);
int endLine = getLine();
int endCol = getCol() - 1;
in.endObject();
if (trackOrigins && !stopTracking) {
kws.put(kws.containsKey("src") ? "rascal-src" : "src",
vf.sourceLocation(getRootLoc(), startPos, endPos - startPos + 1, startLine, endLine, startCol, endCol + 1));
}
IValue[] argArray = args.entrySet().stream().sorted((e, f) -> e.getKey().compareTo(f.getKey()))
.filter(e -> e.getValue() != null).map(e -> e.getValue()).toArray(IValue[]::new);
return vf.node(name, argArray, kws);
}
@Override
public IValue visitNumber(Type type) throws IOException {
if (isNull()) {
return inferNullValue(nulls, type);
}
if (in.peek() == JsonToken.BEGIN_ARRAY) {
return visitRational(type);
}
String numberString = in.nextString();
if (numberString.contains("r")) {
return vf.rational(numberString);
}
if (numberString.matches(".*[\\.eE].*")) {
return vf.real(numberString);
}
else {
return vf.integer(numberString);
}
}
@Override
public IValue visitParameter(Type type) throws IOException {
return type.getBound().accept(this);
}
@Override
public IValue visitDateTime(Type type) throws IOException {
try {
switch (in.peek()) {
case STRING:
Date parsedDate = format.get().parse(in.nextString());
return vf.datetime(parsedDate.toInstant().toEpochMilli());
case NUMBER:
return vf.datetime(in.nextLong());
default:
throw parseErrorHere("Expected a datetime instant " + in.getPath());
}
}
catch (ParseException e) {
throw parseErrorHere("Could not parse date: " + in.getPath());
}
}
@Override
public IValue visitList(Type type) throws IOException {
if (isNull()) {
return inferNullValue(nulls, type);
}
IListWriter w = vf.listWriter();
in.beginArray();
while (in.hasNext()) {
// here we pass label from the higher context
IValue elem =
isNull() ? inferNullValue(nulls, type.getElementType()) : type.getElementType().accept(this);
if (elem != null) {
w.append(elem);
}
}
in.endArray();
return w.done();
}
public IValue visitSet(Type type) throws IOException {
if (isNull()) {
return inferNullValue(nulls, type);
}
ISetWriter w = vf.setWriter();
in.beginArray();
while (in.hasNext()) {
// here we pass label from the higher context
IValue elem =
isNull() ? inferNullValue(nulls, type.getElementType()) : type.getElementType().accept(this);
if (elem != null) {
w.insert(elem);
}
}
in.endArray();
return w.done();
}
private boolean isNull() throws IOException {
// we use null in JSon to encode optional values.
// this will be mapped to keyword parameters in Rascal,
// or an exception if we really need a value
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return true;
}
return false;
}
}
/**
* @param vf factory which will be used to construct values
* @param store type store to lookup constructors of abstract data-types in and the types of keyword
* fields
* @param monitor provides progress reports and warnings
* @param src loc to use to identify the entire file.
*/
public JsonValueReader(IValueFactory vf, TypeStore store, IRascalMonitor monitor, ISourceLocation src) {
this.vf = vf;
this.store = store;
this.monitor = monitor;
this.src = src;
this.stopTracking = false;
setCalendarFormat("yyyy-MM-dd'T'HH:mm:ssZ");
try {
var lookup = MethodHandles.lookup();
var privateLookup = MethodHandles.privateLookupIn(JsonReader.class, lookup);
this.posHandler = privateLookup.findVarHandle(JsonReader.class, "pos", int.class);
if (posHandler == null) {
stopTracking = true;
}
}
catch (NoSuchFieldException | SecurityException | IllegalAccessException e) {
// we disable the origin tracking if we can not get to the fields
stopTracking = true;
monitor.warning("Unable to retrieve origin information due to: " + e.getMessage(), src);
}
}
public JsonValueReader(IValueFactory vf, IRascalMonitor monitor, ISourceLocation src) {
this(vf, new TypeStore(), monitor, src);
}