1 //===--- Transformer.h - Transformer class ----------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLVM_CLANG_TOOLING_TRANSFORMER_TRANSFORMER_H_
10 #define LLVM_CLANG_TOOLING_TRANSFORMER_TRANSFORMER_H_
11 
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/Tooling/Refactoring/AtomicChange.h"
14 #include "clang/Tooling/Transformer/RewriteRule.h"
15 #include "llvm/Support/Error.h"
16 #include <functional>
17 #include <utility>
18 
19 namespace clang {
20 namespace tooling {
21 /// Handles the matcher and callback registration for a single `RewriteRule`, as
22 /// defined by the arguments of the constructor.
23 class Transformer : public ast_matchers::MatchFinder::MatchCallback {
24 public:
25   using ChangeConsumer =
26       std::function<void(Expected<clang::tooling::AtomicChange> Change)>;
27 
28   /// \param Consumer Receives each rewrite or error.  Will not necessarily be
29   /// called for each match; for example, if the rewrite is not applicable
30   /// because of macros, but doesn't fail.  Note that clients are responsible
31   /// for handling the case that independent \c AtomicChanges conflict with each
32   /// other.
33   Transformer(transformer::RewriteRule Rule, ChangeConsumer Consumer)
34       : Rule(std::move(Rule)), Consumer(std::move(Consumer)) {}
35 
36   /// N.B. Passes `this` pointer to `MatchFinder`.  So, this object should not
37   /// be moved after this call.
38   void registerMatchers(ast_matchers::MatchFinder *MatchFinder);
39 
40   /// Not called directly by users -- called by the framework, via base class
41   /// pointer.
42   void run(const ast_matchers::MatchFinder::MatchResult &Result) override;
43 
44 private:
45   transformer::RewriteRule Rule;
46   /// Receives each successful rewrites as an \c AtomicChange.
47   ChangeConsumer Consumer;
48 };
49 } // namespace tooling
50 } // namespace clang
51 
52 #endif // LLVM_CLANG_TOOLING_TRANSFORMER_TRANSFORMER_H_
53