Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 1 | //===--- Preamble.cpp - Reusing expensive parts of the AST ----------------===// |
| 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 "Preamble.h" |
Kadir Cetinkaya | ecd3e67 | 2020-03-11 16:34:01 +0100 | [diff] [blame] | 10 | #include "Compiler.h" |
Kadir Cetinkaya | 2214b90 | 2020-04-02 10:53:23 +0200 | [diff] [blame] | 11 | #include "Headers.h" |
Kadir Cetinkaya | 717bef6 | 2020-04-23 17:44:51 +0200 | [diff] [blame] | 12 | #include "SourceCode.h" |
Sam McCall | ad97ccf | 2020-04-28 17:49:17 +0200 | [diff] [blame] | 13 | #include "support/Logger.h" |
| 14 | #include "support/Trace.h" |
Kadir Cetinkaya | 2214b90 | 2020-04-02 10:53:23 +0200 | [diff] [blame] | 15 | #include "clang/Basic/Diagnostic.h" |
| 16 | #include "clang/Basic/LangOptions.h" |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 17 | #include "clang/Basic/SourceLocation.h" |
Kadir Cetinkaya | 2214b90 | 2020-04-02 10:53:23 +0200 | [diff] [blame] | 18 | #include "clang/Basic/TokenKinds.h" |
| 19 | #include "clang/Frontend/CompilerInvocation.h" |
| 20 | #include "clang/Frontend/FrontendActions.h" |
| 21 | #include "clang/Lex/Lexer.h" |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 22 | #include "clang/Lex/PPCallbacks.h" |
Kadir Cetinkaya | 2214b90 | 2020-04-02 10:53:23 +0200 | [diff] [blame] | 23 | #include "clang/Lex/Preprocessor.h" |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 24 | #include "clang/Lex/PreprocessorOptions.h" |
Kadir Cetinkaya | 2214b90 | 2020-04-02 10:53:23 +0200 | [diff] [blame] | 25 | #include "clang/Tooling/CompilationDatabase.h" |
| 26 | #include "llvm/ADT/ArrayRef.h" |
| 27 | #include "llvm/ADT/IntrusiveRefCntPtr.h" |
| 28 | #include "llvm/ADT/STLExtras.h" |
| 29 | #include "llvm/ADT/SmallString.h" |
Kadir Cetinkaya | 717bef6 | 2020-04-23 17:44:51 +0200 | [diff] [blame] | 30 | #include "llvm/ADT/StringExtras.h" |
Kadir Cetinkaya | 2214b90 | 2020-04-02 10:53:23 +0200 | [diff] [blame] | 31 | #include "llvm/ADT/StringRef.h" |
| 32 | #include "llvm/ADT/StringSet.h" |
| 33 | #include "llvm/Support/Error.h" |
| 34 | #include "llvm/Support/ErrorHandling.h" |
| 35 | #include "llvm/Support/FormatVariadic.h" |
| 36 | #include "llvm/Support/MemoryBuffer.h" |
| 37 | #include "llvm/Support/Path.h" |
| 38 | #include "llvm/Support/VirtualFileSystem.h" |
| 39 | #include "llvm/Support/raw_ostream.h" |
| 40 | #include <iterator> |
| 41 | #include <memory> |
| 42 | #include <string> |
| 43 | #include <system_error> |
| 44 | #include <utility> |
| 45 | #include <vector> |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 46 | |
| 47 | namespace clang { |
| 48 | namespace clangd { |
| 49 | namespace { |
| 50 | |
| 51 | bool compileCommandsAreEqual(const tooling::CompileCommand &LHS, |
| 52 | const tooling::CompileCommand &RHS) { |
| 53 | // We don't check for Output, it should not matter to clangd. |
| 54 | return LHS.Directory == RHS.Directory && LHS.Filename == RHS.Filename && |
| 55 | llvm::makeArrayRef(LHS.CommandLine).equals(RHS.CommandLine); |
| 56 | } |
| 57 | |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 58 | class CppFilePreambleCallbacks : public PreambleCallbacks { |
| 59 | public: |
| 60 | CppFilePreambleCallbacks(PathRef File, PreambleParsedCallback ParsedCallback) |
Haojian Wu | 7e3c74b | 2019-09-24 11:14:06 +0000 | [diff] [blame] | 61 | : File(File), ParsedCallback(ParsedCallback) {} |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 62 | |
| 63 | IncludeStructure takeIncludes() { return std::move(Includes); } |
| 64 | |
Haojian Wu | 7e3c74b | 2019-09-24 11:14:06 +0000 | [diff] [blame] | 65 | MainFileMacros takeMacros() { return std::move(Macros); } |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 66 | |
| 67 | CanonicalIncludes takeCanonicalIncludes() { return std::move(CanonIncludes); } |
| 68 | |
| 69 | void AfterExecute(CompilerInstance &CI) override { |
| 70 | if (!ParsedCallback) |
| 71 | return; |
| 72 | trace::Span Tracer("Running PreambleCallback"); |
| 73 | ParsedCallback(CI.getASTContext(), CI.getPreprocessorPtr(), CanonIncludes); |
| 74 | } |
| 75 | |
| 76 | void BeforeExecute(CompilerInstance &CI) override { |
Ilya Biryukov | 8b76709 | 2019-09-09 15:32:51 +0000 | [diff] [blame] | 77 | CanonIncludes.addSystemHeadersMapping(CI.getLangOpts()); |
Haojian Wu | 7e3c74b | 2019-09-24 11:14:06 +0000 | [diff] [blame] | 78 | LangOpts = &CI.getLangOpts(); |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 79 | SourceMgr = &CI.getSourceManager(); |
| 80 | } |
| 81 | |
| 82 | std::unique_ptr<PPCallbacks> createPPCallbacks() override { |
Haojian Wu | 7e3c74b | 2019-09-24 11:14:06 +0000 | [diff] [blame] | 83 | assert(SourceMgr && LangOpts && |
| 84 | "SourceMgr and LangOpts must be set at this point"); |
| 85 | |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 86 | return std::make_unique<PPChainedCallbacks>( |
| 87 | collectIncludeStructureCallback(*SourceMgr, &Includes), |
Kadir Cetinkaya | 3755039 | 2020-03-01 16:05:12 +0100 | [diff] [blame] | 88 | std::make_unique<CollectMainFileMacros>(*SourceMgr, Macros)); |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 89 | } |
| 90 | |
| 91 | CommentHandler *getCommentHandler() override { |
| 92 | IWYUHandler = collectIWYUHeaderMaps(&CanonIncludes); |
| 93 | return IWYUHandler.get(); |
| 94 | } |
| 95 | |
| 96 | private: |
| 97 | PathRef File; |
| 98 | PreambleParsedCallback ParsedCallback; |
| 99 | IncludeStructure Includes; |
| 100 | CanonicalIncludes CanonIncludes; |
Haojian Wu | 7e3c74b | 2019-09-24 11:14:06 +0000 | [diff] [blame] | 101 | MainFileMacros Macros; |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 102 | std::unique_ptr<CommentHandler> IWYUHandler = nullptr; |
Haojian Wu | 7e3c74b | 2019-09-24 11:14:06 +0000 | [diff] [blame] | 103 | const clang::LangOptions *LangOpts = nullptr; |
| 104 | const SourceManager *SourceMgr = nullptr; |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 105 | }; |
| 106 | |
Kadir Cetinkaya | 2214b90 | 2020-04-02 10:53:23 +0200 | [diff] [blame] | 107 | /// Gets the includes in the preamble section of the file by running |
| 108 | /// preprocessor over \p Contents. Returned includes do not contain resolved |
| 109 | /// paths. \p VFS and \p Cmd is used to build the compiler invocation, which |
| 110 | /// might stat/read files. |
| 111 | llvm::Expected<std::vector<Inclusion>> |
| 112 | scanPreambleIncludes(llvm::StringRef Contents, |
| 113 | llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, |
| 114 | const tooling::CompileCommand &Cmd) { |
| 115 | // Build and run Preprocessor over the preamble. |
| 116 | ParseInputs PI; |
| 117 | PI.Contents = Contents.str(); |
| 118 | PI.FS = std::move(VFS); |
| 119 | PI.CompileCommand = Cmd; |
| 120 | IgnoringDiagConsumer IgnoreDiags; |
| 121 | auto CI = buildCompilerInvocation(PI, IgnoreDiags); |
| 122 | if (!CI) |
| 123 | return llvm::createStringError(llvm::inconvertibleErrorCode(), |
| 124 | "failed to create compiler invocation"); |
| 125 | CI->getDiagnosticOpts().IgnoreWarnings = true; |
| 126 | auto ContentsBuffer = llvm::MemoryBuffer::getMemBuffer(Contents); |
Kadir Cetinkaya | 34e39eb | 2020-05-05 17:55:11 +0200 | [diff] [blame] | 127 | // This means we're scanning (though not preprocessing) the preamble section |
| 128 | // twice. However, it's important to precisely follow the preamble bounds used |
| 129 | // elsewhere. |
| 130 | auto Bounds = |
| 131 | ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0); |
| 132 | auto PreambleContents = |
| 133 | llvm::MemoryBuffer::getMemBufferCopy(Contents.substr(0, Bounds.Size)); |
Kadir Cetinkaya | 2214b90 | 2020-04-02 10:53:23 +0200 | [diff] [blame] | 134 | auto Clang = prepareCompilerInstance( |
Kadir Cetinkaya | 34e39eb | 2020-05-05 17:55:11 +0200 | [diff] [blame] | 135 | std::move(CI), nullptr, std::move(PreambleContents), |
Kadir Cetinkaya | 2214b90 | 2020-04-02 10:53:23 +0200 | [diff] [blame] | 136 | // Provide an empty FS to prevent preprocessor from performing IO. This |
| 137 | // also implies missing resolved paths for includes. |
| 138 | new llvm::vfs::InMemoryFileSystem, IgnoreDiags); |
| 139 | if (Clang->getFrontendOpts().Inputs.empty()) |
| 140 | return llvm::createStringError(llvm::inconvertibleErrorCode(), |
| 141 | "compiler instance had no inputs"); |
| 142 | // We are only interested in main file includes. |
| 143 | Clang->getPreprocessorOpts().SingleFileParseMode = true; |
Kadir Cetinkaya | 34e39eb | 2020-05-05 17:55:11 +0200 | [diff] [blame] | 144 | PreprocessOnlyAction Action; |
Kadir Cetinkaya | 2214b90 | 2020-04-02 10:53:23 +0200 | [diff] [blame] | 145 | if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) |
| 146 | return llvm::createStringError(llvm::inconvertibleErrorCode(), |
| 147 | "failed BeginSourceFile"); |
| 148 | Preprocessor &PP = Clang->getPreprocessor(); |
| 149 | IncludeStructure Includes; |
| 150 | PP.addPPCallbacks( |
| 151 | collectIncludeStructureCallback(Clang->getSourceManager(), &Includes)); |
| 152 | if (llvm::Error Err = Action.Execute()) |
| 153 | return std::move(Err); |
| 154 | Action.EndSourceFile(); |
| 155 | return Includes.MainFileIncludes; |
| 156 | } |
| 157 | |
| 158 | const char *spellingForIncDirective(tok::PPKeywordKind IncludeDirective) { |
| 159 | switch (IncludeDirective) { |
| 160 | case tok::pp_include: |
| 161 | return "include"; |
| 162 | case tok::pp_import: |
| 163 | return "import"; |
| 164 | case tok::pp_include_next: |
| 165 | return "include_next"; |
| 166 | default: |
| 167 | break; |
| 168 | } |
| 169 | llvm_unreachable("not an include directive"); |
| 170 | } |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 171 | } // namespace |
| 172 | |
Kadir Cetinkaya | ecd3e67 | 2020-03-11 16:34:01 +0100 | [diff] [blame] | 173 | PreambleData::PreambleData(const ParseInputs &Inputs, |
Sam McCall | 2cd33e6 | 2020-03-04 00:33:29 +0100 | [diff] [blame] | 174 | PrecompiledPreamble Preamble, |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 175 | std::vector<Diag> Diags, IncludeStructure Includes, |
Haojian Wu | 7e3c74b | 2019-09-24 11:14:06 +0000 | [diff] [blame] | 176 | MainFileMacros Macros, |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 177 | std::unique_ptr<PreambleFileStatusCache> StatCache, |
| 178 | CanonicalIncludes CanonIncludes) |
Kadir Cetinkaya | ecd3e67 | 2020-03-11 16:34:01 +0100 | [diff] [blame] | 179 | : Version(Inputs.Version), CompileCommand(Inputs.CompileCommand), |
| 180 | Preamble(std::move(Preamble)), Diags(std::move(Diags)), |
Haojian Wu | 7e3c74b | 2019-09-24 11:14:06 +0000 | [diff] [blame] | 181 | Includes(std::move(Includes)), Macros(std::move(Macros)), |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 182 | StatCache(std::move(StatCache)), CanonIncludes(std::move(CanonIncludes)) { |
| 183 | } |
| 184 | |
| 185 | std::shared_ptr<const PreambleData> |
Kadir Cetinkaya | 276a95b | 2020-03-13 11:52:19 +0100 | [diff] [blame] | 186 | buildPreamble(PathRef FileName, CompilerInvocation CI, |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 187 | const ParseInputs &Inputs, bool StoreInMemory, |
| 188 | PreambleParsedCallback PreambleCallback) { |
| 189 | // Note that we don't need to copy the input contents, preamble can live |
| 190 | // without those. |
| 191 | auto ContentsBuffer = |
| 192 | llvm::MemoryBuffer::getMemBuffer(Inputs.Contents, FileName); |
| 193 | auto Bounds = |
| 194 | ComputePreambleBounds(*CI.getLangOpts(), ContentsBuffer.get(), 0); |
| 195 | |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 196 | trace::Span Tracer("BuildPreamble"); |
| 197 | SPAN_ATTACH(Tracer, "File", FileName); |
| 198 | StoreDiags PreambleDiagnostics; |
| 199 | llvm::IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine = |
| 200 | CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(), |
| 201 | &PreambleDiagnostics, false); |
| 202 | |
| 203 | // Skip function bodies when building the preamble to speed up building |
| 204 | // the preamble and make it smaller. |
| 205 | assert(!CI.getFrontendOpts().SkipFunctionBodies); |
| 206 | CI.getFrontendOpts().SkipFunctionBodies = true; |
| 207 | // We don't want to write comment locations into PCH. They are racy and slow |
| 208 | // to read back. We rely on dynamic index for the comments instead. |
| 209 | CI.getPreprocessorOpts().WriteCommentListToPCH = false; |
| 210 | |
| 211 | CppFilePreambleCallbacks SerializedDeclsCollector(FileName, PreambleCallback); |
| 212 | if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) { |
| 213 | log("Couldn't set working directory when building the preamble."); |
| 214 | // We proceed anyway, our lit-tests rely on results for non-existing working |
| 215 | // dirs. |
| 216 | } |
| 217 | |
| 218 | llvm::SmallString<32> AbsFileName(FileName); |
| 219 | Inputs.FS->makeAbsolute(AbsFileName); |
| 220 | auto StatCache = std::make_unique<PreambleFileStatusCache>(AbsFileName); |
| 221 | auto BuiltPreamble = PrecompiledPreamble::Build( |
| 222 | CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, |
| 223 | StatCache->getProducingFS(Inputs.FS), |
| 224 | std::make_shared<PCHContainerOperations>(), StoreInMemory, |
| 225 | SerializedDeclsCollector); |
| 226 | |
| 227 | // When building the AST for the main file, we do want the function |
| 228 | // bodies. |
| 229 | CI.getFrontendOpts().SkipFunctionBodies = false; |
| 230 | |
| 231 | if (BuiltPreamble) { |
Sam McCall | 2cd33e6 | 2020-03-04 00:33:29 +0100 | [diff] [blame] | 232 | vlog("Built preamble of size {0} for file {1} version {2}", |
| 233 | BuiltPreamble->getSize(), FileName, Inputs.Version); |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 234 | std::vector<Diag> Diags = PreambleDiagnostics.take(); |
| 235 | return std::make_shared<PreambleData>( |
Kadir Cetinkaya | ecd3e67 | 2020-03-11 16:34:01 +0100 | [diff] [blame] | 236 | Inputs, std::move(*BuiltPreamble), std::move(Diags), |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 237 | SerializedDeclsCollector.takeIncludes(), |
Haojian Wu | 7e3c74b | 2019-09-24 11:14:06 +0000 | [diff] [blame] | 238 | SerializedDeclsCollector.takeMacros(), std::move(StatCache), |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 239 | SerializedDeclsCollector.takeCanonicalIncludes()); |
| 240 | } else { |
Adam Czachorowski | 55b92dc | 2020-03-19 15:09:28 +0100 | [diff] [blame] | 241 | elog("Could not build a preamble for file {0} version {1}", FileName, |
Sam McCall | 2cd33e6 | 2020-03-04 00:33:29 +0100 | [diff] [blame] | 242 | Inputs.Version); |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 243 | return nullptr; |
| 244 | } |
| 245 | } |
| 246 | |
Kadir Cetinkaya | c31367e | 2020-03-15 21:43:00 +0100 | [diff] [blame] | 247 | bool isPreambleCompatible(const PreambleData &Preamble, |
| 248 | const ParseInputs &Inputs, PathRef FileName, |
| 249 | const CompilerInvocation &CI) { |
| 250 | auto ContentsBuffer = |
| 251 | llvm::MemoryBuffer::getMemBuffer(Inputs.Contents, FileName); |
| 252 | auto Bounds = |
| 253 | ComputePreambleBounds(*CI.getLangOpts(), ContentsBuffer.get(), 0); |
| 254 | return compileCommandsAreEqual(Inputs.CompileCommand, |
| 255 | Preamble.CompileCommand) && |
| 256 | Preamble.Preamble.CanReuse(CI, ContentsBuffer.get(), Bounds, |
| 257 | Inputs.FS.get()); |
| 258 | } |
Kadir Cetinkaya | 2214b90 | 2020-04-02 10:53:23 +0200 | [diff] [blame] | 259 | |
Kadir Cetinkaya | 717bef6 | 2020-04-23 17:44:51 +0200 | [diff] [blame] | 260 | void escapeBackslashAndQuotes(llvm::StringRef Text, llvm::raw_ostream &OS) { |
| 261 | for (char C : Text) { |
| 262 | switch (C) { |
| 263 | case '\\': |
| 264 | case '"': |
| 265 | OS << '\\'; |
| 266 | break; |
| 267 | default: |
| 268 | break; |
| 269 | } |
| 270 | OS << C; |
| 271 | } |
| 272 | } |
| 273 | |
Kadir Cetinkaya | 2214b90 | 2020-04-02 10:53:23 +0200 | [diff] [blame] | 274 | PreamblePatch PreamblePatch::create(llvm::StringRef FileName, |
| 275 | const ParseInputs &Modified, |
| 276 | const PreambleData &Baseline) { |
| 277 | // First scan the include directives in Baseline and Modified. These will be |
| 278 | // used to figure out newly added directives in Modified. Scanning can fail, |
| 279 | // the code just bails out and creates an empty patch in such cases, as: |
| 280 | // - If scanning for Baseline fails, no knowledge of existing includes hence |
| 281 | // patch will contain all the includes in Modified. Leading to rebuild of |
| 282 | // whole preamble, which is terribly slow. |
| 283 | // - If scanning for Modified fails, cannot figure out newly added ones so |
| 284 | // there's nothing to do but generate an empty patch. |
| 285 | auto BaselineIncludes = scanPreambleIncludes( |
| 286 | // Contents needs to be null-terminated. |
| 287 | Baseline.Preamble.getContents().str(), |
| 288 | Baseline.StatCache->getConsumingFS(Modified.FS), Modified.CompileCommand); |
| 289 | if (!BaselineIncludes) { |
| 290 | elog("Failed to scan includes for baseline of {0}: {1}", FileName, |
| 291 | BaselineIncludes.takeError()); |
| 292 | return {}; |
| 293 | } |
| 294 | auto ModifiedIncludes = scanPreambleIncludes( |
| 295 | Modified.Contents, Baseline.StatCache->getConsumingFS(Modified.FS), |
| 296 | Modified.CompileCommand); |
| 297 | if (!ModifiedIncludes) { |
| 298 | elog("Failed to scan includes for modified contents of {0}: {1}", FileName, |
| 299 | ModifiedIncludes.takeError()); |
| 300 | return {}; |
| 301 | } |
Kadir Cetinkaya | 717bef6 | 2020-04-23 17:44:51 +0200 | [diff] [blame] | 302 | // No patch needed if includes are equal. |
| 303 | if (*BaselineIncludes == *ModifiedIncludes) |
| 304 | return {}; |
Kadir Cetinkaya | 2214b90 | 2020-04-02 10:53:23 +0200 | [diff] [blame] | 305 | |
| 306 | PreamblePatch PP; |
| 307 | // This shouldn't coincide with any real file name. |
| 308 | llvm::SmallString<128> PatchName; |
| 309 | llvm::sys::path::append(PatchName, llvm::sys::path::parent_path(FileName), |
| 310 | "__preamble_patch__.h"); |
| 311 | PP.PatchFileName = PatchName.str().str(); |
| 312 | |
| 313 | // We are only interested in newly added includes, record the ones in Baseline |
| 314 | // for exclusion. |
| 315 | llvm::DenseSet<std::pair<tok::PPKeywordKind, llvm::StringRef>> |
| 316 | ExistingIncludes; |
| 317 | for (const auto &Inc : *BaselineIncludes) |
| 318 | ExistingIncludes.insert({Inc.Directive, Inc.Written}); |
| 319 | // Calculate extra includes that needs to be inserted. |
| 320 | llvm::raw_string_ostream Patch(PP.PatchContents); |
Kadir Cetinkaya | 717bef6 | 2020-04-23 17:44:51 +0200 | [diff] [blame] | 321 | // Set default filename for subsequent #line directives |
| 322 | Patch << "#line 0 \""; |
| 323 | // FileName part of a line directive is subject to backslash escaping, which |
| 324 | // might lead to problems on windows especially. |
| 325 | escapeBackslashAndQuotes(FileName, Patch); |
| 326 | Patch << "\"\n"; |
Kadir Cetinkaya | 2214b90 | 2020-04-02 10:53:23 +0200 | [diff] [blame] | 327 | for (const auto &Inc : *ModifiedIncludes) { |
| 328 | if (ExistingIncludes.count({Inc.Directive, Inc.Written})) |
| 329 | continue; |
Kadir Cetinkaya | 717bef6 | 2020-04-23 17:44:51 +0200 | [diff] [blame] | 330 | // Include is new in the modified preamble. Inject it into the patch and use |
| 331 | // #line to set the presumed location to where it is spelled. |
| 332 | auto LineCol = offsetToClangLineColumn(Modified.Contents, Inc.HashOffset); |
| 333 | Patch << llvm::formatv("#line {0}\n", LineCol.first); |
Kadir Cetinkaya | 2214b90 | 2020-04-02 10:53:23 +0200 | [diff] [blame] | 334 | Patch << llvm::formatv("#{0} {1}\n", spellingForIncDirective(Inc.Directive), |
| 335 | Inc.Written); |
| 336 | } |
| 337 | Patch.flush(); |
| 338 | |
| 339 | // FIXME: Handle more directives, e.g. define/undef. |
| 340 | return PP; |
| 341 | } |
| 342 | |
| 343 | void PreamblePatch::apply(CompilerInvocation &CI) const { |
| 344 | // No need to map an empty file. |
| 345 | if (PatchContents.empty()) |
| 346 | return; |
| 347 | auto &PPOpts = CI.getPreprocessorOpts(); |
| 348 | auto PatchBuffer = |
| 349 | // we copy here to ensure contents are still valid if CI outlives the |
| 350 | // PreamblePatch. |
| 351 | llvm::MemoryBuffer::getMemBufferCopy(PatchContents, PatchFileName); |
| 352 | // CI will take care of the lifetime of the buffer. |
| 353 | PPOpts.addRemappedFile(PatchFileName, PatchBuffer.release()); |
| 354 | // The patch will be parsed after loading the preamble ast and before parsing |
| 355 | // the main file. |
| 356 | PPOpts.Includes.push_back(PatchFileName); |
| 357 | } |
| 358 | |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 359 | } // namespace clangd |
| 360 | } // namespace clang |