cmJSONState: Use StructuredErrors when available

When the version of JsonCpp permits it, use StructuredErrors to generate
error messages for parse errors in the same style as other CMake-generated
JSON error messages.

Fixes: #26717
This commit is contained in:
Martin Duffy 2025-03-14 13:54:25 -04:00
parent 2604f5d8b3
commit bed7e90bae
3 changed files with 30 additions and 5 deletions

View File

@ -4,10 +4,12 @@
#include "cmJSONState.h"
#include <iterator>
#include <memory>
#include <sstream>
#include <cm3p/json/reader.h>
#include <cm3p/json/value.h>
#include <cm3p/json/version.h>
#include "cmsys/FStream.hxx"
@ -35,14 +37,27 @@ cmJSONState::cmJSONState(std::string jsonFile, Json::Value* root)
}
fin.seekg(finBegin);
// Parse the document.
Json::CharReaderBuilder builder;
Json::CharReaderBuilder::strictMode(&builder.settings_);
std::string errMsg;
#if JSONCPP_VERSION_HEXA >= 0x01090600
// Has StructuredError
std::unique_ptr<Json::CharReader> const reader(builder.newCharReader());
reader->parse(doc.data(), doc.data() + doc.size(), root, &errMsg);
std::vector<Json::CharReader::StructuredError> structuredErrors =
reader->getStructuredErrors();
for (auto const& structuredError : structuredErrors) {
this->AddErrorAtOffset(structuredError.message,
structuredError.offset_start);
}
#else
// No StructuredError Available, Use error string from jsonCpp
if (!Json::parseFromStream(builder, fin, root, &errMsg)) {
errMsg = cmStrCat("JSON Parse Error: ", this->Filename, ":\n", errMsg);
this->AddError(errMsg);
}
#endif
}
void cmJSONState::AddError(std::string const& errMsg)

View File

@ -1,8 +1,13 @@
^CMake Error: Could not read presets from [^
]*/Tests/RunCMake/CMakePresets/Comment:
JSON Parse Error: [^
(CMakePresets.json:1: Syntax error: value, object or array expected.
// Comment
\^
CMakePresets.json:2: Extra non-whitespace after JSON value.
{
\^|JSON Parse Error: [^
]*Comment\/CMakePresets.json:
\* Line 1, Column 1
Syntax error: value, object or array expected\.
\* Line 2, Column 1
Extra non-whitespace after JSON value\.$
Extra non-whitespace after JSON value\.$)

View File

@ -1,6 +1,11 @@
^Could not read/parse resource spec file [^
]*/Tests/RunCMake/CTestResourceAllocation/invalid\.json:
JSON Parse Error: [^
(invalid.json:1: Syntax error: value, object or array expected.
This is not a valid JSON file!
\^
invalid.json:1: Extra non-whitespace after JSON value.
This is not a valid JSON file!
\^|JSON Parse Error: [^
]*/Tests/RunCMake/CTestResourceAllocation/invalid\.json:
\* Line 1, Column 1
Syntax error: value, object or array expected\.
@ -8,7 +13,7 @@ JSON Parse Error: [^
Extra non-whitespace after JSON value\.
|\* Line 1, Column 1
A valid JSON document must be either an array or an object value\.
)
))
Errors while running CTest
Output from these tests are in: [^
]*/Tests/RunCMake/CTestResourceAllocation/invalid-build/Testing/Temporary/LastTest\.log