constraint.h 52 KB

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