schema.h 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. #pragma once
  2. #include <memory>
  3. #include <unordered_map>
  4. #include <vector>
  5. #include <jvalidate/adapter.h>
  6. #include <jvalidate/constraint.h>
  7. #include <jvalidate/detail/expect.h>
  8. #include <jvalidate/detail/pointer.h>
  9. #include <jvalidate/detail/reference.h>
  10. #include <jvalidate/enum.h>
  11. #include <jvalidate/forward.h>
  12. #include <jvalidate/parser_context.h>
  13. namespace jvalidate::schema {
  14. class Node {
  15. private:
  16. std::string description_;
  17. std::unique_ptr<adapter::Const const> default_{nullptr};
  18. detail::Reference uri_;
  19. bool rejects_all_{false};
  20. schema::Node const * reference_{nullptr};
  21. std::map<std::string, std::unique_ptr<constraint::Constraint>> constraints_{};
  22. protected:
  23. static Version schema_version(std::string_view url);
  24. static Version schema_version(Adapter auto const & json);
  25. static Version schema_version(Adapter auto const & json, Version default_version);
  26. public:
  27. Node(bool rejects_all = false) : rejects_all_(rejects_all) {}
  28. template <Adapter A> Node(ParserContext<A> context);
  29. bool is_pure_reference() const { return reference_ && constraints_.empty() && not default_; }
  30. };
  31. inline Version Node::schema_version(std::string_view url) {
  32. static std::map<std::string_view, Version> const g_schema_ids{
  33. {"http://json-schema.org/draft-04/schema", Version::Draft04},
  34. {"http://json-schema.org/draft-06/schema", Version::Draft06},
  35. {"http://json-schema.org/draft-07/schema", Version::Draft07},
  36. {"http://json-schema.org/draft/2019-09/schema", Version::Draft2019_09},
  37. {"http://json-schema.org/draft/2020-12/schema", Version::Draft2020_12},
  38. };
  39. if (url.ends_with('#')) {
  40. url.remove_suffix(1);
  41. }
  42. auto it = g_schema_ids.find(url);
  43. EXPECT_T(it != g_schema_ids.end(), std::invalid_argument, url);
  44. return it->second;
  45. }
  46. Version Node::schema_version(Adapter auto const & json) {
  47. EXPECT(json.type() == adapter::Type::Object);
  48. EXPECT(json.as_object().contains("$schema"));
  49. auto const & schema = json.as_object()["$schema"];
  50. EXPECT(schema.type() == adapter::Type::String);
  51. return schema_version(schema.as_string());
  52. }
  53. Version Node::schema_version(Adapter auto const & json, Version default_version) {
  54. RETURN_UNLESS(json.type() == adapter::Type::Object, default_version);
  55. RETURN_UNLESS(json.as_object().contains("$schema"), default_version);
  56. auto const & schema = json.as_object()["$schema"];
  57. RETURN_UNLESS(schema.type() == adapter::Type::String, default_version);
  58. return schema_version(schema.as_string());
  59. }
  60. }
  61. namespace jvalidate {
  62. class Schema : public schema::Node {
  63. private:
  64. friend class schema::Node;
  65. template <Adapter A> friend class ParserContext;
  66. private:
  67. schema::Node accept_{true};
  68. schema::Node reject_{false};
  69. std::map<std::string, detail::Reference> anchors_;
  70. std::map<detail::Reference, schema::Node> cache_;
  71. std::map<detail::Reference, schema::Node const *> alias_cache_;
  72. public:
  73. explicit Schema(Adapter auto const & json) : Schema(json, schema_version(json)) {}
  74. template <Adapter A>
  75. Schema(A const & json, schema::Version version)
  76. : schema::Node(ParserContext<A>{.root = *this, .schema = json, .version = version}) {}
  77. private:
  78. void anchor(std::string anchor, detail::Reference const & from) {}
  79. schema::Node const * alias(detail::Reference const & where, schema::Node const * schema) {
  80. EXPECT_M(alias_cache_.try_emplace(where, schema).second,
  81. "more than one schema found with uri " << where);
  82. return schema;
  83. }
  84. template <Adapter A>
  85. schema::Node const * resolve(detail::Reference ref, detail::Reference const & from,
  86. schema::Version default_version) {
  87. // Special case if the root-level document does not have an $id property
  88. if (ref == detail::Reference() && ref.anchor() == from.anchor()) {
  89. return this;
  90. }
  91. if (auto it = anchors_.find(ref.anchor()); it != anchors_.end()) {
  92. ref = it->second / ref.pointer();
  93. }
  94. EXPECT_M(ref.anchor().back() != '#', "Unmatched anchor: " << ref.anchor());
  95. if (auto it = alias_cache_.find(ref); it != alias_cache_.end()) {
  96. return it->second;
  97. }
  98. throw;
  99. }
  100. template <Adapter A> schema::Node const * fetch_schema(ParserContext<A> const & context) {
  101. adapter::Type const type = context.schema.type();
  102. if (type == adapter::Type::Boolean) {
  103. // TODO: Legal Context...
  104. return alias(context.where, context.schema.as_boolean() ? &accept_ : &reject_);
  105. }
  106. EXPECT(type == adapter::Type::Object);
  107. if (context.schema.object_size() == 0) {
  108. return alias(context.where, &accept_);
  109. }
  110. auto [it, created] = cache_.try_emplace(context.where, context);
  111. EXPECT_M(created, "more than one schema found with uri " << context.where);
  112. schema::Node const * node = &it->second;
  113. // Special Case - if the only is the reference constraint, then we don't need
  114. // to store it uniquely. Draft2019_09 supports directly extending a $ref schema
  115. // in the same schema, instead of requiring an allOf clause.
  116. if (node->is_pure_reference()) {
  117. cache_.erase(it);
  118. return alias(context.where, node);
  119. }
  120. return alias(context.where, node);
  121. }
  122. };
  123. template <Adapter A> schema::Node const * ParserContext<A>::resolve(std::string_view uri) const {
  124. return root.resolve<A>(detail::Reference(uri), where, version);
  125. }
  126. template <Adapter A> schema::Node const * ParserContext<A>::node() const {
  127. return root.fetch_schema(*this);
  128. }
  129. }
  130. namespace jvalidate::schema {
  131. template <Adapter A> Node::Node(ParserContext<A> context) {
  132. EXPECT(context.schema.type() == adapter::Type::Object);
  133. auto const schema = context.schema.as_object();
  134. if (schema.contains("$schema")) {
  135. // At any point in the schema, we're allowed to change versions
  136. // This means that we're not version-locked to the latest grammar
  137. // (which is especially important for some breaking changes)
  138. context.version = schema_version(context.schema);
  139. }
  140. if (schema.contains("$id")) {
  141. context.root.alias(detail::Reference(schema["$id"].as_string(), false), this);
  142. }
  143. // TODO(sjaffe): $recursiveAnchor, $dynamicAnchor, $recursiveRef, $dynamicRef
  144. if (schema.contains("$anchor")) {
  145. // Create an anchor mapping using the current document and the anchor
  146. // string. There's no need for special validation/chaining here, because
  147. // {@see Schema::resolve} will turn all $ref/$dynamicRef anchors into
  148. // their fully-qualified path.
  149. context.root.anchor(context.where.anchor() + schema["$anchor"].as_string(), context.where);
  150. }
  151. bool has_reference;
  152. if ((has_reference = schema.contains("$ref"))) {
  153. auto ref = schema["$ref"];
  154. EXPECT(ref.type() == adapter::Type::String);
  155. reference_ = context.resolve(ref.as_string());
  156. }
  157. if (schema.contains("default")) {
  158. default_ = schema["default"].freeze();
  159. }
  160. if (schema.contains("description")) {
  161. description_ = schema["description"].as_string();
  162. }
  163. for (auto [key, subschema] : schema) {
  164. // Using a constraint store allows overriding certain rules, or the creation
  165. // of user-defined extention vocabularies.
  166. // TODO(sjaffe): Pass this around instead
  167. if (auto make_constraint = ConstraintFactory<A>()(key, context.version)) {
  168. EXPECT_M(not has_reference || context.version >= Version::Draft2019_09,
  169. "Cannot directly extend $ref schemas before Draft2019-09");
  170. // A constraint may return null if it is not applicable - but otherwise
  171. // well-formed. For example, before Draft-06 "exclusiveMaximum" was a
  172. // modifier property for "maximum", and not a unique constaint on its own.
  173. // Therefore, we parse it alongside parsing "maximum", and could return
  174. // nullptr when requesting a constraint pointer for "exclusiveMaximum".
  175. if (auto constraint = make_constraint(context.child(subschema, key))) {
  176. constraints_.emplace(key, std::move(constraint));
  177. }
  178. }
  179. }
  180. }
  181. }