Coverage Report

Created: 2020-02-25 14:32

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Frontend/Rewrite/FrontendActions.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- FrontendActions.cpp ----------------------------------------------===//
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/Rewrite/Frontend/FrontendActions.h"
10
#include "clang/AST/ASTConsumer.h"
11
#include "clang/Basic/CharInfo.h"
12
#include "clang/Basic/LangStandard.h"
13
#include "clang/Config/config.h"
14
#include "clang/Frontend/CompilerInstance.h"
15
#include "clang/Frontend/FrontendActions.h"
16
#include "clang/Frontend/FrontendDiagnostic.h"
17
#include "clang/Frontend/Utils.h"
18
#include "clang/Lex/Preprocessor.h"
19
#include "clang/Lex/PreprocessorOptions.h"
20
#include "clang/Rewrite/Frontend/ASTConsumers.h"
21
#include "clang/Rewrite/Frontend/FixItRewriter.h"
22
#include "clang/Rewrite/Frontend/Rewriters.h"
23
#include "clang/Serialization/ASTReader.h"
24
#include "clang/Serialization/ModuleFile.h"
25
#include "clang/Serialization/ModuleManager.h"
26
#include "llvm/ADT/DenseSet.h"
27
#include "llvm/Support/CrashRecoveryContext.h"
28
#include "llvm/Support/FileSystem.h"
29
#include "llvm/Support/Path.h"
30
#include "llvm/Support/raw_ostream.h"
31
#include <memory>
32
#include <utility>
33
34
using namespace clang;
35
36
//===----------------------------------------------------------------------===//
37
// AST Consumer Actions
38
//===----------------------------------------------------------------------===//
39
40
std::unique_ptr<ASTConsumer>
41
3
HTMLPrintAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
42
3
  if (std::unique_ptr<raw_ostream> OS =
43
3
          CI.createDefaultOutputFile(false, InFile))
44
3
    return CreateHTMLPrinter(std::move(OS), CI.getPreprocessor());
45
0
  return nullptr;
46
0
}
47
48
67
FixItAction::FixItAction() {}
49
67
FixItAction::~FixItAction() {}
50
51
std::unique_ptr<ASTConsumer>
52
67
FixItAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
53
67
  return std::make_unique<ASTConsumer>();
