Repository navigation
Conversation
The return value of json_sax::parse_error() was documented both as "must return false" and as "whether the parsing should continue", and the code just passed it on. For JSON text, parsing stopped anyway, but sax_parse() could report success for invalid input. The binary readers read on after the error, looping forever on a CBOR indefinite-length array without its end. Now false stops parsing, and true recovers from the error: - JSON text is repaired with the smallest local edit (insert a missing ',' or ':', remove a stray token, keep the readable part of a broken string or number, null for a value that cannot be read, close the innermost container at a wrong closing bracket and all of them at the end of the input), and parsing continues. The SAX events stay balanced, every key is followed by exactly one value, and each token is reported at most once. - The binary formats cannot resynchronize, so they stop, but complete the value read so far. sax_parse() returns false after any error. parse(), accept(), and the from_*() functions never recover and compile to the same code as before. Supersedes #4522. Signed-off-by: Niels Lohmann <mail@nlohmann.me>
…989-db7e45 Signed-off-by: Niels Lohmann <mail@nlohmann.me>
…ue (#3989) When the SAX parser asks to recover, the binary readers now repair an item whose end is known and read on after it, as RFC 8949, Section 5.3 describes for CBOR: - CBOR: tags are ignored, and simple values other than false, true, and null become null (RFC 8949, Section 6.1); a negative integer below the range of number_integer_t becomes the nearest floating-point number. - Strings that are not valid UTF-8 get U+FFFD for each ill-formed sequence, as in JSON text; so does a UBJSON/BJData char above 0x7F. - UBJSON/BJData high-precision numbers keep their longest valid beginning (via the lexer's recover_token()), or become infinity. - Members whose key is not a string are skipped (CBOR, MessagePack, BON8), like members without a key in JSON text. - BSON elements of types the library does not read (ObjectId, datetime, decimal128, ...) become null; a string without its terminator and a document whose size does not match are kept. Where the end of an item is unknown, reading stops as before, except that BSON skips to the end of the document, whose size it knows. The value read before such an error is now completed by the reader from its container stack, as the JSON parser does, instead of by a proxy SAX parser, which is removed. Like the parser, binary_reader gets an AllowRecovery template parameter, so that from_*() compile without the new code. Tests: a table of repairs, numbers out of range, errors that stop, and a sweep over changed and removed bytes of eight encodings that checks balanced events and that the first error is the one from_*() reports. All fuzzers now run a recovering checker; the binary ones also check that it reports an error exactly when from_*() fails. Signed-off-by: Niels Lohmann <mail@nlohmann.me>
recover_number() used back(), pop_back(), front(), and find_first_of(const char*), which the minimal alt_string of unit-alt-string.cpp does not provide. Since the binary readers recover UBJSON/BJData high-precision numbers with it, from_ubjson() instantiated it, too, and the test no longer compiled. It now uses only size(), operator[], and resize(), and unit-alt-string.cpp recovers from errors in JSON text, UBJSON, and CBOR. Signed-off-by: Niels Lohmann <mail@nlohmann.me>
…989-db7e45 Signed-off-by: Niels Lohmann <mail@nlohmann.me> # Conflicts: # include/nlohmann/detail/input/binary_reader.hpp # single_include/nlohmann/json.hpp
Moving the report of an unsupported BSON element type into skip_unsupported_bson_element() moved its snprintf() call, which Flawfinder then reported as a new CWE-134 finding. The two hexadecimal digits are now computed directly; the message is unchanged. Signed-off-by: Niels Lohmann <mail@nlohmann.me>
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
MSVC stringizes the arguments of doctest's CHECK() so that a raw string literal becomes an ordinary one, and then reported the "\q" in the new alt_string recovery test as warning C4129, an error with /WX. The input is now a variable. The same pattern with "\u0000" in the parser's recovery test is replaced by a JSON value built from a std::string. Signed-off-by: Niels Lohmann <mail@nlohmann.me>
…to claude/fix-issue-3989-db7e45 Signed-off-by: Niels Lohmann <mail@nlohmann.me>
The U+FFFD constant was a global std::string, which the clang CI build rejects with -Wglobal-constructors. It is now a function. Signed-off-by: Niels Lohmann <mail@nlohmann.me>
ci_clang_tidy flagged nested conditional operators in the BON8 skip code and in remove_incomplete_utf8_sequence() (readability-avoid-nested-conditional-operator), and two branches with the same body in recover_string() (bugprone-branch-clone). Use if chains instead of the nested conditionals and merge the two branches into one condition; the short-circuit order is unchanged. ci_test_noexceptions aborted in the #3989 regression test: it compares the first recovered error with the message of the exception that from_cbor() and friends throw, and under JSON_NOEXCEPTION that call aborts instead of throwing. Guard binary_error_message() and its uses with #if !defined(JSON_NOEXCEPTION), as other tests in the suite do. Signed-off-by: Niels Lohmann <mail@nlohmann.me>
|
Fixed the two red jobs of run 36536773620 in 792853d: ci_static_analysis_clang (ci_clang_tidy): clang-tidy reported four errors in code added by this PR:
ci_cmake_options (ci_test_noexceptions): Verification: local clang-tidy on — posted by Claude Code on behalf of @nlohmann |
clang-tidy's bugprone-derived-method-shadowing-base-method rejected the test SAX parsers that derive from json_sax_dom_parser (or the test's SaxEventLogger) and redefine their non-virtual event functions. The recovering DOM parsers of unit-class_parser.cpp and unit-regression2.cpp now hold a json_sax_dom_parser and forward to it, SaxEventLogger gets a flag to recover from errors instead of a derived class, and the one function unit-alt-string.cpp redefines is marked as intended. Signed-off-by: Niels Lohmann <mail@nlohmann.me>
…arse() json_sax_dom_callback_parser and json_sax_dom_parser branches of parser::parse() ran the same ~25 lines after sax_parse_internal(): the strict-mode EOF check (raising parse_error.101 through the SAX parser), release_lookahead() in non-strict mode, and mapping an errored SAX parser to a discarded result. The two copies had already drifted apart in formatting and in the second copy's "see above" comment. Add a private parse_dom(DomSax&, strict) member that runs this shared sequence once and returns whether the SAX parser did not error; both branches of parse() now only construct their DOM SAX parser, call parse_dom(), and (for the callback parser) map a discarded top-level value to null. sax_parse() is left untouched, since it only runs the EOF check and release_lookahead() when sax_parse_internal() succeeded, unlike parse(), which runs them unconditionally. Behavior-preserving: same operations in the same order for both SAX parser kinds. Verified with unit-class_parser (strict/non-strict, callback and non-callback), unit-deserialization and unit-disabled_exceptions (JSON_NOEXCEPTION), plus a clean make amalgamate / make check-amalgamation diff. Overlaps #5601, which touches the same lines. Signed-off-by: Niels Lohmann <mail@nlohmann.me> #5712 item 2
tests/src/round_trip_corpus.hpp exists so that the byte-stability invariant the fuzzer drivers check also runs on a fixed corpus in CI, instead of only at OSS-Fuzz. So far only the UBJSON and BJData drivers had a matching unit test; the CBOR, MessagePack, BSON and BON8 drivers assert the same invariant (assert(to_X(j2) == vec)) but nothing ran it outside OSS-Fuzz. Add "<FORMAT> round-trip invariants" test cases to unit-cbor.cpp, unit-msgpack.cpp, unit-bson.cpp and unit-bon8.cpp, modeled on the UBJSON case: seed j1 from the corpus (skipping values that do not survive the format's own round trip, as the fuzzer drivers only ever see values from_X() actually produced), then require from_X(to_X(j1)) not to throw and check to_X(j2) == to_X(j1). BSON only serializes objects, so non-object corpus values are skipped. Update the comments in round_trip_corpus.hpp and tests/fuzzing.md to name all six formats. The stream-versus-contiguous check in the BON8 driver is left out, as #5601 reworks it. A local probe confirms no violations on the current corpus (CBOR 3849 checked, MessagePack 3909, BSON 2958, BON8 3841 - matching the counts already recorded for this probe in the issue). Closes #5714 item 1. Signed-off-by: Niels Lohmann <mail@nlohmann.me>
The header comment of six of the seven binary-format fuzzer drivers listed an invariant the code does not check: CBOR, MessagePack, BSON and BON8 said "assert(j1 == j2)", but the code checks byte stability, assert(to_X(j2) == vec). UBJSON and BJData still described the old "assert(j1 == j2/j3/j4)" byte-exact check from before PR #5494 replaced it with a use_size/use_type-aware round trip (UBJSON) and a value-stability check (BJData); BJData's added paragraph already explained the new check, but the step list above it did not. Also remove a dead branch in fuzzer-parse_bson.cpp: from_bson() is called with allow_exceptions = true, so it throws instead of returning a discarded value, and the "if (j1.is_discarded()) return 0;" guard could never trigger. Drop the unused <iostream> include from all seven drivers and <sstream> from all but fuzzer-parse_bon8.cpp, which is the only one that uses std::istringstream. Overlaps #5601, which edits all seven drivers in the same hunks. Closes #5714 item 4. Signed-off-by: Niels Lohmann <mail@nlohmann.me>
parse_cbor_internal() hand-wrote the same "read a 1/2/4/8-byte big-endian unsigned integer" ladder four times over: - twice for tag numbers 0xD8-0xDB, once in the tag_handler::ignore branch and once, nearly identically, in the ::store branch (~90 lines to read one integer); - twice more for container lengths, once for array heads 0x98-0x9B and once for map heads 0xB8-0xBB, where the 1/2-byte forms called enter_array()/enter_object() directly and the 4/8-byte forms additionally went through get_cbor_container_size(). Add get_cbor_argument(std::uint64_t&), reading the width selected by current & 0x1F via the same get_number() calls as before (so EOF is reported exactly as before), and route all four sites through it: - 0xD8-0xDB now read the argument once per branch instead of switching on `current` a second time; behavior split cleanly from embedded tags 0xC0-0xD7 (tag value in the head, no argument to read), which is now its own case block that no longer has to fall into the ::store switch's "default" case to reach the same tag_pending = true; return true; outcome. - 0x98-0x9B and 0xB8-0xBB collapse into one case block each, always going through get_cbor_container_size() (harmless for 1/2-byte lengths, which already always fit). Verified byte-for-byte identical behavior before/after with a standalone probe covering embedded and multi-byte tags under all three tag_handler_t settings, a tag over a byte string (subtype path), truncated tag/length arguments of every width, and array/map lengths of every width, including the out_of_range.408 "excessive size" case: same exceptions, same messages, same chars_read, same successful results. Left the string/byte-string length ladders in get_cbor_string()/ get_cbor_binary() untouched, as noted in #5711 item 2, since #5325 is expected to touch them separately. Overlaps #5601 (adds a branch right above the embedded-tag case) and #5607 (touches the integer cases 0x18-0x1B, which share this ladder's shape in separate hunks). #5711 item 2 Signed-off-by: Niels Lohmann <mail@nlohmann.me>
…5731) * Share the diagnostic-position setter of the DOM SAX parsers json_sax_dom_parser and json_sax_dom_callback_parser each had a private copy of handle_diagnostic_positions_for_json_value(), identical except for comments. Move the body into one static member function, detail::diagnostic_positions::set_from_lexer(value, lexer), which both classes call with their lexer pointer. basic_json befriends the new struct (only when JSON_DIAGNOSTIC_POSITIONS is enabled), as the position members are private. The discarded case is reached through the callback parser, so the LCOV_EXCL markers that only the dom parser's copy had are gone. The NOLINT on the unreachable default case loses the stray "-warnings-as-errors", which is not a check name. The start-position setup in start_object()/start_array() is left alone, as #5706 is editing the callback parser's versions. Behavior, the public API and the ABI are unchanged. Part of #5712 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Correct the parser comments on recursion and skip_to_state_evaluation The class documentation called the parser a recursive descent parser, but sax_parse_internal() is a loop that keeps the open containers on an explicit stack. The comment at the end of an array and of an object said the flag is set to false while the code below it sets it to true. Describe what the code does instead. Comments only; behavior, the public API and the ABI are unchanged. Part of #5712 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Update the discard_number_values comments to the current number path The comments explaining the accept() shortcut in convert_number() and the member documentation still argued in terms of strtoull()/strtoll() and errno, which #5283 replaced with convert_integer(), and pointed at scan_number() instead of convert_number(). They also did not say that scan_number_bulk_contiguous() converts integers itself, so the shortcut is only reached for input without bulk access, with JSON_DIAGNOSTIC_POSITIONS, or when the bulk scanner falls back. Rewrite both comments to describe the digit-count check in front of convert_integer(), keeping the 18-digit bound and the json_sax_acceptor argument. The stale <cstdlib> comment is left for after #5616, which edits that include block. Comments only; behavior, the public API and the ABI are unchanged. Part of #5712 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * List the UTF-8 validators instead of calling the DFA the only one The documentation of decode() called the Hoehrmann DFA the single source of truth for UTF-8 validation. It is used only by the serializer and by is_valid_utf8() (CBOR/MessagePack/BSON/UBJSON/BJData text strings). The lexer's scan_string() switch, validate_one_utf8() / valid_utf8_prefix() (bulk string scan, BON8 bulk path and BON8 writer) and the BON8 byte path in get_bon8_string() check the RFC 3629 ranges on their own. Replace the sentence with a list of the four validators, what each is used for, and a note that they must accept the same sequences. Sharing code between them was considered and dropped: it would save a few lines in a validator that is entangled with BON8 pushback, and #5677 is editing the BON8 byte path. Comments only; behavior, the public API and the ABI are unchanged. Part of #5712 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Fix stale doc comments and include lists in the input headers input_adapters.hpp included <memory> and <numeric> for the removed shared_ptr-based adapter design but used neither; it called (std::min) without including <algorithm>. json_sax.hpp used std::numeric_limits without including <limits>. Also corrected comments that no longer matched the code: input_stream_adapter does not skip the input's BOM (the lexer's skip_bom() does), the span_input_adapter comment named the no-longer-existing input_buffer_adapter type, lexer::get_string() does not reset the token, binary_reader's get_number() doc opened with /* instead of /*! (so Doxygen skipped it) and omitted BON8 from its endianness note, and the UBJSON-binary-types note did not mention that BJData 'B' arrays are read as binary. Left out: the lgtm suppression on lexer.hpp's scan_number() (in #5616's hunk) and the "-1 if unknown" wording in json_sax.hpp's start_object/start_array docs (in draft #5267's hunk), per the verdict's conflict list. Part of #5712 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Deduplicate the strict-EOF/release_lookahead/error block in parser::parse() json_sax_dom_callback_parser and json_sax_dom_parser branches of parser::parse() ran the same ~25 lines after sax_parse_internal(): the strict-mode EOF check (raising parse_error.101 through the SAX parser), release_lookahead() in non-strict mode, and mapping an errored SAX parser to a discarded result. The two copies had already drifted apart in formatting and in the second copy's "see above" comment. Add a private parse_dom(DomSax&, strict) member that runs this shared sequence once and returns whether the SAX parser did not error; both branches of parse() now only construct their DOM SAX parser, call parse_dom(), and (for the callback parser) map a discarded top-level value to null. sax_parse() is left untouched, since it only runs the EOF check and release_lookahead() when sax_parse_internal() succeeded, unlike parse(), which runs them unconditionally. Behavior-preserving: same operations in the same order for both SAX parser kinds. Verified with unit-class_parser (strict/non-strict, callback and non-callback), unit-deserialization and unit-disabled_exceptions (JSON_NOEXCEPTION), plus a clean make amalgamate / make check-amalgamation diff. Overlaps #5601, which touches the same lines. Signed-off-by: Niels Lohmann <mail@nlohmann.me> #5712 item 2 * Share the code point to UTF-8 encoding between the wide-string helpers and the lexer The 1/2/3/4-byte UTF-8 encoding ladder was written out by hand three times: in wide_string_input_helper<..., 4>::fill_buffer() for a UTF-32 code point, in the UTF-16 helper for both a BMP code unit and a valid surrogate pair, and in the lexer's \uXXXX/\uXXXX\uYYYY handling. The copies had drifted: the UTF-32 helper masked the leading bits of each byte (& 0x1Fu, & 0x0Fu, & 0x07u) where the others relied on the shift alone, even though both give the same result for a code point that is already known to be in range. Add detail::encode_utf8(cp, out) in string_utils.hpp, a single encoder that invokes a callable once per output byte, most significant byte first. Use it in the three valid-code-point branches (UTF-32 code points up to U+10FFFF, UTF-16 code units outside the surrogate range, and valid UTF-16 surrogate pairs) and in the lexer's \u handling, where out forwards to add(). The UTF-16 helper's deliberate pass-through of malformed surrogate units and the UTF-32 helper's 0xFF sentinel for code points above U+10FFFF are untouched, since neither reaches the new helper. Behavior-preserving: same bytes in the same order for every valid code point, verified with unit-class_lexer, unit-class_parser, unit-deserialization, unit-wstring and the non-test-data parts of unit-unicode1..5 (ASan/UBSan, C++11/17/20), and an escape-heavy parse microbenchmark that shows no change (about 73 ms either way, median of 3, 1M escape sequences). single_include/ regenerated with make amalgamate; make check-amalgamation leaves a clean tree. Overlaps #5704, which rewrites the wide_string_input_helper specializations touched here. Signed-off-by: Niels Lohmann <mail@nlohmann.me> #5712 item 6 --------- Signed-off-by: Niels Lohmann <mail@nlohmann.me>
…les (#5732) * Run the README test case in JSON_FastTests jobs The "README" test case was marked doctest::skip() when the tests moved from Catch to doctest in 2019, where it replaced Catch's hidden tag. It is not slow (17 assertions, about 0.00 s), but cmake/test.cmake only passes --no-skip when JSON_FastTests is off, so the per-compiler ci_test_*_cxxNN matrix, macOS, Windows Release/ARM, icpc, icpx and nvhpc compiled the README examples without running them. Drop the skip decorator so every job runs the case. Test-only change. Part of #5713 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Remove stale clang ranges guards in unit-iterators2.cpp The "algorithms" and "views" sections were guarded by clang/libstdc++ checks written for a clang 15 (04/2022) bug. The first guard's condition contradicts its own comment: it skips clang+libc++ and keeps clang+libstdc++. Both sections already sit inside `#if JSON_HAS_RANGES`, which macro_scope.hpp excludes for the toolchains these guards targeted, so the inner guards never let the sections run on the platforms they meant to protect and are redundant on the rest. Verified locally with Apple clang 21/libc++ and clang 16.0.6/libstdc++ 12 (Docker): both pass all 1355 assertions with the guards removed. Part of #5713 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Fix copy-pasted CBOR half-float checks; enable stale encode checks In the RFC 8949 Appendix A test case, the decode checks for 5.960464477539063e-8 (0xf9 0x00 0x01) and 0.00006103515625 (0xf9 0x04 0x00) were copy-pasted from the neighboring -4.0 example, so those two half-float byte sequences were never actually decoded and checked, and -4.0 was checked three times instead. The two float32 encode checks for 100000.0 and 3.4028234663852886e+38 were commented out before the writer supported emitting float32 and are now verified to match byte for byte, so they are enabled. The remaining commented-out half-precision to_cbor checks are collapsed into a single explanatory comment, since the writer never emits half-precision floats. Part of #5713 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Assert on the result of STL container conversions in tests The "object-like STL containers" and "array-like STL containers" sections converted json values into std::map, unordered_map, multimap, unordered_multimap, list, forward_list, array, valarray, vector, deque, set and unordered_set and discarded the result, so these ~60 conversions only proved that the code compiles and does not throw; a conversion that dropped or reordered elements would still pass. Bind each result and compare it against the expected container. Also fix a copy-paste slip in the deque section (`j2.get<std::deque<double>>()` instead of j3, so j3's doubles were never converted to a deque), and remove the dead `// CHECK(m5["one"] == "eins")` comments that referred to a variable that did not exist by asserting the equivalent through the bound result. Part of #5713 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Deduplicate SaxCountdown and other test helpers across formats SaxCountdown was copied byte-for-byte into six binary-format test files (unit-cbor.cpp, unit-msgpack.cpp, unit-ubjson.cpp, unit-bjdata.cpp, unit-bon8.cpp, unit-bson.cpp), about 370 redundant lines. Move it into tests/src/sax_countdown.hpp (namespace utils, alongside test_utils.hpp and round_trip_corpus.hpp) and include it from all six. trait_test_arg and the "value_in_range_of trait" TEST_CASE_TEMPLATE_DEFINE were duplicated between unit-32bit.cpp and unit-bjdata.cpp; the trait is a detail/meta trait, not specific to either file. Move it into tests/src/value_in_range_of_test.hpp; unit-32bit.cpp keeps its own include, since JSON_32bitTest=ONLY builds only that file. Each file keeps its own TEST_CASE_TEMPLATE_INVOKE list. sax_no_exception and the "issue #2824" section were duplicated in unit-regression2.cpp and unit-disabled_exceptions.cpp. Drop the copy from unit-regression2.cpp; unit-disabled_exceptions.cpp already covers the no-exceptions case that #2824 was about, and ci_test_noexceptions reruns it. No behavior change. Verified by building and running unit-cbor, unit-msgpack, unit-ubjson, unit-bjdata, unit-bon8, unit-bson, unit-32bit, unit-regression2 and unit-disabled_exceptions against include/ (clang++ -std=c++11, ASan/UBSan where applicable); assertion counts are unchanged from before the refactor. Part of #5714 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Remove the unreferenced vendored libFuzzer tests/thirdparty/Fuzzer (155 files, ~776 KB of vendored Apache-2.0 LLVM code from the 2016 OSS-Fuzz import) is not referenced by any CMakeLists, Makefile or workflow: the fuzz drivers link against -fsanitize=fuzzer or the repo's own tests/src/fuzzer-driver_afl.cpp. Its vendored README only points at llvm.org's own libFuzzer docs. Being dead code, it also adds noise to the flawfinder code-scanning workflow, which scans the whole tree. Remove the directory and its .reuse/dep5 entry. Part of #5714 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Remove unreferenced 2016 benchmark and fuzz reports tests/reports (1.6 MB) holds AFL status pages and plots from 2016-08-29 and 2016-10-02, and a nativejson-benchmark snapshot from 2016 with links to rawgit.com, which shut down in 2019. Nothing references this directory: no doc, README section, script or workflow points at it, and it describes a ten-years-old, pre-2.0 snapshot of the library. Part of #5714 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Run the CBOR, MessagePack, BSON and BON8 round-trip invariants in CI tests/src/round_trip_corpus.hpp exists so that the byte-stability invariant the fuzzer drivers check also runs on a fixed corpus in CI, instead of only at OSS-Fuzz. So far only the UBJSON and BJData drivers had a matching unit test; the CBOR, MessagePack, BSON and BON8 drivers assert the same invariant (assert(to_X(j2) == vec)) but nothing ran it outside OSS-Fuzz. Add "<FORMAT> round-trip invariants" test cases to unit-cbor.cpp, unit-msgpack.cpp, unit-bson.cpp and unit-bon8.cpp, modeled on the UBJSON case: seed j1 from the corpus (skipping values that do not survive the format's own round trip, as the fuzzer drivers only ever see values from_X() actually produced), then require from_X(to_X(j1)) not to throw and check to_X(j2) == to_X(j1). BSON only serializes objects, so non-object corpus values are skipped. Update the comments in round_trip_corpus.hpp and tests/fuzzing.md to name all six formats. The stream-versus-contiguous check in the BON8 driver is left out, as #5601 reworks it. A local probe confirms no violations on the current corpus (CBOR 3849 checked, MessagePack 3909, BSON 2958, BON8 3841 - matching the counts already recorded for this probe in the issue). Closes #5714 item 1. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Fix fuzzer driver step lists to match the checks the code performs The header comment of six of the seven binary-format fuzzer drivers listed an invariant the code does not check: CBOR, MessagePack, BSON and BON8 said "assert(j1 == j2)", but the code checks byte stability, assert(to_X(j2) == vec). UBJSON and BJData still described the old "assert(j1 == j2/j3/j4)" byte-exact check from before PR #5494 replaced it with a use_size/use_type-aware round trip (UBJSON) and a value-stability check (BJData); BJData's added paragraph already explained the new check, but the step list above it did not. Also remove a dead branch in fuzzer-parse_bson.cpp: from_bson() is called with allow_exceptions = true, so it throws instead of returning a discarded value, and the "if (j1.is_discarded()) return 0;" guard could never trigger. Drop the unused <iostream> include from all seven drivers and <sstream> from all but fuzzer-parse_bon8.cpp, which is the only one that uses std::istringstream. Overlaps #5601, which edits all seven drivers in the same hunks. Closes #5714 item 4. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Silence the CMP0169 deprecation in cmake_fetch_content, fix stale guards tests/cmake_fetch_content/project calls the single-argument FetchContent_Populate(json) after FetchContent_Declare(), which CMake 3.30 deprecated as CMP0169. Since the project declares cmake_minimum_required(VERSION 3.11...3.14), the policy stays unset, so every configure with a current CMake prints the deprecation warning. The test is kept on purpose: it is the only coverage of the FetchContent_Populate + add_subdirectory pattern for CMake 3.11-3.13 users, which the docs still describe as supported. Explicitly set CMP0169 to OLD, with a comment explaining why. Also fix two stale version guards: - tests/cmake_fetch_content/CMakeLists.txt guarded the test with VERSION_GREATER "3.11.0", which is dead now that tests/CMakeLists.txt requires CMake 3.13. - tests/cmake_fetch_content2/CMakeLists.txt guarded with VERSION_GREATER "3.14.0", which skips exactly 3.14.0, the first version with FetchContent_MakeAvailable. Change it to VERSION_GREATER_EQUAL "3.14". Verified locally: `ctest -R cmake_fetch_content` passes with CMake 4.1, and the CMP0169 deprecation warning that appeared before this change is gone. Closes #5714 item 5. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Make the CMake integration-test wrappers consistent The six tests/cmake_* integration-test wrappers had drifted: - Only cmake_import and cmake_import_minver forwarded -A "${CMAKE_GENERATOR_PLATFORM}" to the inner configure, and none forwarded -T "${CMAKE_GENERATOR_TOOLSET}". The Windows workflow configures the outer build with -A Win32 -T ClangCL, so without forwarding, the inner projects of cmake_add_subdirectory, cmake_fetch_content, cmake_fetch_content2 and cmake_target_include_directories built with the generator defaults instead of matching the outer build's platform and toolset. Forward both consistently from all six wrappers. - cmake_fetch_content and cmake_fetch_content2 passed -Dnlohmann_json_source to their inner projects, which never read it (CMake warns "manually-specified variables were not used"); the inner projects fetch their own copy of the library instead. Drop it. - tests/CMakeLists.txt set JSON_FORCED_GLOBAL_COMPILE_OPTIONS from the matching environment variable but never read the cache variable again; the lines right below it read $ENV{JSON_FORCED_GLOBAL_COMPILE_OPTIONS} directly, like the LINK_OPTIONS counterpart already does. Remove the dead set(). This changes which platform and toolset the Win32 and ClangCL CI jobs build the four newly-forwarding wrappers' inner projects with, which may surface new failures there; CI has to confirm those jobs. Verified locally with Ninja (empty -A ""/-T "" is accepted): all 12 cmake_* tests still pass, and the inner fetch_content configures no longer warn about the unused variable. Closes #5714 item 6. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Turn the #972 fifo_map regression test into a real test The #972 regression test in unit-regression1.cpp only built a my_json array from a string literal (the original crash) and had no CHECK, so the fifo_map object type it exists to demonstrate was never exercised. Meanwhile the docs recommend fifo_map for keeping object keys in insertion order (object_order.md, template_parameters.md), and nothing tested that recommendation. Extend the section: after the original array assignment, parse an object with my_json::parse() (not via the "..."_json UDL, which returns a plain nlohmann::json and would exercise the cross-basic_json conversion constructor instead of the parser's own key insertion - and, as tried locally, does not keep fifo order for this stateful comparator) and check that dump() keeps insertion order, and that it survives erase() and inserting a new key. Also narrow thirdparty/fifo_map off the include path of every other test-* target: it was a PUBLIC include directory of test_main, even though unit-regression1.cpp is its only user. Add a small fifo_map_include INTERFACE library with that include directory and attach it to test-regression1 only via json_test_set_test_options(). Verified locally (test-regression1_cpp11, default build and -fsanitize=address,undefined): the new checks pass; `git grep fifo_map tests` still only finds unit-regression1.cpp and the vendored header. Closes #5714 item 7. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Document the vendored doctest.h patch; fix stale doctest_compatibility.h comments tests/thirdparty/doctest/doctest.h is doctest 2.4.12, imported in #4771. Two weeks later, #4801 hand-edited translateActiveException() to declare "String res;" inside the translator loop instead of before it, so a translator that does not match does not leave a previous translator's result in "res" for the next iteration to see. Nothing recorded this, so re-vendoring doctest.h from upstream would silently drop the fix. Add a comment at the patched site naming the version, the PR and the reason, so a future re-vendor knows to re-apply it. Also fix two stale comments in doctest_compatibility.h: - The DOCTEST_THREAD_LOCAL comment referenced Xcode 6/7, which is no longer supported; reword it to explain why the define must stay regardless (it keeps doctest's own thread_local usage out of the way of the same Clang/MinGW crash that JSON_NO_THREAD_LOCAL works around in the library, see ci_test_no_thread_local). - The <iosfwd> include's comment justified it with tests that define "private" as "public"; no test under tests/src does that any more (removed by #2352). Reword the comment instead of dropping the include, since confirming it is safe to drop needs the full CI matrix including MSVC 2015+. Verified locally that tests/src/unit-readme.cpp still builds and passes 17/17 with these headers. Closes #5714 item 9. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Stop compiling unit-wstring.cpp out entirely on classic ICC tests/src/unit-wstring.cpp wrapped the whole file in #ifndef __INTEL_COMPILER, with the comment "ICPC errors out on multibyte character sequences in source files". The ci_icpc job (intel/oneapi-hpckit:2023.2.1) still exists, so that job ran none of the wstring/u16string/u32string input adapter tests, including the malformed-input checks #5704 (open) extends. Only 9 lines contained non-ASCII bytes: the three *_is_utf16()/ *_is_utf32() probe functions, and three std::wstring/u16string/ u32string literals plus their narrow-string dump() expectations. Rewrite all of them with \u/\U escapes in the wide/u16/u32 literals and \x escapes (split into separate string-literal tokens so a following byte is never read as part of the same hex escape, e.g. "\xE1\x83\x85" "a") in the narrow ones. Remove the #ifndef __INTEL_COMPILER/#endif guard along with it. The *_is_utf16()/*_is_utf32() probes compared a raw multibyte literal against an escape-based one to detect a compiler that misreads the source file's encoding; with no raw literals left to misread, the comparison is now tautological, so drop the probes and the "if" guards around each SECTION's body instead of leaving them in as dead checks. The same non-ASCII-in-source-and-in-a-narrow-comparison pattern existed once more in unit-deserialization.cpp's "Using _json with char8_t literals #4945" test: a raw emoji character in a u8R"(...)" literal, guarded by a check_utf8() that returned false for ICC (same reason) and for Windows without the active UTF-8 code page. Rewrite the literal with a \U escape and compare it against a \x-escaped expectation instead of a second raw literal, and drop check_utf8() and the now-unused <windows.h> include along with the guard. Verified locally (clang, -std=c++11 and -std=c++20, -fsanitize=address,undefined, and a plain build): test-wstring keeps 18/18 assertions and unit-deserialization keeps 466/466 (c++11) and 477/477 (c++20) assertions, matching this branch before the change exactly - no coverage was gained or lost, only the source-encoding dependency was removed. ci_icpc has to confirm classic ICC actually builds and passes test-wstring now; if it does not, that is a real finding, not a reason to restore the guard. Overlaps #5704 (open), which edits unit-wstring.cpp inside the previously-guarded region (an include near the top, checks in the invalid-string sections, and a new section at the end). Closes #5713 item 5. Signed-off-by: Niels Lohmann <mail@nlohmann.me> --------- Signed-off-by: Niels Lohmann <mail@nlohmann.me>
…989-db7e45 Signed-off-by: Niels Lohmann <mail@nlohmann.me> # Conflicts: # include/nlohmann/detail/input/lexer.hpp # include/nlohmann/detail/input/parser.hpp # single_include/nlohmann/json.hpp # tests/src/fuzzer-parse_json.cpp
…989-db7e45 Signed-off-by: Niels Lohmann <mail@nlohmann.me> # Conflicts: # docs/mkdocs/docs/api/json_sax/parse_error.md # docs/mkdocs/docs/features/parsing/index.md
clang's -Wdocumentation-unknown-command reads "\u" in a doc comment as an unknown command, even in backticks. Two comments of the recovery code now say "Unicode escape" instead. Signed-off-by: Niels Lohmann <mail@nlohmann.me>
The MinGW job ("clang (20.1.8)", Debug) failed to link test-msgpack_cpp17
with "relocation truncated to fit: IMAGE_REL_AMD64_REL32 against
`.rdata'". Its GNU ld (MinGW 12.2.0) cannot link an object file with
more than 32767 sections. Reproduced with clang 20.1.8 and binutils
2.40: unit-msgpack.cpp's object has 31958 sections on develop and had
33210 with #3989; binutils 2.44 links both.
The readers of from_*() never recover, but unoptimized builds still
emitted the recovery code their dead branches referenced: about 20
helpers per reader instantiation, plus the lexer's recovery functions
through the UBJSON high-precision number repair. Now:
- Errors are reported with report_error() only. The helpers that act on
the SAX parser's answer (repair_requested(), resync(), value_failed(),
close_open_containers(), and the repairs of high-precision numbers and
unsupported BSON elements) have one trivial variant for readers that do
not recover, so the recovery code is not referenced there.
- Object keys that are not strings and BSON elements whose end is lost
are marked at the error site and skipped by resync() in the reading
loops; report_repairable_error(), report_error_repairable_if(),
report_bson_element_error(), and bon8_error_repairable_if() are gone.
- is_cbor_item_head() is a free function, and the BSON element type is
formatted as on develop again.
The object now has 32638 sections and links. Behavior is unchanged
(regression tests, binary format suites, and fuzzing), and an optimized
program that only calls from_*() is now 256 bytes smaller than on
develop.
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
…989-db7e45 Signed-off-by: Niels Lohmann <mail@nlohmann.me> # Conflicts: # tests/src/unit-alt-string.cpp
…989-db7e45 Signed-off-by: Niels Lohmann <mail@nlohmann.me> # Conflicts: # include/nlohmann/detail/input/binary_reader.hpp # include/nlohmann/detail/string_utils.hpp # single_include/nlohmann/json.hpp
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
…989-db7e45 Signed-off-by: Niels Lohmann <mail@nlohmann.me>
…989-db7e45 Signed-off-by: Niels Lohmann <mail@nlohmann.me>
…989-db7e45 Signed-off-by: Niels Lohmann <mail@nlohmann.me>
…989-db7e45 Signed-off-by: Niels Lohmann <mail@nlohmann.me>
…989-db7e45 Signed-off-by: Niels Lohmann <mail@nlohmann.me>
…989-db7e45 Signed-off-by: Niels Lohmann <mail@nlohmann.me>
…989-db7e45 Signed-off-by: Niels Lohmann <mail@nlohmann.me>
The local alias that the out-of-range test declared shadows the identical file-scope one, which GCC's -Wshadow=global turns into an error. Signed-off-by: Niels Lohmann <mail@nlohmann.me>
The MinGW clang job links with a GNU ld that cannot relocate an object with more than 32767 sections. unit-regression2, unit-regression3 and unit-msgpack went over it: - At -O0, the parser and binary reader for parse(), accept() and from_*() still emitted the stubs that stand in for recovering, and the parser referenced its recovery helpers from code that never runs. The stubs are now always inlined, and the parser reaches its helpers through the same allow_recovery tag as the stubs, so that this code is not even instantiated there. This removes about 300 sections from unit-msgpack. - Every sax_parse call instantiates the parser and binary reader that recover from errors. The tests that call it move from unit-regression2.cpp (#3989) and unit-regression3.cpp (#5676) into unit-sax_parse.cpp, like unit-explicit_instantiation.cpp got a file of its own (#5511), and CONTRIBUTING.md points there. Section counts of the MinGW Debug objects (clang 19, -g0), develop / PR: unit-msgpack 32281 / 32558, unit-regression2 31272 / 31278, unit-regression3 32392 / 27462, unit-sax_parse - / 19836. Signed-off-by: Niels Lohmann <mail@nlohmann.me>
f8ff094 marked the stubs that stand in for error recovery with JSON_HEDLEY_ALWAYS_INLINE, which is __forceinline with MSVC. Visual Studio 2015 and 2017 do not inline them and warn (C4714), which /WX turns into an error on AppVeyor. The new internal macro JSON_INTERNAL_ALWAYS_INLINE forces inlining everywhere else (including clang-cl), and leaves the decision to MSVC. The MinGW objects keep their smaller section counts, as GCC and clang still inline the stubs. Signed-off-by: Niels Lohmann <mail@nlohmann.me>
- parser::report_error() calls only sax->parse_error(). For a SAX parser whose parse_error() is static, as in unit-disabled_exceptions.cpp, Visual Studio 2015 then reports the parameter as unreferenced (C4100), which /WX turns into an error. - The variadic concatenated() helper in unit-sax_parse.cpp made Visual Studio 2015 fail with an internal compiler error (C1001). It now takes an initializer list of byte vectors. Signed-off-by: Niels Lohmann <mail@nlohmann.me>
…989-db7e45 Signed-off-by: Niels Lohmann <mail@nlohmann.me>
With develop's latest changes, the MinGW Debug object of unit-msgpack.cpp has 33134 COFF sections on its own and 33411 with this PR, more than the 32767 that the MinGW linker of the "clang (20.1.8)" job can relocate. Its sax_parse calls, all with utils::SaxCountdown, instantiate a parser and binary reader of their own; moving those tests into unit-sax_parse.cpp brings the object down to 32271 sections (unit-sax_parse: 20678). The moved tests are unchanged: the "SAX aborts" sections, the user-defined SAX consumer of #5405, the deep value read through the SAX interface (#5104), and "MessagePack SAX parsing stops at every event". Signed-off-by: Niels Lohmann <mail@nlohmann.me>
…989-db7e45 Signed-off-by: Niels Lohmann <mail@nlohmann.me>
…989-db7e45 Signed-off-by: Niels Lohmann <mail@nlohmann.me>
…989-db7e45 Signed-off-by: Niels Lohmann <mail@nlohmann.me>
…989-db7e45 Signed-off-by: Niels Lohmann <mail@nlohmann.me>
…989-db7e45 Signed-off-by: Niels Lohmann <mail@nlohmann.me>
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
With seekable input, the lexer derives line and column on demand (#5809) by counting the newlines in all input consumed so far. A SAX parser that recovers from errors asks for the position once per error, so input with an error at every character took quadratic time: "{" followed by 100000 commas took 85 s at -O0, and the parser tests timed out under Valgrind (1500 s, was 69 s on develop). get_position() now remembers what it counted and only scans the input consumed since the previous call; count_consumed_lines() takes the start of the range. The 100000 commas now take 0.17 s, unit-class_parser 0.9 s instead of 86 s. Over 69284 error messages from random multi-line inputs, the messages are identical to those before the change. Signed-off-by: Niels Lohmann <mail@nlohmann.me>
Addresses #3989 and supersedes #4522.
Problem
The return value of
json_sax::parse_error()was documented both as "must returnfalse" (parse_error) and as "whether the parsing should continue" (parse exceptions). The code just passed the value on (return sax->parse_error(...)), so a handler returningtruegot broken behavior:sax_parse()returnedtruefor invalid input such as[1,2,3,].0x9F(an indefinite-length array) followed by the end of the input looped forever, callingparse_error()each time. A truncated MessagePackarray32made about 4 billion calls.#4522 let the parser carry on after the error without repairing anything, which produced meaningless events (e.g.
key(1)for{1}).Change
parse_error()returningfalsestops parsing, as before. Returningtruenow recovers from the error.JSON text: repair and continue
Every error is repaired with the smallest local edit:
,or:[1 2],{"a" 1}[1,2],{"a":1}nullfor an object key or between commas in an array{"a":},[1,,2]{"a":null},[1,null,2][1,2,][1,2]\uescape, a lone surrogate, or ill-formed UTF-8 becomes U+FFFD["a\qb"]["aqb"][1., 2e+][1,2]null[1, NaN, tru][1,null,null][1e999]number_float(inf, "1e999"):["a":1]["a",1],or}{1:2, "b":3}{"b":3}{"a":[1,2}, "b":3}{"a":[1,2],"b":3}{"a":[1,2{"a":[1,2]})]}'{"a":1}{"a":1}Guarantees while recovering:
key()is followed by exactly one value. A DOM-building handler therefore always gets a complete value.false.Binary formats: repair what is complete, complete what was read
The binary formats have no delimiters to find the next value by, so what can be repaired depends on whether the end of the item with the error is known. RFC 8949, Section 5.3 makes the same distinction for CBOR, and names the two choices a decoder has for an item that is complete but invalid: replace it with an error marker and continue, or stop. That is
parse_error()returningtrueorfalse.The item is complete, but cannot be passed on as it is: it is replaced, and reading continues after it.
cbor_tag_handler_t::error)false,true,null, e.g. undefinednullnumber_float_t, likefloatC) that is not ASCIIH)nullnullsax_parseuses that default. If a reader is set to reject them (error_handler_t::strict, Add an error_handler parameter for UTF-8 to the binary readers and writers #5746), recovering repairs them aserror_handler_t::replacedoes.sax_parse's defaultcbor_tag_handler_t::error(Allow SAX parsing of tagged CBOR #5740), every tag is an error; when recovering, it is ignored.The end of the item is unknown (the input ended, a byte is not a valid type marker, or a size cannot be right):
nullfor a key that waits for its value, and end events for all open containers.null, the rest of its document is skipped, and reading continues after it.sax_parse()resultsax_parse()now returnstrueonly if the input was parsed without errors and no event returnedfalse.Comparison with VS Code's jsonc-parser
The design is modeled on the error-tolerant parser in microsoft/node-jsonc-parser (source checked):
:is inserted; jsonc-parser drops the member.nullinstead of silently disappearing, which would shift array indices and leave keys without values.{"a":[1,2}, "b":3}gives{"a":[1,2,"b"]}there.onErrorreturnsvoid.Implementation notes
sax_parse_internaltakes abool AllowRecovery.parse()andaccept()usefalse, and theirreport_errorreturnsstd::false_type, so all recovery code is dead there even when the call isn't inlined. A parse-only program's__textis 260 bytes smaller than before, and none of the recovery functions are in it.recover_token()(keeps the readable part of a rejected token) andunget_token()(lets a repair hand,]}or the end of input back to the state evaluation). The hot path ofscan_stringis unchanged; three surrogate error paths now record how to resume.binary_readergets abool AllowRecoverytemplate parameter, too.sax_parseusestrue;from_*()usefalse, and their repair code is dead through the samestd::false_typeoverloads as in the parser.report_error: the end of the item is unknown, so it stops.report_repairable_error: the item is complete.report_error_repairable_if: it depends on the byte, and the error is still reported in one place when recovery is not compiled.container_stack, as the JSON parser does from itsstates. A key waiting for its value is noted where reading a value fails; the object and array of a BJData ndarray are tracked by a small counter.skip_itemsskips a member whose key is not a string without passing events. It uses a heap stack of counts and a head reader per format for CBOR, MessagePack, and BON8.replace_invalid_utf8(instring_utils.hpp) substitutes maximal subparts (Unicode, Section 3.9).json_sax_dom_parser/json_sax_dom_callback_parserget a defaultInputAdapterType. The documentedjson_sax_dom_parser<json>has not compiled since json start/end position implementation #4517.json_sax_dom_parseris also exported from the C++ module, so that the documented way to recover into ajsonvalue works.Performance
Median of 61 runs, before → after. Measured on an array of 40 000 small objects ("objects") and an array of 20 000 nested numeric arrays ("arrays"). The
sax_parsehandler is a do-nothing virtual counter, so the numbers show the parser loop itself.parse(objects)parse(arrays)accept(objects)sax_parse(objects)sax_parse(arrays)parse()andaccept()are unchanged.sax_parse()with a handler that does nothing moves by a few percent, slower with clang and faster with GCC, so that part is code layout.Binary formats, clang (Apple Silicon), median of 3×41 runs,
develop→ this PR, on the same 20 000 objects:from_*()sax_parseA program that only calls
from_*()for all six formats is 136 bytes (0.14%) larger in__text.In unoptimized builds,
parse(),accept(), andfrom_*()do not instantiate the recovery code: the stubs that stand in for it are always inlined, and the parser reaches its recovery helpers only through the recovering instantiation.Tests
unit-class_parser.cpp:ignore_trailing_commas, strict and non-strict parsing, and NUL bytes;[]{},:"x\NUL0xFFin several documents, checking that events are balanced, error counts are bounded, and valid input is unaffected.unit-sax_parse.cpp(new): everysax_parsecall instantiates the parser and binary reader that recover from errors, which pushedunit-regression2.cppandunit-regression3.cpppast the MinGW linker's section limit (32767 COFF sections). So the tests that callsax_parse(these, sax_parse cannot read CBOR that contains tags, including binary values with a subtype written by to_cbor #5676's tagged-CBOR test fromunit-regression3.cpp, and the MessagePack SAX tests fromunit-msgpack.cpp) have a file of their own, and CONTRIBUTING.md points there.from_*()fails, and the first error must be the onefrom_*()throws.fuzzer-recovering_checker.hpp) from memory and from a stream. The binary ones also check that it reports an error exactly whenfrom_*()fails. Locally, with ASan/UBSan: 3.6 + 1.4 million runs for JSON text and 21 million for the binary formats found nothing.JSON_STRICT_NUL_HANDLING=1,JSON_DIAGNOSTICS=1,JSON_DIAGNOSTIC_POSITIONS=1; the CI's clang-Weverythingand GCC 16 warning flags; the binary format suites (with stubbed test data);make check-amalgamation; docs example output and style check.Docs
parse_error,sax_parse, the SAX interface and parse-exceptions pages, and the README.Breaking changes
parse_error()returnstrue, which was documented as "must returnfalse":sax_parse()returnsfalseafter any error; before, it could returntruefor invalid input.parse(),accept(), andfrom_*(), events, error messages, and positions are unchanged.detail::json_sax_dom_parseranddetail::json_sax_dom_callback_parser;bool AllowRecoverytemplate parameter fordetail::binary_reader;json_sax_dom_parser.🤖 Generated with Claude Code