constraint.h 51 KB

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