clang-tools  14.0.0git
ParsedAST.cpp
Go to the documentation of this file.
1 //===--- ParsedAST.cpp -------------------------------------------*- C++-*-===//
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 "ParsedAST.h"
10 #include "../clang-tidy/ClangTidyCheck.h"
11 #include "../clang-tidy/ClangTidyDiagnosticConsumer.h"
12 #include "../clang-tidy/ClangTidyModuleRegistry.h"
13 #include "AST.h"
14 #include "Compiler.h"
15 #include "Config.h"
16 #include "Diagnostics.h"
17 #include "Feature.h"
18 #include "FeatureModule.h"
19 #include "Headers.h"
20 #include "HeuristicResolver.h"
21 #include "IncludeCleaner.h"
22 #include "IncludeFixer.h"
23 #include "Preamble.h"
24 #include "SourceCode.h"
25 #include "TidyProvider.h"
27 #include "index/Index.h"
28 #include "support/Logger.h"
29 #include "support/Trace.h"
30 #include "clang/AST/ASTContext.h"
31 #include "clang/AST/Decl.h"
32 #include "clang/Basic/Diagnostic.h"
33 #include "clang/Basic/DiagnosticSema.h"
34 #include "clang/Basic/LangOptions.h"
35 #include "clang/Basic/SourceLocation.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Basic/TokenKinds.h"
38 #include "clang/Frontend/CompilerInstance.h"
39 #include "clang/Frontend/CompilerInvocation.h"
40 #include "clang/Frontend/FrontendActions.h"
41 #include "clang/Lex/Lexer.h"
42 #include "clang/Lex/PPCallbacks.h"
43 #include "clang/Lex/Preprocessor.h"
44 #include "clang/Serialization/ASTWriter.h"
45 #include "clang/Tooling/CompilationDatabase.h"
46 #include "clang/Tooling/Syntax/Tokens.h"
47 #include "llvm/ADT/ArrayRef.h"
48 #include "llvm/ADT/STLExtras.h"
49 #include "llvm/ADT/SmallString.h"
50 #include "llvm/ADT/SmallVector.h"
51 #include "llvm/ADT/StringRef.h"
52 #include <algorithm>
53 #include <memory>
54 #include <vector>
55 
56 // Force the linker to link in Clang-tidy modules.
57 // clangd doesn't support the static analyzer.
58 #if CLANGD_TIDY_CHECKS
59 #define CLANG_TIDY_DISABLE_STATIC_ANALYZER_CHECKS
60 #include "../clang-tidy/ClangTidyForceLinker.h"
61 #endif
62 
63 namespace clang {
64 namespace clangd {
65 namespace {
66 
67 template <class T> std::size_t getUsedBytes(const std::vector<T> &Vec) {
68  return Vec.capacity() * sizeof(T);
69 }
70 
71 class DeclTrackingASTConsumer : public ASTConsumer {
72 public:
73  DeclTrackingASTConsumer(std::vector<Decl *> &TopLevelDecls)
74  : TopLevelDecls(TopLevelDecls) {}
75 
76  bool HandleTopLevelDecl(DeclGroupRef DG) override {
77  for (Decl *D : DG) {
78  auto &SM = D->getASTContext().getSourceManager();
79  if (!isInsideMainFile(D->getLocation(), SM))
80  continue;
81  if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
83  continue;
84 
85  // ObjCMethodDecl are not actually top-level decls.
86  if (isa<ObjCMethodDecl>(D))
87  continue;
88 
89  TopLevelDecls.push_back(D);
90  }
91  return true;
92  }
93 
94 private:
95  std::vector<Decl *> &TopLevelDecls;
96 };
97 
98 class ClangdFrontendAction : public SyntaxOnlyAction {
99 public:
100  std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }
101 
102 protected:
103  std::unique_ptr<ASTConsumer>
104  CreateASTConsumer(CompilerInstance &CI, llvm::StringRef InFile) override {
105  return std::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
106  }
107 
108 private:
109  std::vector<Decl *> TopLevelDecls;
110 };
111 
112 // When using a preamble, only preprocessor events outside its bounds are seen.
113 // This is almost what we want: replaying transitive preprocessing wastes time.
114 // However this confuses clang-tidy checks: they don't see any #includes!
115 // So we replay the *non-transitive* #includes that appear in the main-file.
116 // It would be nice to replay other events (macro definitions, ifdefs etc) but
117 // this addresses the most common cases fairly cheaply.
118 class ReplayPreamble : private PPCallbacks {
119 public:
120  // Attach preprocessor hooks such that preamble events will be injected at
121  // the appropriate time.
122  // Events will be delivered to the *currently registered* PP callbacks.
123  static void attach(std::vector<Inclusion> Includes, CompilerInstance &Clang,
124  const PreambleBounds &PB) {
125  auto &PP = Clang.getPreprocessor();
126  auto *ExistingCallbacks = PP.getPPCallbacks();
127  // No need to replay events if nobody is listening.
128  if (!ExistingCallbacks)
129  return;
130  PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(new ReplayPreamble(
131  std::move(Includes), ExistingCallbacks, Clang.getSourceManager(), PP,
132  Clang.getLangOpts(), PB)));
133  // We're relying on the fact that addPPCallbacks keeps the old PPCallbacks
134  // around, creating a chaining wrapper. Guard against other implementations.
135  assert(PP.getPPCallbacks() != ExistingCallbacks &&
136  "Expected chaining implementation");
137  }
138 
139 private:
140  ReplayPreamble(std::vector<Inclusion> Includes, PPCallbacks *Delegate,
141  const SourceManager &SM, Preprocessor &PP,
142  const LangOptions &LangOpts, const PreambleBounds &PB)
143  : Includes(std::move(Includes)), Delegate(Delegate), SM(SM), PP(PP) {
144  // Only tokenize the preamble section of the main file, as we are not
145  // interested in the rest of the tokens.
146  MainFileTokens = syntax::tokenize(
147  syntax::FileRange(SM.getMainFileID(), 0, PB.Size), SM, LangOpts);
148  }
149 
150  // In a normal compile, the preamble traverses the following structure:
151  //
152  // mainfile.cpp
153  // <built-in>
154  // ... macro definitions like __cplusplus ...
155  // <command-line>
156  // ... macro definitions for args like -Dfoo=bar ...
157  // "header1.h"
158  // ... header file contents ...
159  // "header2.h"
160  // ... header file contents ...
161  // ... main file contents ...
162  //
163  // When using a preamble, the "header1" and "header2" subtrees get skipped.
164  // We insert them right after the built-in header, which still appears.
165  void FileChanged(SourceLocation Loc, FileChangeReason Reason,
166  SrcMgr::CharacteristicKind Kind, FileID PrevFID) override {
167  // It'd be nice if there was a better way to identify built-in headers...
168  if (Reason == FileChangeReason::ExitFile &&
169  SM.getBufferOrFake(PrevFID).getBufferIdentifier() == "<built-in>")
170  replay();
171  }
172 
173  void replay() {
174  for (const auto &Inc : Includes) {
175  llvm::Optional<FileEntryRef> File;
176  if (Inc.Resolved != "")
177  File = expectedToOptional(SM.getFileManager().getFileRef(Inc.Resolved));
178 
179  // Re-lex the #include directive to find its interesting parts.
180  auto HashLoc = SM.getComposedLoc(SM.getMainFileID(), Inc.HashOffset);
181  auto HashTok = llvm::partition_point(MainFileTokens,
182  [&HashLoc](const syntax::Token &T) {
183  return T.location() < HashLoc;
184  });
185  assert(HashTok != MainFileTokens.end() && HashTok->kind() == tok::hash);
186 
187  auto IncludeTok = std::next(HashTok);
188  assert(IncludeTok != MainFileTokens.end());
189 
190  auto FileTok = std::next(IncludeTok);
191  assert(FileTok != MainFileTokens.end());
192 
193  // Create a fake import/include token, none of the callers seem to care
194  // about clang::Token::Flags.
195  Token SynthesizedIncludeTok;
196  SynthesizedIncludeTok.startToken();
197  SynthesizedIncludeTok.setLocation(IncludeTok->location());
198  SynthesizedIncludeTok.setLength(IncludeTok->length());
199  SynthesizedIncludeTok.setKind(tok::raw_identifier);
200  SynthesizedIncludeTok.setRawIdentifierData(IncludeTok->text(SM).data());
201  PP.LookUpIdentifierInfo(SynthesizedIncludeTok);
202 
203  // Same here, create a fake one for Filename, including angles or quotes.
204  Token SynthesizedFilenameTok;
205  SynthesizedFilenameTok.startToken();
206  SynthesizedFilenameTok.setLocation(FileTok->location());
207  // Note that we can't make use of FileTok->length/text in here as in the
208  // case of angled includes this will contain tok::less instead of
209  // filename. Whereas Inc.Written contains the full header name including
210  // quotes/angles.
211  SynthesizedFilenameTok.setLength(Inc.Written.length());
212  SynthesizedFilenameTok.setKind(tok::header_name);
213  SynthesizedFilenameTok.setLiteralData(Inc.Written.data());
214 
215  const FileEntry *FE = File ? &File->getFileEntry() : nullptr;
216  llvm::StringRef WrittenFilename =
217  llvm::StringRef(Inc.Written).drop_front().drop_back();
218  Delegate->InclusionDirective(
219  HashTok->location(), SynthesizedIncludeTok, WrittenFilename,
220  Inc.Written.front() == '<',
221  syntax::FileRange(SM, SynthesizedFilenameTok.getLocation(),
222  SynthesizedFilenameTok.getEndLoc())
223  .toCharRange(SM),
224  FE, "SearchPath", "RelPath",
225  /*Imported=*/nullptr, Inc.FileKind);
226  if (File)
227  Delegate->FileSkipped(*File, SynthesizedFilenameTok, Inc.FileKind);
228  else {
229  llvm::SmallString<1> UnusedRecovery;
230  Delegate->FileNotFound(WrittenFilename, UnusedRecovery);
231  }
232  }
233  }
234 
235  const std::vector<Inclusion> Includes;
236  PPCallbacks *Delegate;
237  const SourceManager &SM;
238  Preprocessor &PP;
239  std::vector<syntax::Token> MainFileTokens;
240 };
241 
242 // Find -W<group> and -Wno-<group> options in ExtraArgs and apply them to Diags.
243 //
244 // This is used to handle ExtraArgs in clang-tidy configuration.
245 // We don't use clang's standard handling of this as we want slightly different
246 // behavior (e.g. we want to exclude these from -Wno-error).
247 void applyWarningOptions(llvm::ArrayRef<std::string> ExtraArgs,
248  DiagnosticsEngine &Diags) {
249  for (llvm::StringRef Group : ExtraArgs) {
250  // Only handle args that are of the form -W[no-]<group>.
251  // Other flags are possible but rare and deliberately out of scope.
252  llvm::SmallVector<diag::kind> Members;
253  if (!Group.consume_front("-W") || Group.empty())
254  continue;
255  bool Enable = !Group.consume_front("no-");
256  if (Diags.getDiagnosticIDs()->getDiagnosticsInGroup(
257  diag::Flavor::WarningOrError, Group, Members))
258  continue;
259 
260  // Upgrade (or downgrade) the severity of each diagnostic in the group.
261  // If -Werror is on, newly added warnings will be treated as errors.
262  // We don't want this, so keep track of them to fix afterwards.
263  bool NeedsWerrorExclusion = false;
264  for (diag::kind ID : Members) {
265  if (Enable) {
266  if (Diags.getDiagnosticLevel(ID, SourceLocation()) <
268  Diags.setSeverity(ID, diag::Severity::Warning, SourceLocation());
269  if (Diags.getWarningsAsErrors())
270  NeedsWerrorExclusion = true;
271  }
272  } else {
273  Diags.setSeverity(ID, diag::Severity::Ignored, SourceLocation());
274  }
275  }
276  if (NeedsWerrorExclusion) {
277  // FIXME: there's no API to suppress -Werror for single diagnostics.
278  // In some cases with sub-groups, we may end up erroneously
279  // downgrading diagnostics that were -Werror in the compile command.
280  Diags.setDiagnosticGroupWarningAsError(Group, false);
281  }
282  }
283 }
284 
285 } // namespace
286 
287 llvm::Optional<ParsedAST>
288 ParsedAST::build(llvm::StringRef Filename, const ParseInputs &Inputs,
289  std::unique_ptr<clang::CompilerInvocation> CI,
290  llvm::ArrayRef<Diag> CompilerInvocationDiags,
291  std::shared_ptr<const PreambleData> Preamble) {
292  trace::Span Tracer("BuildAST");
293  SPAN_ATTACH(Tracer, "File", Filename);
294 
295  auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
296  if (Preamble && Preamble->StatCache)
297  VFS = Preamble->StatCache->getConsumingFS(std::move(VFS));
298 
299  assert(CI);
300  // Command-line parsing sets DisableFree to true by default, but we don't want
301  // to leak memory in clangd.
302  CI->getFrontendOpts().DisableFree = false;
303  const PrecompiledPreamble *PreamblePCH =
304  Preamble ? &Preamble->Preamble : nullptr;
305 
306  // This is on-by-default in windows to allow parsing SDK headers, but it
307  // breaks many features. Disable it for the main-file (not preamble).
308  CI->getLangOpts()->DelayedTemplateParsing = false;
309 
310  std::vector<std::unique_ptr<FeatureModule::ASTListener>> ASTListeners;
311  if (Inputs.FeatureModules) {
312  for (auto &M : *Inputs.FeatureModules) {
313  if (auto Listener = M.astListeners())
314  ASTListeners.emplace_back(std::move(Listener));
315  }
316  }
317  StoreDiags ASTDiags;
318  ASTDiags.setDiagCallback(
319  [&ASTListeners](const clang::Diagnostic &D, clangd::Diag &Diag) {
320  llvm::for_each(ASTListeners,
321  [&](const auto &L) { L->sawDiagnostic(D, Diag); });
322  });
323 
324  llvm::Optional<PreamblePatch> Patch;
325  bool PreserveDiags = true;
326  // We might use an ignoring diagnostic consumer if they are going to be
327  // dropped later on to not pay for extra latency by processing them.
328  DiagnosticConsumer *DiagConsumer = &ASTDiags;
329  IgnoreDiagnostics DropDiags;
330  if (Preamble) {
332  Patch->apply(*CI);
333  PreserveDiags = Patch->preserveDiagnostics();
334  if (!PreserveDiags)
335  DiagConsumer = &DropDiags;
336  }
338  std::move(CI), PreamblePCH,
339  llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents, Filename), VFS,
340  *DiagConsumer);
341  if (!Clang) {
342  // The last diagnostic contains information about the reason of this
343  // failure.
344  std::vector<Diag> Diags(ASTDiags.take());
345  elog("Failed to prepare a compiler instance: {0}",
346  !Diags.empty() ? static_cast<DiagBase &>(Diags.back()).Message
347  : "unknown error");
348  return None;
349  }
350  tidy::ClangTidyOptions ClangTidyOpts;
351  if (PreserveDiags) {
352  trace::Span Tracer("ClangTidyOpts");
353  ClangTidyOpts = getTidyOptionsForFile(Inputs.ClangTidyProvider, Filename);
354  dlog("ClangTidy configuration for file {0}: {1}", Filename,
355  tidy::configurationAsText(ClangTidyOpts));
356 
357  // If clang-tidy is configured to emit clang warnings, we should too.
358  //
359  // Such clang-tidy configuration consists of two parts:
360  // - ExtraArgs: ["-Wfoo"] causes clang to produce the warnings
361  // - Checks: "clang-diagnostic-foo" prevents clang-tidy filtering them out
362  //
363  // We treat these as clang warnings, so the Checks part is not relevant.
364  // We must enable the warnings specified in ExtraArgs.
365  //
366  // We *don't* want to change the compile command directly. this can have
367  // too many unexpected effects: breaking the command, interactions with
368  // -- and -Werror, etc. Besides, we've already parsed the command.
369  // Instead we parse the -W<group> flags and handle them directly.
370  auto &Diags = Clang->getDiagnostics();
371  if (ClangTidyOpts.ExtraArgsBefore)
372  applyWarningOptions(*ClangTidyOpts.ExtraArgsBefore, Diags);
373  if (ClangTidyOpts.ExtraArgs)
374  applyWarningOptions(*ClangTidyOpts.ExtraArgs, Diags);
375  } else {
376  // Skips some analysis.
377  Clang->getDiagnosticOpts().IgnoreWarnings = true;
378  }
379 
380  auto Action = std::make_unique<ClangdFrontendAction>();
381  const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
382  if (!Action->BeginSourceFile(*Clang, MainInput)) {
383  log("BeginSourceFile() failed when building AST for {0}",
384  MainInput.getFile());
385  return None;
386  }
387  // If we saw an include guard in the preamble section of the main file,
388  // mark the main-file as include-guarded.
389  // This information is part of the HeaderFileInfo but is not loaded from the
390  // preamble as the file's size is part of its identity and may have changed.
391  // (The rest of HeaderFileInfo is not relevant for our purposes).
392  if (Preamble && Preamble->MainIsIncludeGuarded) {
393  const SourceManager &SM = Clang->getSourceManager();
394  const FileEntry *MainFE = SM.getFileEntryForID(SM.getMainFileID());
395  Clang->getPreprocessor().getHeaderSearchInfo().MarkFileIncludeOnce(MainFE);
396  }
397 
398  // Set up ClangTidy. Must happen after BeginSourceFile() so ASTContext exists.
399  // Clang-tidy has some limitations to ensure reasonable performance:
400  // - checks don't see all preprocessor events in the preamble
401  // - matchers run only over the main-file top-level decls (and can't see
402  // ancestors outside this scope).
403  // In practice almost all checks work well without modifications.
404  std::vector<std::unique_ptr<tidy::ClangTidyCheck>> CTChecks;
405  ast_matchers::MatchFinder CTFinder;
406  llvm::Optional<tidy::ClangTidyContext> CTContext;
407  llvm::Optional<IncludeFixer> FixIncludes;
408  llvm::DenseMap<diag::kind, DiagnosticsEngine::Level> OverriddenSeverity;
409  // No need to run clang-tidy or IncludeFixerif we are not going to surface
410  // diagnostics.
411  if (PreserveDiags) {
412  trace::Span Tracer("ClangTidyInit");
413  tidy::ClangTidyCheckFactories CTFactories;
414  for (const auto &E : tidy::ClangTidyModuleRegistry::entries())
415  E.instantiate()->addCheckFactories(CTFactories);
416  CTContext.emplace(std::make_unique<tidy::DefaultOptionsProvider>(
417  tidy::ClangTidyGlobalOptions(), ClangTidyOpts));
418  CTContext->setDiagnosticsEngine(&Clang->getDiagnostics());
419  CTContext->setASTContext(&Clang->getASTContext());
420  CTContext->setCurrentFile(Filename);
421  CTChecks = CTFactories.createChecks(CTContext.getPointer());
422  llvm::erase_if(CTChecks, [&](const auto &Check) {
423  return !Check->isLanguageVersionSupported(CTContext->getLangOpts());
424  });
425  Preprocessor *PP = &Clang->getPreprocessor();
426  for (const auto &Check : CTChecks) {
427  Check->registerPPCallbacks(Clang->getSourceManager(), PP, PP);
428  Check->registerMatchers(&CTFinder);
429  }
430 
431  // Clang only corrects typos for use of undeclared functions in C if that
432  // use is an error. Include fixer relies on typo correction, so pretend
433  // this is an error. (The actual typo correction is nice too).
434  // We restore the original severity in the level adjuster.
435  // FIXME: It would be better to have a real API for this, but what?
436  for (auto ID : {diag::ext_implicit_function_decl,
437  diag::warn_implicit_function_decl}) {
438  OverriddenSeverity.try_emplace(
439  ID, Clang->getDiagnostics().getDiagnosticLevel(ID, SourceLocation()));
440  Clang->getDiagnostics().setSeverity(ID, diag::Severity::Error,
441  SourceLocation());
442  }
443 
444  const Config &Cfg = Config::current();
445  ASTDiags.setLevelAdjuster([&](DiagnosticsEngine::Level DiagLevel,
446  const clang::Diagnostic &Info) {
447  if (Cfg.Diagnostics.SuppressAll ||
448  isBuiltinDiagnosticSuppressed(Info.getID(), Cfg.Diagnostics.Suppress,
449  Clang->getLangOpts()))
450  return DiagnosticsEngine::Ignored;
451 
452  auto It = OverriddenSeverity.find(Info.getID());
453  if (It != OverriddenSeverity.end())
454  DiagLevel = It->second;
455 
456  if (!CTChecks.empty()) {
457  std::string CheckName = CTContext->getCheckName(Info.getID());
458  bool IsClangTidyDiag = !CheckName.empty();
459  if (IsClangTidyDiag) {
460  if (Cfg.Diagnostics.Suppress.contains(CheckName))
461  return DiagnosticsEngine::Ignored;
462  // Check for suppression comment. Skip the check for diagnostics not
463  // in the main file, because we don't want that function to query the
464  // source buffer for preamble files. For the same reason, we ask
465  // shouldSuppressDiagnostic to avoid I/O.
466  // We let suppression comments take precedence over warning-as-error
467  // to match clang-tidy's behaviour.
468  bool IsInsideMainFile =
469  Info.hasSourceManager() &&
470  isInsideMainFile(Info.getLocation(), Info.getSourceManager());
471  SmallVector<tidy::ClangTidyError, 1> TidySuppressedErrors;
472  if (IsInsideMainFile &&
473  tidy::shouldSuppressDiagnostic(DiagLevel, Info, *CTContext,
474  TidySuppressedErrors,
475  /*AllowIO=*/false,
476  /*EnableNolintBlocks=*/false)) {
477  // FIXME: should we expose the suppression error (invalid use of
478  // NOLINT comments)?
479  return DiagnosticsEngine::Ignored;
480  }
481 
482  // Check for warning-as-error.
483  if (DiagLevel == DiagnosticsEngine::Warning &&
484  CTContext->treatAsError(CheckName)) {
485  return DiagnosticsEngine::Error;
486  }
487  }
488  }
489  return DiagLevel;
490  });
491 
492  // Add IncludeFixer which can recover diagnostics caused by missing includes
493  // (e.g. incomplete type) and attach include insertion fixes to diagnostics.
494  auto BuildDir = VFS->getCurrentWorkingDirectory();
495  if (Inputs.Index && !BuildDir.getError()) {
496  auto Style =
497  getFormatStyleForFile(Filename, Inputs.Contents, *Inputs.TFS);
498  auto Inserter = std::make_shared<IncludeInserter>(
499  Filename, Inputs.Contents, Style, BuildDir.get(),
500  &Clang->getPreprocessor().getHeaderSearchInfo());
501  if (Preamble) {
502  for (const auto &Inc : Preamble->Includes.MainFileIncludes)
503  Inserter->addExisting(Inc);
504  }
505  FixIncludes.emplace(Filename, Inserter, *Inputs.Index,
506  /*IndexRequestLimit=*/5);
507  ASTDiags.contributeFixes([&FixIncludes](DiagnosticsEngine::Level DiagLevl,
508  const clang::Diagnostic &Info) {
509  return FixIncludes->fix(DiagLevl, Info);
510  });
511  Clang->setExternalSemaSource(FixIncludes->unresolvedNameRecorder());
512  }
513  }
514 
515  IncludeStructure Includes;
516  // If we are using a preamble, copy existing includes.
517  if (Preamble) {
518  Includes = Preamble->Includes;
519  Includes.MainFileIncludes = Patch->preambleIncludes();
520  // Replay the preamble includes so that clang-tidy checks can see them.
521  ReplayPreamble::attach(Patch->preambleIncludes(), *Clang,
522  Patch->modifiedBounds());
523  }
524  // Important: collectIncludeStructure is registered *after* ReplayPreamble!
525  // Otherwise we would collect the replayed includes again...
526  // (We can't *just* use the replayed includes, they don't have Resolved path).
527  Includes.collect(*Clang);
528  // Copy over the macros in the preamble region of the main file, and combine
529  // with non-preamble macros below.
530  MainFileMacros Macros;
531  if (Preamble)
533  Clang->getPreprocessor().addPPCallbacks(
534  std::make_unique<CollectMainFileMacros>(Clang->getSourceManager(),
535  Macros));
536 
537  std::vector<PragmaMark> Marks;
538  // FIXME: We need to patch the marks for stale preambles.
539  if (Preamble)
540  Marks = Preamble->Marks;
541  Clang->getPreprocessor().addPPCallbacks(
542  collectPragmaMarksCallback(Clang->getSourceManager(), Marks));
543 
544  // Copy over the includes from the preamble, then combine with the
545  // non-preamble includes below.
546  CanonicalIncludes CanonIncludes;
547  if (Preamble)
548  CanonIncludes = Preamble->CanonIncludes;
549  else
550  CanonIncludes.addSystemHeadersMapping(Clang->getLangOpts());
551  std::unique_ptr<CommentHandler> IWYUHandler =
552  collectIWYUHeaderMaps(&CanonIncludes);
553  Clang->getPreprocessor().addCommentHandler(IWYUHandler.get());
554 
555  // Collect tokens of the main file.
556  syntax::TokenCollector CollectTokens(Clang->getPreprocessor());
557 
558  if (llvm::Error Err = Action->Execute())
559  log("Execute() failed when building AST for {0}: {1}", MainInput.getFile(),
560  toString(std::move(Err)));
561 
562  // We have to consume the tokens before running clang-tidy to avoid collecting
563  // tokens from running the preprocessor inside the checks (only
564  // modernize-use-trailing-return-type does that today).
565  syntax::TokenBuffer Tokens = std::move(CollectTokens).consume();
566  // Makes SelectionTree build much faster.
567  Tokens.indexExpandedTokens();
568  std::vector<Decl *> ParsedDecls = Action->takeTopLevelDecls();
569  // AST traversals should exclude the preamble, to avoid performance cliffs.
570  Clang->getASTContext().setTraversalScope(ParsedDecls);
571  if (!CTChecks.empty()) {
572  // Run the AST-dependent part of the clang-tidy checks.
573  // (The preprocessor part ran already, via PPCallbacks).
574  trace::Span Tracer("ClangTidyMatch");
575  CTFinder.matchAST(Clang->getASTContext());
576  }
577 
578  // XXX: This is messy: clang-tidy checks flush some diagnostics at EOF.
579  // However Action->EndSourceFile() would destroy the ASTContext!
580  // So just inform the preprocessor of EOF, while keeping everything alive.
581  Clang->getPreprocessor().EndSourceFile();
582  // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
583  // has a longer lifetime.
584  Clang->getDiagnostics().setClient(new IgnoreDiagnostics);
585  // CompilerInstance won't run this callback, do it directly.
586  ASTDiags.EndSourceFile();
587 
588  llvm::Optional<std::vector<Diag>> Diags;
589  // FIXME: Also skip generation of diagnostics alltogether to speed up ast
590  // builds when we are patching a stale preamble.
591  if (PreserveDiags) {
592  Diags = CompilerInvocationDiags;
593  // Add diagnostics from the preamble, if any.
594  if (Preamble)
595  Diags->insert(Diags->end(), Preamble->Diags.begin(),
596  Preamble->Diags.end());
597  // Finally, add diagnostics coming from the AST.
598  {
599  std::vector<Diag> D = ASTDiags.take(CTContext.getPointer());
600  Diags->insert(Diags->end(), D.begin(), D.end());
601  }
602  }
603  ParsedAST Result(Inputs.Version, std::move(Preamble), std::move(Clang),
604  std::move(Action), std::move(Tokens), std::move(Macros),
605  std::move(Marks), std::move(ParsedDecls), std::move(Diags),
606  std::move(Includes), std::move(CanonIncludes));
607  if (Result.Diags) {
608  auto UnusedHeadersDiags =
610  Result.Diags->insert(Result.Diags->end(),
611  make_move_iterator(UnusedHeadersDiags.begin()),
612  make_move_iterator(UnusedHeadersDiags.end()));
613  }
614  return Result;
615 }
616 
617 ParsedAST::ParsedAST(ParsedAST &&Other) = default;
618 
619 ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
620 
621 ParsedAST::~ParsedAST() {
622  if (Action) {
623  // We already notified the PP of end-of-file earlier, so detach it first.
624  // We must keep it alive until after EndSourceFile(), Sema relies on this.
625  auto PP = Clang->getPreprocessorPtr(); // Keep PP alive for now.
626  Clang->setPreprocessor(nullptr); // Detach so we don't send EOF again.
627  Action->EndSourceFile(); // Destroy ASTContext and Sema.
628  // Now Sema is gone, it's safe for PP to go out of scope.
629  }
630 }
631 
632 ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
633 
634 const ASTContext &ParsedAST::getASTContext() const {
635  return Clang->getASTContext();
636 }
637 
638 Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
639 
640 std::shared_ptr<Preprocessor> ParsedAST::getPreprocessorPtr() {
641  return Clang->getPreprocessorPtr();
642 }
643 
644 const Preprocessor &ParsedAST::getPreprocessor() const {
645  return Clang->getPreprocessor();
646 }
647 
648 llvm::ArrayRef<Decl *> ParsedAST::getLocalTopLevelDecls() {
649  return LocalTopLevelDecls;
650 }
651 
652 const MainFileMacros &ParsedAST::getMacros() const { return Macros; }
653 const std::vector<PragmaMark> &ParsedAST::getMarks() const { return Marks; }
654 
655 std::size_t ParsedAST::getUsedBytes() const {
656  auto &AST = getASTContext();
657  // FIXME(ibiryukov): we do not account for the dynamically allocated part of
658  // Message and Fixes inside each diagnostic.
659  std::size_t Total = clangd::getUsedBytes(LocalTopLevelDecls) +
660  (Diags ? clangd::getUsedBytes(*Diags) : 0);
661 
662  // FIXME: the rest of the function is almost a direct copy-paste from
663  // libclang's clang_getCXTUResourceUsage. We could share the implementation.
664 
665  // Sum up various allocators inside the ast context and the preprocessor.
666  Total += AST.getASTAllocatedMemory();
667  Total += AST.getSideTableAllocatedMemory();
668  Total += AST.Idents.getAllocator().getTotalMemory();
669  Total += AST.Selectors.getTotalMemory();
670 
671  Total += AST.getSourceManager().getContentCacheSize();
672  Total += AST.getSourceManager().getDataStructureSizes();
673  Total += AST.getSourceManager().getMemoryBufferSizes().malloc_bytes;
674 
675  if (ExternalASTSource *Ext = AST.getExternalSource())
676  Total += Ext->getMemoryBufferSizes().malloc_bytes;
677 
678  const Preprocessor &PP = getPreprocessor();
679  Total += PP.getTotalMemory();
680  if (PreprocessingRecord *PRec = PP.getPreprocessingRecord())
681  Total += PRec->getTotalMemory();
682  Total += PP.getHeaderSearchInfo().getTotalMemory();
683 
684  return Total;
685 }
686 
687 const IncludeStructure &ParsedAST::getIncludeStructure() const {
688  return Includes;
689 }
690 
691 const CanonicalIncludes &ParsedAST::getCanonicalIncludes() const {
692  return CanonIncludes;
693 }
694 
695 ParsedAST::ParsedAST(llvm::StringRef Version,
696  std::shared_ptr<const PreambleData> Preamble,
697  std::unique_ptr<CompilerInstance> Clang,
698  std::unique_ptr<FrontendAction> Action,
699  syntax::TokenBuffer Tokens, MainFileMacros Macros,
700  std::vector<PragmaMark> Marks,
701  std::vector<Decl *> LocalTopLevelDecls,
702  llvm::Optional<std::vector<Diag>> Diags,
703  IncludeStructure Includes, CanonicalIncludes CanonIncludes)
704  : Version(Version), Preamble(std::move(Preamble)), Clang(std::move(Clang)),
705  Action(std::move(Action)), Tokens(std::move(Tokens)),
706  Macros(std::move(Macros)), Marks(std::move(Marks)),
707  Diags(std::move(Diags)),
708  LocalTopLevelDecls(std::move(LocalTopLevelDecls)),
709  Includes(std::move(Includes)), CanonIncludes(std::move(CanonIncludes)) {
710  Resolver = std::make_unique<HeuristicResolver>(getASTContext());
711  assert(this->Clang);
712  assert(this->Action);
713 }
714 
715 llvm::Optional<llvm::StringRef> ParsedAST::preambleVersion() const {
716  if (!Preamble)
717  return llvm::None;
718  return llvm::StringRef(Preamble->Version);
719 }
720 
721 } // namespace clangd
722 } // namespace clang
clang::clangd::CanonicalIncludes::addSystemHeadersMapping
void addSystemHeadersMapping(const LangOptions &Language)
Adds mapping for system headers and some special symbols (e.g.
Definition: CanonicalIncludes.cpp:84
dlog
#define dlog(...)
Definition: Logger.h:102
clang::clangd::ParseInputs::Version
std::string Version
Definition: Compiler.h:52
Total
unsigned Total
Definition: FunctionCognitiveComplexityCheck.cpp:145
clang::clangd::IncludeStructure::collect
void collect(const CompilerInstance &CI)
Definition: Headers.cpp:212
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
SyntaxOnlyAction
Headers.h
IncludeCleaner.h
E
const Expr * E
Definition: AvoidBindCheck.cpp:88
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:114
clang::clangd::ParseInputs::Contents
std::string Contents
Definition: Compiler.h:50
Macros
llvm::DenseSet< FileID > Macros
Definition: IncludeCleaner.cpp:171
Tracer
std::unique_ptr< trace::EventTracer > Tracer
Definition: TraceTests.cpp:164
DiagnosticConsumer
clang::clangd::getTidyOptionsForFile
tidy::ClangTidyOptions getTidyOptionsForFile(TidyProviderRef Provider, llvm::StringRef Filename)
Definition: TidyProvider.cpp:279
clang::clangd::ParsedAST::getASTContext
ASTContext & getASTContext()
Note that the returned ast will not contain decls from the preamble that were not deserialized during...
Definition: ParsedAST.cpp:632
clang::clangd::isImplicitTemplateInstantiation
bool isImplicitTemplateInstantiation(const NamedDecl *D)
Indicates if D is a template instantiation implicitly generated by the compiler, e....
Definition: AST.cpp:154
clang::clangd::PreambleData::Macros
MainFileMacros Macros
Definition: Preamble.h:63
Index.h
clang::clangd::issueUnusedIncludesDiagnostics
std::vector< Diag > issueUnusedIncludesDiagnostics(ParsedAST &AST, llvm::StringRef Code)
Definition: IncludeCleaner.cpp:395
CI
std::unique_ptr< CompilerInvocation > CI
Definition: TUScheduler.cpp:456
Kind
BindArgumentKind Kind
Definition: AvoidBindCheck.cpp:59
Filename
std::string Filename
Filename as a string.
Definition: IncludeOrderCheck.cpp:39
Preamble.h
Feature.h
Trace.h
clang::tidy::ClangTidyOptions::ExtraArgsBefore
llvm::Optional< ArgList > ExtraArgsBefore
Add extra compilation arguments to the start of the list.
Definition: ClangTidyOptions.h:126
clang::clangd::Config
Settings that express user/project preferences and control clangd behavior.
Definition: Config.h:43
clang::clangd::PreambleData::Includes
IncludeStructure Includes
Definition: Preamble.h:59
IncludeFixer.h
Action
llvm::unique_function< void()> Action
Definition: TUScheduler.cpp:604
clang::clangd::IncludeStructure::MainFileIncludes
std::vector< Inclusion > MainFileIncludes
Definition: Headers.h:236
clang::tidy::ClangTidyOptions
Contains options for clang-tidy.
Definition: ClangTidyOptions.h:50
Preamble
const PreambleData & Preamble
Definition: CodeComplete.cpp:1193
clang::tidy::ClangTidyCheckFactories
A collection of ClangTidyCheckFactory instances.
Definition: ClangTidyModule.h:28
M
const google::protobuf::Message & M
Definition: Server.cpp:309
clang::clangd::ParsedAST::build
static llvm::Optional< ParsedAST > build(llvm::StringRef Filename, const ParseInputs &Inputs, std::unique_ptr< clang::CompilerInvocation > CI, llvm::ArrayRef< Diag > CompilerInvocationDiags, std::shared_ptr< const PreambleData > Preamble)
Attempts to run Clang and store the parsed AST.
Definition: ParsedAST.cpp:288
clang::clangd::IncludeStructure
Definition: Headers.h:192
Error
constexpr static llvm::SourceMgr::DiagKind Error
Definition: ConfigCompile.cpp:546
Inputs
ParseInputs Inputs
Definition: TUScheduler.cpp:457
clang::clangd::ParseInputs
Information required to run clang, e.g. to parse AST or do code completion.
Definition: Compiler.h:47
CanonicalIncludes.h
ns1::ns2::D
@ D
Definition: CategoricalFeature.h:3
Diagnostic
DiagnosticCallback Diagnostic
Definition: ConfigCompile.cpp:101
clang::clangd::DiagBase::Message
std::string Message
Definition: Diagnostics.h:62
Decl
const FunctionDecl * Decl
Definition: AvoidBindCheck.cpp:100
clang::clangd::CanonicalIncludes
Maps a definition location onto an #include file, based on a set of filename rules.
Definition: CanonicalIncludes.h:36
TidyProvider.h
clang::clangd::Diag
A top-level diagnostic that may have Notes and Fixes.
Definition: Diagnostics.h:97
Logger.h
clang::clangd::MainFileMacros
Definition: CollectMacros.h:31
if
if(CLANGD_ENABLE_REMOTE) generate_protos(RemoteIndexProto "Index.proto") generate_protos(MonitoringServiceProto "MonitoringService.proto" GRPC) generate_protos(RemoteIndexServiceProto "Service.proto" DEPENDS "Index.proto" GRPC) target_link_libraries(RemoteIndexServiceProto PRIVATE RemoteIndexProto MonitoringServiceProto) include_directories($
Definition: clangd/index/remote/CMakeLists.txt:1
clang::clangd::collectPragmaMarksCallback
std::unique_ptr< PPCallbacks > collectPragmaMarksCallback(const SourceManager &SM, std::vector< PragmaMark > &Out)
Collect all pragma marks from the main file.
Definition: CollectMacros.cpp:56
Patch
const llvm::Optional< PreamblePatch > Patch
Definition: CodeComplete.cpp:1194
clang::clangd::PreambleData::Diags
std::vector< Diag > Diags
Definition: Preamble.h:56
SPAN_ATTACH
#define SPAN_ATTACH(S, Name, Expr)
Attach a key-value pair to a Span event.
Definition: Trace.h:164
clang::clangd::toString
static const char * toString(OffsetEncoding OE)
Definition: Protocol.cpp:1348
Diagnostics.h
clang::tidy::configurationAsText
std::string configurationAsText(const ClangTidyOptions &Options)
Serializes configuration to a YAML-encoded string.
Definition: ClangTidyOptions.cpp:409
clang::clangd::PreambleData::Marks
std::vector< PragmaMark > Marks
Definition: Preamble.h:65
clang::clangd::getFormatStyleForFile
format::FormatStyle getFormatStyleForFile(llvm::StringRef File, llvm::StringRef Content, const ThreadsafeFS &TFS)
Choose the clang-format style we should apply to a certain file.
Definition: SourceCode.cpp:580
clang::clangd::log
void log(const char *Fmt, Ts &&... Vals)
Definition: Logger.h:68
clang::tidy::ClangTidyGlobalOptions
Global options.
Definition: ClangTidyOptions.h:42
SourceCode.h
HeuristicResolver.h
clang::clangd::StoreDiags::contributeFixes
void contributeFixes(DiagFixer Fixer)
If set, possibly adds fixes for diagnostics using Fixer.
Definition: Diagnostics.h:156
Config.h
Compiler.h
FeatureModule.h
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:545
Info
FunctionInfo Info
Definition: FunctionSizeCheck.cpp:120
ID
static char ID
Definition: Logger.cpp:74
ASTConsumer
PPCallbacks
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
clang::clangd::isInsideMainFile
bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM)
Returns true iff Loc is inside the main file.
Definition: SourceCode.cpp:417
clang::clangd::StoreDiags::setDiagCallback
void setDiagCallback(DiagCallback CB)
Invokes a callback every time a diagnostics is completely formed.
Definition: Diagnostics.h:163
clang::clangd::StoreDiags
StoreDiags collects the diagnostics that can later be reported by clangd.
Definition: Diagnostics.h:136
Diags
CapturedDiags Diags
Definition: ConfigCompileTests.cpp:38
clang::clangd::Config::current
static const Config & current()
Returns the Config of the current Context, or an empty configuration.
Definition: Config.cpp:17
clang::clangd::PreambleData::CanonIncludes
CanonicalIncludes CanonIncludes
Definition: Preamble.h:69
clang::tidy::ClangTidyCheckFactories::createChecks
std::vector< std::unique_ptr< ClangTidyCheck > > createChecks(ClangTidyContext *Context)
Create instances of checks that are enabled.
Definition: ClangTidyModule.cpp:25
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:160
clang::clangd::elog
void elog(const char *Fmt, Ts &&... Vals)
Definition: Logger.h:62
clang::clangd::DiagBase
Contains basic information about a diagnostic.
Definition: Diagnostics.h:61
Warning
constexpr static llvm::SourceMgr::DiagKind Warning
Definition: ConfigCompile.cpp:547
clang::clangd::isBuiltinDiagnosticSuppressed
bool isBuiltinDiagnosticSuppressed(unsigned ID, const llvm::StringSet<> &Suppress, const LangOptions &LangOpts)
Determine whether a (non-clang-tidy) diagnostic is suppressed by config.
Definition: Diagnostics.cpp:884
clang::clangd::StoreDiags::take
std::vector< Diag > take(const clang::tidy::ClangTidyContext *Tidy=nullptr)
Definition: Diagnostics.cpp:562
clang::clangd::ParsedAST::preambleVersion
llvm::Optional< llvm::StringRef > preambleVersion() const
Returns the version of the ParseInputs used to build Preamble part of this AST.
Definition: ParsedAST.cpp:715
clang::tidy::ClangTidyOptions::ExtraArgs
llvm::Optional< ArgList > ExtraArgs
Add extra compilation arguments to the end of the list.
Definition: ClangTidyOptions.h:123
Clang
std::unique_ptr< CompilerInstance > Clang
Definition: HeadersTests.cpp:139
clang::clangd::IgnoreDiagnostics
Definition: Compiler.h:32
AST.h
ParsedAST.h
clang::clangd::trace::Span
Records an event whose duration is the lifetime of the Span object.
Definition: Trace.h:143