diff --git a/benchmark/CMakeLists.txt b/benchmark/CMakeLists.txt index 2cc127772..760a37fb6 100644 --- a/benchmark/CMakeLists.txt +++ b/benchmark/CMakeLists.txt @@ -48,6 +48,10 @@ if(SOURCEMETA_CORE_MARKDOWN) list(APPEND BENCHMARK_SOURCES spec/markdown.cc) endif() +if(SOURCEMETA_CORE_YAML) + list(APPEND BENCHMARK_SOURCES spec/yaml.cc) +endif() + if(SOURCEMETA_CORE_GZIP) list(APPEND BENCHMARK_SOURCES spec/gzip.cc) endif() @@ -108,6 +112,11 @@ if(BENCHMARK_SOURCES) sourcemeta::core::jsonpointer) endif() + if(SOURCEMETA_CORE_YAML) + target_link_libraries(sourcemeta_core_benchmarks + PRIVATE sourcemeta::core::yaml sourcemeta::core::json) + endif() + if(SOURCEMETA_CORE_URITEMPLATE) target_link_libraries(sourcemeta_core_benchmarks PRIVATE sourcemeta::core::uritemplate) diff --git a/benchmark/spec/jsonld.cc b/benchmark/spec/jsonld.cc index 66938f4f4..394f44de9 100644 --- a/benchmark/spec/jsonld.cc +++ b/benchmark/spec/jsonld.cc @@ -349,6 +349,49 @@ static auto populate_annotation_list( } } +// Expansion branches on how a term is defined, so the context states a +// language map, an index map, set containers, a date and a decimal coercion, +// a typed identifier, a property scoped context and a reverse property, and +// the catalog carries a value of every one of those shapes +// Parsing this at namespace scope would be a static initialiser that throws, +// so it is built on first use the way the keys above are +static auto catalog_context() -> const sourcemeta::core::JSON & { + static const auto INSTANCE{sourcemeta::core::parse_json(R"JSON({ + "@vocab": "https://example.com/vocab/", + "schema": "https://schema.org/", + "xsd": "http://www.w3.org/2001/XMLSchema#", + "id": "@id", + "members": { "@id": "schema:hasPart", "@container": "@set" }, + "isbn": "schema:isbn", + "title": { "@id": "schema:name", "@container": "@language" }, + "abstract": "schema:abstract", + "datePublished": { "@id": "schema:datePublished", "@type": "xsd:date" }, + "authors": { "@id": "schema:author", "@container": "@set" }, + "name": "schema:name", + "keywords": { "@id": "schema:keywords", "@container": "@set" }, + "identifiers": { "@id": "schema:identifier", "@container": "@index" }, + "price": { + "@id": "schema:offers", + "@context": { + "value": { "@id": "schema:price", "@type": "xsd:decimal" }, + "currency": "schema:priceCurrency" + } + }, + "publisher": "schema:publisher", + "url": { "@id": "schema:url", "@type": "@id" }, + "series": "schema:isPartOf", + "metadata": { "@id": "schema:additionalProperty", "@container": "@index" }, + "provenance": { "@reverse": "schema:about" } + })JSON")}; + return INSTANCE; +} + +static auto make_described_catalog() -> sourcemeta::core::JSON { + auto catalog{make_catalog()}; + catalog.assign("@context", catalog_context()); + return catalog; +} + BENCHMARK(JSONLD_Catalog_Annotation_List_Populate) { for (auto iteration : state) { sourcemeta::core::JSONLDWeakAnnotationList annotations; @@ -371,3 +414,53 @@ BENCHMARK(JSONLD_Catalog_Materialize) { sourcemeta::core::benchmark_do_not_optimize(result); } } + +BENCHMARK(JSONLD_Catalog_Expand) { + const auto instance{make_described_catalog()}; + + for (auto iteration : state) { + auto result{sourcemeta::core::jsonld_expand(instance)}; + assert(result.is_array()); + assert(result.size() == 1); + assert(result.at(0).defines("https://schema.org/hasPart")); + assert(result.at(0).at("https://schema.org/hasPart").size() == + CATALOG_MEMBER_COUNT); + sourcemeta::core::benchmark_do_not_optimize(result); + } +} + +// Processing the context happens once per document, so a catalog of one member +// is what shows a change to it, while the full catalog amortises it away +BENCHMARK(JSONLD_Member_Expand) { + auto members{sourcemeta::core::JSON::make_array()}; + members.push_back(make_member(0)); + auto instance{sourcemeta::core::JSON::make_object()}; + instance.assign("@context", catalog_context()); + instance.assign("members", std::move(members)); + + for (auto iteration : state) { + auto result{sourcemeta::core::jsonld_expand(instance)}; + assert(result.is_array()); + assert(result.size() == 1); + assert(result.at(0).at("https://schema.org/hasPart").size() == 1); + [[maybe_unused]] const auto &member{ + result.at(0).at("https://schema.org/hasPart").at(0)}; + assert(member.defines("@reverse")); + assert(member.at("https://schema.org/name").size() == 3); + assert(member.at("https://schema.org/identifier").size() == 3); + sourcemeta::core::benchmark_do_not_optimize(result); + } +} + +BENCHMARK(JSONLD_Catalog_Compact) { + const auto expanded{ + sourcemeta::core::jsonld_expand(make_described_catalog())}; + const auto &context{catalog_context()}; + + for (auto iteration : state) { + auto result{sourcemeta::core::jsonld_compact(expanded, context)}; + assert(result.is_object()); + assert(result.at("members").size() == CATALOG_MEMBER_COUNT); + sourcemeta::core::benchmark_do_not_optimize(result); + } +} diff --git a/benchmark/spec/openapi.cc b/benchmark/spec/openapi.cc index ca1afa1f9..df2ec3648 100644 --- a/benchmark/spec/openapi.cc +++ b/benchmark/spec/openapi.cc @@ -1,6 +1,13 @@ #include -#include // std::filesystem +#include // assert +#include // std::size_t +#include // std::filesystem +#include // std::nullopt +#include // std::string, std::to_string +#include // std::string_view +#include // std::move, std::pair +#include // std::vector #include @@ -43,3 +50,152 @@ BENCHMARK(OpenAPI_Format_Synthetic_3_1) { sourcemeta::core::benchmark_do_not_optimize(description); } } + +// The path count sets how many references bundling has to gather for, and the +// shared count how many distinct documents it reaches, so they are the knobs +// to turn when stress testing this functionality +static constexpr std::size_t PATH_COUNT{64}; +static constexpr std::size_t SHARED_COUNT{8}; +static constexpr std::size_t FIELDS_PER_SCHEMA{4}; + +static auto shared_identifier(const std::size_t index) -> std::string { + return "https://example.com/shared-" + std::to_string(index) + ".json"; +} + +static auto make_shared_schema(const std::size_t index) + -> sourcemeta::core::JSON { + auto properties{sourcemeta::core::JSON::make_object()}; + for (std::size_t field = 0; field < FIELDS_PER_SCHEMA; field += 1) { + auto property{sourcemeta::core::JSON::make_object()}; + property.assign("type", sourcemeta::core::JSON{"string"}); + property.assign("title", + sourcemeta::core::JSON{"Field " + std::to_string(field) + + " of " + std::to_string(index)}); + properties.assign("field-" + std::to_string(field), std::move(property)); + } + + auto schema{sourcemeta::core::JSON::make_object()}; + schema.assign("type", sourcemeta::core::JSON{"object"}); + schema.assign("properties", std::move(properties)); + return schema; +} + +static auto make_shared_document(const std::size_t index) + -> sourcemeta::core::JSON { + const auto number{std::to_string(index)}; + auto schema{make_shared_schema(index)}; + + auto media{sourcemeta::core::JSON::make_object()}; + media.assign("schema", schema); + auto content{sourcemeta::core::JSON::make_object()}; + content.assign("application/json", std::move(media)); + auto response{sourcemeta::core::JSON::make_object()}; + response.assign("description", sourcemeta::core::JSON{"Shared " + number}); + response.assign("content", std::move(content)); + + auto responses{sourcemeta::core::JSON::make_object()}; + responses.assign("Thing", std::move(response)); + auto schemas{sourcemeta::core::JSON::make_object()}; + schemas.assign("Thing", std::move(schema)); + auto components{sourcemeta::core::JSON::make_object()}; + components.assign("responses", std::move(responses)); + components.assign("schemas", std::move(schemas)); + + auto info{sourcemeta::core::JSON::make_object()}; + info.assign("title", sourcemeta::core::JSON{"Shared " + number}); + info.assign("version", sourcemeta::core::JSON{"1.0.0"}); + + auto document{sourcemeta::core::JSON::make_object()}; + document.assign("openapi", sourcemeta::core::JSON{"3.1.1"}); + document.assign("info", std::move(info)); + document.assign("components", std::move(components)); + return document; +} + +using SharedDocument = std::pair; + +static auto make_shared_documents() -> std::vector { + std::vector result; + result.reserve(SHARED_COUNT); + for (std::size_t index = 0; index < SHARED_COUNT; index += 1) { + result.emplace_back(shared_identifier(index), make_shared_document(index)); + } + return result; +} + +// The resolver below runs inside the timed loop, so each document is stored +// against the identifier it answers to rather than having one built per +// candidate on every lookup +static auto shared_documents() -> const std::vector & { + static const std::vector INSTANCE{make_shared_documents()}; + return INSTANCE; +} + +static auto bundle_resolver(const std::string_view identifier) + -> sourcemeta::core::OpenAPIResolverResult { + for (const auto &entry : shared_documents()) { + if (identifier == entry.first) { + return entry.second; + } + } + + return std::nullopt; +} + +static auto make_split_description() -> sourcemeta::core::JSON { + auto paths{sourcemeta::core::JSON::make_object()}; + for (std::size_t index = 0; index < PATH_COUNT; index += 1) { + const auto shared{shared_identifier(index % SHARED_COUNT)}; + + auto response{sourcemeta::core::JSON::make_object()}; + response.assign("$ref", sourcemeta::core::JSON{ + shared + "#/components/responses/Thing"}); + auto responses{sourcemeta::core::JSON::make_object()}; + responses.assign("200", std::move(response)); + + auto schema{sourcemeta::core::JSON::make_object()}; + schema.assign( + "$ref", sourcemeta::core::JSON{shared + "#/components/schemas/Thing"}); + auto media{sourcemeta::core::JSON::make_object()}; + media.assign("schema", std::move(schema)); + auto content{sourcemeta::core::JSON::make_object()}; + content.assign("application/json", std::move(media)); + auto body{sourcemeta::core::JSON::make_object()}; + body.assign("content", std::move(content)); + + auto operation{sourcemeta::core::JSON::make_object()}; + operation.assign("operationId", + sourcemeta::core::JSON{"thing" + std::to_string(index)}); + operation.assign("requestBody", std::move(body)); + operation.assign("responses", std::move(responses)); + + auto item{sourcemeta::core::JSON::make_object()}; + item.assign("post", std::move(operation)); + paths.assign("/thing-" + std::to_string(index), std::move(item)); + } + + auto info{sourcemeta::core::JSON::make_object()}; + info.assign("title", sourcemeta::core::JSON{"Split"}); + info.assign("version", sourcemeta::core::JSON{"1.0.0"}); + + auto document{sourcemeta::core::JSON::make_object()}; + document.assign("openapi", sourcemeta::core::JSON{"3.1.1"}); + document.assign("info", std::move(info)); + document.assign("paths", std::move(paths)); + return document; +} + +BENCHMARK(OpenAPI_Bundle_Split_3_1) { + const auto document{make_split_description()}; + + for (auto iteration : state) { + auto result{sourcemeta::core::openapi_bundle( + document, sourcemeta::core::schema_walker, + sourcemeta::core::schema_resolver, bundle_resolver)}; + assert(result.is_object()); + assert(result.at("paths").size() == PATH_COUNT); + assert(result.at("components").at("responses").size() == SHARED_COUNT); + assert(result.at("components").at("schemas").size() == SHARED_COUNT); + sourcemeta::core::benchmark_do_not_optimize(result); + } +} diff --git a/benchmark/spec/yaml.cc b/benchmark/spec/yaml.cc new file mode 100644 index 000000000..a36560407 --- /dev/null +++ b/benchmark/spec/yaml.cc @@ -0,0 +1,92 @@ +#include + +#include // assert +#include // std::size_t +#include // std::string, std::to_string + +#include +#include + +// The record count sets how much of each construct the parser walks over, so +// it is the knob to turn when stress testing this functionality +static constexpr std::size_t RECORD_COUNT{128}; +static constexpr std::size_t PARAGRAPH_COUNT{256}; + +// A record carries one of every shape the block parser branches on: plain, +// single quoted and double quoted scalars, a literal and a folded block +// scalar, a flow sequence, a flow mapping, and a nested block sequence of +// block mappings +static auto append_record(std::string &result, const std::size_t index) + -> void { + const auto number{std::to_string(index)}; + result.append(" - name: record-"); + result.append(number); + result.append("\n identifier: "); + result.append(number); + result.append("\n enabled: true\n ratio: 0."); + result.append(number); + result.append("\n title: \"Quoted title "); + result.append(number); + result.append("\"\n summary: 'Single quoted summary "); + result.append(number); + result.append("'\n description: |\n A literal block scalar for " + "record "); + result.append(number); + result.append(".\n" + " It keeps every line break it was given, and carries\n" + " on for several lines so that scanning one costs\n" + " something worth measuring.\n" + " abstract: >\n" + " A folded block scalar whose lines are joined into a\n" + " single paragraph unless one of them is indented\n" + " further than the rest.\n" + " tags: [ alpha, beta, gamma ]\n" + " limits: { soft: 10, hard: 20 }\n" + " history:\n" + " - at: 2020-01-01\n" + " note: created\n" + " - at: 2021-06-15\n" + " note: updated\n"); +} + +BENCHMARK(YAML_Parse_Records) { + std::string input{"records:\n"}; + for (std::size_t index = 0; index < RECORD_COUNT; index += 1) { + append_record(input, index); + } + + for (auto iteration : state) { + auto result{sourcemeta::core::parse_yaml(input)}; + assert(result.is_object()); + assert(result.at("records").size() == RECORD_COUNT); + assert(result.at("records").at(0).at("history").size() == 2); + assert(result.at("records").at(0).at("tags").size() == 3); + assert(result.at("records").at(0).at("limits").size() == 2); + sourcemeta::core::benchmark_do_not_optimize(result); + } +} + +// A document that is almost entirely block scalars, so that what this measures +// is scanning them rather than the surrounding mapping +BENCHMARK(YAML_Parse_Block_Scalars) { + std::string input{"paragraphs:\n"}; + for (std::size_t index = 0; index < PARAGRAPH_COUNT; index += 1) { + const auto number{std::to_string(index)}; + input.append(" paragraph-") + .append(number) + .append(": |-\n The first line of paragraph ") + .append(number) + .append(".\n" + " A second line that carries on from it.\n" + " A third line, indented the same as the rest.\n" + " A fourth line indented further than the rest.\n" + " A fifth line back at the original indentation.\n"); + } + + for (auto iteration : state) { + auto result{sourcemeta::core::parse_yaml(input)}; + assert(result.is_object()); + assert(result.at("paragraphs").size() == PARAGRAPH_COUNT); + sourcemeta::core::benchmark_do_not_optimize(result); + } +} diff --git a/cmake/common/clang-tidy.json b/cmake/common/clang-tidy.json index 89118a781..995646242 100644 --- a/cmake/common/clang-tidy.json +++ b/cmake/common/clang-tidy.json @@ -1,11 +1,13 @@ { - "Checks": "-*,bugprone-*,cert-*,concurrency-*,cppcoreguidelines-*,google-*,hicpp-*,misc-*,modernize-*,performance-*,portability-*,readability-*,llvm-namespace-comment,-readability-avoid-const-params-in-decls,-llvm-prefer-static-over-anonymous-namespace,-hicpp-multiway-paths-covered,-cppcoreguidelines-pro-bounds-avoid-unchecked-container-access,-cppcoreguidelines-pro-bounds-pointer-arithmetic,-cppcoreguidelines-pro-bounds-constant-array-index,-cppcoreguidelines-pro-bounds-array-to-pointer-decay,-hicpp-no-array-decay,-cppcoreguidelines-avoid-goto,-hicpp-avoid-goto,-readability-magic-numbers,-cppcoreguidelines-avoid-magic-numbers,-cppcoreguidelines-macro-usage,-misc-no-recursion,-cppcoreguidelines-pro-type-reinterpret-cast,-cppcoreguidelines-pro-type-union-access,-cppcoreguidelines-pro-type-vararg,-hicpp-vararg,-cppcoreguidelines-owning-memory,-misc-non-private-member-variables-in-classes,-cppcoreguidelines-non-private-member-variables-in-classes,-llvm-header-guard,-readability-use-anyofallof,-readability-use-concise-preprocessor-directives,-hicpp-signed-bitwise,-bugprone-easily-swappable-parameters,-google-objc-*,-google-readability-todo,-google-readability-avoid-underscore-in-googletest-name,-misc-include-cleaner,-modernize-use-std-numbers,-bugprone-exception-escape,-bugprone-macro-parentheses,-bugprone-unchecked-optional-access,-cert-dcl59-cpp,-cert-err33-c,-concurrency-mt-unsafe,-cppcoreguidelines-avoid-c-arrays,-cppcoreguidelines-avoid-const-or-ref-data-members,-cppcoreguidelines-avoid-non-const-global-variables,-cppcoreguidelines-init-variables,-cppcoreguidelines-no-malloc,-cppcoreguidelines-prefer-member-initializer,-cppcoreguidelines-pro-type-const-cast,-cppcoreguidelines-pro-type-member-init,-cppcoreguidelines-rvalue-reference-param-not-moved,-cppcoreguidelines-special-member-functions,-google-build-namespaces,-google-build-using-namespace,-google-explicit-constructor,-google-runtime-int,-hicpp-avoid-c-arrays,-hicpp-exception-baseclass,-hicpp-explicit-conversions,-hicpp-invalid-access-moved,-hicpp-member-init,-hicpp-named-parameter,-hicpp-no-malloc,-hicpp-special-member-functions,-hicpp-uppercase-literal-suffix,-misc-anonymous-namespace-in-header,-misc-const-correctness,-misc-definitions-in-headers,-misc-misplaced-const,-misc-multiple-inheritance,-misc-redundant-expression,-misc-use-anonymous-namespace,-misc-use-internal-linkage,-modernize-use-ranges,-modernize-use-trailing-return-type,-performance-no-automatic-move,-readability-avoid-nested-conditional-operator,-readability-container-contains,-readability-convert-member-functions-to-static,-readability-function-cognitive-complexity,-readability-named-parameter,-readability-redundant-casting,-readability-redundant-member-init,-readability-redundant-string-init,-readability-simplify-boolean-expr,-readability-static-accessed-through-instance,-readability-suspicious-call-argument,-readability-uppercase-literal-suffix", + "Checks": "-*,bugprone-*,cert-*,concurrency-*,cppcoreguidelines-*,google-*,hicpp-*,misc-*,modernize-*,performance-*,portability-*,readability-*,llvm-namespace-comment,-readability-avoid-const-params-in-decls,-llvm-prefer-static-over-anonymous-namespace,-hicpp-multiway-paths-covered,-cppcoreguidelines-pro-bounds-avoid-unchecked-container-access,-cppcoreguidelines-pro-bounds-pointer-arithmetic,-cppcoreguidelines-pro-bounds-constant-array-index,-cppcoreguidelines-pro-bounds-array-to-pointer-decay,-hicpp-no-array-decay,-cppcoreguidelines-avoid-goto,-hicpp-avoid-goto,-readability-magic-numbers,-cppcoreguidelines-avoid-magic-numbers,-cppcoreguidelines-macro-usage,-misc-no-recursion,-cppcoreguidelines-pro-type-reinterpret-cast,-cppcoreguidelines-pro-type-union-access,-cppcoreguidelines-pro-type-vararg,-hicpp-vararg,-cppcoreguidelines-owning-memory,-misc-non-private-member-variables-in-classes,-cppcoreguidelines-non-private-member-variables-in-classes,-llvm-header-guard,-readability-use-anyofallof,-readability-use-concise-preprocessor-directives,-hicpp-signed-bitwise,-bugprone-easily-swappable-parameters,-google-objc-*,-google-readability-todo,-google-readability-avoid-underscore-in-googletest-name,-misc-include-cleaner,-modernize-use-std-numbers,-bugprone-exception-escape,-bugprone-macro-parentheses,-bugprone-unchecked-optional-access,-cert-dcl59-cpp,-cert-err33-c,-concurrency-mt-unsafe,-cppcoreguidelines-avoid-c-arrays,-cppcoreguidelines-avoid-const-or-ref-data-members,-cppcoreguidelines-avoid-non-const-global-variables,-cppcoreguidelines-init-variables,-cppcoreguidelines-no-malloc,-cppcoreguidelines-prefer-member-initializer,-cppcoreguidelines-pro-type-const-cast,-cppcoreguidelines-pro-type-member-init,-cppcoreguidelines-rvalue-reference-param-not-moved,-cppcoreguidelines-special-member-functions,-google-build-namespaces,-google-build-using-namespace,-google-explicit-constructor,-google-runtime-int,-hicpp-avoid-c-arrays,-hicpp-exception-baseclass,-hicpp-explicit-conversions,-hicpp-invalid-access-moved,-hicpp-member-init,-hicpp-named-parameter,-hicpp-no-malloc,-hicpp-special-member-functions,-hicpp-uppercase-literal-suffix,-misc-anonymous-namespace-in-header,-misc-const-correctness,-misc-definitions-in-headers,-misc-misplaced-const,-misc-multiple-inheritance,-misc-redundant-expression,-misc-use-anonymous-namespace,-misc-use-internal-linkage,-modernize-use-ranges,-modernize-use-trailing-return-type,-performance-no-automatic-move,-readability-avoid-nested-conditional-operator,-readability-container-contains,-readability-convert-member-functions-to-static,-readability-named-parameter,-readability-redundant-casting,-readability-redundant-member-init,-readability-redundant-string-init,-readability-simplify-boolean-expr,-readability-static-accessed-through-instance,-readability-suspicious-call-argument,-readability-uppercase-literal-suffix", "WarningsAsErrors": "*", "FormatStyle": "none", "UseColor": true, "CheckOptions": { "bugprone-empty-catch.IgnoreCatchWithKeywords": "@TODO;@FIXME;expected", "portability-restrict-system-includes.Includes": "*,-expected", + "readability-function-cognitive-complexity.IgnoreMacros": "true", + "readability-function-cognitive-complexity.Threshold": "100", "readability-identifier-length.IgnoredVariableNames": "^([a-h]|[x-z]|r|s|iv|IV)$", "readability-identifier-length.IgnoredParameterNames": "^(iv|n|x|y)$", "readability-identifier-naming.NamespaceCase": "lower_case", diff --git a/src/spec/gzip/inflate.h b/src/spec/gzip/inflate.h index 70063eec8..9da8c7777 100644 --- a/src/spec/gzip/inflate.h +++ b/src/spec/gzip/inflate.h @@ -1320,6 +1320,46 @@ class InflateDecoder { return this->decode_huffman_careful(buffers); } + // A run of literals from the primary table, which the margins let this + // emit without re-checking the buffers between them. Answers whether + // the decode loop carries on + static auto decode_literal_run( + const std::uint32_t *const literal_length_table, + std::uint64_t &bit_buffer, unsigned int &bits_available, + const std::uint8_t *&input_next, const std::uint8_t *const input_limit, + std::uint8_t *&output_next, const std::uint8_t *const output_limit, + std::uint32_t &entry) -> bool { + // Every literal leaves the entry of the next symbol loaded, and a + // refill only appends bits past the ones that entry was read from + bit_buffer >>= entry & 0x3fU; + bits_available -= entry; + *output_next++ = static_cast(entry >> 16); + entry = literal_length_table[low_bits(bit_buffer, + INFLATE_LITERAL_LENGTH_TABLE_BITS)]; + if ((entry & INFLATE_ENTRY_LITERAL) != 0) { + bit_buffer >>= entry & 0x3fU; + bits_available -= entry; + *output_next++ = static_cast(entry >> 16); + entry = literal_length_table[low_bits(bit_buffer, + INFLATE_LITERAL_LENGTH_TABLE_BITS)]; + if ((entry & INFLATE_ENTRY_LITERAL) != 0) { + bit_buffer >>= entry & 0x3fU; + bits_available -= entry; + *output_next++ = static_cast(entry >> 16); + entry = literal_length_table[low_bits( + bit_buffer, INFLATE_LITERAL_LENGTH_TABLE_BITS)]; + } + } + + if (input_next >= input_limit || output_next >= output_limit) { + return false; + } + + bit_buffer |= load_word(input_next) << (bits_available & 63U); + input_next += (63U - (bits_available & 63U)) >> 3; + bits_available |= 56; + return true; + } // Returns whether the block ended auto decode_huffman_fast(InflateBuffers &buffers) -> bool { const auto *literal_length_table{this->literal_length_table_.data()}; @@ -1349,35 +1389,12 @@ class InflateDecoder { bit_buffer, INFLATE_LITERAL_LENGTH_TABLE_BITS)]}; while (true) { if ((entry & INFLATE_ENTRY_LITERAL) != 0) { - // Every literal leaves the entry of the next symbol loaded, and a - // refill only appends bits past the ones that entry was read from - bit_buffer >>= entry & 0x3fU; - bits_available -= entry; - *output_next++ = static_cast(entry >> 16); - entry = literal_length_table[low_bits( - bit_buffer, INFLATE_LITERAL_LENGTH_TABLE_BITS)]; - if ((entry & INFLATE_ENTRY_LITERAL) != 0) { - bit_buffer >>= entry & 0x3fU; - bits_available -= entry; - *output_next++ = static_cast(entry >> 16); - entry = literal_length_table[low_bits( - bit_buffer, INFLATE_LITERAL_LENGTH_TABLE_BITS)]; - if ((entry & INFLATE_ENTRY_LITERAL) != 0) { - bit_buffer >>= entry & 0x3fU; - bits_available -= entry; - *output_next++ = static_cast(entry >> 16); - entry = literal_length_table[low_bits( - bit_buffer, INFLATE_LITERAL_LENGTH_TABLE_BITS)]; - } - } - - if (input_next >= input_limit || output_next >= output_limit) { + if (!decode_literal_run(literal_length_table, bit_buffer, + bits_available, input_next, input_limit, + output_next, output_limit, entry)) { break; } - bit_buffer |= load_word(input_next) << (bits_available & 63U); - input_next += (63U - (bits_available & 63U)) >> 3; - bits_available |= 56; continue; } diff --git a/src/spec/jsonld/jsonld_compaction.cc b/src/spec/jsonld/jsonld_compaction.cc index d45700dc5..005f0845b 100644 --- a/src/spec/jsonld/jsonld_compaction.cc +++ b/src/spec/jsonld/jsonld_compaction.cc @@ -84,6 +84,397 @@ auto nest_target(JSON &result, const TermDefinition *const definition, return result.at(key); } +// The @graph container case of placing an item into the compacted +// result (JSON-LD 1.1 API Section 6.1.2) +auto compact_graph_container(ExpansionState &state, + const ActiveContext &node_context, + const JSON &node_inverse, + const bool compact_arrays, const JSON &item, + const JSON::String &item_property, + const TermDefinition *const item_definition, + JSON &target) -> void { + const bool graph_as_array{container_includes(item_definition, KEYWORD_SET) || + !compact_arrays}; + const bool by_id{container_includes(item_definition, KEYWORD_ID)}; + const bool by_index{container_includes(item_definition, KEYWORD_INDEX)}; + const bool simple_graph{!item.defines(KEYWORD_ID, KEYWORD_ID_HASH)}; + auto compacted{compact(state, node_context, node_inverse, item_property, + item.at(KEYWORD_GRAPH, KEYWORD_GRAPH_HASH), + compact_arrays)}; + const auto none_key{compact_iri(node_context, node_inverse, + JSON::String{KEYWORD_NONE}, nullptr, true, + false)}; + if (by_id || (by_index && simple_graph)) { + if (!target.defines(item_property)) { + target.assign_assume_new(item_property, JSON::make_object()); + } + JSON::String key{none_key}; + if (by_id && item.defines(KEYWORD_ID, KEYWORD_ID_HASH)) { + key = compact_iri(node_context, node_inverse, + item.at(KEYWORD_ID, KEYWORD_ID_HASH).to_string(), + nullptr, false, false); + } else if (by_index && item.defines(KEYWORD_INDEX, KEYWORD_INDEX_HASH)) { + key = item.at(KEYWORD_INDEX, KEYWORD_INDEX_HASH).to_string(); + } + // The graph value is already compacted to an array when the term has + // an @set container or compactArrays is false, so it is added as-is. + add_value(target.at(item_property), key, std::move(compacted), false); + return; + } + if (simple_graph) { + // A single node is inlined, several are wrapped in an @included + // block. + if (compacted.is_array() && compacted.size() != 1) { + const auto included_alias{compact_iri(node_context, node_inverse, + JSON::String{KEYWORD_INCLUDED}, + nullptr, true, false)}; + auto wrapper{JSON::make_object()}; + wrapper.assign_assume_new(included_alias, std::move(compacted)); + compacted = std::move(wrapper); + } else if (compacted.is_array()) { + auto single{compacted.front()}; + compacted = std::move(single); + } + add_value(target, item_property, std::move(compacted), graph_as_array); + return; + } + // Wrap a graph object that retains its @id back into a graph object. + const auto graph_alias{compact_iri(node_context, node_inverse, + JSON::String{KEYWORD_GRAPH}, nullptr, true, + false)}; + auto wrapper{JSON::make_object()}; + const auto id_alias{compact_iri(node_context, node_inverse, + JSON::String{KEYWORD_ID}, nullptr, true, + false)}; + wrapper.assign_assume_new( + id_alias, + JSON{compact_iri(node_context, node_inverse, + item.at(KEYWORD_ID, KEYWORD_ID_HASH).to_string(), + nullptr, false, false)}); + if (item.defines(KEYWORD_INDEX, KEYWORD_INDEX_HASH)) { + const auto index_alias{compact_iri(node_context, node_inverse, + JSON::String{KEYWORD_INDEX}, nullptr, + true, false)}; + wrapper.assign_assume_new(index_alias, + JSON{item.at(KEYWORD_INDEX, KEYWORD_INDEX_HASH)}); + } + wrapper.assign_assume_new(graph_alias, std::move(compacted)); + add_value(target, item_property, std::move(wrapper), graph_as_array); +} + +// The @list container case of placing an item into the compacted +// result (JSON-LD 1.1 API Section 6.1.2) +auto compact_list_container(ExpansionState &state, + const ActiveContext &node_context, + const JSON &node_inverse, const bool compact_arrays, + const JSON &item, const JSON::String &item_property, + const TermDefinition *const item_definition, + const bool is_list, JSON &target) -> void { + const auto &list_value{is_list ? item.at(KEYWORD_LIST, KEYWORD_LIST_HASH) + : item}; + // JSON-LD 1.0 forbids a list of lists. + if (state.processing_1_0 && list_value.is_array()) { + for (const auto &member : list_value.as_array()) { + // As above, a list holds maps + assert(member.is_object()); + if (member.defines(KEYWORD_LIST, KEYWORD_LIST_HASH)) { + throw JSONLDError("Compaction to list of lists", EMPTY_WEAK_POINTER); + } + } + } + auto compacted{compact(state, node_context, node_inverse, item_property, + list_value, compact_arrays)}; + if (!compacted.is_array()) { + auto array{JSON::make_array()}; + array.push_back(std::move(compacted)); + compacted = std::move(array); + } + if (container_includes(item_definition, KEYWORD_LIST)) { + add_value(target, item_property, std::move(compacted), + container_includes(item_definition, KEYWORD_SET)); + } else { + const auto list_alias{compact_iri(node_context, node_inverse, + JSON::String{KEYWORD_LIST}, nullptr, true, + false)}; + auto list_object{JSON::make_object()}; + list_object.assign_assume_new(list_alias, std::move(compacted)); + if (item.defines(KEYWORD_INDEX, KEYWORD_INDEX_HASH)) { + const auto index_alias{compact_iri(node_context, node_inverse, + JSON::String{KEYWORD_INDEX}, nullptr, + true, false)}; + list_object.assign_assume_new( + index_alias, JSON{item.at(KEYWORD_INDEX, KEYWORD_INDEX_HASH)}); + } + add_value(target, item_property, std::move(list_object), + container_includes(item_definition, KEYWORD_SET) || + !compact_arrays); + } +} + +// The @language container case of placing an item into the compacted +// result (JSON-LD 1.1 API Section 6.1.2) +auto compact_language_container(const JSON &item, + const JSON::String &item_property, JSON &target, + const bool as_array, + const JSON::String &none_key) -> void { + if (!target.defines(item_property)) { + target.assign_assume_new(item_property, JSON::make_object()); + } + const JSON::String key{ + item.defines(KEYWORD_LANGUAGE, KEYWORD_LANGUAGE_HASH) + ? item.at(KEYWORD_LANGUAGE, KEYWORD_LANGUAGE_HASH).to_string() + : none_key}; + add_value(target.at(item_property), key, + JSON{item.at(KEYWORD_VALUE, KEYWORD_VALUE_HASH)}, as_array); +} + +// The @index container case of placing an item into the compacted +// result (JSON-LD 1.1 API Section 6.1.2) +auto compact_index_container(ExpansionState &state, + const ActiveContext &node_context, + const JSON &node_inverse, + const bool compact_arrays, const JSON &item, + const JSON::String &item_property, + const TermDefinition *const item_definition, + JSON &target, const bool as_array, + const JSON::String &none_key) -> void { + if (!target.defines(item_property)) { + target.assign_assume_new(item_property, JSON::make_object()); + } + // The container test above answers false for a definition that is + // not there, so one stands here + assert(item_definition != nullptr); + const bool property_index{item_definition->index_iri.has_value()}; + auto compacted{compact(state, node_context, node_inverse, item_property, item, + compact_arrays)}; + std::optional key; + if (property_index) { + // The index key is the expanded index mapping, compacted to match the + // corresponding property of the compacted item (Section 6.1.2). + const auto container_key{compact_iri(node_context, node_inverse, + item_definition->index_iri.value(), + nullptr, true, false)}; + if (compacted.is_object() && compacted.defines(container_key)) { + auto &values{compacted.at(container_key)}; + if (values.is_array() && !values.empty() && values.front().is_string()) { + key = values.front().to_string(); + if (values.size() == 1) { + compacted.erase(container_key); + } else { + values.erase(values.as_array().cbegin()); + // A lone remaining value collapses to a scalar only when arrays + // are being compacted. + if (compact_arrays && values.size() == 1) { + auto remaining{values.front()}; + values = std::move(remaining); + } + } + } else if (!values.is_array() && values.is_string()) { + key = values.to_string(); + compacted.erase(container_key); + } + } + } else if (item.defines(KEYWORD_INDEX, KEYWORD_INDEX_HASH)) { + key = item.at(KEYWORD_INDEX, KEYWORD_INDEX_HASH).to_string(); + if (compacted.is_object()) { + compacted.erase(compact_iri(node_context, node_inverse, + JSON::String{KEYWORD_INDEX}, nullptr, true, + false)); + } + } + add_value(target.at(item_property), key.value_or(none_key), + std::move(compacted), as_array); +} + +// The @id container case of placing an item into the compacted +// result (JSON-LD 1.1 API Section 6.1.2) +auto compact_id_container(ExpansionState &state, + const ActiveContext &node_context, + const JSON &node_inverse, const bool compact_arrays, + const JSON &item, const JSON::String &item_property, + JSON &target, const bool as_array, + const JSON::String &none_key) -> void { + if (!target.defines(item_property)) { + target.assign_assume_new(item_property, JSON::make_object()); + } + auto compacted{compact(state, node_context, node_inverse, item_property, item, + compact_arrays)}; + const auto id_alias{compact_iri(node_context, node_inverse, + JSON::String{KEYWORD_ID}, nullptr, true, + false)}; + JSON::String key{none_key}; + if (compacted.is_object()) { + // An identifier compacts to a name, so the entry it stands under + // holds a string wherever the member carries one + const auto *identifier{compacted.try_at(id_alias)}; + assert(identifier == nullptr || identifier->is_string()); + if (identifier != nullptr) { + key = identifier->to_string(); + compacted.erase(id_alias); + } + } + add_value(target.at(item_property), key, std::move(compacted), as_array); +} + +// The @type container case of placing an item into the compacted +// result (JSON-LD 1.1 API Section 6.1.2) +auto compact_type_container(ExpansionState &state, + const ActiveContext &node_context, + const JSON &node_inverse, const bool compact_arrays, + const JSON &item, const JSON::String &item_property, + const TermDefinition *const item_definition, + JSON &target, const bool as_array, + const JSON::String &none_key) -> void { + if (!target.defines(item_property)) { + target.assign_assume_new(item_property, JSON::make_object()); + } + JSON::String key{none_key}; + if (item.defines(KEYWORD_TYPE, KEYWORD_TYPE_HASH) && + !item.at(KEYWORD_TYPE, KEYWORD_TYPE_HASH).empty()) { + key = compact_iri( + node_context, node_inverse, + item.at(KEYWORD_TYPE, KEYWORD_TYPE_HASH).front().to_string(), nullptr, + true, false); + } + auto compacted{compact(state, node_context, node_inverse, item_property, item, + compact_arrays)}; + if (compacted.is_object()) { + const auto type_alias{compact_iri(node_context, node_inverse, + JSON::String{KEYWORD_TYPE}, nullptr, true, + false)}; + if (compacted.defines(type_alias)) { + auto &types{compacted.at(type_alias)}; + if (!types.is_array() || types.size() <= 1) { + compacted.erase(type_alias); + } else { + types.erase(types.as_array().cbegin()); + // A lone remaining type collapses to a scalar only when arrays + // are being compacted. + if (compact_arrays && types.size() == 1) { + auto remaining{types.front()}; + types = std::move(remaining); + } + } + } + // A node left with only an @id reduces to that identifier, compacted + // with vocab when the term coerces @vocab. + const auto id_alias{compact_iri(node_context, node_inverse, + JSON::String{KEYWORD_ID}, nullptr, true, + false)}; + // A node left with only an @id reduces to that identifier, compacted + // with vocab when the term coerces @vocab. The entry it was left + // with was compacted from the item's own, so the item carries one + // too, and the container test above answers false for a definition + // that is not there, which a type container also gives a type + // mapping (JSON-LD 1.1 API Section 4.2.2 step 21.4.1) + assert(!(compacted.object_size() == 1 && compacted.defines(id_alias)) || + item.defines(KEYWORD_ID, KEYWORD_ID_HASH)); + if (compacted.object_size() == 1 && compacted.defines(id_alias)) { + assert(item_definition != nullptr && + item_definition->type_mapping.has_value()); + const bool vocab{item_definition->type_mapping.value() == KEYWORD_VOCAB}; + compacted = + JSON{compact_iri(node_context, node_inverse, + item.at(KEYWORD_ID, KEYWORD_ID_HASH).to_string(), + nullptr, vocab, false)}; + } + } + add_value(target.at(item_property), key, std::move(compacted), as_array); +} +// The loop that places each item a property holds into the compacted +// result, one case per container the term declares (JSON-LD 1.1 API +// Section 6.1.2) +auto compact_property_items(ExpansionState &state, + const ActiveContext &node_context, + const JSON &node_inverse, const bool compact_arrays, + const JSON::String &expanded_property, + const JSON &expanded_value, + const bool inside_reverse, JSON &result) -> void { + for (const auto &item : expanded_value.as_array()) { + // What a property holds in expanded form is maps, which the entry point + // holds the input to before any of this runs + assert(item.is_object()); + const auto item_property{compact_iri(node_context, node_inverse, + expanded_property, &item, true, + inside_reverse)}; + const auto *item_definition{definition_for(node_context, item_property)}; + const bool is_list{item.defines(KEYWORD_LIST, KEYWORD_LIST_HASH)}; + const bool is_graph_object{item.defines(KEYWORD_GRAPH, KEYWORD_GRAPH_HASH)}; + JSON &target{ + nest_target(result, item_definition, node_context, node_inverse)}; + + // @graph container: a simple graph object (without @id) is mapped by @id + // or @index or inlined; a graph object carrying an @id that is not keyed + // by @id is wrapped back into a graph object (Section 6.1.2). + if (container_includes(item_definition, KEYWORD_GRAPH) && is_graph_object) { + compact_graph_container(state, node_context, node_inverse, compact_arrays, + item, item_property, item_definition, target); + continue; + } + + if (container_includes(item_definition, KEYWORD_LIST) || is_list) { + compact_list_container(state, node_context, node_inverse, compact_arrays, + item, item_property, item_definition, is_list, + target); + continue; + } + + const bool as_array{container_includes(item_definition, KEYWORD_SET) || + !compact_arrays}; + + const auto none_key{compact_iri(node_context, node_inverse, + JSON::String{KEYWORD_NONE}, nullptr, true, + false)}; + + // @language map container: index value objects by their language. + if (container_includes(item_definition, KEYWORD_LANGUAGE) && + item.defines(KEYWORD_VALUE, KEYWORD_VALUE_HASH)) { + compact_language_container(item, item_property, target, as_array, + none_key); + continue; + } + + // @index map container: index by the item's @index, or for a + // property-valued index by the value of that property in the compacted + // item (Section 6.1.2). + if (container_includes(item_definition, KEYWORD_INDEX)) { + compact_index_container(state, node_context, node_inverse, compact_arrays, + item, item_property, item_definition, target, + as_array, none_key); + continue; + } + + // @id map container: the key is the identifier the member carries once + // compacted, which is where the step reads it from, so a member that + // compacted to anything other than a map carries no identifier to key + // by and stands under the none label (Section 6.1.2) + if (container_includes(item_definition, KEYWORD_ID)) { + compact_id_container(state, node_context, node_inverse, compact_arrays, + item, item_property, target, as_array, none_key); + continue; + } + + // @type map container: index node objects by their first type. + if (container_includes(item_definition, KEYWORD_TYPE)) { + compact_type_container(state, node_context, node_inverse, compact_arrays, + item, item_property, item_definition, target, + as_array, none_key); + continue; + } + + auto compacted{compact(state, node_context, node_inverse, item_property, + item, compact_arrays)}; + // A compacted JSON literal may itself be an array, in which case its + // members are added individually rather than nesting another array. + if (compacted.is_array()) { + for (const auto &member : compacted.as_array()) { + add_value(target, item_property, JSON{member}, as_array); + } + } else { + add_value(target, item_property, std::move(compacted), as_array); + } + } +} } // namespace auto compact(ExpansionState &state, const ActiveContext &active_context, @@ -357,322 +748,9 @@ auto compact(ExpansionState &state, const ActiveContext &active_context, continue; } - for (const auto &item : expanded_value.as_array()) { - // What a property holds in expanded form is maps, which the entry point - // holds the input to before any of this runs - assert(item.is_object()); - const auto item_property{compact_iri(node_context, node_inverse, - expanded_property, &item, true, - inside_reverse)}; - const auto *item_definition{definition_for(node_context, item_property)}; - const bool is_list{item.defines(KEYWORD_LIST, KEYWORD_LIST_HASH)}; - const bool is_graph_object{ - item.defines(KEYWORD_GRAPH, KEYWORD_GRAPH_HASH)}; - JSON &target{ - nest_target(result, item_definition, node_context, node_inverse)}; - - // @graph container: a simple graph object (without @id) is mapped by @id - // or @index or inlined; a graph object carrying an @id that is not keyed - // by @id is wrapped back into a graph object (Section 6.1.2). - if (container_includes(item_definition, KEYWORD_GRAPH) && - is_graph_object) { - const bool graph_as_array{ - container_includes(item_definition, KEYWORD_SET) || - !compact_arrays}; - const bool by_id{container_includes(item_definition, KEYWORD_ID)}; - const bool by_index{container_includes(item_definition, KEYWORD_INDEX)}; - const bool simple_graph{!item.defines(KEYWORD_ID, KEYWORD_ID_HASH)}; - auto compacted{compact(state, node_context, node_inverse, item_property, - item.at(KEYWORD_GRAPH, KEYWORD_GRAPH_HASH), - compact_arrays)}; - const auto none_key{compact_iri(node_context, node_inverse, - JSON::String{KEYWORD_NONE}, nullptr, - true, false)}; - if (by_id || (by_index && simple_graph)) { - if (!target.defines(item_property)) { - target.assign_assume_new(item_property, JSON::make_object()); - } - JSON::String key{none_key}; - if (by_id && item.defines(KEYWORD_ID, KEYWORD_ID_HASH)) { - key = compact_iri(node_context, node_inverse, - item.at(KEYWORD_ID, KEYWORD_ID_HASH).to_string(), - nullptr, false, false); - } else if (by_index && - item.defines(KEYWORD_INDEX, KEYWORD_INDEX_HASH)) { - key = item.at(KEYWORD_INDEX, KEYWORD_INDEX_HASH).to_string(); - } - // The graph value is already compacted to an array when the term has - // an @set container or compactArrays is false, so it is added as-is. - add_value(target.at(item_property), key, std::move(compacted), false); - continue; - } - if (simple_graph) { - // A single node is inlined, several are wrapped in an @included - // block. - if (compacted.is_array() && compacted.size() != 1) { - const auto included_alias{compact_iri( - node_context, node_inverse, JSON::String{KEYWORD_INCLUDED}, - nullptr, true, false)}; - auto wrapper{JSON::make_object()}; - wrapper.assign_assume_new(included_alias, std::move(compacted)); - compacted = std::move(wrapper); - } else if (compacted.is_array()) { - auto single{compacted.front()}; - compacted = std::move(single); - } - add_value(target, item_property, std::move(compacted), - graph_as_array); - continue; - } - // Wrap a graph object that retains its @id back into a graph object. - const auto graph_alias{compact_iri(node_context, node_inverse, - JSON::String{KEYWORD_GRAPH}, nullptr, - true, false)}; - auto wrapper{JSON::make_object()}; - const auto id_alias{compact_iri(node_context, node_inverse, - JSON::String{KEYWORD_ID}, nullptr, true, - false)}; - wrapper.assign_assume_new( - id_alias, - JSON{compact_iri(node_context, node_inverse, - item.at(KEYWORD_ID, KEYWORD_ID_HASH).to_string(), - nullptr, false, false)}); - if (item.defines(KEYWORD_INDEX, KEYWORD_INDEX_HASH)) { - const auto index_alias{compact_iri(node_context, node_inverse, - JSON::String{KEYWORD_INDEX}, - nullptr, true, false)}; - wrapper.assign_assume_new( - index_alias, JSON{item.at(KEYWORD_INDEX, KEYWORD_INDEX_HASH)}); - } - wrapper.assign_assume_new(graph_alias, std::move(compacted)); - add_value(target, item_property, std::move(wrapper), graph_as_array); - continue; - } - - if (container_includes(item_definition, KEYWORD_LIST) || is_list) { - const auto &list_value{ - is_list ? item.at(KEYWORD_LIST, KEYWORD_LIST_HASH) : item}; - // JSON-LD 1.0 forbids a list of lists. - if (state.processing_1_0 && list_value.is_array()) { - for (const auto &member : list_value.as_array()) { - // As above, a list holds maps - assert(member.is_object()); - if (member.defines(KEYWORD_LIST, KEYWORD_LIST_HASH)) { - throw JSONLDError("Compaction to list of lists", - EMPTY_WEAK_POINTER); - } - } - } - auto compacted{compact(state, node_context, node_inverse, item_property, - list_value, compact_arrays)}; - if (!compacted.is_array()) { - auto array{JSON::make_array()}; - array.push_back(std::move(compacted)); - compacted = std::move(array); - } - if (container_includes(item_definition, KEYWORD_LIST)) { - add_value(target, item_property, std::move(compacted), - container_includes(item_definition, KEYWORD_SET)); - } else { - const auto list_alias{compact_iri(node_context, node_inverse, - JSON::String{KEYWORD_LIST}, nullptr, - true, false)}; - auto list_object{JSON::make_object()}; - list_object.assign_assume_new(list_alias, std::move(compacted)); - if (item.defines(KEYWORD_INDEX, KEYWORD_INDEX_HASH)) { - const auto index_alias{compact_iri(node_context, node_inverse, - JSON::String{KEYWORD_INDEX}, - nullptr, true, false)}; - list_object.assign_assume_new( - index_alias, JSON{item.at(KEYWORD_INDEX, KEYWORD_INDEX_HASH)}); - } - add_value(target, item_property, std::move(list_object), - container_includes(item_definition, KEYWORD_SET) || - !compact_arrays); - } - continue; - } - - const bool as_array{container_includes(item_definition, KEYWORD_SET) || - !compact_arrays}; - - const auto none_key{compact_iri(node_context, node_inverse, - JSON::String{KEYWORD_NONE}, nullptr, true, - false)}; - - // @language map container: index value objects by their language. - if (container_includes(item_definition, KEYWORD_LANGUAGE) && - item.defines(KEYWORD_VALUE, KEYWORD_VALUE_HASH)) { - if (!target.defines(item_property)) { - target.assign_assume_new(item_property, JSON::make_object()); - } - const JSON::String key{ - item.defines(KEYWORD_LANGUAGE, KEYWORD_LANGUAGE_HASH) - ? item.at(KEYWORD_LANGUAGE, KEYWORD_LANGUAGE_HASH).to_string() - : none_key}; - add_value(target.at(item_property), key, - JSON{item.at(KEYWORD_VALUE, KEYWORD_VALUE_HASH)}, as_array); - continue; - } - - // @index map container: index by the item's @index, or for a - // property-valued index by the value of that property in the compacted - // item (Section 6.1.2). - if (container_includes(item_definition, KEYWORD_INDEX)) { - if (!target.defines(item_property)) { - target.assign_assume_new(item_property, JSON::make_object()); - } - // The container test above answers false for a definition that is - // not there, so one stands here - assert(item_definition != nullptr); - const bool property_index{item_definition->index_iri.has_value()}; - auto compacted{compact(state, node_context, node_inverse, item_property, - item, compact_arrays)}; - std::optional key; - if (property_index) { - // The index key is the expanded index mapping, compacted to match the - // corresponding property of the compacted item (Section 6.1.2). - const auto container_key{compact_iri( - node_context, node_inverse, item_definition->index_iri.value(), - nullptr, true, false)}; - if (compacted.is_object() && compacted.defines(container_key)) { - auto &values{compacted.at(container_key)}; - if (values.is_array() && !values.empty() && - values.front().is_string()) { - key = values.front().to_string(); - if (values.size() == 1) { - compacted.erase(container_key); - } else { - values.erase(values.as_array().cbegin()); - // A lone remaining value collapses to a scalar only when arrays - // are being compacted. - if (compact_arrays && values.size() == 1) { - auto remaining{values.front()}; - values = std::move(remaining); - } - } - } else if (!values.is_array() && values.is_string()) { - key = values.to_string(); - compacted.erase(container_key); - } - } - } else if (item.defines(KEYWORD_INDEX, KEYWORD_INDEX_HASH)) { - key = item.at(KEYWORD_INDEX, KEYWORD_INDEX_HASH).to_string(); - if (compacted.is_object()) { - compacted.erase(compact_iri(node_context, node_inverse, - JSON::String{KEYWORD_INDEX}, nullptr, - true, false)); - } - } - add_value(target.at(item_property), key.value_or(none_key), - std::move(compacted), as_array); - continue; - } - - // @id map container: the key is the identifier the member carries once - // compacted, which is where the step reads it from, so a member that - // compacted to anything other than a map carries no identifier to key - // by and stands under the none label (Section 6.1.2) - if (container_includes(item_definition, KEYWORD_ID)) { - if (!target.defines(item_property)) { - target.assign_assume_new(item_property, JSON::make_object()); - } - auto compacted{compact(state, node_context, node_inverse, item_property, - item, compact_arrays)}; - const auto id_alias{compact_iri(node_context, node_inverse, - JSON::String{KEYWORD_ID}, nullptr, true, - false)}; - JSON::String key{none_key}; - if (compacted.is_object()) { - // An identifier compacts to a name, so the entry it stands under - // holds a string wherever the member carries one - const auto *identifier{compacted.try_at(id_alias)}; - assert(identifier == nullptr || identifier->is_string()); - if (identifier != nullptr) { - key = identifier->to_string(); - compacted.erase(id_alias); - } - } - add_value(target.at(item_property), key, std::move(compacted), - as_array); - continue; - } - - // @type map container: index node objects by their first type. - if (container_includes(item_definition, KEYWORD_TYPE)) { - if (!target.defines(item_property)) { - target.assign_assume_new(item_property, JSON::make_object()); - } - JSON::String key{none_key}; - if (item.defines(KEYWORD_TYPE, KEYWORD_TYPE_HASH) && - !item.at(KEYWORD_TYPE, KEYWORD_TYPE_HASH).empty()) { - key = compact_iri( - node_context, node_inverse, - item.at(KEYWORD_TYPE, KEYWORD_TYPE_HASH).front().to_string(), - nullptr, true, false); - } - auto compacted{compact(state, node_context, node_inverse, item_property, - item, compact_arrays)}; - if (compacted.is_object()) { - const auto type_alias{compact_iri(node_context, node_inverse, - JSON::String{KEYWORD_TYPE}, nullptr, - true, false)}; - if (compacted.defines(type_alias)) { - auto &types{compacted.at(type_alias)}; - if (!types.is_array() || types.size() <= 1) { - compacted.erase(type_alias); - } else { - types.erase(types.as_array().cbegin()); - // A lone remaining type collapses to a scalar only when arrays - // are being compacted. - if (compact_arrays && types.size() == 1) { - auto remaining{types.front()}; - types = std::move(remaining); - } - } - } - // A node left with only an @id reduces to that identifier, compacted - // with vocab when the term coerces @vocab. - const auto id_alias{compact_iri(node_context, node_inverse, - JSON::String{KEYWORD_ID}, nullptr, - true, false)}; - // A node left with only an @id reduces to that identifier, compacted - // with vocab when the term coerces @vocab. The entry it was left - // with was compacted from the item's own, so the item carries one - // too, and the container test above answers false for a definition - // that is not there, which a type container also gives a type - // mapping (JSON-LD 1.1 API Section 4.2.2 step 21.4.1) - assert( - !(compacted.object_size() == 1 && compacted.defines(id_alias)) || - item.defines(KEYWORD_ID, KEYWORD_ID_HASH)); - if (compacted.object_size() == 1 && compacted.defines(id_alias)) { - assert(item_definition != nullptr && - item_definition->type_mapping.has_value()); - const bool vocab{item_definition->type_mapping.value() == - KEYWORD_VOCAB}; - compacted = JSON{ - compact_iri(node_context, node_inverse, - item.at(KEYWORD_ID, KEYWORD_ID_HASH).to_string(), - nullptr, vocab, false)}; - } - } - add_value(target.at(item_property), key, std::move(compacted), - as_array); - continue; - } - - auto compacted{compact(state, node_context, node_inverse, item_property, - item, compact_arrays)}; - // A compacted JSON literal may itself be an array, in which case its - // members are added individually rather than nesting another array. - if (compacted.is_array()) { - for (const auto &member : compacted.as_array()) { - add_value(target, item_property, JSON{member}, as_array); - } - } else { - add_value(target, item_property, std::move(compacted), as_array); - } - } + compact_property_items(state, node_context, node_inverse, compact_arrays, + expanded_property, expanded_value, inside_reverse, + result); } return result; diff --git a/src/spec/jsonld/jsonld_context_processing.cc b/src/spec/jsonld/jsonld_context_processing.cc index 5c0ed6b9d..783a90999 100644 --- a/src/spec/jsonld/jsonld_context_processing.cc +++ b/src/spec/jsonld/jsonld_context_processing.cc @@ -123,6 +123,326 @@ auto foreign_origin(const ExpansionState &state, const WeakPointer &location) return to_pointer(location); } +// A context named by a string, which is retrieved and processed in place +// of the name (JSON-LD 1.1 API Section 4.1.2) +auto process_remote_context(ExpansionState &state, + ActiveContext &active_context, const JSON &context, + const WeakPointer &location) -> void { + const auto resolved{ + absolute_reference(state.context_resolution_base(), context.to_string())}; + if (!resolved.has_value()) { + throw JSONLDError("Loading document failed", location); + } + + const auto &reference{resolved.value()}; + + bool already_loaded{false}; + for (const auto &loaded : state.remote_context_chain) { + if (loaded == reference) { + already_loaded = true; + break; + } + } + + // A scoped context being validated stops at a reference that is already + // loading rather than treating it as recursion (JSON-LD 1.1 API Section + // 4.1.2 step 5.2.2) + if (already_loaded && !state.validate_scoped_context) { + return; + } + + if (already_loaded) { + // A scoped context can be loaded again on purpose, so JSON-LD 1.1 + // withdrew the recursion error and treats meeting a context already + // in the chain as reaching the limit on how many may be loaded + // (JSON-LD 1.1 API Section 4.1.2 step 5.2.3) + if (state.processing_1_0) { + throw JSONLDError("Recursive context inclusion", location); + } + + throw JSONLDError("Context overflow", location); + } + if (state.remote_context_chain.size() >= + ExpansionState::MAXIMUM_REMOTE_CONTEXTS) { + throw JSONLDError("Context overflow", location); + } + // Step 5.2.4: "If context was previously dereferenced, then the + // processor MUST NOT do a further dereference, and context is set to the + // previously established internal representation", with the note that + // "Only the @context entry need be retained", which is why the cache + // holds that entry rather than the document (JSON-LD 1.1 API + // Section 4.1.2 step 5.2.4) + const auto dereferenced{state.remote_documents.find(reference)}; + const JSON *context_entry{nullptr}; + if (dereferenced != state.remote_documents.cend()) { + context_entry = &dereferenced->second; + } else { + // Every entry point hands the state the address of a resolver, so + // what stands to be settled is whether that resolver holds anything + assert(state.resolver != nullptr); + if (!*state.resolver) { + throw JSONLDError("Loading remote context failed", location); + } + const auto document{resolve(*state.resolver, reference)}; + if (!document.has_value()) { + throw JSONLDError("Loading remote context failed", location); + } + const auto *loaded{ + document->is_object() + ? document->try_at(KEYWORD_CONTEXT, KEYWORD_CONTEXT_HASH) + : nullptr}; + if (loaded == nullptr) { + throw JSONLDError("Invalid remote context", location); + } + context_entry = + &state.remote_documents.emplace(reference, *loaded).first->second; + } + const RemoteContextScope chain{state.remote_context_chain, reference}; + // A scoped context the loaded document defines is processed again when + // its term comes into use, long after this location is out of reach, so + // the reference is recorded for it to report against + const ForeignContextScope origin{state, foreign_origin(state, location)}; + try { + // A loaded remote context is processed with the default propagation. + process_context(state, active_context, *context_entry, location); + } catch (const JSONLDError &error) { + // The offending entries live in the remote document, whose keys have + // no position in the input, so the error is located at the reference + // that loaded it + throw JSONLDError(error.message(), location); + } +} + +// The @import entry of a context, which names a remote context that the +// local one is merged over (JSON-LD 1.1 API Section 4.1.2) +auto process_import(ExpansionState &state, ActiveContext &active_context, + const JSON &context, const WeakPointer &location, + const bool propagate, const bool saved_protected) -> bool { + const auto *import_entry{context.try_at(KEYWORD_IMPORT, KEYWORD_IMPORT_HASH)}; + if (import_entry == nullptr) { + return false; + } + + const auto &import{*import_entry}; + if (!import.is_string()) { + throw JSONLDError("Invalid @import value", location, {KEYWORD_IMPORT}); + } + // What cannot be dereferenced is a loading failure (JSON-LD 1.1 API + // Section 4.1.2 step 5.6.5) + const auto resolved{ + absolute_reference(state.context_resolution_base(), import.to_string())}; + if (!resolved.has_value()) { + throw JSONLDError("Loading remote context failed", location, + {KEYWORD_IMPORT}); + } + + const auto &reference{resolved.value()}; + assert(state.resolver != nullptr); + if (!*state.resolver) { + throw JSONLDError("Loading remote context failed", location, + {KEYWORD_IMPORT}); + } + const auto document{resolve(*state.resolver, reference)}; + if (!document.has_value()) { + throw JSONLDError("Loading remote context failed", location, + {KEYWORD_IMPORT}); + } + const auto *imported_context{ + document->is_object() + ? document->try_at(KEYWORD_CONTEXT, KEYWORD_CONTEXT_HASH) + : nullptr}; + if (imported_context == nullptr || !imported_context->is_object()) { + throw JSONLDError("Invalid remote context", location, {KEYWORD_IMPORT}); + } + if (imported_context->defines(KEYWORD_IMPORT, KEYWORD_IMPORT_HASH)) { + throw JSONLDError("Invalid context entry", location, {KEYWORD_IMPORT}); + } + // Merge the imported entries with the current ones, the current ones + // overriding, and process the result as a single context. + auto merged{JSON{*imported_context}}; + for (const auto &entry : context.as_object()) { + if (!entry.key_equals(KEYWORD_IMPORT, KEYWORD_IMPORT_HASH)) { + merged.assign(entry.first, entry.second); + } + } + // The merged context holds entries from two documents, so a scoped + // context defined among the ones only the imported document carries is + // reported against the entry that merged them in, while the input's own + // entries keep their position + auto import_location{foreign_origin(state, location)}; + if (!state.foreign_context_location.has_value()) { + import_location.value().push_back(JSON::String{KEYWORD_IMPORT}); + } + const ForeignContextScope origin{state, std::move(import_location), &context}; + try { + process_context(state, active_context, merged, location, propagate); + } catch (const JSONLDError &error) { + if (is_input_authored(error, context, location)) { + throw; + } + throw JSONLDError(error.message(), location, {KEYWORD_IMPORT}); + } + state.context_protected = saved_protected; + + return true; +} + +// A null context, which clears the active context (JSON-LD 1.1 API +// Section 4.1.2) +auto process_null_context(ExpansionState &state, ActiveContext &active_context, + const WeakPointer &location, + const bool effective_propagate) -> void { + if (!state.protected_override) { + for (const auto &entry : active_context.terms) { + if (entry.second.is_protected) { + throw JSONLDError("Invalid context nullification", location); + } + } + } + // Nullifying the context resets to the initial context, whose base is + // the document base. The relativise option and the processing mode are + // processing state rather than context state, so they survive the reset. + const bool relativise{active_context.compact_to_relative}; + // What a scope reverts to outlives the nullification inside it, or the + // nodes below would never regain the context the scope was entered from + // (JSON-LD 1.1 API Section 4.1.2 step 5.1.2) + auto saved_previous{effective_propagate ? nullptr : active_context.previous}; + active_context = ActiveContext{}; + active_context.base = state.document_base; + active_context.compact_to_relative = relativise; + active_context.processing_1_0 = state.processing_1_0; + active_context.previous = std::move(saved_previous); +} + +// The @base entry of a context, which a remote context does not carry +// (JSON-LD 1.1 API Section 4.1.2) +auto process_base_entry(ExpansionState &state, ActiveContext &active_context, + const JSON &context, const WeakPointer &location) + -> void { + const auto *base_entry{state.remote_context_chain.empty() + ? context.try_at(KEYWORD_BASE, KEYWORD_BASE_HASH) + : nullptr}; + if (base_entry == nullptr) { + return; + } + + const auto &base{*base_entry}; + if (base.is_null()) { + active_context.base = std::nullopt; + } else if (!base.is_string()) { + throw JSONLDError("Invalid base IRI", location, {KEYWORD_BASE}); + } else { + auto resolved{resolved_base(active_context.base, base.to_string())}; + if (!resolved.has_value()) { + throw JSONLDError("Invalid base IRI", location, {KEYWORD_BASE}); + } + + active_context.base = std::move(resolved); + } +} + +// The @vocab entry of a context (JSON-LD 1.1 API Section 4.1.2) +auto process_vocabulary_entry(ExpansionState &state, + ActiveContext &active_context, + const JSON &context, const WeakPointer &location) + -> void { + const auto *vocabulary_entry{ + context.try_at(KEYWORD_VOCAB, KEYWORD_VOCAB_HASH)}; + if (vocabulary_entry == nullptr) { + return; + } + + const auto &vocabulary{*vocabulary_entry}; + if (vocabulary.is_null()) { + active_context.vocabulary = std::nullopt; + } else if (!vocabulary.is_string()) { + throw JSONLDError("Invalid vocab mapping", location, {KEYWORD_VOCAB}); + } else { + const auto &vocabulary_string{vocabulary.to_string()}; + // In 1.0, @vocab must be an absolute IRI or blank node identifier. + if (state.processing_1_0 && !vocabulary_string.contains(':')) { + throw JSONLDError("Invalid vocab mapping", location, {KEYWORD_VOCAB}); + } + auto mapping{expand_iri(state, active_context, vocabulary_string, true, + true, nullptr, nullptr, EMPTY_WEAK_POINTER)}; + // Step 5.8.3: "If it is not an IRI, or a blank node identifier, an + // invalid vocab mapping error has been detected". The expansion is + // what has to pass, since a relative reference is admitted here and + // resolved against the base (JSON-LD 1.1 API Section 4.1.2 step 5.8.3) + if (!mapping.has_value() || + (!URI::is_iri(mapping.value()) && !is_blank_node(mapping.value()))) { + throw JSONLDError("Invalid vocab mapping", location, {KEYWORD_VOCAB}); + } + active_context.vocabulary = std::move(mapping); + } +} + +// The @language entry of a context (JSON-LD 1.1 API Section 4.1.2) +auto process_language_entry(ActiveContext &active_context, const JSON &context, + const WeakPointer &location) -> void { + const auto *language_entry{ + context.try_at(KEYWORD_LANGUAGE, KEYWORD_LANGUAGE_HASH)}; + if (language_entry == nullptr) { + return; + } + + const auto &language{*language_entry}; + if (language.is_null()) { + active_context.default_language = std::nullopt; + } else if (!language.is_string()) { + throw JSONLDError("Invalid default language", location, {KEYWORD_LANGUAGE}); + } else { + active_context.default_language = language.to_string(); + } +} + +// The @direction entry of a context (JSON-LD 1.1 API Section 4.1.2) +auto process_direction_entry(ExpansionState &state, + ActiveContext &active_context, const JSON &context, + const WeakPointer &location) -> void { + const auto *direction_entry{ + context.try_at(KEYWORD_DIRECTION, KEYWORD_DIRECTION_HASH)}; + if (direction_entry == nullptr) { + return; + } + + if (state.processing_1_0) { + throw JSONLDError("Invalid context entry", location, {KEYWORD_DIRECTION}); + } + + const auto &direction{*direction_entry}; + if (direction.is_null()) { + active_context.default_direction = std::nullopt; + } else if (!direction.is_string()) { + throw JSONLDError("Invalid base direction", location, {KEYWORD_DIRECTION}); + } else { + const auto &direction_string{direction.to_string()}; + if (direction_string != "ltr" && direction_string != "rtl") { + throw JSONLDError("Invalid base direction", location, + {KEYWORD_DIRECTION}); + } + active_context.default_direction = direction_string; + } +} + +// The @propagate entry of a context (JSON-LD 1.1 API Section 4.1.2) +auto process_propagate_entry(ExpansionState &state, const JSON &context, + const WeakPointer &location) -> void { + const auto *propagate_entry{ + context.try_at(KEYWORD_PROPAGATE, KEYWORD_PROPAGATE_HASH)}; + if (propagate_entry == nullptr) { + return; + } + + if (state.processing_1_0) { + throw JSONLDError("Invalid context entry", location, {KEYWORD_PROPAGATE}); + } + + if (!propagate_entry->is_boolean()) { + throw JSONLDError("Invalid @propagate value", location, + {KEYWORD_PROPAGATE}); + } +} } // namespace // Context Processing (JSON-LD 1.1 API Section 4.1.2) @@ -160,115 +480,13 @@ auto process_context(ExpansionState &state, ActiveContext &active_context, for (const auto &[entry_pointer, location] : contexts) { const auto &context{*entry_pointer}; if (context.is_null()) { - if (!state.protected_override) { - for (const auto &entry : active_context.terms) { - if (entry.second.is_protected) { - throw JSONLDError("Invalid context nullification", location); - } - } - } - // Nullifying the context resets to the initial context, whose base is - // the document base. The relativise option and the processing mode are - // processing state rather than context state, so they survive the reset. - const bool relativise{active_context.compact_to_relative}; - // What a scope reverts to outlives the nullification inside it, or the - // nodes below would never regain the context the scope was entered from - // (JSON-LD 1.1 API Section 4.1.2 step 5.1.2) - auto saved_previous{effective_propagate ? nullptr - : active_context.previous}; - active_context = ActiveContext{}; - active_context.base = state.document_base; - active_context.compact_to_relative = relativise; - active_context.processing_1_0 = state.processing_1_0; - active_context.previous = std::move(saved_previous); + process_null_context(state, active_context, location, + effective_propagate); continue; } if (context.is_string()) { - const auto resolved{absolute_reference(state.context_resolution_base(), - context.to_string())}; - if (!resolved.has_value()) { - throw JSONLDError("Loading document failed", location); - } - - const auto &reference{resolved.value()}; - - bool already_loaded{false}; - for (const auto &loaded : state.remote_context_chain) { - if (loaded == reference) { - already_loaded = true; - break; - } - } - - // A scoped context being validated stops at a reference that is already - // loading rather than treating it as recursion (JSON-LD 1.1 API Section - // 4.1.2 step 5.2.2) - if (already_loaded && !state.validate_scoped_context) { - continue; - } - - if (already_loaded) { - // A scoped context can be loaded again on purpose, so JSON-LD 1.1 - // withdrew the recursion error and treats meeting a context already - // in the chain as reaching the limit on how many may be loaded - // (JSON-LD 1.1 API Section 4.1.2 step 5.2.3) - if (state.processing_1_0) { - throw JSONLDError("Recursive context inclusion", location); - } - - throw JSONLDError("Context overflow", location); - } - if (state.remote_context_chain.size() >= - ExpansionState::MAXIMUM_REMOTE_CONTEXTS) { - throw JSONLDError("Context overflow", location); - } - // Step 5.2.4: "If context was previously dereferenced, then the - // processor MUST NOT do a further dereference, and context is set to the - // previously established internal representation", with the note that - // "Only the @context entry need be retained", which is why the cache - // holds that entry rather than the document (JSON-LD 1.1 API - // Section 4.1.2 step 5.2.4) - const auto dereferenced{state.remote_documents.find(reference)}; - const JSON *context_entry{nullptr}; - if (dereferenced != state.remote_documents.cend()) { - context_entry = &dereferenced->second; - } else { - // Every entry point hands the state the address of a resolver, so - // what stands to be settled is whether that resolver holds anything - assert(state.resolver != nullptr); - if (!*state.resolver) { - throw JSONLDError("Loading remote context failed", location); - } - const auto document{resolve(*state.resolver, reference)}; - if (!document.has_value()) { - throw JSONLDError("Loading remote context failed", location); - } - const auto *loaded{ - document->is_object() - ? document->try_at(KEYWORD_CONTEXT, KEYWORD_CONTEXT_HASH) - : nullptr}; - if (loaded == nullptr) { - throw JSONLDError("Invalid remote context", location); - } - context_entry = - &state.remote_documents.emplace(reference, *loaded).first->second; - } - const RemoteContextScope chain{state.remote_context_chain, reference}; - // A scoped context the loaded document defines is processed again when - // its term comes into use, long after this location is out of reach, so - // the reference is recorded for it to report against - const ForeignContextScope origin{state, foreign_origin(state, location)}; - try { - // A loaded remote context is processed with the default propagation. - process_context(state, active_context, *context_entry, location); - } catch (const JSONLDError &error) { - // The offending entries live in the remote document, whose keys have - // no position in the input, so the error is located at the reference - // that loaded it - throw JSONLDError(error.message(), location); - } - + process_remote_context(state, active_context, context, location); continue; } @@ -286,9 +504,9 @@ auto process_context(ExpansionState &state, ActiveContext &active_context, throw JSONLDError("Processing mode conflict", location, {KEYWORD_VERSION}); } - // The entries 1.1 introduced are refused where the algorithm reaches them, - // so each names itself and none stands in for an entry judged earlier - // (JSON-LD 1.1 API Section 4.1.2 step 5.6.1) + // The entries 1.1 introduced are refused where the algorithm reaches + // them, so each names itself and none stands in for an entry judged + // earlier (JSON-LD 1.1 API Section 4.1.2 step 5.6.1) if (state.processing_1_0) { if (context.defines(KEYWORD_IMPORT, KEYWORD_IMPORT_HASH)) { throw JSONLDError("Invalid context entry", location, {KEYWORD_IMPORT}); @@ -311,174 +529,28 @@ auto process_context(ExpansionState &state, ActiveContext &active_context, state.context_protected = protected_entry->to_boolean(); } - if (const auto *import_entry{ - context.try_at(KEYWORD_IMPORT, KEYWORD_IMPORT_HASH)}) { - const auto &import{*import_entry}; - if (!import.is_string()) { - throw JSONLDError("Invalid @import value", location, {KEYWORD_IMPORT}); - } - // What cannot be dereferenced is a loading failure (JSON-LD 1.1 API - // Section 4.1.2 step 5.6.5) - const auto resolved{absolute_reference(state.context_resolution_base(), - import.to_string())}; - if (!resolved.has_value()) { - throw JSONLDError("Loading remote context failed", location, - {KEYWORD_IMPORT}); - } - - const auto &reference{resolved.value()}; - assert(state.resolver != nullptr); - if (!*state.resolver) { - throw JSONLDError("Loading remote context failed", location, - {KEYWORD_IMPORT}); - } - const auto document{resolve(*state.resolver, reference)}; - if (!document.has_value()) { - throw JSONLDError("Loading remote context failed", location, - {KEYWORD_IMPORT}); - } - const auto *imported_context{ - document->is_object() - ? document->try_at(KEYWORD_CONTEXT, KEYWORD_CONTEXT_HASH) - : nullptr}; - if (imported_context == nullptr || !imported_context->is_object()) { - throw JSONLDError("Invalid remote context", location, {KEYWORD_IMPORT}); - } - if (imported_context->defines(KEYWORD_IMPORT, KEYWORD_IMPORT_HASH)) { - throw JSONLDError("Invalid context entry", location, {KEYWORD_IMPORT}); - } - // Merge the imported entries with the current ones, the current ones - // overriding, and process the result as a single context. - auto merged{JSON{*imported_context}}; - for (const auto &entry : context.as_object()) { - if (!entry.key_equals(KEYWORD_IMPORT, KEYWORD_IMPORT_HASH)) { - merged.assign(entry.first, entry.second); - } - } - // The merged context holds entries from two documents, so a scoped - // context defined among the ones only the imported document carries is - // reported against the entry that merged them in, while the input's own - // entries keep their position - auto import_location{foreign_origin(state, location)}; - if (!state.foreign_context_location.has_value()) { - import_location.value().push_back(JSON::String{KEYWORD_IMPORT}); - } - const ForeignContextScope origin{state, std::move(import_location), - &context}; - try { - process_context(state, active_context, merged, location, propagate); - } catch (const JSONLDError &error) { - if (is_input_authored(error, context, location)) { - throw; - } - throw JSONLDError(error.message(), location, {KEYWORD_IMPORT}); - } - state.context_protected = saved_protected; + if (process_import(state, active_context, context, location, propagate, + saved_protected)) { continue; } - if (const auto *base_entry{ - state.remote_context_chain.empty() - ? context.try_at(KEYWORD_BASE, KEYWORD_BASE_HASH) - : nullptr}) { - const auto &base{*base_entry}; - if (base.is_null()) { - active_context.base = std::nullopt; - } else if (!base.is_string()) { - throw JSONLDError("Invalid base IRI", location, {KEYWORD_BASE}); - } else { - auto resolved{resolved_base(active_context.base, base.to_string())}; - if (!resolved.has_value()) { - throw JSONLDError("Invalid base IRI", location, {KEYWORD_BASE}); - } - - active_context.base = std::move(resolved); - } - } + process_base_entry(state, active_context, context, location); - if (const auto *vocabulary_entry{ - context.try_at(KEYWORD_VOCAB, KEYWORD_VOCAB_HASH)}) { - const auto &vocabulary{*vocabulary_entry}; - if (vocabulary.is_null()) { - active_context.vocabulary = std::nullopt; - } else if (!vocabulary.is_string()) { - throw JSONLDError("Invalid vocab mapping", location, {KEYWORD_VOCAB}); - } else { - const auto &vocabulary_string{vocabulary.to_string()}; - // In 1.0, @vocab must be an absolute IRI or blank node identifier. - if (state.processing_1_0 && !vocabulary_string.contains(':')) { - throw JSONLDError("Invalid vocab mapping", location, {KEYWORD_VOCAB}); - } - auto mapping{expand_iri(state, active_context, vocabulary_string, true, - true, nullptr, nullptr, EMPTY_WEAK_POINTER)}; - // Step 5.8.3: "If it is not an IRI, or a blank node identifier, an - // invalid vocab mapping error has been detected". The expansion is - // what has to pass, since a relative reference is admitted here and - // resolved against the base (JSON-LD 1.1 API Section 4.1.2 step 5.8.3) - if (!mapping.has_value() || (!URI::is_iri(mapping.value()) && - !is_blank_node(mapping.value()))) { - throw JSONLDError("Invalid vocab mapping", location, {KEYWORD_VOCAB}); - } - active_context.vocabulary = std::move(mapping); - } - } + process_vocabulary_entry(state, active_context, context, location); - if (const auto *language_entry{ - context.try_at(KEYWORD_LANGUAGE, KEYWORD_LANGUAGE_HASH)}) { - const auto &language{*language_entry}; - if (language.is_null()) { - active_context.default_language = std::nullopt; - } else if (!language.is_string()) { - throw JSONLDError("Invalid default language", location, - {KEYWORD_LANGUAGE}); - } else { - active_context.default_language = language.to_string(); - } - } + process_language_entry(active_context, context, location); // (JSON-LD 1.1 API Section 4.1.2 step 5.10) - if (const auto *direction_entry{ - context.try_at(KEYWORD_DIRECTION, KEYWORD_DIRECTION_HASH)}) { - if (state.processing_1_0) { - throw JSONLDError("Invalid context entry", location, - {KEYWORD_DIRECTION}); - } - - const auto &direction{*direction_entry}; - if (direction.is_null()) { - active_context.default_direction = std::nullopt; - } else if (!direction.is_string()) { - throw JSONLDError("Invalid base direction", location, - {KEYWORD_DIRECTION}); - } else { - const auto &direction_string{direction.to_string()}; - if (direction_string != "ltr" && direction_string != "rtl") { - throw JSONLDError("Invalid base direction", location, - {KEYWORD_DIRECTION}); - } - active_context.default_direction = direction_string; - } - } + process_direction_entry(state, active_context, context, location); // The flag itself is read before the entries are, so that a context that // does not propagate is remembered first, and only what it says is judged // here (JSON-LD 1.1 API Section 4.1.2 step 5.11) - if (const auto *propagate_entry{ - context.try_at(KEYWORD_PROPAGATE, KEYWORD_PROPAGATE_HASH)}) { - if (state.processing_1_0) { - throw JSONLDError("Invalid context entry", location, - {KEYWORD_PROPAGATE}); - } - - if (!propagate_entry->is_boolean()) { - throw JSONLDError("Invalid @propagate value", location, - {KEYWORD_PROPAGATE}); - } - } + process_propagate_entry(state, context, location); DefinedTerms defined; - // An import entry is consumed where the two documents are merged above, so - // none stands among the entries terms are made from + // An import entry is consumed where the two documents are merged above, + // so none stands among the entries terms are made from assert(!context.defines(KEYWORD_IMPORT, KEYWORD_IMPORT_HASH)); for (const auto &entry : context.as_object()) { const auto &name{entry.first}; diff --git a/src/spec/jsonld/jsonld_create_term_definition.cc b/src/spec/jsonld/jsonld_create_term_definition.cc index e9eeec810..8967761c4 100644 --- a/src/spec/jsonld/jsonld_create_term_definition.cc +++ b/src/spec/jsonld/jsonld_create_term_definition.cc @@ -105,6 +105,572 @@ auto check_iri_mapping([[maybe_unused]] const ActiveContext &active_context, } } +// The @type entry of a term definition (JSON-LD 1.1 API Section 4.2.2) +auto define_type_mapping(ExpansionState &state, ActiveContext &active_context, + const JSON &local_context, DefinedTerms &defined, + const WeakPointer &context_pointer, + const WeakPointer &term_pointer, const JSON &value, + TermDefinition &definition) -> void { + const auto *type_entry{value.try_at(KEYWORD_TYPE, KEYWORD_TYPE_HASH)}; + if (type_entry == nullptr) { + return; + } + + const auto &type_value{*type_entry}; + if (!type_value.is_string()) { + throw JSONLDError("Invalid type mapping", term_pointer, {KEYWORD_TYPE}); + } + const auto type{expand_iri(state, active_context, type_value.to_string(), + false, true, &local_context, &defined, + context_pointer)}; + // The step asks three separate things of a type mapping, and they are + // asked one at a time because the two keywords that arrived with 1.1 + // answer to both the second and the third (JSON-LD 1.1 API Section + // 4.2.2 step 12) + if (!type.has_value() || type.value().starts_with("_:")) { + throw JSONLDError("Invalid type mapping", term_pointer, {KEYWORD_TYPE}); + } + + const bool keyword_of_1_1{type.value() == KEYWORD_JSON || + type.value() == KEYWORD_NONE}; + if (type.value() != KEYWORD_ID && type.value() != KEYWORD_VOCAB && + !keyword_of_1_1 && !type.value().contains(':')) { + throw JSONLDError("Invalid type mapping", term_pointer, {KEYWORD_TYPE}); + } + + if (state.processing_1_0 && keyword_of_1_1) { + throw JSONLDError("Invalid type mapping", term_pointer, {KEYWORD_TYPE}); + } + definition.type_mapping = type; +} + +// The @container entry of a term definition (JSON-LD 1.1 API Section 4.2.2) +auto define_container_mapping(ExpansionState &state, + const WeakPointer &term_pointer, + const JSON &value, TermDefinition &definition) + -> void { + const auto *container_entry{ + value.try_at(KEYWORD_CONTAINER, KEYWORD_CONTAINER_HASH)}; + if (container_entry == nullptr) { + return; + } + + const auto &container{*container_entry}; + // A reverse property names one container, which must be @set or @index, + // and an explicit null leaves no container mapping at all (JSON-LD 1.1 + // Section 9.15.1, JSON-LD 1.1 API Section 4.2.2 step 15.5) + if (definition.reverse) { + if (!container.is_null()) { + if (!container.is_string() || (container.to_string() != KEYWORD_SET && + container.to_string() != KEYWORD_INDEX)) { + throw JSONLDError("Invalid reverse property", term_pointer, + {KEYWORD_CONTAINER}); + } + + definition.container.push_back(container.to_string()); + } + } else if (container.is_array()) { + // Array containers are a 1.1 feature. + if (state.processing_1_0) { + throw JSONLDError("Invalid container mapping", term_pointer, + {KEYWORD_CONTAINER}); + } + std::size_t container_index{0}; + for (const auto &item : container.as_array()) { + if (!item.is_string()) { + throw JSONLDError( + "Invalid container mapping", + container_member_pointer(term_pointer, container_index)); + } + const auto &item_string{item.to_string()}; + if (!is_valid_container(item_string)) { + throw JSONLDError( + "Invalid container mapping", + container_member_pointer(term_pointer, container_index)); + } + // A keyword may not appear more than once in the container array. + for (const auto &seen : definition.container) { + if (seen == item_string) { + throw JSONLDError( + "Invalid container mapping", + container_member_pointer(term_pointer, container_index)); + } + } + definition.container.push_back(item_string); + container_index += 1; + } + } else if (container.is_string()) { + const auto &container_string{container.to_string()}; + // In 1.0, the @graph, @id and @type containers are not permitted. + if (state.processing_1_0 && + (container_string == KEYWORD_GRAPH || container_string == KEYWORD_ID || + container_string == KEYWORD_TYPE)) { + throw JSONLDError("Invalid container mapping", term_pointer, + {KEYWORD_CONTAINER}); + } + if (!is_valid_container(container_string)) { + throw JSONLDError("Invalid container mapping", term_pointer, + {KEYWORD_CONTAINER}); + } + definition.container.push_back(container_string); + } else { + throw JSONLDError("Invalid container mapping", term_pointer, + {KEYWORD_CONTAINER}); + } + + // The combinations that may name several keywords accept them in any + // order, so the same set spelled either way is the same mapping, and + // storing it in one order is what lets a protected term be redefined + // with the same mapping written differently + std::ranges::sort(definition.container); + + bool container_graph{false}; + bool container_id{false}; + bool container_index{false}; + bool container_language{false}; + bool container_list{false}; + bool container_set{false}; + bool container_type{false}; + for (const auto &item : definition.container) { + if (item == KEYWORD_GRAPH) { + container_graph = true; + } else if (item == KEYWORD_ID) { + container_id = true; + } else if (item == KEYWORD_INDEX) { + container_index = true; + } else if (item == KEYWORD_LANGUAGE) { + container_language = true; + } else if (item == KEYWORD_LIST) { + container_list = true; + } else if (item == KEYWORD_SET) { + container_set = true; + // Every name was held to being one of the container keywords + // before the set was read, and the others are named above, so what + // is left can only be this one + } else { + assert(item == KEYWORD_TYPE); + container_type = true; + } + } + // Valid array combinations (JSON-LD 1.1 API Section 4.2.2 step 21.1): a + // single keyword, or @graph with exactly one of @id or @index optionally + // with @set, or @set combined with any one of @index, @graph, @id, + // @type, or @language. + if (!definition.reverse && definition.container.size() != 1) { + const bool graph_form{ + container_graph && (container_id != container_index) && + !container_list && !container_type && !container_language}; + const bool set_form{container_set && definition.container.size() == 2 && + !container_list}; + if (!graph_form && !set_form) { + throw JSONLDError("Invalid container mapping", term_pointer, + {KEYWORD_CONTAINER}); + } + } + // Step 21.4.1: "If type mapping in definition is undefined, set it to + // @id", then step 21.4.2: "If type mapping in definition is neither @id + // nor @vocab, an invalid type mapping error has been detected and + // processing is aborted". The default is what coerces a non-map value of + // the term to an identifier (JSON-LD 1.1 API Section 4.2.2 steps 21.4.1 + // and 21.4.2) + if (container_type) { + if (!definition.type_mapping.has_value()) { + definition.type_mapping = JSON::String{KEYWORD_ID}; + } else if (definition.type_mapping.value() != KEYWORD_ID && + definition.type_mapping.value() != KEYWORD_VOCAB) { + throw JSONLDError("Invalid type mapping", term_pointer, {KEYWORD_TYPE}); + } + } +} + +// The @context entry of a term definition (JSON-LD 1.1 API Section 4.2.2) +auto define_scoped_context(ExpansionState &state, ActiveContext &active_context, + const JSON::String &term, + const WeakPointer &term_pointer, const JSON &value, + TermDefinition &definition) -> void { + const auto *context_entry{ + value.try_at(KEYWORD_CONTEXT, KEYWORD_CONTEXT_HASH)}; + if (context_entry == nullptr) { + return; + } + + if (state.processing_1_0) { + throw JSONLDError("Invalid term definition", term_pointer, + {KEYWORD_CONTEXT}); + } + // The scoped context is processed here so that it is validated even + // when the term is never used, and however it fails, the term is the one + // at fault. A reference that is already loading is skipped rather than + // followed (JSON-LD 1.1 API Section 4.2.2 step 21) + const bool saved_override{state.protected_override}; + const bool saved_context_protected{state.context_protected}; + const bool saved_validate{state.validate_scoped_context}; + try { + // The error raised here is always discarded below, so its location does + // not matter. + ActiveContext probe{active_context}; + state.protected_override = true; + state.validate_scoped_context = false; + process_context(state, probe, *context_entry, EMPTY_WEAK_POINTER); + state.validate_scoped_context = saved_validate; + state.protected_override = saved_override; + state.context_protected = saved_context_protected; + } catch (const JSONLDError &) { + state.validate_scoped_context = saved_validate; + state.protected_override = saved_override; + state.context_protected = saved_context_protected; + throw JSONLDError("Invalid scoped context", term_pointer, + {KEYWORD_CONTEXT}); + } + definition.context = *context_entry; + definition.context_base = state.context_resolution_base(); + // Step 21.7 keeps the local context of the definition to re-process when + // the term comes into use, so whatever it says wrong then belongs where + // it was written. Only a context the input spells out has entries of its + // own to point into, which a context merged from an import settles one + // term at a time (JSON-LD 1.1 API Section 4.2.2 step 21.7) + definition.context_authored = + !state.foreign_context_location.has_value() || + (state.input_context != nullptr && state.input_context->defines(term)); + definition.context_location = + definition.context_authored + ? to_pointer(term_pointer.concat(keyword_context())) + : state.foreign_context_location.value(); +} + +// The @index entry of a term definition (JSON-LD 1.1 API Section 4.2.2) +auto define_index_mapping(ExpansionState &state, ActiveContext &active_context, + const JSON &local_context, DefinedTerms &defined, + const WeakPointer &context_pointer, + const WeakPointer &term_pointer, const JSON &value, + TermDefinition &definition) -> void { + const auto *index_entry{value.try_at(KEYWORD_INDEX, KEYWORD_INDEX_HASH)}; + if (index_entry == nullptr) { + return; + } + + if (state.processing_1_0) { + throw JSONLDError("Invalid term definition", term_pointer, {KEYWORD_INDEX}); + } + bool has_index_container{false}; + for (const auto &item : definition.container) { + if (item == KEYWORD_INDEX) { + has_index_container = true; + } + } + const auto &index{*index_entry}; + if (!index.is_string() || !has_index_container) { + throw JSONLDError("Invalid term definition", term_pointer, {KEYWORD_INDEX}); + } + const auto &index_string{index.to_string()}; + const auto index_iri{expand_iri(state, active_context, index_string, false, + true, &local_context, &defined, + context_pointer)}; + // The expansion of the value has to name an IRI, which neither a + // keyword nor a term that stayed relative does (JSON-LD 1.1 API Section + // 4.2.2 step 21.2) + if (!index_iri.has_value() || is_keyword(index_iri.value()) || + !URI::is_iri(index_iri.value())) { + throw JSONLDError("Invalid term definition", term_pointer, {KEYWORD_INDEX}); + } + definition.index = index_string; + definition.index_iri = index_iri.value(); +} + +// A term definition may not carry an entry other than the keywords the +// steps above recognise (JSON-LD 1.1 API Section 4.2.2) +auto reject_unknown_entries(const JSON &value, const WeakPointer &term_pointer) + -> void { + for (const auto &entry : value.as_object()) { + if (!entry.key_equals(KEYWORD_ID, KEYWORD_ID_HASH) && + !entry.key_equals(KEYWORD_REVERSE, KEYWORD_REVERSE_HASH) && + !entry.key_equals(KEYWORD_CONTAINER, KEYWORD_CONTAINER_HASH) && + !entry.key_equals(KEYWORD_CONTEXT, KEYWORD_CONTEXT_HASH) && + !entry.key_equals(KEYWORD_DIRECTION, KEYWORD_DIRECTION_HASH) && + !entry.key_equals(KEYWORD_INDEX, KEYWORD_INDEX_HASH) && + !entry.key_equals(KEYWORD_LANGUAGE, KEYWORD_LANGUAGE_HASH) && + !entry.key_equals(KEYWORD_NEST, KEYWORD_NEST_HASH) && + !entry.key_equals(KEYWORD_PREFIX, KEYWORD_PREFIX_HASH) && + !entry.key_equals(KEYWORD_PROTECTED, KEYWORD_PROTECTED_HASH) && + !entry.key_equals(KEYWORD_TYPE, KEYWORD_TYPE_HASH)) { + throw JSONLDError("Invalid term definition", term_pointer, {entry.first}); + } + } +} + +// Step 12 of Create Term Definition: a term that spells a keyword, which +// only @type may redefine and only with a map (JSON-LD 1.1 API Section +// 4.2.2 step 12) +auto define_keyword_term(ExpansionState &state, ActiveContext &active_context, + DefinedTerms &defined, const JSON::String &term, + const WeakPointer &term_pointer, const JSON &value) + -> void { + if (term == KEYWORD_TYPE && value.is_object() && !state.processing_1_0) { + TermDefinition type_definition; + // Step 12 creates the definition "initializing prefix flag to false, + // protected to protected", which context processing step 5.13 supplies + // as "the value of the @protected entry from context, if any", and step + // 13 then sets the flag "to the value of this entry", so an entry of the + // definition overrides the context default in either direction (JSON-LD + // 1.1 API Section 4.2.2 steps 12 and 13, Section 4.1.2 step 5.13) + type_definition.is_protected = state.context_protected; + bool has_container{false}; + bool has_protected{false}; + bool invalid_entry{false}; + for (const auto &entry : value.as_object()) { + if (entry.key_equals(KEYWORD_PROTECTED, KEYWORD_PROTECTED_HASH)) { + if (!entry.second.is_boolean()) { + throw JSONLDError("Invalid @protected value", term_pointer, + {KEYWORD_PROTECTED}); + } + type_definition.is_protected = entry.second.to_boolean(); + has_protected = true; + } else if (entry.key_equals(KEYWORD_CONTAINER, KEYWORD_CONTAINER_HASH) && + entry.second.is_string()) { + const auto &container{entry.second.to_string()}; + if (container == KEYWORD_SET) { + type_definition.container.push_back(container); + has_container = true; + } else { + invalid_entry = true; + } + } else { + invalid_entry = true; + } + } + // Step 4: the value of a @type definition "MUST be a map with only + // either or both of the following entries: An entry for @container with + // value @set. An entry for @protected", so either one alone is enough + // and only a map carrying neither is an error. The shape is settled here + // because step 4 precedes step 8, which reads the previous definition, + // and step 29, which compares against it (JSON-LD 1.1 API Section 4.2.2 + // step 4) + if (invalid_entry || (!has_container && !has_protected)) { + throw JSONLDError("Keyword redefinition", term_pointer); + } + + std::optional previous_type; + const auto existing_type{active_context.terms.find(KEYWORD_TYPE)}; + if (existing_type != active_context.terms.cend()) { + previous_type = existing_type->second; + } + + finalize_definition(state, active_context, defined, + JSON::String{KEYWORD_TYPE}, term_pointer, previous_type, + std::move(type_definition)); + return; + } + throw JSONLDError("Keyword redefinition", term_pointer); +} + +// Step 10 of Create Term Definition: a term that a string defines. +// Answers whether the caller carries on (JSON-LD 1.1 API Section +// 4.2.2 step 10) +auto define_string_term(ExpansionState &state, ActiveContext &active_context, + const JSON &local_context, const JSON::String &term, + DefinedTerms &defined, + const WeakPointer &context_pointer, + const WeakPointer &term_pointer, const JSON &value, + TermDefinition &definition) -> bool { + const auto &string_value{value.to_string()}; + if (!is_keyword(string_value) && has_keyword_form(string_value)) { + defined[term] = true; + return false; + } + if (string_value == term) { + // A self-referential simple term resolves through the term itself. + const auto colon{term.find(':')}; + if (colon != JSON::String::npos) { + const auto prefix{term.substr(0, colon)}; + const auto suffix{term.substr(colon + 1)}; + // A term is only ever made while a map of them is being read, so the + // context holding this one is a map + assert(local_context.is_object()); + // A prefix already recorded as being worked on would have been met as + // a cycle before reaching here, so the record only ever reads as + // settled + if (prefix != "_" && !suffix.starts_with("//") && + local_context.defines(prefix)) { + const auto iterator{defined.find(prefix)}; + if (iterator == defined.cend() || !iterator->second) { + create_term_definition(state, active_context, local_context, prefix, + defined, context_pointer); + } + } + const auto prefix_definition{active_context.terms.find(prefix)}; + if (prefix_definition != active_context.terms.cend() && + prefix_definition->second.iri.has_value()) { + definition.iri = prefix_definition->second.iri.value() + suffix; + } else { + definition.iri = term; + } + } else if (term.contains('/')) { + definition.iri = expand_iri(state, active_context, term, false, true, + nullptr, nullptr, EMPTY_WEAK_POINTER); + } else if (active_context.vocabulary.has_value()) { + definition.iri = active_context.vocabulary.value() + term; + } + } else { + definition.iri = + expand_iri(state, active_context, string_value, false, true, + &local_context, &defined, context_pointer); + // Holding an IRI-like term to re-expanding onto its own IRI mapping + // arrived with 1.1 and is asked for whatever mode is in force (JSON-LD + // 1.1 API Section 4.2.2), while 1.0 knew no such step (JSON-LD 1.0 API + // Section 6.2). Standing in for a 1.0 processor therefore means + // withholding it, which is what the earlier mode does here and what two + // suite cases declaring that version rest on. The mapping always holds + // something by now, for the reason given where it is checked + if (!state.processing_1_0 && definition.iri.has_value()) { + const auto colon_position{term.find(':')}; + const bool iri_like_colon{colon_position != JSON::String::npos && + colon_position != 0 && + colon_position + 1 != term.size()}; + if (iri_like_colon || term.contains('/')) { + auto probe{active_context}; + const auto expanded_term{expand_iri(state, probe, term, false, true, + nullptr, nullptr, + EMPTY_WEAK_POINTER)}; + // A term is only weighed here for carrying a colon or a slash, + // neither of which a name of keyword form may hold, and that shape + // is the only one expanding to nothing + // A name of keyword form carries nothing but letters after its + // sign, so a term weighed here for its colon or its slash is of no + // such form, and that form is the only one expansion answers + // nothing for + assert(expanded_term.has_value()); + if (expanded_term != definition.iri) { + throw JSONLDError("Invalid IRI mapping", term_pointer); + } + } + } + + // A string definition stands for a map carrying that value under @id + // (JSON-LD 1.1 API Section 4.2.2 step 10), so its mapping is held to the + // same account as the spelled-out form + check_iri_mapping(active_context, definition.iri, term_pointer, {}); + } + + return true; +} + +// Steps 13 to 16 of Create Term Definition: the IRI that the term maps to, +// whether a reverse property names it, an @id entry does, the term is a +// compact or relative IRI, or the active context carries a vocabulary. +// Answers whether the caller carries on (JSON-LD 1.1 API Section 4.2.2) +auto define_iri_mapping(ExpansionState &state, ActiveContext &active_context, + const JSON &local_context, const JSON::String &term, + DefinedTerms &defined, + const WeakPointer &context_pointer, + const WeakPointer &term_pointer, const JSON &value, + const JSON *const id_entry, const bool explicit_null_id, + TermDefinition &definition) -> bool { + const bool has_id{id_entry != nullptr}; + const JSON *const identifier{id_entry}; + + if (const auto *reverse_entry{ + value.try_at(KEYWORD_REVERSE, KEYWORD_REVERSE_HASH)}) { + if (has_id || value.defines(KEYWORD_NEST, KEYWORD_NEST_HASH)) { + throw JSONLDError("Invalid reverse property", term_pointer, + {KEYWORD_REVERSE}); + } + const auto &reverse{*reverse_entry}; + if (!reverse.is_string()) { + throw JSONLDError("Invalid IRI mapping", term_pointer, {KEYWORD_REVERSE}); + } + // A reverse value that looks like a keyword is left alone, the keywords + // themselves included (JSON-LD 1.1 API Section 4.2.2 step 15.3) + if (has_keyword_form(reverse.to_string())) { + defined[term] = true; + return false; + } + + definition.reverse = true; + definition.iri = + expand_iri(state, active_context, reverse.to_string(), false, true, + &local_context, &defined, context_pointer); + // A value shaped like a keyword is the only one expansion answers + // nothing for, and the step above has already left such a value alone, + // so what stands to be settled here is whether the expansion names an + // absolute IRI + if (!definition.iri.has_value() || !definition.iri.value().contains(':')) { + throw JSONLDError("Invalid IRI mapping", term_pointer, {KEYWORD_REVERSE}); + } + } else if (has_id && !identifier->is_null() && + (!identifier->is_string() || identifier->to_string() != term)) { + if (!identifier->is_string()) { + throw JSONLDError("Invalid IRI mapping", term_pointer, {KEYWORD_ID}); + } + const auto &id_value{identifier->to_string()}; + if (!is_keyword(id_value) && has_keyword_form(id_value)) { + defined[term] = true; + return false; + } + definition.iri = expand_iri(state, active_context, id_value, false, true, + &local_context, &defined, context_pointer); + const auto &mapping{definition.iri}; + check_iri_mapping(active_context, mapping, term_pointer, {KEYWORD_ID}); + // A term shaped like an IRI, carrying a colon other than at its edges + // or carrying a slash, must re-expand onto its own IRI mapping. The + // step arrived with 1.1 and the earlier mode withholds it, for the + // reason given where the same test stands above. The mapping always + // holds something by now, as the step above left a value shaped like a + // keyword alone + assert(mapping.has_value()); + if (!state.processing_1_0) { + const auto colon_position{term.find(':')}; + const bool iri_like_colon{colon_position != JSON::String::npos && + colon_position != 0 && + colon_position + 1 != term.size()}; + if (iri_like_colon || term.contains('/')) { + auto probe{active_context}; + const auto expanded_term{expand_iri(state, probe, term, false, true, + nullptr, nullptr, + EMPTY_WEAK_POINTER)}; + // As above, a name carrying a colon or a slash is of no keyword + // form, so it never expands to nothing + // As above, a name carrying a colon or a slash is of no keyword + // form + assert(expanded_term.has_value()); + if (expanded_term != mapping) { + throw JSONLDError("Invalid IRI mapping", term_pointer, {KEYWORD_ID}); + } + } + } + } else if (explicit_null_id) { + // No identifier is derived for a term that gave up its own + } else if (term.contains(':') && !term.starts_with(':') && + !term.ends_with(':')) { + const auto colon{term.find(':')}; + const auto prefix{term.substr(0, colon)}; + const auto suffix{term.substr(colon + 1)}; + // As above, the context holding the term is a map, and a prefix + // recorded as being worked on would already have been met as a cycle + assert(local_context.is_object()); + if (prefix != "_" && !suffix.starts_with("//") && + local_context.defines(prefix)) { + const auto iterator{defined.find(prefix)}; + if (iterator == defined.cend() || !iterator->second) { + create_term_definition(state, active_context, local_context, prefix, + defined, context_pointer); + } + } + const auto prefix_definition{active_context.terms.find(prefix)}; + if (prefix_definition != active_context.terms.cend() && + prefix_definition->second.iri.has_value()) { + definition.iri = prefix_definition->second.iri.value() + suffix; + } else { + definition.iri = term; + } + } else if (term.contains('/')) { + definition.iri = expand_iri(state, active_context, term, false, true, + nullptr, nullptr, EMPTY_WEAK_POINTER); + } else if (active_context.vocabulary.has_value()) { + definition.iri = active_context.vocabulary.value() + term; + } + + return true; +} } // namespace // Create Term Definition (JSON-LD 1.1 API Section 4.2.2) @@ -130,63 +696,9 @@ auto create_term_definition(ExpansionState &state, const WeakPointer term_pointer{context_pointer.concat(term)}; if (is_keyword(term)) { - if (term == KEYWORD_TYPE && value.is_object() && !state.processing_1_0) { - TermDefinition type_definition; - // Step 12 creates the definition "initializing prefix flag to false, - // protected to protected", which context processing step 5.13 supplies - // as "the value of the @protected entry from context, if any", and step - // 13 then sets the flag "to the value of this entry", so an entry of the - // definition overrides the context default in either direction (JSON-LD - // 1.1 API Section 4.2.2 steps 12 and 13, Section 4.1.2 step 5.13) - type_definition.is_protected = state.context_protected; - bool has_container{false}; - bool has_protected{false}; - bool invalid_entry{false}; - for (const auto &entry : value.as_object()) { - if (entry.key_equals(KEYWORD_PROTECTED, KEYWORD_PROTECTED_HASH)) { - if (!entry.second.is_boolean()) { - throw JSONLDError("Invalid @protected value", term_pointer, - {KEYWORD_PROTECTED}); - } - type_definition.is_protected = entry.second.to_boolean(); - has_protected = true; - } else if (entry.key_equals(KEYWORD_CONTAINER, - KEYWORD_CONTAINER_HASH) && - entry.second.is_string()) { - const auto &container{entry.second.to_string()}; - if (container == KEYWORD_SET) { - type_definition.container.push_back(container); - has_container = true; - } else { - invalid_entry = true; - } - } else { - invalid_entry = true; - } - } - // Step 4: the value of a @type definition "MUST be a map with only - // either or both of the following entries: An entry for @container with - // value @set. An entry for @protected", so either one alone is enough - // and only a map carrying neither is an error. The shape is settled here - // because step 4 precedes step 8, which reads the previous definition, - // and step 29, which compares against it (JSON-LD 1.1 API Section 4.2.2 - // step 4) - if (invalid_entry || (!has_container && !has_protected)) { - throw JSONLDError("Keyword redefinition", term_pointer); - } - - std::optional previous_type; - const auto existing_type{active_context.terms.find(KEYWORD_TYPE)}; - if (existing_type != active_context.terms.cend()) { - previous_type = existing_type->second; - } - - finalize_definition(state, active_context, defined, - JSON::String{KEYWORD_TYPE}, term_pointer, - previous_type, std::move(type_definition)); - return; - } - throw JSONLDError("Keyword redefinition", term_pointer); + define_keyword_term(state, active_context, defined, term, term_pointer, + value); + return; } if (has_keyword_form(term)) { @@ -223,87 +735,11 @@ auto create_term_definition(ExpansionState &state, if (value.is_string()) { simple_term = true; - const auto &string_value{value.to_string()}; - if (!is_keyword(string_value) && has_keyword_form(string_value)) { - defined[term] = true; + if (!define_string_term(state, active_context, local_context, term, defined, + context_pointer, term_pointer, value, definition)) { return; } - if (string_value == term) { - // A self-referential simple term resolves through the term itself. - const auto colon{term.find(':')}; - if (colon != JSON::String::npos) { - const auto prefix{term.substr(0, colon)}; - const auto suffix{term.substr(colon + 1)}; - // A term is only ever made while a map of them is being read, so the - // context holding this one is a map - assert(local_context.is_object()); - // A prefix already recorded as being worked on would have been met as - // a cycle before reaching here, so the record only ever reads as - // settled - if (prefix != "_" && !suffix.starts_with("//") && - local_context.defines(prefix)) { - const auto iterator{defined.find(prefix)}; - if (iterator == defined.cend() || !iterator->second) { - create_term_definition(state, active_context, local_context, prefix, - defined, context_pointer); - } - } - const auto prefix_definition{active_context.terms.find(prefix)}; - if (prefix_definition != active_context.terms.cend() && - prefix_definition->second.iri.has_value()) { - definition.iri = prefix_definition->second.iri.value() + suffix; - } else { - definition.iri = term; - } - } else if (term.contains('/')) { - definition.iri = expand_iri(state, active_context, term, false, true, - nullptr, nullptr, EMPTY_WEAK_POINTER); - } else if (active_context.vocabulary.has_value()) { - definition.iri = active_context.vocabulary.value() + term; - } - } else { - definition.iri = - expand_iri(state, active_context, string_value, false, true, - &local_context, &defined, context_pointer); - // Holding an IRI-like term to re-expanding onto its own IRI mapping - // arrived with 1.1 and is asked for whatever mode is in force (JSON-LD - // 1.1 API Section 4.2.2), while 1.0 knew no such step (JSON-LD 1.0 API - // Section 6.2). Standing in for a 1.0 processor therefore means - // withholding it, which is what the earlier mode does here and what two - // suite cases declaring that version rest on. The mapping always holds - // something by now, for the reason given where it is checked - if (!state.processing_1_0 && definition.iri.has_value()) { - const auto colon_position{term.find(':')}; - const bool iri_like_colon{colon_position != JSON::String::npos && - colon_position != 0 && - colon_position + 1 != term.size()}; - if (iri_like_colon || term.contains('/')) { - auto probe{active_context}; - const auto expanded_term{expand_iri(state, probe, term, false, true, - nullptr, nullptr, - EMPTY_WEAK_POINTER)}; - // A term is only weighed here for carrying a colon or a slash, - // neither of which a name of keyword form may hold, and that shape - // is the only one expanding to nothing - // A name of keyword form carries nothing but letters after its - // sign, so a term weighed here for its colon or its slash is of no - // such form, and that form is the only one expansion answers - // nothing for - assert(expanded_term.has_value()); - if (expanded_term != definition.iri) { - throw JSONLDError("Invalid IRI mapping", term_pointer); - } - } - } - - // A string definition stands for a map carrying that value under @id - // (JSON-LD 1.1 API Section 4.2.2 step 10), so its mapping is held to the - // same account as the spelled-out form - check_iri_mapping(active_context, definition.iri, term_pointer, {}); - } } else if (value.is_object()) { - const bool has_id{id_entry != nullptr}; - const JSON *const identifier{id_entry}; // The protected flag and the type mapping are settled before the entry // that names the term is, so what either of them says wrong is reported @@ -322,271 +758,16 @@ auto create_term_definition(ExpansionState &state, definition.is_protected = protected_entry->to_boolean(); } - if (const auto *type_entry{value.try_at(KEYWORD_TYPE, KEYWORD_TYPE_HASH)}) { - const auto &type_value{*type_entry}; - if (!type_value.is_string()) { - throw JSONLDError("Invalid type mapping", term_pointer, {KEYWORD_TYPE}); - } - const auto type{expand_iri(state, active_context, type_value.to_string(), - false, true, &local_context, &defined, - context_pointer)}; - // The step asks three separate things of a type mapping, and they are - // asked one at a time because the two keywords that arrived with 1.1 - // answer to both the second and the third (JSON-LD 1.1 API Section - // 4.2.2 step 12) - if (!type.has_value() || type.value().starts_with("_:")) { - throw JSONLDError("Invalid type mapping", term_pointer, {KEYWORD_TYPE}); - } + define_type_mapping(state, active_context, local_context, defined, + context_pointer, term_pointer, value, definition); - const bool keyword_of_1_1{type.value() == KEYWORD_JSON || - type.value() == KEYWORD_NONE}; - if (type.value() != KEYWORD_ID && type.value() != KEYWORD_VOCAB && - !keyword_of_1_1 && !type.value().contains(':')) { - throw JSONLDError("Invalid type mapping", term_pointer, {KEYWORD_TYPE}); - } - - if (state.processing_1_0 && keyword_of_1_1) { - throw JSONLDError("Invalid type mapping", term_pointer, {KEYWORD_TYPE}); - } - definition.type_mapping = type; - } - - if (const auto *reverse_entry{ - value.try_at(KEYWORD_REVERSE, KEYWORD_REVERSE_HASH)}) { - if (has_id || value.defines(KEYWORD_NEST, KEYWORD_NEST_HASH)) { - throw JSONLDError("Invalid reverse property", term_pointer, - {KEYWORD_REVERSE}); - } - const auto &reverse{*reverse_entry}; - if (!reverse.is_string()) { - throw JSONLDError("Invalid IRI mapping", term_pointer, - {KEYWORD_REVERSE}); - } - // A reverse value that looks like a keyword is left alone, the keywords - // themselves included (JSON-LD 1.1 API Section 4.2.2 step 15.3) - if (has_keyword_form(reverse.to_string())) { - defined[term] = true; - return; - } - - definition.reverse = true; - definition.iri = - expand_iri(state, active_context, reverse.to_string(), false, true, - &local_context, &defined, context_pointer); - // A value shaped like a keyword is the only one expansion answers - // nothing for, and the step above has already left such a value alone, - // so what stands to be settled here is whether the expansion names an - // absolute IRI - if (!definition.iri.has_value() || - !definition.iri.value().contains(':')) { - throw JSONLDError("Invalid IRI mapping", term_pointer, - {KEYWORD_REVERSE}); - } - } else if (has_id && !identifier->is_null() && - (!identifier->is_string() || identifier->to_string() != term)) { - if (!identifier->is_string()) { - throw JSONLDError("Invalid IRI mapping", term_pointer, {KEYWORD_ID}); - } - const auto &id_value{identifier->to_string()}; - if (!is_keyword(id_value) && has_keyword_form(id_value)) { - defined[term] = true; - return; - } - definition.iri = expand_iri(state, active_context, id_value, false, true, - &local_context, &defined, context_pointer); - const auto &mapping{definition.iri}; - check_iri_mapping(active_context, mapping, term_pointer, {KEYWORD_ID}); - // A term shaped like an IRI, carrying a colon other than at its edges - // or carrying a slash, must re-expand onto its own IRI mapping. The - // step arrived with 1.1 and the earlier mode withholds it, for the - // reason given where the same test stands above. The mapping always - // holds something by now, as the step above left a value shaped like a - // keyword alone - assert(mapping.has_value()); - if (!state.processing_1_0) { - const auto colon_position{term.find(':')}; - const bool iri_like_colon{colon_position != JSON::String::npos && - colon_position != 0 && - colon_position + 1 != term.size()}; - if (iri_like_colon || term.contains('/')) { - auto probe{active_context}; - const auto expanded_term{expand_iri(state, probe, term, false, true, - nullptr, nullptr, - EMPTY_WEAK_POINTER)}; - // As above, a name carrying a colon or a slash is of no keyword - // form, so it never expands to nothing - // As above, a name carrying a colon or a slash is of no keyword - // form - assert(expanded_term.has_value()); - if (expanded_term != mapping) { - throw JSONLDError("Invalid IRI mapping", term_pointer, - {KEYWORD_ID}); - } - } - } - } else if (explicit_null_id) { - // No identifier is derived for a term that gave up its own - } else if (term.contains(':') && !term.starts_with(':') && - !term.ends_with(':')) { - const auto colon{term.find(':')}; - const auto prefix{term.substr(0, colon)}; - const auto suffix{term.substr(colon + 1)}; - // As above, the context holding the term is a map, and a prefix - // recorded as being worked on would already have been met as a cycle - assert(local_context.is_object()); - if (prefix != "_" && !suffix.starts_with("//") && - local_context.defines(prefix)) { - const auto iterator{defined.find(prefix)}; - if (iterator == defined.cend() || !iterator->second) { - create_term_definition(state, active_context, local_context, prefix, - defined, context_pointer); - } - } - const auto prefix_definition{active_context.terms.find(prefix)}; - if (prefix_definition != active_context.terms.cend() && - prefix_definition->second.iri.has_value()) { - definition.iri = prefix_definition->second.iri.value() + suffix; - } else { - definition.iri = term; - } - } else if (term.contains('/')) { - definition.iri = expand_iri(state, active_context, term, false, true, - nullptr, nullptr, EMPTY_WEAK_POINTER); - } else if (active_context.vocabulary.has_value()) { - definition.iri = active_context.vocabulary.value() + term; + if (!define_iri_mapping(state, active_context, local_context, term, defined, + context_pointer, term_pointer, value, id_entry, + explicit_null_id, definition)) { + return; } - if (const auto *container_entry{ - value.try_at(KEYWORD_CONTAINER, KEYWORD_CONTAINER_HASH)}) { - const auto &container{*container_entry}; - // A reverse property names one container, which must be @set or @index, - // and an explicit null leaves no container mapping at all (JSON-LD 1.1 - // Section 9.15.1, JSON-LD 1.1 API Section 4.2.2 step 15.5) - if (definition.reverse) { - if (!container.is_null()) { - if (!container.is_string() || - (container.to_string() != KEYWORD_SET && - container.to_string() != KEYWORD_INDEX)) { - throw JSONLDError("Invalid reverse property", term_pointer, - {KEYWORD_CONTAINER}); - } - - definition.container.push_back(container.to_string()); - } - } else if (container.is_array()) { - // Array containers are a 1.1 feature. - if (state.processing_1_0) { - throw JSONLDError("Invalid container mapping", term_pointer, - {KEYWORD_CONTAINER}); - } - std::size_t container_index{0}; - for (const auto &item : container.as_array()) { - if (!item.is_string()) { - throw JSONLDError( - "Invalid container mapping", - container_member_pointer(term_pointer, container_index)); - } - const auto &item_string{item.to_string()}; - if (!is_valid_container(item_string)) { - throw JSONLDError( - "Invalid container mapping", - container_member_pointer(term_pointer, container_index)); - } - // A keyword may not appear more than once in the container array. - for (const auto &seen : definition.container) { - if (seen == item_string) { - throw JSONLDError( - "Invalid container mapping", - container_member_pointer(term_pointer, container_index)); - } - } - definition.container.push_back(item_string); - container_index += 1; - } - } else if (container.is_string()) { - const auto &container_string{container.to_string()}; - // In 1.0, the @graph, @id and @type containers are not permitted. - if (state.processing_1_0 && (container_string == KEYWORD_GRAPH || - container_string == KEYWORD_ID || - container_string == KEYWORD_TYPE)) { - throw JSONLDError("Invalid container mapping", term_pointer, - {KEYWORD_CONTAINER}); - } - if (!is_valid_container(container_string)) { - throw JSONLDError("Invalid container mapping", term_pointer, - {KEYWORD_CONTAINER}); - } - definition.container.push_back(container_string); - } else { - throw JSONLDError("Invalid container mapping", term_pointer, - {KEYWORD_CONTAINER}); - } - - // The combinations that may name several keywords accept them in any - // order, so the same set spelled either way is the same mapping, and - // storing it in one order is what lets a protected term be redefined - // with the same mapping written differently - std::ranges::sort(definition.container); - - bool container_graph{false}; - bool container_id{false}; - bool container_index{false}; - bool container_language{false}; - bool container_list{false}; - bool container_set{false}; - bool container_type{false}; - for (const auto &item : definition.container) { - if (item == KEYWORD_GRAPH) { - container_graph = true; - } else if (item == KEYWORD_ID) { - container_id = true; - } else if (item == KEYWORD_INDEX) { - container_index = true; - } else if (item == KEYWORD_LANGUAGE) { - container_language = true; - } else if (item == KEYWORD_LIST) { - container_list = true; - } else if (item == KEYWORD_SET) { - container_set = true; - // Every name was held to being one of the container keywords - // before the set was read, and the others are named above, so what - // is left can only be this one - } else { - assert(item == KEYWORD_TYPE); - container_type = true; - } - } - // Valid array combinations (JSON-LD 1.1 API Section 4.2.2 step 21.1): a - // single keyword, or @graph with exactly one of @id or @index optionally - // with @set, or @set combined with any one of @index, @graph, @id, - // @type, or @language. - if (!definition.reverse && definition.container.size() != 1) { - const bool graph_form{ - container_graph && (container_id != container_index) && - !container_list && !container_type && !container_language}; - const bool set_form{container_set && definition.container.size() == 2 && - !container_list}; - if (!graph_form && !set_form) { - throw JSONLDError("Invalid container mapping", term_pointer, - {KEYWORD_CONTAINER}); - } - } - // Step 21.4.1: "If type mapping in definition is undefined, set it to - // @id", then step 21.4.2: "If type mapping in definition is neither @id - // nor @vocab, an invalid type mapping error has been detected and - // processing is aborted". The default is what coerces a non-map value of - // the term to an identifier (JSON-LD 1.1 API Section 4.2.2 steps 21.4.1 - // and 21.4.2) - if (container_type) { - if (!definition.type_mapping.has_value()) { - definition.type_mapping = JSON::String{KEYWORD_ID}; - } else if (definition.type_mapping.value() != KEYWORD_ID && - definition.type_mapping.value() != KEYWORD_VOCAB) { - throw JSONLDError("Invalid type mapping", term_pointer, - {KEYWORD_TYPE}); - } - } - } + define_container_mapping(state, term_pointer, value, definition); if (const auto *language_entry{ value.try_at(KEYWORD_LANGUAGE, KEYWORD_LANGUAGE_HASH)}; @@ -620,52 +801,8 @@ auto create_term_definition(ExpansionState &state, } } - if (const auto *context_entry{ - value.try_at(KEYWORD_CONTEXT, KEYWORD_CONTEXT_HASH)}) { - if (state.processing_1_0) { - throw JSONLDError("Invalid term definition", term_pointer, - {KEYWORD_CONTEXT}); - } - // The scoped context is processed here so that it is validated even - // when the term is never used, and however it fails, the term is the one - // at fault. A reference that is already loading is skipped rather than - // followed (JSON-LD 1.1 API Section 4.2.2 step 21) - const bool saved_override{state.protected_override}; - const bool saved_context_protected{state.context_protected}; - const bool saved_validate{state.validate_scoped_context}; - try { - // The error raised here is always discarded below, so its location does - // not matter. - ActiveContext probe{active_context}; - state.protected_override = true; - state.validate_scoped_context = false; - process_context(state, probe, *context_entry, EMPTY_WEAK_POINTER); - state.validate_scoped_context = saved_validate; - state.protected_override = saved_override; - state.context_protected = saved_context_protected; - } catch (const JSONLDError &) { - state.validate_scoped_context = saved_validate; - state.protected_override = saved_override; - state.context_protected = saved_context_protected; - throw JSONLDError("Invalid scoped context", term_pointer, - {KEYWORD_CONTEXT}); - } - definition.context = *context_entry; - definition.context_base = state.context_resolution_base(); - // Step 21.7 keeps the local context of the definition to re-process when - // the term comes into use, so whatever it says wrong then belongs where - // it was written. Only a context the input spells out has entries of its - // own to point into, which a context merged from an import settles one - // term at a time (JSON-LD 1.1 API Section 4.2.2 step 21.7) - definition.context_authored = - !state.foreign_context_location.has_value() || - (state.input_context != nullptr && - state.input_context->defines(term)); - definition.context_location = - definition.context_authored - ? to_pointer(term_pointer.concat(keyword_context())) - : state.foreign_context_location.value(); - } + define_scoped_context(state, active_context, term, term_pointer, value, + definition); // The @reverse step of Create Term Definition sets the term definition and // returns before any @prefix processing, so a reverse property never takes @@ -705,57 +842,12 @@ auto create_term_definition(ExpansionState &state, definition.nest = nest_string; } - if (const auto *index_entry{ - value.try_at(KEYWORD_INDEX, KEYWORD_INDEX_HASH)}) { - if (state.processing_1_0) { - throw JSONLDError("Invalid term definition", term_pointer, - {KEYWORD_INDEX}); - } - bool has_index_container{false}; - for (const auto &item : definition.container) { - if (item == KEYWORD_INDEX) { - has_index_container = true; - } - } - const auto &index{*index_entry}; - if (!index.is_string() || !has_index_container) { - throw JSONLDError("Invalid term definition", term_pointer, - {KEYWORD_INDEX}); - } - const auto &index_string{index.to_string()}; - const auto index_iri{expand_iri(state, active_context, index_string, - false, true, &local_context, &defined, - context_pointer)}; - // The expansion of the value has to name an IRI, which neither a - // keyword nor a term that stayed relative does (JSON-LD 1.1 API Section - // 4.2.2 step 21.2) - if (!index_iri.has_value() || is_keyword(index_iri.value()) || - !URI::is_iri(index_iri.value())) { - throw JSONLDError("Invalid term definition", term_pointer, - {KEYWORD_INDEX}); - } - definition.index = index_string; - definition.index_iri = index_iri.value(); - } + define_index_mapping(state, active_context, local_context, defined, + context_pointer, term_pointer, value, definition); // A term definition may not contain any entry other than the keywords // recognised above. - for (const auto &entry : value.as_object()) { - if (!entry.key_equals(KEYWORD_ID, KEYWORD_ID_HASH) && - !entry.key_equals(KEYWORD_REVERSE, KEYWORD_REVERSE_HASH) && - !entry.key_equals(KEYWORD_CONTAINER, KEYWORD_CONTAINER_HASH) && - !entry.key_equals(KEYWORD_CONTEXT, KEYWORD_CONTEXT_HASH) && - !entry.key_equals(KEYWORD_DIRECTION, KEYWORD_DIRECTION_HASH) && - !entry.key_equals(KEYWORD_INDEX, KEYWORD_INDEX_HASH) && - !entry.key_equals(KEYWORD_LANGUAGE, KEYWORD_LANGUAGE_HASH) && - !entry.key_equals(KEYWORD_NEST, KEYWORD_NEST_HASH) && - !entry.key_equals(KEYWORD_PREFIX, KEYWORD_PREFIX_HASH) && - !entry.key_equals(KEYWORD_PROTECTED, KEYWORD_PROTECTED_HASH) && - !entry.key_equals(KEYWORD_TYPE, KEYWORD_TYPE_HASH)) { - throw JSONLDError("Invalid term definition", term_pointer, - {entry.first}); - } - } + reject_unknown_entries(value, term_pointer); } else { throw JSONLDError("Invalid term definition", term_pointer); } diff --git a/src/spec/jsonld/jsonld_expansion.cc b/src/spec/jsonld/jsonld_expansion.cc index b918c893b..1c46d4d50 100644 --- a/src/spec/jsonld/jsonld_expansion.cc +++ b/src/spec/jsonld/jsonld_expansion.cc @@ -564,6 +564,713 @@ auto expand_object(ExpansionState &state, ActiveContext active_context, return result; } +// Step 13.4.4 of the Expansion algorithm, the @type entry of a map +// (JSON-LD 1.1 API Section 5.1.2 step 13.4.4) +auto expand_type_entry( + ExpansionState &state, const ActiveContext &type_context, JSON &result, + KeywordOrigins &origins, + const std::pair &entry, + const WeakPointer &entry_pointer) -> void { + if (entry.second.is_array()) { + std::size_t type_index{0}; + for (const auto &item : entry.second.as_array()) { + if (!item.is_string()) { + throw JSONLDError("Invalid type value", + entry_pointer.concat(type_index)); + } + type_index += 1; + } + } else if (!entry.second.is_string()) { + throw JSONLDError("Invalid type value", entry_pointer); + } + // Expand each value, preserving whether the input was a string or an + // array. The node-object post-processing later turns a lone string into + // an array, but a value object keeps its @type as a string. + JSON expanded_type{nullptr}; + if (entry.second.is_array()) { + expanded_type = JSON::make_array(); + std::size_t expanded_type_index{0}; + for (const auto &item : entry.second.as_array()) { + // A value that does not expand to an IRI is omitted, so @type stays + // an array of strings. + auto type{expand_type(state, type_context, item)}; + if (type.is_null()) { + report_drop(state, JSONLDExpandDropReason::UndefinedType, + entry_pointer.concat(expanded_type_index), item); + } else { + expanded_type.push_back(std::move(type)); + } + expanded_type_index += 1; + } + } else { + expanded_type = expand_type(state, type_context, entry.second); + } + // A lone @type value that does not expand to an IRI carries nothing, + // which includes carrying no blame for what the element ends up with + if (expanded_type.is_null()) { + report_drop(state, JSONLDExpandDropReason::UndefinedType, entry_pointer, + entry.second); + return; + } + origins.type = entry_pointer; + if (result.defines(KEYWORD_TYPE, KEYWORD_TYPE_HASH)) { + auto merged{ + into_array(std::move(result.at(KEYWORD_TYPE, KEYWORD_TYPE_HASH)))}; + auto expanded_type_array{into_array(std::move(expanded_type))}; + for (auto &item : expanded_type_array.as_array()) { + merged.push_back(item); + } + result.assign(KEYWORD_TYPE, std::move(merged)); + } else { + result.assign_assume_new(JSON::String{KEYWORD_TYPE}, + std::move(expanded_type), KEYWORD_TYPE_HASH); + } +} + +// Steps 13.4.11 and 13.4.12 of the Expansion algorithm, the @list and +// @set entries of a map (JSON-LD 1.1 API Section 5.1.2 steps 13.4.11, +// 13.4.12) +auto expand_collection_entry( + ExpansionState &state, ActiveContext &active_context, JSON &result, + KeywordOrigins &origins, const std::optional &active_property, + const WeakPointer &source_pointer, + const std::pair &entry, + const WeakPointer &entry_pointer, const JSON::String &name) -> void { + // A free-floating list is removed before its items are expanded + // (JSON-LD 1.1 API Section 5.1.2 step 13.4.11.1) + if (name == KEYWORD_LIST && (!active_property.has_value() || + active_property.value() == KEYWORD_GRAPH)) { + report_drop(state, JSONLDExpandDropReason::FreeFloatingValue, entry_pointer, + entry.second); + return; + } + + // A set object expands its value as it stands rather than as an array, + // so a null value expands to null and the collapse below leaves nothing + // for the enclosing property to carry (JSON-LD 1.1 API Section 5.1.2 + // steps 13.4.12 and 18.2) + if (name == KEYWORD_SET && entry.second.is_null()) { + report_drop(state, JSONLDExpandDropReason::NullValue, entry_pointer, + entry.second); + origins.collection = source_pointer; + result.assign(name, JSON{nullptr}); + return; + } + + origins.collection = source_pointer; + auto elements{JSON::make_array()}; + const auto values{into_array(JSON{entry.second})}; + std::size_t value_index{0}; + for (const auto &item : values.as_array()) { + const WeakPointer item_pointer{entry.second.is_array() + ? entry_pointer.concat(value_index) + : entry_pointer}; + auto expanded_item{ + expand(state, active_context, active_property, item, item_pointer)}; + if (expanded_item.is_array()) { + for (auto &nested : expanded_item.as_array()) { + elements.push_back(nested); + } + } else if (!expanded_item.is_null()) { + elements.push_back(std::move(expanded_item)); + } + value_index += 1; + } + // JSON-LD 1.0 refuses a list among the items of a list, whichever + // keyword hands those items over (JSON-LD 1.0 API Expansion Algorithm + // step 3.2) + if (state.processing_1_0 && + collects_into_a_list(active_context, active_property, name)) { + for (const auto &item : elements.as_array()) { + if (is_list_object(item)) { + throw JSONLDError("List of lists", + forbidden_member_pointer( + state, active_context, active_property, + entry.second, entry_pointer, is_list_object)); + } + } + } + result.assign(name, std::move(elements)); +} + +// Step 13.4.6 of the Expansion algorithm, the @included entry of a map +// (JSON-LD 1.1 API Section 5.1.2 step 13.4.6) +auto expand_included_entry( + ExpansionState &state, ActiveContext &active_context, JSON &result, + const std::pair &entry, + const WeakPointer &entry_pointer) -> void { + if (state.processing_1_0) { + return; + } + // Step 13.4.7.2 expands the value with a null active property, which + // would drop the free-floating values step 13.4.7.3 has to reject, so + // the official suite requires a value that is a scalar, a value object, + // or a list object to be an error rather than nothing (suite entries + // #tin07 to #tin09). The keyword stands in as the active property so + // that nothing is dropped before being judged, which also keeps the + // identifier-only node references that the step admits. Each member is + // expanded on its own, so what goes wrong names the input position it + // came from (JSON-LD 1.1 API Section 5.1.2 steps 13.4.7.2 and 13.4.7.3) + auto included{JSON::make_array()}; + const bool from_array{entry.second.is_array()}; + const auto members{into_array(JSON{entry.second})}; + std::size_t member_index{0}; + for (const auto &member : members.as_array()) { + const WeakPointer member_pointer{ + from_array ? entry_pointer.concat(member_index) : entry_pointer}; + auto expanded_member{expand(state, active_context, + JSON::String{KEYWORD_INCLUDED}, member, + member_pointer)}; + // A null member of an array carries nothing over, the way step 5.2.3 + // drops one from any array, whereas a lone null value is no included + // block at all and is held to the same account as any other member + // (JSON-LD 1.1 Section 9.13, JSON-LD 1.1 API Section 5.1.2 step 5.2.3) + auto member_items{ + included_member_items(from_array, std::move(expanded_member))}; + for (auto &item : member_items.as_array()) { + if (is_not_node_object(item)) { + throw JSONLDError( + "Invalid @included value", + forbidden_member_pointer(state, active_context, + JSON::String{KEYWORD_INCLUDED}, member, + member_pointer, is_not_node_object)); + } + included.push_back(std::move(item)); + } + member_index += 1; + } + merge(result, KEYWORD_INCLUDED, std::move(included)); +} + +// Step 13.4.13 of the Expansion algorithm, the @reverse entry of a map +// (JSON-LD 1.1 API Section 5.1.2 step 13.4.13) +auto expand_reverse_entry( + ExpansionState &state, ActiveContext &active_context, JSON &result, + const std::pair &entry, + const WeakPointer &entry_pointer) -> void { + if (!entry.second.is_object()) { + throw JSONLDError("Invalid @reverse value", entry_pointer); + } + auto reversed{expand(state, active_context, JSON::String{KEYWORD_REVERSE}, + entry.second, entry_pointer)}; + if (reversed.is_object()) { + // A keyword whose entry the node already carries is refused as a + // collision further up this very loop, so the map is always made here + // rather than added to. Two terms carrying a reverse mapping reach the + // same map through the merge below instead + assert(result.try_at(KEYWORD_REVERSE, KEYWORD_REVERSE_HASH) == nullptr); + auto reverse_map{JSON::make_object()}; + for (const auto &reverse_entry : reversed.as_object()) { + const auto &reverse_property{reverse_entry.first}; + if (reverse_entry.key_equals(KEYWORD_REVERSE, KEYWORD_REVERSE_HASH)) { + for (const auto &forward : reverse_entry.second.as_object()) { + merge(result, JSON::StringView{forward.first}, + into_array(JSON{forward.second})); + } + } else { + const auto reverse_values{into_array(JSON{reverse_entry.second})}; + for (const auto &item : reverse_values.as_array()) { + if (is_value_or_list_object(item)) { + const SuspendedDropReportingScope silent{state}; + // The map carries its own context into how its keys expand, so + // what it says wrong is located against that same context, + // which is only worth putting together to report it. Reading + // it again outside the expansion that already took it may not + // go through, and a location is not worth an error of its own + ActiveContext reverse_context{active_context}; + if (entry.second.defines(KEYWORD_CONTEXT, KEYWORD_CONTEXT_HASH)) { + try { + process_context( + state, reverse_context, + entry.second.at(KEYWORD_CONTEXT, KEYWORD_CONTEXT_HASH), + entry_pointer.concat(keyword_context())); + } catch (const JSONLDError &) { + reverse_context = active_context; + } + } + + // Several keys of the map may reach the same reverse + // property, and what they carry is merged before it is + // inspected, so each is expanded again to find the one that + // holds the offending member + for (const auto &[input_key, input_value] : + sorted_entries(entry.second)) { + const auto input_property{ + expand_iri(state, reverse_context, *input_key, false, true, + nullptr, nullptr, EMPTY_WEAK_POINTER)}; + if (!input_property.has_value() || + input_property.value() != reverse_property) { + continue; + } + const WeakPointer input_pointer{entry_pointer.concat(*input_key)}; + if (holds_forbidden_member(expand(state, reverse_context, + *input_key, *input_value, + input_pointer), + is_value_or_list_object)) { + throw JSONLDError( + "Invalid reverse property value", + forbidden_member_pointer(state, reverse_context, *input_key, + *input_value, input_pointer, + is_value_or_list_object)); + } + } + + throw JSONLDError("Invalid reverse property value", entry_pointer); + } + } + merge(reverse_map, reverse_property, + into_array(JSON{reverse_entry.second})); + } + } + result.assign(KEYWORD_REVERSE, std::move(reverse_map)); + } +} +// Step 13.4 of the Expansion algorithm: the branch per keyword that an +// expanded property can name. Every branch below names a keyword, so the +// caller is the one that decides whether the entry is one at all (JSON-LD +// 1.1 API Section 5.1.2 step 13.4) +auto expand_keyword_entry( + ExpansionState &state, ActiveContext &active_context, + const ActiveContext &type_context, JSON &result, KeywordOrigins &origins, + const std::optional &active_property, + const WeakPointer &source_pointer, + const std::pair &entry, + const WeakPointer &entry_pointer, const JSON::String &name) -> void { + if (name == KEYWORD_ID) { + if (!entry.second.is_string()) { + throw JSONLDError("Invalid @id value", entry_pointer); + } + const auto identifier{expand_iri(state, active_context, + entry.second.to_string(), true, false, + nullptr, nullptr, EMPTY_WEAK_POINTER)}; + if (identifier.has_value()) { + result.assign_assume_new(JSON::String{KEYWORD_ID}, + JSON{identifier.value()}, KEYWORD_ID_HASH); + } else { + result.assign_assume_new(JSON::String{KEYWORD_ID}, JSON{nullptr}, + KEYWORD_ID_HASH); + } + return; + } + + if (name == KEYWORD_TYPE) { + expand_type_entry(state, type_context, result, origins, entry, + entry_pointer); + return; + } + + if (name == KEYWORD_VALUE) { + origins.value = entry_pointer; + result.assign_assume_new(JSON::String{KEYWORD_VALUE}, JSON{entry.second}, + KEYWORD_VALUE_HASH); + return; + } + + if (name == KEYWORD_LANGUAGE) { + if (!entry.second.is_string()) { + throw JSONLDError("Invalid language-tagged string", entry_pointer); + } + result.assign_assume_new(JSON::String{KEYWORD_LANGUAGE}, JSON{entry.second}, + KEYWORD_LANGUAGE_HASH); + return; + } + + if (name == KEYWORD_DIRECTION) { + if (state.processing_1_0) { + return; + } + if (!entry.second.is_string() || (entry.second.to_string() != "ltr" && + entry.second.to_string() != "rtl")) { + throw JSONLDError("Invalid base direction", entry_pointer); + } + result.assign_assume_new(JSON::String{KEYWORD_DIRECTION}, + JSON{entry.second}, KEYWORD_DIRECTION_HASH); + return; + } + + if (name == KEYWORD_LIST || name == KEYWORD_SET) { + expand_collection_entry(state, active_context, result, origins, + active_property, source_pointer, entry, + entry_pointer, name); + return; + } + + if (name == KEYWORD_GRAPH) { + // @graph expands to an array of node objects, so a value that expands to + // null contributes no element rather than a null one. + auto graph{expand(state, active_context, JSON::String{KEYWORD_GRAPH}, + entry.second, entry_pointer)}; + merge(result, KEYWORD_GRAPH, + graph.is_null() ? JSON::make_array() : into_array(std::move(graph))); + return; + } + + if (name == KEYWORD_INCLUDED) { + expand_included_entry(state, active_context, result, entry, entry_pointer); + return; + } + + if (name == KEYWORD_INDEX) { + if (!entry.second.is_string()) { + throw JSONLDError("Invalid @index value", entry_pointer); + } + result.assign_assume_new(JSON::String{KEYWORD_INDEX}, JSON{entry.second}, + KEYWORD_INDEX_HASH); + return; + } + + if (name == KEYWORD_REVERSE) { + expand_reverse_entry(state, active_context, result, entry, entry_pointer); + return; + } + + // Keywords with no property-level handler (such as @vocab or @none + // reached through an alias) carry no expanded value, so the Expansion + // algorithm adds nothing to the result for them. + report_drop(state, JSONLDExpandDropReason::UnhandledKeyword, entry_pointer, + entry.second); +} + +// Part of step 13.8 of the Expansion algorithm: a value that a @graph +// container indexes by @id or by @index (JSON-LD 1.1 API Section 5.1.2 +// step 13.8) +auto expand_graph_map_entry( + ExpansionState &state, ActiveContext &active_context, + const TermDefinition *definition, const JSON::String &property, + const std::pair &entry, + const WeakPointer &entry_pointer, JSON &expanded_value) -> void { + const bool by_id{container_includes(definition, KEYWORD_ID)}; + // An index mapping is held to naming an IRI that is no keyword when the + // term is made, so a term naming one names a property to index by + // (JSON-LD 1.1 API Section 4.2.2 step 21.2) + const bool property_valued{definition->index.has_value()}; + std::optional index_property; + if (property_valued) { + index_property = + expand_iri(state, active_context, definition->index.value(), false, + true, nullptr, nullptr, EMPTY_WEAK_POINTER); + } + expanded_value = JSON::make_array(); + for (const auto &[graph_key, graph_value] : sorted_entries(entry.second)) { + const JSON::String &index{*graph_key}; + const auto expanded_key{index == KEYWORD_NONE + ? std::optional{KEYWORD_NONE} + : expand_iri(state, active_context, index, true, + false, nullptr, nullptr, + EMPTY_WEAK_POINTER)}; + const bool none_key{expanded_key.has_value() && + expanded_key.value() == KEYWORD_NONE}; + auto graph_items{ + into_array(expand(state, active_context, property, *graph_value, + entry_pointer.concat(index), true))}; + for (auto &item : graph_items.as_array()) { + // Nothing is carried over for a null, as in an array (JSON-LD 1.1 + // API Section 5.1.2 step 5.2.3) + if (item.is_null()) { + continue; + } + + // Wrap the item in a graph object, unless it is already one. What + // the container gathered is a map, anything null having been passed + // over just above + JSON graph{nullptr}; + assert(item.is_object()); + if (item.defines(KEYWORD_GRAPH, KEYWORD_GRAPH_HASH)) { + graph = std::move(item); + } else { + graph = JSON::make_object(); + graph.assign_assume_new(JSON::String{KEYWORD_GRAPH}, + into_array(std::move(item)), + KEYWORD_GRAPH_HASH); + } + if (!none_key) { + if (by_id) { + // The name comes out of expanding the key, and a key shaped like + // a keyword expands to nothing, leaving the algorithm with + // nothing to add rather than a name of its own invention. An + // index container keys by the key as written instead, which is + // why only this one goes through expansion (JSON-LD 1.1 API + // Section 5.1.2) + if (!graph.defines(KEYWORD_ID, KEYWORD_ID_HASH) && + expanded_key.has_value()) { + graph.assign_assume_new(JSON::String{KEYWORD_ID}, + JSON{expanded_key.value()}, + KEYWORD_ID_HASH); + } + } else if (property_valued) { + // A term that no longer names anything carries no metadata + // (JSON-LD 1.1 API Section 5.1.2 step 13.8.3.7.2) + if (index_property.has_value()) { + auto combined{into_array(expand_value( + state, active_context, definition->index, JSON{index}))}; + if (graph.defines(index_property.value())) { + for (auto &existing : + graph.at(index_property.value()).as_array()) { + combined.push_back(existing); + } + } + graph.assign(index_property.value(), std::move(combined)); + } + } else if (!graph.defines(KEYWORD_INDEX, KEYWORD_INDEX_HASH)) { + graph.assign_assume_new(JSON::String{KEYWORD_INDEX}, JSON{index}, + KEYWORD_INDEX_HASH); + } + } + expanded_value.push_back(std::move(graph)); + } + } +} + +// Part of the Expansion algorithm: a value that an @language container +// indexes, where each member is a language tag (JSON-LD 1.1 API Section +// 5.1.2) +auto expand_language_map_entry( + ExpansionState &state, ActiveContext &active_context, + const TermDefinition *definition, + const std::pair &entry, + const WeakPointer &entry_pointer, JSON &expanded_value) -> void { + expanded_value = JSON::make_array(); + for (const auto &[language_key, language_value] : + sorted_entries(entry.second)) { + const JSON::String &language{*language_key}; + const auto expanded_language{expand_iri(state, active_context, language, + false, true, nullptr, nullptr, + EMPTY_WEAK_POINTER)}; + const bool is_none{language == KEYWORD_NONE || + (expanded_language.has_value() && + expanded_language.value() == KEYWORD_NONE)}; + const WeakPointer language_pointer{entry_pointer.concat(language)}; + const bool language_array{language_value->is_array()}; + auto language_items{into_array(JSON{*language_value})}; + std::size_t language_index{0}; + for (auto &item : language_items.as_array()) { + const WeakPointer item_pointer{ + language_array ? language_pointer.concat(language_index) + : language_pointer}; + language_index += 1; + if (item.is_null()) { + report_drop(state, JSONLDExpandDropReason::NullValue, item_pointer, + item); + continue; + } + if (!item.is_string()) { + throw JSONLDError("Invalid language map value", item_pointer); + } + auto value{JSON::make_object()}; + value.assign_assume_new(JSON::String{KEYWORD_VALUE}, JSON{item}, + KEYWORD_VALUE_HASH); + if (!is_none) { + value.assign_assume_new(JSON::String{KEYWORD_LANGUAGE}, JSON{language}, + KEYWORD_LANGUAGE_HASH); + } + const auto direction{definition->has_direction + ? definition->direction + : active_context.default_direction}; + if (direction.has_value()) { + value.assign_assume_new(JSON::String{KEYWORD_DIRECTION}, + JSON{direction.value()}, + KEYWORD_DIRECTION_HASH); + } + expanded_value.push_back(std::move(value)); + } + } +} + +// Part of step 13.8 of the Expansion algorithm: a value that an @index +// container indexes (JSON-LD 1.1 API Section 5.1.2 step 13.8) +auto expand_index_map_entry( + ExpansionState &state, ActiveContext &active_context, + const TermDefinition *definition, const JSON::String &property, + const std::pair &entry, + const WeakPointer &entry_pointer, JSON &expanded_value) -> void { + // An index mapping is held to naming an IRI that is no keyword when the + // term is made, so a term naming one names a property to index by + // (JSON-LD 1.1 API Section 4.2.2 step 21.2) + const bool property_valued{definition->index.has_value()}; + std::optional index_property; + if (property_valued) { + index_property = + expand_iri(state, active_context, definition->index.value(), false, + true, nullptr, nullptr, EMPTY_WEAK_POINTER); + } + expanded_value = JSON::make_array(); + for (const auto &[index_key, index_value] : sorted_entries(entry.second)) { + const JSON::String &index{*index_key}; + // Step 13.8.3.4 initialises "expanded index to the result of IRI + // expanding index", and every step that goes on to add index metadata + // requires that "expanded index is not @none", so an alias of the + // keyword suppresses the metadata exactly as the keyword does + // (JSON-LD 1.1 API Section 5.1.2 steps 13.8.3.4 and 13.8.3.7.2 to + // 13.8.3.7.5) + const auto expanded_index{expand_iri(state, active_context, index, false, + true, nullptr, nullptr, + EMPTY_WEAK_POINTER)}; + const bool index_is_none{expanded_index.has_value() && + expanded_index.value() == KEYWORD_NONE}; + auto index_items{ + into_array(expand(state, active_context, property, *index_value, + entry_pointer.concat(index), true))}; + for (auto &item : index_items.as_array()) { + // An entry of a map expands the way it would as a member of an + // array, where nothing is carried over for a null (JSON-LD 1.1 API + // Section 5.1.2 step 5.2.3), so the steps below only ever see a value + if (item.is_null()) { + continue; + } + + if (!index_is_none) { + if (property_valued) { + // A term that no longer names anything carries no metadata, and + // the value object check that follows the addition does not + // apply when nothing was added (JSON-LD 1.1 API Section 5.1.2 + // step 13.8.3.7.2) + if (index_property.has_value()) { + if (is_value_object(item)) { + throw JSONLDError("Invalid value object", + forbidden_member_pointer( + state, active_context, property, + *index_value, entry_pointer.concat(index), + is_value_object)); + } + // The index value is prepended to any existing values. + auto combined{into_array(expand_value( + state, active_context, definition->index, JSON{index}))}; + if (item.defines(index_property.value())) { + for (auto &existing : + item.at(index_property.value()).as_array()) { + combined.push_back(existing); + } + } + item.assign(index_property.value(), std::move(combined)); + } + } else if (!item.defines(KEYWORD_INDEX, KEYWORD_INDEX_HASH)) { + item.assign_assume_new(JSON::String{KEYWORD_INDEX}, JSON{index}, + KEYWORD_INDEX_HASH); + } + } + expanded_value.push_back(item); + } + } +} + +// Part of step 13.8 of the Expansion algorithm: a value that an @id or an +// @type container indexes (JSON-LD 1.1 API Section 5.1.2 step 13.8) +auto expand_id_type_map_entry( + ExpansionState &state, ActiveContext &active_context, + const TermDefinition *definition, const JSON::String &property, + const std::pair &entry, + const WeakPointer &entry_pointer, JSON &expanded_value) -> void { + const bool by_id{container_includes(definition, KEYWORD_ID)}; + expanded_value = JSON::make_array(); + for (const auto &[map_key, map_value] : sorted_entries(entry.second)) { + const JSON::String &index{*map_key}; + std::optional expanded_index; + if (index != KEYWORD_NONE) { + expanded_index = expand_iri(state, active_context, index, by_id, !by_id, + nullptr, nullptr, EMPTY_WEAK_POINTER); + } + // The key may be an alias of @none, which carries no identifier. + if (expanded_index.has_value() && expanded_index.value() == KEYWORD_NONE) { + expanded_index = std::nullopt; + } + // A type map key may carry a type-scoped context for its values. + // Type-scoped contexts do not propagate, so the values are resolved + // against the context that preceded the containing type-scoped + // context, with only this key's context layered on top. + const ActiveContext *base_context{&active_context}; + if (active_context.previous && !by_id) { + base_context = active_context.previous.get(); + } + ActiveContext entry_context{*base_context}; + if (!by_id) { + // Resolve the type term against the context the copy was made from, + // which outlives the copy being mutated below. + const auto type_definition{base_context->terms.find(index)}; + if (type_definition != base_context->terms.cend() && + type_definition->second.context.has_value()) { + process_deferred_scoped_context(state, entry_context, + type_definition->second, true); + entry_context.previous = nullptr; + } + } + // String values in a type map are node references. The recursion the + // other values take would expand them under the property's own + // context, so the shortcut carries it too (JSON-LD 1.1 API Section + // 5.1.2 steps 13.8.3.6 and 4.2) + ActiveContext reference_scope; + ActiveContext *reference_context{&entry_context}; + if (!by_id && definition->context.has_value()) { + reference_scope = entry_context; + reference_scope.previous = nullptr; + apply_scoped_context(state, reference_scope, *definition); + reference_context = &reference_scope; + } + + auto entries{JSON::make_array()}; + const bool value_array{map_value->is_array()}; + auto raw_values{into_array(JSON{*map_value})}; + std::size_t raw_index{0}; + for (auto &raw : raw_values.as_array()) { + // An entry holding an array is located by the element the value came + // from, as an array of properties is + const WeakPointer entry_value_pointer{entry_pointer.concat(index)}; + const WeakPointer raw_pointer{value_array + ? entry_value_pointer.concat(raw_index) + : entry_value_pointer}; + raw_index += 1; + if (raw.is_string() && !by_id) { + auto reference{JSON::make_object()}; + // A container that gathers by type is given a type mapping when + // the term is made, defaulting to the identifier (JSON-LD 1.1 API + // Section 4.2.2 step 21.4.1) + assert(definition->type_mapping.has_value()); + const bool reference_vocab{definition->type_mapping.value() == + KEYWORD_VOCAB}; + const auto &raw_string{raw.to_string()}; + const auto referenced{expand_iri(state, *reference_context, raw_string, + true, reference_vocab, nullptr, + nullptr, EMPTY_WEAK_POINTER)}; + reference.assign_assume_new(JSON::String{KEYWORD_ID}, + JSON{referenced.value_or(raw_string)}, + KEYWORD_ID_HASH); + entries.push_back(std::move(reference)); + } else { + auto expanded_items{into_array( + expand(state, entry_context, property, raw, raw_pointer, true))}; + for (auto &expanded : expanded_items.as_array()) { + // Nothing is carried over for a null, as in an array + // (JSON-LD 1.1 API Section 5.1.2 step 5.2.3) + if (!expanded.is_null()) { + entries.push_back(expanded); + } + } + } + } + for (auto &item : entries.as_array()) { + if (expanded_index.has_value()) { + if (by_id) { + if (!item.defines(KEYWORD_ID, KEYWORD_ID_HASH)) { + item.assign_assume_new(JSON::String{KEYWORD_ID}, + JSON{expanded_index.value()}, + KEYWORD_ID_HASH); + } + } else { + auto types{JSON::make_array()}; + types.push_back(JSON{expanded_index.value()}); + if (item.defines(KEYWORD_TYPE, KEYWORD_TYPE_HASH)) { + auto existing_types{into_array( + std::move(item.at(KEYWORD_TYPE, KEYWORD_TYPE_HASH)))}; + for (auto &existing : existing_types.as_array()) { + types.push_back(existing); + } + } + item.assign(KEYWORD_TYPE, std::move(types)); + } + } + expanded_value.push_back(item); + } + } +} auto expand_entries(ExpansionState &state, ActiveContext &active_context, const ActiveContext &type_context, JSON &result, KeywordOrigins &origins, @@ -644,323 +1351,10 @@ auto expand_entries(ExpansionState &state, ActiveContext &active_context, throw JSONLDError("Colliding keywords", entry_pointer); } - if (name == KEYWORD_ID) { - if (!entry.second.is_string()) { - throw JSONLDError("Invalid @id value", entry_pointer); - } - const auto identifier{expand_iri(state, active_context, - entry.second.to_string(), true, false, - nullptr, nullptr, EMPTY_WEAK_POINTER)}; - if (identifier.has_value()) { - result.assign_assume_new(JSON::String{KEYWORD_ID}, - JSON{identifier.value()}, KEYWORD_ID_HASH); - } else { - result.assign_assume_new(JSON::String{KEYWORD_ID}, JSON{nullptr}, - KEYWORD_ID_HASH); - } - continue; - } - - if (name == KEYWORD_TYPE) { - if (entry.second.is_array()) { - std::size_t type_index{0}; - for (const auto &item : entry.second.as_array()) { - if (!item.is_string()) { - throw JSONLDError("Invalid type value", - entry_pointer.concat(type_index)); - } - type_index += 1; - } - } else if (!entry.second.is_string()) { - throw JSONLDError("Invalid type value", entry_pointer); - } - // Expand each value, preserving whether the input was a string or an - // array. The node-object post-processing later turns a lone string into - // an array, but a value object keeps its @type as a string. - JSON expanded_type{nullptr}; - if (entry.second.is_array()) { - expanded_type = JSON::make_array(); - std::size_t expanded_type_index{0}; - for (const auto &item : entry.second.as_array()) { - // A value that does not expand to an IRI is omitted, so @type stays - // an array of strings. - auto type{expand_type(state, type_context, item)}; - if (type.is_null()) { - report_drop(state, JSONLDExpandDropReason::UndefinedType, - entry_pointer.concat(expanded_type_index), item); - } else { - expanded_type.push_back(std::move(type)); - } - expanded_type_index += 1; - } - } else { - expanded_type = expand_type(state, type_context, entry.second); - } - // A lone @type value that does not expand to an IRI carries nothing, - // which includes carrying no blame for what the element ends up with - if (expanded_type.is_null()) { - report_drop(state, JSONLDExpandDropReason::UndefinedType, entry_pointer, - entry.second); - continue; - } - origins.type = entry_pointer; - if (result.defines(KEYWORD_TYPE, KEYWORD_TYPE_HASH)) { - auto merged{ - into_array(std::move(result.at(KEYWORD_TYPE, KEYWORD_TYPE_HASH)))}; - auto expanded_type_array{into_array(std::move(expanded_type))}; - for (auto &item : expanded_type_array.as_array()) { - merged.push_back(item); - } - result.assign(KEYWORD_TYPE, std::move(merged)); - } else { - result.assign_assume_new(JSON::String{KEYWORD_TYPE}, - std::move(expanded_type), KEYWORD_TYPE_HASH); - } - continue; - } - - if (name == KEYWORD_VALUE) { - origins.value = entry_pointer; - result.assign_assume_new(JSON::String{KEYWORD_VALUE}, JSON{entry.second}, - KEYWORD_VALUE_HASH); - continue; - } - - if (name == KEYWORD_LANGUAGE) { - if (!entry.second.is_string()) { - throw JSONLDError("Invalid language-tagged string", entry_pointer); - } - result.assign_assume_new(JSON::String{KEYWORD_LANGUAGE}, - JSON{entry.second}, KEYWORD_LANGUAGE_HASH); - continue; - } - - if (name == KEYWORD_DIRECTION) { - if (state.processing_1_0) { - continue; - } - if (!entry.second.is_string() || (entry.second.to_string() != "ltr" && - entry.second.to_string() != "rtl")) { - throw JSONLDError("Invalid base direction", entry_pointer); - } - result.assign_assume_new(JSON::String{KEYWORD_DIRECTION}, - JSON{entry.second}, KEYWORD_DIRECTION_HASH); - continue; - } - - if (name == KEYWORD_LIST || name == KEYWORD_SET) { - // A free-floating list is removed before its items are expanded - // (JSON-LD 1.1 API Section 5.1.2 step 13.4.11.1) - if (name == KEYWORD_LIST && (!active_property.has_value() || - active_property.value() == KEYWORD_GRAPH)) { - report_drop(state, JSONLDExpandDropReason::FreeFloatingValue, - entry_pointer, entry.second); - continue; - } - - // A set object expands its value as it stands rather than as an array, - // so a null value expands to null and the collapse below leaves nothing - // for the enclosing property to carry (JSON-LD 1.1 API Section 5.1.2 - // steps 13.4.12 and 18.2) - if (name == KEYWORD_SET && entry.second.is_null()) { - report_drop(state, JSONLDExpandDropReason::NullValue, entry_pointer, - entry.second); - origins.collection = source_pointer; - result.assign(name, JSON{nullptr}); - continue; - } - - origins.collection = source_pointer; - auto elements{JSON::make_array()}; - const auto values{into_array(JSON{entry.second})}; - std::size_t value_index{0}; - for (const auto &item : values.as_array()) { - const WeakPointer item_pointer{entry.second.is_array() - ? entry_pointer.concat(value_index) - : entry_pointer}; - auto expanded_item{ - expand(state, active_context, active_property, item, item_pointer)}; - if (expanded_item.is_array()) { - for (auto &nested : expanded_item.as_array()) { - elements.push_back(nested); - } - } else if (!expanded_item.is_null()) { - elements.push_back(std::move(expanded_item)); - } - value_index += 1; - } - // JSON-LD 1.0 refuses a list among the items of a list, whichever - // keyword hands those items over (JSON-LD 1.0 API Expansion Algorithm - // step 3.2) - if (state.processing_1_0 && - collects_into_a_list(active_context, active_property, name)) { - for (const auto &item : elements.as_array()) { - if (is_list_object(item)) { - throw JSONLDError("List of lists", - forbidden_member_pointer( - state, active_context, active_property, - entry.second, entry_pointer, is_list_object)); - } - } - } - result.assign(name, std::move(elements)); - continue; - } - - if (name == KEYWORD_GRAPH) { - // @graph expands to an array of node objects, so a value that expands to - // null contributes no element rather than a null one. - auto graph{expand(state, active_context, JSON::String{KEYWORD_GRAPH}, - entry.second, entry_pointer)}; - merge(result, KEYWORD_GRAPH, - graph.is_null() ? JSON::make_array() - : into_array(std::move(graph))); - continue; - } - - if (name == KEYWORD_INCLUDED) { - if (state.processing_1_0) { - continue; - } - // Step 13.4.7.2 expands the value with a null active property, which - // would drop the free-floating values step 13.4.7.3 has to reject, so - // the official suite requires a value that is a scalar, a value object, - // or a list object to be an error rather than nothing (suite entries - // #tin07 to #tin09). The keyword stands in as the active property so - // that nothing is dropped before being judged, which also keeps the - // identifier-only node references that the step admits. Each member is - // expanded on its own, so what goes wrong names the input position it - // came from (JSON-LD 1.1 API Section 5.1.2 steps 13.4.7.2 and 13.4.7.3) - auto included{JSON::make_array()}; - const bool from_array{entry.second.is_array()}; - const auto members{into_array(JSON{entry.second})}; - std::size_t member_index{0}; - for (const auto &member : members.as_array()) { - const WeakPointer member_pointer{ - from_array ? entry_pointer.concat(member_index) : entry_pointer}; - auto expanded_member{expand(state, active_context, - JSON::String{KEYWORD_INCLUDED}, member, - member_pointer)}; - // A null member of an array carries nothing over, the way step 5.2.3 - // drops one from any array, whereas a lone null value is no included - // block at all and is held to the same account as any other member - // (JSON-LD 1.1 Section 9.13, JSON-LD 1.1 API Section 5.1.2 step 5.2.3) - auto member_items{ - included_member_items(from_array, std::move(expanded_member))}; - for (auto &item : member_items.as_array()) { - if (is_not_node_object(item)) { - throw JSONLDError( - "Invalid @included value", - forbidden_member_pointer(state, active_context, - JSON::String{KEYWORD_INCLUDED}, member, - member_pointer, is_not_node_object)); - } - included.push_back(std::move(item)); - } - member_index += 1; - } - merge(result, KEYWORD_INCLUDED, std::move(included)); - continue; - } - - if (name == KEYWORD_INDEX) { - if (!entry.second.is_string()) { - throw JSONLDError("Invalid @index value", entry_pointer); - } - result.assign_assume_new(JSON::String{KEYWORD_INDEX}, JSON{entry.second}, - KEYWORD_INDEX_HASH); - continue; - } - - if (name == KEYWORD_REVERSE) { - if (!entry.second.is_object()) { - throw JSONLDError("Invalid @reverse value", entry_pointer); - } - auto reversed{expand(state, active_context, JSON::String{KEYWORD_REVERSE}, - entry.second, entry_pointer)}; - if (reversed.is_object()) { - // A keyword whose entry the node already carries is refused as a - // collision further up this very loop, so the map is always made here - // rather than added to. Two terms carrying a reverse mapping reach the - // same map through the merge below instead - assert(result.try_at(KEYWORD_REVERSE, KEYWORD_REVERSE_HASH) == nullptr); - auto reverse_map{JSON::make_object()}; - for (const auto &reverse_entry : reversed.as_object()) { - const auto &reverse_property{reverse_entry.first}; - if (reverse_entry.key_equals(KEYWORD_REVERSE, KEYWORD_REVERSE_HASH)) { - for (const auto &forward : reverse_entry.second.as_object()) { - merge(result, JSON::StringView{forward.first}, - into_array(JSON{forward.second})); - } - } else { - const auto reverse_values{into_array(JSON{reverse_entry.second})}; - for (const auto &item : reverse_values.as_array()) { - if (is_value_or_list_object(item)) { - const SuspendedDropReportingScope silent{state}; - // The map carries its own context into how its keys expand, so - // what it says wrong is located against that same context, - // which is only worth putting together to report it. Reading - // it again outside the expansion that already took it may not - // go through, and a location is not worth an error of its own - ActiveContext reverse_context{active_context}; - if (entry.second.defines(KEYWORD_CONTEXT, - KEYWORD_CONTEXT_HASH)) { - try { - process_context( - state, reverse_context, - entry.second.at(KEYWORD_CONTEXT, KEYWORD_CONTEXT_HASH), - entry_pointer.concat(keyword_context())); - } catch (const JSONLDError &) { - reverse_context = active_context; - } - } - - // Several keys of the map may reach the same reverse - // property, and what they carry is merged before it is - // inspected, so each is expanded again to find the one that - // holds the offending member - for (const auto &[input_key, input_value] : - sorted_entries(entry.second)) { - const auto input_property{ - expand_iri(state, reverse_context, *input_key, false, - true, nullptr, nullptr, EMPTY_WEAK_POINTER)}; - if (!input_property.has_value() || - input_property.value() != reverse_property) { - continue; - } - const WeakPointer input_pointer{ - entry_pointer.concat(*input_key)}; - if (holds_forbidden_member(expand(state, reverse_context, - *input_key, *input_value, - input_pointer), - is_value_or_list_object)) { - throw JSONLDError("Invalid reverse property value", - forbidden_member_pointer( - state, reverse_context, *input_key, - *input_value, input_pointer, - is_value_or_list_object)); - } - } - - throw JSONLDError("Invalid reverse property value", - entry_pointer); - } - } - merge(reverse_map, reverse_property, - into_array(JSON{reverse_entry.second})); - } - } - result.assign(KEYWORD_REVERSE, std::move(reverse_map)); - } - continue; - } - if (is_keyword(name)) { - // Keywords with no property-level handler (such as @vocab or @none - // reached through an alias) carry no expanded value, so the Expansion - // algorithm adds nothing to the result for them. - report_drop(state, JSONLDExpandDropReason::UnhandledKeyword, - entry_pointer, entry.second); + expand_keyword_entry(state, active_context, type_context, result, origins, + active_property, source_pointer, entry, + entry_pointer, name); continue; } @@ -984,320 +1378,21 @@ auto expand_entries(ExpansionState &state, ActiveContext &active_context, container_includes(definition, KEYWORD_GRAPH) && (container_includes(definition, KEYWORD_ID) || container_includes(definition, KEYWORD_INDEX))) { - const bool by_id{container_includes(definition, KEYWORD_ID)}; - // An index mapping is held to naming an IRI that is no keyword when the - // term is made, so a term naming one names a property to index by - // (JSON-LD 1.1 API Section 4.2.2 step 21.2) - const bool property_valued{definition->index.has_value()}; - std::optional index_property; - if (property_valued) { - index_property = - expand_iri(state, active_context, definition->index.value(), false, - true, nullptr, nullptr, EMPTY_WEAK_POINTER); - } - expanded_value = JSON::make_array(); - for (const auto &[graph_key, graph_value] : - sorted_entries(entry.second)) { - const JSON::String &index{*graph_key}; - const auto expanded_key{index == KEYWORD_NONE - ? std::optional{KEYWORD_NONE} - : expand_iri(state, active_context, index, - true, false, nullptr, nullptr, - EMPTY_WEAK_POINTER)}; - const bool none_key{expanded_key.has_value() && - expanded_key.value() == KEYWORD_NONE}; - auto graph_items{ - into_array(expand(state, active_context, property, *graph_value, - entry_pointer.concat(index), true))}; - for (auto &item : graph_items.as_array()) { - // Nothing is carried over for a null, as in an array (JSON-LD 1.1 - // API Section 5.1.2 step 5.2.3) - if (item.is_null()) { - continue; - } - - // Wrap the item in a graph object, unless it is already one. What - // the container gathered is a map, anything null having been passed - // over just above - JSON graph{nullptr}; - assert(item.is_object()); - if (item.defines(KEYWORD_GRAPH, KEYWORD_GRAPH_HASH)) { - graph = std::move(item); - } else { - graph = JSON::make_object(); - graph.assign_assume_new(JSON::String{KEYWORD_GRAPH}, - into_array(std::move(item)), - KEYWORD_GRAPH_HASH); - } - if (!none_key) { - if (by_id) { - // The name comes out of expanding the key, and a key shaped like - // a keyword expands to nothing, leaving the algorithm with - // nothing to add rather than a name of its own invention. An - // index container keys by the key as written instead, which is - // why only this one goes through expansion (JSON-LD 1.1 API - // Section 5.1.2) - if (!graph.defines(KEYWORD_ID, KEYWORD_ID_HASH) && - expanded_key.has_value()) { - graph.assign_assume_new(JSON::String{KEYWORD_ID}, - JSON{expanded_key.value()}, - KEYWORD_ID_HASH); - } - } else if (property_valued) { - // A term that no longer names anything carries no metadata - // (JSON-LD 1.1 API Section 5.1.2 step 13.8.3.7.2) - if (index_property.has_value()) { - auto combined{into_array(expand_value( - state, active_context, definition->index, JSON{index}))}; - if (graph.defines(index_property.value())) { - for (auto &existing : - graph.at(index_property.value()).as_array()) { - combined.push_back(existing); - } - } - graph.assign(index_property.value(), std::move(combined)); - } - } else if (!graph.defines(KEYWORD_INDEX, KEYWORD_INDEX_HASH)) { - graph.assign_assume_new(JSON::String{KEYWORD_INDEX}, JSON{index}, - KEYWORD_INDEX_HASH); - } - } - expanded_value.push_back(std::move(graph)); - } - } + expand_graph_map_entry(state, active_context, definition, property, entry, + entry_pointer, expanded_value); } else if (entry.second.is_object() && container_includes(definition, KEYWORD_LANGUAGE)) { - expanded_value = JSON::make_array(); - for (const auto &[language_key, language_value] : - sorted_entries(entry.second)) { - const JSON::String &language{*language_key}; - const auto expanded_language{expand_iri(state, active_context, language, - false, true, nullptr, nullptr, - EMPTY_WEAK_POINTER)}; - const bool is_none{language == KEYWORD_NONE || - (expanded_language.has_value() && - expanded_language.value() == KEYWORD_NONE)}; - const WeakPointer language_pointer{entry_pointer.concat(language)}; - const bool language_array{language_value->is_array()}; - auto language_items{into_array(JSON{*language_value})}; - std::size_t language_index{0}; - for (auto &item : language_items.as_array()) { - const WeakPointer item_pointer{ - language_array ? language_pointer.concat(language_index) - : language_pointer}; - language_index += 1; - if (item.is_null()) { - report_drop(state, JSONLDExpandDropReason::NullValue, item_pointer, - item); - continue; - } - if (!item.is_string()) { - throw JSONLDError("Invalid language map value", item_pointer); - } - auto value{JSON::make_object()}; - value.assign_assume_new(JSON::String{KEYWORD_VALUE}, JSON{item}, - KEYWORD_VALUE_HASH); - if (!is_none) { - value.assign_assume_new(JSON::String{KEYWORD_LANGUAGE}, - JSON{language}, KEYWORD_LANGUAGE_HASH); - } - const auto direction{definition->has_direction - ? definition->direction - : active_context.default_direction}; - if (direction.has_value()) { - value.assign_assume_new(JSON::String{KEYWORD_DIRECTION}, - JSON{direction.value()}, - KEYWORD_DIRECTION_HASH); - } - expanded_value.push_back(std::move(value)); - } - } + expand_language_map_entry(state, active_context, definition, entry, + entry_pointer, expanded_value); } else if (entry.second.is_object() && container_includes(definition, KEYWORD_INDEX)) { - // An index mapping is held to naming an IRI that is no keyword when the - // term is made, so a term naming one names a property to index by - // (JSON-LD 1.1 API Section 4.2.2 step 21.2) - const bool property_valued{definition->index.has_value()}; - std::optional index_property; - if (property_valued) { - index_property = - expand_iri(state, active_context, definition->index.value(), false, - true, nullptr, nullptr, EMPTY_WEAK_POINTER); - } - expanded_value = JSON::make_array(); - for (const auto &[index_key, index_value] : - sorted_entries(entry.second)) { - const JSON::String &index{*index_key}; - // Step 13.8.3.4 initialises "expanded index to the result of IRI - // expanding index", and every step that goes on to add index metadata - // requires that "expanded index is not @none", so an alias of the - // keyword suppresses the metadata exactly as the keyword does - // (JSON-LD 1.1 API Section 5.1.2 steps 13.8.3.4 and 13.8.3.7.2 to - // 13.8.3.7.5) - const auto expanded_index{expand_iri(state, active_context, index, - false, true, nullptr, nullptr, - EMPTY_WEAK_POINTER)}; - const bool index_is_none{expanded_index.has_value() && - expanded_index.value() == KEYWORD_NONE}; - auto index_items{ - into_array(expand(state, active_context, property, *index_value, - entry_pointer.concat(index), true))}; - for (auto &item : index_items.as_array()) { - // An entry of a map expands the way it would as a member of an - // array, where nothing is carried over for a null (JSON-LD 1.1 API - // Section 5.1.2 step 5.2.3), so the steps below only ever see a value - if (item.is_null()) { - continue; - } - - if (!index_is_none) { - if (property_valued) { - // A term that no longer names anything carries no metadata, and - // the value object check that follows the addition does not - // apply when nothing was added (JSON-LD 1.1 API Section 5.1.2 - // step 13.8.3.7.2) - if (index_property.has_value()) { - if (is_value_object(item)) { - throw JSONLDError( - "Invalid value object", - forbidden_member_pointer( - state, active_context, property, *index_value, - entry_pointer.concat(index), is_value_object)); - } - // The index value is prepended to any existing values. - auto combined{into_array(expand_value( - state, active_context, definition->index, JSON{index}))}; - if (item.defines(index_property.value())) { - for (auto &existing : - item.at(index_property.value()).as_array()) { - combined.push_back(existing); - } - } - item.assign(index_property.value(), std::move(combined)); - } - } else if (!item.defines(KEYWORD_INDEX, KEYWORD_INDEX_HASH)) { - item.assign_assume_new(JSON::String{KEYWORD_INDEX}, JSON{index}, - KEYWORD_INDEX_HASH); - } - } - expanded_value.push_back(item); - } - } + expand_index_map_entry(state, active_context, definition, property, entry, + entry_pointer, expanded_value); } else if (entry.second.is_object() && (container_includes(definition, KEYWORD_ID) || container_includes(definition, KEYWORD_TYPE))) { - const bool by_id{container_includes(definition, KEYWORD_ID)}; - expanded_value = JSON::make_array(); - for (const auto &[map_key, map_value] : sorted_entries(entry.second)) { - const JSON::String &index{*map_key}; - std::optional expanded_index; - if (index != KEYWORD_NONE) { - expanded_index = - expand_iri(state, active_context, index, by_id, !by_id, nullptr, - nullptr, EMPTY_WEAK_POINTER); - } - // The key may be an alias of @none, which carries no identifier. - if (expanded_index.has_value() && - expanded_index.value() == KEYWORD_NONE) { - expanded_index = std::nullopt; - } - // A type map key may carry a type-scoped context for its values. - // Type-scoped contexts do not propagate, so the values are resolved - // against the context that preceded the containing type-scoped - // context, with only this key's context layered on top. - const ActiveContext *base_context{&active_context}; - if (active_context.previous && !by_id) { - base_context = active_context.previous.get(); - } - ActiveContext entry_context{*base_context}; - if (!by_id) { - // Resolve the type term against the context the copy was made from, - // which outlives the copy being mutated below. - const auto type_definition{base_context->terms.find(index)}; - if (type_definition != base_context->terms.cend() && - type_definition->second.context.has_value()) { - process_deferred_scoped_context(state, entry_context, - type_definition->second, true); - entry_context.previous = nullptr; - } - } - // String values in a type map are node references. The recursion the - // other values take would expand them under the property's own - // context, so the shortcut carries it too (JSON-LD 1.1 API Section - // 5.1.2 steps 13.8.3.6 and 4.2) - ActiveContext reference_scope; - ActiveContext *reference_context{&entry_context}; - if (!by_id && definition->context.has_value()) { - reference_scope = entry_context; - reference_scope.previous = nullptr; - apply_scoped_context(state, reference_scope, *definition); - reference_context = &reference_scope; - } - - auto entries{JSON::make_array()}; - const bool value_array{map_value->is_array()}; - auto raw_values{into_array(JSON{*map_value})}; - std::size_t raw_index{0}; - for (auto &raw : raw_values.as_array()) { - // An entry holding an array is located by the element the value came - // from, as an array of properties is - const WeakPointer entry_value_pointer{entry_pointer.concat(index)}; - const WeakPointer raw_pointer{ - value_array ? entry_value_pointer.concat(raw_index) - : entry_value_pointer}; - raw_index += 1; - if (raw.is_string() && !by_id) { - auto reference{JSON::make_object()}; - // A container that gathers by type is given a type mapping when - // the term is made, defaulting to the identifier (JSON-LD 1.1 API - // Section 4.2.2 step 21.4.1) - assert(definition->type_mapping.has_value()); - const bool reference_vocab{definition->type_mapping.value() == - KEYWORD_VOCAB}; - const auto &raw_string{raw.to_string()}; - const auto referenced{expand_iri( - state, *reference_context, raw_string, true, reference_vocab, - nullptr, nullptr, EMPTY_WEAK_POINTER)}; - reference.assign_assume_new(JSON::String{KEYWORD_ID}, - JSON{referenced.value_or(raw_string)}, - KEYWORD_ID_HASH); - entries.push_back(std::move(reference)); - } else { - auto expanded_items{into_array(expand( - state, entry_context, property, raw, raw_pointer, true))}; - for (auto &expanded : expanded_items.as_array()) { - // Nothing is carried over for a null, as in an array - // (JSON-LD 1.1 API Section 5.1.2 step 5.2.3) - if (!expanded.is_null()) { - entries.push_back(expanded); - } - } - } - } - for (auto &item : entries.as_array()) { - if (expanded_index.has_value()) { - if (by_id) { - if (!item.defines(KEYWORD_ID, KEYWORD_ID_HASH)) { - item.assign_assume_new(JSON::String{KEYWORD_ID}, - JSON{expanded_index.value()}, - KEYWORD_ID_HASH); - } - } else { - auto types{JSON::make_array()}; - types.push_back(JSON{expanded_index.value()}); - if (item.defines(KEYWORD_TYPE, KEYWORD_TYPE_HASH)) { - auto existing_types{into_array( - std::move(item.at(KEYWORD_TYPE, KEYWORD_TYPE_HASH)))}; - for (auto &existing : existing_types.as_array()) { - types.push_back(existing); - } - } - item.assign(KEYWORD_TYPE, std::move(types)); - } - } - expanded_value.push_back(item); - } - } + expand_id_type_map_entry(state, active_context, definition, property, + entry, entry_pointer, expanded_value); } else if (container_includes(definition, KEYWORD_GRAPH)) { auto graph_value{ expand(state, active_context, property, entry.second, entry_pointer)}; diff --git a/src/spec/jsonld/jsonld_iri_compaction.cc b/src/spec/jsonld/jsonld_iri_compaction.cc index 14bd55e7c..a976296df 100644 --- a/src/spec/jsonld/jsonld_iri_compaction.cc +++ b/src/spec/jsonld/jsonld_iri_compaction.cc @@ -65,307 +65,319 @@ auto relativize(const JSON::String &iri, const JSON::String &base) return relative; } -} // namespace +// Steps 2 to 4 of IRI Compaction: the term that the inverse context picks +// for the value, where it names one (JSON-LD 1.1 API Section 6.2) +auto select_compact_term(const ActiveContext &active_context, + const JSON &inverse_context, + const JSON::String &variable, const JSON *const value, + const bool vocabulary, const bool reverse) + -> std::optional { + if (!vocabulary || !inverse_context.defines(variable)) { + return std::nullopt; + } -auto compact_iri(const ActiveContext &active_context, - const JSON &inverse_context, const JSON::String &variable, - const JSON *const value, const bool vocabulary, - const bool reverse) -> JSON::String { - if (variable.empty()) { - return variable; + // When a default base direction is set, the default language is the + // language and direction joined by an underscore, even if there is no + // default language (Section 6.2.2). + JSON::String default_language{KEYWORD_NONE}; + if (active_context.default_direction.has_value()) { + default_language = active_context.default_language.has_value() + ? lowercase(active_context.default_language.value()) + : JSON::String{}; + default_language += "_"; + default_language += lowercase(active_context.default_direction.value()); + } else if (active_context.default_language.has_value()) { + default_language = lowercase(active_context.default_language.value()); } - if (vocabulary && inverse_context.defines(variable)) { - // When a default base direction is set, the default language is the - // language and direction joined by an underscore, even if there is no - // default language (Section 6.2.2). - JSON::String default_language{KEYWORD_NONE}; - if (active_context.default_direction.has_value()) { - default_language = - active_context.default_language.has_value() - ? lowercase(active_context.default_language.value()) - : JSON::String{}; - default_language += "_"; - default_language += lowercase(active_context.default_direction.value()); - } else if (active_context.default_language.has_value()) { - default_language = lowercase(active_context.default_language.value()); - } + std::vector containers; + JSON::String type_language{KEYWORD_LANGUAGE}; + JSON::String type_language_value{KEYWORD_NULL}; - std::vector containers; - JSON::String type_language{KEYWORD_LANGUAGE}; - JSON::String type_language_value{KEYWORD_NULL}; + const bool is_object{value != nullptr && value->is_object()}; + const bool has_index{is_object && + value->defines(KEYWORD_INDEX, KEYWORD_INDEX_HASH)}; + const bool is_graph{is_object && + value->defines(KEYWORD_GRAPH, KEYWORD_GRAPH_HASH)}; - const bool is_object{value != nullptr && value->is_object()}; - const bool has_index{is_object && - value->defines(KEYWORD_INDEX, KEYWORD_INDEX_HASH)}; - const bool is_graph{is_object && - value->defines(KEYWORD_GRAPH, KEYWORD_GRAPH_HASH)}; + if (has_index && !is_graph) { + containers.emplace_back(KEYWORD_INDEX); + containers.emplace_back(JSON::String{KEYWORD_INDEX} + + JSON::String{KEYWORD_SET}); + } - if (has_index && !is_graph) { + if (reverse) { + type_language = KEYWORD_TYPE; + type_language_value = KEYWORD_REVERSE; + containers.emplace_back(KEYWORD_SET); + containers.emplace_back(KEYWORD_NONE); + // JSON-LD 1.1 API Section 6.2.2: the @index and @index@set candidates are + // added only when the processing mode is not json-ld-1.0 and the value + // carries no @index entry + if (!active_context.processing_1_0 && !has_index) { containers.emplace_back(KEYWORD_INDEX); containers.emplace_back(JSON::String{KEYWORD_INDEX} + JSON::String{KEYWORD_SET}); } - - if (reverse) { - type_language = KEYWORD_TYPE; - type_language_value = KEYWORD_REVERSE; - containers.emplace_back(KEYWORD_SET); - containers.emplace_back(KEYWORD_NONE); - // JSON-LD 1.1 API Section 6.2.2: the @index and @index@set candidates are - // added only when the processing mode is not json-ld-1.0 and the value - // carries no @index entry - if (!active_context.processing_1_0 && !has_index) { - containers.emplace_back(KEYWORD_INDEX); - containers.emplace_back(JSON::String{KEYWORD_INDEX} + - JSON::String{KEYWORD_SET}); - } - } else if (is_graph) { - const JSON::String graph{KEYWORD_GRAPH}; - const JSON::String set{KEYWORD_SET}; - const bool has_id{value->defines(KEYWORD_ID, KEYWORD_ID_HASH)}; - // Container preference for a graph object: the @graph@index and @graph@id - // variants rank first only when the value carries the matching entry, - // otherwise the plain graph containers rank ahead of them (JSON-LD 1.1 - // API Section 6.2.2) - if (has_index) { - containers.emplace_back(graph + JSON::String{KEYWORD_INDEX}); - containers.emplace_back(graph + JSON::String{KEYWORD_INDEX} + set); - } - if (has_id) { - containers.emplace_back(graph + JSON::String{KEYWORD_ID}); - containers.emplace_back(graph + JSON::String{KEYWORD_ID} + set); - } - containers.emplace_back(graph); - containers.emplace_back(graph + set); - containers.emplace_back(KEYWORD_SET); - if (!has_index) { - containers.emplace_back(graph + JSON::String{KEYWORD_INDEX}); - containers.emplace_back(graph + JSON::String{KEYWORD_INDEX} + set); - } - if (!has_id) { - containers.emplace_back(graph + JSON::String{KEYWORD_ID}); - containers.emplace_back(graph + JSON::String{KEYWORD_ID} + set); - } - containers.emplace_back(KEYWORD_INDEX); - containers.emplace_back(JSON::String{KEYWORD_INDEX} + set); - // The graph-object candidate list ends with @none as a last resort, after - // every graph container above, so a graph object still compacts against a - // term with no container mapping when the active context defines no - // graph-container term for its property (W3C JSON-LD 1.1 compaction suite - // cases 0090 through 0094) - containers.emplace_back(KEYWORD_NONE); - type_language = KEYWORD_TYPE; - type_language_value = KEYWORD_ID; - } else if (is_object && value->defines(KEYWORD_LIST, KEYWORD_LIST_HASH)) { - if (!has_index) { - containers.emplace_back(KEYWORD_LIST); - } - const auto &list{value->at(KEYWORD_LIST, KEYWORD_LIST_HASH)}; - std::optional common_type; - std::optional common_language; - if (list.empty()) { - common_language = default_language; - } - for (const auto &item : list.as_array()) { - JSON::String item_language{KEYWORD_NONE}; - JSON::String item_type{KEYWORD_NONE}; - // What a list holds in expanded form is maps, which the entry point - // holds the input to - assert(item.is_object()); - if (item.defines(KEYWORD_VALUE, KEYWORD_VALUE_HASH)) { - const bool item_has_language{ - item.defines(KEYWORD_LANGUAGE, KEYWORD_LANGUAGE_HASH)}; - const bool item_has_direction{ - item.defines(KEYWORD_DIRECTION, KEYWORD_DIRECTION_HASH)}; - if (item_has_language && item_has_direction) { - item_language = - lowercase(item.at(KEYWORD_LANGUAGE, KEYWORD_LANGUAGE_HASH) - .to_string()) + - "_" + - lowercase(item.at(KEYWORD_DIRECTION, KEYWORD_DIRECTION_HASH) - .to_string()); - } else if (item_has_language) { - item_language = lowercase( - item.at(KEYWORD_LANGUAGE, KEYWORD_LANGUAGE_HASH).to_string()); - } else if (item_has_direction) { - item_language = "_" + lowercase(item.at(KEYWORD_DIRECTION, - KEYWORD_DIRECTION_HASH) - .to_string()); - } else if (item.defines(KEYWORD_TYPE, KEYWORD_TYPE_HASH)) { - item_type = item.at(KEYWORD_TYPE, KEYWORD_TYPE_HASH).to_string(); - } else { - item_language = KEYWORD_NULL; - } + } else if (is_graph) { + const JSON::String graph{KEYWORD_GRAPH}; + const JSON::String set{KEYWORD_SET}; + const bool has_id{value->defines(KEYWORD_ID, KEYWORD_ID_HASH)}; + // Container preference for a graph object: the @graph@index and @graph@id + // variants rank first only when the value carries the matching entry, + // otherwise the plain graph containers rank ahead of them (JSON-LD 1.1 + // API Section 6.2.2) + if (has_index) { + containers.emplace_back(graph + JSON::String{KEYWORD_INDEX}); + containers.emplace_back(graph + JSON::String{KEYWORD_INDEX} + set); + } + if (has_id) { + containers.emplace_back(graph + JSON::String{KEYWORD_ID}); + containers.emplace_back(graph + JSON::String{KEYWORD_ID} + set); + } + containers.emplace_back(graph); + containers.emplace_back(graph + set); + containers.emplace_back(KEYWORD_SET); + if (!has_index) { + containers.emplace_back(graph + JSON::String{KEYWORD_INDEX}); + containers.emplace_back(graph + JSON::String{KEYWORD_INDEX} + set); + } + if (!has_id) { + containers.emplace_back(graph + JSON::String{KEYWORD_ID}); + containers.emplace_back(graph + JSON::String{KEYWORD_ID} + set); + } + containers.emplace_back(KEYWORD_INDEX); + containers.emplace_back(JSON::String{KEYWORD_INDEX} + set); + // The graph-object candidate list ends with @none as a last resort, after + // every graph container above, so a graph object still compacts against a + // term with no container mapping when the active context defines no + // graph-container term for its property (W3C JSON-LD 1.1 compaction suite + // cases 0090 through 0094) + containers.emplace_back(KEYWORD_NONE); + type_language = KEYWORD_TYPE; + type_language_value = KEYWORD_ID; + } else if (is_object && value->defines(KEYWORD_LIST, KEYWORD_LIST_HASH)) { + if (!has_index) { + containers.emplace_back(KEYWORD_LIST); + } + const auto &list{value->at(KEYWORD_LIST, KEYWORD_LIST_HASH)}; + std::optional common_type; + std::optional common_language; + if (list.empty()) { + common_language = default_language; + } + for (const auto &item : list.as_array()) { + JSON::String item_language{KEYWORD_NONE}; + JSON::String item_type{KEYWORD_NONE}; + // What a list holds in expanded form is maps, which the entry point + // holds the input to + assert(item.is_object()); + if (item.defines(KEYWORD_VALUE, KEYWORD_VALUE_HASH)) { + const bool item_has_language{ + item.defines(KEYWORD_LANGUAGE, KEYWORD_LANGUAGE_HASH)}; + const bool item_has_direction{ + item.defines(KEYWORD_DIRECTION, KEYWORD_DIRECTION_HASH)}; + if (item_has_language && item_has_direction) { + item_language = + lowercase(item.at(KEYWORD_LANGUAGE, KEYWORD_LANGUAGE_HASH) + .to_string()) + + "_" + + lowercase(item.at(KEYWORD_DIRECTION, KEYWORD_DIRECTION_HASH) + .to_string()); + } else if (item_has_language) { + item_language = lowercase( + item.at(KEYWORD_LANGUAGE, KEYWORD_LANGUAGE_HASH).to_string()); + } else if (item_has_direction) { + item_language = + "_" + lowercase(item.at(KEYWORD_DIRECTION, KEYWORD_DIRECTION_HASH) + .to_string()); + } else if (item.defines(KEYWORD_TYPE, KEYWORD_TYPE_HASH)) { + item_type = item.at(KEYWORD_TYPE, KEYWORD_TYPE_HASH).to_string(); } else { - item_type = KEYWORD_ID; - } - if (!common_language.has_value()) { - common_language = item_language; - } else if (common_language.value() != item_language && - item.defines(KEYWORD_VALUE, KEYWORD_VALUE_HASH)) { - common_language = JSON::String{KEYWORD_NONE}; + item_language = KEYWORD_NULL; } - if (!common_type.has_value()) { - common_type = item_type; - } else if (common_type.value() != item_type) { - common_type = JSON::String{KEYWORD_NONE}; - } - } - // An empty list takes the default language, and any other settles one - // from its first item, so the language is spoken for either way - assert(common_language.has_value()); - if (!common_type.has_value()) { - common_type = JSON::String{KEYWORD_NONE}; - } - if (common_type.value() != KEYWORD_NONE) { - type_language = KEYWORD_TYPE; - type_language_value = common_type.value(); } else { - type_language_value = common_language.value(); + item_type = KEYWORD_ID; } - // An empty list matches a term via the @any fallback. - if (list.empty()) { - type_language = KEYWORD_ANY; + if (!common_language.has_value()) { + common_language = item_language; + } else if (common_language.value() != item_language && + item.defines(KEYWORD_VALUE, KEYWORD_VALUE_HASH)) { + common_language = JSON::String{KEYWORD_NONE}; } - // Fall back to an exact-match term when no list-container term applies. - containers.emplace_back(KEYWORD_NONE); - } else if (is_object && value->defines(KEYWORD_VALUE, KEYWORD_VALUE_HASH)) { - const bool has_language{ - value->defines(KEYWORD_LANGUAGE, KEYWORD_LANGUAGE_HASH)}; - const bool has_direction{ - value->defines(KEYWORD_DIRECTION, KEYWORD_DIRECTION_HASH)}; - const JSON::String language_set{JSON::String{KEYWORD_LANGUAGE} + - JSON::String{KEYWORD_SET}}; - if (has_direction && !has_index) { - type_language_value = - (has_language - ? lowercase(value->at(KEYWORD_LANGUAGE, KEYWORD_LANGUAGE_HASH) - .to_string()) - : JSON::String{}) + - "_" + - lowercase(value->at(KEYWORD_DIRECTION, KEYWORD_DIRECTION_HASH) - .to_string()); - containers.emplace_back(KEYWORD_LANGUAGE); - containers.emplace_back(language_set); - } else if (has_language && !has_index) { - type_language_value = lowercase( - value->at(KEYWORD_LANGUAGE, KEYWORD_LANGUAGE_HASH).to_string()); - containers.emplace_back(KEYWORD_LANGUAGE); - containers.emplace_back(language_set); - } else if (value->defines(KEYWORD_TYPE, KEYWORD_TYPE_HASH)) { - type_language = KEYWORD_TYPE; - type_language_value = - value->at(KEYWORD_TYPE, KEYWORD_TYPE_HASH).to_string(); - } - containers.emplace_back(KEYWORD_SET); - containers.emplace_back(KEYWORD_NONE); - // A value with no @index entry may also match an @index container, but - // never under the 1.0 processing mode (JSON-LD 1.1 API Section 6.2.2) - if (!active_context.processing_1_0 && !has_index) { - containers.emplace_back(KEYWORD_INDEX); - containers.emplace_back(JSON::String{KEYWORD_INDEX} + - JSON::String{KEYWORD_SET}); - } - // JSON-LD 1.1 API Section 6.2.2: a value object carrying only @value also - // matches a language container term as a last resort, but only when the - // processing mode is not json-ld-1.0 - if (!active_context.processing_1_0 && value->object_size() == 1) { - containers.emplace_back(KEYWORD_LANGUAGE); - containers.emplace_back(language_set); + if (!common_type.has_value()) { + common_type = item_type; + } else if (common_type.value() != item_type) { + common_type = JSON::String{KEYWORD_NONE}; } + } + // An empty list takes the default language, and any other settles one + // from its first item, so the language is spoken for either way + assert(common_language.has_value()); + if (!common_type.has_value()) { + common_type = JSON::String{KEYWORD_NONE}; + } + if (common_type.value() != KEYWORD_NONE) { + type_language = KEYWORD_TYPE; + type_language_value = common_type.value(); } else { + type_language_value = common_language.value(); + } + // An empty list matches a term via the @any fallback. + if (list.empty()) { + type_language = KEYWORD_ANY; + } + // Fall back to an exact-match term when no list-container term applies. + containers.emplace_back(KEYWORD_NONE); + } else if (is_object && value->defines(KEYWORD_VALUE, KEYWORD_VALUE_HASH)) { + const bool has_language{ + value->defines(KEYWORD_LANGUAGE, KEYWORD_LANGUAGE_HASH)}; + const bool has_direction{ + value->defines(KEYWORD_DIRECTION, KEYWORD_DIRECTION_HASH)}; + const JSON::String language_set{JSON::String{KEYWORD_LANGUAGE} + + JSON::String{KEYWORD_SET}}; + if (has_direction && !has_index) { + type_language_value = + (has_language + ? lowercase(value->at(KEYWORD_LANGUAGE, KEYWORD_LANGUAGE_HASH) + .to_string()) + : JSON::String{}) + + "_" + + lowercase( + value->at(KEYWORD_DIRECTION, KEYWORD_DIRECTION_HASH).to_string()); + containers.emplace_back(KEYWORD_LANGUAGE); + containers.emplace_back(language_set); + } else if (has_language && !has_index) { + type_language_value = lowercase( + value->at(KEYWORD_LANGUAGE, KEYWORD_LANGUAGE_HASH).to_string()); + containers.emplace_back(KEYWORD_LANGUAGE); + containers.emplace_back(language_set); + } else if (value->defines(KEYWORD_TYPE, KEYWORD_TYPE_HASH)) { type_language = KEYWORD_TYPE; - type_language_value = KEYWORD_ID; - // Container preference for a node reference or null: the @id and @type - // containers first, then a plain @set, then no container, and an @index - // container last (JSON-LD 1.1 API Section 6.2.2) - containers.emplace_back(KEYWORD_ID); - containers.emplace_back(JSON::String{KEYWORD_ID} + + type_language_value = + value->at(KEYWORD_TYPE, KEYWORD_TYPE_HASH).to_string(); + } + containers.emplace_back(KEYWORD_SET); + containers.emplace_back(KEYWORD_NONE); + // A value with no @index entry may also match an @index container, but + // never under the 1.0 processing mode (JSON-LD 1.1 API Section 6.2.2) + if (!active_context.processing_1_0 && !has_index) { + containers.emplace_back(KEYWORD_INDEX); + containers.emplace_back(JSON::String{KEYWORD_INDEX} + JSON::String{KEYWORD_SET}); - containers.emplace_back(KEYWORD_TYPE); - containers.emplace_back(JSON::String{KEYWORD_SET} + - JSON::String{KEYWORD_TYPE}); - containers.emplace_back(KEYWORD_SET); - containers.emplace_back(KEYWORD_NONE); - // JSON-LD 1.1 API Section 6.2.2: the @index and @index@set candidates are - // added only when the processing mode is not json-ld-1.0 and the value - // carries no @index entry - if (!active_context.processing_1_0 && !has_index) { - containers.emplace_back(KEYWORD_INDEX); - containers.emplace_back(JSON::String{KEYWORD_INDEX} + - JSON::String{KEYWORD_SET}); - } } - - std::vector preferred; - if (type_language_value == KEYWORD_REVERSE) { - preferred.emplace_back(KEYWORD_REVERSE); + // JSON-LD 1.1 API Section 6.2.2: a value object carrying only @value also + // matches a language container term as a last resort, but only when the + // processing mode is not json-ld-1.0 + if (!active_context.processing_1_0 && value->object_size() == 1) { + containers.emplace_back(KEYWORD_LANGUAGE); + containers.emplace_back(language_set); } - if ((type_language_value == KEYWORD_ID || - type_language_value == KEYWORD_REVERSE) && - is_object && value->defines(KEYWORD_ID, KEYWORD_ID_HASH)) { - // An identifier is a string in expanded form, which the entry point - // holds the input to - const auto &identifier{value->at(KEYWORD_ID, KEYWORD_ID_HASH)}; - assert(identifier.is_string()); - { - const auto compacted_id{compact_iri(active_context, inverse_context, - identifier.to_string(), nullptr, - true, false)}; - // A term whose name carries a colon must expand onto the very IRI it - // maps, so a term found under a name settled on above maps that IRI - // where it maps anything at all (JSON-LD 1.1 API Section 4.2.2 step 16) - const auto iterator{active_context.terms.find(compacted_id)}; - assert(iterator == active_context.terms.cend() || - !iterator->second.iri.has_value() || - iterator->second.iri.value() == identifier.to_string()); - if (iterator != active_context.terms.cend() && - iterator->second.iri.has_value()) { - preferred.emplace_back(KEYWORD_VOCAB); - preferred.emplace_back(KEYWORD_ID); - preferred.emplace_back(KEYWORD_NONE); - } else { - preferred.emplace_back(KEYWORD_ID); - preferred.emplace_back(KEYWORD_VOCAB); - preferred.emplace_back(KEYWORD_NONE); - } - } - } else if (value == nullptr) { - // For a bare value the preferred list is the type or language value - // followed by @none (JSON-LD 1.1 API Section 6.2.2). The @vocab candidate - // is not literally listed there for this case, but it is load-bearing: - // the W3C compaction suite case 0114 regresses without it, so a bare - // vocabulary reference must also be allowed to match a term coercing - // @vocab, exactly as the @none candidate is required for the graph branch - preferred.emplace_back(KEYWORD_ID); - preferred.emplace_back(KEYWORD_VOCAB); - preferred.emplace_back(KEYWORD_NONE); - } else { - preferred.emplace_back(type_language_value); - preferred.emplace_back(KEYWORD_NONE); + } else { + type_language = KEYWORD_TYPE; + type_language_value = KEYWORD_ID; + // Container preference for a node reference or null: the @id and @type + // containers first, then a plain @set, then no container, and an @index + // container last (JSON-LD 1.1 API Section 6.2.2) + containers.emplace_back(KEYWORD_ID); + containers.emplace_back(JSON::String{KEYWORD_ID} + + JSON::String{KEYWORD_SET}); + containers.emplace_back(KEYWORD_TYPE); + containers.emplace_back(JSON::String{KEYWORD_SET} + + JSON::String{KEYWORD_TYPE}); + containers.emplace_back(KEYWORD_SET); + containers.emplace_back(KEYWORD_NONE); + // JSON-LD 1.1 API Section 6.2.2: the @index and @index@set candidates are + // added only when the processing mode is not json-ld-1.0 and the value + // carries no @index entry + if (!active_context.processing_1_0 && !has_index) { + containers.emplace_back(KEYWORD_INDEX); + containers.emplace_back(JSON::String{KEYWORD_INDEX} + + JSON::String{KEYWORD_SET}); } - preferred.emplace_back(KEYWORD_ANY); + } - // A language-and-direction preferred value also allows matching a term that - // only coerces direction, via the substring from the underscore onwards. - std::vector direction_fallbacks; - for (const auto &item : preferred) { - const auto underscore{item.find('_')}; - if (underscore != JSON::String::npos) { - direction_fallbacks.emplace_back(item.substr(underscore)); + std::vector preferred; + if (type_language_value == KEYWORD_REVERSE) { + preferred.emplace_back(KEYWORD_REVERSE); + } + if ((type_language_value == KEYWORD_ID || + type_language_value == KEYWORD_REVERSE) && + is_object && value->defines(KEYWORD_ID, KEYWORD_ID_HASH)) { + // An identifier is a string in expanded form, which the entry point + // holds the input to + const auto &identifier{value->at(KEYWORD_ID, KEYWORD_ID_HASH)}; + assert(identifier.is_string()); + { + const auto compacted_id{compact_iri(active_context, inverse_context, + identifier.to_string(), nullptr, true, + false)}; + // A term whose name carries a colon must expand onto the very IRI it + // maps, so a term found under a name settled on above maps that IRI + // where it maps anything at all (JSON-LD 1.1 API Section 4.2.2 step 16) + const auto iterator{active_context.terms.find(compacted_id)}; + assert(iterator == active_context.terms.cend() || + !iterator->second.iri.has_value() || + iterator->second.iri.value() == identifier.to_string()); + if (iterator != active_context.terms.cend() && + iterator->second.iri.has_value()) { + preferred.emplace_back(KEYWORD_VOCAB); + preferred.emplace_back(KEYWORD_ID); + preferred.emplace_back(KEYWORD_NONE); + } else { + preferred.emplace_back(KEYWORD_ID); + preferred.emplace_back(KEYWORD_VOCAB); + preferred.emplace_back(KEYWORD_NONE); } } - for (auto &fallback : direction_fallbacks) { - preferred.push_back(std::move(fallback)); - } + } else if (value == nullptr) { + // For a bare value the preferred list is the type or language value + // followed by @none (JSON-LD 1.1 API Section 6.2.2). The @vocab candidate + // is not literally listed there for this case, but it is load-bearing: + // the W3C compaction suite case 0114 regresses without it, so a bare + // vocabulary reference must also be allowed to match a term coercing + // @vocab, exactly as the @none candidate is required for the graph branch + preferred.emplace_back(KEYWORD_ID); + preferred.emplace_back(KEYWORD_VOCAB); + preferred.emplace_back(KEYWORD_NONE); + } else { + preferred.emplace_back(type_language_value); + preferred.emplace_back(KEYWORD_NONE); + } + preferred.emplace_back(KEYWORD_ANY); - const auto term{term_selection(inverse_context, variable, containers, - type_language, preferred)}; - if (term.has_value()) { - return term.value(); + // A language-and-direction preferred value also allows matching a term that + // only coerces direction, via the substring from the underscore onwards. + std::vector direction_fallbacks; + for (const auto &item : preferred) { + const auto underscore{item.find('_')}; + if (underscore != JSON::String::npos) { + direction_fallbacks.emplace_back(item.substr(underscore)); } } + for (auto &fallback : direction_fallbacks) { + preferred.push_back(std::move(fallback)); + } + + const auto term{term_selection(inverse_context, variable, containers, + type_language, preferred)}; + return term; +} +} // namespace + +auto compact_iri(const ActiveContext &active_context, + const JSON &inverse_context, const JSON::String &variable, + const JSON *const value, const bool vocabulary, + const bool reverse) -> JSON::String { + if (variable.empty()) { + return variable; + } + + const auto selected{select_compact_term( + active_context, inverse_context, variable, value, vocabulary, reverse)}; + if (selected.has_value()) { + return selected.value(); + } // Compact relative to @vocab. if (vocabulary && active_context.vocabulary.has_value()) { diff --git a/src/spec/jsonpath/jsonpath.cc b/src/spec/jsonpath/jsonpath.cc index 3e7f0714b..c55d060e8 100644 --- a/src/spec/jsonpath/jsonpath.cc +++ b/src/spec/jsonpath/jsonpath.cc @@ -290,6 +290,242 @@ struct FilterWorkItem { std::size_t cursor; }; +// Mutually recursive with visit_selector below +auto filter_query_visit(const std::vector &segments, + const std::size_t cursor, const JSON ¤t, + const JSON &root, FilterCollector &collector, + const std::size_t depth = 0) -> bool; + +// What one selector of a segment contributes, pushed onto the work stack +// rather than followed down +template +auto push_selector_work(const JSON ¤t, const JSON &root, + const FilterWorkItem &item, + std::vector &pool, + const Selector &selector, const JSON::Type type) + -> void { + switch (static_cast(selector->index())) { + case JSONPath::SelectorKind::Name: + if (type == JSON::Type::Object) { + const auto *entry{std::get_if(selector)}; + const auto *child{current.try_at(entry->name, entry->hash)}; + if (child != nullptr) { + pool.push_back({.node = child, .cursor = item.cursor + 1}); + } + } + + break; + case JSONPath::SelectorKind::Wildcard: + if (type == JSON::Type::Object) { + const auto &object{current.as_object()}; + auto [member, members_end]{member_range(object)}; + for (; member != members_end; ++member) { + pool.push_back({.node = &member->second, .cursor = item.cursor + 1}); + } + } else if (type == JSON::Type::Array) { + const auto &array{current.as_array()}; + auto [element, elements_end]{element_range(array)}; + for (; element != elements_end; ++element) { + pool.push_back({.node = element, .cursor = item.cursor + 1}); + } + } + + break; + case JSONPath::SelectorKind::Index: + if (type == JSON::Type::Array) { + const auto *entry{std::get_if(selector)}; + const auto &array{current.as_array()}; + const auto size{static_cast(array.size())}; + const auto index{entry->index < 0 ? entry->index + size : entry->index}; + if (index >= 0 && index < size) { + pool.push_back( + {.node = first_element(array) + static_cast(index), + .cursor = item.cursor + 1}); + } + } + + break; + case JSONPath::SelectorKind::Slice: { + const auto *entry{std::get_if(selector)}; + if (type == JSON::Type::Array) { + const auto &array{current.as_array()}; + const auto size{static_cast(array.size())}; + std::int64_t lower{0}; + std::int64_t upper{0}; + if (!slice_bounds(*entry, size, lower, upper)) { + break; + } + + const auto *const array_base{first_element(array)}; + if (entry->step > 0) { + for (auto index{lower}; index < upper; index += entry->step) { + pool.push_back( + {.node = array_base + static_cast(index), + .cursor = item.cursor + 1}); + } + } else { + for (auto index{upper}; index > lower; index += entry->step) { + pool.push_back( + {.node = array_base + static_cast(index), + .cursor = item.cursor + 1}); + } + } + } + + break; + } + SOURCEMETA_CORE_JSONPATH_SELECTOR_FILTER: { + const auto *entry{std::get_if(selector)}; + if (type == JSON::Type::Object) { + const auto &object{current.as_object()}; + auto [member, members_end]{member_range(object)}; + for (; member != members_end; ++member) { + if (filter_matches(entry->expression, member->second, root)) { + pool.push_back( + {.node = &member->second, .cursor = item.cursor + 1}); + } + } + } else if (type == JSON::Type::Array) { + const auto &array{current.as_array()}; + auto [element, elements_end]{element_range(array)}; + for (; element != elements_end; ++element) { + if (filter_matches(entry->expression, *element, root)) { + pool.push_back({.node = element, .cursor = item.cursor + 1}); + } + } + } + + break; + } + } +} + +// What one selector of a segment contributes, following each match down +// the segments that remain. Answers whether the walk carries on +template +auto visit_selector(const std::vector &segments, + const std::size_t cursor, const JSON ¤t, + const JSON &root, FilterCollector &collector, + const std::size_t depth, const Selector &selector, + const JSON::Type type) -> bool { + switch (static_cast(selector->index())) { + case JSONPath::SelectorKind::Name: { + const auto *entry{std::get_if(selector)}; + if (type == JSON::Type::Object) { + const auto *child{current.try_at(entry->name, entry->hash)}; + if (child != nullptr && + !filter_query_visit(segments, cursor + 1, *child, root, collector, + depth + 1)) { + return false; + } + } + + break; + } + case JSONPath::SelectorKind::Wildcard: + if (type == JSON::Type::Object) { + const auto &object{current.as_object()}; + auto [member, members_end]{member_range(object)}; + for (; member != members_end; ++member) { + if (!filter_query_visit(segments, cursor + 1, member->second, root, + collector, depth + 1)) { + return false; + } + } + } else if (type == JSON::Type::Array) { + const auto &array{current.as_array()}; + auto [element, elements_end]{element_range(array)}; + for (; element != elements_end; ++element) { + if (!filter_query_visit(segments, cursor + 1, *element, root, + collector, depth + 1)) { + return false; + } + } + } + + break; + case JSONPath::SelectorKind::Index: { + const auto *entry{std::get_if(selector)}; + if (type == JSON::Type::Array) { + const auto &array{current.as_array()}; + const auto size{static_cast(array.size())}; + const auto index{entry->index < 0 ? entry->index + size : entry->index}; + if (index >= 0 && index < size && + !filter_query_visit( + segments, cursor + 1, + *(first_element(array) + static_cast(index)), root, + collector, depth + 1)) { + return false; + } + } + + break; + } + case JSONPath::SelectorKind::Slice: { + const auto *entry{std::get_if(selector)}; + if (type == JSON::Type::Array) { + const auto &array{current.as_array()}; + const auto size{static_cast(array.size())}; + std::int64_t lower{0}; + std::int64_t upper{0}; + if (!slice_bounds(*entry, size, lower, upper)) { + break; + } + + const auto *const array_base{first_element(array)}; + if (entry->step > 0) { + for (auto index{lower}; index < upper; index += entry->step) { + if (!filter_query_visit( + segments, cursor + 1, + *(array_base + static_cast(index)), root, + collector, depth + 1)) { + return false; + } + } + } else { + for (auto index{upper}; index > lower; index += entry->step) { + if (!filter_query_visit( + segments, cursor + 1, + *(array_base + static_cast(index)), root, + collector, depth + 1)) { + return false; + } + } + } + } + + break; + } + SOURCEMETA_CORE_JSONPATH_SELECTOR_FILTER: { + const auto *entry{std::get_if(selector)}; + if (type == JSON::Type::Object) { + const auto &object{current.as_object()}; + auto [member, members_end]{member_range(object)}; + for (; member != members_end; ++member) { + if (filter_matches(entry->expression, member->second, root) && + !filter_query_visit(segments, cursor + 1, member->second, root, + collector, depth + 1)) { + return false; + } + } + } else if (type == JSON::Type::Array) { + const auto &array{current.as_array()}; + auto [element, elements_end]{element_range(array)}; + for (; element != elements_end; ++element) { + if (filter_matches(entry->expression, *element, root) && + !filter_query_visit(segments, cursor + 1, *element, root, + collector, depth + 1)) { + return false; + } + } + } + + break; + } + } + + return true; +} auto filter_query_visit_iterative( const std::vector &segments, const std::size_t cursor, const JSON &origin, const JSON &root, FilterCollector &collector) -> bool { @@ -351,102 +587,7 @@ auto filter_query_visit_iterative( const auto *selector{segment.selectors.data()}; const auto *const selectors_end{selector + segment.selectors.size()}; for (; selector != selectors_end; ++selector) { - switch (static_cast(selector->index())) { - case JSONPath::SelectorKind::Name: - if (type == JSON::Type::Object) { - const auto *entry{std::get_if(selector)}; - const auto *child{current.try_at(entry->name, entry->hash)}; - if (child != nullptr) { - pool.push_back({.node = child, .cursor = item.cursor + 1}); - } - } - - break; - case JSONPath::SelectorKind::Wildcard: - if (type == JSON::Type::Object) { - const auto &object{current.as_object()}; - auto [member, members_end]{member_range(object)}; - for (; member != members_end; ++member) { - pool.push_back( - {.node = &member->second, .cursor = item.cursor + 1}); - } - } else if (type == JSON::Type::Array) { - const auto &array{current.as_array()}; - auto [element, elements_end]{element_range(array)}; - for (; element != elements_end; ++element) { - pool.push_back({.node = element, .cursor = item.cursor + 1}); - } - } - - break; - case JSONPath::SelectorKind::Index: - if (type == JSON::Type::Array) { - const auto *entry{std::get_if(selector)}; - const auto &array{current.as_array()}; - const auto size{static_cast(array.size())}; - const auto index{entry->index < 0 ? entry->index + size - : entry->index}; - if (index >= 0 && index < size) { - pool.push_back({.node = first_element(array) + - static_cast(index), - .cursor = item.cursor + 1}); - } - } - - break; - case JSONPath::SelectorKind::Slice: { - const auto *entry{std::get_if(selector)}; - if (type == JSON::Type::Array) { - const auto &array{current.as_array()}; - const auto size{static_cast(array.size())}; - std::int64_t lower{0}; - std::int64_t upper{0}; - if (!slice_bounds(*entry, size, lower, upper)) { - break; - } - - const auto *const array_base{first_element(array)}; - if (entry->step > 0) { - for (auto index{lower}; index < upper; index += entry->step) { - pool.push_back( - {.node = array_base + static_cast(index), - .cursor = item.cursor + 1}); - } - } else { - for (auto index{upper}; index > lower; index += entry->step) { - pool.push_back( - {.node = array_base + static_cast(index), - .cursor = item.cursor + 1}); - } - } - } - - break; - } - SOURCEMETA_CORE_JSONPATH_SELECTOR_FILTER: { - const auto *entry{std::get_if(selector)}; - if (type == JSON::Type::Object) { - const auto &object{current.as_object()}; - auto [member, members_end]{member_range(object)}; - for (; member != members_end; ++member) { - if (filter_matches(entry->expression, member->second, root)) { - pool.push_back( - {.node = &member->second, .cursor = item.cursor + 1}); - } - } - } else if (type == JSON::Type::Array) { - const auto &array{current.as_array()}; - auto [element, elements_end]{element_range(array)}; - for (; element != elements_end; ++element) { - if (filter_matches(entry->expression, *element, root)) { - pool.push_back({.node = element, .cursor = item.cursor + 1}); - } - } - } - - break; - } - } + push_selector_work(current, root, item, pool, selector, type); } if (segment.descendant) { @@ -481,7 +622,7 @@ constexpr std::size_t JSONPATH_EVALUATION_RECURSION_LIMIT{256}; auto filter_query_visit(const std::vector &segments, const std::size_t cursor, const JSON ¤t, const JSON &root, FilterCollector &collector, - const std::size_t depth = 0) -> bool { + const std::size_t depth) -> bool { if (depth >= JSONPATH_EVALUATION_RECURSION_LIMIT) { return filter_query_visit_iterative(segments, cursor, current, root, collector); @@ -530,121 +671,9 @@ auto filter_query_visit(const std::vector &segments, const auto *selector{segment.selectors.data()}; const auto *const selectors_end{selector + segment.selectors.size()}; for (; selector != selectors_end; ++selector) { - switch (static_cast(selector->index())) { - case JSONPath::SelectorKind::Name: { - const auto *entry{std::get_if(selector)}; - if (type == JSON::Type::Object) { - const auto *child{current.try_at(entry->name, entry->hash)}; - if (child != nullptr && - !filter_query_visit(segments, cursor + 1, *child, root, collector, - depth + 1)) { - return false; - } - } - - break; - } - case JSONPath::SelectorKind::Wildcard: - if (type == JSON::Type::Object) { - const auto &object{current.as_object()}; - auto [member, members_end]{member_range(object)}; - for (; member != members_end; ++member) { - if (!filter_query_visit(segments, cursor + 1, member->second, root, - collector, depth + 1)) { - return false; - } - } - } else if (type == JSON::Type::Array) { - const auto &array{current.as_array()}; - auto [element, elements_end]{element_range(array)}; - for (; element != elements_end; ++element) { - if (!filter_query_visit(segments, cursor + 1, *element, root, - collector, depth + 1)) { - return false; - } - } - } - - break; - case JSONPath::SelectorKind::Index: { - const auto *entry{std::get_if(selector)}; - if (type == JSON::Type::Array) { - const auto &array{current.as_array()}; - const auto size{static_cast(array.size())}; - const auto index{entry->index < 0 ? entry->index + size - : entry->index}; - if (index >= 0 && index < size && - !filter_query_visit( - segments, cursor + 1, - *(first_element(array) + static_cast(index)), - root, collector, depth + 1)) { - return false; - } - } - - break; - } - case JSONPath::SelectorKind::Slice: { - const auto *entry{std::get_if(selector)}; - if (type == JSON::Type::Array) { - const auto &array{current.as_array()}; - const auto size{static_cast(array.size())}; - std::int64_t lower{0}; - std::int64_t upper{0}; - if (!slice_bounds(*entry, size, lower, upper)) { - break; - } - - const auto *const array_base{first_element(array)}; - if (entry->step > 0) { - for (auto index{lower}; index < upper; index += entry->step) { - if (!filter_query_visit( - segments, cursor + 1, - *(array_base + static_cast(index)), root, - collector, depth + 1)) { - return false; - } - } - } else { - for (auto index{upper}; index > lower; index += entry->step) { - if (!filter_query_visit( - segments, cursor + 1, - *(array_base + static_cast(index)), root, - collector, depth + 1)) { - return false; - } - } - } - } - - break; - } - SOURCEMETA_CORE_JSONPATH_SELECTOR_FILTER: { - const auto *entry{std::get_if(selector)}; - if (type == JSON::Type::Object) { - const auto &object{current.as_object()}; - auto [member, members_end]{member_range(object)}; - for (; member != members_end; ++member) { - if (filter_matches(entry->expression, member->second, root) && - !filter_query_visit(segments, cursor + 1, member->second, root, - collector, depth + 1)) { - return false; - } - } - } else if (type == JSON::Type::Array) { - const auto &array{current.as_array()}; - auto [element, elements_end]{element_range(array)}; - for (; element != elements_end; ++element) { - if (filter_matches(entry->expression, *element, root) && - !filter_query_visit(segments, cursor + 1, *element, root, - collector, depth + 1)) { - return false; - } - } - } - - break; - } + if (!visit_selector(segments, cursor, current, root, collector, depth, + selector, type)) { + return false; } } @@ -974,6 +1003,112 @@ inline auto filter_matches(const JSONPath::FilterExpression &expression, #endif } +// What one selector of a segment contributes to the evaluation stack +template +inline auto evaluate_selector(const JSON ¤t, const WorkItem &item, + WorkStack &stack, EvaluationState &state, + const Selector &selector, const JSON::Type type, + const std::size_t child_depth) -> void { + switch (static_cast(selector->index())) { + case JSONPath::SelectorKind::Name: + if (type == JSON::Type::Object) { + const auto *entry{std::get_if(selector)}; + const auto *child{current.try_at(entry->name, entry->hash)}; + if (child != nullptr) { + stack.push_visit_property(child, item.cursor + 1, child_depth, + entry->name, entry->hash); + } + } + + break; + case JSONPath::SelectorKind::Wildcard: + if (type == JSON::Type::Object) { + const auto &object{current.as_object()}; + auto [member, members_end]{member_range(object)}; + for (; member != members_end; ++member) { + stack.push_visit_property(&member->second, item.cursor + 1, + child_depth, member->first, member->hash); + } + } else if (type == JSON::Type::Array) { + const auto &array{current.as_array()}; + auto [element, elements_end]{element_range(array)}; + for (std::size_t index{0}; element != elements_end; + ++element, ++index) { + stack.push_visit_index(element, item.cursor + 1, child_depth, index); + } + } + + break; + case JSONPath::SelectorKind::Index: + if (type == JSON::Type::Array) { + const auto *entry{std::get_if(selector)}; + const auto &array{current.as_array()}; + const auto size{static_cast(array.size())}; + const auto index{entry->index < 0 ? entry->index + size : entry->index}; + if (index >= 0 && index < size) { + stack.push_visit_index( + first_element(array) + static_cast(index), + item.cursor + 1, child_depth, static_cast(index)); + } + } + + break; + case JSONPath::SelectorKind::Slice: { + const auto *entry{std::get_if(selector)}; + if (type == JSON::Type::Array) { + const auto &array{current.as_array()}; + const auto size{static_cast(array.size())}; + std::int64_t lower{0}; + std::int64_t upper{0}; + if (!slice_bounds(*entry, size, lower, upper)) { + break; + } + + const auto *const array_base{first_element(array)}; + if (entry->step > 0) { + for (auto index{lower}; index < upper; index += entry->step) { + stack.push_visit_index(array_base + static_cast(index), + item.cursor + 1, child_depth, + static_cast(index)); + } + } else { + for (auto index{upper}; index > lower; index += entry->step) { + stack.push_visit_index(array_base + static_cast(index), + item.cursor + 1, child_depth, + static_cast(index)); + } + } + } + + break; + } + SOURCEMETA_CORE_JSONPATH_SELECTOR_FILTER: { + const auto *entry{std::get_if(selector)}; + if (type == JSON::Type::Object) { + const auto &object{current.as_object()}; + auto [member, members_end]{member_range(object)}; + for (; member != members_end; ++member) { + if (filter_matches(entry->expression, member->second, *state.root)) { + stack.push_visit_property(&member->second, item.cursor + 1, + child_depth, member->first, member->hash); + } + } + } else if (type == JSON::Type::Array) { + const auto &array{current.as_array()}; + auto [element, elements_end]{element_range(array)}; + for (std::size_t index{0}; element != elements_end; + ++element, ++index) { + if (filter_matches(entry->expression, *element, *state.root)) { + stack.push_visit_index(element, item.cursor + 1, child_depth, + index); + } + } + } + + break; + } + } +} // The main walk is iterative over an explicit stack, so document depth // cannot exhaust the machine stack, as RFC 9535 Section 4.1 warns about // naive recursive implementations of the descendant segment @@ -1051,113 +1186,8 @@ inline auto evaluate_query(const std::vector &segments, const auto *selector{segment.selectors.data()}; const auto *const selectors_end{selector + segment.selectors.size()}; for (; selector != selectors_end; ++selector) { - switch (static_cast(selector->index())) { - case JSONPath::SelectorKind::Name: - if (type == JSON::Type::Object) { - const auto *entry{std::get_if(selector)}; - const auto *child{current.try_at(entry->name, entry->hash)}; - if (child != nullptr) { - stack.push_visit_property(child, item.cursor + 1, child_depth, - entry->name, entry->hash); - } - } - - break; - case JSONPath::SelectorKind::Wildcard: - if (type == JSON::Type::Object) { - const auto &object{current.as_object()}; - auto [member, members_end]{member_range(object)}; - for (; member != members_end; ++member) { - stack.push_visit_property(&member->second, item.cursor + 1, - child_depth, member->first, - member->hash); - } - } else if (type == JSON::Type::Array) { - const auto &array{current.as_array()}; - auto [element, elements_end]{element_range(array)}; - for (std::size_t index{0}; element != elements_end; - ++element, ++index) { - stack.push_visit_index(element, item.cursor + 1, child_depth, - index); - } - } - - break; - case JSONPath::SelectorKind::Index: - if (type == JSON::Type::Array) { - const auto *entry{std::get_if(selector)}; - const auto &array{current.as_array()}; - const auto size{static_cast(array.size())}; - const auto index{entry->index < 0 ? entry->index + size - : entry->index}; - if (index >= 0 && index < size) { - stack.push_visit_index(first_element(array) + - static_cast(index), - item.cursor + 1, child_depth, - static_cast(index)); - } - } - - break; - case JSONPath::SelectorKind::Slice: { - const auto *entry{std::get_if(selector)}; - if (type == JSON::Type::Array) { - const auto &array{current.as_array()}; - const auto size{static_cast(array.size())}; - std::int64_t lower{0}; - std::int64_t upper{0}; - if (!slice_bounds(*entry, size, lower, upper)) { - break; - } - - const auto *const array_base{first_element(array)}; - if (entry->step > 0) { - for (auto index{lower}; index < upper; index += entry->step) { - stack.push_visit_index(array_base + - static_cast(index), - item.cursor + 1, child_depth, - static_cast(index)); - } - } else { - for (auto index{upper}; index > lower; index += entry->step) { - stack.push_visit_index(array_base + - static_cast(index), - item.cursor + 1, child_depth, - static_cast(index)); - } - } - } - - break; - } - SOURCEMETA_CORE_JSONPATH_SELECTOR_FILTER: { - const auto *entry{std::get_if(selector)}; - if (type == JSON::Type::Object) { - const auto &object{current.as_object()}; - auto [member, members_end]{member_range(object)}; - for (; member != members_end; ++member) { - if (filter_matches(entry->expression, member->second, - *state.root)) { - stack.push_visit_property(&member->second, item.cursor + 1, - child_depth, member->first, - member->hash); - } - } - } else if (type == JSON::Type::Array) { - const auto &array{current.as_array()}; - auto [element, elements_end]{element_range(array)}; - for (std::size_t index{0}; element != elements_end; - ++element, ++index) { - if (filter_matches(entry->expression, *element, *state.root)) { - stack.push_visit_index(element, item.cursor + 1, child_depth, - index); - } - } - } - - break; - } - } + evaluate_selector(current, item, stack, state, selector, type, + child_depth); } if (segment.descendant) { diff --git a/src/spec/jsonschema/bundle.cc b/src/spec/jsonschema/bundle.cc index 2118a8ad2..294281a0f 100644 --- a/src/spec/jsonschema/bundle.cc +++ b/src/spec/jsonschema/bundle.cc @@ -1387,6 +1387,367 @@ auto fragment_is_there(const JSON &document, const std::string_view destination) return try_get(document, pointer.value()) != nullptr; } +// One reference the document does not already answer, which may bring a +// whole remote schema in with it +auto expand_unresolved_reference( + const WeakPointer &pointer, const SchemaFrame::Reference &reference, + BundleState &state, const SchemaWalker &walker, + const SchemaResolver &resolver, const SchemaBundleOptions::Mode mode, + const std::string_view default_dialect, + const std::string_view container_dialect, std::uint64_t &remaining, + const bool entry_document, const SchemaFrame &frame, + const JSON::String &canonical_base, JSON::String &serving_identifier, + Pointer &serving_reference, std::vector &reached, + std::vector> &ref_rewrites) -> void { + // We don't want to bundle official schemas, as we can expect + // virtually all implementations to understand them out of the box. + // Depending on the bundling strategy, we may skip meta-schemas entirely + if (is_skippable_metaschema_reference(mode, pointer, reference.destination)) { + return; + } + + // Where a refusal names this reference, it names where the reference was + // written rather than where bundling moved it to + const auto sits_beside_a_root_that_was_one_reference{state.wrapped_root && + entry_document}; + const auto reported{ + sits_beside_a_root_that_was_one_reference + ? without_the_branch_bundling_made(to_pointer(pointer)) + : to_pointer(pointer)}; + + // If we can't find the destination but there is a base and we can + // find base, then we are facing an unresolved fragment + if (!reference.base.empty() && frame.traverse(reference.base).has_value()) { + throw SchemaReferenceError("Could not resolve schema reference", + reference.destination, reported); + } + + // And so is one whose base is the very document being bundled. A wrapper + // format puts the schemas it holds below a root that is no schema + // resource of its own, so nothing framed answers to the document's base + // and the test above passes it over, even though the fragment is all that + // leads nowhere + if (!canonical_base.empty() && reference.base == canonical_base) { + throw SchemaReferenceError("Could not resolve schema reference", + reference.destination, reported); + } + + if (reference.base.empty()) { + throw SchemaReferenceError("Could not resolve schema reference", + reference.destination, reported); + } + + assert(!reference.base.empty()); + const JSON::String identifier{reference.base}; + + // Framing already holds every base and every resource URI it reports to + // its canonical spelling, as `expand_references` notes, so what it hands + // back needs no second pass. Only a name the caller wrote or the + // document carries has to be settled + const auto &canonical{identifier}; + if (state.bundled.contains(canonical)) { + // A target that went in without a name answers to nothing, so this + // reference is settled against the finished document rather than here. + // Spelling it out in full is what lets that pass recognise it, since a + // relative spelling reads against wherever the schema ends up + if (state.positional.unnamed.contains(identifier)) { + ref_rewrites.emplace_back(to_pointer(pointer), + JSON::String{reference.destination}); + return; + } + + const auto &mapped_id{state.bundled.at(canonical)}; + // Whether the place the fragment names is really there. Where the + // document that answers is still in hand it is asked now, which both + // holds the fragment against what came back and saves reading the + // finished document all over again. Otherwise the question waits + const auto settle_fragment{[&](const JSON::String &destination) -> void { + if (!reference.fragment.has_value()) { + return; + } + + const auto *answering{document_in_hand(reached, state, mapped_id)}; + const auto there{answering == nullptr + ? std::nullopt + : fragment_is_there(*answering, destination)}; + if (!there.has_value()) { + state.held_over.push_back( + {.destination = destination, .location = reported}); + } else if (!there.value()) { + throw SchemaReferenceError("Could not resolve schema reference", + destination, reported); + } + }}; + + if (mapped_id != identifier) { + auto rebased{rebase_reference(mapped_id, reference.fragment)}; + settle_fragment(rebased); + ref_rewrites.emplace_back(to_pointer(pointer), std::move(rebased)); + } else { + settle_fragment(JSON::String{reference.destination}); + if (spells_another_document_relatively(reference)) { + ref_rewrites.emplace_back(to_pointer(pointer), + JSON::String{reference.destination}); + } + } + + return; + } + + // A name that something already on its way in carries is answered by the + // embedding, so there is nothing to fetch. What it is spelled as still + // has to not depend on where the document it sits in came from + if (state.reachable.contains(canonical)) { + if (reference.fragment.has_value()) { + state.held_over.push_back( + {.destination = JSON::String{reference.destination}, + .location = reported}); + } + + if (spells_another_document_relatively(reference)) { + ref_rewrites.emplace_back(to_pointer(pointer), + JSON::String{reference.destination}); + } + + return; + } + + serving_identifier = identifier; + serving_reference = reported; + + auto resolved{resolver(identifier)}; + if (!resolved.has_value()) { + // A base the document itself holds is already answered for above, so + // one that nobody hands over is a schema from elsewhere that is missing + throw SchemaResolutionError( + "Could not resolve the reference to an external schema", identifier); + } + + // Bundling rewrites the schema before embedding it, so it needs a copy + // it owns rather than whatever the resolver chose to hand back + auto remote{std::move(resolved).to_owned()}; + // A boolean is a schema only from Draft 6 onward: every dialect before + // it says a schema is an object, which the meta-schema of each states + // as `"type": "object"`. Where the dialect a boolean would be read + // under is one of those, what came back is no schema at all + const auto remote_base{ + to_base_dialect(declared_dialect(remote, default_dialect))}; + const auto boolean_reads_as_no_schema{ + remote.is_boolean() && remote_base.has_value() && + !supports_boolean_schemas(remote_base.value())}; + if ((!remote.is_object() && !remote.is_boolean()) || + boolean_reads_as_no_schema) { + throw SchemaReferenceError("The JSON document is not a valid JSON " + "Schema", + identifier, reported); + } + + std::optional remote_root_frame; + try { + // What a relative identifier resolves against is where the document was + // retrieved from, which JSON Schema 2020-12 Section 8.2.1 settles: "If + // this URI is a relative reference, it is resolved against the base URI + // of the schema resource that contains it", and the resource containing + // the root of a fetched document is the document itself. Saying nothing + // here would leave a relative one resolving against whatever document + // this is bundling into, which names something else + remote_root_frame.emplace( + SchemaFrame::Mode::Root, remote, walker, resolver, default_dialect, "", + SchemaFrame::IdentifierMode::Additional, + SchemaFrame::Paths{EMPTY_WEAK_POINTER}, identifier, remaining); + charge(remaining, remote_root_frame.value()); + } catch (const SchemaUnknownBaseDialectError &) { + throw SchemaReferenceError("The JSON document is not a valid JSON " + "Schema", + identifier, reported); + } + + const auto &remote_root{remote_root_frame->root_location().value().get()}; + // Both of the questions below are of the same vocabularies, and working + // them out can cost a meta-schema to resolve, so it happens once + const auto &remote_vocabularies{ + remote_root_frame->vocabularies(remote_root, resolver)}; + + // A schema that names a dialect which gives the keyword that named it no + // meaning cannot be taken at its word, and framing refuses it wherever it + // meets one. Saying so here is what names the document it came from and + // the reference that went looking for it, which a refusal from whichever + // frame happens to reach it first cannot do + if (remote.is_object() && + remote.defines("$schema"sv, JSONSCHEMA_HASH_SCHEMA) && + !schema_defines_keyword(walker, remote_vocabularies, "$schema"sv)) { + throw SchemaReferenceError("The referenced schema declares a dialect " + "that does not define the keyword that " + "declares it", + identifier, reported); + } + + const auto remote_base_dialect{remote_root.base_dialect}; + auto remote_id = remote_root_frame->root(); + + // Whether what the reference names within the remote carries a name of + // its own, which settles how the reference reads without settling where + // the remote goes + bool names_a_resource{false}; + + // If the reference has a fragment, verify it exists in the remote + // schema + if (reference.fragment.has_value()) { + // A pointer fragment names a place of the document, and the document + // can answer for that on its own without paying to frame it + const auto fragment_pointer{ + fragment_to_pointer(URI{reference.destination})}; + const auto *named_value{fragment_pointer.has_value() + ? try_get(remote, fragment_pointer.value()) + : nullptr}; + bool exists{named_value != nullptr}; + + // An anchor is not a place of the document, and the drafts that spell + // identifiers as `id` let one look just like a pointer, so a miss above + // still has to ask the frame. Only the anchors of the remote matter + // here, rather than every pointer of it + if (!exists) { + const SchemaFrame remote_frame{SchemaFrame::Mode::Locations, + remote, + walker, + resolver, + default_dialect, + identifier, + SchemaFrame::IdentifierMode::Additional, + {EMPTY_WEAK_POINTER}, + identifier, + remaining}; + charge(remaining, remote_frame); + exists = remote_frame.traverse(reference.destination).has_value(); + } + + if (!exists) { + throw SchemaReferenceError("Could not resolve schema reference", + reference.destination, reported); + } + + // Where the place it named sits within something that carries a name + // of its own, that name is what reaches it from anywhere, and goes on + // doing so wherever the bundling puts it. Saying where it sits instead + // would only hold while it sat there, and elevating a carried resource + // moves it. The place the pointer ends on is not the only one that can + // carry such a name, so every step down is asked, which costs a lookup + // each where asking the frame costs a walk of the whole remote + if (fragment_pointer.has_value() && + a_step_names_itself(remote, fragment_pointer.value())) { + const SchemaFrame located{SchemaFrame::Mode::Locations, + remote, + walker, + resolver, + default_dialect, + identifier, + SchemaFrame::IdentifierMode::Additional, + {EMPTY_WEAK_POINTER}, + "", + remaining}; + charge(remaining, located); + const auto named{ + located.traverse(to_weak_pointer(fragment_pointer.value()))}; + if (named.has_value() && named.value().get().base != identifier) { + // What the place sits within answers to a name of its own, so the + // reference is spelled against that name and whatever of the + // pointer is left over. Spelling it against the remote instead + // would only hold while the place sat where it sits, and elevating + // a carried resource moves it. Where the pointer named the + // resource itself there is nothing left over, and the name alone + // is the whole of it + const auto resource{ + enclosing_resource(located, named.value().get().pointer)}; + Pointer remainder; + for (auto index{resource.size()}; + index < fragment_pointer.value().size(); index += 1) { + const auto &token{fragment_pointer.value().at(index)}; + if (token.is_property()) { + remainder.push_back(token.to_property()); + } else { + remainder.push_back(token.to_index()); + } + } + + ref_rewrites.emplace_back( + to_pointer(pointer), + remainder.empty() + ? JSON::String{named.value().get().base} + : rebase_reference(JSON::String{named.value().get().base}, + sourcemeta::core::to_string(remainder))); + names_a_resource = true; + } + } + } + + JSON::String effective_id{remote_id.empty() ? JSON::String{identifier} + : JSON::String{remote_id}}; + + // Whether the remote can be made to name itself at all, which decides + // between giving it a name and pointing at wherever it lands. A boolean + // has to be restated as the object that says the same thing before it can + // hold one, which is not something every dialect can say + const auto remote_can_name_itself{ + dialect_defines_identifier(walker, remote_vocabularies, + remote_base_dialect) && + (remote.is_object() || + boolean_can_be_restated(walker, remote_vocabularies, remote))}; + + const auto remote_dialect_uri{declared_dialect(remote, default_dialect)}; + + if (remote_can_name_itself || remote.is_object()) { + if (remote_can_name_itself) { + if (remote.is_boolean()) { + restate_boolean(remote); + } + + // Otherwise the embedded resource would be re-interpreted under the + // dialect of the schema it gets embedded into, which can differ from + // the default dialect that the remote was resolved with + if (!remote.defines("$schema"sv, JSONSCHEMA_HASH_SCHEMA)) { + remote.assign("$schema", JSON{remote_dialect_uri}); + } + + schema_reidentify(remote, effective_id, remote_base_dialect); + } else if (remote_dialect_uri != container_dialect) { + // Marking is what carries a dialect that no keyword of the schema can + // declare. Where whatever holds the container already reads under the + // dialect the remote was read under, inheritance says the same thing + // for free + mark_dialect_of_every_subschema(remote, walker, resolver, + remote_dialect_uri, remaining); + } + } + + if (names_a_resource) { + // Settled above, and by a name rather than by a place, so none of what + // follows has anything to add to it + } else if (!remote_can_name_itself) { + // A remote that cannot declare an identifier, whether because its + // dialect defines no keyword for one or because it says what no object + // of that dialect can say, is left by the embedding without the name it + // was resolved by + assert(effective_id == identifier); + state.positional.unnamed.insert(identifier); + ref_rewrites.emplace_back(to_pointer(pointer), + JSON::String{reference.destination}); + } else if (effective_id != identifier) { + ref_rewrites.emplace_back( + to_pointer(pointer), + rebase_reference(effective_id, reference.fragment)); + } else if (spells_another_document_relatively(reference)) { + ref_rewrites.emplace_back(to_pointer(pointer), + JSON::String{reference.destination}); + } + + state.bundled.emplace(canonical, effective_id); + state.bundled.emplace(canonical_uri(effective_id), effective_id); + reached.push_back(PendingEmbed{.document = std::move(remote), + .identifier = std::move(effective_id), + .dialect = remote_base_dialect, + .origin = identifier, + .origin_reference = reported}); +} // Read one document, settle the references it spells, and hand back the // remotes it reaches for the caller to embed auto expand_references( @@ -1481,359 +1842,10 @@ auto expand_references( try { frame.for_each_unresolved_reference([&](const auto &pointer, const auto &reference) -> void { - // We don't want to bundle official schemas, as we can expect - // virtually all implementations to understand them out of the box. - // Depending on the bundling strategy, we may skip meta-schemas entirely - if (is_skippable_metaschema_reference(mode, pointer, - reference.destination)) { - return; - } - - // Where a refusal names this reference, it names where the reference was - // written rather than where bundling moved it to - const auto sits_beside_a_root_that_was_one_reference{state.wrapped_root && - entry_document}; - const auto reported{ - sits_beside_a_root_that_was_one_reference - ? without_the_branch_bundling_made(to_pointer(pointer)) - : to_pointer(pointer)}; - - // If we can't find the destination but there is a base and we can - // find base, then we are facing an unresolved fragment - if (!reference.base.empty() && - frame.traverse(reference.base).has_value()) { - throw SchemaReferenceError("Could not resolve schema reference", - reference.destination, reported); - } - - // And so is one whose base is the very document being bundled. A wrapper - // format puts the schemas it holds below a root that is no schema - // resource of its own, so nothing framed answers to the document's base - // and the test above passes it over, even though the fragment is all that - // leads nowhere - if (!canonical_base.empty() && reference.base == canonical_base) { - throw SchemaReferenceError("Could not resolve schema reference", - reference.destination, reported); - } - - if (reference.base.empty()) { - throw SchemaReferenceError("Could not resolve schema reference", - reference.destination, reported); - } - - assert(!reference.base.empty()); - const JSON::String identifier{reference.base}; - - // Framing already holds every base and every resource URI it reports to - // its canonical spelling, as the comment above says, so what it hands - // back needs no second pass. Only a name the caller wrote or the - // document carries has to be settled - const auto &canonical{identifier}; - if (state.bundled.contains(canonical)) { - // A target that went in without a name answers to nothing, so this - // reference is settled against the finished document rather than here. - // Spelling it out in full is what lets that pass recognise it, since a - // relative spelling reads against wherever the schema ends up - if (state.positional.unnamed.contains(identifier)) { - ref_rewrites.emplace_back(to_pointer(pointer), - JSON::String{reference.destination}); - return; - } - - const auto &mapped_id{state.bundled.at(canonical)}; - // Whether the place the fragment names is really there. Where the - // document that answers is still in hand it is asked now, which both - // holds the fragment against what came back and saves reading the - // finished document all over again. Otherwise the question waits - const auto settle_fragment{[&](const JSON::String &destination) - -> void { - if (!reference.fragment.has_value()) { - return; - } - - const auto *answering{document_in_hand(reached, state, mapped_id)}; - const auto there{answering == nullptr - ? std::nullopt - : fragment_is_there(*answering, destination)}; - if (!there.has_value()) { - state.held_over.push_back( - {.destination = destination, .location = reported}); - } else if (!there.value()) { - throw SchemaReferenceError("Could not resolve schema reference", - destination, reported); - } - }}; - - if (mapped_id != identifier) { - auto rebased{rebase_reference(mapped_id, reference.fragment)}; - settle_fragment(rebased); - ref_rewrites.emplace_back(to_pointer(pointer), std::move(rebased)); - } else { - settle_fragment(JSON::String{reference.destination}); - if (spells_another_document_relatively(reference)) { - ref_rewrites.emplace_back(to_pointer(pointer), - JSON::String{reference.destination}); - } - } - - return; - } - - // A name that something already on its way in carries is answered by the - // embedding, so there is nothing to fetch. What it is spelled as still - // has to not depend on where the document it sits in came from - if (state.reachable.contains(canonical)) { - if (reference.fragment.has_value()) { - state.held_over.push_back( - {.destination = JSON::String{reference.destination}, - .location = reported}); - } - - if (spells_another_document_relatively(reference)) { - ref_rewrites.emplace_back(to_pointer(pointer), - JSON::String{reference.destination}); - } - - return; - } - - serving_identifier = identifier; - serving_reference = reported; - - auto resolved{resolver(identifier)}; - if (!resolved.has_value()) { - // A base the document itself holds is already answered for above, so - // one that nobody hands over is a schema from elsewhere that is missing - throw SchemaResolutionError( - "Could not resolve the reference to an external schema", - identifier); - } - - // Bundling rewrites the schema before embedding it, so it needs a copy - // it owns rather than whatever the resolver chose to hand back - auto remote{std::move(resolved).to_owned()}; - // A boolean is a schema only from Draft 6 onward: every dialect before - // it says a schema is an object, which the meta-schema of each states - // as `"type": "object"`. Where the dialect a boolean would be read - // under is one of those, what came back is no schema at all - const auto remote_base{ - to_base_dialect(declared_dialect(remote, default_dialect))}; - const auto boolean_reads_as_no_schema{ - remote.is_boolean() && remote_base.has_value() && - !supports_boolean_schemas(remote_base.value())}; - if ((!remote.is_object() && !remote.is_boolean()) || - boolean_reads_as_no_schema) { - throw SchemaReferenceError("The JSON document is not a valid JSON " - "Schema", - identifier, reported); - } - - std::optional remote_root_frame; - try { - // What a relative identifier resolves against is where the document was - // retrieved from, which JSON Schema 2020-12 Section 8.2.1 settles: "If - // this URI is a relative reference, it is resolved against the base URI - // of the schema resource that contains it", and the resource containing - // the root of a fetched document is the document itself. Saying nothing - // here would leave a relative one resolving against whatever document - // this is bundling into, which names something else - remote_root_frame.emplace( - SchemaFrame::Mode::Root, remote, walker, resolver, default_dialect, - "", SchemaFrame::IdentifierMode::Additional, - SchemaFrame::Paths{EMPTY_WEAK_POINTER}, identifier, remaining); - charge(remaining, remote_root_frame.value()); - } catch (const SchemaUnknownBaseDialectError &) { - throw SchemaReferenceError("The JSON document is not a valid JSON " - "Schema", - identifier, reported); - } - - const auto &remote_root{remote_root_frame->root_location().value().get()}; - // Both of the questions below are of the same vocabularies, and working - // them out can cost a meta-schema to resolve, so it happens once - const auto &remote_vocabularies{ - remote_root_frame->vocabularies(remote_root, resolver)}; - - // A schema that names a dialect which gives the keyword that named it no - // meaning cannot be taken at its word, and framing refuses it wherever it - // meets one. Saying so here is what names the document it came from and - // the reference that went looking for it, which a refusal from whichever - // frame happens to reach it first cannot do - if (remote.is_object() && - remote.defines("$schema"sv, JSONSCHEMA_HASH_SCHEMA) && - !schema_defines_keyword(walker, remote_vocabularies, "$schema"sv)) { - throw SchemaReferenceError("The referenced schema declares a dialect " - "that does not define the keyword that " - "declares it", - identifier, reported); - } - - const auto remote_base_dialect{remote_root.base_dialect}; - auto remote_id = remote_root_frame->root(); - - // Whether what the reference names within the remote carries a name of - // its own, which settles how the reference reads without settling where - // the remote goes - bool names_a_resource{false}; - - // If the reference has a fragment, verify it exists in the remote - // schema - if (reference.fragment.has_value()) { - // A pointer fragment names a place of the document, and the document - // can answer for that on its own without paying to frame it - const auto fragment_pointer{ - fragment_to_pointer(URI{reference.destination})}; - const auto *named_value{fragment_pointer.has_value() - ? try_get(remote, fragment_pointer.value()) - : nullptr}; - bool exists{named_value != nullptr}; - - // An anchor is not a place of the document, and the drafts that spell - // identifiers as `id` let one look just like a pointer, so a miss above - // still has to ask the frame. Only the anchors of the remote matter - // here, rather than every pointer of it - if (!exists) { - const SchemaFrame remote_frame{ - SchemaFrame::Mode::Locations, - remote, - walker, - resolver, - default_dialect, - identifier, - SchemaFrame::IdentifierMode::Additional, - {EMPTY_WEAK_POINTER}, - identifier, - remaining}; - charge(remaining, remote_frame); - exists = remote_frame.traverse(reference.destination).has_value(); - } - - if (!exists) { - throw SchemaReferenceError("Could not resolve schema reference", - reference.destination, reported); - } - - // Where the place it named sits within something that carries a name - // of its own, that name is what reaches it from anywhere, and goes on - // doing so wherever the bundling puts it. Saying where it sits instead - // would only hold while it sat there, and elevating a carried resource - // moves it. The place the pointer ends on is not the only one that can - // carry such a name, so every step down is asked, which costs a lookup - // each where asking the frame costs a walk of the whole remote - if (fragment_pointer.has_value() && - a_step_names_itself(remote, fragment_pointer.value())) { - const SchemaFrame located{SchemaFrame::Mode::Locations, - remote, - walker, - resolver, - default_dialect, - identifier, - SchemaFrame::IdentifierMode::Additional, - {EMPTY_WEAK_POINTER}, - "", - remaining}; - charge(remaining, located); - const auto named{ - located.traverse(to_weak_pointer(fragment_pointer.value()))}; - if (named.has_value() && named.value().get().base != identifier) { - // What the place sits within answers to a name of its own, so the - // reference is spelled against that name and whatever of the - // pointer is left over. Spelling it against the remote instead - // would only hold while the place sat where it sits, and elevating - // a carried resource moves it. Where the pointer named the - // resource itself there is nothing left over, and the name alone - // is the whole of it - const auto resource{ - enclosing_resource(located, named.value().get().pointer)}; - Pointer remainder; - for (auto index{resource.size()}; - index < fragment_pointer.value().size(); index += 1) { - const auto &token{fragment_pointer.value().at(index)}; - if (token.is_property()) { - remainder.push_back(token.to_property()); - } else { - remainder.push_back(token.to_index()); - } - } - - ref_rewrites.emplace_back( - to_pointer(pointer), - remainder.empty() - ? JSON::String{named.value().get().base} - : rebase_reference(JSON::String{named.value().get().base}, - sourcemeta::core::to_string(remainder))); - names_a_resource = true; - } - } - } - - JSON::String effective_id{remote_id.empty() ? JSON::String{identifier} - : JSON::String{remote_id}}; - - // Whether the remote can be made to name itself at all, which decides - // between giving it a name and pointing at wherever it lands. A boolean - // has to be restated as the object that says the same thing before it can - // hold one, which is not something every dialect can say - const auto remote_can_name_itself{ - dialect_defines_identifier(walker, remote_vocabularies, - remote_base_dialect) && - (remote.is_object() || - boolean_can_be_restated(walker, remote_vocabularies, remote))}; - - const auto remote_dialect_uri{declared_dialect(remote, default_dialect)}; - - if (remote_can_name_itself || remote.is_object()) { - if (remote_can_name_itself) { - if (remote.is_boolean()) { - restate_boolean(remote); - } - - // Otherwise the embedded resource would be re-interpreted under the - // dialect of the schema it gets embedded into, which can differ from - // the default dialect that the remote was resolved with - if (!remote.defines("$schema"sv, JSONSCHEMA_HASH_SCHEMA)) { - remote.assign("$schema", JSON{remote_dialect_uri}); - } - - schema_reidentify(remote, effective_id, remote_base_dialect); - } else if (remote_dialect_uri != container_dialect) { - // Marking is what carries a dialect that no keyword of the schema can - // declare. Where whatever holds the container already reads under the - // dialect the remote was read under, inheritance says the same thing - // for free - mark_dialect_of_every_subschema(remote, walker, resolver, - remote_dialect_uri, remaining); - } - } - - if (names_a_resource) { - // Settled above, and by a name rather than by a place, so none of what - // follows has anything to add to it - } else if (!remote_can_name_itself) { - // A remote that cannot declare an identifier, whether because its - // dialect defines no keyword for one or because it says what no object - // of that dialect can say, is left by the embedding without the name it - // was resolved by - assert(effective_id == identifier); - state.positional.unnamed.insert(identifier); - ref_rewrites.emplace_back(to_pointer(pointer), - JSON::String{reference.destination}); - } else if (effective_id != identifier) { - ref_rewrites.emplace_back( - to_pointer(pointer), - rebase_reference(effective_id, reference.fragment)); - } else if (spells_another_document_relatively(reference)) { - ref_rewrites.emplace_back(to_pointer(pointer), - JSON::String{reference.destination}); - } - - state.bundled.emplace(canonical, effective_id); - state.bundled.emplace(canonical_uri(effective_id), effective_id); - reached.push_back(PendingEmbed{.document = std::move(remote), - .identifier = std::move(effective_id), - .dialect = remote_base_dialect, - .origin = identifier, - .origin_reference = reported}); + expand_unresolved_reference( + pointer, reference, state, walker, resolver, mode, default_dialect, + container_dialect, remaining, entry_document, frame, canonical_base, + serving_identifier, serving_reference, reached, ref_rewrites); }); } catch (const SchemaDialectImpossibleError &) { throw SchemaReferenceError("The referenced schema declares a dialect that " diff --git a/src/spec/jsonschema/frame.cc b/src/spec/jsonschema/frame.cc index fe12ca924..1c90f9953 100644 --- a/src/spec/jsonschema/frame.cc +++ b/src/spec/jsonschema/frame.cc @@ -40,7 +40,6 @@ constexpr auto HASH_STATIC{sourcemeta::core::JSON::Object::hash("static"sv)}; constexpr auto HASH_DYNAMIC{sourcemeta::core::JSON::Object::hash("dynamic"sv)}; constexpr auto HASH_REFERENCES{ sourcemeta::core::JSON::Object::hash("references"sv)}; - } // namespace // A switch that names every enumerator and carries no default of its own @@ -662,6 +661,913 @@ auto reference_destinations(const References &references, return result; } +template +auto resolve_ref( + const InternalEntry &entry, + const std::vector &nearest_bases, + References &references) -> void { + using sourcemeta::core::SchemaFrame; + using sourcemeta::core::SchemaReferenceType; + const auto &common_pointer_weak{entry.common.pointer}; + const auto *ref_value{entry.common.subschema.get().try_at( + "$ref"sv, sourcemeta::core::JSONSCHEMA_HASH_REF)}; + if (ref_value != nullptr) { + if (!ref_value->is_string()) { + std::ostringstream value; + sourcemeta::core::stringify(*ref_value, value); + throw sourcemeta::core::SchemaKeywordError("Invalid reference value", + "$ref", value.str()); + } + + const auto &original{ref_value->to_string()}; + sourcemeta::core::URI ref; + try { + ref = sourcemeta::core::URI{original}; + } catch (const sourcemeta::core::URIParseError &) { + throw sourcemeta::core::SchemaKeywordError( + "The reference is not a valid URI", "$ref", original); + } + + if (!nearest_bases.empty()) { + ref.resolve_from(sourcemeta::core::URI{nearest_bases.front()}); + } + + ref.canonicalize(); + canonicalize_pointer_fragment(ref); + auto ref_pointer{common_pointer_weak}; + ref_pointer.push_back(std::cref(KEYWORD_REF)); + const auto [entry_iterator, inserted] = references.insert_or_assign( + {SchemaReferenceType::Static, std::move(ref_pointer)}, + SchemaFrame::Reference{.original = original, + .destination = ref.recompose(), + .base = std::string_view{}, + .fragment = std::nullopt}); + set_base_and_fragment(entry_iterator->second); + } +} + +template +auto resolve_recursive_ref( + const InternalEntry &entry, + const std::vector &nearest_bases, + const Locations &locations, References &references) -> void { + using sourcemeta::core::SchemaFrame; + using sourcemeta::core::SchemaReferenceType; + using sourcemeta::core::SchemaVocabularies; + const auto &common_pointer_weak{entry.common.pointer}; + const auto *recursive_ref_value{ + entry.common.vocabularies.contains( + SchemaVocabularies::Known::JSON_SCHEMA_2019_09_CORE) + ? entry.common.subschema.get().try_at( + "$recursiveRef"sv, + sourcemeta::core::JSONSCHEMA_HASH_RECURSIVE_REF) + : nullptr}; + if (recursive_ref_value != nullptr) { + if (!recursive_ref_value->is_string()) { + std::ostringstream value; + sourcemeta::core::stringify(*recursive_ref_value, value); + throw sourcemeta::core::SchemaKeywordError( + "Invalid recursive reference value", "$recursiveRef", value.str()); + } + + const auto &ref{recursive_ref_value->to_string()}; + + // The behavior of this keyword is defined only for the value "#". + // Implementations MAY choose to consider other values to be errors. + // See + // https://json-schema.org/draft/2019-09/draft-handrews-json-schema-02#rfc.section.8.2.4.2.1 + if (ref != "#") { + throw sourcemeta::core::SchemaReferenceError( + "Invalid recursive reference", entry.id.value_or(""), + to_pointer(common_pointer_weak).concat("$recursiveRef")); + } + + auto anchor_uri_string{nearest_bases.empty() ? "" : nearest_bases.front()}; + const auto recursive_anchor{ + locations.find({SchemaReferenceType::Dynamic, anchor_uri_string})}; + const auto reference_type{recursive_anchor == locations.end() + ? SchemaReferenceType::Static + : SchemaReferenceType::Dynamic}; + const sourcemeta::core::URI anchor_uri{anchor_uri_string}; + auto recursive_ref_pointer{common_pointer_weak}; + recursive_ref_pointer.push_back(std::cref(KEYWORD_RECURSIVE_REF)); + const auto [entry_iterator, inserted] = references.insert_or_assign( + {reference_type, std::move(recursive_ref_pointer)}, + SchemaFrame::Reference{.original = ref, + .destination = anchor_uri.recompose(), + .base = std::string_view{}, + .fragment = std::nullopt}); + set_base_and_fragment(entry_iterator->second); + } +} + +template +auto resolve_dynamic_ref( + const InternalEntry &entry, + const std::vector &nearest_bases, + const Locations &locations, References &references) -> void { + using sourcemeta::core::SchemaFrame; + using sourcemeta::core::SchemaReferenceType; + using sourcemeta::core::SchemaVocabularies; + const auto &common_pointer_weak{entry.common.pointer}; + const auto *dynamic_ref_value{ + entry.common.vocabularies.contains( + SchemaVocabularies::Known::JSON_SCHEMA_2020_12_CORE) + ? entry.common.subschema.get().try_at( + "$dynamicRef"sv, sourcemeta::core::JSONSCHEMA_HASH_DYNAMIC_REF) + : nullptr}; + if (dynamic_ref_value != nullptr) { + if (!dynamic_ref_value->is_string()) { + std::ostringstream value; + sourcemeta::core::stringify(*dynamic_ref_value, value); + throw sourcemeta::core::SchemaKeywordError( + "Invalid dynamic reference value", "$dynamicRef", value.str()); + } + + const auto &original{dynamic_ref_value->to_string()}; + sourcemeta::core::URI ref; + try { + ref = sourcemeta::core::URI{original}; + } catch (const sourcemeta::core::URIParseError &) { + throw sourcemeta::core::SchemaKeywordError( + "The dynamic reference is not a valid URI", "$dynamicRef", original); + } + + if (!nearest_bases.empty()) { + ref.resolve_from(sourcemeta::core::URI{nearest_bases.front()}); + } + + ref.canonicalize(); + canonicalize_pointer_fragment(ref); + auto ref_string{ref.recompose()}; + + // Note that here we cannot enforce the bookending requirement, + // as the dynamic reference may point to a schema resource that + // is not part of or bundled within the schema we are analyzing here. + + const auto has_fragment{ref.fragment().has_value()}; + const auto maybe_static_frame{ + locations.find({SchemaReferenceType::Static, ref_string})}; + const auto maybe_dynamic_frame{ + locations.find({SchemaReferenceType::Dynamic, ref_string})}; + const auto behaves_as_static{!has_fragment || + (maybe_static_frame != locations.end() && + maybe_dynamic_frame == locations.end())}; + auto dynamic_ref_pointer{common_pointer_weak}; + dynamic_ref_pointer.push_back(std::cref(KEYWORD_DYNAMIC_REF)); + const auto [entry_iterator, inserted] = references.insert_or_assign( + {behaves_as_static ? SchemaReferenceType::Static + : SchemaReferenceType::Dynamic, + std::move(dynamic_ref_pointer)}, + SchemaFrame::Reference{.original = original, + .destination = std::move(ref_string), + .base = std::string_view{}, + .fragment = std::nullopt}); + set_base_and_fragment(entry_iterator->second); + } +} + +// A dynamic anchor declares a static anchor of the same name too, so one +// anchor can name as many as three locations +template +auto store_anchor(Locations &locations, const std::uint64_t max_locations, + const AnchorType type, const InternalEntry &entry, + const sourcemeta::core::JSON::String &anchor_uri, + const std::string_view base, + const std::size_t relative_pointer_offset) -> void { + using sourcemeta::core::SchemaFrame; + using sourcemeta::core::SchemaReferenceType; + using sourcemeta::core::SchemaVocabularies; + + if (type == AnchorType::Static || type == AnchorType::All) { + store(locations, max_locations, SchemaReferenceType::Static, + SchemaFrame::LocationType::Anchor, anchor_uri, base, + entry.common.pointer, relative_pointer_offset, entry.common.dialect, + entry.common.base_dialect.value(), entry.common.parent, + entry.common.property_name, entry.common.orphan); + } + + if (type != AnchorType::Dynamic && type != AnchorType::All) { + return; + } + + store(locations, max_locations, SchemaReferenceType::Dynamic, + SchemaFrame::LocationType::Anchor, anchor_uri, base, + entry.common.pointer, relative_pointer_offset, entry.common.dialect, + entry.common.base_dialect.value(), entry.common.parent, + entry.common.property_name, entry.common.orphan); + + // When the location also carries `$anchor`, the static branch above already + // registered it + if (type == AnchorType::Dynamic && + entry.common.vocabularies.contains( + SchemaVocabularies::Known::JSON_SCHEMA_2020_12_CORE)) { + store(locations, max_locations, SchemaReferenceType::Static, + SchemaFrame::LocationType::Anchor, anchor_uri, base, + entry.common.pointer, relative_pointer_offset, entry.common.dialect, + entry.common.base_dialect.value(), entry.common.parent, + entry.common.property_name, entry.common.orphan); + } +} + +template +auto store_anchors(Locations &locations, Owned &owned, + const sourcemeta::core::JSON::String &default_base, + const std::uint64_t max_locations, + const BaseMapType &base_uris, const InternalEntry &entry) + -> void { + const auto anchors{ + find_anchors(entry.common.subschema.get(), entry.common.vocabularies)}; + if (anchors.empty()) { + return; + } + + // Every anchor of one subschema resolves against the same bases, so the + // lookup does not belong inside the loop + const auto bases{find_nearest_bases( + base_uris, entry.common.pointer, + entry.id ? std::optional{*entry.id} : std::nullopt)}; + + for (const auto &[name, type] : anchors) { + if (bases.first.empty()) { + const auto anchor_uri{sourcemeta::core::URI::from_fragment(name)}; + store_anchor(locations, max_locations, type, entry, + anchor_uri.recompose(), "", bases.second.size()); + continue; + } + + [[maybe_unused]] bool is_first{true}; + for (const auto &base_string : bases.first) { + sourcemeta::core::URI anchor_uri_builder{base_string}; + anchor_uri_builder.fragment(name); + anchor_uri_builder.canonicalize(); + const auto anchor_uri{anchor_uri_builder.recompose()}; + + // Two bases of one place never spell a single anchor, as the fragment + // put on them is the same and each base is a name of its own, so the + // first of them is the only one that can have taken the name this one + // is about to + assert(is_first || + !locations.contains( + {sourcemeta::core::SchemaReferenceType::Static, anchor_uri})); + + store_anchor(locations, max_locations, type, entry, anchor_uri, + owned_base_view(locations, owned, default_base, base_string), + bases.second.size()); + is_first = false; + } + } +} + +template +auto resolve_metaschema_ref(const InternalEntry &entry, + const BaseMapType &base_uris, + References &references) -> void { + using sourcemeta::core::SchemaFrame; + using sourcemeta::core::SchemaReferenceType; + + const auto maybe_metaschema{ + sourcemeta::core::dialect(entry.common.subschema.get(), {}, false)}; + if (maybe_metaschema.empty()) { + return; + } + + sourcemeta::core::URI metaschema; + try { + metaschema = sourcemeta::core::URI{maybe_metaschema}; + } catch (const sourcemeta::core::URIParseError &) { + throw sourcemeta::core::SchemaKeywordError("The dialect is not a valid URI", + "$schema", maybe_metaschema); + } + + const auto nearest_bases{find_nearest_bases( + base_uris, entry.common.pointer, + entry.id ? std::optional{*entry.id} : std::nullopt)}; + if (!nearest_bases.first.empty()) { + metaschema.resolve_from(sourcemeta::core::URI{nearest_bases.first.front()}); + } + + metaschema.canonicalize(); + assert(entry.common.subschema.get().defines( + "$schema"sv, sourcemeta::core::JSONSCHEMA_HASH_SCHEMA)); + auto schema_pointer{entry.common.pointer}; + schema_pointer.push_back(std::cref(KEYWORD_SCHEMA)); + const auto [entry_iterator, inserted] = references.insert_or_assign( + {SchemaReferenceType::Static, std::move(schema_pointer)}, + SchemaFrame::Reference{.original = maybe_metaschema, + .destination = metaschema.recompose(), + .base = std::string_view{}, + .fragment = std::nullopt}); + set_base_and_fragment(entry_iterator->second); +} + +// A reference may target a place that the walker never descends into, like +// a keyword value or a container that a top-level `$ref` overrides, so +// materialise a location for each of those +template +auto materialise_reference_locations( + const sourcemeta::core::JSON &root, const BaseMapType &base_uris, + const DialectMapType &base_dialects, const SubschemaMapType &subschemas, + const std::uint64_t max_locations, Locations &locations, + const References &references, + std::deque &reference_pointers) -> void { + using sourcemeta::core::SchemaFrame; + using sourcemeta::core::SchemaReferenceType; + for (const auto &reference : references) { + const auto &fragment{reference.second.fragment}; + if (!fragment.has_value() || !fragment.value().starts_with('/')) { + continue; + } + + if (locations.contains( + {SchemaReferenceType::Static, reference.second.destination})) { + continue; + } + + const auto base_entry{locations.find( + {SchemaReferenceType::Static, + sourcemeta::core::JSON::String{reference.second.base}})}; + if (base_entry == locations.cend()) { + continue; + } + + // The fragment of a reference is URI-encoded, so it has to be decoded + // rather than read as-is, else an escape like `a%20b` would stand for a + // property of that literal name + const auto relative{sourcemeta::core::fragment_to_pointer( + sourcemeta::core::URI{reference.second.destination})}; + if (!relative.has_value()) { + continue; + } + + auto absolute{sourcemeta::core::to_pointer(base_entry->second.pointer) + .concat(relative.value())}; + if (sourcemeta::core::try_get(root, absolute) == nullptr) { + continue; + } + + reference_pointers.push_back(std::move(absolute)); + const auto pointer_weak{ + sourcemeta::core::to_weak_pointer(reference_pointers.back())}; + const auto combined{ + find_dialect_and_all_bases(base_dialects, base_uris, pointer_weak)}; + + std::size_t nearest_base_depth{base_entry->second.pointer.size()}; + std::string_view nearest_base_view{base_entry->first.second}; + for (const auto &candidate : combined.every_base) { + if (candidate.first.empty()) { + continue; + } + + nearest_base_depth = candidate.second.size(); + // Every base a subschema reads against was registered as a resource + // of this frame on the way down + const auto candidate_entry{ + locations.find({SchemaReferenceType::Static, + sourcemeta::core::JSON::String{candidate.first}})}; + assert(candidate_entry != locations.cend()); + nearest_base_view = candidate_entry->first.second; + + break; + } + + // The document states a dialect at its root, which sits above wherever + // this destination landed, so the search above always comes back with + // one + assert(combined.dialect_match.has_value()); + const auto &parent{combined.dialect_match->second}; + // The place above is a schema that the traversal reported, so it is one + // of the subschemas gathered here + const auto parent_subschema{subschemas.find(parent)}; + assert(parent_subschema != subschemas.cend()); + store(locations, max_locations, SchemaReferenceType::Static, + SchemaFrame::LocationType::Pointer, + sourcemeta::core::JSON::String{reference.second.destination}, + nearest_base_view, pointer_weak, nearest_base_depth, + combined.dialect_match->first.get().dialects.front(), + combined.dialect_match->first.get().base_dialect, parent, + parent_subschema->second.property_name, + parent_subschema->second.orphan, true); + } +} + +// Whether a lone destination can stand for a dynamic reference turns on +// seeing every anchor the schema could reach, so the ones that answer to +// a single destination are rewritten to it +template +auto resolve_dynamic_anchors(Locations &locations, References &references) + -> void { + using sourcemeta::core::SchemaFrame; + using sourcemeta::core::SchemaReferenceType; + // Find all dynamic anchors + // Values are pointers to full URIs in locations_ + std::unordered_map> + dynamic_anchors; + for (const auto &entry : locations) { + if (entry.first.first != SchemaReferenceType::Dynamic) { + continue; + } + + // An anchor is the only thing a dialect lets a dynamic name reach, so it + // is the only kind of location registered under one + assert(entry.second.type == SchemaFrame::LocationType::Anchor); + + const sourcemeta::core::URI anchor_uri{entry.first.second}; + // Copy the fragment to avoid dangling string_view (anchor_uri is local) + const sourcemeta::core::JSON::String fragment{ + anchor_uri.fragment().value_or("")}; + dynamic_anchors[fragment].push_back(&entry.first.second); + } + + // If there is a dynamic reference that only has one possible + // dynamic anchor destination, then that dynamic reference + // is a static reference in disguise + std::vector to_delete; + std::vector to_insert; + for (const auto &reference : references) { + if (reference.first.first != SchemaReferenceType::Dynamic || + !reference.second.fragment.has_value()) { + continue; + } + + const auto match{dynamic_anchors.find( + sourcemeta::core::JSON::String{reference.second.fragment.value()})}; + assert(match != dynamic_anchors.cend()); + // Otherwise we can assume there is only one possible target for the + // dynamic reference + if (match->second.size() != 1) { + continue; + } + + to_delete.push_back(reference.first); + to_insert.emplace_back( + typename References::key_type{SchemaReferenceType::Static, + reference.first.second}, + typename References::mapped_type{.original = reference.second.original, + .destination = *match->second.front(), + .base = std::string_view{}, + .fragment = std::nullopt}); + } + + // Because we can't mutate a map as we are traversing it + + for (const auto &key : to_delete) { + references.erase(key); + } + + for (auto &&entry : to_insert) { + const auto [entry_iterator, inserted] = + references.emplace(std::move(entry)); + set_base_and_fragment(entry_iterator->second); + } +} + +// Every pointer of the analysed document becomes a location of its own, +// under each base that names the place it sits in +template +auto register_pointer_locations( + const std::vector &pointers, + const BaseMapType &base_uris, const DialectMapType &base_dialects, + const SubschemaMapType &subschemas, const std::uint64_t max_locations, + Locations &locations, Owned &owned, + const sourcemeta::core::JSON::String &default_base) -> void { + using sourcemeta::core::SchemaFrame; + using sourcemeta::core::SchemaReferenceType; + for (const auto &pointer_weak : pointers) { + + const auto combined{ + find_dialect_and_all_bases(base_dialects, base_uris, pointer_weak)}; + // Every schema records the dialect it is read under, the root among + // them, so the walk up from any pointer reaches one + assert(combined.dialect_match.has_value()); + const auto &dialect_for_pointer{ + combined.dialect_match->first.get().dialects.front()}; + const auto base_dialect_for_pointer{ + combined.dialect_match->first.get().base_dialect}; + const auto &every_base_result{combined.every_base}; + + std::optional> + nearest_base_info; + for (const auto &entry : every_base_result) { + if (!entry.first.empty()) { + nearest_base_info = entry; + break; + } + } + + const auto subschema_it{subschemas.find(pointer_weak)}; + const bool is_subschema{subschema_it != subschemas.cend()}; + const auto nearest_base_depth = + nearest_base_info.has_value() ? nearest_base_info->second.size() : 0; + + std::string_view hoisted_base_view{}; + if (nearest_base_info.has_value()) { + hoisted_base_view = owned_base_view(locations, owned, default_base, + nearest_base_info->first); + } + + sourcemeta::core::WeakPointer cached_base{}; + for (const auto &base : every_base_result) { + const auto resolved{cached_base == base.second + ? pointer_weak.resolve_from(cached_base) + : pointer_weak.resolve_from(base.second)}; + cached_base = base.second; + + auto relative_pointer_uri{ + base.first.empty() ? sourcemeta::core::to_uri(resolved) + : sourcemeta::core::to_uri(resolved, base.first)}; + + relative_pointer_uri.canonicalize(); + auto result{relative_pointer_uri.recompose()}; + + bool contains = locations.contains({SchemaReferenceType::Static, result}); + + if (!contains) { + std::string_view base_view; + + if (nearest_base_info.has_value()) { + base_view = hoisted_base_view; + } else { + base_view = + owned_base_view(locations, owned, default_base, base.first); + } + + if (is_subschema) { + store(locations, max_locations, SchemaReferenceType::Static, + SchemaFrame::LocationType::Subschema, std::move(result), + base_view, pointer_weak, nearest_base_depth, + dialect_for_pointer, base_dialect_for_pointer, + subschema_it->second.parent, subschema_it->second.property_name, + subschema_it->second.orphan, true); + } else { + // What a dialect match names is the schema nearest above the + // place, which the traversal reported as a subschema of its own + const auto &parent_pointer{combined.dialect_match->second}; + const auto parent_subschema_it{subschemas.find(parent_pointer)}; + assert(parent_subschema_it != subschemas.cend()); + const bool parent_property_name{ + parent_subschema_it->second.property_name}; + const bool parent_orphan{parent_subschema_it->second.orphan}; + + store(locations, max_locations, SchemaReferenceType::Static, + SchemaFrame::LocationType::Pointer, std::move(result), + base_view, pointer_weak, nearest_base_depth, + dialect_for_pointer, base_dialect_for_pointer, parent_pointer, + parent_property_name, parent_orphan, true); + } + } + } + } +} + +// Each subschema the walker reached under this path, registered as a +// location of its own along with the references and anchors it carries +template +auto register_subschema_entries( + const EntryList &subschema_entries, + const std::vector ¤t_subschema_entries, + BaseMapType &base_uris, + const std::optional &root_id, + const bool has_explicit_different_id, const std::uint64_t max_locations, + const sourcemeta::core::SchemaFrame::Mode mode, Locations &locations, + References &references, Owned &owned, + const sourcemeta::core::JSON::String &default_base, + const sourcemeta::core::JSON::String &default_id_canonical) -> void { + using sourcemeta::core::SchemaFrame; + using sourcemeta::core::SchemaFrameError; + using sourcemeta::core::SchemaReferenceType; + using sourcemeta::core::StaticString; + for (const auto &entry_index : current_subschema_entries) { + const auto &entry{subschema_entries[entry_index]}; + const auto &common_pointer_weak{entry.common.pointer}; + const auto &common_parent{entry.common.parent}; + if (entry.id.has_value()) { + assert(entry.common.base_dialect.has_value()); + const bool ref_overrides = + sourcemeta::core::ref_overrides_adjacent_keywords( + entry.common.base_dialect.value()); + const bool is_pre_2019_09_location_independent_identifier = + supports_id_anchors(entry.common.base_dialect.value()) && + entry.id.value().starts_with('#'); + + if ((!entry.common.subschema.get().is_object() || + !entry.common.subschema.get().defines( + "$ref"sv, sourcemeta::core::JSONSCHEMA_HASH_REF) || + !ref_overrides) && + // If we are dealing with a pre-2019-09 location independent + // identifier, we ignore it as a traditional identifier and take + // care of it as an anchor + !is_pre_2019_09_location_independent_identifier) { + // RFC 3986 Section 5.1 resolves a reference against a base, and an + // identifier is what states the base that the rest of its resource + // reads against, so where nothing above states one the identifier + // has nothing to resolve against. Everything else within the + // resource does resolve against it, which is why this lookup is the + // one that declines to take it as a base of its own + const auto stated{ + find_nearest_bases_ref( + base_uris, common_pointer_weak)}; + std::vector own_base; + if (!stated.has_value()) { + own_base.emplace_back(entry.id.value()); + } + + const auto &base_strings{stated.has_value() ? stated->first.get() + : own_base}; + for (const auto &base_string : base_strings) { + // Otherwise we end up pushing the top-level resource twice. The + // name the caller gave is compared as it was resolved rather than + // as it was written, which is what the schema is known by + if (entry_index == 0 && has_explicit_different_id && + !default_id_canonical.empty() && + default_id_canonical == base_string) { + continue; + } + + // RFC 3986 Section 5.1 puts the base a document was retrieved + // from last, after whatever the document carries within itself, + // so an identifier resolves against it only where the document + // carries no base of its own. The identifier that the top of the + // document carries resolved against it already, and an identifier + // below the top resolves against the resource enclosing it, which + // JSON Schema 2020-12 Section 8.2.1 names as the one base either + // way. Registering from the retrieval base as well would name a + // resource that nothing resolves to. Where the document goes by + // no other base, that earlier registration is this one rather + // than a second copy of it, and skipping would leave the document + // as no resource at all. The name the caller gave is not one of + // those other bases, as the check above skips it in its own right + if (base_string == default_base && + std::ranges::any_of(base_strings, + [&default_base, &default_id_canonical]( + const auto &candidate) -> bool { + return candidate != default_base && + candidate != default_id_canonical; + })) { + continue; + } + + sourcemeta::core::URI base; + sourcemeta::core::URI maybe_relative; + try { + base = sourcemeta::core::URI{base_string}; + maybe_relative = sourcemeta::core::URI{entry.id.value()}; + } catch (const sourcemeta::core::URIParseError &) { + throw sourcemeta::core::SchemaKeywordError( + "The identifier is not a valid URI", + sourcemeta::core::id_keyword(entry.common.base_dialect.value()) + .name, + entry.id.value()); + } + + const auto maybe_fragment{maybe_relative.fragment()}; + + // Both 2019-09 and 2020-12 state: + // + // "$id" MUST NOT contain a non-empty fragment, and SHOULD NOT + // contain an empty fragment. + // + // See + // https://json-schema.org/draft/2019-09/draft-handrews-json-schema-02#rfc.section.8.2.2 + // See + // https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-01#section-8.2.1-5 + if (maybe_fragment.has_value() && !maybe_fragment.value().empty()) { + // Before 2019-09 an identifier may carry a fragment, but only by + // consisting of nothing else, in which case it declares an anchor + // and never reaches here + throw SchemaFrameError( + supports_id_anchors(entry.common.base_dialect.value()) + ? StaticString{"Identifiers may only carry a fragment " + "when they consist of nothing else"} + : StaticString{"Identifiers must not contain non-empty " + "fragments"}, + entry.id.value()); + } + + // An identifier of the document that names an anchor was taken + // apart above, so a document reaching here with one declared it as + // a resource, which is the name the frame came back with + sourcemeta::core::JSON::String new_id; + assert(!common_pointer_weak.empty() || root_id.has_value()); + if (common_pointer_weak.empty() && base_string == root_id.value()) { + new_id = root_id.value(); + } else if (!stated.has_value()) { + // RFC 3986 Section 5.2.3 merges a relative reference into the + // directory of its base, so resolving the identifier against + // itself would name a place one level below the resource + maybe_relative.canonicalize(); + new_id = maybe_relative.recompose(); + } else { + maybe_relative.resolve_from(base).canonicalize(); + new_id = maybe_relative.recompose(); + } + + const auto maybe_match{ + locations.find({SchemaReferenceType::Static, new_id})}; + if (maybe_match != locations.cend() && + maybe_match->second.pointer != common_pointer_weak) { + throw_already_exists(new_id); + } + + // Two bases that differ only in their last segment resolve the + // same relative identifier to the same place, because merging a + // relative reference drops everything after the base's last + // slash. The check above has already refused a match that sits + // somewhere else, so a match here is this very place under the + // name it already goes by, and storing it again would only + // collide with itself + if (maybe_match == locations.cend()) { + assert(entry.common.base_dialect.has_value()); + + store(locations, max_locations, SchemaReferenceType::Static, + SchemaFrame::LocationType::Resource, new_id, new_id, + common_pointer_weak, common_pointer_weak.size(), + entry.common.dialect, entry.common.base_dialect.value(), + common_parent, entry.common.property_name, + entry.common.orphan); + } + + auto base_uri_match{base_uris.find(common_pointer_weak)}; + if (base_uri_match != base_uris.cend()) { + if (!std::ranges::contains(base_uri_match->second, new_id)) { + base_uri_match->second.push_back(new_id); + } + } else { + base_uris.insert({common_pointer_weak, {new_id}}); + } + } + } + } + + if (mode >= SchemaFrame::Mode::References) { + resolve_metaschema_ref(entry, base_uris, references); + } + + store_anchors(locations, owned, default_base, max_locations, base_uris, + entry); + } +} + +// Every subschema the walker reaches under this path, collected along with +// the bases and dialects that hold at each of them +template +auto collect_subschema_entries( + const sourcemeta::core::JSON &schema, + const sourcemeta::core::WeakPointer &path, + const sourcemeta::core::SchemaWalker &walker, + const sourcemeta::core::SchemaResolver &resolver, + const sourcemeta::core::SchemaResolver &effective_resolver, + const std::string_view default_dialect, const bool root_declares_anchor, + const std::optional &root_id, + EntryList &subschema_entries, + std::vector ¤t_subschema_entries, + SubschemaMapType &subschemas, DialectMapType &base_dialects, + ProbedMetaschemas &probed_metaschemas) -> void { + using sourcemeta::core::SchemaIterator; + for (const auto &relative_entry : sourcemeta::core::SchemaIterator{ + schema, walker, effective_resolver, default_dialect}) { + // Rephrase the iterator entry as being for the current base + auto entry{relative_entry}; + entry.pointer = path.concat(relative_entry.pointer); + if (entry.parent.has_value()) { + entry.parent = path.concat(relative_entry.parent.value()); + } + + // Dialect + assert(!entry.dialect.empty()); + assert(entry.base_dialect.has_value()); + base_dialects.insert( + {entry.pointer, + DialectAtPointer{.dialects = {entry.dialect}, + .base_dialect = entry.base_dialect.value()}}); + + // A nested resource may pin a custom meta-schema inside its own + // containers. Cache it here, just like we do for the root, so that later + // vocabulary lookups (which consult this cache) can resolve it. If the + // same meta-schema identifier is embedded in more than one place with a + // different definition, that is an ambiguity we refuse to resolve + if (!sourcemeta::core::to_base_dialect(entry.dialect).has_value()) { + const sourcemeta::core::JSON::String dialect_key{entry.dialect}; + const auto *embedded{sourcemeta::core::metaschema_try_embedded( + entry.subschema.get(), entry.dialect, resolver)}; + if (embedded != nullptr) { + const auto match{probed_metaschemas.find(dialect_key)}; + if (match == probed_metaschemas.cend()) { + probed_metaschemas.emplace(dialect_key, embedded); + } else if (*(match->second) != *embedded) { + throw_already_exists(dialect_key); + } + } + } + + // Schema identifier + // We need to store the default_id in a local variable to ensure + // it survives the identify() call, as identify() returns a string_view + const auto entry_is_the_document{entry.pointer.empty() && + root_id.has_value()}; + const std::string default_id_for_entry{ + entry_is_the_document ? root_id.value() : std::string{}}; + // An identifier that only names the top of the document in place was + // taken apart above, which leaves the name the caller gave it, if any, + // as the one that identifies the document + // A name for the entry only stands where the entry is the top of the + // document, which is the one place the name above comes from, so asking + // for that name is asking where the entry sits as well + const auto document_answers_to_the_name_given{ + root_declares_anchor && !default_id_for_entry.empty()}; + auto maybe_id{document_answers_to_the_name_given + ? std::string_view{default_id_for_entry} + : sourcemeta::core::identify(entry.subschema.get(), + entry.base_dialect.value(), + default_id_for_entry)}; + // Anything other than what the caller supplied came out of the schema + // itself, and only counts where the dialect gives its keyword a meaning. + // Comparing first keeps the lookup off the path that declares nothing + if (maybe_id != default_id_for_entry && + !sourcemeta::core::dialect_defines_identifier( + walker, entry.vocabularies, entry.base_dialect.value())) { + maybe_id = default_id_for_entry; + } + std::optional identifier{ + !maybe_id.empty() + ? std::make_optional(maybe_id) + : std::nullopt}; + + // Store information + subschemas.emplace(entry.pointer, + CacheSubschema{.orphan = entry.orphan, + .property_name = entry.property_name, + .parent = entry.parent}); + subschema_entries.emplace_back( + InternalEntry{.common = std::move(entry), .id = std::move(identifier)}); + current_subschema_entries.emplace_back(subschema_entries.size() - 1); + } +} + +// In the mode that reports on a single schema, the root is the one location +// there is, named by each base it answers to +template +auto register_root_location( + const sourcemeta::core::JSON &schema, + const sourcemeta::core::WeakPointer &path, + const sourcemeta::core::SchemaResolver &resolver, + const std::optional &root_base_dialect, + const std::string_view root_dialect, + const std::optional &root_id, + const std::uint64_t max_locations, Locations &locations, + const sourcemeta::core::JSON::String &default_base, + ProbedMetaschemas &probed_metaschemas) -> void { + using sourcemeta::core::SchemaFrame; + using sourcemeta::core::SchemaFrameError; + using sourcemeta::core::SchemaReferenceType; + using sourcemeta::core::StaticString; + // The schema may pin a custom meta-schema inside its own containers. + // Cache it, as the vocabulary lookups that this mode exists to serve + // consult that cache + if (!sourcemeta::core::to_base_dialect(root_dialect).has_value()) { + const sourcemeta::core::JSON::String dialect_key{root_dialect}; + const auto *embedded{sourcemeta::core::metaschema_try_embedded( + schema, root_dialect, resolver)}; + if (embedded != nullptr) { + probed_metaschemas.emplace(dialect_key, embedded); + } + } + + if (root_id.has_value()) { + const sourcemeta::core::URI identifier{root_id.value()}; + // The identifier was settled to its canonical spelling above, which + // leaves no empty fragment behind, so one that is there carries + // something + const auto fragment{identifier.fragment()}; + assert(!fragment.has_value() || !fragment.value().empty()); + if (fragment.has_value()) { + throw SchemaFrameError( + supports_id_anchors(root_base_dialect.value()) + ? StaticString{"Identifiers may only carry a fragment when " + "they consist of nothing else"} + : StaticString{"Identifiers must not contain non-empty " + "fragments"}, + root_id.value()); + } + } + + // A document that declares no identifier is still addressed by the base + // it was retrieved from, which is how every other mode addresses it. + // That base addresses the top of the document, so it names the schema + // under analysis only where the two are the same place + const auto location_uri{root_id.value_or( + path.empty() ? default_base : sourcemeta::core::JSON::String{})}; + store(locations, max_locations, SchemaReferenceType::Static, + root_id.has_value() ? SchemaFrame::LocationType::Resource + : SchemaFrame::LocationType::Subschema, + location_uri, location_uri, path, path.size(), root_dialect, + root_base_dialect.value(), std::nullopt, false, false, true); +} } // namespace namespace sourcemeta::core { @@ -1154,435 +2060,25 @@ SchemaFrame::SchemaFrame(const Mode mode, const sourcemeta::core::JSON &root, } if (this->mode_ == SchemaFrame::Mode::Root) { - // The schema may pin a custom meta-schema inside its own containers. - // Cache it, as the vocabulary lookups that this mode exists to serve - // consult that cache - if (!sourcemeta::core::to_base_dialect(root_dialect).has_value()) { - const sourcemeta::core::JSON::String dialect_key{root_dialect}; - const auto *embedded{sourcemeta::core::metaschema_try_embedded( - schema, root_dialect, resolver)}; - if (embedded != nullptr) { - this->cache_->probed_metaschemas.emplace(dialect_key, embedded); - } - } - - if (root_id.has_value()) { - const sourcemeta::core::URI identifier{root_id.value()}; - // The identifier was settled to its canonical spelling above, which - // leaves no empty fragment behind, so one that is there carries - // something - const auto fragment{identifier.fragment()}; - assert(!fragment.has_value() || !fragment.value().empty()); - if (fragment.has_value()) { - throw SchemaFrameError( - supports_id_anchors(root_base_dialect.value()) - ? StaticString{"Identifiers may only carry a fragment when " - "they consist of nothing else"} - : StaticString{"Identifiers must not contain non-empty " - "fragments"}, - root_id.value()); - } - } - - // A document that declares no identifier is still addressed by the base - // it was retrieved from, which is how every other mode addresses it. - // That base addresses the top of the document, so it names the schema - // under analysis only where the two are the same place - const auto location_uri{ - root_id.value_or(path.empty() ? this->cache_->default_base - : sourcemeta::core::JSON::String{})}; - store(this->locations_, max_locations, SchemaReferenceType::Static, - root_id.has_value() ? SchemaFrame::LocationType::Resource - : SchemaFrame::LocationType::Subschema, - location_uri, location_uri, path, path.size(), root_dialect, - root_base_dialect.value(), std::nullopt, false, false, true); + register_root_location(schema, path, resolver, root_base_dialect, + root_dialect, root_id, max_locations, + this->locations_, this->cache_->default_base, + this->cache_->probed_metaschemas); continue; } std::vector current_subschema_entries; - for (const auto &relative_entry : sourcemeta::core::SchemaIterator{ - schema, walker, effective_resolver, default_dialect}) { - // Rephrase the iterator entry as being for the current base - auto entry{relative_entry}; - entry.pointer = path.concat(relative_entry.pointer); - if (entry.parent.has_value()) { - entry.parent = path.concat(relative_entry.parent.value()); - } - - // Dialect - assert(!entry.dialect.empty()); - assert(entry.base_dialect.has_value()); - base_dialects.insert( - {entry.pointer, - DialectAtPointer{.dialects = {entry.dialect}, - .base_dialect = entry.base_dialect.value()}}); - - // A nested resource may pin a custom meta-schema inside its own - // containers. Cache it here, just like we do for the root, so that later - // vocabulary lookups (which consult this cache) can resolve it. If the - // same meta-schema identifier is embedded in more than one place with a - // different definition, that is an ambiguity we refuse to resolve - if (!sourcemeta::core::to_base_dialect(entry.dialect).has_value()) { - const sourcemeta::core::JSON::String dialect_key{entry.dialect}; - const auto *embedded{sourcemeta::core::metaschema_try_embedded( - entry.subschema.get(), entry.dialect, resolver)}; - if (embedded != nullptr) { - const auto match{this->cache_->probed_metaschemas.find(dialect_key)}; - if (match == this->cache_->probed_metaschemas.cend()) { - this->cache_->probed_metaschemas.emplace(dialect_key, embedded); - } else if (*(match->second) != *embedded) { - throw_already_exists(dialect_key); - } - } - } - - // Schema identifier - // We need to store the default_id in a local variable to ensure - // it survives the identify() call, as identify() returns a string_view - const auto entry_is_the_document{entry.pointer.empty() && - root_id.has_value()}; - const std::string default_id_for_entry{ - entry_is_the_document ? root_id.value() : std::string{}}; - // An identifier that only names the top of the document in place was - // taken apart above, which leaves the name the caller gave it, if any, - // as the one that identifies the document - // A name for the entry only stands where the entry is the top of the - // document, which is the one place the name above comes from, so asking - // for that name is asking where the entry sits as well - const auto document_answers_to_the_name_given{ - root_declares_anchor && !default_id_for_entry.empty()}; - auto maybe_id{document_answers_to_the_name_given - ? std::string_view{default_id_for_entry} - : sourcemeta::core::identify(entry.subschema.get(), - entry.base_dialect.value(), - default_id_for_entry)}; - // Anything other than what the caller supplied came out of the schema - // itself, and only counts where the dialect gives its keyword a meaning. - // Comparing first keeps the lookup off the path that declares nothing - if (maybe_id != default_id_for_entry && - !sourcemeta::core::dialect_defines_identifier( - walker, entry.vocabularies, entry.base_dialect.value())) { - maybe_id = default_id_for_entry; - } - std::optional identifier{ - !maybe_id.empty() - ? std::make_optional(maybe_id) - : std::nullopt}; - - // Store information - subschemas.emplace(entry.pointer, - CacheSubschema{.orphan = entry.orphan, - .property_name = entry.property_name, - .parent = entry.parent}); - subschema_entries.emplace_back(InternalEntry{ - .common = std::move(entry), .id = std::move(identifier)}); - current_subschema_entries.emplace_back(subschema_entries.size() - 1); - } - - for (const auto &entry_index : current_subschema_entries) { - const auto &entry{subschema_entries[entry_index]}; - const auto &common_pointer_weak{entry.common.pointer}; - const auto &common_parent{entry.common.parent}; - if (entry.id.has_value()) { - assert(entry.common.base_dialect.has_value()); - const bool ref_overrides = - sourcemeta::core::ref_overrides_adjacent_keywords( - entry.common.base_dialect.value()); - const bool is_pre_2019_09_location_independent_identifier = - supports_id_anchors(entry.common.base_dialect.value()) && - entry.id.value().starts_with('#'); - - if ((!entry.common.subschema.get().is_object() || - !entry.common.subschema.get().defines( - "$ref"sv, sourcemeta::core::JSONSCHEMA_HASH_REF) || - !ref_overrides) && - // If we are dealing with a pre-2019-09 location independent - // identifier, we ignore it as a traditional identifier and take - // care of it as an anchor - !is_pre_2019_09_location_independent_identifier) { - // RFC 3986 Section 5.1 resolves a reference against a base, and an - // identifier is what states the base that the rest of its resource - // reads against, so where nothing above states one the identifier - // has nothing to resolve against. Everything else within the - // resource does resolve against it, which is why this lookup is the - // one that declines to take it as a base of its own - const auto stated{ - find_nearest_bases_ref( - base_uris, common_pointer_weak)}; - std::vector own_base; - if (!stated.has_value()) { - own_base.emplace_back(entry.id.value()); - } - - const auto &base_strings{stated.has_value() ? stated->first.get() - : own_base}; - for (const auto &base_string : base_strings) { - // Otherwise we end up pushing the top-level resource twice. The - // name the caller gave is compared as it was resolved rather than - // as it was written, which is what the schema is known by - if (entry_index == 0 && has_explicit_different_id && - !default_id_canonical.empty() && - default_id_canonical == base_string) { - continue; - } - - // RFC 3986 Section 5.1 puts the base a document was retrieved - // from last, after whatever the document carries within itself, - // so an identifier resolves against it only where the document - // carries no base of its own. The identifier that the top of the - // document carries resolved against it already, and an identifier - // below the top resolves against the resource enclosing it, which - // JSON Schema 2020-12 Section 8.2.1 names as the one base either - // way. Registering from the retrieval base as well would name a - // resource that nothing resolves to. Where the document goes by - // no other base, that earlier registration is this one rather - // than a second copy of it, and skipping would leave the document - // as no resource at all. The name the caller gave is not one of - // those other bases, as the check above skips it in its own right - if (base_string == this->cache_->default_base && - std::ranges::any_of(base_strings, - [this, &default_id_canonical]( - const auto &candidate) -> bool { - return candidate != - this->cache_->default_base && - candidate != default_id_canonical; - })) { - continue; - } - - sourcemeta::core::URI base; - sourcemeta::core::URI maybe_relative; - try { - base = sourcemeta::core::URI{base_string}; - maybe_relative = sourcemeta::core::URI{entry.id.value()}; - } catch (const sourcemeta::core::URIParseError &) { - throw sourcemeta::core::SchemaKeywordError( - "The identifier is not a valid URI", - sourcemeta::core::id_keyword( - entry.common.base_dialect.value()) - .name, - entry.id.value()); - } - - const auto maybe_fragment{maybe_relative.fragment()}; - - // Both 2019-09 and 2020-12 state: - // - // "$id" MUST NOT contain a non-empty fragment, and SHOULD NOT - // contain an empty fragment. - // - // See - // https://json-schema.org/draft/2019-09/draft-handrews-json-schema-02#rfc.section.8.2.2 - // See - // https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-01#section-8.2.1-5 - if (maybe_fragment.has_value() && !maybe_fragment.value().empty()) { - // Before 2019-09 an identifier may carry a fragment, but only by - // consisting of nothing else, in which case it declares an anchor - // and never reaches here - throw SchemaFrameError( - supports_id_anchors(entry.common.base_dialect.value()) - ? StaticString{"Identifiers may only carry a fragment " - "when they consist of nothing else"} - : StaticString{"Identifiers must not contain non-empty " - "fragments"}, - entry.id.value()); - } - - // An identifier of the document that names an anchor was taken - // apart above, so a document reaching here with one declared it as - // a resource, which is the name the frame came back with - sourcemeta::core::JSON::String new_id; - assert(!common_pointer_weak.empty() || root_id.has_value()); - if (common_pointer_weak.empty() && base_string == root_id.value()) { - new_id = root_id.value(); - } else if (!stated.has_value()) { - // RFC 3986 Section 5.2.3 merges a relative reference into the - // directory of its base, so resolving the identifier against - // itself would name a place one level below the resource - maybe_relative.canonicalize(); - new_id = maybe_relative.recompose(); - } else { - maybe_relative.resolve_from(base).canonicalize(); - new_id = maybe_relative.recompose(); - } - - const auto maybe_match{ - this->locations_.find({SchemaReferenceType::Static, new_id})}; - if (maybe_match != this->locations_.cend() && - maybe_match->second.pointer != common_pointer_weak) { - throw_already_exists(new_id); - } - - // Two bases that differ only in their last segment resolve the - // same relative identifier to the same place, because merging a - // relative reference drops everything after the base's last - // slash. The check above has already refused a match that sits - // somewhere else, so a match here is this very place under the - // name it already goes by, and storing it again would only - // collide with itself - if (maybe_match == this->locations_.cend()) { - assert(entry.common.base_dialect.has_value()); - - store(this->locations_, max_locations, - SchemaReferenceType::Static, - SchemaFrame::LocationType::Resource, new_id, new_id, - common_pointer_weak, common_pointer_weak.size(), - entry.common.dialect, entry.common.base_dialect.value(), - common_parent, entry.common.property_name, - entry.common.orphan); - } - - auto base_uri_match{base_uris.find(common_pointer_weak)}; - if (base_uri_match != base_uris.cend()) { - if (!std::ranges::contains(base_uri_match->second, new_id)) { - base_uri_match->second.push_back(new_id); - } - } else { - base_uris.insert({common_pointer_weak, {new_id}}); - } - } - } - } - - if (this->mode_ >= SchemaFrame::Mode::References) { - // Handle metaschema references - const auto maybe_metaschema{ - sourcemeta::core::dialect(entry.common.subschema.get(), {}, false)}; - if (!maybe_metaschema.empty()) { - sourcemeta::core::URI metaschema; - try { - metaschema = sourcemeta::core::URI{maybe_metaschema}; - } catch (const sourcemeta::core::URIParseError &) { - throw SchemaKeywordError("The dialect is not a valid URI", - "$schema", maybe_metaschema); - } - - const auto nearest_bases{ - find_nearest_bases( - base_uris, common_pointer_weak, - entry.id ? std::optional{*entry.id} - : std::nullopt)}; - if (!nearest_bases.first.empty()) { - metaschema.resolve_from( - sourcemeta::core::URI{nearest_bases.first.front()}); - } - - metaschema.canonicalize(); - assert(entry.common.subschema.get().defines( - "$schema"sv, sourcemeta::core::JSONSCHEMA_HASH_SCHEMA)); - auto schema_pointer{common_pointer_weak}; - schema_pointer.push_back(std::cref(KEYWORD_SCHEMA)); - const auto [entry_iterator, inserted] = - this->references_.insert_or_assign( - {SchemaReferenceType::Static, std::move(schema_pointer)}, - SchemaFrame::Reference{.original = maybe_metaschema, - .destination = metaschema.recompose(), - .base = std::string_view{}, - .fragment = std::nullopt}); - set_base_and_fragment(entry_iterator->second); - } - } - - // Handle schema anchors - for (const auto &[name, type] : find_anchors(entry.common.subschema.get(), - entry.common.vocabularies)) { - const auto bases{find_nearest_bases( - base_uris, common_pointer_weak, - entry.id ? std::optional{*entry.id} - : std::nullopt)}; - - if (bases.first.empty()) { - const auto anchor_uri{sourcemeta::core::URI::from_fragment(name)}; - const auto relative_anchor_uri{anchor_uri.recompose()}; - - if (type == AnchorType::Static || type == AnchorType::All) { - store(this->locations_, max_locations, SchemaReferenceType::Static, - SchemaFrame::LocationType::Anchor, relative_anchor_uri, "", - common_pointer_weak, bases.second.size(), - entry.common.dialect, entry.common.base_dialect.value(), - common_parent, entry.common.property_name, - entry.common.orphan); - } - - if (type == AnchorType::Dynamic || type == AnchorType::All) { - store(this->locations_, max_locations, SchemaReferenceType::Dynamic, - SchemaFrame::LocationType::Anchor, relative_anchor_uri, "", - common_pointer_weak, bases.second.size(), - entry.common.dialect, entry.common.base_dialect.value(), - common_parent, entry.common.property_name, - entry.common.orphan); - - // A dynamic anchor declares a static anchor of the same name - // too. When the location also carries `$anchor`, the branch above - // already registered it - if (type == AnchorType::Dynamic && - entry.common.vocabularies.contains( - SchemaVocabularies::Known::JSON_SCHEMA_2020_12_CORE)) { - store(this->locations_, max_locations, - SchemaReferenceType::Static, - SchemaFrame::LocationType::Anchor, relative_anchor_uri, "", - common_pointer_weak, bases.second.size(), - entry.common.dialect, entry.common.base_dialect.value(), - common_parent, entry.common.property_name, - entry.common.orphan); - } - } - } else { - [[maybe_unused]] bool is_first{true}; - for (const auto &base_string : bases.first) { - sourcemeta::core::URI anchor_uri_builder{base_string}; - anchor_uri_builder.fragment(name); - anchor_uri_builder.canonicalize(); - const auto anchor_uri{anchor_uri_builder.recompose()}; - - // Two bases of one place never spell a single anchor, as the - // fragment put on them is the same and each base is a name of its - // own, so the first of them is the only one that can have taken - // the name this one is about to - assert(is_first || !this->locations_.contains( - {SchemaReferenceType::Static, anchor_uri})); - - const auto base_view{ - owned_base_view(this->locations_, this->cache_->bases, - this->cache_->default_base, base_string)}; - - if (type == AnchorType::Static || type == AnchorType::All) { - store(this->locations_, max_locations, - sourcemeta::core::SchemaReferenceType::Static, - SchemaFrame::LocationType::Anchor, anchor_uri, base_view, - common_pointer_weak, bases.second.size(), - entry.common.dialect, entry.common.base_dialect.value(), - common_parent, entry.common.property_name, - entry.common.orphan); - } - - if (type == AnchorType::Dynamic || type == AnchorType::All) { - store(this->locations_, max_locations, - sourcemeta::core::SchemaReferenceType::Dynamic, - SchemaFrame::LocationType::Anchor, anchor_uri, base_view, - common_pointer_weak, bases.second.size(), - entry.common.dialect, entry.common.base_dialect.value(), - common_parent, entry.common.property_name, - entry.common.orphan); - - if (type == AnchorType::Dynamic && - entry.common.vocabularies.contains( - SchemaVocabularies::Known::JSON_SCHEMA_2020_12_CORE)) { - store(this->locations_, max_locations, - sourcemeta::core::SchemaReferenceType::Static, - SchemaFrame::LocationType::Anchor, anchor_uri, base_view, - common_pointer_weak, bases.second.size(), - entry.common.dialect, entry.common.base_dialect.value(), - common_parent, entry.common.property_name, - entry.common.orphan); - } - } - - is_first = false; - } - } - } - } + collect_subschema_entries(schema, path, walker, resolver, + effective_resolver, default_dialect, + root_declares_anchor, root_id, subschema_entries, + current_subschema_entries, subschemas, + base_dialects, this->cache_->probed_metaschemas); + + register_subschema_entries( + subschema_entries, current_subschema_entries, base_uris, root_id, + has_explicit_different_id, max_locations, this->mode_, this->locations_, + this->references_, this->cache_->bases, this->cache_->default_base, + default_id_canonical); // It is important for the loop that follows to assume a specific ordering // where smaller pointers (by number of tokens) are scanned first. @@ -1605,95 +2101,9 @@ SchemaFrame::SchemaFrame(const Mode mode, const sourcemeta::core::JSON &root, std::ranges::sort(pointers, std::less<>()); // Pre-compute every possible pointer to the schema - for (const auto &pointer_weak : pointers) { - - const auto combined{ - find_dialect_and_all_bases(base_dialects, base_uris, pointer_weak)}; - // Every schema records the dialect it is read under, the root among - // them, so the walk up from any pointer reaches one - assert(combined.dialect_match.has_value()); - const auto &dialect_for_pointer{ - combined.dialect_match->first.get().dialects.front()}; - const auto base_dialect_for_pointer{ - combined.dialect_match->first.get().base_dialect}; - const auto &every_base_result{combined.every_base}; - - std::optional> - nearest_base_info; - for (const auto &entry : every_base_result) { - if (!entry.first.empty()) { - nearest_base_info = entry; - break; - } - } - - const auto subschema_it{subschemas.find(pointer_weak)}; - const bool is_subschema{subschema_it != subschemas.cend()}; - const auto nearest_base_depth = - nearest_base_info.has_value() ? nearest_base_info->second.size() : 0; - - std::string_view hoisted_base_view{}; - if (nearest_base_info.has_value()) { - hoisted_base_view = owned_base_view( - this->locations_, this->cache_->bases, this->cache_->default_base, - nearest_base_info->first); - } - - sourcemeta::core::WeakPointer cached_base{}; - for (const auto &base : every_base_result) { - const auto resolved{cached_base == base.second - ? pointer_weak.resolve_from(cached_base) - : pointer_weak.resolve_from(base.second)}; - cached_base = base.second; - - auto relative_pointer_uri{ - base.first.empty() - ? sourcemeta::core::to_uri(resolved) - : sourcemeta::core::to_uri(resolved, base.first)}; - - relative_pointer_uri.canonicalize(); - auto result{relative_pointer_uri.recompose()}; - - bool contains = - this->locations_.contains({SchemaReferenceType::Static, result}); - - if (!contains) { - std::string_view base_view; - - if (nearest_base_info.has_value()) { - base_view = hoisted_base_view; - } else { - base_view = owned_base_view(this->locations_, this->cache_->bases, - this->cache_->default_base, base.first); - } - - if (is_subschema) { - store(this->locations_, max_locations, SchemaReferenceType::Static, - SchemaFrame::LocationType::Subschema, std::move(result), - base_view, pointer_weak, nearest_base_depth, - dialect_for_pointer, base_dialect_for_pointer, - subschema_it->second.parent, - subschema_it->second.property_name, - subschema_it->second.orphan, true); - } else { - // What a dialect match names is the schema nearest above the - // place, which the traversal reported as a subschema of its own - const auto &parent_pointer{combined.dialect_match->second}; - const auto parent_subschema_it{subschemas.find(parent_pointer)}; - assert(parent_subschema_it != subschemas.cend()); - const bool parent_property_name{ - parent_subschema_it->second.property_name}; - const bool parent_orphan{parent_subschema_it->second.orphan}; - - store(this->locations_, max_locations, SchemaReferenceType::Static, - SchemaFrame::LocationType::Pointer, std::move(result), - base_view, pointer_weak, nearest_base_depth, - dialect_for_pointer, base_dialect_for_pointer, parent_pointer, - parent_property_name, parent_orphan, true); - } - } - } - } + register_pointer_locations(pointers, base_uris, base_dialects, subschemas, + max_locations, this->locations_, + this->cache_->bases, this->cache_->default_base); // The entry above borrowed `this->root_` as its base. Re-point it at the // location that owns that URI, so that no location ends up with a view @@ -1718,157 +2128,18 @@ SchemaFrame::SchemaFrame(const Mode mode, const sourcemeta::core::JSON &root, // Resolve references after all framing was performed for (const auto &entry : subschema_entries) { - const auto &common_pointer_weak{entry.common.pointer}; - if (entry.common.subschema.get().is_object()) { - const auto nearest_bases{ - find_nearest_bases( - base_uris, common_pointer_weak, - entry.id ? std::optional{*entry.id} - : std::nullopt)}; - const auto *ref_value{entry.common.subschema.get().try_at( - "$ref"sv, sourcemeta::core::JSONSCHEMA_HASH_REF)}; - if (ref_value != nullptr) { - if (!ref_value->is_string()) { - std::ostringstream value; - sourcemeta::core::stringify(*ref_value, value); - throw sourcemeta::core::SchemaKeywordError("Invalid reference value", - "$ref", value.str()); - } - - const auto &original{ref_value->to_string()}; - sourcemeta::core::URI ref; - try { - ref = sourcemeta::core::URI{original}; - } catch (const sourcemeta::core::URIParseError &) { - throw sourcemeta::core::SchemaKeywordError( - "The reference is not a valid URI", "$ref", original); - } - - if (!nearest_bases.first.empty()) { - ref.resolve_from(sourcemeta::core::URI{nearest_bases.first.front()}); - } - - ref.canonicalize(); - canonicalize_pointer_fragment(ref); - auto ref_pointer{common_pointer_weak}; - ref_pointer.push_back(std::cref(KEYWORD_REF)); - const auto [entry_iterator, inserted] = - this->references_.insert_or_assign( - {SchemaReferenceType::Static, std::move(ref_pointer)}, - SchemaFrame::Reference{.original = original, - .destination = ref.recompose(), - .base = std::string_view{}, - .fragment = std::nullopt}); - set_base_and_fragment(entry_iterator->second); - } - - const auto *recursive_ref_value{ - entry.common.vocabularies.contains( - SchemaVocabularies::Known::JSON_SCHEMA_2019_09_CORE) - ? entry.common.subschema.get().try_at( - "$recursiveRef"sv, - sourcemeta::core::JSONSCHEMA_HASH_RECURSIVE_REF) - : nullptr}; - if (recursive_ref_value != nullptr) { - if (!recursive_ref_value->is_string()) { - std::ostringstream value; - sourcemeta::core::stringify(*recursive_ref_value, value); - throw sourcemeta::core::SchemaKeywordError( - "Invalid recursive reference value", "$recursiveRef", - value.str()); - } - - const auto &ref{recursive_ref_value->to_string()}; - - // The behavior of this keyword is defined only for the value "#". - // Implementations MAY choose to consider other values to be errors. - // See - // https://json-schema.org/draft/2019-09/draft-handrews-json-schema-02#rfc.section.8.2.4.2.1 - if (ref != "#") { - throw sourcemeta::core::SchemaReferenceError( - "Invalid recursive reference", entry.id.value_or(""), - to_pointer(common_pointer_weak).concat("$recursiveRef")); - } - - auto anchor_uri_string{ - nearest_bases.first.empty() ? "" : nearest_bases.first.front()}; - const auto recursive_anchor{this->locations_.find( - {SchemaReferenceType::Dynamic, anchor_uri_string})}; - const auto reference_type{recursive_anchor == this->locations_.end() - ? SchemaReferenceType::Static - : SchemaReferenceType::Dynamic}; - const sourcemeta::core::URI anchor_uri{anchor_uri_string}; - auto recursive_ref_pointer{common_pointer_weak}; - recursive_ref_pointer.push_back(std::cref(KEYWORD_RECURSIVE_REF)); - const auto [entry_iterator, inserted] = - this->references_.insert_or_assign( - {reference_type, std::move(recursive_ref_pointer)}, - SchemaFrame::Reference{.original = ref, - .destination = anchor_uri.recompose(), - .base = std::string_view{}, - .fragment = std::nullopt}); - set_base_and_fragment(entry_iterator->second); - } - - const auto *dynamic_ref_value{ - entry.common.vocabularies.contains( - SchemaVocabularies::Known::JSON_SCHEMA_2020_12_CORE) - ? entry.common.subschema.get().try_at( - "$dynamicRef"sv, - sourcemeta::core::JSONSCHEMA_HASH_DYNAMIC_REF) - : nullptr}; - if (dynamic_ref_value != nullptr) { - if (!dynamic_ref_value->is_string()) { - std::ostringstream value; - sourcemeta::core::stringify(*dynamic_ref_value, value); - throw sourcemeta::core::SchemaKeywordError( - "Invalid dynamic reference value", "$dynamicRef", value.str()); - } - - const auto &original{dynamic_ref_value->to_string()}; - sourcemeta::core::URI ref; - try { - ref = sourcemeta::core::URI{original}; - } catch (const sourcemeta::core::URIParseError &) { - throw sourcemeta::core::SchemaKeywordError( - "The dynamic reference is not a valid URI", "$dynamicRef", - original); - } - - if (!nearest_bases.first.empty()) { - ref.resolve_from(sourcemeta::core::URI{nearest_bases.first.front()}); - } - - ref.canonicalize(); - canonicalize_pointer_fragment(ref); - auto ref_string{ref.recompose()}; - - // Note that here we cannot enforce the bookending requirement, - // as the dynamic reference may point to a schema resource that - // is not part of or bundled within the schema we are analyzing here. - - const auto has_fragment{ref.fragment().has_value()}; - const auto maybe_static_frame{ - this->locations_.find({SchemaReferenceType::Static, ref_string})}; - const auto maybe_dynamic_frame{ - this->locations_.find({SchemaReferenceType::Dynamic, ref_string})}; - const auto behaves_as_static{ - !has_fragment || (maybe_static_frame != this->locations_.end() && - maybe_dynamic_frame == this->locations_.end())}; - auto dynamic_ref_pointer{common_pointer_weak}; - dynamic_ref_pointer.push_back(std::cref(KEYWORD_DYNAMIC_REF)); - const auto [entry_iterator, inserted] = - this->references_.insert_or_assign( - {behaves_as_static ? SchemaReferenceType::Static - : SchemaReferenceType::Dynamic, - std::move(dynamic_ref_pointer)}, - SchemaFrame::Reference{.original = original, - .destination = std::move(ref_string), - .base = std::string_view{}, - .fragment = std::nullopt}); - set_base_and_fragment(entry_iterator->second); - } + if (!entry.common.subschema.get().is_object()) { + continue; } + + const auto nearest_bases{find_nearest_bases( + base_uris, entry.common.pointer, + entry.id ? std::optional{*entry.id} : std::nullopt)}; + resolve_ref(entry, nearest_bases.first, this->references_); + resolve_recursive_ref(entry, nearest_bases.first, this->locations_, + this->references_); + resolve_dynamic_ref(entry, nearest_bases.first, this->locations_, + this->references_); } // A reference may target a place that the walker never descends into, like @@ -1878,82 +2149,9 @@ SchemaFrame::SchemaFrame(const Mode mode, const sourcemeta::core::JSON &root, // each, which costs an entry per reference rather than one per pointer of // the analysed document if (this->mode_ < SchemaFrame::Mode::Pointers) { - for (const auto &reference : this->references_) { - const auto &fragment{reference.second.fragment}; - if (!fragment.has_value() || !fragment.value().starts_with('/')) { - continue; - } - - if (this->locations_.contains( - {SchemaReferenceType::Static, reference.second.destination})) { - continue; - } - - const auto base_entry{this->locations_.find( - {SchemaReferenceType::Static, - sourcemeta::core::JSON::String{reference.second.base}})}; - if (base_entry == this->locations_.cend()) { - continue; - } - - // The fragment of a reference is URI-encoded, so it has to be decoded - // rather than read as-is, else an escape like `a%20b` would stand for a - // property of that literal name - const auto relative{sourcemeta::core::fragment_to_pointer( - sourcemeta::core::URI{reference.second.destination})}; - if (!relative.has_value()) { - continue; - } - - auto absolute{sourcemeta::core::to_pointer(base_entry->second.pointer) - .concat(relative.value())}; - if (sourcemeta::core::try_get(root, absolute) == nullptr) { - continue; - } - - this->reference_pointers_.push_back(std::move(absolute)); - const auto pointer_weak{ - sourcemeta::core::to_weak_pointer(this->reference_pointers_.back())}; - const auto combined{ - find_dialect_and_all_bases(base_dialects, base_uris, pointer_weak)}; - - std::size_t nearest_base_depth{base_entry->second.pointer.size()}; - std::string_view nearest_base_view{base_entry->first.second}; - for (const auto &candidate : combined.every_base) { - if (candidate.first.empty()) { - continue; - } - - nearest_base_depth = candidate.second.size(); - // Every base a subschema reads against was registered as a resource - // of this frame on the way down - const auto candidate_entry{this->locations_.find( - {SchemaReferenceType::Static, - sourcemeta::core::JSON::String{candidate.first}})}; - assert(candidate_entry != this->locations_.cend()); - nearest_base_view = candidate_entry->first.second; - - break; - } - - // The document states a dialect at its root, which sits above wherever - // this destination landed, so the search above always comes back with - // one - assert(combined.dialect_match.has_value()); - const auto &parent{combined.dialect_match->second}; - // The place above is a schema that the traversal reported, so it is one - // of the subschemas gathered here - const auto parent_subschema{subschemas.find(parent)}; - assert(parent_subschema != subschemas.cend()); - store(this->locations_, max_locations, SchemaReferenceType::Static, - SchemaFrame::LocationType::Pointer, - sourcemeta::core::JSON::String{reference.second.destination}, - nearest_base_view, pointer_weak, nearest_base_depth, - combined.dialect_match->first.get().dialects.front(), - combined.dialect_match->first.get().base_dialect, parent, - parent_subschema->second.property_name, - parent_subschema->second.orphan, true); - } + materialise_reference_locations( + root, base_uris, base_dialects, subschemas, max_locations, + this->locations_, this->references_, this->reference_pointers_); } // A schema is standalone if all references can be resolved within itself, @@ -2002,69 +2200,7 @@ SchemaFrame::SchemaFrame(const Mode mode, const sourcemeta::core::JSON &root, // references between schemas. A dialect the document does not carry // contributes no anchor of its own, so it has no say here if (this->cache_->standalone_ignoring_metaschemas) { - // Find all dynamic anchors - // Values are pointers to full URIs in locations_ - std::unordered_map> - dynamic_anchors; - for (const auto &entry : this->locations_) { - if (entry.first.first != SchemaReferenceType::Dynamic) { - continue; - } - - // An anchor is the only thing a dialect lets a dynamic name reach, so it - // is the only kind of location registered under one - assert(entry.second.type == SchemaFrame::LocationType::Anchor); - - const sourcemeta::core::URI anchor_uri{entry.first.second}; - // Copy the fragment to avoid dangling string_view (anchor_uri is local) - const sourcemeta::core::JSON::String fragment{ - anchor_uri.fragment().value_or("")}; - dynamic_anchors[fragment].push_back(&entry.first.second); - } - - // If there is a dynamic reference that only has one possible - // dynamic anchor destination, then that dynamic reference - // is a static reference in disguise - std::vector to_delete; - std::vector to_insert; - for (const auto &reference : this->references_) { - if (reference.first.first != SchemaReferenceType::Dynamic || - !reference.second.fragment.has_value()) { - continue; - } - - const auto match{dynamic_anchors.find( - sourcemeta::core::JSON::String{reference.second.fragment.value()})}; - assert(match != dynamic_anchors.cend()); - // Otherwise we can assume there is only one possible target for the - // dynamic reference - if (match->second.size() != 1) { - continue; - } - - to_delete.push_back(reference.first); - to_insert.emplace_back( - SchemaFrame::References::key_type{SchemaReferenceType::Static, - reference.first.second}, - SchemaFrame::References::mapped_type{ - .original = reference.second.original, - .destination = *match->second.front(), - .base = std::string_view{}, - .fragment = std::nullopt}); - } - - // Because we can't mutate a map as we are traversing it - - for (const auto &key : to_delete) { - this->references_.erase(key); - } - - for (auto &&entry : to_insert) { - const auto [entry_iterator, inserted] = - this->references_.emplace(std::move(entry)); - set_base_and_fragment(entry_iterator->second); - } + resolve_dynamic_anchors(this->locations_, this->references_); } // Only meaningful once the rewrite above has settled, as that is what diff --git a/src/spec/jsonschema/iterator.h b/src/spec/jsonschema/iterator.h index d39090b9e..265753a06 100644 --- a/src/spec/jsonschema/iterator.h +++ b/src/spec/jsonschema/iterator.h @@ -185,6 +185,241 @@ inline auto enqueue(std::vector &children, .property_name = property_name}); } +// What each kind of keyword contributes to the traversal, which is a +// subschema of its own, a map or an array of them, or nothing +template +inline auto +walk_keyword(const sourcemeta::core::SchemaKeywordType type, + const ObjectEntry &pair, + const sourcemeta::core::WeakPointer &pointer, + const std::string_view child_dialect, + const sourcemeta::core::SchemaBaseDialect child_base_dialect, + const std::size_t level, const bool orphan, + const bool property_name, std::vector &children) + -> void { + switch (type) { + case sourcemeta::core::SchemaKeywordType:: + ApplicatorValueTraverseSomeProperty: { + sourcemeta::core::WeakPointer new_pointer{pointer}; + new_pointer.push_back(std::cref(pair.first)); + enqueue(children, pointer, std::move(new_pointer), pair.second, + child_dialect, child_base_dialect, level + 1, orphan, false); + } break; + + case sourcemeta::core::SchemaKeywordType:: + ApplicatorValueTraverseAnyPropertyKey: { + sourcemeta::core::WeakPointer new_pointer{pointer}; + new_pointer.push_back(std::cref(pair.first)); + enqueue(children, pointer, std::move(new_pointer), pair.second, + child_dialect, child_base_dialect, level + 1, orphan, true); + } break; + + case sourcemeta::core::SchemaKeywordType::ApplicatorValueTraverseAnyItem: { + sourcemeta::core::WeakPointer new_pointer{pointer}; + new_pointer.push_back(std::cref(pair.first)); + enqueue(children, pointer, std::move(new_pointer), pair.second, + child_dialect, child_base_dialect, level + 1, orphan, false); + } break; + + case sourcemeta::core::SchemaKeywordType::ApplicatorValueTraverseSomeItem: { + sourcemeta::core::WeakPointer new_pointer{pointer}; + new_pointer.push_back(std::cref(pair.first)); + enqueue(children, pointer, std::move(new_pointer), pair.second, + child_dialect, child_base_dialect, level + 1, orphan, false); + } break; + + case sourcemeta::core::SchemaKeywordType::ApplicatorValueTraverseParent: { + sourcemeta::core::WeakPointer new_pointer{pointer}; + new_pointer.push_back(std::cref(pair.first)); + enqueue(children, pointer, std::move(new_pointer), pair.second, + child_dialect, child_base_dialect, level + 1, orphan, false); + } break; + + case sourcemeta::core::SchemaKeywordType::ApplicatorValueInPlaceOther: { + sourcemeta::core::WeakPointer new_pointer{pointer}; + new_pointer.push_back(std::cref(pair.first)); + enqueue(children, pointer, std::move(new_pointer), pair.second, + child_dialect, child_base_dialect, level + 1, orphan, + property_name); + } break; + + case sourcemeta::core::SchemaKeywordType::ApplicatorValueInPlaceNegate: { + sourcemeta::core::WeakPointer new_pointer{pointer}; + new_pointer.push_back(std::cref(pair.first)); + enqueue(children, pointer, std::move(new_pointer), pair.second, + child_dialect, child_base_dialect, level + 1, orphan, + property_name); + } break; + + case sourcemeta::core::SchemaKeywordType::ApplicatorValueInPlaceMaybe: { + sourcemeta::core::WeakPointer new_pointer{pointer}; + new_pointer.push_back(std::cref(pair.first)); + enqueue(children, pointer, std::move(new_pointer), pair.second, + child_dialect, child_base_dialect, level + 1, orphan, + property_name); + } break; + + case sourcemeta::core::SchemaKeywordType::ApplicatorElementsTraverseItem: + if (pair.second.is_array()) { + for (std::size_t index = 0; index < pair.second.size(); index++) { + sourcemeta::core::WeakPointer new_pointer{pointer}; + new_pointer.push_back(std::cref(pair.first)); + new_pointer.emplace_back(index); + enqueue(children, pointer, std::move(new_pointer), + pair.second.at(index), child_dialect, child_base_dialect, + level + 1, orphan, false); + } + } + + break; + + case sourcemeta::core::SchemaKeywordType::ApplicatorElementsInPlace: + if (pair.second.is_array()) { + for (std::size_t index = 0; index < pair.second.size(); index++) { + sourcemeta::core::WeakPointer new_pointer{pointer}; + new_pointer.push_back(std::cref(pair.first)); + new_pointer.emplace_back(index); + enqueue(children, pointer, std::move(new_pointer), + pair.second.at(index), child_dialect, child_base_dialect, + level + 1, orphan, property_name); + } + } + + break; + + case sourcemeta::core::SchemaKeywordType::ApplicatorElementsInPlaceSome: + if (pair.second.is_array()) { + for (std::size_t index = 0; index < pair.second.size(); index++) { + sourcemeta::core::WeakPointer new_pointer{pointer}; + new_pointer.push_back(std::cref(pair.first)); + new_pointer.emplace_back(index); + enqueue(children, pointer, std::move(new_pointer), + pair.second.at(index), child_dialect, child_base_dialect, + level + 1, orphan, property_name); + } + } + + break; + + case sourcemeta::core::SchemaKeywordType:: + ApplicatorElementsInPlaceSomeNegate: + if (pair.second.is_array()) { + for (std::size_t index = 0; index < pair.second.size(); index++) { + sourcemeta::core::WeakPointer new_pointer{pointer}; + new_pointer.push_back(std::cref(pair.first)); + new_pointer.emplace_back(index); + enqueue(children, pointer, std::move(new_pointer), + pair.second.at(index), child_dialect, child_base_dialect, + level + 1, orphan, property_name); + } + } + + break; + + case sourcemeta::core::SchemaKeywordType:: + ApplicatorMembersTraversePropertyStatic: + if (pair.second.is_object()) { + for (const auto &subpair : pair.second.as_object()) { + sourcemeta::core::WeakPointer new_pointer{pointer}; + new_pointer.push_back(std::cref(pair.first)); + new_pointer.push_back(std::cref(subpair.first)); + enqueue(children, pointer, std::move(new_pointer), subpair.second, + child_dialect, child_base_dialect, level + 1, orphan, false); + } + } + + break; + + case sourcemeta::core::SchemaKeywordType:: + ApplicatorMembersTraversePropertyRegex: + if (pair.second.is_object()) { + for (const auto &subpair : pair.second.as_object()) { + sourcemeta::core::WeakPointer new_pointer{pointer}; + new_pointer.push_back(std::cref(pair.first)); + new_pointer.push_back(std::cref(subpair.first)); + enqueue(children, pointer, std::move(new_pointer), subpair.second, + child_dialect, child_base_dialect, level + 1, orphan, false); + } + } + + break; + + case sourcemeta::core::SchemaKeywordType::ApplicatorMembersInPlaceSome: + if (pair.second.is_object()) { + for (const auto &subpair : pair.second.as_object()) { + sourcemeta::core::WeakPointer new_pointer{pointer}; + new_pointer.push_back(std::cref(pair.first)); + new_pointer.push_back(std::cref(subpair.first)); + enqueue(children, pointer, std::move(new_pointer), subpair.second, + child_dialect, child_base_dialect, level + 1, orphan, + property_name); + } + } + + break; + + case sourcemeta::core::SchemaKeywordType::LocationMembers: + if (pair.second.is_object()) { + for (const auto &subpair : pair.second.as_object()) { + sourcemeta::core::WeakPointer new_pointer{pointer}; + new_pointer.push_back(std::cref(pair.first)); + new_pointer.push_back(std::cref(subpair.first)); + enqueue(children, pointer, std::move(new_pointer), subpair.second, + child_dialect, child_base_dialect, level + 1, true, false); + } + } + + break; + + case sourcemeta::core::SchemaKeywordType:: + ApplicatorValueOrElementsTraverseAnyItemOrItem: + if (pair.second.is_array()) { + for (std::size_t index = 0; index < pair.second.size(); index++) { + sourcemeta::core::WeakPointer new_pointer{pointer}; + new_pointer.push_back(std::cref(pair.first)); + new_pointer.emplace_back(index); + enqueue(children, pointer, std::move(new_pointer), + pair.second.at(index), child_dialect, child_base_dialect, + level + 1, orphan, false); + } + } else { + sourcemeta::core::WeakPointer new_pointer{pointer}; + new_pointer.push_back(std::cref(pair.first)); + enqueue(children, pointer, std::move(new_pointer), pair.second, + child_dialect, child_base_dialect, level + 1, orphan, false); + } + + break; + + case sourcemeta::core::SchemaKeywordType::ApplicatorValueOrElementsInPlace: + if (pair.second.is_array()) { + for (std::size_t index = 0; index < pair.second.size(); index++) { + sourcemeta::core::WeakPointer new_pointer{pointer}; + new_pointer.push_back(std::cref(pair.first)); + new_pointer.emplace_back(index); + enqueue(children, pointer, std::move(new_pointer), + pair.second.at(index), child_dialect, child_base_dialect, + level + 1, orphan, property_name); + } + } else { + sourcemeta::core::WeakPointer new_pointer{pointer}; + new_pointer.push_back(std::cref(pair.first)); + enqueue(children, pointer, std::move(new_pointer), pair.second, + child_dialect, child_base_dialect, level + 1, orphan, + property_name); + } + + break; + case sourcemeta::core::SchemaKeywordType::Assertion: + case sourcemeta::core::SchemaKeywordType::Annotation: + case sourcemeta::core::SchemaKeywordType::Reference: + case sourcemeta::core::SchemaKeywordType::Other: + case sourcemeta::core::SchemaKeywordType::Comment: + case sourcemeta::core::SchemaKeywordType::Unknown: + break; + } +} + // Traversal is driven by an explicit work stack rather than recursion, so that // framing a deeply nested schema is bounded by the heap instead of the call // stack @@ -316,237 +551,8 @@ walk(const std::optional &root_parent, continue; } - switch (keyword_info.type) { - case sourcemeta::core::SchemaKeywordType:: - ApplicatorValueTraverseSomeProperty: { - sourcemeta::core::WeakPointer new_pointer{pointer}; - new_pointer.push_back(std::cref(pair.first)); - enqueue(children, pointer, std::move(new_pointer), pair.second, - child_dialect, child_base_dialect, level + 1, orphan, false); - } break; - - case sourcemeta::core::SchemaKeywordType:: - ApplicatorValueTraverseAnyPropertyKey: { - sourcemeta::core::WeakPointer new_pointer{pointer}; - new_pointer.push_back(std::cref(pair.first)); - enqueue(children, pointer, std::move(new_pointer), pair.second, - child_dialect, child_base_dialect, level + 1, orphan, true); - } break; - - case sourcemeta::core::SchemaKeywordType:: - ApplicatorValueTraverseAnyItem: { - sourcemeta::core::WeakPointer new_pointer{pointer}; - new_pointer.push_back(std::cref(pair.first)); - enqueue(children, pointer, std::move(new_pointer), pair.second, - child_dialect, child_base_dialect, level + 1, orphan, false); - } break; - - case sourcemeta::core::SchemaKeywordType:: - ApplicatorValueTraverseSomeItem: { - sourcemeta::core::WeakPointer new_pointer{pointer}; - new_pointer.push_back(std::cref(pair.first)); - enqueue(children, pointer, std::move(new_pointer), pair.second, - child_dialect, child_base_dialect, level + 1, orphan, false); - } break; - - case sourcemeta::core::SchemaKeywordType:: - ApplicatorValueTraverseParent: { - sourcemeta::core::WeakPointer new_pointer{pointer}; - new_pointer.push_back(std::cref(pair.first)); - enqueue(children, pointer, std::move(new_pointer), pair.second, - child_dialect, child_base_dialect, level + 1, orphan, false); - } break; - - case sourcemeta::core::SchemaKeywordType::ApplicatorValueInPlaceOther: { - sourcemeta::core::WeakPointer new_pointer{pointer}; - new_pointer.push_back(std::cref(pair.first)); - enqueue(children, pointer, std::move(new_pointer), pair.second, - child_dialect, child_base_dialect, level + 1, orphan, - property_name); - } break; - - case sourcemeta::core::SchemaKeywordType:: - ApplicatorValueInPlaceNegate: { - sourcemeta::core::WeakPointer new_pointer{pointer}; - new_pointer.push_back(std::cref(pair.first)); - enqueue(children, pointer, std::move(new_pointer), pair.second, - child_dialect, child_base_dialect, level + 1, orphan, - property_name); - } break; - - case sourcemeta::core::SchemaKeywordType::ApplicatorValueInPlaceMaybe: { - sourcemeta::core::WeakPointer new_pointer{pointer}; - new_pointer.push_back(std::cref(pair.first)); - enqueue(children, pointer, std::move(new_pointer), pair.second, - child_dialect, child_base_dialect, level + 1, orphan, - property_name); - } break; - - case sourcemeta::core::SchemaKeywordType:: - ApplicatorElementsTraverseItem: - if (pair.second.is_array()) { - for (std::size_t index = 0; index < pair.second.size(); index++) { - sourcemeta::core::WeakPointer new_pointer{pointer}; - new_pointer.push_back(std::cref(pair.first)); - new_pointer.emplace_back(index); - enqueue(children, pointer, std::move(new_pointer), - pair.second.at(index), child_dialect, child_base_dialect, - level + 1, orphan, false); - } - } - - break; - - case sourcemeta::core::SchemaKeywordType::ApplicatorElementsInPlace: - if (pair.second.is_array()) { - for (std::size_t index = 0; index < pair.second.size(); index++) { - sourcemeta::core::WeakPointer new_pointer{pointer}; - new_pointer.push_back(std::cref(pair.first)); - new_pointer.emplace_back(index); - enqueue(children, pointer, std::move(new_pointer), - pair.second.at(index), child_dialect, child_base_dialect, - level + 1, orphan, property_name); - } - } - - break; - - case sourcemeta::core::SchemaKeywordType::ApplicatorElementsInPlaceSome: - if (pair.second.is_array()) { - for (std::size_t index = 0; index < pair.second.size(); index++) { - sourcemeta::core::WeakPointer new_pointer{pointer}; - new_pointer.push_back(std::cref(pair.first)); - new_pointer.emplace_back(index); - enqueue(children, pointer, std::move(new_pointer), - pair.second.at(index), child_dialect, child_base_dialect, - level + 1, orphan, property_name); - } - } - - break; - - case sourcemeta::core::SchemaKeywordType:: - ApplicatorElementsInPlaceSomeNegate: - if (pair.second.is_array()) { - for (std::size_t index = 0; index < pair.second.size(); index++) { - sourcemeta::core::WeakPointer new_pointer{pointer}; - new_pointer.push_back(std::cref(pair.first)); - new_pointer.emplace_back(index); - enqueue(children, pointer, std::move(new_pointer), - pair.second.at(index), child_dialect, child_base_dialect, - level + 1, orphan, property_name); - } - } - - break; - - case sourcemeta::core::SchemaKeywordType:: - ApplicatorMembersTraversePropertyStatic: - if (pair.second.is_object()) { - for (const auto &subpair : pair.second.as_object()) { - sourcemeta::core::WeakPointer new_pointer{pointer}; - new_pointer.push_back(std::cref(pair.first)); - new_pointer.push_back(std::cref(subpair.first)); - enqueue(children, pointer, std::move(new_pointer), subpair.second, - child_dialect, child_base_dialect, level + 1, orphan, - false); - } - } - - break; - - case sourcemeta::core::SchemaKeywordType:: - ApplicatorMembersTraversePropertyRegex: - if (pair.second.is_object()) { - for (const auto &subpair : pair.second.as_object()) { - sourcemeta::core::WeakPointer new_pointer{pointer}; - new_pointer.push_back(std::cref(pair.first)); - new_pointer.push_back(std::cref(subpair.first)); - enqueue(children, pointer, std::move(new_pointer), subpair.second, - child_dialect, child_base_dialect, level + 1, orphan, - false); - } - } - - break; - - case sourcemeta::core::SchemaKeywordType::ApplicatorMembersInPlaceSome: - if (pair.second.is_object()) { - for (const auto &subpair : pair.second.as_object()) { - sourcemeta::core::WeakPointer new_pointer{pointer}; - new_pointer.push_back(std::cref(pair.first)); - new_pointer.push_back(std::cref(subpair.first)); - enqueue(children, pointer, std::move(new_pointer), subpair.second, - child_dialect, child_base_dialect, level + 1, orphan, - property_name); - } - } - - break; - - case sourcemeta::core::SchemaKeywordType::LocationMembers: - if (pair.second.is_object()) { - for (const auto &subpair : pair.second.as_object()) { - sourcemeta::core::WeakPointer new_pointer{pointer}; - new_pointer.push_back(std::cref(pair.first)); - new_pointer.push_back(std::cref(subpair.first)); - enqueue(children, pointer, std::move(new_pointer), subpair.second, - child_dialect, child_base_dialect, level + 1, true, - false); - } - } - - break; - - case sourcemeta::core::SchemaKeywordType:: - ApplicatorValueOrElementsTraverseAnyItemOrItem: - if (pair.second.is_array()) { - for (std::size_t index = 0; index < pair.second.size(); index++) { - sourcemeta::core::WeakPointer new_pointer{pointer}; - new_pointer.push_back(std::cref(pair.first)); - new_pointer.emplace_back(index); - enqueue(children, pointer, std::move(new_pointer), - pair.second.at(index), child_dialect, child_base_dialect, - level + 1, orphan, false); - } - } else { - sourcemeta::core::WeakPointer new_pointer{pointer}; - new_pointer.push_back(std::cref(pair.first)); - enqueue(children, pointer, std::move(new_pointer), pair.second, - child_dialect, child_base_dialect, level + 1, orphan, - false); - } - - break; - - case sourcemeta::core::SchemaKeywordType:: - ApplicatorValueOrElementsInPlace: - if (pair.second.is_array()) { - for (std::size_t index = 0; index < pair.second.size(); index++) { - sourcemeta::core::WeakPointer new_pointer{pointer}; - new_pointer.push_back(std::cref(pair.first)); - new_pointer.emplace_back(index); - enqueue(children, pointer, std::move(new_pointer), - pair.second.at(index), child_dialect, child_base_dialect, - level + 1, orphan, property_name); - } - } else { - sourcemeta::core::WeakPointer new_pointer{pointer}; - new_pointer.push_back(std::cref(pair.first)); - enqueue(children, pointer, std::move(new_pointer), pair.second, - child_dialect, child_base_dialect, level + 1, orphan, - property_name); - } - - break; - case sourcemeta::core::SchemaKeywordType::Assertion: - case sourcemeta::core::SchemaKeywordType::Annotation: - case sourcemeta::core::SchemaKeywordType::Reference: - case sourcemeta::core::SchemaKeywordType::Other: - case sourcemeta::core::SchemaKeywordType::Comment: - case sourcemeta::core::SchemaKeywordType::Unknown: - break; - } + walk_keyword(keyword_info.type, pair, pointer, child_dialect, + child_base_dialect, level, orphan, property_name, children); } // Push in reverse so that the first child is popped first, which keeps the diff --git a/src/spec/openapi/bundle.cc b/src/spec/openapi/bundle.cc index f95dc83b6..5bd37e302 100644 --- a/src/spec/openapi/bundle.cc +++ b/src/spec/openapi/bundle.cc @@ -2053,6 +2053,409 @@ auto adopt_mappings( return changed; } +// One reference the description does not already answer: what it names, +// which document carries it, and where that lands once gathered in +template +auto expand_openapi_reference( + const Reference &reference, JSON &document, const SchemaWalker &walker, + const SchemaResolver &schema_resolver, const OpenAPIResolver &resolver, + const OpenAPIBundleOptions &options, std::uint64_t &remaining, + const Walk &walk, const JSON::String &base, + std::map &documents, + std::map &bundled, OpenAPIInlined &inlined, + std::set &unavailable, + std::map> &identifiers, + std::map> &deferred, + std::map &walks, const OpenAPIWalk &names, + bool &changed) -> void { + // Only the shell knows which documents an OpenAPI Description spans. A + // Schema Object naming something this does not reach is left exactly as + // it was written, for whatever reads inside one to resolve + const auto names_a_schema{reference.expected == OpenAPIObjectKind::Schema}; + + // Where a reference leads before the document holding it has been read, + // which is all a fragment shaped like a pointer ever needs + const auto pointed{target_of(reference.destination)}; + // Which document it leads to, if it names one at all + const auto holder{openapi_document_uri(reference.destination)}; + + // What another document's Schema Object declares for itself is a name + // for a place of that document, so a reference naming one is a reference + // into it rather than one to go looking for a document of that name. + // + // Whatever the description can reach as a document answers ahead of + // that, as 3.2.1 Section 4.1.1 has a reference name a document by the URI + // that document answers to, and a Schema Object is free to declare an + // identifier that collides with one. So this is asked where a fragment + // names no place to begin with, and otherwise only once the document has + // turned out not to be one + std::optional> declared; + if (names_a_schema && + (!pointed.has_value() || unavailable.contains(holder))) { + declared = declared_target(identifiers, reference.destination); + } + + const auto initial{declared.has_value() + ? std::optional{declared.value().second} + : pointed}; + // A fragment shaped like anything else names an identifier or an anchor + // rather than a place, and which document declares one is only settled + // by framing the documents the description spans. 3.2.1 Section 4.1.2 + // leaves none of those to be given up on before that has happened, so a + // reference of this shape goes on to have its document read rather than + // being left here + const URI destination{reference.destination}; + assert(!destination.fragment().has_value() || + !destination.fragment().value().empty()); + const auto names_an_anchor{names_a_schema && !initial.has_value() && + destination.fragment().has_value()}; + + if (!initial.has_value() && !names_an_anchor) { + if (names_a_schema) { + if (reference.mapping) { + deferred[reference.destination].push_back(reference); + } + + return; + } + + // OpenAPI Specification 3.2.1, Section 4.30 admits "the URI of a + // Security Scheme Object" as a name, and Section 4.1.2 puts "either an + // OpenAPI Object or a Schema Object at the root" of every document a + // description spans, so a name reaching for a whole document reaches + // no scheme whatever that document turns out to hold. Settling that + // from the name alone is what keeps a name nobody wrote as a document + // from being reported as a document that could not be fetched + if (reference.requirement) { + throw OpenAPIReferenceError{ + "This security requirement must name a Security Scheme Object " + "within the document it points at", + base, reference.origin, reference.destination}; + } + + // Everything else goes on to have its document read, so that a + // reference landing on something that is no OpenAPI Description at all + // hears that rather than hearing about the place it did not name. + // Naming no place is the lesser of the two complaints, as a document + // of the wrong shape holds no place worth naming either + } + + const auto identifier{declared.has_value() ? declared.value().first : holder}; + + if (names_a_schema && !declared.has_value() && + unavailable.contains(identifier)) { + // A mapping whose schema has already been brought in still names the + // URI that schema was fetched by, and a revision that gives an + // embedded Schema Object no way of keeping that URI leaves nothing in + // the result answering to it. Leaving it here would hand back a + // description that does not hold what it names, so it goes on to be + // pointed at where that schema landed instead. + // + // A reference of a Schema Object wants nothing of that, as bringing + // the schemas of a description in is what settles where it leads, and + // it settles it the same way however many positions name one schema + if (reference.mapping) { + deferred[reference.destination].push_back(reference); + } + + return; + } + + if (!documents.contains(identifier)) { + auto resolved{resolver(identifier)}; + if (!resolved.has_value()) { + if (names_a_schema) { + unavailable.insert(identifier); + if (reference.mapping) { + deferred[reference.destination].push_back(reference); + } + + return; + } + + throw OpenAPIResolutionError{ + "Could not resolve the reference to an external document", base, + reference.origin, identifier}; + } + + auto candidate{std::move(resolved).to_owned()}; + // OpenAPI Specification 3.2.1, Section 4.1.2: "all documents in an + // OAD MUST have either an OpenAPI Object or a Schema Object at the + // root, and MUST be parsed as complete documents". A Schema Object at + // the root is what a Schema Object reference may name, and that + // document is one a JSON Schema implementation reads rather than this. + // + // Only 3.2 carries that sentence. No release of 3.1 or of 3.0 does, + // and 3.0 reads the other way: its Reference Object offers + // `definitions.json#/Pet` as a worked example, and its Structural + // Interoperability section admits a reference target "with the Object + // type matching the reference source's context". So holding an earlier + // revision to it narrows what that revision allows, and is a choice + // this makes rather than a rule it follows. + // + // What makes the choice is that nothing else tells a document of a + // description from any other JSON document. Section 4.1 marks + // `openapi` "REQUIRED", and it is the only member a document carries + // that says what the document is: every Object this specification + // defines is an ordinary JSON object, and most of them are open to a + // member nobody expected, so there is no shape to recognise either. A + // reader handed a document without that field has nothing to decide + // by, and reading one as whichever kind a reference happened to expect + // is what Appendix G leaves undefined: "If the same JSON/YAML object + // is parsed multiple times and the respective contexts require it to + // be parsed as different Object types, the resulting behavior is + // implementation defined, and MAY be treated as an error if detected". + // + // So the rule the latest revision writes down is the one every + // revision is held to here. It costs a description that splits itself + // into bare Objects, which the earlier revisions permit, and it buys + // whatever reads what this produces a document that says what it is + if (!openapi_has_version_field(candidate)) { + if (names_a_schema) { + unavailable.insert(identifier); + // Section 4.1.2 puts "either an OpenAPI Object or a Schema Object + // at the root" of a document of a description, and a mapping names + // the second of those, so one reaching a document that holds no + // description has reached a schema that is there to be brought in. + // Which resolver a caller answers for such a document with is the + // caller's business rather than this one's + if (reference.mapping) { + deferred[reference.destination].push_back(reference); + } + + return; + } + + throw OpenAPIReferenceError{"This reference must name a document " + "that holds an OpenAPI Description", + base, reference.origin, identifier}; + } + + // Nothing in the specification asks for this. It says what a + // description may span and says nothing of the revisions the documents + // it spans declare, so turning one of these down is a choice this + // makes rather than a rule it follows. + // + // What makes the choice is where bundling ends. Section 4.1 has one + // document declare one revision, so everything the result holds has to + // be what that one revision can express, and there is no revision to + // pick that can express both. A 3.2 document holds fields that 3.1 has + // no way of spelling, and 3.2.1 Section 2.1 leaves no room to assume + // the other direction is safe either: "Occasionally, non-backwards + // compatible changes may be made in `minor` versions of the OAS where + // impact is believed to be low relative to the benefit provided". So + // the choice is between turning such a description down and handing + // back a document that says it is one revision while holding what + // another one means. + // + // What the patch component says is no part of this, as 3.2.1 + // Section 2.1 makes a revision the `major`.`minor` pair alone, + // which 3.1.1 says the same of under Section 4.1 + const auto revision{openapi_version(candidate)}; + if (revision.has_value() && revision.value() != walk.version) { + throw OpenAPIReferenceError{ + "This reference must name a document of the same OpenAPI " + "Specification revision", + base, reference.origin, identifier}; + } + + // The walk keeps a view into the document it read, so the document + // takes its place before anything walks it + const auto &held{ + documents.emplace(identifier, std::move(candidate)).first->second}; + auto analysis{openapi_analyse(held, identifier, remaining, &names)}; + charge(remaining, analysis.locations.size()); + const auto &recorded{ + walks.emplace(identifier, std::move(analysis)).first->second}; + index_schemas(held, recorded, identifier, walker, schema_resolver, + identifiers, remaining); + } + + // A fragment shaped like anything but a pointer names an identifier or + // an anchor rather than a place, which only framing the document that + // declares it settles. 3.2.1 Section 4.1.2 leaves none of those to be + // given up on before that document has been read, so this is asked again + // now that it has been. A fragment that is a pointer already named a + // place of the document just read, and nothing another document declares + // for itself is to take that place from it + if (names_a_schema && !declared.has_value() && !pointed.has_value()) { + declared = declared_target(identifiers, reference.destination); + } + + // A document that holds an OpenAPI Description is never what a reference + // from the shell expects to find, so one naming a whole document has + // landed on the wrong kind of thing. This is where such a reference is + // turned down, once that document has been read and has turned out to + // hold a description of the revision this one spans. A fragment shaped + // like anything but a pointer names no place of it either, and reaches + // here the same way + const auto target{declared.has_value() + ? std::optional{declared.value().second} + : target_of(reference.destination)}; + if (!target.has_value()) { + // A mapping is the one name here that a schema of its own may answer + // for, as what it reaches is resolved for schemas rather than by the + // shell, so it goes on to be told where that schema landed. Every + // other name, a reference of a Schema Object among them, has landed + // on a document that holds no place answering to it + if (reference.mapping) { + deferred[reference.destination].push_back(reference); + return; + } + + // Section 4.3.1 asks for "a requirement to parse complete documents + // before deeming a Schema Object reference to be unresolvable", and + // reading the whole of the document this names is what meets it: every + // place of it is settled, its Schema Objects among them, and a Schema + // Object of some document still unread that claimed the URI this one + // answers to would be claiming a whole document rather than declaring + // the place this names + throw OpenAPIReferenceError{"This reference must name a place within " + "the document it points at", + base, reference.origin, reference.destination}; + } + + const auto &remote_document{documents.at(identifier)}; + const auto &remote{walks.at(identifier)}; + // Spelled as the document that holds it spells it, before anything + // compares it against what the walk of that document recorded + const auto spelled{retype(remote_document, target.value())}; + // What a reference names is held to the kind the position it sits in + // expects, however many references reach the Object that holds it. A + // second one that named nothing would otherwise be written out as a + // place the result does not hold + if (!lands(remote, remote.base, spelled, reference.expected)) { + throw OpenAPIReferenceError{ + "This reference must name an Object of the kind that the " + "position it sits in expects", + base, reference.origin, reference.destination}; + } + + // An Operation Object is the one kind the Components Object has no home + // for, so what gets embedded is the Path Item Object holding it and the + // reference goes on reaching its operation through that + const auto names_an_operation{reference.expected == + OpenAPIObjectKind::Operation}; + const auto origin{promote(names_an_operation ? path_item_of(remote, spelled) + : names_a_schema ? schema_of(remote, spelled) + : spelled)}; + + // Where a document was retrieved from is how a resolver is asked for it, + // and what it answers to is its own to say. OpenAPI Specification 3.2.1, + // Section 4.1.1 lets a document declare the latter and requires the two + // to be told apart: "references MUST use the target document's `$self` + // URI if the `$self` field is present". So every place of it is named by + // the base its own analysis settled on rather than by where it was found + const auto key{openapi_location_uri(remote.base, origin)}; + + // Before 3.1 the Components Object holds no Path Item Object, so one of + // those has nowhere to be moved to and is written into the Object that + // referenced it instead. Section 4.3.3 keeps the Paths Object of the + // entry document the only thing that "contributes URLs to the described + // API", so putting it there is no alternative: that would describe an + // endpoint the description never exposed + if (reference.expected == OpenAPIObjectKind::PathItem && + !openapi_components_hold_path_items(walk.version)) { + const auto host{reference.origin.initial()}; + // Keyed the way every other map in this file keys a place, by what the + // document answers for it rather than by the pointer on its own + const auto within{openapi_location_uri(base, host)}; + if (!inlined[within].insert(key).second) { + throw OpenAPIError{ + "The Path Item Object references must not form a cycle", base, + reference.origin}; + } + + inline_path_item(document, remote_document, remote, origin, host, key, base, + walk.dialect, walker, schema_resolver, options, remaining); + changed = true; + return; + } + + // And an Operation Object of another document is reached through a Path + // Item Object that there is likewise nowhere to put, which leaves + // nothing to reach it through + if (names_an_operation && !openapi_components_hold_path_items(walk.version)) { + throw OpenAPIReferenceError{ + "This revision has nowhere to hold the Path Item Object that " + "holds the operation this reference names", + base, reference.origin, reference.destination}; + } + + const auto container{container_of(origin, names_an_operation + ? OpenAPIObjectKind::PathItem + : reference.expected)}; + // Every kind that a reference position expects has a home of its own + // once an Operation Object is reached through the Path Item holding it + assert(!container.empty()); + + if (!bundled.contains(key)) { + bundled.emplace(key, adopt(document, remote_document, remote, origin, + container, key, base, walk.dialect, walker, + schema_resolver, options, remaining)); + } + + // The reference is rewritten as a fragment of the document it now sits + // in, rather than as the URI that document answers to, so that bundling + // leaves behind an output that keeps working wherever it is moved to + const auto landed{spelled.rebase(origin, bundled.at(key))}; + + // What a Security Requirement Object names is the member the scopes sit + // under, so what makes it whole is renaming that member to whatever the + // scheme is called once it sits here, which carries the scopes across + // untouched. 3.2.1 Section 4.30 then reads the result as a component name + // rather than as a URI: "Property names that are identical to a + // component name under the Components Object MUST be treated as a + // component name", and the name was taken free of that Object for it + if (reference.requirement) { + auto &requirement{get(document, reference.origin.initial())}; + const auto &member{reference.origin.back().to_property()}; + JSON::String name{landed.back().to_property()}; + const auto *taken{requirement.try_at(name)}; + if (taken != nullptr && *taken != requirement.at(member)) { + throw OpenAPIError{"A Security Requirement Object that names one " + "security scheme twice over cannot keep a list of " + "scopes for each of them", + base, reference.origin}; + } + + requirement.rename(member, std::move(name)); + changed = true; + return; + } + + // A reference that resolves against the document it sits in is written + // as a fragment of it, which is what keeps what bundling produces + // working wherever it is moved to. One that resolves against something + // else, which is a Schema Object that declares an identifier of its own, + // would name a place within that identifier instead, so it cannot be + // written that way + if (reference.scope == base) { + set(document, reference.origin, JSON{to_uri(landed).recompose()}); + changed = true; + return; + } + + // What such a reference names instead is what the schema it leads to + // says of itself, wherever that schema says anything. JSON Schema + // Section 9.3.1 has a reference to an embedded resource "resolve to a + // schema using the `$id` of an embedded Schema Resource", and an + // identifier holds wherever the description ends up while a place in a + // document does not. Only a schema that declares none leaves the + // document itself as the sole way to name where it leads + const auto *reached{try_get(document, landed)}; + assert(reached != nullptr); + // Section 4.8.24 lets a Schema Object be a boolean, which declares + // nothing of itself, so one of those leaves the document holding it as + // the only way to name where this leads just as a schema that declares + // no identifier does + const auto *identity{reached->is_object() ? reached->try_at("$id") : nullptr}; + assert(identity == nullptr || identity->is_string()); + set(document, reference.origin, + identity != nullptr ? JSON{identity->to_string()} + : JSON{openapi_location_uri(base, landed)}); + changed = true; +} auto bundle_internal(JSON &document, const SchemaWalker &walker, const SchemaResolver &schema_resolver, const OpenAPIResolver &resolver, @@ -2130,400 +2533,10 @@ auto bundle_internal(JSON &document, const SchemaWalker &walker, bool changed{false}; for (const auto &reference : unresolved) { - // Only the shell knows which documents an OpenAPI Description spans. A - // Schema Object naming something this does not reach is left exactly as - // it was written, for whatever reads inside one to resolve - const auto names_a_schema{reference.expected == - OpenAPIObjectKind::Schema}; - - // Where a reference leads before the document holding it has been read, - // which is all a fragment shaped like a pointer ever needs - const auto pointed{target_of(reference.destination)}; - // Which document it leads to, if it names one at all - const auto holder{openapi_document_uri(reference.destination)}; - - // What another document's Schema Object declares for itself is a name - // for a place of that document, so a reference naming one is a reference - // into it rather than one to go looking for a document of that name. - // - // Whatever the description can reach as a document answers ahead of - // that, as 3.2.1 Section 4.1.1 has a reference name a document by the URI - // that document answers to, and a Schema Object is free to declare an - // identifier that collides with one. So this is asked where a fragment - // names no place to begin with, and otherwise only once the document has - // turned out not to be one - std::optional> declared; - if (names_a_schema && - (!pointed.has_value() || unavailable.contains(holder))) { - declared = declared_target(identifiers, reference.destination); - } - - const auto initial{declared.has_value() - ? std::optional{declared.value().second} - : pointed}; - // A fragment shaped like anything else names an identifier or an anchor - // rather than a place, and which document declares one is only settled - // by framing the documents the description spans. 3.2.1 Section 4.1.2 - // leaves none of those to be given up on before that has happened, so a - // reference of this shape goes on to have its document read rather than - // being left here - const URI destination{reference.destination}; - assert(!destination.fragment().has_value() || - !destination.fragment().value().empty()); - const auto names_an_anchor{names_a_schema && !initial.has_value() && - destination.fragment().has_value()}; - - if (!initial.has_value() && !names_an_anchor) { - if (names_a_schema) { - if (reference.mapping) { - deferred[reference.destination].push_back(reference); - } - - continue; - } - - // OpenAPI Specification 3.2.1, Section 4.30 admits "the URI of a - // Security Scheme Object" as a name, and Section 4.1.2 puts "either an - // OpenAPI Object or a Schema Object at the root" of every document a - // description spans, so a name reaching for a whole document reaches - // no scheme whatever that document turns out to hold. Settling that - // from the name alone is what keeps a name nobody wrote as a document - // from being reported as a document that could not be fetched - if (reference.requirement) { - throw OpenAPIReferenceError{ - "This security requirement must name a Security Scheme Object " - "within the document it points at", - base, reference.origin, reference.destination}; - } - - // Everything else goes on to have its document read, so that a - // reference landing on something that is no OpenAPI Description at all - // hears that rather than hearing about the place it did not name. - // Naming no place is the lesser of the two complaints, as a document - // of the wrong shape holds no place worth naming either - } - - const auto identifier{declared.has_value() ? declared.value().first - : holder}; - - if (names_a_schema && !declared.has_value() && - unavailable.contains(identifier)) { - // A mapping whose schema has already been brought in still names the - // URI that schema was fetched by, and a revision that gives an - // embedded Schema Object no way of keeping that URI leaves nothing in - // the result answering to it. Leaving it here would hand back a - // description that does not hold what it names, so it goes on to be - // pointed at where that schema landed instead. - // - // A reference of a Schema Object wants nothing of that, as bringing - // the schemas of a description in is what settles where it leads, and - // it settles it the same way however many positions name one schema - if (reference.mapping) { - deferred[reference.destination].push_back(reference); - } - - continue; - } - - if (!documents.contains(identifier)) { - auto resolved{resolver(identifier)}; - if (!resolved.has_value()) { - if (names_a_schema) { - unavailable.insert(identifier); - if (reference.mapping) { - deferred[reference.destination].push_back(reference); - } - - continue; - } - - throw OpenAPIResolutionError{ - "Could not resolve the reference to an external document", base, - reference.origin, identifier}; - } - - auto candidate{std::move(resolved).to_owned()}; - // OpenAPI Specification 3.2.1, Section 4.1.2: "all documents in an - // OAD MUST have either an OpenAPI Object or a Schema Object at the - // root, and MUST be parsed as complete documents". A Schema Object at - // the root is what a Schema Object reference may name, and that - // document is one a JSON Schema implementation reads rather than this. - // - // Only 3.2 carries that sentence. No release of 3.1 or of 3.0 does, - // and 3.0 reads the other way: its Reference Object offers - // `definitions.json#/Pet` as a worked example, and its Structural - // Interoperability section admits a reference target "with the Object - // type matching the reference source's context". So holding an earlier - // revision to it narrows what that revision allows, and is a choice - // this makes rather than a rule it follows. - // - // What makes the choice is that nothing else tells a document of a - // description from any other JSON document. Section 4.1 marks - // `openapi` "REQUIRED", and it is the only member a document carries - // that says what the document is: every Object this specification - // defines is an ordinary JSON object, and most of them are open to a - // member nobody expected, so there is no shape to recognise either. A - // reader handed a document without that field has nothing to decide - // by, and reading one as whichever kind a reference happened to expect - // is what Appendix G leaves undefined: "If the same JSON/YAML object - // is parsed multiple times and the respective contexts require it to - // be parsed as different Object types, the resulting behavior is - // implementation defined, and MAY be treated as an error if detected". - // - // So the rule the latest revision writes down is the one every - // revision is held to here. It costs a description that splits itself - // into bare Objects, which the earlier revisions permit, and it buys - // whatever reads what this produces a document that says what it is - if (!openapi_has_version_field(candidate)) { - if (names_a_schema) { - unavailable.insert(identifier); - // Section 4.1.2 puts "either an OpenAPI Object or a Schema Object - // at the root" of a document of a description, and a mapping names - // the second of those, so one reaching a document that holds no - // description has reached a schema that is there to be brought in. - // Which resolver a caller answers for such a document with is the - // caller's business rather than this one's - if (reference.mapping) { - deferred[reference.destination].push_back(reference); - } - - continue; - } - - throw OpenAPIReferenceError{"This reference must name a document " - "that holds an OpenAPI Description", - base, reference.origin, identifier}; - } - - // Nothing in the specification asks for this. It says what a - // description may span and says nothing of the revisions the documents - // it spans declare, so turning one of these down is a choice this - // makes rather than a rule it follows. - // - // What makes the choice is where bundling ends. Section 4.1 has one - // document declare one revision, so everything the result holds has to - // be what that one revision can express, and there is no revision to - // pick that can express both. A 3.2 document holds fields that 3.1 has - // no way of spelling, and 3.2.1 Section 2.1 leaves no room to assume - // the other direction is safe either: "Occasionally, non-backwards - // compatible changes may be made in `minor` versions of the OAS where - // impact is believed to be low relative to the benefit provided". So - // the choice is between turning such a description down and handing - // back a document that says it is one revision while holding what - // another one means. - // - // What the patch component says is no part of this, as 3.2.1 - // Section 2.1 makes a revision the `major`.`minor` pair alone, - // which 3.1.1 says the same of under Section 4.1 - const auto revision{openapi_version(candidate)}; - if (revision.has_value() && revision.value() != walk.version) { - throw OpenAPIReferenceError{ - "This reference must name a document of the same OpenAPI " - "Specification revision", - base, reference.origin, identifier}; - } - - // The walk keeps a view into the document it read, so the document - // takes its place before anything walks it - const auto &held{ - documents.emplace(identifier, std::move(candidate)).first->second}; - auto analysis{openapi_analyse(held, identifier, remaining, &names)}; - charge(remaining, analysis.locations.size()); - const auto &recorded{ - walks.emplace(identifier, std::move(analysis)).first->second}; - index_schemas(held, recorded, identifier, walker, schema_resolver, - identifiers, remaining); - } - - // A fragment shaped like anything but a pointer names an identifier or - // an anchor rather than a place, which only framing the document that - // declares it settles. 3.2.1 Section 4.1.2 leaves none of those to be - // given up on before that document has been read, so this is asked again - // now that it has been. A fragment that is a pointer already named a - // place of the document just read, and nothing another document declares - // for itself is to take that place from it - if (names_a_schema && !declared.has_value() && !pointed.has_value()) { - declared = declared_target(identifiers, reference.destination); - } - - // A document that holds an OpenAPI Description is never what a reference - // from the shell expects to find, so one naming a whole document has - // landed on the wrong kind of thing. This is where such a reference is - // turned down, once that document has been read and has turned out to - // hold a description of the revision this one spans. A fragment shaped - // like anything but a pointer names no place of it either, and reaches - // here the same way - const auto target{declared.has_value() - ? std::optional{declared.value().second} - : target_of(reference.destination)}; - if (!target.has_value()) { - // A mapping is the one name here that a schema of its own may answer - // for, as what it reaches is resolved for schemas rather than by the - // shell, so it goes on to be told where that schema landed. Every - // other name, a reference of a Schema Object among them, has landed - // on a document that holds no place answering to it - if (reference.mapping) { - deferred[reference.destination].push_back(reference); - continue; - } - - // Section 4.3.1 asks for "a requirement to parse complete documents - // before deeming a Schema Object reference to be unresolvable", and - // reading the whole of the document this names is what meets it: every - // place of it is settled, its Schema Objects among them, and a Schema - // Object of some document still unread that claimed the URI this one - // answers to would be claiming a whole document rather than declaring - // the place this names - throw OpenAPIReferenceError{"This reference must name a place within " - "the document it points at", - base, reference.origin, - reference.destination}; - } - - const auto &remote_document{documents.at(identifier)}; - const auto &remote{walks.at(identifier)}; - // Spelled as the document that holds it spells it, before anything - // compares it against what the walk of that document recorded - const auto spelled{retype(remote_document, target.value())}; - // What a reference names is held to the kind the position it sits in - // expects, however many references reach the Object that holds it. A - // second one that named nothing would otherwise be written out as a - // place the result does not hold - if (!lands(remote, remote.base, spelled, reference.expected)) { - throw OpenAPIReferenceError{ - "This reference must name an Object of the kind that the " - "position it sits in expects", - base, reference.origin, reference.destination}; - } - - // An Operation Object is the one kind the Components Object has no home - // for, so what gets embedded is the Path Item Object holding it and the - // reference goes on reaching its operation through that - const auto names_an_operation{reference.expected == - OpenAPIObjectKind::Operation}; - const auto origin{promote(names_an_operation - ? path_item_of(remote, spelled) - : names_a_schema ? schema_of(remote, spelled) - : spelled)}; - - // Where a document was retrieved from is how a resolver is asked for it, - // and what it answers to is its own to say. OpenAPI Specification 3.2.1, - // Section 4.1.1 lets a document declare the latter and requires the two - // to be told apart: "references MUST use the target document's `$self` - // URI if the `$self` field is present". So every place of it is named by - // the base its own analysis settled on rather than by where it was found - const auto key{openapi_location_uri(remote.base, origin)}; - - // Before 3.1 the Components Object holds no Path Item Object, so one of - // those has nowhere to be moved to and is written into the Object that - // referenced it instead. Section 4.3.3 keeps the Paths Object of the - // entry document the only thing that "contributes URLs to the described - // API", so putting it there is no alternative: that would describe an - // endpoint the description never exposed - if (reference.expected == OpenAPIObjectKind::PathItem && - !openapi_components_hold_path_items(walk.version)) { - const auto host{reference.origin.initial()}; - // Keyed the way every other map in this file keys a place, by what the - // document answers for it rather than by the pointer on its own - const auto within{openapi_location_uri(base, host)}; - if (!inlined[within].insert(key).second) { - throw OpenAPIError{ - "The Path Item Object references must not form a cycle", base, - reference.origin}; - } - - inline_path_item(document, remote_document, remote, origin, host, key, - base, walk.dialect, walker, schema_resolver, options, - remaining); - changed = true; - continue; - } - - // And an Operation Object of another document is reached through a Path - // Item Object that there is likewise nowhere to put, which leaves - // nothing to reach it through - if (names_an_operation && - !openapi_components_hold_path_items(walk.version)) { - throw OpenAPIReferenceError{ - "This revision has nowhere to hold the Path Item Object that " - "holds the operation this reference names", - base, reference.origin, reference.destination}; - } - - const auto container{ - container_of(origin, names_an_operation ? OpenAPIObjectKind::PathItem - : reference.expected)}; - // Every kind that a reference position expects has a home of its own - // once an Operation Object is reached through the Path Item holding it - assert(!container.empty()); - - if (!bundled.contains(key)) { - bundled.emplace(key, adopt(document, remote_document, remote, origin, - container, key, base, walk.dialect, walker, - schema_resolver, options, remaining)); - } - - // The reference is rewritten as a fragment of the document it now sits - // in, rather than as the URI that document answers to, so that bundling - // leaves behind an output that keeps working wherever it is moved to - const auto landed{spelled.rebase(origin, bundled.at(key))}; - - // What a Security Requirement Object names is the member the scopes sit - // under, so what makes it whole is renaming that member to whatever the - // scheme is called once it sits here, which carries the scopes across - // untouched. 3.2.1 Section 4.30 then reads the result as a component name - // rather than as a URI: "Property names that are identical to a - // component name under the Components Object MUST be treated as a - // component name", and the name was taken free of that Object for it - if (reference.requirement) { - auto &requirement{get(document, reference.origin.initial())}; - const auto &member{reference.origin.back().to_property()}; - JSON::String name{landed.back().to_property()}; - const auto *taken{requirement.try_at(name)}; - if (taken != nullptr && *taken != requirement.at(member)) { - throw OpenAPIError{"A Security Requirement Object that names one " - "security scheme twice over cannot keep a list of " - "scopes for each of them", - base, reference.origin}; - } - - requirement.rename(member, std::move(name)); - changed = true; - continue; - } - - // A reference that resolves against the document it sits in is written - // as a fragment of it, which is what keeps what bundling produces - // working wherever it is moved to. One that resolves against something - // else, which is a Schema Object that declares an identifier of its own, - // would name a place within that identifier instead, so it cannot be - // written that way - if (reference.scope == base) { - set(document, reference.origin, JSON{to_uri(landed).recompose()}); - changed = true; - continue; - } - - // What such a reference names instead is what the schema it leads to - // says of itself, wherever that schema says anything. JSON Schema - // Section 9.3.1 has a reference to an embedded resource "resolve to a - // schema using the `$id` of an embedded Schema Resource", and an - // identifier holds wherever the description ends up while a place in a - // document does not. Only a schema that declares none leaves the - // document itself as the sole way to name where it leads - const auto *reached{try_get(document, landed)}; - assert(reached != nullptr); - // Section 4.8.24 lets a Schema Object be a boolean, which declares - // nothing of itself, so one of those leaves the document holding it as - // the only way to name where this leads just as a schema that declares - // no identifier does - const auto *identity{reached->is_object() ? reached->try_at("$id") - : nullptr}; - assert(identity == nullptr || identity->is_string()); - set(document, reference.origin, - identity != nullptr ? JSON{identity->to_string()} - : JSON{openapi_location_uri(base, landed)}); - changed = true; + expand_openapi_reference(reference, document, walker, schema_resolver, + resolver, options, remaining, walk, base, + documents, bundled, inlined, unavailable, + identifiers, deferred, walks, names, changed); } // A pass that leaves the document as it found it is one that has nothing diff --git a/src/spec/regex/permissive.h b/src/spec/regex/permissive.h index ecadb823f..b54ade7e9 100644 --- a/src/spec/regex/permissive.h +++ b/src/spec/regex/permissive.h @@ -706,6 +706,81 @@ inline auto exceeds_class_depth(const std::string &pattern) -> bool { return false; } +// A group opener, which this dialect allows only in the forms the +// specification names (RFC 9485 Section 3) +inline auto check_group_opener(const std::string &pattern, + const std::size_t position, bool &ecma_valid) + -> void { + // (*...) backtracking control verbs + if (pattern[position + 1] == '*') { + ecma_valid = false; + } + // (?X...): ECMA only allows (?: (?= (?! (?<= (? + if (pattern[position + 1] == '?' && position + 2 < pattern.size()) { + const char third = pattern[position + 2]; + bool valid_extension{third == ':' || third == '=' || third == '!'}; + if (!valid_extension && third == '<' && position + 3 < pattern.size()) { + const char fourth = pattern[position + 3]; + valid_extension = + fourth == '=' || fourth == '!' || (fourth >= 'a' && fourth <= 'z') || + (fourth >= 'A' && fourth <= 'Z') || fourth == '_' || fourth == '$'; + } + if (!valid_extension) { + ecma_valid = false; + } + } +} +// A `\uXXXX` escape, which this dialect spells as `\x{XXXX}`. Answers +// whether it consumed the escape (RFC 9485 Section 3) +inline auto translate_unicode_escape(const std::string &pattern, + std::size_t &position, std::string &result) + -> bool { + if (pattern[position + 2] == '{') { + result += "\\x{"; + for (position += 3; position < pattern.size() && pattern[position] != '}'; + ++position) { + result += pattern[position]; + } + + if (position < pattern.size()) { + result += '}'; + } + + return true; + } + + if (position + 5 < pattern.size() && all_hex(pattern, position + 2, 4)) { + result += "\\x{" + pattern.substr(position + 2, 4) + '}'; + position += 5; + return true; + } + + return false; +} + +// A `\p{...}` or `\P{...}` property escape (RFC 9485 Section 3) +inline auto translate_property_escape(const std::string &pattern, + std::size_t &position, const char current, + const char next, std::string &result) + -> void { + const auto start = position; + std::string name; + for (position += 3; position < pattern.size() && pattern[position] != '}'; + ++position) { + name += pattern[position]; + } + + if (position < pattern.size()) { + if (auto translated = translate_property(name, next == 'P')) { + result += *translated; + } else { + result += pattern.substr(start, position - start + 1); + } + } else { + position = start; + result += current; + } +} inline auto translate_permissive(const std::string &pattern) -> PermissiveResult { if (exceeds_class_depth(pattern)) { @@ -723,25 +798,7 @@ inline auto translate_permissive(const std::string &pattern) // PCRE-only group constructs that are not part of ECMA-262 if (current == '(' && !is_escaped(pattern, position) && !in_class && position + 1 < pattern.size()) { - // (*...) backtracking control verbs - if (pattern[position + 1] == '*') { - ecma_valid = false; - } - // (?X...): ECMA only allows (?: (?= (?! (?<= (? - if (pattern[position + 1] == '?' && position + 2 < pattern.size()) { - const char third = pattern[position + 2]; - bool valid_extension{third == ':' || third == '=' || third == '!'}; - if (!valid_extension && third == '<' && position + 3 < pattern.size()) { - const char fourth = pattern[position + 3]; - valid_extension = fourth == '=' || fourth == '!' || - (fourth >= 'a' && fourth <= 'z') || - (fourth >= 'A' && fourth <= 'Z') || fourth == '_' || - fourth == '$'; - } - if (!valid_extension) { - ecma_valid = false; - } - } + check_group_opener(pattern, position, ecma_valid); } // PCRE-only possessive quantifiers: *+ ++ ?+ {n,m}+ @@ -831,24 +888,7 @@ inline auto translate_permissive(const std::string &pattern) } if (next == 'u' && position + 2 < pattern.size()) { - if (pattern[position + 2] == '{') { - result += "\\x{"; - for (position += 3; - position < pattern.size() && pattern[position] != '}'; - ++position) { - result += pattern[position]; - } - - if (position < pattern.size()) { - result += '}'; - } - - continue; - } - - if (position + 5 < pattern.size() && all_hex(pattern, position + 2, 4)) { - result += "\\x{" + pattern.substr(position + 2, 4) + '}'; - position += 5; + if (translate_unicode_escape(pattern, position, result)) { continue; } } @@ -873,24 +913,7 @@ inline auto translate_permissive(const std::string &pattern) if ((next == 'p' || next == 'P') && position + 2 < pattern.size() && pattern[position + 2] == '{') { - const auto start = position; - std::string name; - for (position += 3; position < pattern.size() && pattern[position] != '}'; - ++position) { - name += pattern[position]; - } - - if (position < pattern.size()) { - if (auto translated = translate_property(name, next == 'P')) { - result += *translated; - } else { - result += pattern.substr(start, position - start + 1); - } - } else { - position = start; - result += current; - } - + translate_property_escape(pattern, position, current, next, result); continue; } diff --git a/src/spec/uritemplate/uritemplate_router.cc b/src/spec/uritemplate/uritemplate_router.cc index 1040436f1..137824575 100644 --- a/src/spec/uritemplate/uritemplate_router.cc +++ b/src/spec/uritemplate/uritemplate_router.cc @@ -178,6 +178,147 @@ inline auto finalize_match(const Node &otherwise, return {identifier, context}; } +// A variable expression of a template, which becomes a node that captures +// rather than one that matches literal text. Answers whether the scan +// carries on (RFC 6570 Section 2.2) +auto add_variable_expression( + sourcemeta::core::URITemplateRouter::Node &root, + sourcemeta::core::URITemplateRouter::Node *¤t, const char *&position, + const char *const end, bool &absorbed) -> bool { + const char *expression_start = position; + const char *expression_end = find_expression_end(position, end); + std::string_view expression{ + expression_start, + static_cast(expression_end - expression_start)}; + + ++position; + + if (position >= end) { + throw URITemplateRouterInvalidSegmentError{"Unclosed brace", expression}; + } + + NodeType type = NodeType::Variable; + bool path_segment_operator = false; + if (is_operator(*position)) { + if (*position == '+') { + type = NodeType::Expansion; + } else if (*position == '/') { + path_segment_operator = true; + } else { + throw URITemplateRouterInvalidSegmentError{ + "Unsupported URI Template operator", expression}; + } + + ++position; + if (position >= end || *position == '}') { + throw URITemplateRouterInvalidSegmentError{"Empty variable name", + expression}; + } + } else if (is_reserved_operator(*position)) { + throw URITemplateRouterInvalidSegmentError{"Reserved URI Template operator", + expression}; + } else if (*position == '{') { + throw URITemplateRouterInvalidSegmentError{ + "Nested opening brace", extract_segment(expression_start, end)}; + } else if (*position == ' ') { + throw URITemplateRouterInvalidSegmentError{"Space before variable name", + expression}; + } else if (*position == '}') { + throw URITemplateRouterInvalidSegmentError{"Empty variable name", + expression}; + } + + const char *varname_start = position; + while (position < end && *position != '}' && *position != ' ' && + !is_modifier(*position) && *position != ',') { + if (!is_varname_char(*position)) { + throw URITemplateRouterInvalidSegmentError{ + "Invalid character in variable name", expression}; + } + ++position; + } + + if (position >= end) { + throw URITemplateRouterInvalidSegmentError{"Unclosed brace", expression}; + } + + const char *const varname_end = position; + + if (*position == ' ') { + throw URITemplateRouterInvalidSegmentError{"Space in variable expression", + expression}; + } + + if (*position == ':') { + throw URITemplateRouterInvalidSegmentError{"Prefix modifier not supported", + expression}; + } + + if (*position == '*') { + if (!path_segment_operator) { + throw URITemplateRouterInvalidSegmentError{ + "Explode modifier not supported", expression}; + } + if (varname_end == varname_start) { + throw URITemplateRouterInvalidSegmentError{"Empty variable name", + expression}; + } + type = NodeType::OptionalExpansion; + ++position; + if (position >= end || *position != '}') { + throw URITemplateRouterInvalidSegmentError{ + "Unexpected characters after explode modifier", expression}; + } + } else if (path_segment_operator) { + throw URITemplateRouterInvalidSegmentError{ + "Path-segment expansion without the explode modifier is not " + "supported", + expression}; + } + + if (*position == ',') { + throw URITemplateRouterInvalidSegmentError{ + "Multiple variables not supported", expression}; + } + + const std::string_view varname{ + varname_start, static_cast(varname_end - varname_start)}; + + ++position; + + const bool followed_by_path_operator = position < end && *position == '{' && + position + 1 < end && + *(position + 1) == '/'; + + if (position < end && *position != '/' && !followed_by_path_operator) { + throw URITemplateRouterInvalidSegmentError{ + "Path segment cannot mix literals and variables", + extract_segment(expression_start, end)}; + } + + if (is_expansion_type(type) && position < end) { + throw URITemplateRouterInvalidSegmentError{ + "Expansion operator must be the last segment", expression}; + } + + auto &variable = (current != nullptr) ? current->variable : root.variable; + auto *result = + find_or_create_variable_child(variable, varname, type, expression); + if (result == nullptr) { + absorbed = true; + } else { + current = result; + } + + if (absorbed || position >= end) { + return false; + } + if (followed_by_path_operator) { + return true; + } + ++position; + return true; +} } // namespace URITemplateRouter::URITemplateRouter(const std::string_view base_path, @@ -411,141 +552,11 @@ auto URITemplateRouter::add(const std::string_view uri_template, } if (*position == '{') { - const char *expression_start = position; - const char *expression_end = find_expression_end(position, end); - std::string_view expression{ - expression_start, - static_cast(expression_end - expression_start)}; - - ++position; - - if (position >= end) { - throw URITemplateRouterInvalidSegmentError{"Unclosed brace", - expression}; - } - - NodeType type = NodeType::Variable; - bool path_segment_operator = false; - if (is_operator(*position)) { - if (*position == '+') { - type = NodeType::Expansion; - } else if (*position == '/') { - path_segment_operator = true; - } else { - throw URITemplateRouterInvalidSegmentError{ - "Unsupported URI Template operator", expression}; - } - - ++position; - if (position >= end || *position == '}') { - throw URITemplateRouterInvalidSegmentError{"Empty variable name", - expression}; - } - } else if (is_reserved_operator(*position)) { - throw URITemplateRouterInvalidSegmentError{ - "Reserved URI Template operator", expression}; - } else if (*position == '{') { - throw URITemplateRouterInvalidSegmentError{ - "Nested opening brace", extract_segment(expression_start, end)}; - } else if (*position == ' ') { - throw URITemplateRouterInvalidSegmentError{"Space before variable name", - expression}; - } else if (*position == '}') { - throw URITemplateRouterInvalidSegmentError{"Empty variable name", - expression}; - } - - const char *varname_start = position; - while (position < end && *position != '}' && *position != ' ' && - !is_modifier(*position) && *position != ',') { - if (!is_varname_char(*position)) { - throw URITemplateRouterInvalidSegmentError{ - "Invalid character in variable name", expression}; - } - ++position; - } - - if (position >= end) { - throw URITemplateRouterInvalidSegmentError{"Unclosed brace", - expression}; - } - - const char *const varname_end = position; - - if (*position == ' ') { - throw URITemplateRouterInvalidSegmentError{ - "Space in variable expression", expression}; - } - - if (*position == ':') { - throw URITemplateRouterInvalidSegmentError{ - "Prefix modifier not supported", expression}; - } - - if (*position == '*') { - if (!path_segment_operator) { - throw URITemplateRouterInvalidSegmentError{ - "Explode modifier not supported", expression}; - } - if (varname_end == varname_start) { - throw URITemplateRouterInvalidSegmentError{"Empty variable name", - expression}; - } - type = NodeType::OptionalExpansion; - ++position; - if (position >= end || *position != '}') { - throw URITemplateRouterInvalidSegmentError{ - "Unexpected characters after explode modifier", expression}; - } - } else if (path_segment_operator) { - throw URITemplateRouterInvalidSegmentError{ - "Path-segment expansion without the explode modifier is not " - "supported", - expression}; - } - - if (*position == ',') { - throw URITemplateRouterInvalidSegmentError{ - "Multiple variables not supported", expression}; - } - - const std::string_view varname{ - varname_start, static_cast(varname_end - varname_start)}; - - ++position; - - const bool followed_by_path_operator = - position < end && *position == '{' && position + 1 < end && - *(position + 1) == '/'; - - if (position < end && *position != '/' && !followed_by_path_operator) { - throw URITemplateRouterInvalidSegmentError{ - "Path segment cannot mix literals and variables", - extract_segment(expression_start, end)}; - } - - if (is_expansion_type(type) && position < end) { - throw URITemplateRouterInvalidSegmentError{ - "Expansion operator must be the last segment", expression}; - } - - auto &variable = - (current != nullptr) ? current->variable : this->root_.variable; - auto *result = - find_or_create_variable_child(variable, varname, type, expression); - if (result == nullptr) { - absorbed = true; - } else { - current = result; - } - - if (absorbed || position >= end) { + if (!add_variable_expression(this->root_, current, position, end, + absorbed)) { break; } - if (followed_by_path_operator) { - continue; - } - ++position; + continue; } diff --git a/src/spec/yaml/lexer.h b/src/spec/yaml/lexer.h index 987c54098..296481c52 100644 --- a/src/spec/yaml/lexer.h +++ b/src/spec/yaml/lexer.h @@ -1238,6 +1238,169 @@ class Lexer { return content_indent; } + // One line of a block scalar's content, answering whether the scan + // carries on past it (YAML 1.2.2 Section 8.1) + auto scan_block_scalar_line(const ScalarStyle style, + const std::size_t content_indent, + std::string &buffer, std::string *const original, + std::string &original_trailing, + std::string &trailing_newlines, + std::size_t &blank_line_count, + bool &had_line_break, + bool &previous_was_more_indented, + bool &previous_started_with_whitespace) -> bool { + std::size_t line_indent{0}; + while (this->position_ < this->input_.size() && this->peek() == ' ') { + line_indent++; + this->advance(1); + } + + // YAML 1.2.2 Section 6.1: the white space of an empty block scalar line + // is indentation, which is made of spaces, so a tab before any space, + // leaving the line otherwise blank, is invalid indentation + if (line_indent == 0 && this->peek() == '\t') { + auto lookahead{this->position_}; + while ( + lookahead < this->input_.size() && + (this->input_[lookahead] == ' ' || this->input_[lookahead] == '\t')) { + lookahead++; + } + if (lookahead >= this->input_.size() || this->input_[lookahead] == '\n' || + this->input_[lookahead] == '\r') [[unlikely]] { + throw YAMLParseError{"Tab characters cannot be used for indentation", + this->line_, this->column_}; + } + } + + // A line that holds only white space, whether it ends with a line break + // or the end of input, is empty. YAML 1.2.2 Section 8.1.1.1 treats the + // spaces beyond the content indentation of such a line as content + const bool blank_line_at_input_end{this->position_ >= this->input_.size()}; + if (this->peek() == '\n' || this->peek() == '\r' || + blank_line_at_input_end) { + if (style == ScalarStyle::Literal) { + if (line_indent > content_indent) { + buffer += trailing_newlines; + trailing_newlines.clear(); + for (std::size_t index = content_indent; index < line_indent; + ++index) { + buffer += ' '; + } + } + trailing_newlines += '\n'; + } else { + blank_line_count++; + if (original != nullptr) { + if (line_indent > content_indent) { + *original += original_trailing; + original_trailing.clear(); + for (std::size_t index = content_indent; index < line_indent; + ++index) { + *original += ' '; + } + } + original_trailing += '\n'; + } + } + if (blank_line_at_input_end) { + return false; + } + this->advance(1); + if (this->input_[this->position_ - 1] == '\r' && this->peek() == '\n') { + this->advance(1); + } + return true; + } + + if (line_indent < content_indent) { + for (std::size_t index = 0; index < line_indent; ++index) { + this->position_--; + this->column_--; + } + return false; + } + + // YAML 1.2.2 production 206 forbids a document marker from standing at + // the start of a line of the bare document, and the marker is only one + // where white space or the end of input follows it, so a line that + // merely begins with those three characters is content + if (line_indent == 0 && (this->check_document_marker('-') || + this->check_document_marker('.'))) { + return false; + } + + if (style == ScalarStyle::Literal) { + buffer += trailing_newlines; + trailing_newlines.clear(); + } else { + const bool starts_with_whitespace{this->peek() == '\t'}; + if (had_line_break) { + const bool preserve_line_break{ + previous_was_more_indented || previous_started_with_whitespace || + line_indent > content_indent || starts_with_whitespace}; + if (blank_line_count == 0 && !preserve_line_break) { + buffer += ' '; + } else { + if (preserve_line_break) { + buffer += '\n'; + } + for (std::size_t count = 0; count < blank_line_count; ++count) { + buffer += '\n'; + } + } + } else if (blank_line_count > 0) { + for (std::size_t count = 0; count < blank_line_count; ++count) { + buffer += '\n'; + } + } + blank_line_count = 0; + had_line_break = false; + previous_started_with_whitespace = starts_with_whitespace; + + if (original != nullptr) { + *original += original_trailing; + original_trailing.clear(); + } + } + + for (std::size_t index = content_indent; index < line_indent; ++index) { + buffer += ' '; + if (original != nullptr) { + *original += ' '; + } + } + + while (this->position_ < this->input_.size() && this->peek() != '\n' && + this->peek() != '\r') { + const auto character{this->peek()}; + buffer += character; + if (original != nullptr) { + *original += character; + } + this->advance(1); + } + + if (style == ScalarStyle::Folded) { + previous_was_more_indented = (line_indent > content_indent); + } + + if (this->peek() == '\n' || this->peek() == '\r') { + if (style == ScalarStyle::Literal) { + trailing_newlines += '\n'; + } else { + had_line_break = true; + if (original != nullptr) { + original_trailing += '\n'; + } + } + this->advance(1); + if (this->input_[this->position_ - 1] == '\r' && this->peek() == '\n') { + this->advance(1); + } + } + + return true; + } auto scan_block_scalar(const ScalarStyle style) -> Token { const auto start_line{this->line_}; const auto start_column{this->column_}; @@ -1316,157 +1479,12 @@ class Lexer { std::string trailing_newlines; while (this->position_ < this->input_.size()) { - std::size_t line_indent{0}; - while (this->position_ < this->input_.size() && this->peek() == ' ') { - line_indent++; - this->advance(1); - } - - // YAML 1.2.2 Section 6.1: the white space of an empty block scalar line - // is indentation, which is made of spaces, so a tab before any space, - // leaving the line otherwise blank, is invalid indentation - if (line_indent == 0 && this->peek() == '\t') { - auto lookahead{this->position_}; - while (lookahead < this->input_.size() && - (this->input_[lookahead] == ' ' || - this->input_[lookahead] == '\t')) { - lookahead++; - } - if (lookahead >= this->input_.size() || - this->input_[lookahead] == '\n' || this->input_[lookahead] == '\r') - [[unlikely]] { - throw YAMLParseError{"Tab characters cannot be used for indentation", - this->line_, this->column_}; - } - } - - // A line that holds only white space, whether it ends with a line break - // or the end of input, is empty. YAML 1.2.2 Section 8.1.1.1 treats the - // spaces beyond the content indentation of such a line as content - const bool blank_line_at_input_end{this->position_ >= - this->input_.size()}; - if (this->peek() == '\n' || this->peek() == '\r' || - blank_line_at_input_end) { - if (style == ScalarStyle::Literal) { - if (line_indent > content_indent) { - buffer += trailing_newlines; - trailing_newlines.clear(); - for (std::size_t index = content_indent; index < line_indent; - ++index) { - buffer += ' '; - } - } - trailing_newlines += '\n'; - } else { - blank_line_count++; - if (original != nullptr) { - if (line_indent > content_indent) { - *original += original_trailing; - original_trailing.clear(); - for (std::size_t index = content_indent; index < line_indent; - ++index) { - *original += ' '; - } - } - original_trailing += '\n'; - } - } - if (blank_line_at_input_end) { - break; - } - this->advance(1); - if (this->input_[this->position_ - 1] == '\r' && this->peek() == '\n') { - this->advance(1); - } - continue; - } - - if (line_indent < content_indent) { - for (std::size_t index = 0; index < line_indent; ++index) { - this->position_--; - this->column_--; - } + if (!this->scan_block_scalar_line( + style, content_indent, buffer, original, original_trailing, + trailing_newlines, blank_line_count, had_line_break, + previous_was_more_indented, previous_started_with_whitespace)) { break; } - - // YAML 1.2.2 production 206 forbids a document marker from standing at - // the start of a line of the bare document, and the marker is only one - // where white space or the end of input follows it, so a line that - // merely begins with those three characters is content - if (line_indent == 0 && (this->check_document_marker('-') || - this->check_document_marker('.'))) { - break; - } - - if (style == ScalarStyle::Literal) { - buffer += trailing_newlines; - trailing_newlines.clear(); - } else { - const bool starts_with_whitespace{this->peek() == '\t'}; - if (had_line_break) { - const bool preserve_line_break{ - previous_was_more_indented || previous_started_with_whitespace || - line_indent > content_indent || starts_with_whitespace}; - if (blank_line_count == 0 && !preserve_line_break) { - buffer += ' '; - } else { - if (preserve_line_break) { - buffer += '\n'; - } - for (std::size_t count = 0; count < blank_line_count; ++count) { - buffer += '\n'; - } - } - } else if (blank_line_count > 0) { - for (std::size_t count = 0; count < blank_line_count; ++count) { - buffer += '\n'; - } - } - blank_line_count = 0; - had_line_break = false; - previous_started_with_whitespace = starts_with_whitespace; - - if (original != nullptr) { - *original += original_trailing; - original_trailing.clear(); - } - } - - for (std::size_t index = content_indent; index < line_indent; ++index) { - buffer += ' '; - if (original != nullptr) { - *original += ' '; - } - } - - while (this->position_ < this->input_.size() && this->peek() != '\n' && - this->peek() != '\r') { - const auto character{this->peek()}; - buffer += character; - if (original != nullptr) { - *original += character; - } - this->advance(1); - } - - if (style == ScalarStyle::Folded) { - previous_was_more_indented = (line_indent > content_indent); - } - - if (this->peek() == '\n' || this->peek() == '\r') { - if (style == ScalarStyle::Literal) { - trailing_newlines += '\n'; - } else { - had_line_break = true; - if (original != nullptr) { - original_trailing += '\n'; - } - } - this->advance(1); - if (this->input_[this->position_ - 1] == '\r' && this->peek() == '\n') { - this->advance(1); - } - } } if (chomping == '+') { diff --git a/src/spec/yaml/parser.h b/src/spec/yaml/parser.h index aa6b91c39..23a7dfa35 100644 --- a/src/spec/yaml/parser.h +++ b/src/spec/yaml/parser.h @@ -781,6 +781,161 @@ class Parser { token.line, token.column); } + // The value that a token of each type introduces, written into the + // result the caller is building (YAML 1.2.2 Section 8) + auto parse_value_by_type( + const Token &token, const Token ¤t_token, + const JSON::ParseContext context, const std::size_t index, + const std::string &property, const std::uint64_t key_line, + const std::uint64_t key_column, const std::uint64_t node_start_column, + std::optional &anchor_name, + const std::uint64_t anchor_line, const std::size_t anchor_count, + const std::optional &tag, JSON &result) -> void { + switch (current_token.type) { + case TokenType::Scalar: { + auto next{this->next_token()}; + // YAML 1.2.2 Section 7.4.2: the value of an entry of a flow collection + // is a single node, and a pair carrying no brackets of its own is a + // node only where a flow sequence takes its entries. Leaving the + // indicator unread in that position hands the scalar back on its own, + // which is what lets the caller report the separator the entry is + // really missing + const auto pair_without_brackets_allowed{ + this->lexer_->flow_level() == 0 || + context != JSON::ParseContext::Property}; + // YAML 1.2.2 Section 6.7: "Implicit keys are restricted to a single + // line", so an indicator standing on a later line belongs to a mapping + // further out rather than making this scalar a key of its own. Flow + // context is told the same by the error below, which reports where the + // indicator was read instead of handing it back + const bool indicator_shares_the_key_line{( + this->lexer_->flow_level() > 0 || next.line == current_token.line)}; + if (next.type == TokenType::BlockMappingValue && + pair_without_brackets_allowed && indicator_shares_the_key_line) { + if (current_token.multiline) [[unlikely]] { + throw YAMLParseError{"Multi-line implicit mapping key", + current_token.line, current_token.column}; + } + if (this->lexer_->flow_level() > 0 && next.line != current_token.line) + [[unlikely]] { + throw YAMLParseError{"Implicit key and value indicator on " + "different lines in flow context", + next.line, next.column}; + } + if (this->lexer_->flow_level() == 0 && + context == JSON::ParseContext::Property && + current_token.line == key_line) [[unlikely]] { + throw YAMLParseError{"Implicit mapping key in block value on " + "same line as parent key", + current_token.line, current_token.column}; + } + if (this->lexer_->flow_level() == 0 && + (anchor_name.has_value() || tag.has_value()) && + this->document_start_line_ > 0 && + current_token.line == this->document_start_line_) [[unlikely]] { + throw YAMLParseError{ + "Node properties before implicit mapping key on " + "document start line", + current_token.line, current_token.column}; + } + if (anchor_name.has_value() && anchor_line == current_token.line) { + // The anchor names the resolved key node, so that aliasing it + // yields the very same member name rather than the raw text + this->recording_anchor_ = false; + this->record_anchored_key( + std::string{anchor_name.value()}, + this->resolve_scalar_node(current_token, tag), current_token); + this->current_anchor_callbacks_.clear(); + anchor_name.reset(); + } + result = this->parse_block_mapping_from_first_key( + current_token, context, index, property, key_line, key_column, + node_start_column, tag); + } else { + if (anchor_count > 1) [[unlikely]] { + throw YAMLParseError{"Multiple anchors on a scalar node", + current_token.line, current_token.column}; + } + result = this->parse_scalar(current_token, tag, context, index, + property, key_line, key_column); + this->pending_tokens_.push_back(next); + } + break; + } + case TokenType::MappingStart: + result = this->parse_flow_mapping(current_token, context, index, + property, key_line, key_column); + this->record_collection_style(YAMLRoundTrip::CollectionStyle::Flow); + break; + case TokenType::SequenceStart: + result = this->parse_flow_sequence(current_token, context, index, + property, key_line, key_column); + this->record_collection_style(YAMLRoundTrip::CollectionStyle::Flow); + break; + case TokenType::BlockSequenceEntry: + result = this->parse_block_sequence(current_token, context, index, + property, key_line, key_column); + break; + case TokenType::BlockMappingKey: + case TokenType::BlockMappingValue: + // YAML 1.2.2 production 193 reads node properties standing before a + // value indicator as the implicit key of the entry, which production + // 106 leaves free to hold nothing, so an anchor there names that empty + // node rather than the mapping the entry opens + if (anchor_name.has_value() && + current_token.type == TokenType::BlockMappingValue && + anchor_line == current_token.line) { + this->recording_anchor_ = false; + this->record_anchored_key(std::string{anchor_name.value()}, + empty_node(tag), token); + this->current_anchor_callbacks_.clear(); + anchor_name.reset(); + } + result = + this->parse_block_mapping(current_token, context, index, property, + key_line, key_column, node_start_column); + break; + case TokenType::Alias: { + // Reading the token that follows the alias skips over any comment + // between them, so how far the document had been read is settled here + const auto input_read{this->position()}; + auto next{this->next_token()}; + if (next.type == TokenType::BlockMappingValue) { + const std::string alias_name{current_token.value}; + const auto iterator{this->anchors_.find(alias_name)}; + if (iterator == this->anchors_.end()) [[unlikely]] { + throw YAMLUnknownAnchorError{alias_name, current_token.line, + current_token.column}; + } + const auto key_string{this->json_to_key_string(iterator->second.value, + current_token.line, + current_token.column)}; + Token key_token{current_token}; + key_token.type = TokenType::Scalar; + key_token.value = key_string; + result = this->parse_block_mapping_from_first_key( + key_token, context, index, property, key_line, key_column, + node_start_column, std::nullopt, true); + } else { + if (anchor_name.has_value()) [[unlikely]] { + throw YAMLParseError{"Cannot anchor an alias node", + current_token.line, current_token.column}; + } + result = this->resolve_alias(current_token, context, index, property, + input_read, key_line, key_column); + if (this->roundtrip_ != nullptr) { + this->roundtrip_->aliases[this->pointer_stack_] = + std::string{current_token.value}; + } + this->pending_tokens_.push_back(next); + } + break; + } + default: + throw YAMLParseError{"Unexpected token", current_token.line, + current_token.column}; + } + } auto parse_value(const Token &token, const JSON::ParseContext context, const std::size_t index, const std::string &property, const std::uint64_t key_line = 0, @@ -975,150 +1130,9 @@ class Parser { JSON result{nullptr}; - switch (current_token.type) { - case TokenType::Scalar: { - auto next{this->next_token()}; - // YAML 1.2.2 Section 7.4.2: the value of an entry of a flow collection - // is a single node, and a pair carrying no brackets of its own is a - // node only where a flow sequence takes its entries. Leaving the - // indicator unread in that position hands the scalar back on its own, - // which is what lets the caller report the separator the entry is - // really missing - const auto pair_without_brackets_allowed{ - this->lexer_->flow_level() == 0 || - context != JSON::ParseContext::Property}; - // YAML 1.2.2 Section 6.7: "Implicit keys are restricted to a single - // line", so an indicator standing on a later line belongs to a mapping - // further out rather than making this scalar a key of its own. Flow - // context is told the same by the error below, which reports where the - // indicator was read instead of handing it back - const bool indicator_shares_the_key_line{( - this->lexer_->flow_level() > 0 || next.line == current_token.line)}; - if (next.type == TokenType::BlockMappingValue && - pair_without_brackets_allowed && indicator_shares_the_key_line) { - if (current_token.multiline) [[unlikely]] { - throw YAMLParseError{"Multi-line implicit mapping key", - current_token.line, current_token.column}; - } - if (this->lexer_->flow_level() > 0 && next.line != current_token.line) - [[unlikely]] { - throw YAMLParseError{"Implicit key and value indicator on " - "different lines in flow context", - next.line, next.column}; - } - if (this->lexer_->flow_level() == 0 && - context == JSON::ParseContext::Property && - current_token.line == key_line) [[unlikely]] { - throw YAMLParseError{"Implicit mapping key in block value on " - "same line as parent key", - current_token.line, current_token.column}; - } - if (this->lexer_->flow_level() == 0 && - (anchor_name.has_value() || tag.has_value()) && - this->document_start_line_ > 0 && - current_token.line == this->document_start_line_) [[unlikely]] { - throw YAMLParseError{ - "Node properties before implicit mapping key on " - "document start line", - current_token.line, current_token.column}; - } - if (anchor_name.has_value() && anchor_line == current_token.line) { - // The anchor names the resolved key node, so that aliasing it - // yields the very same member name rather than the raw text - this->recording_anchor_ = false; - this->record_anchored_key( - std::string{anchor_name.value()}, - this->resolve_scalar_node(current_token, tag), current_token); - this->current_anchor_callbacks_.clear(); - anchor_name.reset(); - } - result = this->parse_block_mapping_from_first_key( - current_token, context, index, property, key_line, key_column, - node_start_column, tag); - } else { - if (anchor_count > 1) [[unlikely]] { - throw YAMLParseError{"Multiple anchors on a scalar node", - current_token.line, current_token.column}; - } - result = this->parse_scalar(current_token, tag, context, index, - property, key_line, key_column); - this->pending_tokens_.push_back(next); - } - break; - } - case TokenType::MappingStart: - result = this->parse_flow_mapping(current_token, context, index, - property, key_line, key_column); - this->record_collection_style(YAMLRoundTrip::CollectionStyle::Flow); - break; - case TokenType::SequenceStart: - result = this->parse_flow_sequence(current_token, context, index, - property, key_line, key_column); - this->record_collection_style(YAMLRoundTrip::CollectionStyle::Flow); - break; - case TokenType::BlockSequenceEntry: - result = this->parse_block_sequence(current_token, context, index, - property, key_line, key_column); - break; - case TokenType::BlockMappingKey: - case TokenType::BlockMappingValue: - // YAML 1.2.2 production 193 reads node properties standing before a - // value indicator as the implicit key of the entry, which production - // 106 leaves free to hold nothing, so an anchor there names that empty - // node rather than the mapping the entry opens - if (anchor_name.has_value() && - current_token.type == TokenType::BlockMappingValue && - anchor_line == current_token.line) { - this->recording_anchor_ = false; - this->record_anchored_key(std::string{anchor_name.value()}, - empty_node(tag), token); - this->current_anchor_callbacks_.clear(); - anchor_name.reset(); - } - result = - this->parse_block_mapping(current_token, context, index, property, - key_line, key_column, node_start_column); - break; - case TokenType::Alias: { - // Reading the token that follows the alias skips over any comment - // between them, so how far the document had been read is settled here - const auto input_read{this->position()}; - auto next{this->next_token()}; - if (next.type == TokenType::BlockMappingValue) { - const std::string alias_name{current_token.value}; - const auto iterator{this->anchors_.find(alias_name)}; - if (iterator == this->anchors_.end()) [[unlikely]] { - throw YAMLUnknownAnchorError{alias_name, current_token.line, - current_token.column}; - } - const auto key_string{this->json_to_key_string(iterator->second.value, - current_token.line, - current_token.column)}; - Token key_token{current_token}; - key_token.type = TokenType::Scalar; - key_token.value = key_string; - result = this->parse_block_mapping_from_first_key( - key_token, context, index, property, key_line, key_column, - node_start_column, std::nullopt, true); - } else { - if (anchor_name.has_value()) [[unlikely]] { - throw YAMLParseError{"Cannot anchor an alias node", - current_token.line, current_token.column}; - } - result = this->resolve_alias(current_token, context, index, property, - input_read, key_line, key_column); - if (this->roundtrip_ != nullptr) { - this->roundtrip_->aliases[this->pointer_stack_] = - std::string{current_token.value}; - } - this->pending_tokens_.push_back(next); - } - break; - } - default: - throw YAMLParseError{"Unexpected token", current_token.line, - current_token.column}; - } + this->parse_value_by_type( + token, current_token, context, index, property, key_line, key_column, + node_start_column, anchor_name, anchor_line, anchor_count, tag, result); if (anchor_name.has_value()) { this->recording_anchor_ = false; @@ -2206,6 +2220,143 @@ class Parser { return true; } + // A key the lexer reported as a block mapping key of its own, rather + // than one the caller already had in hand. Answers whether the loop + // that reads keys carries on + auto read_block_mapping_key(const std::uint64_t base_column, JSON &result, + std::unordered_set &seen_keys, + std::string &key, std::uint64_t &key_line, + std::uint64_t &key_column, Token &next) -> bool { + if (next.column != base_column) { + return false; + } + next = this->next_token(); + + // YAML 1.2.2 production 159 writes a key as node properties followed + // by content, so the properties are read before the key they decorate + std::optional explicit_key_anchor; + std::optional explicit_key_tag; + while (next.type == TokenType::Anchor || next.type == TokenType::Tag) { + if (next.type == TokenType::Tag) { + explicit_key_tag = this->resolve_tag(next.value); + } else { + explicit_key_anchor = std::string{next.value}; + } + next = this->next_token(); + } + + // YAML 1.2.2 production 190 reads the key of an explicit entry as a + // node indented further than the mapping, so a key standing at the + // indentation of the mapping itself opens the next entry instead, and + // the entry the indicator opened is left holding an empty key + if (next.column <= base_column && + (next.type == TokenType::Scalar || next.type == TokenType::Alias)) { + key.clear(); + note_implicit_key(seen_keys, key, next); + this->record_empty_key_anchor(explicit_key_anchor, explicit_key_tag, + next); + result.assign(key, JSON{nullptr}); + return true; + } + + if (next.type == TokenType::Alias) { + key = this->resolve_alias_key(next, explicit_key_anchor); + } else if (next.type == TokenType::BlockMappingValue) { + // YAML 1.2.2 production 192 writes an entry as + // `( ns-s-block-map-implicit-key | e-node ) + // c-l-block-map-implicit-value`, so an explicit key with nothing + // after its indicator is the empty node, and the value indicator + // standing here opens the value rather than naming the key + key.clear(); + this->record_empty_key_anchor(explicit_key_anchor, explicit_key_tag, + next); + this->pending_tokens_.push_back(next); + } else if (next.type == TokenType::SequenceStart || + next.type == TokenType::MappingStart || + (next.type == TokenType::BlockSequenceEntry && + next.column >= base_column)) [[unlikely]] { + // RFC 8259 Section 4: an object member name is a string, so a key + // that is itself a collection cannot be represented as JSON, and is + // rejected rather than silently dropped. YAML 1.2.2 production 201 + // reads the block sequence that is the value of a mapping entry one + // indentation level further out than the mapping, so only an entry + // standing before that belongs to whatever encloses the mapping + // rather than naming a key of its own + throw YAMLParseError{"Mapping key cannot be a collection", next.line, + next.column}; + } else if (next.type != TokenType::Scalar) { + // YAML 1.2.2 production 190 writes an explicit key as the indicator + // followed by a node, which production 185 leaves free to be the + // empty node of production 106, and production 189 leaves the value + // of such an entry free to be empty as well, so the indicator on its + // own still opens an entry, with an empty key and no value + key.clear(); + note_implicit_key(seen_keys, key, next); + this->record_empty_key_anchor(explicit_key_anchor, explicit_key_tag, + next); + result.assign(key, JSON{nullptr}); + + // Another indicator standing here opens the next entry + if (next.type == TokenType::BlockMappingKey) { + return true; + } + + return false; + } else { + key = this->resolve_scalar_key(next, explicit_key_tag); + this->record_key_scalar_style(key, next.scalar_style, + next.quoted_original); + this->record_key_anchor(explicit_key_anchor, next, explicit_key_tag); + } + + key_line = next.line; + key_column = next.column; + + if (seen_keys.contains(key)) [[unlikely]] { + throw YAMLDuplicateKeyError{key, next.line, next.column}; + } + seen_keys.insert(key); + + auto colon{this->next_token()}; + // YAML 1.2.2 production 191 writes the value of an explicit entry + // with the indicator standing at the indentation of the mapping, which + // follows a line break, so an indicator beside the key leaves that key + // reading as the compact mapping of production 195, which RFC 8259 + // Section 4 cannot hold as an object member name + if (next.type != TokenType::BlockMappingValue && + colon.type == TokenType::BlockMappingValue && colon.line == next.line) + [[unlikely]] { + throw YAMLParseError{"Mapping key cannot be a collection", next.line, + next.column}; + } + if (colon.type != TokenType::BlockMappingValue) { + result.assign(key, JSON{nullptr}); + this->pending_tokens_.push_back(colon); + next = this->next_token(); + return true; + } + + next = this->next_token(); + if (next.type == TokenType::StreamEnd || + next.type == TokenType::DocumentEnd || + next.type == TokenType::DocumentStart) { + result.assign(key, JSON{nullptr}); + this->pending_tokens_.push_back(next); + return false; + } + if (next.type == TokenType::BlockMappingValue || + next.type == TokenType::BlockMappingKey) { + result.assign(key, JSON{nullptr}); + } else { + this->record_inline_comment_for_key(key, next.line != key_line); + this->lexer_->set_block_indent(static_cast(base_column - 1)); + auto value{this->parse_value(next, JSON::ParseContext::Property, 0, key, + key_line, key_column)}; + result.assign(key, std::move(value)); + next = this->next_token(); + } + return true; + } auto parse_block_mapping_from_first_key( const Token &key_token, const JSON::ParseContext context, const std::size_t index, const std::string &property, @@ -2322,135 +2473,11 @@ class Parser { this->lexer_->set_block_indent(static_cast(base_column - 1)); if (next.type == TokenType::BlockMappingKey) { - if (next.column != base_column) { + if (!this->read_block_mapping_key(base_column, result, seen_keys, key, + key_line, key_column, next)) { break; } - next = this->next_token(); - - // YAML 1.2.2 production 159 writes a key as node properties followed - // by content, so the properties are read before the key they decorate - std::optional explicit_key_anchor; - std::optional explicit_key_tag; - while (next.type == TokenType::Anchor || next.type == TokenType::Tag) { - if (next.type == TokenType::Tag) { - explicit_key_tag = this->resolve_tag(next.value); - } else { - explicit_key_anchor = std::string{next.value}; - } - next = this->next_token(); - } - - // YAML 1.2.2 production 190 reads the key of an explicit entry as a - // node indented further than the mapping, so a key standing at the - // indentation of the mapping itself opens the next entry instead, and - // the entry the indicator opened is left holding an empty key - if (next.column <= base_column && - (next.type == TokenType::Scalar || next.type == TokenType::Alias)) { - key.clear(); - note_implicit_key(seen_keys, key, next); - this->record_empty_key_anchor(explicit_key_anchor, explicit_key_tag, - next); - result.assign(key, JSON{nullptr}); - continue; - } - if (next.type == TokenType::Alias) { - key = this->resolve_alias_key(next, explicit_key_anchor); - } else if (next.type == TokenType::BlockMappingValue) { - // YAML 1.2.2 production 192 writes an entry as - // `( ns-s-block-map-implicit-key | e-node ) - // c-l-block-map-implicit-value`, so an explicit key with nothing - // after its indicator is the empty node, and the value indicator - // standing here opens the value rather than naming the key - key.clear(); - this->record_empty_key_anchor(explicit_key_anchor, explicit_key_tag, - next); - this->pending_tokens_.push_back(next); - } else if (next.type == TokenType::SequenceStart || - next.type == TokenType::MappingStart || - (next.type == TokenType::BlockSequenceEntry && - next.column >= base_column)) [[unlikely]] { - // RFC 8259 Section 4: an object member name is a string, so a key - // that is itself a collection cannot be represented as JSON, and is - // rejected rather than silently dropped. YAML 1.2.2 production 201 - // reads the block sequence that is the value of a mapping entry one - // indentation level further out than the mapping, so only an entry - // standing before that belongs to whatever encloses the mapping - // rather than naming a key of its own - throw YAMLParseError{"Mapping key cannot be a collection", next.line, - next.column}; - } else if (next.type != TokenType::Scalar) { - // YAML 1.2.2 production 190 writes an explicit key as the indicator - // followed by a node, which production 185 leaves free to be the - // empty node of production 106, and production 189 leaves the value - // of such an entry free to be empty as well, so the indicator on its - // own still opens an entry, with an empty key and no value - key.clear(); - note_implicit_key(seen_keys, key, next); - this->record_empty_key_anchor(explicit_key_anchor, explicit_key_tag, - next); - result.assign(key, JSON{nullptr}); - - // Another indicator standing here opens the next entry - if (next.type == TokenType::BlockMappingKey) { - continue; - } - - break; - } else { - key = this->resolve_scalar_key(next, explicit_key_tag); - this->record_key_scalar_style(key, next.scalar_style, - next.quoted_original); - this->record_key_anchor(explicit_key_anchor, next, explicit_key_tag); - } - - key_line = next.line; - key_column = next.column; - - if (seen_keys.contains(key)) [[unlikely]] { - throw YAMLDuplicateKeyError{key, next.line, next.column}; - } - seen_keys.insert(key); - - auto colon{this->next_token()}; - // YAML 1.2.2 production 191 writes the value of an explicit entry - // with the indicator standing at the indentation of the mapping, which - // follows a line break, so an indicator beside the key leaves that key - // reading as the compact mapping of production 195, which RFC 8259 - // Section 4 cannot hold as an object member name - if (next.type != TokenType::BlockMappingValue && - colon.type == TokenType::BlockMappingValue && - colon.line == next.line) [[unlikely]] { - throw YAMLParseError{"Mapping key cannot be a collection", next.line, - next.column}; - } - if (colon.type != TokenType::BlockMappingValue) { - result.assign(key, JSON{nullptr}); - this->pending_tokens_.push_back(colon); - next = this->next_token(); - continue; - } - - next = this->next_token(); - if (next.type == TokenType::StreamEnd || - next.type == TokenType::DocumentEnd || - next.type == TokenType::DocumentStart) { - result.assign(key, JSON{nullptr}); - this->pending_tokens_.push_back(next); - break; - } - if (next.type == TokenType::BlockMappingValue || - next.type == TokenType::BlockMappingKey) { - result.assign(key, JSON{nullptr}); - } else { - this->record_inline_comment_for_key(key, next.line != key_line); - this->lexer_->set_block_indent( - static_cast(base_column - 1)); - auto value{this->parse_value(next, JSON::ParseContext::Property, 0, - key, key_line, key_column)}; - result.assign(key, std::move(value)); - next = this->next_token(); - } continue; }