xref: /llvm-project/clang-tools-extra/clangd/refactor/Tweak.h (revision b735c66da9c9ae752b88941d466895a0b696c75e)
1 //===--- Tweak.h -------------------------------------------------*- 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 // Tweaks are small actions that run over the AST and produce edits, messages
9 // etc as a result. They are local, i.e. they should take the current editor
10 // context, e.g. the cursor position and selection into account.
11 // The actions are executed in two stages:
12 //   - Stage 1 should check whether the action is available in a current
13 //     context. It should be cheap and fast to compute as it is executed for all
14 //     available actions on every client request, which happen quite frequently.
15 //   - Stage 2 is performed after stage 1 and can be more expensive to compute.
16 //     It is performed when the user actually chooses the action.
17 //===----------------------------------------------------------------------===//
18 
19 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_REFACTOR_TWEAK_H
20 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_REFACTOR_TWEAK_H
21 
22 #include "ParsedAST.h"
23 #include "Selection.h"
24 #include "SourceCode.h"
25 #include "index/Index.h"
26 #include "support/Path.h"
27 #include "clang/Tooling/Core/Replacement.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/Support/Error.h"
30 #include <optional>
31 #include <string>
32 
33 namespace clang {
34 namespace clangd {
35 
36 class FeatureModuleSet;
37 
38 /// An interface base for small context-sensitive refactoring actions.
39 /// To implement a new tweak use the following pattern in a .cpp file:
40 ///   class MyTweak : public Tweak {
41 ///   public:
42 ///     const char* id() const override final; // defined by REGISTER_TWEAK.
43 ///     // implement other methods here.
44 ///   };
45 ///   REGISTER_TWEAK(MyTweak);
46 class Tweak {
47 public:
48   /// Input to prepare and apply tweaks.
49   struct Selection {
50     Selection(const SymbolIndex *Index, ParsedAST &AST, unsigned RangeBegin,
51               unsigned RangeEnd, SelectionTree ASTSelection,
52               llvm::vfs::FileSystem *VFS);
53     /// The text of the active document.
54     llvm::StringRef Code;
55     /// The Index for handling codebase related queries.
56     const SymbolIndex *Index = nullptr;
57     /// The parsed active file. Never null. (Pointer so Selection is movable).
58     ParsedAST *AST;
59     /// A location of the cursor in the editor.
60     // FIXME: Cursor is redundant and should be removed
61     SourceLocation Cursor;
62     /// The begin offset of the selection
63     unsigned SelectionBegin;
64     /// The end offset of the selection
65     unsigned SelectionEnd;
66     /// The AST nodes that were selected.
67     SelectionTree ASTSelection;
68     /// File system used to access source code (for cross-file tweaks).
69     /// This is only populated when applying a tweak, not during prepare.
70     llvm::vfs::FileSystem *FS = nullptr;
71     // FIXME: provide a way to get sources and ASTs for other files.
72   };
73 
74   struct Effect {
75     /// A message to be displayed to the user.
76     std::optional<std::string> ShowMessage;
77     FileEdits ApplyEdits;
78     /// Whether the edits should be formatted before presenting to the client.
79     /// Note that it applies to all files.
80     bool FormatEdits = true;
81 
82     static Effect showMessage(StringRef S) {
83       Effect E;
84       E.ShowMessage = std::string(S);
85       return E;
86     }
87 
88     /// Path is the absolute, symlink-resolved path for the file pointed by FID
89     /// in SM. Edit is generated from Replacements.
90     /// Fails if cannot figure out absolute path for FID.
91     static llvm::Expected<std::pair<Path, Edit>>
92     fileEdit(const SourceManager &SM, FileID FID,
93              tooling::Replacements Replacements);
94 
95     /// Creates an effect with an Edit for the main file.
96     /// Fails if cannot figure out absolute path for main file.
97     static llvm::Expected<Tweak::Effect>
98     mainFileEdit(const SourceManager &SM, tooling::Replacements Replacements);
99   };
100 
101   virtual ~Tweak() = default;
102   /// A unique id of the action, it is always equal to the name of the class
103   /// defining the Tweak. Definition is provided automatically by
104   /// REGISTER_TWEAK.
105   virtual const char *id() const = 0;
106   /// Run the first stage of the action. Returns true indicating that the
107   /// action is available and should be shown to the user. Returns false if the
108   /// action is not available.
109   /// This function should be fast, if the action requires non-trivial work it
110   /// should be moved into 'apply'.
111   /// Returns true iff the action is available and apply() can be called on it.
112   virtual bool prepare(const Selection &Sel) = 0;
113   /// Run the second stage of the action that would produce the actual effect.
114   /// EXPECTS: prepare() was called and returned true.
115   virtual Expected<Effect> apply(const Selection &Sel) = 0;
116 
117   /// A one-line title of the action that should be shown to the users in the
118   /// UI.
119   /// EXPECTS: prepare() was called and returned true.
120   virtual std::string title() const = 0;
121   /// Describes what kind of action this is.
122   /// EXPECTS: prepare() was called and returned true.
123   virtual llvm::StringLiteral kind() const = 0;
124   /// Is this a 'hidden' tweak, which are off by default.
125   virtual bool hidden() const { return false; }
126 };
127 
128 // All tweaks must be registered in the .cpp file next to their definition.
129 #define REGISTER_TWEAK(Subclass)                                               \
130   ::llvm::Registry<::clang::clangd::Tweak>::Add<Subclass>                      \
131       TweakRegistrationFor##Subclass(#Subclass, /*Description=*/"");           \
132   const char *Subclass::id() const { return #Subclass; }
133 
134 /// Calls prepare() on all tweaks that satisfy the filter, returning those that
135 /// can run on the selection.
136 std::vector<std::unique_ptr<Tweak>>
137 prepareTweaks(const Tweak::Selection &S,
138               llvm::function_ref<bool(const Tweak &)> Filter,
139               const FeatureModuleSet *Modules);
140 
141 // Calls prepare() on the tweak with a given ID.
142 // If prepare() returns false, returns an error.
143 // If prepare() returns true, returns the corresponding tweak.
144 llvm::Expected<std::unique_ptr<Tweak>>
145 prepareTweak(StringRef ID, const Tweak::Selection &S,
146              const FeatureModuleSet *Modules);
147 } // namespace clangd
148 } // namespace clang
149 
150 namespace llvm {
151 extern template class Registry<clang::clangd::Tweak>;
152 } // namespace llvm
153 
154 #endif
155