Coverage Report

Created: 2021-01-19 06:58

/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
4
  StartPos = (StartPos == llvm::StringRef::npos) ? 
03
: StartPos + 1;
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
117
                      const clang::tooling::Replacements &Replaces) {
110
  // kNone suppresses formatting entirely.
111
117
  if (Format == ApplyChangesSpec::kNone)
112
93
    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
30
        R.getReplacementText().back() == '\n' && 
R.getLength() == 07
&&
123
6
        R.getOffset() > 0 && 
R.getOffset() <= Code.size()4
&&
124
4
        Code[R.getOffset() - 1] == '\n')
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
7
        violatesColumnLimit(Code, ColumnLimit, Start, End))
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
120
                             const format::FormatStyle &Style) {
147
  // Create header insertion/deletion replacements to be cleaned up
148
  // (i.e. converted to real insertion/deletion replacements).
149
120
  Replacements HeaderReplacements;
150
158
  for (const auto &Change : Changes) {
151
12
    for (llvm::StringRef Header : Change.getInsertedHeaders()) {
152
12
      std::string EscapedHeader =
153
12
          Header.startswith("<") || 
Header.startswith("\"")7
154
6
              ? Header.str()
155
6
              : ("\"" + Header + "\"").str();
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
158
    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
158
  }
173
174
  // cleanupAroundReplacements() converts header insertions/deletions into
175
  // actual replacements that add/remove headers at the right location.
176
120
  return clang::format::cleanupAroundReplacements(Code, HeaderReplacements,
177
120
                                                  Style);
178
120
}
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
120
                             llvm::ArrayRef<AtomicChange> Changes) {
185
120
  Replacements Replaces;
186
120
  for (const auto &Change : Changes)
187
158
    for (const auto &R : Change.getReplacements())
188
230
      if (auto Err = Replaces.add(Replacement(
189
3
              FilePath, R.getOffset(), R.getLength(), R.getReplacementText())))
190
3
        return std::move(Err);
191
117
  return Replaces;
192
120
}
193
194
} // end namespace
195
196
AtomicChange::AtomicChange(const SourceManager &SM,
197
1.30k
                           SourceLocation KeyPosition) {
198
1.30k
  const FullSourceLoc FullKeyPosition(KeyPosition, SM);
199
1.30k
  std::pair<FileID, unsigned> FileIDAndOffset =
200
1.30k
      FullKeyPosition.getSpellingLoc().getDecomposedLoc();
201
1.30k
  const FileEntry *FE = SM.getFileEntryForID(FileIDAndOffset.first);
202
1.30k
  assert(FE && "Cannot create AtomicChange with invalid location.");
203
1.30k
  FilePath = std::string(FE->getName());
204
1.30k
  Key = FilePath + ":" + std::to_string(FileIDAndOffset.second);
205
1.30k
}
206
207
AtomicChange::AtomicChange(const SourceManager &SM, SourceLocation KeyPosition,
208
                           llvm::Any M)
209
123
    : AtomicChange(SM, KeyPosition) {
210
123
  Metadata = std::move(M);
211
123
}
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
123
    : AtomicChange(SM, KeyPosition) {
210
123
  Metadata = std::move(M);
211
123
}
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
    : Key(std::move(Key)), FilePath(std::move(FilePath)),
219
      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
2
        });
288
5
  }
289
35
  return llvm::Error::success();
290
35
}
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
120
                   const ApplyChangesSpec &Spec) {
304
120
  llvm::Expected<Replacements> HeaderReplacements =
305
120
      createReplacementsForHeaders(FilePath, Code, Changes, Spec.Style);
306
120
  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
120
  llvm::Expected<Replacements> Replaces =
312
120
      combineReplacementsInChanges(FilePath, Changes);
313
120
  if (!Replaces)
314
3
    return make_string_error("Failed to combine replacements in all changes: " +
315
3
                             llvm::toString(Replaces.takeError()));
316
317
117
  Replacements AllReplaces = std::move(*Replaces);
318
12
  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
117
  if (Spec.Cleanup) {
327
81
    llvm::Expected<Replacements> CleanReplaces =
328
81
        format::cleanupAroundReplacements(Code, AllReplaces, Spec.Style);
329
81
    if (!CleanReplaces)
330
0
      return make_string_error("Failed to cleanup around replacements: " +
331
0
                               llvm::toString(CleanReplaces.takeError()));
332
81
    AllReplaces = std::move(*CleanReplaces);
333
81
  }
334
335
  // Apply all replacements.
336
117
  llvm::Expected<std::string> ChangedCode =
337
117
      applyAllReplacements(Code, AllReplaces);
338
117
  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
117
  Replacements HeaderSortingReplacements = format::sortIncludes(
346
117
      Spec.Style, *ChangedCode, AllReplaces.getAffectedRanges(), FilePath);
347
117
  ChangedCode = applyAllReplacements(*ChangedCode, HeaderSortingReplacements);
348
117
  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
117
  AllReplaces = AllReplaces.merge(HeaderSortingReplacements);
354
355
117
  std::vector<Range> FormatRanges = getRangesForFormating(
356
117
      *ChangedCode, Spec.Style.ColumnLimit, Spec.Format, AllReplaces);
357
117
  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
117
  }
366
117
  return ChangedCode;
367
117
}
368
369
} // end namespace tooling
370
} // end namespace clang