Build tool
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BXParser.h 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #pragma once
  2. #include <unordered_map>
  3. #include <vector>
  4. #include <string>
  5. #include <iostream>
  6. #include <exception>
  7. struct BXParseError: std::exception {
  8. BXParseError(std::string msg): message(msg) {}
  9. std::string message;
  10. const char *what() const noexcept override {
  11. return message.c_str();
  12. }
  13. };
  14. using BXVariables = std::unordered_map<std::string, std::vector<std::string>>;
  15. class BXParser {
  16. public:
  17. static const int FLAG_NONE = 0;
  18. static const int FLAG_ONE_LINE = 1 << 0;
  19. BXParser(std::istream &stream, int flags, int line = 1, int ch = 1):
  20. flags_(flags), line_(line), ch_(ch), stream_(stream) {}
  21. void parse(BXVariables &vars);
  22. void parseList(const BXVariables &vars, std::vector<std::string> &values);
  23. int get();
  24. int peek();
  25. int peek2();
  26. void skip(char expected);
  27. void skip() { get(); }
  28. int line() const { return line_; }
  29. int ch() const { return ch_; }
  30. private:
  31. enum class Operator {
  32. COLON_EQUALS,
  33. PLUS_EQUALS,
  34. EQUALS_PLUS,
  35. NONE,
  36. };
  37. [[noreturn]] void error(std::string);
  38. Operator readOperator();
  39. void skipWhitespaceLine();
  40. void skipWhitespace();
  41. char parseEscape();
  42. void parseExpansion(const BXVariables &vars, std::vector<std::string> &values);
  43. void parseQuotedExpansion(const BXVariables &vars, std::string &content);
  44. void parseQuotedString(const BXVariables &vars, std::string &content);
  45. bool parseString(const BXVariables &vars, std::string &content, int sep = -1);
  46. bool parseIdentifier(std::string &content);
  47. int flags_;
  48. int line_;
  49. int ch_;
  50. std::istream &stream_;
  51. char buf_[1024];
  52. size_t bufidx_ = 0;
  53. size_t buflen_ = 0;
  54. };
  55. class BXWriter {
  56. public:
  57. BXWriter(std::ostream &stream): stream_(stream) {}
  58. ~BXWriter();
  59. void write(const BXVariables &vars);
  60. private:
  61. void put(char ch);
  62. void put(const std::string &str);
  63. void newline();
  64. void escape(const std::string &str);
  65. std::ostream &stream_;
  66. char buf_[1024];
  67. size_t bufidx_ = 0;
  68. };