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.AnonymousTagLocations =
false;
74 Base.TerseOutput =
true;
75 Base.PolishForDeclaration =
true;
76 Base.ConstantsAsWritten =
true;
77 Base.SuppressTemplateArgsInCXXConstructors =
true;
84std::string getLocalScope(
const Decl *D) {
85 std::vector<std::string> Scopes;
86 const DeclContext *DC =
D->getDeclContext();
91 if (
const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
93 if (
const ObjCContainerDecl *CD = dyn_cast<ObjCContainerDecl>(DC))
96 auto GetName = [](
const TypeDecl *
D) {
97 if (!
D->getDeclName().isEmpty()) {
98 PrintingPolicy Policy =
D->getASTContext().getPrintingPolicy();
99 Policy.SuppressScope =
true;
102 if (
auto *RD = dyn_cast<RecordDecl>(D))
103 return (
"(anonymous " + RD->getKindName() +
")").str();
104 return std::string(
"");
107 if (
const TypeDecl *TD = dyn_cast<TypeDecl>(DC))
108 Scopes.push_back(GetName(TD));
109 else if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
110 Scopes.push_back(FD->getNameAsString());
111 DC = DC->getParent();
114 return llvm::join(llvm::reverse(Scopes),
"::");
119std::string getNamespaceScope(
const Decl *D) {
120 const DeclContext *DC =
D->getDeclContext();
124 if (isa<ObjCMethodDecl, ObjCContainerDecl>(DC))
127 if (
const TagDecl *TD = dyn_cast<TagDecl>(DC))
128 return getNamespaceScope(TD);
129 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
130 return getNamespaceScope(FD);
131 if (
const NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(DC)) {
133 if (NSD->isInline() || NSD->isAnonymousNamespace())
134 return getNamespaceScope(NSD);
136 if (
const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
142std::string printDefinition(
const Decl *D, PrintingPolicy PP,
143 const syntax::TokenBuffer &TB) {
144 if (
auto *VD = llvm::dyn_cast<VarDecl>(D)) {
145 if (
auto *IE = VD->getInit()) {
149 if (200 < TB.expandedTokens(IE->getSourceRange()).size())
150 PP.SuppressInitializers =
true;
159const char *getMarkdownLanguage(
const ASTContext &Ctx) {
160 const auto &LangOpts = Ctx.getLangOpts();
161 if (LangOpts.ObjC && LangOpts.CPlusPlus)
162 return "objective-cpp";
163 return LangOpts.ObjC ?
"objective-c" :
"cpp";
167 const PrintingPolicy &PP) {
171 while (!QT.isNull() && QT->isDecltypeType())
172 QT = QT->castAs<DecltypeType>()->getUnderlyingType();
174 llvm::raw_string_ostream OS(Result.Type);
179 if (!QT.isNull() && !QT.hasQualifiers() && PP.SuppressTagKeyword) {
180 if (
auto *TT = llvm::dyn_cast<TagType>(QT.getTypePtr());
181 TT && TT->isCanonicalUnqualified())
182 OS << TT->getOriginalDecl()->getKindName() <<
" ";
187 if (!QT.isNull() && Cfg.Hover.ShowAKA) {
188 bool ShouldAKA =
false;
189 QualType DesugaredTy = clang::desugarForDiagnostic(ASTCtx, QT, ShouldAKA);
191 Result.AKA = DesugaredTy.getAsString(PP);
198 Result.
Type = TTP->wasDeclaredWithTypename() ?
"typename" :
"class";
199 if (TTP->isParameterPack())
200 Result.Type +=
"...";
205 const PrintingPolicy &PP) {
206 auto PrintedType =
printType(NTTP->getType(), NTTP->getASTContext(), PP);
207 if (NTTP->isParameterPack()) {
208 PrintedType.Type +=
"...";
210 *PrintedType.AKA +=
"...";
216 const PrintingPolicy &PP) {
218 llvm::raw_string_ostream OS(Result.Type);
220 llvm::StringRef Sep =
"";
221 for (
const Decl *Param : *TTP->getTemplateParameters()) {
224 if (
const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
226 else if (
const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
228 else if (
const auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param))
237std::vector<HoverInfo::Param>
238fetchTemplateParameters(
const TemplateParameterList *Params,
239 const PrintingPolicy &PP) {
241 std::vector<HoverInfo::Param> TempParameters;
243 for (
const Decl *Param : *Params) {
245 if (
const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
248 if (!TTP->getName().empty())
249 P.Name = TTP->getNameAsString();
251 if (TTP->hasDefaultArgument()) {
253 llvm::raw_string_ostream Out(*
P.Default);
254 TTP->getDefaultArgument().getArgument().print(PP, Out,
257 }
else if (
const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
260 if (IdentifierInfo *II = NTTP->getIdentifier())
261 P.Name = II->getName().str();
263 if (NTTP->hasDefaultArgument()) {
265 llvm::raw_string_ostream Out(*
P.Default);
266 NTTP->getDefaultArgument().getArgument().print(PP, Out,
269 }
else if (
const auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param)) {
272 if (!TTPD->getName().empty())
273 P.Name = TTPD->getNameAsString();
275 if (TTPD->hasDefaultArgument()) {
277 llvm::raw_string_ostream Out(*
P.Default);
278 TTPD->getDefaultArgument().getArgument().print(PP, Out,
282 TempParameters.push_back(std::move(P));
285 return TempParameters;
288const FunctionDecl *getUnderlyingFunction(
const Decl *D) {
290 if (
const VarDecl *VD = llvm::dyn_cast<VarDecl>(D)) {
291 auto QT = VD->getType();
293 while (!QT->getPointeeType().isNull())
294 QT = QT->getPointeeType();
296 if (
const auto *CD = QT->getAsCXXRecordDecl())
297 return CD->getLambdaCallOperator();
302 return D->getAsFunction();
307const NamedDecl *getDeclForComment(
const NamedDecl *D) {
308 const NamedDecl *DeclForComment =
D;
309 if (
const auto *TSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(D)) {
312 if (TSD->getTemplateSpecializationKind() == TSK_Undeclared)
313 DeclForComment = TSD->getSpecializedTemplate();
314 else if (
const auto *TIP = TSD->getTemplateInstantiationPattern())
315 DeclForComment = TIP;
316 }
else if (
const auto *TSD =
317 llvm::dyn_cast<VarTemplateSpecializationDecl>(D)) {
318 if (TSD->getTemplateSpecializationKind() == TSK_Undeclared)
319 DeclForComment = TSD->getSpecializedTemplate();
320 else if (
const auto *TIP = TSD->getTemplateInstantiationPattern())
321 DeclForComment = TIP;
322 }
else if (
const auto *FD =
D->getAsFunction())
323 if (
const auto *TIP = FD->getTemplateInstantiationPattern())
324 DeclForComment = TIP;
329 if (D != DeclForComment)
330 DeclForComment = getDeclForComment(DeclForComment);
331 return DeclForComment;
337 assert(&ND == getDeclForComment(&ND));
339 if (!
Hover.Documentation.empty() || !Index)
353 Index->lookup(Req, [&](
const Symbol &S) {
354 Hover.Documentation = std::string(S.Documentation);
361const Expr *getDefaultArg(
const ParmVarDecl *PVD) {
366 if (!PVD->hasDefaultArg() || PVD->hasUnparsedDefaultArg())
368 return PVD->hasUninstantiatedDefaultArg() ? PVD->getUninstantiatedDefaultArg()
369 : PVD->getDefaultArg();
373 const PrintingPolicy &PP) {
375 Out.
Type =
printType(PVD->getType(), PVD->getASTContext(), PP);
376 if (!PVD->getName().empty())
377 Out.Name = PVD->getNameAsString();
378 if (
const Expr *DefArg = getDefaultArg(PVD)) {
379 Out.Default.emplace();
380 llvm::raw_string_ostream OS(*Out.Default);
381 DefArg->printPretty(OS,
nullptr, PP);
387void fillFunctionTypeAndParams(
HoverInfo &HI,
const Decl *D,
388 const FunctionDecl *FD,
389 const PrintingPolicy &PP) {
390 HI.Parameters.emplace();
391 for (
const ParmVarDecl *PVD : FD->parameters())
392 HI.Parameters->emplace_back(toHoverInfoParam(PVD, PP));
396 const auto NK = FD->getDeclName().getNameKind();
397 if (NK == DeclarationName::CXXConstructorName ||
398 NK == DeclarationName::CXXDestructorName ||
399 NK == DeclarationName::CXXConversionFunctionName)
402 HI.ReturnType =
printType(FD->getReturnType(), FD->getASTContext(), PP);
403 QualType QT = FD->getType();
404 if (
const VarDecl *VD = llvm::dyn_cast<VarDecl>(D))
405 QT = VD->getType().getDesugaredType(
D->getASTContext());
406 HI.Type =
printType(QT,
D->getASTContext(), PP);
416static llvm::FormattedNumber printHex(
const llvm::APSInt &V) {
417 assert(V.getSignificantBits() <= 64 &&
"Can't print more than 64 bits.");
419 V.getBitWidth() > 64 ? V.trunc(64).getZExtValue() : V.getZExtValue();
420 if (V.isNegative() && V.getSignificantBits() <= 32)
421 return llvm::format_hex(uint32_t(Bits), 0);
422 return llvm::format_hex(Bits, 0);
425std::optional<std::string> printExprValue(
const Expr *E,
426 const ASTContext &Ctx) {
431 if (
const auto *ILE = llvm::dyn_cast<InitListExpr>(E)) {
432 if (!ILE->isSemanticForm())
433 E = ILE->getSemanticForm();
439 QualType
T = E->getType();
440 if (
T.isNull() ||
T->isFunctionType() ||
T->isFunctionPointerType() ||
441 T->isFunctionReferenceType() ||
T->isVoidType())
446 if (E->isValueDependent() || !E->EvaluateAsRValue(
Constant, Ctx) ||
453 if (
T->isEnumeralType() &&
Constant.Val.isInt() &&
454 Constant.Val.getInt().getSignificantBits() <= 64) {
456 int64_t Val =
Constant.Val.getInt().getExtValue();
457 for (
const EnumConstantDecl *ECD :
T->castAsEnumDecl()->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 {
475 std::optional<std::string> PrintedValue;
478 const clang::Expr *TheExpr;
480 const SelectionTree::Node *TheNode;
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,
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);
634 HI.CommentOpts =
D->getASTContext().getLangOpts().CommentOpts;
635 enhanceFromIndex(HI, *CommentD, Index);
636 if (HI.Documentation.empty())
637 HI.Documentation = synthesizeDocumentation(D);
639 HI.Kind = index::getSymbolInfo(D).Kind;
642 if (
const TemplateDecl *TD =
D->getDescribedTemplate()) {
643 HI.TemplateParameters =
644 fetchTemplateParameters(TD->getTemplateParameters(), PP);
646 }
else if (
const FunctionDecl *FD =
D->getAsFunction()) {
647 if (
const auto *FTD = FD->getDescribedTemplate()) {
648 HI.TemplateParameters =
649 fetchTemplateParameters(FTD->getTemplateParameters(), PP);
655 if (
const FunctionDecl *FD = getUnderlyingFunction(D))
656 fillFunctionTypeAndParams(HI, D, FD, PP);
657 else if (
const auto *VD = dyn_cast<ValueDecl>(D))
658 HI.Type =
printType(VD->getType(), Ctx, PP);
659 else if (
const auto *TTP = dyn_cast<TemplateTypeParmDecl>(D))
660 HI.Type = TTP->wasDeclaredWithTypename() ?
"typename" :
"class";
661 else if (
const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(D))
663 else if (
const auto *VT = dyn_cast<VarTemplateDecl>(D))
664 HI.Type =
printType(VT->getTemplatedDecl()->getType(), Ctx, PP);
665 else if (
const auto *TN = dyn_cast<TypedefNameDecl>(D))
666 HI.Type =
printType(TN->getUnderlyingType().getDesugaredType(Ctx), Ctx, PP);
667 else if (
const auto *TAT = dyn_cast<TypeAliasTemplateDecl>(D))
668 HI.Type =
printType(TAT->getTemplatedDecl()->getUnderlyingType(), Ctx, PP);
671 if (
const auto *Var = dyn_cast<VarDecl>(D); Var && !Var->isInvalidDecl()) {
672 if (
const Expr *Init = Var->getInit())
673 HI.Value = printExprValue(Init, Ctx);
674 }
else if (
const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
676 if (!ECD->getType()->isDependentType())
677 HI.Value =
toString(ECD->getInitVal(), 10);
680 HI.Definition = printDefinition(D, PP, TB);
685std::optional<HoverInfo>
686getPredefinedExprHoverContents(
const PredefinedExpr &PE, ASTContext &Ctx,
687 const PrintingPolicy &PP) {
689 HI.
Name = PE.getIdentKindName();
690 HI.Kind = index::SymbolKind::Variable;
691 HI.Documentation =
"Name of the current function (predefined variable)";
692 if (
const StringLiteral *Name = PE.getFunctionName()) {
694 llvm::raw_string_ostream OS(*HI.Value);
695 Name->outputString(OS);
696 HI.Type =
printType(Name->getType(), Ctx, PP);
699 QualType StringType = Ctx.getIncompleteArrayType(Ctx.CharTy.withConst(),
700 ArraySizeModifier::Normal,
702 HI.Type =
printType(StringType, Ctx, PP);
707HoverInfo evaluateMacroExpansion(
unsigned int SpellingBeginOffset,
708 unsigned int SpellingEndOffset,
709 llvm::ArrayRef<syntax::Token> Expanded,
712 auto &Tokens =
AST.getTokens();
713 auto PP = getPrintingPolicy(
Context.getPrintingPolicy());
722 if (Expanded.size() == 1)
723 if (tok::getPunctuatorSpelling(Expanded[0].kind()))
726 auto *StartNode = Tree.commonAncestor();
737 if (!StartNode->Children.empty())
742 auto ExprResult = printExprValue(StartNode,
Context);
743 HI.Value = std::move(ExprResult.PrintedValue);
744 if (
auto *E = ExprResult.TheExpr)
748 if (!HI.Value && !HI.Type && ExprResult.TheNode)
749 if (
auto *VD = ExprResult.TheNode->ASTNode.get<VarDecl>())
759 SourceManager &SM =
AST.getSourceManager();
760 HI.Name = std::string(
Macro.Name);
761 HI.Kind = index::SymbolKind::Macro;
766 SourceLocation StartLoc =
Macro.Info->getDefinitionLoc();
767 SourceLocation EndLoc =
Macro.Info->getDefinitionEndLoc();
775 if (SM.getPresumedLoc(EndLoc,
false).isValid()) {
776 EndLoc = Lexer::getLocForEndOfToken(EndLoc, 0, SM,
AST.getLangOpts());
778 StringRef Buffer = SM.getBufferData(SM.getFileID(StartLoc), &Invalid);
780 unsigned StartOffset = SM.getFileOffset(StartLoc);
781 unsigned EndOffset = SM.getFileOffset(EndLoc);
782 if (EndOffset <= Buffer.size() && StartOffset < EndOffset)
784 (
"#define " + Buffer.substr(StartOffset, EndOffset - StartOffset))
789 if (
auto Expansion =
AST.getTokens().expansionStartingAt(&Tok)) {
793 std::string ExpansionText;
794 for (
const auto &ExpandedTok : Expansion->Expanded) {
795 ExpansionText += ExpandedTok.text(SM);
796 ExpansionText +=
" ";
798 const size_t Limit =
static_cast<size_t>(Cfg.Hover.MacroContentsLimit);
799 if (Limit && ExpansionText.size() > Limit) {
800 ExpansionText.clear();
805 if (!ExpansionText.empty()) {
806 if (!HI.Definition.empty()) {
807 HI.Definition +=
"\n\n";
809 HI.Definition +=
"// Expands to\n";
810 HI.Definition += ExpansionText;
813 auto Evaluated = evaluateMacroExpansion(
814 SM.getFileOffset(Tok.location()),
815 SM.getFileOffset(Tok.endLocation()),
816 Expansion->Expanded,
AST);
817 HI.Value = std::move(Evaluated.Value);
818 HI.Type = std::move(Evaluated.Type);
825 llvm::raw_string_ostream OS(Result);
828 OS <<
" // aka: " << *PType.AKA;
832std::optional<HoverInfo> getThisExprHoverContents(
const CXXThisExpr *CTE,
834 const PrintingPolicy &PP) {
835 QualType OriginThisType = CTE->getType()->getPointeeType();
836 QualType ClassType =
declaredType(OriginThisType->castAsTagDecl());
841 QualType PrettyThisType = ASTCtx.getPointerType(
842 QualType(ClassType.getTypePtr(), OriginThisType.getCVRQualifiers()));
846 HI.Definition = typeAsDefinition(
printType(PrettyThisType, ASTCtx, PP));
851HoverInfo getDeducedTypeHoverContents(QualType QT,
const syntax::Token &Tok,
853 const PrintingPolicy &PP,
857 HI.
Name = tok::getTokenName(Tok.kind());
858 HI.Kind = index::SymbolKind::TypeAlias;
860 if (QT->isUndeducedAutoType()) {
861 HI.Definition =
"/* not deduced */";
863 HI.Definition = typeAsDefinition(
printType(QT, ASTCtx, PP));
865 if (
const auto *D = QT->getAsTagDecl()) {
866 const auto *CommentD = getDeclForComment(D);
868 enhanceFromIndex(HI, *CommentD, Index);
875HoverInfo getStringLiteralContents(
const StringLiteral *SL,
876 const PrintingPolicy &PP) {
879 HI.
Name =
"string-literal";
880 HI.Size = (SL->getLength() + 1) * SL->getCharByteWidth() * 8;
881 HI.Type = SL->getType().getAsString(PP).c_str();
886bool isLiteral(
const Expr *E) {
889 return llvm::isa<CompoundLiteralExpr>(E) ||
890 llvm::isa<CXXBoolLiteralExpr>(E) ||
891 llvm::isa<CXXNullPtrLiteralExpr>(E) ||
892 llvm::isa<FixedPointLiteral>(E) || llvm::isa<FloatingLiteral>(E) ||
893 llvm::isa<ImaginaryLiteral>(E) || llvm::isa<IntegerLiteral>(E) ||
894 llvm::isa<StringLiteral>(E) || llvm::isa<UserDefinedLiteral>(E);
897llvm::StringLiteral getNameForExpr(
const Expr *E) {
905 return llvm::StringLiteral(
"expression");
909 const PrintingPolicy &PP);
915 const PrintingPolicy &PP,
917 std::optional<HoverInfo> HI;
919 if (
const StringLiteral *SL = dyn_cast<StringLiteral>(E)) {
921 HI = getStringLiteralContents(SL, PP);
922 }
else if (isLiteral(E)) {
926 maybeAddCalleeArgInfo(N, HI.emplace(), PP);
927 if (HI->CalleeArgInfo) {
931 HI->Name =
"literal";
938 if (
const CXXThisExpr *CTE = dyn_cast<CXXThisExpr>(E))
939 HI = getThisExprHoverContents(CTE,
AST.getASTContext(), PP);
940 if (
const PredefinedExpr *PE = dyn_cast<PredefinedExpr>(E))
941 HI = getPredefinedExprHoverContents(*PE,
AST.getASTContext(), PP);
944 if (
auto Val = printExprValue(E,
AST.getASTContext())) {
946 HI->Type =
printType(E->getType(),
AST.getASTContext(), PP);
948 HI->Name = std::string(getNameForExpr(E));
952 maybeAddCalleeArgInfo(N, *HI, PP);
958std::optional<HoverInfo> getHoverContents(
const Attr *A,
ParsedAST &
AST) {
960 HI.
Name =
A->getSpelling();
962 HI.LocalScope =
A->getScopeName()->getName().str();
964 llvm::raw_string_ostream OS(HI.Definition);
965 A->printPretty(OS,
AST.getASTContext().getPrintingPolicy());
967 HI.Documentation = Attr::getDocumentation(
A->getKind()).str();
971void addLayoutInfo(
const NamedDecl &ND,
HoverInfo &HI) {
972 if (ND.isInvalidDecl())
975 const auto &Ctx = ND.getASTContext();
976 if (
auto *RD = llvm::dyn_cast<RecordDecl>(&ND)) {
977 CanQualType RT = Ctx.getCanonicalTagType(RD);
978 if (
auto Size = Ctx.getTypeSizeInCharsIfKnown(RT))
979 HI.Size = Size->getQuantity() * 8;
980 if (!RD->isDependentType() && RD->isCompleteDefinition())
981 HI.Align = Ctx.getTypeAlign(RT);
985 if (
const auto *FD = llvm::dyn_cast<FieldDecl>(&ND)) {
986 const auto *
Record = FD->getParent();
989 if (Record && !
Record->isInvalidDecl() && !
Record->isDependentType()) {
990 HI.Align = Ctx.getTypeAlign(FD->getType());
991 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Record);
992 HI.Offset = Layout.getFieldOffset(FD->getFieldIndex());
993 if (FD->isBitField())
994 HI.Size = FD->getBitWidthValue();
995 else if (
auto Size = Ctx.getTypeSizeInCharsIfKnown(FD->getType()))
996 HI.Size = FD->isZeroSize(Ctx) ? 0 : Size->getQuantity() * 8;
998 unsigned EndOfField = *HI.Offset + *HI.Size;
1001 if (!
Record->isUnion() &&
1002 FD->getFieldIndex() + 1 < Layout.getFieldCount()) {
1004 unsigned NextOffset = Layout.getFieldOffset(FD->getFieldIndex() + 1);
1005 if (NextOffset >= EndOfField)
1006 HI.Padding = NextOffset - EndOfField;
1009 HI.Padding = Layout.getSize().getQuantity() * 8 - EndOfField;
1021 if (ParmType->isReferenceType()) {
1022 if (ParmType->getPointeeType().isConstQualified())
1032 const PrintingPolicy &PP) {
1033 const auto &OuterNode = N->outerImplicit();
1034 if (!OuterNode.Parent)
1037 const FunctionDecl *FD =
nullptr;
1038 llvm::ArrayRef<const Expr *> Args;
1040 if (
const auto *CE = OuterNode.Parent->ASTNode.get<CallExpr>()) {
1041 FD = CE->getDirectCallee();
1042 Args = {CE->getArgs(), CE->getNumArgs()};
1043 }
else if (
const auto *CE =
1044 OuterNode.Parent->ASTNode.get<CXXConstructExpr>()) {
1045 FD = CE->getConstructor();
1046 Args = {CE->getArgs(), CE->getNumArgs()};
1057 if (!FD || FD->isOverloadedOperator() || FD->isVariadic())
1065 for (
unsigned I = 0; I < Args.size() && I < Parameters.size(); ++I) {
1066 if (Args[I] != OuterNode.ASTNode.get<Expr>())
1070 if (
const ParmVarDecl *PVD = Parameters[I]) {
1071 HI.CalleeArgInfo.emplace(toHoverInfoParam(PVD, PP));
1072 if (N == &OuterNode)
1073 PassType.PassBy = getPassMode(PVD->getType());
1077 if (!HI.CalleeArgInfo)
1083 if (
const auto *E = N->ASTNode.get<Expr>()) {
1084 if (E->getType().isConstQualified())
1088 for (
auto *CastNode = N->Parent;
1089 CastNode != OuterNode.Parent && !PassType.Converted;
1090 CastNode = CastNode->Parent) {
1091 if (
const auto *ImplicitCast = CastNode->ASTNode.get<ImplicitCastExpr>()) {
1092 switch (ImplicitCast->getCastKind()) {
1094 case CK_DerivedToBase:
1095 case CK_UncheckedDerivedToBase:
1098 PassType.PassBy = ImplicitCast->getType().isConstQualified()
1102 case CK_LValueToRValue:
1103 case CK_ArrayToPointerDecay:
1104 case CK_FunctionToPointerDecay:
1105 case CK_NullToPointer:
1106 case CK_NullToMemberPointer:
1112 PassType.Converted =
true;
1115 }
else if (
const auto *CtorCall =
1116 CastNode->ASTNode.get<CXXConstructExpr>()) {
1119 if (CtorCall->getConstructor()->isCopyConstructor())
1122 PassType.Converted =
true;
1123 }
else if (CastNode->ASTNode.get<MaterializeTemporaryExpr>()) {
1128 PassType.Converted =
true;
1132 HI.CallPassType.emplace(PassType);
1135const NamedDecl *pickDeclToUse(llvm::ArrayRef<const NamedDecl *> Candidates) {
1136 if (Candidates.empty())
1145 if (Candidates.size() <= 2) {
1146 if (llvm::isa<UsingDecl>(Candidates.front()))
1147 return Candidates.back();
1148 return Candidates.front();
1157 auto BaseDecls = llvm::make_filter_range(
1158 Candidates, [](
const NamedDecl *D) {
return llvm::isa<UsingDecl>(D); });
1159 if (std::distance(BaseDecls.begin(), BaseDecls.end()) == 1)
1160 return *BaseDecls.begin();
1162 return Candidates.front();
1166 include_cleaner::Symbol Sym) {
1167 trace::Span Tracer(
"Hover::maybeAddSymbolProviders");
1169 llvm::SmallVector<include_cleaner::Header> RankedProviders =
1170 include_cleaner::headersForSymbol(Sym,
AST.getPreprocessor(),
1171 &
AST.getPragmaIncludes());
1172 if (RankedProviders.empty())
1175 const SourceManager &SM =
AST.getSourceManager();
1178 for (
const auto &P : RankedProviders) {
1179 if (
P.kind() == include_cleaner::Header::Physical &&
1180 P.physical() == SM.getFileEntryForID(SM.getMainFileID()))
1185 auto Matches = ConvertedIncludes.match(P);
1186 if (!Matches.empty()) {
1187 Result = Matches[0]->quote();
1192 if (!Result.empty()) {
1193 HI.Provider = std::move(Result);
1198 const auto &H = RankedProviders.front();
1199 if (H.kind() == include_cleaner::Header::Physical &&
1200 H.physical() == SM.getFileEntryForID(SM.getMainFileID()))
1205 HI.Provider = include_cleaner::spellHeader(
1206 {H,
AST.getPreprocessor().getHeaderSearchInfo(),
1207 SM.getFileEntryForID(SM.getMainFileID())});
1213std::string getSymbolName(include_cleaner::Symbol Sym) {
1215 switch (Sym.kind()) {
1216 case include_cleaner::Symbol::Declaration:
1217 if (
const auto *ND = llvm::dyn_cast<NamedDecl>(&Sym.declaration()))
1218 Name = ND->getDeclName().getAsString();
1220 case include_cleaner::Symbol::Macro:
1221 Name = Sym.macro().Name->getName();
1229 llvm::DenseSet<include_cleaner::Symbol> UsedSymbols;
1230 include_cleaner::walkUsed(
1232 &
AST.getPragmaIncludes(),
AST.getPreprocessor(),
1233 [&](
const include_cleaner::SymbolReference &
Ref,
1234 llvm::ArrayRef<include_cleaner::Header> Providers) {
1235 if (Ref.RT != include_cleaner::RefType::Explicit ||
1236 UsedSymbols.contains(Ref.Target))
1239 if (isPreferredProvider(Inc, Converted, Providers))
1240 UsedSymbols.insert(Ref.Target);
1243 for (
const auto &UsedSymbolDecl : UsedSymbols)
1244 HI.UsedSymbolNames.push_back(getSymbolName(UsedSymbolDecl));
1245 llvm::sort(HI.UsedSymbolNames);
1246 HI.UsedSymbolNames.erase(llvm::unique(HI.UsedSymbolNames),
1247 HI.UsedSymbolNames.end());
1253 const format::FormatStyle &Style,
1258 getPrintingPolicy(
AST.getASTContext().getPrintingPolicy());
1259 const SourceManager &SM =
AST.getSourceManager();
1262 llvm::consumeError(CurLoc.takeError());
1263 return std::nullopt;
1265 const auto &TB =
AST.getTokens();
1266 auto TokensTouchingCursor = syntax::spelledTokensTouching(*CurLoc, TB);
1268 if (TokensTouchingCursor.empty())
1269 return std::nullopt;
1272 for (
const auto &Inc :
AST.getIncludeStructure().MainFileIncludes) {
1273 if (Inc.Resolved.empty() || Inc.HashLine != Pos.
line)
1275 HoverCountMetric.
record(1,
"include");
1277 HI.
Name = std::string(llvm::sys::path::filename(Inc.Resolved));
1281 HI.
Kind = index::SymbolKind::IncludeDirective;
1282 maybeAddUsedSymbols(
AST, HI, Inc);
1289 CharSourceRange HighlightRange =
1290 TokensTouchingCursor.back().range(SM).toCharRange(SM);
1291 std::optional<HoverInfo> HI;
1295 for (
const auto &Tok : TokensTouchingCursor) {
1296 if (Tok.kind() == tok::identifier) {
1298 HighlightRange = Tok.range(SM).toCharRange(SM);
1300 HoverCountMetric.
record(1,
"macro");
1301 HI = getHoverContents(*M, Tok,
AST);
1302 if (
auto DefLoc = M->Info->getDefinitionLoc(); DefLoc.isValid()) {
1303 include_cleaner::Macro IncludeCleanerMacro{
1304 AST.getPreprocessor().getIdentifierInfo(Tok.text(SM)), DefLoc};
1305 maybeAddSymbolProviders(
AST, *HI,
1306 include_cleaner::Symbol{IncludeCleanerMacro});
1310 }
else if (Tok.kind() == tok::kw_auto || Tok.kind() == tok::kw_decltype) {
1311 HoverCountMetric.
record(1,
"keyword");
1315 HI = getDeducedTypeHoverContents(*
Deduced, Tok,
AST.getASTContext(), PP,
1317 HighlightRange = Tok.range(SM).toCharRange(SM);
1324 return std::nullopt;
1330 auto Offset = SM.getFileOffset(*CurLoc);
1338 AST.getHeuristicResolver());
1339 if (
const auto *DeclToUse = pickDeclToUse(Decls)) {
1340 HoverCountMetric.
record(1,
"decl");
1341 HI = getHoverContents(DeclToUse, PP, Index, TB);
1343 if (DeclToUse == N->ASTNode.get<Decl>())
1344 addLayoutInfo(*DeclToUse, *HI);
1347 HI->Value = printExprValue(N,
AST.getASTContext()).PrintedValue;
1348 maybeAddCalleeArgInfo(N, *HI, PP);
1350 if (!isa<NamespaceDecl>(DeclToUse))
1351 maybeAddSymbolProviders(
AST, *HI,
1352 include_cleaner::Symbol{*DeclToUse});
1353 }
else if (
const Expr *E = N->ASTNode.get<Expr>()) {
1354 HoverCountMetric.
record(1,
"expr");
1355 HI = getHoverContents(N, E,
AST, PP, Index);
1356 }
else if (
const Attr *A = N->ASTNode.get<Attr>()) {
1357 HoverCountMetric.
record(1,
"attribute");
1358 HI = getHoverContents(A,
AST);
1366 return std::nullopt;
1369 if (!HI->Definition.empty()) {
1370 auto Replacements = format::reformat(
1371 Style, HI->Definition, tooling::Range(0, HI->Definition.size()));
1372 if (
auto Formatted =
1373 tooling::applyAllReplacements(HI->Definition, Replacements))
1374 HI->Definition = *Formatted;
1377 HI->DefinitionLanguage = getMarkdownLanguage(
AST.getASTContext());
1385 uint64_t
Value = SizeInBits % 8 == 0 ? SizeInBits / 8 : SizeInBits;
1386 const char *
Unit =
Value != 0 &&
Value == SizeInBits ?
"bit" :
"byte";
1387 return llvm::formatv(
"{0} {1}{2}",
Value,
Unit,
Value == 1 ?
"" :
"s").str();
1393 const auto Bytes = OffsetInBits / 8;
1394 const auto Bits = OffsetInBits % 8;
1401void HoverInfo::calleeArgInfoToMarkupParagraph(markup::Paragraph &P)
const {
1404 llvm::raw_string_ostream OS(Buffer);
1417 OS <<
" (converted to " <<
CalleeArgInfo->Type->Type <<
")";
1418 P.appendText(OS.str());
1421void HoverInfo::usedSymbolNamesToMarkup(markup::Document &Output)
const {
1422 markup::Paragraph &
P = Output.addParagraph();
1423 P.appendText(
"provides ");
1425 const std::vector<std::string>::size_type SymbolNamesLimit = 5;
1426 auto Front = llvm::ArrayRef(
UsedSymbolNames).take_front(SymbolNamesLimit);
1429 Front, [&](llvm::StringRef Sym) {
P.appendCode(Sym); },
1430 [&] {
P.appendText(
", "); });
1432 P.appendText(
" and ");
1434 P.appendText(
" more");
1438void HoverInfo::providerToMarkupParagraph(markup::Document &Output)
const {
1439 markup::Paragraph &DI = Output.addParagraph();
1440 DI.appendText(
"provided by");
1445void HoverInfo::definitionScopeToMarkup(markup::Document &Output)
const {
1455 Buffer +=
"// In " + llvm::StringRef(
LocalScope).rtrim(
':').str() +
'\n';
1457 Buffer +=
"// In namespace " +
1458 llvm::StringRef(*NamespaceScope).rtrim(
':').str() +
'\n';
1471 P.appendText(
"Value = ");
1488markup::Document HoverInfo::presentDoxygen()
const {
1490 markup::Document Output;
1503 markup::Paragraph &Header = Output.addHeading(3);
1504 if (
Kind != index::SymbolKind::Unknown &&
1505 Kind != index::SymbolKind::IncludeDirective)
1506 Header.appendText(index::getSymbolKindString(
Kind)).appendSpace();
1507 assert(!
Name.empty() &&
"hover triggered on a nameless symbol");
1509 if (
Kind == index::SymbolKind::IncludeDirective) {
1510 Header.appendCode(
Name);
1513 Output.addParagraph().appendCode(
Definition);
1517 usedSymbolNamesToMarkup(Output);
1525 definitionScopeToMarkup(Output);
1527 Header.appendCode(
Name);
1531 providerToMarkupParagraph(Output);
1539 if (SymbolDoc.hasBriefCommand()) {
1540 SymbolDoc.briefToMarkup(Output.addParagraph());
1553 Output.addParagraph().appendBoldText(
"Template Parameters:");
1554 markup::BulletList &L = Output.addBulletList();
1556 markup::Paragraph &
P = L.addItem().addParagraph();
1557 P.appendCode(llvm::to_string(
Param));
1558 if (SymbolDoc.isTemplateTypeParmDocumented(llvm::to_string(
Param.
Name))) {
1559 P.appendText(
" - ");
1560 SymbolDoc.templateTypeParmDocToMarkup(llvm::to_string(
Param.
Name), P);
1567 Output.addParagraph().appendBoldText(
"Parameters:");
1568 markup::BulletList &L = Output.addBulletList();
1570 markup::Paragraph &
P = L.addItem().addParagraph();
1571 P.appendCode(llvm::to_string(
Param));
1573 if (SymbolDoc.isParameterDocumented(llvm::to_string(
Param.
Name))) {
1574 P.appendText(
" - ");
1575 SymbolDoc.parameterDocToMarkup(llvm::to_string(
Param.
Name), P);
1586 Output.addParagraph().appendBoldText(
"Returns:");
1587 markup::Paragraph &
P = Output.addParagraph();
1590 if (SymbolDoc.hasReturnCommand()) {
1591 P.appendText(
" - ");
1592 SymbolDoc.returnToMarkup(P);
1598 SymbolDoc.warningsToMarkup(Output);
1599 SymbolDoc.notesToMarkup(Output);
1602 SymbolDoc.docToMarkup(Output);
1609 Output.addParagraph().appendText(
"Type: ").appendCode(
1610 llvm::to_string(*
Type));
1613 valueToMarkupParagraph(Output.addParagraph());
1617 offsetToMarkupParagraph(Output.addParagraph());
1619 sizeToMarkupParagraph(Output.addParagraph());
1623 calleeArgInfoToMarkupParagraph(Output.addParagraph());
1628 usedSymbolNamesToMarkup(Output);
1634markup::Document HoverInfo::presentDefault()
const {
1635 markup::Document Output;
1648 markup::Paragraph &Header = Output.addHeading(3);
1649 if (
Kind != index::SymbolKind::Unknown &&
1650 Kind != index::SymbolKind::IncludeDirective)
1651 Header.appendText(index::getSymbolKindString(
Kind)).appendSpace();
1652 assert(!
Name.empty() &&
"hover triggered on a nameless symbol");
1653 Header.appendCode(
Name);
1656 providerToMarkupParagraph(Output);
1669 Output.addParagraph().appendText(
"→ ").appendCode(
1674 Output.addParagraph().appendText(
"Parameters:");
1675 markup::BulletList &L = Output.addBulletList();
1677 L.addItem().addParagraph().appendCode(llvm::to_string(
Param));
1683 Output.addParagraph().appendText(
"Type: ").appendCode(
1684 llvm::to_string(*
Type));
1687 valueToMarkupParagraph(Output.addParagraph());
1691 offsetToMarkupParagraph(Output.addParagraph());
1693 sizeToMarkupParagraph(Output.addParagraph());
1697 calleeArgInfoToMarkupParagraph(Output.addParagraph());
1705 definitionScopeToMarkup(Output);
1710 usedSymbolNamesToMarkup(Output);
1721 return presentDefault().asMarkdown();
1723 return presentDoxygen().asMarkdown();
1728 return presentDefault().asEscapedMarkdown();
1731 return presentDefault().asPlainText();
1738 assert(Line[Offset] ==
'`');
1741 llvm::StringRef Prefix = Line.substr(0, Offset);
1742 constexpr llvm::StringLiteral BeforeStartChars =
" \t(=";
1743 if (!Prefix.empty() && !BeforeStartChars.contains(Prefix.back()))
1744 return std::nullopt;
1747 auto Next = Line.find_first_of(
"`\n", Offset + 1);
1748 if (Next == llvm::StringRef::npos)
1749 return std::nullopt;
1752 if (Line[Next] ==
'\n')
1753 return std::nullopt;
1755 llvm::StringRef Contents = Line.slice(Offset + 1, Next);
1756 if (Contents.empty() || isWhitespace(Contents.front()) ||
1757 isWhitespace(Contents.back()))
1758 return std::nullopt;
1761 llvm::StringRef Suffix = Line.substr(Next + 1);
1762 constexpr llvm::StringLiteral AfterEndChars =
" \t)=.,;:";
1763 if (!Suffix.empty() && !AfterEndChars.contains(Suffix.front()))
1764 return std::nullopt;
1766 return Line.slice(Offset, Next + 1);
1771 for (
unsigned I = 0; I <
Text.size(); ++I) {
1776 Out.appendCode(
Range->trim(
"`"),
true);
1793 for (std::tie(
Paragraph, Rest) = Input.split(
"\n\n");
1795 std::tie(
Paragraph, Rest) = Rest.split(
"\n\n")) {
1807 OS <<
" (aka " << *T.AKA <<
")";
1816 OS <<
" " << *P.Name;
1818 OS <<
" = " << *P.Default;
1819 if (P.Type && P.Type->AKA)
1820 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
@ Invalid
Sentinel bit pattern. DO NOT USE!
cppcoreguidelines::ProBoundsAvoidUncheckedContainerAccess 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::@340212122325041323223256240301061135214102252040 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.