Coverage Report

Created: 2020-02-15 09:57

/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
      : Key(E.getKey()), FilePath(E.getFilePath()), Error(E.getError()),
31
        InsertedHeaders(E.getInsertedHeaders()),
32
        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
7
94
7
  auto EndPos = Code.find("\n", End);
95
7
  if (EndPos == llvm::StringRef::npos)
96
2
    EndPos = Code.size();
97
7
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
7
  
return false5
;
104
7
}
105
106
std::vector<Range>
107
getRangesForFormating(llvm::StringRef Code, unsigned ColumnLimit,
108
                      ApplyChangesSpec::FormatOption Format,
109
88
                      const clang::tooling::Replacements &Replaces) {
110
88
  // kNone suppresses formatting entirely.
111
88
  if (Format == ApplyChangesSpec::kNone)
112
64
    return {};
113
24
  std::vector<clang::tooling::Range> Ranges;
114
24
  // This works assuming that replacements are ordered by offset.
115
24
  // FIXME: use `getAffectedRanges()` to calculate when it does not include '\n'
116
24
  // 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
2
      // If we are inserting at the start of a line and the replacement ends in
126
2
      // a newline, we don't need to format the subsequent line.
127
2
      --End;
128
58
    Offset += R.getReplacementText().size() - R.getLength();
129
58
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
24
}
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
91
                             const format::FormatStyle &Style) {
147
91
  // Create header insertion/deletion replacements to be cleaned up
148
91
  // (i.e. converted to real insertion/deletion replacements).
149
91
  Replacements HeaderReplacements;
150
118
  for (const auto &Change : Changes) {
151
118
    for (llvm::StringRef Header : Change.getInsertedHeaders()) {
152
10
      std::string EscapedHeader =
153
10
          Header.startswith("<") || 
Header.startswith("\"")6
154
10
              ? 
Header.str()5
155
10
              : 
("\"" + Header + "\"").str()5
;
156
10
      std::string ReplacementText = "#include " + EscapedHeader;
157
10
      // Offset UINT_MAX and length 0 indicate that the replacement is a header
158
10
      // insertion.
159
10
      llvm::Error Err = HeaderReplacements.add(
160
10
          tooling::Replacement(FilePath, UINT_MAX, 0, ReplacementText));
161
10
      if (Err)
162
0
        return std::move(Err);
163
10
    }
164
118
    for (const std::string &Header : Change.getRemovedHeaders()) {
165
3
      // Offset UINT_MAX and length 1 indicate that the replacement is a header
166
3
      // 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
118
  }
173
91
174
91
  // cleanupAroundReplacements() converts header insertions/deletions into
175
91
  // actual replacements that add/remove headers at the right location.
176
91
  return clang::format::cleanupAroundReplacements(Code, HeaderReplacements,
177
91
                                                  Style);
178
91
}
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
91
                             llvm::ArrayRef<AtomicChange> Changes) {
185
91
  Replacements Replaces;
186
91
  for (const auto &Change : Changes)
187
118
    for (const auto &R : Change.getReplacements())
188
160
      if (auto Err = Replaces.add(Replacement(
189
3
              FilePath, R.getOffset(), R.getLength(), R.getReplacementText())))
190
3
        return std::move(Err);
191
91
  
return Replaces88
;
192
91
}
193
194
} // end namespace
195
196
AtomicChange::AtomicChange(const SourceManager &SM,
197
1.17k
                           SourceLocation KeyPosition) {
198
1.17k
  const FullSourceLoc FullKeyPosition(KeyPosition, SM);
199
1.17k
  std::pair<FileID, unsigned> FileIDAndOffset =
200
1.17k
      FullKeyPosition.getSpellingLoc().getDecomposedLoc();
201
1.17k
  const FileEntry *FE = SM.getFileEntryForID(FileIDAndOffset.first);
202
1.17k
  assert(FE && "Cannot create AtomicChange with invalid location.");
203
1.17k
  FilePath = std::string(FE->getName());
204
1.17k
  Key = FilePath + ":" + std::to_string(FileIDAndOffset.second);
205
1.17k
}
206
207
AtomicChange::AtomicChange(std::string Key, std::string FilePath,
208
                           std::string Error,
209
                           std::vector<std::string> InsertedHeaders,
210
                           std::vector<std::string> RemovedHeaders,
211
                           clang::tooling::Replacements Replaces)
