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.7KB

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