RegexLexer.h 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * Copyright (c) 2020, Emanuel Sprung <emanuel.sprung@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Forward.h>
  8. #include <AK/StringView.h>
  9. namespace regex {
  10. #define ENUMERATE_REGEX_TOKENS \
  11. __ENUMERATE_REGEX_TOKEN(Eof) \
  12. __ENUMERATE_REGEX_TOKEN(Char) \
  13. __ENUMERATE_REGEX_TOKEN(Circumflex) \
  14. __ENUMERATE_REGEX_TOKEN(Period) \
  15. __ENUMERATE_REGEX_TOKEN(LeftParen) \
  16. __ENUMERATE_REGEX_TOKEN(RightParen) \
  17. __ENUMERATE_REGEX_TOKEN(LeftCurly) \
  18. __ENUMERATE_REGEX_TOKEN(RightCurly) \
  19. __ENUMERATE_REGEX_TOKEN(LeftBracket) \
  20. __ENUMERATE_REGEX_TOKEN(RightBracket) \
  21. __ENUMERATE_REGEX_TOKEN(Asterisk) \
  22. __ENUMERATE_REGEX_TOKEN(EscapeSequence) \
  23. __ENUMERATE_REGEX_TOKEN(Dollar) \
  24. __ENUMERATE_REGEX_TOKEN(Pipe) \
  25. __ENUMERATE_REGEX_TOKEN(Plus) \
  26. __ENUMERATE_REGEX_TOKEN(Comma) \
  27. __ENUMERATE_REGEX_TOKEN(Slash) \
  28. __ENUMERATE_REGEX_TOKEN(EqualSign) \
  29. __ENUMERATE_REGEX_TOKEN(HyphenMinus) \
  30. __ENUMERATE_REGEX_TOKEN(Colon) \
  31. __ENUMERATE_REGEX_TOKEN(Questionmark)
  32. enum class TokenType {
  33. #define __ENUMERATE_REGEX_TOKEN(x) x,
  34. ENUMERATE_REGEX_TOKENS
  35. #undef __ENUMERATE_REGEX_TOKEN
  36. };
  37. class Token {
  38. public:
  39. Token() = default;
  40. Token(const TokenType type, const size_t start_position, const StringView value)
  41. : m_type(type)
  42. , m_position(start_position)
  43. , m_value(value)
  44. {
  45. }
  46. TokenType type() const { return m_type; }
  47. const StringView& value() const { return m_value; }
  48. size_t position() const { return m_position; }
  49. const char* name() const;
  50. static const char* name(const TokenType);
  51. private:
  52. TokenType m_type { TokenType::Eof };
  53. size_t m_position { 0 };
  54. StringView m_value { nullptr };
  55. };
  56. class Lexer {
  57. public:
  58. Lexer() = default;
  59. explicit Lexer(const StringView source);
  60. Token next();
  61. void reset();
  62. void back(size_t offset);
  63. void set_source(const StringView source) { m_source = source; }
  64. bool try_skip(char);
  65. char skip();
  66. const auto& source() const { return m_source; }
  67. private:
  68. ALWAYS_INLINE int peek(size_t offset = 0) const;
  69. ALWAYS_INLINE void consume();
  70. StringView m_source {};
  71. size_t m_position { 0 };
  72. size_t m_previous_position { 0 };
  73. Token m_current_token { TokenType::Eof, 0, StringView(nullptr) };
  74. int m_current_char { 0 };
  75. };
  76. }
  77. using regex::Lexer;