constraint.h 52 KB

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