clang-tools 20.0.0git
Tweak.h
Go to the documentation of this file.
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
33namespace clang {
34namespace clangd {
35
36class 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);
46class Tweak {
47public:
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).
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
64 /// The end offset of the selection
65 unsigned SelectionEnd;
66 /// The AST nodes that were selected.
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;
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.
136std::vector<std::unique_ptr<Tweak>>
137prepareTweaks(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.
144llvm::Expected<std::unique_ptr<Tweak>>
145prepareTweak(StringRef ID, const Tweak::Selection &S,
146 const FeatureModuleSet *Modules);
147} // namespace clangd
148} // namespace clang
149
150#endif
const Expr * E
Stores and provides access to parsed AST.
Definition: ParsedAST.h:46
Interface for symbol indexes that can be used for searching or matching symbols among a set of symbol...
Definition: Index.h:113
An interface base for small context-sensitive refactoring actions.
Definition: Tweak.h:46
virtual bool prepare(const Selection &Sel)=0
Run the first stage of the action.
virtual ~Tweak()=default
virtual std::string title() const =0
A one-line title of the action that should be shown to the users in the UI.
virtual bool hidden() const
Is this a 'hidden' tweak, which are off by default.
Definition: Tweak.h:125
virtual const char * id() const =0
A unique id of the action, it is always equal to the name of the class defining the Tweak.
virtual Expected< Effect > apply(const Selection &Sel)=0
Run the second stage of the action that would produce the actual effect.
virtual llvm::StringLiteral kind() const =0
Describes what kind of action this is.
llvm::Expected< std::unique_ptr< Tweak > > prepareTweak(StringRef ID, const Tweak::Selection &S, const FeatureModuleSet *Modules)
Definition: Tweak.cpp:91
llvm::StringMap< Edit > FileEdits
A mapping from absolute file path (the one used for accessing the underlying VFS) to edits.
Definition: SourceCode.h:209
std::vector< std::unique_ptr< Tweak > > prepareTweaks(const Tweak::Selection &S, llvm::function_ref< bool(const Tweak &)> Filter, const FeatureModuleSet *Modules)
Calls prepare() on all tweaks that satisfy the filter, returning those that can run on the selection.
Definition: Tweak.cpp:72
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
static llvm::Expected< Tweak::Effect > mainFileEdit(const SourceManager &SM, tooling::Replacements Replacements)
Creates an effect with an Edit for the main file.
Definition: Tweak.cpp:115
static Effect showMessage(StringRef S)
Definition: Tweak.h:82
std::optional< std::string > ShowMessage
A message to be displayed to the user.
Definition: Tweak.h:76
bool FormatEdits
Whether the edits should be formatted before presenting to the client.
Definition: Tweak.h:80
static llvm::Expected< std::pair< Path, Edit > > fileEdit(const SourceManager &SM, FileID FID, tooling::Replacements Replacements)
Path is the absolute, symlink-resolved path for the file pointed by FID in SM.
Definition: Tweak.cpp:104
Input to prepare and apply tweaks.
Definition: Tweak.h:49
SourceLocation Cursor
A location of the cursor in the editor.
Definition: Tweak.h:61
unsigned SelectionBegin
The begin offset of the selection.
Definition: Tweak.h:63
llvm::vfs::FileSystem * FS
File system used to access source code (for cross-file tweaks).
Definition: Tweak.h:70
unsigned SelectionEnd
The end offset of the selection.
Definition: Tweak.h:65
ParsedAST * AST
The parsed active file. Never null. (Pointer so Selection is movable).
Definition: Tweak.h:58
const SymbolIndex * Index
The Index for handling codebase related queries.
Definition: Tweak.h:56
SelectionTree ASTSelection
The AST nodes that were selected.
Definition: Tweak.h:67
llvm::StringRef Code
The text of the active document.
Definition: Tweak.h:54