clang-tools  14.0.0git
Preamble.cpp
Go to the documentation of this file.
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"
10 #include "Compiler.h"
11 #include "Headers.h"
12 #include "SourceCode.h"
13 #include "support/Logger.h"
14 #include "support/ThreadsafeFS.h"
15 #include "support/Trace.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/Basic/Diagnostic.h"
18 #include "clang/Basic/DiagnosticLex.h"
19 #include "clang/Basic/LangOptions.h"
20 #include "clang/Basic/SourceLocation.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Basic/TokenKinds.h"
23 #include "clang/Frontend/CompilerInvocation.h"
24 #include "clang/Frontend/FrontendActions.h"
25 #include "clang/Lex/Lexer.h"
26 #include "clang/Lex/PPCallbacks.h"
27 #include "clang/Lex/Preprocessor.h"
28 #include "clang/Lex/PreprocessorOptions.h"
29 #include "clang/Tooling/CompilationDatabase.h"
30 #include "llvm/ADT/ArrayRef.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/DenseSet.h"
33 #include "llvm/ADT/IntrusiveRefCntPtr.h"
34 #include "llvm/ADT/None.h"
35 #include "llvm/ADT/Optional.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/ADT/StringRef.h"
40 #include "llvm/ADT/StringSet.h"
41 #include "llvm/Support/Error.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/FormatVariadic.h"
44 #include "llvm/Support/MemoryBuffer.h"
45 #include "llvm/Support/Path.h"
46 #include "llvm/Support/VirtualFileSystem.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include <iterator>
49 #include <memory>
50 #include <string>
51 #include <system_error>
52 #include <utility>
53 #include <vector>
54 
55 namespace clang {
56 namespace clangd {
57 namespace {
58 constexpr llvm::StringLiteral PreamblePatchHeaderName = "__preamble_patch__.h";
59 
60 bool compileCommandsAreEqual(const tooling::CompileCommand &LHS,
61  const tooling::CompileCommand &RHS) {
62  // We don't check for Output, it should not matter to clangd.
63  return LHS.Directory == RHS.Directory && LHS.Filename == RHS.Filename &&
64  llvm::makeArrayRef(LHS.CommandLine).equals(RHS.CommandLine);
65 }
66 
67 class CppFilePreambleCallbacks : public PreambleCallbacks {
68 public:
69  CppFilePreambleCallbacks(PathRef File, PreambleParsedCallback ParsedCallback)
70  : File(File), ParsedCallback(ParsedCallback) {}
71 
72  IncludeStructure takeIncludes() { return std::move(Includes); }
73 
74  MainFileMacros takeMacros() { return std::move(Macros); }
75 
76  CanonicalIncludes takeCanonicalIncludes() { return std::move(CanonIncludes); }
77 
78  bool isMainFileIncludeGuarded() const { return IsMainFileIncludeGuarded; }
79 
80  void AfterExecute(CompilerInstance &CI) override {
81  if (ParsedCallback) {
82  trace::Span Tracer("Running PreambleCallback");
83  ParsedCallback(CI.getASTContext(), CI.getPreprocessorPtr(),
84  CanonIncludes);
85  }
86 
87  const SourceManager &SM = CI.getSourceManager();
88  const FileEntry *MainFE = SM.getFileEntryForID(SM.getMainFileID());
89  IsMainFileIncludeGuarded =
90  CI.getPreprocessor().getHeaderSearchInfo().isFileMultipleIncludeGuarded(
91  MainFE);
92  }
93 
94  void BeforeExecute(CompilerInstance &CI) override {
95  CanonIncludes.addSystemHeadersMapping(CI.getLangOpts());
96  LangOpts = &CI.getLangOpts();
97  SourceMgr = &CI.getSourceManager();
98  }
99 
100  std::unique_ptr<PPCallbacks> createPPCallbacks() override {
101  assert(SourceMgr && LangOpts &&
102  "SourceMgr and LangOpts must be set at this point");
103 
104  return std::make_unique<PPChainedCallbacks>(
106  std::make_unique<CollectMainFileMacros>(*SourceMgr, Macros));
107  }
108 
109  CommentHandler *getCommentHandler() override {
110  IWYUHandler = collectIWYUHeaderMaps(&CanonIncludes);
111  return IWYUHandler.get();
112  }
113 
114  bool shouldSkipFunctionBody(Decl *D) override {
115  // Generally we skip function bodies in preambles for speed.
116  // We can make exceptions for functions that are cheap to parse and
117  // instantiate, widely used, and valuable (e.g. commonly produce errors).
118  if (const auto *FT = llvm::dyn_cast<clang::FunctionTemplateDecl>(D)) {
119  if (const auto *II = FT->getDeclName().getAsIdentifierInfo())
120  // std::make_unique is trivial, and we diagnose bad constructor calls.
121  if (II->isStr("make_unique") && FT->isInStdNamespace())
122  return false;
123  }
124  return true;
125  }
126 
127 private:
128  PathRef File;
129  PreambleParsedCallback ParsedCallback;
130  IncludeStructure Includes;
131  CanonicalIncludes CanonIncludes;
132  MainFileMacros Macros;
133  bool IsMainFileIncludeGuarded = false;
134  std::unique_ptr<CommentHandler> IWYUHandler = nullptr;
135  const clang::LangOptions *LangOpts = nullptr;
136  const SourceManager *SourceMgr = nullptr;
137 };
138 
139 // Represents directives other than includes, where basic textual information is
140 // enough.
141 struct TextualPPDirective {
142  unsigned DirectiveLine;
143  // Full text that's representing the directive, including the `#`.
144  std::string Text;
145  unsigned Offset;
146 
147  bool operator==(const TextualPPDirective &RHS) const {
148  return std::tie(DirectiveLine, Offset, Text) ==
149  std::tie(RHS.DirectiveLine, RHS.Offset, RHS.Text);
150  }
151 };
152 
153 // Formats a PP directive consisting of Prefix (e.g. "#define ") and Body ("X
154 // 10"). The formatting is copied so that the tokens in Body have PresumedLocs
155 // with correct columns and lines.
156 std::string spellDirective(llvm::StringRef Prefix,
157  CharSourceRange DirectiveRange,
158  const LangOptions &LangOpts, const SourceManager &SM,
159  unsigned &DirectiveLine, unsigned &Offset) {
160  std::string SpelledDirective;
161  llvm::raw_string_ostream OS(SpelledDirective);
162  OS << Prefix;
163 
164  // Make sure DirectiveRange is a char range and doesn't contain macro ids.
165  DirectiveRange = SM.getExpansionRange(DirectiveRange);
166  if (DirectiveRange.isTokenRange()) {
167  DirectiveRange.setEnd(
168  Lexer::getLocForEndOfToken(DirectiveRange.getEnd(), 0, SM, LangOpts));
169  }
170 
171  auto DecompLoc = SM.getDecomposedLoc(DirectiveRange.getBegin());
172  DirectiveLine = SM.getLineNumber(DecompLoc.first, DecompLoc.second);
173  Offset = DecompLoc.second;
174  auto TargetColumn = SM.getColumnNumber(DecompLoc.first, DecompLoc.second) - 1;
175 
176  // Pad with spaces before DirectiveRange to make sure it will be on right
177  // column when patched.
178  if (Prefix.size() <= TargetColumn) {
179  // There is enough space for Prefix and space before directive, use it.
180  // We try to squeeze the Prefix into the same line whenever we can, as
181  // putting onto a separate line won't work at the beginning of the file.
182  OS << std::string(TargetColumn - Prefix.size(), ' ');
183  } else {
184  // Prefix was longer than the space we had. We produce e.g.:
185  // #line N-1
186  // #define \
187  // X 10
188  OS << "\\\n" << std::string(TargetColumn, ' ');
189  // Decrement because we put an additional line break before
190  // DirectiveRange.begin().
191  --DirectiveLine;
192  }
193  OS << toSourceCode(SM, DirectiveRange.getAsRange());
194  return OS.str();
195 }
196 
197 // Collects #define directives inside the main file.
198 struct DirectiveCollector : public PPCallbacks {
199  DirectiveCollector(const Preprocessor &PP,
200  std::vector<TextualPPDirective> &TextualDirectives)
201  : LangOpts(PP.getLangOpts()), SM(PP.getSourceManager()),
202  TextualDirectives(TextualDirectives) {}
203 
204  void FileChanged(SourceLocation Loc, FileChangeReason Reason,
205  SrcMgr::CharacteristicKind FileType,
206  FileID PrevFID) override {
207  InMainFile = SM.isWrittenInMainFile(Loc);
208  }
209 
210  void MacroDefined(const Token &MacroNameTok,
211  const MacroDirective *MD) override {
212  if (!InMainFile)
213  return;
214  TextualDirectives.emplace_back();
215  TextualPPDirective &TD = TextualDirectives.back();
216 
217  const auto *MI = MD->getMacroInfo();
218  TD.Text =
219  spellDirective("#define ",
220  CharSourceRange::getTokenRange(
221  MI->getDefinitionLoc(), MI->getDefinitionEndLoc()),
222  LangOpts, SM, TD.DirectiveLine, TD.Offset);
223  }
224 
225 private:
226  bool InMainFile = true;
227  const LangOptions &LangOpts;
228  const SourceManager &SM;
229  std::vector<TextualPPDirective> &TextualDirectives;
230 };
231 
232 struct ScannedPreamble {
233  std::vector<Inclusion> Includes;
234  std::vector<TextualPPDirective> TextualDirectives;
235  PreambleBounds Bounds = {0, false};
236 };
237 
238 /// Scans the preprocessor directives in the preamble section of the file by
239 /// running preprocessor over \p Contents. Returned includes do not contain
240 /// resolved paths. \p Cmd is used to build the compiler invocation, which might
241 /// stat/read files.
242 llvm::Expected<ScannedPreamble>
243 scanPreamble(llvm::StringRef Contents, const tooling::CompileCommand &Cmd) {
244  class EmptyFS : public ThreadsafeFS {
245  private:
246  llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> viewImpl() const override {
248  }
249  };
250  EmptyFS FS;
251  // Build and run Preprocessor over the preamble.
252  ParseInputs PI;
253  PI.Contents = Contents.str();
254  PI.TFS = &FS;
255  PI.CompileCommand = Cmd;
256  IgnoringDiagConsumer IgnoreDiags;
258  if (!CI)
259  return error("failed to create compiler invocation");
260  CI->getDiagnosticOpts().IgnoreWarnings = true;
261  auto ContentsBuffer = llvm::MemoryBuffer::getMemBuffer(Contents);
262  // This means we're scanning (though not preprocessing) the preamble section
263  // twice. However, it's important to precisely follow the preamble bounds used
264  // elsewhere.
265  auto Bounds = ComputePreambleBounds(*CI->getLangOpts(), *ContentsBuffer, 0);
266  auto PreambleContents =
267  llvm::MemoryBuffer::getMemBufferCopy(Contents.substr(0, Bounds.Size));
268  auto Clang = prepareCompilerInstance(
269  std::move(CI), nullptr, std::move(PreambleContents),
270  // Provide an empty FS to prevent preprocessor from performing IO. This
271  // also implies missing resolved paths for includes.
272  FS.view(llvm::None), IgnoreDiags);
273  if (Clang->getFrontendOpts().Inputs.empty())
274  return error("compiler instance had no inputs");
275  // We are only interested in main file includes.
276  Clang->getPreprocessorOpts().SingleFileParseMode = true;
277  PreprocessOnlyAction Action;
278  if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0]))
279  return error("failed BeginSourceFile");
280  const auto &SM = Clang->getSourceManager();
281  Preprocessor &PP = Clang->getPreprocessor();
282  IncludeStructure Includes;
283  PP.addPPCallbacks(collectIncludeStructureCallback(SM, &Includes));
284  ScannedPreamble SP;
285  SP.Bounds = Bounds;
286  PP.addPPCallbacks(
287  std::make_unique<DirectiveCollector>(PP, SP.TextualDirectives));
288  if (llvm::Error Err = Action.Execute())
289  return std::move(Err);
290  Action.EndSourceFile();
291  SP.Includes = std::move(Includes.MainFileIncludes);
292  return SP;
293 }
294 
295 const char *spellingForIncDirective(tok::PPKeywordKind IncludeDirective) {
296  switch (IncludeDirective) {
297  case tok::pp_include:
298  return "include";
299  case tok::pp_import:
300  return "import";
301  case tok::pp_include_next:
302  return "include_next";
303  default:
304  break;
305  }
306  llvm_unreachable("not an include directive");
307 }
308 
309 // Checks whether \p FileName is a valid spelling of main file.
310 bool isMainFile(llvm::StringRef FileName, const SourceManager &SM) {
311  auto FE = SM.getFileManager().getFile(FileName);
312  return FE && *FE == SM.getFileEntryForID(SM.getMainFileID());
313 }
314 
315 } // namespace
316 
317 std::shared_ptr<const PreambleData>
318 buildPreamble(PathRef FileName, CompilerInvocation CI,
319  const ParseInputs &Inputs, bool StoreInMemory,
320  PreambleParsedCallback PreambleCallback) {
321  // Note that we don't need to copy the input contents, preamble can live
322  // without those.
323  auto ContentsBuffer =
324  llvm::MemoryBuffer::getMemBuffer(Inputs.Contents, FileName);
325  auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), *ContentsBuffer, 0);
326 
327  trace::Span Tracer("BuildPreamble");
328  SPAN_ATTACH(Tracer, "File", FileName);
329  std::vector<std::unique_ptr<FeatureModule::ASTListener>> ASTListeners;
330  if (Inputs.FeatureModules) {
331  for (auto &M : *Inputs.FeatureModules) {
332  if (auto Listener = M.astListeners())
333  ASTListeners.emplace_back(std::move(Listener));
334  }
335  }
336  StoreDiags PreambleDiagnostics;
337  PreambleDiagnostics.setDiagCallback(
338  [&ASTListeners](const clang::Diagnostic &D, clangd::Diag &Diag) {
339  llvm::for_each(ASTListeners,
340  [&](const auto &L) { L->sawDiagnostic(D, Diag); });
341  });
342  llvm::IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine =
343  CompilerInstance::createDiagnostics(&CI.getDiagnosticOpts(),
344  &PreambleDiagnostics, false);
345  PreambleDiagnostics.setLevelAdjuster(
346  [&](DiagnosticsEngine::Level DiagLevel, const clang::Diagnostic &Info) {
347  switch (Info.getID()) {
348  case diag::warn_no_newline_eof:
349  case diag::warn_cxx98_compat_no_newline_eof:
350  case diag::ext_no_newline_eof:
351  // If the preamble doesn't span the whole file, drop the no newline at
352  // eof warnings.
353  return Bounds.Size != ContentsBuffer->getBufferSize()
354  ? DiagnosticsEngine::Level::Ignored
355  : DiagLevel;
356  }
357  return DiagLevel;
358  });
359 
360  // Skip function bodies when building the preamble to speed up building
361  // the preamble and make it smaller.
362  assert(!CI.getFrontendOpts().SkipFunctionBodies);
363  CI.getFrontendOpts().SkipFunctionBodies = true;
364  // We don't want to write comment locations into PCH. They are racy and slow
365  // to read back. We rely on dynamic index for the comments instead.
366  CI.getPreprocessorOpts().WriteCommentListToPCH = false;
367 
368  CppFilePreambleCallbacks CapturedInfo(FileName, PreambleCallback);
369  auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
370  llvm::SmallString<32> AbsFileName(FileName);
371  VFS->makeAbsolute(AbsFileName);
372  auto StatCache = std::make_unique<PreambleFileStatusCache>(AbsFileName);
373  auto BuiltPreamble = PrecompiledPreamble::Build(
374  CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine,
375  StatCache->getProducingFS(VFS),
376  std::make_shared<PCHContainerOperations>(), StoreInMemory, CapturedInfo);
377 
378  // When building the AST for the main file, we do want the function
379  // bodies.
380  CI.getFrontendOpts().SkipFunctionBodies = false;
381 
382  if (BuiltPreamble) {
383  vlog("Built preamble of size {0} for file {1} version {2}",
384  BuiltPreamble->getSize(), FileName, Inputs.Version);
385  std::vector<Diag> Diags = PreambleDiagnostics.take();
386  auto Result = std::make_shared<PreambleData>(std::move(*BuiltPreamble));
387  Result->Version = Inputs.Version;
388  Result->CompileCommand = Inputs.CompileCommand;
389  Result->Diags = std::move(Diags);
390  Result->Includes = CapturedInfo.takeIncludes();
391  Result->Macros = CapturedInfo.takeMacros();
392  Result->CanonIncludes = CapturedInfo.takeCanonicalIncludes();
393  Result->StatCache = std::move(StatCache);
394  Result->MainIsIncludeGuarded = CapturedInfo.isMainFileIncludeGuarded();
395  return Result;
396  }
397 
398  elog("Could not build a preamble for file {0} version {1}: {2}", FileName,
399  Inputs.Version, BuiltPreamble.getError().message());
400  return nullptr;
401 }
402 
405  const CompilerInvocation &CI) {
406  auto ContentsBuffer =
407  llvm::MemoryBuffer::getMemBuffer(Inputs.Contents, FileName);
408  auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), *ContentsBuffer, 0);
409  auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
410  return compileCommandsAreEqual(Inputs.CompileCommand,
412  Preamble.Preamble.CanReuse(CI, *ContentsBuffer, Bounds, *VFS);
413 }
414 
415 void escapeBackslashAndQuotes(llvm::StringRef Text, llvm::raw_ostream &OS) {
416  for (char C : Text) {
417  switch (C) {
418  case '\\':
419  case '"':
420  OS << '\\';
421  break;
422  default:
423  break;
424  }
425  OS << C;
426  }
427 }
428 
429 PreamblePatch PreamblePatch::create(llvm::StringRef FileName,
430  const ParseInputs &Modified,
431  const PreambleData &Baseline,
432  PatchType PatchType) {
433  trace::Span Tracer("CreatePreamblePatch");
434  SPAN_ATTACH(Tracer, "File", FileName);
435  assert(llvm::sys::path::is_absolute(FileName) && "relative FileName!");
436  // First scan preprocessor directives in Baseline and Modified. These will be
437  // used to figure out newly added directives in Modified. Scanning can fail,
438  // the code just bails out and creates an empty patch in such cases, as:
439  // - If scanning for Baseline fails, no knowledge of existing includes hence
440  // patch will contain all the includes in Modified. Leading to rebuild of
441  // whole preamble, which is terribly slow.
442  // - If scanning for Modified fails, cannot figure out newly added ones so
443  // there's nothing to do but generate an empty patch.
444  auto BaselineScan = scanPreamble(
445  // Contents needs to be null-terminated.
446  Baseline.Preamble.getContents().str(), Modified.CompileCommand);
447  if (!BaselineScan) {
448  elog("Failed to scan baseline of {0}: {1}", FileName,
449  BaselineScan.takeError());
450  return PreamblePatch::unmodified(Baseline);
451  }
452  auto ModifiedScan = scanPreamble(Modified.Contents, Modified.CompileCommand);
453  if (!ModifiedScan) {
454  elog("Failed to scan modified contents of {0}: {1}", FileName,
455  ModifiedScan.takeError());
456  return PreamblePatch::unmodified(Baseline);
457  }
458 
459  bool IncludesChanged = BaselineScan->Includes != ModifiedScan->Includes;
460  bool DirectivesChanged =
461  BaselineScan->TextualDirectives != ModifiedScan->TextualDirectives;
462  if ((PatchType == PatchType::MacroDirectives || !IncludesChanged) &&
463  !DirectivesChanged)
464  return PreamblePatch::unmodified(Baseline);
465 
466  PreamblePatch PP;
467  // This shouldn't coincide with any real file name.
468  llvm::SmallString<128> PatchName;
469  llvm::sys::path::append(PatchName, llvm::sys::path::parent_path(FileName),
470  PreamblePatchHeaderName);
471  PP.PatchFileName = PatchName.str().str();
472  PP.ModifiedBounds = ModifiedScan->Bounds;
473 
474  llvm::raw_string_ostream Patch(PP.PatchContents);
475  // Set default filename for subsequent #line directives
476  Patch << "#line 0 \"";
477  // FileName part of a line directive is subject to backslash escaping, which
478  // might lead to problems on windows especially.
480  Patch << "\"\n";
481 
482  if (IncludesChanged && PatchType == PatchType::All) {
483  // We are only interested in newly added includes, record the ones in
484  // Baseline for exclusion.
485  llvm::DenseMap<std::pair<tok::PPKeywordKind, llvm::StringRef>,
486  /*Resolved=*/llvm::StringRef>
487  ExistingIncludes;
488  for (const auto &Inc : Baseline.Includes.MainFileIncludes)
489  ExistingIncludes[{Inc.Directive, Inc.Written}] = Inc.Resolved;
490  // There might be includes coming from disabled regions, record these for
491  // exclusion too. note that we don't have resolved paths for those.
492  for (const auto &Inc : BaselineScan->Includes)
493  ExistingIncludes.try_emplace({Inc.Directive, Inc.Written});
494  // Calculate extra includes that needs to be inserted.
495  for (auto &Inc : ModifiedScan->Includes) {
496  auto It = ExistingIncludes.find({Inc.Directive, Inc.Written});
497  // Include already present in the baseline preamble. Set resolved path and
498  // put into preamble includes.
499  if (It != ExistingIncludes.end()) {
500  Inc.Resolved = It->second.str();
501  PP.PreambleIncludes.push_back(Inc);
502  continue;
503  }
504  // Include is new in the modified preamble. Inject it into the patch and
505  // use #line to set the presumed location to where it is spelled.
506  auto LineCol = offsetToClangLineColumn(Modified.Contents, Inc.HashOffset);
507  Patch << llvm::formatv("#line {0}\n", LineCol.first);
508  Patch << llvm::formatv(
509  "#{0} {1}\n", spellingForIncDirective(Inc.Directive), Inc.Written);
510  }
511  }
512 
513  if (DirectivesChanged) {
514  // We need to patch all the directives, since they are order dependent. e.g:
515  // #define BAR(X) NEW(X) // Newly introduced in Modified
516  // #define BAR(X) OLD(X) // Exists in the Baseline
517  //
518  // If we've patched only the first directive, the macro definition would've
519  // been wrong for the rest of the file, since patch is applied after the
520  // baseline preamble.
521  //
522  // Note that we deliberately ignore conditional directives and undefs to
523  // reduce complexity. The former might cause problems because scanning is
524  // imprecise and might pick directives from disabled regions.
525  for (const auto &TD : ModifiedScan->TextualDirectives) {
526  Patch << "#line " << TD.DirectiveLine << '\n';
527  Patch << TD.Text << '\n';
528  }
529  }
530  dlog("Created preamble patch: {0}", Patch.str());
531  Patch.flush();
532  return PP;
533 }
534 
536  const ParseInputs &Modified,
537  const PreambleData &Baseline) {
538  return create(FileName, Modified, Baseline, PatchType::All);
539 }
540 
542  const ParseInputs &Modified,
543  const PreambleData &Baseline) {
544  return create(FileName, Modified, Baseline, PatchType::MacroDirectives);
545 }
546 
547 void PreamblePatch::apply(CompilerInvocation &CI) const {
548  // No need to map an empty file.
549  if (PatchContents.empty())
550  return;
551  auto &PPOpts = CI.getPreprocessorOpts();
552  auto PatchBuffer =
553  // we copy here to ensure contents are still valid if CI outlives the
554  // PreamblePatch.
555  llvm::MemoryBuffer::getMemBufferCopy(PatchContents, PatchFileName);
556  // CI will take care of the lifetime of the buffer.
557  PPOpts.addRemappedFile(PatchFileName, PatchBuffer.release());
558  // The patch will be parsed after loading the preamble ast and before parsing
559  // the main file.
560  PPOpts.Includes.push_back(PatchFileName);
561 }
562 
563 std::vector<Inclusion> PreamblePatch::preambleIncludes() const {
564  return PreambleIncludes;
565 }
566 
569  PP.PreambleIncludes = Preamble.Includes.MainFileIncludes;
570  PP.ModifiedBounds = Preamble.Preamble.getBounds();
571  return PP;
572 }
573 
574 SourceLocation translatePreamblePatchLocation(SourceLocation Loc,
575  const SourceManager &SM) {
576  auto DefFile = SM.getFileID(Loc);
577  if (auto *FE = SM.getFileEntryForID(DefFile)) {
578  auto IncludeLoc = SM.getIncludeLoc(DefFile);
579  // Preamble patch is included inside the builtin file.
580  if (IncludeLoc.isValid() && SM.isWrittenInBuiltinFile(IncludeLoc) &&
581  FE->getName().endswith(PreamblePatchHeaderName)) {
582  auto Presumed = SM.getPresumedLoc(Loc);
583  // Check that line directive is pointing at main file.
584  if (Presumed.isValid() && Presumed.getFileID().isInvalid() &&
585  isMainFile(Presumed.getFilename(), SM)) {
586  Loc = SM.translateLineCol(SM.getMainFileID(), Presumed.getLine(),
587  Presumed.getColumn());
588  }
589  }
590  }
591  return Loc;
592 }
593 } // namespace clangd
594 } // namespace clang
dlog
#define dlog(...)
Definition: Logger.h:102
clang::clangd::ParseInputs::Version
std::string Version
Definition: Compiler.h:52
Loc
SourceLocation Loc
Definition: KernelNameRestrictionCheck.cpp:45
clang::clangd::collectIWYUHeaderMaps
std::unique_ptr< CommentHandler > collectIWYUHeaderMaps(CanonicalIncludes *Includes)
Returns a CommentHandler that parses pragma comment on include files to determine when we should incl...
Definition: CanonicalIncludes.cpp:59
clang::clangd::isPreambleCompatible
bool isPreambleCompatible(const PreambleData &Preamble, const ParseInputs &Inputs, PathRef FileName, const CompilerInvocation &CI)
Returns true if Preamble is reusable for Inputs.
Definition: Preamble.cpp:403
Headers.h
clang::clangd::ParseInputs::FeatureModules
FeatureModuleSet * FeatureModules
Definition: Compiler.h:61
clang::clangd::escapeBackslashAndQuotes
void escapeBackslashAndQuotes(llvm::StringRef Text, llvm::raw_ostream &OS)
Definition: Preamble.cpp:415
clang::clangd::prepareCompilerInstance
std::unique_ptr< CompilerInstance > prepareCompilerInstance(std::unique_ptr< clang::CompilerInvocation > CI, const PrecompiledPreamble *Preamble, std::unique_ptr< llvm::MemoryBuffer > Buffer, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, DiagnosticConsumer &DiagsClient)
Definition: Compiler.cpp:110
clang::clangd::ParseInputs::Contents
std::string Contents
Definition: Compiler.h:50
clang::clangd::PreambleParsedCallback
std::function< void(ASTContext &, std::shared_ptr< clang::Preprocessor >, const CanonicalIncludes &)> PreambleParsedCallback
Definition: Preamble.h:75
clang::doc::MD
static GeneratorRegistry::Add< MDGenerator > MD(MDGenerator::Format, "Generator for MD output.")
Tracer
std::unique_ptr< trace::EventTracer > Tracer
Definition: TraceTests.cpp:164
clang::clangd::error
llvm::Error error(std::error_code EC, const char *Fmt, Ts &&... Vals)
Definition: Logger.h:80
clang::clangd::PreambleData::Preamble
PrecompiledPreamble Preamble
Definition: Preamble.h:55
CI
std::unique_ptr< CompilerInvocation > CI
Definition: TUScheduler.cpp:450
clang::clangd::PreamblePatch::unmodified
static PreamblePatch unmodified(const PreambleData &Preamble)
Preamble is used verbatim.
Definition: Preamble.cpp:567
Preamble.h
Text
std::string Text
Definition: HTMLGenerator.cpp:80
Trace.h
clang::clangd::PreamblePatch
Stores information required to parse a TU using a (possibly stale) Baseline preamble.
Definition: Preamble.h:98
SourceMgr
llvm::SourceMgr * SourceMgr
Definition: ConfigCompile.cpp:102
clang::clangd::ParseInputs::CompileCommand
tooling::CompileCommand CompileCommand
Definition: Compiler.h:48
Action
llvm::unique_function< void()> Action
Definition: TUScheduler.cpp:596
clang::clangd::IncludeStructure::MainFileIncludes
std::vector< Inclusion > MainFileIncludes
Definition: Headers.h:115
Preamble
const PreambleData & Preamble
Definition: CodeComplete.cpp:1104
M
const google::protobuf::Message & M
Definition: Server.cpp:309
ThreadsafeFS.h
Inputs
ParseInputs Inputs
Definition: TUScheduler.cpp:451
clang::clangd::PreamblePatch::apply
void apply(CompilerInvocation &CI) const
Adjusts CI (which compiles the modified inputs) to be used with the baseline preamble.
Definition: Preamble.cpp:547
clang::clangd::ParseInputs
Information required to run clang, e.g. to parse AST or do code completion.
Definition: Compiler.h:47
ns1::ns2::D
@ D
Definition: CategoricalFeature.h:3
Diagnostic
DiagnosticCallback Diagnostic
Definition: ConfigCompile.cpp:101
clang::clangd::ParseInputs::TFS
const ThreadsafeFS * TFS
Definition: Compiler.h:49
Decl
const FunctionDecl * Decl
Definition: AvoidBindCheck.cpp:100
clang::clangd::PreambleData
The parsed preamble and associated data.
Definition: Preamble.h:49
clang::clangd::PreamblePatch::createMacroPatch
static PreamblePatch createMacroPatch(llvm::StringRef FileName, const ParseInputs &Modified, const PreambleData &Baseline)
Definition: Preamble.cpp:541
clang::clangd::PreamblePatch::PatchType::MacroDirectives
@ MacroDirectives
clang::clangd::PreamblePatch::PatchType
PatchType
Definition: Preamble.h:100
clang::clangd::Diag
A top-level diagnostic that may have Notes and Fixes.
Definition: Diagnostics.h:97
clang::clangd::buildPreamble
std::shared_ptr< const PreambleData > buildPreamble(PathRef FileName, CompilerInvocation CI, const ParseInputs &Inputs, bool StoreInMemory, PreambleParsedCallback PreambleCallback)
Build a preamble for the new inputs unless an old one can be reused.
Definition: Preamble.cpp:318
Logger.h
Bounds
PreambleBounds Bounds
Definition: Preamble.cpp:235
Patch
const llvm::Optional< PreamblePatch > Patch
Definition: CodeComplete.cpp:1105
SPAN_ATTACH
#define SPAN_ATTACH(S, Name, Expr)
Attach a key-value pair to a Span event.
Definition: Trace.h:164
clang::clangd::vlog
void vlog(const char *Fmt, Ts &&... Vals)
Definition: Logger.h:73
clang::clangd::collectIncludeStructureCallback
std::unique_ptr< PPCallbacks > collectIncludeStructureCallback(const SourceManager &SM, IncludeStructure *Out)
Returns a PPCallback that visits all inclusions in the main file.
Definition: Headers.cpp:152
FileName
StringRef FileName
Definition: KernelNameRestrictionCheck.cpp:46
Offset
unsigned Offset
Definition: Preamble.cpp:145
DirectiveLine
unsigned DirectiveLine
Definition: Preamble.cpp:142
clang::tidy::bugprone::PP
static Preprocessor * PP
Definition: BadSignalToKillThreadCheck.cpp:29
clang::clangd::PreambleData::CompileCommand
tooling::CompileCommand CompileCommand
Definition: Preamble.h:54
clang::clangd::buildCompilerInvocation
std::unique_ptr< CompilerInvocation > buildCompilerInvocation(const ParseInputs &Inputs, clang::DiagnosticConsumer &D, std::vector< std::string > *CC1Args)
Builds compiler invocation that could be used to build AST or preamble.
Definition: Compiler.cpp:84
SourceCode.h
Compiler.h
InMemoryFileSystem
llvm::IntrusiveRefCntPtr< llvm::vfs::InMemoryFileSystem > InMemoryFileSystem
Definition: IndexActionTests.cpp:109
clang::clangd::PreamblePatch::createFullPatch
static PreamblePatch createFullPatch(llvm::StringRef FileName, const ParseInputs &Modified, const PreambleData &Baseline)
Builds a patch that contains new PP directives introduced to the preamble section of Modified compare...
Definition: Preamble.cpp:535
Info
FunctionInfo Info
Definition: FunctionSizeCheck.cpp:120
clang::clangd::PathRef
llvm::StringRef PathRef
A typedef to represent a ref to file path.
Definition: Path.h:29
clang::clangd::ThreadsafeFS::view
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > view(llvm::NoneType CWD) const
Obtain a vfs::FileSystem with an arbitrary initial working directory.
Definition: ThreadsafeFS.h:34
C
const Criteria C
Definition: FunctionCognitiveComplexityCheck.cpp:93
PPCallbacks
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
OS
llvm::raw_string_ostream OS
Definition: TraceTests.cpp:163
clang::clangd::StoreDiags::setDiagCallback
void setDiagCallback(DiagCallback CB)
Invokes a callback every time a diagnostics is completely formed.
Definition: Diagnostics.h:160
clang::clangd::StoreDiags
StoreDiags collects the diagnostics that can later be reported by clangd.
Definition: Diagnostics.h:135
Diags
CapturedDiags Diags
Definition: ConfigCompileTests.cpp:38
clang::clangd::operator==
bool operator==(const Inclusion &LHS, const Inclusion &RHS)
Definition: Headers.cpp:273
clang::clangd::StoreDiags::setLevelAdjuster
void setLevelAdjuster(LevelAdjuster Adjuster)
If set, this allows the client of this class to adjust the level of diagnostics, such as promoting wa...
Definition: Diagnostics.h:157
clang::clangd::elog
void elog(const char *Fmt, Ts &&... Vals)
Definition: Logger.h:62
clang::clangd::PreamblePatch::preambleIncludes
std::vector< Inclusion > preambleIncludes() const
Returns #include directives from the Modified preamble that were resolved using the Baseline preamble...
Definition: Preamble.cpp:563
clang::clangd::toSourceCode
llvm::StringRef toSourceCode(const SourceManager &SM, SourceRange R)
Returns the source code covered by the source range.
Definition: SourceCode.cpp:446
clang::clangd::PreamblePatch::PatchType::All
@ All
clang::clangd::StoreDiags::take
std::vector< Diag > take(const clang::tidy::ClangTidyContext *Tidy=nullptr)
Definition: Diagnostics.cpp:558
IgnoreDiags
IgnoringDiagConsumer IgnoreDiags
Definition: HeadersTests.cpp:128
clang::clangd::translatePreamblePatchLocation
SourceLocation translatePreamblePatchLocation(SourceLocation Loc, const SourceManager &SM)
Translates locations inside preamble patch to their main-file equivalent using presumed locations.
Definition: Preamble.cpp:574
clang::clangd::offsetToClangLineColumn
std::pair< size_t, size_t > offsetToClangLineColumn(llvm::StringRef Code, size_t Offset)
Definition: SourceCode.cpp:474
clang::clangd::trace::Span
Records an event whose duration is the lifetime of the Span object.
Definition: Trace.h:143