constraint.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. #pragma once
  2. #include <functional>
  3. #include <map>
  4. #include <memory>
  5. #include <set>
  6. #include <string_view>
  7. #include <unordered_map>
  8. #include <unordered_set>
  9. #include <jvalidate/constraint/array_constraint.h>
  10. #include <jvalidate/constraint/general_constraint.h>
  11. #include <jvalidate/constraint/number_constraint.h>
  12. #include <jvalidate/constraint/object_constraint.h>
  13. #include <jvalidate/constraint/string_constraint.h>
  14. #include <jvalidate/detail/expect.h>
  15. #include <jvalidate/detail/parser_context.h>
  16. #include <jvalidate/enum.h>
  17. #include <jvalidate/forward.h>
  18. namespace jvalidate {
  19. template <Adapter A> class ConstraintFactory {
  20. public:
  21. using pConstraint = std::unique_ptr<constraint::Constraint>;
  22. using Object = decltype(std::declval<A>().as_object());
  23. using MakeConstraint = std::function<pConstraint(detail::ParserContext<A> const &)>;
  24. template <typename V> using Versioned = std::map<schema::Version, V, std::greater<>>;
  25. template <typename V> using Keywords = std::unordered_map<std::string_view, V>;
  26. private:
  27. using Self = ConstraintFactory<A>;
  28. private:
  29. std::unordered_map<std::string_view, MakeConstraint> constraints_{
  30. {"additionalProperties", &Self::additionalProperties},
  31. {"enum", &Self::isInEnumuration},
  32. {"maxItems", &Self::maxItems},
  33. {"maxLength", &Self::maxLength},
  34. {"maximum", &Self::maximum},
  35. {"minItems", &Self::minItems},
  36. {"minLength", &Self::minLength},
  37. {"minimum", &Self::minimum},
  38. {"pattern", &Self::pattern},
  39. {"patternProperties", &Self::patternProperties},
  40. {"properties", &Self::properties},
  41. {"type", &Self::type},
  42. {"uniqueItems", &Self::uniqueItems},
  43. };
  44. std::unordered_map<std::string_view, Versioned<MakeConstraint>> versioned_constraints_{
  45. {"additionalItems",
  46. {{schema::Version::Draft04, &Self::additionalItems},
  47. {schema::Version::Draft2020_12, nullptr}}},
  48. {"allOf", {{schema::Version::Draft04, &Self::allOf}}},
  49. {"anyOf", {{schema::Version::Draft04, &Self::anyOf}}},
  50. {"const", {{schema::Version::Draft06, &Self::isConstant}}},
  51. {"contains", {{schema::Version::Draft06, &Self::contains}}},
  52. {"dependencies", {{schema::Version::Draft04, &Self::dependencies}}},
  53. {"dependentRequired", {{schema::Version::Draft2019_09, &Self::dependentRequired}}},
  54. {"dependentSchemas", {{schema::Version::Draft2019_09, &Self::dependentSchemas}}},
  55. {"divisibleBy",
  56. {{schema::Version::Draft04, &Self::multipleOf}, {schema::Version::Draft04, nullptr}}},
  57. {"exclusiveMaximum", {{schema::Version::Draft06, &Self::exclusiveMaximum}}},
  58. {"exclusiveMinimum", {{schema::Version::Draft06, &Self::exclusiveMinimum}}},
  59. {"format",
  60. {{schema::Version::Draft04, &Self::format}, {schema::Version::Draft2020_12, nullptr}}},
  61. {"if", {{schema::Version::Draft07, &Self::ifThenElse}}},
  62. {"items",
  63. {{schema::Version::Draft04, &Self::itemsTupleOrVector},
  64. {schema::Version::Draft2020_12, &Self::additionalItems}}},
  65. {"maxProperties", {{schema::Version::Draft04, &Self::maxProperties}}},
  66. {"minProperties", {{schema::Version::Draft04, &Self::minProperties}}},
  67. {"multipleOf", {{schema::Version::Draft04, &Self::multipleOf}}},
  68. {"not", {{schema::Version::Draft04, &Self::isNot}}},
  69. {"oneOf", {{schema::Version::Draft04, &Self::oneOf}}},
  70. {"prefixItems", {{schema::Version::Draft2020_12, &Self::prefixItems}}},
  71. {"propertyNames", {{schema::Version::Draft06, &Self::propertyNames}}},
  72. {"required", {{schema::Version::Draft04, &Self::required}}},
  73. {"unevaluatedItems", {{schema::Version::Draft2019_09, &Self::unevaluatedItems}}},
  74. {"unevaluatedProperties", {{schema::Version::Draft2019_09, &Self::unevaluatedProperties}}},
  75. };
  76. Keywords<Versioned<std::set<schema::Wraps>>> keywords_{
  77. {"$defs", {{schema::Version::Draft2019_09, {schema::Wraps::Object}}}},
  78. {"additionalItems",
  79. {{schema::Version::Draft04, {schema::Wraps::Schema}}, {schema::Version::Draft2020_12, {}}}},
  80. {"additionalProperties", {{schema::Version::Draft04, {schema::Wraps::Schema}}}},
  81. {"allOf", {{schema::Version::Draft04, {schema::Wraps::Array}}}},
  82. {"anyOf", {{schema::Version::Draft04, {schema::Wraps::Array}}}},
  83. {"definitions",
  84. {{schema::Version::Draft04, {schema::Wraps::Object}}, {schema::Version::Draft2019_09, {}}}},
  85. {"dependencies",
  86. {{schema::Version::Draft04, {schema::Wraps::Object}}, {schema::Version::Draft2019_09, {}}}},
  87. {"dependentSchemas", {{schema::Version::Draft2019_09, {schema::Wraps::Object}}}},
  88. {"else", {{schema::Version::Draft07, {schema::Wraps::Schema}}}},
  89. {"if", {{schema::Version::Draft07, {schema::Wraps::Schema}}}},
  90. {"items",
  91. {{schema::Version::Draft04, {schema::Wraps::Array, schema::Wraps::Schema}},
  92. {schema::Version::Draft2020_12, {schema::Wraps::Schema}}}},
  93. {"not", {{schema::Version::Draft04, {schema::Wraps::Schema}}}},
  94. {"oneOf", {{schema::Version::Draft04, {schema::Wraps::Array}}}},
  95. {"patternProperties", {{schema::Version::Draft04, {schema::Wraps::Object}}}},
  96. {"prefixItems", {{schema::Version::Draft2020_12, {schema::Wraps::Array}}}},
  97. {"properties", {{schema::Version::Draft04, {schema::Wraps::Object}}}},
  98. {"then", {{schema::Version::Draft07, {schema::Wraps::Schema}}}},
  99. {"unevaluatedItems", {{schema::Version::Draft2020_12, {schema::Wraps::Schema}}}},
  100. {"unevaluatedProperties", {{schema::Version::Draft2020_12, {schema::Wraps::Schema}}}},
  101. };
  102. public:
  103. ConstraintFactory() = default;
  104. explicit ConstraintFactory(
  105. Keywords<MakeConstraint> const & user_keywords,
  106. Keywords<Versioned<MakeConstraint>> const & user_versioned_keywords = {}) {
  107. constraints_.insert(constraints_.end(), user_keywords.begin(), user_keywords.end());
  108. versioned_constraints_.insert(versioned_constraints_.end(), user_versioned_keywords.begin(),
  109. user_versioned_keywords.end());
  110. }
  111. bool is_post_constraint(std::string_view key) const {
  112. return key == "unevaluatedItems" || key == "unevaluatedProperties";
  113. }
  114. Keywords<std::set<schema::Wraps>> keywords(schema::Version version) const {
  115. Keywords<std::set<schema::Wraps>> rval;
  116. for (auto const & [key, versions] : keywords_) {
  117. if (auto it = versions.lower_bound(version); it != versions.end()) {
  118. rval.emplace(key, it->second);
  119. }
  120. }
  121. return rval;
  122. }
  123. MakeConstraint operator()(std::string_view key, schema::Version version) const {
  124. if (auto it = constraints_.find(key); it != constraints_.end()) {
  125. return it->second;
  126. }
  127. if (auto it = versioned_constraints_.find(key); it != versioned_constraints_.end()) {
  128. if (auto vit = it->second.lower_bound(version); vit != it->second.end()) {
  129. return vit->second;
  130. }
  131. }
  132. return nullptr;
  133. }
  134. // SECTION: Untyped Constraints
  135. static auto type(detail::ParserContext<A> const & context) {
  136. static std::unordered_map<std::string_view, adapter::Type> const s_type_names{
  137. {"null", adapter::Type::Null}, {"boolean", adapter::Type::Boolean},
  138. {"integer", adapter::Type::Integer}, {"number", adapter::Type::Number},
  139. {"string", adapter::Type::String}, {"array", adapter::Type::Array},
  140. {"object", adapter::Type::Object},
  141. };
  142. auto to_type = [](std::string_view type) {
  143. EXPECT_M(s_type_names.contains(type), "Unknown type " << type);
  144. return s_type_names.at(type);
  145. };
  146. adapter::Type const type = context.schema.type();
  147. if (type == adapter::Type::String) {
  148. return std::make_unique<constraint::TypeConstraint>(to_type(context.schema.as_string()));
  149. }
  150. EXPECT(type == adapter::Type::Array);
  151. std::set<adapter::Type> types;
  152. for (auto subschema : context.schema.as_array()) {
  153. types.insert(to_type(subschema.as_string()));
  154. }
  155. return std::make_unique<constraint::TypeConstraint>(types);
  156. }
  157. static pConstraint ifThenElse(detail::ParserContext<A> const & context) {
  158. schema::Node const * then_ = context.fixed_schema(true);
  159. if (context.parent->contains("then")) {
  160. then_ = context.neighbor("then").node();
  161. }
  162. schema::Node const * else_ = context.fixed_schema(true);
  163. if (context.parent->contains("else")) {
  164. else_ = context.neighbor("else").node();
  165. }
  166. return std::make_unique<constraint::ConditionalConstraint>(context.node(), then_, else_);
  167. }
  168. static auto isInEnumuration(detail::ParserContext<A> const & context) {
  169. EXPECT(context.schema.type() == adapter::Type::Array);
  170. std::vector<std::unique_ptr<adapter::Const const>> rval;
  171. for (auto subschema : context.schema.as_array()) {
  172. rval.push_back(subschema.freeze());
  173. }
  174. return std::make_unique<constraint::EnumConstraint>(std::move(rval));
  175. }
  176. static auto isConstant(detail::ParserContext<A> const & context) {
  177. return std::make_unique<constraint::EnumConstraint>(context.schema.freeze());
  178. }
  179. static auto allOf(detail::ParserContext<A> const & context) {
  180. EXPECT(context.schema.type() == adapter::Type::Array);
  181. std::vector<schema::Node const *> rval;
  182. size_t index = 0;
  183. for (auto subschema : context.schema.as_array()) {
  184. rval.push_back(context.child(subschema, index).node());
  185. ++index;
  186. }
  187. return std::make_unique<constraint::AllOfConstraint>(rval);
  188. }
  189. static auto anyOf(detail::ParserContext<A> const & context) {
  190. EXPECT(context.schema.type() == adapter::Type::Array);
  191. std::vector<schema::Node const *> rval;
  192. size_t index = 0;
  193. for (auto subschema : context.schema.as_array()) {
  194. rval.push_back(context.child(subschema, index).node());
  195. ++index;
  196. }
  197. return std::make_unique<constraint::AnyOfConstraint>(rval);
  198. }
  199. static auto oneOf(detail::ParserContext<A> const & context) {
  200. EXPECT(context.schema.type() == adapter::Type::Array);
  201. std::vector<schema::Node const *> rval;
  202. size_t index = 0;
  203. for (auto subschema : context.schema.as_array()) {
  204. rval.push_back(context.child(subschema, index).node());
  205. ++index;
  206. }
  207. return std::make_unique<constraint::OneOfConstraint>(rval);
  208. }
  209. static auto isNot(detail::ParserContext<A> const & context) {
  210. return std::make_unique<constraint::NotConstraint>(context.node());
  211. }
  212. // SECTION: Numeric Constraints
  213. static auto minimum(detail::ParserContext<A> const & context) {
  214. double value = context.schema.as_number();
  215. if (context.version < schema::Version::Draft06 &&
  216. context.parent->contains("exclusiveMinimum")) {
  217. auto exclusive = (*context.parent)["exclusiveMinimum"];
  218. EXPECT(exclusive.type() == adapter::Type::Boolean);
  219. return std::make_unique<constraint::MinimumConstraint>(value, exclusive.as_boolean());
  220. }
  221. return std::make_unique<constraint::MinimumConstraint>(value, false);
  222. }
  223. static pConstraint exclusiveMinimum(detail::ParserContext<A> const & context) {
  224. double value = context.schema.as_number();
  225. return std::make_unique<constraint::MinimumConstraint>(value, true);
  226. }
  227. static auto maximum(detail::ParserContext<A> const & context) {
  228. double value = context.schema.as_number();
  229. if (context.version < schema::Version::Draft06 &&
  230. context.parent->contains("exclusiveMaximum")) {
  231. auto exclusive = (*context.parent)["exclusiveMaximum"];
  232. EXPECT(exclusive.type() == adapter::Type::Boolean);
  233. return std::make_unique<constraint::MaximumConstraint>(value, exclusive.as_boolean());
  234. }
  235. return std::make_unique<constraint::MaximumConstraint>(value, false);
  236. }
  237. static pConstraint exclusiveMaximum(detail::ParserContext<A> const & context) {
  238. double value = context.schema.as_number();
  239. return std::make_unique<constraint::MaximumConstraint>(value, true);
  240. }
  241. static auto multipleOf(detail::ParserContext<A> const & context) {
  242. double value = context.schema.as_number();
  243. return std::make_unique<constraint::MultipleOfConstraint>(value);
  244. }
  245. // SECTION: String Constraints
  246. static auto minLength(detail::ParserContext<A> const & context) {
  247. EXPECT(context.schema.type() == adapter::Type::Integer ||
  248. context.schema.type() == adapter::Type::Number);
  249. return std::make_unique<constraint::MinLengthConstraint>(context.schema.as_integer());
  250. }
  251. static auto maxLength(detail::ParserContext<A> const & context) {
  252. EXPECT(context.schema.type() == adapter::Type::Integer ||
  253. context.schema.type() == adapter::Type::Number);
  254. return std::make_unique<constraint::MaxLengthConstraint>(context.schema.as_integer());
  255. }
  256. static auto pattern(detail::ParserContext<A> const & context) {
  257. return std::make_unique<constraint::PatternConstraint>(context.schema.as_string());
  258. }
  259. static auto format(detail::ParserContext<A> const & context) {
  260. return std::make_unique<constraint::FormatConstraint>(context.schema.as_string());
  261. }
  262. // SECTION: Array Constraints
  263. static auto contains(detail::ParserContext<A> const & context) {
  264. if (context.version < schema::Version::Draft2019_09) {
  265. return std::make_unique<constraint::ContainsConstraint>(context.node());
  266. }
  267. std::optional<size_t> maximum;
  268. std::optional<size_t> minimum;
  269. if (context.parent->contains("maxContains")) {
  270. maximum = (*context.parent)["maxContains"].as_integer();
  271. }
  272. if (context.parent->contains("minContains")) {
  273. minimum = (*context.parent)["minContains"].as_integer();
  274. }
  275. return std::make_unique<constraint::ContainsConstraint>(context.node(), minimum, maximum);
  276. }
  277. static auto minItems(detail::ParserContext<A> const & context) {
  278. EXPECT(context.schema.type() == adapter::Type::Integer ||
  279. context.schema.type() == adapter::Type::Number);
  280. return std::make_unique<constraint::MinItemsConstraint>(context.schema.as_integer());
  281. }
  282. static auto maxItems(detail::ParserContext<A> const & context) {
  283. EXPECT(context.schema.type() == adapter::Type::Integer ||
  284. context.schema.type() == adapter::Type::Number);
  285. return std::make_unique<constraint::MaxItemsConstraint>(context.schema.as_integer());
  286. }
  287. static auto prefixItems(detail::ParserContext<A> const & context) {
  288. EXPECT(context.schema.type() == adapter::Type::Array);
  289. std::vector<schema::Node const *> rval;
  290. size_t index = 0;
  291. for (auto subschema : context.schema.as_array()) {
  292. rval.push_back(context.child(subschema, index).node());
  293. ++index;
  294. }
  295. return std::make_unique<constraint::TupleConstraint>(rval);
  296. }
  297. static auto additionalItemsAfter(detail::ParserContext<A> const & context, size_t n) {
  298. using C = constraint::AdditionalItemsConstraint;
  299. if (context.version < schema::Version::Draft06 &&
  300. context.schema.type() == adapter::Type::Boolean) {
  301. return std::make_unique<C>(context.always(), n);
  302. }
  303. return std::make_unique<C>(context.node(), n);
  304. }
  305. static pConstraint additionalItems(detail::ParserContext<A> const & context) {
  306. std::string const prefix =
  307. context.version >= schema::Version::Draft2020_12 ? "prefixItems" : "items";
  308. Object const & parent = *context.parent;
  309. // Before Draft 2020-12, the "items" could be either a subschema or a tuple.
  310. // When not provided, we therefore treat it as an "accept-all" schema, and
  311. // thus will never have additionalItems to process. Similarly - if it is an
  312. // Object, then it must act on all items.
  313. if (context.version < schema::Version::Draft2020_12 &&
  314. (not parent.contains(prefix) || parent[prefix].type() == adapter::Type::Object)) {
  315. return nullptr;
  316. }
  317. return additionalItemsAfter(context, parent[prefix].array_size());
  318. }
  319. static pConstraint itemsTupleOrVector(detail::ParserContext<A> const & context) {
  320. if (context.schema.type() == adapter::Type::Array) {
  321. return prefixItems(context);
  322. }
  323. return additionalItemsAfter(context, 0);
  324. }
  325. static auto unevaluatedItems(detail::ParserContext<A> const & context) {
  326. return std::make_unique<constraint::UnevaluatedItemsConstraint>(context.node());
  327. }
  328. static pConstraint uniqueItems(detail::ParserContext<A> const & context) {
  329. EXPECT(context.schema.type() == adapter::Type::Boolean);
  330. if (not context.schema.as_boolean()) {
  331. return nullptr;
  332. }
  333. return std::make_unique<constraint::UniqueItemsConstraint>();
  334. }
  335. // SECTION: Object Constraints
  336. static auto required(detail::ParserContext<A> const & context) {
  337. EXPECT(context.schema.type() == adapter::Type::Array);
  338. std::unordered_set<std::string> rval;
  339. for (auto subschema : context.schema.as_array()) {
  340. EXPECT(subschema.type() == adapter::Type::String);
  341. rval.insert(subschema.as_string());
  342. }
  343. return std::make_unique<constraint::RequiredConstraint>(rval);
  344. }
  345. static auto minProperties(detail::ParserContext<A> const & context) {
  346. EXPECT(context.schema.type() == adapter::Type::Integer ||
  347. context.schema.type() == adapter::Type::Number);
  348. return std::make_unique<constraint::MinPropertiesConstraint>(context.schema.as_integer());
  349. }
  350. static auto maxProperties(detail::ParserContext<A> const & context) {
  351. EXPECT(context.schema.type() == adapter::Type::Integer ||
  352. context.schema.type() == adapter::Type::Number);
  353. return std::make_unique<constraint::MaxPropertiesConstraint>(context.schema.as_integer());
  354. }
  355. static auto patternProperties(detail::ParserContext<A> const & context) {
  356. EXPECT(context.schema.type() == adapter::Type::Object);
  357. std::vector<std::pair<std::string, schema::Node const *>> rval;
  358. for (auto [prop, subschema] : context.schema.as_object()) {
  359. rval.emplace_back(prop, context.child(subschema, prop).node());
  360. }
  361. return std::make_unique<constraint::PatternPropertiesConstraint>(rval);
  362. }
  363. static auto properties(detail::ParserContext<A> const & context) {
  364. EXPECT(context.schema.type() == adapter::Type::Object);
  365. std::map<std::string, schema::Node const *> rval;
  366. for (auto [prop, subschema] : context.schema.as_object()) {
  367. rval.emplace(prop, context.child(subschema, prop).node());
  368. }
  369. return std::make_unique<constraint::PropertiesConstraint>(rval);
  370. }
  371. static auto propertyNames(detail::ParserContext<A> const & context) {
  372. return std::make_unique<constraint::PropertyNamesConstraint>(context.node());
  373. }
  374. static auto unevaluatedProperties(detail::ParserContext<A> const & context) {
  375. return std::make_unique<constraint::UnevaluatedPropertiesConstraint>(context.node());
  376. }
  377. static auto additionalProperties(detail::ParserContext<A> const & context) {
  378. std::unordered_set<std::string> properties;
  379. std::vector<std::string> patterns;
  380. Object const & parent = *context.parent;
  381. if (parent.contains("properties")) {
  382. for (auto [key, _] : parent["properties"].as_object()) {
  383. properties.insert(key);
  384. }
  385. }
  386. if (parent.contains("patternProperties")) {
  387. for (auto [key, _] : parent["patternProperties"].as_object()) {
  388. patterns.push_back(key);
  389. }
  390. }
  391. using C = constraint::AdditionalPropertiesConstraint;
  392. if (context.version < schema::Version::Draft06 &&
  393. context.schema.type() == adapter::Type::Boolean) {
  394. return std::make_unique<C>(context.always(), properties, patterns);
  395. }
  396. return std::make_unique<C>(context.node(), properties, patterns);
  397. }
  398. static auto dependencies(detail::ParserContext<A> const & context) {
  399. EXPECT(context.schema.type() == adapter::Type::Object);
  400. std::map<std::string, schema::Node const *> schemas;
  401. std::map<std::string, std::unordered_set<std::string>> required;
  402. for (auto [prop, subschema] : context.schema.as_object()) {
  403. if (subschema.type() == adapter::Type::Array) {
  404. for (auto key : subschema.as_array()) {
  405. EXPECT(key.type() == adapter::Type::String);
  406. required[prop].insert(key.as_string());
  407. }
  408. } else {
  409. schemas.emplace(prop, context.child(subschema, prop).node());
  410. }
  411. }
  412. return std::make_unique<constraint::DependenciesConstraint>(schemas, required);
  413. }
  414. static auto dependentSchemas(detail::ParserContext<A> const & context) {
  415. EXPECT(context.schema.type() == adapter::Type::Object);
  416. std::map<std::string, schema::Node const *> rval;
  417. for (auto [prop, subschema] : context.schema.as_object()) {
  418. rval.emplace(prop, context.child(subschema, prop).node());
  419. }
  420. return std::make_unique<constraint::DependenciesConstraint>(rval);
  421. }
  422. static auto dependentRequired(detail::ParserContext<A> const & context) {
  423. EXPECT(context.schema.type() == adapter::Type::Object);
  424. std::map<std::string, std::unordered_set<std::string>> rval;
  425. for (auto [prop, subschema] : context.schema.as_object()) {
  426. EXPECT(subschema.type() == adapter::Type::Array);
  427. for (auto key : subschema.as_array()) {
  428. EXPECT(key.type() == adapter::Type::String);
  429. rval[prop].insert(key.as_string());
  430. }
  431. }
  432. return std::make_unique<constraint::DependenciesConstraint>(rval);
  433. }
  434. };
  435. }