validation_visitor.h 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. #pragma once
  2. #include <algorithm>
  3. #include <concepts>
  4. #include <cstdint>
  5. #include <cstdlib>
  6. #include <map>
  7. #include <optional>
  8. #include <ranges>
  9. #include <set>
  10. #include <string>
  11. #include <tuple>
  12. #include <type_traits>
  13. #include <unordered_set>
  14. #include <utility>
  15. #include <variant>
  16. #include <vector>
  17. #include <jvalidate/_macro.h>
  18. #include <jvalidate/compat/enumerate.h>
  19. #include <jvalidate/constraint/array_constraint.h>
  20. #include <jvalidate/constraint/general_constraint.h>
  21. #include <jvalidate/constraint/number_constraint.h>
  22. #include <jvalidate/constraint/object_constraint.h>
  23. #include <jvalidate/constraint/string_constraint.h>
  24. #include <jvalidate/detail/iostream.h>
  25. #include <jvalidate/detail/number.h>
  26. #include <jvalidate/detail/pointer.h>
  27. #include <jvalidate/detail/scoped_state.h>
  28. #include <jvalidate/detail/string.h>
  29. #include <jvalidate/detail/string_adapter.h>
  30. #include <jvalidate/detail/tribool.h>
  31. #include <jvalidate/forward.h>
  32. #include <jvalidate/schema.h>
  33. #include <jvalidate/status.h>
  34. #include <jvalidate/validation_config.h>
  35. #include <jvalidate/validation_result.h>
  36. #define VISITED(type) std::get<std::unordered_set<type>>(*visited_)
  37. #define VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT(subschema, subinstance, path, local_visited, ...) \
  38. do { \
  39. Status const partial = \
  40. validate_subschema_on(subschema, subinstance, path __VA_OPT__(, ) __VA_ARGS__); \
  41. rval &= partial; \
  42. if (result_ and partial != Status::Noop) { \
  43. local_visited.insert(local_visited.end(), path); \
  44. } \
  45. } while (false)
  46. #define NOOP_UNLESS_TYPE(etype) \
  47. JVALIDATE_RETURN_UNLESS(adapter::Type::etype == document.type(), Status::Noop)
  48. #define BREAK_EARLY_IF_NO_RESULT_TREE() \
  49. do { \
  50. if (rval == Status::Reject and not result_ and not visited_) { \
  51. break; \
  52. } \
  53. } while (false)
  54. #define ANNOTATION_HELPER(name, ADD, FMT) \
  55. void name(auto const &... args) const { \
  56. if (not result_) { \
  57. /* do nothing if there's no result object to append to */ \
  58. } else if (schema_path_.empty()) { \
  59. result_->ADD(where_, schema_path_, "", FMT(args...)); \
  60. } else { \
  61. result_->ADD(where_, schema_path_.parent(), schema_path_.back(), FMT(args...)); \
  62. } \
  63. }
  64. namespace jvalidate {
  65. JVALIDATE_TRIBOOL_TYPE(StoreResults, ForValid, ForInvalid, ForAnything);
  66. template <Adapter Root, RegexEngine RE, typename ExtensionVisitor> class ValidationVisitor {
  67. private:
  68. using VisitedAnnotation = std::tuple<std::unordered_set<size_t>, std::unordered_set<std::string>>;
  69. friend class ValidationVisitorTest;
  70. private:
  71. detail::Pointer where_;
  72. detail::Pointer schema_path_;
  73. schema::Node const * schema_;
  74. Root const * root_;
  75. ValidationResult * result_;
  76. ValidationConfig const & cfg_;
  77. ExtensionVisitor extension_;
  78. RE & regex_;
  79. mutable VisitedAnnotation * visited_ = nullptr;
  80. mutable StoreResults tracking_ = StoreResults::ForInvalid;
  81. public:
  82. /**
  83. * @brief Construct a new ValidationVisitor
  84. *
  85. * @param schema The parsed JSON Schema
  86. * @param cfg General configuration settings for how the run is executed
  87. * @param regex A cache of string regular expressions to compiled
  88. * regular expressions
  89. * @param[optional] extension A special visitor for extension constraints.
  90. * @param[optional] result A cache of result/annotation info for the user to
  91. * receive a detailed summary of why a document is supported/unsupported.
  92. */
  93. ValidationVisitor(schema::Node const & schema, Root const & root, ValidationConfig const & cfg,
  94. RE & regex, ExtensionVisitor extension, ValidationResult * result)
  95. : schema_(&schema), root_(&root), result_(result), cfg_(cfg), extension_(extension),
  96. regex_(regex) {}
  97. private:
  98. Status visit(constraint::ExtensionConstraint const & cons, Adapter auto const & document) const {
  99. // Because we don't provide any contract constraint on our ExtensionVisitor,
  100. // we instead defer it to here where we validate that the extension can be
  101. // validated given the input document.
  102. // This covers a case where we write the extension around a specific adapter
  103. // instead of generically.
  104. if constexpr (std::is_invocable_r_v<Status, ExtensionVisitor, decltype(cons),
  105. decltype(document), ValidationVisitor const &>) {
  106. return extension_(cons, document, *this);
  107. }
  108. annotate("unsupported extension");
  109. return Status::Noop;
  110. }
  111. Status visit(constraint::TypeConstraint const & cons, Adapter auto const & document) const {
  112. adapter::Type const type = document.type();
  113. for (adapter::Type const accept : cons.types) {
  114. if (type == accept) { // Simple case, types are equal
  115. return result(Status::Accept, type, " is in types [", cons.types, "]");
  116. }
  117. if (accept == adapter::Type::Number && type == adapter::Type::Integer) {
  118. // Number is a super-type of Integer, therefore all Integer values are
  119. // accepted by a `"type": "number"` schema.
  120. return result(Status::Accept, type, " is in types [", cons.types, "]");
  121. }
  122. if (accept == adapter::Type::Integer && type == adapter::Type::Number &&
  123. detail::is_json_integer(document.as_number())) {
  124. // Since the JSON specification does not distinguish between Number
  125. // and Integer, but JSON Schema does, we need to check that the number
  126. // is a whole integer that is representable within the system (64-bit).
  127. return result(Status::Accept, type, " is in types [", cons.types, "]");
  128. }
  129. }
  130. return result(Status::Reject, type, " is not in types [", cons.types, "]");
  131. }
  132. Status visit(constraint::ConstConstraint const & cons, Adapter auto const & document) const {
  133. auto is_equal = [this, &document](auto const & frozen) {
  134. return document.equals(frozen, cfg_.strict_equality);
  135. };
  136. if (cons.value->apply(is_equal)) {
  137. return result(Status::Accept, "matches value");
  138. }
  139. return result(Status::Reject, cons.value, " was expected");
  140. }
  141. Status visit(constraint::EnumConstraint const & cons, Adapter auto const & document) const {
  142. auto is_equal = [this, &document](auto const & frozen) {
  143. return document.equals(frozen, cfg_.strict_equality);
  144. };
  145. for (auto const & [index, option] : detail::enumerate(cons.enumeration)) {
  146. if (option->apply(is_equal)) {
  147. return result(Status::Accept, index);
  148. }
  149. }
  150. return result(Status::Reject, document, " value is not one of ", cons.enumeration);
  151. }
  152. Status visit(constraint::AllOfConstraint const & cons, Adapter auto const & document) const {
  153. Status rval = Status::Accept;
  154. std::set<size_t> unmatched;
  155. for (auto const & [index, subschema] : detail::enumerate(cons.children)) {
  156. if (auto stat = validate_subschema(subschema, document, index); stat == Status::Reject) {
  157. rval = Status::Reject;
  158. unmatched.insert(index);
  159. }
  160. BREAK_EARLY_IF_NO_RESULT_TREE();
  161. }
  162. if (rval == Status::Reject) {
  163. return result(rval, "does not validate subschemas ", unmatched);
  164. }
  165. return result(rval, "validates all subschemas");
  166. }
  167. Status visit(constraint::AnyOfConstraint const & cons, Adapter auto const & document) const {
  168. std::optional<size_t> first_validated;
  169. for (auto const & [index, subschema] : detail::enumerate(cons.children)) {
  170. if (validate_subschema(subschema, document, index)) {
  171. // This technically will produce different results when we're tracking
  172. // visited nodes, but in practice it doesn't actually matter which
  173. // subschema index we record in the annotation.
  174. first_validated = index;
  175. }
  176. if (not visited_ && first_validated.has_value()) {
  177. break;
  178. }
  179. }
  180. if (first_validated.has_value()) {
  181. return result(Status::Accept, "validates subschema ", *first_validated);
  182. }
  183. return result(Status::Reject, "validates none of the subschemas");
  184. }
  185. Status visit(constraint::OneOfConstraint const & cons, Adapter auto const & document) const {
  186. std::set<size_t> matches;
  187. for (auto const & [index, subschema] : detail::enumerate(cons.children)) {
  188. scoped_state(tracking_, StoreResults::ForAnything);
  189. if (validate_subschema(subschema, document, index)) {
  190. matches.insert(index);
  191. }
  192. }
  193. if (matches.empty()) {
  194. return result(Status::Reject, "validates no subschemas");
  195. }
  196. if (matches.size() > 1) {
  197. return result(Status::Reject, "validates multiple subschemas ", matches);
  198. }
  199. size_t const match = *matches.begin();
  200. for (size_t i = 0; result_ and i < cons.children.size(); ++i) {
  201. if (i != match) {
  202. result_->unannotate(where_, schema_path_ / i);
  203. }
  204. }
  205. return result(Status::Accept, "validates subschema ", match);
  206. }
  207. Status visit(constraint::NotConstraint const & cons, Adapter auto const & document) const {
  208. scoped_state(visited_, nullptr);
  209. scoped_state(tracking_, !tracking_);
  210. bool const rejected = validate_subschema(cons.child, document) == Status::Reject;
  211. return rejected;
  212. }
  213. Status visit(constraint::ConditionalConstraint const & cons,
  214. Adapter auto const & document) const {
  215. Status const if_true = [this, &cons, &document]() {
  216. scoped_state(tracking_, StoreResults::ForAnything);
  217. return validate_subschema(cons.if_constraint, document);
  218. }();
  219. annotate(if_true ? "valid" : "invalid");
  220. if (if_true) {
  221. return validate_subschema(cons.then_constraint, document, detail::parent, "then");
  222. }
  223. return validate_subschema(cons.else_constraint, document, detail::parent, "else");
  224. }
  225. Status visit(constraint::MaximumConstraint const & cons, Adapter auto const & document) const {
  226. switch (document.type()) {
  227. case adapter::Type::Integer:
  228. if (int64_t const value = document.as_integer(); not cons(value)) {
  229. return result(Status::Reject, value, cons.exclusive ? " >= " : " > ", cons.value);
  230. } else {
  231. return result(Status::Accept, value, cons.exclusive ? " < " : " <= ", cons.value);
  232. }
  233. case adapter::Type::Number:
  234. if (double const value = document.as_number(); not cons(value)) {
  235. return result(Status::Reject, value, cons.exclusive ? " >= " : " > ", cons.value);
  236. } else {
  237. return result(Status::Accept, value, cons.exclusive ? " < " : " <= ", cons.value);
  238. }
  239. default:
  240. return Status::Noop;
  241. }
  242. }
  243. Status visit(constraint::MinimumConstraint const & cons, Adapter auto const & document) const {
  244. switch (document.type()) {
  245. case adapter::Type::Integer:
  246. if (int64_t const value = document.as_integer(); not cons(value)) {
  247. return result(Status::Reject, value, cons.exclusive ? " <= " : " < ", cons.value);
  248. } else {
  249. return result(Status::Accept, value, cons.exclusive ? " > " : " >= ", cons.value);
  250. }
  251. case adapter::Type::Number:
  252. if (double const value = document.as_number(); not cons(value)) {
  253. return result(Status::Reject, value, cons.exclusive ? " <= " : " < ", cons.value);
  254. } else {
  255. return result(Status::Accept, value, cons.exclusive ? " > " : " >= ", cons.value);
  256. }
  257. default:
  258. return Status::Noop;
  259. }
  260. }
  261. Status visit(constraint::MultipleOfConstraint const & cons, Adapter auto const & document) const {
  262. adapter::Type const type = document.type();
  263. JVALIDATE_RETURN_IF(type != adapter::Type::Number && type != adapter::Type::Integer,
  264. Status::Noop);
  265. double const value = document.as_number();
  266. if (cons(value)) {
  267. return result(Status::Accept, value, " is a multiple of ", cons.value);
  268. }
  269. return result(Status::Reject, value, " is not a multiple of ", cons.value);
  270. }
  271. Status visit(constraint::MaxLengthConstraint const & cons, Adapter auto const & document) const {
  272. NOOP_UNLESS_TYPE(String);
  273. std::string const str = document.as_string();
  274. size_t const len = detail::length(str);
  275. if (len > cons.value) {
  276. return result(Status::Reject, "string of length ", len, " is >", cons.value);
  277. }
  278. return result(Status::Accept, "string of length ", len, " is <=", cons.value);
  279. }
  280. Status visit(constraint::MinLengthConstraint const & cons, Adapter auto const & document) const {
  281. NOOP_UNLESS_TYPE(String);
  282. std::string const str = document.as_string();
  283. size_t const len = detail::length(str);
  284. if (len < cons.value) {
  285. return result(Status::Reject, "string of length ", len, " is <", cons.value);
  286. }
  287. return result(Status::Accept, "string of length ", len, " is >=", cons.value);
  288. }
  289. Status visit(constraint::PatternConstraint const & cons, Adapter auto const & document) const {
  290. NOOP_UNLESS_TYPE(String);
  291. std::string const str = document.as_string();
  292. annotate(regex_.engine_name());
  293. if (regex_.search(cons.regex, str)) {
  294. return result(Status::Accept, "string matches pattern /", cons.regex, "/");
  295. }
  296. return result(Status::Reject, "string does not match pattern /", cons.regex, "/");
  297. }
  298. Status visit(constraint::FormatConstraint const & cons, Adapter auto const & document) const {
  299. // https://json-schema.org/draft/2020-12/json-schema-validation#name-defined-formats
  300. NOOP_UNLESS_TYPE(String);
  301. annotate(cons.format);
  302. if (not cfg_.validate_format && not cons.is_assertion) {
  303. // Don't both validating formats if we're not in assertion mode
  304. // Assertion mode is specified either by using the appropriate "$vocab"
  305. // meta-schema or by requesting it in the ValidationConfig.
  306. return true; // TODO(samjaffe): I think this can be made into Noop
  307. }
  308. return result(Status::Reject, cons.format, " is unimplemented");
  309. }
  310. Status visit(constraint::AdditionalItemsConstraint const & cons,
  311. Adapter auto const & document) const {
  312. NOOP_UNLESS_TYPE(Array);
  313. auto array = document.as_array();
  314. Status rval = Status::Accept;
  315. std::vector<size_t> items;
  316. for (size_t i = cons.applies_after_nth; i < array.size(); ++i) {
  317. VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT(cons.subschema, array[i], i, items);
  318. BREAK_EARLY_IF_NO_RESULT_TREE();
  319. }
  320. annotate_list(items);
  321. return rval;
  322. }
  323. Status visit(constraint::ContainsConstraint const & cons, Adapter auto const & document) const {
  324. NOOP_UNLESS_TYPE(Array);
  325. auto array = document.as_array();
  326. size_t const minimum = cons.minimum.value_or(1);
  327. size_t const maximum = cons.maximum.value_or(array.size());
  328. size_t matches = 0;
  329. for (size_t i = 0; i < array.size(); ++i) {
  330. if (validate_subschema_on(cons.subschema, array[i], i)) {
  331. ++matches;
  332. }
  333. }
  334. if (matches < minimum) {
  335. return result(Status::Reject, "array contains <", minimum, " matching items");
  336. }
  337. if (matches > maximum) {
  338. return result(Status::Reject, "array contains >", maximum, " matching items");
  339. }
  340. return result(Status::Accept, "array contains ", matches, " matching items");
  341. }
  342. Status visit(constraint::MaxItemsConstraint const & cons, Adapter auto const & document) const {
  343. NOOP_UNLESS_TYPE(Array);
  344. size_t const size = document.array_size();
  345. if (size > cons.value) {
  346. return result(Status::Reject, "array of size ", size, " is >", cons.value);
  347. }
  348. return result(Status::Accept, "array of size ", size, " is <=", cons.value);
  349. }
  350. Status visit(constraint::MinItemsConstraint const & cons, Adapter auto const & document) const {
  351. NOOP_UNLESS_TYPE(Array);
  352. size_t const size = document.array_size();
  353. if (size < cons.value) {
  354. return result(Status::Reject, "array of size ", size, " is <", cons.value);
  355. }
  356. return result(Status::Accept, "array of size ", size, " is >=", cons.value);
  357. }
  358. Status visit(constraint::TupleConstraint const & cons, Adapter auto const & document) const {
  359. NOOP_UNLESS_TYPE(Array);
  360. Status rval = Status::Accept;
  361. std::vector<size_t> items;
  362. for (auto const & [index, item] : detail::enumerate(document.as_array())) {
  363. if (index >= cons.items.size()) {
  364. break;
  365. }
  366. VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT(cons.items[index], item, index, items);
  367. BREAK_EARLY_IF_NO_RESULT_TREE();
  368. }
  369. annotate_list(items);
  370. return rval;
  371. }
  372. template <Adapter A>
  373. Status visit(constraint::UniqueItemsConstraint const &, A const & document) const {
  374. NOOP_UNLESS_TYPE(Array);
  375. if constexpr (std::totally_ordered<A>) {
  376. // If the adapter defines comparison operators, then it becomes possible
  377. // to compute uniqueness in O(n*log(n)) checks.
  378. std::map<A, size_t> cache;
  379. for (auto const & [index, elem] : detail::enumerate(document.as_array())) {
  380. if (auto [it, created] = cache.emplace(elem, index); not created) {
  381. return result(Status::Reject, "items ", it->second, " and ", index, " are equal");
  382. }
  383. }
  384. } else {
  385. // Otherwise, we need to run an O(n^2) triangular array search comparing
  386. // equality for each element. This still guarantees that each element is
  387. // compared against each other element no more than once.
  388. auto array = document.as_array();
  389. for (size_t i = 0; i < array.size(); ++i) {
  390. for (size_t j = i + 1; j < array.size(); ++j) {
  391. if (array[i].equals(array[j], true)) {
  392. return result(Status::Reject, "items ", i, " and ", j, " are equal");
  393. }
  394. }
  395. }
  396. }
  397. return result(Status::Accept, "all array items are unique");
  398. }
  399. Status visit(constraint::AdditionalPropertiesConstraint const & cons,
  400. Adapter auto const & document) const {
  401. NOOP_UNLESS_TYPE(Object);
  402. auto matches_any_pattern = [this, &cons](std::string const & key) {
  403. return std::ranges::any_of(cons.patterns, [this, &key](auto const & pattern) {
  404. return regex_.search(pattern, key);
  405. });
  406. };
  407. Status rval = Status::Accept;
  408. std::vector<std::string> properties;
  409. for (auto const & [key, elem] : document.as_object()) {
  410. if (not cons.properties.contains(key) && not matches_any_pattern(key)) {
  411. VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT(cons.subschema, elem, key, properties);
  412. }
  413. BREAK_EARLY_IF_NO_RESULT_TREE();
  414. }
  415. annotate_list(properties);
  416. return rval;
  417. }
  418. Status visit(constraint::DependenciesConstraint const & cons,
  419. Adapter auto const & document) const {
  420. NOOP_UNLESS_TYPE(Object);
  421. auto object = document.as_object();
  422. Status rval = Status::Accept;
  423. for (auto const & [key, subschema] : cons.subschemas) {
  424. if (not object.contains(key)) {
  425. continue;
  426. }
  427. rval &= validate_subschema(subschema, document, key);
  428. BREAK_EARLY_IF_NO_RESULT_TREE();
  429. }
  430. for (auto [key, required] : cons.required) {
  431. if (not object.contains(key)) {
  432. continue;
  433. }
  434. for (auto const & [key, _] : object) {
  435. required.erase(key);
  436. }
  437. rval &= required.empty();
  438. BREAK_EARLY_IF_NO_RESULT_TREE();
  439. }
  440. return rval;
  441. }
  442. Status visit(constraint::MaxPropertiesConstraint const & cons,
  443. Adapter auto const & document) const {
  444. NOOP_UNLESS_TYPE(Object);
  445. size_t const size = document.object_size();
  446. if (size > cons.value) {
  447. return result(Status::Reject, "object of size ", size, " is >", cons.value);
  448. }
  449. return result(Status::Accept, "object of size ", size, " is <=", cons.value);
  450. }
  451. Status visit(constraint::MinPropertiesConstraint const & cons,
  452. Adapter auto const & document) const {
  453. NOOP_UNLESS_TYPE(Object);
  454. size_t const size = document.object_size();
  455. if (size < cons.value) {
  456. return result(Status::Reject, "object of size ", size, " is <", cons.value);
  457. }
  458. return result(Status::Accept, "object of size ", size, " is >=", cons.value);
  459. }
  460. Status visit(constraint::PatternPropertiesConstraint const & cons,
  461. Adapter auto const & document) const {
  462. NOOP_UNLESS_TYPE(Object);
  463. std::vector<std::string> properties;
  464. Status rval = Status::Accept;
  465. for (auto const & [pattern, subschema] : cons.properties) {
  466. for (auto const & [key, elem] : document.as_object()) {
  467. if (not regex_.search(pattern, key)) {
  468. continue;
  469. }
  470. VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT(subschema, elem, key, properties);
  471. BREAK_EARLY_IF_NO_RESULT_TREE();
  472. }
  473. }
  474. annotate_list(properties);
  475. return rval;
  476. }
  477. template <Adapter A>
  478. Status visit(constraint::PropertiesConstraint const & cons, A const & document) const {
  479. NOOP_UNLESS_TYPE(Object);
  480. Status rval = Status::Accept;
  481. auto object = document.as_object();
  482. if constexpr (MutableAdapter<A>) {
  483. // Special Rule - if the adapter is of a mutable json document (wraps a
  484. // non-const reference and exposes the assign function) we will process
  485. // the "default" annotation will be applied.
  486. // https://json-schema.org/draft/2020-12/json-schema-validation#section-9.2
  487. //
  488. // Although the JSON Schema draft only says the the default value ought be
  489. // valid against the schema, this implementation will assure that it is
  490. // valid against this PropertiesConstraint, and any other constraints that
  491. // are run after this one.
  492. for (auto const & [key, subschema] : cons.properties) {
  493. auto const * default_value = subschema->default_value();
  494. if (default_value && not object.contains(key)) {
  495. object.assign(key, *default_value);
  496. }
  497. }
  498. }
  499. std::vector<std::string> properties;
  500. for (auto const & [key, elem] : object) {
  501. if (auto it = cons.properties.find(key); it != cons.properties.end()) {
  502. VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT(it->second, elem, key, properties, key);
  503. }
  504. BREAK_EARLY_IF_NO_RESULT_TREE();
  505. }
  506. annotate_list(properties);
  507. return rval;
  508. }
  509. Status visit(constraint::PropertyNamesConstraint const & cons,
  510. Adapter auto const & document) const {
  511. NOOP_UNLESS_TYPE(Object);
  512. Status rval = Status::Accept;
  513. for (auto const & [key, _] : document.as_object()) {
  514. rval &=
  515. validate_subschema_on(cons.key_schema, detail::StringAdapter(key), std::string("$$key"));
  516. }
  517. return rval;
  518. }
  519. Status visit(constraint::RequiredConstraint const & cons, Adapter auto const & document) const {
  520. NOOP_UNLESS_TYPE(Object);
  521. auto required = cons.properties;
  522. for (auto const & [key, _] : document.as_object()) {
  523. required.erase(key);
  524. }
  525. if (required.empty()) {
  526. return result(Status::Accept, "contains all required properties ", cons.properties);
  527. }
  528. return result(Status::Reject, "missing required properties ", required);
  529. }
  530. Status visit(constraint::UnevaluatedItemsConstraint const & cons,
  531. Adapter auto const & document) const {
  532. NOOP_UNLESS_TYPE(Array);
  533. if (not visited_) {
  534. return Status::Reject;
  535. }
  536. Status rval = Status::Accept;
  537. std::vector<size_t> items;
  538. for (auto const & [index, item] : detail::enumerate(document.as_array())) {
  539. if (not VISITED(size_t).contains(index)) {
  540. VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT(cons.subschema, item, index, items);
  541. }
  542. BREAK_EARLY_IF_NO_RESULT_TREE();
  543. }
  544. annotate_list(items);
  545. return rval;
  546. }
  547. Status visit(constraint::UnevaluatedPropertiesConstraint const & cons,
  548. Adapter auto const & document) const {
  549. NOOP_UNLESS_TYPE(Object);
  550. if (not visited_) {
  551. return Status::Reject;
  552. }
  553. Status rval = Status::Accept;
  554. std::vector<std::string> properties;
  555. for (auto const & [key, elem] : document.as_object()) {
  556. if (not VISITED(std::string).contains(key)) {
  557. VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT(cons.subschema, elem, key, properties);
  558. }
  559. BREAK_EARLY_IF_NO_RESULT_TREE();
  560. }
  561. annotate_list(properties);
  562. return rval;
  563. }
  564. public:
  565. /**
  566. * @brief The main entry point into the validator. Validates the provided
  567. * document according to the schema. This function should only be called
  568. * internally (validate_subschema/validate_subschema_on) or via the Validator
  569. * class.
  570. */
  571. Status validate(Adapter auto const & document) {
  572. // Step 1) Check if this is an always-false schema. Sometimes, this will
  573. // have a custom message.
  574. if (std::optional<std::string> const & reject = schema_->rejects_all()) {
  575. if (should_annotate(Status::Reject)) {
  576. // This will only be run if we are interested in why something is
  577. // rejected. For example - `{ "not": false }` doesn't produce a
  578. // meaningful annotation...
  579. result_->error(where_, schema_path_, "", *reject);
  580. }
  581. // ...We do always record the result if a result object is present.
  582. (result_ ? result_->valid(where_, schema_path_, false) : void());
  583. return Status::Reject;
  584. }
  585. if (schema_->accepts_all()) {
  586. // An accept-all schema is not No-Op for the purpose of unevaluated*
  587. (result_ ? result_->valid(where_, schema_path_, true) : void());
  588. return Status::Accept;
  589. }
  590. // Begin tracking evaluations for unevaluated* keywords. The annotation
  591. // object is passed down from parent visitor to child visitor to allow all
  592. // schemas to mark whether they visited a certain item or property.
  593. VisitedAnnotation annotate;
  594. if (schema_->requires_result_context() and not visited_) {
  595. visited_ = &annotate;
  596. }
  597. Status rval = Status::Noop;
  598. // Before Draft2019_09, reference schemas could not coexist with other
  599. // constraints. This is enforced in the parsing of the schema, rather than
  600. // during validation {@see jvalidate::schema::Node::construct}.
  601. if (std::optional<schema::Node const *> ref = schema_->reference_schema()) {
  602. // TODO(samjaffe): Investigate why this seems to produce .../$ref/$ref pointers
  603. rval = validate_subschema(*ref, document, "$ref");
  604. }
  605. if (result_ && !schema_->description().empty()) {
  606. result_->annotate(where_, schema_path_, "description", schema_->description());
  607. }
  608. detail::Pointer const current_schema = schema_path_;
  609. for (auto const & [key, p_constraint] : schema_->constraints()) {
  610. BREAK_EARLY_IF_NO_RESULT_TREE();
  611. schema_path_ = current_schema / key;
  612. rval &= std::visit([this, &document](auto & cons) { return this->visit(cons, document); },
  613. *p_constraint);
  614. }
  615. // Post Constraints represent the unevaluatedItems and unevaluatedProperties
  616. // keywords.
  617. for (auto const & [key, p_constraint] : schema_->post_constraints()) {
  618. BREAK_EARLY_IF_NO_RESULT_TREE();
  619. schema_path_ = current_schema / key;
  620. rval &= std::visit([this, &document](auto & cons) { return this->visit(cons, document); },
  621. *p_constraint);
  622. }
  623. (result_ ? result_->valid(where_, current_schema, static_cast<bool>(rval)) : void());
  624. return rval;
  625. }
  626. // Functions to grant access to some, but not all of the internals of the
  627. // ValidationVisitor for the purposes of implementing ExtensionVisitor
  628. // validators.
  629. detail::Pointer const & where() const { return where_; }
  630. Root const & root() const { return *root_; }
  631. ValidationConfig const & config() const { return cfg_; }
  632. RE & regex() const { return regex_; }
  633. /**
  634. * @brief Allow ExtensionVisitor to enter a state similar to a NotConstraint
  635. * when calling sub-requests.
  636. *
  637. * @return A ScopedState object that will restore the tracking mode once it
  638. * is destroyed.
  639. */
  640. [[nodiscard]] auto invert_tracking() const { return detail::ScopedState(tracking_, !tracking_); }
  641. /**
  642. * @brief Allow ExtensionVisitor to enable tracking of all results in child
  643. * constraints.
  644. *
  645. * @return A ScopedState object that will restore the tracking mode once it
  646. * is destroyed.
  647. */
  648. [[nodiscard]] auto track_everything() const {
  649. return detail::ScopedState(tracking_, StoreResults::ForAnything);
  650. }
  651. ANNOTATION_HELPER(error, error, jvalidate::to_string)
  652. ANNOTATION_HELPER(annotate, annotate, jvalidate::to_string)
  653. ANNOTATION_HELPER(annotate_list, annotate, jvalidate::to_string_list)
  654. bool should_annotate(Status stat) const {
  655. if (not result_) {
  656. return false;
  657. }
  658. switch (*tracking_) {
  659. case StoreResults::ForAnything:
  660. return stat != Status::Noop;
  661. case StoreResults::ForValid:
  662. return stat == Status::Accept;
  663. case StoreResults::ForInvalid:
  664. return stat == Status::Reject;
  665. }
  666. }
  667. Status result(Status stat, auto const &... args) const {
  668. return (should_annotate(stat) ? error(args...) : void(), stat);
  669. }
  670. /**
  671. * @brief Walking function for entering a subschema.
  672. *
  673. * @param subschema The "subschema" being validated. This is either another
  674. * schema object (jvalidate::schema::Node), or a constraint.
  675. * @param keys... The path to this subschema, relative to the current schema
  676. * evaluation.
  677. *
  678. * @return The status of validating the current instance against the
  679. * subschema.
  680. */
  681. template <typename... K>
  682. Status validate_subschema(constraint::SubConstraint const & subschema,
  683. Adapter auto const & document, K const &... keys) const {
  684. if (schema::Node const * const * ppschema = std::get_if<0>(&subschema)) {
  685. return validate_subschema(*ppschema, document, keys...);
  686. }
  687. return std::visit([this, &document](auto & cons) { return this->visit(cons, document); },
  688. *std::get<1>(subschema));
  689. }
  690. /**
  691. * @brief Walking function for entering a subschema. Creates a new validation
  692. * visitor in order to continue evaluation.
  693. *
  694. * @param subschema The subschema being validated.
  695. * @param keys... The path to this subschema, relative to the current schema
  696. * evaluation.
  697. *
  698. * @return The status of validating the current instance against the
  699. * subschema.
  700. */
  701. template <typename... K>
  702. Status validate_subschema(schema::Node const * subschema, Adapter auto const & document,
  703. K const &... keys) const {
  704. VisitedAnnotation annotate;
  705. ValidationVisitor next = *this;
  706. ((next.schema_path_ /= keys), ...);
  707. std::tie(next.schema_, next.visited_) =
  708. std::forward_as_tuple(subschema, visited_ ? &annotate : nullptr);
  709. Status rval = next.validate(document);
  710. // Only update the visited annotation of the current context if the
  711. // subschema validates as Accepted.
  712. if (rval == Status::Accept and visited_) {
  713. std::get<0>(*visited_).merge(std::get<0>(annotate));
  714. std::get<1>(*visited_).merge(std::get<1>(annotate));
  715. }
  716. return rval;
  717. }
  718. /**
  719. * @brief Walking function for entering a subschema and child document.
  720. * Creates a new validation visitor in order to continue evaluation.
  721. *
  722. * @param subschema The subschema being validated.
  723. * @param document The child document being evaluated.
  724. * @param key The path to this document instance.
  725. * @param schema_keys... The path to this subschema, relative to the current
  726. * schema evaluation.
  727. *
  728. * @return The status of validating the current instance against the
  729. * subschema.
  730. */
  731. template <typename K>
  732. Status validate_subschema_on(schema::Node const * subschema, Adapter auto const & document,
  733. K const & key, auto const &... schema_keys) const {
  734. ValidationResult result;
  735. ValidationVisitor next = *this;
  736. next.where_ /= key;
  737. ((next.schema_path_ /= schema_keys), ...);
  738. std::tie(next.schema_, next.result_, next.visited_) =
  739. std::forward_as_tuple(subschema, result_ ? &result : nullptr, nullptr);
  740. Status rval = next.validate(document);
  741. // Only update the visited annotation of the current context if the
  742. // subschema validates as Accepted.
  743. if (rval == Status::Accept and visited_) {
  744. VISITED(K).insert(key);
  745. }
  746. // Update the annotation/error content only if a failure is being reported,
  747. // or if we are in an "if" schema.
  748. if (should_annotate(rval)) {
  749. result_->merge(std::move(result));
  750. }
  751. return rval;
  752. }
  753. };
  754. }
  755. #undef ANNOTATION_HELPER
  756. #undef BREAK_EARLY_IF_NO_RESULT_TREE
  757. #undef NOOP_UNLESS_TYPE
  758. #undef VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT
  759. #undef VISITED