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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. enum class TokenKind {
  19. E_O_F,
  20. INDENTATION,
  21. NEWLINE,
  22. COMMA,
  23. COLON_EQUALS,
  24. PLUS_EQUALS,
  25. EQUALS_PLUS,
  26. BAR_EQUALS,
  27. EXPANSION,
  28. STRING,
  29. NONE,
  30. };
  31. struct Token {
  32. TokenKind kind;
  33. std::string str;
  34. int line;
  35. int ch;
  36. };
  37. BXParser(bufio::IStream &stream, int line = 1, int ch = 1):
  38. line_(line), ch_(ch), buf_(stream) {}
  39. int get();
  40. int peek(size_t count = 1) { return buf_.peek(count); }
  41. void skip(char expected);
  42. void skip() { get(); }
  43. int line() const { return line_; }
  44. int ch() const { return ch_; }
  45. Token readToken(const BXVariables &vars);
  46. Token &peekToken() { return tok_; }
  47. void parse(BXVariables &vars, bool oneLine = false);
  48. void parseLine(BXVariables &vars) { parse(vars, true); }
  49. void parseList(BXVariables &vars, std::vector<std::string> &list);
  50. private:
  51. [[noreturn]] void error(std::string);
  52. [[noreturn]] void error(std::string, TokenKind);
  53. std::string readIdent(const BXVariables &vars);
  54. void skipWhitespace();
  55. Token getToken(const BXVariables &vars);
  56. std::string readString(const BXVariables &vars);
  57. std::string readQuotedString(const BXVariables &vars);
  58. std::string readStringExpansion(const BXVariables &vars);
  59. char readEscape();
  60. void parseList(
  61. BXVariables &vars, std::vector<std::string> &var,
  62. void (*addVal)(std::vector<std::string> &var, std::string val),
  63. bool oneLine);
  64. int line_;
  65. int ch_;
  66. Token tok_;
  67. bufio::IBuf<> buf_;
  68. };
  69. class BXWriter {
  70. public:
  71. BXWriter(bufio::OStream &stream): buf_(stream) {}
  72. void write(const BXVariables &vars);
  73. private:
  74. void newline();
  75. void escape(const std::string &str);
  76. bufio::OBuf<> buf_;
  77. };