validation_visitor.h 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  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/format.h>
  19. #include <jvalidate/forward.h>
  20. #include <jvalidate/schema.h>
  21. #include <jvalidate/status.h>
  22. #include <jvalidate/validation_config.h>
  23. #include <jvalidate/validation_result.h>
  24. #define VISITED(type) std::get<std::unordered_set<type>>(*visited_)
  25. #define VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT(subschema, subinstance, path, local_visited, ...) \
  26. do { \
  27. Status const partial = \
  28. validate_subschema_on(subschema, subinstance, path __VA_OPT__(, ) __VA_ARGS__); \
  29. rval &= partial; \
  30. if (result_ and partial != Status::Noop) { \
  31. local_visited.insert(local_visited.end(), path); \
  32. } \
  33. } while (false)
  34. #define NOOP_UNLESS_TYPE(etype) RETURN_UNLESS(adapter::Type::etype == document.type(), Status::Noop)
  35. #define BREAK_EARLY_IF_NO_RESULT_TREE() \
  36. do { \
  37. if (rval == Status::Reject and not result_ and not visited_) { \
  38. break; \
  39. } \
  40. } while (false)
  41. #define ANNOTATION_HELPER(name, ADD, FMT) \
  42. void name(auto const &... args) const { \
  43. if (not result_) { \
  44. /* do nothing if there's no result object to append to */ \
  45. } else if (schema_path_.empty()) { \
  46. result_->ADD(where_, schema_path_, "", FMT(args...)); \
  47. } else { \
  48. result_->ADD(where_, schema_path_.parent(), schema_path_.back(), FMT(args...)); \
  49. } \
  50. }
  51. namespace jvalidate {
  52. template <Adapter Root, RegexEngine RE, typename ExtensionVisitor> class ValidationVisitor {
  53. private:
  54. JVALIDATE_TRIBOOL_TYPE(StoreResults, ForValid, ForInvalid, ForAnything);
  55. using VisitedAnnotation = std::tuple<std::unordered_set<size_t>, std::unordered_set<std::string>>;
  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. switch (FormatValidator()(cons.format, document.as_string())) {
  294. case FormatValidator::Status::Unimplemented:
  295. return result(Status::Reject, "unimplemented format '", cons.format, "'");
  296. case FormatValidator::Status::Invalid:
  297. return result(Status::Reject, "does not match format '", cons.format, "'");
  298. case FormatValidator::Status::Unknown:
  299. case FormatValidator::Status::Valid:
  300. return result(Status::Accept, "matches format '", cons.format, "'");
  301. }
  302. }
  303. Status visit(constraint::AdditionalItemsConstraint const & cons,
  304. Adapter auto const & document) const {
  305. NOOP_UNLESS_TYPE(Array);
  306. auto array = document.as_array();
  307. Status rval = Status::Accept;
  308. std::vector<size_t> items;
  309. for (size_t i = cons.applies_after_nth; i < array.size(); ++i) {
  310. VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT(cons.subschema, array[i], i, items);
  311. BREAK_EARLY_IF_NO_RESULT_TREE();
  312. }
  313. annotate_list(items);
  314. return rval;
  315. }
  316. Status visit(constraint::ContainsConstraint const & cons, Adapter auto const & document) const {
  317. NOOP_UNLESS_TYPE(Array);
  318. auto array = document.as_array();
  319. size_t const minimum = cons.minimum.value_or(1);
  320. size_t const maximum = cons.maximum.value_or(array.size());
  321. size_t matches = 0;
  322. for (size_t i = 0; i < array.size(); ++i) {
  323. if (validate_subschema_on(cons.subschema, array[i], i)) {
  324. ++matches;
  325. }
  326. }
  327. if (matches < minimum) {
  328. return result(Status::Reject, "array contains <", minimum, " matching items");
  329. }
  330. if (matches > maximum) {
  331. return result(Status::Reject, "array contains >", maximum, " matching items");
  332. }
  333. return result(Status::Accept, "array contains ", matches, " matching items");
  334. }
  335. Status visit(constraint::MaxItemsConstraint 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::MinItemsConstraint const & cons, Adapter auto const & document) const {
  344. NOOP_UNLESS_TYPE(Array);
  345. if (size_t size = document.array_size(); size < cons.value) {
  346. return result(Status::Reject, "array of size ", size, " is <", cons.value);
  347. } else {
  348. return result(Status::Accept, "array of size ", size, " is >=", cons.value);
  349. }
  350. }
  351. Status visit(constraint::TupleConstraint const & cons, Adapter auto const & document) const {
  352. NOOP_UNLESS_TYPE(Array);
  353. Status rval = Status::Accept;
  354. std::vector<size_t> items;
  355. for (auto const & [index, item] : detail::enumerate(document.as_array())) {
  356. if (index >= cons.items.size()) {
  357. break;
  358. }
  359. VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT(cons.items[index], item, index, items);
  360. BREAK_EARLY_IF_NO_RESULT_TREE();
  361. }
  362. annotate_list(items);
  363. return rval;
  364. }
  365. template <Adapter A>
  366. Status visit(constraint::UniqueItemsConstraint const & cons, A const & document) const {
  367. NOOP_UNLESS_TYPE(Array);
  368. if constexpr (std::totally_ordered<A>) {
  369. // If the adapter defines comparison operators, then it becomes possible
  370. // to compute uniqueness in O(n*log(n)) checks.
  371. std::map<A, size_t> cache;
  372. for (auto const & [index, elem] : detail::enumerate(document.as_array())) {
  373. if (auto [it, created] = cache.emplace(elem, index); not created) {
  374. return result(Status::Reject, "items ", it->second, " and ", index, " are equal");
  375. }
  376. }
  377. } else {
  378. // Otherwise, we need to run an O(n^2) triangular array search comparing
  379. // equality for each element. This still guarantees that each element is
  380. // compared against each other element no more than once.
  381. auto array = document.as_array();
  382. for (size_t i = 0; i < array.size(); ++i) {
  383. for (size_t j = i + 1; j < array.size(); ++j) {
  384. if (array[i].equals(array[j], true)) {
  385. return result(Status::Reject, "items ", i, " and ", j, " are equal");
  386. }
  387. }
  388. }
  389. }
  390. return result(Status::Accept, "all array items are unique");
  391. }
  392. Status visit(constraint::AdditionalPropertiesConstraint const & cons,
  393. Adapter auto const & document) const {
  394. NOOP_UNLESS_TYPE(Object);
  395. auto matches_any_pattern = [this, &cons](std::string const & key) {
  396. return std::ranges::any_of(cons.patterns, [this, &key](auto const & pattern) {
  397. return regex_.search(pattern, key);
  398. });
  399. };
  400. Status rval = Status::Accept;
  401. std::vector<std::string> properties;
  402. for (auto const & [key, elem] : document.as_object()) {
  403. if (not cons.properties.contains(key) && not matches_any_pattern(key)) {
  404. VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT(cons.subschema, elem, key, properties);
  405. }
  406. BREAK_EARLY_IF_NO_RESULT_TREE();
  407. }
  408. annotate_list(properties);
  409. return rval;
  410. }
  411. Status visit(constraint::DependenciesConstraint const & cons,
  412. Adapter auto const & document) const {
  413. NOOP_UNLESS_TYPE(Object);
  414. auto object = document.as_object();
  415. Status rval = Status::Accept;
  416. for (auto const & [key, subschema] : cons.subschemas) {
  417. if (not object.contains(key)) {
  418. continue;
  419. }
  420. rval &= validate_subschema(subschema, document, key);
  421. BREAK_EARLY_IF_NO_RESULT_TREE();
  422. }
  423. for (auto [key, required] : cons.required) {
  424. if (not object.contains(key)) {
  425. continue;
  426. }
  427. for (auto const & [key, _] : object) {
  428. required.erase(key);
  429. }
  430. rval &= required.empty();
  431. BREAK_EARLY_IF_NO_RESULT_TREE();
  432. }
  433. return rval;
  434. }
  435. Status visit(constraint::MaxPropertiesConstraint const & cons,
  436. Adapter auto const & document) const {
  437. NOOP_UNLESS_TYPE(Object);
  438. if (size_t size = document.object_size(); size > cons.value) {
  439. return result(Status::Reject, "object of size ", size, " is >", cons.value);
  440. } else {
  441. return result(Status::Accept, "object of size ", size, " is <=", cons.value);
  442. }
  443. }
  444. Status visit(constraint::MinPropertiesConstraint const & cons,
  445. Adapter auto const & document) const {
  446. NOOP_UNLESS_TYPE(Object);
  447. if (size_t size = document.object_size(); size < cons.value) {
  448. return result(Status::Reject, "object of size ", size, " is <", cons.value);
  449. } else {
  450. return result(Status::Accept, "object of size ", size, " is >=", cons.value);
  451. }
  452. }
  453. Status visit(constraint::PatternPropertiesConstraint const & cons,
  454. Adapter auto const & document) const {
  455. NOOP_UNLESS_TYPE(Object);
  456. std::vector<std::string> properties;
  457. Status rval = Status::Accept;
  458. for (auto const & [pattern, subschema] : cons.properties) {
  459. for (auto const & [key, elem] : document.as_object()) {
  460. if (not regex_.search(pattern, key)) {
  461. continue;
  462. }
  463. VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT(subschema, elem, key, properties);
  464. BREAK_EARLY_IF_NO_RESULT_TREE();
  465. }
  466. }
  467. annotate_list(properties);
  468. return rval;
  469. }
  470. template <Adapter A>
  471. Status visit(constraint::PropertiesConstraint const & cons, A const & document) const {
  472. NOOP_UNLESS_TYPE(Object);
  473. Status rval = Status::Accept;
  474. auto object = document.as_object();
  475. if constexpr (MutableAdapter<A>) {
  476. // Special Rule - if the adapter is of a mutable json document (wraps a
  477. // non-const reference and exposes the assign function) we will process
  478. // the "default" annotation will be applied.
  479. // https://json-schema.org/draft/2020-12/json-schema-validation#section-9.2
  480. //
  481. // Although the JSON Schema draft only says the the default value ought be
  482. // valid against the schema, this implementation will assure that it is
  483. // valid against this PropertiesConstraint, and any other constraints that
  484. // are run after this one.
  485. for (auto const & [key, subschema] : cons.properties) {
  486. auto const * default_value = subschema->default_value();
  487. if (default_value && not object.contains(key)) {
  488. object.assign(key, *default_value);
  489. }
  490. }
  491. }
  492. std::vector<std::string> properties;
  493. for (auto const & [key, elem] : object) {
  494. if (auto it = cons.properties.find(key); it != cons.properties.end()) {
  495. VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT(it->second, elem, key, properties, key);
  496. }
  497. BREAK_EARLY_IF_NO_RESULT_TREE();
  498. }
  499. annotate_list(properties);
  500. return rval;
  501. }
  502. Status visit(constraint::PropertyNamesConstraint const & cons,
  503. Adapter auto const & document) const {
  504. NOOP_UNLESS_TYPE(Object);
  505. Status rval = Status::Accept;
  506. for (auto const & [key, _] : document.as_object()) {
  507. rval &=
  508. validate_subschema_on(cons.key_schema, detail::StringAdapter(key), std::string("$$key"));
  509. }
  510. return rval;
  511. }
  512. Status visit(constraint::RequiredConstraint const & cons, Adapter auto const & document) const {
  513. NOOP_UNLESS_TYPE(Object);
  514. auto required = cons.properties;
  515. for (auto const & [key, _] : document.as_object()) {
  516. required.erase(key);
  517. }
  518. if (required.empty()) {
  519. return result(Status::Accept, "contains all required properties ", cons.properties);
  520. }
  521. return result(Status::Reject, "missing required properties ", required);
  522. }
  523. Status visit(constraint::UnevaluatedItemsConstraint const & cons,
  524. Adapter auto const & document) const {
  525. NOOP_UNLESS_TYPE(Array);
  526. if (not visited_) {
  527. return Status::Reject;
  528. }
  529. Status rval = Status::Accept;
  530. std::vector<size_t> items;
  531. for (auto const & [index, item] : detail::enumerate(document.as_array())) {
  532. if (not VISITED(size_t).contains(index)) {
  533. VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT(cons.subschema, item, index, items);
  534. }
  535. BREAK_EARLY_IF_NO_RESULT_TREE();
  536. }
  537. annotate_list(items);
  538. return rval;
  539. }
  540. Status visit(constraint::UnevaluatedPropertiesConstraint const & cons,
  541. Adapter auto const & document) const {
  542. NOOP_UNLESS_TYPE(Object);
  543. if (not visited_) {
  544. return Status::Reject;
  545. }
  546. Status rval = Status::Accept;
  547. std::vector<std::string> properties;
  548. for (auto const & [key, elem] : document.as_object()) {
  549. if (not VISITED(std::string).contains(key)) {
  550. VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT(cons.subschema, elem, key, properties);
  551. }
  552. BREAK_EARLY_IF_NO_RESULT_TREE();
  553. }
  554. annotate_list(properties);
  555. return rval;
  556. }
  557. public:
  558. /**
  559. * @brief The main entry point into the validator. Validates the provided
  560. * document according to the schema. This function should only be called
  561. * internally (validate_subschema/validate_subschema_on) or via the Validator
  562. * class.
  563. */
  564. Status validate(Adapter auto const & document) {
  565. // Step 1) Check if this is an always-false schema. Sometimes, this will
  566. // have a custom message.
  567. if (std::optional<std::string> const & reject = schema_->rejects_all()) {
  568. if (should_annotate(Status::Reject)) {
  569. // This will only be run if we are interested in why something is
  570. // rejected. For example - `{ "not": false }` doesn't produce a
  571. // meaningful annotation...
  572. result_->error(where_, schema_path_, "", *reject);
  573. }
  574. // ...We do always record the result if a result object is present.
  575. (result_ ? result_->valid(where_, schema_path_, false) : void());
  576. return Status::Reject;
  577. }
  578. if (schema_->accepts_all()) {
  579. // An accept-all schema is not No-Op for the purpose of unevaluated*
  580. (result_ ? result_->valid(where_, schema_path_, true) : void());
  581. return Status::Accept;
  582. }
  583. // Begin tracking evaluations for unevaluated* keywords. The annotation
  584. // object is passed down from parent visitor to child visitor to allow all
  585. // schemas to mark whether they visited a certain item or property.
  586. VisitedAnnotation annotate;
  587. if (schema_->requires_result_context() and not visited_) {
  588. visited_ = &annotate;
  589. }
  590. Status rval = Status::Noop;
  591. // Before Draft2019_09, reference schemas could not coexist with other
  592. // constraints. This is enforced in the parsing of the schema, rather than
  593. // during validation {@see jvalidate::schema::Node::construct}.
  594. if (std::optional<schema::Node const *> ref = schema_->reference_schema()) {
  595. // TODO: Investigate why this seems to produce .../$ref/$ref pointers
  596. rval = validate_subschema(*ref, document, "$ref");
  597. }
  598. if (result_ && !schema_->description().empty()) {
  599. result_->annotate(where_, schema_path_, "description", schema_->description());
  600. }
  601. detail::Pointer const current_schema = schema_path_;
  602. for (auto const & [key, p_constraint] : schema_->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. // Post Constraints represent the unevaluatedItems and unevaluatedProperties
  609. // keywords.
  610. for (auto const & [key, p_constraint] : schema_->post_constraints()) {
  611. BREAK_EARLY_IF_NO_RESULT_TREE();
  612. schema_path_ = current_schema / key;
  613. rval &= std::visit([this, &document](auto & c) { return this->visit(c, document); },
  614. *p_constraint);
  615. }
  616. (result_ ? result_->valid(where_, current_schema, static_cast<bool>(rval)) : void());
  617. return rval;
  618. }
  619. // Functions to grant access to some, but not all of the internals of the
  620. // ValidationVisitor for the purposes of implementing ExtensionVisitor
  621. // validators.
  622. detail::Pointer const & where() const { return where_; }
  623. Root const & root() const { return *root_; }
  624. ValidationConfig const & config() const { return cfg_; }
  625. RE & regex() const { return regex_; }
  626. /**
  627. * @brief Allow ExtensionVisitor to enter a state similar to a NotConstraint
  628. * when calling sub-requests.
  629. *
  630. * @return A ScopedState object that will restore the tracking mode once it
  631. * is destroyed.
  632. */
  633. [[nodiscard]] detail::ScopedState invert_tracking() const {
  634. return detail::ScopedState(tracking_, !tracking_);
  635. }
  636. /**
  637. * @brief Allow ExtensionVisitor to enable tracking of all results in child
  638. * constraints.
  639. *
  640. * @return A ScopedState object that will restore the tracking mode once it
  641. * is destroyed.
  642. */
  643. [[nodiscard]] detail::ScopedState track_everything() const {
  644. return detail::ScopedState(tracking_, StoreResults::ForAnything);
  645. }
  646. ANNOTATION_HELPER(error, error, jvalidate::to_string)
  647. ANNOTATION_HELPER(annotate, annotate, jvalidate::to_string)
  648. ANNOTATION_HELPER(annotate_list, annotate, jvalidate::to_string_list)
  649. bool should_annotate(Status stat) const {
  650. if (not result_) {
  651. return false;
  652. }
  653. switch (*tracking_) {
  654. case StoreResults::ForAnything:
  655. return stat != Status::Noop;
  656. case StoreResults::ForValid:
  657. return stat == Status::Accept;
  658. case StoreResults::ForInvalid:
  659. return stat == Status::Reject;
  660. }
  661. }
  662. Status result(Status stat, auto const &... args) const {
  663. return (should_annotate(stat) ? error(args...) : void(), stat);
  664. }
  665. /**
  666. * @brief Walking function for entering a subschema.
  667. *
  668. * @param subschema The "subschema" being validated. This is either another
  669. * schema object (jvalidate::schema::Node), or a constraint.
  670. * @param keys... The path to this subschema, relative to the current schema
  671. * evaluation.
  672. *
  673. * @return The status of validating the current instance against the
  674. * subschema.
  675. */
  676. template <typename... K>
  677. Status validate_subschema(constraint::SubConstraint const & subschema,
  678. Adapter auto const & document, K const &... keys) const {
  679. if (schema::Node const * const * ppschema = std::get_if<0>(&subschema)) {
  680. return validate_subschema(*ppschema, document, keys...);
  681. } else {
  682. return std::visit([this, &document](auto & c) { return this->visit(c, document); },
  683. *std::get<1>(subschema));
  684. }
  685. }
  686. /**
  687. * @brief Walking function for entering a subschema. Creates a new validation
  688. * visitor in order to continue evaluation.
  689. *
  690. * @param subschema The subschema being validated.
  691. * @param keys... The path to this subschema, relative to the current schema
  692. * evaluation.
  693. *
  694. * @return The status of validating the current instance against the
  695. * subschema.
  696. */
  697. template <typename... K>
  698. Status validate_subschema(schema::Node const * subschema, Adapter auto const & document,
  699. K const &... keys) const {
  700. VisitedAnnotation annotate;
  701. ValidationVisitor next = *this;
  702. ((next.schema_path_ /= keys), ...);
  703. std::tie(next.schema_, next.visited_) =
  704. std::forward_as_tuple(subschema, visited_ ? &annotate : nullptr);
  705. Status rval = next.validate(document);
  706. // Only update the visited annotation of the current context if the
  707. // subschema validates as Accepted.
  708. if (rval == Status::Accept and visited_) {
  709. std::get<0>(*visited_).merge(std::get<0>(annotate));
  710. std::get<1>(*visited_).merge(std::get<1>(annotate));
  711. }
  712. return rval;
  713. }
  714. /**
  715. * @brief Walking function for entering a subschema and child document.
  716. * Creates a new validation visitor in order to continue evaluation.
  717. *
  718. * @param subschema The subschema being validated.
  719. * @param document The child document being evaluated.
  720. * @param key The path to this document instance.
  721. * @param schema_keys... The path to this subschema, relative to the current
  722. * schema evaluation.
  723. *
  724. * @return The status of validating the current instance against the
  725. * subschema.
  726. */
  727. template <typename K>
  728. Status validate_subschema_on(schema::Node const * subschema, Adapter auto const & document,
  729. K const & key, auto const &... schema_keys) const {
  730. ValidationResult result;
  731. ValidationVisitor next = *this;
  732. next.where_ /= key;
  733. ((next.schema_path_ /= schema_keys), ...);
  734. std::tie(next.schema_, next.result_, next.visited_) =
  735. std::forward_as_tuple(subschema, result_ ? &result : nullptr, nullptr);
  736. Status rval = next.validate(document);
  737. // Only update the visited annotation of the current context if the
  738. // subschema validates as Accepted.
  739. if (rval == Status::Accept and visited_) {
  740. VISITED(K).insert(key);
  741. }
  742. // Update the annotation/error content only if a failure is being reported,
  743. // or if we are in an "if" schema.
  744. if (should_annotate(rval)) {
  745. result_->merge(std::move(result));
  746. }
  747. return rval;
  748. }
  749. };
  750. }
  751. #undef ANNOTATION_HELPER
  752. #undef BREAK_EARLY_IF_NO_RESULT_TREE
  753. #undef NOOP_UNLESS_TYPE
  754. #undef VALIDATE_SUBSCHEMA_AND_MARK_LOCAL_VISIT
  755. #undef VISITED