constraint.h 51 KB

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