validation_visitor.h 33 KB

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