validation_visitor.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. #pragma once
  2. #include <tuple>
  3. #include <unordered_map>
  4. #include <jvalidate/constraint/array_constraint.h>
  5. #include <jvalidate/constraint/general_constraint.h>
  6. #include <jvalidate/constraint/number_constraint.h>
  7. #include <jvalidate/constraint/object_constraint.h>
  8. #include <jvalidate/constraint/string_constraint.h>
  9. #include <jvalidate/constraint/visitor.h>
  10. #include <jvalidate/detail/enumerate.h>
  11. #include <jvalidate/detail/expect.h>
  12. #include <jvalidate/detail/iostream.h>
  13. #include <jvalidate/detail/number.h>
  14. #include <jvalidate/detail/pointer.h>
  15. #include <jvalidate/forward.h>
  16. #include <jvalidate/schema.h>
  17. #include <jvalidate/status.h>
  18. #include <jvalidate/validation_config.h>
  19. #include <jvalidate/validation_result.h>
  20. #define VISITED(type) std::get<std::unordered_set<type>>(*visited_)
  21. #define NOOP_UNLESS_TYPE(etype) \
  22. RETURN_UNLESS(adapter::Type::etype == document_.type(), Status::Noop)
  23. #define BREAK_EARLY_IF_NO_RESULT_TREE() \
  24. do { \
  25. if (rval == Status::Reject and not result_ and not visited_) { \
  26. break; \
  27. } \
  28. } while (false)
  29. namespace jvalidate {
  30. template <Adapter A, RegexEngine RE>
  31. class ValidationVisitor : public constraint::ConstraintVisitor {
  32. private:
  33. using VisitedAnnotation = std::tuple<std::unordered_set<size_t>, std::unordered_set<std::string>>;
  34. private:
  35. A document_;
  36. detail::Pointer where_;
  37. detail::Pointer schema_path_;
  38. schema::Node const * schema_;
  39. ValidationResult * result_;
  40. ValidationConfig const & cfg_;
  41. std::unordered_map<std::string, RE> & regex_cache_;
  42. mutable VisitedAnnotation * visited_ = nullptr;
  43. public:
  44. ValidationVisitor(A const & json, schema::Node const & schema, ValidationConfig const & cfg,
  45. std::unordered_map<std::string, RE> & regex_cache, ValidationResult * result)
  46. : document_(json), schema_(&schema), result_(result), cfg_(cfg), regex_cache_(regex_cache) {}
  47. Status visit(constraint::TypeConstraint const & cons) const {
  48. adapter::Type const type = document_.type();
  49. for (adapter::Type const accept : cons.types) {
  50. if (type == accept) {
  51. return Status::Accept;
  52. }
  53. if (accept == adapter::Type::Number && type == adapter::Type::Integer) {
  54. return Status::Accept;
  55. }
  56. if (accept == adapter::Type::Integer && type == adapter::Type::Number &&
  57. detail::is_json_integer(document_.as_number())) {
  58. return Status::Accept;
  59. }
  60. }
  61. add_error("type ", type, " is not one of {", cons.types, "}");
  62. return Status::Reject;
  63. }
  64. Status visit(constraint::ExtensionConstraint const & cons) const {
  65. return cons.validate(document_, where_, result_);
  66. }
  67. Status visit(constraint::EnumConstraint const & cons) const {
  68. auto is_equal = [this](auto const & frozen) {
  69. return document_.equals(frozen, cfg_.strict_equality);
  70. };
  71. for (auto const & option : cons.enumeration) {
  72. if (option->apply(is_equal)) {
  73. return Status::Accept;
  74. }
  75. }
  76. add_error("equals none of the values");
  77. return Status::Reject;
  78. }
  79. Status visit(constraint::AllOfConstraint const & cons) const {
  80. Status rval = Status::Accept;
  81. std::set<size_t> unmatched;
  82. for (auto const & [index, subschema] : detail::enumerate(cons.children)) {
  83. if (auto stat = validate_subschema(subschema, index); stat == Status::Reject) {
  84. rval = Status::Reject;
  85. unmatched.insert(index);
  86. }
  87. BREAK_EARLY_IF_NO_RESULT_TREE();
  88. }
  89. if (rval == Status::Reject) {
  90. add_error("does not validate subschemas ", unmatched);
  91. }
  92. return rval;
  93. }
  94. Status visit(constraint::AnyOfConstraint const & cons) const {
  95. Status rval = Status::Reject;
  96. for (auto const & [index, subschema] : detail::enumerate(cons.children)) {
  97. if (validate_subschema(subschema, index)) {
  98. rval = Status::Accept;
  99. }
  100. if (not visited_ && rval == Status::Accept) {
  101. break;
  102. }
  103. }
  104. if (rval == Status::Reject) {
  105. add_error("validates none of the subschemas");
  106. }
  107. return rval;
  108. }
  109. Status visit(constraint::OneOfConstraint const & cons) const {
  110. std::set<size_t> matches;
  111. for (auto const & [index, subschema] : detail::enumerate(cons.children)) {
  112. if (validate_subschema(subschema, index)) {
  113. matches.insert(index);
  114. }
  115. }
  116. if (matches.size() == 1) {
  117. return Status::Accept;
  118. }
  119. add_error("validates subschemas ", matches);
  120. return Status::Reject;
  121. }
  122. Status visit(constraint::NotConstraint const & cons) const {
  123. VisitedAnnotation * suppress = nullptr;
  124. std::swap(suppress, visited_);
  125. bool const rval = validate_subschema(cons.child) == Status::Reject;
  126. std::swap(suppress, visited_);
  127. if (not rval) {
  128. add_error("actually validates subschema");
  129. }
  130. return rval;
  131. }
  132. Status visit(constraint::ConditionalConstraint const & cons) const {
  133. bool const if_result(validate_subschema(cons.if_constraint));
  134. if (if_result) {
  135. return validate_subschema(cons.then_constraint, detail::parent, "then");
  136. }
  137. return validate_subschema(cons.else_constraint, detail::parent, "else");
  138. }
  139. Status visit(constraint::MaximumConstraint const & cons) const {
  140. switch (document_.type()) {
  141. case adapter::Type::Integer:
  142. if (int64_t value = document_.as_integer(); not cons(value)) {
  143. add_error("integer ", value, " exceeds ", cons.exclusive ? "exclusive " : "", "maximum of ",
  144. cons.value);
  145. return false;
  146. }
  147. return true;
  148. case adapter::Type::Number:
  149. if (double value = document_.as_number(); not cons(value)) {
  150. add_error("number ", value, " exceeds ", cons.exclusive ? "exclusive " : "", "maximum of ",
  151. cons.value);
  152. return false;
  153. }
  154. return true;
  155. default:
  156. return Status::Noop;
  157. }
  158. }
  159. Status visit(constraint::MinimumConstraint const & cons) const {
  160. switch (document_.type()) {
  161. case adapter::Type::Integer:
  162. if (int64_t value = document_.as_integer(); not cons(value)) {
  163. add_error("integer ", value, " fails ", cons.exclusive ? "exclusive " : "", "minimum of ",
  164. cons.value);
  165. return false;
  166. }
  167. return true;
  168. case adapter::Type::Number:
  169. if (double value = document_.as_number(); not cons(value)) {
  170. add_error("number ", value, " fails ", cons.exclusive ? "exclusive " : "", "minimum of ",
  171. cons.value);
  172. return false;
  173. }
  174. return true;
  175. default:
  176. return Status::Noop;
  177. }
  178. }
  179. Status visit(constraint::MultipleOfConstraint const & cons) const {
  180. adapter::Type const type = document_.type();
  181. RETURN_UNLESS(type == adapter::Type::Number || type == adapter::Type::Integer, Status::Noop);
  182. if (double value = document_.as_number(); not cons(value)) {
  183. add_error("number ", value, " is not a multiple of ", cons.value);
  184. return false;
  185. }
  186. return true;
  187. }
  188. Status visit(constraint::MaxLengthConstraint const & cons) const {
  189. NOOP_UNLESS_TYPE(String);
  190. if (auto str = document_.as_string(); detail::length(str) > cons.value) {
  191. add_error("string '", str, "' is greater than the maximum length of ", cons.value);
  192. return false;
  193. }
  194. return true;
  195. }
  196. Status visit(constraint::MinLengthConstraint const & cons) const {
  197. NOOP_UNLESS_TYPE(String);
  198. if (auto str = document_.as_string(); detail::length(str) < cons.value) {
  199. add_error("string '", str, "' is less than the minimum length of ", cons.value);
  200. return false;
  201. }
  202. return true;
  203. }
  204. Status visit(constraint::PatternConstraint const & cons) const {
  205. NOOP_UNLESS_TYPE(String);
  206. RE const & regex = regex_cache_.try_emplace(cons.regex, cons.regex).first->second;
  207. if (auto str = document_.as_string(); not regex.search(str)) {
  208. add_error("string '", str, "' does not match pattern /", cons.regex, "/");
  209. return false;
  210. }
  211. return true;
  212. }
  213. Status visit(constraint::FormatConstraint const & cons) const {
  214. // https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-01#name-defined-formats
  215. NOOP_UNLESS_TYPE(String);
  216. if (not cfg_.validate_format && not cons.is_assertion) {
  217. return true;
  218. }
  219. add_error("unimplemented format assertion: '", cons.format, "'");
  220. return false;
  221. }
  222. Status visit(constraint::AdditionalItemsConstraint const & cons) const {
  223. NOOP_UNLESS_TYPE(Array);
  224. auto array = document_.as_array();
  225. Status rval = Status::Accept;
  226. for (size_t i = cons.applies_after_nth; i < array.size(); ++i) {
  227. rval &= validate_subschema_on(cons.subschema, array[i], i);
  228. BREAK_EARLY_IF_NO_RESULT_TREE();
  229. }
  230. return rval;
  231. }
  232. Status visit(constraint::ContainsConstraint const & cons) const {
  233. NOOP_UNLESS_TYPE(Array);
  234. auto array = document_.as_array();
  235. size_t const minimum = cons.minimum.value_or(1);
  236. size_t const maximum = cons.maximum.value_or(array.size());
  237. size_t matches = 0;
  238. for (size_t i = 0; i < array.size(); ++i) {
  239. if (validate_subschema_on(cons.subschema, array[i], i)) {
  240. ++matches;
  241. }
  242. }
  243. if (matches < minimum) {
  244. add_error("array does not contain at least ", minimum, " matching elements");
  245. return Status::Reject;
  246. }
  247. if (matches > maximum) {
  248. add_error("array contains more than ", maximum, " matching elements");
  249. return Status::Reject;
  250. }
  251. return Status::Accept;
  252. }
  253. Status visit(constraint::MaxItemsConstraint const & cons) const {
  254. NOOP_UNLESS_TYPE(Array);
  255. if (auto size = document_.array_size(); size > cons.value) {
  256. add_error("array with ", size, " items is greater than the maximum of ", cons.value);
  257. return false;
  258. }
  259. return true;
  260. }
  261. Status visit(constraint::MinItemsConstraint const & cons) const {
  262. NOOP_UNLESS_TYPE(Array);
  263. if (auto size = document_.array_size(); size < cons.value) {
  264. add_error("array with ", size, " items is less than the minimum of ", cons.value);
  265. return false;
  266. }
  267. return true;
  268. }
  269. Status visit(constraint::TupleConstraint const & cons) const {
  270. NOOP_UNLESS_TYPE(Array);
  271. Status rval = Status::Accept;
  272. auto array = document_.as_array();
  273. size_t const n = std::min(cons.items.size(), array.size());
  274. for (size_t i = 0; i < n; ++i) {
  275. rval &= validate_subschema_on(cons.items[i], array[i], i);
  276. BREAK_EARLY_IF_NO_RESULT_TREE();
  277. }
  278. return rval;
  279. }
  280. Status visit(constraint::UniqueItemsConstraint const & cons) const {
  281. NOOP_UNLESS_TYPE(Array);
  282. if constexpr (std::totally_ordered<A>) {
  283. std::set<A> cache;
  284. for (A const & elem : document_.as_array()) {
  285. if (not cache.insert(elem).second) {
  286. add_error("array contains duplicate elements");
  287. return Status::Reject;
  288. }
  289. }
  290. } else {
  291. auto array = document_.as_array();
  292. for (size_t i = 0; i < array.size(); ++i) {
  293. for (size_t j = i + 1; j < array.size(); ++j) {
  294. if (array[i].equals(array[j], true)) {
  295. add_error("array elements ", i, " and ", j, " are equal");
  296. return Status::Reject;
  297. }
  298. }
  299. }
  300. }
  301. return Status::Accept;
  302. }
  303. Status visit(constraint::AdditionalPropertiesConstraint const & cons) const {
  304. NOOP_UNLESS_TYPE(Object);
  305. auto matches_any_pattern = [this, &cons](std::string const & key) {
  306. for (auto & pattern : cons.patterns) {
  307. RE const & regex = regex_cache_.try_emplace(pattern, pattern).first->second;
  308. if (regex.search(key)) {
  309. return true;
  310. }
  311. }
  312. return false;
  313. };
  314. Status rval = Status::Accept;
  315. for (auto const & [key, elem] : document_.as_object()) {
  316. if (not cons.properties.contains(key) && not matches_any_pattern(key)) {
  317. rval &= validate_subschema_on(cons.subschema, elem, key);
  318. }
  319. BREAK_EARLY_IF_NO_RESULT_TREE();
  320. }
  321. return rval;
  322. }
  323. Status visit(constraint::DependenciesConstraint const & cons) const {
  324. NOOP_UNLESS_TYPE(Object);
  325. auto object = document_.as_object();
  326. Status rval = Status::Accept;
  327. for (auto const & [key, subschema] : cons.subschemas) {
  328. if (not object.contains(key)) {
  329. continue;
  330. }
  331. rval &= validate_subschema(subschema, key);
  332. BREAK_EARLY_IF_NO_RESULT_TREE();
  333. }
  334. for (auto [key, required] : cons.required) {
  335. if (not object.contains(key)) {
  336. continue;
  337. }
  338. for (auto const & [key, _] : object) {
  339. required.erase(key);
  340. }
  341. rval &= required.empty();
  342. BREAK_EARLY_IF_NO_RESULT_TREE();
  343. }
  344. return rval;
  345. }
  346. Status visit(constraint::MaxPropertiesConstraint const & cons) const {
  347. NOOP_UNLESS_TYPE(Object);
  348. if (auto size = document_.object_size(); size > cons.value) {
  349. add_error("object with ", size, " properties is greater than the maximum of ", cons.value);
  350. return false;
  351. }
  352. return true;
  353. }
  354. Status visit(constraint::MinPropertiesConstraint const & cons) const {
  355. NOOP_UNLESS_TYPE(Object);
  356. if (auto size = document_.object_size(); size < cons.value) {
  357. add_error("object with ", size, " properties is less than the minimum of ", cons.value);
  358. return false;
  359. }
  360. return true;
  361. }
  362. Status visit(constraint::PatternPropertiesConstraint const & cons) const {
  363. NOOP_UNLESS_TYPE(Object);
  364. Status rval = Status::Accept;
  365. for (auto const & [pattern, subschema] : cons.properties) {
  366. RE const & regex = regex_cache_.try_emplace(pattern, pattern).first->second;
  367. for (auto const & [key, elem] : document_.as_object()) {
  368. if (regex.search(key)) {
  369. rval &= validate_subschema_on(subschema, elem, key);
  370. }
  371. BREAK_EARLY_IF_NO_RESULT_TREE();
  372. }
  373. }
  374. return rval;
  375. }
  376. Status visit(constraint::PropertiesConstraint const & cons) const {
  377. NOOP_UNLESS_TYPE(Object);
  378. Status rval = Status::Accept;
  379. auto object = document_.as_object();
  380. if constexpr (MutableAdapter<A>) {
  381. for (auto const & [key, subschema] : cons.properties) {
  382. auto const * default_value = subschema->default_value();
  383. if (default_value && not object.contains(key)) {
  384. object.assign(key, *default_value);
  385. }
  386. }
  387. }
  388. for (auto const & [key, elem] : object) {
  389. if (auto it = cons.properties.find(key); it != cons.properties.end()) {
  390. rval &= validate_subschema_on(it->second, elem, key);
  391. }
  392. BREAK_EARLY_IF_NO_RESULT_TREE();
  393. }
  394. return rval;
  395. }
  396. Status visit(constraint::PropertyNamesConstraint const & cons) const {
  397. NOOP_UNLESS_TYPE(Object);
  398. Status rval = Status::Accept;
  399. for (auto const & [key, _] : document_.as_object()) {
  400. // TODO(samjaffe): Should we prefer a std::string adapter like valijson?
  401. typename A::value_type key_json{key};
  402. rval &= validate_subschema_on(cons.key_schema, A(key_json), std::string("$$key"));
  403. }
  404. return rval;
  405. }
  406. Status visit(constraint::RequiredConstraint const & cons) const {
  407. NOOP_UNLESS_TYPE(Object);
  408. auto required = cons.properties;
  409. for (auto const & [key, _] : document_.as_object()) {
  410. required.erase(key);
  411. }
  412. if (required.empty()) {
  413. return Status::Accept;
  414. }
  415. add_error("missing required properties ", required);
  416. return Status::Reject;
  417. }
  418. Status visit(constraint::UnevaluatedItemsConstraint const & cons) const {
  419. NOOP_UNLESS_TYPE(Array);
  420. if (not visited_) {
  421. return Status::Reject;
  422. }
  423. Status rval = Status::Accept;
  424. auto array = document_.as_array();
  425. for (size_t i = 0; i < array.size(); ++i) {
  426. if (not VISITED(size_t).contains(i)) {
  427. rval &= validate_subschema_on(cons.subschema, array[i], i);
  428. }
  429. BREAK_EARLY_IF_NO_RESULT_TREE();
  430. }
  431. return rval;
  432. }
  433. Status visit(constraint::UnevaluatedPropertiesConstraint const & cons) const {
  434. NOOP_UNLESS_TYPE(Object);
  435. if (not visited_) {
  436. return Status::Reject;
  437. }
  438. Status rval = Status::Accept;
  439. for (auto const & [key, elem] : document_.as_object()) {
  440. if (not VISITED(std::string).contains(key)) {
  441. rval &= validate_subschema_on(cons.subschema, elem, key);
  442. }
  443. BREAK_EARLY_IF_NO_RESULT_TREE();
  444. }
  445. return rval;
  446. }
  447. Status validate() {
  448. if (auto const & reject = schema_->rejects_all()) {
  449. add_error(*reject);
  450. return Status::Reject;
  451. }
  452. if (schema_->accepts_all()) {
  453. // An accept-all schema is not No-Op for the purpose of unevaluated*
  454. return Status::Accept;
  455. }
  456. VisitedAnnotation annotate;
  457. if (schema_->requires_result_context() and not visited_) {
  458. visited_ = &annotate;
  459. }
  460. Status rval = Status::Noop;
  461. if (auto ref = schema_->reference_schema()) {
  462. rval = validate_subschema(*ref, "$ref");
  463. }
  464. detail::Pointer const current_schema = schema_path_;
  465. for (auto const & [key, p_constraint] : schema_->constraints()) {
  466. BREAK_EARLY_IF_NO_RESULT_TREE();
  467. schema_path_ = current_schema / key;
  468. rval &= p_constraint->accept(*this);
  469. }
  470. for (auto const & [key, p_constraint] : schema_->post_constraints()) {
  471. BREAK_EARLY_IF_NO_RESULT_TREE();
  472. schema_path_ = current_schema / key;
  473. rval &= p_constraint->accept(*this);
  474. }
  475. return rval;
  476. }
  477. private:
  478. template <typename... Args> void add_error(Args &&... args) const {
  479. if (not result_) {
  480. return;
  481. }
  482. std::stringstream ss;
  483. using ::jvalidate::operator<<;
  484. [[maybe_unused]] int _[] = {(ss << std::forward<Args>(args), 0)...};
  485. result_->add_error(where_, schema_path_, ss.str());
  486. }
  487. template <typename C> static void merge_visited(C & to, C const & from) {
  488. to.insert(from.begin(), from.end());
  489. }
  490. template <typename... K>
  491. Status validate_subschema(constraint::Constraint::SubConstraint const & subschema,
  492. K const &... keys) const {
  493. if (schema::Node const * const * ppschema = std::get_if<0>(&subschema)) {
  494. return validate_subschema(*ppschema, keys...);
  495. } else {
  496. return std::get<1>(subschema)->accept(*this);
  497. }
  498. }
  499. template <typename... K>
  500. Status validate_subschema(schema::Node const * subschema, K const &... keys) const {
  501. VisitedAnnotation annotate;
  502. ValidationVisitor next = *this;
  503. ((next.schema_path_ /= keys), ...);
  504. std::tie(next.schema_, next.visited_) =
  505. std::forward_as_tuple(subschema, visited_ ? &annotate : nullptr);
  506. Status rval = next.validate();
  507. if (rval == Status::Accept and visited_) {
  508. merge_visited(std::get<0>(*visited_), std::get<0>(annotate));
  509. merge_visited(std::get<1>(*visited_), std::get<1>(annotate));
  510. }
  511. return rval;
  512. }
  513. template <typename K>
  514. Status validate_subschema_on(schema::Node const * subschema, A const & document,
  515. K const & key) const {
  516. ValidationResult result;
  517. ValidationVisitor next = *this;
  518. next.where_ /= key;
  519. std::tie(next.document_, next.schema_, next.result_, next.visited_) =
  520. std::forward_as_tuple(document, subschema, result_ ? &result : nullptr, nullptr);
  521. auto status = next.validate();
  522. if (status == Status::Accept and visited_) {
  523. VISITED(K).insert(key);
  524. }
  525. if (status == Status::Reject and result_) {
  526. result_->add_error(std::move(result));
  527. }
  528. return status;
  529. }
  530. };
  531. }