54
67
}
55
56
namespace {
57
class FixItRewriteInPlace : public FixItOptions {
58
public:
59
62
  FixItRewriteInPlace() { InPlace = true; }
60
61
0
  std::string RewriteFilename(const std::string &Filename, int &fd) override {
62
0
    llvm_unreachable("don't call RewriteFilename for inplace rewrites");
63
0
  }
64
};
65
66
class FixItActionSuffixInserter : public FixItOptions {
67
  std::string NewSuffix;
68
69
public:
70
  FixItActionSuffixInserter(std::string NewSuffix, bool FixWhatYouCan)
71
1
      : NewSuffix(std::move(NewSuffix)) {
72
1
    this->FixWhatYouCan = FixWhatYouCan;
73
1
  }
74
75
1
  std::string RewriteFilename(const std::string &Filename, int &fd) override {
76
1
    fd = -1;
77
1
    SmallString<128> Path(Filename);
78
1
    llvm::sys::path::replace_extension(Path,
79
1
      NewSuffix + llvm::sys::path::extension(Path));
80
1
    return std::string(Path.str());
81
1
  }
82
};
83
84
class FixItRewriteToTemp : public FixItOptions {
85
public:
86
2
  std::string RewriteFilename(const std::string &Filename, int &fd) override {
87
2
    SmallString<128> Path;
88
2
    llvm::sys::fs::createTemporaryFile(llvm::sys::path::filename(Filename),
89
2
                                       llvm::sys::path::extension(Filename).drop_front(), fd,
90
2
                                       Path);
91
2
    return std::string(Path.str());
92
2
  }
93
};
94
} // end anonymous namespace
95
96
63
bool FixItAction::BeginSourceFileAction(CompilerInstance &CI) {
97
63
  const FrontendOptions &FEOpts = getCompilerInstance().getFrontendOpts();
98
63
  if (!FEOpts.FixItSuffix.empty()) {
99
1
    FixItOpts.reset(new FixItActionSuffixInserter(FEOpts.FixItSuffix,
100
1
                                                  FEOpts.FixWhatYouCan));
101
62
  } else {
102
62
    FixItOpts.reset(new FixItRewriteInPlace);
103
62
    FixItOpts->FixWhatYouCan = FEOpts.FixWhatYouCan;
104
62
  }
105
63
  Rewriter.reset(new FixItRewriter(CI.getDiagnostics(), CI.getSourceManager(),
106
63
                                   CI.getLangOpts(), FixItOpts.get()));
107
63
  return true;
108
63
}
109
110
67
void FixItAction::EndSourceFileAction() {
111
67
  // Otherwise rewrite all files.
112
67
  Rewriter->WriteFixedFiles();
113
67
}
114
115
3
bool FixItRecompile::BeginInvocation(CompilerInstance &CI) {
116
3
117
3
  std::vector<std::pair<std::string, std::string> > RewrittenFiles;
118
3
  bool err = false;
119
3
  {
120
3
    const FrontendOptions &FEOpts = CI.getFrontendOpts();
121
3
    std::unique_ptr<FrontendAction> FixAction(new SyntaxOnlyAction());
122
3
    if (FixAction->BeginSourceFile(CI, FEOpts.Inputs[0])) {
123
3
      std::unique_ptr<FixItOptions> FixItOpts;
124
3
      if (FEOpts.FixToTemporaries)
125
3
        FixItOpts.reset(new FixItRewriteToTemp());
126
0
      else
127
0
        FixItOpts.reset(new FixItRewriteInPlace());
128
3
      FixItOpts->Silent = true;
129
3
      FixItOpts->FixWhatYouCan = FEOpts.FixWhatYouCan;
130
3
      FixItOpts->FixOnlyWarnings = FEOpts.FixOnlyWarnings;
131
3
      FixItRewriter Rewriter(CI.getDiagnostics(), CI.getSourceManager(),
132
3
                             CI.getLangOpts(), FixItOpts.get());
133
3
      if (llvm::Error Err = FixAction->Execute()) {
134
0
        // FIXME this drops the error on the floor.
135
0
        consumeError(std::move(Err));
136
0
        return false;
137
0
      }
138
3
139
3
      err = Rewriter.WriteFixedFiles(&RewrittenFiles);
140
3
141
3
      FixAction->EndSourceFile();
142
3
      CI.setSourceManager(nullptr);
143
3
      CI.setFileManager(nullptr);
144
3
    } else {
145
0
      err = true;
146
0
    }
147
3
  }
148
3
  if (err)
149
1
    return false;
150
2
  CI.getDiagnosticClient().clear();
151
2
  CI.getDiagnostics().Reset();
152
2
153
2
  PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
154
2
  PPOpts.RemappedFiles.insert(PPOpts.RemappedFiles.end(),
155
2
                              RewrittenFiles.begin(), RewrittenFiles.end());
156
2
  PPOpts.RemappedFilesKeepOriginalName = false;
157
2
158
2
  return true;
159
2
}
160
161
#if CLANG_ENABLE_OBJC_REWRITER
162
163
std::unique_ptr<ASTConsumer>
164
164
RewriteObjCAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
165
164
  if (std::unique_ptr<raw_ostream> OS =
166
164
          CI.createDefaultOutputFile(false, InFile, "cpp")) {
167
164
    if (CI.getLangOpts().ObjCRuntime.isNonFragile())
168
78
      return CreateModernObjCRewriter(
169
78
          std::string(InFile), std::move(OS), CI.getDiagnostics(),
170
78
          CI.getLangOpts(), CI.getDiagnosticOpts().NoRewriteMacros,
171
78
          (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo));
172
86
    return CreateObjCRewriter(std::string(InFile), std::move(OS),
173
86
                              CI.getDiagnostics(), CI.getLangOpts(),
174
86
                              CI.getDiagnosticOpts().NoRewriteMacros);
175
86
  }
176
0
  return nullptr;
