forked from swiftlang/swift-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSONParserDecoder.swift
More file actions
1878 lines (1638 loc) · 77.4 KB
/
JSONParserDecoder.swift
File metadata and controls
1878 lines (1638 loc) · 77.4 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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2026 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#elseif FOUNDATION_FRAMEWORK
import Foundation
#endif
#if canImport(Darwin)
import Darwin
#elseif canImport(Bionic)
import Bionic
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(ucrt)
import ucrt
#elseif canImport(WASILibc)
import WASILibc
#endif
// TODO: EMBEDDED: Don't use the `final class` Internals type for Embedded only. We shouldn't have the same typed-throws overhead there anyway.
public struct JSONParserDecoder: JSONDecoderProtocol, ~Escapable {
@usableFromInline
internal typealias Options = NewJSONDecoder.Options
// Structures with container nesting deeper than this limit are not valid.
@usableFromInline
internal static var maximumRecursionDepth: Int { 512 }
@usableFromInline
internal var state: ParserState
@usableFromInline
internal var midContainer: Bool
@usableFromInline
@_lifetime(copy state)
init(state: ParserState, midContainer: Bool = false) {
self.state = state
self.midContainer = midContainer
}
public var codingPath: CodingPath {
state.currentTopCodingPathNode.pointee.path
}
public typealias StructDecoder = DictionaryDecoder
public struct DictionaryDecoder: JSONDictionaryDecoder, ~Escapable {
public typealias FieldDecoder = JSONParserDecoder.FieldDecoder
public typealias ValueDecoder = JSONParserDecoder
@usableFromInline
var parserState: ParserState
@usableFromInline
@_lifetime(copy parserState)
init(parserState: ParserState, midContainer: Bool) throws(JSONError) {
// Only check depth and increment when creating a new container
if !midContainer {
// Check depth limit before creating container
guard parserState.depth < JSONParserDecoder.maximumRecursionDepth else {
throw JSONError.tooManyNestedArraysOrDictionaries()
}
self.parserState = parserState
self.parserState.depth += 1
let brace = try self.parserState.reader.consumeWhitespaceAndPeek()
try self.parserState.reader.expectBeginningOfObject(brace)
self.parserState.reader.moveReaderIndex(forwardBy: 1) // consume open brace
} else {
// For midContainer, just copy the state without depth changes
self.parserState = parserState
}
}
public var codingPath: CodingPath {
parserState.currentTopCodingPathNode.pointee.path
}
@_lifetime(self: copy self)
public mutating func decodeExpectedOrderField(required: Bool, matchingClosure: (UTF8Span) -> Bool, optimizedSafeStringKey: JSONSafeStringKey?, andValue valueDecoderClosure: (inout ValueDecoder) throws(CodingError.Decoding) -> Void) throws(CodingError.Decoding) -> Bool {
do {
// The dictionary could be empty.
let nextChar = try parserState.reader.consumeWhitespaceAndPeek()
if nextChar == ._closebrace {
if required {
print("Break here")
}
return !required
}
try parserState.reader.expectBeginningOfObjectKey(nextChar)
let savedPosition = parserState.reader.readOffset
parserState.reader.moveReaderIndex(forwardBy: 1) // consume open quote
let matches: Bool
if let key = optimizedSafeStringKey {
matches = try parserState.reader.matchExpectedString(key.string)
} else {
let parsed = try parserState.reader.parsedStringContentAndTrailingQuote()
switch parsed {
case .span(let span):
matches = matchingClosure(span)
case .string(let str, _):
matches = matchingClosure(str.utf8Span)
}
}
guard matches, parserState.reader.read() == ._quote else {
parserState.reader.readOffset = savedPosition
if required {
print("Break here")
}
return !required
}
let sourceKeyBytes: UnsafeRawBufferPointer = parserState.reader.bytes.extracting(unchecked: savedPosition+1..<parserState.reader.readOffset-1).withUnsafeBytes{ $0 }
let colon = try parserState.reader.consumeWhitespaceAndPeek()
try parserState.reader.expectObjectKeyValueColon(colon)
parserState.reader.moveReaderIndex(forwardBy: 1) // consume colon
// Cheating a bit, using the StaticString parameter for the key here.
parserState.currentTopCodingPathNode.pointee.setDictionaryKey(sourceKeyBytes)
let preValueOffset = self.parserState.reader.readOffset
var valueDecoder = JSONParserDecoder(state: self.parserState)
valueDecoder.state.copyRelevantState(from: self.parserState)
try valueDecoderClosure(&valueDecoder)
if valueDecoder.state.reader.readOffset == preValueOffset {
try valueDecoder.state.skipValue()
}
self.parserState.copyRelevantState(from: valueDecoder.state)
// TODO: What about EOF for assumed dictionary contents.
let next = try parserState.reader.consumeWhitespaceAndPeek()
switch next {
case ._comma:
parserState.reader.moveReaderIndex(forwardBy: 1) // consume comma (which *could* be a trailing comma)
try parserState.reader.consumeWhitespaceAndPeek()
case ._closebrace:
break // Wait for something else to consume brace
default:
throw JSONError.unexpectedCharacter(context: "in object", ascii: next, location: parserState.reader.sourceLocation)
}
} catch let error as JSONError {
throw error.at(self.codingPath)
} catch {
// TODO: Fix unsavory language workaround
throw error as! CodingError.Decoding
}
return true
}
@_lifetime(self: copy self)
public mutating func decodeEachField(_ fieldDecoderClosure: (inout FieldDecoder) throws(CodingError.Decoding) -> Void, andValue valueDecoderClosure: (inout JSONParserDecoder) throws(CodingError.Decoding) -> Void) throws(CodingError.Decoding) {
do {
// The dictionary could be empty.
let nextChar = try parserState.reader.consumeWhitespaceAndPeek()
if nextChar == ._closebrace {
return
}
// A single decoder value that will be reused for each individual sub-value.
var valueDecoder = JSONParserDecoder(state: self.parserState)
var foundQuote = nextChar == ._quote
var foundCloseBrace = false
while !foundCloseBrace {
guard foundQuote else {
throw JSONError.unexpectedCharacter(context: "at beginning of object key", ascii: parserState.reader.peek()!, location: parserState.reader.sourceLocation)
}
parserState.reader.moveReaderIndex(forwardBy: 1) // consume open quote
let key = try parserState.reader.parsedStringContentAndTrailingQuote()
var fieldDecoder = FieldDecoder(string: key)
try fieldDecoderClosure(&fieldDecoder)
let colon = try parserState.reader.consumeWhitespaceAndPeek()
try parserState.reader.expectObjectKeyValueColon(colon)
parserState.reader.moveReaderIndex(forwardBy: 1) // consume colon
parserState.currentTopCodingPathNode.pointee.setDictionaryKey(key.buffer)
let preValueOffset = self.parserState.reader.readOffset
valueDecoder.state.copyRelevantState(from: self.parserState)
try valueDecoderClosure(&valueDecoder)
if valueDecoder.state.reader.readOffset == preValueOffset {
try valueDecoder.state.skipValue()
}
self.parserState.copyRelevantState(from: valueDecoder.state)
// TODO: What about EOF for assumed dictionary contents.
let next = try parserState.reader.consumeWhitespaceAndPeek()
switch next {
case ._comma:
parserState.reader.moveReaderIndex(forwardBy: 1) // consume comma (which *could* be a trailing comma)
foundQuote = try parserState.reader.consumeWhitespaceAndPeek() == ._quote
case ._closebrace:
foundCloseBrace = true
default:
throw JSONError.unexpectedCharacter(context: "in object", ascii: next, location: parserState.reader.sourceLocation)
}
}
} catch let error as JSONError {
throw error.at(self.codingPath)
} catch {
// TODO: Fix unsavory language workaround
throw error as! CodingError.Decoding
}
}
// TODO: Take care of all this code duplication here and above--without sacrificing performance.
@_lifetime(self: copy self)
public mutating func decodeEachKeyAndValue(_ closure: (String, inout ValueDecoder) throws(CodingError.Decoding) -> Bool) throws(CodingError.Decoding) {
do {
// The dictionary could be empty.
let nextChar = try parserState.reader.consumeWhitespaceAndPeek()
if nextChar == ._closebrace {
// TODO: Can we support multiple flattens? When if the first invocation got everything and stopped on the close brace, the second one saw the close brace and consumed it, and then the third one sees data outside the object?
return
}
// A single decoder value that will be reused for each individual sub-value.
var valueDecoder = JSONParserDecoder(state: self.parserState)
var foundQuote = nextChar == ._quote
var foundCloseBrace = false
while !foundCloseBrace {
guard foundQuote else {
throw JSONError.unexpectedCharacter(context: "at beginning of object key", ascii: parserState.reader.peek()!, location: parserState.reader.sourceLocation)
}
parserState.reader.moveReaderIndex(forwardBy: 1) // consume open quote
var key = ""
let keySpan = try parserState.reader.parseStringContentAndTrailingQuote(&key)
let colon = try parserState.reader.consumeWhitespaceAndPeek()
try parserState.reader.expectObjectKeyValueColon(colon)
parserState.reader.moveReaderIndex(forwardBy: 1) // consume colon
// Update coding path with the key
keySpan.withUnsafeBytes {
parserState.currentTopCodingPathNode.pointee.setDictionaryKey($0)
}
let preValueOffset = self.parserState.reader.readOffset
valueDecoder.state.copyRelevantState(from: self.parserState)
let stopped = try closure(key, &valueDecoder)
if valueDecoder.state.reader.readOffset == preValueOffset {
try valueDecoder.state.skipValue()
}
self.parserState.copyRelevantState(from: valueDecoder.state)
// TODO: What about EOF for assumed dictionary contents.
let next = try parserState.reader.consumeWhitespaceAndPeek()
switch next {
case ._comma:
parserState.reader.moveReaderIndex(forwardBy: 1) // consume comma (which *could* be a trailing comma)
foundQuote = try parserState.reader.consumeWhitespaceAndPeek() == ._quote
case ._closebrace:
foundCloseBrace = true
default:
throw JSONError.unexpectedCharacter(context: "in object", ascii: next, location: parserState.reader.sourceLocation)
}
// If stopped, exit loop by returning early, before potentially consuming a close brace. Parser should be queued up to the next quote or the close brace.
if stopped { return }
}
} catch let error as JSONError {
throw error.at(self.codingPath)
} catch {
// TODO: Fix unsavory language workaround
throw error as! CodingError.Decoding
}
}
@_lifetime(self: copy self)
public mutating func decodeKeyAndValue(_ closure: (String, inout JSONParserDecoder) throws(CodingError.Decoding) -> Void) throws(CodingError.Decoding) -> Bool {
var key: String = ""
return try self.decodeKey { keyDecoder throws(CodingError.Decoding) in
key = try keyDecoder.decode(String.self)
} andValue: { valueDecoder throws(CodingError.Decoding) in
try closure(key, &valueDecoder)
}
}
@_lifetime(self: copy self)
public mutating func withWrappingDecoder<T>(_ closure: (inout ValueDecoder) throws(CodingError.Decoding) -> T) throws(CodingError.Decoding) -> T {
var decoder = JSONParserDecoder(state: self.parserState, midContainer: true)
let result = try closure(&decoder)
self.parserState.copyRelevantState(from: decoder.state)
return result
}
public func prepareIntermediateValueStorage() -> JSONIntermediateKeyValueStorage {
.init(options: self.parserState.options[])
}
@usableFromInline
@_lifetime(self: copy self)
internal mutating func _finish() throws(CodingError.Decoding) {
// In many cases we may have already fouund the close brace. If we haven't, then we have to decode and skip value any remaining values.
if parserState.reader.peek() != ._closebrace {
try self.decodeEachField { _ in /* do nothing */ } andValue: { _ in /* do nothing */ }
assert(parserState.reader.peek() == ._closebrace)
}
parserState.reader.moveReaderIndex(forwardBy: 1) // consume close brace
parserState.depth -= 1
}
}
public struct FieldDecoder: JSONFieldDecoder, ~Escapable {
@usableFromInline
let string: ParserState.DocumentReader.ParsedString
@_lifetime(copy string)
init(string: ParserState.DocumentReader.ParsedString) {
self.string = string
}
@_alwaysEmitIntoClient
@inlinable
public func decode<T: DecodingField>(_: T.Type) throws(CodingError.Decoding) -> T {
switch string {
case .span(let span):
return try T.field(for: span)
case .string(let string, _):
return try T.field(for: string)
}
}
@_alwaysEmitIntoClient
public func matches(_ field: some DecodingField) -> Bool {
switch string {
case .span(let span):
field.matches(span)
case .string(let string, _):
field.matches(string)
}
}
// TODO: Only testing this because the above don't appear to inline like I want.
@_alwaysEmitIntoClient
public func matches(_ key: StaticString) -> Bool {
switch string {
case .span(let span):
return span.span.withUnsafeBufferPointer { buff in
guard key.utf8CodeUnitCount == buff.count else {
return false
}
return memcmp(key.utf8Start, buff.baseAddress!, key.utf8CodeUnitCount) == 0
}
case .string(let string, _):
return key.description == string
}
}
}
public struct ArrayDecoder: JSONArrayDecoder, ~Escapable {
public typealias ElementDecoder = JSONParserDecoder
var innerParser: JSONParserDecoder
var hasNext: Bool
@_lifetime(copy parserState)
init(parserState: ParserState, midContainer: Bool) throws(JSONError) {
self.innerParser = .init(state: parserState)
if !midContainer {
// Check depth limit before creating container
guard parserState.depth < JSONParserDecoder.maximumRecursionDepth else {
throw JSONError.tooManyNestedArraysOrDictionaries()
}
self.innerParser.state.depth += 1
try innerParser.parseArrayBeginning()
}
hasNext = try innerParser.prepareForArrayElement(first: true, consumingCloseBracket: false)
}
public var codingPath: CodingPath {
innerParser.codingPath
}
@_lifetime(self: copy self)
public mutating func decodeNext<T: ~Copyable>(_ closure: (inout JSONParserDecoder) throws(CodingError.Decoding) -> T) throws(CodingError.Decoding) -> T? {
do {
guard hasNext else {
return nil
}
let result = try closure(&innerParser)
hasNext = try innerParser.prepareForArrayElement(first: false, consumingCloseBracket: false)
self.innerParser.state.currentTopCodingPathNode.pointee.incrementArrayIndex()
return result
} catch let error as JSONError {
throw error.at(self.codingPath)
} catch {
// TODO: Fix unsavory language workaround
throw error as! CodingError.Decoding
}
}
@_lifetime(self: copy self)
public mutating func decodeEachElement(_ closure: (inout ElementDecoder) throws(CodingError.Decoding) -> Void) throws(CodingError.Decoding) {
do {
repeat {
self.innerParser.state.currentTopCodingPathNode.pointee.incrementArrayIndex()
try closure(&innerParser)
} while try self.innerParser.prepareForArrayElement(first: false, consumingCloseBracket: false)
hasNext = false
} catch let error as JSONError {
throw error.at(self.codingPath)
} catch {
// TODO: Fix unsavory language workaround
throw error as! CodingError.Decoding
}
}
@_lifetime(self: copy self)
internal mutating func _finish() throws(CodingError.Decoding) {
while let _ = try decodeNext(BlackHoleDecodable.self) { }
self.innerParser.finishArray()
}
}
@_lifetime(self: copy self)
public mutating func decodeStruct<T: ~Copyable>(_ closure: (inout StructDecoder) throws(CodingError.Decoding) -> T) throws(CodingError.Decoding) -> T {
var dictionaryNode: InlineArray = [
CodingPathNode.newDictionaryNode(withParent: state.currentTopCodingPathNode)
]
var nodeSpan = dictionaryNode.mutableSpan
state.currentTopCodingPathNode = nodeSpan.withUnsafeMutableBufferPointer {
$0.baseAddress!
}
defer {
withExtendedLifetime(nodeSpan) {
state.currentTopCodingPathNode.unwindToParent()
}
}
do {
var decoder = try StructDecoder(parserState: self.state, midContainer: self.midContainer)
let result = try closure(&decoder)
if !midContainer {
try decoder._finish()
}
self.state.copyRelevantState(from: decoder.parserState)
return result
} catch let error as JSONError {
throw error.at(self.codingPath)
} catch {
// TODO: Fix unsavory language workaround
throw error as! CodingError.Decoding
}
}
@_lifetime(self: copy self)
public mutating func decodeDictionary<T: ~Copyable>(_ closure: (inout DictionaryDecoder) throws(CodingError.Decoding) -> T) throws(CodingError.Decoding) -> T {
try self.decodeStruct(closure)
}
@_lifetime(self: copy self)
public mutating func decodeArray<T: ~Copyable>(_ closure: (inout ArrayDecoder) throws(CodingError.Decoding) -> T) throws(CodingError.Decoding) -> T {
var arrayNode: InlineArray = [
CodingPathNode.newArrayNode(withParent: state.currentTopCodingPathNode)
]
var nodeSpan = arrayNode.mutableSpan
state.currentTopCodingPathNode = nodeSpan.withUnsafeMutableBufferPointer {
$0.baseAddress!
}
defer {
withExtendedLifetime(nodeSpan) {
state.currentTopCodingPathNode.unwindToParent()
}
}
do {
var decoder = try ArrayDecoder(parserState: self.state, midContainer: self.midContainer)
let result = try closure(&decoder)
// TODO: Test if not all elements parsed.
try decoder._finish()
self.state.copyRelevantState(from: decoder.innerParser.state)
return result
} catch let error as JSONError {
throw error.at(self.codingPath)
} catch {
// TODO: Fix unsavory language workaround
throw error as! CodingError.Decoding
}
}
// MARK: - Enum Decoding
/// Decodes an enum case with no associated values from `{"caseName":{}}` format
@_lifetime(self: copy self)
public mutating func decodeEnumCase<T: ~Copyable>(
_ closure: (inout FieldDecoder) throws(CodingError.Decoding) -> T
) throws(CodingError.Decoding) -> T {
// Check depth limit before creating container
guard state.depth < Self.maximumRecursionDepth else {
throw JSONError.tooManyNestedArraysOrDictionaries(location: state.reader.sourceLocation).at(self.codingPath)
}
// Set up coding path node for the enum wrapper dictionary
var dictionaryNode: InlineArray = [
CodingPathNode.newDictionaryNode(withParent: state.currentTopCodingPathNode)
]
var nodeSpan = dictionaryNode.mutableSpan
state.currentTopCodingPathNode = nodeSpan.withUnsafeMutableBufferPointer {
$0.baseAddress!
}
defer {
withExtendedLifetime(nodeSpan) {
state.currentTopCodingPathNode.unwindToParent()
}
}
state.depth += 1
defer { state.depth -= 1 }
do {
// Parse opening brace
let openBrace = try state.reader.consumeWhitespaceAndPeek()
guard openBrace == ._openbrace else {
throw JSONError.unexpectedCharacter(context: "expecting enum object", ascii: openBrace, location: state.reader.sourceLocation)
}
state.reader.moveReaderIndex(forwardBy: 1)
// Parse the case name (key)
let openQuote = try state.reader.consumeWhitespaceAndPeek()
guard openQuote == ._quote else {
throw JSONError.unexpectedCharacter(context: "expecting enum case name", ascii: openQuote, location: state.reader.sourceLocation)
}
state.reader.moveReaderIndex(forwardBy: 1)
let caseName = try state.reader.parsedStringContentAndTrailingQuote()
// Update coding path
state.currentTopCodingPathNode.pointee.setDictionaryKey(caseName.buffer)
var fieldDecoder = FieldDecoder(string: caseName)
let result = try closure(&fieldDecoder)
// Parse colon
let colon = try state.reader.consumeWhitespaceAndPeek()
guard colon == ._colon else {
throw JSONError.unexpectedCharacter(context: "after enum case name", ascii: colon, location: state.reader.sourceLocation)
}
state.reader.moveReaderIndex(forwardBy: 1)
// Verify empty object value: {}
let valueOpenBrace = try state.reader.consumeWhitespaceAndPeek()
guard valueOpenBrace == ._openbrace else {
throw JSONError.unexpectedCharacter(context: "expecting empty object for value-less enum", ascii: valueOpenBrace, location: state.reader.sourceLocation)
}
state.reader.moveReaderIndex(forwardBy: 1)
let closeBrace = try state.reader.consumeWhitespaceAndPeek()
guard closeBrace == ._closebrace else {
throw JSONError.unexpectedCharacter(context: "expecting empty object for value-less enum", ascii: closeBrace, location: state.reader.sourceLocation)
}
state.reader.moveReaderIndex(forwardBy: 1)
// Parse closing brace of outer object
let outerCloseBrace = try state.reader.consumeWhitespaceAndPeek()
guard outerCloseBrace == ._closebrace else {
throw JSONError.unexpectedCharacter(context: "after enum value", ascii: outerCloseBrace, location: state.reader.sourceLocation)
}
state.reader.moveReaderIndex(forwardBy: 1)
return result
} catch let error as JSONError {
throw error.at(self.codingPath)
} catch {
// TODO: Fix unsavory language workaround
throw error as! CodingError.Decoding
}
}
/// Decodes an enum case with associated values from `{"caseName":{"field1":value1,...}}` format
@_lifetime(self: copy self)
public mutating func decodeEnumCase<T: ~Copyable>(
_ closure: (_ caseName: inout FieldDecoder, _ associatedValues: inout StructDecoder) throws(CodingError.Decoding) -> T
) throws(CodingError.Decoding) -> T {
// Check depth limit before creating container
guard state.depth < Self.maximumRecursionDepth else {
throw JSONError.tooManyNestedArraysOrDictionaries(location: state.reader.sourceLocation).at(self.codingPath)
}
// Set up coding path node for the enum wrapper dictionary
var outerDictionaryNode: InlineArray = [
CodingPathNode.newDictionaryNode(withParent: state.currentTopCodingPathNode)
]
var outerNodeSpan = outerDictionaryNode.mutableSpan
state.currentTopCodingPathNode = outerNodeSpan.withUnsafeMutableBufferPointer {
$0.baseAddress!
}
defer {
withExtendedLifetime(outerNodeSpan) {
state.currentTopCodingPathNode.unwindToParent()
}
}
state.depth += 1
defer { state.depth -= 1 }
do {
// Parse opening brace
let openBrace = try state.reader.consumeWhitespaceAndPeek()
guard openBrace == ._openbrace else {
throw JSONError.unexpectedCharacter(context: "expecting enum object", ascii: openBrace, location: state.reader.sourceLocation)
}
state.reader.moveReaderIndex(forwardBy: 1)
// Parse the case name (key)
let openQuote = try state.reader.consumeWhitespaceAndPeek()
guard openQuote == ._quote else {
throw JSONError.unexpectedCharacter(context: "expecting enum case name", ascii: openQuote, location: state.reader.sourceLocation)
}
state.reader.moveReaderIndex(forwardBy: 1)
let caseName = try state.reader.parsedStringContentAndTrailingQuote()
// Update coding path with case name
state.currentTopCodingPathNode.pointee.setDictionaryKey(caseName.buffer)
var fieldDecoder = FieldDecoder(string: caseName)
// Parse colon
let colon = try state.reader.consumeWhitespaceAndPeek()
guard colon == ._colon else {
throw JSONError.unexpectedCharacter(context: "after enum case name", ascii: colon, location: state.reader.sourceLocation)
}
state.reader.moveReaderIndex(forwardBy: 1)
// Parse associated values dictionary - use midContainer: false so it handles the braces
let preValueOffset = state.reader.readOffset
var valueDecoder = try StructDecoder(parserState: state, midContainer: false)
let result = try closure(&fieldDecoder, &valueDecoder)
// Skip if not consumed, and finish the struct (consume closing brace)
if valueDecoder.parserState.reader.readOffset == preValueOffset {
try valueDecoder.parserState.skipValue()
} else {
try valueDecoder._finish()
}
state.copyRelevantState(from: valueDecoder.parserState)
// Parse closing brace of outer object
let next = try state.reader.consumeWhitespaceAndPeek()
let foundCloseBrace: Bool
switch next {
case ._comma:
state.reader.moveReaderIndex(forwardBy: 1)
foundCloseBrace = try state.reader.consumeWhitespaceAndPeek() == ._closebrace
case ._closebrace:
foundCloseBrace = true
default:
foundCloseBrace = false
}
guard foundCloseBrace else {
throw JSONError.unexpectedCharacter(context: "after enum object", ascii: next, location: state.reader.sourceLocation)
}
state.reader.moveReaderIndex(forwardBy: 1)
return result
} catch let error as JSONError {
throw error.at(self.codingPath)
} catch {
// TODO: Fix unsavory language workaround
throw error as! CodingError.Decoding
}
}
@usableFromInline
@_lifetime(self: copy self)
internal mutating func parseDictionaryBeginning() throws(JSONError) {
let byte = try state.reader.consumeWhitespaceAndPeek()
try state.reader.expectBeginningOfObject(byte)
state.reader.moveReaderIndex(forwardBy: 1) // Consume open brace.
}
@usableFromInline
@_lifetime(self: copy self)
internal mutating func prepareForDictKey(first: Bool) throws(JSONError) -> Bool {
let byte = try state.reader.consumeWhitespaceAndPeek()
switch (first, byte) {
case (_, ._closebrace):
state.reader.moveReaderIndex(forwardBy: 1) // Consume close brace.
return false
case (false, ._comma):
state.reader.moveReaderIndex(forwardBy: 1) // Consume comma.
let nextChar = try state.reader.consumeWhitespaceAndPeek()
try state.reader.expectBeginningOfObjectKey(nextChar)
fallthrough // to quote
case (true, ._quote):
state.reader.moveReaderIndex(forwardBy: 1) // Consume quote.
return true
default:
throw .unexpectedCharacter(context: "in object", ascii: byte, location: state.reader.sourceLocation)
}
}
@usableFromInline
@_lifetime(self: copy self)
internal mutating func prepareForDictValue() throws(JSONError) {
let colon = try state.reader.consumeWhitespaceAndPeek()
try state.reader.expectObjectKeyValueColon(colon)
state.reader.moveReaderIndex(forwardBy: 1) // consume colon
}
// TODO: See below on [Element] decoder for relevant comments.
@inlinable
@_lifetime(self: copy self)
public mutating func decode<Key: CodingStringKeyRepresentable, Value: JSONDecodable>(_: [Key:Value].Type, sizeHint: Int = 0) throws(CodingError.Decoding) -> [Key:Value] {
do {
try parseDictionaryBeginning()
guard try prepareForDictKey(first: true) else {
return [:]
}
var result = [Key:Value]()
if sizeHint > 0 {
result.reserveCapacity(sizeHint)
}
// TODO: Append to codingpath.
repeat {
let parsed = try state.reader.parsedStringContentAndTrailingQuote()
let key = switch parsed {
case .span(let span):
try Key.codingStringKeyVisitor.visitUTF8Bytes(span)
case .string(let string, _):
try Key.codingStringKeyVisitor.visitString(string)
}
try prepareForDictValue()
let value = try Value.decode(from: &self)
result[key] = value
} while try prepareForDictKey(first: false)
return result
} catch let error as JSONError {
throw error.at(self.codingPath)
} catch {
// TODO: Fix unsavory language workaround
throw (error as! CodingError.Decoding).addingIfNecessary(codingPath: self.codingPath)
}
}
@usableFromInline
@_lifetime(self: copy self)
internal mutating func parseArrayBeginning() throws(JSONError) {
let byte = try state.reader.consumeWhitespaceAndPeek()
try state.reader.expectBeginningOfArray(byte)
state.reader.moveReaderIndex(forwardBy: 1) // Consume open bracket.
}
// TODO: If we're tolerant of trailing comma, then what if we see [,]?
@usableFromInline
@_lifetime(self: copy self)
internal mutating func prepareForArrayElement(first: Bool, consumingCloseBracket: Bool = true) throws(JSONError) -> Bool {
let byte = try state.reader.consumeWhitespaceAndPeek()
switch (first, byte) {
case (_, ._closebracket):
if consumingCloseBracket {
state.reader.moveReaderIndex(forwardBy: 1) // Consume close bracket
}
return false
case (false, ._comma):
state.reader.moveReaderIndex(forwardBy: 1) // Consume comma
try state.reader.consumeWhitespaceAndPeek()
return true
case (true, _):
return true
default:
throw .unexpectedCharacter(context: "in array", ascii: byte, location: state.reader.sourceLocation)
}
}
@_lifetime(self: copy self)
internal mutating func finishArray() {
assert(state.reader.peek() == ._closebracket)
state.reader.moveReaderIndex(forwardBy: 1) // Consume close bracket
state.depth -= 1
}
@inlinable
@_lifetime(self: copy self)
public mutating func decode<Element: JSONDecodable>(_: [Element].Type, sizeHint: Int = 0) throws(CodingError.Decoding) -> [Element] {
do {
try parseArrayBeginning()
guard try prepareForArrayElement(first: true) else {
return []
}
var result = [Element]()
if sizeHint > 0 {
result.reserveCapacity(sizeHint)
}
var arrayNode: InlineArray = [
CodingPathNode.array(-1, parent: state.currentTopCodingPathNode)
]
var nodeSpan = arrayNode.mutableSpan
state.currentTopCodingPathNode = nodeSpan.withUnsafeMutableBufferPointer {
$0.baseAddress!
}
defer {
withExtendedLifetime(nodeSpan) {
state.currentTopCodingPathNode.unwindToParent()
}
}
repeat {
state.currentTopCodingPathNode.pointee.incrementArrayIndex()
let value = try Element.decode(from: &self)
result.append(value)
} while try prepareForArrayElement(first: false)
return result
} catch let error as JSONError {
throw error.at(self.codingPath)
} catch {
// TODO: Fix unsavory language workaround
throw error as! CodingError.Decoding
}
}
@inlinable
@_lifetime(self: copy self)
public mutating func decode<Element: JSONDecodableWithContext>(_: [Element].Type, context: inout Element.JSONDecodingContext, sizeHint: Int = 0) throws(CodingError.Decoding) -> [Element] {
do {
try parseArrayBeginning()
guard try prepareForArrayElement(first: true) else {
return []
}
var result = [Element]()
if sizeHint > 0 {
result.reserveCapacity(sizeHint)
}
var arrayNode: InlineArray = [
CodingPathNode.array(-1, parent: state.currentTopCodingPathNode)
]
var nodeSpan = arrayNode.mutableSpan
state.currentTopCodingPathNode = nodeSpan.withUnsafeMutableBufferPointer {
$0.baseAddress!
}
defer {
withExtendedLifetime(nodeSpan) {
state.currentTopCodingPathNode.unwindToParent()
}
}
repeat {
state.currentTopCodingPathNode.pointee.incrementArrayIndex()
let value = try Element.decode(from: &self, context: &context)
result.append(value)
} while try prepareForArrayElement(first: false)
return result
} catch let error as JSONError {
throw error.at(self.codingPath)
} catch {
// TODO: Fix unsavory language workaround
throw error as! CodingError.Decoding
}
}
@_lifetime(self: copy self)
public mutating func _finishDecode() throws(CodingError.Decoding) {
do throws(JSONError) {
if let nonWhitespace = try state.reader.consumeWhitespaceAndPeek(allowingEOF: true) {
throw JSONError.unexpectedCharacter(context: "after top-level values", ascii: nonWhitespace, location: state.reader.sourceLocation)
}
} catch {
throw error.at(.init([]))
}
}
}
extension JSONParserDecoder {
@_lifetime(self: copy self)
public mutating func decode(_: Bool.Type) throws(CodingError.Decoding) -> Bool {
do {
let byte = try state.reader.consumeWhitespaceAndPeek()
switch byte {
case UInt8(ascii: "f"), UInt8(ascii: "t"):
return try state.reader.readBool()
default:
throw state.reader.decodingError(expectedTypeDescription: "boolean", at: codingPath)
}
} catch let error as JSONError {
throw error.at(self.codingPath)
} catch {
// TODO: Fix unsavory language workaround
throw error as! CodingError.Decoding
}
}
@_lifetime(self: copy self)
public mutating func decode(_ hint: Int.Type) throws(CodingError.Decoding) -> Int {
do {
try state.reader.consumeWhitespaceAndPeek()
return try state.decode(hint)
} catch {
throw error.at(self.codingPath)
}
}
@_lifetime(self: copy self)
public mutating func decode(_ hint: Int8.Type) throws(CodingError.Decoding) -> Int8 {
do {
try state.reader.consumeWhitespaceAndPeek()
return try state.decode(hint)
} catch {
throw error.at(self.codingPath)
}
}
@_lifetime(self: copy self)
public mutating func decode(_ hint: Int16.Type) throws(CodingError.Decoding) -> Int16 {
do {
try state.reader.consumeWhitespaceAndPeek()
return try state.decode(hint)
} catch {
throw error.at(self.codingPath)
}
}
@_lifetime(self: copy self)
public mutating func decode(_ hint: Int32.Type) throws(CodingError.Decoding) -> Int32 {
do {
try state.reader.consumeWhitespaceAndPeek()
return try state.decode(hint)
} catch {
throw error.at(self.codingPath)
}
}
@_lifetime(self: copy self)
public mutating func decode(_ hint: Int64.Type) throws(CodingError.Decoding) -> Int64 {
do {
try state.reader.consumeWhitespaceAndPeek()
return try state.decode(hint)
} catch {
throw error.at(self.codingPath)
}
}
@_lifetime(self: copy self)
public mutating func decode(_ hint: UInt.Type) throws(CodingError.Decoding) -> UInt {
do {
try state.reader.consumeWhitespaceAndPeek()
return try state.decode(hint)
} catch {
throw error.at(self.codingPath)
}
}
@_lifetime(self: copy self)
public mutating func decode(_ hint: UInt8.Type) throws(CodingError.Decoding) -> UInt8 {
do {
try state.reader.consumeWhitespaceAndPeek()
return try state.decode(hint)
} catch {
throw error.at(self.codingPath)
}
}