constraint.h 55 KB

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