pointer.h 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. #pragma once
  2. #include <algorithm>
  3. #include <cassert>
  4. #include <cstddef>
  5. #include <cstdlib>
  6. #include <iostream>
  7. #include <stdexcept> // IWYU pragma: keep
  8. #include <string>
  9. #include <string_view>
  10. #include <variant>
  11. #include <vector>
  12. #include <jvalidate/compat/compare.h> // IWYU pragma: keep
  13. #include <jvalidate/detail/expect.h>
  14. #include <jvalidate/detail/number.h>
  15. #include <jvalidate/forward.h>
  16. namespace jvalidate::detail {
  17. /**
  18. * @brief A helper struct for use in appending elements to a json Pointer object
  19. * in a way that allows it to be used as a template parameter - similar to how
  20. * ostream allows operator<<(void(*)(ostream&)) to pass in a function callback
  21. * for implementing various iomanip functions as piped (read:fluent) values.
  22. *
  23. * However, the primary usecase for this is in a template context, where I want
  24. * to add 0-or-more path components to a JSON-Pointer of any type, and also want
  25. * to support neighbor Pointers, instead of only child Pointers.
  26. *
  27. * For example, @see ValidationVisitor::visit(constraint::ConditionalConstraint)
  28. * where we use parent to rewind the path back to the owning scope for
  29. * if-then-else processing.
  30. */
  31. struct parent_t {}; // NOLINT(readability-identifier-naming)
  32. constexpr parent_t parent; // NOLINT(readability-identifier-naming)
  33. class Pointer {
  34. private:
  35. using Token = std::variant<std::string, size_t>;
  36. public:
  37. Pointer() = default;
  38. explicit(false) Pointer(std::vector<Token> const & tokens) : tokens_(tokens) {}
  39. /**
  40. * @brief Parse a JSON-Pointer from a serialized JSON-Pointer-String.
  41. *
  42. * @param path A string representation of the Pointer
  43. *
  44. * @returns A Pointer, if the string is considered valid, else an error
  45. * message describing the problem.
  46. */
  47. static expected<Pointer, std::string> parse(std::string_view path) {
  48. if (path.empty()) {
  49. return Pointer();
  50. }
  51. // JSON-Pointers are required to start with a '/'.
  52. JVALIDATE_RETURN_UNLESS(path.starts_with('/'),
  53. unexpected("Missing leading '/' in JSON Pointer"));
  54. path.remove_prefix(1);
  55. // The rules of JSON-Pointer is that if a token were to contain a '/' as a
  56. // strict character: then that character would be escaped, using the above
  57. // rules. We take advantage of string_view's sliding view to make iteration
  58. // easy.
  59. Pointer rval;
  60. for (size_t pos = path.find('/'); pos != std::string::npos;
  61. path.remove_prefix(pos + 1), pos = path.find('/')) {
  62. expected token = parse_token(std::string(path.substr(0, pos)));
  63. JVALIDATE_PROPIGATE_UNEXPECTED(token);
  64. rval.tokens_.push_back(*token);
  65. }
  66. expected token = parse_token(std::string(path));
  67. JVALIDATE_PROPIGATE_UNEXPECTED(token);
  68. rval.tokens_.push_back(*token);
  69. return rval;
  70. }
  71. static expected<Token, std::string> parse_token(std::string in) {
  72. // Best-guess that the input token text represents a numeric value.
  73. // Technically - this could mean that we have an object key that is also
  74. // a number (e.g. the jsonized form of map<int, T>), but we can generally
  75. // assume that we are not going to use those kinds of paths in a reference
  76. // field. Therefore we don't need to include any clever tricks for storage
  77. if (not in.empty() && in.find_first_not_of("0123456789") == std::string::npos) {
  78. return parse_integer<size_t>(in).transform_error(to_message);
  79. }
  80. for (size_t i = 0; i < in.size(); ++i) {
  81. // Allow URL-Escaped characters (%\x\x) to be turned into their
  82. // matching ASCII characters. This allows passing abnormal chars other
  83. // than '/' and '~' to be handled in all contexts.
  84. if (in[i] == '%') {
  85. if (expected code = parse_integer<char>(in.substr(i + 1, 2), {.base = 16})) {
  86. in.replace(i, 3, 1, *code);
  87. } else {
  88. return unexpected(to_message(code.error()));
  89. }
  90. continue;
  91. }
  92. if (in[i] != '~') {
  93. // Not a special char-sequence, does not need massaging
  94. continue;
  95. }
  96. // In order to properly support '/' inside the property name of an
  97. // object, we must escape it. The designers of the JSON-Pointer RFC
  98. // chose to use '~' as a special signifier. Mapping '~0' to '~', and
  99. // '~1' to '/'.
  100. if (in[i + 1] == '0') {
  101. in.replace(i, 2, 1, '~');
  102. } else if (in[i + 1] == '1') {
  103. in.replace(i, 2, 1, '/');
  104. } else {
  105. return unexpected("illegal tilde '" + in.substr(i, 2) + "'");
  106. }
  107. }
  108. return in;
  109. }
  110. /**
  111. * @brief Dive into a JSON object throught the entire path of the this object
  112. *
  113. * @param document A JSON Adapter document - confirming to the following spec:
  114. * 1. Is indexable by size_t, returning its own type
  115. * 2. Is indexable by std::string, returning its own type
  116. * 3. Indexing into a null/incorrect json type, or for an absent child is safe
  117. *
  118. * @returns A new JSON Adapter at the pointed to location, or a generic null
  119. * JSON object.
  120. */
  121. auto walk(Adapter auto document) const {
  122. for (auto const & token : tokens_) {
  123. document = std::visit([&document](auto const & next) { return document[next]; }, token);
  124. }
  125. return document;
  126. }
  127. /**
  128. * @brief Fetch the last item in this pointer as a string (for easy
  129. * formatting). This function is used more-or-less exclusively to support the
  130. * improved annotation/error listing concepts described in the article:
  131. * https://json-schema.org/blog/posts/fixing-json-schema-output
  132. */
  133. std::string back() const {
  134. struct {
  135. std::string operator()(std::string const & in) const { return in; }
  136. std::string operator()(size_t in) const { return std::to_string(in); }
  137. } g_as_str;
  138. return tokens_.empty() ? "" : std::visit(g_as_str, tokens_.back());
  139. }
  140. bool empty() const { return tokens_.empty(); }
  141. /**
  142. * @brief Determines if this JSON-Pointer is prefixed by the other
  143. * JSON-Pointer. For example: `"/A/B/C"_jsptr.starts_with("/A/B") == true`
  144. *
  145. * This is an important thing to know when dealing with schemas that use
  146. * Anchors or nest $id tags in a singular document. Consider the schema below:
  147. * @code{.json}
  148. * {
  149. * "$id": "A",
  150. * "$defs": {
  151. * "B": {
  152. * "$anchor": "B"
  153. * "$defs": {
  154. * "C": {
  155. * "$anchor": "C"
  156. * }
  157. * }
  158. * }
  159. * }
  160. * }
  161. * @endcode
  162. *
  163. * How can we deduce that "A#B" and "A#C" are related to one-another as parent
  164. * and child nodes? First we translate them both into absolute (no-anchor)
  165. * forms "A#/$defs/B" and "A#/$defs/B/$defs/C". Visually - these are now
  166. * obviously related - but we need to expose the functionalty to make that
  167. * check happen (that "/$defs/B/$defs/C" starts with "/$defs/B").
  168. */
  169. bool starts_with(Pointer const & other) const {
  170. return other.tokens_.size() <= tokens_.size() &&
  171. std::equal(other.tokens_.begin(), other.tokens_.end(), tokens_.begin());
  172. }
  173. /**
  174. * @brief A corollary function to starts_with, create a "relative"
  175. * JSON-Pointer to some parent. Relative pointers are only partially supported
  176. * (e.g. if you tried to print it it would still emit the leading slash), so
  177. * the standard use case of this function is to either use it when choosing
  178. * a URI or Anchor that is a closer parent:
  179. * `Reference(uri, anchor, ptr.relative_to(other))`
  180. * or immediately concatenating it onto another absolute pointer:
  181. * `abs /= ptr.relative_to(other)`
  182. */
  183. Pointer relative_to(Pointer const & other) const {
  184. assert(starts_with(other));
  185. return {
  186. std::vector(tokens_.begin() + static_cast<ptrdiff_t>(other.tokens_.size()), tokens_.end())};
  187. }
  188. Pointer parent(size_t levels = 1) const {
  189. return {{tokens_.begin(), tokens_.end() - static_cast<ptrdiff_t>(levels)}};
  190. }
  191. Pointer & operator/=(Pointer const & relative) {
  192. tokens_.insert(tokens_.end(), relative.tokens_.begin(), relative.tokens_.end());
  193. return *this;
  194. }
  195. Pointer operator/(Pointer const & relative) const { return Pointer(*this) /= relative; }
  196. Pointer & operator/=(parent_t) {
  197. tokens_.pop_back();
  198. return *this;
  199. }
  200. Pointer operator/(parent_t) const { return parent(); }
  201. Pointer & operator/=(std::string_view key) {
  202. tokens_.emplace_back(std::string(key));
  203. return *this;
  204. }
  205. Pointer operator/(std::string_view key) const { return Pointer(*this) /= key; }
  206. Pointer & operator/=(size_t index) {
  207. tokens_.emplace_back(index);
  208. return *this;
  209. }
  210. Pointer operator/(size_t index) const { return Pointer(*this) /= index; }
  211. friend std::ostream & operator<<(std::ostream & os, Pointer const & self) {
  212. for (auto const & elem : self.tokens_) {
  213. std::visit([&os](auto const & tok) { os << '/' << tok; }, elem);
  214. }
  215. return os;
  216. }
  217. auto operator<=>(Pointer const &) const = default;
  218. private:
  219. std::vector<Token> tokens_;
  220. };
  221. }