1 //===- IndexBody.cpp - Indexing statements --------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "IndexingContext.h"
11 #include "clang/AST/RecursiveASTVisitor.h"
12 
13 using namespace clang;
14 using namespace clang::index;
15 
16 namespace {
17 
18 class BodyIndexer : public RecursiveASTVisitor<BodyIndexer> {
19   IndexingContext &IndexCtx;
20   const NamedDecl *Parent;
21   const DeclContext *ParentDC;
22   SmallVector<Stmt*, 16> StmtStack;
23 
24   typedef RecursiveASTVisitor<BodyIndexer> base;
25 
26   Stmt *getParentStmt() const {
27     return StmtStack.size() < 2 ? nullptr : StmtStack.end()[-2];
28   }
29 public:
30   BodyIndexer(IndexingContext &indexCtx,
31               const NamedDecl *Parent, const DeclContext *DC)
32     : IndexCtx(indexCtx), Parent(Parent), ParentDC(DC) { }
33 
34   bool shouldWalkTypesOfTypeLocs() const { return false; }
35 
36   bool dataTraverseStmtPre(Stmt *S) {
37     StmtStack.push_back(S);
38     return true;
39   }
40 
41   bool dataTraverseStmtPost(Stmt *S) {
42     assert(StmtStack.back() == S);
43     StmtStack.pop_back();
44     return true;
45   }
46 
47   bool TraverseTypeLoc(TypeLoc TL) {
48     IndexCtx.indexTypeLoc(TL, Parent, ParentDC);
49     return true;
50   }
51 
52   bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
53     IndexCtx.indexNestedNameSpecifierLoc(NNS, Parent, ParentDC);
54     return true;
55   }
56 
57   SymbolRoleSet getRolesForRef(const Expr *E,
58                                SmallVectorImpl<SymbolRelation> &Relations) {
59     SymbolRoleSet Roles{};
60     assert(!StmtStack.empty() && E == StmtStack.back());
61     if (StmtStack.size() == 1)
62       return Roles;
63     auto It = StmtStack.end()-2;
64     while (isa<CastExpr>(*It) || isa<ParenExpr>(*It)) {
65       if (auto ICE = dyn_cast<ImplicitCastExpr>(*It)) {
66         if (ICE->getCastKind() == CK_LValueToRValue)
67           Roles |= (unsigned)(unsigned)SymbolRole::Read;
68       }
69       if (It == StmtStack.begin())
70         break;
71       --It;
72     }
73     const Stmt *Parent = *It;
74 
75     if (auto BO = dyn_cast<BinaryOperator>(Parent)) {
76       if (BO->getOpcode() == BO_Assign && BO->getLHS()->IgnoreParenCasts() == E)
77         Roles |= (unsigned)SymbolRole::Write;
78 
79     } else if (auto UO = dyn_cast<UnaryOperator>(Parent)) {
80       if (UO->isIncrementDecrementOp()) {
81         Roles |= (unsigned)SymbolRole::Read;
82         Roles |= (unsigned)SymbolRole::Write;
83       } else if (UO->getOpcode() == UO_AddrOf) {
84         Roles |= (unsigned)SymbolRole::AddressOf;
85       }
86 
87     } else if (auto CA = dyn_cast<CompoundAssignOperator>(Parent)) {
88       if (CA->getLHS()->IgnoreParenCasts() == E) {
89         Roles |= (unsigned)SymbolRole::Read;
90         Roles |= (unsigned)SymbolRole::Write;
91       }
92 
93     } else if (auto CE = dyn_cast<CallExpr>(Parent)) {
94       if (CE->getCallee()->IgnoreParenCasts() == E) {
95         addCallRole(Roles, Relations);
96         if (auto *ME = dyn_cast<MemberExpr>(E)) {
97           if (auto *CXXMD = dyn_cast_or_null<CXXMethodDecl>(ME->getMemberDecl()))
98             if (CXXMD->isVirtual() && !ME->hasQualifier()) {
99               Roles |= (unsigned)SymbolRole::Dynamic;
100               auto BaseTy = ME->getBase()->IgnoreImpCasts()->getType();
101               if (!BaseTy.isNull())
102                 if (auto *CXXRD = BaseTy->getPointeeCXXRecordDecl())
103                   Relations.emplace_back((unsigned)SymbolRole::RelationReceivedBy,
104                                          CXXRD);
105             }
106         }
107       } else if (auto CXXOp = dyn_cast<CXXOperatorCallExpr>(CE)) {
108         if (CXXOp->getNumArgs() > 0 && CXXOp->getArg(0)->IgnoreParenCasts() == E) {
109           OverloadedOperatorKind Op = CXXOp->getOperator();
110           if (Op == OO_Equal) {
111             Roles |= (unsigned)SymbolRole::Write;
112           } else if ((Op >= OO_PlusEqual && Op <= OO_PipeEqual) ||
113                      Op == OO_LessLessEqual || Op == OO_GreaterGreaterEqual ||
114                      Op == OO_PlusPlus || Op == OO_MinusMinus) {
115             Roles |= (unsigned)SymbolRole::Read;
116             Roles |= (unsigned)SymbolRole::Write;
117           } else if (Op == OO_Amp) {
118             Roles |= (unsigned)SymbolRole::AddressOf;
119           }
120         }
121       }
122     }
123 
124     return Roles;
125   }
126 
127   void addCallRole(SymbolRoleSet &Roles,
128                    SmallVectorImpl<SymbolRelation> &Relations) {
129     Roles |= (unsigned)SymbolRole::Call;
130     if (auto *FD = dyn_cast<FunctionDecl>(ParentDC))
131       Relations.emplace_back((unsigned)SymbolRole::RelationCalledBy, FD);
132     else if (auto *MD = dyn_cast<ObjCMethodDecl>(ParentDC))
133       Relations.emplace_back((unsigned)SymbolRole::RelationCalledBy, MD);
134   }
135 
136   bool VisitDeclRefExpr(DeclRefExpr *E) {
137     SmallVector<SymbolRelation, 4> Relations;
138     SymbolRoleSet Roles = getRolesForRef(E, Relations);
139     return IndexCtx.handleReference(E->getDecl(), E->getLocation(),
140                                     Parent, ParentDC, Roles, Relations, E);
141   }
142 
143   bool VisitMemberExpr(MemberExpr *E) {
144     SourceLocation Loc = E->getMemberLoc();
145     if (Loc.isInvalid())
146       Loc = E->getLocStart();
147     SmallVector<SymbolRelation, 4> Relations;
148     SymbolRoleSet Roles = getRolesForRef(E, Relations);
149     return IndexCtx.handleReference(E->getMemberDecl(), Loc,
150                                     Parent, ParentDC, Roles, Relations, E);
151   }
152 
153   bool indexDependentReference(
154       const Expr *E, const Type *T, const DeclarationNameInfo &NameInfo,
155       llvm::function_ref<bool(const NamedDecl *ND)> Filter) {
156     if (!T)
157       return true;
158     const TemplateSpecializationType *TST =
159         T->getAs<TemplateSpecializationType>();
160     if (!TST)
161       return true;
162     TemplateName TN = TST->getTemplateName();
163     const ClassTemplateDecl *TD =
164         dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
165     if (!TD)
166       return true;
167     CXXRecordDecl *RD = TD->getTemplatedDecl();
168     std::vector<const NamedDecl *> Symbols =
169         RD->lookupDependentName(NameInfo.getName(), Filter);
170     // FIXME: Improve overload handling.
171     if (Symbols.size() != 1)
172       return true;
173     SourceLocation Loc = NameInfo.getLoc();
174     if (Loc.isInvalid())
175       Loc = E->getLocStart();
176     SmallVector<SymbolRelation, 4> Relations;
177     SymbolRoleSet Roles = getRolesForRef(E, Relations);
178     return IndexCtx.handleReference(Symbols[0], Loc, Parent, ParentDC, Roles,
179                                     Relations, E);
180   }
181 
182   bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
183     const DeclarationNameInfo &Info = E->getMemberNameInfo();
184     return indexDependentReference(
185         E, E->getBaseType().getTypePtrOrNull(), Info,
186         [](const NamedDecl *D) { return D->isCXXInstanceMember(); });
187   }
188 
189   bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
190     const DeclarationNameInfo &Info = E->getNameInfo();
191     const NestedNameSpecifier *NNS = E->getQualifier();
192     return indexDependentReference(
193         E, NNS->getAsType(), Info,
194         [](const NamedDecl *D) { return !D->isCXXInstanceMember(); });
195   }
196 
197   bool VisitDesignatedInitExpr(DesignatedInitExpr *E) {
198     for (DesignatedInitExpr::Designator &D : llvm::reverse(E->designators())) {
199       if (D.isFieldDesignator() && D.getField())
200         return IndexCtx.handleReference(D.getField(), D.getFieldLoc(), Parent,
201                                         ParentDC, SymbolRoleSet(), {}, E);
202     }
203     return true;
204   }
205 
206   bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
207     SmallVector<SymbolRelation, 4> Relations;
208     SymbolRoleSet Roles = getRolesForRef(E, Relations);
209     return IndexCtx.handleReference(E->getDecl(), E->getLocation(),
210                                     Parent, ParentDC, Roles, Relations, E);
211   }
212 
213   bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
214     auto isDynamic = [](const ObjCMessageExpr *MsgE)->bool {
215       if (MsgE->getReceiverKind() != ObjCMessageExpr::Instance)
216         return false;
217       if (auto *RecE = dyn_cast<ObjCMessageExpr>(
218               MsgE->getInstanceReceiver()->IgnoreParenCasts())) {
219         if (RecE->getMethodFamily() == OMF_alloc)
220           return false;
221       }
222       return true;
223     };
224 
225     if (ObjCMethodDecl *MD = E->getMethodDecl()) {
226       SymbolRoleSet Roles{};
227       SmallVector<SymbolRelation, 2> Relations;
228       addCallRole(Roles, Relations);
229       Stmt *Containing = getParentStmt();
230       if (E->isImplicit() || (Containing && isa<PseudoObjectExpr>(Containing)))
231         Roles |= (unsigned)SymbolRole::Implicit;
232 
233       if (isDynamic(E)) {
234         Roles |= (unsigned)SymbolRole::Dynamic;
235         if (auto *RecD = E->getReceiverInterface())
236           Relations.emplace_back((unsigned)SymbolRole::RelationReceivedBy, RecD);
237       }
238 
239       return IndexCtx.handleReference(MD, E->getSelectorStartLoc(),
240                                       Parent, ParentDC, Roles, Relations, E);
241     }
242     return true;
243   }
244 
245   bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
246     if (E->isExplicitProperty()) {
247       SmallVector<SymbolRelation, 2> Relations;
248       SymbolRoleSet Roles = getRolesForRef(E, Relations);
249       return IndexCtx.handleReference(E->getExplicitProperty(), E->getLocation(),
250                                       Parent, ParentDC, Roles, Relations, E);
251     }
252 
253     // No need to do a handleReference for the objc method, because there will
254     // be a message expr as part of PseudoObjectExpr.
255     return true;
256   }
257 
258   bool VisitMSPropertyRefExpr(MSPropertyRefExpr *E) {
259     return IndexCtx.handleReference(E->getPropertyDecl(), E->getMemberLoc(),
260                                     Parent, ParentDC, SymbolRoleSet(), {}, E);
261   }
262 
263   bool VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
264     return IndexCtx.handleReference(E->getProtocol(), E->getProtocolIdLoc(),
265                                     Parent, ParentDC, SymbolRoleSet(), {}, E);
266   }
267 
268   bool passObjCLiteralMethodCall(const ObjCMethodDecl *MD, const Expr *E) {
269     SymbolRoleSet Roles{};
270     SmallVector<SymbolRelation, 2> Relations;
271     addCallRole(Roles, Relations);
272     Roles |= (unsigned)SymbolRole::Implicit;
273     return IndexCtx.handleReference(MD, E->getLocStart(),
274                                     Parent, ParentDC, Roles, Relations, E);
275   }
276 
277   bool VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
278     if (ObjCMethodDecl *MD = E->getBoxingMethod()) {
279       return passObjCLiteralMethodCall(MD, E);
280     }
281     return true;
282   }
283 
284   bool VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
285     if (ObjCMethodDecl *MD = E->getDictWithObjectsMethod()) {
286       return passObjCLiteralMethodCall(MD, E);
287     }
288     return true;
289   }
290 
291   bool VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
292     if (ObjCMethodDecl *MD = E->getArrayWithObjectsMethod()) {
293       return passObjCLiteralMethodCall(MD, E);
294     }
295     return true;
296   }
297 
298   bool VisitCXXConstructExpr(CXXConstructExpr *E) {
299     SymbolRoleSet Roles{};
300     SmallVector<SymbolRelation, 2> Relations;
301     addCallRole(Roles, Relations);
302     return IndexCtx.handleReference(E->getConstructor(), E->getLocation(),
303                                     Parent, ParentDC, Roles, Relations, E);
304   }
305 
306   bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *E,
307                                    DataRecursionQueue *Q = nullptr) {
308     if (E->getOperatorLoc().isInvalid())
309       return true; // implicit.
310     return base::TraverseCXXOperatorCallExpr(E, Q);
311   }
312 
313   bool VisitDeclStmt(DeclStmt *S) {
314     if (IndexCtx.shouldIndexFunctionLocalSymbols()) {
315       IndexCtx.indexDeclGroupRef(S->getDeclGroup());
316       return true;
317     }
318 
319     DeclGroupRef DG = S->getDeclGroup();
320     for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
321       const Decl *D = *I;
322       if (!D)
323         continue;
324       if (!isFunctionLocalSymbol(D))
325         IndexCtx.indexTopLevelDecl(D);
326     }
327 
328     return true;
329   }
330 
331   bool TraverseLambdaCapture(LambdaExpr *LE, const LambdaCapture *C,
332                              Expr *Init) {
333     if (C->capturesThis() || C->capturesVLAType())
334       return true;
335 
336     if (C->capturesVariable() && IndexCtx.shouldIndexFunctionLocalSymbols())
337       return IndexCtx.handleReference(C->getCapturedVar(), C->getLocation(),
338                                       Parent, ParentDC, SymbolRoleSet());
339 
340     // FIXME: Lambda init-captures.
341     return true;
342   }
343 
344   // RecursiveASTVisitor visits both syntactic and semantic forms, duplicating
345   // the things that we visit. Make sure to only visit the semantic form.
346   // Also visit things that are in the syntactic form but not the semantic one,
347   // for example the indices in DesignatedInitExprs.
348   bool TraverseInitListExpr(InitListExpr *S, DataRecursionQueue *Q = nullptr) {
349     auto visitForm = [&](InitListExpr *Form) {
350       for (Stmt *SubStmt : Form->children()) {
351         if (!TraverseStmt(SubStmt, Q))
352           return false;
353       }
354       return true;
355     };
356 
357     auto visitSyntacticDesignatedInitExpr = [&](DesignatedInitExpr *E) -> bool {
358       for (DesignatedInitExpr::Designator &D : llvm::reverse(E->designators())) {
359         if (D.isFieldDesignator())
360           return IndexCtx.handleReference(D.getField(), D.getFieldLoc(),
361                                           Parent, ParentDC, SymbolRoleSet(),
362                                           {}, E);
363       }
364       return true;
365     };
366 
367     InitListExpr *SemaForm = S->isSemanticForm() ? S : S->getSemanticForm();
368     InitListExpr *SyntaxForm = S->isSemanticForm() ? S->getSyntacticForm() : S;
369 
370     if (SemaForm) {
371       // Visit things present in syntactic form but not the semantic form.
372       if (SyntaxForm) {
373         for (Expr *init : SyntaxForm->inits()) {
374           if (auto *DIE = dyn_cast<DesignatedInitExpr>(init))
375             visitSyntacticDesignatedInitExpr(DIE);
376         }
377       }
378       return visitForm(SemaForm);
379     }
380 
381     // No semantic, try the syntactic.
382     if (SyntaxForm) {
383       return visitForm(SyntaxForm);
384     }
385 
386     return true;
387   }
388 };
389 
390 } // anonymous namespace
391 
392 void IndexingContext::indexBody(const Stmt *S, const NamedDecl *Parent,
393                                 const DeclContext *DC) {
394   if (!S)
395     return;
396 
397   if (!DC)
398     DC = Parent->getLexicalDeclContext();
399   BodyIndexer(*this, Parent, DC).TraverseStmt(const_cast<Stmt*>(S));
400 }
401