1 //===--- Refactoring.h - Framework for clang refactoring tools --*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Interfaces supporting refactorings that span multiple translation units.
11 // While single translation unit refactorings are supported via the Rewriter,
12 // when refactoring multiple translation units changes must be stored in a
13 // SourceManager independent form, duplicate changes need to be removed, and
14 // all changes must be applied at once at the end of the refactoring so that
15 // the code is always parseable.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #ifndef LLVM_CLANG_TOOLING_REFACTORING_H
20 #define LLVM_CLANG_TOOLING_REFACTORING_H
21
22 #include "clang/Basic/SourceLocation.h"
23 #include "clang/Tooling/Tooling.h"
24 #include "llvm/ADT/StringRef.h"
25 #include <set>
26 #include <string>
27
28 namespace clang {
29
30 class Rewriter;
31 class SourceLocation;
32
33 namespace tooling {
34
35 /// \brief A source range independent of the \c SourceManager.
36 class Range {
37 public:
Range()38 Range() : Offset(0), Length(0) {}
Range(unsigned Offset,unsigned Length)39 Range(unsigned Offset, unsigned Length) : Offset(Offset), Length(Length) {}
40
41 /// \brief Accessors.
42 /// @{
getOffset()43 unsigned getOffset() const { return Offset; }
getLength()44 unsigned getLength() const { return Length; }
45 /// @}
46
47 /// \name Range Predicates
48 /// @{
49 /// \brief Whether this range overlaps with \p RHS or not.
overlapsWith(Range RHS)50 bool overlapsWith(Range RHS) const {
51 return Offset + Length > RHS.Offset && Offset < RHS.Offset + RHS.Length;
52 }
53
54 /// \brief Whether this range contains \p RHS or not.
contains(Range RHS)55 bool contains(Range RHS) const {
56 return RHS.Offset >= Offset &&
57 (RHS.Offset + RHS.Length) <= (Offset + Length);
58 }
59 /// @}
60
61 private:
62 unsigned Offset;
63 unsigned Length;
64 };
65
66 /// \brief A text replacement.
67 ///
68 /// Represents a SourceManager independent replacement of a range of text in a
69 /// specific file.
70 class Replacement {
71 public:
72 /// \brief Creates an invalid (not applicable) replacement.
73 Replacement();
74
75 /// \brief Creates a replacement of the range [Offset, Offset+Length) in
76 /// FilePath with ReplacementText.
77 ///
78 /// \param FilePath A source file accessible via a SourceManager.
79 /// \param Offset The byte offset of the start of the range in the file.
80 /// \param Length The length of the range in bytes.
81 Replacement(StringRef FilePath, unsigned Offset,
82 unsigned Length, StringRef ReplacementText);
83
84 /// \brief Creates a Replacement of the range [Start, Start+Length) with
85 /// ReplacementText.
86 Replacement(const SourceManager &Sources, SourceLocation Start, unsigned Length,
87 StringRef ReplacementText);
88
89 /// \brief Creates a Replacement of the given range with ReplacementText.
90 Replacement(const SourceManager &Sources, const CharSourceRange &Range,
91 StringRef ReplacementText);
92
93 /// \brief Creates a Replacement of the node with ReplacementText.
94 template <typename Node>
95 Replacement(const SourceManager &Sources, const Node &NodeToReplace,
96 StringRef ReplacementText);
97
98 /// \brief Returns whether this replacement can be applied to a file.
99 ///
100 /// Only replacements that are in a valid file can be applied.
101 bool isApplicable() const;
102
103 /// \brief Accessors.
104 /// @{
getFilePath()105 StringRef getFilePath() const { return FilePath; }
getOffset()106 unsigned getOffset() const { return ReplacementRange.getOffset(); }
getLength()107 unsigned getLength() const { return ReplacementRange.getLength(); }
getReplacementText()108 StringRef getReplacementText() const { return ReplacementText; }
109 /// @}
110
111 /// \brief Applies the replacement on the Rewriter.
112 bool apply(Rewriter &Rewrite) const;
113
114 /// \brief Returns a human readable string representation.
115 std::string toString() const;
116
117 private:
118 void setFromSourceLocation(const SourceManager &Sources, SourceLocation Start,
119 unsigned Length, StringRef ReplacementText);
120 void setFromSourceRange(const SourceManager &Sources,
121 const CharSourceRange &Range,
122 StringRef ReplacementText);
123
124 std::string FilePath;
125 Range ReplacementRange;
126 std::string ReplacementText;
127 };
128
129 /// \brief Less-than operator between two Replacements.
130 bool operator<(const Replacement &LHS, const Replacement &RHS);
131
132 /// \brief Equal-to operator between two Replacements.
133 bool operator==(const Replacement &LHS, const Replacement &RHS);
134
135 /// \brief A set of Replacements.
136 /// FIXME: Change to a vector and deduplicate in the RefactoringTool.
137 typedef std::set<Replacement> Replacements;
138
139 /// \brief Apply all replacements in \p Replaces to the Rewriter \p Rewrite.
140 ///
141 /// Replacement applications happen independently of the success of
142 /// other applications.
143 ///
144 /// \returns true if all replacements apply. false otherwise.
145 bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite);
146
147 /// \brief Apply all replacements in \p Replaces to the Rewriter \p Rewrite.
148 ///
149 /// Replacement applications happen independently of the success of
150 /// other applications.
151 ///
152 /// \returns true if all replacements apply. false otherwise.
153 bool applyAllReplacements(const std::vector<Replacement> &Replaces,
154 Rewriter &Rewrite);
155
156 /// \brief Applies all replacements in \p Replaces to \p Code.
157 ///
158 /// This completely ignores the path stored in each replacement. If one or more
159 /// replacements cannot be applied, this returns an empty \c string.
160 std::string applyAllReplacements(StringRef Code, const Replacements &Replaces);
161
162 /// \brief Calculates how a code \p Position is shifted when \p Replaces are
163 /// applied.
164 unsigned shiftedCodePosition(const Replacements& Replaces, unsigned Position);
165
166 /// \brief Calculates how a code \p Position is shifted when \p Replaces are
167 /// applied.
168 ///
169 /// \pre Replaces[i].getOffset() <= Replaces[i+1].getOffset().
170 unsigned shiftedCodePosition(const std::vector<Replacement> &Replaces,
171 unsigned Position);
172
173 /// \brief Removes duplicate Replacements and reports if Replacements conflict
174 /// with one another.
175 ///
176 /// \post Replaces[i].getOffset() <= Replaces[i+1].getOffset().
177 ///
178 /// This function sorts \p Replaces so that conflicts can be reported simply by
179 /// offset into \p Replaces and number of elements in the conflict.
180 void deduplicate(std::vector<Replacement> &Replaces,
181 std::vector<Range> &Conflicts);
182
183 /// \brief Collection of Replacements generated from a single translation unit.
184 struct TranslationUnitReplacements {
185 /// Name of the main source for the translation unit.
186 std::string MainSourceFile;
187
188 /// A freeform chunk of text to describe the context of the replacements.
189 /// Will be printed, for example, when detecting conflicts during replacement
190 /// deduplication.
191 std::string Context;
192
193 std::vector<Replacement> Replacements;
194 };
195
196 /// \brief A tool to run refactorings.
197 ///
198 /// This is a refactoring specific version of \see ClangTool. FrontendActions
199 /// passed to run() and runAndSave() should add replacements to
200 /// getReplacements().
201 class RefactoringTool : public ClangTool {
202 public:
203 /// \see ClangTool::ClangTool.
204 RefactoringTool(const CompilationDatabase &Compilations,
205 ArrayRef<std::string> SourcePaths);
206
207 /// \brief Returns the set of replacements to which replacements should
208 /// be added during the run of the tool.
209 Replacements &getReplacements();
210
211 /// \brief Call run(), apply all generated replacements, and immediately save
212 /// the results to disk.
213 ///
214 /// \returns 0 upon success. Non-zero upon failure.
215 int runAndSave(FrontendActionFactory *ActionFactory);
216
217 /// \brief Apply all stored replacements to the given Rewriter.
218 ///
219 /// Replacement applications happen independently of the success of other
220 /// applications.
221 ///
222 /// \returns true if all replacements apply. false otherwise.
223 bool applyAllReplacements(Rewriter &Rewrite);
224
225 private:
226 /// \brief Write all refactored files to disk.
227 int saveRewrittenFiles(Rewriter &Rewrite);
228
229 private:
230 Replacements Replace;
231 };
232
233 template <typename Node>
Replacement(const SourceManager & Sources,const Node & NodeToReplace,StringRef ReplacementText)234 Replacement::Replacement(const SourceManager &Sources,
235 const Node &NodeToReplace, StringRef ReplacementText) {
236 const CharSourceRange Range =
237 CharSourceRange::getTokenRange(NodeToReplace->getSourceRange());
238 setFromSourceRange(Sources, Range, ReplacementText);
239 }
240
241 } // end namespace tooling
242 } // end namespace clang
243
244 #endif // end namespace LLVM_CLANG_TOOLING_REFACTORING_H
245