validation_visitor.h 32 KB

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