177
0
}
178
179
#endif
180
181
//===----------------------------------------------------------------------===//
182
// Preprocessor Actions
183
//===----------------------------------------------------------------------===//
184
185
1
void RewriteMacrosAction::ExecuteAction() {
186
1
  CompilerInstance &CI = getCompilerInstance();
187
1
  std::unique_ptr<raw_ostream> OS =
188
1
      CI.createDefaultOutputFile(true, getCurrentFileOrBufferName());
189
1
  if (!OS) 
return0
;
190
1
191
1
  RewriteMacrosInInput(CI.getPreprocessor(), OS.get());
192
1
}
193
194
0
void RewriteTestAction::ExecuteAction() {
195
0
  CompilerInstance &CI = getCompilerInstance();
196
0
  std::unique_ptr<raw_ostream> OS =
197
0
      CI.createDefaultOutputFile(false, getCurrentFileOrBufferName());
198
0
  if (!OS) return;
199
0
200
0
  DoRewriteTest(CI.getPreprocessor(), OS.get());
201
0
}
202
203
class RewriteIncludesAction::RewriteImportsListener : public ASTReaderListener {
204
  CompilerInstance &CI;
205
  std::weak_ptr<raw_ostream> Out;
206
207
  llvm::DenseSet<const FileEntry*> Rewritten;
208
209
public:
210
  RewriteImportsListener(CompilerInstance &CI, std::shared_ptr<raw_ostream> Out)
211
5
      : CI(CI), Out(Out) {}
212
213
  void visitModuleFile(StringRef Filename,
214
9
                       serialization::ModuleKind Kind) override {
215
9
    auto File = CI.getFileManager().getFile(Filename);
216
9
    assert(File && "missing file for loaded module?");
217
9
218
9
    // Only rewrite each module file once.
219
9
    if (!Rewritten.insert(*File).second)
220
0
      return;
221
9
222
9
    serialization::ModuleFile *MF =
223
9
        CI.getASTReader()->getModuleManager().lookup(*File);
224
9
    assert(MF && "missing module file for loaded module?");
225
9
226
9
    // Not interested in PCH / preambles.
227
9
    if (!MF->isModule())
228
0
      return;
229
9
230
9
    auto OS = Out.lock();
231
9
    assert(OS && "loaded module file after finishing rewrite action?");
232
9
233
9
    (*OS) << "#pragma clang module build ";
234
9
    if (isValidIdentifier(MF->ModuleName))
235
7
      (*OS) << MF->ModuleName;
236
2
    else {
237
2
      (*OS) << '"';
238
2
      OS->write_escaped(MF->ModuleName);
239
2
      (*OS) << '"';
240
2
    }
241
9
    (*OS) << '\n';
242
9
243
9
    // Rewrite the contents of the module in a separate compiler instance.
244
9
    CompilerInstance Instance(CI.getPCHContainerOperations(),
245
9
                              &CI.getModuleCache());
246
9
    Instance.setInvocation(
247
9
        std::make_shared<CompilerInvocation>(CI.getInvocation()));
248
9
    Instance.createDiagnostics(
249
9
        new ForwardingDiagnosticConsumer(CI.getDiagnosticClient()),
250
9
        /*ShouldOwnClient=*/true);
251
9
    Instance.getFrontendOpts().DisableFree = false;
252
9
    Instance.getFrontendOpts().Inputs.clear();
253
9
    Instance.getFrontendOpts().Inputs.emplace_back(
254
9
        Filename, InputKind(Language::Unknown, InputKind::Precompiled));
255
9
    Instance.getFrontendOpts().ModuleFiles.clear();
256
9
    Instance.getFrontendOpts().ModuleMapFiles.clear();
257
9
    // Don't recursively rewrite imports. We handle them all at the top level.
258
9
    Instance.getPreprocessorOutputOpts().RewriteImports = false;
259
9
260
9
    llvm::CrashRecoveryContext().RunSafelyOnThread([&]() {
261
9
      RewriteIncludesAction Action;
262
9
      Action.OutputStream = OS;
263
9
      Instance.ExecuteAction(Action);
264
9
    });
265
9
266
9
    (*OS) << "#pragma clang module endbuild /*" << MF->ModuleName << "*/\n";
267
9
  }
268
};
269
270
54
bool RewriteIncludesAction::BeginSourceFileAction(CompilerInstance &CI) {
271
54
  if (!OutputStream) {
272
45
    OutputStream =
273
45
        CI.createDefaultOutputFile(true, getCurrentFileOrBufferName());
274
45
    if (!OutputStream)
275
0
      return false;
276
54
  }
277
54
278
54
  auto &OS = *OutputStream;
279
54
280
54
  // If we're preprocessing a module map, start by dumping the contents of the
281
54
  // module itself before switching to the input buffer.
282
54
  auto &Input = getCurrentInput();
283
54
  if (Input.getKind().getFormat() == InputKind::ModuleMap) {
284
14
    if (Input.isFile()) {
285
14
      OS << "# 1 \"";
286
14
      OS.write_escaped(Input.getFile());
287
14
      OS << "\"\n";
288
14
    }
289
14
    getCurrentModule()->print(OS);
290
14
    OS << "#pragma clang module contents\n";
291
14
  }
292
54
293
54
  // If we're rewriting imports, set up a listener to track when we import
294
54
  // module files.
295
54
  if (CI.getPreprocessorOutputOpts().RewriteImports) {
296
5
    CI.createASTReader();
297
5
    CI.getASTReader()->addListener(
298
5
        std::make_unique<RewriteImportsListener>(CI, OutputStream));
299
5
  }
300
54
301
54
  return true;
302
54
}
303
304
54
void RewriteIncludesAction::ExecuteAction() {
305
54
  CompilerInstance &CI = getCompilerInstance();
306
54
307
54
  // If we're rewriting imports, emit the module build output first rather
308
54
  // than switching back and forth (potentially in the middle of a line).
309
54
  if (CI.getPreprocessorOutputOpts().RewriteImports) {
310
5
    std::string Buffer;
311
5
    llvm::raw_string_ostream OS(Buffer);
312
5
313
5
    RewriteIncludesInInput(CI.getPreprocessor(), &OS,
314
5
                           CI.getPreprocessorOutputOpts());
315
5
316
5
    (*OutputStream) << OS.str();
317
49
  } else {
318
49
    RewriteIncludesInInput(CI.getPreprocessor(), OutputStream.get(),
319
49
                           CI.getPreprocessorOutputOpts());
320
49
  }
321
54
322
54
  OutputStream.reset();
323
54
}