Preprocessor.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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/HashMap.h>
  9. #include <AK/Optional.h>
  10. #include <AK/String.h>
  11. #include <AK/StringView.h>
  12. #include <AK/Vector.h>
  13. namespace Cpp {
  14. class Preprocessor {
  15. public:
  16. explicit Preprocessor(const String& filename, const StringView& program);
  17. const String& process();
  18. const String& processed_text();
  19. Vector<StringView> included_paths() const { return m_included_paths; }
  20. struct DefinedValue {
  21. Optional<StringView> value;
  22. FlyString filename;
  23. size_t line { 0 };
  24. size_t column { 0 };
  25. };
  26. using Definitions = HashMap<StringView, DefinedValue>;
  27. const Definitions& definitions() const { return m_definitions; }
  28. void set_ignore_unsupported_keywords(bool ignore) { m_options.ignore_unsupported_keywords = ignore; }
  29. void set_keep_include_statements(bool keep) { m_options.keep_include_statements = keep; }
  30. private:
  31. using PreprocessorKeyword = StringView;
  32. PreprocessorKeyword handle_preprocessor_line(const StringView&);
  33. void handle_preprocessor_keyword(const StringView& keyword, GenericLexer& line_lexer);
  34. Definitions m_definitions;
  35. const String m_filename;
  36. const StringView m_program;
  37. StringBuilder m_builder;
  38. Vector<StringView> m_lines;
  39. size_t m_line_index { 0 };
  40. size_t m_current_depth { 0 };
  41. Vector<size_t> m_depths_of_taken_branches;
  42. Vector<size_t> m_depths_of_not_taken_branches;
  43. enum class State {
  44. Normal,
  45. SkipIfBranch,
  46. SkipElseBranch
  47. };
  48. State m_state { State::Normal };
  49. Vector<StringView> m_included_paths;
  50. String m_processed_text;
  51. struct Options {
  52. bool ignore_unsupported_keywords { false };
  53. bool keep_include_statements { false };
  54. } m_options;
  55. };
  56. }