vocabulary.h 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #pragma once
  2. #include <string_view>
  3. #include <unordered_map>
  4. #include <unordered_set>
  5. #include <jvalidate/enum.h>
  6. #include <jvalidate/forward.h>
  7. namespace jvalidate::detail {
  8. template <Adapter A> struct ParserContext;
  9. template <Adapter A> class Vocabulary {
  10. public:
  11. friend class ConstraintFactory<A>;
  12. using pConstraint = std::unique_ptr<constraint::Constraint>;
  13. using MakeConstraint = std::function<pConstraint(ParserContext<A> const &)>;
  14. private:
  15. schema::Version version_;
  16. std::unordered_map<std::string_view, MakeConstraint> make_;
  17. std::unordered_set<std::string_view> special_keywords_;
  18. // TODO(samjaffe): Migrate this back to constraintsfactory
  19. std::unordered_set<std::string_view> keywords_{"$defs",
  20. "additionalItems",
  21. "additionalProperties",
  22. "allOf",
  23. "anyOf",
  24. "definitions",
  25. "dependencies",
  26. "dependentSchemas",
  27. "else",
  28. "if",
  29. "items",
  30. "not",
  31. "oneOf",
  32. "patternProperties",
  33. "prefixItems",
  34. "properties",
  35. "then",
  36. "unevaluatedItems",
  37. "unevaluatedProperties"};
  38. std::unordered_set<std::string_view> property_keywords_{
  39. "$defs", "definitions", "dependencies", "dependentSchemas", "patternProperties",
  40. "properties"};
  41. std::unordered_set<std::string_view> post_constraints_{"unevaluatedItems",
  42. "unevaluatedProperties"};
  43. public:
  44. Vocabulary(schema::Version version, std::unordered_map<std::string_view, MakeConstraint> make)
  45. : version_(version), make_(std::move(make)) {}
  46. schema::Version version() const { return version_; }
  47. /**
  48. * @brief Is the given "key"word actually a keyword? As in, would
  49. * I expect to resolve a constraint out of it.
  50. */
  51. bool is_keyword(std::string_view word) const {
  52. return make_.contains(word) && keywords_.contains(word);
  53. }
  54. /**
  55. * @brief Does the given "key"word represent a property object - that is to
  56. * say, an object containing some number of schemas mapped by arbitrary keys
  57. */
  58. bool is_property_keyword(std::string_view word) const {
  59. return is_keyword(word) && property_keywords_.contains(word);
  60. }
  61. bool is_constraint(std::string_view word) const { return make_.contains(word) && make_.at(word); }
  62. auto constraint(std::string_view word, ParserContext<A> const & context) const {
  63. return std::make_pair(is_constraint(word) ? make_.at(word)(context) : nullptr,
  64. post_constraints_.contains(word));
  65. }
  66. };
  67. }