schema.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. #pragma once
  2. #include <memory>
  3. #include <type_traits>
  4. #include <unordered_map>
  5. #include <vector>
  6. #include <jvalidate/adapter.h>
  7. #include <jvalidate/constraint.h>
  8. #include <jvalidate/detail/anchor.h>
  9. #include <jvalidate/detail/expect.h>
  10. #include <jvalidate/detail/on_block_exit.h>
  11. #include <jvalidate/detail/parser_context.h>
  12. #include <jvalidate/detail/pointer.h>
  13. #include <jvalidate/detail/reference.h>
  14. #include <jvalidate/detail/reference_manager.h>
  15. #include <jvalidate/document_cache.h>
  16. #include <jvalidate/enum.h>
  17. #include <jvalidate/forward.h>
  18. namespace jvalidate::schema {
  19. class Node {
  20. private:
  21. std::string description_;
  22. std::unique_ptr<adapter::Const const> default_{nullptr};
  23. std::optional<std::string> rejects_all_;
  24. std::optional<schema::Node const *> reference_{};
  25. std::unordered_map<std::string, std::unique_ptr<constraint::Constraint>> constraints_{};
  26. std::unordered_map<std::string, std::unique_ptr<constraint::Constraint>> post_constraints_{};
  27. public:
  28. Node() = default;
  29. Node(std::string const & rejection_reason) : rejects_all_(rejection_reason) {}
  30. template <Adapter A> void construct(detail::ParserContext<A> context);
  31. bool is_pure_reference() const {
  32. return reference_ && constraints_.empty() && post_constraints_.empty() && not default_;
  33. }
  34. bool accepts_all() const {
  35. return not reference_ && constraints_.empty() && post_constraints_.empty();
  36. }
  37. std::optional<std::string> const & rejects_all() const { return rejects_all_; }
  38. std::optional<schema::Node const *> reference_schema() const { return reference_; }
  39. bool requires_result_context() const { return not post_constraints_.empty(); }
  40. auto const & constraints() const { return constraints_; }
  41. auto const & post_constraints() const { return post_constraints_; }
  42. adapter::Const const * default_value() const { return default_.get(); }
  43. private:
  44. template <Adapter A> detail::OnBlockExit resolve_anchor(detail::ParserContext<A> const & context);
  45. template <Adapter A> bool resolve_reference(detail::ParserContext<A> const & context);
  46. };
  47. }
  48. namespace jvalidate {
  49. class Schema : public schema::Node {
  50. private:
  51. friend class schema::Node;
  52. template <Adapter A> friend class detail::ParserContext;
  53. private:
  54. schema::Node accept_;
  55. schema::Node reject_{"always false"};
  56. // An owning cache of all created schemas. Avoids storing duplicates such as
  57. // the "always-true" schema, "always-false" schema, and schemas whose only
  58. // meaningful field is "$ref", "$recursiveRef", or "$dynamicRef".
  59. std::map<detail::Reference, schema::Node> cache_;
  60. // A non-owning cache of all schemas, including duplcates where multiple
  61. // References map to the same underlying schema.
  62. std::map<detail::Reference, schema::Node const *> alias_cache_;
  63. public:
  64. /**
  65. * @brief Construct a new schema. All other constructors of this type may be
  66. * considered syntactic sugar for this constructor.
  67. *
  68. * As such, the true signature of this class's contructor is:
  69. *
  70. * Schema(Adapter| JSON
  71. * [, schema::Version]
  72. * [, URIResolver<A> | DocumentCache<A> &]
  73. * [, ConstraintFactory<A> const &])
  74. *
  75. * as long as the order of arguments is preserved - the constructor will work
  76. * no matter which arguments are ignored. The only required argument being
  77. * the JSON object/Adapter.
  78. *
  79. * @param json An adapter to a json object
  80. *
  81. * @param version The json-schema draft version that all schemas will prefer
  82. *
  83. * @param external An object capable of resolving URIs, and turning them into
  84. * Adapter objects. Holds a cache and so must be mutable.
  85. *
  86. * @param factory An object that manuafactures constraints - allows the user
  87. * to provide custom extensions or even modify the behavior of existing
  88. * keywords by overridding the virtual accessor function(s).
  89. */
  90. template <Adapter A>
  91. Schema(A const & json, schema::Version version, DocumentCache<A> & external,
  92. ConstraintFactory<A> const & factory = {}) {
  93. // Prevent unintialized data caches
  94. if (version >= schema::Version::Draft06 && json.type() == adapter::Type::Boolean) {
  95. schema::Node::operator=(std::move(json.as_boolean() ? accept_ : reject_));
  96. return;
  97. }
  98. detail::ReferenceManager<A> ref(external, json, version, factory);
  99. detail::ParserContext<A> root{*this, json, &ref.vocab(version), ref};
  100. root.where = root.dynamic_where = ref.canonicalize({}, {}, false);
  101. construct(root);
  102. }
  103. /**
  104. * @param json An adapter to a json schema
  105. *
  106. * @param version The json-schema draft version that all schemas will prefer
  107. *
  108. * @param external An object capable of resolving URIs, and turning them into
  109. * Adapter objects. Holds a cache and so must be mutable. If this constructor
  110. * is called, then it means that the cache is a one-off object, and will not
  111. * be reused.
  112. */
  113. template <Adapter A, typename... Args>
  114. Schema(A const & json, schema::Version version, DocumentCache<A> && external, Args &&... args)
  115. : Schema(json, version, external, std::forward<Args>(args)...) {}
  116. /**
  117. * @param json An adapter to a json schema
  118. *
  119. * @param version The json-schema draft version that all schemas will prefer
  120. *
  121. * @param resolve A function capable of resolving URIs, and storing the
  122. * contents in a provided concrete JSON object.
  123. */
  124. template <Adapter A, typename... Args>
  125. Schema(A const & json, schema::Version version, URIResolver<A> resolve, Args &&... args)
  126. : Schema(json, version, DocumentCache<A>(resolve), std::forward<Args>(args)...) {}
  127. /**
  128. * @param json An adapter to a json schema
  129. *
  130. * @param version The json-schema draft version that all schemas will prefer
  131. */
  132. template <Adapter A, Not<DocumentCache<A>>... Args>
  133. Schema(A const & json, schema::Version version, Args &&... args)
  134. : Schema(json, version, DocumentCache<A>(), std::forward<Args>(args)...) {}
  135. /**
  136. * @param json Any non-adapter (JSON) object. Will be immedately converted
  137. * into an Adapter object to allow us to walk through it w/o specialization.
  138. */
  139. template <typename JSON, typename... Args>
  140. explicit Schema(JSON const & json, Args &&... args)
  141. : Schema(adapter::AdapterFor<JSON const>(json), std::forward<Args>(args)...) {}
  142. private:
  143. schema::Node const * alias(detail::Reference const & where, schema::Node const * schema) {
  144. alias_cache_.emplace(where, schema);
  145. return schema;
  146. }
  147. std::optional<schema::Node const *> from_cache(detail::Reference const & ref) {
  148. if (auto it = alias_cache_.find(ref); it != alias_cache_.end()) {
  149. return it->second;
  150. }
  151. return std::nullopt;
  152. }
  153. template <Adapter A>
  154. schema::Node const * resolve(detail::Reference const & ref,
  155. detail::ParserContext<A> const & context, bool dynamic_reference) {
  156. detail::Reference lexical = context.ref.canonicalize(ref, context.where, dynamic_reference);
  157. detail::Reference dynamic = dynamic_reference ? lexical : context.dynamic_where / "$ref";
  158. if (std::optional cached = from_cache(dynamic)) {
  159. return *cached;
  160. }
  161. if (std::optional root = context.ref.load(lexical, context.vocab->version())) {
  162. return fetch_schema(context.rebind(*root, lexical, dynamic));
  163. }
  164. std::string error = "URIResolver could not resolve " + std::string(lexical.uri());
  165. return alias(dynamic, &cache_.try_emplace(dynamic, error).first->second);
  166. }
  167. template <Adapter A> schema::Node const * fetch_schema(detail::ParserContext<A> const & context) {
  168. // TODO(samjaffe): No longer promises uniqueness - instead track unique URI's
  169. if (std::optional cached = from_cache(context.dynamic_where)) {
  170. return *cached;
  171. }
  172. adapter::Type const type = context.schema.type();
  173. if (type == adapter::Type::Boolean && context.vocab->version() >= schema::Version::Draft06) {
  174. return alias(context.dynamic_where, context.schema.as_boolean() ? &accept_ : &reject_);
  175. }
  176. EXPECT_M(type == adapter::Type::Object, "invalid schema at " << context.dynamic_where);
  177. if (context.schema.object_size() == 0) {
  178. return alias(context.dynamic_where, &accept_);
  179. }
  180. auto [it, created] = cache_.try_emplace(context.dynamic_where);
  181. EXPECT_M(created, "creating duplicate schema at... " << context.dynamic_where);
  182. // Do this here first in order to protect from infinite loops
  183. alias(context.dynamic_where, &it->second);
  184. it->second.construct(context);
  185. return &it->second;
  186. }
  187. };
  188. }
  189. namespace jvalidate::detail {
  190. template <Adapter A> schema::Node const * ParserContext<A>::node() const {
  191. return root.fetch_schema(*this);
  192. }
  193. template <Adapter A> schema::Node const * ParserContext<A>::always() const {
  194. return fixed_schema(schema.as_boolean());
  195. }
  196. template <Adapter A> schema::Node const * ParserContext<A>::fixed_schema(bool accept) const {
  197. return accept ? &root.accept_ : &root.reject_;
  198. }
  199. }
  200. namespace jvalidate::schema {
  201. template <Adapter A>
  202. detail::OnBlockExit Node::resolve_anchor(detail::ParserContext<A> const & context) {
  203. auto const schema = context.schema.as_object();
  204. if (context.vocab->version() < schema::Version::Draft2019_09 || not schema.contains("$id")) {
  205. return nullptr;
  206. }
  207. return context.ref.dynamic_scope(context.where);
  208. }
  209. template <Adapter A> bool Node::resolve_reference(detail::ParserContext<A> const & context) {
  210. auto const schema = context.schema.as_object();
  211. if (schema.contains("$ref")) {
  212. detail::Reference ref(schema["$ref"].as_string());
  213. reference_ = context.root.resolve(ref, context, false);
  214. return true;
  215. }
  216. if (context.vocab->version() < Version::Draft2019_09) {
  217. return false;
  218. }
  219. std::string const dyn_ref =
  220. context.vocab->version() > schema::Version::Draft2019_09 ? "$dynamicRef" : "$recursiveRef";
  221. if (schema.contains(dyn_ref)) {
  222. detail::Reference ref(schema[dyn_ref].as_string());
  223. reference_ = context.root.resolve(ref, context, true);
  224. return true;
  225. }
  226. return false;
  227. }
  228. template <Adapter A> void Node::construct(detail::ParserContext<A> context) {
  229. EXPECT(context.schema.type() == adapter::Type::Object);
  230. auto const schema = context.schema.as_object();
  231. if (schema.contains("$schema")) {
  232. // At any point in the schema, we're allowed to change versions
  233. // This means that we're not version-locked to the latest grammar
  234. // (which is especially important for some breaking changes)
  235. context.vocab = &context.ref.vocab(URI(schema["$schema"].as_string()));
  236. }
  237. auto _ = resolve_anchor(context);
  238. bool const has_reference = resolve_reference(context);
  239. if (schema.contains("default")) {
  240. default_ = schema["default"].freeze();
  241. }
  242. if (schema.contains("description")) {
  243. description_ = schema["description"].as_string();
  244. }
  245. // Prior to Draft 2019-09, reference keywords take precedence over everything
  246. // else (instead of allowing direct extensions).
  247. if (has_reference && context.vocab->version() < Version::Draft2019_09) {
  248. return;
  249. }
  250. for (auto const & [key, subschema] : schema) {
  251. // Using a constraint store allows overriding certain rules, or the creation
  252. // of user-defined extention vocabularies.
  253. if (not context.vocab->is_constraint(key)) {
  254. continue;
  255. }
  256. // A constraint may return null if it is not applicable - but otherwise
  257. // well-formed. For example, before Draft-06 "exclusiveMaximum" was a
  258. // modifier property for "maximum", and not a unique constaint on its own.
  259. // Therefore, we parse it alongside parsing "maximum", and could return
  260. // nullptr when requesting a constraint pointer for "exclusiveMaximum".
  261. auto [constraint, post] = context.vocab->constraint(key, context.child(subschema, key));
  262. if (not constraint) {
  263. continue;
  264. }
  265. if (post) {
  266. post_constraints_.emplace(key, std::move(constraint));
  267. } else {
  268. constraints_.emplace(key, std::move(constraint));
  269. }
  270. }
  271. }
  272. }