FrontendActions.cpp 11 KB

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