22#include "clang-include-cleaner/Analysis.h"
23#include "clang-include-cleaner/IncludeSpeller.h"
24#include "clang-include-cleaner/Types.h"
28#include "clang/AST/ASTContext.h"
29#include "clang/AST/ASTDiagnostic.h"
30#include "clang/AST/ASTTypeTraits.h"
31#include "clang/AST/Attr.h"
32#include "clang/AST/Decl.h"
33#include "clang/AST/DeclBase.h"
34#include "clang/AST/DeclCXX.h"
35#include "clang/AST/DeclObjC.h"
36#include "clang/AST/DeclTemplate.h"
37#include "clang/AST/Expr.h"
38#include "clang/AST/ExprCXX.h"
39#include "clang/AST/OperationKinds.h"
40#include "clang/AST/PrettyPrinter.h"
41#include "clang/AST/RecordLayout.h"
42#include "clang/AST/Type.h"
43#include "clang/Basic/CharInfo.h"
44#include "clang/Basic/LLVM.h"
45#include "clang/Basic/LangOptions.h"
46#include "clang/Basic/SourceLocation.h"
47#include "clang/Basic/SourceManager.h"
48#include "clang/Basic/Specifiers.h"
49#include "clang/Basic/TokenKinds.h"
50#include "clang/Index/IndexSymbol.h"
51#include "clang/Tooling/Syntax/Tokens.h"
52#include "llvm/ADT/ArrayRef.h"
53#include "llvm/ADT/DenseSet.h"
54#include "llvm/ADT/STLExtras.h"
55#include "llvm/ADT/SmallVector.h"
56#include "llvm/ADT/StringExtras.h"
57#include "llvm/ADT/StringRef.h"
58#include "llvm/Support/Casting.h"
59#include "llvm/Support/Error.h"
60#include "llvm/Support/Format.h"
61#include "llvm/Support/ScopedPrinter.h"
62#include "llvm/Support/raw_ostream.h"
72PrintingPolicy getPrintingPolicy(PrintingPolicy Base) {
73 Base.AnonymousTagNameStyle =
74 llvm::to_underlying(PrintingPolicy::AnonymousTagMode::Plain);
75 Base.TerseOutput =
true;
76 Base.PolishForDeclaration =
true;
77 Base.ConstantsAsWritten =
true;
78 Base.SuppressTemplateArgsInCXXConstructors =
true;
85std::string getLocalScope(
const Decl *D) {
86 std::vector<std::string> Scopes;
87 const DeclContext *DC =
D->getDeclContext();
92 if (
const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
94 if (
const ObjCContainerDecl *CD = dyn_cast<ObjCContainerDecl>(DC))
97 auto GetName = [](
const TypeDecl *
D) {
98 if (!
D->getDeclName().isEmpty()) {
99 PrintingPolicy Policy =
D->getASTContext().getPrintingPolicy();
100 Policy.SuppressScope =
true;
103 if (
auto *RD = dyn_cast<RecordDecl>(D))
104 return (
"(anonymous " + RD->getKindName() +
")").str();
105 return std::string(
"");
108 if (
const TypeDecl *TD = dyn_cast<TypeDecl>(DC))
109 Scopes.push_back(GetName(TD));
110 else if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
111 Scopes.push_back(FD->getNameAsString());
112 DC = DC->getParent();
115 return llvm::join(llvm::reverse(Scopes),
"::");
120std::string getNamespaceScope(
const Decl *D) {
121 const DeclContext *DC =
D->getDeclContext();
125 if (isa<ObjCMethodDecl, ObjCContainerDecl>(DC))
128 if (
const TagDecl *TD = dyn_cast<TagDecl>(DC))
129 return getNamespaceScope(TD);
130 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
131 return getNamespaceScope(FD);
132 if (
const NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(DC)) {
134 if (NSD->isInline() || NSD->isAnonymousNamespace())
135 return getNamespaceScope(NSD);
137 if (
const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
143std::string printDefinition(
const Decl *D, PrintingPolicy PP,
144 const syntax::TokenBuffer &TB) {
145 if (
auto *VD = llvm::dyn_cast<VarDecl>(D)) {
146 if (
auto *IE = VD->getInit()) {
150 if (200 < TB.expandedTokens(IE->getSourceRange()).size())
151 PP.SuppressInitializers =
true;
160const char *getMarkdownLanguage(
const ASTContext &Ctx) {
161 const auto &LangOpts = Ctx.getLangOpts();
162 if (LangOpts.ObjC && LangOpts.CPlusPlus)
163 return "objective-cpp";
164 return LangOpts.ObjC ?
"objective-c" :
"cpp";
168 const PrintingPolicy &PP) {
172 while (!QT.isNull() && QT->isDecltypeType())
173 QT = QT->castAs<DecltypeType>()->getUnderlyingType();
175 llvm::raw_string_ostream OS(Result.Type);
180 PrintingPolicy Copy(PP);
181 if (!QT.isNull() && !QT.hasQualifiers() && PP.SuppressTagKeyword) {
182 if (
auto *TT = llvm::dyn_cast<TagType>(QT.getTypePtr());
183 TT && TT->isCanonicalUnqualified()) {
184 Copy.SuppressTagKeywordInAnonNames =
true;
185 OS << TT->getDecl()->getKindName() <<
" ";
191 if (!QT.isNull() && Cfg.Hover.ShowAKA) {
192 bool ShouldAKA =
false;
193 QualType DesugaredTy = clang::desugarForDiagnostic(ASTCtx, QT, ShouldAKA);
195 Result.AKA = DesugaredTy.getAsString(Copy);
202 Result.
Type = TTP->wasDeclaredWithTypename() ?
"typename" :
"class";
203 if (TTP->isParameterPack())
204 Result.Type +=
"...";
209 const PrintingPolicy &PP) {
210 auto PrintedType =
printType(NTTP->getType(), NTTP->getASTContext(), PP);
211 if (NTTP->isParameterPack()) {
212 PrintedType.Type +=
"...";
214 *PrintedType.AKA +=
"...";
220 const PrintingPolicy &PP) {
222 llvm::raw_string_ostream OS(Result.Type);
224 llvm::StringRef Sep =
"";
225 for (
const Decl *Param : *TTP->getTemplateParameters()) {
228 if (
const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
230 else if (
const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
232 else if (
const auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param))
241std::vector<HoverInfo::Param>
242fetchTemplateParameters(
const TemplateParameterList *Params,
243 const PrintingPolicy &PP) {
245 std::vector<HoverInfo::Param> TempParameters;
247 for (
const Decl *Param : *Params) {
249 if (
const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
252 if (!TTP->getName().empty())
253 P.Name = TTP->getNameAsString();
255 if (TTP->hasDefaultArgument()) {
257 llvm::raw_string_ostream Out(*
P.Default);
258 TTP->getDefaultArgument().getArgument().print(PP, Out,
261 }
else if (
const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
264 if (IdentifierInfo *II = NTTP->getIdentifier())
265 P.Name = II->getName().str();
267 if (NTTP->hasDefaultArgument()) {
269 llvm::raw_string_ostream Out(*
P.Default);
270 NTTP->getDefaultArgument().getArgument().print(PP, Out,
273 }
else if (
const auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param)) {
276 if (!TTPD->getName().empty())
277 P.Name = TTPD->getNameAsString();
279 if (TTPD->hasDefaultArgument()) {
281 llvm::raw_string_ostream Out(*
P.Default);
282 TTPD->getDefaultArgument().getArgument().print(PP, Out,
286 TempParameters.push_back(std::move(P));
289 return TempParameters;
292const FunctionDecl *getUnderlyingFunction(
const Decl *D) {
294 if (
const VarDecl *VD = llvm::dyn_cast<VarDecl>(D)) {
295 auto QT = VD->getType();
297 while (!QT->getPointeeType().isNull())
298 QT = QT->getPointeeType();
300 if (
const auto *CD = QT->getAsCXXRecordDecl())
301 return CD->getLambdaCallOperator();
306 return D->getAsFunction();
311const NamedDecl *getDeclForComment(
const NamedDecl *D) {
312 const NamedDecl *DeclForComment =
D;
313 if (
const auto *TSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(D)) {
316 if (TSD->getTemplateSpecializationKind() == TSK_Undeclared)
317 DeclForComment = TSD->getSpecializedTemplate();
318 else if (
const auto *TIP = TSD->getTemplateInstantiationPattern())
319 DeclForComment = TIP;
320 }
else if (
const auto *TSD =
321 llvm::dyn_cast<VarTemplateSpecializationDecl>(D)) {
322 if (TSD->getTemplateSpecializationKind() == TSK_Undeclared)
323 DeclForComment = TSD->getSpecializedTemplate();
324 else if (
const auto *TIP = TSD->getTemplateInstantiationPattern())
325 DeclForComment = TIP;
326 }
else if (
const auto *FD =
D->getAsFunction())
327 if (
const auto *TIP = FD->getTemplateInstantiationPattern())
328 DeclForComment = TIP;
333 if (D != DeclForComment)
334 DeclForComment = getDeclForComment(DeclForComment);
335 return DeclForComment;
341 assert(&ND == getDeclForComment(&ND));
343 if (!
Hover.Documentation.empty() || !Index)
357 Index->lookup(Req, [&](
const Symbol &S) {
358 Hover.Documentation = std::string(S.Documentation);
365const Expr *getDefaultArg(
const ParmVarDecl *PVD) {
370 if (!PVD->hasDefaultArg() || PVD->hasUnparsedDefaultArg())
372 return PVD->hasUninstantiatedDefaultArg() ? PVD->getUninstantiatedDefaultArg()
373 : PVD->getDefaultArg();
377 const PrintingPolicy &PP) {
379 Out.
Type =
printType(PVD->getType(), PVD->getASTContext(), PP);
380 if (!PVD->getName().empty())
381 Out.Name = PVD->getNameAsString();
382 if (
const Expr *DefArg = getDefaultArg(PVD)) {
383 Out.Default.emplace();
384 llvm::raw_string_ostream OS(*Out.Default);
385 DefArg->printPretty(OS,
nullptr, PP);
391void fillFunctionTypeAndParams(
HoverInfo &HI,
const Decl *D,
392 const FunctionDecl *FD,
393 const PrintingPolicy &PP) {
394 HI.Parameters.emplace();
395 for (
const ParmVarDecl *PVD : FD->parameters())
396 HI.Parameters->emplace_back(toHoverInfoParam(PVD, PP));
400 const auto NK = FD->getDeclName().getNameKind();
401 if (NK == DeclarationName::CXXConstructorName ||
402 NK == DeclarationName::CXXDestructorName ||
403 NK == DeclarationName::CXXConversionFunctionName)
406 HI.ReturnType =
printType(FD->getReturnType(), FD->getASTContext(), PP);
407 QualType QT = FD->getType();
408 if (
const VarDecl *VD = llvm::dyn_cast<VarDecl>(D))
409 QT = VD->getType().getDesugaredType(
D->getASTContext());
410 HI.Type =
printType(QT,
D->getASTContext(), PP);
420static llvm::FormattedNumber printHex(
const llvm::APSInt &V) {
421 assert(V.getSignificantBits() <= 64 &&
"Can't print more than 64 bits.");
423 V.getBitWidth() > 64 ? V.trunc(64).getZExtValue() : V.getZExtValue();
424 if (V.isNegative() && V.getSignificantBits() <= 32)
425 return llvm::format_hex(uint32_t(Bits), 0);
426 return llvm::format_hex(Bits, 0);
429std::optional<std::string> printExprValue(
const Expr *E,
430 const ASTContext &Ctx) {
435 if (
const auto *ILE = llvm::dyn_cast<InitListExpr>(E)) {
436 if (!ILE->isSemanticForm())
437 E = ILE->getSemanticForm();
443 QualType
T = E->getType();
444 if (
T.isNull() ||
T->isFunctionType() ||
T->isFunctionPointerType() ||
445 T->isFunctionReferenceType() ||
T->isVoidType())
450 if (E->isValueDependent() || !E->EvaluateAsRValue(
Constant, Ctx) ||
457 if (
T->isEnumeralType() &&
Constant.Val.isInt() &&
458 Constant.Val.getInt().getSignificantBits() <= 64) {
460 int64_t Val =
Constant.Val.getInt().getExtValue();
461 for (
const EnumConstantDecl *ECD :
T->castAsEnumDecl()->enumerators())
462 if (ECD->getInitVal() == Val)
463 return llvm::formatv(
"{0} ({1})", ECD->getNameAsString(),
468 if (
T->isIntegralOrEnumerationType() &&
Constant.Val.isInt() &&
469 Constant.Val.getInt().getSignificantBits() <= 64 &&
471 return llvm::formatv(
"{0} ({1})",
Constant.Val.getAsString(Ctx, T),
474 return Constant.Val.getAsString(Ctx, T);
477struct PrintExprResult {
479 std::optional<std::string> PrintedValue;
482 const clang::Expr *TheExpr;
484 const SelectionTree::Node *TheNode;
493 const ASTContext &Ctx) {
494 for (; N; N = N->Parent) {
496 if (
const Expr *E = N->ASTNode.get<Expr>()) {
499 if (!E->getType().isNull() && E->getType()->isVoidType())
501 if (
auto Val = printExprValue(E, Ctx))
502 return PrintExprResult{std::move(Val), E,
504 }
else if (N->ASTNode.get<Decl>() || N->ASTNode.get<Stmt>()) {
510 return PrintExprResult{std::nullopt,
nullptr,
515const FieldDecl *fieldDecl(
const Expr *E) {
516 const auto *ME = llvm::dyn_cast<MemberExpr>(E->IgnoreCasts());
517 if (!ME || !llvm::isa<CXXThisExpr>(ME->getBase()->IgnoreCasts()))
519 return llvm::dyn_cast<FieldDecl>(ME->getMemberDecl());
522std::optional<StringRef> fieldName(
const Expr *E) {
523 const auto *
Field = fieldDecl(E);
524 if (!
Field || !
Field->getDeclName().isIdentifier())
526 return Field->getDeclName().getAsIdentifierInfo()->getName();
529std::optional<std::string> fieldComment(
const ASTContext &Ctx,
const Expr *E) {
530 const auto *
Field = fieldDecl(E);
541const Expr *getterReturnExpr(
const CXXMethodDecl *CMD) {
542 assert(CMD->hasBody());
543 if (CMD->getNumParams() != 0 || CMD->isVariadic())
545 const auto *Body = llvm::dyn_cast<CompoundStmt>(CMD->getBody());
546 const auto *OnlyReturn = (Body && Body->size() == 1)
547 ? llvm::dyn_cast<ReturnStmt>(Body->body_front())
549 if (!OnlyReturn || !OnlyReturn->getRetValue())
551 return OnlyReturn->getRetValue();
564const Expr *setterLHS(
const CXXMethodDecl *CMD) {
565 assert(CMD->hasBody());
566 if (CMD->isConst() || CMD->getNumParams() != 1 || CMD->isVariadic())
568 const ParmVarDecl *Arg = CMD->getParamDecl(0);
569 if (Arg->isParameterPack())
572 const auto *Body = llvm::dyn_cast<CompoundStmt>(CMD->getBody());
573 if (!Body || Body->size() == 0 || Body->size() > 2)
576 if (Body->size() == 2) {
577 auto *Ret = llvm::dyn_cast<ReturnStmt>(Body->body_back());
578 if (!Ret || !Ret->getRetValue())
580 const Expr *RetVal = Ret->getRetValue()->IgnoreCasts();
581 if (
const auto *UO = llvm::dyn_cast<UnaryOperator>(RetVal)) {
582 if (UO->getOpcode() != UO_Deref)
584 RetVal = UO->getSubExpr()->IgnoreCasts();
586 if (!llvm::isa<CXXThisExpr>(RetVal))
590 const Expr *LHS, *RHS;
591 if (
const auto *BO = llvm::dyn_cast<BinaryOperator>(Body->body_front())) {
592 if (BO->getOpcode() != BO_Assign)
596 }
else if (
const auto *COCE =
597 llvm::dyn_cast<CXXOperatorCallExpr>(Body->body_front())) {
598 if (COCE->getOperator() != OO_Equal || COCE->getNumArgs() != 2)
600 LHS = COCE->getArg(0);
601 RHS = COCE->getArg(1);
607 if (
auto *CE = llvm::dyn_cast<CallExpr>(RHS->IgnoreCasts())) {
608 if (CE->getNumArgs() != 1)
610 auto *ND = llvm::dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl());
611 if (!ND || !ND->getIdentifier() || ND->getName() !=
"move" ||
612 !ND->isInStdNamespace())
617 auto *DRE = llvm::dyn_cast<DeclRefExpr>(RHS->IgnoreCasts());
618 if (!DRE || DRE->getDecl() != Arg)
623std::string synthesizeDocumentation(
const ASTContext &Ctx,
624 const NamedDecl *ND) {
625 const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(ND);
630 if (!CMD->getDeclName().isIdentifier() || CMD->isStatic())
633 CMD = llvm::dyn_cast_or_null<CXXMethodDecl>(CMD->getDefinition());
634 if (!CMD || !CMD->hasBody())
637 if (
const Expr *RetVal = getterReturnExpr(CMD)) {
638 if (
const auto GetterField = fieldName(RetVal)) {
639 if (
const auto Comment = fieldComment(Ctx, RetVal))
640 return llvm::formatv(
"Trivial accessor for `{0}`.\n\n{1}", *GetterField,
642 return llvm::formatv(
"Trivial accessor for `{0}`.", *GetterField);
645 if (
const auto *
const SetterLHS = setterLHS(CMD)) {
646 if (
const auto FieldName = fieldName(SetterLHS)) {
647 if (
const auto Comment = fieldComment(Ctx, SetterLHS))
648 return llvm::formatv(
"Trivial setter for `{0}`.\n\n{1}", *FieldName,
650 return llvm::formatv(
"Trivial setter for `{0}`.", *FieldName);
658HoverInfo getHoverContents(
const NamedDecl *D,
const PrintingPolicy &PP,
660 const syntax::TokenBuffer &TB) {
662 auto &Ctx =
D->getASTContext();
664 HI.AccessSpecifier = getAccessSpelling(
D->getAccess()).str();
665 HI.NamespaceScope = getNamespaceScope(D);
666 if (!HI.NamespaceScope->empty())
667 HI.NamespaceScope->append(
"::");
668 HI.LocalScope = getLocalScope(D);
669 if (!HI.LocalScope.empty())
670 HI.LocalScope.append(
"::");
673 const auto *CommentD = getDeclForComment(D);
677 HI.CommentOpts =
D->getASTContext().getLangOpts().CommentOpts;
678 enhanceFromIndex(HI, *CommentD, Index);
679 if (HI.Documentation.empty())
680 HI.Documentation = synthesizeDocumentation(Ctx, D);
682 HI.Kind = index::getSymbolInfo(D).Kind;
685 if (
const TemplateDecl *TD =
D->getDescribedTemplate()) {
686 HI.TemplateParameters =
687 fetchTemplateParameters(TD->getTemplateParameters(), PP);
689 }
else if (
const FunctionDecl *FD =
D->getAsFunction()) {
690 if (
const auto *FTD = FD->getDescribedTemplate()) {
691 HI.TemplateParameters =
692 fetchTemplateParameters(FTD->getTemplateParameters(), PP);
698 if (
const FunctionDecl *FD = getUnderlyingFunction(D))
699 fillFunctionTypeAndParams(HI, D, FD, PP);
700 else if (
const auto *VD = dyn_cast<ValueDecl>(D))
701 HI.Type =
printType(VD->getType(), Ctx, PP);
702 else if (
const auto *TTP = dyn_cast<TemplateTypeParmDecl>(D))
703 HI.Type = TTP->wasDeclaredWithTypename() ?
"typename" :
"class";
704 else if (
const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(D))
706 else if (
const auto *VT = dyn_cast<VarTemplateDecl>(D))
707 HI.Type =
printType(VT->getTemplatedDecl()->getType(), Ctx, PP);
708 else if (
const auto *TN = dyn_cast<TypedefNameDecl>(D))
709 HI.Type =
printType(TN->getUnderlyingType().getDesugaredType(Ctx), Ctx, PP);
710 else if (
const auto *TAT = dyn_cast<TypeAliasTemplateDecl>(D))
711 HI.Type =
printType(TAT->getTemplatedDecl()->getUnderlyingType(), Ctx, PP);
714 if (
const auto *Var = dyn_cast<VarDecl>(D); Var && !Var->isInvalidDecl()) {
715 if (
const Expr *Init = Var->getInit())
716 HI.Value = printExprValue(Init, Ctx);
717 }
else if (
const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
719 if (!ECD->getType()->isDependentType())
720 HI.Value =
toString(ECD->getInitVal(), 10);
723 HI.Definition = printDefinition(D, PP, TB);
728std::optional<HoverInfo>
729getPredefinedExprHoverContents(
const PredefinedExpr &PE, ASTContext &Ctx,
730 const PrintingPolicy &PP) {
732 HI.
Name = PE.getIdentKindName();
733 HI.Kind = index::SymbolKind::Variable;
734 HI.Documentation =
"Name of the current function (predefined variable)";
735 if (
const StringLiteral *Name = PE.getFunctionName()) {
737 llvm::raw_string_ostream OS(*HI.Value);
738 Name->outputString(OS);
739 HI.Type =
printType(Name->getType(), Ctx, PP);
742 QualType StringType = Ctx.getIncompleteArrayType(Ctx.CharTy.withConst(),
743 ArraySizeModifier::Normal,
745 HI.Type =
printType(StringType, Ctx, PP);
750HoverInfo evaluateMacroExpansion(
unsigned int SpellingBeginOffset,
751 unsigned int SpellingEndOffset,
752 llvm::ArrayRef<syntax::Token> Expanded,
755 auto &Tokens =
AST.getTokens();
756 auto PP = getPrintingPolicy(
Context.getPrintingPolicy());
765 if (Expanded.size() == 1)
766 if (tok::getPunctuatorSpelling(Expanded[0].kind()))
769 auto *StartNode = Tree.commonAncestor();
780 if (!StartNode->Children.empty())
785 auto ExprResult = printExprValue(StartNode,
Context);
786 HI.Value = std::move(ExprResult.PrintedValue);
787 if (
auto *E = ExprResult.TheExpr)
791 if (!HI.Value && !HI.Type && ExprResult.TheNode)
792 if (
auto *VD = ExprResult.TheNode->ASTNode.get<VarDecl>())
802 SourceManager &SM =
AST.getSourceManager();
803 HI.Name = std::string(
Macro.Name);
804 HI.Kind = index::SymbolKind::Macro;
809 SourceLocation StartLoc =
Macro.Info->getDefinitionLoc();
810 SourceLocation EndLoc =
Macro.Info->getDefinitionEndLoc();
818 if (SM.getPresumedLoc(EndLoc,
false).isValid()) {
819 EndLoc = Lexer::getLocForEndOfToken(EndLoc, 0, SM,
AST.getLangOpts());
821 StringRef Buffer = SM.getBufferData(SM.getFileID(StartLoc), &Invalid);
823 unsigned StartOffset = SM.getFileOffset(StartLoc);
824 unsigned EndOffset = SM.getFileOffset(EndLoc);
825 if (EndOffset <= Buffer.size() && StartOffset < EndOffset)
827 (
"#define " + Buffer.substr(StartOffset, EndOffset - StartOffset))
832 if (
auto Expansion =
AST.getTokens().expansionStartingAt(&Tok)) {
836 std::string ExpansionText;
837 for (
const auto &ExpandedTok : Expansion->Expanded) {
838 ExpansionText += ExpandedTok.text(SM);
839 ExpansionText +=
" ";
841 const size_t Limit =
static_cast<size_t>(Cfg.Hover.MacroContentsLimit);
842 if (Limit && ExpansionText.size() > Limit) {
843 ExpansionText.clear();
848 if (!ExpansionText.empty()) {
849 if (!HI.Definition.empty()) {
850 HI.Definition +=
"\n\n";
852 HI.Definition +=
"// Expands to\n";
853 HI.Definition += ExpansionText;
856 auto Evaluated = evaluateMacroExpansion(
857 SM.getFileOffset(Tok.location()),
858 SM.getFileOffset(Tok.endLocation()),
859 Expansion->Expanded,
AST);
860 HI.Value = std::move(Evaluated.Value);
861 HI.Type = std::move(Evaluated.Type);
868 llvm::raw_string_ostream OS(Result);
871 OS <<
" // aka: " << *PType.AKA;
875std::optional<HoverInfo> getThisExprHoverContents(
const CXXThisExpr *CTE,
877 const PrintingPolicy &PP) {
878 QualType OriginThisType = CTE->getType()->getPointeeType();
879 QualType ClassType =
declaredType(OriginThisType->castAsTagDecl());
884 QualType PrettyThisType = ASTCtx.getPointerType(
885 QualType(ClassType.getTypePtr(), OriginThisType.getCVRQualifiers()));
889 HI.Definition = typeAsDefinition(
printType(PrettyThisType, ASTCtx, PP));
894HoverInfo getDeducedTypeHoverContents(QualType QT,
const syntax::Token &Tok,
896 const PrintingPolicy &PP,
900 HI.
Name = tok::getTokenName(Tok.kind());
901 HI.Kind = index::SymbolKind::TypeAlias;
903 if (QT->isUndeducedAutoType()) {
904 HI.Definition =
"/* not deduced */";
906 HI.Definition = typeAsDefinition(
printType(QT, ASTCtx, PP));
908 if (
const auto *D = QT->getAsTagDecl()) {
909 const auto *CommentD = getDeclForComment(D);
911 enhanceFromIndex(HI, *CommentD, Index);
918HoverInfo getStringLiteralContents(
const StringLiteral *SL,
919 const PrintingPolicy &PP) {
922 HI.
Name =
"string-literal";
923 HI.Size = (SL->getLength() + 1) * SL->getCharByteWidth() * 8;
924 HI.Type = SL->getType().getAsString(PP).c_str();
929bool isLiteral(
const Expr *E) {
932 return llvm::isa<CompoundLiteralExpr>(E) ||
933 llvm::isa<CXXBoolLiteralExpr>(E) ||
934 llvm::isa<CXXNullPtrLiteralExpr>(E) ||
935 llvm::isa<FixedPointLiteral>(E) || llvm::isa<FloatingLiteral>(E) ||
936 llvm::isa<ImaginaryLiteral>(E) || llvm::isa<IntegerLiteral>(E) ||
937 llvm::isa<StringLiteral>(E) || llvm::isa<UserDefinedLiteral>(E);
940llvm::StringLiteral getNameForExpr(
const Expr *E) {
948 return llvm::StringLiteral(
"expression");
952 const PrintingPolicy &PP);
958 const PrintingPolicy &PP,
960 std::optional<HoverInfo> HI;
962 if (
const StringLiteral *SL = dyn_cast<StringLiteral>(E)) {
964 HI = getStringLiteralContents(SL, PP);
965 }
else if (isLiteral(E)) {
969 maybeAddCalleeArgInfo(N, HI.emplace(), PP);
970 if (HI->CalleeArgInfo) {
974 HI->Name =
"literal";
981 if (
const CXXThisExpr *CTE = dyn_cast<CXXThisExpr>(E))
982 HI = getThisExprHoverContents(CTE,
AST.getASTContext(), PP);
983 if (
const PredefinedExpr *PE = dyn_cast<PredefinedExpr>(E))
984 HI = getPredefinedExprHoverContents(*PE,
AST.getASTContext(), PP);
987 if (
auto Val = printExprValue(E,
AST.getASTContext())) {
989 HI->Type =
printType(E->getType(),
AST.getASTContext(), PP);
991 HI->Name = std::string(getNameForExpr(E));
995 maybeAddCalleeArgInfo(N, *HI, PP);
1001std::optional<HoverInfo> getHoverContents(
const Attr *A,
ParsedAST &
AST) {
1003 HI.
Name =
A->getSpelling();
1005 HI.LocalScope =
A->getScopeName()->getName().str();
1007 llvm::raw_string_ostream OS(HI.Definition);
1008 A->printPretty(OS,
AST.getASTContext().getPrintingPolicy());
1010 HI.Documentation = Attr::getDocumentation(
A->getKind()).str();
1014void addLayoutInfo(
const NamedDecl &ND,
HoverInfo &HI) {
1015 if (ND.isInvalidDecl())
1018 const auto &Ctx = ND.getASTContext();
1019 if (
auto *RD = llvm::dyn_cast<RecordDecl>(&ND)) {
1020 CanQualType RT = Ctx.getCanonicalTagType(RD);
1021 if (
auto Size = Ctx.getTypeSizeInCharsIfKnown(RT))
1022 HI.Size = Size->getQuantity() * 8;
1023 if (!RD->isDependentType() && RD->isCompleteDefinition())
1024 HI.Align = Ctx.getTypeAlign(RT);
1028 if (
const auto *FD = llvm::dyn_cast<FieldDecl>(&ND)) {
1029 const auto *
Record = FD->getParent();
1032 if (Record && !
Record->isInvalidDecl() && !
Record->isDependentType()) {
1033 HI.Align = Ctx.getTypeAlign(FD->getType());
1034 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Record);
1035 HI.Offset = Layout.getFieldOffset(FD->getFieldIndex());
1036 if (FD->isBitField())
1037 HI.Size = FD->getBitWidthValue();
1038 else if (
auto Size = Ctx.getTypeSizeInCharsIfKnown(FD->getType()))
1039 HI.Size = FD->isZeroSize(Ctx) ? 0 : Size->getQuantity() * 8;
1041 unsigned EndOfField = *HI.Offset + *HI.Size;
1044 if (!
Record->isUnion() &&
1045 FD->getFieldIndex() + 1 < Layout.getFieldCount()) {
1047 unsigned NextOffset = Layout.getFieldOffset(FD->getFieldIndex() + 1);
1048 if (NextOffset >= EndOfField)
1049 HI.Padding = NextOffset - EndOfField;
1052 HI.Padding = Layout.getSize().getQuantity() * 8 - EndOfField;
1064 if (ParmType->isReferenceType()) {
1065 if (ParmType->getPointeeType().isConstQualified())
1075 const PrintingPolicy &PP) {
1076 const auto &OuterNode = N->outerImplicit();
1077 if (!OuterNode.Parent)
1080 const FunctionDecl *FD =
nullptr;
1081 llvm::ArrayRef<const Expr *> Args;
1083 if (
const auto *CE = OuterNode.Parent->ASTNode.get<CallExpr>()) {
1084 FD = CE->getDirectCallee();
1085 Args = {CE->getArgs(), CE->getNumArgs()};
1086 }
else if (
const auto *CE =
1087 OuterNode.Parent->ASTNode.get<CXXConstructExpr>()) {
1088 FD = CE->getConstructor();
1089 Args = {CE->getArgs(), CE->getNumArgs()};
1100 if (!FD || FD->isOverloadedOperator() || FD->isVariadic())
1108 for (
unsigned I = 0; I < Args.size() && I < Parameters.size(); ++I) {
1109 if (Args[I] != OuterNode.ASTNode.get<Expr>())
1113 if (
const ParmVarDecl *PVD = Parameters[I]) {
1114 HI.CalleeArgInfo.emplace(toHoverInfoParam(PVD, PP));
1115 if (N == &OuterNode)
1116 PassType.PassBy = getPassMode(PVD->getType());
1120 if (!HI.CalleeArgInfo)
1126 if (
const auto *E = N->ASTNode.get<Expr>()) {
1127 if (E->getType().isConstQualified())
1131 for (
auto *CastNode = N->Parent;
1132 CastNode != OuterNode.Parent && !PassType.Converted;
1133 CastNode = CastNode->Parent) {
1134 if (
const auto *ImplicitCast = CastNode->ASTNode.get<ImplicitCastExpr>()) {
1135 switch (ImplicitCast->getCastKind()) {
1137 case CK_DerivedToBase:
1138 case CK_UncheckedDerivedToBase:
1141 PassType.PassBy = ImplicitCast->getType().isConstQualified()
1145 case CK_LValueToRValue:
1146 case CK_ArrayToPointerDecay:
1147 case CK_FunctionToPointerDecay:
1148 case CK_NullToPointer:
1149 case CK_NullToMemberPointer:
1155 PassType.Converted =
true;
1158 }
else if (
const auto *CtorCall =
1159 CastNode->ASTNode.get<CXXConstructExpr>()) {
1162 if (CtorCall->getConstructor()->isCopyConstructor())
1165 PassType.Converted =
true;
1166 }
else if (CastNode->ASTNode.get<MaterializeTemporaryExpr>()) {
1171 PassType.Converted =
true;
1175 HI.CallPassType.emplace(PassType);
1178const NamedDecl *pickDeclToUse(llvm::ArrayRef<const NamedDecl *> Candidates) {
1179 if (Candidates.empty())
1188 if (Candidates.size() <= 2) {
1189 if (llvm::isa<UsingDecl>(Candidates.front()))
1190 return Candidates.back();
1191 return Candidates.front();
1200 auto BaseDecls = llvm::make_filter_range(
1201 Candidates, [](
const NamedDecl *D) {
return llvm::isa<UsingDecl>(D); });
1202 if (std::distance(BaseDecls.begin(), BaseDecls.end()) == 1)
1203 return *BaseDecls.begin();
1205 return Candidates.front();
1209 include_cleaner::Symbol Sym) {
1210 trace::Span Tracer(
"Hover::maybeAddSymbolProviders");
1212 llvm::SmallVector<include_cleaner::Header> RankedProviders =
1213 include_cleaner::headersForSymbol(Sym,
AST.getPreprocessor(),
1214 &
AST.getPragmaIncludes());
1215 if (RankedProviders.empty())
1218 const SourceManager &SM =
AST.getSourceManager();
1221 for (
const auto &P : RankedProviders) {
1222 if (
P.kind() == include_cleaner::Header::Physical &&
1223 P.physical() == SM.getFileEntryForID(SM.getMainFileID()))
1228 auto Matches = ConvertedIncludes.match(P);
1229 if (!Matches.empty()) {
1230 Result = Matches[0]->quote();
1235 if (!Result.empty()) {
1236 HI.Provider = std::move(Result);
1241 const auto &H = RankedProviders.front();
1242 if (H.kind() == include_cleaner::Header::Physical &&
1243 H.physical() == SM.getFileEntryForID(SM.getMainFileID()))
1248 HI.Provider = include_cleaner::spellHeader(
1249 {H,
AST.getPreprocessor().getHeaderSearchInfo(),
1250 SM.getFileEntryForID(SM.getMainFileID())});
1256std::string getSymbolName(include_cleaner::Symbol Sym) {
1258 switch (Sym.kind()) {
1259 case include_cleaner::Symbol::Declaration:
1260 if (
const auto *ND = llvm::dyn_cast<NamedDecl>(&Sym.declaration()))
1261 Name = ND->getDeclName().getAsString();
1263 case include_cleaner::Symbol::Macro:
1264 Name = Sym.macro().Name->getName();
1272 llvm::DenseSet<include_cleaner::Symbol> UsedSymbols;
1273 include_cleaner::walkUsed(
1275 &
AST.getPragmaIncludes(),
AST.getPreprocessor(),
1276 [&](
const include_cleaner::SymbolReference &
Ref,
1277 llvm::ArrayRef<include_cleaner::Header> Providers) {
1278 if (Ref.RT != include_cleaner::RefType::Explicit ||
1279 UsedSymbols.contains(Ref.Target))
1282 if (isPreferredProvider(Inc, Converted, Providers))
1283 UsedSymbols.insert(Ref.Target);
1286 for (
const auto &UsedSymbolDecl : UsedSymbols)
1287 HI.UsedSymbolNames.push_back(getSymbolName(UsedSymbolDecl));
1288 llvm::sort(HI.UsedSymbolNames);
1289 HI.UsedSymbolNames.erase(llvm::unique(HI.UsedSymbolNames),
1290 HI.UsedSymbolNames.end());
1296 const format::FormatStyle &Style,
1301 getPrintingPolicy(
AST.getASTContext().getPrintingPolicy());
1302 const SourceManager &SM =
AST.getSourceManager();
1305 llvm::consumeError(CurLoc.takeError());
1306 return std::nullopt;
1308 const auto &TB =
AST.getTokens();
1309 auto TokensTouchingCursor = syntax::spelledTokensTouching(*CurLoc, TB);
1311 if (TokensTouchingCursor.empty())
1312 return std::nullopt;
1315 for (
const auto &Inc :
AST.getIncludeStructure().MainFileIncludes) {
1316 if (Inc.Resolved.empty() || Inc.HashLine != Pos.
line)
1318 HoverCountMetric.
record(1,
"include");
1320 HI.
Name = std::string(llvm::sys::path::filename(Inc.Resolved));
1324 HI.
Kind = index::SymbolKind::IncludeDirective;
1325 maybeAddUsedSymbols(
AST, HI, Inc);
1332 CharSourceRange HighlightRange =
1333 TokensTouchingCursor.back().range(SM).toCharRange(SM);
1334 std::optional<HoverInfo> HI;
1338 for (
const auto &Tok : TokensTouchingCursor) {
1339 if (Tok.kind() == tok::identifier) {
1341 HighlightRange = Tok.range(SM).toCharRange(SM);
1343 HoverCountMetric.
record(1,
"macro");
1344 HI = getHoverContents(*M, Tok,
AST);
1345 if (
auto DefLoc = M->Info->getDefinitionLoc(); DefLoc.isValid()) {
1346 include_cleaner::Macro IncludeCleanerMacro{
1347 AST.getPreprocessor().getIdentifierInfo(Tok.text(SM)), DefLoc};
1348 maybeAddSymbolProviders(
AST, *HI,
1349 include_cleaner::Symbol{IncludeCleanerMacro});
1353 }
else if (Tok.kind() == tok::kw_auto || Tok.kind() == tok::kw_decltype) {
1354 HoverCountMetric.
record(1,
"keyword");
1358 HI = getDeducedTypeHoverContents(*
Deduced, Tok,
AST.getASTContext(), PP,
1360 HighlightRange = Tok.range(SM).toCharRange(SM);
1367 return std::nullopt;
1373 auto Offset = SM.getFileOffset(*CurLoc);
1381 AST.getHeuristicResolver());
1382 if (
const auto *DeclToUse = pickDeclToUse(Decls)) {
1383 HoverCountMetric.
record(1,
"decl");
1384 HI = getHoverContents(DeclToUse, PP, Index, TB);
1386 if (DeclToUse == N->ASTNode.get<Decl>())
1387 addLayoutInfo(*DeclToUse, *HI);
1390 HI->Value = printExprValue(N,
AST.getASTContext()).PrintedValue;
1391 maybeAddCalleeArgInfo(N, *HI, PP);
1393 if (!isa<NamespaceDecl>(DeclToUse))
1394 maybeAddSymbolProviders(
AST, *HI,
1395 include_cleaner::Symbol{*DeclToUse});
1396 }
else if (
const Expr *E = N->ASTNode.get<Expr>()) {
1397 HoverCountMetric.
record(1,
"expr");
1398 HI = getHoverContents(N, E,
AST, PP, Index);
1399 }
else if (
const Attr *A = N->ASTNode.get<Attr>()) {
1400 HoverCountMetric.
record(1,
"attribute");
1401 HI = getHoverContents(A,
AST);
1409 return std::nullopt;
1412 if (!HI->Definition.empty()) {
1413 auto Replacements = format::reformat(
1414 Style, HI->Definition, tooling::Range(0, HI->Definition.size()));
1415 if (
auto Formatted =
1416 tooling::applyAllReplacements(HI->Definition, Replacements))
1417 HI->Definition = *Formatted;
1420 HI->DefinitionLanguage = getMarkdownLanguage(
AST.getASTContext());
1428 uint64_t
Value = SizeInBits % 8 == 0 ? SizeInBits / 8 : SizeInBits;
1429 const char *
Unit =
Value != 0 &&
Value == SizeInBits ?
"bit" :
"byte";
1430 return llvm::formatv(
"{0} {1}{2}",
Value,
Unit,
Value == 1 ?
"" :
"s").str();
1436 const auto Bytes = OffsetInBits / 8;
1437 const auto Bits = OffsetInBits % 8;
1444void HoverInfo::calleeArgInfoToMarkupParagraph(markup::Paragraph &P)
const {
1447 llvm::raw_string_ostream OS(Buffer);
1460 OS <<
" (converted to " <<
CalleeArgInfo->Type->Type <<
")";
1461 P.appendText(OS.str());
1464void HoverInfo::usedSymbolNamesToMarkup(markup::Document &Output)
const {
1465 markup::Paragraph &
P = Output.addParagraph();
1466 P.appendText(
"provides ");
1468 const std::vector<std::string>::size_type SymbolNamesLimit = 5;
1469 auto Front = llvm::ArrayRef(
UsedSymbolNames).take_front(SymbolNamesLimit);
1472 Front, [&](llvm::StringRef Sym) {
P.appendCode(Sym); },
1473 [&] {
P.appendText(
", "); });
1475 P.appendText(
" and ");
1477 P.appendText(
" more");
1481void HoverInfo::providerToMarkupParagraph(markup::Document &Output)
const {
1482 markup::Paragraph &DI = Output.addParagraph();
1483 DI.appendText(
"provided by");
1488void HoverInfo::definitionScopeToMarkup(markup::Document &Output)
const {
1498 Buffer +=
"// In " + llvm::StringRef(
LocalScope).rtrim(
':').str() +
'\n';
1500 Buffer +=
"// In namespace " +
1501 llvm::StringRef(*NamespaceScope).rtrim(
':').str() +
'\n';
1514 P.appendText(
"Value = ");
1531markup::Document HoverInfo::presentDoxygen()
const {
1533 markup::Document Output;
1546 markup::Paragraph &Header = Output.addHeading(3);
1547 if (
Kind != index::SymbolKind::Unknown &&
1548 Kind != index::SymbolKind::IncludeDirective)
1549 Header.appendText(index::getSymbolKindString(
Kind)).appendSpace();
1550 assert(!
Name.empty() &&
"hover triggered on a nameless symbol");
1552 if (
Kind == index::SymbolKind::IncludeDirective) {
1553 Header.appendCode(
Name);
1556 Output.addParagraph().appendCode(
Definition);
1560 usedSymbolNamesToMarkup(Output);
1568 definitionScopeToMarkup(Output);
1570 Header.appendCode(
Name);
1574 providerToMarkupParagraph(Output);
1582 if (SymbolDoc.hasBriefCommand()) {
1583 if (
Kind != index::SymbolKind::Parameter &&
1584 Kind != index::SymbolKind::TemplateTypeParm)
1588 Output.addHeading(3).appendText(
"Brief");
1589 SymbolDoc.briefToMarkup(Output.addParagraph());
1602 Output.addHeading(3).appendText(
"Template Parameters");
1603 markup::BulletList &L = Output.addBulletList();
1605 markup::Paragraph &
P = L.addItem().addParagraph();
1606 P.appendCode(llvm::to_string(
Param));
1607 if (SymbolDoc.isTemplateTypeParmDocumented(llvm::to_string(
Param.
Name))) {
1608 P.appendText(
" - ");
1609 SymbolDoc.templateTypeParmDocToMarkup(llvm::to_string(
Param.
Name), P);
1616 Output.addHeading(3).appendText(
"Parameters");
1617 markup::BulletList &L = Output.addBulletList();
1619 markup::Paragraph &
P = L.addItem().addParagraph();
1620 P.appendCode(llvm::to_string(
Param));
1622 if (SymbolDoc.isParameterDocumented(llvm::to_string(
Param.
Name))) {
1623 P.appendText(
" - ");
1624 SymbolDoc.parameterDocToMarkup(llvm::to_string(
Param.
Name), P);
1635 Output.addHeading(3).appendText(
"Returns");
1636 markup::Paragraph &
P = Output.addParagraph();
1639 if (SymbolDoc.hasReturnCommand()) {
1640 P.appendText(
" - ");
1641 SymbolDoc.returnToMarkup(P);
1644 SymbolDoc.retvalsToMarkup(Output);
1648 if (SymbolDoc.hasDetailedDoc()) {
1649 Output.addHeading(3).appendText(
"Details");
1650 SymbolDoc.detailedDocToMarkup(Output);
1658 Output.addParagraph().appendText(
"Type: ").appendCode(
1659 llvm::to_string(*
Type));
1662 valueToMarkupParagraph(Output.addParagraph());
1666 offsetToMarkupParagraph(Output.addParagraph());
1668 sizeToMarkupParagraph(Output.addParagraph());
1672 calleeArgInfoToMarkupParagraph(Output.addParagraph());
1677 usedSymbolNamesToMarkup(Output);
1683markup::Document HoverInfo::presentDefault()
const {
1684 markup::Document Output;
1697 markup::Paragraph &Header = Output.addHeading(3);
1698 if (
Kind != index::SymbolKind::Unknown &&
1699 Kind != index::SymbolKind::IncludeDirective)
1700 Header.appendText(index::getSymbolKindString(
Kind)).appendSpace();
1701 assert(!
Name.empty() &&
"hover triggered on a nameless symbol");
1702 Header.appendCode(
Name);
1705 providerToMarkupParagraph(Output);
1718 Output.addParagraph().appendText(
"→ ").appendCode(
1723 Output.addParagraph().appendText(
"Parameters:");
1724 markup::BulletList &L = Output.addBulletList();
1726 L.addItem().addParagraph().appendCode(llvm::to_string(
Param));
1732 Output.addParagraph().appendText(
"Type: ").appendCode(
1733 llvm::to_string(*
Type));
1736 valueToMarkupParagraph(Output.addParagraph());
1740 offsetToMarkupParagraph(Output.addParagraph());
1742 sizeToMarkupParagraph(Output.addParagraph());
1746 calleeArgInfoToMarkupParagraph(Output.addParagraph());
1754 definitionScopeToMarkup(Output);
1759 usedSymbolNamesToMarkup(Output);
1770 return presentDefault().asMarkdown();
1772 return presentDoxygen().asMarkdown();
1777 return presentDefault().asEscapedMarkdown();
1780 return presentDefault().asPlainText();
1787 assert(Line[Offset] ==
'`');
1790 llvm::StringRef Prefix = Line.substr(0, Offset);
1791 constexpr llvm::StringLiteral BeforeStartChars =
" \t(=";
1792 if (!Prefix.empty() && !BeforeStartChars.contains(Prefix.back()))
1793 return std::nullopt;
1796 auto Next = Line.find_first_of(
"`\n", Offset + 1);
1797 if (Next == llvm::StringRef::npos)
1798 return std::nullopt;
1801 if (Line[Next] ==
'\n')
1802 return std::nullopt;
1804 llvm::StringRef Contents = Line.slice(Offset + 1, Next);
1805 if (Contents.empty() || isWhitespace(Contents.front()) ||
1806 isWhitespace(Contents.back()))
1807 return std::nullopt;
1810 llvm::StringRef Suffix = Line.substr(Next + 1);
1811 constexpr llvm::StringLiteral AfterEndChars =
" \t)=.,;:";
1812 if (!Suffix.empty() && !AfterEndChars.contains(Suffix.front()))
1813 return std::nullopt;
1815 return Line.slice(Offset, Next + 1);
1820 for (
unsigned I = 0; I <
Text.size(); ++I) {
1825 Out.appendCode(
Range->trim(
"`"),
true);
1842 for (std::tie(
Paragraph, Rest) = Input.split(
"\n\n");
1844 std::tie(
Paragraph, Rest) = Rest.split(
"\n\n")) {
1856 OS <<
" (aka " << *T.AKA <<
")";
1865 OS <<
" " << *P.Name;
1867 OS <<
" = " << *P.Default;
1868 if (P.Type && P.Type->AKA)
1869 OS <<
" (aka " << *P.Type->AKA <<
")";
Include Cleaner is clangd functionality for providing diagnostics for misuse of transitive headers an...
A context is an immutable container for per-request data that must be propagated through layers that ...
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 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.
Records an event whose duration is the lifetime of the Span object.
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
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 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,.
std::string printType(const QualType QT, const DeclContext &CurContext, const llvm::StringRef Placeholder, bool FullyQualify)
Returns a QualType as string.
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)
std::optional< QualType > getDeducedType(ASTContext &ASTCtx, const HeuristicResolver *Resolver, SourceLocation Loc)
Retrieves the deduced type at a given location (auto, decltype).
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, const CodeCompletion &C)
void parseDocumentationParagraph(llvm::StringRef Text, markup::Paragraph &Out)
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.
llvm::SmallVector< uint64_t, 1024 > Record
cppcoreguidelines::ProBoundsAvoidUncheckedContainerAccessCheck P
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Settings that express user/project preferences and control clangd behavior.
static const Config & current()
Returns the Config of the current Context, or an empty configuration.
@ Markdown
Treat comments as Markdown.
@ Doxygen
Treat comments as doxygen.
@ PlainText
Treat comments as plain text.
struct clang::clangd::Config::@205014242342057164216030136313205137334246150047 Documentation
CommentFormatPolicy CommentFormat
Represents parameters of a function, a template or a macro.
std::optional< PrintedType > Type
The printable parameter type, e.g.
std::optional< std::string > Name
std::nullopt for unnamed parameters.
Contains pretty-printed type and desugared type.
std::string Type
Pretty-printed 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::string present(MarkupKind Kind) const
Produce a user-readable information based on the specified markup kind.
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.
std::optional< std::vector< Param > > TemplateParameters
Set for all templates(function, class, variable).
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
CommentOptions CommentOpts
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.
llvm::DenseSet< SymbolID > IDs
int line
Line position in a document (zero-based).
Represents a symbol occurrence in the source file.
The class presents a C++ symbol, e.g.
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.