20#include "clang-include-cleaner/Analysis.h"
21#include "clang-include-cleaner/IncludeSpeller.h"
22#include "clang-include-cleaner/Types.h"
26#include "clang/AST/ASTContext.h"
27#include "clang/AST/ASTDiagnostic.h"
28#include "clang/AST/ASTTypeTraits.h"
29#include "clang/AST/Attr.h"
30#include "clang/AST/Decl.h"
31#include "clang/AST/DeclBase.h"
32#include "clang/AST/DeclCXX.h"
33#include "clang/AST/DeclObjC.h"
34#include "clang/AST/DeclTemplate.h"
35#include "clang/AST/Expr.h"
36#include "clang/AST/ExprCXX.h"
37#include "clang/AST/OperationKinds.h"
38#include "clang/AST/PrettyPrinter.h"
39#include "clang/AST/RecordLayout.h"
40#include "clang/AST/Type.h"
41#include "clang/Basic/CharInfo.h"
42#include "clang/Basic/LLVM.h"
43#include "clang/Basic/SourceLocation.h"
44#include "clang/Basic/SourceManager.h"
45#include "clang/Basic/Specifiers.h"
46#include "clang/Basic/TokenKinds.h"
47#include "clang/Index/IndexSymbol.h"
48#include "clang/Tooling/Syntax/Tokens.h"
49#include "llvm/ADT/ArrayRef.h"
50#include "llvm/ADT/DenseSet.h"
51#include "llvm/ADT/STLExtras.h"
52#include "llvm/ADT/SmallVector.h"
53#include "llvm/ADT/StringExtras.h"
54#include "llvm/ADT/StringRef.h"
55#include "llvm/Support/Casting.h"
56#include "llvm/Support/Error.h"
57#include "llvm/Support/Format.h"
58#include "llvm/Support/ScopedPrinter.h"
59#include "llvm/Support/raw_ostream.h"
69PrintingPolicy getPrintingPolicy(PrintingPolicy Base) {
70 Base.AnonymousTagLocations =
false;
71 Base.TerseOutput =
true;
72 Base.PolishForDeclaration =
true;
73 Base.ConstantsAsWritten =
true;
74 Base.SuppressTemplateArgsInCXXConstructors =
true;
81std::string getLocalScope(
const Decl *D) {
82 std::vector<std::string> Scopes;
83 const DeclContext *DC = D->getDeclContext();
88 if (
const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
90 if (
const ObjCContainerDecl *CD = dyn_cast<ObjCContainerDecl>(DC))
93 auto GetName = [](
const TypeDecl *D) {
94 if (!D->getDeclName().isEmpty()) {
95 PrintingPolicy Policy = D->getASTContext().getPrintingPolicy();
96 Policy.SuppressScope =
true;
99 if (
auto *RD = dyn_cast<RecordDecl>(D))
100 return (
"(anonymous " + RD->getKindName() +
")").str();
101 return std::string(
"");
104 if (
const TypeDecl *TD = dyn_cast<TypeDecl>(DC))
105 Scopes.push_back(GetName(TD));
106 else if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
107 Scopes.push_back(FD->getNameAsString());
108 DC = DC->getParent();
111 return llvm::join(llvm::reverse(Scopes),
"::");
116std::string getNamespaceScope(
const Decl *D) {
117 const DeclContext *DC = D->getDeclContext();
121 if (isa<ObjCMethodDecl, ObjCContainerDecl>(DC))
124 if (
const TagDecl *TD = dyn_cast<TagDecl>(DC))
125 return getNamespaceScope(TD);
126 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
127 return getNamespaceScope(FD);
128 if (
const NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(DC)) {
130 if (NSD->isInline() || NSD->isAnonymousNamespace())
131 return getNamespaceScope(NSD);
133 if (
const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
139std::string printDefinition(
const Decl *D, PrintingPolicy PP,
140 const syntax::TokenBuffer &TB) {
141 if (
auto *VD = llvm::dyn_cast<VarDecl>(D)) {
142 if (
auto *IE = VD->getInit()) {
146 if (200 < TB.expandedTokens(IE->getSourceRange()).size())
147 PP.SuppressInitializers =
true;
157const char *getMarkdownLanguage(
const ASTContext &Ctx) {
158 const auto &LangOpts = Ctx.getLangOpts();
159 if (LangOpts.ObjC && LangOpts.CPlusPlus)
160 return "objective-cpp";
161 return LangOpts.ObjC ?
"objective-c" :
"cpp";
164HoverInfo::PrintedType
printType(QualType QT, ASTContext &ASTCtx,
165 const PrintingPolicy &PP) {
169 while (!QT.isNull() && QT->isDecltypeType())
170 QT = QT->castAs<DecltypeType>()->getUnderlyingType();
171 HoverInfo::PrintedType Result;
172 llvm::raw_string_ostream
OS(Result.Type);
177 if (!QT.isNull() && !QT.hasQualifiers() && PP.SuppressTagKeyword) {
178 if (
auto *TT = llvm::dyn_cast<TagType>(QT.getTypePtr()))
179 OS << TT->getDecl()->getKindName() <<
" ";
186 bool ShouldAKA =
false;
187 QualType DesugaredTy = clang::desugarForDiagnostic(ASTCtx, QT, ShouldAKA);
189 Result.AKA = DesugaredTy.getAsString(PP);
194HoverInfo::PrintedType
printType(
const TemplateTypeParmDecl *TTP) {
195 HoverInfo::PrintedType Result;
196 Result.Type = TTP->wasDeclaredWithTypename() ?
"typename" :
"class";
197 if (TTP->isParameterPack())
198 Result.Type +=
"...";
202HoverInfo::PrintedType
printType(
const NonTypeTemplateParmDecl *NTTP,
203 const PrintingPolicy &PP) {
204 auto PrintedType =
printType(NTTP->getType(), NTTP->getASTContext(), PP);
205 if (NTTP->isParameterPack()) {
206 PrintedType.Type +=
"...";
208 *PrintedType.AKA +=
"...";
213HoverInfo::PrintedType
printType(
const TemplateTemplateParmDecl *TTP,
214 const PrintingPolicy &PP) {
215 HoverInfo::PrintedType Result;
216 llvm::raw_string_ostream
OS(Result.Type);
218 llvm::StringRef Sep =
"";
219 for (
const Decl *Param : *TTP->getTemplateParameters()) {
222 if (
const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
224 else if (
const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
226 else if (
const auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param))
236std::vector<HoverInfo::Param>
237fetchTemplateParameters(
const TemplateParameterList *Params,
238 const PrintingPolicy &PP) {
240 std::vector<HoverInfo::Param> TempParameters;
242 for (
const Decl *Param : *Params) {
244 if (
const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
247 if (!TTP->getName().empty())
248 P.Name = TTP->getNameAsString();
250 if (TTP->hasDefaultArgument()) {
252 llvm::raw_string_ostream
Out(*P.Default);
253 TTP->getDefaultArgument().getArgument().print(PP,
Out,
256 }
else if (
const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
259 if (IdentifierInfo *II = NTTP->getIdentifier())
260 P.Name = II->getName().str();
262 if (NTTP->hasDefaultArgument()) {
264 llvm::raw_string_ostream
Out(*P.Default);
265 NTTP->getDefaultArgument().getArgument().print(PP,
Out,
268 }
else if (
const auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param)) {
271 if (!TTPD->getName().empty())
272 P.Name = TTPD->getNameAsString();
274 if (TTPD->hasDefaultArgument()) {
276 llvm::raw_string_ostream
Out(*P.Default);
277 TTPD->getDefaultArgument().getArgument().print(PP,
Out,
281 TempParameters.push_back(std::move(P));
284 return TempParameters;
287const FunctionDecl *getUnderlyingFunction(
const Decl *D) {
289 if (
const VarDecl *VD = llvm::dyn_cast<VarDecl>(D)) {
290 auto QT = VD->getType();
292 while (!QT->getPointeeType().isNull())
293 QT = QT->getPointeeType();
295 if (
const auto *CD = QT->getAsCXXRecordDecl())
296 return CD->getLambdaCallOperator();
301 return D->getAsFunction();
306const NamedDecl *getDeclForComment(
const NamedDecl *D) {
307 const NamedDecl *DeclForComment = D;
308 if (
const auto *TSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(D)) {
311 if (TSD->getTemplateSpecializationKind() == TSK_Undeclared)
312 DeclForComment = TSD->getSpecializedTemplate();
313 else if (
const auto *TIP = TSD->getTemplateInstantiationPattern())
314 DeclForComment = TIP;
315 }
else if (
const auto *TSD =
316 llvm::dyn_cast<VarTemplateSpecializationDecl>(D)) {
317 if (TSD->getTemplateSpecializationKind() == TSK_Undeclared)
318 DeclForComment = TSD->getSpecializedTemplate();
319 else if (
const auto *TIP = TSD->getTemplateInstantiationPattern())
320 DeclForComment = TIP;
321 }
else if (
const auto *FD = D->getAsFunction())
322 if (
const auto *TIP = FD->getTemplateInstantiationPattern())
323 DeclForComment = TIP;
328 if (D != DeclForComment)
329 DeclForComment = getDeclForComment(DeclForComment);
330 return DeclForComment;
334void enhanceFromIndex(HoverInfo &Hover,
const NamedDecl &ND,
335 const SymbolIndex *Index) {
336 assert(&ND == getDeclForComment(&ND));
338 if (!Hover.Documentation.empty() || !Index)
344 SymbolCollector::Options(),
352 Index->lookup(Req, [&](
const Symbol &S) {
353 Hover.Documentation = std::string(S.Documentation);
360const Expr *getDefaultArg(
const ParmVarDecl *PVD) {
365 if (!PVD->hasDefaultArg() || PVD->hasUnparsedDefaultArg())
367 return PVD->hasUninstantiatedDefaultArg() ? PVD->getUninstantiatedDefaultArg()
368 : PVD->getDefaultArg();
371HoverInfo::Param toHoverInfoParam(
const ParmVarDecl *PVD,
372 const PrintingPolicy &PP) {
373 HoverInfo::Param
Out;
374 Out.Type =
printType(PVD->getType(), PVD->getASTContext(), PP);
375 if (!PVD->getName().empty())
376 Out.Name = PVD->getNameAsString();
377 if (
const Expr *DefArg = getDefaultArg(PVD)) {
378 Out.Default.emplace();
379 llvm::raw_string_ostream
OS(*
Out.Default);
380 DefArg->printPretty(
OS,
nullptr, PP);
386void fillFunctionTypeAndParams(HoverInfo &HI,
const Decl *D,
387 const FunctionDecl *FD,
388 const PrintingPolicy &PP) {
389 HI.Parameters.emplace();
390 for (
const ParmVarDecl *PVD : FD->parameters())
391 HI.Parameters->emplace_back(toHoverInfoParam(PVD, PP));
395 const auto NK = FD->getDeclName().getNameKind();
396 if (NK == DeclarationName::CXXConstructorName ||
397 NK == DeclarationName::CXXDestructorName ||
398 NK == DeclarationName::CXXConversionFunctionName)
401 HI.ReturnType =
printType(FD->getReturnType(), FD->getASTContext(), PP);
402 QualType QT = FD->getType();
403 if (
const VarDecl *VD = llvm::dyn_cast<VarDecl>(D))
404 QT = VD->getType().getDesugaredType(D->getASTContext());
405 HI.Type =
printType(QT, D->getASTContext(), PP);
415static llvm::FormattedNumber printHex(
const llvm::APSInt &V) {
416 assert(V.getSignificantBits() <= 64 &&
"Can't print more than 64 bits.");
418 V.getBitWidth() > 64 ? V.trunc(64).getZExtValue() : V.getZExtValue();
419 if (V.isNegative() && V.getSignificantBits() <= 32)
420 return llvm::format_hex(uint32_t(Bits), 0);
421 return llvm::format_hex(Bits, 0);
424std::optional<std::string> printExprValue(
const Expr *
E,
425 const ASTContext &Ctx) {
430 if (
const auto *ILE = llvm::dyn_cast<InitListExpr>(
E)) {
431 if (!ILE->isSemanticForm())
432 E = ILE->getSemanticForm();
438 QualType
T =
E->getType();
439 if (
T.isNull() ||
T->isFunctionType() ||
T->isFunctionPointerType() ||
440 T->isFunctionReferenceType() ||
T->isVoidType())
445 if (
E->isValueDependent() || !
E->EvaluateAsRValue(
Constant, Ctx) ||
452 if (
T->isEnumeralType() &&
Constant.Val.isInt() &&
453 Constant.Val.getInt().getSignificantBits() <= 64) {
455 int64_t Val =
Constant.Val.getInt().getExtValue();
456 for (
const EnumConstantDecl *ECD :
457 T->castAs<EnumType>()->getDecl()->enumerators())
458 if (ECD->getInitVal() == Val)
459 return llvm::formatv(
"{0} ({1})", ECD->getNameAsString(),
464 if (
T->isIntegralOrEnumerationType() &&
Constant.Val.isInt() &&
465 Constant.Val.getInt().getSignificantBits() <= 64 &&
467 return llvm::formatv(
"{0} ({1})",
Constant.Val.getAsString(Ctx, T),
470 return Constant.Val.getAsString(Ctx, T);
473struct PrintExprResult {
488PrintExprResult printExprValue(
const SelectionTree::Node *N,
489 const ASTContext &Ctx) {
490 for (; N; N = N->Parent) {
492 if (
const Expr *
E = N->ASTNode.get<Expr>()) {
495 if (!
E->getType().isNull() &&
E->getType()->isVoidType())
497 if (
auto Val = printExprValue(
E, Ctx))
498 return PrintExprResult{std::move(Val),
E,
500 }
else if (N->ASTNode.get<
Decl>() || N->ASTNode.get<Stmt>()) {
506 return PrintExprResult{std::nullopt,
nullptr,
510std::optional<StringRef> fieldName(
const Expr *
E) {
511 const auto *ME = llvm::dyn_cast<MemberExpr>(
E->IgnoreCasts());
512 if (!ME || !llvm::isa<CXXThisExpr>(ME->getBase()->IgnoreCasts()))
514 const auto *
Field = llvm::dyn_cast<FieldDecl>(ME->getMemberDecl());
515 if (!
Field || !
Field->getDeclName().isIdentifier())
517 return Field->getDeclName().getAsIdentifierInfo()->getName();
521std::optional<StringRef> getterVariableName(
const CXXMethodDecl *CMD) {
522 assert(CMD->hasBody());
523 if (CMD->getNumParams() != 0 || CMD->isVariadic())
525 const auto *Body = llvm::dyn_cast<CompoundStmt>(CMD->getBody());
526 const auto *OnlyReturn = (Body && Body->size() == 1)
527 ? llvm::dyn_cast<ReturnStmt>(Body->body_front())
529 if (!OnlyReturn || !OnlyReturn->getRetValue())
531 return fieldName(OnlyReturn->getRetValue());
540std::optional<StringRef> setterVariableName(
const CXXMethodDecl *CMD) {
541 assert(CMD->hasBody());
542 if (CMD->isConst() || CMD->getNumParams() != 1 || CMD->isVariadic())
544 const ParmVarDecl *Arg = CMD->getParamDecl(0);
545 if (Arg->isParameterPack())
548 const auto *Body = llvm::dyn_cast<CompoundStmt>(CMD->getBody());
549 if (!Body || Body->size() == 0 || Body->size() > 2)
552 if (Body->size() == 2) {
553 auto *Ret = llvm::dyn_cast<ReturnStmt>(Body->body_back());
554 if (!Ret || !Ret->getRetValue())
556 const Expr *RetVal = Ret->getRetValue()->IgnoreCasts();
557 if (
const auto *UO = llvm::dyn_cast<UnaryOperator>(RetVal)) {
558 if (UO->getOpcode() != UO_Deref)
560 RetVal = UO->getSubExpr()->IgnoreCasts();
562 if (!llvm::isa<CXXThisExpr>(RetVal))
566 const Expr *LHS, *RHS;
567 if (
const auto *BO = llvm::dyn_cast<BinaryOperator>(Body->body_front())) {
568 if (BO->getOpcode() != BO_Assign)
572 }
else if (
const auto *COCE =
573 llvm::dyn_cast<CXXOperatorCallExpr>(Body->body_front())) {
574 if (COCE->getOperator() != OO_Equal || COCE->getNumArgs() != 2)
576 LHS = COCE->getArg(0);
577 RHS = COCE->getArg(1);
583 if (
auto *
CE = llvm::dyn_cast<CallExpr>(RHS->IgnoreCasts())) {
584 if (
CE->getNumArgs() != 1)
586 auto *ND = llvm::dyn_cast_or_null<NamedDecl>(
CE->getCalleeDecl());
587 if (!ND || !ND->getIdentifier() || ND->getName() !=
"move" ||
588 !ND->isInStdNamespace())
593 auto *DRE = llvm::dyn_cast<DeclRefExpr>(RHS->IgnoreCasts());
594 if (!DRE || DRE->getDecl() != Arg)
596 return fieldName(LHS);
599std::string synthesizeDocumentation(
const NamedDecl *ND) {
600 if (
const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(ND)) {
602 if (CMD->getDeclName().isIdentifier() && !CMD->isStatic() &&
603 (CMD = llvm::dyn_cast_or_null<CXXMethodDecl>(CMD->getDefinition())) &&
605 if (
const auto GetterField = getterVariableName(CMD))
606 return llvm::formatv(
"Trivial accessor for `{0}`.", *GetterField);
607 if (
const auto SetterField = setterVariableName(CMD))
608 return llvm::formatv(
"Trivial setter for `{0}`.", *SetterField);
615HoverInfo getHoverContents(
const NamedDecl *D,
const PrintingPolicy &PP,
616 const SymbolIndex *Index,
617 const syntax::TokenBuffer &TB) {
619 auto &Ctx = D->getASTContext();
621 HI.AccessSpecifier = getAccessSpelling(D->getAccess()).str();
622 HI.NamespaceScope = getNamespaceScope(D);
623 if (!HI.NamespaceScope->empty())
624 HI.NamespaceScope->append(
"::");
625 HI.LocalScope = getLocalScope(D);
626 if (!HI.LocalScope.empty())
627 HI.LocalScope.append(
"::");
630 const auto *CommentD = getDeclForComment(D);
632 enhanceFromIndex(HI, *CommentD, Index);
633 if (HI.Documentation.empty())
634 HI.Documentation = synthesizeDocumentation(D);
636 HI.Kind = index::getSymbolInfo(D).Kind;
639 if (
const TemplateDecl *TD = D->getDescribedTemplate()) {
640 HI.TemplateParameters =
641 fetchTemplateParameters(TD->getTemplateParameters(), PP);
643 }
else if (
const FunctionDecl *FD = D->getAsFunction()) {
644 if (
const auto *FTD = FD->getDescribedTemplate()) {
645 HI.TemplateParameters =
646 fetchTemplateParameters(FTD->getTemplateParameters(), PP);
652 if (
const FunctionDecl *FD = getUnderlyingFunction(D))
653 fillFunctionTypeAndParams(HI, D, FD, PP);
654 else if (
const auto *VD = dyn_cast<ValueDecl>(D))
655 HI.Type =
printType(VD->getType(), Ctx, PP);
656 else if (
const auto *TTP = dyn_cast<TemplateTypeParmDecl>(D))
657 HI.Type = TTP->wasDeclaredWithTypename() ?
"typename" :
"class";
658 else if (
const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(D))
660 else if (
const auto *VT = dyn_cast<VarTemplateDecl>(D))
661 HI.Type =
printType(VT->getTemplatedDecl()->getType(), Ctx, PP);
662 else if (
const auto *TN = dyn_cast<TypedefNameDecl>(D))
663 HI.Type =
printType(TN->getUnderlyingType().getDesugaredType(Ctx), Ctx, PP);
664 else if (
const auto *TAT = dyn_cast<TypeAliasTemplateDecl>(D))
665 HI.Type =
printType(TAT->getTemplatedDecl()->getUnderlyingType(), Ctx, PP);
668 if (
const auto *Var = dyn_cast<VarDecl>(D); Var && !Var->isInvalidDecl()) {
669 if (
const Expr *Init = Var->getInit())
670 HI.Value = printExprValue(Init, Ctx);
671 }
else if (
const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
673 if (!ECD->getType()->isDependentType())
674 HI.Value =
toString(ECD->getInitVal(), 10);
677 HI.Definition = printDefinition(D, PP, TB);
682std::optional<HoverInfo>
683getPredefinedExprHoverContents(
const PredefinedExpr &PE, ASTContext &Ctx,
684 const PrintingPolicy &PP) {
686 HI.Name = PE.getIdentKindName();
687 HI.Kind = index::SymbolKind::Variable;
688 HI.Documentation =
"Name of the current function (predefined variable)";
689 if (
const StringLiteral *
Name = PE.getFunctionName()) {
691 llvm::raw_string_ostream
OS(*HI.Value);
696 QualType StringType = Ctx.getIncompleteArrayType(Ctx.CharTy.withConst(),
697 ArraySizeModifier::Normal,
699 HI.Type =
printType(StringType, Ctx, PP);
704HoverInfo evaluateMacroExpansion(
unsigned int SpellingBeginOffset,
705 unsigned int SpellingEndOffset,
706 llvm::ArrayRef<syntax::Token> Expanded,
708 auto &Context =
AST.getASTContext();
709 auto &Tokens =
AST.getTokens();
710 auto PP = getPrintingPolicy(Context.getPrintingPolicy());
719 if (Expanded.size() == 1)
720 if (tok::getPunctuatorSpelling(Expanded[0].kind()))
723 auto *StartNode = Tree.commonAncestor();
734 if (!StartNode->Children.empty())
739 auto ExprResult = printExprValue(StartNode, Context);
740 HI.Value = std::move(ExprResult.PrintedValue);
741 if (
auto *
E = ExprResult.TheExpr)
742 HI.Type =
printType(
E->getType(), Context, PP);
745 if (!HI.Value && !HI.Type && ExprResult.TheNode)
746 if (
auto *VD = ExprResult.TheNode->ASTNode.get<VarDecl>())
747 HI.Type =
printType(VD->getType(), Context, PP);
753HoverInfo getHoverContents(
const DefinedMacro &
Macro,
const syntax::Token &Tok,
756 SourceManager &SM =
AST.getSourceManager();
757 HI.Name = std::string(
Macro.Name);
758 HI.Kind = index::SymbolKind::Macro;
763 SourceLocation StartLoc =
Macro.Info->getDefinitionLoc();
764 SourceLocation EndLoc =
Macro.Info->getDefinitionEndLoc();
772 if (SM.getPresumedLoc(EndLoc,
false).isValid()) {
773 EndLoc = Lexer::getLocForEndOfToken(EndLoc, 0, SM,
AST.getLangOpts());
775 StringRef Buffer = SM.getBufferData(SM.getFileID(StartLoc), &Invalid);
777 unsigned StartOffset = SM.getFileOffset(StartLoc);
778 unsigned EndOffset = SM.getFileOffset(EndLoc);
779 if (EndOffset <= Buffer.size() && StartOffset < EndOffset)
781 (
"#define " + Buffer.substr(StartOffset, EndOffset - StartOffset))
786 if (
auto Expansion =
AST.getTokens().expansionStartingAt(&Tok)) {
790 std::string ExpansionText;
791 for (
const auto &ExpandedTok : Expansion->Expanded) {
792 ExpansionText += ExpandedTok.text(SM);
793 ExpansionText +=
" ";
794 if (ExpansionText.size() > 2048) {
795 ExpansionText.clear();
800 if (!ExpansionText.empty()) {
801 if (!HI.Definition.empty()) {
802 HI.Definition +=
"\n\n";
804 HI.Definition +=
"// Expands to\n";
805 HI.Definition += ExpansionText;
808 auto Evaluated = evaluateMacroExpansion(
809 SM.getFileOffset(Tok.location()),
810 SM.getFileOffset(Tok.endLocation()),
811 Expansion->Expanded,
AST);
812 HI.Value = std::move(Evaluated.Value);
813 HI.Type = std::move(Evaluated.Type);
818std::string typeAsDefinition(
const HoverInfo::PrintedType &PType) {
820 llvm::raw_string_ostream
OS(Result);
823 OS <<
" // aka: " << *PType.AKA;
828std::optional<HoverInfo> getThisExprHoverContents(
const CXXThisExpr *CTE,
830 const PrintingPolicy &PP) {
831 QualType OriginThisType = CTE->getType()->getPointeeType();
832 QualType ClassType =
declaredType(OriginThisType->getAsTagDecl());
837 QualType PrettyThisType = ASTCtx.getPointerType(
838 QualType(ClassType.getTypePtr(), OriginThisType.getCVRQualifiers()));
842 HI.Definition = typeAsDefinition(
printType(PrettyThisType, ASTCtx, PP));
847HoverInfo getDeducedTypeHoverContents(QualType QT,
const syntax::Token &Tok,
849 const PrintingPolicy &PP,
850 const SymbolIndex *Index) {
853 HI.Name = tok::getTokenName(Tok.kind());
854 HI.Kind = index::SymbolKind::TypeAlias;
856 if (QT->isUndeducedAutoType()) {
857 HI.Definition =
"/* not deduced */";
859 HI.Definition = typeAsDefinition(
printType(QT, ASTCtx, PP));
861 if (
const auto *D = QT->getAsTagDecl()) {
862 const auto *CommentD = getDeclForComment(D);
864 enhanceFromIndex(HI, *CommentD, Index);
871HoverInfo getStringLiteralContents(
const StringLiteral *SL,
872 const PrintingPolicy &PP) {
875 HI.Name =
"string-literal";
876 HI.Size = (SL->getLength() + 1) * SL->getCharByteWidth() * 8;
877 HI.Type = SL->getType().getAsString(PP).c_str();
882bool isLiteral(
const Expr *
E) {
885 return llvm::isa<CompoundLiteralExpr>(
E) ||
886 llvm::isa<CXXBoolLiteralExpr>(
E) ||
887 llvm::isa<CXXNullPtrLiteralExpr>(
E) ||
888 llvm::isa<FixedPointLiteral>(
E) || llvm::isa<FloatingLiteral>(
E) ||
889 llvm::isa<ImaginaryLiteral>(
E) || llvm::isa<IntegerLiteral>(
E) ||
890 llvm::isa<StringLiteral>(
E) || llvm::isa<UserDefinedLiteral>(
E);
893llvm::StringLiteral getNameForExpr(
const Expr *
E) {
901 return llvm::StringLiteral(
"expression");
904void maybeAddCalleeArgInfo(
const SelectionTree::Node *N, HoverInfo &HI,
905 const PrintingPolicy &PP);
909std::optional<HoverInfo> getHoverContents(
const SelectionTree::Node *N,
910 const Expr *
E, ParsedAST &
AST,
911 const PrintingPolicy &PP,
912 const SymbolIndex *Index) {
913 std::optional<HoverInfo> HI;
915 if (
const StringLiteral *SL = dyn_cast<StringLiteral>(
E)) {
917 HI = getStringLiteralContents(SL, PP);
918 }
else if (isLiteral(
E)) {
922 maybeAddCalleeArgInfo(N, HI.emplace(), PP);
923 if (HI->CalleeArgInfo) {
927 HI->Name =
"literal";
934 if (
const CXXThisExpr *CTE = dyn_cast<CXXThisExpr>(
E))
935 HI = getThisExprHoverContents(CTE,
AST.getASTContext(), PP);
936 if (
const PredefinedExpr *PE = dyn_cast<PredefinedExpr>(
E))
937 HI = getPredefinedExprHoverContents(*PE,
AST.getASTContext(), PP);
940 if (
auto Val = printExprValue(
E,
AST.getASTContext())) {
944 HI->Name = std::string(getNameForExpr(
E));
948 maybeAddCalleeArgInfo(N, *HI, PP);
954std::optional<HoverInfo> getHoverContents(
const Attr *A, ParsedAST &
AST) {
956 HI.Name =
A->getSpelling();
958 HI.LocalScope =
A->getScopeName()->getName().str();
960 llvm::raw_string_ostream
OS(HI.Definition);
961 A->printPretty(
OS,
AST.getASTContext().getPrintingPolicy());
963 HI.Documentation = Attr::getDocumentation(
A->getKind()).str();
967bool isParagraphBreak(llvm::StringRef Rest) {
968 return Rest.ltrim(
" \t").starts_with(
"\n");
971bool punctuationIndicatesLineBreak(llvm::StringRef Line) {
972 constexpr llvm::StringLiteral
Punctuation = R
"txt(.:,;!?)txt";
978bool isHardLineBreakIndicator(llvm::StringRef Rest) {
981 constexpr llvm::StringLiteral LinebreakIndicators = R
"txt(-*@>#`)txt";
983 Rest = Rest.ltrim(" \t");
987 if (LinebreakIndicators.contains(Rest.front()))
990 if (llvm::isDigit(Rest.front())) {
991 llvm::StringRef AfterDigit = Rest.drop_while(llvm::isDigit);
992 if (AfterDigit.starts_with(
".") || AfterDigit.starts_with(
")"))
998bool isHardLineBreakAfter(llvm::StringRef Line, llvm::StringRef Rest) {
1000 return punctuationIndicatesLineBreak(Line) || isHardLineBreakIndicator(Rest);
1003void addLayoutInfo(
const NamedDecl &ND, HoverInfo &HI) {
1004 if (ND.isInvalidDecl())
1007 const auto &Ctx = ND.getASTContext();
1008 if (
auto *RD = llvm::dyn_cast<RecordDecl>(&ND)) {
1009 if (
auto Size = Ctx.getTypeSizeInCharsIfKnown(RD->getTypeForDecl()))
1010 HI.Size = Size->getQuantity() * 8;
1011 if (!RD->isDependentType() && RD->isCompleteDefinition())
1012 HI.Align = Ctx.getTypeAlign(RD->getTypeForDecl());
1016 if (
const auto *FD = llvm::dyn_cast<FieldDecl>(&ND)) {
1017 const auto *
Record = FD->getParent();
1020 if (Record && !
Record->isInvalidDecl() && !
Record->isDependentType()) {
1021 HI.Align = Ctx.getTypeAlign(FD->getType());
1022 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Record);
1023 HI.Offset = Layout.getFieldOffset(FD->getFieldIndex());
1024 if (FD->isBitField())
1025 HI.Size = FD->getBitWidthValue(Ctx);
1026 else if (
auto Size = Ctx.getTypeSizeInCharsIfKnown(FD->getType()))
1027 HI.Size = FD->isZeroSize(Ctx) ? 0 : Size->getQuantity() * 8;
1029 unsigned EndOfField = *HI.Offset + *HI.Size;
1032 if (!
Record->isUnion() &&
1033 FD->getFieldIndex() + 1 < Layout.getFieldCount()) {
1035 unsigned NextOffset = Layout.getFieldOffset(FD->getFieldIndex() + 1);
1036 if (NextOffset >= EndOfField)
1037 HI.Padding = NextOffset - EndOfField;
1040 HI.Padding = Layout.getSize().getQuantity() * 8 - EndOfField;
1052 if (ParmType->isReferenceType()) {
1053 if (ParmType->getPointeeType().isConstQualified())
1062void maybeAddCalleeArgInfo(
const SelectionTree::Node *N, HoverInfo &HI,
1063 const PrintingPolicy &PP) {
1064 const auto &OuterNode = N->outerImplicit();
1065 if (!OuterNode.Parent)
1068 const FunctionDecl *FD =
nullptr;
1069 llvm::ArrayRef<const Expr *>
Args;
1071 if (
const auto *
CE = OuterNode.Parent->ASTNode.get<CallExpr>()) {
1072 FD =
CE->getDirectCallee();
1073 Args = {
CE->getArgs(),
CE->getNumArgs()};
1074 }
else if (
const auto *
CE =
1075 OuterNode.Parent->ASTNode.get<CXXConstructExpr>()) {
1076 FD =
CE->getConstructor();
1077 Args = {
CE->getArgs(),
CE->getNumArgs()};
1088 if (!FD || FD->isOverloadedOperator() || FD->isVariadic())
1091 HoverInfo::PassType PassType;
1096 for (
unsigned I = 0; I <
Args.size() && I <
Parameters.size(); ++I) {
1097 if (
Args[I] != OuterNode.ASTNode.get<Expr>())
1101 if (
const ParmVarDecl *PVD =
Parameters[I]) {
1102 HI.CalleeArgInfo.emplace(toHoverInfoParam(PVD, PP));
1103 if (N == &OuterNode)
1104 PassType.PassBy = getPassMode(PVD->getType());
1108 if (!HI.CalleeArgInfo)
1114 if (
const auto *
E = N->ASTNode.get<Expr>()) {
1115 if (
E->getType().isConstQualified())
1119 for (
auto *CastNode = N->Parent;
1120 CastNode != OuterNode.Parent && !PassType.Converted;
1121 CastNode = CastNode->Parent) {
1122 if (
const auto *ImplicitCast = CastNode->ASTNode.get<ImplicitCastExpr>()) {
1123 switch (ImplicitCast->getCastKind()) {
1125 case CK_DerivedToBase:
1126 case CK_UncheckedDerivedToBase:
1129 PassType.PassBy = ImplicitCast->getType().isConstQualified()
1133 case CK_LValueToRValue:
1134 case CK_ArrayToPointerDecay:
1135 case CK_FunctionToPointerDecay:
1136 case CK_NullToPointer:
1137 case CK_NullToMemberPointer:
1143 PassType.Converted =
true;
1146 }
else if (
const auto *CtorCall =
1147 CastNode->ASTNode.get<CXXConstructExpr>()) {
1150 if (CtorCall->getConstructor()->isCopyConstructor())
1153 PassType.Converted =
true;
1154 }
else if (CastNode->ASTNode.get<MaterializeTemporaryExpr>()) {
1159 PassType.Converted =
true;
1163 HI.CallPassType.emplace(PassType);
1166const NamedDecl *pickDeclToUse(llvm::ArrayRef<const NamedDecl *> Candidates) {
1167 if (Candidates.empty())
1176 if (Candidates.size() <= 2) {
1177 if (llvm::isa<UsingDecl>(Candidates.front()))
1178 return Candidates.back();
1179 return Candidates.front();
1188 auto BaseDecls = llvm::make_filter_range(
1189 Candidates, [](
const NamedDecl *D) {
return llvm::isa<UsingDecl>(D); });
1190 if (std::distance(BaseDecls.begin(), BaseDecls.end()) == 1)
1191 return *BaseDecls.begin();
1193 return Candidates.front();
1196void maybeAddSymbolProviders(ParsedAST &
AST, HoverInfo &HI,
1197 include_cleaner::Symbol Sym) {
1198 trace::Span Tracer(
"Hover::maybeAddSymbolProviders");
1200 const SourceManager &SM =
AST.getSourceManager();
1201 llvm::SmallVector<include_cleaner::Header> RankedProviders =
1202 include_cleaner::headersForSymbol(Sym, SM, &
AST.getPragmaIncludes());
1203 if (RankedProviders.empty())
1208 for (
const auto &P : RankedProviders) {
1209 if (P.kind() == include_cleaner::Header::Physical &&
1210 P.physical() == SM.getFileEntryForID(SM.getMainFileID()))
1215 auto Matches = ConvertedIncludes.match(P);
1216 if (!Matches.empty()) {
1217 Result = Matches[0]->quote();
1222 if (!Result.empty()) {
1223 HI.Provider = std::move(Result);
1228 const auto &H = RankedProviders.front();
1229 if (H.kind() == include_cleaner::Header::Physical &&
1230 H.physical() == SM.getFileEntryForID(SM.getMainFileID()))
1235 HI.Provider = include_cleaner::spellHeader(
1236 {H,
AST.getPreprocessor().getHeaderSearchInfo(),
1237 SM.getFileEntryForID(SM.getMainFileID())});
1243std::string getSymbolName(include_cleaner::Symbol Sym) {
1245 switch (Sym.kind()) {
1246 case include_cleaner::Symbol::Declaration:
1247 if (
const auto *ND = llvm::dyn_cast<NamedDecl>(&Sym.declaration()))
1248 Name = ND->getDeclName().getAsString();
1250 case include_cleaner::Symbol::Macro:
1251 Name = Sym.macro().Name->getName();
1257void maybeAddUsedSymbols(ParsedAST &
AST, HoverInfo &HI,
const Inclusion &Inc) {
1259 llvm::DenseSet<include_cleaner::Symbol> UsedSymbols;
1260 include_cleaner::walkUsed(
1262 &
AST.getPragmaIncludes(),
AST.getPreprocessor(),
1263 [&](
const include_cleaner::SymbolReference &Ref,
1264 llvm::ArrayRef<include_cleaner::Header> Providers) {
1265 if (Ref.RT != include_cleaner::RefType::Explicit ||
1266 UsedSymbols.contains(Ref.Target))
1269 if (isPreferredProvider(Inc, Converted, Providers))
1270 UsedSymbols.insert(Ref.Target);
1273 for (
const auto &UsedSymbolDecl : UsedSymbols)
1274 HI.UsedSymbolNames.push_back(getSymbolName(UsedSymbolDecl));
1275 llvm::sort(HI.UsedSymbolNames);
1276 HI.UsedSymbolNames.erase(
1277 std::unique(HI.UsedSymbolNames.begin(), HI.UsedSymbolNames.end()),
1278 HI.UsedSymbolNames.end());
1284 const format::FormatStyle &Style,
1289 getPrintingPolicy(
AST.getASTContext().getPrintingPolicy());
1290 const SourceManager &SM =
AST.getSourceManager();
1293 llvm::consumeError(CurLoc.takeError());
1294 return std::nullopt;
1296 const auto &TB =
AST.getTokens();
1297 auto TokensTouchingCursor = syntax::spelledTokensTouching(*CurLoc, TB);
1299 if (TokensTouchingCursor.empty())
1300 return std::nullopt;
1303 for (
const auto &Inc :
AST.getIncludeStructure().MainFileIncludes) {
1304 if (Inc.Resolved.empty() || Inc.HashLine !=
Pos.line)
1306 HoverCountMetric.
record(1,
"include");
1308 HI.
Name = std::string(llvm::sys::path::filename(Inc.Resolved));
1313 maybeAddUsedSymbols(
AST, HI, Inc);
1320 CharSourceRange HighlightRange =
1321 TokensTouchingCursor.back().range(SM).toCharRange(SM);
1322 std::optional<HoverInfo> HI;
1326 for (
const auto &Tok : TokensTouchingCursor) {
1327 if (Tok.kind() == tok::identifier) {
1329 HighlightRange = Tok.range(SM).toCharRange(SM);
1331 HoverCountMetric.
record(1,
"macro");
1332 HI = getHoverContents(*
M, Tok,
AST);
1333 if (
auto DefLoc =
M->Info->getDefinitionLoc(); DefLoc.isValid()) {
1334 include_cleaner::Macro IncludeCleanerMacro{
1335 AST.getPreprocessor().getIdentifierInfo(Tok.text(SM)), DefLoc};
1336 maybeAddSymbolProviders(
AST, *HI,
1337 include_cleaner::Symbol{IncludeCleanerMacro});
1341 }
else if (Tok.kind() == tok::kw_auto || Tok.kind() == tok::kw_decltype) {
1342 HoverCountMetric.
record(1,
"keyword");
1344 HI = getDeducedTypeHoverContents(*
Deduced, Tok,
AST.getASTContext(), PP,
1346 HighlightRange = Tok.range(SM).toCharRange(SM);
1353 return std::nullopt;
1359 auto Offset = SM.getFileOffset(*CurLoc);
1367 AST.getHeuristicResolver());
1368 if (
const auto *DeclToUse = pickDeclToUse(Decls)) {
1369 HoverCountMetric.
record(1,
"decl");
1370 HI = getHoverContents(DeclToUse, PP, Index, TB);
1372 if (DeclToUse == N->ASTNode.get<
Decl>())
1373 addLayoutInfo(*DeclToUse, *HI);
1376 HI->Value = printExprValue(N,
AST.getASTContext()).PrintedValue;
1377 maybeAddCalleeArgInfo(N, *HI, PP);
1379 if (!isa<NamespaceDecl>(DeclToUse))
1380 maybeAddSymbolProviders(
AST, *HI,
1381 include_cleaner::Symbol{*DeclToUse});
1382 }
else if (
const Expr *
E = N->ASTNode.get<Expr>()) {
1383 HoverCountMetric.
record(1,
"expr");
1384 HI = getHoverContents(N,
E,
AST, PP, Index);
1385 }
else if (
const Attr *A = N->ASTNode.get<Attr>()) {
1386 HoverCountMetric.
record(1,
"attribute");
1387 HI = getHoverContents(A,
AST);
1395 return std::nullopt;
1398 if (!HI->Definition.empty()) {
1399 auto Replacements = format::reformat(
1400 Style, HI->Definition, tooling::Range(0, HI->Definition.size()));
1401 if (
auto Formatted =
1402 tooling::applyAllReplacements(HI->Definition, Replacements))
1403 HI->Definition = *Formatted;
1406 HI->DefinitionLanguage = getMarkdownLanguage(
AST.getASTContext());
1414 uint64_t
Value = SizeInBits % 8 == 0 ? SizeInBits / 8 : SizeInBits;
1415 const char *
Unit =
Value != 0 &&
Value == SizeInBits ?
"bit" :
"byte";
1416 return llvm::formatv(
"{0} {1}{2}",
Value,
Unit,
Value == 1 ?
"" :
"s").str();
1422 const auto Bytes = OffsetInBits / 8;
1423 const auto Bits = OffsetInBits % 8;
1446 if (
Kind != index::SymbolKind::Unknown)
1447 Header.appendText(index::getSymbolKindString(
Kind)).appendSpace();
1448 assert(!
Name.empty() &&
"hover triggered on a nameless symbol");
1449 Header.appendCode(
Name);
1469 Output.addParagraph().appendText(
"→ ").appendCode(
1474 Output.addParagraph().appendText(
"Parameters: ");
1477 L.addItem().addParagraph().appendCode(llvm::to_string(
Param));
1483 Output.addParagraph().appendText(
"Type: ").appendCode(
1484 llvm::to_string(*
Type));
1507 llvm::raw_string_ostream
OS(Buffer);
1521 Output.addParagraph().appendText(
OS.str());
1540 "// In " + llvm::StringRef(
LocalScope).rtrim(
':').str() +
'\n';
1542 Buffer +=
"// In namespace " +
1543 llvm::StringRef(*NamespaceScope).rtrim(
':').str() +
'\n';
1561 const std::vector<std::string>::size_type SymbolNamesLimit = 5;
1562 auto Front = llvm::ArrayRef(
UsedSymbolNames).take_front(SymbolNamesLimit);
1565 Front, [&](llvm::StringRef Sym) { P.
appendCode(Sym); },
1584 llvm::StringRef Prefix =
Line.substr(0,
Offset);
1585 constexpr llvm::StringLiteral BeforeStartChars =
" \t(=";
1586 if (!Prefix.empty() && !BeforeStartChars.contains(Prefix.back()))
1587 return std::nullopt;
1591 if (Next == llvm::StringRef::npos)
1592 return std::nullopt;
1593 llvm::StringRef Contents =
Line.slice(
Offset + 1, Next);
1594 if (Contents.empty() || isWhitespace(Contents.front()) ||
1595 isWhitespace(Contents.back()))
1596 return std::nullopt;
1599 llvm::StringRef
Suffix =
Line.substr(Next + 1);
1600 constexpr llvm::StringLiteral AfterEndChars =
" \t)=.,;:";
1601 if (!
Suffix.empty() && !AfterEndChars.contains(
Suffix.front()))
1602 return std::nullopt;
1609 for (
unsigned I = 0; I <
Line.size(); ++I) {
1613 Out.appendText(
Line.substr(0, I));
1614 Out.appendCode(
Range->trim(
"`"),
true);
1620 Out.appendText(
Line).appendSpace();
1624 std::vector<llvm::StringRef> ParagraphLines;
1625 auto FlushParagraph = [&] {
1626 if (ParagraphLines.empty())
1628 auto &P =
Output.addParagraph();
1629 for (llvm::StringRef
Line : ParagraphLines)
1631 ParagraphLines.clear();
1634 llvm::StringRef
Line, Rest;
1635 for (std::tie(
Line, Rest) = Input.split(
'\n');
1636 !(
Line.empty() && Rest.empty());
1637 std::tie(
Line, Rest) = Rest.split(
'\n')) {
1643 ParagraphLines.push_back(
Line);
1645 if (isParagraphBreak(Rest) || isHardLineBreakAfter(
Line, Rest)) {
1656 OS <<
" (aka " << *T.AKA <<
")";
1669 OS <<
" (aka " << *P.
Type->AKA <<
")";
ArrayRef< const ParmVarDecl * > Parameters
const FunctionDecl * Decl
llvm::SmallString< 256U > Name
CompiledFragmentImpl & Out
std::optional< std::string > PrintedValue
The evaluation result on expression Expr.
const SelectionTree::Node * TheNode
The node of selection tree where the traversal stops.
const clang::Expr * TheExpr
The Expr object that represents the closest evaluable expression.
Include Cleaner is clangd functionality for providing diagnostics for misuse of transitive headers an...
const google::protobuf::Message & M
llvm::raw_string_ostream OS
Stores and provides access to parsed AST.
static SelectionTree createRight(ASTContext &AST, const syntax::TokenBuffer &Tokens, unsigned Begin, unsigned End)
const Node * commonAncestor() const
static bool shouldCollectSymbol(const NamedDecl &ND, const ASTContext &ASTCtx, const Options &Opts, bool IsMainFileSymbol)
Returns true is ND should be collected.
Interface for symbol indexes that can be used for searching or matching symbols among a set of symbol...
Represents a sequence of one or more documents.
A format-agnostic representation for structured text.
Represents parts of the markup that can contain strings, like inline code, code block or plain text.
Paragraph & appendText(llvm::StringRef Text)
Append plain text to the end of the string.
Paragraph & appendSpace()
Ensure there is space between the surrounding chunks.
Paragraph & appendCode(llvm::StringRef Code, bool Preserve=false)
Append inline code, this translates to the ` block in markdown.
SmallVector< const ParmVarDecl * > resolveForwardingParameters(const FunctionDecl *D, unsigned MaxDepth)
Recursively resolves the parameters of a FunctionDecl that forwards its parameters to another functio...
std::string printObjCMethod(const ObjCMethodDecl &Method)
Print the Objective-C method name, including the full container name, e.g.
SymbolID getSymbolID(const Decl *D)
Gets the symbol ID for a declaration. Returned SymbolID might be null.
Range halfOpenToRange(const SourceManager &SM, CharSourceRange R)
std::string printType(const QualType QT, const DeclContext &CurContext, const llvm::StringRef Placeholder)
Returns a QualType as string.
std::string printName(const ASTContext &Ctx, const NamedDecl &ND)
Prints unqualified name of the decl for the purpose of displaying it to the user.
std::string getDeclComment(const ASTContext &Ctx, const NamedDecl &Decl)
Similar to getDocComment, but returns the comment for a NamedDecl.
std::string printObjCContainer(const ObjCContainerDecl &C)
Print the Objective-C container name including categories, e.g. MyClass,.
void parseDocumentationLine(llvm::StringRef Line, markup::Paragraph &Out)
std::optional< llvm::StringRef > getBacktickQuoteRange(llvm::StringRef Line, unsigned Offset)
llvm::SmallVector< const NamedDecl *, 1 > explicitReferenceTargets(DynTypedNode N, DeclRelationSet Mask, const HeuristicResolver *Resolver)
Find declarations explicitly referenced in the source code defined by N.
std::vector< include_cleaner::SymbolReference > collectMacroReferences(ParsedAST &AST)
include_cleaner::Includes convertIncludes(const ParsedAST &AST)
Converts the clangd include representation to include-cleaner include representation.
static const char * toString(OffsetEncoding OE)
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, const CodeCompletion &C)
std::optional< DefinedMacro > locateMacroAt(const syntax::Token &SpelledTok, Preprocessor &PP)
Gets the macro referenced by SpelledTok.
std::optional< HoverInfo > getHover(ParsedAST &AST, Position Pos, const format::FormatStyle &Style, const SymbolIndex *Index)
Get the hover information when hovering at Pos.
static std::string formatOffset(uint64_t OffsetInBits)
static std::string formatSize(uint64_t SizeInBits)
llvm::Expected< SourceLocation > sourceLocationInMainFile(const SourceManager &SM, Position P)
Return the file location, corresponding to P.
QualType declaredType(const TypeDecl *D)
void parseDocumentation(llvm::StringRef Input, markup::Document &Output)
std::string printQualifiedName(const NamedDecl &ND)
Returns the qualified name of ND.
@ Alias
This declaration is an alias that was referred to.
std::optional< QualType > getDeducedType(ASTContext &ASTCtx, SourceLocation Loc)
Retrieves the deduced type at a given location (auto, decltype).
llvm::SmallVector< uint64_t, 1024 > Record
@ Invalid
Sentinel bit pattern. DO NOT USE!
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
static const Config & current()
Returns the Config of the current Context, or an empty configuration.
bool ShowAKA
Whether hover show a.k.a type.
struct clang::clangd::Config::@7 Hover
Configures hover feature.
Represents parameters of a function, a template or a macro.
std::optional< PrintedType > Type
The printable parameter type, e.g.
std::optional< std::string > Default
std::nullopt if no default is provided.
std::optional< std::string > Name
std::nullopt for unnamed parameters.
Contains pretty-printed type and desugared type.
Contains detailed information about a Symbol.
std::optional< PrintedType > ReturnType
Set for functions and lambdas.
std::optional< uint64_t > Padding
Contains the padding following a field within the enclosing class.
std::optional< uint64_t > Offset
Contains the offset of fields within the enclosing class.
std::string Provider
Header providing the symbol (best match). Contains ""<>.
std::optional< PassType > CallPassType
std::optional< std::vector< Param > > Parameters
Set for functions, lambdas and macros with parameters.
const char * DefinitionLanguage
std::string Name
Name of the symbol, does not contain any "::".
std::optional< PrintedType > Type
Printable variable type.
markup::Document present() const
Produce a user-readable information.
std::optional< uint64_t > Align
Contains the alignment of fields and types where it's interesting.
std::optional< uint64_t > Size
Contains the bit-size of fields and types where it's interesting.
std::vector< std::string > UsedSymbolNames
std::optional< std::string > Value
Contains the evaluated value of the symbol if available.
std::string Definition
Source code containing the definition of the symbol.
std::optional< std::string > NamespaceScope
For a variable named Bar, declared in clang::clangd::Foo::getFoo the following fields will hold:
std::string Documentation
std::string AccessSpecifier
Access specifier for declarations inside class/struct/unions, empty for others.
std::optional< Param > CalleeArgInfo
std::string LocalScope
Remaining named contexts in symbol's qualified name, empty string means symbol is not local.
static URIForFile canonicalize(llvm::StringRef AbsPath, llvm::StringRef TUPath)
Canonicalizes AbsPath via URI.
llvm::StringRef file() const
Retrieves absolute path to the file.
Represents measurements of clangd events, e.g.
@ Counter
An aggregate number whose rate of change over time is meaningful.
void record(double Value, llvm::StringRef Label="") const
Records a measurement for this metric to active tracer.