adapter.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. #pragma once
  2. #include "jvalidate/compat/expected.h"
  3. #include <cstdint>
  4. #include <filesystem>
  5. #include <fstream>
  6. #include <optional>
  7. #include <ostream>
  8. #include <jvalidate/detail/array_iterator.h>
  9. #include <jvalidate/detail/number.h>
  10. #include <jvalidate/detail/object_iterator.h>
  11. #include <jvalidate/enum.h>
  12. #include <jvalidate/forward.h>
  13. #include <jvalidate/status.h>
  14. namespace jvalidate::adapter {
  15. /**
  16. * @brief An interface for a type-erased reference-wrapper around a JSON node.
  17. *
  18. * Unlike languages like python, there are dozens of different C++ Libraries
  19. * for JSON parsing/construction. Each of these libraries has its own set of
  20. * getter functions, rules for handling missing values, and degree to which it
  21. * can engage in fuzziness of types.
  22. *
  23. * Adapter has two main groups of methods:
  24. * - as_*() and *_size() virtual functions
  25. * - maybe_*() concrete functions
  26. *
  27. * Most interaction with Adapter will be done via the maybe_*() functions,
  28. * with or without strictness enabled depending on what constraint is being
  29. * checked.
  30. */
  31. class Adapter {
  32. public:
  33. virtual ~Adapter() = default;
  34. /**
  35. * @brief Get the jvalidate::adapter::Type that this adapter represents.
  36. * This represents the types recognized by json-schema:
  37. * null, bool, integer, number, string, array, object
  38. * This function is meant to be used internally - and not by any of the
  39. * Constraint objects.
  40. */
  41. virtual Type type() const = 0;
  42. /**
  43. * @brief Obtain an immutable copy of the current node.
  44. * Because an Adapter stores a reference to the underlying JSON, it cannot
  45. * be stored by e.g. a Const/Enum Constraint without risking a Segfault.
  46. */
  47. virtual std::unique_ptr<Const const> freeze() const = 0;
  48. /**
  49. * @brief Extract a boolean value from this JSON node.
  50. * @pre type() == Type::Boolean
  51. *
  52. * @throws If the pre-condition is not valid, then this function may throw
  53. * or produce other undefined behavior, depending on the implementation
  54. * details of the underlying type.
  55. */
  56. virtual bool as_boolean() const = 0;
  57. /**
  58. * @brief Extract an integer value from this JSON node.
  59. * @pre type() == Type::Integer
  60. *
  61. * @throws If the pre-condition is not valid, then this function may throw
  62. * or produce other undefined behavior, depending on the implementation
  63. * details of the underlying type.
  64. */
  65. virtual int64_t as_integer() const = 0;
  66. /**
  67. * @brief Extract a decimal value from this JSON node.
  68. * @pre type() == Type::Number
  69. *
  70. * @throws If the pre-condition is not valid, then this function may throw
  71. * or produce other undefined behavior, depending on the implementation
  72. * details of the underlying type.
  73. */
  74. virtual double as_number() const = 0;
  75. /**
  76. * @brief Extract a string value from this JSON node.
  77. * @pre type() == Type::String
  78. *
  79. * @throws If the pre-condition is not valid, then this function may throw
  80. * or produce other undefined behavior, depending on the implementation
  81. * details of the underlying type.
  82. */
  83. virtual std::string as_string() const = 0;
  84. /**
  85. * @brief Get the size of the JSON array in this node.
  86. * @pre type() == Type::Array
  87. *
  88. * @throws If the pre-condition is not valid, then this function may throw
  89. * or produce other undefined behavior, depending on the implementation
  90. * details of the underlying type.
  91. */
  92. virtual size_t array_size() const = 0;
  93. /**
  94. * @brief Get the size of the JSON object in this node.
  95. * @pre type() == Type::Object
  96. *
  97. * @throws If the pre-condition is not valid, then this function may throw
  98. * or produce other undefined behavior, depending on the implementation
  99. * details of the underlying type.
  100. */
  101. virtual size_t object_size() const = 0;
  102. /**
  103. * @brief Loop through every element of the JSON array in this node, applying
  104. * the given callback function to them.
  105. *
  106. * @param cb A callback of the form Adapter => Status
  107. *
  108. * @return Status::Accept iff there are no errors
  109. */
  110. virtual Status apply_array(AdapterCallback const & cb) const = 0;
  111. /**
  112. * @brief Loop through every element of the JSON object in this node, applying
  113. * the given callback function to them.
  114. *
  115. * @param cb A callback of the form (string, Adapter) => Status
  116. *
  117. * @return Status::Accept iff there are no errors
  118. */
  119. virtual Status apply_object(ObjectAdapterCallback const & cb) const = 0;
  120. virtual bool equals(Adapter const & lhs, bool strict) const = 0;
  121. /**
  122. * @brief Test if this object is null-like
  123. *
  124. * @param strict Does this function allow for fuzzy comparisons with strings?
  125. */
  126. bool maybe_null(bool strict) const {
  127. switch (type()) {
  128. case Type::Null:
  129. return true;
  130. case Type::String:
  131. return not strict and as_string().empty();
  132. default:
  133. return false;
  134. }
  135. }
  136. /**
  137. * @brief Attempts to extract a boolean value from this JSON node
  138. *
  139. * @param strict Does this function allow for fuzzy comparisons with strings?
  140. *
  141. * @return The boolean value contained if it is possible to deduce
  142. * (or type() == Type::Boolean), else nullopt.
  143. */
  144. std::optional<bool> maybe_boolean(bool strict) const {
  145. switch (type()) {
  146. case Type::Boolean:
  147. return as_boolean();
  148. case Type::String:
  149. if (not strict) {
  150. auto str = as_string();
  151. if (str == "true") {
  152. return true;
  153. }
  154. if (str == "false") {
  155. return false;
  156. }
  157. }
  158. return std::nullopt;
  159. default:
  160. return std::nullopt;
  161. }
  162. }
  163. /**
  164. * @brief Attempts to extract a integer value from this JSON node
  165. *
  166. * @param strict Does this function allow for fuzzy comparisons with strings
  167. * and/or booleans?
  168. *
  169. * @return The integer value contained if it is possible to deduce from an
  170. * integer, number, boolean, or string. Else nullopt
  171. */
  172. std::optional<int64_t> maybe_integer(bool strict) const {
  173. switch (type()) {
  174. case Type::Number:
  175. if (double value = as_number(); jvalidate::detail::fits_in_integer(value)) {
  176. return static_cast<int64_t>(value);
  177. }
  178. return std::nullopt;
  179. case Type::Integer:
  180. return as_integer();
  181. case Type::Boolean:
  182. if (not strict) {
  183. return as_boolean() ? 1 : 0;
  184. }
  185. return std::nullopt;
  186. case Type::String:
  187. if (not strict) {
  188. auto str = as_string();
  189. size_t end = 0;
  190. int64_t rval = std::stoll(str, &end);
  191. if (end == str.size()) {
  192. return rval;
  193. }
  194. }
  195. return std::nullopt;
  196. default:
  197. return std::nullopt;
  198. }
  199. }
  200. /**
  201. * @brief Attempts to extract a number value from this JSON node
  202. *
  203. * @param strict Does this function allow for fuzzy comparisons with strings?
  204. *
  205. * @return The number value contained if it is possible to deduce
  206. * (or type() == Type::Integer || type() == Type::Number), else nullopt.
  207. */
  208. std::optional<double> maybe_number(bool strict) const {
  209. switch (type()) {
  210. case Type::Number:
  211. return as_number();
  212. case Type::Integer:
  213. return as_integer();
  214. case Type::String:
  215. if (not strict) {
  216. auto str = as_string();
  217. size_t end = 0;
  218. double rval = std::stod(str, &end);
  219. if (end == str.size()) {
  220. return rval;
  221. }
  222. }
  223. return std::nullopt;
  224. default:
  225. return std::nullopt;
  226. }
  227. }
  228. /**
  229. * @brief Attempts to extract a string value from this JSON node
  230. *
  231. * @param strict Does this function allow for fuzzy comparisons with other
  232. * types?
  233. *
  234. * @return The string value contained if it is possible to deduce from a
  235. * scalar type, else nullopt.
  236. */
  237. std::optional<std::string> maybe_string(bool strict) const {
  238. switch (type()) {
  239. case Type::Null:
  240. return strict ? std::nullopt : std::make_optional("");
  241. case Type::String:
  242. return as_string();
  243. case Type::Number:
  244. if (not strict) {
  245. return std::to_string(as_number());
  246. }
  247. return std::nullopt;
  248. case Type::Integer:
  249. if (not strict) {
  250. return std::to_string(as_integer());
  251. }
  252. return std::nullopt;
  253. case Type::Boolean:
  254. if (not strict) {
  255. return as_boolean() ? "true" : "false";
  256. }
  257. return std::nullopt;
  258. default:
  259. return std::nullopt;
  260. }
  261. }
  262. /**
  263. * @brief Attempts to extract the array length from this JSON node
  264. *
  265. * @param strict Does this function allow for fuzzy comparisons with other
  266. * types?
  267. *
  268. * @return array_size() if this is an array, else 0 or nullopt, depending
  269. * on some factors.
  270. */
  271. std::optional<size_t> maybe_array_size(bool strict) const {
  272. switch (type()) {
  273. case Type::Array:
  274. return array_size();
  275. case Type::Null:
  276. return strict ? std::nullopt : std::make_optional(0UL);
  277. case Type::Object:
  278. return (strict || object_size() != 0) ? std::nullopt : std::make_optional(0UL);
  279. default:
  280. return std::nullopt;
  281. }
  282. }
  283. /**
  284. * @brief Attempts to extract the object length from this JSON node
  285. *
  286. * @param strict Does this function allow for fuzzy comparisons with other
  287. * types?
  288. *
  289. * @return object_size() if this is an object, else 0 or nullopt, depending
  290. * on some factors.
  291. */
  292. std::optional<size_t> maybe_object_size(bool strict) const {
  293. switch (type()) {
  294. case Type::Object:
  295. return object_size();
  296. case Type::Null:
  297. return strict ? std::nullopt : std::make_optional(0UL);
  298. case Type::Array:
  299. return (strict || array_size() != 0) ? std::nullopt : std::make_optional(0UL);
  300. default:
  301. return std::nullopt;
  302. }
  303. }
  304. virtual void write(std::ostream & os) const {
  305. std::string_view div;
  306. switch (type()) {
  307. case Type::Null:
  308. os << "null";
  309. break;
  310. case Type::Boolean:
  311. os << (as_boolean() ? "true" : "false");
  312. break;
  313. case Type::Integer:
  314. os << as_integer();
  315. break;
  316. case Type::Number:
  317. os << as_number();
  318. break;
  319. case Type::String:
  320. os << '"' << as_string() << '"';
  321. break;
  322. case Type::Array:
  323. os << '[';
  324. apply_array([&os, &div](Adapter const & elem) {
  325. os << std::exchange(div, ", ") << elem;
  326. return Status::Accept;
  327. });
  328. os << ']';
  329. break;
  330. case Type::Object:
  331. os << '{';
  332. apply_object([&os, &div](std::string const & key, Adapter const & elem) {
  333. os << std::exchange(div, ", ") << '"' << key << '"' << ':' << elem;
  334. return Status::Accept;
  335. });
  336. os << '}';
  337. break;
  338. }
  339. }
  340. friend std::ostream & operator<<(std::ostream & os, Adapter const & self) {
  341. self.write(os);
  342. return os;
  343. }
  344. };
  345. /**
  346. * @brief An interface for an immutable, owning handle to a type-erased JSON
  347. * node. {@see Adapter::freeze} for more explaination why this is necessary.
  348. */
  349. class Const {
  350. public:
  351. virtual ~Const() = default;
  352. /**
  353. * @brief Perform an action on this object, such as copying or testing
  354. * equality.
  355. *
  356. * @param cb A callback function of the form Adapter => Status
  357. *
  358. * @return the result of cb on the contained JSON
  359. */
  360. virtual Status apply(AdapterCallback const & cb) const = 0;
  361. friend std::ostream & operator<<(std::ostream & os, Const const & self) {
  362. self.apply([&os](Adapter const & adapter) {
  363. adapter.write(os);
  364. return Status::Accept;
  365. });
  366. return os;
  367. }
  368. };
  369. template <typename JSON>
  370. auto load_file(std::filesystem::path const & path, JSON & out) noexcept
  371. -> detail::expected<void, std::string> {
  372. std::ifstream in(path);
  373. if (in.bad()) {
  374. return detail::unexpected("file error");
  375. }
  376. return load_stream(in, out);
  377. }
  378. }
  379. namespace jvalidate::adapter::detail {
  380. /**
  381. * @brief The simplest implementation of Const.
  382. * Depends on the AdapterTraits struct.
  383. *
  384. * @tparam JSON The type being adapted
  385. */
  386. template <typename JSON> class GenericConst final : public Const {
  387. public:
  388. explicit GenericConst(JSON const & value) : value_(value) {}
  389. Status apply(AdapterCallback const & cb) const {
  390. return cb(typename AdapterTraits<JSON>::ConstAdapter(value_));
  391. }
  392. JSON const & value() const { return value_; }
  393. private:
  394. JSON value_;
  395. };
  396. }
  397. namespace std {
  398. inline ostream & operator<<(ostream & os, unique_ptr<jvalidate::adapter::Const const> const & ptr) {
  399. return os << *ptr;
  400. }
  401. inline ostream & operator<<(ostream & os,
  402. vector<unique_ptr<jvalidate::adapter::Const const>> const & items) {
  403. std::string_view div;
  404. os << '[';
  405. for (auto const & ptr : items) {
  406. os << std::exchange(div, ", ") << *ptr;
  407. }
  408. return os << ']';
  409. }
  410. }