constraint.h 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  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::EnumConstraint rval;
  422. rval.enumeration.push_back(context.schema.freeze());
  423. return ptr(rval);
  424. }
  425. /**
  426. * @brief Parser for a "allOf" constraint (10.2.1.1). This constraint
  427. * validates that all of the underlying schemas validate the instance.
  428. *
  429. * @pre context.schema is an array
  430. *
  431. * @param context The operating context of the schema parsing.
  432. *
  433. * @returns A AllOfConstraint
  434. *
  435. * @throws std::runtime_error if precondition #1 is broken
  436. */
  437. static auto allOf(detail::ParserContext<A> const & context) {
  438. EXPECT(context.schema.type() == adapter::Type::Array);
  439. std::vector<constraint::SubConstraint> rval;
  440. for (auto const & [index, subschema] : detail::enumerate(context.schema.as_array())) {
  441. rval.push_back(context.child(subschema, index).node());
  442. }
  443. return ptr(constraint::AllOfConstraint{std::move(rval)});
  444. }
  445. /**
  446. * @brief Parser for a "anyOf" constraint (10.2.1.2). This constraint
  447. * validates that any of the underlying schemas validate the instance.
  448. *
  449. * @pre context.schema is an array
  450. *
  451. * @param context The operating context of the schema parsing.
  452. *
  453. * @returns A AnyOfConstraint
  454. *
  455. * @throws std::runtime_error if precondition #1 is broken
  456. */
  457. static auto anyOf(detail::ParserContext<A> const & context) {
  458. EXPECT(context.schema.type() == adapter::Type::Array);
  459. std::vector<constraint::SubConstraint> rval;
  460. for (auto const & [index, subschema] : detail::enumerate(context.schema.as_array())) {
  461. rval.push_back(context.child(subschema, index).node());
  462. }
  463. return ptr(constraint::AnyOfConstraint{std::move(rval)});
  464. }
  465. /**
  466. * @brief Parser for a "oneOf" constraint (10.2.1.3). This constraint
  467. * validates that exactly one of the underlying schemas validate the instance.
  468. *
  469. * @pre context.schema is an array
  470. *
  471. * @param context The operating context of the schema parsing.
  472. *
  473. * @returns A OneOfConstraint
  474. *
  475. * @throws std::runtime_error if precondition #1 is broken
  476. */
  477. static auto oneOf(detail::ParserContext<A> const & context) {
  478. EXPECT(context.schema.type() == adapter::Type::Array);
  479. std::vector<schema::Node const *> rval;
  480. for (auto const & [index, subschema] : detail::enumerate(context.schema.as_array())) {
  481. rval.push_back(context.child(subschema, index).node());
  482. }
  483. return ptr(constraint::OneOfConstraint{rval});
  484. }
  485. /**
  486. * @brief Parser for a "not" constraint (10.2.1.4). This constraint inverts
  487. * the acceptance of the underlying schema.
  488. *
  489. * @param context The operating context of the schema parsing.
  490. *
  491. * @returns A NotConstraint
  492. */
  493. static auto isNot(detail::ParserContext<A> const & context) {
  494. return ptr(constraint::NotConstraint{context.node()});
  495. }
  496. // SECTION: Numeric Constraints
  497. /**
  498. * @brief Parser for the "minimum" constraint (6.2.4). This constraint
  499. * validates numberic JSON instances where `instance >= context.schema`
  500. * Before Draft06, this constraint must test for/evaluate the neighbor keyword
  501. * "exclusiveMinimum", which is a boolean.
  502. * Starting in Draft06, the "exclusiveMinimum" constraint exists separately,
  503. * and this constraint represents "inclusive minimum".
  504. *
  505. * @param context The operating context of the schema parsing.
  506. *
  507. * @returns A MinimumConstraint
  508. *
  509. * @throws If the contained value is not interpretable as a number
  510. * @throws std::runtime_error if version < Draft06 AND exclusiveMinimum exists
  511. * and is not a boolean.
  512. */
  513. static auto minimum(detail::ParserContext<A> const & context) {
  514. double value = context.schema.as_number();
  515. if (context.vocab->version() < schema::Version::Draft06 &&
  516. context.parent->contains("exclusiveMinimum")) {
  517. auto exclusive = (*context.parent)["exclusiveMinimum"];
  518. EXPECT(exclusive.type() == adapter::Type::Boolean);
  519. return ptr(constraint::MinimumConstraint{value, exclusive.as_boolean()});
  520. }
  521. return ptr(constraint::MinimumConstraint{value, false});
  522. }
  523. /**
  524. * @brief Parser for the "exclusiveMinimum" constraint (6.2.5) for JSON Schema
  525. * Draft06 and up. This constraint validates numberic JSON instances where
  526. * `instance > context.schema`
  527. *
  528. * @param context The operating context of the schema parsing.
  529. *
  530. * @returns A MinimumConstraint
  531. *
  532. * @throws If the contained value is not interpretable as a number
  533. */
  534. static pConstraint exclusiveMinimum(detail::ParserContext<A> const & context) {
  535. double value = context.schema.as_number();
  536. return ptr(constraint::MinimumConstraint{value, true});
  537. }
  538. /**
  539. * @brief Parser for the "maximum" constraint (6.2.2). This constraint
  540. * validates numberic JSON instances where `instance <= context.schema`
  541. * Before Draft06, this constraint must test for/evaluate the neighbor keyword
  542. * "exclusiveMaximum", which is a boolean.
  543. * Starting in Draft06, the "exclusiveMaximum" constraint exists separately,
  544. * and this constraint represents "inclusive maximum".
  545. *
  546. * @param context The operating context of the schema parsing.
  547. *
  548. * @returns A MaximumConstraint
  549. *
  550. * @throws If the contained value is not interpretable as a number
  551. * @throws std::runtime_error if version < Draft06 AND exclusiveMaximum exists
  552. * and is not a boolean.
  553. */
  554. static auto maximum(detail::ParserContext<A> const & context) {
  555. double value = context.schema.as_number();
  556. if (context.vocab->version() < schema::Version::Draft06 &&
  557. context.parent->contains("exclusiveMaximum")) {
  558. auto exclusive = (*context.parent)["exclusiveMaximum"];
  559. EXPECT(exclusive.type() == adapter::Type::Boolean);
  560. return ptr(constraint::MaximumConstraint{value, exclusive.as_boolean()});
  561. }
  562. return ptr(constraint::MaximumConstraint{value, false});
  563. }
  564. /**
  565. * @brief Parser for the "exclusiveMaximum" constraint (6.2.3) for JSON Schema
  566. * Draft06 and up. This constraint validates numberic JSON instances where
  567. * `instance < context.schema`
  568. *
  569. * @param context The operating context of the schema parsing.
  570. *
  571. * @returns A MaximumConstraint
  572. *
  573. * @throws If the contained value is not interpretable as a number
  574. */
  575. static pConstraint exclusiveMaximum(detail::ParserContext<A> const & context) {
  576. double value = context.schema.as_number();
  577. return ptr(constraint::MaximumConstraint{value, true});
  578. }
  579. /**
  580. * @brief Parser for the "multipleOf" constraint (6.2.1) for JSON Schema
  581. * Draft04 and up. In Draft03 this covers the "divisibleBy" constraint (5.24).
  582. * This constraint validates numeric JSON instances where
  583. * `instance / context.schema` is a whole number. Because of differences in
  584. * handling of numbers between C++, Python, JavaScript, etc. there are some
  585. * edge cases which cannot be properly handled.
  586. *
  587. * @pre context.schema matches { "type": "number" }
  588. * @pre context.schema.as_number() > 0
  589. *
  590. * @param context The operating context of the schema parsing.
  591. *
  592. * @returns A MultipleOfConstraint
  593. *
  594. * @throws If the contained value is not interpretable as a number
  595. */
  596. static auto multipleOf(detail::ParserContext<A> const & context) {
  597. double value = context.schema.as_number();
  598. return ptr(constraint::MultipleOfConstraint{value});
  599. }
  600. // SECTION: String Constraints
  601. /**
  602. * @brief Parser for the "minLength" constraint (6.3.2). This constraint
  603. * validates string JSON instances has a length >= context.schema, as per
  604. * RFC 8259.
  605. *
  606. * @pre context.schema MUST be an integer
  607. * @pre context.schema >= 0
  608. *
  609. * @param context The operating context of the schema parsing.
  610. *
  611. * @returns A MinLengthConstraint
  612. *
  613. * @throws If the contained value is not interpretable as an integer
  614. */
  615. static auto minLength(detail::ParserContext<A> const & context) {
  616. EXPECT(context.schema.type() == adapter::Type::Integer ||
  617. context.schema.type() == adapter::Type::Number);
  618. return ptr(constraint::MinLengthConstraint{context.schema.as_integer()});
  619. }
  620. /**
  621. * @brief Parser for the "maxLength" constraint (6.3.1). This constraint
  622. * validates string JSON instances have a length <= context.schema, as per
  623. * RFC 8259.
  624. *
  625. * @pre context.schema MUST be an integer
  626. * @pre context.schema >= 0
  627. *
  628. * @param context The operating context of the schema parsing.
  629. *
  630. * @returns A MaxLengthConstraint
  631. *
  632. * @throws If the contained value is not interpretable as an integer
  633. */
  634. static auto maxLength(detail::ParserContext<A> const & context) {
  635. EXPECT(context.schema.type() == adapter::Type::Integer ||
  636. context.schema.type() == adapter::Type::Number);
  637. return ptr(constraint::MaxLengthConstraint{context.schema.as_integer()});
  638. }
  639. /**
  640. * @brief Parser for the "pattern" constraint (6.3.3). This constraint
  641. * validates string JSON instances match an ECMA-262 compatible regular
  642. * expression.
  643. *
  644. * This function does not attempt to compile the regular expression,
  645. * meaning that if the pattern is not a valid regex, it will fail at a later
  646. * point.
  647. *
  648. * @pre context.schema MUST be a string
  649. *
  650. * @param context The operating context of the schema parsing.
  651. *
  652. * @returns A PatternConstraint
  653. *
  654. * @throws If the contained value is not interpretable as a string
  655. */
  656. static auto pattern(detail::ParserContext<A> const & context) {
  657. return ptr(constraint::PatternConstraint{context.schema.as_string()});
  658. }
  659. /**
  660. * @brief Parser for the "format" constraint, which validates string JSON
  661. * instances against one of several pre-defined formats that either would
  662. * be unnecessarily complicated to represent as PatternConstraint, prone to
  663. * user-error when done so, or cannot be represented as regular expressions
  664. * at all.
  665. *
  666. * @pre context.schema MUST be a string
  667. *
  668. * @param context The operating context of the schema parsing.
  669. *
  670. * @returns A FormatConstraint, if the vocabulary enabled "format assertions",
  671. * then this constraint will actually validate the JSON instance. Otherwise,
  672. * it simply annotates that the field is expected to match the format.
  673. *
  674. * @throws If the contained value is not interpretable as a string
  675. */
  676. static auto format(detail::ParserContext<A> const & context) {
  677. return ptr(constraint::FormatConstraint{context.schema.as_string(),
  678. context.vocab->is_format_assertion()});
  679. }
  680. // SECTION: Array Constraints
  681. /**
  682. * @brief Parser for the "contains" constraint (10.3.1.3, 6.4.4, 6.4.5). This
  683. * constraint is divided between three different keywords.
  684. * The "contains" keyword acts as a subschema, and is required for parsing.
  685. * "minContains" and "maxContains" act as boundaries on the number of matches,
  686. * such that the number of array elements matching the "contains" schema is at
  687. * least "minContains" and at most "maxContains".
  688. *
  689. * If "minContains" is null, then it is the equivalent of 1.
  690. * A "minContains" value of zero is only meaningful in the context of
  691. * setting an upper-bound.
  692. * If "maxContains" is null, then it is the equivalent of INFINITY
  693. *
  694. * @pre context.schema MUST be a valid JSON schema
  695. * @pre context.parent["maxContains"] is null OR an integer >= 0
  696. * @pre context.parent["minContains"] is null OR an integer >= 0
  697. *
  698. * @param context The operating context of the schema parsing.
  699. *
  700. * @returns A ContainsConstraint, with optional minimum and maximum matching
  701. */
  702. static auto contains(detail::ParserContext<A> const & context) {
  703. if (context.vocab->version() < schema::Version::Draft2019_09) {
  704. return ptr(constraint::ContainsConstraint{context.node()});
  705. }
  706. std::optional<size_t> maximum;
  707. std::optional<size_t> minimum;
  708. if (context.parent->contains("maxContains")) {
  709. maximum = (*context.parent)["maxContains"].as_integer();
  710. }
  711. if (context.parent->contains("minContains")) {
  712. minimum = (*context.parent)["minContains"].as_integer();
  713. }
  714. return ptr(constraint::ContainsConstraint{context.node(), minimum, maximum});
  715. }
  716. /**
  717. * @brief Parser for the "minItems" constraint (6.4.2). This constraint
  718. * validates array JSON instances have a length <= context.schema.
  719. *
  720. * @pre context.schema MUST be an integer
  721. * @pre context.schema >= 0
  722. *
  723. * @param context The operating context of the schema parsing.
  724. *
  725. * @returns A MinItemsConstraint
  726. *
  727. * @throws If the contained value is not interpretable as an integer
  728. */
  729. static auto minItems(detail::ParserContext<A> const & context) {
  730. EXPECT(context.schema.type() == adapter::Type::Integer ||
  731. context.schema.type() == adapter::Type::Number);
  732. return ptr(constraint::MinItemsConstraint{context.schema.as_integer()});
  733. }
  734. /**
  735. * @brief Parser for the "maxItems" constraint (6.4.1). This constraint
  736. * validates array JSON instances have a length <= context.schema.
  737. *
  738. * @pre context.schema MUST be an integer
  739. * @pre context.schema >= 0
  740. *
  741. * @param context The operating context of the schema parsing.
  742. *
  743. * @returns A MaxItemsConstraint
  744. *
  745. * @throws If the contained value is not interpretable as an integer
  746. */
  747. static auto maxItems(detail::ParserContext<A> const & context) {
  748. EXPECT(context.schema.type() == adapter::Type::Integer ||
  749. context.schema.type() == adapter::Type::Number);
  750. return ptr(constraint::MaxItemsConstraint{context.schema.as_integer()});
  751. }
  752. /**
  753. * @brief Parser for the "prefixItems" constraint (10.3.1.1) for JSON Schema
  754. * Draft2020_12 and up. This constraint validates the first N elements of an
  755. * array JSON instance with its own subschemas.
  756. *
  757. * @pre context.schema MUST be an array
  758. * @pre context.schema MUST have at least 1 element
  759. * @pre each element of context.schema MUST be a valid JSON Schema
  760. *
  761. * @param context The operating context of the schema parsing.
  762. *
  763. * @returns A TupleConstraint
  764. *
  765. * @throws std::runtime_error if preconditions #1 or #2 are broken
  766. * @throws if precondition #3 is broken
  767. */
  768. static auto prefixItems(detail::ParserContext<A> const & context) {
  769. EXPECT(context.schema.type() == adapter::Type::Array);
  770. std::vector<schema::Node const *> rval;
  771. for (auto const & [index, subschema] : detail::enumerate(context.schema.as_array())) {
  772. rval.push_back(context.child(subschema, index).node());
  773. }
  774. return ptr(constraint::TupleConstraint{rval});
  775. }
  776. /**
  777. * @brief Parser for the "additionalItems" constraint (9.3.1.1) for JSON
  778. * Schema Draft2019_09 and prior, and the "items" constraint (10.3.1.2) for
  779. * JSON Schema Draft2020_12 and up.
  780. * This constraint validates an array JSON instance starting from the N-th
  781. * element, as determined by the "items" schema (<= Draft2019_09), or the
  782. * "prefixItems" schema (>= Draft2020_12).
  783. *
  784. * @pre context.schema MUST be a valid JSON Schema (including boolean schema)
  785. *
  786. * @param context The operating context of the schema parsing.
  787. *
  788. * @returns An AdditionalItemsConstraint, unless the special condition
  789. * described below is met.
  790. *
  791. * @throws if the precondition is broken
  792. */
  793. static pConstraint additionalItems(detail::ParserContext<A> const & context) {
  794. std::string const prefix =
  795. context.vocab->version() >= schema::Version::Draft2020_12 ? "prefixItems" : "items";
  796. auto const & parent = *context.parent;
  797. // Before Draft 2020-12, the "items" could be either a subschema or a tuple.
  798. // When not provided, we therefore treat it as an "accept-all" schema, and
  799. // thus will never have additionalItems to process. Similarly - if it is an
  800. // Object, then it must act on all items.
  801. if (context.vocab->version() < schema::Version::Draft2020_12 &&
  802. (not parent.contains(prefix) || parent[prefix].type() == adapter::Type::Object)) {
  803. return nullptr;
  804. }
  805. size_t const n = parent[prefix].array_size();
  806. // Prior to Draft06, boolean schemas were not allowed in a general context,
  807. // they were instead reserved for the "additionalItems" and
  808. // "additionalProperties" keywords.
  809. if (context.vocab->version() < schema::Version::Draft06 &&
  810. context.schema.type() == adapter::Type::Boolean) {
  811. return ptr(constraint::AdditionalItemsConstraint{context.always(), n});
  812. }
  813. return ptr(constraint::AdditionalItemsConstraint{context.node(), n});
  814. }
  815. /**
  816. * @brief Parser for the "items" constraint (9.3.1.1) for JSON Schema
  817. * Draft2019_09 and prior.
  818. * https://json-schema.org/draft/2019-09/draft-handrews-json-schema-02
  819. * This constraint validates either the first N elements of an array JSON
  820. * instance with its own subschemas, or all elements of an array JSON instance
  821. * with its single subschema.
  822. *
  823. * @pre context.schema MUST satisfy the preconditions of either
  824. * {@see ConstraintFactory::prefixItems} or
  825. * {@see ConstraintFactory::additionalItems}.
  826. *
  827. * @param context The operating context of the schema parsing.
  828. *
  829. * @returns If the schema is an array, a TupleConstraint. If the schema is an
  830. * object, an AdditionalItemsConstraint.
  831. *
  832. * @throws {@see ConstraintFactory::prefixItems}
  833. * @throws {@see ConstraintFactory::additionalItems}
  834. */
  835. static pConstraint itemsTupleOrVector(detail::ParserContext<A> const & context) {
  836. if (context.schema.type() == adapter::Type::Array) {
  837. return prefixItems(context);
  838. }
  839. return ptr(constraint::AdditionalItemsConstraint{context.node(), 0});
  840. }
  841. /**
  842. * @brief Parser for the "unevaluatedItems" constraint (11.2). This constraint
  843. * validates every element of an array JSON instance that is not handled by
  844. * any other subschema of this schema's parent.
  845. * In terms of annotation, we flag instance paths as "Accept", "Reject", or
  846. * "Noop" - "unevaluatedItems" constraints will be run after all other
  847. * constraints, applying to every item that is labeled "Noop" (or was never
  848. * visited to get even that tag).
  849. *
  850. * @param context The operating context of the schema parsing.
  851. *
  852. * @returns An AdditionalPropertiesConstraint
  853. */
  854. static auto unevaluatedItems(detail::ParserContext<A> const & context) {
  855. return ptr(constraint::UnevaluatedItemsConstraint{context.node()});
  856. }
  857. /**
  858. * @brief Parser for the "uniqueItems" constraint (6.4.3). This constraint
  859. * validates array JSON instances where no member of the array is repeated.
  860. * In other words: `std::set{instance}.size() == instance.size()`
  861. *
  862. * @pre context.schema MUST be a boolean
  863. *
  864. * @returns An "accept-all" constraint if the schema is "false", else a
  865. * UniqueItemsConstraint.
  866. *
  867. * @throws std::runtime_error if precondition #1 is broken
  868. */
  869. static pConstraint uniqueItems(detail::ParserContext<A> const & context) {
  870. EXPECT(context.schema.type() == adapter::Type::Boolean);
  871. if (not context.schema.as_boolean()) {
  872. return nullptr;
  873. }
  874. return ptr(constraint::UniqueItemsConstraint{});
  875. }
  876. // SECTION: Object Constraints
  877. /**
  878. * @brief Parser for the "required" constraint (6.5.3) starting in Draft04.
  879. * In Draft03, the required keyword is a boolean property of subschemas, and
  880. * so must be evaluated by {@see ConstraintFactory::propertiesDraft3}.
  881. * This constraint validates object JSON instances MUST contain every property
  882. * in the schema array provided.
  883. *
  884. * @pre context.schema MUST be an array of strings
  885. *
  886. * @param context The operating context of the schema parsing.
  887. *
  888. * @returns A RequiredConstraint
  889. *
  890. * @throws std::runtime_error if precondition #1 is broken
  891. */
  892. static auto required(detail::ParserContext<A> const & context) {
  893. EXPECT(context.schema.type() == adapter::Type::Array);
  894. std::unordered_set<std::string> rval;
  895. for (auto subschema : context.schema.as_array()) {
  896. EXPECT(subschema.type() == adapter::Type::String);
  897. rval.insert(subschema.as_string());
  898. }
  899. return ptr(constraint::RequiredConstraint{rval});
  900. }
  901. /**
  902. * @brief Parser for the "minProperties" constraint (6.5.2). This constraint
  903. * validates object JSON instances have a length <= context.schema.
  904. *
  905. * @pre context.schema MUST be an integer
  906. * @pre context.schema >= 0
  907. *
  908. * @param context The operating context of the schema parsing.
  909. *
  910. * @returns A MinPropertiesConstraint
  911. *
  912. * @throws If the contained value is not interpretable as an integer
  913. */
  914. static auto minProperties(detail::ParserContext<A> const & context) {
  915. EXPECT(context.schema.type() == adapter::Type::Integer ||
  916. context.schema.type() == adapter::Type::Number);
  917. return ptr(constraint::MinPropertiesConstraint{context.schema.as_integer()});
  918. }
  919. /**
  920. * @brief Parser for the "maxProperties" constraint (6.5.1). This constraint
  921. * validates object JSON instances have a length <= context.schema.
  922. *
  923. * @pre context.schema MUST be an integer
  924. * @pre context.schema >= 0
  925. *
  926. * @param context The operating context of the schema parsing.
  927. *
  928. * @returns A MaxPropertiesConstraint
  929. *
  930. * @throws If the contained value is not interpretable as an integer
  931. */
  932. static auto maxProperties(detail::ParserContext<A> const & context) {
  933. EXPECT(context.schema.type() == adapter::Type::Integer ||
  934. context.schema.type() == adapter::Type::Number);
  935. return ptr(constraint::MaxPropertiesConstraint{context.schema.as_integer()});
  936. }
  937. /**
  938. * @brief Parser for the "patternProperties" constraint (10.3.2.2). This
  939. * constraint validates an object JSON instance where each key in the instance
  940. * is checked against each of the ECMA-262 compatible regular expression keys
  941. * in this constraint, and validated against the subschema of that pattern if
  942. * matched. EVERY subschema whose pattern matches is validated against, so the
  943. * order does not strictly matter.
  944. *
  945. * This function does not attempt to compile the regular expression(s),
  946. * meaning that if the pattern is not a valid regex, it will fail at a later
  947. * point.
  948. *
  949. * @pre context.schema is an object
  950. *
  951. * @param context The operating context of the schema parsing.
  952. *
  953. * @returns A PatternPropertiesConstraint
  954. *
  955. * @throws std::runtime_error if precondition #1 is broken
  956. */
  957. static auto patternProperties(detail::ParserContext<A> const & context) {
  958. EXPECT(context.schema.type() == adapter::Type::Object);
  959. std::vector<std::pair<std::string, schema::Node const *>> rval;
  960. for (auto [prop, subschema] : context.schema.as_object()) {
  961. rval.emplace_back(prop, context.child(subschema, prop).node());
  962. }
  963. return ptr(constraint::PatternPropertiesConstraint{rval});
  964. }
  965. /**
  966. * @brief Parser for the "properties" constraint (10.3.2.1) for JSON Schema
  967. * Draft04 and up. This constraint validates an object JSON instance where if
  968. * a key in the instance is in this constraint, then the value is validated
  969. * against the subschema.
  970. *
  971. * @pre context.schema is an object
  972. *
  973. * @param context The operating context of the schema parsing.
  974. *
  975. * @returns A PropertiesConstraint
  976. *
  977. * @throws std::runtime_error if precondition #1 is broken
  978. */
  979. static auto properties(detail::ParserContext<A> const & context) {
  980. EXPECT(context.schema.type() == adapter::Type::Object);
  981. std::map<std::string, schema::Node const *> rval;
  982. for (auto [prop, subschema] : context.schema.as_object()) {
  983. rval.emplace(prop, context.child(subschema, prop).node());
  984. }
  985. return ptr(constraint::PropertiesConstraint{rval});
  986. }
  987. /**
  988. * @brief Parser for the "properties" constraint (5.2) for JSON Schema
  989. * Draft03. This constraint validates an object JSON instance where if a key
  990. * in the instance is in this constraint, then the value is validated against
  991. * the subschema.
  992. *
  993. * The Draft03 version of this method differs from the general version because
  994. * of the way that the "required" keyword is handled in Draft03, vs others.
  995. * In Draft03, "required" is a boolean field, that may be placed in each
  996. * subschema of the properties constraint.
  997. * There would be two possible ways to handle this:
  998. * 1) Implement a constraint like "MustBeVisitedConstraint", and make it so
  999. * the ValidationVisitor will look-forward into properties constraints to
  1000. * check for its presence.
  1001. * 2) During Schema parsing, scan the children of the properties constraint
  1002. * for the required keyword. If present, add a RequiredConstraint in our
  1003. * output.
  1004. *
  1005. * @pre context.schema is an object
  1006. *
  1007. * @param context The operating context of the schema parsing.
  1008. *
  1009. * @returns A PropertiesConstraint
  1010. *
  1011. * @throws std::runtime_error if precondition #1 is broken
  1012. */
  1013. static pConstraint propertiesDraft3(detail::ParserContext<A> const & context) {
  1014. EXPECT(context.schema.type() == adapter::Type::Object);
  1015. std::unordered_set<std::string> required;
  1016. for (auto [prop, subschema] : context.schema.as_object()) {
  1017. EXPECT(subschema.type() == adapter::Type::Object);
  1018. if (auto sub = subschema.as_object();
  1019. sub.contains("required") && sub["required"].as_boolean()) {
  1020. required.insert(prop);
  1021. }
  1022. }
  1023. if (required.empty()) {
  1024. return properties(context);
  1025. }
  1026. std::vector<constraint::SubConstraint> rval;
  1027. rval.push_back(properties(context));
  1028. rval.push_back(ptr(constraint::RequiredConstraint{std::move(required)}));
  1029. return ptr(constraint::AllOfConstraint{std::move(rval)});
  1030. }
  1031. /**
  1032. * @brief Parser for the "propertyNames" constraint (10.3.2.4). This
  1033. * constraint validates the keys of an object JSON instance against a
  1034. * subschema, the values of the object are ignored.
  1035. *
  1036. * @param context The operating context of the schema parsing.
  1037. *
  1038. * @returns A PropertyNamesConstraint
  1039. */
  1040. static auto propertyNames(detail::ParserContext<A> const & context) {
  1041. return ptr(constraint::PropertyNamesConstraint{context.node()});
  1042. }
  1043. /**
  1044. * @brief Parser for the "unevaluatedProperties" constraint (11.3). This
  1045. * constraint validates every element of an object JSON instance that is not
  1046. * handled by any other subschema of this schema's parent.
  1047. * In terms of annotation, we flag instance paths as "Accept", "Reject", or
  1048. * "Noop" - "unevaluatedProperties" constraints will be run after all other
  1049. * constraints, applying to every property that is labeled "Noop" (or was
  1050. * never visited to get even that tag).
  1051. *
  1052. * @param context The operating context of the schema parsing.
  1053. *
  1054. * @returns An AdditionalPropertiesConstraint
  1055. */
  1056. static auto unevaluatedProperties(detail::ParserContext<A> const & context) {
  1057. return ptr(constraint::UnevaluatedPropertiesConstraint{context.node()});
  1058. }
  1059. /**
  1060. * @brief Parser for the "additionalProperties" constraint (10.3.2.3). This
  1061. * constraint validates every element of an object JSON instance that is not
  1062. * handled by a "properties" or "patternProperties" constraint in the same
  1063. * parent schema.
  1064. *
  1065. * Constrast this with the "unevaluatedProperties" of Draft2019_09, which is
  1066. * able to investigate various complex interactions and nested schemas.
  1067. *
  1068. * @param context The operating context of the schema parsing.
  1069. *
  1070. * @returns An AdditionalPropertiesConstraint
  1071. */
  1072. static auto additionalProperties(detail::ParserContext<A> const & context) {
  1073. std::unordered_set<std::string> properties;
  1074. std::vector<std::string> patterns;
  1075. auto const & parent = *context.parent;
  1076. if (parent.contains("properties")) {
  1077. for (auto [key, _] : parent["properties"].as_object()) {
  1078. properties.insert(key);
  1079. }
  1080. }
  1081. if (parent.contains("patternProperties")) {
  1082. for (auto [key, _] : parent["patternProperties"].as_object()) {
  1083. patterns.push_back(key);
  1084. }
  1085. }
  1086. using C = constraint::AdditionalPropertiesConstraint; // Otherwise - the formatting is ugly
  1087. // Prior to Draft06, boolean schemas were not allowed in a general context,
  1088. // they were instead reserved for the "additionalItems" and
  1089. // "additionalProperties" keywords.
  1090. if (context.vocab->version() < schema::Version::Draft06 &&
  1091. context.schema.type() == adapter::Type::Boolean) {
  1092. return ptr(C{context.always(), properties, patterns});
  1093. }
  1094. return ptr(C{context.node(), properties, patterns});
  1095. }
  1096. /**
  1097. * @brief Parser for the "dependencies" constraint (6.5.7) until JSON Schema
  1098. * Draft2019_09
  1099. * (https://json-schema.org/draft-07/draft-handrews-json-schema-validation-01)
  1100. * This constraint creates an if-then relationship where "if property X exists
  1101. * in the instance, then we must validate schema Y (object) or properties Y...
  1102. * must also exist (array)".
  1103. * It is not required for every key in this schema to be contained within the
  1104. * instance being validated.
  1105. *
  1106. * In Draft03, we additionally permit
  1107. * In Draft2019_09, this was split into the "dependentSchemas" and
  1108. * "dependentRequired" keyword.
  1109. *
  1110. * @pre context.schema MUST be an object
  1111. * @pre all object values in context.schema are valid JSON Schemas, or a
  1112. * lists of strings
  1113. *
  1114. * @param context The operating context of the schema parsing.
  1115. *
  1116. * @returns A DependenciesConstraint
  1117. *
  1118. * @throws std::runtime_error if precondition #1 is broken
  1119. * @throws if precondition #2 is broken
  1120. */
  1121. static auto dependencies(detail::ParserContext<A> const & context) {
  1122. EXPECT(context.schema.type() == adapter::Type::Object);
  1123. std::map<std::string, schema::Node const *> schemas;
  1124. std::map<std::string, std::unordered_set<std::string>> required;
  1125. for (auto [prop, subschema] : context.schema.as_object()) {
  1126. if (subschema.type() == adapter::Type::Array) {
  1127. // Option 1) dependentRequired
  1128. for (auto key : subschema.as_array()) {
  1129. EXPECT(key.type() == adapter::Type::String);
  1130. required[prop].insert(key.as_string());
  1131. }
  1132. } else if (context.vocab->version() <= schema::Version::Draft03 &&
  1133. subschema.type() == adapter::Type::String) {
  1134. // Option 2) Special single-element dependentRequired in Draft03
  1135. required[prop].insert(subschema.as_string());
  1136. } else {
  1137. // Option 3) dependentSchemas
  1138. schemas.emplace(prop, context.child(subschema, prop).node());
  1139. }
  1140. }
  1141. return ptr(constraint::DependenciesConstraint{schemas, required});
  1142. }
  1143. /**
  1144. * @brief Parser for the "dependentSchemas" constraint (10.2.2.4) for
  1145. * JSON Schema Draft2019_09 and up. This constraint creates an if-then
  1146. * relationship where "if property X exists in the instance, then we must
  1147. * validate schema Y". It is not required for every key in this schema to be
  1148. * contained within the instance being validated.
  1149. *
  1150. * Before Draft2019_09, this was part of the "dependencies" keyword, along
  1151. * with "dependentRequired".
  1152. *
  1153. * @pre context.schema MUST be an object
  1154. * @pre all object values in context.schema are lists of strings
  1155. *
  1156. * @param context The operating context of the schema parsing.
  1157. *
  1158. * @returns A DependenciesConstraint
  1159. *
  1160. * @throws std::runtime_error if precondition #1 is broken
  1161. * @throws if precondition #2 is broken
  1162. */
  1163. static auto dependentSchemas(detail::ParserContext<A> const & context) {
  1164. EXPECT(context.schema.type() == adapter::Type::Object);
  1165. std::map<std::string, schema::Node const *> rval;
  1166. for (auto [prop, subschema] : context.schema.as_object()) {
  1167. rval.emplace(prop, context.child(subschema, prop).node());
  1168. }
  1169. return ptr(constraint::DependenciesConstraint{rval});
  1170. }
  1171. /**
  1172. * @brief Parser for the "dependentRequired" constraint (6.5.4) for
  1173. * JSON Schema Draft2019_09 and up. This constraint creates an if-then
  1174. * relationship where "if property X exists in the instance, properties Y...
  1175. * must also exist". It is not required for every key in this schema to be
  1176. * contained within the instance being validated.
  1177. *
  1178. * Before Draft2019_09, this was part of the "dependencies" keyword, along
  1179. * with "dependentSchemas".
  1180. *
  1181. * @pre context.schema MUST be an object
  1182. * @pre all object values in context.schema are valid JSON Schemas
  1183. *
  1184. * @param context The operating context of the schema parsing.
  1185. *
  1186. * @returns A DependenciesConstraint
  1187. *
  1188. * @throws std::runtime_error if any preconditions are broken
  1189. */
  1190. static auto dependentRequired(detail::ParserContext<A> const & context) {
  1191. EXPECT(context.schema.type() == adapter::Type::Object);
  1192. std::map<std::string, std::unordered_set<std::string>> rval;
  1193. for (auto [prop, subschema] : context.schema.as_object()) {
  1194. EXPECT(subschema.type() == adapter::Type::Array);
  1195. for (auto key : subschema.as_array()) {
  1196. EXPECT(key.type() == adapter::Type::String);
  1197. rval[prop].insert(key.as_string());
  1198. }
  1199. }
  1200. return ptr(constraint::DependenciesConstraint{{}, rval});
  1201. }
  1202. };
  1203. }