/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Tooling/Refactoring/AtomicChange.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | //===--- AtomicChange.cpp - AtomicChange implementation -----------------*- 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 | | #include "clang/Tooling/Refactoring/AtomicChange.h" |
10 | | #include "clang/Tooling/ReplacementsYaml.h" |
11 | | #include "llvm/Support/YAMLTraits.h" |
12 | | #include <string> |
13 | | |
14 | | LLVM_YAML_IS_SEQUENCE_VECTOR(clang::tooling::AtomicChange) |
15 | | |
16 | | namespace { |
17 | | /// Helper to (de)serialize an AtomicChange since we don't have direct |
18 | | /// access to its data members. |
19 | | /// Data members of a normalized AtomicChange can be directly mapped from/to |
20 | | /// YAML string. |
21 | | struct NormalizedAtomicChange { |
22 | 1 | NormalizedAtomicChange() = default; |
23 | | |
24 | 0 | NormalizedAtomicChange(const llvm::yaml::IO &) {} |
25 | | |
26 | | // This converts AtomicChange's internal implementation of the replacements |
27 | | // set to a vector of replacements. |
28 | | NormalizedAtomicChange(const llvm::yaml::IO &, |
29 | | const clang::tooling::AtomicChange &E) |
30 | 2 | : Key(E.getKey()), FilePath(E.getFilePath()), Error(E.getError()), |
31 | 2 | InsertedHeaders(E.getInsertedHeaders()), |
32 | 2 | RemovedHeaders(E.getRemovedHeaders()), |
33 | 2 | Replaces(E.getReplacements().begin(), E.getReplacements().end()) {} |
34 | | |
35 | | // This is not expected to be called but needed for template instantiation. |
36 | 0 | clang::tooling::AtomicChange denormalize(const llvm::yaml::IO &) { |
37 | 0 | llvm_unreachable("Do not convert YAML to AtomicChange directly with '>>'. " |
38 | 0 | "Use AtomicChange::convertFromYAML instead."); |
39 | 0 | } |
40 | | std::string Key; |
41 | | std::string FilePath; |
42 | | std::string Error; |
43 | | std::vector<std::string> InsertedHeaders; |
44 | | std::vector<std::string> RemovedHeaders; |
45 | | std::vector<clang::tooling::Replacement> Replaces; |
46 | | }; |
47 | | } // anonymous namespace |
48 | | |
49 | | namespace llvm { |
50 | | namespace yaml { |
51 | | |
52 | | /// Specialized MappingTraits to describe how an AtomicChange is |
53 | | /// (de)serialized. |
54 | | template <> struct MappingTraits<NormalizedAtomicChange> { |
55 | 1 | static void mapping(IO &Io, NormalizedAtomicChange &Doc) { |
56 | 1 | Io.mapRequired("Key", Doc.Key); |
57 | 1 | Io.mapRequired("FilePath", Doc.FilePath); |
58 | 1 | Io.mapRequired("Error", Doc.Error); |
59 | 1 | Io.mapRequired("InsertedHeaders", Doc.InsertedHeaders); |
60 | 1 | Io.mapRequired("RemovedHeaders", Doc.RemovedHeaders); |
61 | 1 | Io.mapRequired("Replacements", Doc.Replaces); |
62 | 1 | } |
63 | | }; |
64 | | |
65 | | /// Specialized MappingTraits to describe how an AtomicChange is |
66 | | /// (de)serialized. |
67 | | template <> struct MappingTraits<clang::tooling::AtomicChange> { |
68 | 2 | static void mapping(IO &Io, clang::tooling::AtomicChange &Doc) { |
69 | 2 | MappingNormalization<NormalizedAtomicChange, clang::tooling::AtomicChange> |
70 | 2 | Keys(Io, Doc); |
71 | 2 | Io.mapRequired("Key", Keys->Key); |
72 | 2 | Io.mapRequired("FilePath", Keys->FilePath); |
73 | 2 | Io.mapRequired("Error", Keys->Error); |
74 | 2 | Io.mapRequired("InsertedHeaders", Keys->InsertedHeaders); |
75 | 2 | Io.mapRequired("RemovedHeaders", Keys->RemovedHeaders); |
76 | 2 | Io.mapRequired("Replacements", Keys->Replaces); |
77 | 2 | } |
78 | | }; |
79 | | |
80 | | } // end namespace yaml |
81 | | } // end namespace llvm |
82 | | |
83 | | namespace clang { |
84 | | namespace tooling { |
85 | | namespace { |
86 | | |
87 | | // Returns true if there is any line that violates \p ColumnLimit in range |
88 | | // [Start, End]. |
89 | | bool violatesColumnLimit(llvm::StringRef Code, unsigned ColumnLimit, |
90 | 7 | unsigned Start, unsigned End) { |
91 | 7 | auto StartPos = Code.rfind('\n', Start); |
92 | 7 | StartPos = (StartPos == llvm::StringRef::npos) ? 03 : StartPos + 14 ; |
93 | | |
94 | 7 | auto EndPos = Code.find("\n", End); |
95 | 7 | if (EndPos == llvm::StringRef::npos) |
96 | 2 | EndPos = Code.size(); |
97 | | |
98 | 7 | llvm::SmallVector<llvm::StringRef, 8> Lines; |
99 | 7 | Code.substr(StartPos, EndPos - StartPos).split(Lines, '\n'); |
100 | 7 | for (llvm::StringRef Line : Lines) |
101 | 8 | if (Line.size() > ColumnLimit) |
102 | 2 | return true; |
103 | 5 | return false; |
104 | 7 | } |
105 | | |
106 | | std::vector<Range> |
107 | | getRangesForFormating(llvm::StringRef Code, unsigned ColumnLimit, |
108 | | ApplyChangesSpec::FormatOption Format, |
109 | 119 | const clang::tooling::Replacements &Replaces) { |
110 | | // kNone suppresses formatting entirely. |
111 | 119 | if (Format == ApplyChangesSpec::kNone) |
112 | 95 | return {}; |
113 | 24 | std::vector<clang::tooling::Range> Ranges; |
114 | | // This works assuming that replacements are ordered by offset. |
115 | | // FIXME: use `getAffectedRanges()` to calculate when it does not include '\n' |
116 | | // at the end of an insertion in affected ranges. |
117 | 24 | int Offset = 0; |
118 | 58 | for (const clang::tooling::Replacement &R : Replaces) { |
119 | 58 | int Start = R.getOffset() + Offset; |
120 | 58 | int End = Start + R.getReplacementText().size(); |
121 | 58 | if (!R.getReplacementText().empty() && |
122 | 58 | R.getReplacementText().back() == '\n'30 && R.getLength() == 07 && |
123 | 58 | R.getOffset() > 06 && R.getOffset() <= Code.size()4 && |
124 | 58 | Code[R.getOffset() - 1] == '\n'4 ) |
125 | | // If we are inserting at the start of a line and the replacement ends in |
126 | | // a newline, we don't need to format the subsequent line. |
127 | 2 | --End; |
128 | 58 | Offset += R.getReplacementText().size() - R.getLength(); |
129 | | |
130 | 58 | if (Format == ApplyChangesSpec::kAll || |
131 | 58 | violatesColumnLimit(Code, ColumnLimit, Start, End)7 ) |
132 | 53 | Ranges.emplace_back(Start, End - Start); |
133 | 58 | } |
134 | 24 | return Ranges; |
135 | 119 | } |
136 | | |
137 | 3 | inline llvm::Error make_string_error(const llvm::Twine &Message) { |
138 | 3 | return llvm::make_error<llvm::StringError>(Message, |
139 | 3 | llvm::inconvertibleErrorCode()); |
140 | 3 | } |
141 | | |
142 | | // Creates replacements for inserting/deleting #include headers. |
143 | | llvm::Expected<Replacements> |
144 | | createReplacementsForHeaders(llvm::StringRef FilePath, llvm::StringRef Code, |
145 | | llvm::ArrayRef<AtomicChange> Changes, |
146 | 122 | const format::FormatStyle &Style) { |
147 | | // Create header insertion/deletion replacements to be cleaned up |
148 | | // (i.e. converted to real insertion/deletion replacements). |
149 | 122 | Replacements HeaderReplacements; |
150 | 159 | for (const auto &Change : Changes) { |
151 | 159 | for (llvm::StringRef Header : Change.getInsertedHeaders()) { |
152 | 12 | std::string EscapedHeader = |
153 | 12 | Header.startswith("<") || Header.startswith("\"")7 |
154 | 12 | ? Header.str()6 |
155 | 12 | : ("\"" + Header + "\"").str()6 ; |
156 | 12 | std::string ReplacementText = "#include " + EscapedHeader; |
157 | | // Offset UINT_MAX and length 0 indicate that the replacement is a header |
158 | | // insertion. |
159 | 12 | llvm::Error Err = HeaderReplacements.add( |
160 | 12 | tooling::Replacement(FilePath, UINT_MAX, 0, ReplacementText)); |
161 | 12 | if (Err) |
162 | 0 | return std::move(Err); |
163 | 12 | } |
164 | 159 | for (const std::string &Header : Change.getRemovedHeaders()) { |
165 | | // Offset UINT_MAX and length 1 indicate that the replacement is a header |
166 | | // deletion. |
167 | 3 | llvm::Error Err = |
168 | 3 | HeaderReplacements.add(Replacement(FilePath, UINT_MAX, 1, Header)); |
169 | 3 | if (Err) |
170 | 0 | return std::move(Err); |
171 | 3 | } |
172 | 159 | } |
173 | | |
174 | | // cleanupAroundReplacements() converts header insertions/deletions into |
175 | | // actual replacements that add/remove headers at the right location. |
176 | 122 | return clang::format::cleanupAroundReplacements(Code, HeaderReplacements, |
177 | 122 | Style); |
178 | 122 | } |
179 | | |
180 | | // Combine replacements in all Changes as a `Replacements`. This ignores the |
181 | | // file path in all replacements and replaces them with \p FilePath. |
182 | | llvm::Expected<Replacements> |
183 | | combineReplacementsInChanges(llvm::StringRef FilePath, |
184 | 122 | llvm::ArrayRef<AtomicChange> Changes) { |
185 | 122 | Replacements Replaces; |
186 | 122 | for (const auto &Change : Changes) |
187 | 159 | for (const auto &R : Change.getReplacements()) |
188 | 231 | if (auto Err = Replaces.add(Replacement( |
189 | 231 | FilePath, R.getOffset(), R.getLength(), R.getReplacementText()))) |
190 | 3 | return std::move(Err); |
191 | 119 | return Replaces; |
192 | 122 | } |
193 | | |
194 | | } // end namespace |
195 | | |
196 | | AtomicChange::AtomicChange(const SourceManager &SM, |
197 | 1.31k | SourceLocation KeyPosition) { |
198 | 1.31k | const FullSourceLoc FullKeyPosition(KeyPosition, SM); |
199 | 1.31k | std::pair<FileID, unsigned> FileIDAndOffset = |
200 | 1.31k | FullKeyPosition.getSpellingLoc().getDecomposedLoc(); |
201 | 1.31k | OptionalFileEntryRef FE = SM.getFileEntryRefForID(FileIDAndOffset.first); |
202 | 1.31k | assert(FE && "Cannot create AtomicChange with invalid location."); |
203 | 1.31k | FilePath = std::string(FE->getName()); |
204 | 1.31k | Key = FilePath + ":" + std::to_string(FileIDAndOffset.second); |
205 | 1.31k | } |
206 | | |
207 | | AtomicChange::AtomicChange(const SourceManager &SM, SourceLocation KeyPosition, |
208 | | llvm::Any M) |
209 | 127 | : AtomicChange(SM, KeyPosition) { |
210 | 127 | Metadata = std::move(M); |
211 | 127 | } Unexecuted instantiation: clang::tooling::AtomicChange::AtomicChange(clang::SourceManager const&, clang::SourceLocation, llvm::Any) clang::tooling::AtomicChange::AtomicChange(clang::SourceManager const&, clang::SourceLocation, llvm::Any) Line | Count | Source | 209 | 127 | : AtomicChange(SM, KeyPosition) { | 210 | 127 | Metadata = std::move(M); | 211 | 127 | } |
|
212 | | |
213 | | AtomicChange::AtomicChange(std::string Key, std::string FilePath, |
214 | | std::string Error, |
215 | | std::vector<std::string> InsertedHeaders, |
216 | | std::vector<std::string> RemovedHeaders, |
217 | | clang::tooling::Replacements Replaces) |
218 | 1 | : Key(std::move(Key)), FilePath(std::move(FilePath)), |
219 | 1 | Error(std::move(Error)), InsertedHeaders(std::move(InsertedHeaders)), |
220 | 1 | RemovedHeaders(std::move(RemovedHeaders)), Replaces(std::move(Replaces)) { |
221 | 1 | } |
222 | | |
223 | 12 | bool AtomicChange::operator==(const AtomicChange &Other) const { |
224 | 12 | if (Key != Other.Key || FilePath != Other.FilePath || Error != Other.Error) |
225 | 0 | return false; |
226 | 12 | if (!(Replaces == Other.Replaces)) |
227 | 0 | return false; |
228 | | // FXIME: Compare header insertions/removals. |
229 | 12 | return true; |
230 | 12 | } |
231 | | |
232 | 2 | std::string AtomicChange::toYAMLString() { |
233 | 2 | std::string YamlContent; |
234 | 2 | llvm::raw_string_ostream YamlContentStream(YamlContent); |
235 | | |
236 | 2 | llvm::yaml::Output YAML(YamlContentStream); |
237 | 2 | YAML << *this; |
238 | 2 | YamlContentStream.flush(); |
239 | 2 | return YamlContent; |
240 | 2 | } |
241 | | |
242 | 1 | AtomicChange AtomicChange::convertFromYAML(llvm::StringRef YAMLContent) { |
243 | 1 | NormalizedAtomicChange NE; |
244 | 1 | llvm::yaml::Input YAML(YAMLContent); |
245 | 1 | YAML >> NE; |
246 | 1 | AtomicChange E(NE.Key, NE.FilePath, NE.Error, NE.InsertedHeaders, |
247 | 1 | NE.RemovedHeaders, tooling::Replacements()); |
248 | 2 | for (const auto &R : NE.Replaces) { |
249 | 2 | llvm::Error Err = E.Replaces.add(R); |
250 | 2 | if (Err) |
251 | 0 | llvm_unreachable( |
252 | 2 | "Failed to add replacement when Converting YAML to AtomicChange."); |
253 | 2 | llvm::consumeError(std::move(Err)); |
254 | 2 | } |
255 | 1 | return E; |
256 | 1 | } |
257 | | |
258 | | llvm::Error AtomicChange::replace(const SourceManager &SM, |
259 | | const CharSourceRange &Range, |
260 | 1.29k | llvm::StringRef ReplacementText) { |
261 | 1.29k | return Replaces.add(Replacement(SM, Range, ReplacementText)); |
262 | 1.29k | } |
263 | | |
264 | | llvm::Error AtomicChange::replace(const SourceManager &SM, SourceLocation Loc, |
265 | 56 | unsigned Length, llvm::StringRef Text) { |
266 | 56 | return Replaces.add(Replacement(SM, Loc, Length, Text)); |
267 | 56 | } |
268 | | |
269 | | llvm::Error AtomicChange::insert(const SourceManager &SM, SourceLocation Loc, |
270 | 40 | llvm::StringRef Text, bool InsertAfter) { |
271 | 40 | if (Text.empty()) |
272 | 0 | return llvm::Error::success(); |
273 | 40 | Replacement R(SM, Loc, 0, Text); |
274 | 40 | llvm::Error Err = Replaces.add(R); |
275 | 40 | if (Err) { |
276 | 5 | return llvm::handleErrors( |
277 | 5 | std::move(Err), [&](const ReplacementError &RE) -> llvm::Error { |
278 | 5 | if (RE.get() != replacement_error::insert_conflict) |
279 | 3 | return llvm::make_error<ReplacementError>(RE); |
280 | 2 | unsigned NewOffset = Replaces.getShiftedCodePosition(R.getOffset()); |
281 | 2 | if (!InsertAfter) |
282 | 1 | NewOffset -= |
283 | 1 | RE.getExistingReplacement()->getReplacementText().size(); |
284 | 2 | Replacement NewR(R.getFilePath(), NewOffset, 0, Text); |
285 | 2 | Replaces = Replaces.merge(Replacements(NewR)); |
286 | 2 | return llvm::Error::success(); |
287 | 5 | }); |
288 | 5 | } |
289 | 35 | return llvm::Error::success(); |
290 | 40 | } |
291 | | |
292 | 15 | void AtomicChange::addHeader(llvm::StringRef Header) { |
293 | 15 | InsertedHeaders.push_back(std::string(Header)); |
294 | 15 | } |
295 | | |
296 | 5 | void AtomicChange::removeHeader(llvm::StringRef Header) { |
297 | 5 | RemovedHeaders.push_back(std::string(Header)); |
298 | 5 | } |
299 | | |
300 | | llvm::Expected<std::string> |
301 | | applyAtomicChanges(llvm::StringRef FilePath, llvm::StringRef Code, |
302 | | llvm::ArrayRef<AtomicChange> Changes, |
303 | 122 | const ApplyChangesSpec &Spec) { |
304 | 122 | llvm::Expected<Replacements> HeaderReplacements = |
305 | 122 | createReplacementsForHeaders(FilePath, Code, Changes, Spec.Style); |
306 | 122 | if (!HeaderReplacements) |
307 | 0 | return make_string_error( |
308 | 0 | "Failed to create replacements for header changes: " + |
309 | 0 | llvm::toString(HeaderReplacements.takeError())); |
310 | | |
311 | 122 | llvm::Expected<Replacements> Replaces = |
312 | 122 | combineReplacementsInChanges(FilePath, Changes); |
313 | 122 | if (!Replaces) |
314 | 3 | return make_string_error("Failed to combine replacements in all changes: " + |
315 | 3 | llvm::toString(Replaces.takeError())); |
316 | | |
317 | 119 | Replacements AllReplaces = std::move(*Replaces); |
318 | 119 | for (const auto &R : *HeaderReplacements) { |
319 | 12 | llvm::Error Err = AllReplaces.add(R); |
320 | 12 | if (Err) |
321 | 0 | return make_string_error( |
322 | 0 | "Failed to combine existing replacements with header replacements: " + |
323 | 0 | llvm::toString(std::move(Err))); |
324 | 12 | } |
325 | | |
326 | 119 | if (Spec.Cleanup) { |
327 | 83 | llvm::Expected<Replacements> CleanReplaces = |
328 | 83 | format::cleanupAroundReplacements(Code, AllReplaces, Spec.Style); |
329 | 83 | if (!CleanReplaces) |
330 | 0 | return make_string_error("Failed to cleanup around replacements: " + |
331 | 0 | llvm::toString(CleanReplaces.takeError())); |
332 | 83 | AllReplaces = std::move(*CleanReplaces); |
333 | 83 | } |
334 | | |
335 | | // Apply all replacements. |
336 | 119 | llvm::Expected<std::string> ChangedCode = |
337 | 119 | applyAllReplacements(Code, AllReplaces); |
338 | 119 | if (!ChangedCode) |
339 | 0 | return make_string_error("Failed to apply all replacements: " + |
340 | 0 | llvm::toString(ChangedCode.takeError())); |
341 | | |
342 | | // Sort inserted headers. This is done even if other formatting is turned off |
343 | | // as incorrectly sorted headers are always just wrong, it's not a matter of |
344 | | // taste. |
345 | 119 | Replacements HeaderSortingReplacements = format::sortIncludes( |
346 | 119 | Spec.Style, *ChangedCode, AllReplaces.getAffectedRanges(), FilePath); |
347 | 119 | ChangedCode = applyAllReplacements(*ChangedCode, HeaderSortingReplacements); |
348 | 119 | if (!ChangedCode) |
349 | 0 | return make_string_error( |
350 | 0 | "Failed to apply replacements for sorting includes: " + |
351 | 0 | llvm::toString(ChangedCode.takeError())); |
352 | | |
353 | 119 | AllReplaces = AllReplaces.merge(HeaderSortingReplacements); |
354 | | |
355 | 119 | std::vector<Range> FormatRanges = getRangesForFormating( |
356 | 119 | *ChangedCode, Spec.Style.ColumnLimit, Spec.Format, AllReplaces); |
357 | 119 | if (!FormatRanges.empty()) { |
358 | 23 | Replacements FormatReplacements = |
359 | 23 | format::reformat(Spec.Style, *ChangedCode, FormatRanges, FilePath); |
360 | 23 | ChangedCode = applyAllReplacements(*ChangedCode, FormatReplacements); |
361 | 23 | if (!ChangedCode) |
362 | 0 | return make_string_error( |
363 | 0 | "Failed to apply replacements for formatting changed code: " + |
364 | 0 | llvm::toString(ChangedCode.takeError())); |
365 | 23 | } |
366 | 119 | return ChangedCode; |
367 | 119 | } |
368 | | |
369 | | } // end namespace tooling |
370 | | } // end namespace clang |