cmJSONState.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #pragma once
  4. #include "cmConfigure.h" // IWYU pragma: keep
  5. #include <cstddef>
  6. #include <string>
  7. #include <utility>
  8. #include <vector>
  9. #include "cmStringAlgorithms.h"
  10. namespace Json {
  11. class Value;
  12. }
  13. class cmJSONState
  14. {
  15. using Location = struct
  16. {
  17. int line;
  18. int column;
  19. };
  20. public:
  21. using JsonPair = std::pair<const std::string, const Json::Value*>;
  22. cmJSONState() = default;
  23. cmJSONState(const std::string& filename, Json::Value* root);
  24. void AddError(std::string const& errMsg);
  25. void AddErrorAtValue(std::string const& errMsg, const Json::Value* value);
  26. void AddErrorAtOffset(std::string const& errMsg, std::ptrdiff_t offset);
  27. std::string GetErrorMessage(bool showContext = true);
  28. std::string key();
  29. std::string key_after(std::string const& key);
  30. const Json::Value* value_after(std::string const& key);
  31. void push_stack(std::string const& key, const Json::Value* value);
  32. void pop_stack();
  33. class Error
  34. {
  35. public:
  36. Error(Location loc, std::string errMsg)
  37. : location(loc)
  38. , message(std::move(errMsg)){};
  39. Error(std::string errMsg)
  40. : location({ -1, -1 })
  41. , message(std::move(errMsg)){};
  42. std::string GetErrorMessage() const
  43. {
  44. std::string output = message;
  45. if (location.line > 0) {
  46. output = cmStrCat("Error: @", location.line, ",", location.column,
  47. ": ", output);
  48. }
  49. return output;
  50. }
  51. Location GetLocation() const { return location; }
  52. private:
  53. Location location;
  54. std::string message;
  55. };
  56. std::vector<JsonPair> parseStack;
  57. std::vector<Error> errors;
  58. std::string doc;
  59. private:
  60. std::string GetJsonContext(Location loc);
  61. Location LocateInDocument(ptrdiff_t offset);
  62. };