constraint.h 52 KB

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