schema.h 14 KB

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