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 HI.AccessSpecifier = getAccessSpelling(
D->getAccess()).str();
670 HI.NamespaceScope = getNamespaceScope(D);
671 if (!HI.NamespaceScope->empty())
672 HI.NamespaceScope->append(
"::");
673 HI.LocalScope = getLocalScope(D);
674 if (!HI.LocalScope.empty())
675 HI.LocalScope.append(
"::");
678 const auto *CommentD = getDeclForComment(D);
682 HI.CommentOpts =
D->getASTContext().getLangOpts().CommentOpts;
683 enhanceFromIndex(HI, *CommentD, Index);
684 if (HI.Documentation.empty())
685 HI.Documentation = synthesizeDocumentation(Ctx, D);
687 HI.Kind = index::getSymbolInfo(D).Kind;
690 if (
const TemplateDecl *TD =
D->getDescribedTemplate()) {
691 HI.TemplateParameters =
692 fetchTemplateParameters(TD->getTemplateParameters(), PP);
694 }
else if (
const FunctionDecl *FD =
D->getAsFunction()) {
695 if (
const auto *FTD = FD->getDescribedTemplate()) {
696 HI.TemplateParameters =
697 fetchTemplateParameters(FTD->getTemplateParameters(), PP);
703 if (
const FunctionDecl *FD = getUnderlyingFunction(D))
704 fillFunctionTypeAndParams(HI, D, FD, PP);
705 else if (
const auto *VD = dyn_cast<ValueDecl>(D))
706 HI.Type =
printType(VD->getType(), Ctx, PP);
707 else if (
const auto *TTP = dyn_cast<TemplateTypeParmDecl>(D))
708 HI.Type = TTP->wasDeclaredWithTypename() ?
"typename" :
"class";
709 else if (
const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(D))
711 else if (
const auto *VT = dyn_cast<VarTemplateDecl>(D))
712 HI.Type =
printType(VT->getTemplatedDecl()->getType(), Ctx, PP);
713 else if (
const auto *TN = dyn_cast<TypedefNameDecl>(D))
714 HI.Type =
printType(TN->getUnderlyingType().getDesugaredType(Ctx), Ctx, PP);
715 else if (
const auto *TAT = dyn_cast<TypeAliasTemplateDecl>(D))
716 HI.Type =
printType(TAT->getTemplatedDecl()->getUnderlyingType(), Ctx, PP);
719 if (
const auto *Var = dyn_cast<VarDecl>(D); Var && !Var->isInvalidDecl()) {
720 if (
const Expr *Init = Var->getInit())
721 HI.Value = printExprValue(Init, Ctx);
722 }
else if (
const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
724 if (!ECD->getType()->isDependentType())
725 HI.Value =
toString(ECD->getInitVal(), 10);
728 HI.Definition = printDefinition(D, PP, TB);
733std::optional<HoverInfo>
734getPredefinedExprHoverContents(
const PredefinedExpr &PE, ASTContext &Ctx,
735 const PrintingPolicy &PP) {
737 HI.
Name = PE.getIdentKindName();
738 HI.Kind = index::SymbolKind::Variable;
739 HI.Documentation =
"Name of the current function (predefined variable)";
740 if (
const StringLiteral *Name = PE.getFunctionName()) {
742 llvm::raw_string_ostream OS(*HI.Value);
743 Name->outputString(OS);
744 HI.Type =
printType(Name->getType(), Ctx, PP);
747 QualType StringType = Ctx.getIncompleteArrayType(Ctx.CharTy.withConst(),
748 ArraySizeModifier::Normal,
750 HI.Type =
printType(StringType, Ctx, PP);
755HoverInfo evaluateMacroExpansion(
unsigned int SpellingBeginOffset,
756 unsigned int SpellingEndOffset,
757 llvm::ArrayRef<syntax::Token> Expanded,
760 auto &Tokens =
AST.getTokens();
761 auto PP = getPrintingPolicy(
Context.getPrintingPolicy());
770 if (Expanded.size() == 1)
771 if (tok::getPunctuatorSpelling(Expanded[0].kind()))
774 auto *StartNode = Tree.commonAncestor();
785 if (!StartNode->Children.empty())
790 auto ExprResult = printExprValue(StartNode,
Context);
791 HI.Value = std::move(ExprResult.PrintedValue);
792 if (
auto *E = ExprResult.TheExpr)
796 if (!HI.Value && !HI.Type && ExprResult.TheNode)
797 if (
auto *VD = ExprResult.TheNode->ASTNode.get<VarDecl>())
807 SourceManager &SM =
AST.getSourceManager();
808 HI.Name = std::string(
Macro.Name);
809 HI.Kind = index::SymbolKind::Macro;
814 SourceLocation StartLoc =
Macro.Info->getDefinitionLoc();
815 SourceLocation EndLoc =
Macro.Info->getDefinitionEndLoc();
823 if (SM.getPresumedLoc(EndLoc,
false).isValid()) {
824 EndLoc = Lexer::getLocForEndOfToken(EndLoc, 0, SM,
AST.getLangOpts());
826 StringRef Buffer = SM.getBufferData(SM.getFileID(StartLoc), &Invalid);
828 unsigned StartOffset = SM.getFileOffset(StartLoc);
829 unsigned EndOffset = SM.getFileOffset(EndLoc);
830 if (EndOffset <= Buffer.size() && StartOffset < EndOffset)
832 (
"#define " + Buffer.substr(StartOffset, EndOffset - StartOffset))
837 if (
auto Expansion =
AST.getTokens().expansionStartingAt(&Tok)) {
841 std::string ExpansionText;
842 for (
const auto &ExpandedTok : Expansion->Expanded) {
843 ExpansionText += ExpandedTok.text(SM);
844 ExpansionText +=
" ";
846 const size_t Limit =
static_cast<size_t>(Cfg.Hover.MacroContentsLimit);
847 if (Limit && ExpansionText.size() > Limit) {
848 ExpansionText.clear();
853 if (!ExpansionText.empty()) {
854 if (!HI.Definition.empty()) {
855 HI.Definition +=
"\n\n";
857 HI.Definition +=
"// Expands to\n";
858 HI.Definition += ExpansionText;
861 auto Evaluated = evaluateMacroExpansion(
862 SM.getFileOffset(Tok.location()),
863 SM.getFileOffset(Tok.endLocation()),
864 Expansion->Expanded,
AST);
865 HI.Value = std::move(Evaluated.Value);
866 HI.Type = std::move(Evaluated.Type);
873 llvm::raw_string_ostream OS(Result);
876 OS <<
" // aka: " << *PType.AKA;
880std::optional<HoverInfo> getThisExprHoverContents(
const CXXThisExpr *CTE,
882 const PrintingPolicy &PP) {
883 QualType OriginThisType = CTE->getType()->getPointeeType();
884 QualType ClassType =
declaredType(OriginThisType->castAsTagDecl());
889 QualType PrettyThisType = ASTCtx.getPointerType(
890 QualType(ClassType.getTypePtr(), OriginThisType.getCVRQualifiers()));
894 HI.Definition = typeAsDefinition(
printType(PrettyThisType, ASTCtx, PP));
899HoverInfo getDeducedTypeHoverContents(QualType QT,
const syntax::Token &Tok,
901 const PrintingPolicy &PP,
905 HI.
Name = tok::getTokenName(Tok.kind());
906 HI.Kind = index::SymbolKind::TypeAlias;
908 if (QT->isUndeducedAutoType()) {
909 HI.Definition =
"/* not deduced */";
911 HI.Definition = typeAsDefinition(
printType(QT, ASTCtx, PP));
913 if (
const auto *D = QT->getAsTagDecl()) {
914 const auto *CommentD = getDeclForComment(D);
916 enhanceFromIndex(HI, *CommentD, Index);
923HoverInfo getStringLiteralContents(
const StringLiteral *SL,
924 const PrintingPolicy &PP) {
927 HI.
Name =
"string-literal";
928 HI.Size = (SL->getLength() + 1) * SL->getCharByteWidth() * 8;
929 HI.Type = SL->getType().getAsString(PP).c_str();
934bool isLiteral(
const Expr *E) {
937 return llvm::isa<CompoundLiteralExpr>(E) ||
938 llvm::isa<CXXBoolLiteralExpr>(E) ||
939 llvm::isa<CXXNullPtrLiteralExpr>(E) ||
940 llvm::isa<FixedPointLiteral>(E) || llvm::isa<FloatingLiteral>(E) ||
941 llvm::isa<ImaginaryLiteral>(E) || llvm::isa<IntegerLiteral>(E) ||
942 llvm::isa<StringLiteral>(E) || llvm::isa<UserDefinedLiteral>(E);
945llvm::StringLiteral getNameForExpr(
const Expr *E) {
953 return llvm::StringLiteral(
"expression");
957 const PrintingPolicy &PP);
963 const PrintingPolicy &PP,
965 std::optional<HoverInfo> HI;
967 if (
const auto *VecExpr = dyn_cast<ExtVectorElementExpr>(E)) {
969 HI->Name = VecExpr->getAccessor().getName().str();
970 HI->Type =
printType(VecExpr->getType(),
AST.getASTContext(), PP);
973 if (
const auto *MatExpr = dyn_cast<MatrixElementExpr>(E)) {
975 HI->Name = MatExpr->getAccessor().getName().str();
976 HI->Type =
printType(MatExpr->getType(),
AST.getASTContext(), PP);
980 if (
const StringLiteral *SL = dyn_cast<StringLiteral>(E)) {
982 HI = getStringLiteralContents(SL, PP);
983 }
else if (isLiteral(E)) {
987 maybeAddCalleeArgInfo(N, HI.emplace(), PP);
988 if (HI->CalleeArgInfo) {
992 HI->Name =
"literal";
999 if (
const CXXThisExpr *CTE = dyn_cast<CXXThisExpr>(E))
1000 HI = getThisExprHoverContents(CTE,
AST.getASTContext(), PP);
1001 if (
const PredefinedExpr *PE = dyn_cast<PredefinedExpr>(E))
1002 HI = getPredefinedExprHoverContents(*PE,
AST.getASTContext(), PP);
1005 if (
auto Val = printExprValue(E,
AST.getASTContext())) {
1007 HI->Type =
printType(E->getType(),
AST.getASTContext(), PP);
1009 HI->Name = std::string(getNameForExpr(E));
1013 maybeAddCalleeArgInfo(N, *HI, PP);
1019std::optional<HoverInfo> getHoverContents(
const Attr *A,
ParsedAST &
AST) {
1021 HI.
Name =
A->getSpelling();
1023 HI.LocalScope =
A->getScopeName()->getName().str();
1025 llvm::raw_string_ostream OS(HI.Definition);
1026 A->printPretty(OS,
AST.getASTContext().getPrintingPolicy());
1028 HI.Documentation = Attr::getDocumentation(
A->getKind()).str();
1032void addLayoutInfo(
const NamedDecl &ND,
HoverInfo &HI) {
1033 if (ND.isInvalidDecl())
1036 const auto &Ctx = ND.getASTContext();
1037 if (
auto *RD = llvm::dyn_cast<RecordDecl>(&ND)) {
1038 CanQualType RT = Ctx.getCanonicalTagType(RD);
1039 if (
auto Size = Ctx.getTypeSizeInCharsIfKnown(RT))
1040 HI.Size = Size->getQuantity() * 8;
1041 if (!RD->isDependentType() && RD->isCompleteDefinition())
1042 HI.Align = Ctx.getTypeAlign(RT);
1046 if (
const auto *FD = llvm::dyn_cast<FieldDecl>(&ND)) {
1047 const auto *
Record = FD->getParent();
1050 if (Record && !
Record->isInvalidDecl() && !
Record->isDependentType()) {
1051 HI.Align = Ctx.getTypeAlign(FD->getType());
1052 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Record);
1053 HI.Offset = Layout.getFieldOffset(FD->getFieldIndex());
1054 if (FD->isBitField())
1055 HI.Size = FD->getBitWidthValue();
1056 else if (
auto Size = Ctx.getTypeSizeInCharsIfKnown(FD->getType()))
1057 HI.Size = FD->isZeroSize(Ctx) ? 0 : Size->getQuantity() * 8;
1059 unsigned EndOfField = *HI.Offset + *HI.Size;
1062 if (!
Record->isUnion() &&
1063 FD->getFieldIndex() + 1 < Layout.getFieldCount()) {
1065 unsigned NextOffset = Layout.getFieldOffset(FD->getFieldIndex() + 1);
1066 if (NextOffset >= EndOfField)
1067 HI.Padding = NextOffset - EndOfField;
1070 HI.Padding = Layout.getSize().getQuantity() * 8 - EndOfField;
1082 if (ParmType->isReferenceType()) {
1083 if (ParmType->getPointeeType().isConstQualified())
1093 const PrintingPolicy &PP) {
1094 const auto &OuterNode = N->outerImplicit();
1095 if (!OuterNode.Parent)
1098 const FunctionDecl *FD =
nullptr;
1099 llvm::ArrayRef<const Expr *> Args;
1101 if (
const auto *CE = OuterNode.Parent->ASTNode.get<CallExpr>()) {
1102 FD = CE->getDirectCallee();
1103 Args = {CE->getArgs(), CE->getNumArgs()};
1104 }
else if (
const auto *CE =
1105 OuterNode.Parent->ASTNode.get<CXXConstructExpr>()) {
1106 FD = CE->getConstructor();
1107 Args = {CE->getArgs(), CE->getNumArgs()};
1118 if (!FD || FD->isOverloadedOperator() || FD->isVariadic())
1126 for (
unsigned I = 0; I < Args.size() && I < Parameters.size(); ++I) {
1127 if (Args[I] != OuterNode.ASTNode.get<Expr>())
1131 if (
const ParmVarDecl *PVD = Parameters[I]) {
1132 HI.CalleeArgInfo.emplace(toHoverInfoParam(PVD, PP));
1133 if (N == &OuterNode)
1134 PassType.PassBy = getPassMode(PVD->getType());
1138 if (!HI.CalleeArgInfo)
1144 if (
const auto *E = N->ASTNode.get<Expr>()) {
1145 if (E->getType().isConstQualified())
1149 for (
auto *CastNode = N->Parent;
1150 CastNode != OuterNode.Parent && !PassType.Converted;
1151 CastNode = CastNode->Parent) {
1152 if (
const auto *ImplicitCast = CastNode->ASTNode.get<ImplicitCastExpr>()) {
1153 switch (ImplicitCast->getCastKind()) {
1155 case CK_DerivedToBase:
1156 case CK_UncheckedDerivedToBase:
1159 PassType.PassBy = ImplicitCast->getType().isConstQualified()
1163 case CK_LValueToRValue:
1164 case CK_ArrayToPointerDecay:
1165 case CK_FunctionToPointerDecay:
1166 case CK_NullToPointer:
1167 case CK_NullToMemberPointer:
1173 PassType.Converted =
true;
1176 }
else if (
const auto *CtorCall =
1177 CastNode->ASTNode.get<CXXConstructExpr>()) {
1180 if (CtorCall->getConstructor()->isCopyConstructor())
1183 PassType.Converted =
true;
1184 }
else if (CastNode->ASTNode.get<MaterializeTemporaryExpr>()) {
1189 PassType.Converted =
true;
1193 HI.CallPassType.emplace(PassType);
1196const NamedDecl *pickDeclToUse(llvm::ArrayRef<const NamedDecl *> Candidates) {
1197 if (Candidates.empty())
1206 if (Candidates.size() <= 2) {
1207 if (llvm::isa<UsingDecl>(Candidates.front()))
1208 return Candidates.back();
1209 return Candidates.front();
1218 auto BaseDecls = llvm::make_filter_range(
1219 Candidates, [](
const NamedDecl *D) {
return llvm::isa<UsingDecl>(D); });
1220 if (std::distance(BaseDecls.begin(), BaseDecls.end()) == 1)
1221 return *BaseDecls.begin();
1223 return Candidates.front();
1227 include_cleaner::Symbol Sym) {
1228 trace::Span Tracer(
"Hover::maybeAddSymbolProviders");
1230 llvm::SmallVector<include_cleaner::Header> RankedProviders =
1231 include_cleaner::headersForSymbol(Sym,
AST.getPreprocessor(),
1232 &
AST.getPragmaIncludes());
1233 if (RankedProviders.empty())
1236 const SourceManager &SM =
AST.getSourceManager();
1239 for (
const auto &P : RankedProviders) {
1240 if (
P.kind() == include_cleaner::Header::Physical &&
1241 P.physical() == SM.getFileEntryForID(SM.getMainFileID()))
1246 auto Matches = ConvertedIncludes.match(P);
1247 if (!Matches.empty()) {
1248 Result = Matches[0]->quote();
1253 if (!Result.empty()) {
1254 HI.Provider = std::move(Result);
1259 const auto &H = RankedProviders.front();
1260 if (H.kind() == include_cleaner::Header::Physical &&
1261 H.physical() == SM.getFileEntryForID(SM.getMainFileID()))
1266 HI.Provider = include_cleaner::spellHeader(
1267 {H,
AST.getPreprocessor().getHeaderSearchInfo(),
1268 SM.getFileEntryForID(SM.getMainFileID())});
1274std::string getSymbolName(include_cleaner::Symbol Sym) {
1276 switch (Sym.kind()) {
1277 case include_cleaner::Symbol::Declaration:
1278 if (
const auto *ND = llvm::dyn_cast<NamedDecl>(&Sym.declaration()))
1279 Name = ND->getDeclName().getAsString();
1281 case include_cleaner::Symbol::Macro:
1282 Name = Sym.macro().Name->getName();
1290 llvm::DenseSet<include_cleaner::Symbol> UsedSymbols;
1291 include_cleaner::walkUsed(
1293 &
AST.getPragmaIncludes(),
AST.getPreprocessor(),
1294 [&](
const include_cleaner::SymbolReference &
Ref,
1295 llvm::ArrayRef<include_cleaner::Header> Providers) {
1296 if (Ref.RT != include_cleaner::RefType::Explicit ||
1297 UsedSymbols.contains(Ref.Target))
1300 if (isPreferredProvider(Inc, Converted, Providers))
1301 UsedSymbols.insert(Ref.Target);
1304 for (
const auto &UsedSymbolDecl : UsedSymbols)
1305 HI.UsedSymbolNames.push_back(getSymbolName(UsedSymbolDecl));
1306 llvm::sort(HI.UsedSymbolNames);
1307 HI.UsedSymbolNames.erase(llvm::unique(HI.UsedSymbolNames),
1308 HI.UsedSymbolNames.end());
1314 const format::FormatStyle &Style,
1319 getPrintingPolicy(
AST.getASTContext().getPrintingPolicy());
1320 const SourceManager &SM =
AST.getSourceManager();
1323 llvm::consumeError(CurLoc.takeError());
1324 return std::nullopt;
1326 const auto &TB =
AST.getTokens();
1327 auto TokensTouchingCursor = syntax::spelledTokensTouching(*CurLoc, TB);
1329 if (TokensTouchingCursor.empty())
1330 return std::nullopt;
1333 for (
const auto &Inc :
AST.getIncludeStructure().MainFileIncludes) {
1334 if (Inc.Resolved.empty() || Inc.HashLine != Pos.
line)
1336 HoverCountMetric.
record(1,
"include");
1338 HI.
Name = std::string(llvm::sys::path::filename(Inc.Resolved));
1342 HI.
Kind = index::SymbolKind::IncludeDirective;
1343 maybeAddUsedSymbols(
AST, HI, Inc);
1350 CharSourceRange HighlightRange =
1351 TokensTouchingCursor.back().range(SM).toCharRange(SM);
1352 std::optional<HoverInfo> HI;
1356 for (
const auto &Tok : TokensTouchingCursor) {
1357 if (Tok.kind() == tok::identifier) {
1359 HighlightRange = Tok.range(SM).toCharRange(SM);
1361 HoverCountMetric.
record(1,
"macro");
1362 HI = getHoverContents(*M, Tok,
AST);
1363 if (
auto DefLoc = M->Info->getDefinitionLoc(); DefLoc.isValid()) {
1364 include_cleaner::Macro IncludeCleanerMacro{
1365 AST.getPreprocessor().getIdentifierInfo(Tok.text(SM)), DefLoc};
1366 maybeAddSymbolProviders(
AST, *HI,
1367 include_cleaner::Symbol{IncludeCleanerMacro});
1371 }
else if (Tok.kind() == tok::kw_auto || Tok.kind() == tok::kw_decltype) {
1372 HoverCountMetric.
record(1,
"keyword");
1376 HI = getDeducedTypeHoverContents(*
Deduced, Tok,
AST.getASTContext(), PP,
1378 HighlightRange = Tok.range(SM).toCharRange(SM);
1385 return std::nullopt;
1391 auto Offset = SM.getFileOffset(*CurLoc);
1399 AST.getHeuristicResolver());
1400 if (
const auto *DeclToUse = pickDeclToUse(Decls)) {
1401 HoverCountMetric.
record(1,
"decl");
1402 HI = getHoverContents(DeclToUse, PP, Index, TB);
1404 if (DeclToUse == N->ASTNode.get<Decl>())
1405 addLayoutInfo(*DeclToUse, *HI);
1408 HI->Value = printExprValue(N,
AST.getASTContext()).PrintedValue;
1409 maybeAddCalleeArgInfo(N, *HI, PP);
1411 if (!isa<NamespaceDecl>(DeclToUse))
1412 maybeAddSymbolProviders(
AST, *HI,
1413 include_cleaner::Symbol{*DeclToUse});
1414 }
else if (
const Expr *E = N->ASTNode.get<Expr>()) {
1415 HoverCountMetric.
record(1,
"expr");
1416 HI = getHoverContents(N, E,
AST, PP, Index);
1417 }
else if (
const Attr *A = N->ASTNode.get<Attr>()) {
1418 HoverCountMetric.
record(1,
"attribute");
1419 HI = getHoverContents(A,
AST);
1427 return std::nullopt;
1430 if (!HI->Definition.empty()) {
1431 auto Replacements = format::reformat(
1432 Style, HI->Definition, tooling::Range(0, HI->Definition.size()));
1433 if (
auto Formatted =
1434 tooling::applyAllReplacements(HI->Definition, Replacements))
1435 HI->Definition = *Formatted;
1438 HI->DefinitionLanguage = getMarkdownLanguage(
AST.getASTContext());
1446 uint64_t
Value = SizeInBits % 8 == 0 ? SizeInBits / 8 : SizeInBits;
1447 const char *
Unit =
Value != 0 &&
Value == SizeInBits ?
"bit" :
"byte";
1448 return llvm::formatv(
"{0} {1}{2}",
Value,
Unit,
Value == 1 ?
"" :
"s").str();
1454 const auto Bytes = OffsetInBits / 8;
1455 const auto Bits = OffsetInBits % 8;
1462void HoverInfo::calleeArgInfoToMarkupParagraph(markup::Paragraph &P)
const {
1465 llvm::raw_string_ostream OS(Buffer);
1478 OS <<
" (converted to " <<
CalleeArgInfo->Type->Type <<
")";
1479 P.appendText(OS.str());
1482void HoverInfo::usedSymbolNamesToMarkup(markup::Document &Output)
const {
1483 markup::Paragraph &
P = Output.addParagraph();
1484 P.appendText(
"provides ");
1486 const std::vector<std::string>::size_type SymbolNamesLimit = 5;
1487 auto Front = llvm::ArrayRef(
UsedSymbolNames).take_front(SymbolNamesLimit);
1490 Front, [&](llvm::StringRef Sym) {
P.appendCode(Sym); },
1491 [&] {
P.appendText(
", "); });
1493 P.appendText(
" and ");
1495 P.appendText(
" more");
1499void HoverInfo::providerToMarkupParagraph(markup::Document &Output)
const {
1500 markup::Paragraph &DI = Output.addParagraph();
1501 DI.appendText(
"provided by");
1506void HoverInfo::definitionScopeToMarkup(markup::Document &Output)
const {
1516 Buffer +=
"// In " + llvm::StringRef(
LocalScope).rtrim(
':').str() +
'\n';
1518 Buffer +=
"// In namespace " +
1519 llvm::StringRef(*NamespaceScope).rtrim(
':').str() +
'\n';
1532 P.appendText(
"Value = ");
1549markup::Document HoverInfo::presentDoxygen()
const {
1551 markup::Document Output;
1564 markup::Paragraph &Header = Output.addHeading(3);
1565 if (
Kind != index::SymbolKind::Unknown &&
1566 Kind != index::SymbolKind::IncludeDirective)
1567 Header.appendText(index::getSymbolKindString(
Kind)).appendSpace();
1568 assert(!
Name.empty() &&
"hover triggered on a nameless symbol");
1570 if (
Kind == index::SymbolKind::IncludeDirective) {
1571 Header.appendCode(
Name);
1574 Output.addParagraph().appendCode(
Definition);
1578 usedSymbolNamesToMarkup(Output);
1586 definitionScopeToMarkup(Output);
1588 Header.appendCode(
Name);
1592 providerToMarkupParagraph(Output);
1600 if (SymbolDoc.hasBriefCommand()) {
1601 if (
Kind != index::SymbolKind::Parameter &&
1602 Kind != index::SymbolKind::TemplateTypeParm)
1606 Output.addHeading(3).appendText(
"Brief");
1607 SymbolDoc.briefToMarkup(Output.addParagraph());
1620 Output.addHeading(3).appendText(
"Template Parameters");
1621 markup::BulletList &L = Output.addBulletList();
1623 markup::Paragraph &
P = L.addItem().addParagraph();
1624 P.appendCode(llvm::to_string(
Param));
1625 if (SymbolDoc.isTemplateTypeParmDocumented(llvm::to_string(
Param.
Name))) {
1626 P.appendText(
" - ");
1627 SymbolDoc.templateTypeParmDocToMarkup(llvm::to_string(
Param.
Name), P);
1634 Output.addHeading(3).appendText(
"Parameters");
1635 markup::BulletList &L = Output.addBulletList();
1637 markup::Paragraph &
P = L.addItem().addParagraph();
1638 P.appendCode(llvm::to_string(
Param));
1640 if (SymbolDoc.isParameterDocumented(llvm::to_string(
Param.
Name))) {
1641 P.appendText(
" - ");
1642 SymbolDoc.parameterDocToMarkup(llvm::to_string(
Param.
Name), P);
1653 Output.addHeading(3).appendText(
"Returns");
1654 markup::Paragraph &
P = Output.addParagraph();
1657 if (SymbolDoc.hasReturnCommand()) {
1658 P.appendText(
" - ");
1659 SymbolDoc.returnToMarkup(P);
1662 SymbolDoc.retvalsToMarkup(Output);
1666 if (SymbolDoc.hasDetailedDoc()) {
1667 Output.addHeading(3).appendText(
"Details");
1668 SymbolDoc.detailedDocToMarkup(Output);
1676 Output.addParagraph().appendText(
"Type: ").appendCode(
1677 llvm::to_string(*
Type));
1680 valueToMarkupParagraph(Output.addParagraph());
1684 offsetToMarkupParagraph(Output.addParagraph());
1686 sizeToMarkupParagraph(Output.addParagraph());
1690 calleeArgInfoToMarkupParagraph(Output.addParagraph());
1695 usedSymbolNamesToMarkup(Output);
1701markup::Document HoverInfo::presentDefault()
const {
1702 markup::Document Output;
1715 markup::Paragraph &Header = Output.addHeading(3);
1716 if (
Kind != index::SymbolKind::Unknown &&
1717 Kind != index::SymbolKind::IncludeDirective)
1718 Header.appendText(index::getSymbolKindString(
Kind)).appendSpace();
1719 assert(!
Name.empty() &&
"hover triggered on a nameless symbol");
1720 Header.appendCode(
Name);
1723 providerToMarkupParagraph(Output);
1736 Output.addParagraph().appendText(
"→ ").appendCode(
1741 Output.addParagraph().appendText(
"Parameters:");
1742 markup::BulletList &L = Output.addBulletList();
1744 L.addItem().addParagraph().appendCode(llvm::to_string(
Param));
1750 Output.addParagraph().appendText(
"Type: ").appendCode(
1751 llvm::to_string(*
Type));
1754 valueToMarkupParagraph(Output.addParagraph());
1758 offsetToMarkupParagraph(Output.addParagraph());
1760 sizeToMarkupParagraph(Output.addParagraph());
1764 calleeArgInfoToMarkupParagraph(Output.addParagraph());
1772 definitionScopeToMarkup(Output);
1777 usedSymbolNamesToMarkup(Output);
1788 return presentDefault().asMarkdown();
1790 return presentDoxygen().asMarkdown();
1795 return presentDefault().asEscapedMarkdown();
1798 return presentDefault().asPlainText();
1805 assert(Line[Offset] ==
'`');
1808 llvm::StringRef Prefix = Line.substr(0, Offset);
1809 constexpr llvm::StringLiteral BeforeStartChars =
" \t(=";
1810 if (!Prefix.empty() && !BeforeStartChars.contains(Prefix.back()))
1811 return std::nullopt;
1814 auto Next = Line.find_first_of(
"`\n", Offset + 1);
1815 if (Next == llvm::StringRef::npos)
1816 return std::nullopt;
1819 if (Line[Next] ==
'\n')
1820 return std::nullopt;
1822 llvm::StringRef Contents = Line.slice(Offset + 1, Next);
1823 if (Contents.empty() || isWhitespace(Contents.front()) ||
1824 isWhitespace(Contents.back()))
1825 return std::nullopt;
1828 llvm::StringRef Suffix = Line.substr(Next + 1);
1829 constexpr llvm::StringLiteral AfterEndChars =
" \t)=.,;:";
1830 if (!Suffix.empty() && !AfterEndChars.contains(Suffix.front()))
1831 return std::nullopt;
1833 return Line.slice(Offset, Next + 1);
1838 for (
unsigned I = 0; I <
Text.size(); ++I) {
1843 Out.appendCode(
Range->trim(
"`"),
true);
1860 for (std::tie(
Paragraph, Rest) = Input.split(
"\n\n");
1862 std::tie(
Paragraph, Rest) = Rest.split(
"\n\n")) {
1874 OS <<
" (aka " << *T.AKA <<
")";
1883 OS <<
" " << *P.Name;
1885 OS <<
" = " << *P.Default;
1886 if (P.Type && P.Type->AKA)
1887 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.