clang-tools 22.0.0git
Serialize.cpp
Go to the documentation of this file.
1//===-- Serialize.cpp - ClangDoc Serializer ---------------------*- 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 "Serialize.h"
10#include "BitcodeWriter.h"
11
12#include "clang/AST/Attr.h"
13#include "clang/AST/Comment.h"
14#include "clang/AST/CommentVisitor.h"
15#include "clang/AST/DeclFriend.h"
16#include "clang/AST/ExprConcepts.h"
17#include "clang/AST/Mangle.h"
18#include "clang/Index/USRGeneration.h"
19#include "clang/Lex/Lexer.h"
20#include "llvm/ADT/StringExtras.h"
21#include "llvm/Support/SHA1.h"
22
23using clang::comments::FullComment;
24
25namespace clang {
26namespace doc {
27namespace serialize {
28
29namespace {
30static SmallString<16> exprToString(const clang::Expr *E) {
31 clang::LangOptions Opts;
32 clang::PrintingPolicy Policy(Opts);
33 SmallString<16> Result;
34 llvm::raw_svector_ostream OS(Result);
35 E->printPretty(OS, nullptr, Policy);
36 return Result;
37}
38} // namespace
39
40SymbolID hashUSR(llvm::StringRef USR) {
41 return llvm::SHA1::hash(arrayRefFromStringRef(USR));
42}
43
44template <typename T>
45static void
46populateParentNamespaces(llvm::SmallVector<Reference, 4> &Namespaces,
47 const T *D, bool &IsAnonymousNamespace);
48
49static void populateMemberTypeInfo(MemberTypeInfo &I, const Decl *D);
50static void populateMemberTypeInfo(RecordInfo &I, AccessSpecifier &Access,
51 const DeclaratorDecl *D,
52 bool IsStatic = false);
53
54static void getTemplateParameters(const TemplateParameterList *TemplateParams,
55 llvm::raw_ostream &Stream) {
56 Stream << "template <";
57
58 for (unsigned i = 0; i < TemplateParams->size(); ++i) {
59 if (i > 0)
60 Stream << ", ";
61
62 const NamedDecl *Param = TemplateParams->getParam(i);
63 if (const auto *TTP = llvm::dyn_cast<TemplateTypeParmDecl>(Param)) {
64 if (TTP->wasDeclaredWithTypename())
65 Stream << "typename";
66 else
67 Stream << "class";
68 if (TTP->isParameterPack())
69 Stream << "...";
70 Stream << " " << TTP->getNameAsString();
71
72 // We need to also handle type constraints for code like:
73 // template <class T = void>
74 // class C {};
75 if (TTP->hasTypeConstraint()) {
76 Stream << " = ";
77 TTP->getTypeConstraint()->print(
78 Stream, TTP->getASTContext().getPrintingPolicy());
79 }
80 } else if (const auto *NTTP =
81 llvm::dyn_cast<NonTypeTemplateParmDecl>(Param)) {
82 NTTP->getType().print(Stream, NTTP->getASTContext().getPrintingPolicy());
83 if (NTTP->isParameterPack())
84 Stream << "...";
85 Stream << " " << NTTP->getNameAsString();
86 } else if (const auto *TTPD =
87 llvm::dyn_cast<TemplateTemplateParmDecl>(Param)) {
88 Stream << "template <";
89 getTemplateParameters(TTPD->getTemplateParameters(), Stream);
90 Stream << "> class " << TTPD->getNameAsString();
91 }
92 }
93
94 Stream << "> ";
95}
96
97// Extract the full function prototype from a FunctionDecl including
98// Full Decl
99static llvm::SmallString<256>
100getFunctionPrototype(const FunctionDecl *FuncDecl) {
101 llvm::SmallString<256> Result;
102 llvm::raw_svector_ostream Stream(Result);
103 const ASTContext &Ctx = FuncDecl->getASTContext();
104 const auto *Method = llvm::dyn_cast<CXXMethodDecl>(FuncDecl);
105 // If it's a templated function, handle the template parameters
106 if (const auto *TmplDecl = FuncDecl->getDescribedTemplate())
107 getTemplateParameters(TmplDecl->getTemplateParameters(), Stream);
108
109 // If it's a virtual method
110 if (Method && Method->isVirtual())
111 Stream << "virtual ";
112
113 // Print return type
114 FuncDecl->getReturnType().print(Stream, Ctx.getPrintingPolicy());
115
116 // Print function name
117 Stream << " " << FuncDecl->getNameAsString() << "(";
118
119 // Print parameter list with types, names, and default values
120 for (unsigned I = 0; I < FuncDecl->getNumParams(); ++I) {
121 if (I > 0)
122 Stream << ", ";
123 const ParmVarDecl *ParamDecl = FuncDecl->getParamDecl(I);
124 QualType ParamType = ParamDecl->getType();
125 ParamType.print(Stream, Ctx.getPrintingPolicy());
126
127 // Print parameter name if it has one
128 if (!ParamDecl->getName().empty())
129 Stream << " " << ParamDecl->getNameAsString();
130
131 // Print default argument if it exists
132 if (ParamDecl->hasDefaultArg() &&
133 !ParamDecl->hasUninstantiatedDefaultArg()) {
134 if (const Expr *DefaultArg = ParamDecl->getDefaultArg()) {
135 Stream << " = ";
136 DefaultArg->printPretty(Stream, nullptr, Ctx.getPrintingPolicy());
137 }
138 }
139 }
140
141 // If it is a variadic function, add '...'
142 if (FuncDecl->isVariadic()) {
143 if (FuncDecl->getNumParams() > 0)
144 Stream << ", ";
145 Stream << "...";
146 }
147
148 Stream << ")";
149
150 // If it's a const method, add 'const' qualifier
151 if (Method) {
152 if (Method->isDeleted())
153 Stream << " = delete";
154 if (Method->size_overridden_methods())
155 Stream << " override";
156 if (Method->hasAttr<clang::FinalAttr>())
157 Stream << " final";
158 if (Method->isConst())
159 Stream << " const";
160 if (Method->isPureVirtual())
161 Stream << " = 0";
162 }
163
164 if (auto ExceptionSpecType = FuncDecl->getExceptionSpecType())
165 Stream << " " << ExceptionSpecType;
166
167 return Result; // Convert SmallString to std::string for return
168}
169
170static llvm::SmallString<16> getTypeAlias(const TypeAliasDecl *Alias) {
171 llvm::SmallString<16> Result;
172 llvm::raw_svector_ostream Stream(Result);
173 const ASTContext &Ctx = Alias->getASTContext();
174 if (const auto *TmplDecl = Alias->getDescribedTemplate())
175 getTemplateParameters(TmplDecl->getTemplateParameters(), Stream);
176 Stream << "using " << Alias->getNameAsString() << " = ";
177 QualType Q = Alias->getUnderlyingType();
178 Q.print(Stream, Ctx.getPrintingPolicy());
179
180 return Result;
181}
182
183// A function to extract the appropriate relative path for a given info's
184// documentation. The path returned is a composite of the parent namespaces.
185//
186// Example: Given the below, the directory path for class C info will be
187// <root>/A/B
188//
189// namespace A {
190// namespace B {
191//
192// class C {};
193//
194// }
195// }
196static llvm::SmallString<128>
198 llvm::SmallString<128> Path;
199 for (auto R = Namespaces.rbegin(), E = Namespaces.rend(); R != E; ++R)
200 llvm::sys::path::append(Path, R->Name);
201 return Path;
202}
203
204static llvm::SmallString<128> getInfoRelativePath(const Decl *D) {
205 llvm::SmallVector<Reference, 4> Namespaces;
206 // The third arg in populateParentNamespaces is a boolean passed by reference,
207 // its value is not relevant in here so it's not used anywhere besides the
208 // function call
209 bool B = true;
210 populateParentNamespaces(Namespaces, D, B);
211 return getInfoRelativePath(Namespaces);
212}
213
215 : public ConstCommentVisitor<ClangDocCommentVisitor> {
216public:
217 ClangDocCommentVisitor(CommentInfo &CI) : CurrentCI(CI) {}
218
219 void parseComment(const comments::Comment *C);
220
221 void visitTextComment(const TextComment *C);
222 void visitInlineCommandComment(const InlineCommandComment *C);
223 void visitHTMLStartTagComment(const HTMLStartTagComment *C);
224 void visitHTMLEndTagComment(const HTMLEndTagComment *C);
225 void visitBlockCommandComment(const BlockCommandComment *C);
226 void visitParamCommandComment(const ParamCommandComment *C);
227 void visitTParamCommandComment(const TParamCommandComment *C);
228 void visitVerbatimBlockComment(const VerbatimBlockComment *C);
229 void visitVerbatimBlockLineComment(const VerbatimBlockLineComment *C);
230 void visitVerbatimLineComment(const VerbatimLineComment *C);
231
232private:
233 std::string getCommandName(unsigned CommandID) const;
234 bool isWhitespaceOnly(StringRef S) const;
235
236 CommentInfo &CurrentCI;
237};
238
239void ClangDocCommentVisitor::parseComment(const comments::Comment *C) {
240 CurrentCI.Kind = stringToCommentKind(C->getCommentKindName());
242 for (comments::Comment *Child :
243 llvm::make_range(C->child_begin(), C->child_end())) {
244 CurrentCI.Children.emplace_back(std::make_unique<CommentInfo>());
245 ClangDocCommentVisitor Visitor(*CurrentCI.Children.back());
246 Visitor.parseComment(Child);
247 }
248}
249
251 if (!isWhitespaceOnly(C->getText()))
252 CurrentCI.Text = C->getText();
253}
254
256 const InlineCommandComment *C) {
257 CurrentCI.Name = getCommandName(C->getCommandID());
258 for (unsigned I = 0, E = C->getNumArgs(); I != E; ++I)
259 CurrentCI.Args.push_back(C->getArgText(I));
260}
261
263 const HTMLStartTagComment *C) {
264 CurrentCI.Name = C->getTagName();
265 CurrentCI.SelfClosing = C->isSelfClosing();
266 for (unsigned I = 0, E = C->getNumAttrs(); I < E; ++I) {
267 const HTMLStartTagComment::Attribute &Attr = C->getAttr(I);
268 CurrentCI.AttrKeys.push_back(Attr.Name);
269 CurrentCI.AttrValues.push_back(Attr.Value);
270 }
271}
272
274 const HTMLEndTagComment *C) {
275 CurrentCI.Name = C->getTagName();
276 CurrentCI.SelfClosing = true;
277}
278
280 const BlockCommandComment *C) {
281 CurrentCI.Name = getCommandName(C->getCommandID());
282 for (unsigned I = 0, E = C->getNumArgs(); I < E; ++I)
283 CurrentCI.Args.push_back(C->getArgText(I));
284}
285
287 const ParamCommandComment *C) {
288 CurrentCI.Direction =
289 ParamCommandComment::getDirectionAsString(C->getDirection());
290 CurrentCI.Explicit = C->isDirectionExplicit();
291 if (C->hasParamName())
292 CurrentCI.ParamName = C->getParamNameAsWritten();
293}
294
296 const TParamCommandComment *C) {
297 if (C->hasParamName())
298 CurrentCI.ParamName = C->getParamNameAsWritten();
299}
300
302 const VerbatimBlockComment *C) {
303 CurrentCI.Name = getCommandName(C->getCommandID());
304 CurrentCI.CloseName = C->getCloseName();
305}
306
308 const VerbatimBlockLineComment *C) {
309 if (!isWhitespaceOnly(C->getText()))
310 CurrentCI.Text = C->getText();
311}
312
314 const VerbatimLineComment *C) {
315 if (!isWhitespaceOnly(C->getText()))
316 CurrentCI.Text = C->getText();
317}
318
319bool ClangDocCommentVisitor::isWhitespaceOnly(llvm::StringRef S) const {
320 return llvm::all_of(S, isspace);
321}
322
323std::string ClangDocCommentVisitor::getCommandName(unsigned CommandID) const {
324 const CommandInfo *Info = CommandTraits::getBuiltinCommandInfo(CommandID);
325 if (Info)
326 return Info->Name;
327 // TODO: Add parsing for \file command.
328 return "<not a builtin command>";
329}
330
331// Serializing functions.
332
333static std::string getSourceCode(const Decl *D, const SourceRange &R) {
334 return Lexer::getSourceText(CharSourceRange::getTokenRange(R),
335 D->getASTContext().getSourceManager(),
336 D->getASTContext().getLangOpts())
337 .str();
338}
339
340template <typename T>
341static std::string serialize(T &I, DiagnosticsEngine &Diags) {
342 SmallString<2048> Buffer;
343 llvm::BitstreamWriter Stream(Buffer);
344 ClangDocBitcodeWriter Writer(Stream, Diags);
345 Writer.emitBlock(I);
346 return Buffer.str().str();
347}
348
349std::string serialize(std::unique_ptr<Info> &I, DiagnosticsEngine &Diags) {
350 switch (I->IT) {
352 return serialize(*static_cast<NamespaceInfo *>(I.get()), Diags);
354 return serialize(*static_cast<RecordInfo *>(I.get()), Diags);
356 return serialize(*static_cast<EnumInfo *>(I.get()), Diags);
358 return serialize(*static_cast<FunctionInfo *>(I.get()), Diags);
360 return serialize(*static_cast<ConceptInfo *>(I.get()), Diags);
362 return serialize(*static_cast<VarInfo *>(I.get()), Diags);
366 return "";
367 }
368 llvm_unreachable("unhandled enumerator");
369}
370
371static void parseFullComment(const FullComment *C, CommentInfo &CI) {
372 ClangDocCommentVisitor Visitor(CI);
373 Visitor.parseComment(C);
374}
375
376static SymbolID getUSRForDecl(const Decl *D) {
377 llvm::SmallString<128> USR;
378 if (index::generateUSRForDecl(D, USR))
379 return SymbolID();
380 return hashUSR(USR);
381}
382
383static TagDecl *getTagDeclForType(const QualType &T) {
384 if (const TagDecl *D = T->getAsTagDecl())
385 return D->getDefinition();
386 return nullptr;
387}
388
389static RecordDecl *getRecordDeclForType(const QualType &T) {
390 if (const RecordDecl *D = T->getAsRecordDecl())
391 return D->getDefinition();
392 return nullptr;
393}
394
395static TypeInfo getTypeInfoForType(const QualType &T,
396 const PrintingPolicy &Policy) {
397 const TagDecl *TD = getTagDeclForType(T);
398 if (!TD) {
399 TypeInfo TI = TypeInfo(Reference(SymbolID(), T.getAsString(Policy)));
400 TI.IsBuiltIn = T->isBuiltinType();
401 TI.IsTemplate = T->isTemplateTypeParmType();
402 return TI;
403 }
404 InfoType IT;
405 if (isa<EnumDecl>(TD)) {
407 } else if (isa<RecordDecl>(TD)) {
409 } else {
411 }
412 Reference R = Reference(getUSRForDecl(TD), TD->getNameAsString(), IT,
413 T.getAsString(Policy), getInfoRelativePath(TD));
414 TypeInfo TI = TypeInfo(R);
415 TI.IsBuiltIn = T->isBuiltinType();
416 TI.IsTemplate = T->isTemplateTypeParmType();
417 return TI;
418}
419
420static bool isPublic(const clang::AccessSpecifier AS,
421 const clang::Linkage Link) {
422 if (AS == clang::AccessSpecifier::AS_private)
423 return false;
424 if ((Link == clang::Linkage::Module) || (Link == clang::Linkage::External))
425 return true;
426 return false; // otherwise, linkage is some form of internal linkage
427}
428
429static bool shouldSerializeInfo(bool PublicOnly, bool IsInAnonymousNamespace,
430 const NamedDecl *D) {
431 bool IsAnonymousNamespace = false;
432 if (const auto *N = dyn_cast<NamespaceDecl>(D))
433 IsAnonymousNamespace = N->isAnonymousNamespace();
434 return !PublicOnly ||
435 (!IsInAnonymousNamespace && !IsAnonymousNamespace &&
436 isPublic(D->getAccessUnsafe(), D->getLinkageInternal()));
437}
438
439// The InsertChild functions insert the given info into the given scope using
440// the method appropriate for that type. Some types are moved into the
441// appropriate vector, while other types have Reference objects generated to
442// refer to them.
443//
444// See MakeAndInsertIntoParent().
449
450static void InsertChild(ScopeChildren &Scope, const RecordInfo &Info) {
451 Scope.Records.emplace_back(Info.USR, Info.Name, InfoType::IT_record,
453 Info.MangledName);
454}
455
457 Scope.Enums.push_back(std::move(Info));
458}
459
461 Scope.Functions.push_back(std::move(Info));
462}
463
465 Scope.Typedefs.push_back(std::move(Info));
466}
467
469 Scope.Concepts.push_back(std::move(Info));
470}
471
472static void InsertChild(ScopeChildren &Scope, VarInfo Info) {
473 Scope.Variables.push_back(std::move(Info));
474}
475
476// Creates a parent of the correct type for the given child and inserts it into
477// that parent.
478//
479// This is complicated by the fact that namespaces and records are inserted by
480// reference (constructing a "Reference" object with that namespace/record's
481// info), while everything else is inserted by moving it directly into the child
482// vectors.
483//
484// For namespaces and records, explicitly specify a const& template parameter
485// when invoking this function:
486// MakeAndInsertIntoParent<const Record&>(...);
487// Otherwise, specify an rvalue reference <EnumInfo&&> and move into the
488// parameter. Since each variant is used once, it's not worth having a more
489// elaborate system to automatically deduce this information.
490template <typename ChildType>
491static std::unique_ptr<Info> makeAndInsertIntoParent(ChildType Child) {
492 if (Child.Namespace.empty()) {
493 // Insert into unnamed parent namespace.
494 auto ParentNS = std::make_unique<NamespaceInfo>();
495 InsertChild(ParentNS->Children, std::forward<ChildType>(Child));
496 return ParentNS;
497 }
498
499 switch (Child.Namespace[0].RefType) {
501 auto ParentNS = std::make_unique<NamespaceInfo>();
502 ParentNS->USR = Child.Namespace[0].USR;
503 InsertChild(ParentNS->Children, std::forward<ChildType>(Child));
504 return ParentNS;
505 }
506 case InfoType::IT_record: {
507 auto ParentRec = std::make_unique<RecordInfo>();
508 ParentRec->USR = Child.Namespace[0].USR;
509 InsertChild(ParentRec->Children, std::forward<ChildType>(Child));
510 return ParentRec;
511 }
519 break;
520 }
521 llvm_unreachable("Invalid reference type for parent namespace");
522}
523
524// There are two uses for this function.
525// 1) Getting the resulting mode of inheritance of a record.
526// Example: class A {}; class B : private A {}; class C : public B {};
527// It's explicit that C is publicly inherited from C and B is privately
528// inherited from A. It's not explicit but C is also privately inherited from
529// A. This is the AS that this function calculates. FirstAS is the
530// inheritance mode of `class C : B` and SecondAS is the inheritance mode of
531// `class B : A`.
532// 2) Getting the inheritance mode of an inherited attribute / method.
533// Example : class A { public: int M; }; class B : private A {};
534// Class B is inherited from class A, which has a public attribute. This
535// attribute is now part of the derived class B but it's not public. This
536// will be private because the inheritance is private. This is the AS that
537// this function calculates. FirstAS is the inheritance mode and SecondAS is
538// the AS of the attribute / method.
539static AccessSpecifier getFinalAccessSpecifier(AccessSpecifier FirstAS,
540 AccessSpecifier SecondAS) {
541 if (FirstAS == AccessSpecifier::AS_none ||
542 SecondAS == AccessSpecifier::AS_none)
543 return AccessSpecifier::AS_none;
544 if (FirstAS == AccessSpecifier::AS_private ||
545 SecondAS == AccessSpecifier::AS_private)
546 return AccessSpecifier::AS_private;
547 if (FirstAS == AccessSpecifier::AS_protected ||
548 SecondAS == AccessSpecifier::AS_protected)
549 return AccessSpecifier::AS_protected;
550 return AccessSpecifier::AS_public;
551}
552
553// The Access parameter is only provided when parsing the field of an inherited
554// record, the access specification of the field depends on the inheritance mode
555static void parseFields(RecordInfo &I, const RecordDecl *D, bool PublicOnly,
556 AccessSpecifier Access = AccessSpecifier::AS_public) {
557 for (const FieldDecl *F : D->fields()) {
558 if (!shouldSerializeInfo(PublicOnly, /*IsInAnonymousNamespace=*/false, F))
559 continue;
560 populateMemberTypeInfo(I, Access, F);
561 }
562 const auto *CxxRD = dyn_cast<CXXRecordDecl>(D);
563 if (!CxxRD)
564 return;
565 for (Decl *CxxDecl : CxxRD->decls()) {
566 auto *VD = dyn_cast<VarDecl>(CxxDecl);
567 if (!VD ||
568 !shouldSerializeInfo(PublicOnly, /*IsInAnonymousNamespace=*/false, VD))
569 continue;
570
571 if (VD->isStaticDataMember())
572 populateMemberTypeInfo(I, Access, VD, /*IsStatic=*/true);
573 }
574}
575
576static void parseEnumerators(EnumInfo &I, const EnumDecl *D) {
577 for (const EnumConstantDecl *E : D->enumerators()) {
578 std::string ValueExpr;
579 if (const Expr *InitExpr = E->getInitExpr())
580 ValueExpr = getSourceCode(D, InitExpr->getSourceRange());
581 SmallString<16> ValueStr;
582 E->getInitVal().toString(ValueStr);
583 I.Members.emplace_back(E->getNameAsString(), ValueStr.str(), ValueExpr);
584 ASTContext &Context = E->getASTContext();
585 if (RawComment *Comment =
586 E->getASTContext().getRawCommentForDeclNoCache(E)) {
587 Comment->setAttached();
588 if (comments::FullComment *Fc = Comment->parse(Context, nullptr, E)) {
589 EnumValueInfo &Member = I.Members.back();
590 Member.Description.emplace_back();
591 parseFullComment(Fc, Member.Description.back());
592 }
593 }
594 }
595}
596
597static void parseParameters(FunctionInfo &I, const FunctionDecl *D) {
598 auto &LO = D->getLangOpts();
599 for (const ParmVarDecl *P : D->parameters()) {
600 FieldTypeInfo &FieldInfo = I.Params.emplace_back(
601 getTypeInfoForType(P->getOriginalType(), LO), P->getNameAsString());
602 FieldInfo.DefaultValue = getSourceCode(D, P->getDefaultArgRange());
603 }
604}
605
606// TODO: Remove the serialization of Parents and VirtualParents, this
607// information is also extracted in the other definition of parseBases.
608static void parseBases(RecordInfo &I, const CXXRecordDecl *D) {
609 // Don't parse bases if this isn't a definition.
610 if (!D->isThisDeclarationADefinition())
611 return;
612
613 for (const CXXBaseSpecifier &B : D->bases()) {
614 if (B.isVirtual())
615 continue;
616 if (const auto *Ty = B.getType()->getAs<TemplateSpecializationType>()) {
617 const TemplateDecl *D = Ty->getTemplateName().getAsTemplateDecl();
618 I.Parents.emplace_back(getUSRForDecl(D), B.getType().getAsString(),
619 InfoType::IT_record, B.getType().getAsString());
620 } else if (const RecordDecl *P = getRecordDeclForType(B.getType()))
621 I.Parents.emplace_back(getUSRForDecl(P), P->getNameAsString(),
622 InfoType::IT_record, P->getQualifiedNameAsString(),
624 else
625 I.Parents.emplace_back(SymbolID(), B.getType().getAsString());
626 }
627 for (const CXXBaseSpecifier &B : D->vbases()) {
628 if (const RecordDecl *P = getRecordDeclForType(B.getType()))
629 I.VirtualParents.emplace_back(
630 getUSRForDecl(P), P->getNameAsString(), InfoType::IT_record,
631 P->getQualifiedNameAsString(), getInfoRelativePath(P));
632 else
633 I.VirtualParents.emplace_back(SymbolID(), B.getType().getAsString());
634 }
635}
636
637template <typename T>
638static void
639populateParentNamespaces(llvm::SmallVector<Reference, 4> &Namespaces,
640 const T *D, bool &IsInAnonymousNamespace) {
641 const DeclContext *DC = D->getDeclContext();
642 do {
643 if (const auto *N = dyn_cast<NamespaceDecl>(DC)) {
644 std::string Namespace;
645 if (N->isAnonymousNamespace()) {
646 Namespace = "@nonymous_namespace";
647 IsInAnonymousNamespace = true;
648 } else
649 Namespace = N->getNameAsString();
650 Namespaces.emplace_back(getUSRForDecl(N), Namespace,
652 N->getQualifiedNameAsString());
653 } else if (const auto *N = dyn_cast<RecordDecl>(DC))
654 Namespaces.emplace_back(getUSRForDecl(N), N->getNameAsString(),
656 N->getQualifiedNameAsString());
657 else if (const auto *N = dyn_cast<FunctionDecl>(DC))
658 Namespaces.emplace_back(getUSRForDecl(N), N->getNameAsString(),
660 N->getQualifiedNameAsString());
661 else if (const auto *N = dyn_cast<EnumDecl>(DC))
662 Namespaces.emplace_back(getUSRForDecl(N), N->getNameAsString(),
663 InfoType::IT_enum, N->getQualifiedNameAsString());
664 } while ((DC = DC->getParent()));
665 // The global namespace should be added to the list of namespaces if the decl
666 // corresponds to a Record and if it doesn't have any namespace (because this
667 // means it's in the global namespace). Also if its outermost namespace is a
668 // record because that record matches the previous condition mentioned.
669 if ((Namespaces.empty() && isa<RecordDecl>(D)) ||
670 (!Namespaces.empty() && Namespaces.back().RefType == InfoType::IT_record))
671 Namespaces.emplace_back(SymbolID(), "GlobalNamespace",
673}
674
675static void
676populateTemplateParameters(std::optional<TemplateInfo> &TemplateInfo,
677 const clang::Decl *D) {
678 if (const TemplateParameterList *ParamList =
679 D->getDescribedTemplateParams()) {
680 if (!TemplateInfo) {
681 TemplateInfo.emplace();
682 }
683 for (const NamedDecl *ND : *ParamList) {
684 TemplateInfo->Params.emplace_back(
685 getSourceCode(ND, ND->getSourceRange()));
686 }
687 }
688}
689
690static TemplateParamInfo convertTemplateArgToInfo(const clang::Decl *D,
691 const TemplateArgument &Arg) {
692 // The TemplateArgument's pretty printing handles all the normal cases
693 // well enough for our requirements.
694 std::string Str;
695 llvm::raw_string_ostream Stream(Str);
696 Arg.print(PrintingPolicy(D->getLangOpts()), Stream, false);
697 return TemplateParamInfo(Str);
698}
699
700template <typename T>
701static void populateInfo(Info &I, const T *D, const FullComment *C,
702 bool &IsInAnonymousNamespace) {
703 I.USR = getUSRForDecl(D);
704 if (auto ConversionDecl = dyn_cast_or_null<CXXConversionDecl>(D);
705 ConversionDecl && ConversionDecl->getConversionType()
706 .getTypePtr()
707 ->isTemplateTypeParmType())
708 I.Name = "operator " + ConversionDecl->getConversionType().getAsString();
709 else
710 I.Name = D->getNameAsString();
711 populateParentNamespaces(I.Namespace, D, IsInAnonymousNamespace);
712 if (C) {
713 I.Description.emplace_back();
714 parseFullComment(C, I.Description.back());
715 }
716}
717
718template <typename T>
719static void populateSymbolInfo(SymbolInfo &I, const T *D, const FullComment *C,
720 Location Loc, bool &IsInAnonymousNamespace) {
721 populateInfo(I, D, C, IsInAnonymousNamespace);
722 if (D->isThisDeclarationADefinition())
723 I.DefLoc = Loc;
724 else
725 I.Loc.emplace_back(Loc);
726
727 auto *Mangler = ItaniumMangleContext::create(
728 D->getASTContext(), D->getASTContext().getDiagnostics());
729 std::string MangledName;
730 llvm::raw_string_ostream MangledStream(MangledName);
731 if (auto *CXXD = dyn_cast<CXXRecordDecl>(D))
732 Mangler->mangleCXXVTable(CXXD, MangledStream);
733 else
734 MangledStream << D->getNameAsString();
735 // A 250 length limit was chosen since 255 is a common limit across
736 // different filesystems, with a 5 character buffer for file extensions.
737 if (MangledName.size() > 250) {
738 auto SymbolID = llvm::toStringRef(llvm::toHex(I.USR)).str();
739 I.MangledName = MangledName.substr(0, 250 - SymbolID.size()) + SymbolID;
740 } else
741 I.MangledName = MangledName;
742 delete Mangler;
743}
744
745static void
746handleCompoundConstraints(const Expr *Constraint,
747 std::vector<ConstraintInfo> &ConstraintInfos) {
748 if (Constraint->getStmtClass() == Stmt::ParenExprClass) {
749 handleCompoundConstraints(dyn_cast<ParenExpr>(Constraint)->getSubExpr(),
750 ConstraintInfos);
751 } else if (Constraint->getStmtClass() == Stmt::BinaryOperatorClass) {
752 auto *BinaryOpExpr = dyn_cast<BinaryOperator>(Constraint);
753 handleCompoundConstraints(BinaryOpExpr->getLHS(), ConstraintInfos);
754 handleCompoundConstraints(BinaryOpExpr->getRHS(), ConstraintInfos);
755 } else if (Constraint->getStmtClass() ==
756 Stmt::ConceptSpecializationExprClass) {
757 auto *Concept = dyn_cast<ConceptSpecializationExpr>(Constraint);
758 ConstraintInfo CI(getUSRForDecl(Concept->getNamedConcept()),
759 Concept->getNamedConcept()->getNameAsString());
760 CI.ConstraintExpr = exprToString(Concept);
761 ConstraintInfos.push_back(CI);
762 }
763}
764
765static void populateConstraints(TemplateInfo &I, const TemplateDecl *D) {
766 if (!D || !D->hasAssociatedConstraints())
767 return;
768
769 SmallVector<AssociatedConstraint> AssociatedConstraints;
770 D->getAssociatedConstraints(AssociatedConstraints);
771 for (const auto &Constraint : AssociatedConstraints) {
772 if (!Constraint)
773 continue;
774
775 // TODO: Investigate if atomic constraints need to be handled specifically.
776 if (const auto *ConstraintExpr =
777 dyn_cast_or_null<ConceptSpecializationExpr>(
778 Constraint.ConstraintExpr)) {
779 ConstraintInfo CI(getUSRForDecl(ConstraintExpr->getNamedConcept()),
780 ConstraintExpr->getNamedConcept()->getNameAsString());
781 CI.ConstraintExpr = exprToString(ConstraintExpr);
782 I.Constraints.push_back(std::move(CI));
783 } else {
784 handleCompoundConstraints(Constraint.ConstraintExpr, I.Constraints);
785 }
786 }
787}
788
789static void populateFunctionInfo(FunctionInfo &I, const FunctionDecl *D,
790 const FullComment *FC, Location Loc,
791 bool &IsInAnonymousNamespace) {
792 populateSymbolInfo(I, D, FC, Loc, IsInAnonymousNamespace);
793 auto &LO = D->getLangOpts();
794 I.ReturnType = getTypeInfoForType(D->getReturnType(), LO);
796 parseParameters(I, D);
797 I.IsStatic = D->isStatic();
798
800 if (I.Template)
801 populateConstraints(I.Template.value(), D->getDescribedFunctionTemplate());
802
803 // Handle function template specializations.
804 if (const FunctionTemplateSpecializationInfo *FTSI =
805 D->getTemplateSpecializationInfo()) {
806 if (!I.Template)
807 I.Template.emplace();
808 I.Template->Specialization.emplace();
809 auto &Specialization = *I.Template->Specialization;
810
811 Specialization.SpecializationOf = getUSRForDecl(FTSI->getTemplate());
812
813 // Template parameters to the specialization.
814 if (FTSI->TemplateArguments) {
815 for (const TemplateArgument &Arg : FTSI->TemplateArguments->asArray()) {
816 Specialization.Params.push_back(convertTemplateArgToInfo(D, Arg));
817 }
818 }
819 }
820}
821
822static void populateMemberTypeInfo(MemberTypeInfo &I, const Decl *D) {
823 assert(D && "Expect non-null FieldDecl in populateMemberTypeInfo");
824
825 ASTContext &Context = D->getASTContext();
826 // TODO investigate whether we can use ASTContext::getCommentForDecl instead
827 // of this logic. See also similar code in Mapper.cpp.
828 RawComment *Comment = Context.getRawCommentForDeclNoCache(D);
829 if (!Comment)
830 return;
831
832 Comment->setAttached();
833 if (comments::FullComment *Fc = Comment->parse(Context, nullptr, D)) {
834 I.Description.emplace_back();
835 parseFullComment(Fc, I.Description.back());
836 }
837}
838
839static void populateMemberTypeInfo(RecordInfo &I, AccessSpecifier &Access,
840 const DeclaratorDecl *D, bool IsStatic) {
841 // Use getAccessUnsafe so that we just get the default AS_none if it's not
842 // valid, as opposed to an assert.
843 MemberTypeInfo &NewMember = I.Members.emplace_back(
844 getTypeInfoForType(D->getTypeSourceInfo()->getType(), D->getLangOpts()),
845 D->getNameAsString(),
846 getFinalAccessSpecifier(Access, D->getAccessUnsafe()), IsStatic);
847 populateMemberTypeInfo(NewMember, D);
848}
849
850static void
851parseBases(RecordInfo &I, const CXXRecordDecl *D, bool IsFileInRootDir,
852 bool PublicOnly, bool IsParent,
853 AccessSpecifier ParentAccess = AccessSpecifier::AS_public) {
854 // Don't parse bases if this isn't a definition.
855 if (!D->isThisDeclarationADefinition())
856 return;
857 for (const CXXBaseSpecifier &B : D->bases()) {
858 if (const auto *Base = B.getType()->getAsCXXRecordDecl()) {
859 if (Base->isCompleteDefinition()) {
860 // Initialized without USR and name, this will be set in the following
861 // if-else stmt.
863 {}, "", getInfoRelativePath(Base), B.isVirtual(),
864 getFinalAccessSpecifier(ParentAccess, B.getAccessSpecifier()),
865 IsParent);
866 if (const auto *Ty = B.getType()->getAs<TemplateSpecializationType>()) {
867 const TemplateDecl *D = Ty->getTemplateName().getAsTemplateDecl();
868 BI.USR = getUSRForDecl(D);
869 BI.Name = B.getType().getAsString();
870 } else {
871 BI.USR = getUSRForDecl(Base);
872 BI.Name = Base->getNameAsString();
873 }
874 parseFields(BI, Base, PublicOnly, BI.Access);
875 for (const auto &Decl : Base->decls())
876 if (const auto *MD = dyn_cast<CXXMethodDecl>(Decl)) {
877 // Don't serialize private methods
878 if (MD->getAccessUnsafe() == AccessSpecifier::AS_private ||
879 !MD->isUserProvided())
880 continue;
881 FunctionInfo FI;
882 FI.IsMethod = true;
883 FI.IsStatic = MD->isStatic();
884 // The seventh arg in populateFunctionInfo is a boolean passed by
885 // reference, its value is not relevant in here so it's not used
886 // anywhere besides the function call.
887 bool IsInAnonymousNamespace;
888 populateFunctionInfo(FI, MD, /*FullComment=*/{}, /*Location=*/{},
889 IsInAnonymousNamespace);
890 FI.Access =
891 getFinalAccessSpecifier(BI.Access, MD->getAccessUnsafe());
892 BI.Children.Functions.emplace_back(std::move(FI));
893 }
894 I.Bases.emplace_back(std::move(BI));
895 // Call this function recursively to get the inherited classes of
896 // this base; these new bases will also get stored in the original
897 // RecordInfo: I.
898 parseBases(I, Base, IsFileInRootDir, PublicOnly, false,
899 I.Bases.back().Access);
900 }
901 }
902 }
903}
904
905std::pair<std::unique_ptr<Info>, std::unique_ptr<Info>>
906emitInfo(const NamespaceDecl *D, const FullComment *FC, Location Loc,
907 bool PublicOnly) {
908 auto NSI = std::make_unique<NamespaceInfo>();
909 bool IsInAnonymousNamespace = false;
910 populateInfo(*NSI, D, FC, IsInAnonymousNamespace);
911 if (!shouldSerializeInfo(PublicOnly, IsInAnonymousNamespace, D))
912 return {};
913
914 NSI->Name = D->isAnonymousNamespace()
915 ? llvm::SmallString<16>("@nonymous_namespace")
916 : NSI->Name;
917 NSI->Path = getInfoRelativePath(NSI->Namespace);
918 if (NSI->Namespace.empty() && NSI->USR == SymbolID())
919 return {std::unique_ptr<Info>{std::move(NSI)}, nullptr};
920
921 // Namespaces are inserted into the parent by reference, so we need to return
922 // both the parent and the record itself.
923 return {std::move(NSI), makeAndInsertIntoParent<const NamespaceInfo &>(*NSI)};
924}
925
926static void parseFriends(RecordInfo &RI, const CXXRecordDecl *D) {
927 if (!D->hasDefinition() || !D->hasFriends())
928 return;
929
930 for (const FriendDecl *FD : D->friends()) {
931 if (FD->isUnsupportedFriend())
932 continue;
933
935 const auto *ActualDecl = FD->getFriendDecl();
936 if (!ActualDecl) {
937 const auto *FriendTypeInfo = FD->getFriendType();
938 if (!FriendTypeInfo)
939 continue;
940 ActualDecl = FriendTypeInfo->getType()->getAsCXXRecordDecl();
941
942 if (!ActualDecl)
943 continue;
944 F.IsClass = true;
945 }
946
947 if (const auto *ActualTD = dyn_cast_or_null<TemplateDecl>(ActualDecl)) {
948 if (isa<RecordDecl>(ActualTD->getTemplatedDecl()))
949 F.IsClass = true;
950 F.Template.emplace();
951 for (const auto *Param : ActualTD->getTemplateParameters()->asArray())
952 F.Template->Params.emplace_back(
953 getSourceCode(Param, Param->getSourceRange()));
954 ActualDecl = ActualTD->getTemplatedDecl();
955 }
956
957 if (auto *FuncDecl = dyn_cast_or_null<FunctionDecl>(ActualDecl)) {
958 FunctionInfo TempInfo;
959 parseParameters(TempInfo, FuncDecl);
960 F.Params.emplace();
961 F.Params = std::move(TempInfo.Params);
962 F.ReturnType = getTypeInfoForType(FuncDecl->getReturnType(),
963 FuncDecl->getLangOpts());
964 }
965
966 F.Ref =
967 Reference(getUSRForDecl(ActualDecl), ActualDecl->getNameAsString(),
968 InfoType::IT_default, ActualDecl->getQualifiedNameAsString(),
969 getInfoRelativePath(ActualDecl));
970
971 RI.Friends.push_back(std::move(F));
972 }
973}
974
975std::pair<std::unique_ptr<Info>, std::unique_ptr<Info>>
976emitInfo(const RecordDecl *D, const FullComment *FC, Location Loc,
977 bool PublicOnly) {
978
979 auto RI = std::make_unique<RecordInfo>();
980 bool IsInAnonymousNamespace = false;
981
982 populateSymbolInfo(*RI, D, FC, Loc, IsInAnonymousNamespace);
983 if (!shouldSerializeInfo(PublicOnly, IsInAnonymousNamespace, D))
984 return {};
985
986 RI->TagType = D->getTagKind();
987 parseFields(*RI, D, PublicOnly);
988
989 if (const auto *C = dyn_cast<CXXRecordDecl>(D)) {
990 if (const TypedefNameDecl *TD = C->getTypedefNameForAnonDecl()) {
991 RI->Name = TD->getNameAsString();
992 RI->IsTypeDef = true;
993 }
994 // TODO: remove first call to parseBases, that function should be deleted
995 parseBases(*RI, C);
996 parseBases(*RI, C, /*IsFileInRootDir=*/true, PublicOnly, /*IsParent=*/true);
997 parseFriends(*RI, C);
998 }
999 RI->Path = getInfoRelativePath(RI->Namespace);
1000
1001 populateTemplateParameters(RI->Template, D);
1002 if (RI->Template)
1003 populateConstraints(RI->Template.value(), D->getDescribedTemplate());
1004
1005 // Full and partial specializations.
1006 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
1007 if (!RI->Template)
1008 RI->Template.emplace();
1009 RI->Template->Specialization.emplace();
1010 auto &Specialization = *RI->Template->Specialization;
1011
1012 // What this is a specialization of.
1013 auto SpecOf = CTSD->getSpecializedTemplateOrPartial();
1014 if (auto *SpecTD = dyn_cast<ClassTemplateDecl *>(SpecOf))
1015 Specialization.SpecializationOf = getUSRForDecl(SpecTD);
1016 else if (auto *SpecTD =
1017 dyn_cast<ClassTemplatePartialSpecializationDecl *>(SpecOf))
1018 Specialization.SpecializationOf = getUSRForDecl(SpecTD);
1019
1020 // Parameters to the specialization. For partial specializations, get the
1021 // parameters "as written" from the ClassTemplatePartialSpecializationDecl
1022 // because the non-explicit template parameters will have generated internal
1023 // placeholder names rather than the names the user typed that match the
1024 // template parameters.
1025 if (const ClassTemplatePartialSpecializationDecl *CTPSD =
1026 dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
1027 if (const ASTTemplateArgumentListInfo *AsWritten =
1028 CTPSD->getTemplateArgsAsWritten()) {
1029 for (unsigned Idx = 0; Idx < AsWritten->getNumTemplateArgs(); Idx++) {
1030 Specialization.Params.emplace_back(
1031 getSourceCode(D, (*AsWritten)[Idx].getSourceRange()));
1032 }
1033 }
1034 } else {
1035 for (const TemplateArgument &Arg : CTSD->getTemplateArgs().asArray()) {
1036 Specialization.Params.push_back(convertTemplateArgToInfo(D, Arg));
1037 }
1038 }
1039 }
1040
1041 // Records are inserted into the parent by reference, so we need to return
1042 // both the parent and the record itself.
1044 return {std::move(RI), std::move(Parent)};
1045}
1046
1047std::pair<std::unique_ptr<Info>, std::unique_ptr<Info>>
1048emitInfo(const FunctionDecl *D, const FullComment *FC, Location Loc,
1049 bool PublicOnly) {
1050 FunctionInfo Func;
1051 bool IsInAnonymousNamespace = false;
1052 populateFunctionInfo(Func, D, FC, Loc, IsInAnonymousNamespace);
1053 Func.Access = clang::AccessSpecifier::AS_none;
1054 if (!shouldSerializeInfo(PublicOnly, IsInAnonymousNamespace, D))
1055 return {};
1056
1057 // Info is wrapped in its parent scope so is returned in the second position.
1058 return {nullptr, makeAndInsertIntoParent<FunctionInfo &&>(std::move(Func))};
1059}
1060
1061std::pair<std::unique_ptr<Info>, std::unique_ptr<Info>>
1062emitInfo(const CXXMethodDecl *D, const FullComment *FC, Location Loc,
1063 bool PublicOnly) {
1064 FunctionInfo Func;
1065 bool IsInAnonymousNamespace = false;
1066 populateFunctionInfo(Func, D, FC, Loc, IsInAnonymousNamespace);
1067 if (!shouldSerializeInfo(PublicOnly, IsInAnonymousNamespace, D))
1068 return {};
1069
1070 Func.IsMethod = true;
1071 Func.IsStatic = D->isStatic();
1072
1073 const NamedDecl *Parent = nullptr;
1074 if (const auto *SD =
1075 dyn_cast<ClassTemplateSpecializationDecl>(D->getParent()))
1076 Parent = SD->getSpecializedTemplate();
1077 else
1078 Parent = D->getParent();
1079
1080 SymbolID ParentUSR = getUSRForDecl(Parent);
1081 Func.Parent =
1082 Reference{ParentUSR, Parent->getNameAsString(), InfoType::IT_record,
1083 Parent->getQualifiedNameAsString()};
1084 Func.Access = D->getAccess();
1085
1086 // Info is wrapped in its parent scope so is returned in the second position.
1087 return {nullptr, makeAndInsertIntoParent<FunctionInfo &&>(std::move(Func))};
1088}
1089
1090static void extractCommentFromDecl(const Decl *D, TypedefInfo &Info) {
1091 assert(D && "Invalid Decl when extracting comment");
1092 ASTContext &Context = D->getASTContext();
1093 RawComment *Comment = Context.getRawCommentForDeclNoCache(D);
1094 if (!Comment)
1095 return;
1096
1097 Comment->setAttached();
1098 if (comments::FullComment *Fc = Comment->parse(Context, nullptr, D)) {
1099 Info.Description.emplace_back();
1100 parseFullComment(Fc, Info.Description.back());
1101 }
1102}
1103
1104std::pair<std::unique_ptr<Info>, std::unique_ptr<Info>>
1105emitInfo(const TypedefDecl *D, const FullComment *FC, Location Loc,
1106 bool PublicOnly) {
1108 bool IsInAnonymousNamespace = false;
1109 populateInfo(Info, D, FC, IsInAnonymousNamespace);
1110
1111 if (!shouldSerializeInfo(PublicOnly, IsInAnonymousNamespace, D))
1112 return {};
1113
1114 Info.DefLoc = Loc;
1115 auto &LO = D->getLangOpts();
1116 Info.Underlying = getTypeInfoForType(D->getUnderlyingType(), LO);
1117
1118 if (Info.Underlying.Type.Name.empty()) {
1119 // Typedef for an unnamed type. This is like "typedef struct { } Foo;"
1120 // The record serializer explicitly checks for this syntax and constructs
1121 // a record with that name, so we don't want to emit a duplicate here.
1122 return {};
1123 }
1124 Info.IsUsing = false;
1126
1127 // Info is wrapped in its parent scope so is returned in the second position.
1128 return {nullptr, makeAndInsertIntoParent<TypedefInfo &&>(std::move(Info))};
1129}
1130
1131// A type alias is a C++ "using" declaration for a type. It gets mapped to a
1132// TypedefInfo with the IsUsing flag set.
1133std::pair<std::unique_ptr<Info>, std::unique_ptr<Info>>
1134emitInfo(const TypeAliasDecl *D, const FullComment *FC, Location Loc,
1135 bool PublicOnly) {
1137 bool IsInAnonymousNamespace = false;
1138 populateInfo(Info, D, FC, IsInAnonymousNamespace);
1139 if (!shouldSerializeInfo(PublicOnly, IsInAnonymousNamespace, D))
1140 return {};
1141
1142 Info.DefLoc = Loc;
1143 const LangOptions &LO = D->getLangOpts();
1144 Info.Underlying = getTypeInfoForType(D->getUnderlyingType(), LO);
1145 Info.TypeDeclaration = getTypeAlias(D);
1146 Info.IsUsing = true;
1147
1149
1150 // Info is wrapped in its parent scope so is returned in the second position.
1151 return {nullptr, makeAndInsertIntoParent<TypedefInfo &&>(std::move(Info))};
1152}
1153
1154std::pair<std::unique_ptr<Info>, std::unique_ptr<Info>>
1155emitInfo(const EnumDecl *D, const FullComment *FC, Location Loc,
1156 bool PublicOnly) {
1157 EnumInfo Enum;
1158 bool IsInAnonymousNamespace = false;
1159 populateSymbolInfo(Enum, D, FC, Loc, IsInAnonymousNamespace);
1160
1161 if (!shouldSerializeInfo(PublicOnly, IsInAnonymousNamespace, D))
1162 return {};
1163
1164 Enum.Scoped = D->isScoped();
1165 if (D->isFixed()) {
1166 auto Name = D->getIntegerType().getAsString();
1167 Enum.BaseType = TypeInfo(Name, Name);
1168 }
1169 parseEnumerators(Enum, D);
1170
1171 // Info is wrapped in its parent scope so is returned in the second position.
1172 return {nullptr, makeAndInsertIntoParent<EnumInfo &&>(std::move(Enum))};
1173}
1174
1175std::pair<std::unique_ptr<Info>, std::unique_ptr<Info>>
1176emitInfo(const ConceptDecl *D, const FullComment *FC, const Location &Loc,
1177 bool PublicOnly) {
1178 ConceptInfo Concept;
1179
1180 bool IsInAnonymousNamespace = false;
1181 populateInfo(Concept, D, FC, IsInAnonymousNamespace);
1182 Concept.IsType = D->isTypeConcept();
1183 Concept.DefLoc = Loc;
1184 Concept.ConstraintExpression = exprToString(D->getConstraintExpr());
1185
1186 if (auto *ConceptParams = D->getTemplateParameters()) {
1187 for (const auto *Param : ConceptParams->asArray()) {
1188 Concept.Template.Params.emplace_back(
1189 getSourceCode(Param, Param->getSourceRange()));
1190 }
1191 }
1192
1193 if (!shouldSerializeInfo(PublicOnly, IsInAnonymousNamespace, D))
1194 return {};
1195
1196 return {nullptr, makeAndInsertIntoParent<ConceptInfo &&>(std::move(Concept))};
1197}
1198
1199std::pair<std::unique_ptr<Info>, std::unique_ptr<Info>>
1200emitInfo(const VarDecl *D, const FullComment *FC, const Location &Loc,
1201 bool PublicOnly) {
1202 VarInfo Var;
1203 bool IsInAnonymousNamespace = false;
1204 populateSymbolInfo(Var, D, FC, Loc, IsInAnonymousNamespace);
1205 if (!shouldSerializeInfo(PublicOnly, IsInAnonymousNamespace, D))
1206 return {};
1207
1208 if (D->getStorageClass() == StorageClass::SC_Static)
1209 Var.IsStatic = true;
1210 Var.Type =
1211 getTypeInfoForType(D->getType(), D->getASTContext().getPrintingPolicy());
1212
1213 if (!shouldSerializeInfo(PublicOnly, IsInAnonymousNamespace, D))
1214 return {};
1215
1216 return {nullptr, makeAndInsertIntoParent<VarInfo &&>(std::move(Var))};
1217}
1218
1219} // namespace serialize
1220} // namespace doc
1221} // namespace clang
static llvm::cl::opt< bool > PublicOnly("public", llvm::cl::desc("Document only public declarations."), llvm::cl::init(false), llvm::cl::cat(ClangDocCategory))
void emitBlock(const NamespaceInfo &I)
void visitHTMLEndTagComment(const HTMLEndTagComment *C)
void visitVerbatimLineComment(const VerbatimLineComment *C)
void visitVerbatimBlockLineComment(const VerbatimBlockLineComment *C)
void visitHTMLStartTagComment(const HTMLStartTagComment *C)
void visitTParamCommandComment(const TParamCommandComment *C)
void visitVerbatimBlockComment(const VerbatimBlockComment *C)
void visitParamCommandComment(const ParamCommandComment *C)
void visitInlineCommandComment(const InlineCommandComment *C)
void parseComment(const comments::Comment *C)
void visitTextComment(const TextComment *C)
void visitBlockCommandComment(const BlockCommandComment *C)
static void parseFields(RecordInfo &I, const RecordDecl *D, bool PublicOnly, AccessSpecifier Access=AccessSpecifier::AS_public)
static void extractCommentFromDecl(const Decl *D, TypedefInfo &Info)
static void populateConstraints(TemplateInfo &I, const TemplateDecl *D)
static bool shouldSerializeInfo(bool PublicOnly, bool IsInAnonymousNamespace, const NamedDecl *D)
static std::unique_ptr< Info > makeAndInsertIntoParent(ChildType Child)
static RecordDecl * getRecordDeclForType(const QualType &T)
std::pair< std::unique_ptr< Info >, std::unique_ptr< Info > > emitInfo(const NamespaceDecl *D, const FullComment *FC, Location Loc, bool PublicOnly)
static bool isPublic(const clang::AccessSpecifier AS, const clang::Linkage Link)
static void parseFriends(RecordInfo &RI, const CXXRecordDecl *D)
static void parseFullComment(const FullComment *C, CommentInfo &CI)
static void getTemplateParameters(const TemplateParameterList *TemplateParams, llvm::raw_ostream &Stream)
Definition Serialize.cpp:54
static void parseParameters(FunctionInfo &I, const FunctionDecl *D)
static void populateMemberTypeInfo(MemberTypeInfo &I, const Decl *D)
static SymbolID getUSRForDecl(const Decl *D)
static AccessSpecifier getFinalAccessSpecifier(AccessSpecifier FirstAS, AccessSpecifier SecondAS)
static std::string serialize(T &I, DiagnosticsEngine &Diags)
static llvm::SmallString< 128 > getInfoRelativePath(const llvm::SmallVectorImpl< doc::Reference > &Namespaces)
static void populateFunctionInfo(FunctionInfo &I, const FunctionDecl *D, const FullComment *FC, Location Loc, bool &IsInAnonymousNamespace)
static TemplateParamInfo convertTemplateArgToInfo(const clang::Decl *D, const TemplateArgument &Arg)
static void populateTemplateParameters(std::optional< TemplateInfo > &TemplateInfo, const clang::Decl *D)
static void InsertChild(ScopeChildren &Scope, const NamespaceInfo &Info)
static TypeInfo getTypeInfoForType(const QualType &T, const PrintingPolicy &Policy)
static llvm::SmallString< 16 > getTypeAlias(const TypeAliasDecl *Alias)
static void populateParentNamespaces(llvm::SmallVector< Reference, 4 > &Namespaces, const T *D, bool &IsAnonymousNamespace)
static std::string getSourceCode(const Decl *D, const SourceRange &R)
static void populateSymbolInfo(SymbolInfo &I, const T *D, const FullComment *C, Location Loc, bool &IsInAnonymousNamespace)
static void parseEnumerators(EnumInfo &I, const EnumDecl *D)
static TagDecl * getTagDeclForType(const QualType &T)
static void parseBases(RecordInfo &I, const CXXRecordDecl *D)
static llvm::SmallString< 256 > getFunctionPrototype(const FunctionDecl *FuncDecl)
SymbolID hashUSR(llvm::StringRef USR)
Definition Serialize.cpp:40
static void handleCompoundConstraints(const Expr *Constraint, std::vector< ConstraintInfo > &ConstraintInfos)
static void populateInfo(Info &I, const T *D, const FullComment *C, bool &IsInAnonymousNamespace)
static GeneratorRegistry::Add< MDGenerator > MD(MDGenerator::Format, "Generator for MD output.")
CommentKind stringToCommentKind(llvm::StringRef KindStr)
std::array< uint8_t, 20 > SymbolID
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
SmallString< 16 > ConstraintExpr
llvm::SmallVector< EnumValueInfo, 4 > Members
std::vector< CommentInfo > Description
Comment description of this field.
SmallString< 16 > DefaultValue
std::optional< TypeInfo > ReturnType
std::optional< SmallVector< FieldTypeInfo, 4 > > Params
std::optional< TemplateInfo > Template
llvm::SmallVector< FieldTypeInfo, 4 > Params
std::optional< TemplateInfo > Template
SmallString< 256 > Prototype
A base struct for Infos.
SmallString< 16 > Name
std::vector< CommentInfo > Description
llvm::SmallVector< Reference, 4 > Namespace
std::vector< CommentInfo > Description
llvm::SmallVector< MemberTypeInfo, 4 > Members
std::vector< FriendInfo > Friends
llvm::SmallVector< Reference, 4 > VirtualParents
llvm::SmallVector< Reference, 4 > Parents
std::vector< BaseRecordInfo > Bases
std::vector< Reference > Records
std::vector< TypedefInfo > Typedefs
std::vector< FunctionInfo > Functions
std::vector< Reference > Namespaces
std::vector< VarInfo > Variables
std::vector< EnumInfo > Enums
std::vector< ConceptInfo > Concepts
llvm::SmallVector< Location, 2 > Loc
std::optional< Location > DefLoc
SmallString< 16 > MangledName
std::vector< ConstraintInfo > Constraints
std::vector< TemplateParamInfo > Params
static constexpr const char FuncDecl[]