FrontendActions.cpp 11 KB

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