-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpjson.cpp
More file actions
6075 lines (5780 loc) · 244 KB
/
Copy pathpjson.cpp
File metadata and controls
6075 lines (5780 loc) · 244 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 2025 ByteDance Ltd. and/or its affiliates. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//===----------------------------------------------------------------------===//
// Author: Praveen Babu J D
// License: Apache 2.0
//
#include "pjson.h"
#include <algorithm>
#include <cerrno>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <iomanip>
#include <istream>
#include <limits>
#include <locale>
#include <new>
#include <ostream>
#include <regex>
#include <set>
#include <sstream>
#include <stdexcept>
#include <type_traits>
#include <utility>
using namespace ByteDance;
//===----------------------------------------------------------------------===//
// pjsonImpl — all parsing, schema-validation, and encoding helpers.
//
// Keeping implementation-only operations in one friend struct leaves pjson.h
// declaration-focused while allowing these helpers to maintain DOM invariants.
//===----------------------------------------------------------------------===//
struct ByteDance::pjsonImpl {
// Public APIs deliberately hide the owning container representation.
typedef std::vector<pjson*> ArrayStorage;
typedef std::map<std::string, pjson*> ObjectStorage;
// Parser state threaded through the recursive-descent scanner: the input
// buffer, cursor, options, current/maximum nesting depth, a running count
// of allocated nodes (bounded by maxNodes to stop memory-amplification
// attacks), and the first error encountered (if any).
struct ParseCtx {
const char* src;
size_t pos;
size_t end;
pjson::ParseOptions::DuplicateKeyPolicy duplicateKeys;
int depth;
int maxDepth;
size_t nodeCount;
size_t maxNodes; // 0 = unlimited
pjson::Allocator* allocator;
bool failed;
size_t errPos;
std::string errMsg;
};
// One suspended container in the iterative serializer. Exactly one of
// array/object is active according to isObject; the associated cursor
// always denotes the next child to emit.
struct SerializeFrame {
bool isObject;
size_t depth;
bool first;
const ArrayStorage* array;
size_t arrayIndex;
const ObjectStorage* object;
ObjectStorage::const_iterator objectIt;
ObjectStorage::const_reverse_iterator objectReverseIt;
};
// One compiled schema regex or a cached policy/syntax rejection. Keeping
// failures in the cache is as important as caching successful compilation:
// patternProperties must not repeatedly parse an invalid expression.
struct RegexCacheEntry {
enum State { Uninitialized, Ready, PatternTooLarge, UnsafePattern, InvalidPattern };
State state;
std::regex expression;
RegexCacheEntry()
: state(Uninitialized) {}
};
// Mutable limits and recursion state shared by one schema-validation run.
// activeRefs tracks (instance, schema) pairs rather than schema nodes alone:
// revisiting a schema at a different instance is legitimate, while the same
// pair indicates a cyclic $ref evaluation.
struct SchemaValidationCtx {
const pjson& rootSchema;
const pjson::SchemaOptions& options;
std::vector<pjson::SchemaError>* publicErrors;
size_t depth;
size_t refResolutions;
size_t workUsed;
size_t errorsUsed;
size_t publicErrorStart;
bool aborted;
std::vector<std::pair<const pjson*, const pjson*>> activeRefs;
std::map<std::string, RegexCacheEntry> regexCache;
// Starts a validation run with no active recursion or resolved references.
SchemaValidationCtx(const pjson& aRootSchema, const pjson::SchemaOptions& aOptions,
std::vector<pjson::SchemaError>* aPublicErrors)
: rootSchema(aRootSchema)
, options(aOptions)
, publicErrors(aPublicErrors)
, depth(0)
, refResolutions(0)
, workUsed(0)
, errorsUsed(0)
, publicErrorStart(aPublicErrors == nullptr ? 0 : aPublicErrors->size())
, aborted(false) {}
};
struct SchemaBudgetExceeded {};
// Facade over a caller or speculative error vector that enforces one shared
// per-validation diagnostic budget without exposing a public container type.
struct SchemaErrorSink {
std::vector<pjson::SchemaError>& values;
SchemaValidationCtx& ctx;
bool reported;
size_t discardedFailures;
SchemaErrorSink(std::vector<pjson::SchemaError>& aValues, SchemaValidationCtx& aCtx,
bool aReported = true)
: values(aValues)
, ctx(aCtx)
, reported(aReported)
, discardedFailures(0) {}
size_t size() const { return reported ? values.size() : discardedFailures; }
void push_back(const pjson::SchemaError& error) {
if (ctx.aborted)
return;
if (!reported) {
// Speculative anyOf/oneOf/not branches need only a pass/fail
// signal. Retaining every hidden diagnostic would let an
// attacker amplify a compact schema into large scratch vectors.
(void)error;
if (discardedFailures != std::numeric_limits<size_t>::max())
++discardedFailures;
return;
}
const size_t limit = ctx.options.maxErrors == 0 ? size_t(100) : ctx.options.maxErrors;
if (ctx.errorsUsed >= limit) {
ctx.aborted = true;
if (ctx.publicErrors != nullptr &&
ctx.publicErrors->size() - ctx.publicErrorStart < limit) {
try {
ctx.publicErrors->push_back(pjson::SchemaError(
error.path, "schema validation error budget exceeded"));
} catch (...) {
// The validation result remains a safe failure even if
// the best-effort terminal diagnostic cannot allocate.
ctx.publicErrors = nullptr;
}
}
throw SchemaBudgetExceeded();
}
values.push_back(error);
++ctx.errorsUsed;
}
};
static bool _isWhitespace(char c);
static void _appendUtf8(uint32_t aCodePoint, std::string& aOut);
static bool _hex4(const char* aSrc, size_t aStart, uint32_t& aOut);
static int _utf8Len(const char* src, size_t pos, size_t end);
static std::string _formatDouble(double aValue);
static bool _parseDouble(const std::string& aText, double& aValue);
static bool _fail(ParseCtx& c, size_t aPos, const char* aMsg);
static pjson* _newNode(ParseCtx& c); // budget-checked allocation (nullptr on overflow)
static bool _peek(ParseCtx& c, char& aOut);
static bool _skipColon(ParseCtx& c);
static bool _parseValue(ParseCtx& c, pjson*& aOut);
static bool _parseString(ParseCtx& c, pjson*& aOut);
static bool _extractString(ParseCtx& c, std::string& aOut);
static bool _decodeStringBody(ParseCtx& c, std::string& aOut, bool bStopAtQuote);
static bool _parseKeyword(ParseCtx& c, pjson*& aOut);
static bool _parseNumber(ParseCtx& c, pjson*& aOut);
static bool _parseArray(ParseCtx& c, pjson*& aOut);
static bool _parseObject(ParseCtx& c, pjson*& aOut);
static pjson::unique_ptr _parseTop(const char* aSrc, size_t aSize,
const pjson::ParseOptions& aOpts, pjson::ParseError* aErr,
pjson::Allocator& aAlloc);
static pjson::unique_ptr _parseStream(std::istream& aIn, const pjson::ParseOptions& aOpts,
pjson::ParseError* aErr, pjson::Allocator& aAlloc);
template <typename Sink>
static bool _writeEscapedTo(Sink& aOut, const std::string& aIn, bool bEscapeNonAscii);
template <typename Sink>
static bool _openOrEmit(Sink& aOut, const pjson* aValue, size_t aDepth,
const pjson::SerializeOptions& aOpts,
std::vector<SerializeFrame>& aFrames);
template <typename Sink>
static bool _writeValueTo(Sink& aOut, const pjson& aValue,
const pjson::SerializeOptions& aOpts);
static void _appendValue(std::string& aOut, const pjson& aValue,
const pjson::SerializeOptions& aOpts);
static bool _writeValue(std::ostream& aOut, const pjson& aValue,
const pjson::SerializeOptions& aOpts);
static bool _parseSaxTop(const char* aSrc, size_t aSize, pjson::SaxHandler& aHandler,
const pjson::ParseOptions& aOpts, pjson::ParseError* aErr);
static bool _parseSaxStream(std::istream& aIn, pjson::SaxHandler& aHandler,
const pjson::ParseOptions& aOpts, pjson::ParseError* aErr);
static std::string _pointerAppend(const std::string& aBase, const std::string& aToken);
static bool _validateCtx(const pjson& aNode, const pjson& aSchema, const std::string& aPath,
SchemaErrorSink& aErrors, SchemaValidationCtx& aCtx);
static bool _validate(const pjson& aNode, const pjson& aSchema, const std::string& aPath,
std::vector<pjson::SchemaError>& aErrors,
const pjson::SchemaOptions& aOpts) noexcept;
static bool _typeMatches(const pjson& aNode, const std::string& aTypeName);
static std::string _typeName(const pjson& aNode);
static bool _isSafeRegex(const std::string& aPattern);
// Internal typed/storage access keeps representation and permissive
// conversion helpers out of the public API. Callers first establish type.
static ArrayStorage& _array(pjson& aValue) { return *aValue._uValue._pValueArray; }
static const ArrayStorage& _array(const pjson& aValue) { return *aValue._uValue._pValueArray; }
static ObjectStorage& _object(pjson& aValue) { return *aValue._uValue._pValueMap; }
static const ObjectStorage& _object(const pjson& aValue) { return *aValue._uValue._pValueMap; }
static int64_t _integer(const pjson& aValue) { return aValue._uValue._valueInt; }
static double _floating(const pjson& aValue) { return aValue._uValue._valueDouble; }
static double _numberAsDouble(const pjson& aValue) {
return aValue._eType == pjson::jsonNumberInt ? static_cast<double>(aValue._uValue._valueInt)
: aValue._uValue._valueDouble;
}
static bool _boolean(const pjson& aValue) { return aValue._uValue._valueBool; }
static const std::string& _string(const pjson& aValue) { return *aValue._uValue._pValueString; }
// Returns -1, 0, or 1, and 2 when either floating operand is NaN.
static int _compareNumbers(const pjson& aLeft, const pjson& aRight);
static bool _equalWithBudget(const pjson& aLeft, const pjson& aRight, SchemaValidationCtx& aCtx,
SchemaErrorSink& aErrors, const std::string& aPath, bool& aEqual);
// Iteratively frees every descendant pjson of node's array/map, leaving the
// node's own top-level container allocated but empty (a no-op for scalars).
// Using an explicit work-list instead of the recursive destructor keeps
// teardown safe on arbitrarily deep documents. Marked noexcept: it is
// reached from ~pjson, so an allocation failure here terminates rather than
// escaping a destructor.
static void _disposeChildren(pjson& node) noexcept;
static pjson::Allocator& _defaultAllocator() noexcept;
static pjson* _allocateNode(pjson::Allocator& aAlloc);
static void _destroyNode(pjson* aValue) noexcept;
static pjson::unique_ptr _makeNode(pjson::Allocator& aAlloc);
static pjson::unique_ptr _cloneNode(const pjson& aValue, pjson::Allocator& aAlloc);
};
// File-scope aliases keep internal type names concise without exposing the
// owning containers in the public header.
typedef pjson::jsonType jsonType;
typedef pjsonImpl::ArrayStorage PJSONARRAY;
typedef pjsonImpl::ObjectStorage PJSONMAP;
typedef pjson::SchemaError SchemaError;
typedef pjson::SchemaOptions SchemaOptions;
typedef pjson::ParseOptions ParseOptions;
typedef pjson::ParseError ParseError;
typedef pjson::SaxHandler SaxHandler;
typedef pjsonImpl::ParseCtx ParseCtx;
// Schema validation still uses native recursion for applicator keywords. Keep
// its logical depth below a conservative stack-safe ceiling even when callers
// request a larger value. Consecutive local references are resolved iteratively
// but continue to consume this same logical-depth budget.
static const size_t kSchemaValidationDepthHardLimit = 64;
namespace {
//===------------------------------------------------------------------===//
// Parse diagnostics and SAX cursor adapters
//===------------------------------------------------------------------===//
// Converts a zero-based byte offset into one-based source coordinates. CRLF
// counts as one line ending; a lone CR or LF also starts a new line.
void lineAndColumn(const char* src, size_t size, size_t offset, size_t& line, size_t& column) {
line = 1;
column = 1;
const size_t end = offset < size ? offset : size;
for (size_t i = 0; i < end; ++i) {
if (src[i] == '\r') {
if (i + 1 < end && src[i + 1] == '\n')
++i;
++line;
column = 1;
} else if (src[i] == '\n') {
++line;
column = 1;
} else {
++column;
}
}
}
// Publishes a buffer-parser failure, deriving source coordinates from the
// authoritative byte offset. A null destination intentionally discards it.
void setParseError(ParseError* err, const char* src, size_t size, size_t offset,
const std::string& message) {
if (!err)
return;
err->ok = false;
err->offset = offset;
lineAndColumn(src, size, offset, err->line, err->column);
err->message = message;
}
// Restores the public error object to its successful, start-of-input state.
void resetParseError(ParseError* err) {
if (!err)
return;
err->ok = true;
err->offset = 0;
err->line = 1;
err->column = 1;
err->message.clear();
}
// Internal control-flow exception used to unwind immediately when a SAX
// callback returns false; parseDocument converts it back into ParseError.
class SaxParseCancelled : public std::exception {
public:
// Supplies a stable diagnostic if cancellation escapes an internal frame.
const char* what() const noexcept override { return "SAX parse aborted"; }
};
// Non-owning cursor over a contiguous input buffer. Positions are byte
// offsets, while line/column values are maintained incrementally.
class BufferSaxCursor {
public:
// Binds the cursor to caller-owned bytes, which must outlive parsing.
BufferSaxCursor(const char* src, size_t size)
: _src(src)
, _size(size)
, _pos(0)
, _line(1)
, _column(1)
, _prevWasCR(false) {}
// Observes the next byte without advancing source coordinates.
bool peek(char& ch) {
if (_pos >= _size)
return false;
ch = _src[_pos];
return true;
}
// Consumes one byte and advances CR/LF-aware source coordinates.
bool get(char& ch) {
if (!peek(ch))
return false;
advance(ch);
++_pos;
return true;
}
// Reports whether every byte in the fixed buffer has been consumed.
bool eof() const { return _pos >= _size; }
// A memory cursor cannot suffer an I/O failure.
bool failed() const { return false; }
// Returns the zero-based byte offset of the next input byte.
size_t position() const { return _pos; }
// Returns the one-based line containing the next input byte.
size_t line() const { return _line; }
// Returns the one-based column containing the next input byte.
size_t column() const { return _column; }
private:
// Counts CRLF as one newline even though its bytes arrive separately.
void advance(char ch) {
if (ch == '\r') {
++_line;
_column = 1;
_prevWasCR = true;
} else if (ch == '\n') {
if (_prevWasCR) {
_prevWasCR = false;
} else {
++_line;
_column = 1;
}
} else {
++_column;
_prevWasCR = false;
}
}
const char* _src;
size_t _size;
size_t _pos;
size_t _line;
size_t _column;
bool _prevWasCR;
};
// Buffered cursor that gives the SAX parser the same interface for streams
// without first materializing the complete input.
class StreamSaxCursor {
public:
// Binds to a caller-owned stream and delays reads until bytes are needed.
explicit StreamSaxCursor(std::istream& in)
: _in(in)
, _used(0)
, _posInBuf(0)
, _pos(0)
, _line(1)
, _column(1)
, _prevWasCR(false)
, _failed(false)
, _eof(false) {}
// Observes the next buffered byte, refilling on demand.
bool peek(char& ch) {
if (!ensure())
return false;
ch = _buffer[_posInBuf];
return true;
}
// Consumes one byte while maintaining absolute and source positions.
bool get(char& ch) {
if (!ensure())
return false;
ch = _buffer[_posInBuf++];
if (ch == '\r') {
++_line;
_column = 1;
_prevWasCR = true;
} else if (ch == '\n') {
if (_prevWasCR) {
_prevWasCR = false;
} else {
++_line;
_column = 1;
}
} else {
++_column;
_prevWasCR = false;
}
++_pos;
return true;
}
// Reports EOF only after both the stream and the refill buffer are empty.
bool eof() const { return _eof && _posInBuf >= _used; }
// Distinguishes an I/O failure from an ordinary end of stream.
bool failed() const { return _failed; }
// Returns the number of bytes consumed across all refills.
size_t position() const { return _pos; }
// Returns the one-based line containing the next input byte.
size_t line() const { return _line; }
// Returns the one-based column containing the next input byte.
size_t column() const { return _column; }
private:
// Makes one byte available unless EOF or an unrecoverable read failure
// has already been observed. Short reads with data are still usable.
bool ensure() {
if (_posInBuf < _used)
return true;
if (_eof || _failed)
return false;
// Pull directly from streambuf so a source that intentionally
// exposes one short chunk at a time is not mistaken for EOF by
// istream::read's exact-count semantics. One byte is sufficient for
// the parser; the streambuf retains any remaining get-area bytes.
std::streambuf* buffer = _in.rdbuf();
if (buffer == nullptr || _in.bad()) {
_failed = true;
return false;
}
const std::streambuf::int_type next = buffer->sbumpc();
if (!std::streambuf::traits_type::eq_int_type(next,
std::streambuf::traits_type::eof())) {
_buffer[0] = std::streambuf::traits_type::to_char_type(next);
_used = 1;
_posInBuf = 0;
return true;
}
if (_in.bad()) {
_failed = true;
return false;
}
_eof = true;
return false;
}
std::istream& _in;
char _buffer[8192];
size_t _used;
size_t _posInBuf;
size_t _pos;
size_t _line;
size_t _column;
bool _prevWasCR;
bool _failed;
bool _eof;
};
// Recursive-descent event parser shared by buffer and stream cursors. It
// applies the same grammar, resource budgets, and duplicate-key policy as
// DOM parsing, but can suppress callbacks for KeepFirstDuplicate values.
template <typename Cursor> struct SaxParser {
Cursor& cur;
SaxHandler& handler;
const ParseOptions& opts;
ParseError* err;
size_t nodeCount;
// Couples a cursor and event sink for one parse, with fresh node accounting.
SaxParser(Cursor& aCur, SaxHandler& aHandler, const ParseOptions& aOpts, ParseError* aErr)
: cur(aCur)
, handler(aHandler)
, opts(aOpts)
, err(aErr)
, nodeCount(0) {}
// Parses exactly one complete document, translating parser, handler,
// allocation, and stream failures into a stable non-throwing result.
bool parseDocument() noexcept {
try {
resetParseError(err);
if (!parseValue(0, true))
return false;
if (!skipWhitespace())
return false;
char ch = 0;
if (opts.maxInputBytes != 0 && cur.position() >= opts.maxInputBytes) {
if (cur.peek(ch))
return failAt(opts.maxInputBytes, cur.line(), cur.column(),
"input exceeds maxInputBytes");
} else if (cur.peek(ch)) {
return fail("trailing characters after JSON value");
}
if (cur.failed())
return fail("stream read failed");
return true;
} catch (const SaxParseCancelled&) {
return failNoThrow("SAX parse aborted");
} catch (const std::bad_alloc&) {
return failNoThrow("SAX parse ran out of memory");
} catch (const std::exception&) {
return failNoThrow("SAX parse or handler exception");
} catch (...) {
return failNoThrow("SAX parse or handler exception");
}
}
// Dispatches one value at the current nesting depth. emit=false still
// validates and counts the subtree but deliberately skips callbacks.
bool parseValue(size_t depth, bool emit) {
if (!skipWhitespace())
return false;
char ch = 0;
if (!cur.peek(ch)) {
if (cur.failed())
return fail("stream read failed");
return fail("unexpected end of input; expected a value");
}
if (ch == '"')
return parseStringValue(emit);
if (ch == '{')
return parseObject(depth + 1, emit);
if (ch == '[')
return parseArray(depth + 1, emit);
if (ch == '-' || (ch >= '0' && ch <= '9'))
return parseNumberValue(emit);
return parseKeywordValue(emit);
}
// Consumes only the four whitespace bytes admitted by JSON.
bool skipWhitespace() {
char ch = 0;
while (cur.peek(ch) && pjsonImpl::_isWhitespace(ch)) {
if (!getChar(ch))
return false;
}
if (cur.failed())
return fail("stream read failed");
return true;
}
// Parses a string value and emits it after it has consumed one node from
// the configured budget. Object keys are handled separately.
bool parseStringValue(bool emit) {
if (!reserveNode())
return false;
std::string value;
if (!parseStringRaw(value))
return false;
if (!emit)
return true;
return dispatch(handler.onString(value));
}
// Recognizes the lowercase null/boolean literals required by RFC 8259.
bool parseKeywordValue(bool emit) {
char ch = 0;
if (!cur.peek(ch))
return fail("unexpected end of input; expected a value");
if (ch == 'n') {
if (!matchLiteral("null"))
return false;
if (!reserveNode())
return false;
return !emit || dispatch(handler.onNull());
}
if (ch == 't') {
if (!matchLiteral("true"))
return false;
if (!reserveNode())
return false;
return !emit || dispatch(handler.onBool(true));
}
if (ch == 'f') {
if (!matchLiteral("false"))
return false;
if (!reserveNode())
return false;
return !emit || dispatch(handler.onBool(false));
}
return fail("invalid JSON value");
}
// Scans the JSON number grammar before conversion. Integral tokens that
// overflow int64 are preserved as finite doubles rather than truncated.
bool parseNumberValue(bool emit) {
std::string text;
char ch = 0;
if (!cur.peek(ch))
return fail("unexpected end of input; expected a value");
if (ch == '-') {
if (!getChar(ch))
return false;
text.push_back(ch);
if (!cur.peek(ch))
return fail("invalid number: expected digit");
}
if (ch == '0') {
if (!getChar(ch))
return false;
text.push_back(ch);
} else if (ch >= '1' && ch <= '9') {
do {
if (!getChar(ch))
return false;
text.push_back(ch);
} while (cur.peek(ch) && ch >= '0' && ch <= '9');
} else {
return fail("invalid number: expected digit");
}
bool isFloat = false;
if (cur.peek(ch) && ch == '.') {
isFloat = true;
if (!getChar(ch))
return false;
text.push_back(ch);
if (!cur.peek(ch) || ch < '0' || ch > '9')
return fail("invalid number: '.' must be followed by a digit");
do {
if (!getChar(ch))
return false;
text.push_back(ch);
} while (cur.peek(ch) && ch >= '0' && ch <= '9');
}
if (cur.peek(ch) && (ch == 'e' || ch == 'E')) {
isFloat = true;
if (!getChar(ch))
return false;
text.push_back(ch);
if (cur.peek(ch) && (ch == '+' || ch == '-')) {
if (!getChar(ch))
return false;
text.push_back(ch);
}
if (!cur.peek(ch) || ch < '0' || ch > '9')
return fail("invalid number: exponent must have a digit");
do {
if (!getChar(ch))
return false;
text.push_back(ch);
} while (cur.peek(ch) && ch >= '0' && ch <= '9');
}
if (!reserveNode())
return false;
if (isFloat) {
double d = 0.0;
if (!pjsonImpl::_parseDouble(text, d) || !std::isfinite(d))
return fail("number out of range");
return !emit || dispatch(handler.onDouble(d));
}
errno = 0;
const long long llVal = strtoll(text.c_str(), nullptr, 10);
if (errno == ERANGE) {
double d = 0.0;
if (!pjsonImpl::_parseDouble(text, d) || !std::isfinite(d))
return fail("number out of range");
return !emit || dispatch(handler.onDouble(d));
}
return !emit || dispatch(handler.onInt(static_cast<int64_t>(llVal)));
}
// Parses an array while explicitly tracking comma state so leading,
// repeated, missing, and trailing commas receive deterministic errors.
bool parseArray(size_t depth, bool emit) {
const size_t maxDepth = opts.maxDepth > 0 ? static_cast<size_t>(opts.maxDepth) : 1U;
if (depth > maxDepth)
return fail("maximum nesting depth exceeded");
if (!reserveNode())
return false;
char ch = 0;
if (!getChar(ch) || ch != '[')
return fail("unexpected end of input; expected a value");
if (emit && !dispatch(handler.onStartArray()))
return false;
bool expectValue = false;
bool any = false;
while (true) {
if (!skipWhitespace())
return false;
if (!cur.peek(ch)) {
if (cur.failed())
return fail("stream read failed");
return fail("unterminated array");
}
if (ch == ']') {
if (expectValue)
return fail("trailing comma in array");
if (!getChar(ch))
return false;
return !emit || dispatch(handler.onEndArray());
}
if (ch == ',') {
if (!any || expectValue)
return fail("unexpected ',' in array");
if (!getChar(ch))
return false;
expectValue = true;
continue;
}
if (any && !expectValue)
return fail("missing ',' between array elements");
if (!parseValue(depth, emit))
return false;
any = true;
expectValue = false;
}
}
// Parses an object and implements duplicate-key policy at event time.
// KeepFirst parses duplicate values with emit=false so malformed input
// and resource-limit violations cannot hide inside discarded members.
bool parseObject(size_t depth, bool emit) {
const size_t maxDepth = opts.maxDepth > 0 ? static_cast<size_t>(opts.maxDepth) : 1U;
if (depth > maxDepth)
return fail("maximum nesting depth exceeded");
if (!reserveNode())
return false;
char ch = 0;
if (!getChar(ch) || ch != '{')
return fail("unexpected end of input; expected a value");
if (emit && !dispatch(handler.onStartObject()))
return false;
bool expectMember = false;
bool any = false;
std::map<std::string, bool> seenKeys;
while (true) {
if (!skipWhitespace())
return false;
if (!cur.peek(ch)) {
if (cur.failed())
return fail("stream read failed");
return fail("unterminated object");
}
if (ch == '}') {
if (expectMember)
return fail("trailing comma in object");
if (!getChar(ch))
return false;
return !emit || dispatch(handler.onEndObject());
}
if (ch == ',') {
if (!any || expectMember)
return fail("unexpected ',' in object");
if (!getChar(ch))
return false;
expectMember = true;
continue;
}
if (ch != '"')
return fail("expected '\"' to start an object key");
if (any && !expectMember)
return fail("missing ',' between object members");
const size_t keyOffset = cur.position();
const size_t keyLine = cur.line();
const size_t keyColumn = cur.column();
std::string key;
if (!parseStringRaw(key))
return false;
if (!skipWhitespace())
return false;
if (!getChar(ch) || ch != ':')
return fail("expected ':' after object key");
bool duplicate = false;
if (opts.duplicateKeys != ParseOptions::KeepLastDuplicate) {
duplicate = seenKeys.find(key) != seenKeys.end();
}
if (duplicate && opts.duplicateKeys == ParseOptions::RejectDuplicateKeys) {
return failAt(keyOffset, keyLine, keyColumn, "duplicate object key");
}
if (!duplicate && opts.duplicateKeys != ParseOptions::KeepLastDuplicate)
seenKeys[key] = true;
const bool emitValue =
emit && !(duplicate && opts.duplicateKeys == ParseOptions::KeepFirstDuplicate);
if (emitValue && !dispatch(handler.onKey(key)))
return false;
if (!parseValue(depth, emitValue))
return false;
any = true;
expectMember = false;
}
}
// Decodes a quoted JSON string and rejects invalid Unicode/control bytes.
bool parseStringRaw(std::string& out) {
char ch = 0;
if (!getChar(ch) || ch != '"')
return fail("expected '\"' to start a string");
out.clear();
while (true) {
if (!getChar(ch)) {
if (cur.failed())
return fail("stream read failed");
return fail("unterminated string");
}
const unsigned char uch = static_cast<unsigned char>(ch);
if (ch == '"')
return true;
if (ch == '\\') {
if (!getChar(ch))
return fail("dangling escape at end of input");
switch (ch) {
case '"':
out += '"';
break;
case '\\':
out += '\\';
break;
case '/':
out += '/';
break;
case 'b':
out += '\b';
break;
case 'f':
out += '\f';
break;
case 'n':
out += '\n';
break;
case 'r':
out += '\r';
break;
case 't':
out += '\t';
break;
case 'u': {
uint32_t cp = 0;
if (!readHex4(cp))
return false;
if (cp >= 0xD800 && cp <= 0xDBFF) {
char slash = 0;
if (cur.peek(slash) && slash == '\\') {
if (!getChar(slash))
return fail("invalid \\u escape");
char u = 0;
if (!getChar(u))
return fail("invalid \\u escape");
if (u == 'u') {
std::string hex;
hex.reserve(4);
bool complete = true;
for (int i = 0; i < 4; ++i) {
char hx = 0;
if (!getChar(hx)) {
complete = false;
break;
}
hex.push_back(hx);
}
uint32_t low = 0;
const bool validLow =
complete && hex.size() == 4 &&
pjsonImpl::_hex4(hex.c_str(), 0, low) &&
low >= 0xDC00 && low <= 0xDFFF;
if (validLow) {
cp = 0x10000 + ((cp - 0xD800) << 10) + (low - 0xDC00);
} else {
return fail("unpaired high surrogate");
}
} else {
return fail("unpaired high surrogate");
}
} else {
return fail("unpaired high surrogate");
}
} else if (cp >= 0xDC00 && cp <= 0xDFFF) {
return fail("unpaired low surrogate");
}
pjsonImpl::_appendUtf8(cp, out);
break;
}
default:
return fail("invalid escape sequence");
}
continue;
}
if (uch < 0x20) {
return fail("unescaped control character in string");
}
if (uch >= 0x80) {
out += static_cast<char>(uch);
if (!consumeUtf8Tail(uch, out))
return false;
continue;
}
out += static_cast<char>(uch);
}
}
// Consumes and validates the continuation bytes for an already-stored
// UTF-8 lead byte, including overlong, surrogate, and range checks.
bool consumeUtf8Tail(unsigned char lead, std::string& out) {
int need = 0;
uint32_t code = 0;
if ((lead & 0xE0U) == 0xC0U) {
need = 1;
code = lead & 0x1FU;
} else if ((lead & 0xF0U) == 0xE0U) {
need = 2;
code = lead & 0x0FU;
} else if ((lead & 0xF8U) == 0xF0U) {
need = 3;
code = lead & 0x07U;
} else {
return fail("invalid UTF-8 sequence");
}
for (int i = 0; i < need; ++i) {
char ch = 0;
if (!getChar(ch))
return fail("invalid UTF-8 sequence");
const unsigned char byte = static_cast<unsigned char>(ch);
if ((byte & 0xC0U) != 0x80U)
return fail("invalid UTF-8 sequence");
code = (code << 6) | (byte & 0x3FU);
out += ch;
}
if ((need == 1 && code < 0x80U) || (need == 2 && code < 0x800U) ||
(need == 3 && code < 0x10000U) || code > 0x10FFFFU ||
(code >= 0xD800U && code <= 0xDFFFU)) {
return fail("invalid UTF-8 sequence");
}
return true;
}
// Reads exactly four hexadecimal digits following a \u escape.