constraint.h 55 KB

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