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) {
170 llvm::raw_string_ostream OS(Result.Type);
175 PrintingPolicy Copy(PP);
179 Copy.ResolveDecltype =
true;
180 if (!QT.isNull() && !QT.hasQualifiers() && PP.SuppressTagKeyword) {
181 if (
auto *TT = llvm::dyn_cast<TagType>(QT.getTypePtr());
182 TT && TT->isCanonicalUnqualified()) {
183 Copy.SuppressTagKeywordInAnonNames =
true;
184 OS << TT->getDecl()->getKindName() <<
" ";
190 if (!QT.isNull() && Cfg.Hover.ShowAKA) {
191 bool ShouldAKA =
false;
192 QualType DesugaredTy = clang::desugarForDiagnostic(ASTCtx, QT, ShouldAKA);
194 Result.AKA = DesugaredTy.getAsString(Copy);
198 if (Result.AKA == Result.Type)
207 Result.
Type = TTP->wasDeclaredWithTypename() ?
"typename" :
"class";
208 if (TTP->isParameterPack())
209 Result.Type +=
"...";
214 const PrintingPolicy &PP) {
215 auto PrintedType =
printType(NTTP->getType(), NTTP->getASTContext(), PP);
216 if (NTTP->isParameterPack()) {
217 PrintedType.Type +=
"...";
219 *PrintedType.AKA +=
"...";
225 const PrintingPolicy &PP) {
227 llvm::raw_string_ostream OS(Result.Type);
229 llvm::StringRef Sep =
"";
230 for (
const Decl *Param : *TTP->getTemplateParameters()) {
233 if (
const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
235 else if (
const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
237 else if (
const auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param))
246std::vector<HoverInfo::Param>
247fetchTemplateParameters(
const TemplateParameterList *Params,
248 const PrintingPolicy &PP) {
250 std::vector<HoverInfo::Param> TempParameters;
252 for (
const Decl *Param : *Params) {
254 if (
const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
257 if (!TTP->getName().empty())
258 P.Name = TTP->getNameAsString();
260 if (TTP->hasDefaultArgument()) {
262 llvm::raw_string_ostream Out(*
P.Default);
263 TTP->getDefaultArgument().getArgument().print(PP, Out,
266 }
else if (
const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
269 if (IdentifierInfo *II = NTTP->getIdentifier())
270 P.Name = II->getName().str();
272 if (NTTP->hasDefaultArgument()) {
274 llvm::raw_string_ostream Out(*
P.Default);
275 NTTP->getDefaultArgument().getArgument().print(PP, Out,
278 }
else if (
const auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param)) {
281 if (!TTPD->getName().empty())
282 P.Name = TTPD->getNameAsString();
284 if (TTPD->hasDefaultArgument()) {
286 llvm::raw_string_ostream Out(*
P.Default);
287 TTPD->getDefaultArgument().getArgument().print(PP, Out,
291 TempParameters.push_back(std::move(P));
294 return TempParameters;
297const FunctionDecl *getUnderlyingFunction(
const Decl *D) {
299 if (
const VarDecl *VD = llvm::dyn_cast<VarDecl>(D)) {
300 auto QT = VD->getType();
302 while (!QT->getPointeeType().isNull())
303 QT = QT->getPointeeType();
305 if (
const auto *CD = QT->getAsCXXRecordDecl())
306 return CD->getLambdaCallOperator();
311 return D->getAsFunction();
316const NamedDecl *getDeclForComment(
const NamedDecl *D) {
317 const NamedDecl *DeclForComment =
D;
318 if (
const auto *TSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(D)) {
321 if (TSD->getTemplateSpecializationKind() == TSK_Undeclared)
322 DeclForComment = TSD->getSpecializedTemplate();
323 else if (
const auto *TIP = TSD->getTemplateInstantiationPattern())
324 DeclForComment = TIP;
325 }
else if (
const auto *TSD =
326 llvm::dyn_cast<VarTemplateSpecializationDecl>(D)) {
327 if (TSD->getTemplateSpecializationKind() == TSK_Undeclared)
328 DeclForComment = TSD->getSpecializedTemplate();
329 else if (
const auto *TIP = TSD->getTemplateInstantiationPattern())
330 DeclForComment = TIP;
331 }
else if (
const auto *FD =
D->getAsFunction())
332 if (
const auto *TIP = FD->getTemplateInstantiationPattern())
333 DeclForComment = TIP;
338 if (D != DeclForComment)
339 DeclForComment = getDeclForComment(DeclForComment);
340 return DeclForComment;
346 assert(&ND == getDeclForComment(&ND));
348 if (!
Hover.Documentation.empty() || !Index)
362 Index->lookup(Req, [&](
const Symbol &S) {
363 Hover.Documentation = std::string(S.Documentation);
370const Expr *getDefaultArg(
const ParmVarDecl *PVD) {
375 if (!PVD->hasDefaultArg() || PVD->hasUnparsedDefaultArg())
377 return PVD->hasUninstantiatedDefaultArg() ? PVD->getUninstantiatedDefaultArg()
378 : PVD->getDefaultArg();
382 const PrintingPolicy &PP) {
384 Out.
Type =
printType(PVD->getType(), PVD->getASTContext(), PP);
385 if (!PVD->getName().empty())
386 Out.Name = PVD->getNameAsString();
387 if (
const Expr *DefArg = getDefaultArg(PVD)) {
388 Out.Default.emplace();
389 llvm::raw_string_ostream OS(*Out.Default);
390 DefArg->printPretty(OS,
nullptr, PP);
396void fillFunctionTypeAndParams(
HoverInfo &HI,
const Decl *D,
397 const FunctionDecl *FD,
398 const PrintingPolicy &PP) {
399 HI.Parameters.emplace();
400 for (
const ParmVarDecl *PVD : FD->parameters())
401 HI.Parameters->emplace_back(toHoverInfoParam(PVD, PP));
405 const auto NK = FD->getDeclName().getNameKind();
406 if (NK == DeclarationName::CXXConstructorName ||
407 NK == DeclarationName::CXXDestructorName ||
408 NK == DeclarationName::CXXConversionFunctionName)
411 HI.ReturnType =
printType(FD->getReturnType(), FD->getASTContext(), PP);
412 QualType QT = FD->getType();
413 if (
const VarDecl *VD = llvm::dyn_cast<VarDecl>(D))
414 QT = VD->getType().getDesugaredType(
D->getASTContext());
415 HI.Type =
printType(QT,
D->getASTContext(), PP);
425static llvm::FormattedNumber printHex(
const llvm::APSInt &V) {
426 assert(V.getSignificantBits() <= 64 &&
"Can't print more than 64 bits.");
428 V.getBitWidth() > 64 ? V.trunc(64).getZExtValue() : V.getZExtValue();
429 if (V.isNegative() && V.getSignificantBits() <= 32)
430 return llvm::format_hex(uint32_t(Bits), 0);
431 return llvm::format_hex(Bits, 0);
434std::optional<std::string> printExprValue(
const Expr *E,
435 const ASTContext &Ctx) {
440 if (
const auto *ILE = llvm::dyn_cast<InitListExpr>(E)) {
441 if (!ILE->isSemanticForm())
442 E = ILE->getSemanticForm();
448 QualType
T = E->getType();
449 if (
T.isNull() ||
T->isFunctionType() ||
T->isFunctionPointerType() ||
450 T->isFunctionReferenceType() ||
T->isVoidType())
455 if (E->isValueDependent() || !E->EvaluateAsRValue(
Constant, Ctx) ||
462 if (
T->isEnumeralType() &&
Constant.Val.isInt() &&
463 Constant.Val.getInt().getSignificantBits() <= 64) {
465 int64_t Val =
Constant.Val.getInt().getExtValue();
466 for (
const EnumConstantDecl *ECD :
T->castAsEnumDecl()->enumerators())
467 if (ECD->getInitVal() == Val)
468 return llvm::formatv(
"{0} ({1})", ECD->getNameAsString(),
473 if (
T->isIntegralOrEnumerationType() &&
Constant.Val.isInt() &&
474 Constant.Val.getInt().getSignificantBits() <= 64 &&
476 return llvm::formatv(
"{0} ({1})",
Constant.Val.getAsString(Ctx, T),
479 return Constant.Val.getAsString(Ctx, T);
482struct PrintExprResult {
484 std::optional<std::string> PrintedValue;
487 const clang::Expr *TheExpr;
489 const SelectionTree::Node *TheNode;
498 const ASTContext &Ctx) {
499 for (; N; N = N->Parent) {
501 if (
const Expr *E = N->ASTNode.get<Expr>()) {
504 if (!E->getType().isNull() && E->getType()->isVoidType())
506 if (
auto Val = printExprValue(E, Ctx))
507 return PrintExprResult{std::move(Val), E,
509 }
else if (N->ASTNode.get<Decl>() || N->ASTNode.get<Stmt>()) {
515 return PrintExprResult{std::nullopt,
nullptr,
520const FieldDecl *fieldDecl(
const Expr *E) {
521 const auto *ME = llvm::dyn_cast<MemberExpr>(E->IgnoreCasts());
522 if (!ME || !llvm::isa<CXXThisExpr>(ME->getBase()->IgnoreCasts()))
524 return llvm::dyn_cast<FieldDecl>(ME->getMemberDecl());
527std::optional<StringRef> fieldName(
const Expr *E) {
528 const auto *
Field = fieldDecl(E);
529 if (!
Field || !
Field->getDeclName().isIdentifier())
531 return Field->getDeclName().getAsIdentifierInfo()->getName();
534std::optional<std::string> fieldComment(
const ASTContext &Ctx,
const Expr *E) {
535 const auto *
Field = fieldDecl(E);
546const Expr *getterReturnExpr(
const CXXMethodDecl *CMD) {
547 assert(CMD->hasBody());
548 if (CMD->getNumParams() != 0 || CMD->isVariadic())
550 const auto *Body = llvm::dyn_cast<CompoundStmt>(CMD->getBody());
551 const auto *OnlyReturn = (Body && Body->size() == 1)
552 ? llvm::dyn_cast<ReturnStmt>(Body->body_front())
554 if (!OnlyReturn || !OnlyReturn->getRetValue())
556 return OnlyReturn->getRetValue();
569const Expr *setterLHS(
const CXXMethodDecl *CMD) {
570 assert(CMD->hasBody());
571 if (CMD->isConst() || CMD->getNumParams() != 1 || CMD->isVariadic())
573 const ParmVarDecl *Arg = CMD->getParamDecl(0);
574 if (Arg->isParameterPack())
577 const auto *Body = llvm::dyn_cast<CompoundStmt>(CMD->getBody());
578 if (!Body || Body->size() == 0 || Body->size() > 2)
581 if (Body->size() == 2) {
582 auto *Ret = llvm::dyn_cast<ReturnStmt>(Body->body_back());
583 if (!Ret || !Ret->getRetValue())
585 const Expr *RetVal = Ret->getRetValue()->IgnoreCasts();
586 if (
const auto *UO = llvm::dyn_cast<UnaryOperator>(RetVal)) {
587 if (UO->getOpcode() != UO_Deref)
589 RetVal = UO->getSubExpr()->IgnoreCasts();
591 if (!llvm::isa<CXXThisExpr>(RetVal))
595 const Expr *LHS, *RHS;
596 if (
const auto *BO = llvm::dyn_cast<BinaryOperator>(Body->body_front())) {
597 if (BO->getOpcode() != BO_Assign)
601 }
else if (
const auto *COCE =
602 llvm::dyn_cast<CXXOperatorCallExpr>(Body->body_front())) {
603 if (COCE->getOperator() != OO_Equal || COCE->getNumArgs() != 2)
605 LHS = COCE->getArg(0);
606 RHS = COCE->getArg(1);
612 if (
auto *CE = llvm::dyn_cast<CallExpr>(RHS->IgnoreCasts())) {
613 if (CE->getNumArgs() != 1)
615 auto *ND = llvm::dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl());
616 if (!ND || !ND->getIdentifier() || ND->getName() !=
"move" ||
617 !ND->isInStdNamespace())
622 auto *DRE = llvm::dyn_cast<DeclRefExpr>(RHS->IgnoreCasts());
623 if (!DRE || DRE->getDecl() != Arg)
628std::string synthesizeDocumentation(
const ASTContext &Ctx,
629 const NamedDecl *ND) {
630 const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(ND);
635 if (!CMD->getDeclName().isIdentifier() || CMD->isStatic())
638 CMD = llvm::dyn_cast_or_null<CXXMethodDecl>(CMD->getDefinition());
639 if (!CMD || !CMD->hasBody())
642 if (
const Expr *RetVal = getterReturnExpr(CMD)) {
643 if (
const auto GetterField = fieldName(RetVal)) {
644 if (
const auto Comment = fieldComment(Ctx, RetVal))
645 return llvm::formatv(
"Trivial accessor for `{0}`.\n\n{1}", *GetterField,
647 return llvm::formatv(
"Trivial accessor for `{0}`.", *GetterField);
650 if (
const auto *
const SetterLHS = setterLHS(CMD)) {
651 if (
const auto FieldName = fieldName(SetterLHS)) {
652 if (
const auto Comment = fieldComment(Ctx, SetterLHS))
653 return llvm::formatv(
"Trivial setter for `{0}`.\n\n{1}", *FieldName,
655 return llvm::formatv(
"Trivial setter for `{0}`.", *FieldName);
663HoverInfo getHoverContents(
const NamedDecl *D,
const PrintingPolicy &PP,
665 const syntax::TokenBuffer &TB) {
667 auto &Ctx =
D->getASTContext();
669 if (Ctx.getLangOpts().CPlusPlus)
670 HI.AccessSpecifier = getAccessSpelling(
D->getAccess()).str();
671 HI.NamespaceScope = getNamespaceScope(D);
672 if (!HI.NamespaceScope->empty())
673 HI.NamespaceScope->append(
"::");
674 HI.LocalScope = getLocalScope(D);
675 if (!HI.LocalScope.empty())
676 HI.LocalScope.append(
"::");
679 const auto *CommentD = getDeclForComment(D);
683 HI.CommentOpts =
D->getASTContext().getLangOpts().CommentOpts;
684 enhanceFromIndex(HI, *CommentD, Index);
685 if (HI.Documentation.empty())
686 HI.Documentation = synthesizeDocumentation(Ctx, D);
688 HI.Kind = index::getSymbolInfo(D).Kind;
691 if (
const TemplateDecl *TD =
D->getDescribedTemplate()) {
692 HI.TemplateParameters =
693 fetchTemplateParameters(TD->getTemplateParameters(), PP);
695 }
else if (
const FunctionDecl *FD =
D->getAsFunction()) {
696 if (
const auto *FTD = FD->getDescribedTemplate()) {
697 HI.TemplateParameters =
698 fetchTemplateParameters(FTD->getTemplateParameters(), PP);
704 if (
const FunctionDecl *FD = getUnderlyingFunction(D))
705 fillFunctionTypeAndParams(HI, D, FD, PP);
706 else if (
const auto *VD = dyn_cast<ValueDecl>(D))
707 HI.Type =
printType(VD->getType(), Ctx, PP);
708 else if (
const auto *TTP = dyn_cast<TemplateTypeParmDecl>(D))
709 HI.Type = TTP->wasDeclaredWithTypename() ?
"typename" :
"class";
710 else if (
const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(D))
712 else if (
const auto *VT = dyn_cast<VarTemplateDecl>(D))
713 HI.Type =
printType(VT->getTemplatedDecl()->getType(), Ctx, PP);
714 else if (
const auto *TN = dyn_cast<TypedefNameDecl>(D))
715 HI.Type =
printType(TN->getUnderlyingType().getDesugaredType(Ctx), Ctx, PP);
716 else if (
const auto *TAT = dyn_cast<TypeAliasTemplateDecl>(D))
717 HI.Type =
printType(TAT->getTemplatedDecl()->getUnderlyingType(), Ctx, PP);
720 if (
const auto *Var = dyn_cast<VarDecl>(D); Var && !Var->isInvalidDecl()) {
721 if (
const Expr *Init = Var->getInit())
722 HI.Value = printExprValue(Init, Ctx);
723 }
else if (
const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
725 if (!ECD->getType()->isDependentType())
726 HI.Value =
toString(ECD->getInitVal(), 10);
729 HI.Definition = printDefinition(D, PP, TB);
734std::optional<HoverInfo>
735getPredefinedExprHoverContents(
const PredefinedExpr &PE, ASTContext &Ctx,
736 const PrintingPolicy &PP) {
738 HI.
Name = PE.getIdentKindName();
739 HI.Kind = index::SymbolKind::Variable;
740 HI.Documentation =
"Name of the current function (predefined variable)";
741 if (
const StringLiteral *Name = PE.getFunctionName()) {
743 llvm::raw_string_ostream OS(*HI.Value);
744 Name->outputString(OS);
745 HI.Type =
printType(Name->getType(), Ctx, PP);
748 QualType StringType = Ctx.getIncompleteArrayType(Ctx.CharTy.withConst(),
749 ArraySizeModifier::Normal,
751 HI.Type =
printType(StringType, Ctx, PP);
756HoverInfo evaluateMacroExpansion(
unsigned int SpellingBeginOffset,
757 unsigned int SpellingEndOffset,
758 llvm::ArrayRef<syntax::Token> Expanded,
761 auto &Tokens =
AST.getTokens();
762 auto PP = getPrintingPolicy(
Context.getPrintingPolicy());
771 if (Expanded.size() == 1)
772 if (tok::getPunctuatorSpelling(Expanded[0].kind()))
775 auto *StartNode = Tree.commonAncestor();
786 if (!StartNode->Children.empty())
791 auto ExprResult = printExprValue(StartNode,
Context);
792 HI.Value = std::move(ExprResult.PrintedValue);
793 if (
auto *E = ExprResult.TheExpr)
797 if (!HI.Value && !HI.Type && ExprResult.TheNode)
798 if (
auto *VD = ExprResult.TheNode->ASTNode.get<VarDecl>())
808 SourceManager &SM =
AST.getSourceManager();
809 HI.Name = std::string(
Macro.Name);
810 HI.Kind = index::SymbolKind::Macro;
815 SourceLocation StartLoc =
Macro.Info->getDefinitionLoc();
816 SourceLocation EndLoc =
Macro.Info->getDefinitionEndLoc();
824 if (SM.getPresumedLoc(EndLoc,
false).isValid()) {
825 EndLoc = Lexer::getLocForEndOfToken(EndLoc, 0, SM,
AST.getLangOpts());
827 StringRef Buffer = SM.getBufferData(SM.getFileID(StartLoc), &Invalid);
829 unsigned StartOffset = SM.getFileOffset(StartLoc);
830 unsigned EndOffset = SM.getFileOffset(EndLoc);
831 if (EndOffset <= Buffer.size() && StartOffset < EndOffset)
833 (
"#define " + Buffer.substr(StartOffset, EndOffset - StartOffset))
838 if (
auto Expansion =
AST.getTokens().expansionStartingAt(&Tok)) {
842 std::string ExpansionText;
843 for (
const auto &ExpandedTok : Expansion->Expanded) {
844 ExpansionText += ExpandedTok.text(SM);
845 ExpansionText +=
" ";
847 const size_t Limit =
static_cast<size_t>(Cfg.Hover.MacroContentsLimit);
848 if (Limit && ExpansionText.size() > Limit) {
849 ExpansionText.clear();
854 if (!ExpansionText.empty()) {
855 if (!HI.Definition.empty()) {
856 HI.Definition +=
"\n\n";
858 HI.Definition +=
"// Expands to\n";
859 HI.Definition += ExpansionText;
862 auto Evaluated = evaluateMacroExpansion(
863 SM.getFileOffset(Tok.location()),
864 SM.getFileOffset(Tok.endLocation()),
865 Expansion->Expanded,
AST);
866 HI.Value = std::move(Evaluated.Value);
867 HI.Type = std::move(Evaluated.Type);
874 llvm::raw_string_ostream OS(Result);
877 OS <<
" // aka: " << *PType.AKA;
881std::optional<HoverInfo> getThisExprHoverContents(
const CXXThisExpr *CTE,
883 const PrintingPolicy &PP) {
884 QualType OriginThisType = CTE->getType()->getPointeeType();
885 QualType ClassType =
declaredType(OriginThisType->castAsTagDecl());
890 QualType PrettyThisType = ASTCtx.getPointerType(
891 QualType(ClassType.getTypePtr(), OriginThisType.getCVRQualifiers()));
895 HI.Definition = typeAsDefinition(
printType(PrettyThisType, ASTCtx, PP));
900HoverInfo getDeducedTypeHoverContents(QualType QT,
const syntax::Token &Tok,
902 const PrintingPolicy &PP,
906 HI.
Name = tok::getTokenName(Tok.kind());
907 HI.Kind = index::SymbolKind::TypeAlias;
909 if (QT->isUndeducedAutoType()) {
910 HI.Definition =
"/* not deduced */";
912 HI.Definition = typeAsDefinition(
printType(QT, ASTCtx, PP));
914 if (
const auto *D = QT->getAsTagDecl()) {
915 const auto *CommentD = getDeclForComment(D);
917 enhanceFromIndex(HI, *CommentD, Index);
924HoverInfo getStringLiteralContents(
const StringLiteral *SL,
925 const PrintingPolicy &PP) {
928 HI.
Name =
"string-literal";
929 HI.Size = (SL->getLength() + 1) * SL->getCharByteWidth() * 8;
930 HI.Type = SL->getType().getAsString(PP).c_str();
935bool isLiteral(
const Expr *E) {
938 return llvm::isa<CompoundLiteralExpr>(E) ||
939 llvm::isa<CXXBoolLiteralExpr>(E) ||
940 llvm::isa<CXXNullPtrLiteralExpr>(E) ||
941 llvm::isa<FixedPointLiteral>(E) || llvm::isa<FloatingLiteral>(E) ||
942 llvm::isa<ImaginaryLiteral>(E) || llvm::isa<IntegerLiteral>(E) ||
943 llvm::isa<StringLiteral>(E) || llvm::isa<UserDefinedLiteral>(E);
946llvm::StringLiteral getNameForExpr(
const Expr *E) {
954 return llvm::StringLiteral(
"expression");
958 const PrintingPolicy &PP);
964 const PrintingPolicy &PP,
966 std::optional<HoverInfo> HI;
968 if (
const auto *VecExpr = dyn_cast<ExtVectorElementExpr>(E)) {
970 HI->Name = VecExpr->getAccessor().getName().str();
971 HI->Type =
printType(VecExpr->getType(),
AST.getASTContext(), PP);
974 if (
const auto *MatExpr = dyn_cast<MatrixElementExpr>(E)) {
976 HI->Name = MatExpr->getAccessor().getName().str();
977 HI->Type =
printType(MatExpr->getType(),
AST.getASTContext(), PP);
981 if (
const StringLiteral *SL = dyn_cast<StringLiteral>(E)) {
983 HI = getStringLiteralContents(SL, PP);
984 }
else if (isLiteral(E)) {
988 maybeAddCalleeArgInfo(N, HI.emplace(), PP);
989 if (HI->CalleeArgInfo) {
993 HI->Name =
"literal";
1000 if (
const CXXThisExpr *CTE = dyn_cast<CXXThisExpr>(E))
1001 HI = getThisExprHoverContents(CTE,
AST.getASTContext(), PP);
1002 if (
const PredefinedExpr *PE = dyn_cast<PredefinedExpr>(E))
1003 HI = getPredefinedExprHoverContents(*PE,
AST.getASTContext(), PP);
1006 if (
auto Val = printExprValue(E,
AST.getASTContext())) {
1008 HI->Type =
printType(E->getType(),
AST.getASTContext(), PP);
1010 HI->Name = std::string(getNameForExpr(E));
1014 maybeAddCalleeArgInfo(N, *HI, PP);
1020std::optional<HoverInfo> getHoverContents(
const Attr *A,
ParsedAST &
AST) {
1022 HI.
Name =
A->getSpelling();
1024 HI.LocalScope =
A->getScopeName()->getName().str();
1026 llvm::raw_string_ostream OS(HI.Definition);
1027 A->printPretty(OS,
AST.getASTContext().getPrintingPolicy());
1029 HI.Documentation = Attr::getDocumentation(
A->getKind()).str();
1033void addLayoutInfo(
const NamedDecl &ND,
HoverInfo &HI) {
1034 if (ND.isInvalidDecl())
1037 const auto &Ctx = ND.getASTContext();
1038 if (
auto *RD = llvm::dyn_cast<RecordDecl>(&ND)) {
1039 CanQualType RT = Ctx.getCanonicalTagType(RD);
1040 if (
auto Size = Ctx.getTypeSizeInCharsIfKnown(RT))
1041 HI.Size = Size->getQuantity() * 8;
1042 if (!RD->isDependentType() && RD->isCompleteDefinition())
1043 HI.Align = Ctx.getTypeAlign(RT);
1047 if (
const auto *FD = llvm::dyn_cast<FieldDecl>(&ND)) {
1048 const auto *
Record = FD->getParent();
1051 if (Record && !
Record->isInvalidDecl() && !
Record->isDependentType()) {
1052 HI.Align = Ctx.getTypeAlign(FD->getType());
1053 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Record);
1054 HI.Offset = Layout.getFieldOffset(FD->getFieldIndex());
1055 if (FD->isBitField())
1056 HI.Size = FD->getBitWidthValue();
1057 else if (
auto Size = Ctx.getTypeSizeInCharsIfKnown(FD->getType()))
1058 HI.Size = FD->isZeroSize(Ctx) ? 0 : Size->getQuantity() * 8;
1060 unsigned EndOfField = *HI.Offset + *HI.Size;
1063 if (!
Record->isUnion() &&
1064 FD->getFieldIndex() + 1 < Layout.getFieldCount()) {
1066 unsigned NextOffset = Layout.getFieldOffset(FD->getFieldIndex() + 1);
1067 if (NextOffset >= EndOfField)
1068 HI.Padding = NextOffset - EndOfField;
1071 HI.Padding = Layout.getSize().getQuantity() * 8 - EndOfField;
1083 if (ParmType->isReferenceType()) {
1084 if (ParmType->getPointeeType().isConstQualified())
1094 const PrintingPolicy &PP) {
1095 const auto &OuterNode = N->outerImplicit();
1096 if (!OuterNode.Parent)
1099 const FunctionDecl *FD =
nullptr;
1100 llvm::ArrayRef<const Expr *> Args;
1102 if (
const auto *CE = OuterNode.Parent->ASTNode.get<CallExpr>()) {
1103 FD = CE->getDirectCallee();
1104 Args = {CE->getArgs(), CE->getNumArgs()};
1105 }
else if (
const auto *CE =
1106 OuterNode.Parent->ASTNode.get<CXXConstructExpr>()) {
1107 FD = CE->getConstructor();
1108 Args = {CE->getArgs(), CE->getNumArgs()};
1119 if (!FD || FD->isOverloadedOperator() || FD->isVariadic())
1127 for (
unsigned I = 0; I < Args.size() && I < Parameters.size(); ++I) {
1128 if (Args[I] != OuterNode.ASTNode.get<Expr>())
1132 if (
const ParmVarDecl *PVD = Parameters[I]) {
1133 HI.CalleeArgInfo.emplace(toHoverInfoParam(PVD, PP));
1134 if (N == &OuterNode)
1135 PassType.PassBy = getPassMode(PVD->getType());
1139 if (!HI.CalleeArgInfo)
1145 if (
const auto *E = N->ASTNode.get<Expr>()) {
1146 if (E->getType().isConstQualified())
1150 for (
auto *CastNode = N->Parent;
1151 CastNode != OuterNode.Parent && !PassType.Converted;
1152 CastNode = CastNode->Parent) {
1153 if (
const auto *ImplicitCast = CastNode->ASTNode.get<ImplicitCastExpr>()) {
1154 switch (ImplicitCast->getCastKind()) {
1156 case CK_DerivedToBase:
1157 case CK_UncheckedDerivedToBase:
1160 PassType.PassBy = ImplicitCast->getType().isConstQualified()
1164 case CK_LValueToRValue:
1165 case CK_ArrayToPointerDecay:
1166 case CK_FunctionToPointerDecay:
1167 case CK_NullToPointer:
1168 case CK_NullToMemberPointer:
1174 PassType.Converted =
true;
1177 }
else if (
const auto *CtorCall =
1178 CastNode->ASTNode.get<CXXConstructExpr>()) {
1181 if (CtorCall->getConstructor()->isCopyConstructor())
1184 PassType.Converted =
true;
1185 }
else if (CastNode->ASTNode.get<MaterializeTemporaryExpr>()) {
1190 PassType.Converted =
true;
1194 HI.CallPassType.emplace(PassType);
1197const NamedDecl *pickDeclToUse(llvm::ArrayRef<const NamedDecl *> Candidates) {
1198 if (Candidates.empty())
1207 if (Candidates.size() <= 2) {
1208 if (llvm::isa<UsingDecl>(Candidates.front()))
1209 return Candidates.back();
1210 return Candidates.front();
1219 auto BaseDecls = llvm::make_filter_range(
1220 Candidates, [](
const NamedDecl *D) {
return llvm::isa<UsingDecl>(D); });
1221 if (std::distance(BaseDecls.begin(), BaseDecls.end()) == 1)
1222 return *BaseDecls.begin();
1224 return Candidates.front();
1228 include_cleaner::Symbol Sym) {
1229 trace::Span Tracer(
"Hover::maybeAddSymbolProviders");
1231 llvm::SmallVector<include_cleaner::Header> RankedProviders =
1232 include_cleaner::headersForSymbol(Sym,
AST.getPreprocessor(),
1233 &
AST.getPragmaIncludes());
1234 if (RankedProviders.empty())
1237 const SourceManager &SM =
AST.getSourceManager();
1240 for (
const auto &P : RankedProviders) {
1241 if (
P.kind() == include_cleaner::Header::Physical &&
1242 P.physical() == SM.getFileEntryForID(SM.getMainFileID()))
1247 auto Matches = ConvertedIncludes.match(P);
1248 if (!Matches.empty()) {
1249 Result = Matches[0]->quote();
1254 if (!Result.empty()) {
1255 HI.Provider = std::move(Result);
1260 const auto &H = RankedProviders.front();
1261 if (H.kind() == include_cleaner::Header::Physical &&
1262 H.physical() == SM.getFileEntryForID(SM.getMainFileID()))
1267 HI.Provider = include_cleaner::spellHeader(
1268 {H,
AST.getPreprocessor().getHeaderSearchInfo(),
1269 SM.getFileEntryForID(SM.getMainFileID())});
1275std::string getSymbolName(include_cleaner::Symbol Sym) {
1277 switch (Sym.kind()) {
1278 case include_cleaner::Symbol::Declaration:
1279 if (
const auto *ND = llvm::dyn_cast<NamedDecl>(&Sym.declaration()))
1280 Name = ND->getDeclName().getAsString();
1282 case include_cleaner::Symbol::Macro:
1283 Name = Sym.macro().Name->getName();
1291 llvm::DenseSet<include_cleaner::Symbol> UsedSymbols;
1292 include_cleaner::walkUsed(
1294 &
AST.getPragmaIncludes(),
AST.getPreprocessor(),
1295 [&](
const include_cleaner::SymbolReference &
Ref,
1296 llvm::ArrayRef<include_cleaner::Header> Providers) {
1297 if (Ref.RT != include_cleaner::RefType::Explicit ||
1298 UsedSymbols.contains(Ref.Target))
1301 if (isPreferredProvider(Inc, Converted, Providers))
1302 UsedSymbols.insert(Ref.Target);
1305 for (
const auto &UsedSymbolDecl : UsedSymbols)
1306 HI.UsedSymbolNames.push_back(getSymbolName(UsedSymbolDecl));
1307 llvm::sort(HI.UsedSymbolNames);
1308 HI.UsedSymbolNames.erase(llvm::unique(HI.UsedSymbolNames),
1309 HI.UsedSymbolNames.end());
1315 const format::FormatStyle &Style,
1320 getPrintingPolicy(
AST.getASTContext().getPrintingPolicy());
1321 const SourceManager &SM =
AST.getSourceManager();
1324 llvm::consumeError(CurLoc.takeError());
1325 return std::nullopt;
1327 const auto &TB =
AST.getTokens();
1328 auto TokensTouchingCursor = syntax::spelledTokensTouching(*CurLoc, TB);
1330 if (TokensTouchingCursor.empty())
1331 return std::nullopt;
1334 for (
const auto &Inc :
AST.getIncludeStructure().MainFileIncludes) {
1335 if (Inc.Resolved.empty() || Inc.HashLine != Pos.
line)
1337 HoverCountMetric.
record(1,
"include");
1339 HI.
Name = std::string(llvm::sys::path::filename(Inc.Resolved));
1343 HI.
Kind = index::SymbolKind::IncludeDirective;
1344 maybeAddUsedSymbols(
AST, HI, Inc);
1351 CharSourceRange HighlightRange =
1352 TokensTouchingCursor.back().range(SM).toCharRange(SM);
1353 std::optional<HoverInfo> HI;
1357 for (
const auto &Tok : TokensTouchingCursor) {
1358 if (Tok.kind() == tok::identifier) {
1360 HighlightRange = Tok.range(SM).toCharRange(SM);
1362 HoverCountMetric.
record(1,
"macro");
1363 HI = getHoverContents(*M, Tok,
AST);
1364 if (
auto DefLoc = M->Info->getDefinitionLoc(); DefLoc.isValid()) {
1365 include_cleaner::Macro IncludeCleanerMacro{
1366 AST.getPreprocessor().getIdentifierInfo(Tok.text(SM)), DefLoc};
1367 maybeAddSymbolProviders(
AST, *HI,
1368 include_cleaner::Symbol{IncludeCleanerMacro});
1372 }
else if (Tok.kind() == tok::kw_auto || Tok.kind() == tok::kw_decltype) {
1373 HoverCountMetric.
record(1,
"keyword");
1377 HI = getDeducedTypeHoverContents(*
Deduced, Tok,
AST.getASTContext(), PP,
1379 HighlightRange = Tok.range(SM).toCharRange(SM);
1386 return std::nullopt;
1392 auto Offset = SM.getFileOffset(*CurLoc);
1400 AST.getHeuristicResolver());
1401 if (
const auto *DeclToUse = pickDeclToUse(Decls)) {
1402 HoverCountMetric.
record(1,
"decl");
1403 HI = getHoverContents(DeclToUse, PP, Index, TB);
1405 if (DeclToUse == N->ASTNode.get<Decl>())
1406 addLayoutInfo(*DeclToUse, *HI);
1409 HI->Value = printExprValue(N,
AST.getASTContext()).PrintedValue;
1410 maybeAddCalleeArgInfo(N, *HI, PP);
1412 if (!isa<NamespaceDecl>(DeclToUse))
1413 maybeAddSymbolProviders(
AST, *HI,
1414 include_cleaner::Symbol{*DeclToUse});
1415 }
else if (
const Expr *E = N->ASTNode.get<Expr>()) {
1416 HoverCountMetric.
record(1,
"expr");
1417 HI = getHoverContents(N, E,
AST, PP, Index);
1418 }
else if (
const Attr *A = N->ASTNode.get<Attr>()) {
1419 HoverCountMetric.
record(1,
"attribute");
1420 HI = getHoverContents(A,
AST);
1428 return std::nullopt;
1431 if (!HI->Definition.empty()) {
1432 auto Replacements = format::reformat(
1433 Style, HI->Definition, tooling::Range(0, HI->Definition.size()));
1434 if (
auto Formatted =
1435 tooling::applyAllReplacements(HI->Definition, Replacements))
1436 HI->Definition = *Formatted;
1439 HI->DefinitionLanguage = getMarkdownLanguage(
AST.getASTContext());
1447 uint64_t
Value = SizeInBits % 8 == 0 ? SizeInBits / 8 : SizeInBits;
1448 const char *
Unit =
Value != 0 &&
Value == SizeInBits ?
"bit" :
"byte";
1449 return llvm::formatv(
"{0} {1}{2}",
Value,
Unit,
Value == 1 ?
"" :
"s").str();
1455 const auto Bytes = OffsetInBits / 8;
1456 const auto Bits = OffsetInBits % 8;
1463void HoverInfo::calleeArgInfoToMarkupParagraph(markup::Paragraph &P)
const {
1466 llvm::raw_string_ostream OS(Buffer);
1479 OS <<
" (converted to " <<
CalleeArgInfo->Type->Type <<
")";
1480 P.appendText(OS.str());
1483void HoverInfo::usedSymbolNamesToMarkup(markup::Document &Output)
const {
1484 markup::Paragraph &
P = Output.addParagraph();
1485 P.appendText(
"provides ");
1487 const std::vector<std::string>::size_type SymbolNamesLimit = 5;
1488 auto Front = llvm::ArrayRef(
UsedSymbolNames).take_front(SymbolNamesLimit);
1491 Front, [&](llvm::StringRef Sym) {
P.appendCode(Sym); },
1492 [&] {
P.appendText(
", "); });
1494 P.appendText(
" and ");
1496 P.appendText(
" more");
1500void HoverInfo::providerToMarkupParagraph(markup::Document &Output)
const {
1501 markup::Paragraph &DI = Output.addParagraph();
1502 DI.appendText(
"provided by");
1507void HoverInfo::definitionScopeToMarkup(markup::Document &Output)
const {
1517 Buffer +=
"// In " + llvm::StringRef(
LocalScope).rtrim(
':').str() +
'\n';
1519 Buffer +=
"// In namespace " +
1520 llvm::StringRef(*NamespaceScope).rtrim(
':').str() +
'\n';
1533 P.appendText(
"Value = ");
1550markup::Document HoverInfo::presentDoxygen()
const {
1552 markup::Document Output;
1565 markup::Paragraph &Header = Output.addHeading(3);
1566 if (
Kind != index::SymbolKind::Unknown &&
1567 Kind != index::SymbolKind::IncludeDirective)
1568 Header.appendText(index::getSymbolKindString(
Kind)).appendSpace();
1569 assert(!
Name.empty() &&
"hover triggered on a nameless symbol");
1571 if (
Kind == index::SymbolKind::IncludeDirective) {
1572 Header.appendCode(
Name);
1575 Output.addParagraph().appendCode(
Definition);
1579 usedSymbolNamesToMarkup(Output);
1587 definitionScopeToMarkup(Output);
1589 Header.appendCode(
Name);
1593 providerToMarkupParagraph(Output);
1601 if (SymbolDoc.hasBriefCommand()) {
1602 if (
Kind != index::SymbolKind::Parameter &&
1603 Kind != index::SymbolKind::TemplateTypeParm)
1607 Output.addHeading(3).appendText(
"Brief");
1608 SymbolDoc.briefToMarkup(Output.addParagraph());
1621 Output.addHeading(3).appendText(
"Template Parameters");
1622 markup::BulletList &L = Output.addBulletList();
1624 markup::Paragraph &
P = L.addItem().addParagraph();
1625 P.appendCode(llvm::to_string(
Param));
1626 if (SymbolDoc.isTemplateTypeParmDocumented(llvm::to_string(
Param.
Name))) {
1627 P.appendText(
" - ");
1628 SymbolDoc.templateTypeParmDocToMarkup(llvm::to_string(
Param.
Name), P);
1635 Output.addHeading(3).appendText(
"Parameters");
1636 markup::BulletList &L = Output.addBulletList();
1638 markup::Paragraph &
P = L.addItem().addParagraph();
1639 P.appendCode(llvm::to_string(
Param));
1641 if (SymbolDoc.isParameterDocumented(llvm::to_string(
Param.
Name))) {
1642 P.appendText(
" - ");
1643 SymbolDoc.parameterDocToMarkup(llvm::to_string(
Param.
Name), P);
1654 Output.addHeading(3).appendText(
"Returns");
1655 markup::Paragraph &
P = Output.addParagraph();
1658 if (SymbolDoc.hasReturnCommand()) {
1659 P.appendText(
" - ");
1660 SymbolDoc.returnToMarkup(P);
1663 SymbolDoc.retvalsToMarkup(Output);
1667 if (SymbolDoc.hasDetailedDoc()) {
1668 Output.addHeading(3).appendText(
"Details");
1669 SymbolDoc.detailedDocToMarkup(Output);
1677 Output.addParagraph().appendText(
"Type: ").appendCode(
1678 llvm::to_string(*
Type));
1681 valueToMarkupParagraph(Output.addParagraph());
1685 offsetToMarkupParagraph(Output.addParagraph());
1687 sizeToMarkupParagraph(Output.addParagraph());
1691 calleeArgInfoToMarkupParagraph(Output.addParagraph());
1696 usedSymbolNamesToMarkup(Output);
1702markup::Document HoverInfo::presentDefault()
const {
1703 markup::Document Output;
1716 markup::Paragraph &Header = Output.addHeading(3);
1717 if (
Kind != index::SymbolKind::Unknown &&
1718 Kind != index::SymbolKind::IncludeDirective)
1719 Header.appendText(index::getSymbolKindString(
Kind)).appendSpace();
1720 assert(!
Name.empty() &&
"hover triggered on a nameless symbol");
1721 Header.appendCode(
Name);
1724 providerToMarkupParagraph(Output);
1737 Output.addParagraph().appendText(
"→ ").appendCode(
1742 Output.addParagraph().appendText(
"Parameters:");
1743 markup::BulletList &L = Output.addBulletList();
1745 L.addItem().addParagraph().appendCode(llvm::to_string(
Param));
1751 Output.addParagraph().appendText(
"Type: ").appendCode(
1752 llvm::to_string(*
Type));
1755 valueToMarkupParagraph(Output.addParagraph());
1759 offsetToMarkupParagraph(Output.addParagraph());
1761 sizeToMarkupParagraph(Output.addParagraph());
1765 calleeArgInfoToMarkupParagraph(Output.addParagraph());
1773 definitionScopeToMarkup(Output);
1778 usedSymbolNamesToMarkup(Output);
1789 return presentDefault().asMarkdown();
1791 return presentDoxygen().asMarkdown();
1796 return presentDefault().asEscapedMarkdown();
1799 return presentDefault().asPlainText();
1806 assert(Line[Offset] ==
'`');
1809 llvm::StringRef Prefix = Line.substr(0, Offset);
1810 constexpr llvm::StringLiteral BeforeStartChars =
" \t(=";
1811 if (!Prefix.empty() && !BeforeStartChars.contains(Prefix.back()))
1812 return std::nullopt;
1815 auto Next = Line.find_first_of(
"`\n", Offset + 1);
1816 if (Next == llvm::StringRef::npos)
1817 return std::nullopt;
1820 if (Line[Next] ==
'\n')
1821 return std::nullopt;
1823 llvm::StringRef Contents = Line.slice(Offset + 1, Next);
1824 if (Contents.empty() || isWhitespace(Contents.front()) ||
1825 isWhitespace(Contents.back()))
1826 return std::nullopt;
1829 llvm::StringRef Suffix = Line.substr(Next + 1);
1830 constexpr llvm::StringLiteral AfterEndChars =
" \t)=.,;:";
1831 if (!Suffix.empty() && !AfterEndChars.contains(Suffix.front()))
1832 return std::nullopt;
1834 return Line.slice(Offset, Next + 1);
1839 for (
unsigned I = 0; I <
Text.size(); ++I) {
1844 Out.appendCode(
Range->trim(
"`"),
true);
1861 for (std::tie(
Paragraph, Rest) = Input.split(
"\n\n");
1863 std::tie(
Paragraph, Rest) = Rest.split(
"\n\n")) {
1875 OS <<
" (aka " << *T.AKA <<
")";
1884 OS <<
" " << *P.Name;
1886 OS <<
" = " << *P.Default;
1887 if (P.Type && P.Type->AKA)
1888 OS <<
" (aka " << *P.Type->AKA <<
")";
Include Cleaner is clangd functionality for providing diagnostics for misuse of transitive headers an...
static GeneratorRegistry::Add< MDGenerator > MD(MDGenerator::Format, "Generator for Markdown output.")
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.
Ensure we have enough bits to represent all SymbolTag values.
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.