constraint.h 51 KB

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