| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424 |
- #pragma once
- #include <memory>
- #include <type_traits>
- #include <unordered_map>
- #include <vector>
- #include <jvalidate/adapter.h>
- #include <jvalidate/constraint.h>
- #include <jvalidate/detail/anchor.h>
- #include <jvalidate/detail/expect.h>
- #include <jvalidate/detail/on_block_exit.h>
- #include <jvalidate/detail/parser_context.h>
- #include <jvalidate/detail/pointer.h>
- #include <jvalidate/detail/reference.h>
- #include <jvalidate/document_cache.h>
- #include <jvalidate/enum.h>
- #include <jvalidate/forward.h>
- namespace jvalidate::schema {
- class Node {
- private:
- std::string description_;
- std::unique_ptr<adapter::Const const> default_{nullptr};
- detail::Reference uri_;
- bool rejects_all_{false};
- std::optional<schema::Node const *> reference_{};
- std::unordered_map<std::string, std::unique_ptr<constraint::Constraint>> constraints_{};
- std::unordered_map<std::string, std::unique_ptr<constraint::Constraint>> post_constraints_{};
- protected:
- static Version schema_version(std::string_view url);
- static Version schema_version(Adapter auto const & json);
- static Version schema_version(Adapter auto const & json, Version default_version);
- public:
- Node(bool rejects_all = false) : rejects_all_(rejects_all) {}
- template <Adapter A> Node(detail::ParserContext<A> context);
- bool is_pure_reference() const {
- return reference_ && constraints_.empty() && post_constraints_.empty() && not default_;
- }
- bool rejects_all() const { return rejects_all_; }
- std::optional<schema::Node const *> reference_schema() const { return reference_; }
- bool requires_result_context() const { return not post_constraints_.empty(); }
- auto const & constraints() const { return constraints_; }
- auto const & post_constraints() const { return constraints_; }
- adapter::Const const * default_value() const { return default_.get(); }
- private:
- template <Adapter A> detail::OnBlockExit resolve_anchor(detail::ParserContext<A> & context);
- template <Adapter A> bool resolve_reference(detail::ParserContext<A> const & context);
- };
- inline Version Node::schema_version(std::string_view url) {
- static std::map<std::string_view, Version> const g_schema_ids{
- {"http://json-schema.org/draft-04/schema", Version::Draft04},
- {"http://json-schema.org/draft-06/schema", Version::Draft06},
- {"http://json-schema.org/draft-07/schema", Version::Draft07},
- {"http://json-schema.org/draft/2019-09/schema", Version::Draft2019_09},
- {"http://json-schema.org/draft/2020-12/schema", Version::Draft2020_12},
- };
- if (url.ends_with('#')) {
- url.remove_suffix(1);
- }
- auto it = g_schema_ids.find(url);
- EXPECT_T(it != g_schema_ids.end(), std::invalid_argument, url);
- return it->second;
- }
- Version Node::schema_version(Adapter auto const & json) {
- EXPECT(json.type() == adapter::Type::Object);
- EXPECT(json.as_object().contains("$schema"));
- auto const & schema = json.as_object()["$schema"];
- EXPECT(schema.type() == adapter::Type::String);
- return schema_version(schema.as_string());
- }
- Version Node::schema_version(Adapter auto const & json, Version default_version) {
- RETURN_UNLESS(json.type() == adapter::Type::Object, default_version);
- RETURN_UNLESS(json.as_object().contains("$schema"), default_version);
- auto const & schema = json.as_object()["$schema"];
- RETURN_UNLESS(schema.type() == adapter::Type::String, default_version);
- return schema_version(schema.as_string());
- }
- }
- namespace jvalidate {
- class Schema : public schema::Node {
- private:
- friend class schema::Node;
- template <Adapter A> friend class detail::ParserContext;
- struct DynamicRef {
- template <typename F>
- DynamicRef(detail::Reference const & where, F const & reconstruct)
- : where(where), reconstruct(reconstruct) {}
- detail::Reference where;
- std::function<schema::Node const *()> reconstruct;
- };
- private:
- schema::Node accept_{true};
- schema::Node reject_{false};
- std::map<detail::Reference, detail::Reference> anchors_;
- std::map<detail::Anchor, DynamicRef> dynamic_anchors_;
- std::map<detail::Reference, schema::Node> cache_;
- std::map<detail::Reference, schema::Node const *> alias_cache_;
- public:
- /**
- * @brief Construct a new schema. All other constructors of this type may be
- * considered syntactic sugar for this constructor.
- *
- * As such, the true signature of this class's contructor is:
- *
- * Schema(Adapter| JSON
- * [, schema::Version]
- * [, URIResolver<A> | DocumentCache<A> &]
- * [, ConstraintFactory<A> const &])
- *
- * as long as the order of arguments is preserved - the constructor will work
- * no matter which arguments are ignored. The only required argument being
- * the JSON object/Adapter.
- *
- * @param json An adapter to a json object
- *
- * @param version The json-schema draft version that all schemas will prefer
- *
- * @param external An object capable of resolving URIs, and turning them into
- * Adapter objects. Holds a cache and so must be mutable.
- *
- * @param factory An object that manuafactures constraints - allows the user
- * to provide custom extensions or even modify the behavior of existing
- * keywords by overridding the virtual accessor function(s).
- */
- template <Adapter A>
- Schema(A const & json, schema::Version version, DocumentCache<A> & external,
- ConstraintFactory<A> const & factory = {})
- : schema::Node(detail::ParserContext<A>{*this, json, version, factory, external}) {}
- /**
- * @param json An adapter to a json schema
- *
- * @param version The json-schema draft version that all schemas will prefer
- *
- * @param external An object capable of resolving URIs, and turning them into
- * Adapter objects. Holds a cache and so must be mutable. If this constructor
- * is called, then it means that the cache is a one-off object, and will not
- * be reused.
- */
- template <Adapter A, typename... Args>
- Schema(A const & json, schema::Version version, DocumentCache<A> && external, Args &&... args)
- : Schema(json, version, external, std::forward<Args>(args)...) {}
- /**
- * @param json An adapter to a json schema
- *
- * @param version The json-schema draft version that all schemas will prefer
- *
- * @param resolve A function capable of resolving URIs, and storing the
- * contents in a provided concrete JSON object.
- */
- template <Adapter A, typename... Args>
- Schema(A const & json, schema::Version version, URIResolver<A> resolve, Args &&... args)
- : Schema(json, version, DocumentCache<A>(resolve), std::forward<Args>(args)...) {}
- /**
- * @param json An adapter to a json schema
- *
- * @param version The json-schema draft version that all schemas will prefer
- */
- template <Adapter A, Not<DocumentCache<A>>... Args>
- Schema(A const & json, schema::Version version, Args &&... args)
- : Schema(json, version, DocumentCache<A>(), std::forward<Args>(args)...) {}
- /**
- * @param json An adapter to a json schema
- */
- template <Adapter A, Not<schema::Version>... Args>
- explicit Schema(A const & json, Args &&... args)
- : Schema(json, schema_version(json), std::forward<Args>(args)...) {}
- /**
- * @param json Any non-adapter (JSON) object. Will be immedately converted
- * into an Adapter object to allow us to walk through it w/o specialization.
- */
- template <typename JSON, typename... Args>
- explicit Schema(JSON const & json, Args &&... args)
- : Schema(adapter::AdapterFor<JSON const>(json), std::forward<Args>(args)...) {}
- private:
- void anchor(detail::Reference const & anchor, detail::Reference const & from) {
- EXPECT_M(anchors_.try_emplace(anchor.root(), from).second,
- "more than one anchor found for uri " << anchor);
- }
- template <Adapter A>
- void dynamic_anchor(detail::Anchor const & anchor, detail::ParserContext<A> const & context) {
- dynamic_anchors_.try_emplace(anchor, context.where,
- [this, context]() { return fetch_schema(context); });
- }
- void remove_dynamic_anchor(detail::Anchor const & anchor, detail::Reference const & where) {
- if (auto it = dynamic_anchors_.find(anchor);
- it != dynamic_anchors_.end() && it->second.where == where) {
- dynamic_anchors_.erase(it);
- }
- }
- schema::Node const * alias(detail::Reference const & where, schema::Node const * schema) {
- EXPECT_M(alias_cache_.try_emplace(where, schema).second,
- "more than one schema found with uri " << where);
- return schema;
- }
- std::optional<schema::Node const *> from_cache(detail::Reference ref) {
- if (auto it = anchors_.find(ref.root()); it != anchors_.end()) {
- ref = it->second / ref.pointer();
- }
- if (auto it = alias_cache_.find(ref); it != alias_cache_.end()) {
- return it->second;
- }
- return std::nullopt;
- }
- template <Adapter A>
- schema::Node const * resolve(detail::Reference ref, detail::ParserContext<A> const & context) {
- // Special case if the root-level document does not have an $id property
- if (ref == detail::Reference() && ref.anchor() == context.where.anchor()) {
- return this;
- }
- if (std::optional cached = from_cache(ref)) {
- return *cached;
- }
- // SPECIAL RULE: Resolve this URI into the context of the calling URI
- if (ref.uri().scheme().empty()) {
- URI const & relative_to = context.where.uri();
- EXPECT_M(relative_to.resource().rfind('/') != std::string::npos,
- "Relative URIs require that the current context has a resolved URI");
- ref = detail::Reference(relative_to.parent() / ref.uri(), ref.anchor(), ref.pointer());
- }
- EXPECT_M(context.external, "Unable to resolve external reference(s) without a URIResolver");
- std::optional schema = context.external.try_load(ref.uri());
- EXPECT_M(schema.has_value(), "URIResolver could not resolve " << ref.uri());
- (void)fetch_schema(context.rebind(*schema, ref.uri()));
- std::optional referenced_node = from_cache(ref);
- EXPECT_M(referenced_node.has_value(),
- "Could not locate reference '" << ref << "' within external schema.");
- return *referenced_node;
- }
- schema::Node const * resolve_dynamic(detail::Anchor const & ref) {
- auto it = dynamic_anchors_.find(ref);
- EXPECT_M(it != dynamic_anchors_.end(), "Unmatched $dynamicRef '" << ref << "'");
- return it->second.reconstruct();
- }
- template <Adapter A> schema::Node const * fetch_schema(detail::ParserContext<A> const & context) {
- adapter::Type const type = context.schema.type();
- if (type == adapter::Type::Boolean && context.version >= schema::Version::Draft06) {
- return alias(context.where, context.schema.as_boolean() ? &accept_ : &reject_);
- }
- EXPECT(type == adapter::Type::Object);
- if (context.schema.object_size() == 0) {
- return alias(context.where, &accept_);
- }
- auto [it, created] = cache_.try_emplace(context.where, context);
- EXPECT_M(created, "more than one schema found with uri " << context.where);
- schema::Node const * node = &it->second;
- // Special Case - if the only is the reference constraint, then we don't need
- // to store it uniquely. Draft2019_09 supports directly extending a $ref schema
- // in the same schema, instead of requiring an allOf clause.
- if (node->is_pure_reference()) {
- node = *node->reference_schema();
- cache_.erase(it);
- return alias(context.where, node);
- }
- return alias(context.where, node);
- }
- };
- }
- namespace jvalidate::detail {
- template <Adapter A> schema::Node const * ParserContext<A>::node() const {
- return root.fetch_schema(*this);
- }
- template <Adapter A> schema::Node const * ParserContext<A>::always() const {
- return schema.as_boolean() ? &root.accept_ : &root.reject_;
- }
- }
- namespace jvalidate::schema {
- template <Adapter A> detail::OnBlockExit Node::resolve_anchor(detail::ParserContext<A> & context) {
- auto const schema = context.schema.as_object();
- if (schema.contains("$anchor")) {
- // Create an anchor mapping using the current document and the anchor
- // string. There's no need for special validation/chaining here, because
- // {@see Schema::resolve} will turn all $ref/$dynamicRef anchors into
- // their fully-qualified path.
- detail::Anchor anchor(schema["$anchor"].as_string());
- context.root.anchor(detail::Reference(context.where.uri(), anchor), context.where);
- return nullptr;
- }
- if (context.version == Version::Draft2019_09 && schema.contains("$recursiveAnchor")) {
- EXPECT_M(schema["$recursiveAnchor"].as_boolean(), "$recursiveAnchor MUST be 'true'");
- context.root.dynamic_anchor(detail::Anchor(), context);
- return [&context]() { context.root.remove_dynamic_anchor(detail::Anchor(), context.where); };
- }
- if (context.version > Version::Draft2019_09 && schema.contains("$dynamicAnchor")) {
- detail::Anchor anchor(schema["$dynamicAnchor"].as_string());
- context.root.dynamic_anchor(anchor, context);
- return [&context, anchor]() { context.root.remove_dynamic_anchor(anchor, context.where); };
- }
- }
- template <Adapter A> bool Node::resolve_reference(detail::ParserContext<A> const & context) {
- auto const schema = context.schema.as_object();
- if (schema.contains("$ref")) {
- detail::Reference ref(schema["$ref"].as_string());
- reference_ = context.root.resolve(ref, context);
- return true;
- }
- if (context.version < Version::Draft2019_09) {
- return false;
- }
- if (context.version == Version::Draft2019_09 && schema.contains("$recursiveRef")) {
- detail::Reference ref(schema["$recursiveRef"].as_string());
- EXPECT_M(ref == detail::Reference(), "Only the root schema is permitted as a $recursiveRef");
- reference_ = context.root.resolve_dynamic(detail::Anchor());
- return true;
- }
- if (context.version > Version::Draft2019_09 && schema.contains("$dynamicRef")) {
- detail::Reference ref(schema["$dynamicRef"].as_string());
- reference_ = context.root.resolve_dynamic(ref.anchor());
- return true;
- }
- return false;
- }
- template <Adapter A> Node::Node(detail::ParserContext<A> context) {
- EXPECT(context.schema.type() == adapter::Type::Object);
- auto const schema = context.schema.as_object();
- if (schema.contains("$schema")) {
- // At any point in the schema, we're allowed to change versions
- // This means that we're not version-locked to the latest grammar
- // (which is especially important for some breaking changes)
- context.version = schema_version(context.schema);
- }
- if (schema.contains("$id")) {
- context.root.alias(detail::Reference(schema["$id"].as_string(), false), this);
- }
- [[maybe_unused]] auto _ = resolve_anchor(context);
- bool const has_reference = resolve_reference(context);
- if (schema.contains("default")) {
- default_ = schema["default"].freeze();
- }
- if (schema.contains("description")) {
- description_ = schema["description"].as_string();
- }
- for (auto [key, subschema] : schema) {
- // Using a constraint store allows overriding certain rules, or the creation
- // of user-defined extention vocabularies.
- if (auto make_constraint = context.factory(key, context.version)) {
- EXPECT_M(not has_reference || context.version >= Version::Draft2019_09,
- "Cannot directly extend $ref schemas before Draft2019-09");
- // A constraint may return null if it is not applicable - but otherwise
- // well-formed. For example, before Draft-06 "exclusiveMaximum" was a
- // modifier property for "maximum", and not a unique constaint on its own.
- // Therefore, we parse it alongside parsing "maximum", and could return
- // nullptr when requesting a constraint pointer for "exclusiveMaximum".
- if (auto constraint = make_constraint(context.child(subschema, key))) {
- auto & into = context.factory.is_post_constraint(key) ? post_constraints_ : constraints_;
- into.emplace(key, std::move(constraint));
- }
- }
- }
- }
- }
|