schema.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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> & 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. std::map<detail::Anchor, detail::Reference> dynamic_anchors_;
  93. // An owning cache of all created schemas. Avoids storing duplicates such as
  94. // the "always-true" schema, "always-false" schema, and schemas whose only
  95. // meaningful field is "$ref", "$recursiveRef", or "$dynamicRef".
  96. std::map<detail::Reference, schema::Node> cache_;
  97. // A non-owning cache of all schemas, including duplcates where multiple
  98. // References map to the same underlying schema.
  99. std::map<detail::Reference, schema::Node const *> alias_cache_;
  100. public:
  101. /**
  102. * @brief Construct a new schema. All other constructors of this type may be
  103. * considered syntactic sugar for this constructor.
  104. *
  105. * As such, the true signature of this class's contructor is:
  106. *
  107. * Schema(Adapter| JSON
  108. * [, schema::Version]
  109. * [, URIResolver<A> | DocumentCache<A> &]
  110. * [, ConstraintFactory<A> const &])
  111. *
  112. * as long as the order of arguments is preserved - the constructor will work
  113. * no matter which arguments are ignored. The only required argument being
  114. * the JSON object/Adapter.
  115. *
  116. * @param json An adapter to a json object
  117. *
  118. * @param version The json-schema draft version that all schemas will prefer
  119. *
  120. * @param external An object capable of resolving URIs, and turning them into
  121. * Adapter objects. Holds a cache and so must be mutable.
  122. *
  123. * @param factory An object that manuafactures constraints - allows the user
  124. * to provide custom extensions or even modify the behavior of existing
  125. * keywords by overridding the virtual accessor function(s).
  126. */
  127. template <Adapter A>
  128. Schema(A const & json, schema::Version version, DocumentCache<A> & external,
  129. ConstraintFactory<A> const & factory = {}) {
  130. // Prevent unintialized data caches
  131. if (version >= schema::Version::Draft06 && json.type() == adapter::Type::Boolean) {
  132. schema::Node::operator=(std::move(json.as_boolean() ? accept_ : reject_));
  133. return;
  134. }
  135. ReferenceManager<A> ref(json, version, factory.keywords(version));
  136. detail::ParserContext<A> root{*this, json, version, factory, external, ref};
  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 ref, detail::ParserContext<A> const & context) {
  197. ref = context.ref.canonicalize(ref, context.where);
  198. // Special case if the root-level document does not have an $id property
  199. if (std::optional root = context.ref.root(ref.root())) {
  200. return fetch_schema(context.rebind(ref.pointer().walk(*root), ref));
  201. }
  202. if (std::optional cached = from_cache(ref)) {
  203. return *cached;
  204. }
  205. std::optional schema = context.external.try_load(ref.uri());
  206. if (not schema.has_value()) {
  207. std::string error = "URIResolver could not resolve " + std::string(ref.uri());
  208. return alias(ref, &cache_.try_emplace(ref, error).first->second);
  209. }
  210. context.ref.prime(*schema, ref.uri(), context.version,
  211. context.factory.keywords(context.version));
  212. if (std::optional root = context.ref.root(ref.root())) {
  213. return fetch_schema(context.rebind(ref.pointer().walk(*root), ref));
  214. }
  215. return fetch_schema(context.rebind(ref.pointer().walk(*schema), ref));
  216. }
  217. template <Adapter A> schema::Node const * fetch_schema(detail::ParserContext<A> const & context) {
  218. // TODO(samjaffe): No longer promises uniqueness - instead track unique URI's
  219. if (std::optional cached = from_cache(context.where)) {
  220. return *cached;
  221. }
  222. adapter::Type const type = context.schema.type();
  223. if (type == adapter::Type::Boolean && context.version >= schema::Version::Draft06) {
  224. return alias(context.where, context.schema.as_boolean() ? &accept_ : &reject_);
  225. }
  226. EXPECT_M(type == adapter::Type::Object, "invalid schema at " << context.where);
  227. if (context.schema.object_size() == 0) {
  228. return alias(context.where, &accept_);
  229. }
  230. auto [it, created] = cache_.try_emplace(context.where);
  231. EXPECT_M(created, "creating duplicate schema at... " << context.where);
  232. // Do this here first in order to protect from infinite loops
  233. alias(context.where, &it->second);
  234. it->second.construct(context);
  235. /* if (not it->second.is_pure_reference()) { */
  236. return &it->second;
  237. /* } */
  238. // Special Case - if the only is the reference constraint, then we don't need
  239. // to store it uniquely. Draft2019_09 supports directly extending a $ref schema
  240. // in the same schema, instead of requiring an allOf clause.
  241. /* schema::Node const * node = *it->second.reference_schema(); */
  242. /* cache_.erase(it); */
  243. /* return alias_cache_[context.where] = node; */
  244. }
  245. };
  246. }
  247. namespace jvalidate::detail {
  248. template <Adapter A> schema::Node const * ParserContext<A>::node() const {
  249. return root.fetch_schema(*this);
  250. }
  251. template <Adapter A> schema::Node const * ParserContext<A>::always() const {
  252. return fixed_schema(schema.as_boolean());
  253. }
  254. template <Adapter A> schema::Node const * ParserContext<A>::fixed_schema(bool accept) const {
  255. return accept ? &root.accept_ : &root.reject_;
  256. }
  257. }
  258. namespace jvalidate::schema {
  259. template <Adapter A> detail::OnBlockExit Node::resolve_anchor(detail::ParserContext<A> & context) {
  260. auto const schema = context.schema.as_object();
  261. if (schema.contains("$anchor")) {
  262. return nullptr;
  263. }
  264. if (context.version == schema::Version::Draft2019_09 && schema.contains("$recursiveAnchor") &&
  265. schema["$recursiveAnchor"].as_boolean()) {
  266. detail::Reference actual_location = context.ref.canonicalize({}, context.where);
  267. if (context.root.dynamic_anchors_.emplace(detail::Anchor(), actual_location).second) {
  268. return [&root = context.root]() { root.dynamic_anchors_.erase(detail::Anchor()); };
  269. }
  270. }
  271. if (context.version > Version::Draft2019_09 && schema.contains("$dynamicAnchor")) {
  272. detail::Anchor anchor(schema["$dynamicAnchor"].as_string());
  273. detail::Reference actual_location = context.ref.canonicalize({}, context.where);
  274. if (context.root.dynamic_anchors_.emplace(anchor, actual_location).second) {
  275. return [&root = context.root, anchor]() { root.dynamic_anchors_.erase(anchor); };
  276. }
  277. }
  278. return nullptr;
  279. }
  280. template <Adapter A> bool Node::resolve_reference(detail::ParserContext<A> const & context) {
  281. auto const schema = context.schema.as_object();
  282. if (schema.contains("$ref")) {
  283. detail::Reference ref(schema["$ref"].as_string());
  284. reference_ = context.root.resolve(ref, context);
  285. return true;
  286. }
  287. if (context.version < Version::Draft2019_09) {
  288. return false;
  289. }
  290. std::string const dyn_ref =
  291. context.version > schema::Version::Draft2019_09 ? "$dynamicRef" : "$recursiveRef";
  292. if (schema.contains(dyn_ref)) {
  293. detail::RootReference ref(schema[dyn_ref].as_string());
  294. // TODO(samjaffe): Relocate...
  295. if (auto it = context.root.dynamic_anchors_.find(ref.anchor());
  296. it != context.root.dynamic_anchors_.end()) {
  297. // TODO(samjaffe): This does not re-compute things...
  298. reference_ = context.root.resolve(it->second, context);
  299. } else {
  300. reference_ = context.root.resolve(detail::Reference(ref), context);
  301. }
  302. return true;
  303. }
  304. return false;
  305. }
  306. template <Adapter A> void Node::construct(detail::ParserContext<A> context) {
  307. EXPECT(context.schema.type() == adapter::Type::Object);
  308. auto const schema = context.schema.as_object();
  309. if (schema.contains("$schema")) {
  310. // At any point in the schema, we're allowed to change versions
  311. // This means that we're not version-locked to the latest grammar
  312. // (which is especially important for some breaking changes)
  313. context.version = schema_version(context.schema);
  314. }
  315. [[maybe_unused]] auto _ = resolve_anchor(context);
  316. bool const has_reference = resolve_reference(context);
  317. if (schema.contains("default")) {
  318. default_ = schema["default"].freeze();
  319. }
  320. if (schema.contains("description")) {
  321. description_ = schema["description"].as_string();
  322. }
  323. // Prior to Draft 2019-09, reference keywords take precedence over everything
  324. // else (instead of allowing direct extensions).
  325. if (has_reference && context.version < Version::Draft2019_09) {
  326. return;
  327. }
  328. for (auto const & [key, subschema] : schema) {
  329. // Using a constraint store allows overriding certain rules, or the creation
  330. // of user-defined extention vocabularies.
  331. auto make_constraint = context.factory(key, context.version);
  332. if (not make_constraint) {
  333. continue;
  334. }
  335. // A constraint may return null if it is not applicable - but otherwise
  336. // well-formed. For example, before Draft-06 "exclusiveMaximum" was a
  337. // modifier property for "maximum", and not a unique constaint on its own.
  338. // Therefore, we parse it alongside parsing "maximum", and could return
  339. // nullptr when requesting a constraint pointer for "exclusiveMaximum".
  340. auto constraint = make_constraint(context.child(subschema, key));
  341. if (not constraint) {
  342. continue;
  343. }
  344. if (context.factory.is_post_constraint(key)) {
  345. post_constraints_.emplace(key, std::move(constraint));
  346. } else {
  347. constraints_.emplace(key, std::move(constraint));
  348. }
  349. }
  350. }
  351. }