constraint.h 53 KB

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