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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 peek() { return stream_.peek(); }
  24. int peek2() { stream_.get(); int ch = peek(); stream_.unget(); return ch; }
  25. int get();
  26. void skip(char);
  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. };
  52. class BXWriter {
  53. public:
  54. BXWriter(std::ostream &stream, int line = 1, int ch = 1):
  55. line_(line), ch_(ch), stream_(stream) {}
  56. void write(const BXVariables &vars);
  57. private:
  58. void put(char ch);
  59. void put(const std::string &str);
  60. void newline();
  61. void escape(const std::string &str);
  62. int line_;
  63. int ch_;
  64. std::ostream &stream_;
  65. };