constraint.h 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317
  1. #pragma once
  2. #include <functional>
  3. #include <map>
  4. #include <memory>
  5. #include <set>
  6. #include <string_view>
  7. #include <unordered_map>
  8. #include <unordered_set>
  9. #include <jvalidate/constraint/array_constraint.h>
  10. #include <jvalidate/constraint/general_constraint.h>
  11. #include <jvalidate/constraint/number_constraint.h>
  12. #include <jvalidate/constraint/object_constraint.h>
  13. #include <jvalidate/constraint/string_constraint.h>
  14. #include <jvalidate/compat/enumerate.h>
  15. #include <jvalidate/detail/expect.h>
  16. #include <jvalidate/detail/parser_context.h>
  17. #include <jvalidate/detail/vocabulary.h>
  18. #include <jvalidate/enum.h>
  19. #include <jvalidate/forward.h>
  20. namespace jvalidate {
  21. /**
  22. * @brief A factory object for the generation of constraints in JSON Schema
  23. * Parsing.
  24. *
  25. * Unless specified, the reference numbers in function documentation
  26. * refer to the Draft2020_12 specification, located on the following webpage(s):
  27. * https://json-schema.org/draft/2020-12/json-schema-validation OR
  28. * https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-01
  29. *
  30. * The ConstraintFactory supports, by default, all of the vocabulary of every
  31. * JSON Schema Draft covered by the Version enum.
  32. *
  33. * @tparam A The concrete Adapter type being used with this factory.
  34. * By providing this as a template parameter to ConstraintFactory - it allows us
  35. * to write code that does not need to operate on an abstract interface type
  36. * with a lot of annoying pointers and indirections.
  37. */
  38. template <Adapter A> class ConstraintFactory {
  39. public:
  40. using pConstraint = std::unique_ptr<constraint::Constraint>;
  41. // ParserContext<A> => pConstraint
  42. using MakeConstraint = typename detail::Vocabulary<A>::MakeConstraint;
  43. using Object = decltype(std::declval<A>().as_object());
  44. enum KeywordType { Keyword, Removed };
  45. /**
  46. * @brief This type represents a union of three different "parsing handler"
  47. * states:
  48. * 1) "Removed" - this schema token is not a keyword, and does not generate
  49. * a constraint.
  50. * 2) "Keyword" - this schema token represents a keyword, but does not
  51. * have a constraint associated with it. For example: "$defs" or "$comment"
  52. * 3) "Make" - this schema token is a keyword with an associated constant
  53. * generating function.
  54. */
  55. struct Make {
  56. Make(KeywordType t) : is_keyword(t == Keyword) {}
  57. template <typename F> Make(F make) : make(make), is_keyword(true) {}
  58. explicit operator bool() const { return make || is_keyword; }
  59. operator MakeConstraint() const { return make; }
  60. MakeConstraint make = nullptr;
  61. bool is_keyword = false;
  62. };
  63. /**
  64. * @brief In order to support multiple schema versions in a single instance of
  65. * a ConstraintFactory, we need to be able to describe which version a keyword
  66. * becomes part of the language vocabulary, and what (if any) version it
  67. * leaves the vocabulary after.
  68. *
  69. * To do this, we store an ordered map of Version enum onto Make (see above),
  70. * and then use {@see std::map::lower_bound} to determine which Make object is
  71. * the most approriate for the schema version being evaluated.
  72. *
  73. * For example:
  74. * The "additionalProperties" constraint is the same across all versions, and
  75. * so can be represented using only a function pointer.
  76. * {"additionalProperties", &Self::additionalProperties}
  77. *
  78. * The "const" constraint was not added until Draft06, so we include the
  79. * version when constructing its constraint bindings like so:
  80. * {"const", {schema::Version::Draft06, &Self::isConstant}}
  81. *
  82. * The "divisibleBy" constraint was removed in favor of "multipleOf" in
  83. * Draft04, and therefore is represented as:
  84. * {"divisibleBy", {{schema::Version::Earliest, &Self::multipleOf},
  85. * {schema::Version::Draft04, Removed}}},
  86. * {"multipleOf", {schema::Version::Draft04, &Self::multipleOf}}
  87. *
  88. * A small number of rare constraints change their meaning when moving from
  89. * one draft version to another in such a significant way that it makes more
  90. * sense to use different MakeConstraint functions for them.
  91. * {"items", {{schema::Version::Earliest, &Self::itemsTupleOrVector},
  92. * {schema::Version::Draft2020_12, &Self::additionalItems}}}
  93. */
  94. struct Versioned {
  95. template <typename M> Versioned(M make) : data{{schema::Version::Earliest, make}} {}
  96. template <typename M> Versioned(schema::Version version, M make) : data{{version, make}} {}
  97. Versioned(std::initializer_list<std::pair<schema::Version const, Make>> init) : data(init) {}
  98. std::map<schema::Version, Make, std::greater<>> data;
  99. };
  100. using Store = std::unordered_map<std::string_view, Versioned>;
  101. private:
  102. using Self = ConstraintFactory<A>;
  103. private:
  104. std::unordered_map<std::string_view, Versioned> constraints_{
  105. {"$defs", {schema::Version::Draft2019_09, Keyword}},
  106. {"additionalItems",
  107. {{schema::Version::Earliest, &Self::additionalItems},
  108. {schema::Version::Draft2020_12, Removed}}},
  109. {"additionalProperties", &Self::additionalProperties},
  110. {"allOf", {schema::Version::Draft04, &Self::allOf}},
  111. {"anyOf", {schema::Version::Draft04, &Self::anyOf}},
  112. {"const", {schema::Version::Draft06, &Self::isConstant}},
  113. {"contains", {schema::Version::Draft06, &Self::contains}},
  114. {"definitions", Keyword},
  115. {"dependencies", &Self::dependencies},
  116. {"dependentRequired", {schema::Version::Draft2019_09, &Self::dependentRequired}},
  117. {"dependentSchemas", {schema::Version::Draft2019_09, &Self::dependentSchemas}},
  118. {"disallow",
  119. {{schema::Version::Earliest, &Self::disallowDraft3}, {schema::Version::Draft04, Removed}}},
  120. {"divisibleBy",
  121. {{schema::Version::Earliest, &Self::multipleOf}, {schema::Version::Draft04, Removed}}},
  122. {"else", {{schema::Version::Draft07, Keyword}}},
  123. {"enum", &Self::isInEnumuration},
  124. {"exclusiveMaximum", {schema::Version::Draft06, &Self::exclusiveMaximum}},
  125. {"exclusiveMinimum", {schema::Version::Draft06, &Self::exclusiveMinimum}},
  126. {"extends",
  127. {{schema::Version::Earliest, &Self::extendsDraft3}, {schema::Version::Draft04, Removed}}},
  128. {"format", &Self::format},
  129. {"if", {schema::Version::Draft07, &Self::ifThenElse}},
  130. {"items",
  131. {{schema::Version::Earliest, &Self::itemsTupleOrVector},
  132. {schema::Version::Draft2020_12, &Self::additionalItems}}},
  133. {"maxItems", &Self::maxItems},
  134. {"maxLength", &Self::maxLength},
  135. {"maxProperties", {schema::Version::Draft04, &Self::maxProperties}},
  136. {"maximum", &Self::maximum},
  137. {"minItems", &Self::minItems},
  138. {"minLength", &Self::minLength},
  139. {"minProperties", {schema::Version::Draft04, &Self::minProperties}},
  140. {"minimum", &Self::minimum},
  141. {"multipleOf", {schema::Version::Draft04, &Self::multipleOf}},
  142. {"not", {schema::Version::Draft04, &Self::isNot}},
  143. {"oneOf", {schema::Version::Draft04, &Self::oneOf}},
  144. {"pattern", &Self::pattern},
  145. {"patternProperties", &Self::patternProperties},
  146. {"prefixItems", {schema::Version::Draft2020_12, &Self::prefixItems}},
  147. {"properties",
  148. {{schema::Version::Earliest, &Self::propertiesDraft3},
  149. {schema::Version::Draft04, &Self::properties}}},
  150. {"propertyNames", {schema::Version::Draft06, &Self::propertyNames}},
  151. {"required", {schema::Version::Draft04, &Self::required}},
  152. {"then", {schema::Version::Draft07, Keyword}},
  153. {"type",
  154. {{schema::Version::Earliest, &Self::typeDraft3}, {schema::Version::Draft04, &Self::type}}},
  155. {"unevaluatedItems", {schema::Version::Draft2019_09, &Self::unevaluatedItems}},
  156. {"unevaluatedProperties", {schema::Version::Draft2019_09, &Self::unevaluatedProperties}},
  157. {"uniqueItems", &Self::uniqueItems},
  158. };
  159. public:
  160. ConstraintFactory() = default;
  161. /**
  162. * @brief Construct a new ConstraintFactory, with a pre-defined list of user
  163. * keywords to be injected into the vocabulary. Does not override any keywords
  164. * that currently exist. Operates equivalently to calling with_user_keyword
  165. * for each element of init.
  166. *
  167. * @param init A list of keyword => Versioned constraint generators
  168. */
  169. ConstraintFactory(std::initializer_list<std::pair<std::string_view, Versioned>> init) {
  170. constraints_.insert(init.begin(), init.end());
  171. }
  172. /**
  173. * @brief A "with-er" function that adds a user-defined keyword to the
  174. * vocabulary. This keyword cannot already exist in the schema (although it is
  175. * not asserted).
  176. *
  177. * Only usable on rval references to prevent injections.
  178. *
  179. * @param word The keyword being added
  180. * @param make The Versioned constraint generators
  181. *
  182. * @returns This factory
  183. */
  184. ConstraintFactory<A> && with_user_keyword(std::string_view word, Versioned make) && {
  185. constraints_.insert(word, std::move(make));
  186. return *this;
  187. }
  188. /**
  189. * @brief A "with-er" function that overrides a draft-defined keyword to the
  190. * vocabulary. This keyword is expected to already exist (although it is not
  191. * asserted).
  192. *
  193. * Only usable on rval references to prevent injections.
  194. *
  195. * @param word The keyword being overwritten
  196. * @param make The Versioned constraint generators
  197. *
  198. * @returns This factory
  199. */
  200. ConstraintFactory<A> && override_keyword(std::string_view word, Versioned make) && {
  201. constraints_[word] = std::move(make);
  202. return *this;
  203. }
  204. detail::Vocabulary<A> keywords(schema::Version version) const {
  205. std::unordered_map<std::string_view, MakeConstraint> rval;
  206. for (auto const & [key, versions] : constraints_) {
  207. if (auto it = versions.data.lower_bound(version); it != versions.data.end() && it->second) {
  208. rval.emplace(key, it->second);
  209. }
  210. }
  211. return detail::Vocabulary<A>(version, std::move(rval));
  212. }
  213. // SECTION: Untyped Constraints
  214. /**
  215. * @brief Parser for the "type" constraint (6.1.1) for JSON Schema Draft04
  216. * and up. This validates that a JSON document instance is of a specified
  217. * type or list of types.
  218. *
  219. * @pre context.schema MUST be either a string, or an array of strings.
  220. * @pre each string must be one of the six JSON primitives, or "integer"
  221. *
  222. * @param context The operating context of the schema parsing.
  223. *
  224. * @returns If the value at "type" is a string, then we return a constraint
  225. * that is true if the type of the instance is of the type represented by the
  226. * string. If the value is an array, then the constraint will validate if the
  227. * instance is any of the listed types.
  228. *
  229. * @throws std::runtime_error if precondition #1 is broken
  230. * @throws std::out_of_range if precondition #2 is broken
  231. */
  232. static auto type(detail::ParserContext<A> const & context) {
  233. static std::unordered_map<std::string_view, adapter::Type> const s_type_names{
  234. {"null", adapter::Type::Null}, {"boolean", adapter::Type::Boolean},
  235. {"integer", adapter::Type::Integer}, {"number", adapter::Type::Number},
  236. {"string", adapter::Type::String}, {"array", adapter::Type::Array},
  237. {"object", adapter::Type::Object},
  238. };
  239. auto to_type = [](std::string_view type) {
  240. EXPECT_M(s_type_names.contains(type), "Unknown type " << type);
  241. return s_type_names.at(type);
  242. };
  243. adapter::Type const type = context.schema.type();
  244. if (type == adapter::Type::String) {
  245. return std::make_unique<constraint::TypeConstraint>(to_type(context.schema.as_string()));
  246. }
  247. EXPECT(type == adapter::Type::Array);
  248. std::set<adapter::Type> types;
  249. for (auto subschema : context.schema.as_array()) {
  250. types.insert(to_type(subschema.as_string()));
  251. }
  252. return std::make_unique<constraint::TypeConstraint>(types);
  253. }
  254. /**
  255. * @brief Parser for the "type" constraint (5.1) for JSON Schema Draft03
  256. * (https://json-schema.org/draft-03/draft-zyp-json-schema-03.pdf). This
  257. * validates that a JSON document instance is of a specified type, or list of
  258. * types/subschemas.
  259. *
  260. * Despite the draft document not indicating so, it is considered legal for a
  261. * type constraint to allow subschemas when in array form.
  262. *
  263. * Additionally, it supports the additional type enumeration "any", which is
  264. * equivalent to not having a type constraint at all.
  265. *
  266. * @pre context.schema MUST be either a string, or an array of
  267. * strings/subschemas.
  268. * @pre each string MUST be one of the six JSON primitives, "integer",
  269. * or "any"
  270. *
  271. * @param context The operating context of the schema parsing.
  272. *
  273. * @returns If the value at "type" is a string, then we return a constraint
  274. * that is true if the type of the instance is of the type represented by the
  275. * string. If the value is an array, then the constraint will validate if the
  276. * instance is any of the listed types or validated by the subschema.
  277. *
  278. * @throws std::runtime_error if precondition #1 is broken
  279. * @throws std::out_of_range if precondition #2 is broken
  280. */
  281. static pConstraint typeDraft3(detail::ParserContext<A> const & context) {
  282. static std::unordered_map<std::string_view, adapter::Type> const s_type_names{
  283. {"null", adapter::Type::Null}, {"boolean", adapter::Type::Boolean},
  284. {"integer", adapter::Type::Integer}, {"number", adapter::Type::Number},
  285. {"string", adapter::Type::String}, {"array", adapter::Type::Array},
  286. {"object", adapter::Type::Object},
  287. };
  288. auto to_type = [](std::string_view type) {
  289. EXPECT_M(s_type_names.contains(type), "Unknown type " << type);
  290. return s_type_names.at(type);
  291. };
  292. adapter::Type const type = context.schema.type();
  293. if (type == adapter::Type::String) {
  294. if (context.schema.as_string() == "any") {
  295. return nullptr; // nullptr is a synonym for "always accept"
  296. }
  297. return std::make_unique<constraint::TypeConstraint>(to_type(context.schema.as_string()));
  298. }
  299. EXPECT(type == adapter::Type::Array);
  300. std::vector<schema::Node const *> children;
  301. std::set<adapter::Type> types;
  302. for (auto const & [index, subschema] : detail::enumerate(context.schema.as_array())) {
  303. if (subschema.type() != adapter::Type::String) {
  304. children.push_back(context.child(subschema, index).node());
  305. } else if (subschema.as_string() == "any") {
  306. return nullptr; // nullptr is a synonym for "always accept"
  307. } else {
  308. types.insert(to_type(subschema.as_string()));
  309. }
  310. }
  311. auto rval = std::make_unique<constraint::AnyOfConstraint>(children);
  312. rval->children.push_back(std::make_unique<constraint::TypeConstraint>(types));
  313. return rval;
  314. }
  315. /**
  316. * @brief Parser for the "disallow" constraint (5.25) for JSON Schema Draft03.
  317. * This constraint has the same preconditions and parsing rules as "type"
  318. * (Draft03) does, but inverts it.
  319. *
  320. * @pre context.schema MUST be either a string, or an array of
  321. * strings/subschemas.
  322. * @pre each string must be one of the six JSON primitives, "integer",
  323. * or "any"
  324. *
  325. * @param context The operating context of the schema parsing.
  326. *
  327. * @returns not(typeDraft3())
  328. *
  329. * @throws {@see ConstraintFactory::typeDraft3}
  330. */
  331. static pConstraint disallowDraft3(detail::ParserContext<A> const & context) {
  332. return std::make_unique<constraint::NotConstraint>(typeDraft3(context));
  333. }
  334. /**
  335. * @brief Parser for the "extends" constraint (5.26) for JSON Schema Draft03.
  336. * This validates that a JSON document instance meets both the parent schema,
  337. * and the child schema(s).
  338. *
  339. * The draft document shows examples that make sense as "$ref" constraints,
  340. * but the actual form of the "extends" is another schema, or an array of
  341. * schemas.
  342. * In Draft04 - the array/object form is replaced by including an "allOf"
  343. * constraint will all of the subschemas.
  344. * In Draft2019_09 - the single-object form can be implemented using "$ref",
  345. * since the parsing rules of reference handling have been relaxed.
  346. *
  347. * @pre context.schema MUST be either an object, or an array
  348. * @pre each object MUST be valid as a top-level schema
  349. *
  350. * @param context The operating context of the schema parsing.
  351. *
  352. * @returns An AllOf constraint matching the one/many requested subschema(s).
  353. *
  354. * @throws std::runtime_error if precondition #1 is broken
  355. * @throws any std::exception if precondition #2 is broken
  356. */
  357. static pConstraint extendsDraft3(detail::ParserContext<A> const & context) {
  358. std::vector<schema::Node const *> children;
  359. switch (context.schema.type()) {
  360. case adapter::Type::Object:
  361. children.push_back(context.node());
  362. break;
  363. case adapter::Type::Array: {
  364. for (auto const & [index, subschema] : detail::enumerate(context.schema.as_array())) {
  365. children.push_back(context.child(subschema, index).node());
  366. }
  367. break;
  368. }
  369. default:
  370. JVALIDATE_THROW(std::runtime_error, "extends must be a schema of array-of-schemas");
  371. }
  372. return std::make_unique<constraint::AllOfConstraint>(children);
  373. }
  374. /**
  375. * @brief Parser for the "if" constraint (10.2.2.1, 10.2.2.2, 10.2.2.3). This
  376. * constraint is divided between three keywords.
  377. * If the "if" keyword is present, then we will attempt to validate the "then"
  378. * and "else keywords as well. All three are implemented as subschemas.
  379. * The evaluation forms an if-then-else, if-then, or if-else block, depending
  380. * on which of "then" and "else" are present.
  381. * There is no rule preventing an "if" keyword from existing without either
  382. * of the "then" or "else" keywords, but doing so only serves the purpose of
  383. * annotation gathering.
  384. * TODO: Only gather annotations from then/else if the if clause is present
  385. *
  386. * @param context The operating context of the schema parsing.
  387. *
  388. * @returns A ContainsConstraint, with optional minimum and maximum matching
  389. */
  390. static pConstraint ifThenElse(detail::ParserContext<A> const & context) {
  391. schema::Node const * then_ = context.fixed_schema(true);
  392. if (context.parent->contains("then")) {
  393. then_ = context.neighbor("then").node();
  394. }
  395. schema::Node const * else_ = context.fixed_schema(true);
  396. if (context.parent->contains("else")) {
  397. else_ = context.neighbor("else").node();
  398. }
  399. return std::make_unique<constraint::ConditionalConstraint>(context.node(), then_, else_);
  400. }
  401. /**
  402. * @brief Parser for the "enum" constraint (6.1.2) for JSON Schema Draft04
  403. * and up. This validates that the JSON document instance is equal to one of
  404. * the given JSON document samples.
  405. *
  406. * @param context The operating context of the schema parsing.
  407. *
  408. * @returns A constraint that checks equality against a set of values.
  409. */
  410. static auto isInEnumuration(detail::ParserContext<A> const & context) {
  411. EXPECT(context.schema.type() == adapter::Type::Array);
  412. std::vector<std::unique_ptr<adapter::Const const>> rval;
  413. for (auto subschema : context.schema.as_array()) {
  414. rval.push_back(subschema.freeze());
  415. }
  416. return std::make_unique<constraint::EnumConstraint>(std::move(rval));
  417. }
  418. /**
  419. * @brief Parser for the "const" constraint (6.1.3) for JSON Schema Draft04
  420. * and up. This validates that the JSON document instance is equal to the
  421. * given JSON document samples.
  422. *
  423. * @param context The operating context of the schema parsing.
  424. *
  425. * @returns A constraint that checks equality against a single value.
  426. */
  427. static auto isConstant(detail::ParserContext<A> const & context) {
  428. return std::make_unique<constraint::EnumConstraint>(context.schema.freeze());
  429. }
  430. /**
  431. * @brief Parser for a "allOf" constraint (10.2.1.1). This constraint
  432. * validates that all of the underlying schemas validate the instance.
  433. *
  434. * @pre context.schema is an array
  435. *
  436. * @param context The operating context of the schema parsing.
  437. *
  438. * @returns A AllOfConstraint
  439. *
  440. * @throws std::runtime_error if precondition #1 is broken
  441. */
  442. static auto allOf(detail::ParserContext<A> const & context) {
  443. EXPECT(context.schema.type() == adapter::Type::Array);
  444. std::vector<schema::Node const *> rval;
  445. for (auto const & [index, subschema] : detail::enumerate(context.schema.as_array())) {
  446. rval.push_back(context.child(subschema, index).node());
  447. }
  448. return std::make_unique<constraint::AllOfConstraint>(rval);
  449. }
  450. /**
  451. * @brief Parser for a "anyOf" constraint (10.2.1.2). This constraint
  452. * validates that any of the underlying schemas validate the instance.
  453. *
  454. * @pre context.schema is an array
  455. *
  456. * @param context The operating context of the schema parsing.
  457. *
  458. * @returns A AnyOfConstraint
  459. *
  460. * @throws std::runtime_error if precondition #1 is broken
  461. */
  462. static auto anyOf(detail::ParserContext<A> const & context) {
  463. EXPECT(context.schema.type() == adapter::Type::Array);
  464. std::vector<schema::Node const *> rval;
  465. for (auto const & [index, subschema] : detail::enumerate(context.schema.as_array())) {
  466. rval.push_back(context.child(subschema, index).node());
  467. }
  468. return std::make_unique<constraint::AnyOfConstraint>(rval);
  469. }
  470. /**
  471. * @brief Parser for a "oneOf" constraint (10.2.1.3). This constraint
  472. * validates that exactly one of the underlying schemas validate the instance.
  473. *
  474. * @pre context.schema is an array
  475. *
  476. * @param context The operating context of the schema parsing.
  477. *
  478. * @returns A OneOfConstraint
  479. *
  480. * @throws std::runtime_error if precondition #1 is broken
  481. */
  482. static auto oneOf(detail::ParserContext<A> const & context) {
  483. EXPECT(context.schema.type() == adapter::Type::Array);
  484. std::vector<schema::Node const *> rval;
  485. for (auto const & [index, subschema] : detail::enumerate(context.schema.as_array())) {
  486. rval.push_back(context.child(subschema, index).node());
  487. }
  488. return std::make_unique<constraint::OneOfConstraint>(rval);
  489. }
  490. /**
  491. * @brief Parser for a "not" constraint (10.2.1.4). This constraint inverts
  492. * the acceptance of the underlying schema.
  493. *
  494. * @param context The operating context of the schema parsing.
  495. *
  496. * @returns A NotConstraint
  497. */
  498. static auto isNot(detail::ParserContext<A> const & context) {
  499. return std::make_unique<constraint::NotConstraint>(context.node());
  500. }
  501. // SECTION: Numeric Constraints
  502. /**
  503. * @brief Parser for the "minimum" constraint (6.2.4). This constraint
  504. * validates numberic JSON instances where `instance >= context.schema`
  505. * Before Draft06, this constraint must test for/evaluate the neighbor keyword
  506. * "exclusiveMinimum", which is a boolean.
  507. * Starting in Draft06, the "exclusiveMinimum" constraint exists separately,
  508. * and this constraint represents "inclusive minimum".
  509. *
  510. * @param context The operating context of the schema parsing.
  511. *
  512. * @returns A MinimumConstraint
  513. *
  514. * @throws If the contained value is not interpretable as a number
  515. * @throws std::runtime_error if version < Draft06 AND exclusiveMinimum exists
  516. * and is not a boolean.
  517. */
  518. static auto minimum(detail::ParserContext<A> const & context) {
  519. double value = context.schema.as_number();
  520. if (context.vocab->version() < schema::Version::Draft06 &&
  521. context.parent->contains("exclusiveMinimum")) {
  522. auto exclusive = (*context.parent)["exclusiveMinimum"];
  523. EXPECT(exclusive.type() == adapter::Type::Boolean);
  524. return std::make_unique<constraint::MinimumConstraint>(value, exclusive.as_boolean());
  525. }
  526. return std::make_unique<constraint::MinimumConstraint>(value, false);
  527. }
  528. /**
  529. * @brief Parser for the "exclusiveMinimum" constraint (6.2.5) for JSON Schema
  530. * Draft06 and up. This constraint validates numberic JSON instances where
  531. * `instance > context.schema`
  532. *
  533. * @param context The operating context of the schema parsing.
  534. *
  535. * @returns A MinimumConstraint
  536. *
  537. * @throws If the contained value is not interpretable as a number
  538. */
  539. static pConstraint exclusiveMinimum(detail::ParserContext<A> const & context) {
  540. double value = context.schema.as_number();
  541. return std::make_unique<constraint::MinimumConstraint>(value, true);
  542. }
  543. /**
  544. * @brief Parser for the "maximum" constraint (6.2.2). This constraint
  545. * validates numberic JSON instances where `instance <= context.schema`
  546. * Before Draft06, this constraint must test for/evaluate the neighbor keyword
  547. * "exclusiveMaximum", which is a boolean.
  548. * Starting in Draft06, the "exclusiveMaximum" constraint exists separately,
  549. * and this constraint represents "inclusive maximum".
  550. *
  551. * @param context The operating context of the schema parsing.
  552. *
  553. * @returns A MaximumConstraint
  554. *
  555. * @throws If the contained value is not interpretable as a number
  556. * @throws std::runtime_error if version < Draft06 AND exclusiveMaximum exists
  557. * and is not a boolean.
  558. */
  559. static auto maximum(detail::ParserContext<A> const & context) {
  560. double value = context.schema.as_number();
  561. if (context.vocab->version() < schema::Version::Draft06 &&
  562. context.parent->contains("exclusiveMaximum")) {
  563. auto exclusive = (*context.parent)["exclusiveMaximum"];
  564. EXPECT(exclusive.type() == adapter::Type::Boolean);
  565. return std::make_unique<constraint::MaximumConstraint>(value, exclusive.as_boolean());
  566. }
  567. return std::make_unique<constraint::MaximumConstraint>(value, false);
  568. }
  569. /**
  570. * @brief Parser for the "exclusiveMaximum" constraint (6.2.3) for JSON Schema
  571. * Draft06 and up. This constraint validates numberic JSON instances where
  572. * `instance < context.schema`
  573. *
  574. * @param context The operating context of the schema parsing.
  575. *
  576. * @returns A MaximumConstraint
  577. *
  578. * @throws If the contained value is not interpretable as a number
  579. */
  580. static pConstraint exclusiveMaximum(detail::ParserContext<A> const & context) {
  581. double value = context.schema.as_number();
  582. return std::make_unique<constraint::MaximumConstraint>(value, true);
  583. }
  584. /**
  585. * @brief Parser for the "multipleOf" constraint (6.2.1) for JSON Schema
  586. * Draft04 and up. In Draft03 this covers the "divisibleBy" constraint (5.24).
  587. * This constraint validates numeric JSON instances where
  588. * `instance / context.schema` is a whole number. Because of differences in
  589. * handling of numbers between C++, Python, JavaScript, etc. there are some
  590. * edge cases which cannot be properly handled.
  591. *
  592. * @pre context.schema matches { "type": "number" }
  593. * @pre context.schema.as_number() > 0
  594. *
  595. * @param context The operating context of the schema parsing.
  596. *
  597. * @returns A MultipleOfConstraint
  598. *
  599. * @throws If the contained value is not interpretable as a number
  600. */
  601. static auto multipleOf(detail::ParserContext<A> const & context) {
  602. double value = context.schema.as_number();
  603. return std::make_unique<constraint::MultipleOfConstraint>(value);
  604. }
  605. // SECTION: String Constraints
  606. /**
  607. * @brief Parser for the "minLength" constraint (6.3.2). This constraint
  608. * validates string JSON instances has a length >= context.schema, as per
  609. * RFC 8259.
  610. *
  611. * @pre context.schema MUST be an integer
  612. * @pre context.schema >= 0
  613. *
  614. * @param context The operating context of the schema parsing.
  615. *
  616. * @returns A MinLengthConstraint
  617. *
  618. * @throws If the contained value is not interpretable as an integer
  619. */
  620. static auto minLength(detail::ParserContext<A> const & context) {
  621. EXPECT(context.schema.type() == adapter::Type::Integer ||
  622. context.schema.type() == adapter::Type::Number);
  623. return std::make_unique<constraint::MinLengthConstraint>(context.schema.as_integer());
  624. }
  625. /**
  626. * @brief Parser for the "maxLength" constraint (6.3.1). This constraint
  627. * validates string JSON instances have a length <= context.schema, as per
  628. * RFC 8259.
  629. *
  630. * @pre context.schema MUST be an integer
  631. * @pre context.schema >= 0
  632. *
  633. * @param context The operating context of the schema parsing.
  634. *
  635. * @returns A MaxLengthConstraint
  636. *
  637. * @throws If the contained value is not interpretable as an integer
  638. */
  639. static auto maxLength(detail::ParserContext<A> const & context) {
  640. EXPECT(context.schema.type() == adapter::Type::Integer ||
  641. context.schema.type() == adapter::Type::Number);
  642. return std::make_unique<constraint::MaxLengthConstraint>(context.schema.as_integer());
  643. }
  644. /**
  645. * @brief Parser for the "pattern" constraint (6.3.3). This constraint
  646. * validates string JSON instances match an ECMA-262 compatible regular
  647. * expression.
  648. *
  649. * This function does not attempt to compile the regular expression,
  650. * meaning that if the pattern is not a valid regex, it will fail at a later
  651. * point.
  652. *
  653. * @pre context.schema MUST be a string
  654. *
  655. * @param context The operating context of the schema parsing.
  656. *
  657. * @returns A PatternConstraint
  658. *
  659. * @throws If the contained value is not interpretable as a string
  660. */
  661. static auto pattern(detail::ParserContext<A> const & context) {
  662. return std::make_unique<constraint::PatternConstraint>(context.schema.as_string());
  663. }
  664. /**
  665. * @brief Parser for the "format" constraint, which validates string JSON
  666. * instances against one of several pre-defined formats that either would
  667. * be unnecessarily complicated to represent as PatternConstraint, prone to
  668. * user-error when done so, or cannot be represented as regular expressions
  669. * at all.
  670. *
  671. * @pre context.schema MUST be a string
  672. *
  673. * @param context The operating context of the schema parsing.
  674. *
  675. * @returns A FormatConstraint, if the vocabulary enabled "format assertions",
  676. * then this constraint will actually validate the JSON instance. Otherwise,
  677. * it simply annotates that the field is expected to match the format.
  678. *
  679. * @throws If the contained value is not interpretable as a string
  680. */
  681. static auto format(detail::ParserContext<A> const & context) {
  682. return std::make_unique<constraint::FormatConstraint>(context.schema.as_string(),
  683. context.vocab->is_format_assertion());
  684. }
  685. // SECTION: Array Constraints
  686. /**
  687. * @brief Parser for the "contains" constraint (10.3.1.3, 6.4.4, 6.4.5). This
  688. * constraint is divided between three different keywords.
  689. * The "contains" keyword acts as a subschema, and is required for parsing.
  690. * "minContains" and "maxContains" act as boundaries on the number of matches,
  691. * such that the number of array elements matching the "contains" schema is at
  692. * least "minContains" and at most "maxContains".
  693. *
  694. * If "minContains" is null, then it is the equivalent of 1.
  695. * A "minContains" value of zero is only meaningful in the context of
  696. * setting an upper-bound.
  697. * If "maxContains" is null, then it is the equivalent of INFINITY
  698. *
  699. * @pre context.schema MUST be a valid JSON schema
  700. * @pre context.parent["maxContains"] is null OR an integer >= 0
  701. * @pre context.parent["minContains"] is null OR an integer >= 0
  702. *
  703. * @param context The operating context of the schema parsing.
  704. *
  705. * @returns A ContainsConstraint, with optional minimum and maximum matching
  706. */
  707. static auto contains(detail::ParserContext<A> const & context) {
  708. if (context.vocab->version() < schema::Version::Draft2019_09) {
  709. return std::make_unique<constraint::ContainsConstraint>(context.node());
  710. }
  711. std::optional<size_t> maximum;
  712. std::optional<size_t> minimum;
  713. if (context.parent->contains("maxContains")) {
  714. maximum = (*context.parent)["maxContains"].as_integer();
  715. }
  716. if (context.parent->contains("minContains")) {
  717. minimum = (*context.parent)["minContains"].as_integer();
  718. }
  719. return std::make_unique<constraint::ContainsConstraint>(context.node(), minimum, maximum);
  720. }
  721. /**
  722. * @brief Parser for the "minItems" constraint (6.4.2). This constraint
  723. * validates array JSON instances have a length <= context.schema.
  724. *
  725. * @pre context.schema MUST be an integer
  726. * @pre context.schema >= 0
  727. *
  728. * @param context The operating context of the schema parsing.
  729. *
  730. * @returns A MinItemsConstraint
  731. *
  732. * @throws If the contained value is not interpretable as an integer
  733. */
  734. static auto minItems(detail::ParserContext<A> const & context) {
  735. EXPECT(context.schema.type() == adapter::Type::Integer ||
  736. context.schema.type() == adapter::Type::Number);
  737. return std::make_unique<constraint::MinItemsConstraint>(context.schema.as_integer());
  738. }
  739. /**
  740. * @brief Parser for the "maxItems" constraint (6.4.1). This constraint
  741. * validates array JSON instances have a length <= context.schema.
  742. *
  743. * @pre context.schema MUST be an integer
  744. * @pre context.schema >= 0
  745. *
  746. * @param context The operating context of the schema parsing.
  747. *
  748. * @returns A MaxItemsConstraint
  749. *
  750. * @throws If the contained value is not interpretable as an integer
  751. */
  752. static auto maxItems(detail::ParserContext<A> const & context) {
  753. EXPECT(context.schema.type() == adapter::Type::Integer ||
  754. context.schema.type() == adapter::Type::Number);
  755. return std::make_unique<constraint::MaxItemsConstraint>(context.schema.as_integer());
  756. }
  757. /**
  758. * @brief Parser for the "prefixItems" constraint (10.3.1.1) for JSON Schema
  759. * Draft2020_12 and up. This constraint validates the first N elements of an
  760. * array JSON instance with its own subschemas.
  761. *
  762. * @pre context.schema MUST be an array
  763. * @pre context.schema MUST have at least 1 element
  764. * @pre each element of context.schema MUST be a valid JSON Schema
  765. *
  766. * @param context The operating context of the schema parsing.
  767. *
  768. * @returns A TupleConstraint
  769. *
  770. * @throws std::runtime_error if preconditions #1 or #2 are broken
  771. * @throws if precondition #3 is broken
  772. */
  773. static auto prefixItems(detail::ParserContext<A> const & context) {
  774. EXPECT(context.schema.type() == adapter::Type::Array);
  775. std::vector<schema::Node const *> rval;
  776. for (auto const & [index, subschema] : detail::enumerate(context.schema.as_array())) {
  777. rval.push_back(context.child(subschema, index).node());
  778. }
  779. return std::make_unique<constraint::TupleConstraint>(rval);
  780. }
  781. /**
  782. * @brief Parser for the "additionalItems" constraint (9.3.1.1) for JSON
  783. * Schema Draft2019_09 and prior, and the "items" constraint (10.3.1.2) for
  784. * JSON Schema Draft2020_12 and up.
  785. * This constraint validates an array JSON instance starting from the N-th
  786. * element, as determined by the "items" schema (<= Draft2019_09), or the
  787. * "prefixItems" schema (>= Draft2020_12).
  788. *
  789. * @pre context.schema MUST be a valid JSON Schema (including boolean schema)
  790. *
  791. * @param context The operating context of the schema parsing.
  792. *
  793. * @returns An AdditionalItemsConstraint, unless the special condition
  794. * described below is met.
  795. *
  796. * @throws if the precondition is broken
  797. */
  798. static pConstraint additionalItems(detail::ParserContext<A> const & context) {
  799. std::string const prefix =
  800. context.vocab->version() >= schema::Version::Draft2020_12 ? "prefixItems" : "items";
  801. Object const & parent = *context.parent;
  802. // Before Draft 2020-12, the "items" could be either a subschema or a tuple.
  803. // When not provided, we therefore treat it as an "accept-all" schema, and
  804. // thus will never have additionalItems to process. Similarly - if it is an
  805. // Object, then it must act on all items.
  806. if (context.vocab->version() < schema::Version::Draft2020_12 &&
  807. (not parent.contains(prefix) || parent[prefix].type() == adapter::Type::Object)) {
  808. return nullptr;
  809. }
  810. size_t const n = parent[prefix].array_size();
  811. // Prior to Draft06, boolean schemas were not allowed in a general context,
  812. // they were instead reserved for the "additionalItems" and
  813. // "additionalProperties" keywords.
  814. if (context.vocab->version() < schema::Version::Draft06 &&
  815. context.schema.type() == adapter::Type::Boolean) {
  816. return std::make_unique<constraint::AdditionalItemsConstraint>(context.always(), n);
  817. }
  818. return std::make_unique<constraint::AdditionalItemsConstraint>(context.node(), n);
  819. }
  820. /**
  821. * @brief Parser for the "items" constraint (9.3.1.1) for JSON Schema
  822. * Draft2019_09 and prior.
  823. * https://json-schema.org/draft/2019-09/draft-handrews-json-schema-02
  824. * This constraint validates either the first N elements of an array JSON
  825. * instance with its own subschemas, or all elements of an array JSON instance
  826. * with its single subschema.
  827. *
  828. * @pre context.schema MUST satisfy the preconditions of either
  829. * {@see ConstraintFactory::prefixItems} or
  830. * {@see ConstraintFactory::additionalItems}.
  831. *
  832. * @param context The operating context of the schema parsing.
  833. *
  834. * @returns If the schema is an array, a TupleConstraint. If the schema is an
  835. * object, an AdditionalItemsConstraint.
  836. *
  837. * @throws {@see ConstraintFactory::prefixItems}
  838. * @throws {@see ConstraintFactory::additionalItems}
  839. */
  840. static pConstraint itemsTupleOrVector(detail::ParserContext<A> const & context) {
  841. if (context.schema.type() == adapter::Type::Array) {
  842. return prefixItems(context);
  843. }
  844. return std::make_unique<constraint::AdditionalItemsConstraint>(context.node(), 0);
  845. }
  846. /**
  847. * @brief Parser for the "unevaluatedItems" constraint (11.2). This constraint
  848. * validates every element of an array JSON instance that is not handled by
  849. * any other subschema of this schema's parent.
  850. * In terms of annotation, we flag instance paths as "Accept", "Reject", or
  851. * "Noop" - "unevaluatedItems" constraints will be run after all other
  852. * constraints, applying to every item that is labeled "Noop" (or was never
  853. * visited to get even that tag).
  854. *
  855. * @param context The operating context of the schema parsing.
  856. *
  857. * @returns An AdditionalPropertiesConstraint
  858. */
  859. static auto unevaluatedItems(detail::ParserContext<A> const & context) {
  860. return std::make_unique<constraint::UnevaluatedItemsConstraint>(context.node());
  861. }
  862. /**
  863. * @brief Parser for the "uniqueItems" constraint (6.4.3). This constraint
  864. * validates array JSON instances where no member of the array is repeated.
  865. * In other words: `std::set{instance}.size() == instance.size()`
  866. *
  867. * @pre context.schema MUST be a boolean
  868. *
  869. * @returns An "accept-all" constraint if the schema is "false", else a
  870. * UniqueItemsConstraint.
  871. *
  872. * @throws std::runtime_error if precondition #1 is broken
  873. */
  874. static pConstraint uniqueItems(detail::ParserContext<A> const & context) {
  875. EXPECT(context.schema.type() == adapter::Type::Boolean);
  876. if (not context.schema.as_boolean()) {
  877. return nullptr;
  878. }
  879. return std::make_unique<constraint::UniqueItemsConstraint>();
  880. }
  881. // SECTION: Object Constraints
  882. /**
  883. * @brief Parser for the "required" constraint (6.5.3) starting in Draft04.
  884. * In Draft03, the required keyword is a boolean property of subschemas, and
  885. * so must be evaluated by {@see ConstraintFactory::propertiesDraft3}.
  886. * This constraint validates object JSON instances MUST contain every property
  887. * in the schema array provided.
  888. *
  889. * @pre context.schema MUST be an array of strings
  890. *
  891. * @param context The operating context of the schema parsing.
  892. *
  893. * @returns A RequiredConstraint
  894. *
  895. * @throws std::runtime_error if precondition #1 is broken
  896. */
  897. static auto required(detail::ParserContext<A> const & context) {
  898. EXPECT(context.schema.type() == adapter::Type::Array);
  899. std::unordered_set<std::string> rval;
  900. for (auto subschema : context.schema.as_array()) {
  901. EXPECT(subschema.type() == adapter::Type::String);
  902. rval.insert(subschema.as_string());
  903. }
  904. return std::make_unique<constraint::RequiredConstraint>(rval);
  905. }
  906. /**
  907. * @brief Parser for the "minProperties" constraint (6.5.2). This constraint
  908. * validates object JSON instances have a length <= context.schema.
  909. *
  910. * @pre context.schema MUST be an integer
  911. * @pre context.schema >= 0
  912. *
  913. * @param context The operating context of the schema parsing.
  914. *
  915. * @returns A MinPropertiesConstraint
  916. *
  917. * @throws If the contained value is not interpretable as an integer
  918. */
  919. static auto minProperties(detail::ParserContext<A> const & context) {
  920. EXPECT(context.schema.type() == adapter::Type::Integer ||
  921. context.schema.type() == adapter::Type::Number);
  922. return std::make_unique<constraint::MinPropertiesConstraint>(context.schema.as_integer());
  923. }
  924. /**
  925. * @brief Parser for the "maxProperties" constraint (6.5.1). This constraint
  926. * validates object JSON instances have a length <= context.schema.
  927. *
  928. * @pre context.schema MUST be an integer
  929. * @pre context.schema >= 0
  930. *
  931. * @param context The operating context of the schema parsing.
  932. *
  933. * @returns A MaxPropertiesConstraint
  934. *
  935. * @throws If the contained value is not interpretable as an integer
  936. */
  937. static auto maxProperties(detail::ParserContext<A> const & context) {
  938. EXPECT(context.schema.type() == adapter::Type::Integer ||
  939. context.schema.type() == adapter::Type::Number);
  940. return std::make_unique<constraint::MaxPropertiesConstraint>(context.schema.as_integer());
  941. }
  942. /**
  943. * @brief Parser for the "patternProperties" constraint (10.3.2.2). This
  944. * constraint validates an object JSON instance where each key in the instance
  945. * is checked against each of the ECMA-262 compatible regular expression keys
  946. * in this constraint, and validated against the subschema of that pattern if
  947. * matched. EVERY subschema whose pattern matches is validated against, so the
  948. * order does not strictly matter.
  949. *
  950. * This function does not attempt to compile the regular expression(s),
  951. * meaning that if the pattern is not a valid regex, it will fail at a later
  952. * point.
  953. *
  954. * @pre context.schema is an object
  955. *
  956. * @param context The operating context of the schema parsing.
  957. *
  958. * @returns A PatternPropertiesConstraint
  959. *
  960. * @throws std::runtime_error if precondition #1 is broken
  961. */
  962. static auto patternProperties(detail::ParserContext<A> const & context) {
  963. EXPECT(context.schema.type() == adapter::Type::Object);
  964. std::vector<std::pair<std::string, schema::Node const *>> rval;
  965. for (auto [prop, subschema] : context.schema.as_object()) {
  966. rval.emplace_back(prop, context.child(subschema, prop).node());
  967. }
  968. return std::make_unique<constraint::PatternPropertiesConstraint>(rval);
  969. }
  970. /**
  971. * @brief Parser for the "properties" constraint (10.3.2.1) for JSON Schema
  972. * Draft04 and up. This constraint validates an object JSON instance where if
  973. * a key in the instance is in this constraint, then the value is validated
  974. * against the subschema.
  975. *
  976. * @pre context.schema is an object
  977. *
  978. * @param context The operating context of the schema parsing.
  979. *
  980. * @returns A PropertiesConstraint
  981. *
  982. * @throws std::runtime_error if precondition #1 is broken
  983. */
  984. static auto properties(detail::ParserContext<A> const & context) {
  985. EXPECT(context.schema.type() == adapter::Type::Object);
  986. std::map<std::string, schema::Node const *> rval;
  987. for (auto [prop, subschema] : context.schema.as_object()) {
  988. rval.emplace(prop, context.child(subschema, prop).node());
  989. }
  990. return std::make_unique<constraint::PropertiesConstraint>(rval);
  991. }
  992. /**
  993. * @brief Parser for the "properties" constraint (5.2) for JSON Schema
  994. * Draft03. This constraint validates an object JSON instance where if a key
  995. * in the instance is in this constraint, then the value is validated against
  996. * the subschema.
  997. *
  998. * The Draft03 version of this method differs from the general version because
  999. * of the way that the "required" keyword is handled in Draft03, vs others.
  1000. * In Draft03, "required" is a boolean field, that may be placed in each
  1001. * subschema of the properties constraint.
  1002. * There would be two possible ways to handle this:
  1003. * 1) Implement a constraint like "MustBeVisitedConstraint", and make it so
  1004. * the ValidationVisitor will look-forward into properties constraints to
  1005. * check for its presence.
  1006. * 2) During Schema parsing, scan the children of the properties constraint
  1007. * for the required keyword. If present, add a RequiredConstraint in our
  1008. * output.
  1009. *
  1010. * @pre context.schema is an object
  1011. *
  1012. * @param context The operating context of the schema parsing.
  1013. *
  1014. * @returns A PropertiesConstraint
  1015. *
  1016. * @throws std::runtime_error if precondition #1 is broken
  1017. */
  1018. static pConstraint propertiesDraft3(detail::ParserContext<A> const & context) {
  1019. EXPECT(context.schema.type() == adapter::Type::Object);
  1020. std::unordered_set<std::string> required;
  1021. for (auto [prop, subschema] : context.schema.as_object()) {
  1022. EXPECT(subschema.type() == adapter::Type::Object);
  1023. if (auto sub = subschema.as_object();
  1024. sub.contains("required") && sub["required"].as_boolean()) {
  1025. required.insert(prop);
  1026. }
  1027. }
  1028. if (required.empty()) {
  1029. return properties(context);
  1030. }
  1031. std::vector<pConstraint> rval;
  1032. rval.push_back(properties(context));
  1033. rval.push_back(std::make_unique<constraint::RequiredConstraint>(std::move(required)));
  1034. return std::make_unique<constraint::AllOfConstraint>(std::move(rval));
  1035. }
  1036. /**
  1037. * @brief Parser for the "propertyNames" constraint (10.3.2.4). This
  1038. * constraint validates the keys of an object JSON instance against a
  1039. * subschema, the values of the object are ignored.
  1040. *
  1041. * @param context The operating context of the schema parsing.
  1042. *
  1043. * @returns A PropertyNamesConstraint
  1044. */
  1045. static auto propertyNames(detail::ParserContext<A> const & context) {
  1046. return std::make_unique<constraint::PropertyNamesConstraint>(context.node());
  1047. }
  1048. /**
  1049. * @brief Parser for the "unevaluatedProperties" constraint (11.3). This
  1050. * constraint validates every element of an object JSON instance that is not
  1051. * handled by any other subschema of this schema's parent.
  1052. * In terms of annotation, we flag instance paths as "Accept", "Reject", or
  1053. * "Noop" - "unevaluatedProperties" constraints will be run after all other
  1054. * constraints, applying to every property that is labeled "Noop" (or was
  1055. * never visited to get even that tag).
  1056. *
  1057. * @param context The operating context of the schema parsing.
  1058. *
  1059. * @returns An AdditionalPropertiesConstraint
  1060. */
  1061. static auto unevaluatedProperties(detail::ParserContext<A> const & context) {
  1062. return std::make_unique<constraint::UnevaluatedPropertiesConstraint>(context.node());
  1063. }
  1064. /**
  1065. * @brief Parser for the "additionalProperties" constraint (10.3.2.3). This
  1066. * constraint validates every element of an object JSON instance that is not
  1067. * handled by a "properties" or "patternProperties" constraint in the same
  1068. * parent schema.
  1069. *
  1070. * Constrast this with the "unevaluatedProperties" of Draft2019_09, which is
  1071. * able to investigate various complex interactions and nested schemas.
  1072. *
  1073. * @param context The operating context of the schema parsing.
  1074. *
  1075. * @returns An AdditionalPropertiesConstraint
  1076. */
  1077. static auto additionalProperties(detail::ParserContext<A> const & context) {
  1078. std::unordered_set<std::string> properties;
  1079. std::vector<std::string> patterns;
  1080. Object const & parent = *context.parent;
  1081. if (parent.contains("properties")) {
  1082. for (auto [key, _] : parent["properties"].as_object()) {
  1083. properties.insert(key);
  1084. }
  1085. }
  1086. if (parent.contains("patternProperties")) {
  1087. for (auto [key, _] : parent["patternProperties"].as_object()) {
  1088. patterns.push_back(key);
  1089. }
  1090. }
  1091. using C = constraint::AdditionalPropertiesConstraint; // Otherwise - the formatting is ugly
  1092. // Prior to Draft06, boolean schemas were not allowed in a general context,
  1093. // they were instead reserved for the "additionalItems" and
  1094. // "additionalProperties" keywords.
  1095. if (context.vocab->version() < schema::Version::Draft06 &&
  1096. context.schema.type() == adapter::Type::Boolean) {
  1097. return std::make_unique<C>(context.always(), properties, patterns);
  1098. }
  1099. return std::make_unique<C>(context.node(), properties, patterns);
  1100. }
  1101. /**
  1102. * @brief Parser for the "dependencies" constraint (6.5.7) until JSON Schema
  1103. * Draft2019_09
  1104. * (https://json-schema.org/draft-07/draft-handrews-json-schema-validation-01)
  1105. * This constraint creates an if-then relationship where "if property X exists
  1106. * in the instance, then we must validate schema Y (object) or properties Y...
  1107. * must also exist (array)".
  1108. * It is not required for every key in this schema to be contained within the
  1109. * instance being validated.
  1110. *
  1111. * In Draft03, we additionally permit
  1112. * In Draft2019_09, this was split into the "dependentSchemas" and
  1113. * "dependentRequired" keyword.
  1114. *
  1115. * @pre context.schema MUST be an object
  1116. * @pre all object values in context.schema are valid JSON Schemas, or a
  1117. * lists of strings
  1118. *
  1119. * @param context The operating context of the schema parsing.
  1120. *
  1121. * @returns A DependenciesConstraint
  1122. *
  1123. * @throws std::runtime_error if precondition #1 is broken
  1124. * @throws if precondition #2 is broken
  1125. */
  1126. static auto dependencies(detail::ParserContext<A> const & context) {
  1127. EXPECT(context.schema.type() == adapter::Type::Object);
  1128. std::map<std::string, schema::Node const *> schemas;
  1129. std::map<std::string, std::unordered_set<std::string>> required;
  1130. for (auto [prop, subschema] : context.schema.as_object()) {
  1131. if (subschema.type() == adapter::Type::Array) {
  1132. // Option 1) dependentRequired
  1133. for (auto key : subschema.as_array()) {
  1134. EXPECT(key.type() == adapter::Type::String);
  1135. required[prop].insert(key.as_string());
  1136. }
  1137. } else if (context.vocab->version() <= schema::Version::Draft03 &&
  1138. subschema.type() == adapter::Type::String) {
  1139. // Option 2) Special single-element dependentRequired in Draft03
  1140. required[prop].insert(subschema.as_string());
  1141. } else {
  1142. // Option 3) dependentSchemas
  1143. schemas.emplace(prop, context.child(subschema, prop).node());
  1144. }
  1145. }
  1146. return std::make_unique<constraint::DependenciesConstraint>(schemas, required);
  1147. }
  1148. /**
  1149. * @brief Parser for the "dependentSchemas" constraint (10.2.2.4) for
  1150. * JSON Schema Draft2019_09 and up. This constraint creates an if-then
  1151. * relationship where "if property X exists in the instance, then we must
  1152. * validate schema Y". It is not required for every key in this schema to be
  1153. * contained within the instance being validated.
  1154. *
  1155. * Before Draft2019_09, this was part of the "dependencies" keyword, along
  1156. * with "dependentRequired".
  1157. *
  1158. * @pre context.schema MUST be an object
  1159. * @pre all object values in context.schema are lists of strings
  1160. *
  1161. * @param context The operating context of the schema parsing.
  1162. *
  1163. * @returns A DependenciesConstraint
  1164. *
  1165. * @throws std::runtime_error if precondition #1 is broken
  1166. * @throws if precondition #2 is broken
  1167. */
  1168. static auto dependentSchemas(detail::ParserContext<A> const & context) {
  1169. EXPECT(context.schema.type() == adapter::Type::Object);
  1170. std::map<std::string, schema::Node const *> rval;
  1171. for (auto [prop, subschema] : context.schema.as_object()) {
  1172. rval.emplace(prop, context.child(subschema, prop).node());
  1173. }
  1174. return std::make_unique<constraint::DependenciesConstraint>(rval);
  1175. }
  1176. /**
  1177. * @brief Parser for the "dependentRequired" constraint (6.5.4) for
  1178. * JSON Schema Draft2019_09 and up. This constraint creates an if-then
  1179. * relationship where "if property X exists in the instance, properties Y...
  1180. * must also exist". It is not required for every key in this schema to be
  1181. * contained within the instance being validated.
  1182. *
  1183. * Before Draft2019_09, this was part of the "dependencies" keyword, along
  1184. * with "dependentSchemas".
  1185. *
  1186. * @pre context.schema MUST be an object
  1187. * @pre all object values in context.schema are valid JSON Schemas
  1188. *
  1189. * @param context The operating context of the schema parsing.
  1190. *
  1191. * @returns A DependenciesConstraint
  1192. *
  1193. * @throws std::runtime_error if any preconditions are broken
  1194. */
  1195. static auto dependentRequired(detail::ParserContext<A> const & context) {
  1196. EXPECT(context.schema.type() == adapter::Type::Object);
  1197. std::map<std::string, std::unordered_set<std::string>> rval;
  1198. for (auto [prop, subschema] : context.schema.as_object()) {
  1199. EXPECT(subschema.type() == adapter::Type::Array);
  1200. for (auto key : subschema.as_array()) {
  1201. EXPECT(key.type() == adapter::Type::String);
  1202. rval[prop].insert(key.as_string());
  1203. }
  1204. }
  1205. return std::make_unique<constraint::DependenciesConstraint>(rval);
  1206. }
  1207. };
  1208. }