matcher_manager.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef CARBON_MIGRATE_CPP_CPP_REFACTORING_MATCHER_MANAGER_H_
  5. #define CARBON_MIGRATE_CPP_CPP_REFACTORING_MATCHER_MANAGER_H_
  6. #include "clang/ASTMatchers/ASTMatchFinder.h"
  7. #include "clang/Tooling/Core/Replacement.h"
  8. #include "migrate_cpp/cpp_refactoring/matcher.h"
  9. namespace Carbon {
  10. // Manages registration of AST matchers.
  11. class MatcherManager {
  12. public:
  13. explicit MatcherManager(Matcher::ReplacementMap* in_replacements)
  14. : replacements(in_replacements) {}
  15. // Registers Matcher implementations.
  16. void Register(std::unique_ptr<MatcherFactory> factory) {
  17. matchers.push_back(std::make_unique<MatchCallbackWrapper>(
  18. &finder, std::move(factory), replacements));
  19. }
  20. auto GetFinder() -> clang::ast_matchers::MatchFinder* { return &finder; }
  21. private:
  22. // Adapts Matcher for use with MatchCallback.
  23. class MatchCallbackWrapper
  24. : public clang::ast_matchers::MatchFinder::MatchCallback {
  25. public:
  26. explicit MatchCallbackWrapper(clang::ast_matchers::MatchFinder* finder,
  27. std::unique_ptr<MatcherFactory> in_factory,
  28. Matcher::ReplacementMap* in_replacements)
  29. : factory(std::move(in_factory)), replacements(in_replacements) {
  30. factory->AddMatcher(finder, this);
  31. }
  32. void run(const clang::ast_matchers::MatchFinder::MatchResult& match_result)
  33. override {
  34. factory->CreateMatcher(&match_result, replacements)->Run();
  35. }
  36. private:
  37. std::unique_ptr<MatcherFactory> factory;
  38. Matcher::ReplacementMap* const replacements;
  39. };
  40. Matcher::ReplacementMap* const replacements;
  41. clang::ast_matchers::MatchFinder finder;
  42. std::vector<std::unique_ptr<MatcherFactory>> factories;
  43. std::vector<std::unique_ptr<MatchCallbackWrapper>> matchers;
  44. };
  45. } // namespace Carbon
  46. #endif // CARBON_MIGRATE_CPP_CPP_REFACTORING_MATCHER_MANAGER_H_