212
    : Key(std::move(Key)), FilePath(std::move(FilePath)),
213
      Error(std::move(Error)), InsertedHeaders(std::move(InsertedHeaders)),
214
1
      RemovedHeaders(std::move(RemovedHeaders)), Replaces(std::move(Replaces)) {
215
1
}
216
217
12
bool AtomicChange::operator==(const AtomicChange &Other) const {
218
12
  if (Key != Other.Key || FilePath != Other.FilePath || Error != Other.Error)
219
0
    return false;
220
12
  if (!(Replaces == Other.Replaces))
221
0
    return false;
222
12
  // FXIME: Compare header insertions/removals.
223
12
  return true;
224
12
}
225
226
2
std::string AtomicChange::toYAMLString() {
227
2
  std::string YamlContent;
228
2
  llvm::raw_string_ostream YamlContentStream(YamlContent);
229
2
230
2
  llvm::yaml::Output YAML(YamlContentStream);
231
2
  YAML << *this;
232
2
  YamlContentStream.flush();
233
2
  return YamlContent;
234
2
}
235
236
1
AtomicChange AtomicChange::convertFromYAML(llvm::StringRef YAMLContent) {
237
1
  NormalizedAtomicChange NE;
238
1
  llvm::yaml::Input YAML(YAMLContent);
239
1
  YAML >> NE;
240
1
  AtomicChange E(NE.Key, NE.FilePath, NE.Error, NE.InsertedHeaders,
241
1
                 NE.RemovedHeaders, tooling::Replacements());
242
2
  for (const auto &R : NE.Replaces) {
243
2
    llvm::Error Err = E.Replaces.add(R);
244
2
    if (Err)
245
2
      
llvm_unreachable0
(
246
2
          "Failed to add replacement when Converting YAML to AtomicChange.");
247
2
    llvm::consumeError(std::move(Err));
248
2
  }
249
1
  return E;
250
1
}
251
252
llvm::Error AtomicChange::replace(const SourceManager &SM,
253
                                  const CharSourceRange &Range,
254
1.17k
                                  llvm::StringRef ReplacementText) {
255
1.17k
  return Replaces.add(Replacement(SM, Range, ReplacementText));
256
1.17k
}
257
258
llvm::Error AtomicChange::replace(const SourceManager &SM, SourceLocation Loc,
259
56
                                  unsigned Length, llvm::StringRef Text) {
260
56
  return Replaces.add(Replacement(SM, Loc, Length, Text));
261
56
}
262
263
llvm::Error AtomicChange::insert(const SourceManager &SM, SourceLocation Loc,
264
40
                                 llvm::StringRef Text, bool InsertAfter) {
265
40
  if (Text.empty())
266
0
    return llvm::Error::success();
267
40
  Replacement R(SM, Loc, 0, Text);
268
40
  llvm::Error Err = Replaces.add(R);
269
40
  if (Err) {
270
5
    return llvm::handleErrors(
271
5
        std::move(Err), [&](const ReplacementError &RE) -> llvm::Error {
272
5
          if (RE.get() != replacement_error::insert_conflict)
273
3
            return llvm::make_error<ReplacementError>(RE);
274
2
          unsigned NewOffset = Replaces.getShiftedCodePosition(R.getOffset());
275
2
          if (!InsertAfter)
276
1
            NewOffset -=
277
1
                RE.getExistingReplacement()->getReplacementText().size();
278
2
          Replacement NewR(R.getFilePath(), NewOffset, 0, Text);
279
2
          Replaces = Replaces.merge(Replacements(NewR));
280
2
          return llvm::Error::success();
281
2
        });
282
5
  }
283
35
  return llvm::Error::success();
284
35
}
285
286
12
void AtomicChange::addHeader(llvm::StringRef Header) {
287
12
  InsertedHeaders.push_back(std::string(Header));
288
12
}
289
290
5
void AtomicChange::removeHeader(llvm::StringRef Header) {
291
5
  RemovedHeaders.push_back(std::string(Header));
292
5
}
293
294
llvm::Expected<std::string>
295
applyAtomicChanges(llvm::StringRef FilePath, llvm::StringRef Code,
296
                   llvm::ArrayRef<AtomicChange> Changes,
297
91
                   const ApplyChangesSpec &Spec) {
298
91
  llvm::Expected<Replacements> HeaderReplacements =
299
91
      createReplacementsForHeaders(FilePath, Code, Changes, Spec.Style);
300
91
  if (!HeaderReplacements)
301
0
    return make_string_error(
302
0
        "Failed to create replacements for header changes: " +
303
0
        llvm::toString(HeaderReplacements.takeError()));
304
91
305
91
  llvm::Expected<Replacements> Replaces =
306
91
      combineReplacementsInChanges(FilePath, Changes);
307
91
  if (!Replaces)
308
3
    return make_string_error("Failed to combine replacements in all changes: " +
309
3
                             llvm::toString(Replaces.takeError()));
310
88
311
88
  Replacements AllReplaces = std::move(*Replaces);
312
88
  for (const auto &R : *HeaderReplacements) {
313
10
    llvm::Error Err = AllReplaces.add(R);
314
10
    if (Err)
315
0
      return make_string_error(
316
0
          "Failed to combine existing replacements with header replacements: " +
317
0
          llvm::toString(std::move(Err)));
318
10
  }
319
88
320
88
  if (Spec.Cleanup) {
321
52
    llvm::Expected<Replacements> CleanReplaces =
322
52
        format::cleanupAroundReplacements(Code, AllReplaces, Spec.Style);
323
52
    if (!CleanReplaces)
324
0
      return make_string_error("Failed to cleanup around replacements: " +
325
0
                               llvm::toString(CleanReplaces.takeError()));
326
52
    AllReplaces = std::move(*CleanReplaces);
327
52
  }
328
88
329
88
  // Apply all replacements.
330
88
  llvm::Expected<std::string> ChangedCode =
331
88
      applyAllReplacements(Code, AllReplaces);
332
88
  if (!ChangedCode)
333
0
    return make_string_error("Failed to apply all replacements: " +
334
0
                             llvm::toString(ChangedCode.takeError()));
335
88
336
88
  // Sort inserted headers. This is done even if other formatting is turned off
337
88
  // as incorrectly sorted headers are always just wrong, it's not a matter of
338
88
  // taste.
339
88
  Replacements HeaderSortingReplacements = format::sortIncludes(
340
88
      Spec.Style, *ChangedCode, AllReplaces.getAffectedRanges(), FilePath);
341
88
  ChangedCode = applyAllReplacements(*ChangedCode, HeaderSortingReplacements);
342
88
  if (!ChangedCode)
343
0
    return make_string_error(
344
0
        "Failed to apply replacements for sorting includes: " +
345
0
        llvm::toString(ChangedCode.takeError()));
346
88
347
88
  AllReplaces = AllReplaces.merge(HeaderSortingReplacements);
348
88
349
88
  std::vector<Range> FormatRanges = getRangesForFormating(
350
88
      *ChangedCode, Spec.Style.ColumnLimit, Spec.Format, AllReplaces);
351
88
  if (!FormatRanges.empty()) {
352
23
    Replacements FormatReplacements =
353
23
        format::reformat(Spec.Style, *ChangedCode, FormatRanges, FilePath);
354
23
    ChangedCode = applyAllReplacements(*ChangedCode, FormatReplacements);
355
23
    if (!ChangedCode)
356
0
      return make_string_error(
357
0
          "Failed to apply replacements for formatting changed code: " +
358
0
          llvm::toString(ChangedCode.takeError()));
359
88
  }
360
88
  return ChangedCode;
361
88
}
362
363
} // end namespace tooling
364
} // end namespace clang