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 "../clang-tidy/NoLintDirectiveHandler.h"
14 #include "AST.h"
15 #include "Compiler.h"
16 #include "Config.h"
17 #include "Diagnostics.h"
18 #include "Feature.h"
19 #include "FeatureModule.h"
20 #include "Headers.h"
21 #include "HeuristicResolver.h"
22 #include "IncludeCleaner.h"
23 #include "IncludeFixer.h"
24 #include "Preamble.h"
25 #include "SourceCode.h"
26 #include "TidyProvider.h"
27 #include "index/CanonicalIncludes.h"
28 #include "index/Index.h"
29 #include "support/Logger.h"
30 #include "support/Trace.h"
31 #include "clang/AST/ASTContext.h"
32 #include "clang/AST/Decl.h"
33 #include "clang/Basic/Diagnostic.h"
34 #include "clang/Basic/DiagnosticSema.h"
35 #include "clang/Basic/LangOptions.h"
36 #include "clang/Basic/SourceLocation.h"
37 #include "clang/Basic/SourceManager.h"
38 #include "clang/Basic/TokenKinds.h"
39 #include "clang/Frontend/CompilerInstance.h"
40 #include "clang/Frontend/CompilerInvocation.h"
41 #include "clang/Frontend/FrontendActions.h"
42 #include "clang/Lex/Lexer.h"
43 #include "clang/Lex/PPCallbacks.h"
44 #include "clang/Lex/Preprocessor.h"
45 #include "clang/Serialization/ASTWriter.h"
46 #include "clang/Tooling/CompilationDatabase.h"
47 #include "clang/Tooling/Syntax/Tokens.h"
48 #include "llvm/ADT/ArrayRef.h"
49 #include "llvm/ADT/STLExtras.h"
50 #include "llvm/ADT/SmallString.h"
51 #include "llvm/ADT/SmallVector.h"
52 #include "llvm/ADT/StringRef.h"
53 #include <algorithm>
54 #include <memory>
55 #include <vector>
56 
57 // Force the linker to link in Clang-tidy modules.
58 // clangd doesn't support the static analyzer.
59 #if CLANGD_TIDY_CHECKS
60 #define CLANG_TIDY_DISABLE_STATIC_ANALYZER_CHECKS
61 #include "../clang-tidy/ClangTidyForceLinker.h"
62 #endif
63 
64 namespace clang {
65 namespace clangd {
66 namespace {
67 
68 template <class T> std::size_t getUsedBytes(const std::vector<T> &Vec) {
69   return Vec.capacity() * sizeof(T);
70 }
71 
72 class DeclTrackingASTConsumer : public ASTConsumer {
73 public:
74   DeclTrackingASTConsumer(std::vector<Decl *> &TopLevelDecls)
75       : TopLevelDecls(TopLevelDecls) {}
76 
77   bool HandleTopLevelDecl(DeclGroupRef DG) override {
78     for (Decl *D : DG) {
79       auto &SM = D->getASTContext().getSourceManager();
80       if (!isInsideMainFile(D->getLocation(), SM))
81         continue;
82       if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
83         if (isImplicitTemplateInstantiation(ND))
84           continue;
85 
86       // ObjCMethodDecl are not actually top-level decls.
87       if (isa<ObjCMethodDecl>(D))
88         continue;
89 
90       TopLevelDecls.push_back(D);
91     }
92     return true;
93   }
94 
95 private:
96   std::vector<Decl *> &TopLevelDecls;
97 };
98 
99 class ClangdFrontendAction : public SyntaxOnlyAction {
100 public:
101   std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }
102 
103 protected:
104   std::unique_ptr<ASTConsumer>
105   CreateASTConsumer(CompilerInstance &CI, llvm::StringRef InFile) override {
106     return std::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
107   }
108 
109 private:
110   std::vector<Decl *> TopLevelDecls;
111 };
112 
113 // When using a preamble, only preprocessor events outside its bounds are seen.
114 // This is almost what we want: replaying transitive preprocessing wastes time.
115 // However this confuses clang-tidy checks: they don't see any #includes!
116 // So we replay the *non-transitive* #includes that appear in the main-file.
117 // It would be nice to replay other events (macro definitions, ifdefs etc) but
118 // this addresses the most common cases fairly cheaply.
119 class ReplayPreamble : private PPCallbacks {
120 public:
121   // Attach preprocessor hooks such that preamble events will be injected at
122   // the appropriate time.
123   // Events will be delivered to the *currently registered* PP callbacks.
124   static void attach(std::vector<Inclusion> Includes, CompilerInstance &Clang,
125                      const PreambleBounds &PB) {
126     auto &PP = Clang.getPreprocessor();
127     auto *ExistingCallbacks = PP.getPPCallbacks();
128     // No need to replay events if nobody is listening.
129     if (!ExistingCallbacks)
130       return;
131     PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(new ReplayPreamble(
132         std::move(Includes), ExistingCallbacks, Clang.getSourceManager(), PP,
133         Clang.getLangOpts(), PB)));
134     // We're relying on the fact that addPPCallbacks keeps the old PPCallbacks
135     // around, creating a chaining wrapper. Guard against other implementations.
136     assert(PP.getPPCallbacks() != ExistingCallbacks &&
137            "Expected chaining implementation");
138   }
139 
140 private:
141   ReplayPreamble(std::vector<Inclusion> Includes, PPCallbacks *Delegate,
142                  const SourceManager &SM, Preprocessor &PP,
143                  const LangOptions &LangOpts, const PreambleBounds &PB)
144       : Includes(std::move(Includes)), Delegate(Delegate), SM(SM), PP(PP) {
145     // Only tokenize the preamble section of the main file, as we are not
146     // interested in the rest of the tokens.
147     MainFileTokens = syntax::tokenize(
148         syntax::FileRange(SM.getMainFileID(), 0, PB.Size), SM, LangOpts);
149   }
150 
151   // In a normal compile, the preamble traverses the following structure:
152   //
153   // mainfile.cpp
154   //   <built-in>
155   //     ... macro definitions like __cplusplus ...
156   //     <command-line>
157   //       ... macro definitions for args like -Dfoo=bar ...
158   //   "header1.h"
159   //     ... header file contents ...
160   //   "header2.h"
161   //     ... header file contents ...
162   //   ... main file contents ...
163   //
164   // When using a preamble, the "header1" and "header2" subtrees get skipped.
165   // We insert them right after the built-in header, which still appears.
166   void FileChanged(SourceLocation Loc, FileChangeReason Reason,
167                    SrcMgr::CharacteristicKind Kind, FileID PrevFID) override {
168     // It'd be nice if there was a better way to identify built-in headers...
169     if (Reason == FileChangeReason::ExitFile &&
170         SM.getBufferOrFake(PrevFID).getBufferIdentifier() == "<built-in>")
171       replay();
172   }
173 
174   void replay() {
175     for (const auto &Inc : Includes) {
176       llvm::Optional<FileEntryRef> File;
177       if (Inc.Resolved != "")
178         File = expectedToOptional(SM.getFileManager().getFileRef(Inc.Resolved));
179 
180       // Re-lex the #include directive to find its interesting parts.
181       auto HashLoc = SM.getComposedLoc(SM.getMainFileID(), Inc.HashOffset);
182       auto HashTok = llvm::partition_point(MainFileTokens,
183                                            [&HashLoc](const syntax::Token &T) {
184                                              return T.location() < HashLoc;
185                                            });
186       assert(HashTok != MainFileTokens.end() && HashTok->kind() == tok::hash);
187 
188       auto IncludeTok = std::next(HashTok);
189       assert(IncludeTok != MainFileTokens.end());
190 
191       auto FileTok = std::next(IncludeTok);
192       assert(FileTok != MainFileTokens.end());
193 
194       // Create a fake import/include token, none of the callers seem to care
195       // about clang::Token::Flags.
196       Token SynthesizedIncludeTok;
197       SynthesizedIncludeTok.startToken();
198       SynthesizedIncludeTok.setLocation(IncludeTok->location());
199       SynthesizedIncludeTok.setLength(IncludeTok->length());
200       SynthesizedIncludeTok.setKind(tok::raw_identifier);
201       SynthesizedIncludeTok.setRawIdentifierData(IncludeTok->text(SM).data());
202       PP.LookUpIdentifierInfo(SynthesizedIncludeTok);
203 
204       // Same here, create a fake one for Filename, including angles or quotes.
205       Token SynthesizedFilenameTok;
206       SynthesizedFilenameTok.startToken();
207       SynthesizedFilenameTok.setLocation(FileTok->location());
208       // Note that we can't make use of FileTok->length/text in here as in the
209       // case of angled includes this will contain tok::less instead of
210       // filename. Whereas Inc.Written contains the full header name including
211       // quotes/angles.
212       SynthesizedFilenameTok.setLength(Inc.Written.length());
213       SynthesizedFilenameTok.setKind(tok::header_name);
214       SynthesizedFilenameTok.setLiteralData(Inc.Written.data());
215 
216       const FileEntry *FE = File ? &File->getFileEntry() : nullptr;
217       llvm::StringRef WrittenFilename =
218           llvm::StringRef(Inc.Written).drop_front().drop_back();
219       Delegate->InclusionDirective(
220           HashTok->location(), SynthesizedIncludeTok, WrittenFilename,
221           Inc.Written.front() == '<',
222           syntax::FileRange(SM, SynthesizedFilenameTok.getLocation(),
223                             SynthesizedFilenameTok.getEndLoc())
224               .toCharRange(SM),
225           FE, "SearchPath", "RelPath",
226           /*Imported=*/nullptr, Inc.FileKind);
227       if (File)
228         Delegate->FileSkipped(*File, SynthesizedFilenameTok, Inc.FileKind);
229       else {
230         llvm::SmallString<1> UnusedRecovery;
231         Delegate->FileNotFound(WrittenFilename, UnusedRecovery);
232       }
233     }
234   }
235 
236   const std::vector<Inclusion> Includes;
237   PPCallbacks *Delegate;
238   const SourceManager &SM;
239   Preprocessor &PP;
240   std::vector<syntax::Token> MainFileTokens;
241 };
242 
243 // Find -W<group> and -Wno-<group> options in ExtraArgs and apply them to Diags.
244 //
245 // This is used to handle ExtraArgs in clang-tidy configuration.
246 // We don't use clang's standard handling of this as we want slightly different
247 // behavior (e.g. we want to exclude these from -Wno-error).
248 void applyWarningOptions(llvm::ArrayRef<std::string> ExtraArgs,
249                          DiagnosticsEngine &Diags) {
250   for (llvm::StringRef Group : ExtraArgs) {
251     // Only handle args that are of the form -W[no-]<group>.
252     // Other flags are possible but rare and deliberately out of scope.
253     llvm::SmallVector<diag::kind> Members;
254     if (!Group.consume_front("-W") || Group.empty())
255       continue;
256     bool Enable = !Group.consume_front("no-");
257     if (Diags.getDiagnosticIDs()->getDiagnosticsInGroup(
258             diag::Flavor::WarningOrError, Group, Members))
259       continue;
260 
261     // Upgrade (or downgrade) the severity of each diagnostic in the group.
262     // If -Werror is on, newly added warnings will be treated as errors.
263     // We don't want this, so keep track of them to fix afterwards.
264     bool NeedsWerrorExclusion = false;
265     for (diag::kind ID : Members) {
266       if (Enable) {
267         if (Diags.getDiagnosticLevel(ID, SourceLocation()) <
268             DiagnosticsEngine::Warning) {
269           Diags.setSeverity(ID, diag::Severity::Warning, SourceLocation());
270           if (Diags.getWarningsAsErrors())
271             NeedsWerrorExclusion = true;
272         }
273       } else {
274         Diags.setSeverity(ID, diag::Severity::Ignored, SourceLocation());
275       }
276     }
277     if (NeedsWerrorExclusion) {
278       // FIXME: there's no API to suppress -Werror for single diagnostics.
279       // In some cases with sub-groups, we may end up erroneously
280       // downgrading diagnostics that were -Werror in the compile command.
281       Diags.setDiagnosticGroupWarningAsError(Group, false);
282     }
283   }
284 }
285 
286 } // namespace
287 
288 llvm::Optional<ParsedAST>
289 ParsedAST::build(llvm::StringRef Filename, const ParseInputs &Inputs,
290                  std::unique_ptr<clang::CompilerInvocation> CI,
291                  llvm::ArrayRef<Diag> CompilerInvocationDiags,
292                  std::shared_ptr<const PreambleData> Preamble) {
293   trace::Span Tracer("BuildAST");
294   SPAN_ATTACH(Tracer, "File", Filename);
295 
296   auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
297   if (Preamble && Preamble->StatCache)
298     VFS = Preamble->StatCache->getConsumingFS(std::move(VFS));
299 
300   assert(CI);
301   // Command-line parsing sets DisableFree to true by default, but we don't want
302   // to leak memory in clangd.
303   CI->getFrontendOpts().DisableFree = false;
304   const PrecompiledPreamble *PreamblePCH =
305       Preamble ? &Preamble->Preamble : nullptr;
306 
307   // This is on-by-default in windows to allow parsing SDK headers, but it
308   // breaks many features. Disable it for the main-file (not preamble).
309   CI->getLangOpts()->DelayedTemplateParsing = false;
310 
311   std::vector<std::unique_ptr<FeatureModule::ASTListener>> ASTListeners;
312   if (Inputs.FeatureModules) {
313     for (auto &M : *Inputs.FeatureModules) {
314       if (auto Listener = M.astListeners())
315         ASTListeners.emplace_back(std::move(Listener));
316     }
317   }
318   StoreDiags ASTDiags;
319   ASTDiags.setDiagCallback(
320       [&ASTListeners](const clang::Diagnostic &D, clangd::Diag &Diag) {
321         llvm::for_each(ASTListeners,
322                        [&](const auto &L) { L->sawDiagnostic(D, Diag); });
323       });
324 
325   llvm::Optional<PreamblePatch> Patch;
326   bool PreserveDiags = true;
327   // We might use an ignoring diagnostic consumer if they are going to be
328   // dropped later on to not pay for extra latency by processing them.
329   DiagnosticConsumer *DiagConsumer = &ASTDiags;
330   IgnoreDiagnostics DropDiags;
331   if (Preamble) {
332     Patch = PreamblePatch::createFullPatch(Filename, Inputs, *Preamble);
333     Patch->apply(*CI);
334     PreserveDiags = Patch->preserveDiagnostics();
335     if (!PreserveDiags)
336       DiagConsumer = &DropDiags;
337   }
338   auto Clang = prepareCompilerInstance(
339       std::move(CI), PreamblePCH,
340       llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents, Filename), VFS,
341       *DiagConsumer);
342   if (!Clang) {
343     // The last diagnostic contains information about the reason of this
344     // failure.
345     std::vector<Diag> Diags(ASTDiags.take());
346     elog("Failed to prepare a compiler instance: {0}",
347          !Diags.empty() ? static_cast<DiagBase &>(Diags.back()).Message
348                         : "unknown error");
349     return None;
350   }
351   tidy::ClangTidyOptions ClangTidyOpts;
352   if (PreserveDiags) {
353     trace::Span Tracer("ClangTidyOpts");
354     ClangTidyOpts = getTidyOptionsForFile(Inputs.ClangTidyProvider, Filename);
355     dlog("ClangTidy configuration for file {0}: {1}", Filename,
356          tidy::configurationAsText(ClangTidyOpts));
357 
358     // If clang-tidy is configured to emit clang warnings, we should too.
359     //
360     // Such clang-tidy configuration consists of two parts:
361     //   - ExtraArgs: ["-Wfoo"] causes clang to produce the warnings
362     //   - Checks: "clang-diagnostic-foo" prevents clang-tidy filtering them out
363     //
364     // We treat these as clang warnings, so the Checks part is not relevant.
365     // We must enable the warnings specified in ExtraArgs.
366     //
367     // We *don't* want to change the compile command directly. this can have
368     // too many unexpected effects: breaking the command, interactions with
369     // -- and -Werror, etc. Besides, we've already parsed the command.
370     // Instead we parse the -W<group> flags and handle them directly.
371     auto &Diags = Clang->getDiagnostics();
372     if (ClangTidyOpts.ExtraArgsBefore)
373       applyWarningOptions(*ClangTidyOpts.ExtraArgsBefore, Diags);
374     if (ClangTidyOpts.ExtraArgs)
375       applyWarningOptions(*ClangTidyOpts.ExtraArgs, Diags);
376   } else {
377     // Skips some analysis.
378     Clang->getDiagnosticOpts().IgnoreWarnings = true;
379   }
380 
381   auto Action = std::make_unique<ClangdFrontendAction>();
382   const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
383   if (!Action->BeginSourceFile(*Clang, MainInput)) {
384     log("BeginSourceFile() failed when building AST for {0}",
385         MainInput.getFile());
386     return None;
387   }
388   // If we saw an include guard in the preamble section of the main file,
389   // mark the main-file as include-guarded.
390   // This information is part of the HeaderFileInfo but is not loaded from the
391   // preamble as the file's size is part of its identity and may have changed.
392   // (The rest of HeaderFileInfo is not relevant for our purposes).
393   if (Preamble && Preamble->MainIsIncludeGuarded) {
394     const SourceManager &SM = Clang->getSourceManager();
395     const FileEntry *MainFE = SM.getFileEntryForID(SM.getMainFileID());
396     Clang->getPreprocessor().getHeaderSearchInfo().MarkFileIncludeOnce(MainFE);
397   }
398 
399   // Set up ClangTidy. Must happen after BeginSourceFile() so ASTContext exists.
400   // Clang-tidy has some limitations to ensure reasonable performance:
401   //  - checks don't see all preprocessor events in the preamble
402   //  - matchers run only over the main-file top-level decls (and can't see
403   //    ancestors outside this scope).
404   // In practice almost all checks work well without modifications.
405   std::vector<std::unique_ptr<tidy::ClangTidyCheck>> CTChecks;
406   ast_matchers::MatchFinder CTFinder;
407   llvm::Optional<tidy::ClangTidyContext> CTContext;
408   llvm::Optional<IncludeFixer> FixIncludes;
409   llvm::DenseMap<diag::kind, DiagnosticsEngine::Level> OverriddenSeverity;
410   // No need to run clang-tidy or IncludeFixerif we are not going to surface
411   // diagnostics.
412   if (PreserveDiags) {
413     trace::Span Tracer("ClangTidyInit");
414     tidy::ClangTidyCheckFactories CTFactories;
415     for (const auto &E : tidy::ClangTidyModuleRegistry::entries())
416       E.instantiate()->addCheckFactories(CTFactories);
417     CTContext.emplace(std::make_unique<tidy::DefaultOptionsProvider>(
418         tidy::ClangTidyGlobalOptions(), ClangTidyOpts));
419     CTContext->setDiagnosticsEngine(&Clang->getDiagnostics());
420     CTContext->setASTContext(&Clang->getASTContext());
421     CTContext->setCurrentFile(Filename);
422     CTChecks = CTFactories.createChecks(CTContext.getPointer());
423     llvm::erase_if(CTChecks, [&](const auto &Check) {
424       return !Check->isLanguageVersionSupported(CTContext->getLangOpts());
425     });
426     Preprocessor *PP = &Clang->getPreprocessor();
427     for (const auto &Check : CTChecks) {
428       Check->registerPPCallbacks(Clang->getSourceManager(), PP, PP);
429       Check->registerMatchers(&CTFinder);
430     }
431 
432     // Clang only corrects typos for use of undeclared functions in C if that
433     // use is an error. Include fixer relies on typo correction, so pretend
434     // this is an error. (The actual typo correction is nice too).
435     // We restore the original severity in the level adjuster.
436     // FIXME: It would be better to have a real API for this, but what?
437     for (auto ID : {diag::ext_implicit_function_decl,
438                     diag::warn_implicit_function_decl}) {
439       OverriddenSeverity.try_emplace(
440           ID, Clang->getDiagnostics().getDiagnosticLevel(ID, SourceLocation()));
441       Clang->getDiagnostics().setSeverity(ID, diag::Severity::Error,
442                                           SourceLocation());
443     }
444 
445     const Config &Cfg = Config::current();
446     ASTDiags.setLevelAdjuster([&](DiagnosticsEngine::Level DiagLevel,
447                                   const clang::Diagnostic &Info) {
448       if (Cfg.Diagnostics.SuppressAll ||
449           isBuiltinDiagnosticSuppressed(Info.getID(), Cfg.Diagnostics.Suppress,
450                                         Clang->getLangOpts()))
451         return DiagnosticsEngine::Ignored;
452 
453       auto It = OverriddenSeverity.find(Info.getID());
454       if (It != OverriddenSeverity.end())
455         DiagLevel = It->second;
456 
457       if (!CTChecks.empty()) {
458         std::string CheckName = CTContext->getCheckName(Info.getID());
459         bool IsClangTidyDiag = !CheckName.empty();
460         if (IsClangTidyDiag) {
461           if (Cfg.Diagnostics.Suppress.contains(CheckName))
462             return DiagnosticsEngine::Ignored;
463           // Check for suppression comment. Skip the check for diagnostics not
464           // in the main file, because we don't want that function to query the
465           // source buffer for preamble files. For the same reason, we ask
466           // shouldSuppressDiagnostic to avoid I/O.
467           // We let suppression comments take precedence over warning-as-error
468           // to match clang-tidy's behaviour.
469           bool IsInsideMainFile =
470               Info.hasSourceManager() &&
471               isInsideMainFile(Info.getLocation(), Info.getSourceManager());
472           SmallVector<tooling::Diagnostic, 1> TidySuppressedErrors;
473           if (IsInsideMainFile && CTContext->shouldSuppressDiagnostic(
474                                       DiagLevel, Info, 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)
532     Macros = Preamble->Macros;
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 =
609         issueUnusedIncludesDiagnostics(Result, Inputs.Contents);
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
723