CXCursor.cpp revision 534986f2b21e6050bf00163cd6423fd92155a6ed
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 "clang/Frontend/ASTUnit.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprObjC.h"
27#include "clang-c/Index.h"
28#include "llvm/Support/ErrorHandling.h"
29
30using namespace clang;
31using namespace cxcursor;
32
33CXCursor cxcursor::MakeCXCursorInvalid(CXCursorKind K) {
34  assert(K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid);
35  CXCursor C = { K, 0, { 0, 0, 0 } };
36  return C;
37}
38
39static CXCursorKind GetCursorKind(const Attr *A) {
40  assert(A && "Invalid arguments!");
41  switch (A->getKind()) {
42    default: break;
43    case attr::IBAction: return CXCursor_IBActionAttr;
44    case attr::IBOutlet: return CXCursor_IBOutletAttr;
45    case attr::IBOutletCollection: return CXCursor_IBOutletCollectionAttr;
46    case attr::Final: return CXCursor_CXXFinalAttr;
47    case attr::Override: return CXCursor_CXXOverrideAttr;
48    case attr::Annotate: return CXCursor_AnnotateAttr;
49    case attr::AsmLabel: return CXCursor_AsmLabelAttr;
50  }
51
52  return CXCursor_UnexposedAttr;
53}
54
55CXCursor cxcursor::MakeCXCursor(const Attr *A, Decl *Parent,
56                                CXTranslationUnit TU) {
57  assert(A && Parent && TU && "Invalid arguments!");
58  CXCursor C = { GetCursorKind(A), 0, { Parent, (void*)A, TU } };
59  return C;
60}
61
62CXCursor cxcursor::MakeCXCursor(Decl *D, CXTranslationUnit TU,
63                                SourceRange RegionOfInterest,
64                                bool FirstInDeclGroup) {
65  assert(D && TU && "Invalid arguments!");
66
67  CXCursorKind K = getCursorKindForDecl(D);
68
69  if (K == CXCursor_ObjCClassMethodDecl ||
70      K == CXCursor_ObjCInstanceMethodDecl) {
71    int SelectorIdIndex = -1;
72    // Check if cursor points to a selector id.
73    if (RegionOfInterest.isValid() &&
74        RegionOfInterest.getBegin() == RegionOfInterest.getEnd()) {
75      SmallVector<SourceLocation, 16> SelLocs;
76      cast<ObjCMethodDecl>(D)->getSelectorLocs(SelLocs);
77      SmallVector<SourceLocation, 16>::iterator
78        I=std::find(SelLocs.begin(), SelLocs.end(),RegionOfInterest.getBegin());
79      if (I != SelLocs.end())
80        SelectorIdIndex = I - SelLocs.begin();
81    }
82    CXCursor C = { K, SelectorIdIndex,
83                   { D, (void*)(intptr_t) (FirstInDeclGroup ? 1 : 0), TU }};
84    return C;
85  }
86
87  CXCursor C = { K, 0, { D, (void*)(intptr_t) (FirstInDeclGroup ? 1 : 0), TU }};
88  return C;
89}
90
91CXCursor cxcursor::MakeCXCursor(Stmt *S, Decl *Parent, CXTranslationUnit TU,
92                                SourceRange RegionOfInterest) {
93  assert(S && TU && "Invalid arguments!");
94  CXCursorKind K = CXCursor_NotImplemented;
95
96  switch (S->getStmtClass()) {
97  case Stmt::NoStmtClass:
98    break;
99
100  case Stmt::CaseStmtClass:
101    K = CXCursor_CaseStmt;
102    break;
103
104  case Stmt::DefaultStmtClass:
105    K = CXCursor_DefaultStmt;
106    break;
107
108  case Stmt::IfStmtClass:
109    K = CXCursor_IfStmt;
110    break;
111
112  case Stmt::SwitchStmtClass:
113    K = CXCursor_SwitchStmt;
114    break;
115
116  case Stmt::WhileStmtClass:
117    K = CXCursor_WhileStmt;
118    break;
119
120  case Stmt::DoStmtClass:
121    K = CXCursor_DoStmt;
122    break;
123
124  case Stmt::ForStmtClass:
125    K = CXCursor_ForStmt;
126    break;
127
128  case Stmt::GotoStmtClass:
129    K = CXCursor_GotoStmt;
130    break;
131
132  case Stmt::IndirectGotoStmtClass:
133    K = CXCursor_IndirectGotoStmt;
134    break;
135
136  case Stmt::ContinueStmtClass:
137    K = CXCursor_ContinueStmt;
138    break;
139
140  case Stmt::BreakStmtClass:
141    K = CXCursor_BreakStmt;
142    break;
143
144  case Stmt::ReturnStmtClass:
145    K = CXCursor_ReturnStmt;
146    break;
147
148  case Stmt::AsmStmtClass:
149    K = CXCursor_AsmStmt;
150    break;
151
152  case Stmt::ObjCAtTryStmtClass:
153    K = CXCursor_ObjCAtTryStmt;
154    break;
155
156  case Stmt::ObjCAtCatchStmtClass:
157    K = CXCursor_ObjCAtCatchStmt;
158    break;
159
160  case Stmt::ObjCAtFinallyStmtClass:
161    K = CXCursor_ObjCAtFinallyStmt;
162    break;
163
164  case Stmt::ObjCAtThrowStmtClass:
165    K = CXCursor_ObjCAtThrowStmt;
166    break;
167
168  case Stmt::ObjCAtSynchronizedStmtClass:
169    K = CXCursor_ObjCAtSynchronizedStmt;
170    break;
171
172  case Stmt::ObjCAutoreleasePoolStmtClass:
173    K = CXCursor_ObjCAutoreleasePoolStmt;
174    break;
175
176  case Stmt::ObjCForCollectionStmtClass:
177    K = CXCursor_ObjCForCollectionStmt;
178    break;
179
180  case Stmt::CXXCatchStmtClass:
181    K = CXCursor_CXXCatchStmt;
182    break;
183
184  case Stmt::CXXTryStmtClass:
185    K = CXCursor_CXXTryStmt;
186    break;
187
188  case Stmt::CXXForRangeStmtClass:
189    K = CXCursor_CXXForRangeStmt;
190    break;
191
192  case Stmt::SEHTryStmtClass:
193    K = CXCursor_SEHTryStmt;
194    break;
195
196  case Stmt::SEHExceptStmtClass:
197    K = CXCursor_SEHExceptStmt;
198    break;
199
200  case Stmt::SEHFinallyStmtClass:
201    K = CXCursor_SEHFinallyStmt;
202    break;
203
204  case Stmt::ArrayTypeTraitExprClass:
205  case Stmt::AsTypeExprClass:
206  case Stmt::AtomicExprClass:
207  case Stmt::BinaryConditionalOperatorClass:
208  case Stmt::BinaryTypeTraitExprClass:
209  case Stmt::TypeTraitExprClass:
210  case Stmt::CXXBindTemporaryExprClass:
211  case Stmt::CXXDefaultArgExprClass:
212  case Stmt::CXXScalarValueInitExprClass:
213  case Stmt::CXXUuidofExprClass:
214  case Stmt::ChooseExprClass:
215  case Stmt::DesignatedInitExprClass:
216  case Stmt::ExprWithCleanupsClass:
217  case Stmt::ExpressionTraitExprClass:
218  case Stmt::ExtVectorElementExprClass:
219  case Stmt::ImplicitCastExprClass:
220  case Stmt::ImplicitValueInitExprClass:
221  case Stmt::MaterializeTemporaryExprClass:
222  case Stmt::ObjCIndirectCopyRestoreExprClass:
223  case Stmt::OffsetOfExprClass:
224  case Stmt::ParenListExprClass:
225  case Stmt::PredefinedExprClass:
226  case Stmt::ShuffleVectorExprClass:
227  case Stmt::UnaryExprOrTypeTraitExprClass:
228  case Stmt::UnaryTypeTraitExprClass:
229  case Stmt::VAArgExprClass:
230  case Stmt::ObjCArrayLiteralClass:
231  case Stmt::ObjCDictionaryLiteralClass:
232  case Stmt::ObjCNumericLiteralClass:
233  case Stmt::ObjCSubscriptRefExprClass:
234    K = CXCursor_UnexposedExpr;
235    break;
236
237  case Stmt::OpaqueValueExprClass:
238    if (Expr *Src = cast<OpaqueValueExpr>(S)->getSourceExpr())
239      return MakeCXCursor(Src, Parent, TU, RegionOfInterest);
240    K = CXCursor_UnexposedExpr;
241    break;
242
243  case Stmt::PseudoObjectExprClass:
244    return MakeCXCursor(cast<PseudoObjectExpr>(S)->getSyntacticForm(),
245                        Parent, TU, RegionOfInterest);
246
247  case Stmt::CompoundStmtClass:
248    K = CXCursor_CompoundStmt;
249    break;
250
251  case Stmt::NullStmtClass:
252    K = CXCursor_NullStmt;
253    break;
254
255  case Stmt::LabelStmtClass:
256    K = CXCursor_LabelStmt;
257    break;
258
259  case Stmt::AttributedStmtClass:
260    K = CXCursor_UnexposedStmt;
261    break;
262
263  case Stmt::DeclStmtClass:
264    K = CXCursor_DeclStmt;
265    break;
266
267  case Stmt::IntegerLiteralClass:
268    K = CXCursor_IntegerLiteral;
269    break;
270
271  case Stmt::FloatingLiteralClass:
272    K = CXCursor_FloatingLiteral;
273    break;
274
275  case Stmt::ImaginaryLiteralClass:
276    K = CXCursor_ImaginaryLiteral;
277    break;
278
279  case Stmt::StringLiteralClass:
280    K = CXCursor_StringLiteral;
281    break;
282
283  case Stmt::CharacterLiteralClass:
284    K = CXCursor_CharacterLiteral;
285    break;
286
287  case Stmt::ParenExprClass:
288    K = CXCursor_ParenExpr;
289    break;
290
291  case Stmt::UnaryOperatorClass:
292    K = CXCursor_UnaryOperator;
293    break;
294
295  case Stmt::CXXNoexceptExprClass:
296    K = CXCursor_UnaryExpr;
297    break;
298
299  case Stmt::ArraySubscriptExprClass:
300    K = CXCursor_ArraySubscriptExpr;
301    break;
302
303  case Stmt::BinaryOperatorClass:
304    K = CXCursor_BinaryOperator;
305    break;
306
307  case Stmt::CompoundAssignOperatorClass:
308    K = CXCursor_CompoundAssignOperator;
309    break;
310
311  case Stmt::ConditionalOperatorClass:
312    K = CXCursor_ConditionalOperator;
313    break;
314
315  case Stmt::CStyleCastExprClass:
316    K = CXCursor_CStyleCastExpr;
317    break;
318
319  case Stmt::CompoundLiteralExprClass:
320    K = CXCursor_CompoundLiteralExpr;
321    break;
322
323  case Stmt::InitListExprClass:
324    K = CXCursor_InitListExpr;
325    break;
326
327  case Stmt::AddrLabelExprClass:
328    K = CXCursor_AddrLabelExpr;
329    break;
330
331  case Stmt::StmtExprClass:
332    K = CXCursor_StmtExpr;
333    break;
334
335  case Stmt::GenericSelectionExprClass:
336    K = CXCursor_GenericSelectionExpr;
337    break;
338
339  case Stmt::GNUNullExprClass:
340    K = CXCursor_GNUNullExpr;
341    break;
342
343  case Stmt::CXXStaticCastExprClass:
344    K = CXCursor_CXXStaticCastExpr;
345    break;
346
347  case Stmt::CXXDynamicCastExprClass:
348    K = CXCursor_CXXDynamicCastExpr;
349    break;
350
351  case Stmt::CXXReinterpretCastExprClass:
352    K = CXCursor_CXXReinterpretCastExpr;
353    break;
354
355  case Stmt::CXXConstCastExprClass:
356    K = CXCursor_CXXConstCastExpr;
357    break;
358
359  case Stmt::CXXFunctionalCastExprClass:
360    K = CXCursor_CXXFunctionalCastExpr;
361    break;
362
363  case Stmt::CXXTypeidExprClass:
364    K = CXCursor_CXXTypeidExpr;
365    break;
366
367  case Stmt::CXXBoolLiteralExprClass:
368    K = CXCursor_CXXBoolLiteralExpr;
369    break;
370
371  case Stmt::CXXNullPtrLiteralExprClass:
372    K = CXCursor_CXXNullPtrLiteralExpr;
373    break;
374
375  case Stmt::CXXThisExprClass:
376    K = CXCursor_CXXThisExpr;
377    break;
378
379  case Stmt::CXXThrowExprClass:
380    K = CXCursor_CXXThrowExpr;
381    break;
382
383  case Stmt::CXXNewExprClass:
384    K = CXCursor_CXXNewExpr;
385    break;
386
387  case Stmt::CXXDeleteExprClass:
388    K = CXCursor_CXXDeleteExpr;
389    break;
390
391  case Stmt::ObjCStringLiteralClass:
392    K = CXCursor_ObjCStringLiteral;
393    break;
394
395  case Stmt::ObjCEncodeExprClass:
396    K = CXCursor_ObjCEncodeExpr;
397    break;
398
399  case Stmt::ObjCSelectorExprClass:
400    K = CXCursor_ObjCSelectorExpr;
401    break;
402
403  case Stmt::ObjCProtocolExprClass:
404    K = CXCursor_ObjCProtocolExpr;
405    break;
406
407  case Stmt::ObjCBoolLiteralExprClass:
408    K = CXCursor_ObjCBoolLiteralExpr;
409    break;
410
411  case Stmt::ObjCBridgedCastExprClass:
412    K = CXCursor_ObjCBridgedCastExpr;
413    break;
414
415  case Stmt::BlockExprClass:
416    K = CXCursor_BlockExpr;
417    break;
418
419  case Stmt::PackExpansionExprClass:
420    K = CXCursor_PackExpansionExpr;
421    break;
422
423  case Stmt::SizeOfPackExprClass:
424    K = CXCursor_SizeOfPackExpr;
425    break;
426
427  case Stmt::DeclRefExprClass:
428  case Stmt::DependentScopeDeclRefExprClass:
429  case Stmt::SubstNonTypeTemplateParmExprClass:
430  case Stmt::SubstNonTypeTemplateParmPackExprClass:
431  case Stmt::UnresolvedLookupExprClass:
432    K = CXCursor_DeclRefExpr;
433    break;
434
435  case Stmt::CXXDependentScopeMemberExprClass:
436  case Stmt::CXXPseudoDestructorExprClass:
437  case Stmt::MemberExprClass:
438  case Stmt::ObjCIsaExprClass:
439  case Stmt::ObjCIvarRefExprClass:
440  case Stmt::ObjCPropertyRefExprClass:
441  case Stmt::UnresolvedMemberExprClass:
442    K = CXCursor_MemberRefExpr;
443    break;
444
445  case Stmt::CallExprClass:
446  case Stmt::CXXOperatorCallExprClass:
447  case Stmt::CXXMemberCallExprClass:
448  case Stmt::CUDAKernelCallExprClass:
449  case Stmt::CXXConstructExprClass:
450  case Stmt::CXXTemporaryObjectExprClass:
451  case Stmt::CXXUnresolvedConstructExprClass:
452  case Stmt::UserDefinedLiteralClass:
453    K = CXCursor_CallExpr;
454    break;
455
456  case Stmt::LambdaExprClass:
457    K = CXCursor_LambdaExpr;
458    break;
459
460  case Stmt::ObjCMessageExprClass: {
461    K = CXCursor_ObjCMessageExpr;
462    int SelectorIdIndex = -1;
463    // Check if cursor points to a selector id.
464    if (RegionOfInterest.isValid() &&
465        RegionOfInterest.getBegin() == RegionOfInterest.getEnd()) {
466      SmallVector<SourceLocation, 16> SelLocs;
467      cast<ObjCMessageExpr>(S)->getSelectorLocs(SelLocs);
468      SmallVector<SourceLocation, 16>::iterator
469        I=std::find(SelLocs.begin(), SelLocs.end(),RegionOfInterest.getBegin());
470      if (I != SelLocs.end())
471        SelectorIdIndex = I - SelLocs.begin();
472    }
473    CXCursor C = { K, 0, { Parent, S, TU } };
474    return getSelectorIdentifierCursor(SelectorIdIndex, C);
475  }
476
477  case Stmt::MSDependentExistsStmtClass:
478    K = CXCursor_UnexposedStmt;
479    break;
480  }
481
482  CXCursor C = { K, 0, { Parent, S, TU } };
483  return C;
484}
485
486CXCursor cxcursor::MakeCursorObjCSuperClassRef(ObjCInterfaceDecl *Super,
487                                               SourceLocation Loc,
488                                               CXTranslationUnit TU) {
489  assert(Super && TU && "Invalid arguments!");
490  void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
491  CXCursor C = { CXCursor_ObjCSuperClassRef, 0, { Super, RawLoc, TU } };
492  return C;
493}
494
495std::pair<ObjCInterfaceDecl *, SourceLocation>
496cxcursor::getCursorObjCSuperClassRef(CXCursor C) {
497  assert(C.kind == CXCursor_ObjCSuperClassRef);
498  return std::make_pair(static_cast<ObjCInterfaceDecl *>(C.data[0]),
499           SourceLocation::getFromRawEncoding(
500                                      reinterpret_cast<uintptr_t>(C.data[1])));
501}
502
503CXCursor cxcursor::MakeCursorObjCProtocolRef(const ObjCProtocolDecl *Proto,
504                                             SourceLocation Loc,
505                                             CXTranslationUnit TU) {
506  assert(Proto && TU && "Invalid arguments!");
507  void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
508  CXCursor C = { CXCursor_ObjCProtocolRef, 0, { (void*)Proto, RawLoc, TU } };
509  return C;
510}
511
512std::pair<ObjCProtocolDecl *, SourceLocation>
513cxcursor::getCursorObjCProtocolRef(CXCursor C) {
514  assert(C.kind == CXCursor_ObjCProtocolRef);
515  return std::make_pair(static_cast<ObjCProtocolDecl *>(C.data[0]),
516           SourceLocation::getFromRawEncoding(
517                                      reinterpret_cast<uintptr_t>(C.data[1])));
518}
519
520CXCursor cxcursor::MakeCursorObjCClassRef(const ObjCInterfaceDecl *Class,
521                                          SourceLocation Loc,
522                                          CXTranslationUnit TU) {
523  // 'Class' can be null for invalid code.
524  if (!Class)
525    return MakeCXCursorInvalid(CXCursor_InvalidCode);
526  assert(TU && "Invalid arguments!");
527  void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
528  CXCursor C = { CXCursor_ObjCClassRef, 0, { (void*)Class, RawLoc, TU } };
529  return C;
530}
531
532std::pair<ObjCInterfaceDecl *, SourceLocation>
533cxcursor::getCursorObjCClassRef(CXCursor C) {
534  assert(C.kind == CXCursor_ObjCClassRef);
535  return std::make_pair(static_cast<ObjCInterfaceDecl *>(C.data[0]),
536           SourceLocation::getFromRawEncoding(
537                                      reinterpret_cast<uintptr_t>(C.data[1])));
538}
539
540CXCursor cxcursor::MakeCursorTypeRef(const TypeDecl *Type, SourceLocation Loc,
541                                     CXTranslationUnit TU) {
542  assert(Type && TU && "Invalid arguments!");
543  void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
544  CXCursor C = { CXCursor_TypeRef, 0, { (void*)Type, RawLoc, TU } };
545  return C;
546}
547
548std::pair<TypeDecl *, SourceLocation>
549cxcursor::getCursorTypeRef(CXCursor C) {
550  assert(C.kind == CXCursor_TypeRef);
551  return std::make_pair(static_cast<TypeDecl *>(C.data[0]),
552           SourceLocation::getFromRawEncoding(
553                                      reinterpret_cast<uintptr_t>(C.data[1])));
554}
555
556CXCursor cxcursor::MakeCursorTemplateRef(const TemplateDecl *Template,
557                                         SourceLocation Loc,
558                                         CXTranslationUnit TU) {
559  assert(Template && TU && "Invalid arguments!");
560  void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
561  CXCursor C = { CXCursor_TemplateRef, 0, { (void*)Template, RawLoc, TU } };
562  return C;
563}
564
565std::pair<TemplateDecl *, SourceLocation>
566cxcursor::getCursorTemplateRef(CXCursor C) {
567  assert(C.kind == CXCursor_TemplateRef);
568  return std::make_pair(static_cast<TemplateDecl *>(C.data[0]),
569                        SourceLocation::getFromRawEncoding(
570                                       reinterpret_cast<uintptr_t>(C.data[1])));
571}
572
573CXCursor cxcursor::MakeCursorNamespaceRef(const NamedDecl *NS,
574                                          SourceLocation Loc,
575                                          CXTranslationUnit TU) {
576
577  assert(NS && (isa<NamespaceDecl>(NS) || isa<NamespaceAliasDecl>(NS)) && TU &&
578         "Invalid arguments!");
579  void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
580  CXCursor C = { CXCursor_NamespaceRef, 0, { (void*)NS, RawLoc, TU } };
581  return C;
582}
583
584std::pair<NamedDecl *, SourceLocation>
585cxcursor::getCursorNamespaceRef(CXCursor C) {
586  assert(C.kind == CXCursor_NamespaceRef);
587  return std::make_pair(static_cast<NamedDecl *>(C.data[0]),
588                        SourceLocation::getFromRawEncoding(
589                                       reinterpret_cast<uintptr_t>(C.data[1])));
590}
591
592CXCursor cxcursor::MakeCursorVariableRef(const VarDecl *Var, SourceLocation Loc,
593                                         CXTranslationUnit TU) {
594
595  assert(Var && TU && "Invalid arguments!");
596  void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
597  CXCursor C = { CXCursor_VariableRef, 0, { (void*)Var, RawLoc, TU } };
598  return C;
599}
600
601std::pair<VarDecl *, SourceLocation>
602cxcursor::getCursorVariableRef(CXCursor C) {
603  assert(C.kind == CXCursor_VariableRef);
604  return std::make_pair(static_cast<VarDecl *>(C.data[0]),
605                        SourceLocation::getFromRawEncoding(
606                          reinterpret_cast<uintptr_t>(C.data[1])));
607}
608
609CXCursor cxcursor::MakeCursorMemberRef(const FieldDecl *Field, SourceLocation Loc,
610                                       CXTranslationUnit TU) {
611
612  assert(Field && TU && "Invalid arguments!");
613  void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
614  CXCursor C = { CXCursor_MemberRef, 0, { (void*)Field, RawLoc, TU } };
615  return C;
616}
617
618std::pair<FieldDecl *, SourceLocation>
619cxcursor::getCursorMemberRef(CXCursor C) {
620  assert(C.kind == CXCursor_MemberRef);
621  return std::make_pair(static_cast<FieldDecl *>(C.data[0]),
622                        SourceLocation::getFromRawEncoding(
623                                       reinterpret_cast<uintptr_t>(C.data[1])));
624}
625
626CXCursor cxcursor::MakeCursorCXXBaseSpecifier(const CXXBaseSpecifier *B,
627                                              CXTranslationUnit TU){
628  CXCursor C = { CXCursor_CXXBaseSpecifier, 0, { (void*)B, 0, TU } };
629  return C;
630}
631
632CXXBaseSpecifier *cxcursor::getCursorCXXBaseSpecifier(CXCursor C) {
633  assert(C.kind == CXCursor_CXXBaseSpecifier);
634  return static_cast<CXXBaseSpecifier*>(C.data[0]);
635}
636
637CXCursor cxcursor::MakePreprocessingDirectiveCursor(SourceRange Range,
638                                                    CXTranslationUnit TU) {
639  CXCursor C = { CXCursor_PreprocessingDirective, 0,
640                 { reinterpret_cast<void *>(Range.getBegin().getRawEncoding()),
641                   reinterpret_cast<void *>(Range.getEnd().getRawEncoding()),
642                   TU }
643               };
644  return C;
645}
646
647SourceRange cxcursor::getCursorPreprocessingDirective(CXCursor C) {
648  assert(C.kind == CXCursor_PreprocessingDirective);
649  SourceRange Range = SourceRange(SourceLocation::getFromRawEncoding(
650                                      reinterpret_cast<uintptr_t> (C.data[0])),
651                     SourceLocation::getFromRawEncoding(
652                                      reinterpret_cast<uintptr_t> (C.data[1])));
653  ASTUnit *TU = getCursorASTUnit(C);
654  return TU->mapRangeFromPreamble(Range);
655}
656
657CXCursor cxcursor::MakeMacroDefinitionCursor(MacroDefinition *MI,
658                                             CXTranslationUnit TU) {
659  CXCursor C = { CXCursor_MacroDefinition, 0, { MI, 0, TU } };
660  return C;
661}
662
663MacroDefinition *cxcursor::getCursorMacroDefinition(CXCursor C) {
664  assert(C.kind == CXCursor_MacroDefinition);
665  return static_cast<MacroDefinition *>(C.data[0]);
666}
667
668CXCursor cxcursor::MakeMacroExpansionCursor(MacroExpansion *MI,
669                                            CXTranslationUnit TU) {
670  CXCursor C = { CXCursor_MacroExpansion, 0, { MI, 0, TU } };
671  return C;
672}
673
674MacroExpansion *cxcursor::getCursorMacroExpansion(CXCursor C) {
675  assert(C.kind == CXCursor_MacroExpansion);
676  return static_cast<MacroExpansion *>(C.data[0]);
677}
678
679CXCursor cxcursor::MakeInclusionDirectiveCursor(InclusionDirective *ID,
680                                                CXTranslationUnit TU) {
681  CXCursor C = { CXCursor_InclusionDirective, 0, { ID, 0, TU } };
682  return C;
683}
684
685InclusionDirective *cxcursor::getCursorInclusionDirective(CXCursor C) {
686  assert(C.kind == CXCursor_InclusionDirective);
687  return static_cast<InclusionDirective *>(C.data[0]);
688}
689
690CXCursor cxcursor::MakeCursorLabelRef(LabelStmt *Label, SourceLocation Loc,
691                                      CXTranslationUnit TU) {
692
693  assert(Label && TU && "Invalid arguments!");
694  void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
695  CXCursor C = { CXCursor_LabelRef, 0, { Label, RawLoc, TU } };
696  return C;
697}
698
699std::pair<LabelStmt*, SourceLocation>
700cxcursor::getCursorLabelRef(CXCursor C) {
701  assert(C.kind == CXCursor_LabelRef);
702  return std::make_pair(static_cast<LabelStmt *>(C.data[0]),
703                        SourceLocation::getFromRawEncoding(
704                                       reinterpret_cast<uintptr_t>(C.data[1])));
705}
706
707CXCursor cxcursor::MakeCursorOverloadedDeclRef(OverloadExpr *E,
708                                               CXTranslationUnit TU) {
709  assert(E && TU && "Invalid arguments!");
710  OverloadedDeclRefStorage Storage(E);
711  void *RawLoc = reinterpret_cast<void *>(E->getNameLoc().getRawEncoding());
712  CXCursor C = {
713                 CXCursor_OverloadedDeclRef, 0,
714                 { Storage.getOpaqueValue(), RawLoc, TU }
715               };
716  return C;
717}
718
719CXCursor cxcursor::MakeCursorOverloadedDeclRef(Decl *D,
720                                               SourceLocation Loc,
721                                               CXTranslationUnit TU) {
722  assert(D && TU && "Invalid arguments!");
723  void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
724  OverloadedDeclRefStorage Storage(D);
725  CXCursor C = {
726    CXCursor_OverloadedDeclRef, 0,
727    { Storage.getOpaqueValue(), RawLoc, TU }
728  };
729  return C;
730}
731
732CXCursor cxcursor::MakeCursorOverloadedDeclRef(TemplateName Name,
733                                               SourceLocation Loc,
734                                               CXTranslationUnit TU) {
735  assert(Name.getAsOverloadedTemplate() && TU && "Invalid arguments!");
736  void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
737  OverloadedDeclRefStorage Storage(Name.getAsOverloadedTemplate());
738  CXCursor C = {
739    CXCursor_OverloadedDeclRef, 0,
740    { Storage.getOpaqueValue(), RawLoc, TU }
741  };
742  return C;
743}
744
745std::pair<cxcursor::OverloadedDeclRefStorage, SourceLocation>
746cxcursor::getCursorOverloadedDeclRef(CXCursor C) {
747  assert(C.kind == CXCursor_OverloadedDeclRef);
748  return std::make_pair(OverloadedDeclRefStorage::getFromOpaqueValue(C.data[0]),
749                        SourceLocation::getFromRawEncoding(
750                                       reinterpret_cast<uintptr_t>(C.data[1])));
751}
752
753Decl *cxcursor::getCursorDecl(CXCursor Cursor) {
754  return (Decl *)Cursor.data[0];
755}
756
757Expr *cxcursor::getCursorExpr(CXCursor Cursor) {
758  return dyn_cast_or_null<Expr>(getCursorStmt(Cursor));
759}
760
761Stmt *cxcursor::getCursorStmt(CXCursor Cursor) {
762  if (Cursor.kind == CXCursor_ObjCSuperClassRef ||
763      Cursor.kind == CXCursor_ObjCProtocolRef ||
764      Cursor.kind == CXCursor_ObjCClassRef)
765    return 0;
766
767  return (Stmt *)Cursor.data[1];
768}
769
770Attr *cxcursor::getCursorAttr(CXCursor Cursor) {
771  return (Attr *)Cursor.data[1];
772}
773
774Decl *cxcursor::getCursorParentDecl(CXCursor Cursor) {
775  return (Decl *)Cursor.data[0];
776}
777
778ASTContext &cxcursor::getCursorContext(CXCursor Cursor) {
779  return getCursorASTUnit(Cursor)->getASTContext();
780}
781
782ASTUnit *cxcursor::getCursorASTUnit(CXCursor Cursor) {
783  CXTranslationUnit TU = static_cast<CXTranslationUnit>(Cursor.data[2]);
784  if (!TU)
785    return 0;
786  return static_cast<ASTUnit *>(TU->TUData);
787}
788
789CXTranslationUnit cxcursor::getCursorTU(CXCursor Cursor) {
790  return static_cast<CXTranslationUnit>(Cursor.data[2]);
791}
792
793static void CollectOverriddenMethodsRecurse(CXTranslationUnit TU,
794                                     ObjCContainerDecl *Container,
795                                     ObjCMethodDecl *Method,
796                                     SmallVectorImpl<CXCursor> &Methods,
797                                     bool MovedToSuper) {
798  if (!Container)
799    return;
800
801  // In categories look for overriden methods from protocols. A method from
802  // category is not "overriden" since it is considered as the "same" method
803  // (same USR) as the one from the interface.
804  if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
805    // Check whether we have a matching method at this category but only if we
806    // are at the super class level.
807    if (MovedToSuper)
808      if (ObjCMethodDecl *
809            Overridden = Container->getMethod(Method->getSelector(),
810                                              Method->isInstanceMethod()))
811        if (Method != Overridden) {
812          // We found an override at this category; there is no need to look
813          // into its protocols.
814          Methods.push_back(MakeCXCursor(Overridden, TU));
815          return;
816        }
817
818    for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
819                                          PEnd = Category->protocol_end();
820         P != PEnd; ++P)
821      CollectOverriddenMethodsRecurse(TU, *P, Method, Methods, MovedToSuper);
822    return;
823  }
824
825  // Check whether we have a matching method at this level.
826  if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
827                                                    Method->isInstanceMethod()))
828    if (Method != Overridden) {
829      // We found an override at this level; there is no need to look
830      // into other protocols or categories.
831      Methods.push_back(MakeCXCursor(Overridden, TU));
832      return;
833    }
834
835  if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
836    for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
837                                          PEnd = Protocol->protocol_end();
838         P != PEnd; ++P)
839      CollectOverriddenMethodsRecurse(TU, *P, Method, Methods, MovedToSuper);
840  }
841
842  if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
843    for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
844                                           PEnd = Interface->protocol_end();
845         P != PEnd; ++P)
846      CollectOverriddenMethodsRecurse(TU, *P, Method, Methods, MovedToSuper);
847
848    for (ObjCCategoryDecl *Category = Interface->getCategoryList();
849         Category; Category = Category->getNextClassCategory())
850      CollectOverriddenMethodsRecurse(TU, Category, Method, Methods,
851                                      MovedToSuper);
852
853    if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
854      return CollectOverriddenMethodsRecurse(TU, Super, Method, Methods,
855                                             /*MovedToSuper=*/true);
856  }
857}
858
859static inline void CollectOverriddenMethods(CXTranslationUnit TU,
860                                           ObjCContainerDecl *Container,
861                                           ObjCMethodDecl *Method,
862                                           SmallVectorImpl<CXCursor> &Methods) {
863  CollectOverriddenMethodsRecurse(TU, Container, Method, Methods,
864                                  /*MovedToSuper=*/false);
865}
866
867void cxcursor::getOverriddenCursors(CXCursor cursor,
868                                    SmallVectorImpl<CXCursor> &overridden) {
869  assert(clang_isDeclaration(cursor.kind));
870  Decl *D = getCursorDecl(cursor);
871  if (!D)
872    return;
873
874  // Handle C++ member functions.
875  CXTranslationUnit TU = getCursorTU(cursor);
876  if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
877    for (CXXMethodDecl::method_iterator
878              M = CXXMethod->begin_overridden_methods(),
879           MEnd = CXXMethod->end_overridden_methods();
880         M != MEnd; ++M)
881      overridden.push_back(MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU));
882    return;
883  }
884
885  ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
886  if (!Method)
887    return;
888
889  if (ObjCProtocolDecl *
890        ProtD = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext())) {
891    CollectOverriddenMethods(TU, ProtD, Method, overridden);
892
893  } else if (ObjCImplDecl *
894               IMD = dyn_cast<ObjCImplDecl>(Method->getDeclContext())) {
895    ObjCInterfaceDecl *ID = IMD->getClassInterface();
896    if (!ID)
897      return;
898    // Start searching for overridden methods using the method from the
899    // interface as starting point.
900    if (ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(),
901                                                  Method->isInstanceMethod()))
902      Method = IFaceMeth;
903    CollectOverriddenMethods(TU, ID, Method, overridden);
904
905  } else if (ObjCCategoryDecl *
906               CatD = dyn_cast<ObjCCategoryDecl>(Method->getDeclContext())) {
907    ObjCInterfaceDecl *ID = CatD->getClassInterface();
908    if (!ID)
909      return;
910    // Start searching for overridden methods using the method from the
911    // interface as starting point.
912    if (ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(),
913                                                  Method->isInstanceMethod()))
914      Method = IFaceMeth;
915    CollectOverriddenMethods(TU, ID, Method, overridden);
916
917  } else {
918    CollectOverriddenMethods(TU,
919                  dyn_cast_or_null<ObjCContainerDecl>(Method->getDeclContext()),
920                  Method, overridden);
921  }
922}
923
924std::pair<int, SourceLocation>
925cxcursor::getSelectorIdentifierIndexAndLoc(CXCursor cursor) {
926  if (cursor.kind == CXCursor_ObjCMessageExpr) {
927    if (cursor.xdata != -1)
928      return std::make_pair(cursor.xdata,
929                            cast<ObjCMessageExpr>(getCursorExpr(cursor))
930                                                ->getSelectorLoc(cursor.xdata));
931  } else if (cursor.kind == CXCursor_ObjCClassMethodDecl ||
932             cursor.kind == CXCursor_ObjCInstanceMethodDecl) {
933    if (cursor.xdata != -1)
934      return std::make_pair(cursor.xdata,
935                            cast<ObjCMethodDecl>(getCursorDecl(cursor))
936                                                ->getSelectorLoc(cursor.xdata));
937  }
938
939  return std::make_pair(-1, SourceLocation());
940}
941
942CXCursor cxcursor::getSelectorIdentifierCursor(int SelIdx, CXCursor cursor) {
943  CXCursor newCursor = cursor;
944
945  if (cursor.kind == CXCursor_ObjCMessageExpr) {
946    if (SelIdx == -1 ||
947        unsigned(SelIdx) >= cast<ObjCMessageExpr>(getCursorExpr(cursor))
948                                                         ->getNumSelectorLocs())
949      newCursor.xdata = -1;
950    else
951      newCursor.xdata = SelIdx;
952  } else if (cursor.kind == CXCursor_ObjCClassMethodDecl ||
953             cursor.kind == CXCursor_ObjCInstanceMethodDecl) {
954    if (SelIdx == -1 ||
955        unsigned(SelIdx) >= cast<ObjCMethodDecl>(getCursorDecl(cursor))
956                                                         ->getNumSelectorLocs())
957      newCursor.xdata = -1;
958    else
959      newCursor.xdata = SelIdx;
960  }
961
962  return newCursor;
963}
964
965CXCursor cxcursor::getTypeRefCursor(CXCursor cursor) {
966  if (cursor.kind != CXCursor_CallExpr)
967    return cursor;
968
969  if (cursor.xdata == 0)
970    return cursor;
971
972  Expr *E = getCursorExpr(cursor);
973  TypeSourceInfo *Type = 0;
974  if (CXXUnresolvedConstructExpr *
975        UnCtor = dyn_cast<CXXUnresolvedConstructExpr>(E)) {
976    Type = UnCtor->getTypeSourceInfo();
977  } else if (CXXTemporaryObjectExpr *Tmp = dyn_cast<CXXTemporaryObjectExpr>(E)){
978    Type = Tmp->getTypeSourceInfo();
979  }
980
981  if (!Type)
982    return cursor;
983
984  CXTranslationUnit TU = getCursorTU(cursor);
985  QualType Ty = Type->getType();
986  TypeLoc TL = Type->getTypeLoc();
987  SourceLocation Loc = TL.getBeginLoc();
988
989  if (const ElaboratedType *ElabT = Ty->getAs<ElaboratedType>()) {
990    Ty = ElabT->getNamedType();
991    ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(TL);
992    Loc = ElabTL.getNamedTypeLoc().getBeginLoc();
993  }
994
995  if (const TypedefType *Typedef = Ty->getAs<TypedefType>())
996    return MakeCursorTypeRef(Typedef->getDecl(), Loc, TU);
997  if (const TagType *Tag = Ty->getAs<TagType>())
998    return MakeCursorTypeRef(Tag->getDecl(), Loc, TU);
999  if (const TemplateTypeParmType *TemplP = Ty->getAs<TemplateTypeParmType>())
1000    return MakeCursorTypeRef(TemplP->getDecl(), Loc, TU);
1001
1002  return cursor;
1003}
1004
1005bool cxcursor::operator==(CXCursor X, CXCursor Y) {
1006  return X.kind == Y.kind && X.data[0] == Y.data[0] && X.data[1] == Y.data[1] &&
1007         X.data[2] == Y.data[2];
1008}
1009
1010// FIXME: Remove once we can model DeclGroups and their appropriate ranges
1011// properly in the ASTs.
1012bool cxcursor::isFirstInDeclGroup(CXCursor C) {
1013  assert(clang_isDeclaration(C.kind));
1014  return ((uintptr_t) (C.data[1])) != 0;
1015}
1016
1017//===----------------------------------------------------------------------===//
1018// libclang CXCursor APIs
1019//===----------------------------------------------------------------------===//
1020
1021extern "C" {
1022
1023int clang_Cursor_isNull(CXCursor cursor) {
1024  return clang_equalCursors(cursor, clang_getNullCursor());
1025}
1026
1027CXTranslationUnit clang_Cursor_getTranslationUnit(CXCursor cursor) {
1028  return getCursorTU(cursor);
1029}
1030
1031int clang_Cursor_getNumArguments(CXCursor C) {
1032  if (clang_isDeclaration(C.kind)) {
1033    Decl *D = cxcursor::getCursorDecl(C);
1034    if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
1035      return MD->param_size();
1036    if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
1037      return FD->param_size();
1038  }
1039
1040  return -1;
1041}
1042
1043CXCursor clang_Cursor_getArgument(CXCursor C, unsigned i) {
1044  if (clang_isDeclaration(C.kind)) {
1045    Decl *D = cxcursor::getCursorDecl(C);
1046    if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
1047      if (i < MD->param_size())
1048        return cxcursor::MakeCXCursor(MD->param_begin()[i],
1049                                      cxcursor::getCursorTU(C));
1050    } else if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
1051      if (i < FD->param_size())
1052        return cxcursor::MakeCXCursor(FD->param_begin()[i],
1053                                      cxcursor::getCursorTU(C));
1054    }
1055  }
1056
1057  return clang_getNullCursor();
1058}
1059
1060} // end: extern "C"
1061
1062//===----------------------------------------------------------------------===//
1063// CXCursorSet.
1064//===----------------------------------------------------------------------===//
1065
1066typedef llvm::DenseMap<CXCursor, unsigned> CXCursorSet_Impl;
1067
1068static inline CXCursorSet packCXCursorSet(CXCursorSet_Impl *setImpl) {
1069  return (CXCursorSet) setImpl;
1070}
1071static inline CXCursorSet_Impl *unpackCXCursorSet(CXCursorSet set) {
1072  return (CXCursorSet_Impl*) set;
1073}
1074namespace llvm {
1075template<> struct DenseMapInfo<CXCursor> {
1076public:
1077  static inline CXCursor getEmptyKey() {
1078    return MakeCXCursorInvalid(CXCursor_InvalidFile);
1079  }
1080  static inline CXCursor getTombstoneKey() {
1081    return MakeCXCursorInvalid(CXCursor_NoDeclFound);
1082  }
1083  static inline unsigned getHashValue(const CXCursor &cursor) {
1084    return llvm::DenseMapInfo<std::pair<void*,void*> >
1085      ::getHashValue(std::make_pair(cursor.data[0], cursor.data[1]));
1086  }
1087  static inline bool isEqual(const CXCursor &x, const CXCursor &y) {
1088    return x.kind == y.kind &&
1089           x.data[0] == y.data[0] &&
1090           x.data[1] == y.data[1];
1091  }
1092};
1093}
1094
1095extern "C" {
1096CXCursorSet clang_createCXCursorSet() {
1097  return packCXCursorSet(new CXCursorSet_Impl());
1098}
1099
1100void clang_disposeCXCursorSet(CXCursorSet set) {
1101  delete unpackCXCursorSet(set);
1102}
1103
1104unsigned clang_CXCursorSet_contains(CXCursorSet set, CXCursor cursor) {
1105  CXCursorSet_Impl *setImpl = unpackCXCursorSet(set);
1106  if (!setImpl)
1107    return 0;
1108  return setImpl->find(cursor) == setImpl->end();
1109}
1110
1111unsigned clang_CXCursorSet_insert(CXCursorSet set, CXCursor cursor) {
1112  // Do not insert invalid cursors into the set.
1113  if (cursor.kind >= CXCursor_FirstInvalid &&
1114      cursor.kind <= CXCursor_LastInvalid)
1115    return 1;
1116
1117  CXCursorSet_Impl *setImpl = unpackCXCursorSet(set);
1118  if (!setImpl)
1119    return 1;
1120  unsigned &entry = (*setImpl)[cursor];
1121  unsigned flag = entry == 0 ? 1 : 0;
1122  entry = 1;
1123  return flag;
1124}
1125
1126CXCompletionString clang_getCursorCompletionString(CXCursor cursor) {
1127  enum CXCursorKind kind = clang_getCursorKind(cursor);
1128  if (clang_isDeclaration(kind)) {
1129    Decl *decl = getCursorDecl(cursor);
1130    if (NamedDecl *namedDecl = dyn_cast_or_null<NamedDecl>(decl)) {
1131      ASTUnit *unit = getCursorASTUnit(cursor);
1132      CodeCompletionResult Result(namedDecl);
1133      CodeCompletionString *String
1134        = Result.CreateCodeCompletionString(unit->getASTContext(),
1135                                            unit->getPreprocessor(),
1136                                 unit->getCodeCompletionTUInfo().getAllocator(),
1137                                 unit->getCodeCompletionTUInfo());
1138      return String;
1139    }
1140  }
1141  else if (kind == CXCursor_MacroDefinition) {
1142    MacroDefinition *definition = getCursorMacroDefinition(cursor);
1143    const IdentifierInfo *MacroInfo = definition->getName();
1144    ASTUnit *unit = getCursorASTUnit(cursor);
1145    CodeCompletionResult Result(const_cast<IdentifierInfo *>(MacroInfo));
1146    CodeCompletionString *String
1147      = Result.CreateCodeCompletionString(unit->getASTContext(),
1148                                          unit->getPreprocessor(),
1149                                 unit->getCodeCompletionTUInfo().getAllocator(),
1150                                 unit->getCodeCompletionTUInfo());
1151    return String;
1152  }
1153  return NULL;
1154}
1155
1156} // end: extern "C"
1157