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/ClangTidyDiagnosticConsumer.h"
11 #include "../clang-tidy/ClangTidyModuleRegistry.h"
12 #include "AST.h"
13 #include "Compiler.h"
14 #include "Diagnostics.h"
15 #include "Headers.h"
16 #include "IncludeFixer.h"
17 #include "SourceCode.h"
18 #include "index/CanonicalIncludes.h"
19 #include "index/Index.h"
20 #include "support/Logger.h"
21 #include "support/Trace.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/Decl.h"
24 #include "clang/Basic/LangOptions.h"
25 #include "clang/Basic/SourceLocation.h"
26 #include "clang/Basic/SourceManager.h"
27 #include "clang/Basic/TokenKinds.h"
28 #include "clang/Frontend/CompilerInstance.h"
29 #include "clang/Frontend/CompilerInvocation.h"
30 #include "clang/Frontend/FrontendActions.h"
31 #include "clang/Frontend/Utils.h"
32 #include "clang/Index/IndexDataConsumer.h"
33 #include "clang/Index/IndexingAction.h"
34 #include "clang/Lex/Lexer.h"
35 #include "clang/Lex/MacroInfo.h"
36 #include "clang/Lex/PPCallbacks.h"
37 #include "clang/Lex/Preprocessor.h"
38 #include "clang/Lex/PreprocessorOptions.h"
39 #include "clang/Sema/Sema.h"
40 #include "clang/Serialization/ASTWriter.h"
41 #include "clang/Serialization/PCHContainerOperations.h"
42 #include "clang/Tooling/CompilationDatabase.h"
43 #include "clang/Tooling/Syntax/Tokens.h"
44 #include "llvm/ADT/ArrayRef.h"
45 #include "llvm/ADT/STLExtras.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/SmallVector.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include <algorithm>
50 #include <memory>
51 
52 // Force the linker to link in Clang-tidy modules.
53 // clangd doesn't support the static analyzer.
54 #define CLANG_TIDY_DISABLE_STATIC_ANALYZER_CHECKS
55 #include "../clang-tidy/ClangTidyForceLinker.h"
56 
57 namespace clang {
58 namespace clangd {
59 namespace {
60 
61 template <class T> std::size_t getUsedBytes(const std::vector<T> &Vec) {
62   return Vec.capacity() * sizeof(T);
63 }
64 
65 class DeclTrackingASTConsumer : public ASTConsumer {
66 public:
67   DeclTrackingASTConsumer(std::vector<Decl *> &TopLevelDecls)
68       : TopLevelDecls(TopLevelDecls) {}
69 
70   bool HandleTopLevelDecl(DeclGroupRef DG) override {
71     for (Decl *D : DG) {
72       auto &SM = D->getASTContext().getSourceManager();
73       if (!isInsideMainFile(D->getLocation(), SM))
74         continue;
75       if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
76         if (isImplicitTemplateInstantiation(ND))
77           continue;
78 
79       // ObjCMethodDecl are not actually top-level decls.
80       if (isa<ObjCMethodDecl>(D))
81         continue;
82 
83       TopLevelDecls.push_back(D);
84     }
85     return true;
86   }
87 
88 private:
89   std::vector<Decl *> &TopLevelDecls;
90 };
91 
92 class ClangdFrontendAction : public SyntaxOnlyAction {
93 public:
94   std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }
95 
96 protected:
97   std::unique_ptr<ASTConsumer>
98   CreateASTConsumer(CompilerInstance &CI, llvm::StringRef InFile) override {
99     return std::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls);
100   }
101 
102 private:
103   std::vector<Decl *> TopLevelDecls;
104 };
105 
106 // When using a preamble, only preprocessor events outside its bounds are seen.
107 // This is almost what we want: replaying transitive preprocessing wastes time.
108 // However this confuses clang-tidy checks: they don't see any #includes!
109 // So we replay the *non-transitive* #includes that appear in the main-file.
110 // It would be nice to replay other events (macro definitions, ifdefs etc) but
111 // this addresses the most common cases fairly cheaply.
112 class ReplayPreamble : private PPCallbacks {
113 public:
114   // Attach preprocessor hooks such that preamble events will be injected at
115   // the appropriate time.
116   // Events will be delivered to the *currently registered* PP callbacks.
117   static void attach(const IncludeStructure &Includes, CompilerInstance &Clang,
118                      const PreambleBounds &PB) {
119     auto &PP = Clang.getPreprocessor();
120     auto *ExistingCallbacks = PP.getPPCallbacks();
121     // No need to replay events if nobody is listening.
122     if (!ExistingCallbacks)
123       return;
124     PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(new ReplayPreamble(
125         Includes, ExistingCallbacks, Clang.getSourceManager(), PP,
126         Clang.getLangOpts(), PB)));
127     // We're relying on the fact that addPPCallbacks keeps the old PPCallbacks
128     // around, creating a chaining wrapper. Guard against other implementations.
129     assert(PP.getPPCallbacks() != ExistingCallbacks &&
130            "Expected chaining implementation");
131   }
132 
133 private:
134   ReplayPreamble(const IncludeStructure &Includes, PPCallbacks *Delegate,
135                  const SourceManager &SM, Preprocessor &PP,
136                  const LangOptions &LangOpts, const PreambleBounds &PB)
137       : Includes(Includes), Delegate(Delegate), SM(SM), PP(PP) {
138     // Only tokenize the preamble section of the main file, as we are not
139     // interested in the rest of the tokens.
140     MainFileTokens = syntax::tokenize(
141         syntax::FileRange(SM.getMainFileID(), 0, PB.Size), SM, LangOpts);
142   }
143 
144   // In a normal compile, the preamble traverses the following structure:
145   //
146   // mainfile.cpp
147   //   <built-in>
148   //     ... macro definitions like __cplusplus ...
149   //     <command-line>
150   //       ... macro definitions for args like -Dfoo=bar ...
151   //   "header1.h"
152   //     ... header file contents ...
153   //   "header2.h"
154   //     ... header file contents ...
155   //   ... main file contents ...
156   //
157   // When using a preamble, the "header1" and "header2" subtrees get skipped.
158   // We insert them right after the built-in header, which still appears.
159   void FileChanged(SourceLocation Loc, FileChangeReason Reason,
160                    SrcMgr::CharacteristicKind Kind, FileID PrevFID) override {
161     // It'd be nice if there was a better way to identify built-in headers...
162     if (Reason == FileChangeReason::ExitFile &&
163         SM.getBuffer(PrevFID)->getBufferIdentifier() == "<built-in>")
164       replay();
165   }
166 
167   void replay() {
168     for (const auto &Inc : Includes.MainFileIncludes) {
169       const FileEntry *File = nullptr;
170       if (Inc.Resolved != "")
171         if (auto FE = SM.getFileManager().getFile(Inc.Resolved))
172           File = *FE;
173 
174       // Re-lex the #include directive to find its interesting parts.
175       auto HashLoc = SM.getComposedLoc(SM.getMainFileID(), Inc.HashOffset);
176       auto HashTok = llvm::partition_point(MainFileTokens,
177                                            [&HashLoc](const syntax::Token &T) {
178                                              return T.location() < HashLoc;
179                                            });
180       assert(HashTok != MainFileTokens.end() && HashTok->kind() == tok::hash);
181 
182       auto IncludeTok = std::next(HashTok);
183       assert(IncludeTok != MainFileTokens.end());
184 
185       auto FileTok = std::next(IncludeTok);
186       assert(FileTok != MainFileTokens.end());
187 
188       // Create a fake import/include token, none of the callers seem to care
189       // about clang::Token::Flags.
190       Token SynthesizedIncludeTok;
191       SynthesizedIncludeTok.startToken();
192       SynthesizedIncludeTok.setLocation(IncludeTok->location());
193       SynthesizedIncludeTok.setLength(IncludeTok->length());
194       SynthesizedIncludeTok.setKind(tok::raw_identifier);
195       SynthesizedIncludeTok.setRawIdentifierData(IncludeTok->text(SM).data());
196       PP.LookUpIdentifierInfo(SynthesizedIncludeTok);
197 
198       // Same here, create a fake one for Filename, including angles or quotes.
199       Token SynthesizedFilenameTok;
200       SynthesizedFilenameTok.startToken();
201       SynthesizedFilenameTok.setLocation(FileTok->location());
202       // Note that we can't make use of FileTok->length/text in here as in the
203       // case of angled includes this will contain tok::less instead of
204       // filename. Whereas Inc.Written contains the full header name including
205       // quotes/angles.
206       SynthesizedFilenameTok.setLength(Inc.Written.length());
207       SynthesizedFilenameTok.setKind(tok::header_name);
208       SynthesizedFilenameTok.setLiteralData(Inc.Written.data());
209 
210       llvm::StringRef WrittenFilename =
211           llvm::StringRef(Inc.Written).drop_front().drop_back();
212       Delegate->InclusionDirective(HashTok->location(), SynthesizedIncludeTok,
213                                    WrittenFilename, Inc.Written.front() == '<',
214                                    FileTok->range(SM).toCharRange(SM), File,
215                                    "SearchPath", "RelPath",
216                                    /*Imported=*/nullptr, Inc.FileKind);
217       if (File)
218         // FIXME: Use correctly named FileEntryRef.
219         Delegate->FileSkipped(FileEntryRef(File->getName(), *File),
220                               SynthesizedFilenameTok, Inc.FileKind);
221       else {
222         llvm::SmallString<1> UnusedRecovery;
223         Delegate->FileNotFound(WrittenFilename, UnusedRecovery);
224       }
225     }
226   }
227 
228   const IncludeStructure &Includes;
229   PPCallbacks *Delegate;
230   const SourceManager &SM;
231   Preprocessor &PP;
232   std::vector<syntax::Token> MainFileTokens;
233 };
234 
235 } // namespace
236 
237 void dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) {
238   AST.getASTContext().getTranslationUnitDecl()->dump(OS, true);
239 }
240 
241 llvm::Optional<ParsedAST>
242 ParsedAST::build(llvm::StringRef Filename, const ParseInputs &Inputs,
243                  std::unique_ptr<clang::CompilerInvocation> CI,
244                  llvm::ArrayRef<Diag> CompilerInvocationDiags,
245                  std::shared_ptr<const PreambleData> Preamble) {
246   trace::Span Tracer("BuildAST");
247   SPAN_ATTACH(Tracer, "File", Filename);
248 
249   auto VFS = Inputs.FS;
250   if (Preamble && Preamble->StatCache)
251     VFS = Preamble->StatCache->getConsumingFS(std::move(VFS));
252   if (VFS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
253     log("Couldn't set working directory when building the preamble.");
254     // We proceed anyway, our lit-tests rely on results for non-existing working
255     // dirs.
256   }
257 
258   assert(CI);
259   // Command-line parsing sets DisableFree to true by default, but we don't want
260   // to leak memory in clangd.
261   CI->getFrontendOpts().DisableFree = false;
262   const PrecompiledPreamble *PreamblePCH =
263       Preamble ? &Preamble->Preamble : nullptr;
264 
265   // Recovery expression currently only works for C++.
266   if (CI->getLangOpts()->CPlusPlus)
267     CI->getLangOpts()->RecoveryAST = Inputs.Opts.BuildRecoveryAST;
268   // This is on-by-default in windows to allow parsing SDK headers, but it
269   // breaks many features. Disable it for the main-file (not preamble).
270   CI->getLangOpts()->DelayedTemplateParsing = false;
271 
272   StoreDiags ASTDiags;
273 
274   auto Clang = prepareCompilerInstance(
275       std::move(CI), PreamblePCH,
276       llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents, Filename), VFS,
277       ASTDiags);
278   if (!Clang)
279     return None;
280 
281   auto Action = std::make_unique<ClangdFrontendAction>();
282   const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
283   if (!Action->BeginSourceFile(*Clang, MainInput)) {
284     log("BeginSourceFile() failed when building AST for {0}",
285         MainInput.getFile());
286     return None;
287   }
288 
289   // Set up ClangTidy. Must happen after BeginSourceFile() so ASTContext exists.
290   // Clang-tidy has some limitations to ensure reasonable performance:
291   //  - checks don't see all preprocessor events in the preamble
292   //  - matchers run only over the main-file top-level decls (and can't see
293   //    ancestors outside this scope).
294   // In practice almost all checks work well without modifications.
295   std::vector<std::unique_ptr<tidy::ClangTidyCheck>> CTChecks;
296   ast_matchers::MatchFinder CTFinder;
297   llvm::Optional<tidy::ClangTidyContext> CTContext;
298   {
299     trace::Span Tracer("ClangTidyInit");
300     dlog("ClangTidy configuration for file {0}: {1}", Filename,
301          tidy::configurationAsText(Inputs.Opts.ClangTidyOpts));
302     tidy::ClangTidyCheckFactories CTFactories;
303     for (const auto &E : tidy::ClangTidyModuleRegistry::entries())
304       E.instantiate()->addCheckFactories(CTFactories);
305     CTContext.emplace(std::make_unique<tidy::DefaultOptionsProvider>(
306         tidy::ClangTidyGlobalOptions(), Inputs.Opts.ClangTidyOpts));
307     CTContext->setDiagnosticsEngine(&Clang->getDiagnostics());
308     CTContext->setASTContext(&Clang->getASTContext());
309     CTContext->setCurrentFile(Filename);
310     CTChecks = CTFactories.createChecks(CTContext.getPointer());
311     ASTDiags.setLevelAdjuster([&CTContext](DiagnosticsEngine::Level DiagLevel,
312                                            const clang::Diagnostic &Info) {
313       if (CTContext) {
314         std::string CheckName = CTContext->getCheckName(Info.getID());
315         bool IsClangTidyDiag = !CheckName.empty();
316         if (IsClangTidyDiag) {
317           // Check for warning-as-error.
318           // We deliberately let this take precedence over suppression comments
319           // to match clang-tidy's behaviour.
320           if (DiagLevel == DiagnosticsEngine::Warning &&
321               CTContext->treatAsError(CheckName)) {
322             return DiagnosticsEngine::Error;
323           }
324 
325           // Check for suppression comment. Skip the check for diagnostics not
326           // in the main file, because we don't want that function to query the
327           // source buffer for preamble files. For the same reason, we ask
328           // shouldSuppressDiagnostic to avoid I/O.
329           bool IsInsideMainFile =
330               Info.hasSourceManager() &&
331               isInsideMainFile(Info.getLocation(), Info.getSourceManager());
332           if (IsInsideMainFile &&
333               tidy::shouldSuppressDiagnostic(DiagLevel, Info, *CTContext,
334                                              /*AllowIO=*/false)) {
335             return DiagnosticsEngine::Ignored;
336           }
337         }
338       }
339       return DiagLevel;
340     });
341     Preprocessor *PP = &Clang->getPreprocessor();
342     for (const auto &Check : CTChecks) {
343       if (!Check->isLanguageVersionSupported(CTContext->getLangOpts()))
344         continue;
345       // FIXME: the PP callbacks skip the entire preamble.
346       // Checks that want to see #includes in the main file do not see them.
347       Check->registerPPCallbacks(Clang->getSourceManager(), PP, PP);
348       Check->registerMatchers(&CTFinder);
349     }
350   }
351 
352   // Add IncludeFixer which can recover diagnostics caused by missing includes
353   // (e.g. incomplete type) and attach include insertion fixes to diagnostics.
354   llvm::Optional<IncludeFixer> FixIncludes;
355   auto BuildDir = VFS->getCurrentWorkingDirectory();
356   if (Inputs.Opts.SuggestMissingIncludes && Inputs.Index &&
357       !BuildDir.getError()) {
358     auto Style = getFormatStyleForFile(Filename, Inputs.Contents, VFS.get());
359     auto Inserter = std::make_shared<IncludeInserter>(
360         Filename, Inputs.Contents, Style, BuildDir.get(),
361         &Clang->getPreprocessor().getHeaderSearchInfo());
362     if (Preamble) {
363       for (const auto &Inc : Preamble->Includes.MainFileIncludes)
364         Inserter->addExisting(Inc);
365     }
366     FixIncludes.emplace(Filename, Inserter, *Inputs.Index,
367                         /*IndexRequestLimit=*/5);
368     ASTDiags.contributeFixes([&FixIncludes](DiagnosticsEngine::Level DiagLevl,
369                                             const clang::Diagnostic &Info) {
370       return FixIncludes->fix(DiagLevl, Info);
371     });
372     Clang->setExternalSemaSource(FixIncludes->unresolvedNameRecorder());
373   }
374 
375   // Copy over the includes from the preamble, then combine with the
376   // non-preamble includes below.
377   auto Includes = Preamble ? Preamble->Includes : IncludeStructure{};
378   // Replay the preamble includes so that clang-tidy checks can see them.
379   if (Preamble)
380     ReplayPreamble::attach(Includes, *Clang, Preamble->Preamble.getBounds());
381   // Important: collectIncludeStructure is registered *after* ReplayPreamble!
382   // Otherwise we would collect the replayed includes again...
383   // (We can't *just* use the replayed includes, they don't have Resolved path).
384   Clang->getPreprocessor().addPPCallbacks(
385       collectIncludeStructureCallback(Clang->getSourceManager(), &Includes));
386   // Copy over the macros in the preamble region of the main file, and combine
387   // with non-preamble macros below.
388   MainFileMacros Macros;
389   if (Preamble)
390     Macros = Preamble->Macros;
391   Clang->getPreprocessor().addPPCallbacks(
392       std::make_unique<CollectMainFileMacros>(Clang->getSourceManager(),
393                                               Macros));
394 
395   // Copy over the includes from the preamble, then combine with the
396   // non-preamble includes below.
397   CanonicalIncludes CanonIncludes;
398   if (Preamble)
399     CanonIncludes = Preamble->CanonIncludes;
400   else
401     CanonIncludes.addSystemHeadersMapping(Clang->getLangOpts());
402   std::unique_ptr<CommentHandler> IWYUHandler =
403       collectIWYUHeaderMaps(&CanonIncludes);
404   Clang->getPreprocessor().addCommentHandler(IWYUHandler.get());
405 
406   // Collect tokens of the main file.
407   syntax::TokenCollector CollectTokens(Clang->getPreprocessor());
408 
409   if (llvm::Error Err = Action->Execute())
410     log("Execute() failed when building AST for {0}: {1}", MainInput.getFile(),
411         toString(std::move(Err)));
412 
413   // We have to consume the tokens before running clang-tidy to avoid collecting
414   // tokens from running the preprocessor inside the checks (only
415   // modernize-use-trailing-return-type does that today).
416   syntax::TokenBuffer Tokens = std::move(CollectTokens).consume();
417   std::vector<Decl *> ParsedDecls = Action->takeTopLevelDecls();
418   // AST traversals should exclude the preamble, to avoid performance cliffs.
419   Clang->getASTContext().setTraversalScope(ParsedDecls);
420   {
421     // Run the AST-dependent part of the clang-tidy checks.
422     // (The preprocessor part ran already, via PPCallbacks).
423     trace::Span Tracer("ClangTidyMatch");
424     CTFinder.matchAST(Clang->getASTContext());
425   }
426 
427   // UnitDiagsConsumer is local, we can not store it in CompilerInstance that
428   // has a longer lifetime.
429   Clang->getDiagnostics().setClient(new IgnoreDiagnostics);
430   // CompilerInstance won't run this callback, do it directly.
431   ASTDiags.EndSourceFile();
432   // XXX: This is messy: clang-tidy checks flush some diagnostics at EOF.
433   // However Action->EndSourceFile() would destroy the ASTContext!
434   // So just inform the preprocessor of EOF, while keeping everything alive.
435   Clang->getPreprocessor().EndSourceFile();
436 
437   std::vector<Diag> Diags = CompilerInvocationDiags;
438   // Add diagnostics from the preamble, if any.
439   if (Preamble)
440     Diags.insert(Diags.end(), Preamble->Diags.begin(), Preamble->Diags.end());
441   // Finally, add diagnostics coming from the AST.
442   {
443     std::vector<Diag> D = ASTDiags.take(CTContext.getPointer());
444     Diags.insert(Diags.end(), D.begin(), D.end());
445   }
446   return ParsedAST(Inputs.Version, std::move(Preamble), std::move(Clang),
447                    std::move(Action), std::move(Tokens), std::move(Macros),
448                    std::move(ParsedDecls), std::move(Diags),
449                    std::move(Includes), std::move(CanonIncludes));
450 }
451 
452 ParsedAST::ParsedAST(ParsedAST &&Other) = default;
453 
454 ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default;
455 
456 ParsedAST::~ParsedAST() {
457   if (Action) {
458     // We already notified the PP of end-of-file earlier, so detach it first.
459     // We must keep it alive until after EndSourceFile(), Sema relies on this.
460     auto PP = Clang->getPreprocessorPtr(); // Keep PP alive for now.
461     Clang->setPreprocessor(nullptr);       // Detach so we don't send EOF again.
462     Action->EndSourceFile();               // Destroy ASTContext and Sema.
463     // Now Sema is gone, it's safe for PP to go out of scope.
464   }
465 }
466 
467 ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
468 
469 const ASTContext &ParsedAST::getASTContext() const {
470   return Clang->getASTContext();
471 }
472 
473 Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
474 
475 std::shared_ptr<Preprocessor> ParsedAST::getPreprocessorPtr() {
476   return Clang->getPreprocessorPtr();
477 }
478 
479 const Preprocessor &ParsedAST::getPreprocessor() const {
480   return Clang->getPreprocessor();
481 }
482 
483 llvm::ArrayRef<Decl *> ParsedAST::getLocalTopLevelDecls() {
484   return LocalTopLevelDecls;
485 }
486 
487 const MainFileMacros &ParsedAST::getMacros() const { return Macros; }
488 
489 const std::vector<Diag> &ParsedAST::getDiagnostics() const { return Diags; }
490 
491 std::size_t ParsedAST::getUsedBytes() const {
492   auto &AST = getASTContext();
493   // FIXME(ibiryukov): we do not account for the dynamically allocated part of
494   // Message and Fixes inside each diagnostic.
495   std::size_t Total =
496       clangd::getUsedBytes(LocalTopLevelDecls) + clangd::getUsedBytes(Diags);
497 
498   // FIXME: the rest of the function is almost a direct copy-paste from
499   // libclang's clang_getCXTUResourceUsage. We could share the implementation.
500 
501   // Sum up various allocators inside the ast context and the preprocessor.
502   Total += AST.getASTAllocatedMemory();
503   Total += AST.getSideTableAllocatedMemory();
504   Total += AST.Idents.getAllocator().getTotalMemory();
505   Total += AST.Selectors.getTotalMemory();
506 
507   Total += AST.getSourceManager().getContentCacheSize();
508   Total += AST.getSourceManager().getDataStructureSizes();
509   Total += AST.getSourceManager().getMemoryBufferSizes().malloc_bytes;
510 
511   if (ExternalASTSource *Ext = AST.getExternalSource())
512     Total += Ext->getMemoryBufferSizes().malloc_bytes;
513 
514   const Preprocessor &PP = getPreprocessor();
515   Total += PP.getTotalMemory();
516   if (PreprocessingRecord *PRec = PP.getPreprocessingRecord())
517     Total += PRec->getTotalMemory();
518   Total += PP.getHeaderSearchInfo().getTotalMemory();
519 
520   return Total;
521 }
522 
523 const IncludeStructure &ParsedAST::getIncludeStructure() const {
524   return Includes;
525 }
526 
527 const CanonicalIncludes &ParsedAST::getCanonicalIncludes() const {
528   return CanonIncludes;
529 }
530 
531 ParsedAST::ParsedAST(llvm::StringRef Version,
532                      std::shared_ptr<const PreambleData> Preamble,
533                      std::unique_ptr<CompilerInstance> Clang,
534                      std::unique_ptr<FrontendAction> Action,
535                      syntax::TokenBuffer Tokens, MainFileMacros Macros,
536                      std::vector<Decl *> LocalTopLevelDecls,
537                      std::vector<Diag> Diags, IncludeStructure Includes,
538                      CanonicalIncludes CanonIncludes)
539     : Version(Version), Preamble(std::move(Preamble)), Clang(std::move(Clang)),
540       Action(std::move(Action)), Tokens(std::move(Tokens)),
541       Macros(std::move(Macros)), Diags(std::move(Diags)),
542       LocalTopLevelDecls(std::move(LocalTopLevelDecls)),
543       Includes(std::move(Includes)), CanonIncludes(std::move(CanonIncludes)) {
544   assert(this->Clang);
545   assert(this->Action);
546 }
547 
548 } // namespace clangd
549 } // namespace clang
550