• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- CXCursor.cpp - Routines for manipulating CXCursors -----------------===//
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 // This file defines routines for manipulating CXCursors. It should be the
11 // only file that has internal knowledge of the encoding of the data in
12 // CXCursor.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "CXTranslationUnit.h"
17 #include "CXCursor.h"
18 #include "CXString.h"
19 #include "CXType.h"
20 #include "clang-c/Index.h"
21 #include "clang/AST/Attr.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/ExprObjC.h"
29 #include "clang/Frontend/ASTUnit.h"
30 #include "llvm/Support/ErrorHandling.h"
31 
32 using namespace clang;
33 using namespace cxcursor;
34 
MakeCXCursorInvalid(CXCursorKind K,CXTranslationUnit TU)35 CXCursor cxcursor::MakeCXCursorInvalid(CXCursorKind K, CXTranslationUnit TU) {
36   assert(K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid);
37   CXCursor C = { K, 0, { nullptr, nullptr, TU } };
38   return C;
39 }
40 
GetCursorKind(const Attr * A)41 static CXCursorKind GetCursorKind(const Attr *A) {
42   assert(A && "Invalid arguments!");
43   switch (A->getKind()) {
44     default: break;
45     case attr::IBAction: return CXCursor_IBActionAttr;
46     case attr::IBOutlet: return CXCursor_IBOutletAttr;
47     case attr::IBOutletCollection: return CXCursor_IBOutletCollectionAttr;
48     case attr::Final: return CXCursor_CXXFinalAttr;
49     case attr::Override: return CXCursor_CXXOverrideAttr;
50     case attr::Annotate: return CXCursor_AnnotateAttr;
51     case attr::AsmLabel: return CXCursor_AsmLabelAttr;
52     case attr::Packed: return CXCursor_PackedAttr;
53     case attr::Pure: return CXCursor_PureAttr;
54     case attr::Const: return CXCursor_ConstAttr;
55     case attr::NoDuplicate: return CXCursor_NoDuplicateAttr;
56     case attr::CUDAConstant: return CXCursor_CUDAConstantAttr;
57     case attr::CUDADevice: return CXCursor_CUDADeviceAttr;
58     case attr::CUDAGlobal: return CXCursor_CUDAGlobalAttr;
59     case attr::CUDAHost: return CXCursor_CUDAHostAttr;
60     case attr::CUDAShared: return CXCursor_CUDASharedAttr;
61     case attr::Visibility: return CXCursor_VisibilityAttr;
62     case attr::DLLExport: return CXCursor_DLLExport;
63     case attr::DLLImport: return CXCursor_DLLImport;
64   }
65 
66   return CXCursor_UnexposedAttr;
67 }
68 
MakeCXCursor(const Attr * A,const Decl * Parent,CXTranslationUnit TU)69 CXCursor cxcursor::MakeCXCursor(const Attr *A, const Decl *Parent,
70                                 CXTranslationUnit TU) {
71   assert(A && Parent && TU && "Invalid arguments!");
72   CXCursor C = { GetCursorKind(A), 0, { Parent, A, TU } };
73   return C;
74 }
75 
MakeCXCursor(const Decl * D,CXTranslationUnit TU,SourceRange RegionOfInterest,bool FirstInDeclGroup)76 CXCursor cxcursor::MakeCXCursor(const Decl *D, CXTranslationUnit TU,
77                                 SourceRange RegionOfInterest,
78                                 bool FirstInDeclGroup) {
79   assert(D && TU && "Invalid arguments!");
80 
81   CXCursorKind K = getCursorKindForDecl(D);
82 
83   if (K == CXCursor_ObjCClassMethodDecl ||
84       K == CXCursor_ObjCInstanceMethodDecl) {
85     int SelectorIdIndex = -1;
86     // Check if cursor points to a selector id.
87     if (RegionOfInterest.isValid() &&
88         RegionOfInterest.getBegin() == RegionOfInterest.getEnd()) {
89       SmallVector<SourceLocation, 16> SelLocs;
90       cast<ObjCMethodDecl>(D)->getSelectorLocs(SelLocs);
91       SmallVectorImpl<SourceLocation>::iterator
92         I=std::find(SelLocs.begin(), SelLocs.end(),RegionOfInterest.getBegin());
93       if (I != SelLocs.end())
94         SelectorIdIndex = I - SelLocs.begin();
95     }
96     CXCursor C = { K, SelectorIdIndex,
97                    { D, (void*)(intptr_t) (FirstInDeclGroup ? 1 : 0), TU }};
98     return C;
99   }
100 
101   CXCursor C = { K, 0, { D, (void*)(intptr_t) (FirstInDeclGroup ? 1 : 0), TU }};
102   return C;
103 }
104 
MakeCXCursor(const Stmt * S,const Decl * Parent,CXTranslationUnit TU,SourceRange RegionOfInterest)105 CXCursor cxcursor::MakeCXCursor(const Stmt *S, const Decl *Parent,
106                                 CXTranslationUnit TU,
107                                 SourceRange RegionOfInterest) {
108   assert(S && TU && "Invalid arguments!");
109   CXCursorKind K = CXCursor_NotImplemented;
110 
111   switch (S->getStmtClass()) {
112   case Stmt::NoStmtClass:
113     break;
114 
115   case Stmt::CaseStmtClass:
116     K = CXCursor_CaseStmt;
117     break;
118 
119   case Stmt::DefaultStmtClass:
120     K = CXCursor_DefaultStmt;
121     break;
122 
123   case Stmt::IfStmtClass:
124     K = CXCursor_IfStmt;
125     break;
126 
127   case Stmt::SwitchStmtClass:
128     K = CXCursor_SwitchStmt;
129     break;
130 
131   case Stmt::WhileStmtClass:
132     K = CXCursor_WhileStmt;
133     break;
134 
135   case Stmt::DoStmtClass:
136     K = CXCursor_DoStmt;
137     break;
138 
139   case Stmt::ForStmtClass:
140     K = CXCursor_ForStmt;
141     break;
142 
143   case Stmt::GotoStmtClass:
144     K = CXCursor_GotoStmt;
145     break;
146 
147   case Stmt::IndirectGotoStmtClass:
148     K = CXCursor_IndirectGotoStmt;
149     break;
150 
151   case Stmt::ContinueStmtClass:
152     K = CXCursor_ContinueStmt;
153     break;
154 
155   case Stmt::BreakStmtClass:
156     K = CXCursor_BreakStmt;
157     break;
158 
159   case Stmt::ReturnStmtClass:
160     K = CXCursor_ReturnStmt;
161     break;
162 
163   case Stmt::GCCAsmStmtClass:
164     K = CXCursor_GCCAsmStmt;
165     break;
166 
167   case Stmt::MSAsmStmtClass:
168     K = CXCursor_MSAsmStmt;
169     break;
170 
171   case Stmt::ObjCAtTryStmtClass:
172     K = CXCursor_ObjCAtTryStmt;
173     break;
174 
175   case Stmt::ObjCAtCatchStmtClass:
176     K = CXCursor_ObjCAtCatchStmt;
177     break;
178 
179   case Stmt::ObjCAtFinallyStmtClass:
180     K = CXCursor_ObjCAtFinallyStmt;
181     break;
182 
183   case Stmt::ObjCAtThrowStmtClass:
184     K = CXCursor_ObjCAtThrowStmt;
185     break;
186 
187   case Stmt::ObjCAtSynchronizedStmtClass:
188     K = CXCursor_ObjCAtSynchronizedStmt;
189     break;
190 
191   case Stmt::ObjCAutoreleasePoolStmtClass:
192     K = CXCursor_ObjCAutoreleasePoolStmt;
193     break;
194 
195   case Stmt::ObjCForCollectionStmtClass:
196     K = CXCursor_ObjCForCollectionStmt;
197     break;
198 
199   case Stmt::CXXCatchStmtClass:
200     K = CXCursor_CXXCatchStmt;
201     break;
202 
203   case Stmt::CXXTryStmtClass:
204     K = CXCursor_CXXTryStmt;
205     break;
206 
207   case Stmt::CXXForRangeStmtClass:
208     K = CXCursor_CXXForRangeStmt;
209     break;
210 
211   case Stmt::SEHTryStmtClass:
212     K = CXCursor_SEHTryStmt;
213     break;
214 
215   case Stmt::SEHExceptStmtClass:
216     K = CXCursor_SEHExceptStmt;
217     break;
218 
219   case Stmt::SEHFinallyStmtClass:
220     K = CXCursor_SEHFinallyStmt;
221     break;
222 
223   case Stmt::SEHLeaveStmtClass:
224     K = CXCursor_SEHLeaveStmt;
225     break;
226 
227   case Stmt::ArrayTypeTraitExprClass:
228   case Stmt::AsTypeExprClass:
229   case Stmt::AtomicExprClass:
230   case Stmt::BinaryConditionalOperatorClass:
231   case Stmt::TypeTraitExprClass:
232   case Stmt::CoroutineBodyStmtClass:
233   case Stmt::CoawaitExprClass:
234   case Stmt::CoreturnStmtClass:
235   case Stmt::CoyieldExprClass:
236   case Stmt::CXXBindTemporaryExprClass:
237   case Stmt::CXXDefaultArgExprClass:
238   case Stmt::CXXDefaultInitExprClass:
239   case Stmt::CXXFoldExprClass:
240   case Stmt::CXXStdInitializerListExprClass:
241   case Stmt::CXXScalarValueInitExprClass:
242   case Stmt::CXXUuidofExprClass:
243   case Stmt::ChooseExprClass:
244   case Stmt::DesignatedInitExprClass:
245   case Stmt::DesignatedInitUpdateExprClass:
246   case Stmt::ExprWithCleanupsClass:
247   case Stmt::ExpressionTraitExprClass:
248   case Stmt::ExtVectorElementExprClass:
249   case Stmt::ImplicitCastExprClass:
250   case Stmt::ImplicitValueInitExprClass:
251   case Stmt::NoInitExprClass:
252   case Stmt::MaterializeTemporaryExprClass:
253   case Stmt::ObjCIndirectCopyRestoreExprClass:
254   case Stmt::OffsetOfExprClass:
255   case Stmt::ParenListExprClass:
256   case Stmt::PredefinedExprClass:
257   case Stmt::ShuffleVectorExprClass:
258   case Stmt::ConvertVectorExprClass:
259   case Stmt::UnaryExprOrTypeTraitExprClass:
260   case Stmt::VAArgExprClass:
261   case Stmt::ObjCArrayLiteralClass:
262   case Stmt::ObjCDictionaryLiteralClass:
263   case Stmt::ObjCBoxedExprClass:
264   case Stmt::ObjCSubscriptRefExprClass:
265     K = CXCursor_UnexposedExpr;
266     break;
267 
268   case Stmt::OpaqueValueExprClass:
269     if (Expr *Src = cast<OpaqueValueExpr>(S)->getSourceExpr())
270       return MakeCXCursor(Src, Parent, TU, RegionOfInterest);
271     K = CXCursor_UnexposedExpr;
272     break;
273 
274   case Stmt::PseudoObjectExprClass:
275     return MakeCXCursor(cast<PseudoObjectExpr>(S)->getSyntacticForm(),
276                         Parent, TU, RegionOfInterest);
277 
278   case Stmt::CompoundStmtClass:
279     K = CXCursor_CompoundStmt;
280     break;
281 
282   case Stmt::NullStmtClass:
283     K = CXCursor_NullStmt;
284     break;
285 
286   case Stmt::LabelStmtClass:
287     K = CXCursor_LabelStmt;
288     break;
289 
290   case Stmt::AttributedStmtClass:
291     K = CXCursor_UnexposedStmt;
292     break;
293 
294   case Stmt::DeclStmtClass:
295     K = CXCursor_DeclStmt;
296     break;
297 
298   case Stmt::CapturedStmtClass:
299     K = CXCursor_UnexposedStmt;
300     break;
301 
302   case Stmt::IntegerLiteralClass:
303     K = CXCursor_IntegerLiteral;
304     break;
305 
306   case Stmt::FloatingLiteralClass:
307     K = CXCursor_FloatingLiteral;
308     break;
309 
310   case Stmt::ImaginaryLiteralClass:
311     K = CXCursor_ImaginaryLiteral;
312     break;
313 
314   case Stmt::StringLiteralClass:
315     K = CXCursor_StringLiteral;
316     break;
317 
318   case Stmt::CharacterLiteralClass:
319     K = CXCursor_CharacterLiteral;
320     break;
321 
322   case Stmt::ParenExprClass:
323     K = CXCursor_ParenExpr;
324     break;
325 
326   case Stmt::UnaryOperatorClass:
327     K = CXCursor_UnaryOperator;
328     break;
329 
330   case Stmt::CXXNoexceptExprClass:
331     K = CXCursor_UnaryExpr;
332     break;
333 
334   case Stmt::MSPropertySubscriptExprClass:
335   case Stmt::ArraySubscriptExprClass:
336     K = CXCursor_ArraySubscriptExpr;
337     break;
338 
339   case Stmt::OMPArraySectionExprClass:
340     K = CXCursor_OMPArraySectionExpr;
341     break;
342 
343   case Stmt::BinaryOperatorClass:
344     K = CXCursor_BinaryOperator;
345     break;
346 
347   case Stmt::CompoundAssignOperatorClass:
348     K = CXCursor_CompoundAssignOperator;
349     break;
350 
351   case Stmt::ConditionalOperatorClass:
352     K = CXCursor_ConditionalOperator;
353     break;
354 
355   case Stmt::CStyleCastExprClass:
356     K = CXCursor_CStyleCastExpr;
357     break;
358 
359   case Stmt::CompoundLiteralExprClass:
360     K = CXCursor_CompoundLiteralExpr;
361     break;
362 
363   case Stmt::InitListExprClass:
364     K = CXCursor_InitListExpr;
365     break;
366 
367   case Stmt::AddrLabelExprClass:
368     K = CXCursor_AddrLabelExpr;
369     break;
370 
371   case Stmt::StmtExprClass:
372     K = CXCursor_StmtExpr;
373     break;
374 
375   case Stmt::GenericSelectionExprClass:
376     K = CXCursor_GenericSelectionExpr;
377     break;
378 
379   case Stmt::GNUNullExprClass:
380     K = CXCursor_GNUNullExpr;
381     break;
382 
383   case Stmt::CXXStaticCastExprClass:
384     K = CXCursor_CXXStaticCastExpr;
385     break;
386 
387   case Stmt::CXXDynamicCastExprClass:
388     K = CXCursor_CXXDynamicCastExpr;
389     break;
390 
391   case Stmt::CXXReinterpretCastExprClass:
392     K = CXCursor_CXXReinterpretCastExpr;
393     break;
394 
395   case Stmt::CXXConstCastExprClass:
396     K = CXCursor_CXXConstCastExpr;
397     break;
398 
399   case Stmt::CXXFunctionalCastExprClass:
400     K = CXCursor_CXXFunctionalCastExpr;
401     break;
402 
403   case Stmt::CXXTypeidExprClass:
404     K = CXCursor_CXXTypeidExpr;
405     break;
406 
407   case Stmt::CXXBoolLiteralExprClass:
408     K = CXCursor_CXXBoolLiteralExpr;
409     break;
410 
411   case Stmt::CXXNullPtrLiteralExprClass:
412     K = CXCursor_CXXNullPtrLiteralExpr;
413     break;
414 
415   case Stmt::CXXThisExprClass:
416     K = CXCursor_CXXThisExpr;
417     break;
418 
419   case Stmt::CXXThrowExprClass:
420     K = CXCursor_CXXThrowExpr;
421     break;
422 
423   case Stmt::CXXNewExprClass:
424     K = CXCursor_CXXNewExpr;
425     break;
426 
427   case Stmt::CXXDeleteExprClass:
428     K = CXCursor_CXXDeleteExpr;
429     break;
430 
431   case Stmt::ObjCStringLiteralClass:
432     K = CXCursor_ObjCStringLiteral;
433     break;
434 
435   case Stmt::ObjCEncodeExprClass:
436     K = CXCursor_ObjCEncodeExpr;
437     break;
438 
439   case Stmt::ObjCSelectorExprClass:
440     K = CXCursor_ObjCSelectorExpr;
441     break;
442 
443   case Stmt::ObjCProtocolExprClass:
444     K = CXCursor_ObjCProtocolExpr;
445     break;
446 
447   case Stmt::ObjCBoolLiteralExprClass:
448     K = CXCursor_ObjCBoolLiteralExpr;
449     break;
450 
451   case Stmt::ObjCBridgedCastExprClass:
452     K = CXCursor_ObjCBridgedCastExpr;
453     break;
454 
455   case Stmt::BlockExprClass:
456     K = CXCursor_BlockExpr;
457     break;
458 
459   case Stmt::PackExpansionExprClass:
460     K = CXCursor_PackExpansionExpr;
461     break;
462 
463   case Stmt::SizeOfPackExprClass:
464     K = CXCursor_SizeOfPackExpr;
465     break;
466 
467   case Stmt::DeclRefExprClass:
468     if (const ImplicitParamDecl *IPD =
469          dyn_cast_or_null<ImplicitParamDecl>(cast<DeclRefExpr>(S)->getDecl())) {
470       if (const ObjCMethodDecl *MD =
471             dyn_cast<ObjCMethodDecl>(IPD->getDeclContext())) {
472         if (MD->getSelfDecl() == IPD) {
473           K = CXCursor_ObjCSelfExpr;
474           break;
475         }
476       }
477     }
478 
479     K = CXCursor_DeclRefExpr;
480     break;
481 
482   case Stmt::DependentScopeDeclRefExprClass:
483   case Stmt::SubstNonTypeTemplateParmExprClass:
484   case Stmt::SubstNonTypeTemplateParmPackExprClass:
485   case Stmt::FunctionParmPackExprClass:
486   case Stmt::UnresolvedLookupExprClass:
487   case Stmt::TypoExprClass: // A typo could actually be a DeclRef or a MemberRef
488     K = CXCursor_DeclRefExpr;
489     break;
490 
491   case Stmt::CXXDependentScopeMemberExprClass:
492   case Stmt::CXXPseudoDestructorExprClass:
493   case Stmt::MemberExprClass:
494   case Stmt::MSPropertyRefExprClass:
495   case Stmt::ObjCIsaExprClass:
496   case Stmt::ObjCIvarRefExprClass:
497   case Stmt::ObjCPropertyRefExprClass:
498   case Stmt::UnresolvedMemberExprClass:
499     K = CXCursor_MemberRefExpr;
500     break;
501 
502   case Stmt::CallExprClass:
503   case Stmt::CXXOperatorCallExprClass:
504   case Stmt::CXXMemberCallExprClass:
505   case Stmt::CUDAKernelCallExprClass:
506   case Stmt::CXXConstructExprClass:
507   case Stmt::CXXTemporaryObjectExprClass:
508   case Stmt::CXXUnresolvedConstructExprClass:
509   case Stmt::UserDefinedLiteralClass:
510     K = CXCursor_CallExpr;
511     break;
512 
513   case Stmt::LambdaExprClass:
514     K = CXCursor_LambdaExpr;
515     break;
516 
517   case Stmt::ObjCMessageExprClass: {
518     K = CXCursor_ObjCMessageExpr;
519     int SelectorIdIndex = -1;
520     // Check if cursor points to a selector id.
521     if (RegionOfInterest.isValid() &&
522         RegionOfInterest.getBegin() == RegionOfInterest.getEnd()) {
523       SmallVector<SourceLocation, 16> SelLocs;
524       cast<ObjCMessageExpr>(S)->getSelectorLocs(SelLocs);
525       SmallVectorImpl<SourceLocation>::iterator
526         I=std::find(SelLocs.begin(), SelLocs.end(),RegionOfInterest.getBegin());
527       if (I != SelLocs.end())
528         SelectorIdIndex = I - SelLocs.begin();
529     }
530     CXCursor C = { K, 0, { Parent, S, TU } };
531     return getSelectorIdentifierCursor(SelectorIdIndex, C);
532   }
533 
534   case Stmt::MSDependentExistsStmtClass:
535     K = CXCursor_UnexposedStmt;
536     break;
537   case Stmt::OMPParallelDirectiveClass:
538     K = CXCursor_OMPParallelDirective;
539     break;
540   case Stmt::OMPSimdDirectiveClass:
541     K = CXCursor_OMPSimdDirective;
542     break;
543   case Stmt::OMPForDirectiveClass:
544     K = CXCursor_OMPForDirective;
545     break;
546   case Stmt::OMPForSimdDirectiveClass:
547     K = CXCursor_OMPForSimdDirective;
548     break;
549   case Stmt::OMPSectionsDirectiveClass:
550     K = CXCursor_OMPSectionsDirective;
551     break;
552   case Stmt::OMPSectionDirectiveClass:
553     K = CXCursor_OMPSectionDirective;
554     break;
555   case Stmt::OMPSingleDirectiveClass:
556     K = CXCursor_OMPSingleDirective;
557     break;
558   case Stmt::OMPMasterDirectiveClass:
559     K = CXCursor_OMPMasterDirective;
560     break;
561   case Stmt::OMPCriticalDirectiveClass:
562     K = CXCursor_OMPCriticalDirective;
563     break;
564   case Stmt::OMPParallelForDirectiveClass:
565     K = CXCursor_OMPParallelForDirective;
566     break;
567   case Stmt::OMPParallelForSimdDirectiveClass:
568     K = CXCursor_OMPParallelForSimdDirective;
569     break;
570   case Stmt::OMPParallelSectionsDirectiveClass:
571     K = CXCursor_OMPParallelSectionsDirective;
572     break;
573   case Stmt::OMPTaskDirectiveClass:
574     K = CXCursor_OMPTaskDirective;
575     break;
576   case Stmt::OMPTaskyieldDirectiveClass:
577     K = CXCursor_OMPTaskyieldDirective;
578     break;
579   case Stmt::OMPBarrierDirectiveClass:
580     K = CXCursor_OMPBarrierDirective;
581     break;
582   case Stmt::OMPTaskwaitDirectiveClass:
583     K = CXCursor_OMPTaskwaitDirective;
584     break;
585   case Stmt::OMPTaskgroupDirectiveClass:
586     K = CXCursor_OMPTaskgroupDirective;
587     break;
588   case Stmt::OMPFlushDirectiveClass:
589     K = CXCursor_OMPFlushDirective;
590     break;
591   case Stmt::OMPOrderedDirectiveClass:
592     K = CXCursor_OMPOrderedDirective;
593     break;
594   case Stmt::OMPAtomicDirectiveClass:
595     K = CXCursor_OMPAtomicDirective;
596     break;
597   case Stmt::OMPTargetDirectiveClass:
598     K = CXCursor_OMPTargetDirective;
599     break;
600   case Stmt::OMPTargetDataDirectiveClass:
601     K = CXCursor_OMPTargetDataDirective;
602     break;
603   case Stmt::OMPTeamsDirectiveClass:
604     K = CXCursor_OMPTeamsDirective;
605     break;
606   case Stmt::OMPCancellationPointDirectiveClass:
607     K = CXCursor_OMPCancellationPointDirective;
608     break;
609   case Stmt::OMPCancelDirectiveClass:
610     K = CXCursor_OMPCancelDirective;
611     break;
612   case Stmt::OMPTaskLoopDirectiveClass:
613     K = CXCursor_OMPTaskLoopDirective;
614     break;
615   case Stmt::OMPTaskLoopSimdDirectiveClass:
616     K = CXCursor_OMPTaskLoopSimdDirective;
617     break;
618   case Stmt::OMPDistributeDirectiveClass:
619     K = CXCursor_OMPDistributeDirective;
620     break;
621   }
622 
623   CXCursor C = { K, 0, { Parent, S, TU } };
624   return C;
625 }
626 
MakeCursorObjCSuperClassRef(ObjCInterfaceDecl * Super,SourceLocation Loc,CXTranslationUnit TU)627 CXCursor cxcursor::MakeCursorObjCSuperClassRef(ObjCInterfaceDecl *Super,
628                                                SourceLocation Loc,
629                                                CXTranslationUnit TU) {
630   assert(Super && TU && "Invalid arguments!");
631   void *RawLoc = Loc.getPtrEncoding();
632   CXCursor C = { CXCursor_ObjCSuperClassRef, 0, { Super, RawLoc, TU } };
633   return C;
634 }
635 
636 std::pair<const ObjCInterfaceDecl *, SourceLocation>
getCursorObjCSuperClassRef(CXCursor C)637 cxcursor::getCursorObjCSuperClassRef(CXCursor C) {
638   assert(C.kind == CXCursor_ObjCSuperClassRef);
639   return std::make_pair(static_cast<const ObjCInterfaceDecl *>(C.data[0]),
640                         SourceLocation::getFromPtrEncoding(C.data[1]));
641 }
642 
MakeCursorObjCProtocolRef(const ObjCProtocolDecl * Proto,SourceLocation Loc,CXTranslationUnit TU)643 CXCursor cxcursor::MakeCursorObjCProtocolRef(const ObjCProtocolDecl *Proto,
644                                              SourceLocation Loc,
645                                              CXTranslationUnit TU) {
646   assert(Proto && TU && "Invalid arguments!");
647   void *RawLoc = Loc.getPtrEncoding();
648   CXCursor C = { CXCursor_ObjCProtocolRef, 0, { Proto, RawLoc, TU } };
649   return C;
650 }
651 
652 std::pair<const ObjCProtocolDecl *, SourceLocation>
getCursorObjCProtocolRef(CXCursor C)653 cxcursor::getCursorObjCProtocolRef(CXCursor C) {
654   assert(C.kind == CXCursor_ObjCProtocolRef);
655   return std::make_pair(static_cast<const ObjCProtocolDecl *>(C.data[0]),
656                         SourceLocation::getFromPtrEncoding(C.data[1]));
657 }
658 
MakeCursorObjCClassRef(const ObjCInterfaceDecl * Class,SourceLocation Loc,CXTranslationUnit TU)659 CXCursor cxcursor::MakeCursorObjCClassRef(const ObjCInterfaceDecl *Class,
660                                           SourceLocation Loc,
661                                           CXTranslationUnit TU) {
662   // 'Class' can be null for invalid code.
663   if (!Class)
664     return MakeCXCursorInvalid(CXCursor_InvalidCode);
665   assert(TU && "Invalid arguments!");
666   void *RawLoc = Loc.getPtrEncoding();
667   CXCursor C = { CXCursor_ObjCClassRef, 0, { Class, RawLoc, TU } };
668   return C;
669 }
670 
671 std::pair<const ObjCInterfaceDecl *, SourceLocation>
getCursorObjCClassRef(CXCursor C)672 cxcursor::getCursorObjCClassRef(CXCursor C) {
673   assert(C.kind == CXCursor_ObjCClassRef);
674   return std::make_pair(static_cast<const ObjCInterfaceDecl *>(C.data[0]),
675                         SourceLocation::getFromPtrEncoding(C.data[1]));
676 }
677 
MakeCursorTypeRef(const TypeDecl * Type,SourceLocation Loc,CXTranslationUnit TU)678 CXCursor cxcursor::MakeCursorTypeRef(const TypeDecl *Type, SourceLocation Loc,
679                                      CXTranslationUnit TU) {
680   assert(Type && TU && "Invalid arguments!");
681   void *RawLoc = Loc.getPtrEncoding();
682   CXCursor C = { CXCursor_TypeRef, 0, { Type, RawLoc, TU } };
683   return C;
684 }
685 
686 std::pair<const TypeDecl *, SourceLocation>
getCursorTypeRef(CXCursor C)687 cxcursor::getCursorTypeRef(CXCursor C) {
688   assert(C.kind == CXCursor_TypeRef);
689   return std::make_pair(static_cast<const TypeDecl *>(C.data[0]),
690                         SourceLocation::getFromPtrEncoding(C.data[1]));
691 }
692 
MakeCursorTemplateRef(const TemplateDecl * Template,SourceLocation Loc,CXTranslationUnit TU)693 CXCursor cxcursor::MakeCursorTemplateRef(const TemplateDecl *Template,
694                                          SourceLocation Loc,
695                                          CXTranslationUnit TU) {
696   assert(Template && TU && "Invalid arguments!");
697   void *RawLoc = Loc.getPtrEncoding();
698   CXCursor C = { CXCursor_TemplateRef, 0, { Template, RawLoc, TU } };
699   return C;
700 }
701 
702 std::pair<const TemplateDecl *, SourceLocation>
getCursorTemplateRef(CXCursor C)703 cxcursor::getCursorTemplateRef(CXCursor C) {
704   assert(C.kind == CXCursor_TemplateRef);
705   return std::make_pair(static_cast<const TemplateDecl *>(C.data[0]),
706                         SourceLocation::getFromPtrEncoding(C.data[1]));
707 }
708 
MakeCursorNamespaceRef(const NamedDecl * NS,SourceLocation Loc,CXTranslationUnit TU)709 CXCursor cxcursor::MakeCursorNamespaceRef(const NamedDecl *NS,
710                                           SourceLocation Loc,
711                                           CXTranslationUnit TU) {
712 
713   assert(NS && (isa<NamespaceDecl>(NS) || isa<NamespaceAliasDecl>(NS)) && TU &&
714          "Invalid arguments!");
715   void *RawLoc = Loc.getPtrEncoding();
716   CXCursor C = { CXCursor_NamespaceRef, 0, { NS, RawLoc, TU } };
717   return C;
718 }
719 
720 std::pair<const NamedDecl *, SourceLocation>
getCursorNamespaceRef(CXCursor C)721 cxcursor::getCursorNamespaceRef(CXCursor C) {
722   assert(C.kind == CXCursor_NamespaceRef);
723   return std::make_pair(static_cast<const NamedDecl *>(C.data[0]),
724                         SourceLocation::getFromPtrEncoding(C.data[1]));
725 }
726 
MakeCursorVariableRef(const VarDecl * Var,SourceLocation Loc,CXTranslationUnit TU)727 CXCursor cxcursor::MakeCursorVariableRef(const VarDecl *Var, SourceLocation Loc,
728                                          CXTranslationUnit TU) {
729 
730   assert(Var && TU && "Invalid arguments!");
731   void *RawLoc = Loc.getPtrEncoding();
732   CXCursor C = { CXCursor_VariableRef, 0, { Var, RawLoc, TU } };
733   return C;
734 }
735 
736 std::pair<const VarDecl *, SourceLocation>
getCursorVariableRef(CXCursor C)737 cxcursor::getCursorVariableRef(CXCursor C) {
738   assert(C.kind == CXCursor_VariableRef);
739   return std::make_pair(static_cast<const VarDecl *>(C.data[0]),
740                         SourceLocation::getFromPtrEncoding(C.data[1]));
741 }
742 
MakeCursorMemberRef(const FieldDecl * Field,SourceLocation Loc,CXTranslationUnit TU)743 CXCursor cxcursor::MakeCursorMemberRef(const FieldDecl *Field, SourceLocation Loc,
744                                        CXTranslationUnit TU) {
745 
746   assert(Field && TU && "Invalid arguments!");
747   void *RawLoc = Loc.getPtrEncoding();
748   CXCursor C = { CXCursor_MemberRef, 0, { Field, RawLoc, TU } };
749   return C;
750 }
751 
752 std::pair<const FieldDecl *, SourceLocation>
getCursorMemberRef(CXCursor C)753 cxcursor::getCursorMemberRef(CXCursor C) {
754   assert(C.kind == CXCursor_MemberRef);
755   return std::make_pair(static_cast<const FieldDecl *>(C.data[0]),
756                         SourceLocation::getFromPtrEncoding(C.data[1]));
757 }
758 
MakeCursorCXXBaseSpecifier(const CXXBaseSpecifier * B,CXTranslationUnit TU)759 CXCursor cxcursor::MakeCursorCXXBaseSpecifier(const CXXBaseSpecifier *B,
760                                               CXTranslationUnit TU){
761   CXCursor C = { CXCursor_CXXBaseSpecifier, 0, { B, nullptr, TU } };
762   return C;
763 }
764 
getCursorCXXBaseSpecifier(CXCursor C)765 const CXXBaseSpecifier *cxcursor::getCursorCXXBaseSpecifier(CXCursor C) {
766   assert(C.kind == CXCursor_CXXBaseSpecifier);
767   return static_cast<const CXXBaseSpecifier*>(C.data[0]);
768 }
769 
MakePreprocessingDirectiveCursor(SourceRange Range,CXTranslationUnit TU)770 CXCursor cxcursor::MakePreprocessingDirectiveCursor(SourceRange Range,
771                                                     CXTranslationUnit TU) {
772   CXCursor C = { CXCursor_PreprocessingDirective, 0,
773                  { Range.getBegin().getPtrEncoding(),
774                    Range.getEnd().getPtrEncoding(),
775                    TU }
776                };
777   return C;
778 }
779 
getCursorPreprocessingDirective(CXCursor C)780 SourceRange cxcursor::getCursorPreprocessingDirective(CXCursor C) {
781   assert(C.kind == CXCursor_PreprocessingDirective);
782   SourceRange Range(SourceLocation::getFromPtrEncoding(C.data[0]),
783                     SourceLocation::getFromPtrEncoding(C.data[1]));
784   ASTUnit *TU = getCursorASTUnit(C);
785   return TU->mapRangeFromPreamble(Range);
786 }
787 
MakeMacroDefinitionCursor(const MacroDefinitionRecord * MI,CXTranslationUnit TU)788 CXCursor cxcursor::MakeMacroDefinitionCursor(const MacroDefinitionRecord *MI,
789                                              CXTranslationUnit TU) {
790   CXCursor C = {CXCursor_MacroDefinition, 0, {MI, nullptr, TU}};
791   return C;
792 }
793 
getCursorMacroDefinition(CXCursor C)794 const MacroDefinitionRecord *cxcursor::getCursorMacroDefinition(CXCursor C) {
795   assert(C.kind == CXCursor_MacroDefinition);
796   return static_cast<const MacroDefinitionRecord *>(C.data[0]);
797 }
798 
MakeMacroExpansionCursor(MacroExpansion * MI,CXTranslationUnit TU)799 CXCursor cxcursor::MakeMacroExpansionCursor(MacroExpansion *MI,
800                                             CXTranslationUnit TU) {
801   CXCursor C = { CXCursor_MacroExpansion, 0, { MI, nullptr, TU } };
802   return C;
803 }
804 
MakeMacroExpansionCursor(MacroDefinitionRecord * MI,SourceLocation Loc,CXTranslationUnit TU)805 CXCursor cxcursor::MakeMacroExpansionCursor(MacroDefinitionRecord *MI,
806                                             SourceLocation Loc,
807                                             CXTranslationUnit TU) {
808   assert(Loc.isValid());
809   CXCursor C = {CXCursor_MacroExpansion, 0, {MI, Loc.getPtrEncoding(), TU}};
810   return C;
811 }
812 
getName() const813 const IdentifierInfo *cxcursor::MacroExpansionCursor::getName() const {
814   if (isPseudo())
815     return getAsMacroDefinition()->getName();
816   return getAsMacroExpansion()->getName();
817 }
818 const MacroDefinitionRecord *
getDefinition() const819 cxcursor::MacroExpansionCursor::getDefinition() const {
820   if (isPseudo())
821     return getAsMacroDefinition();
822   return getAsMacroExpansion()->getDefinition();
823 }
getSourceRange() const824 SourceRange cxcursor::MacroExpansionCursor::getSourceRange() const {
825   if (isPseudo())
826     return getPseudoLoc();
827   return getAsMacroExpansion()->getSourceRange();
828 }
829 
MakeInclusionDirectiveCursor(InclusionDirective * ID,CXTranslationUnit TU)830 CXCursor cxcursor::MakeInclusionDirectiveCursor(InclusionDirective *ID,
831                                                 CXTranslationUnit TU) {
832   CXCursor C = { CXCursor_InclusionDirective, 0, { ID, nullptr, TU } };
833   return C;
834 }
835 
getCursorInclusionDirective(CXCursor C)836 const InclusionDirective *cxcursor::getCursorInclusionDirective(CXCursor C) {
837   assert(C.kind == CXCursor_InclusionDirective);
838   return static_cast<const InclusionDirective *>(C.data[0]);
839 }
840 
MakeCursorLabelRef(LabelStmt * Label,SourceLocation Loc,CXTranslationUnit TU)841 CXCursor cxcursor::MakeCursorLabelRef(LabelStmt *Label, SourceLocation Loc,
842                                       CXTranslationUnit TU) {
843 
844   assert(Label && TU && "Invalid arguments!");
845   void *RawLoc = Loc.getPtrEncoding();
846   CXCursor C = { CXCursor_LabelRef, 0, { Label, RawLoc, TU } };
847   return C;
848 }
849 
850 std::pair<const LabelStmt *, SourceLocation>
getCursorLabelRef(CXCursor C)851 cxcursor::getCursorLabelRef(CXCursor C) {
852   assert(C.kind == CXCursor_LabelRef);
853   return std::make_pair(static_cast<const LabelStmt *>(C.data[0]),
854                         SourceLocation::getFromPtrEncoding(C.data[1]));
855 }
856 
MakeCursorOverloadedDeclRef(const OverloadExpr * E,CXTranslationUnit TU)857 CXCursor cxcursor::MakeCursorOverloadedDeclRef(const OverloadExpr *E,
858                                                CXTranslationUnit TU) {
859   assert(E && TU && "Invalid arguments!");
860   OverloadedDeclRefStorage Storage(E);
861   void *RawLoc = E->getNameLoc().getPtrEncoding();
862   CXCursor C = {
863                  CXCursor_OverloadedDeclRef, 0,
864                  { Storage.getOpaqueValue(), RawLoc, TU }
865                };
866   return C;
867 }
868 
MakeCursorOverloadedDeclRef(const Decl * D,SourceLocation Loc,CXTranslationUnit TU)869 CXCursor cxcursor::MakeCursorOverloadedDeclRef(const Decl *D,
870                                                SourceLocation Loc,
871                                                CXTranslationUnit TU) {
872   assert(D && TU && "Invalid arguments!");
873   void *RawLoc = Loc.getPtrEncoding();
874   OverloadedDeclRefStorage Storage(D);
875   CXCursor C = {
876     CXCursor_OverloadedDeclRef, 0,
877     { Storage.getOpaqueValue(), RawLoc, TU }
878   };
879   return C;
880 }
881 
MakeCursorOverloadedDeclRef(TemplateName Name,SourceLocation Loc,CXTranslationUnit TU)882 CXCursor cxcursor::MakeCursorOverloadedDeclRef(TemplateName Name,
883                                                SourceLocation Loc,
884                                                CXTranslationUnit TU) {
885   assert(Name.getAsOverloadedTemplate() && TU && "Invalid arguments!");
886   void *RawLoc = Loc.getPtrEncoding();
887   OverloadedDeclRefStorage Storage(Name.getAsOverloadedTemplate());
888   CXCursor C = {
889     CXCursor_OverloadedDeclRef, 0,
890     { Storage.getOpaqueValue(), RawLoc, TU }
891   };
892   return C;
893 }
894 
895 std::pair<cxcursor::OverloadedDeclRefStorage, SourceLocation>
getCursorOverloadedDeclRef(CXCursor C)896 cxcursor::getCursorOverloadedDeclRef(CXCursor C) {
897   assert(C.kind == CXCursor_OverloadedDeclRef);
898   return std::make_pair(OverloadedDeclRefStorage::getFromOpaqueValue(
899                                        const_cast<void *>(C.data[0])),
900                         SourceLocation::getFromPtrEncoding(C.data[1]));
901 }
902 
getCursorDecl(CXCursor Cursor)903 const Decl *cxcursor::getCursorDecl(CXCursor Cursor) {
904   return static_cast<const Decl *>(Cursor.data[0]);
905 }
906 
getCursorExpr(CXCursor Cursor)907 const Expr *cxcursor::getCursorExpr(CXCursor Cursor) {
908   return dyn_cast_or_null<Expr>(getCursorStmt(Cursor));
909 }
910 
getCursorStmt(CXCursor Cursor)911 const Stmt *cxcursor::getCursorStmt(CXCursor Cursor) {
912   if (Cursor.kind == CXCursor_ObjCSuperClassRef ||
913       Cursor.kind == CXCursor_ObjCProtocolRef ||
914       Cursor.kind == CXCursor_ObjCClassRef)
915     return nullptr;
916 
917   return static_cast<const Stmt *>(Cursor.data[1]);
918 }
919 
getCursorAttr(CXCursor Cursor)920 const Attr *cxcursor::getCursorAttr(CXCursor Cursor) {
921   return static_cast<const Attr *>(Cursor.data[1]);
922 }
923 
getCursorParentDecl(CXCursor Cursor)924 const Decl *cxcursor::getCursorParentDecl(CXCursor Cursor) {
925   return static_cast<const Decl *>(Cursor.data[0]);
926 }
927 
getCursorContext(CXCursor Cursor)928 ASTContext &cxcursor::getCursorContext(CXCursor Cursor) {
929   return getCursorASTUnit(Cursor)->getASTContext();
930 }
931 
getCursorASTUnit(CXCursor Cursor)932 ASTUnit *cxcursor::getCursorASTUnit(CXCursor Cursor) {
933   CXTranslationUnit TU = getCursorTU(Cursor);
934   if (!TU)
935     return nullptr;
936   return cxtu::getASTUnit(TU);
937 }
938 
getCursorTU(CXCursor Cursor)939 CXTranslationUnit cxcursor::getCursorTU(CXCursor Cursor) {
940   return static_cast<CXTranslationUnit>(const_cast<void*>(Cursor.data[2]));
941 }
942 
getOverriddenCursors(CXCursor cursor,SmallVectorImpl<CXCursor> & overridden)943 void cxcursor::getOverriddenCursors(CXCursor cursor,
944                                     SmallVectorImpl<CXCursor> &overridden) {
945   assert(clang_isDeclaration(cursor.kind));
946   const NamedDecl *D = dyn_cast_or_null<NamedDecl>(getCursorDecl(cursor));
947   if (!D)
948     return;
949 
950   CXTranslationUnit TU = getCursorTU(cursor);
951   SmallVector<const NamedDecl *, 8> OverDecls;
952   D->getASTContext().getOverriddenMethods(D, OverDecls);
953 
954   for (SmallVectorImpl<const NamedDecl *>::iterator
955          I = OverDecls.begin(), E = OverDecls.end(); I != E; ++I) {
956     overridden.push_back(MakeCXCursor(*I, TU));
957   }
958 }
959 
960 std::pair<int, SourceLocation>
getSelectorIdentifierIndexAndLoc(CXCursor cursor)961 cxcursor::getSelectorIdentifierIndexAndLoc(CXCursor cursor) {
962   if (cursor.kind == CXCursor_ObjCMessageExpr) {
963     if (cursor.xdata != -1)
964       return std::make_pair(cursor.xdata,
965                             cast<ObjCMessageExpr>(getCursorExpr(cursor))
966                                                 ->getSelectorLoc(cursor.xdata));
967   } else if (cursor.kind == CXCursor_ObjCClassMethodDecl ||
968              cursor.kind == CXCursor_ObjCInstanceMethodDecl) {
969     if (cursor.xdata != -1)
970       return std::make_pair(cursor.xdata,
971                             cast<ObjCMethodDecl>(getCursorDecl(cursor))
972                                                 ->getSelectorLoc(cursor.xdata));
973   }
974 
975   return std::make_pair(-1, SourceLocation());
976 }
977 
getSelectorIdentifierCursor(int SelIdx,CXCursor cursor)978 CXCursor cxcursor::getSelectorIdentifierCursor(int SelIdx, CXCursor cursor) {
979   CXCursor newCursor = cursor;
980 
981   if (cursor.kind == CXCursor_ObjCMessageExpr) {
982     if (SelIdx == -1 ||
983         unsigned(SelIdx) >= cast<ObjCMessageExpr>(getCursorExpr(cursor))
984                                                          ->getNumSelectorLocs())
985       newCursor.xdata = -1;
986     else
987       newCursor.xdata = SelIdx;
988   } else if (cursor.kind == CXCursor_ObjCClassMethodDecl ||
989              cursor.kind == CXCursor_ObjCInstanceMethodDecl) {
990     if (SelIdx == -1 ||
991         unsigned(SelIdx) >= cast<ObjCMethodDecl>(getCursorDecl(cursor))
992                                                          ->getNumSelectorLocs())
993       newCursor.xdata = -1;
994     else
995       newCursor.xdata = SelIdx;
996   }
997 
998   return newCursor;
999 }
1000 
getTypeRefCursor(CXCursor cursor)1001 CXCursor cxcursor::getTypeRefCursor(CXCursor cursor) {
1002   if (cursor.kind != CXCursor_CallExpr)
1003     return cursor;
1004 
1005   if (cursor.xdata == 0)
1006     return cursor;
1007 
1008   const Expr *E = getCursorExpr(cursor);
1009   TypeSourceInfo *Type = nullptr;
1010   if (const CXXUnresolvedConstructExpr *
1011         UnCtor = dyn_cast<CXXUnresolvedConstructExpr>(E)) {
1012     Type = UnCtor->getTypeSourceInfo();
1013   } else if (const CXXTemporaryObjectExpr *Tmp =
1014                  dyn_cast<CXXTemporaryObjectExpr>(E)){
1015     Type = Tmp->getTypeSourceInfo();
1016   }
1017 
1018   if (!Type)
1019     return cursor;
1020 
1021   CXTranslationUnit TU = getCursorTU(cursor);
1022   QualType Ty = Type->getType();
1023   TypeLoc TL = Type->getTypeLoc();
1024   SourceLocation Loc = TL.getBeginLoc();
1025 
1026   if (const ElaboratedType *ElabT = Ty->getAs<ElaboratedType>()) {
1027     Ty = ElabT->getNamedType();
1028     ElaboratedTypeLoc ElabTL = TL.castAs<ElaboratedTypeLoc>();
1029     Loc = ElabTL.getNamedTypeLoc().getBeginLoc();
1030   }
1031 
1032   if (const TypedefType *Typedef = Ty->getAs<TypedefType>())
1033     return MakeCursorTypeRef(Typedef->getDecl(), Loc, TU);
1034   if (const TagType *Tag = Ty->getAs<TagType>())
1035     return MakeCursorTypeRef(Tag->getDecl(), Loc, TU);
1036   if (const TemplateTypeParmType *TemplP = Ty->getAs<TemplateTypeParmType>())
1037     return MakeCursorTypeRef(TemplP->getDecl(), Loc, TU);
1038 
1039   return cursor;
1040 }
1041 
operator ==(CXCursor X,CXCursor Y)1042 bool cxcursor::operator==(CXCursor X, CXCursor Y) {
1043   return X.kind == Y.kind && X.data[0] == Y.data[0] && X.data[1] == Y.data[1] &&
1044          X.data[2] == Y.data[2];
1045 }
1046 
1047 // FIXME: Remove once we can model DeclGroups and their appropriate ranges
1048 // properly in the ASTs.
isFirstInDeclGroup(CXCursor C)1049 bool cxcursor::isFirstInDeclGroup(CXCursor C) {
1050   assert(clang_isDeclaration(C.kind));
1051   return ((uintptr_t) (C.data[1])) != 0;
1052 }
1053 
1054 //===----------------------------------------------------------------------===//
1055 // libclang CXCursor APIs
1056 //===----------------------------------------------------------------------===//
1057 
1058 extern "C" {
1059 
clang_Cursor_isNull(CXCursor cursor)1060 int clang_Cursor_isNull(CXCursor cursor) {
1061   return clang_equalCursors(cursor, clang_getNullCursor());
1062 }
1063 
clang_Cursor_getTranslationUnit(CXCursor cursor)1064 CXTranslationUnit clang_Cursor_getTranslationUnit(CXCursor cursor) {
1065   return getCursorTU(cursor);
1066 }
1067 
clang_Cursor_getNumArguments(CXCursor C)1068 int clang_Cursor_getNumArguments(CXCursor C) {
1069   if (clang_isDeclaration(C.kind)) {
1070     const Decl *D = cxcursor::getCursorDecl(C);
1071     if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
1072       return MD->param_size();
1073     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
1074       return FD->param_size();
1075   }
1076 
1077   if (clang_isExpression(C.kind)) {
1078     const Expr *E = cxcursor::getCursorExpr(C);
1079     if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1080       return CE->getNumArgs();
1081     }
1082   }
1083 
1084   return -1;
1085 }
1086 
clang_Cursor_getArgument(CXCursor C,unsigned i)1087 CXCursor clang_Cursor_getArgument(CXCursor C, unsigned i) {
1088   if (clang_isDeclaration(C.kind)) {
1089     const Decl *D = cxcursor::getCursorDecl(C);
1090     if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
1091       if (i < MD->param_size())
1092         return cxcursor::MakeCXCursor(MD->parameters()[i],
1093                                       cxcursor::getCursorTU(C));
1094     } else if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
1095       if (i < FD->param_size())
1096         return cxcursor::MakeCXCursor(FD->parameters()[i],
1097                                       cxcursor::getCursorTU(C));
1098     }
1099   }
1100 
1101   if (clang_isExpression(C.kind)) {
1102     const Expr *E = cxcursor::getCursorExpr(C);
1103     if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1104       if (i < CE->getNumArgs()) {
1105         return cxcursor::MakeCXCursor(CE->getArg(i),
1106                                       getCursorDecl(C),
1107                                       cxcursor::getCursorTU(C));
1108       }
1109     }
1110   }
1111 
1112   return clang_getNullCursor();
1113 }
1114 
clang_Cursor_getNumTemplateArguments(CXCursor C)1115 int clang_Cursor_getNumTemplateArguments(CXCursor C) {
1116   if (clang_getCursorKind(C) != CXCursor_FunctionDecl) {
1117     return -1;
1118   }
1119 
1120   const FunctionDecl *FD = llvm::dyn_cast_or_null<clang::FunctionDecl>(
1121       getCursorDecl(C));
1122   if (!FD) {
1123     return -1;
1124   }
1125 
1126   const FunctionTemplateSpecializationInfo* SpecInfo =
1127       FD->getTemplateSpecializationInfo();
1128   if (!SpecInfo) {
1129     return -1;
1130   }
1131 
1132   return SpecInfo->TemplateArguments->size();
1133 }
1134 
1135 enum CXGetTemplateArgumentStatus {
1136   /** \brief The operation completed successfully */
1137   CXGetTemplateArgumentStatus_Success = 0,
1138 
1139   /** \brief The specified cursor did not represent a FunctionDecl. */
1140   CXGetTemplateArgumentStatus_CursorNotFunctionDecl = -1,
1141 
1142   /** \brief The specified cursor was not castable to a FunctionDecl. */
1143   CXGetTemplateArgumentStatus_BadFunctionDeclCast = -2,
1144 
1145   /** \brief A NULL FunctionTemplateSpecializationInfo was retrieved. */
1146   CXGetTemplateArgumentStatus_NullTemplSpecInfo = -3,
1147 
1148   /** \brief An invalid (OOB) argument index was specified */
1149   CXGetTemplateArgumentStatus_InvalidIndex = -4
1150 };
1151 
clang_Cursor_getTemplateArgument(CXCursor C,unsigned I,TemplateArgument * TA)1152 static int clang_Cursor_getTemplateArgument(
1153     CXCursor C, unsigned I, TemplateArgument *TA) {
1154   if (clang_getCursorKind(C) != CXCursor_FunctionDecl) {
1155     return CXGetTemplateArgumentStatus_CursorNotFunctionDecl;
1156   }
1157 
1158   const FunctionDecl *FD = llvm::dyn_cast_or_null<clang::FunctionDecl>(
1159       getCursorDecl(C));
1160   if (!FD) {
1161     return CXGetTemplateArgumentStatus_BadFunctionDeclCast;
1162   }
1163 
1164   const FunctionTemplateSpecializationInfo* SpecInfo =
1165       FD->getTemplateSpecializationInfo();
1166   if (!SpecInfo) {
1167     return CXGetTemplateArgumentStatus_NullTemplSpecInfo;
1168   }
1169 
1170   if (I >= SpecInfo->TemplateArguments->size()) {
1171     return CXGetTemplateArgumentStatus_InvalidIndex;
1172   }
1173 
1174   *TA = SpecInfo->TemplateArguments->get(I);
1175   return 0;
1176 }
1177 
clang_Cursor_getTemplateArgumentKind(CXCursor C,unsigned I)1178 enum CXTemplateArgumentKind clang_Cursor_getTemplateArgumentKind(CXCursor C,
1179                                                                  unsigned I) {
1180   TemplateArgument TA;
1181   if (clang_Cursor_getTemplateArgument(C, I, &TA)) {
1182     return CXTemplateArgumentKind_Invalid;
1183   }
1184 
1185   switch (TA.getKind()) {
1186     case TemplateArgument::Null: return CXTemplateArgumentKind_Null;
1187     case TemplateArgument::Type: return CXTemplateArgumentKind_Type;
1188     case TemplateArgument::Declaration:
1189       return CXTemplateArgumentKind_Declaration;
1190     case TemplateArgument::NullPtr: return CXTemplateArgumentKind_NullPtr;
1191     case TemplateArgument::Integral: return CXTemplateArgumentKind_Integral;
1192     case TemplateArgument::Template: return CXTemplateArgumentKind_Template;
1193     case TemplateArgument::TemplateExpansion:
1194       return CXTemplateArgumentKind_TemplateExpansion;
1195     case TemplateArgument::Expression: return CXTemplateArgumentKind_Expression;
1196     case TemplateArgument::Pack: return CXTemplateArgumentKind_Pack;
1197   }
1198 
1199   return CXTemplateArgumentKind_Invalid;
1200 }
1201 
clang_Cursor_getTemplateArgumentType(CXCursor C,unsigned I)1202 CXType clang_Cursor_getTemplateArgumentType(CXCursor C, unsigned I) {
1203   TemplateArgument TA;
1204   if (clang_Cursor_getTemplateArgument(C, I, &TA) !=
1205       CXGetTemplateArgumentStatus_Success) {
1206     return cxtype::MakeCXType(QualType(), getCursorTU(C));
1207   }
1208 
1209   if (TA.getKind() != TemplateArgument::Type) {
1210     return cxtype::MakeCXType(QualType(), getCursorTU(C));
1211   }
1212 
1213   return cxtype::MakeCXType(TA.getAsType(), getCursorTU(C));
1214 }
1215 
clang_Cursor_getTemplateArgumentValue(CXCursor C,unsigned I)1216 long long clang_Cursor_getTemplateArgumentValue(CXCursor C, unsigned I) {
1217   TemplateArgument TA;
1218   if (clang_Cursor_getTemplateArgument(C, I, &TA) !=
1219       CXGetTemplateArgumentStatus_Success) {
1220     assert(0 && "Unable to retrieve TemplateArgument");
1221     return 0;
1222   }
1223 
1224   if (TA.getKind() != TemplateArgument::Integral) {
1225     assert(0 && "Passed template argument is not Integral");
1226     return 0;
1227   }
1228 
1229   return TA.getAsIntegral().getSExtValue();
1230 }
1231 
clang_Cursor_getTemplateArgumentUnsignedValue(CXCursor C,unsigned I)1232 unsigned long long clang_Cursor_getTemplateArgumentUnsignedValue(CXCursor C,
1233                                                                  unsigned I) {
1234   TemplateArgument TA;
1235   if (clang_Cursor_getTemplateArgument(C, I, &TA) !=
1236       CXGetTemplateArgumentStatus_Success) {
1237     assert(0 && "Unable to retrieve TemplateArgument");
1238     return 0;
1239   }
1240 
1241   if (TA.getKind() != TemplateArgument::Integral) {
1242     assert(0 && "Passed template argument is not Integral");
1243     return 0;
1244   }
1245 
1246   return TA.getAsIntegral().getZExtValue();
1247 }
1248 
1249 } // end: extern "C"
1250 
1251 //===----------------------------------------------------------------------===//
1252 // CXCursorSet.
1253 //===----------------------------------------------------------------------===//
1254 
1255 typedef llvm::DenseMap<CXCursor, unsigned> CXCursorSet_Impl;
1256 
packCXCursorSet(CXCursorSet_Impl * setImpl)1257 static inline CXCursorSet packCXCursorSet(CXCursorSet_Impl *setImpl) {
1258   return (CXCursorSet) setImpl;
1259 }
unpackCXCursorSet(CXCursorSet set)1260 static inline CXCursorSet_Impl *unpackCXCursorSet(CXCursorSet set) {
1261   return (CXCursorSet_Impl*) set;
1262 }
1263 namespace llvm {
1264 template<> struct DenseMapInfo<CXCursor> {
1265 public:
getEmptyKeyllvm::DenseMapInfo1266   static inline CXCursor getEmptyKey() {
1267     return MakeCXCursorInvalid(CXCursor_InvalidFile);
1268   }
getTombstoneKeyllvm::DenseMapInfo1269   static inline CXCursor getTombstoneKey() {
1270     return MakeCXCursorInvalid(CXCursor_NoDeclFound);
1271   }
getHashValuellvm::DenseMapInfo1272   static inline unsigned getHashValue(const CXCursor &cursor) {
1273     return llvm::DenseMapInfo<std::pair<const void *, const void *> >
1274       ::getHashValue(std::make_pair(cursor.data[0], cursor.data[1]));
1275   }
isEqualllvm::DenseMapInfo1276   static inline bool isEqual(const CXCursor &x, const CXCursor &y) {
1277     return x.kind == y.kind &&
1278            x.data[0] == y.data[0] &&
1279            x.data[1] == y.data[1];
1280   }
1281 };
1282 }
1283 
1284 extern "C" {
clang_createCXCursorSet()1285 CXCursorSet clang_createCXCursorSet() {
1286   return packCXCursorSet(new CXCursorSet_Impl());
1287 }
1288 
clang_disposeCXCursorSet(CXCursorSet set)1289 void clang_disposeCXCursorSet(CXCursorSet set) {
1290   delete unpackCXCursorSet(set);
1291 }
1292 
clang_CXCursorSet_contains(CXCursorSet set,CXCursor cursor)1293 unsigned clang_CXCursorSet_contains(CXCursorSet set, CXCursor cursor) {
1294   CXCursorSet_Impl *setImpl = unpackCXCursorSet(set);
1295   if (!setImpl)
1296     return 0;
1297   return setImpl->find(cursor) != setImpl->end();
1298 }
1299 
clang_CXCursorSet_insert(CXCursorSet set,CXCursor cursor)1300 unsigned clang_CXCursorSet_insert(CXCursorSet set, CXCursor cursor) {
1301   // Do not insert invalid cursors into the set.
1302   if (cursor.kind >= CXCursor_FirstInvalid &&
1303       cursor.kind <= CXCursor_LastInvalid)
1304     return 1;
1305 
1306   CXCursorSet_Impl *setImpl = unpackCXCursorSet(set);
1307   if (!setImpl)
1308     return 1;
1309   unsigned &entry = (*setImpl)[cursor];
1310   unsigned flag = entry == 0 ? 1 : 0;
1311   entry = 1;
1312   return flag;
1313 }
1314 
clang_getCursorCompletionString(CXCursor cursor)1315 CXCompletionString clang_getCursorCompletionString(CXCursor cursor) {
1316   enum CXCursorKind kind = clang_getCursorKind(cursor);
1317   if (clang_isDeclaration(kind)) {
1318     const Decl *decl = getCursorDecl(cursor);
1319     if (const NamedDecl *namedDecl = dyn_cast_or_null<NamedDecl>(decl)) {
1320       ASTUnit *unit = getCursorASTUnit(cursor);
1321       CodeCompletionResult Result(namedDecl, CCP_Declaration);
1322       CodeCompletionString *String
1323         = Result.CreateCodeCompletionString(unit->getASTContext(),
1324                                             unit->getPreprocessor(),
1325                                             CodeCompletionContext::CCC_Other,
1326                                  unit->getCodeCompletionTUInfo().getAllocator(),
1327                                  unit->getCodeCompletionTUInfo(),
1328                                  true);
1329       return String;
1330     }
1331   } else if (kind == CXCursor_MacroDefinition) {
1332     const MacroDefinitionRecord *definition = getCursorMacroDefinition(cursor);
1333     const IdentifierInfo *MacroInfo = definition->getName();
1334     ASTUnit *unit = getCursorASTUnit(cursor);
1335     CodeCompletionResult Result(MacroInfo);
1336     CodeCompletionString *String
1337       = Result.CreateCodeCompletionString(unit->getASTContext(),
1338                                           unit->getPreprocessor(),
1339                                           CodeCompletionContext::CCC_Other,
1340                                  unit->getCodeCompletionTUInfo().getAllocator(),
1341                                  unit->getCodeCompletionTUInfo(),
1342                                  false);
1343     return String;
1344   }
1345   return nullptr;
1346 }
1347 } // end: extern C.
1348 
1349 namespace {
1350   struct OverridenCursorsPool {
1351     typedef SmallVector<CXCursor, 2> CursorVec;
1352     std::vector<CursorVec*> AllCursors;
1353     std::vector<CursorVec*> AvailableCursors;
1354 
~OverridenCursorsPool__anon183437c60111::OverridenCursorsPool1355     ~OverridenCursorsPool() {
1356       for (std::vector<CursorVec*>::iterator I = AllCursors.begin(),
1357            E = AllCursors.end(); I != E; ++I) {
1358         delete *I;
1359       }
1360     }
1361   };
1362 }
1363 
createOverridenCXCursorsPool()1364 void *cxcursor::createOverridenCXCursorsPool() {
1365   return new OverridenCursorsPool();
1366 }
1367 
disposeOverridenCXCursorsPool(void * pool)1368 void cxcursor::disposeOverridenCXCursorsPool(void *pool) {
1369   delete static_cast<OverridenCursorsPool*>(pool);
1370 }
1371 
1372 extern "C" {
clang_getOverriddenCursors(CXCursor cursor,CXCursor ** overridden,unsigned * num_overridden)1373 void clang_getOverriddenCursors(CXCursor cursor,
1374                                 CXCursor **overridden,
1375                                 unsigned *num_overridden) {
1376   if (overridden)
1377     *overridden = nullptr;
1378   if (num_overridden)
1379     *num_overridden = 0;
1380 
1381   CXTranslationUnit TU = cxcursor::getCursorTU(cursor);
1382 
1383   if (!overridden || !num_overridden || !TU)
1384     return;
1385 
1386   if (!clang_isDeclaration(cursor.kind))
1387     return;
1388 
1389   OverridenCursorsPool &pool =
1390     *static_cast<OverridenCursorsPool*>(TU->OverridenCursorsPool);
1391 
1392   OverridenCursorsPool::CursorVec *Vec = nullptr;
1393 
1394   if (!pool.AvailableCursors.empty()) {
1395     Vec = pool.AvailableCursors.back();
1396     pool.AvailableCursors.pop_back();
1397   }
1398   else {
1399     Vec = new OverridenCursorsPool::CursorVec();
1400     pool.AllCursors.push_back(Vec);
1401   }
1402 
1403   // Clear out the vector, but don't free the memory contents.  This
1404   // reduces malloc() traffic.
1405   Vec->clear();
1406 
1407   // Use the first entry to contain a back reference to the vector.
1408   // This is a complete hack.
1409   CXCursor backRefCursor = MakeCXCursorInvalid(CXCursor_InvalidFile, TU);
1410   backRefCursor.data[0] = Vec;
1411   assert(cxcursor::getCursorTU(backRefCursor) == TU);
1412   Vec->push_back(backRefCursor);
1413 
1414   // Get the overriden cursors.
1415   cxcursor::getOverriddenCursors(cursor, *Vec);
1416 
1417   // Did we get any overriden cursors?  If not, return Vec to the pool
1418   // of available cursor vectors.
1419   if (Vec->size() == 1) {
1420     pool.AvailableCursors.push_back(Vec);
1421     return;
1422   }
1423 
1424   // Now tell the caller about the overriden cursors.
1425   assert(Vec->size() > 1);
1426   *overridden = &((*Vec)[1]);
1427   *num_overridden = Vec->size() - 1;
1428 }
1429 
clang_disposeOverriddenCursors(CXCursor * overridden)1430 void clang_disposeOverriddenCursors(CXCursor *overridden) {
1431   if (!overridden)
1432     return;
1433 
1434   // Use pointer arithmetic to get back the first faux entry
1435   // which has a back-reference to the TU and the vector.
1436   --overridden;
1437   OverridenCursorsPool::CursorVec *Vec =
1438       static_cast<OverridenCursorsPool::CursorVec *>(
1439           const_cast<void *>(overridden->data[0]));
1440   CXTranslationUnit TU = getCursorTU(*overridden);
1441 
1442   assert(Vec && TU);
1443 
1444   OverridenCursorsPool &pool =
1445     *static_cast<OverridenCursorsPool*>(TU->OverridenCursorsPool);
1446 
1447   pool.AvailableCursors.push_back(Vec);
1448 }
1449 
clang_Cursor_isDynamicCall(CXCursor C)1450 int clang_Cursor_isDynamicCall(CXCursor C) {
1451   const Expr *E = nullptr;
1452   if (clang_isExpression(C.kind))
1453     E = getCursorExpr(C);
1454   if (!E)
1455     return 0;
1456 
1457   if (const ObjCMessageExpr *MsgE = dyn_cast<ObjCMessageExpr>(E)) {
1458     if (MsgE->getReceiverKind() != ObjCMessageExpr::Instance)
1459       return false;
1460     if (auto *RecE = dyn_cast<ObjCMessageExpr>(
1461             MsgE->getInstanceReceiver()->IgnoreParenCasts())) {
1462       if (RecE->getMethodFamily() == OMF_alloc)
1463         return false;
1464     }
1465     return true;
1466   }
1467 
1468   const MemberExpr *ME = nullptr;
1469   if (isa<MemberExpr>(E))
1470     ME = cast<MemberExpr>(E);
1471   else if (const CallExpr *CE = dyn_cast<CallExpr>(E))
1472     ME = dyn_cast_or_null<MemberExpr>(CE->getCallee());
1473 
1474   if (ME) {
1475     if (const CXXMethodDecl *
1476           MD = dyn_cast_or_null<CXXMethodDecl>(ME->getMemberDecl()))
1477       return MD->isVirtual() && !ME->hasQualifier();
1478   }
1479 
1480   return 0;
1481 }
1482 
clang_Cursor_getReceiverType(CXCursor C)1483 CXType clang_Cursor_getReceiverType(CXCursor C) {
1484   CXTranslationUnit TU = cxcursor::getCursorTU(C);
1485   const Expr *E = nullptr;
1486   if (clang_isExpression(C.kind))
1487     E = getCursorExpr(C);
1488 
1489   if (const ObjCMessageExpr *MsgE = dyn_cast_or_null<ObjCMessageExpr>(E))
1490     return cxtype::MakeCXType(MsgE->getReceiverType(), TU);
1491 
1492   return cxtype::MakeCXType(QualType(), TU);
1493 }
1494 
1495 } // end: extern "C"
1496