clang-tools  11.0.0
Hover.cpp
Go to the documentation of this file.
1 //===--- Hover.cpp - Information about code at the cursor location --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "Hover.h"
10 
11 #include "AST.h"
12 #include "CodeCompletionStrings.h"
13 #include "FindTarget.h"
14 #include "ParsedAST.h"
15 #include "Selection.h"
16 #include "SourceCode.h"
17 #include "index/SymbolCollector.h"
18 #include "support/Logger.h"
19 #include "support/Markup.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/ASTTypeTraits.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclBase.h"
24 #include "clang/AST/DeclCXX.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/OperationKinds.h"
29 #include "clang/AST/PrettyPrinter.h"
30 #include "clang/AST/Type.h"
31 #include "clang/Basic/SourceLocation.h"
32 #include "clang/Basic/Specifiers.h"
33 #include "clang/Basic/TokenKinds.h"
34 #include "clang/Index/IndexSymbol.h"
35 #include "clang/Tooling/Syntax/Tokens.h"
36 #include "llvm/ADT/None.h"
37 #include "llvm/ADT/Optional.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/ADT/StringExtras.h"
41 #include "llvm/ADT/StringRef.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include <string>
46 
47 namespace clang {
48 namespace clangd {
49 namespace {
50 
51 PrintingPolicy printingPolicyForDecls(PrintingPolicy Base) {
52  PrintingPolicy Policy(Base);
53 
54  Policy.AnonymousTagLocations = false;
55  Policy.TerseOutput = true;
56  Policy.PolishForDeclaration = true;
57  Policy.ConstantsAsWritten = true;
58  Policy.SuppressTagKeyword = false;
59 
60  return Policy;
61 }
62 
63 /// Given a declaration \p D, return a human-readable string representing the
64 /// local scope in which it is declared, i.e. class(es) and method name. Returns
65 /// an empty string if it is not local.
66 std::string getLocalScope(const Decl *D) {
67  std::vector<std::string> Scopes;
68  const DeclContext *DC = D->getDeclContext();
69  auto GetName = [](const TypeDecl *D) {
70  if (!D->getDeclName().isEmpty()) {
71  PrintingPolicy Policy = D->getASTContext().getPrintingPolicy();
72  Policy.SuppressScope = true;
73  return declaredType(D).getAsString(Policy);
74  }
75  if (auto RD = dyn_cast<RecordDecl>(D))
76  return ("(anonymous " + RD->getKindName() + ")").str();
77  return std::string("");
78  };
79  while (DC) {
80  if (const TypeDecl *TD = dyn_cast<TypeDecl>(DC))
81  Scopes.push_back(GetName(TD));
82  else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
83  Scopes.push_back(FD->getNameAsString());
84  DC = DC->getParent();
85  }
86 
87  return llvm::join(llvm::reverse(Scopes), "::");
88 }
89 
90 /// Returns the human-readable representation for namespace containing the
91 /// declaration \p D. Returns empty if it is contained global namespace.
92 std::string getNamespaceScope(const Decl *D) {
93  const DeclContext *DC = D->getDeclContext();
94 
95  if (const TagDecl *TD = dyn_cast<TagDecl>(DC))
96  return getNamespaceScope(TD);
97  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
98  return getNamespaceScope(FD);
99  if (const NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(DC)) {
100  // Skip inline/anon namespaces.
101  if (NSD->isInline() || NSD->isAnonymousNamespace())
102  return getNamespaceScope(NSD);
103  }
104  if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
105  return printQualifiedName(*ND);
106 
107  return "";
108 }
109 
110 std::string printDefinition(const Decl *D) {
111  std::string Definition;
112  llvm::raw_string_ostream OS(Definition);
113  PrintingPolicy Policy =
114  printingPolicyForDecls(D->getASTContext().getPrintingPolicy());
115  Policy.IncludeTagDefinition = false;
116  Policy.SuppressTemplateArgsInCXXConstructors = true;
117  Policy.SuppressTagKeyword = true;
118  D->print(OS, Policy);
119  OS.flush();
120  return Definition;
121 }
122 
123 std::string printType(QualType QT, const PrintingPolicy &Policy) {
124  // TypePrinter doesn't resolve decltypes, so resolve them here.
125  // FIXME: This doesn't handle composite types that contain a decltype in them.
126  // We should rather have a printing policy for that.
127  while (!QT.isNull() && QT->isDecltypeType())
128  QT = QT->getAs<DecltypeType>()->getUnderlyingType();
129  return QT.getAsString(Policy);
130 }
131 
132 std::string printType(const TemplateTypeParmDecl *TTP) {
133  std::string Res = TTP->wasDeclaredWithTypename() ? "typename" : "class";
134  if (TTP->isParameterPack())
135  Res += "...";
136  return Res;
137 }
138 
139 std::string printType(const NonTypeTemplateParmDecl *NTTP,
140  const PrintingPolicy &PP) {
141  std::string Res = printType(NTTP->getType(), PP);
142  if (NTTP->isParameterPack())
143  Res += "...";
144  return Res;
145 }
146 
147 std::string printType(const TemplateTemplateParmDecl *TTP,
148  const PrintingPolicy &PP) {
149  std::string Res;
150  llvm::raw_string_ostream OS(Res);
151  OS << "template <";
152  llvm::StringRef Sep = "";
153  for (const Decl *Param : *TTP->getTemplateParameters()) {
154  OS << Sep;
155  Sep = ", ";
156  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
157  OS << printType(TTP);
158  else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
159  OS << printType(NTTP, PP);
160  else if (const auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param))
161  OS << printType(TTPD, PP);
162  }
163  // FIXME: TemplateTemplateParameter doesn't store the info on whether this
164  // param was a "typename" or "class".
165  OS << "> class";
166  return OS.str();
167 }
168 
169 std::vector<HoverInfo::Param>
170 fetchTemplateParameters(const TemplateParameterList *Params,
171  const PrintingPolicy &PP) {
172  assert(Params);
173  std::vector<HoverInfo::Param> TempParameters;
174 
175  for (const Decl *Param : *Params) {
176  HoverInfo::Param P;
177  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
178  P.Type = printType(TTP);
179 
180  if (!TTP->getName().empty())
181  P.Name = TTP->getNameAsString();
182 
183  if (TTP->hasDefaultArgument())
184  P.Default = TTP->getDefaultArgument().getAsString(PP);
185  } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
186  P.Type = printType(NTTP, PP);
187 
188  if (IdentifierInfo *II = NTTP->getIdentifier())
189  P.Name = II->getName().str();
190 
191  if (NTTP->hasDefaultArgument()) {
192  P.Default.emplace();
193  llvm::raw_string_ostream Out(*P.Default);
194  NTTP->getDefaultArgument()->printPretty(Out, nullptr, PP);
195  }
196  } else if (const auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param)) {
197  P.Type = printType(TTPD, PP);
198 
199  if (!TTPD->getName().empty())
200  P.Name = TTPD->getNameAsString();
201 
202  if (TTPD->hasDefaultArgument()) {
203  P.Default.emplace();
204  llvm::raw_string_ostream Out(*P.Default);
205  TTPD->getDefaultArgument().getArgument().print(PP, Out);
206  }
207  }
208  TempParameters.push_back(std::move(P));
209  }
210 
211  return TempParameters;
212 }
213 
214 const FunctionDecl *getUnderlyingFunction(const Decl *D) {
215  // Extract lambda from variables.
216  if (const VarDecl *VD = llvm::dyn_cast<VarDecl>(D)) {
217  auto QT = VD->getType();
218  if (!QT.isNull()) {
219  while (!QT->getPointeeType().isNull())
220  QT = QT->getPointeeType();
221 
222  if (const auto *CD = QT->getAsCXXRecordDecl())
223  return CD->getLambdaCallOperator();
224  }
225  }
226 
227  // Non-lambda functions.
228  return D->getAsFunction();
229 }
230 
231 // Returns the decl that should be used for querying comments, either from index
232 // or AST.
233 const NamedDecl *getDeclForComment(const NamedDecl *D) {
234  if (const auto *TSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(D)) {
235  // Template may not be instantiated e.g. if the type didn't need to be
236  // complete; fallback to primary template.
237  if (TSD->getTemplateSpecializationKind() == TSK_Undeclared)
238  return TSD->getSpecializedTemplate();
239  if (const auto *TIP = TSD->getTemplateInstantiationPattern())
240  return TIP;
241  }
242  if (const auto *TSD = llvm::dyn_cast<VarTemplateSpecializationDecl>(D)) {
243  if (TSD->getTemplateSpecializationKind() == TSK_Undeclared)
244  return TSD->getSpecializedTemplate();
245  if (const auto *TIP = TSD->getTemplateInstantiationPattern())
246  return TIP;
247  }
248  if (const auto *FD = D->getAsFunction())
249  if (const auto *TIP = FD->getTemplateInstantiationPattern())
250  return TIP;
251  return D;
252 }
253 
254 // Look up information about D from the index, and add it to Hover.
255 void enhanceFromIndex(HoverInfo &Hover, const NamedDecl &ND,
256  const SymbolIndex *Index) {
257  assert(&ND == getDeclForComment(&ND));
258  // We only add documentation, so don't bother if we already have some.
259  if (!Hover.Documentation.empty() || !Index)
260  return;
261 
262  // Skip querying for non-indexable symbols, there's no point.
263  // We're searching for symbols that might be indexed outside this main file.
264  if (!SymbolCollector::shouldCollectSymbol(ND, ND.getASTContext(),
265  SymbolCollector::Options(),
266  /*IsMainFileOnly=*/false))
267  return;
268  auto ID = getSymbolID(&ND);
269  if (!ID)
270  return;
271  LookupRequest Req;
272  Req.IDs.insert(*ID);
273  Index->lookup(Req, [&](const Symbol &S) {
274  Hover.Documentation = std::string(S.Documentation);
275  });
276 }
277 
278 // Default argument might exist but be unavailable, in the case of unparsed
279 // arguments for example. This function returns the default argument if it is
280 // available.
281 const Expr *getDefaultArg(const ParmVarDecl *PVD) {
282  // Default argument can be unparsed or uninstantiated. For the former we
283  // can't do much, as token information is only stored in Sema and not
284  // attached to the AST node. For the latter though, it is safe to proceed as
285  // the expression is still valid.
286  if (!PVD->hasDefaultArg() || PVD->hasUnparsedDefaultArg())
287  return nullptr;
288  return PVD->hasUninstantiatedDefaultArg() ? PVD->getUninstantiatedDefaultArg()
289  : PVD->getDefaultArg();
290 }
291 
292 HoverInfo::Param toHoverInfoParam(const ParmVarDecl *PVD,
293  const PrintingPolicy &Policy) {
294  HoverInfo::Param Out;
295  Out.Type = printType(PVD->getType(), Policy);
296  if (!PVD->getName().empty())
297  Out.Name = PVD->getNameAsString();
298  if (const Expr *DefArg = getDefaultArg(PVD)) {
299  Out.Default.emplace();
300  llvm::raw_string_ostream OS(*Out.Default);
301  DefArg->printPretty(OS, nullptr, Policy);
302  }
303  return Out;
304 }
305 
306 // Populates Type, ReturnType, and Parameters for function-like decls.
307 void fillFunctionTypeAndParams(HoverInfo &HI, const Decl *D,
308  const FunctionDecl *FD,
309  const PrintingPolicy &Policy) {
310  HI.Parameters.emplace();
311  for (const ParmVarDecl *PVD : FD->parameters())
312  HI.Parameters->emplace_back(toHoverInfoParam(PVD, Policy));
313 
314  // We don't want any type info, if name already contains it. This is true for
315  // constructors/destructors and conversion operators.
316  const auto NK = FD->getDeclName().getNameKind();
317  if (NK == DeclarationName::CXXConstructorName ||
318  NK == DeclarationName::CXXDestructorName ||
319  NK == DeclarationName::CXXConversionFunctionName)
320  return;
321 
322  HI.ReturnType = printType(FD->getReturnType(), Policy);
323  QualType QT = FD->getType();
324  if (const VarDecl *VD = llvm::dyn_cast<VarDecl>(D)) // Lambdas
325  QT = VD->getType().getDesugaredType(D->getASTContext());
326  HI.Type = printType(QT, Policy);
327  // FIXME: handle variadics.
328 }
329 
330 llvm::Optional<std::string> printExprValue(const Expr *E,
331  const ASTContext &Ctx) {
332  // InitListExpr has two forms, syntactic and semantic. They are the same thing
333  // (refer to a same AST node) in most cases.
334  // When they are different, RAV returns the syntactic form, and we should feed
335  // the semantic form to EvaluateAsRValue.
336  if (const auto *ILE = llvm::dyn_cast<InitListExpr>(E)) {
337  if (!ILE->isSemanticForm())
338  E = ILE->getSemanticForm();
339  }
340 
341  // Evaluating [[foo]]() as "&foo" isn't useful, and prevents us walking up
342  // to the enclosing call.
343  QualType T = E->getType();
344  if (T.isNull() || T->isFunctionType() || T->isFunctionPointerType() ||
345  T->isFunctionReferenceType())
346  return llvm::None;
347 
348  Expr::EvalResult Constant;
349  // Attempt to evaluate. If expr is dependent, evaluation crashes!
350  if (E->isValueDependent() || !E->EvaluateAsRValue(Constant, Ctx) ||
351  // Disable printing for record-types, as they are usually confusing and
352  // might make clang crash while printing the expressions.
353  Constant.Val.isStruct() || Constant.Val.isUnion())
354  return llvm::None;
355 
356  // Show enums symbolically, not numerically like APValue::printPretty().
357  if (T->isEnumeralType() && Constant.Val.getInt().getMinSignedBits() <= 64) {
358  // Compare to int64_t to avoid bit-width match requirements.
359  int64_t Val = Constant.Val.getInt().getExtValue();
360  for (const EnumConstantDecl *ECD :
361  T->castAs<EnumType>()->getDecl()->enumerators())
362  if (ECD->getInitVal() == Val)
363  return llvm::formatv("{0} ({1})", ECD->getNameAsString(), Val).str();
364  }
365  return Constant.Val.getAsString(Ctx, T);
366 }
367 
368 llvm::Optional<std::string> printExprValue(const SelectionTree::Node *N,
369  const ASTContext &Ctx) {
370  for (; N; N = N->Parent) {
371  // Try to evaluate the first evaluatable enclosing expression.
372  if (const Expr *E = N->ASTNode.get<Expr>()) {
373  if (auto Val = printExprValue(E, Ctx))
374  return Val;
375  } else if (N->ASTNode.get<Decl>() || N->ASTNode.get<Stmt>()) {
376  // Refuse to cross certain non-exprs. (TypeLoc are OK as part of Exprs).
377  // This tries to ensure we're showing a value related to the cursor.
378  break;
379  }
380  }
381  return llvm::None;
382 }
383 
384 llvm::Optional<StringRef> fieldName(const Expr *E) {
385  const auto *ME = llvm::dyn_cast<MemberExpr>(E->IgnoreCasts());
386  if (!ME || !llvm::isa<CXXThisExpr>(ME->getBase()->IgnoreCasts()))
387  return llvm::None;
388  const auto *Field = llvm::dyn_cast<FieldDecl>(ME->getMemberDecl());
389  if (!Field || !Field->getDeclName().isIdentifier())
390  return llvm::None;
391  return Field->getDeclName().getAsIdentifierInfo()->getName();
392 }
393 
394 // If CMD is of the form T foo() { return FieldName; } then returns "FieldName".
395 llvm::Optional<StringRef> getterVariableName(const CXXMethodDecl *CMD) {
396  assert(CMD->hasBody());
397  if (CMD->getNumParams() != 0 || CMD->isVariadic())
398  return llvm::None;
399  const auto *Body = llvm::dyn_cast<CompoundStmt>(CMD->getBody());
400  const auto *OnlyReturn = (Body && Body->size() == 1)
401  ? llvm::dyn_cast<ReturnStmt>(Body->body_front())
402  : nullptr;
403  if (!OnlyReturn || !OnlyReturn->getRetValue())
404  return llvm::None;
405  return fieldName(OnlyReturn->getRetValue());
406 }
407 
408 // If CMD is one of the forms:
409 // void foo(T arg) { FieldName = arg; }
410 // R foo(T arg) { FieldName = arg; return *this; }
411 // then returns "FieldName"
412 llvm::Optional<StringRef> setterVariableName(const CXXMethodDecl *CMD) {
413  assert(CMD->hasBody());
414  if (CMD->isConst() || CMD->getNumParams() != 1 || CMD->isVariadic())
415  return llvm::None;
416  const ParmVarDecl *Arg = CMD->getParamDecl(0);
417  if (Arg->isParameterPack())
418  return llvm::None;
419 
420  const auto *Body = llvm::dyn_cast<CompoundStmt>(CMD->getBody());
421  if (!Body || Body->size() == 0 || Body->size() > 2)
422  return llvm::None;
423  // If the second statement exists, it must be `return this` or `return *this`.
424  if (Body->size() == 2) {
425  auto *Ret = llvm::dyn_cast<ReturnStmt>(Body->body_back());
426  if (!Ret || !Ret->getRetValue())
427  return llvm::None;
428  const Expr *RetVal = Ret->getRetValue()->IgnoreCasts();
429  if (const auto *UO = llvm::dyn_cast<UnaryOperator>(RetVal)) {
430  if (UO->getOpcode() != UO_Deref)
431  return llvm::None;
432  RetVal = UO->getSubExpr()->IgnoreCasts();
433  }
434  if (!llvm::isa<CXXThisExpr>(RetVal))
435  return llvm::None;
436  }
437  // The first statement must be an assignment of the arg to a field.
438  const Expr *LHS, *RHS;
439  if (const auto *BO = llvm::dyn_cast<BinaryOperator>(Body->body_front())) {
440  if (BO->getOpcode() != BO_Assign)
441  return llvm::None;
442  LHS = BO->getLHS();
443  RHS = BO->getRHS();
444  } else if (const auto *COCE =
445  llvm::dyn_cast<CXXOperatorCallExpr>(Body->body_front())) {
446  if (COCE->getOperator() != OO_Equal || COCE->getNumArgs() != 2)
447  return llvm::None;
448  LHS = COCE->getArg(0);
449  RHS = COCE->getArg(1);
450  } else {
451  return llvm::None;
452  }
453  auto *DRE = llvm::dyn_cast<DeclRefExpr>(RHS->IgnoreCasts());
454  if (!DRE || DRE->getDecl() != Arg)
455  return llvm::None;
456  return fieldName(LHS);
457 }
458 
459 std::string synthesizeDocumentation(const NamedDecl *ND) {
460  if (const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(ND)) {
461  // Is this an ordinary, non-static method whose definition is visible?
462  if (CMD->getDeclName().isIdentifier() && !CMD->isStatic() &&
463  (CMD = llvm::dyn_cast_or_null<CXXMethodDecl>(CMD->getDefinition())) &&
464  CMD->hasBody()) {
465  if (const auto GetterField = getterVariableName(CMD))
466  return llvm::formatv("Trivial accessor for `{0}`.", *GetterField);
467  if (const auto SetterField = setterVariableName(CMD))
468  return llvm::formatv("Trivial setter for `{0}`.", *SetterField);
469  }
470  }
471  return "";
472 }
473 
474 /// Generate a \p Hover object given the declaration \p D.
475 HoverInfo getHoverContents(const NamedDecl *D, const SymbolIndex *Index) {
476  HoverInfo HI;
477  const ASTContext &Ctx = D->getASTContext();
478 
479  HI.AccessSpecifier = getAccessSpelling(D->getAccess()).str();
480  HI.NamespaceScope = getNamespaceScope(D);
481  if (!HI.NamespaceScope->empty())
482  HI.NamespaceScope->append("::");
483  HI.LocalScope = getLocalScope(D);
484  if (!HI.LocalScope.empty())
485  HI.LocalScope.append("::");
486 
487  PrintingPolicy Policy = printingPolicyForDecls(Ctx.getPrintingPolicy());
488  HI.Name = printName(Ctx, *D);
489  const auto *CommentD = getDeclForComment(D);
490  HI.Documentation = getDeclComment(Ctx, *CommentD);
491  enhanceFromIndex(HI, *CommentD, Index);
492  if (HI.Documentation.empty())
493  HI.Documentation = synthesizeDocumentation(D);
494 
495  HI.Kind = index::getSymbolInfo(D).Kind;
496 
497  // Fill in template params.
498  if (const TemplateDecl *TD = D->getDescribedTemplate()) {
499  HI.TemplateParameters =
500  fetchTemplateParameters(TD->getTemplateParameters(), Policy);
501  D = TD;
502  } else if (const FunctionDecl *FD = D->getAsFunction()) {
503  if (const auto *FTD = FD->getDescribedTemplate()) {
504  HI.TemplateParameters =
505  fetchTemplateParameters(FTD->getTemplateParameters(), Policy);
506  D = FTD;
507  }
508  }
509 
510  // Fill in types and params.
511  if (const FunctionDecl *FD = getUnderlyingFunction(D))
512  fillFunctionTypeAndParams(HI, D, FD, Policy);
513  else if (const auto *VD = dyn_cast<ValueDecl>(D))
514  HI.Type = printType(VD->getType(), Policy);
515  else if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(D))
516  HI.Type = TTP->wasDeclaredWithTypename() ? "typename" : "class";
517  else if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(D))
518  HI.Type = printType(TTP, Policy);
519 
520  // Fill in value with evaluated initializer if possible.
521  if (const auto *Var = dyn_cast<VarDecl>(D)) {
522  if (const Expr *Init = Var->getInit())
523  HI.Value = printExprValue(Init, Ctx);
524  } else if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
525  // Dependent enums (e.g. nested in template classes) don't have values yet.
526  if (!ECD->getType()->isDependentType())
527  HI.Value = ECD->getInitVal().toString(10);
528  }
529 
530  HI.Definition = printDefinition(D);
531  return HI;
532 }
533 
534 /// Generate a \p Hover object given the type \p T.
535 HoverInfo getHoverContents(QualType T, ASTContext &ASTCtx,
536  const SymbolIndex *Index) {
537  HoverInfo HI;
538 
539  if (const auto *D = T->getAsTagDecl()) {
540  HI.Name = printName(ASTCtx, *D);
541  HI.Kind = index::getSymbolInfo(D).Kind;
542 
543  const auto *CommentD = getDeclForComment(D);
544  HI.Documentation = getDeclComment(ASTCtx, *CommentD);
545  enhanceFromIndex(HI, *CommentD, Index);
546  } else {
547  // Builtin types
548  auto Policy = printingPolicyForDecls(ASTCtx.getPrintingPolicy());
549  Policy.SuppressTagKeyword = true;
550  HI.Name = T.getAsString(Policy);
551  }
552  return HI;
553 }
554 
555 /// Generate a \p Hover object given the macro \p MacroDecl.
556 HoverInfo getHoverContents(const DefinedMacro &Macro, ParsedAST &AST) {
557  HoverInfo HI;
558  SourceManager &SM = AST.getSourceManager();
559  HI.Name = std::string(Macro.Name);
560  HI.Kind = index::SymbolKind::Macro;
561  // FIXME: Populate documentation
562  // FIXME: Populate parameters
563 
564  // Try to get the full definition, not just the name
565  SourceLocation StartLoc = Macro.Info->getDefinitionLoc();
566  SourceLocation EndLoc = Macro.Info->getDefinitionEndLoc();
567  // Ensure that EndLoc is a valid offset. For example it might come from
568  // preamble, and source file might've changed, in such a scenario EndLoc still
569  // stays valid, but getLocForEndOfToken will fail as it is no longer a valid
570  // offset.
571  // Note that this check is just to ensure there's text data inside the range.
572  // It will still succeed even when the data inside the range is irrelevant to
573  // macro definition.
574  if (SM.getPresumedLoc(EndLoc, /*UseLineDirectives=*/false).isValid()) {
575  EndLoc = Lexer::getLocForEndOfToken(EndLoc, 0, SM, AST.getLangOpts());
576  bool Invalid;
577  StringRef Buffer = SM.getBufferData(SM.getFileID(StartLoc), &Invalid);
578  if (!Invalid) {
579  unsigned StartOffset = SM.getFileOffset(StartLoc);
580  unsigned EndOffset = SM.getFileOffset(EndLoc);
581  if (EndOffset <= Buffer.size() && StartOffset < EndOffset)
582  HI.Definition =
583  ("#define " + Buffer.substr(StartOffset, EndOffset - StartOffset))
584  .str();
585  }
586  }
587  return HI;
588 }
589 
590 bool isLiteral(const Expr *E) {
591  // Unfortunately there's no common base Literal classes inherits from
592  // (apart from Expr), therefore these exclusions.
593  return llvm::isa<CharacterLiteral>(E) || llvm::isa<CompoundLiteralExpr>(E) ||
594  llvm::isa<CXXBoolLiteralExpr>(E) ||
595  llvm::isa<CXXNullPtrLiteralExpr>(E) ||
596  llvm::isa<FixedPointLiteral>(E) || llvm::isa<FloatingLiteral>(E) ||
597  llvm::isa<ImaginaryLiteral>(E) || llvm::isa<IntegerLiteral>(E) ||
598  llvm::isa<StringLiteral>(E) || llvm::isa<UserDefinedLiteral>(E);
599 }
600 
601 llvm::StringLiteral getNameForExpr(const Expr *E) {
602  // FIXME: Come up with names for `special` expressions.
603  //
604  // It's an known issue for GCC5, https://godbolt.org/z/Z_tbgi. Work around
605  // that by using explicit conversion constructor.
606  //
607  // TODO: Once GCC5 is fully retired and not the minimal requirement as stated
608  // in `GettingStarted`, please remove the explicit conversion constructor.
609  return llvm::StringLiteral("expression");
610 }
611 
612 // Generates hover info for evaluatable expressions.
613 // FIXME: Support hover for literals (esp user-defined)
614 llvm::Optional<HoverInfo> getHoverContents(const Expr *E, ParsedAST &AST) {
615  // There's not much value in hovering over "42" and getting a hover card
616  // saying "42 is an int", similar for other literals.
617  if (isLiteral(E))
618  return llvm::None;
619 
620  HoverInfo HI;
621  // For expressions we currently print the type and the value, iff it is
622  // evaluatable.
623  if (auto Val = printExprValue(E, AST.getASTContext())) {
624  auto Policy =
625  printingPolicyForDecls(AST.getASTContext().getPrintingPolicy());
626  Policy.SuppressTagKeyword = true;
627  HI.Type = printType(E->getType(), Policy);
628  HI.Value = *Val;
629  HI.Name = std::string(getNameForExpr(E));
630  return HI;
631  }
632  return llvm::None;
633 }
634 
635 bool isParagraphBreak(llvm::StringRef Rest) {
636  return Rest.ltrim(" \t").startswith("\n");
637 }
638 
639 bool punctuationIndicatesLineBreak(llvm::StringRef Line) {
640  constexpr llvm::StringLiteral Punctuation = R"txt(.:,;!?)txt";
641 
642  Line = Line.rtrim();
643  return !Line.empty() && Punctuation.contains(Line.back());
644 }
645 
646 bool isHardLineBreakIndicator(llvm::StringRef Rest) {
647  // '-'/'*' md list, '@'/'\' documentation command, '>' md blockquote,
648  // '#' headings, '`' code blocks
649  constexpr llvm::StringLiteral LinebreakIndicators = R"txt(-*@>#`)txt";
650 
651  Rest = Rest.ltrim(" \t");
652  if (Rest.empty())
653  return false;
654 
655  if (LinebreakIndicators.contains(Rest.front()))
656  return true;
657 
658  if (llvm::isDigit(Rest.front())) {
659  llvm::StringRef AfterDigit = Rest.drop_while(llvm::isDigit);
660  if (AfterDigit.startswith(".") || AfterDigit.startswith(")"))
661  return true;
662  }
663  return false;
664 }
665 
666 bool isHardLineBreakAfter(llvm::StringRef Line, llvm::StringRef Rest) {
667  // Should we also consider whether Line is short?
668  return punctuationIndicatesLineBreak(Line) || isHardLineBreakIndicator(Rest);
669 }
670 
671 void addLayoutInfo(const NamedDecl &ND, HoverInfo &HI) {
672  if (ND.isInvalidDecl())
673  return;
674 
675  const auto &Ctx = ND.getASTContext();
676  if (auto *RD = llvm::dyn_cast<RecordDecl>(&ND)) {
677  if (auto Size = Ctx.getTypeSizeInCharsIfKnown(RD->getTypeForDecl()))
678  HI.Size = Size->getQuantity();
679  return;
680  }
681 
682  if (const auto *FD = llvm::dyn_cast<FieldDecl>(&ND)) {
683  const auto *Record = FD->getParent();
684  if (Record)
685  Record = Record->getDefinition();
686  if (Record && !Record->isInvalidDecl() && !Record->isDependentType()) {
687  HI.Offset = Ctx.getFieldOffset(FD) / 8;
688  if (auto Size = Ctx.getTypeSizeInCharsIfKnown(FD->getType()))
689  HI.Size = Size->getQuantity();
690  }
691  return;
692  }
693 }
694 
695 // If N is passed as argument to a function, fill HI.CalleeArgInfo with
696 // information about that argument.
697 void maybeAddCalleeArgInfo(const SelectionTree::Node *N, HoverInfo &HI,
698  const PrintingPolicy &Policy) {
699  const auto &OuterNode = N->outerImplicit();
700  if (!OuterNode.Parent)
701  return;
702  const auto *CE = OuterNode.Parent->ASTNode.get<CallExpr>();
703  if (!CE)
704  return;
705  const FunctionDecl *FD = CE->getDirectCallee();
706  // For non-function-call-like operatators (e.g. operator+, operator<<) it's
707  // not immediattely obvious what the "passed as" would refer to and, given
708  // fixed function signature, the value would be very low anyway, so we choose
709  // to not support that.
710  // Both variadic functions and operator() (especially relevant for lambdas)
711  // should be supported in the future.
712  if (!FD || FD->isOverloadedOperator() || FD->isVariadic())
713  return;
714 
715  // Find argument index for N.
716  for (unsigned I = 0; I < CE->getNumArgs() && I < FD->getNumParams(); ++I) {
717  if (CE->getArg(I) != OuterNode.ASTNode.get<Expr>())
718  continue;
719 
720  // Extract matching argument from function declaration.
721  if (const ParmVarDecl *PVD = FD->getParamDecl(I))
722  HI.CalleeArgInfo.emplace(toHoverInfoParam(PVD, Policy));
723  break;
724  }
725  if (!HI.CalleeArgInfo)
726  return;
727 
728  // If we found a matching argument, also figure out if it's a
729  // [const-]reference. For this we need to walk up the AST from the arg itself
730  // to CallExpr and check all implicit casts, constructor calls, etc.
731  HoverInfo::PassType PassType;
732  if (const auto *E = N->ASTNode.get<Expr>()) {
733  if (E->getType().isConstQualified())
734  PassType.PassBy = HoverInfo::PassType::ConstRef;
735  }
736 
737  for (auto *CastNode = N->Parent;
738  CastNode != OuterNode.Parent && !PassType.Converted;
739  CastNode = CastNode->Parent) {
740  if (const auto *ImplicitCast = CastNode->ASTNode.get<ImplicitCastExpr>()) {
741  switch (ImplicitCast->getCastKind()) {
742  case CK_NoOp:
743  case CK_DerivedToBase:
744  case CK_UncheckedDerivedToBase:
745  // If it was a reference before, it's still a reference.
746  if (PassType.PassBy != HoverInfo::PassType::Value)
747  PassType.PassBy = ImplicitCast->getType().isConstQualified()
750  break;
751  case CK_LValueToRValue:
752  case CK_ArrayToPointerDecay:
753  case CK_FunctionToPointerDecay:
754  case CK_NullToPointer:
755  case CK_NullToMemberPointer:
756  // No longer a reference, but we do not show this as type conversion.
757  PassType.PassBy = HoverInfo::PassType::Value;
758  break;
759  default:
760  PassType.PassBy = HoverInfo::PassType::Value;
761  PassType.Converted = true;
762  break;
763  }
764  } else if (const auto *CtorCall =
765  CastNode->ASTNode.get<CXXConstructExpr>()) {
766  // We want to be smart about copy constructors. They should not show up as
767  // type conversion, but instead as passing by value.
768  if (CtorCall->getConstructor()->isCopyConstructor())
769  PassType.PassBy = HoverInfo::PassType::Value;
770  else
771  PassType.Converted = true;
772  } else { // Unknown implicit node, assume type conversion.
773  PassType.PassBy = HoverInfo::PassType::Value;
774  PassType.Converted = true;
775  }
776  }
777 
778  HI.CallPassType.emplace(PassType);
779 }
780 
781 } // namespace
782 
783 llvm::Optional<HoverInfo> getHover(ParsedAST &AST, Position Pos,
784  format::FormatStyle Style,
785  const SymbolIndex *Index) {
786  const SourceManager &SM = AST.getSourceManager();
787  auto CurLoc = sourceLocationInMainFile(SM, Pos);
788  if (!CurLoc) {
789  llvm::consumeError(CurLoc.takeError());
790  return llvm::None;
791  }
792  const auto &TB = AST.getTokens();
793  auto TokensTouchingCursor = syntax::spelledTokensTouching(*CurLoc, TB);
794  // Early exit if there were no tokens around the cursor.
795  if (TokensTouchingCursor.empty())
796  return llvm::None;
797 
798  // To be used as a backup for highlighting the selected token, we use back as
799  // it aligns better with biases elsewhere (editors tend to send the position
800  // for the left of the hovered token).
801  CharSourceRange HighlightRange =
802  TokensTouchingCursor.back().range(SM).toCharRange(SM);
803  llvm::Optional<HoverInfo> HI;
804  // Macros and deducedtype only works on identifiers and auto/decltype keywords
805  // respectively. Therefore they are only trggered on whichever works for them,
806  // similar to SelectionTree::create().
807  for (const auto &Tok : TokensTouchingCursor) {
808  if (Tok.kind() == tok::identifier) {
809  // Prefer the identifier token as a fallback highlighting range.
810  HighlightRange = Tok.range(SM).toCharRange(SM);
811  if (auto M = locateMacroAt(Tok, AST.getPreprocessor())) {
812  HI = getHoverContents(*M, AST);
813  break;
814  }
815  } else if (Tok.kind() == tok::kw_auto || Tok.kind() == tok::kw_decltype) {
816  if (auto Deduced = getDeducedType(AST.getASTContext(), Tok.location())) {
817  HI = getHoverContents(*Deduced, AST.getASTContext(), Index);
818  HighlightRange = Tok.range(SM).toCharRange(SM);
819  break;
820  }
821  }
822  }
823 
824  // If it wasn't auto/decltype or macro, look for decls and expressions.
825  if (!HI) {
826  auto Offset = SM.getFileOffset(*CurLoc);
827  // Editors send the position on the left of the hovered character.
828  // So our selection tree should be biased right. (Tested with VSCode).
829  SelectionTree ST =
831  std::vector<const Decl *> Result;
832  if (const SelectionTree::Node *N = ST.commonAncestor()) {
833  // FIXME: Fill in HighlightRange with range coming from N->ASTNode.
834  auto Decls = explicitReferenceTargets(N->ASTNode, DeclRelation::Alias);
835  if (!Decls.empty()) {
836  HI = getHoverContents(Decls.front(), Index);
837  // Layout info only shown when hovering on the field/class itself.
838  if (Decls.front() == N->ASTNode.get<Decl>())
839  addLayoutInfo(*Decls.front(), *HI);
840  // Look for a close enclosing expression to show the value of.
841  if (!HI->Value)
842  HI->Value = printExprValue(N, AST.getASTContext());
843  maybeAddCalleeArgInfo(N, *HI, AST.getASTContext().getPrintingPolicy());
844  } else if (const Expr *E = N->ASTNode.get<Expr>()) {
845  HI = getHoverContents(E, AST);
846  }
847  // FIXME: support hovers for other nodes?
848  // - built-in types
849  }
850  }
851 
852  if (!HI)
853  return llvm::None;
854 
855  auto Replacements = format::reformat(
856  Style, HI->Definition, tooling::Range(0, HI->Definition.size()));
857  if (auto Formatted =
858  tooling::applyAllReplacements(HI->Definition, Replacements))
859  HI->Definition = *Formatted;
860  HI->SymRange = halfOpenToRange(SM, HighlightRange);
861 
862  return HI;
863 }
864 
867  // Header contains a text of the form:
868  // variable `var`
869  //
870  // class `X`
871  //
872  // function `foo`
873  //
874  // expression
875  //
876  // Note that we are making use of a level-3 heading because VSCode renders
877  // level 1 and 2 headers in a huge font, see
878  // https://github.com/microsoft/vscode/issues/88417 for details.
879  markup::Paragraph &Header = Output.addHeading(3);
880  if (Kind != index::SymbolKind::Unknown)
881  Header.appendText(index::getSymbolKindString(Kind)).appendSpace();
882  assert(!Name.empty() && "hover triggered on a nameless symbol");
883  Header.appendCode(Name);
884 
885  // Put a linebreak after header to increase readability.
886  Output.addRuler();
887  // Print Types on their own lines to reduce chances of getting line-wrapped by
888  // editor, as they might be long.
889  if (ReturnType) {
890  // For functions we display signature in a list form, e.g.:
891  // → `x`
892  // Parameters:
893  // - `bool param1`
894  // - `int param2 = 5`
895  Output.addParagraph().appendText("→ ").appendCode(*ReturnType);
896  if (Parameters && !Parameters->empty()) {
897  Output.addParagraph().appendText("Parameters: ");
898  markup::BulletList &L = Output.addBulletList();
899  for (const auto &Param : *Parameters) {
900  std::string Buffer;
901  llvm::raw_string_ostream OS(Buffer);
902  OS << Param;
903  L.addItem().addParagraph().appendCode(std::move(OS.str()));
904  }
905  }
906  } else if (Type) {
907  Output.addParagraph().appendText("Type: ").appendCode(*Type);
908  }
909 
910  if (Value) {
911  markup::Paragraph &P = Output.addParagraph();
912  P.appendText("Value = ");
913  P.appendCode(*Value);
914  }
915 
916  if (Offset)
917  Output.addParagraph().appendText(
918  llvm::formatv("Offset: {0} byte{1}", *Offset, *Offset == 1 ? "" : "s")
919  .str());
920  if (Size)
921  Output.addParagraph().appendText(
922  llvm::formatv("Size: {0} byte{1}", *Size, *Size == 1 ? "" : "s").str());
923 
924  if (CalleeArgInfo) {
925  assert(CallPassType);
926  std::string Buffer;
927  llvm::raw_string_ostream OS(Buffer);
928  OS << "Passed ";
929  if (CallPassType->PassBy != HoverInfo::PassType::Value) {
930  OS << "by ";
932  OS << "const ";
933  OS << "reference ";
934  }
935  if (CalleeArgInfo->Name)
936  OS << "as " << CalleeArgInfo->Name;
937  if (CallPassType->Converted && CalleeArgInfo->Type)
938  OS << " (converted to " << CalleeArgInfo->Type << ")";
939  Output.addParagraph().appendText(OS.str());
940  }
941 
942  if (!Documentation.empty())
944 
945  if (!Definition.empty()) {
946  Output.addRuler();
947  std::string ScopeComment;
948  // Drop trailing "::".
949  if (!LocalScope.empty()) {
950  // Container name, e.g. class, method, function.
951  // We might want to propagate some info about container type to print
952  // function foo, class X, method X::bar, etc.
953  ScopeComment =
954  "// In " + llvm::StringRef(LocalScope).rtrim(':').str() + '\n';
955  } else if (NamespaceScope && !NamespaceScope->empty()) {
956  ScopeComment = "// In namespace " +
957  llvm::StringRef(*NamespaceScope).rtrim(':').str() + '\n';
958  }
959  std::string DefinitionWithAccess = !AccessSpecifier.empty()
960  ? AccessSpecifier + ": " + Definition
961  : Definition;
962  // Note that we don't print anything for global namespace, to not annoy
963  // non-c++ projects or projects that are not making use of namespaces.
964  Output.addCodeBlock(ScopeComment + DefinitionWithAccess);
965  }
966 
967  return Output;
968 }
969 
970 // If the backtick at `Offset` starts a probable quoted range, return the range
971 // (including the quotes).
972 llvm::Optional<llvm::StringRef> getBacktickQuoteRange(llvm::StringRef Line,
973  unsigned Offset) {
974  assert(Line[Offset] == '`');
975 
976  // The open-quote is usually preceded by whitespace.
977  llvm::StringRef Prefix = Line.substr(0, Offset);
978  constexpr llvm::StringLiteral BeforeStartChars = " \t(=";
979  if (!Prefix.empty() && !BeforeStartChars.contains(Prefix.back()))
980  return llvm::None;
981 
982  // The quoted string must be nonempty and usually has no leading/trailing ws.
983  auto Next = Line.find('`', Offset + 1);
984  if (Next == llvm::StringRef::npos)
985  return llvm::None;
986  llvm::StringRef Contents = Line.slice(Offset + 1, Next);
987  if (Contents.empty() || isWhitespace(Contents.front()) ||
988  isWhitespace(Contents.back()))
989  return llvm::None;
990 
991  // The close-quote is usually followed by whitespace or punctuation.
992  llvm::StringRef Suffix = Line.substr(Next + 1);
993  constexpr llvm::StringLiteral AfterEndChars = " \t)=.,;:";
994  if (!Suffix.empty() && !AfterEndChars.contains(Suffix.front()))
995  return llvm::None;
996 
997  return Line.slice(Offset, Next + 1);
998 }
999 
1001  // Probably this is appendText(Line), but scan for something interesting.
1002  for (unsigned I = 0; I < Line.size(); ++I) {
1003  switch (Line[I]) {
1004  case '`':
1005  if (auto Range = getBacktickQuoteRange(Line, I)) {
1006  Out.appendText(Line.substr(0, I));
1007  Out.appendCode(Range->trim("`"), /*Preserve=*/true);
1008  return parseDocumentationLine(Line.substr(I + Range->size()), Out);
1009  }
1010  break;
1011  }
1012  }
1013  Out.appendText(Line).appendSpace();
1014 }
1015 
1016 void parseDocumentation(llvm::StringRef Input, markup::Document &Output) {
1017  std::vector<llvm::StringRef> ParagraphLines;
1018  auto FlushParagraph = [&] {
1019  if (ParagraphLines.empty())
1020  return;
1021  auto &P = Output.addParagraph();
1022  for (llvm::StringRef Line : ParagraphLines)
1024  ParagraphLines.clear();
1025  };
1026 
1027  llvm::StringRef Line, Rest;
1028  for (std::tie(Line, Rest) = Input.split('\n');
1029  !(Line.empty() && Rest.empty());
1030  std::tie(Line, Rest) = Rest.split('\n')) {
1031 
1032  // After a linebreak remove spaces to avoid 4 space markdown code blocks.
1033  // FIXME: make FlushParagraph handle this.
1034  Line = Line.ltrim();
1035  if (!Line.empty())
1036  ParagraphLines.push_back(Line);
1037 
1038  if (isParagraphBreak(Rest) || isHardLineBreakAfter(Line, Rest)) {
1039  FlushParagraph();
1040  }
1041  }
1042  FlushParagraph();
1043 }
1044 
1045 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
1046  const HoverInfo::Param &P) {
1047  std::vector<llvm::StringRef> Output;
1048  if (P.Type)
1049  Output.push_back(*P.Type);
1050  if (P.Name)
1051  Output.push_back(*P.Name);
1052  OS << llvm::join(Output, " ");
1053  if (P.Default)
1054  OS << " = " << *P.Default;
1055  return OS;
1056 }
1057 
1058 } // namespace clangd
1059 } // namespace clang
Range
CharSourceRange Range
SourceRange for the file name.
Definition: IncludeOrderCheck.cpp:38
clang::clangd::getDeclComment
std::string getDeclComment(const ASTContext &Ctx, const NamedDecl &Decl)
Similar to getDocComment, but returns the comment for a NamedDecl.
Definition: CodeCompletionStrings.cpp:73
clang::clangd::markup::BulletList
Represents a sequence of one or more documents.
Definition: Markup.h:80
Base
std::unique_ptr< GlobalCompilationDatabase > Base
Definition: GlobalCompilationDatabaseTests.cpp:85
Suffix
std::string Suffix
Definition: AddUsing.cpp:96
clang::clangd::locateMacroAt
llvm::Optional< DefinedMacro > locateMacroAt(const syntax::Token &SpelledTok, Preprocessor &PP)
Gets the macro referenced by SpelledTok.
Definition: SourceCode.cpp:968
Selection.h
E
const Expr * E
Definition: AvoidBindCheck.cpp:88
clang::clangd::ParsedAST::getASTContext
ASTContext & getASTContext()
Note that the returned ast will not contain decls from the preamble that were not deserialized during...
Definition: ParsedAST.cpp:471
clang::clangd::declaredType
QualType declaredType(const TypeDecl *D)
Definition: AST.cpp:320
clang::clangd::HoverInfo::Offset
llvm::Optional< uint64_t > Offset
Contains the offset of fields within the enclosing class.
Definition: Hover.h:79
clang::clangd::markup::Paragraph
Represents parts of the markup that can contain strings, like inline code, code block or plain text.
Definition: Markup.h:43
FormatStyle
static cl::opt< std::string > FormatStyle("format-style", cl::desc(R"( Style for formatting code around applied fixes: - 'none' (default) turns off formatting - 'file' (literally 'file', not a placeholder) uses .clang-format file in the closest parent directory - '{ <json> }' specifies options inline, e.g. -format-style='{BasedOnStyle: llvm, IndentWidth: 8}' - 'llvm', 'google', 'webkit', 'mozilla' See clang-format documentation for the up-to-date information about formatting styles and options. This option overrides the 'FormatStyle` option in .clang-tidy file, if any. )"), cl::init("none"), cl::cat(ClangTidyCategory))
clang::clangd::SymbolCollector::shouldCollectSymbol
static bool shouldCollectSymbol(const NamedDecl &ND, const ASTContext &ASTCtx, const Options &Opts, bool IsMainFileSymbol)
Returns true is ND should be collected.
Definition: SymbolCollector.cpp:200
clang::clangd::HoverInfo::Kind
index::SymbolKind Kind
Definition: Hover.h:57
clang::clangd::CompletionItemKind::Field
clang::clangd::markup::Paragraph::appendText
Paragraph & appendText(llvm::StringRef Text)
Append plain text to the end of the string.
Definition: Markup.cpp:422
clang::clangd::Punctuation
Definition: FuzzyMatch.h:45
Contents
llvm::StringRef Contents
Definition: DraftStoreTests.cpp:22
clang::clangd::HoverInfo::CallPassType
llvm::Optional< PassType > CallPassType
Definition: Hover.h:93
clang::clangd::markup::Document::addParagraph
Paragraph & addParagraph()
Adds a semantical block that will be separate from others.
Definition: Markup.cpp:472
Ctx
Context Ctx
Definition: TUScheduler.cpp:324
clang::clangd::getHover
llvm::Optional< HoverInfo > getHover(ParsedAST &AST, Position Pos, format::FormatStyle Style, const SymbolIndex *Index)
Get the hover information when hovering at Pos.
Definition: Hover.cpp:783
clang::clangd::markup::Document
A format-agnostic representation for structured text.
Definition: Markup.h:94
clang::tidy::cppcoreguidelines::join
static std::string join(ArrayRef< SpecialMemberFunctionsCheck::SpecialMemberFunctionKind > SMFS, llvm::StringRef AndOr)
Definition: SpecialMemberFunctionsCheck.cpp:83
clang::clangd::TextDocumentSyncKind::None
Documents should not be synced at all.
FindTarget.h
clang::clangd::getDeducedType
llvm::Optional< QualType > getDeducedType(ASTContext &ASTCtx, SourceLocation Loc)
Retrieves the deduced type at a given location (auto, decltype).
Definition: AST.cpp:417
clang::clangd::ParsedAST::getLangOpts
const LangOptions & getLangOpts() const
Definition: ParsedAST.h:81
clang::clangd::HoverInfo::Type
llvm::Optional< std::string > Type
Pretty-printed variable type.
Definition: Hover.h:67
clang::clangd::HighlightingKind::Macro
clang::clangd::explicitReferenceTargets
llvm::SmallVector< const NamedDecl *, 1 > explicitReferenceTargets(DynTypedNode N, DeclRelationSet Mask)
Definition: FindTarget.cpp:578
clang::clangd::HoverInfo::Parameters
llvm::Optional< std::vector< Param > > Parameters
Set for functions, lambdas and macros with parameters.
Definition: Hover.h:71
clang::clangd::HoverInfo::Size
llvm::Optional< uint64_t > Size
Contains the byte-size of fields and types where it's interesting.
Definition: Hover.h:77
clang::clangd::markup::Paragraph::appendSpace
Paragraph & appendSpace()
Ensure there is space between the surrounding chunks.
Definition: Markup.cpp:416
Hover.h
clang::clangd::CompletionItemKind::Constant
clang::clangd::HoverInfo::Name
std::string Name
Name of the symbol, does not contain any "::".
Definition: Hover.h:55
Offset
size_t Offset
Definition: CodeComplete.cpp:1044
clang::clangd::halfOpenToRange
Range halfOpenToRange(const SourceManager &SM, CharSourceRange R)
Definition: SourceCode.cpp:471
clang::clangd::Position
Definition: Protocol.h:144
clang::clangd::HoverInfo::Definition
std::string Definition
Source code containing the definition of the symbol.
Definition: Hover.h:60
clang::clangd::SymbolIndex::lookup
virtual void lookup(const LookupRequest &Req, llvm::function_ref< void(const Symbol &)> Callback) const =0
Looks up symbols with any of the given symbol IDs and applies Callback on each matched symbol.
clang::clangd::printName
std::string printName(const ASTContext &Ctx, const NamedDecl &ND)
Prints unqualified name of the decl for the purpose of displaying it to the user.
Definition: AST.cpp:207
Decl
const FunctionDecl * Decl
Definition: AvoidBindCheck.cpp:100
CodeCompletionStrings.h
clang::clangd::SelectionTree::createRight
static SelectionTree createRight(ASTContext &AST, const syntax::TokenBuffer &Tokens, unsigned Begin, unsigned End)
Definition: Selection.cpp:787
Line
int Line
Definition: PreprocessorTracker.cpp:513
clang::clangd::printQualifiedName
std::string printQualifiedName(const NamedDecl &ND)
Returns the qualified name of ND.
Definition: AST.cpp:168
Logger.h
Markup.h
clang::clangd::getSymbolInfo
std::vector< SymbolDetails > getSymbolInfo(ParsedAST &AST, Position Pos)
Get info about symbols at Pos.
Definition: XRefs.cpp:1123
clang::clangd::HoverInfo::AccessSpecifier
std::string AccessSpecifier
Access specifier for declarations inside class/struct/unions, empty for others.
Definition: Hover.h:64
clang::clangd::HoverInfo::PassType::Ref
Definition: Hover.h:85
clang::clangd::HoverInfo::Param::Name
llvm::Optional< std::string > Name
None for unnamed parameters.
Definition: Hover.h:35
clang::clangd::SelectionTree
Definition: Selection.h:76
clang::clangd::operator<<
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, const CodeCompletion &C)
Definition: CodeComplete.cpp:1912
clang::clangd::HoverInfo::NamespaceScope
llvm::Optional< std::string > NamespaceScope
For a variable named Bar, declared in clang::clangd::Foo::getFoo the following fields will hold:
Definition: Hover.h:50
clang::clangd::HoverInfo::Param::Type
llvm::Optional< std::string > Type
The pretty-printed parameter type, e.g.
Definition: Hover.h:33
clang::clangd::HoverInfo::Param::Default
llvm::Optional< std::string > Default
None if no default is provided.
Definition: Hover.h:37
Output
std::string Output
Definition: TraceTests.cpp:161
clang::clangd::SelectionTree::Node
Definition: Selection.h:122
clang::tidy::bugprone::PP
static Preprocessor * PP
Definition: BadSignalToKillThreadCheck.cpp:29
clang::clangd::markup::Paragraph::appendCode
Paragraph & appendCode(llvm::StringRef Code, bool Preserve=false)
Append inline code, this translates to the ` block in markdown.
Definition: Markup.cpp:435
clang::clangd::parseDocumentationLine
void parseDocumentationLine(llvm::StringRef Line, markup::Paragraph &Out)
Definition: Hover.cpp:1000
clang::clangd::SelectionTree::commonAncestor
const Node * commonAncestor() const
Definition: Selection.cpp:817
SourceCode.h
Index
const SymbolIndex * Index
Definition: Dexp.cpp:95
clang::clangd::ParsedAST::getPreprocessor
Preprocessor & getPreprocessor()
Definition: ParsedAST.cpp:477
clang::clangd::SymbolIndex
Interface for symbol indexes that can be used for searching or matching symbols among a set of symbol...
Definition: Index.h:85
clang::clangd::HoverInfo::ReturnType
llvm::Optional< std::string > ReturnType
Set for functions and lambdas.
Definition: Hover.h:69
CE
CaptureExpr CE
Definition: AvoidBindCheck.cpp:67
clang::clangd::HoverInfo::LocalScope
std::string LocalScope
Remaining named contexts in symbol's qualified name, empty string means symbol is not local.
Definition: Hover.h:53
clang::clangd::HoverInfo::present
markup::Document present() const
Produce a user-readable information.
Definition: Hover.cpp:865
clang::clangd::Range
Definition: Protocol.h:173
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
OS
llvm::raw_string_ostream OS
Definition: TraceTests.cpp:162
clang::clangd::HoverInfo::CalleeArgInfo
llvm::Optional< Param > CalleeArgInfo
Definition: Hover.h:82
clang::clangd::ParsedAST::getTokens
const syntax::TokenBuffer & getTokens() const
Tokens recorded while parsing the main file.
Definition: ParsedAST.h:103
clang::doc::Record
llvm::SmallVector< uint64_t, 1024 > Record
Definition: BitcodeReader.cpp:18
clang::clangd::HoverInfo::Value
llvm::Optional< std::string > Value
Contains the evaluated value of the symbol if available.
Definition: Hover.h:75
clang::clangd::parseDocumentation
void parseDocumentation(llvm::StringRef Input, markup::Document &Output)
Definition: Hover.cpp:1016
SymbolCollector.h
clang::clangd::getSymbolID
llvm::Optional< SymbolID > getSymbolID(const Decl *D)
Gets the symbol ID for a declaration, if possible.
Definition: AST.cpp:285
clang::clangd::getBacktickQuoteRange
llvm::Optional< llvm::StringRef > getBacktickQuoteRange(llvm::StringRef Line, unsigned Offset)
Definition: Hover.cpp:972
clang::clangd::HoverInfo::PassType::Value
Definition: Hover.h:85
clang::clangd::ParsedAST
Stores and provides access to parsed AST.
Definition: ParsedAST.h:48
clang::clangd::markup::BulletList::addItem
class Document & addItem()
Definition: Markup.cpp:455
Pos
Position Pos
Definition: SourceCode.cpp:649
Out
CompiledFragmentImpl & Out
Definition: ConfigCompile.cpp:70
clang::clangd::RefKind::Definition
clang::clangd::ParsedAST::getSourceManager
SourceManager & getSourceManager()
Definition: ParsedAST.h:74
clang::clangd::HoverInfo::Param
Represents parameters of a function, a template or a macro.
Definition: Hover.h:30
clang::clangd::HoverInfo::PassType::ConstRef
Definition: Hover.h:85
clang::clangd::printType
std::string printType(const QualType QT, const DeclContext &CurContext)
Returns a QualType as string.
Definition: AST.cpp:304
clang::clangd::sourceLocationInMainFile
llvm::Expected< SourceLocation > sourceLocationInMainFile(const SourceManager &SM, Position P)
Return the file location, corresponding to P.
Definition: SourceCode.cpp:461
clang::clangd::HoverInfo::Documentation
std::string Documentation
Definition: Hover.h:58
clang::clangd::DeclRelation::Alias
This declaration is an alias that was referred to.
AST.h
ParsedAST.h