1 //===--- IndexSymbol.cpp - Types and functions for indexing symbols -------===//
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 "clang/Index/IndexSymbol.h"
10 #include "clang/AST/DeclCXX.h"
11 #include "clang/AST/DeclObjC.h"
12 #include "clang/AST/DeclTemplate.h"
13 #include "clang/AST/PrettyPrinter.h"
14 #include "clang/Lex/MacroInfo.h"
15 
16 using namespace clang;
17 using namespace clang::index;
18 
19 /// \returns true if \c D is a subclass of 'XCTestCase'.
20 static bool isUnitTestCase(const ObjCInterfaceDecl *D) {
21   if (!D)
22     return false;
23   while (const ObjCInterfaceDecl *SuperD = D->getSuperClass()) {
24     if (SuperD->getName() == "XCTestCase")
25       return true;
26     D = SuperD;
27   }
28   return false;
29 }
30 
31 /// \returns true if \c D is in a subclass of 'XCTestCase', returns void, has
32 /// no parameters, and its name starts with 'test'.
33 static bool isUnitTest(const ObjCMethodDecl *D) {
34   if (!D->parameters().empty())
35     return false;
36   if (!D->getReturnType()->isVoidType())
37     return false;
38   if (!D->getSelector().getNameForSlot(0).startswith("test"))
39     return false;
40   return isUnitTestCase(D->getClassInterface());
41 }
42 
43 static void checkForIBOutlets(const Decl *D, SymbolPropertySet &PropSet) {
44   if (D->hasAttr<IBOutletAttr>()) {
45     PropSet |= (SymbolPropertySet)SymbolProperty::IBAnnotated;
46   } else if (D->hasAttr<IBOutletCollectionAttr>()) {
47     PropSet |= (SymbolPropertySet)SymbolProperty::IBAnnotated;
48     PropSet |= (SymbolPropertySet)SymbolProperty::IBOutletCollection;
49   }
50 }
51 
52 bool index::isFunctionLocalSymbol(const Decl *D) {
53   assert(D);
54 
55   if (isa<ParmVarDecl>(D))
56     return true;
57 
58   if (isa<ObjCTypeParamDecl>(D))
59     return true;
60 
61   if (isa<UsingDirectiveDecl>(D))
62     return false;
63   if (!D->getParentFunctionOrMethod())
64     return false;
65 
66   if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
67     switch (ND->getFormalLinkage()) {
68       case NoLinkage:
69       case InternalLinkage:
70         return true;
71       case VisibleNoLinkage:
72       case UniqueExternalLinkage:
73       case ModuleInternalLinkage:
74         llvm_unreachable("Not a sema linkage");
75       case ModuleLinkage:
76       case ExternalLinkage:
77         return false;
78     }
79   }
80 
81   return true;
82 }
83 
84 SymbolInfo index::getSymbolInfo(const Decl *D) {
85   assert(D);
86   SymbolInfo Info;
87   Info.Kind = SymbolKind::Unknown;
88   Info.SubKind = SymbolSubKind::None;
89   Info.Properties = SymbolPropertySet();
90   Info.Lang = SymbolLanguage::C;
91 
92   if (isFunctionLocalSymbol(D)) {
93     Info.Properties |= (SymbolPropertySet)SymbolProperty::Local;
94   }
95   if (isa<ObjCProtocolDecl>(D->getDeclContext())) {
96     Info.Properties |= (SymbolPropertySet)SymbolProperty::ProtocolInterface;
97   }
98 
99   if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
100     switch (TD->getTagKind()) {
101     case TTK_Struct:
102       Info.Kind = SymbolKind::Struct; break;
103     case TTK_Union:
104       Info.Kind = SymbolKind::Union; break;
105     case TTK_Class:
106       Info.Kind = SymbolKind::Class;
107       Info.Lang = SymbolLanguage::CXX;
108       break;
109     case TTK_Interface:
110       Info.Kind = SymbolKind::Protocol;
111       Info.Lang = SymbolLanguage::CXX;
112       break;
113     case TTK_Enum:
114       Info.Kind = SymbolKind::Enum; break;
115     }
116 
117     if (const CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(D)) {
118       if (!CXXRec->isCLike()) {
119         Info.Lang = SymbolLanguage::CXX;
120         if (CXXRec->getDescribedClassTemplate()) {
121           Info.Properties |= (SymbolPropertySet)SymbolProperty::Generic;
122         }
123       }
124     }
125 
126     if (isa<ClassTemplatePartialSpecializationDecl>(D)) {
127       Info.Properties |= (SymbolPropertySet)SymbolProperty::Generic;
128       Info.Properties |=
129           (SymbolPropertySet)SymbolProperty::TemplatePartialSpecialization;
130     } else if (isa<ClassTemplateSpecializationDecl>(D)) {
131       Info.Properties |= (SymbolPropertySet)SymbolProperty::Generic;
132       Info.Properties |=
133           (SymbolPropertySet)SymbolProperty::TemplateSpecialization;
134     }
135 
136   } else if (auto *VD = dyn_cast<VarDecl>(D)) {
137     Info.Kind = SymbolKind::Variable;
138     if (isa<ParmVarDecl>(D)) {
139       Info.Kind = SymbolKind::Parameter;
140     } else if (isa<CXXRecordDecl>(D->getDeclContext())) {
141       Info.Kind = SymbolKind::StaticProperty;
142       Info.Lang = SymbolLanguage::CXX;
143     }
144 
145     if (isa<VarTemplatePartialSpecializationDecl>(D)) {
146       Info.Lang = SymbolLanguage::CXX;
147       Info.Properties |= (SymbolPropertySet)SymbolProperty::Generic;
148       Info.Properties |=
149           (SymbolPropertySet)SymbolProperty::TemplatePartialSpecialization;
150     } else if (isa<VarTemplateSpecializationDecl>(D)) {
151       Info.Lang = SymbolLanguage::CXX;
152       Info.Properties |= (SymbolPropertySet)SymbolProperty::Generic;
153       Info.Properties |=
154           (SymbolPropertySet)SymbolProperty::TemplateSpecialization;
155     } else if (VD->getDescribedVarTemplate()) {
156       Info.Lang = SymbolLanguage::CXX;
157       Info.Properties |= (SymbolPropertySet)SymbolProperty::Generic;
158     }
159 
160   } else {
161     switch (D->getKind()) {
162     case Decl::Import:
163       Info.Kind = SymbolKind::Module;
164       break;
165     case Decl::Typedef:
166       Info.Kind = SymbolKind::TypeAlias; break; // Lang = C
167     case Decl::Function:
168       Info.Kind = SymbolKind::Function;
169       break;
170     case Decl::Field:
171       Info.Kind = SymbolKind::Field;
172       if (const CXXRecordDecl *
173             CXXRec = dyn_cast<CXXRecordDecl>(D->getDeclContext())) {
174         if (!CXXRec->isCLike())
175           Info.Lang = SymbolLanguage::CXX;
176       }
177       break;
178     case Decl::EnumConstant:
179       Info.Kind = SymbolKind::EnumConstant; break;
180     case Decl::ObjCInterface:
181     case Decl::ObjCImplementation: {
182       Info.Kind = SymbolKind::Class;
183       Info.Lang = SymbolLanguage::ObjC;
184       const ObjCInterfaceDecl *ClsD = dyn_cast<ObjCInterfaceDecl>(D);
185       if (!ClsD)
186         ClsD = cast<ObjCImplementationDecl>(D)->getClassInterface();
187       if (isUnitTestCase(ClsD))
188         Info.Properties |= (SymbolPropertySet)SymbolProperty::UnitTest;
189       break;
190     }
191     case Decl::ObjCProtocol:
192       Info.Kind = SymbolKind::Protocol;
193       Info.Lang = SymbolLanguage::ObjC;
194       break;
195     case Decl::ObjCCategory:
196     case Decl::ObjCCategoryImpl: {
197       Info.Kind = SymbolKind::Extension;
198       Info.Lang = SymbolLanguage::ObjC;
199       const ObjCInterfaceDecl *ClsD = nullptr;
200       if (auto *CatD = dyn_cast<ObjCCategoryDecl>(D))
201         ClsD = CatD->getClassInterface();
202       else
203         ClsD = cast<ObjCCategoryImplDecl>(D)->getClassInterface();
204       if (isUnitTestCase(ClsD))
205         Info.Properties |= (SymbolPropertySet)SymbolProperty::UnitTest;
206       break;
207     }
208     case Decl::ObjCMethod: {
209       const ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
210       Info.Kind = MD->isInstanceMethod() ? SymbolKind::InstanceMethod : SymbolKind::ClassMethod;
211       if (MD->isPropertyAccessor()) {
212         if (MD->param_size())
213           Info.SubKind = SymbolSubKind::AccessorSetter;
214         else
215           Info.SubKind = SymbolSubKind::AccessorGetter;
216       }
217       Info.Lang = SymbolLanguage::ObjC;
218       if (isUnitTest(MD))
219         Info.Properties |= (SymbolPropertySet)SymbolProperty::UnitTest;
220       if (D->hasAttr<IBActionAttr>())
221         Info.Properties |= (SymbolPropertySet)SymbolProperty::IBAnnotated;
222       break;
223     }
224     case Decl::ObjCProperty:
225       Info.Kind = SymbolKind::InstanceProperty;
226       Info.Lang = SymbolLanguage::ObjC;
227       checkForIBOutlets(D, Info.Properties);
228       if (auto *Annot = D->getAttr<AnnotateAttr>()) {
229         if (Annot->getAnnotation() == "gk_inspectable")
230           Info.Properties |= (SymbolPropertySet)SymbolProperty::GKInspectable;
231       }
232       break;
233     case Decl::ObjCIvar:
234       Info.Kind = SymbolKind::Field;
235       Info.Lang = SymbolLanguage::ObjC;
236       checkForIBOutlets(D, Info.Properties);
237       break;
238     case Decl::Namespace:
239       Info.Kind = SymbolKind::Namespace;
240       Info.Lang = SymbolLanguage::CXX;
241       break;
242     case Decl::NamespaceAlias:
243       Info.Kind = SymbolKind::NamespaceAlias;
244       Info.Lang = SymbolLanguage::CXX;
245       break;
246     case Decl::CXXConstructor: {
247       Info.Kind = SymbolKind::Constructor;
248       Info.Lang = SymbolLanguage::CXX;
249       auto *CD = cast<CXXConstructorDecl>(D);
250       if (CD->isCopyConstructor())
251         Info.SubKind = SymbolSubKind::CXXCopyConstructor;
252       else if (CD->isMoveConstructor())
253         Info.SubKind = SymbolSubKind::CXXMoveConstructor;
254       break;
255     }
256     case Decl::CXXDestructor:
257       Info.Kind = SymbolKind::Destructor;
258       Info.Lang = SymbolLanguage::CXX;
259       break;
260     case Decl::CXXConversion:
261       Info.Kind = SymbolKind::ConversionFunction;
262       Info.Lang = SymbolLanguage::CXX;
263       break;
264     case Decl::CXXMethod: {
265       const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
266       if (MD->isStatic())
267         Info.Kind = SymbolKind::StaticMethod;
268       else
269         Info.Kind = SymbolKind::InstanceMethod;
270       Info.Lang = SymbolLanguage::CXX;
271       break;
272     }
273     case Decl::ClassTemplate:
274       Info.Kind = SymbolKind::Class;
275       Info.Properties |= (SymbolPropertySet)SymbolProperty::Generic;
276       Info.Lang = SymbolLanguage::CXX;
277       break;
278     case Decl::FunctionTemplate:
279       Info.Kind = SymbolKind::Function;
280       Info.Properties |= (SymbolPropertySet)SymbolProperty::Generic;
281       Info.Lang = SymbolLanguage::CXX;
282       if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(
283                            cast<FunctionTemplateDecl>(D)->getTemplatedDecl())) {
284         if (isa<CXXConstructorDecl>(MD))
285           Info.Kind = SymbolKind::Constructor;
286         else if (isa<CXXDestructorDecl>(MD))
287           Info.Kind = SymbolKind::Destructor;
288         else if (isa<CXXConversionDecl>(MD))
289           Info.Kind = SymbolKind::ConversionFunction;
290         else {
291           if (MD->isStatic())
292             Info.Kind = SymbolKind::StaticMethod;
293           else
294             Info.Kind = SymbolKind::InstanceMethod;
295         }
296       }
297       break;
298     case Decl::TypeAliasTemplate:
299       Info.Kind = SymbolKind::TypeAlias;
300       Info.Lang = SymbolLanguage::CXX;
301       Info.Properties |= (SymbolPropertySet)SymbolProperty::Generic;
302       break;
303     case Decl::TypeAlias:
304       Info.Kind = SymbolKind::TypeAlias;
305       Info.Lang = SymbolLanguage::CXX;
306       break;
307     case Decl::UnresolvedUsingTypename:
308       Info.Kind = SymbolKind::Using;
309       Info.SubKind = SymbolSubKind::UsingTypename;
310       Info.Lang = SymbolLanguage::CXX;
311       Info.Properties |= (SymbolPropertySet)SymbolProperty::Generic;
312       break;
313     case Decl::UnresolvedUsingValue:
314       Info.Kind = SymbolKind::Using;
315       Info.SubKind = SymbolSubKind::UsingValue;
316       Info.Lang = SymbolLanguage::CXX;
317       Info.Properties |= (SymbolPropertySet)SymbolProperty::Generic;
318       break;
319     case Decl::Using:
320       Info.Kind = SymbolKind::Using;
321       Info.Lang = SymbolLanguage::CXX;
322       break;
323     case Decl::Binding:
324       Info.Kind = SymbolKind::Variable;
325       Info.Lang = SymbolLanguage::CXX;
326       break;
327     default:
328       break;
329     }
330   }
331 
332   if (Info.Kind == SymbolKind::Unknown)
333     return Info;
334 
335   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
336     if (FD->getTemplatedKind() ==
337           FunctionDecl::TK_FunctionTemplateSpecialization) {
338       Info.Properties |= (SymbolPropertySet)SymbolProperty::Generic;
339       Info.Properties |=
340           (SymbolPropertySet)SymbolProperty::TemplateSpecialization;
341     }
342   }
343 
344   if (Info.Properties & (SymbolPropertySet)SymbolProperty::Generic)
345     Info.Lang = SymbolLanguage::CXX;
346 
347   if (auto *attr = D->getExternalSourceSymbolAttr()) {
348     if (attr->getLanguage() == "Swift")
349       Info.Lang = SymbolLanguage::Swift;
350   }
351 
352   return Info;
353 }
354 
355 SymbolInfo index::getSymbolInfoForMacro(const MacroInfo &) {
356   SymbolInfo Info;
357   Info.Kind = SymbolKind::Macro;
358   Info.SubKind = SymbolSubKind::None;
359   Info.Properties = SymbolPropertySet();
360   Info.Lang = SymbolLanguage::C;
361   return Info;
362 }
363 
364 bool index::applyForEachSymbolRoleInterruptible(SymbolRoleSet Roles,
365                                    llvm::function_ref<bool(SymbolRole)> Fn) {
366 #define APPLY_FOR_ROLE(Role) \
367   if (Roles & (unsigned)SymbolRole::Role) \
368     if (!Fn(SymbolRole::Role)) \
369       return false;
370 
371   APPLY_FOR_ROLE(Declaration);
372   APPLY_FOR_ROLE(Definition);
373   APPLY_FOR_ROLE(Reference);
374   APPLY_FOR_ROLE(Read);
375   APPLY_FOR_ROLE(Write);
376   APPLY_FOR_ROLE(Call);
377   APPLY_FOR_ROLE(Dynamic);
378   APPLY_FOR_ROLE(AddressOf);
379   APPLY_FOR_ROLE(Implicit);
380   APPLY_FOR_ROLE(Undefinition);
381   APPLY_FOR_ROLE(RelationChildOf);
382   APPLY_FOR_ROLE(RelationBaseOf);
383   APPLY_FOR_ROLE(RelationOverrideOf);
384   APPLY_FOR_ROLE(RelationReceivedBy);
385   APPLY_FOR_ROLE(RelationCalledBy);
386   APPLY_FOR_ROLE(RelationExtendedBy);
387   APPLY_FOR_ROLE(RelationAccessorOf);
388   APPLY_FOR_ROLE(RelationContainedBy);
389   APPLY_FOR_ROLE(RelationIBTypeOf);
390   APPLY_FOR_ROLE(RelationSpecializationOf);
391 
392 #undef APPLY_FOR_ROLE
393 
394   return true;
395 }
396 
397 void index::applyForEachSymbolRole(SymbolRoleSet Roles,
398                                    llvm::function_ref<void(SymbolRole)> Fn) {
399   applyForEachSymbolRoleInterruptible(Roles, [&](SymbolRole r) -> bool {
400     Fn(r);
401     return true;
402   });
403 }
404 
405 void index::printSymbolRoles(SymbolRoleSet Roles, raw_ostream &OS) {
406   bool VisitedOnce = false;
407   applyForEachSymbolRole(Roles, [&](SymbolRole Role) {
408     if (VisitedOnce)
409       OS << ',';
410     else
411       VisitedOnce = true;
412     switch (Role) {
413     case SymbolRole::Declaration: OS << "Decl"; break;
414     case SymbolRole::Definition: OS << "Def"; break;
415     case SymbolRole::Reference: OS << "Ref"; break;
416     case SymbolRole::Read: OS << "Read"; break;
417     case SymbolRole::Write: OS << "Writ"; break;
418     case SymbolRole::Call: OS << "Call"; break;
419     case SymbolRole::Dynamic: OS << "Dyn"; break;
420     case SymbolRole::AddressOf: OS << "Addr"; break;
421     case SymbolRole::Implicit: OS << "Impl"; break;
422     case SymbolRole::Undefinition: OS << "Undef"; break;
423     case SymbolRole::RelationChildOf: OS << "RelChild"; break;
424     case SymbolRole::RelationBaseOf: OS << "RelBase"; break;
425     case SymbolRole::RelationOverrideOf: OS << "RelOver"; break;
426     case SymbolRole::RelationReceivedBy: OS << "RelRec"; break;
427     case SymbolRole::RelationCalledBy: OS << "RelCall"; break;
428     case SymbolRole::RelationExtendedBy: OS << "RelExt"; break;
429     case SymbolRole::RelationAccessorOf: OS << "RelAcc"; break;
430     case SymbolRole::RelationContainedBy: OS << "RelCont"; break;
431     case SymbolRole::RelationIBTypeOf: OS << "RelIBType"; break;
432     case SymbolRole::RelationSpecializationOf: OS << "RelSpecialization"; break;
433     }
434   });
435 }
436 
437 bool index::printSymbolName(const Decl *D, const LangOptions &LO,
438                             raw_ostream &OS) {
439   if (auto *ND = dyn_cast<NamedDecl>(D)) {
440     PrintingPolicy Policy(LO);
441     // Forward references can have different template argument names. Suppress
442     // the template argument names in constructors to make their name more
443     // stable.
444     Policy.SuppressTemplateArgsInCXXConstructors = true;
445     DeclarationName DeclName = ND->getDeclName();
446     if (DeclName.isEmpty())
447       return true;
448     DeclName.print(OS, Policy);
449     return false;
450   } else {
451     return true;
452   }
453 }
454 
455 StringRef index::getSymbolKindString(SymbolKind K) {
456   switch (K) {
457   case SymbolKind::Unknown: return "<unknown>";
458   case SymbolKind::Module: return "module";
459   case SymbolKind::Namespace: return "namespace";
460   case SymbolKind::NamespaceAlias: return "namespace-alias";
461   case SymbolKind::Macro: return "macro";
462   case SymbolKind::Enum: return "enum";
463   case SymbolKind::Struct: return "struct";
464   case SymbolKind::Class: return "class";
465   case SymbolKind::Protocol: return "protocol";
466   case SymbolKind::Extension: return "extension";
467   case SymbolKind::Union: return "union";
468   case SymbolKind::TypeAlias: return "type-alias";
469   case SymbolKind::Function: return "function";
470   case SymbolKind::Variable: return "variable";
471   case SymbolKind::Field: return "field";
472   case SymbolKind::EnumConstant: return "enumerator";
473   case SymbolKind::InstanceMethod: return "instance-method";
474   case SymbolKind::ClassMethod: return "class-method";
475   case SymbolKind::StaticMethod: return "static-method";
476   case SymbolKind::InstanceProperty: return "instance-property";
477   case SymbolKind::ClassProperty: return "class-property";
478   case SymbolKind::StaticProperty: return "static-property";
479   case SymbolKind::Constructor: return "constructor";
480   case SymbolKind::Destructor: return "destructor";
481   case SymbolKind::ConversionFunction: return "coversion-func";
482   case SymbolKind::Parameter: return "param";
483   case SymbolKind::Using: return "using";
484   }
485   llvm_unreachable("invalid symbol kind");
486 }
487 
488 StringRef index::getSymbolSubKindString(SymbolSubKind K) {
489   switch (K) {
490   case SymbolSubKind::None: return "<none>";
491   case SymbolSubKind::CXXCopyConstructor: return "cxx-copy-ctor";
492   case SymbolSubKind::CXXMoveConstructor: return "cxx-move-ctor";
493   case SymbolSubKind::AccessorGetter: return "acc-get";
494   case SymbolSubKind::AccessorSetter: return "acc-set";
495   case SymbolSubKind::UsingTypename: return "using-typename";
496   case SymbolSubKind::UsingValue: return "using-value";
497   }
498   llvm_unreachable("invalid symbol subkind");
499 }
500 
501 StringRef index::getSymbolLanguageString(SymbolLanguage K) {
502   switch (K) {
503   case SymbolLanguage::C: return "C";
504   case SymbolLanguage::ObjC: return "ObjC";
505   case SymbolLanguage::CXX: return "C++";
506   case SymbolLanguage::Swift: return "Swift";
507   }
508   llvm_unreachable("invalid symbol language kind");
509 }
510 
511 void index::applyForEachSymbolProperty(SymbolPropertySet Props,
512                                   llvm::function_ref<void(SymbolProperty)> Fn) {
513 #define APPLY_FOR_PROPERTY(K)                                                  \
514   if (Props & (SymbolPropertySet)SymbolProperty::K)                            \
515   Fn(SymbolProperty::K)
516 
517   APPLY_FOR_PROPERTY(Generic);
518   APPLY_FOR_PROPERTY(TemplatePartialSpecialization);
519   APPLY_FOR_PROPERTY(TemplateSpecialization);
520   APPLY_FOR_PROPERTY(UnitTest);
521   APPLY_FOR_PROPERTY(IBAnnotated);
522   APPLY_FOR_PROPERTY(IBOutletCollection);
523   APPLY_FOR_PROPERTY(GKInspectable);
524   APPLY_FOR_PROPERTY(Local);
525   APPLY_FOR_PROPERTY(ProtocolInterface);
526 
527 #undef APPLY_FOR_PROPERTY
528 }
529 
530 void index::printSymbolProperties(SymbolPropertySet Props, raw_ostream &OS) {
531   bool VisitedOnce = false;
532   applyForEachSymbolProperty(Props, [&](SymbolProperty Prop) {
533     if (VisitedOnce)
534       OS << ',';
535     else
536       VisitedOnce = true;
537     switch (Prop) {
538     case SymbolProperty::Generic: OS << "Gen"; break;
539     case SymbolProperty::TemplatePartialSpecialization: OS << "TPS"; break;
540     case SymbolProperty::TemplateSpecialization: OS << "TS"; break;
541     case SymbolProperty::UnitTest: OS << "test"; break;
542     case SymbolProperty::IBAnnotated: OS << "IB"; break;
543     case SymbolProperty::IBOutletCollection: OS << "IBColl"; break;
544     case SymbolProperty::GKInspectable: OS << "GKI"; break;
545     case SymbolProperty::Local: OS << "local"; break;
546     case SymbolProperty::ProtocolInterface: OS << "protocol"; break;
547     }
548   });
549 }
550