Preprocessor.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Copyright (c) 2021, Itamar S. <itamar8910@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/FlyString.h>
  8. #include <AK/Function.h>
  9. #include <AK/HashMap.h>
  10. #include <AK/Optional.h>
  11. #include <AK/String.h>
  12. #include <AK/StringView.h>
  13. #include <AK/Vector.h>
  14. #include <LibCpp/Token.h>
  15. namespace Cpp {
  16. class Preprocessor {
  17. public:
  18. explicit Preprocessor(const String& filename, const StringView& program);
  19. Vector<Token> process_and_lex();
  20. Vector<StringView> included_paths() const { return m_included_paths; }
  21. struct DefinedValue {
  22. String value;
  23. FlyString filename;
  24. size_t line { 0 };
  25. size_t column { 0 };
  26. };
  27. using Definitions = HashMap<StringView, DefinedValue>;
  28. struct Substitution {
  29. Token original_token;
  30. DefinedValue defined_value;
  31. };
  32. Definitions const& definitions() const { return m_definitions; }
  33. Vector<Substitution> const& substitutions() const { return m_substitutions; }
  34. void set_ignore_unsupported_keywords(bool ignore) { m_options.ignore_unsupported_keywords = ignore; }
  35. void set_keep_include_statements(bool keep) { m_options.keep_include_statements = keep; }
  36. Function<Definitions(StringView)> definitions_in_header_callback { nullptr };
  37. private:
  38. using PreprocessorKeyword = StringView;
  39. PreprocessorKeyword handle_preprocessor_line(StringView const&);
  40. void handle_preprocessor_keyword(StringView const& keyword, GenericLexer& line_lexer);
  41. void process_line(StringView const& line);
  42. void do_substitution(Token const& replaced_token, DefinedValue const&);
  43. String m_filename;
  44. String m_program;
  45. Vector<StringView> m_lines;
  46. Vector<Token> m_tokens;
  47. Definitions m_definitions;
  48. Vector<Substitution> m_substitutions;
  49. size_t m_line_index { 0 };
  50. size_t m_current_depth { 0 };
  51. Vector<size_t> m_depths_of_taken_branches;
  52. Vector<size_t> m_depths_of_not_taken_branches;
  53. enum class State {
  54. Normal,
  55. SkipIfBranch,
  56. SkipElseBranch
  57. };
  58. State m_state { State::Normal };
  59. Vector<StringView> m_included_paths;
  60. struct Options {
  61. bool ignore_unsupported_keywords { false };
  62. bool keep_include_statements { false };
  63. } m_options;
  64. };
  65. }