validation_result.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. #pragma once
  2. #include <map>
  3. #include <ostream>
  4. #include <utility>
  5. #include <variant>
  6. #include <vector>
  7. #include <jvalidate/detail/pointer.h>
  8. #include <jvalidate/forward.h>
  9. namespace jvalidate {
  10. class ValidationResult {
  11. public:
  12. // Only allow ValidationVisitor to construct the elements of a validation result
  13. template <RegexEngine, typename> friend class ValidationVisitor;
  14. using DocPointer = detail::Pointer;
  15. using SchemaPointer = detail::Pointer;
  16. using Annotation = std::variant<std::string, std::vector<std::string>>;
  17. /**
  18. * @brief The result info at any given (DocPointer, SchemaPointer) path.
  19. * The key for errors/annotations represents the leaf element of SchemaPointer
  20. * instead of including it in the map.
  21. *
  22. * This allows better locality of error info. For example:
  23. * {
  24. * "valid": false,
  25. * "evaluationPath": "/definitions/EvenPercent",
  26. * "instanceLocation": "/foo/bar/percentages/2",
  27. * "errors": {
  28. * "max": "105 > 100",
  29. * "multipleOf": "105 is not a multiple of 2"
  30. * }
  31. * }
  32. */
  33. struct LocalResult {
  34. bool valid = true;
  35. std::map<std::string, Annotation> errors;
  36. std::map<std::string, Annotation> annotations;
  37. };
  38. struct indent {
  39. indent(int i) : i(i) {}
  40. friend std::ostream & operator<<(std::ostream & os, indent id) {
  41. while (id.i-- > 0)
  42. os << " ";
  43. return os;
  44. }
  45. int i;
  46. };
  47. private:
  48. bool valid_;
  49. std::map<DocPointer, std::map<SchemaPointer, LocalResult>> results_;
  50. public:
  51. /**
  52. * @brief Writes this object to an osteam in the list format as described in
  53. * https://json-schema.org/blog/posts/interpreting-output
  54. * This means that the json-schema for a ValidationResult looks like this:
  55. * {
  56. * "$defs": {
  57. * "Pointer": {
  58. * "format": "json-pointer",
  59. * "type": "string"
  60. * },
  61. * "Annotation": {
  62. * "items": { "type": "string" },
  63. * "type": [ "string", "array" ]
  64. * }
  65. * },
  66. * "properties": {
  67. * "valid": { "type": "boolean" },
  68. * "details": {
  69. * "items": {
  70. * "properties": {
  71. * "valid": { "type": "boolean" },
  72. * "evaluationPath": { "$ref": "#/$defs/Pointer" },
  73. * "instanceLocation": { "$ref": "#/$defs/Pointer" },
  74. * "annotations": { "$ref": "#/$defs/Annotation" },
  75. * "errors": { "$ref": "#/$defs/Annotation" }
  76. * }
  77. * "type": "object"
  78. * },
  79. * "type": "array"
  80. * }
  81. * }
  82. * "type": "object"
  83. * }
  84. */
  85. friend std::ostream & operator<<(std::ostream & os, ValidationResult const & result) {
  86. char const * div = "\n";
  87. os << "{\n" << indent(1) << R"("valid": )" << (result.valid_ ? "true" : "false") << ',' << '\n';
  88. os << indent(1) << R"("details": [)";
  89. for (auto const & [doc_path, by_schema] : result.results_) {
  90. for (auto const & [schema_path, local] : by_schema) {
  91. os << std::exchange(div, ",\n") << indent(2) << '{' << '\n';
  92. os << indent(3) << R"("valid": )" << (local.valid ? "true" : "false") << ',' << '\n';
  93. os << indent(3) << R"("evaluationPath": ")" << schema_path << '"' << ',' << '\n';
  94. os << indent(3) << R"("instanceLocation": ")" << doc_path << '"';
  95. print(os, local.annotations, "annotations", 3);
  96. print(os, local.errors, "errors", 3);
  97. os << '\n' << indent(2) << '}';
  98. }
  99. }
  100. return os << '\n' << indent(1) << ']' << '\n' << '}';
  101. }
  102. static void print(std::ostream & os, std::map<std::string, Annotation> const & named,
  103. std::string_view name, int const i) {
  104. if (named.empty()) {
  105. return;
  106. }
  107. os << ',' << '\n';
  108. os << indent(i) << '"' << name << '"' << ':' << ' ' << '{' << '\n';
  109. char const * odiv = "";
  110. for (auto const & [key, anno] : named) {
  111. os << std::exchange(odiv, ",\n") << indent(i + 1) << '"' << key << '"' << ':' << ' ';
  112. if (auto const * str = std::get_if<0>(&anno)) {
  113. os << '"' << *str << '"';
  114. } else if (auto const * vec = std::get_if<1>(&anno)) {
  115. os << '[';
  116. char const * div = "\n";
  117. for (size_t n = 0; n < vec->size(); ++n) {
  118. os << std::exchange(div, ",\n") << indent(i + 2) << '"' << vec->at(n) << '"';
  119. }
  120. os << '\n' << indent(i + 1) << ']';
  121. }
  122. }
  123. os << '\n' << indent(i) << '}';
  124. }
  125. bool valid() const { return valid_; }
  126. /**
  127. * @brief Are there any validation details associated with the given document
  128. * location and schema section.
  129. *
  130. * @param where A path into the document being validated
  131. * @param schema_path The schema path (not counting the leaf element that
  132. * actually evaluates the document)
  133. *
  134. * @return true if the schema path has produced an annotation or error for the
  135. * document path
  136. */
  137. bool has(detail::Pointer const & where, detail::Pointer const & schema_path) const {
  138. return has(where) && results_.at(where).contains(schema_path);
  139. }
  140. /**
  141. * @brief Are there any validation details associated with the given document
  142. * location
  143. *
  144. * @param where A path into the document being validated
  145. *
  146. * @return true if any rule has produced an annotation or error for the
  147. * document path
  148. */
  149. bool has(detail::Pointer const & where) const { return results_.contains(where); }
  150. /**
  151. * @brief Extracts the annotation for requested document and schema location, if it exists
  152. *
  153. * @param where A path into the document being validated
  154. * @param schema_path The schema path, without its leaf element
  155. * @param name The leaf schema path (i.e. the rule being evaluated).
  156. * @pre name.empty() == schema_path.empty()
  157. *
  158. * @returns An Annotation for the given path info provided, or nullptr if no annotation exists
  159. */
  160. Annotation const * annotation(detail::Pointer const & where, detail::Pointer const & schema_path,
  161. std::string const & name) const {
  162. if (not results_.contains(where)) {
  163. return nullptr;
  164. }
  165. auto const & by_schema = results_.at(where);
  166. if (not by_schema.contains(schema_path)) {
  167. return nullptr;
  168. }
  169. auto const & local = by_schema.at(schema_path);
  170. if (not local.annotations.contains(name)) {
  171. return nullptr;
  172. }
  173. return &local.annotations.at(name);
  174. }
  175. /**
  176. * @brief Extracts the error for requested document and schema location, if it exists
  177. *
  178. * @param where A path into the document being validated
  179. * @param schema_path The schema path, without its leaf element
  180. * @param name The leaf schema path (i.e. the rule being evaluated).
  181. * @pre name.empty() == schema_path.empty()
  182. *
  183. * @returns An Annotation for the given path info provided, or nullptr if no annotation exists
  184. */
  185. Annotation const * error(detail::Pointer const & where, detail::Pointer const & schema_path,
  186. std::string const & name) const {
  187. if (not results_.contains(where)) {
  188. return nullptr;
  189. }
  190. auto const & by_schema = results_.at(where);
  191. if (not by_schema.contains(schema_path)) {
  192. return nullptr;
  193. }
  194. auto const & local = by_schema.at(schema_path);
  195. if (not local.errors.contains(name)) {
  196. return nullptr;
  197. }
  198. return &local.errors.at(name);
  199. }
  200. ValidationResult only_errors() const {
  201. ValidationResult rval;
  202. rval.valid_ = valid_;
  203. for (auto const & [doc, results] : results_) {
  204. for (auto const & [schema, result] : results) {
  205. if (!result.errors.empty()) {
  206. rval.results_[doc][schema] = result;
  207. }
  208. }
  209. }
  210. return rval;
  211. }
  212. private:
  213. /**
  214. * @brief Transfer the contents of another ValidationResult into this one using
  215. * {@see std::map::merge} to transfer the data minimizing the need for copy/move.
  216. *
  217. * @param result The ValidationResult being consumed
  218. */
  219. void merge(ValidationResult && result) & {
  220. for (auto && [where, by_schema] : result.results_) {
  221. for (auto && [schema_path, local] : by_schema) {
  222. results_[where][schema_path].valid &= local.valid;
  223. results_[where][schema_path].annotations.merge(local.annotations);
  224. results_[where][schema_path].errors.merge(local.errors);
  225. }
  226. }
  227. }
  228. /**
  229. * @brief Declare that the document is accepted/rejected by the given schema
  230. *
  231. * @param where A path into the document being validated
  232. * @param schema_path The schema path
  233. * @param valid Is this location valid according to the schema
  234. */
  235. void valid(detail::Pointer const & where, detail::Pointer const & schema_path, bool valid) {
  236. if (has(where, schema_path)) {
  237. results_[where][schema_path].valid = valid;
  238. }
  239. if (where.empty() && schema_path.empty()) {
  240. valid_ = valid;
  241. }
  242. }
  243. /**
  244. * @brief Attach an error message for part of the document.
  245. * Because of the existance of things like "not" schemas, error() can also be
  246. * called to add an Annotation for a gate that is passed, but was within a
  247. * "not" schema.
  248. *
  249. * @param where A path into the document being validated
  250. * @param schema_path The schema path, without its leaf element
  251. * @param name The leaf schema path (i.e. the rule being evaluated).
  252. * @pre name.empty() == schema_path.empty()
  253. * @param message The annotation(s) being placed as an error
  254. */
  255. void error(detail::Pointer const & where, detail::Pointer const & schema_path,
  256. std::string const & name, Annotation message) {
  257. if (std::visit([](auto const & v) { return v.empty(); }, message)) {
  258. return;
  259. }
  260. std::visit([](auto & msg) { sanitize(msg); }, message);
  261. results_[where][schema_path].errors.emplace(name, std::move(message));
  262. }
  263. /**
  264. * @brief Attach some contextual annotations for part of the document
  265. *
  266. * @param where A path into the document being validated
  267. * @param schema_path The schema path, without its leaf element
  268. * @param name The leaf schema path (i.e. the rule being evaluated).
  269. * @pre name.empty() == schema_path.empty()
  270. * @param message The annotation(s) being placed for context
  271. */
  272. void annotate(detail::Pointer const & where, detail::Pointer const & schema_path,
  273. std::string const & name, Annotation message) {
  274. if (std::visit([](auto const & v) { return v.empty(); }, message)) {
  275. return;
  276. }
  277. std::visit([](auto & msg) { sanitize(msg); }, message);
  278. results_[where][schema_path].annotations.emplace(name, std::move(message));
  279. }
  280. /**
  281. * @brief Remove annotations that we added without knowing if they were
  282. * needed, now that we know that they are not required.
  283. *
  284. * @param where A path into the document being validated
  285. * @param schema_path The schema path to remove
  286. */
  287. void unannotate(detail::Pointer const & where, detail::Pointer const & schema_path) {
  288. results_[where].erase(schema_path);
  289. }
  290. static void sanitize(std::string & message) {
  291. for (auto it = message.begin(); it != message.end(); ++it) {
  292. if (*it == '"' || *it == '\\') {
  293. it = ++message.insert(it, '\\');
  294. }
  295. }
  296. }
  297. static void sanitize(std::vector<std::string> & message) {
  298. std::ranges::for_each(message, [](std::string & val) { sanitize(val); });
  299. }
  300. };
  301. }