validation_visitor.h 19 KB

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