|
8 | 8 |
|
9 | 9 | #include "Preamble.h"
|
10 | 10 | #include "Compiler.h"
|
| 11 | +#include "Headers.h" |
11 | 12 | #include "Logger.h"
|
12 | 13 | #include "Trace.h"
|
| 14 | +#include "clang/Basic/Diagnostic.h" |
| 15 | +#include "clang/Basic/LangOptions.h" |
13 | 16 | #include "clang/Basic/SourceLocation.h"
|
| 17 | +#include "clang/Basic/TokenKinds.h" |
| 18 | +#include "clang/Frontend/CompilerInvocation.h" |
| 19 | +#include "clang/Frontend/FrontendActions.h" |
| 20 | +#include "clang/Lex/Lexer.h" |
14 | 21 | #include "clang/Lex/PPCallbacks.h"
|
| 22 | +#include "clang/Lex/Preprocessor.h" |
15 | 23 | #include "clang/Lex/PreprocessorOptions.h"
|
| 24 | +#include "clang/Tooling/CompilationDatabase.h" |
| 25 | +#include "llvm/ADT/ArrayRef.h" |
| 26 | +#include "llvm/ADT/IntrusiveRefCntPtr.h" |
| 27 | +#include "llvm/ADT/STLExtras.h" |
| 28 | +#include "llvm/ADT/SmallString.h" |
| 29 | +#include "llvm/ADT/StringRef.h" |
| 30 | +#include "llvm/ADT/StringSet.h" |
| 31 | +#include "llvm/Support/Error.h" |
| 32 | +#include "llvm/Support/ErrorHandling.h" |
| 33 | +#include "llvm/Support/FormatVariadic.h" |
| 34 | +#include "llvm/Support/MemoryBuffer.h" |
| 35 | +#include "llvm/Support/Path.h" |
| 36 | +#include "llvm/Support/VirtualFileSystem.h" |
| 37 | +#include "llvm/Support/raw_ostream.h" |
| 38 | +#include <iterator> |
| 39 | +#include <memory> |
| 40 | +#include <string> |
| 41 | +#include <system_error> |
| 42 | +#include <utility> |
| 43 | +#include <vector> |
16 | 44 |
|
17 | 45 | namespace clang {
|
18 | 46 | namespace clangd {
|
@@ -74,6 +102,81 @@ class CppFilePreambleCallbacks : public PreambleCallbacks {
|
74 | 102 | const SourceManager *SourceMgr = nullptr;
|
75 | 103 | };
|
76 | 104 |
|
| 105 | +// Runs preprocessor over preamble section. |
| 106 | +class PreambleOnlyAction : public PreprocessorFrontendAction { |
| 107 | +protected: |
| 108 | + void ExecuteAction() override { |
| 109 | + Preprocessor &PP = getCompilerInstance().getPreprocessor(); |
| 110 | + auto &SM = PP.getSourceManager(); |
| 111 | + PP.EnterMainSourceFile(); |
| 112 | + auto Bounds = ComputePreambleBounds(getCompilerInstance().getLangOpts(), |
| 113 | + SM.getBuffer(SM.getMainFileID()), 0); |
| 114 | + Token Tok; |
| 115 | + do { |
| 116 | + PP.Lex(Tok); |
| 117 | + assert(SM.isInMainFile(Tok.getLocation())); |
| 118 | + } while (Tok.isNot(tok::eof) && |
| 119 | + SM.getDecomposedLoc(Tok.getLocation()).second < Bounds.Size); |
| 120 | + } |
| 121 | +}; |
| 122 | + |
| 123 | +/// Gets the includes in the preamble section of the file by running |
| 124 | +/// preprocessor over \p Contents. Returned includes do not contain resolved |
| 125 | +/// paths. \p VFS and \p Cmd is used to build the compiler invocation, which |
| 126 | +/// might stat/read files. |
| 127 | +llvm::Expected<std::vector<Inclusion>> |
| 128 | +scanPreambleIncludes(llvm::StringRef Contents, |
| 129 | + llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, |
| 130 | + const tooling::CompileCommand &Cmd) { |
| 131 | + // Build and run Preprocessor over the preamble. |
| 132 | + ParseInputs PI; |
| 133 | + PI.Contents = Contents.str(); |
| 134 | + PI.FS = std::move(VFS); |
| 135 | + PI.CompileCommand = Cmd; |
| 136 | + IgnoringDiagConsumer IgnoreDiags; |
| 137 | + auto CI = buildCompilerInvocation(PI, IgnoreDiags); |
| 138 | + if (!CI) |
| 139 | + return llvm::createStringError(llvm::inconvertibleErrorCode(), |
| 140 | + "failed to create compiler invocation"); |
| 141 | + CI->getDiagnosticOpts().IgnoreWarnings = true; |
| 142 | + auto ContentsBuffer = llvm::MemoryBuffer::getMemBuffer(Contents); |
| 143 | + auto Clang = prepareCompilerInstance( |
| 144 | + std::move(CI), nullptr, std::move(ContentsBuffer), |
| 145 | + // Provide an empty FS to prevent preprocessor from performing IO. This |
| 146 | + // also implies missing resolved paths for includes. |
| 147 | + new llvm::vfs::InMemoryFileSystem, IgnoreDiags); |
| 148 | + if (Clang->getFrontendOpts().Inputs.empty()) |
| 149 | + return llvm::createStringError(llvm::inconvertibleErrorCode(), |
| 150 | + "compiler instance had no inputs"); |
| 151 | + // We are only interested in main file includes. |
| 152 | + Clang->getPreprocessorOpts().SingleFileParseMode = true; |
| 153 | + PreambleOnlyAction Action; |
| 154 | + if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) |
| 155 | + return llvm::createStringError(llvm::inconvertibleErrorCode(), |
| 156 | + "failed BeginSourceFile"); |
| 157 | + Preprocessor &PP = Clang->getPreprocessor(); |
| 158 | + IncludeStructure Includes; |
| 159 | + PP.addPPCallbacks( |
| 160 | + collectIncludeStructureCallback(Clang->getSourceManager(), &Includes)); |
| 161 | + if (llvm::Error Err = Action.Execute()) |
| 162 | + return std::move(Err); |
| 163 | + Action.EndSourceFile(); |
| 164 | + return Includes.MainFileIncludes; |
| 165 | +} |
| 166 | + |
| 167 | +const char *spellingForIncDirective(tok::PPKeywordKind IncludeDirective) { |
| 168 | + switch (IncludeDirective) { |
| 169 | + case tok::pp_include: |
| 170 | + return "include"; |
| 171 | + case tok::pp_import: |
| 172 | + return "import"; |
| 173 | + case tok::pp_include_next: |
| 174 | + return "include_next"; |
| 175 | + default: |
| 176 | + break; |
| 177 | + } |
| 178 | + llvm_unreachable("not an include directive"); |
| 179 | +} |
77 | 180 | } // namespace
|
78 | 181 |
|
79 | 182 | PreambleData::PreambleData(const ParseInputs &Inputs,
|
@@ -166,5 +269,78 @@ bool isPreambleCompatible(const PreambleData &Preamble,
|
166 | 269 | Preamble.Preamble.CanReuse(CI, ContentsBuffer.get(), Bounds,
|
167 | 270 | Inputs.FS.get());
|
168 | 271 | }
|
| 272 | + |
| 273 | +PreamblePatch PreamblePatch::create(llvm::StringRef FileName, |
| 274 | + const ParseInputs &Modified, |
| 275 | + const PreambleData &Baseline) { |
| 276 | + // First scan the include directives in Baseline and Modified. These will be |
| 277 | + // used to figure out newly added directives in Modified. Scanning can fail, |
| 278 | + // the code just bails out and creates an empty patch in such cases, as: |
| 279 | + // - If scanning for Baseline fails, no knowledge of existing includes hence |
| 280 | + // patch will contain all the includes in Modified. Leading to rebuild of |
| 281 | + // whole preamble, which is terribly slow. |
| 282 | + // - If scanning for Modified fails, cannot figure out newly added ones so |
| 283 | + // there's nothing to do but generate an empty patch. |
| 284 | + auto BaselineIncludes = scanPreambleIncludes( |
| 285 | + // Contents needs to be null-terminated. |
| 286 | + Baseline.Preamble.getContents().str(), |
| 287 | + Baseline.StatCache->getConsumingFS(Modified.FS), Modified.CompileCommand); |
| 288 | + if (!BaselineIncludes) { |
| 289 | + elog("Failed to scan includes for baseline of {0}: {1}", FileName, |
| 290 | + BaselineIncludes.takeError()); |
| 291 | + return {}; |
| 292 | + } |
| 293 | + auto ModifiedIncludes = scanPreambleIncludes( |
| 294 | + Modified.Contents, Baseline.StatCache->getConsumingFS(Modified.FS), |
| 295 | + Modified.CompileCommand); |
| 296 | + if (!ModifiedIncludes) { |
| 297 | + elog("Failed to scan includes for modified contents of {0}: {1}", FileName, |
| 298 | + ModifiedIncludes.takeError()); |
| 299 | + return {}; |
| 300 | + } |
| 301 | + |
| 302 | + PreamblePatch PP; |
| 303 | + // This shouldn't coincide with any real file name. |
| 304 | + llvm::SmallString<128> PatchName; |
| 305 | + llvm::sys::path::append(PatchName, llvm::sys::path::parent_path(FileName), |
| 306 | + "__preamble_patch__.h"); |
| 307 | + PP.PatchFileName = PatchName.str().str(); |
| 308 | + |
| 309 | + // We are only interested in newly added includes, record the ones in Baseline |
| 310 | + // for exclusion. |
| 311 | + llvm::DenseSet<std::pair<tok::PPKeywordKind, llvm::StringRef>> |
| 312 | + ExistingIncludes; |
| 313 | + for (const auto &Inc : *BaselineIncludes) |
| 314 | + ExistingIncludes.insert({Inc.Directive, Inc.Written}); |
| 315 | + // Calculate extra includes that needs to be inserted. |
| 316 | + llvm::raw_string_ostream Patch(PP.PatchContents); |
| 317 | + for (const auto &Inc : *ModifiedIncludes) { |
| 318 | + if (ExistingIncludes.count({Inc.Directive, Inc.Written})) |
| 319 | + continue; |
| 320 | + Patch << llvm::formatv("#{0} {1}\n", spellingForIncDirective(Inc.Directive), |
| 321 | + Inc.Written); |
| 322 | + } |
| 323 | + Patch.flush(); |
| 324 | + |
| 325 | + // FIXME: Handle more directives, e.g. define/undef. |
| 326 | + return PP; |
| 327 | +} |
| 328 | + |
| 329 | +void PreamblePatch::apply(CompilerInvocation &CI) const { |
| 330 | + // No need to map an empty file. |
| 331 | + if (PatchContents.empty()) |
| 332 | + return; |
| 333 | + auto &PPOpts = CI.getPreprocessorOpts(); |
| 334 | + auto PatchBuffer = |
| 335 | + // we copy here to ensure contents are still valid if CI outlives the |
| 336 | + // PreamblePatch. |
| 337 | + llvm::MemoryBuffer::getMemBufferCopy(PatchContents, PatchFileName); |
| 338 | + // CI will take care of the lifetime of the buffer. |
| 339 | + PPOpts.addRemappedFile(PatchFileName, PatchBuffer.release()); |
| 340 | + // The patch will be parsed after loading the preamble ast and before parsing |
| 341 | + // the main file. |
| 342 | + PPOpts.Includes.push_back(PatchFileName); |
| 343 | +} |
| 344 | + |
169 | 345 | } // namespace clangd
|
170 | 346 | } // namespace clang
|
0 commit comments