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 | // Runs preprocessor over preamble section. |
| 108 | class PreambleOnlyAction : public PreprocessorFrontendAction { |
| 109 | protected: |
| 110 | void ExecuteAction() override { |
| 111 | Preprocessor &PP = getCompilerInstance().getPreprocessor(); |
| 112 | auto &SM = PP.getSourceManager(); |
| 113 | PP.EnterMainSourceFile(); |
| 114 | auto Bounds = ComputePreambleBounds(getCompilerInstance().getLangOpts(), |
| 115 | SM.getBuffer(SM.getMainFileID()), 0); |
| 116 | Token Tok; |
| 117 | do { |
| 118 | PP.Lex(Tok); |
| 119 | assert(SM.isInMainFile(Tok.getLocation())); |
| 120 | } while (Tok.isNot(tok::eof) && |
| 121 | SM.getDecomposedLoc(Tok.getLocation()).second < Bounds.Size); |
| 122 | } |
| 123 | }; |
| 124 | |
| 125 | /// Gets the includes in the preamble section of the file by running |
| 126 | /// preprocessor over \p Contents. Returned includes do not contain resolved |
| 127 | /// paths. \p VFS and \p Cmd is used to build the compiler invocation, which |
| 128 | /// might stat/read files. |
| 129 | llvm::Expected<std::vector<Inclusion>> |
| 130 | scanPreambleIncludes(llvm::StringRef Contents, |
| 131 | llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, |
| 132 | const tooling::CompileCommand &Cmd) { |
| 133 | // Build and run Preprocessor over the preamble. |
| 134 | ParseInputs PI; |
| 135 | PI.Contents = Contents.str(); |
| 136 | PI.FS = std::move(VFS); |
| 137 | PI.CompileCommand = Cmd; |
| 138 | IgnoringDiagConsumer IgnoreDiags; |
| 139 | auto CI = buildCompilerInvocation(PI, IgnoreDiags); |
| 140 | if (!CI) |
| 141 | return llvm::createStringError(llvm::inconvertibleErrorCode(), |
| 142 | "failed to create compiler invocation"); |
| 143 | CI->getDiagnosticOpts().IgnoreWarnings = true; |
| 144 | auto ContentsBuffer = llvm::MemoryBuffer::getMemBuffer(Contents); |
| 145 | auto Clang = prepareCompilerInstance( |
| 146 | std::move(CI), nullptr, std::move(ContentsBuffer), |
| 147 | // Provide an empty FS to prevent preprocessor from performing IO. This |
| 148 | // also implies missing resolved paths for includes. |
| 149 | new llvm::vfs::InMemoryFileSystem, IgnoreDiags); |
| 150 | if (Clang->getFrontendOpts().Inputs.empty()) |
| 151 | return llvm::createStringError(llvm::inconvertibleErrorCode(), |
| 152 | "compiler instance had no inputs"); |
| 153 | // We are only interested in main file includes. |
| 154 | Clang->getPreprocessorOpts().SingleFileParseMode = true; |
| 155 | PreambleOnlyAction Action; |
| 156 | if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) |
| 157 | return llvm::createStringError(llvm::inconvertibleErrorCode(), |
| 158 | "failed BeginSourceFile"); |
| 159 | Preprocessor &PP = Clang->getPreprocessor(); |
| 160 | IncludeStructure Includes; |
| 161 | PP.addPPCallbacks( |
| 162 | collectIncludeStructureCallback(Clang->getSourceManager(), &Includes)); |
| 163 | if (llvm::Error Err = Action.Execute()) |
| 164 | return std::move(Err); |
| 165 | Action.EndSourceFile(); |
| 166 | return Includes.MainFileIncludes; |
| 167 | } |
| 168 | |
| 169 | const char *spellingForIncDirective(tok::PPKeywordKind IncludeDirective) { |
| 170 | switch (IncludeDirective) { |
| 171 | case tok::pp_include: |
| 172 | return "include"; |
| 173 | case tok::pp_import: |
| 174 | return "import"; |
| 175 | case tok::pp_include_next: |
| 176 | return "include_next"; |
| 177 | default: |
| 178 | break; |
| 179 | } |
| 180 | llvm_unreachable("not an include directive"); |
| 181 | } |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 182 | } // namespace |
| 183 | |
Kadir Cetinkaya | ecd3e67 | 2020-03-11 16:34:01 +0100 | [diff] [blame] | 184 | PreambleData::PreambleData(const ParseInputs &Inputs, |
Sam McCall | 2cd33e6 | 2020-03-04 00:33:29 +0100 | [diff] [blame] | 185 | PrecompiledPreamble Preamble, |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 186 | std::vector<Diag> Diags, IncludeStructure Includes, |
Haojian Wu | 7e3c74b | 2019-09-24 11:14:06 +0000 | [diff] [blame] | 187 | MainFileMacros Macros, |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 188 | std::unique_ptr<PreambleFileStatusCache> StatCache, |
| 189 | CanonicalIncludes CanonIncludes) |
Kadir Cetinkaya | ecd3e67 | 2020-03-11 16:34:01 +0100 | [diff] [blame] | 190 | : Version(Inputs.Version), CompileCommand(Inputs.CompileCommand), |
| 191 | Preamble(std::move(Preamble)), Diags(std::move(Diags)), |
Haojian Wu | 7e3c74b | 2019-09-24 11:14:06 +0000 | [diff] [blame] | 192 | Includes(std::move(Includes)), Macros(std::move(Macros)), |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 193 | StatCache(std::move(StatCache)), CanonIncludes(std::move(CanonIncludes)) { |
| 194 | } |
| 195 | |
| 196 | std::shared_ptr<const PreambleData> |
Kadir Cetinkaya | 276a95b | 2020-03-13 11:52:19 +0100 | [diff] [blame] | 197 | buildPreamble(PathRef FileName, CompilerInvocation CI, |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 198 | const ParseInputs &Inputs, bool StoreInMemory, |
| 199 | PreambleParsedCallback PreambleCallback) { |
| 200 | // Note that we don't need to copy the input contents, preamble can live |
| 201 | // without those. |
| 202 | auto ContentsBuffer = |
| 203 | llvm::MemoryBuffer::getMemBuffer(Inputs.Contents, FileName); |
| 204 | auto Bounds = |
| 205 | ComputePreambleBounds(*CI.getLangOpts(), ContentsBuffer.get(), 0); |
| 206 | |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 207 | trace::Span Tracer("BuildPreamble"); |
| 208 | SPAN_ATTACH(Tracer, "File", FileName); |
| 209 | StoreDiags PreambleDiagnostics; |
| 210 | llvm::IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine = |
| 211 | CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(), |
| 212 | &PreambleDiagnostics, false); |
| 213 | |
| 214 | // Skip function bodies when building the preamble to speed up building |
| 215 | // the preamble and make it smaller. |
| 216 | assert(!CI.getFrontendOpts().SkipFunctionBodies); |
| 217 | CI.getFrontendOpts().SkipFunctionBodies = true; |
| 218 | // We don't want to write comment locations into PCH. They are racy and slow |
| 219 | // to read back. We rely on dynamic index for the comments instead. |
| 220 | CI.getPreprocessorOpts().WriteCommentListToPCH = false; |
| 221 | |
| 222 | CppFilePreambleCallbacks SerializedDeclsCollector(FileName, PreambleCallback); |
| 223 | if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) { |
| 224 | log("Couldn't set working directory when building the preamble."); |
| 225 | // We proceed anyway, our lit-tests rely on results for non-existing working |
| 226 | // dirs. |
| 227 | } |
| 228 | |
| 229 | llvm::SmallString<32> AbsFileName(FileName); |
| 230 | Inputs.FS->makeAbsolute(AbsFileName); |
| 231 | auto StatCache = std::make_unique<PreambleFileStatusCache>(AbsFileName); |
| 232 | auto BuiltPreamble = PrecompiledPreamble::Build( |
| 233 | CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, |
| 234 | StatCache->getProducingFS(Inputs.FS), |
| 235 | std::make_shared<PCHContainerOperations>(), StoreInMemory, |
| 236 | SerializedDeclsCollector); |
| 237 | |
| 238 | // When building the AST for the main file, we do want the function |
| 239 | // bodies. |
| 240 | CI.getFrontendOpts().SkipFunctionBodies = false; |
| 241 | |
| 242 | if (BuiltPreamble) { |
Sam McCall | 2cd33e6 | 2020-03-04 00:33:29 +0100 | [diff] [blame] | 243 | vlog("Built preamble of size {0} for file {1} version {2}", |
| 244 | BuiltPreamble->getSize(), FileName, Inputs.Version); |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 245 | std::vector<Diag> Diags = PreambleDiagnostics.take(); |
| 246 | return std::make_shared<PreambleData>( |
Kadir Cetinkaya | ecd3e67 | 2020-03-11 16:34:01 +0100 | [diff] [blame] | 247 | Inputs, std::move(*BuiltPreamble), std::move(Diags), |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 248 | SerializedDeclsCollector.takeIncludes(), |
Haojian Wu | 7e3c74b | 2019-09-24 11:14:06 +0000 | [diff] [blame] | 249 | SerializedDeclsCollector.takeMacros(), std::move(StatCache), |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 250 | SerializedDeclsCollector.takeCanonicalIncludes()); |
| 251 | } else { |
Adam Czachorowski | 55b92dc | 2020-03-19 15:09:28 +0100 | [diff] [blame] | 252 | elog("Could not build a preamble for file {0} version {1}", FileName, |
Sam McCall | 2cd33e6 | 2020-03-04 00:33:29 +0100 | [diff] [blame] | 253 | Inputs.Version); |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 254 | return nullptr; |
| 255 | } |
| 256 | } |
| 257 | |
Kadir Cetinkaya | c31367e | 2020-03-15 21:43:00 +0100 | [diff] [blame] | 258 | bool isPreambleCompatible(const PreambleData &Preamble, |
| 259 | const ParseInputs &Inputs, PathRef FileName, |
| 260 | const CompilerInvocation &CI) { |
| 261 | auto ContentsBuffer = |
| 262 | llvm::MemoryBuffer::getMemBuffer(Inputs.Contents, FileName); |
| 263 | auto Bounds = |
| 264 | ComputePreambleBounds(*CI.getLangOpts(), ContentsBuffer.get(), 0); |
| 265 | return compileCommandsAreEqual(Inputs.CompileCommand, |
| 266 | Preamble.CompileCommand) && |
| 267 | Preamble.Preamble.CanReuse(CI, ContentsBuffer.get(), Bounds, |
| 268 | Inputs.FS.get()); |
| 269 | } |
Kadir Cetinkaya | 2214b90 | 2020-04-02 10:53:23 +0200 | [diff] [blame] | 270 | |
Kadir Cetinkaya | 717bef6 | 2020-04-23 17:44:51 +0200 | [diff] [blame] | 271 | void escapeBackslashAndQuotes(llvm::StringRef Text, llvm::raw_ostream &OS) { |
| 272 | for (char C : Text) { |
| 273 | switch (C) { |
| 274 | case '\\': |
| 275 | case '"': |
| 276 | OS << '\\'; |
| 277 | break; |
| 278 | default: |
| 279 | break; |
| 280 | } |
| 281 | OS << C; |
| 282 | } |
| 283 | } |
| 284 | |
Kadir Cetinkaya | 2214b90 | 2020-04-02 10:53:23 +0200 | [diff] [blame] | 285 | PreamblePatch PreamblePatch::create(llvm::StringRef FileName, |
| 286 | const ParseInputs &Modified, |
| 287 | const PreambleData &Baseline) { |
| 288 | // First scan the include directives in Baseline and Modified. These will be |
| 289 | // used to figure out newly added directives in Modified. Scanning can fail, |
| 290 | // the code just bails out and creates an empty patch in such cases, as: |
| 291 | // - If scanning for Baseline fails, no knowledge of existing includes hence |
| 292 | // patch will contain all the includes in Modified. Leading to rebuild of |
| 293 | // whole preamble, which is terribly slow. |
| 294 | // - If scanning for Modified fails, cannot figure out newly added ones so |
| 295 | // there's nothing to do but generate an empty patch. |
| 296 | auto BaselineIncludes = scanPreambleIncludes( |
| 297 | // Contents needs to be null-terminated. |
| 298 | Baseline.Preamble.getContents().str(), |
| 299 | Baseline.StatCache->getConsumingFS(Modified.FS), Modified.CompileCommand); |
| 300 | if (!BaselineIncludes) { |
| 301 | elog("Failed to scan includes for baseline of {0}: {1}", FileName, |
| 302 | BaselineIncludes.takeError()); |
| 303 | return {}; |
| 304 | } |
| 305 | auto ModifiedIncludes = scanPreambleIncludes( |
| 306 | Modified.Contents, Baseline.StatCache->getConsumingFS(Modified.FS), |
| 307 | Modified.CompileCommand); |
| 308 | if (!ModifiedIncludes) { |
| 309 | elog("Failed to scan includes for modified contents of {0}: {1}", FileName, |
| 310 | ModifiedIncludes.takeError()); |
| 311 | return {}; |
| 312 | } |
Kadir Cetinkaya | 717bef6 | 2020-04-23 17:44:51 +0200 | [diff] [blame] | 313 | // No patch needed if includes are equal. |
| 314 | if (*BaselineIncludes == *ModifiedIncludes) |
| 315 | return {}; |
Kadir Cetinkaya | 2214b90 | 2020-04-02 10:53:23 +0200 | [diff] [blame] | 316 | |
| 317 | PreamblePatch PP; |
| 318 | // This shouldn't coincide with any real file name. |
| 319 | llvm::SmallString<128> PatchName; |
| 320 | llvm::sys::path::append(PatchName, llvm::sys::path::parent_path(FileName), |
| 321 | "__preamble_patch__.h"); |
| 322 | PP.PatchFileName = PatchName.str().str(); |
| 323 | |
| 324 | // We are only interested in newly added includes, record the ones in Baseline |
| 325 | // for exclusion. |
| 326 | llvm::DenseSet<std::pair<tok::PPKeywordKind, llvm::StringRef>> |
| 327 | ExistingIncludes; |
| 328 | for (const auto &Inc : *BaselineIncludes) |
| 329 | ExistingIncludes.insert({Inc.Directive, Inc.Written}); |
| 330 | // Calculate extra includes that needs to be inserted. |
| 331 | llvm::raw_string_ostream Patch(PP.PatchContents); |
Kadir Cetinkaya | 717bef6 | 2020-04-23 17:44:51 +0200 | [diff] [blame] | 332 | // Set default filename for subsequent #line directives |
| 333 | Patch << "#line 0 \""; |
| 334 | // FileName part of a line directive is subject to backslash escaping, which |
| 335 | // might lead to problems on windows especially. |
| 336 | escapeBackslashAndQuotes(FileName, Patch); |
| 337 | Patch << "\"\n"; |
Kadir Cetinkaya | 2214b90 | 2020-04-02 10:53:23 +0200 | [diff] [blame] | 338 | for (const auto &Inc : *ModifiedIncludes) { |
| 339 | if (ExistingIncludes.count({Inc.Directive, Inc.Written})) |
| 340 | continue; |
Kadir Cetinkaya | 717bef6 | 2020-04-23 17:44:51 +0200 | [diff] [blame] | 341 | // Include is new in the modified preamble. Inject it into the patch and use |
| 342 | // #line to set the presumed location to where it is spelled. |
| 343 | auto LineCol = offsetToClangLineColumn(Modified.Contents, Inc.HashOffset); |
| 344 | Patch << llvm::formatv("#line {0}\n", LineCol.first); |
Kadir Cetinkaya | 2214b90 | 2020-04-02 10:53:23 +0200 | [diff] [blame] | 345 | Patch << llvm::formatv("#{0} {1}\n", spellingForIncDirective(Inc.Directive), |
| 346 | Inc.Written); |
| 347 | } |
| 348 | Patch.flush(); |
| 349 | |
| 350 | // FIXME: Handle more directives, e.g. define/undef. |
| 351 | return PP; |
| 352 | } |
| 353 | |
| 354 | void PreamblePatch::apply(CompilerInvocation &CI) const { |
| 355 | // No need to map an empty file. |
| 356 | if (PatchContents.empty()) |
| 357 | return; |
| 358 | auto &PPOpts = CI.getPreprocessorOpts(); |
| 359 | auto PatchBuffer = |
| 360 | // we copy here to ensure contents are still valid if CI outlives the |
| 361 | // PreamblePatch. |
| 362 | llvm::MemoryBuffer::getMemBufferCopy(PatchContents, PatchFileName); |
| 363 | // CI will take care of the lifetime of the buffer. |
| 364 | PPOpts.addRemappedFile(PatchFileName, PatchBuffer.release()); |
| 365 | // The patch will be parsed after loading the preamble ast and before parsing |
| 366 | // the main file. |
| 367 | PPOpts.Includes.push_back(PatchFileName); |
| 368 | } |
| 369 | |
Sam McCall | cf3a585 | 2019-09-04 07:35:00 +0000 | [diff] [blame] | 370 | } // namespace clangd |
| 371 | } // namespace clang |