pointer.h 8.7 KB

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