CXCursor.cpp revision d98ef9ae48ab4090d4d5d703ce65cfac62807fda
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::DeclStmtClass:
260    K = CXCursor_DeclStmt;
261    break;
262
263  case Stmt::IntegerLiteralClass:
264    K = CXCursor_IntegerLiteral;
265    break;
266
267  case Stmt::FloatingLiteralClass:
268    K = CXCursor_FloatingLiteral;
269    break;
270
271  case Stmt::ImaginaryLiteralClass:
272    K = CXCursor_ImaginaryLiteral;
273    break;
274
275  case Stmt::StringLiteralClass:
276    K = CXCursor_StringLiteral;
277    break;
278
279  case Stmt::CharacterLiteralClass:
280    K = CXCursor_CharacterLiteral;
281    break;
282
283  case Stmt::ParenExprClass:
284    K = CXCursor_ParenExpr;
285    break;
286
287  case Stmt::UnaryOperatorClass:
288    K = CXCursor_UnaryOperator;
289    break;
290
291  case Stmt::CXXNoexceptExprClass:
292    K = CXCursor_UnaryExpr;
293    break;
294
295  case Stmt::ArraySubscriptExprClass:
296    K = CXCursor_ArraySubscriptExpr;
297    break;
298
299  case Stmt::BinaryOperatorClass:
300    K = CXCursor_BinaryOperator;
301    break;
302
303  case Stmt::CompoundAssignOperatorClass:
304    K = CXCursor_CompoundAssignOperator;
305    break;
306
307  case Stmt::ConditionalOperatorClass:
308    K = CXCursor_ConditionalOperator;
309    break;
310
311  case Stmt::CStyleCastExprClass:
312    K = CXCursor_CStyleCastExpr;
313    break;
314
315  case Stmt::CompoundLiteralExprClass:
316    K = CXCursor_CompoundLiteralExpr;
317    break;
318
319  case Stmt::InitListExprClass:
320    K = CXCursor_InitListExpr;
321    break;
322
323  case Stmt::AddrLabelExprClass:
324    K = CXCursor_AddrLabelExpr;
325    break;
326
327  case Stmt::StmtExprClass:
328    K = CXCursor_StmtExpr;
329    break;
330
331  case Stmt::GenericSelectionExprClass:
332    K = CXCursor_GenericSelectionExpr;
333    break;
334
335  case Stmt::GNUNullExprClass:
336    K = CXCursor_GNUNullExpr;
337    break;
338
339  case Stmt::CXXStaticCastExprClass:
340    K = CXCursor_CXXStaticCastExpr;
341    break;
342
343  case Stmt::CXXDynamicCastExprClass:
344    K = CXCursor_CXXDynamicCastExpr;
345    break;
346
347  case Stmt::CXXReinterpretCastExprClass:
348    K = CXCursor_CXXReinterpretCastExpr;
349    break;
350
351  case Stmt::CXXConstCastExprClass:
352    K = CXCursor_CXXConstCastExpr;
353    break;
354
355  case Stmt::CXXFunctionalCastExprClass:
356    K = CXCursor_CXXFunctionalCastExpr;
357    break;
358
359  case Stmt::CXXTypeidExprClass:
360    K = CXCursor_CXXTypeidExpr;
361    break;
362
363  case Stmt::CXXBoolLiteralExprClass:
364    K = CXCursor_CXXBoolLiteralExpr;
365    break;
366
367  case Stmt::CXXNullPtrLiteralExprClass:
368    K = CXCursor_CXXNullPtrLiteralExpr;
369    break;
370
371  case Stmt::CXXThisExprClass:
372    K = CXCursor_CXXThisExpr;
373    break;
374
375  case Stmt::CXXThrowExprClass:
376    K = CXCursor_CXXThrowExpr;
377    break;
378
379  case Stmt::CXXNewExprClass:
380    K = CXCursor_CXXNewExpr;
381    break;
382
383  case Stmt::CXXDeleteExprClass:
384    K = CXCursor_CXXDeleteExpr;
385    break;
386
387  case Stmt::ObjCStringLiteralClass:
388    K = CXCursor_ObjCStringLiteral;
389    break;
390
391  case Stmt::ObjCEncodeExprClass:
392    K = CXCursor_ObjCEncodeExpr;
393    break;
394
395  case Stmt::ObjCSelectorExprClass:
396    K = CXCursor_ObjCSelectorExpr;
397    break;
398
399  case Stmt::ObjCProtocolExprClass:
400    K = CXCursor_ObjCProtocolExpr;
401    break;
402
403  case Stmt::ObjCBoolLiteralExprClass:
404    K = CXCursor_ObjCBoolLiteralExpr;
405    break;
406
407  case Stmt::ObjCBridgedCastExprClass:
408    K = CXCursor_ObjCBridgedCastExpr;
409    break;
410
411  case Stmt::BlockExprClass:
412    K = CXCursor_BlockExpr;
413    break;
414
415  case Stmt::PackExpansionExprClass:
416    K = CXCursor_PackExpansionExpr;
417    break;
418
419  case Stmt::SizeOfPackExprClass:
420    K = CXCursor_SizeOfPackExpr;
421    break;
422
423  case Stmt::DeclRefExprClass:
424  case Stmt::DependentScopeDeclRefExprClass:
425  case Stmt::SubstNonTypeTemplateParmExprClass:
426  case Stmt::SubstNonTypeTemplateParmPackExprClass:
427  case Stmt::UnresolvedLookupExprClass:
428    K = CXCursor_DeclRefExpr;
429    break;
430
431  case Stmt::CXXDependentScopeMemberExprClass:
432  case Stmt::CXXPseudoDestructorExprClass:
433  case Stmt::MemberExprClass:
434  case Stmt::ObjCIsaExprClass:
435  case Stmt::ObjCIvarRefExprClass:
436  case Stmt::ObjCPropertyRefExprClass:
437  case Stmt::UnresolvedMemberExprClass:
438    K = CXCursor_MemberRefExpr;
439    break;
440
441  case Stmt::CallExprClass:
442  case Stmt::CXXOperatorCallExprClass:
443  case Stmt::CXXMemberCallExprClass:
444  case Stmt::CUDAKernelCallExprClass:
445  case Stmt::CXXConstructExprClass:
446  case Stmt::CXXTemporaryObjectExprClass:
447  case Stmt::CXXUnresolvedConstructExprClass:
448  case Stmt::UserDefinedLiteralClass:
449    K = CXCursor_CallExpr;
450    break;
451
452  case Stmt::LambdaExprClass:
453    K = CXCursor_LambdaExpr;
454    break;
455
456  case Stmt::ObjCMessageExprClass: {
457    K = CXCursor_ObjCMessageExpr;
458    int SelectorIdIndex = -1;
459    // Check if cursor points to a selector id.
460    if (RegionOfInterest.isValid() &&
461        RegionOfInterest.getBegin() == RegionOfInterest.getEnd()) {
462      SmallVector<SourceLocation, 16> SelLocs;
463      cast<ObjCMessageExpr>(S)->getSelectorLocs(SelLocs);
464      SmallVector<SourceLocation, 16>::iterator
465        I=std::find(SelLocs.begin(), SelLocs.end(),RegionOfInterest.getBegin());
466      if (I != SelLocs.end())
467        SelectorIdIndex = I - SelLocs.begin();
468    }
469    CXCursor C = { K, 0, { Parent, S, TU } };
470    return getSelectorIdentifierCursor(SelectorIdIndex, C);
471  }
472
473  case Stmt::MSDependentExistsStmtClass:
474    K = CXCursor_UnexposedStmt;
475    break;
476  }
477
478  CXCursor C = { K, 0, { Parent, S, TU } };
479  return C;
480}
481
482CXCursor cxcursor::MakeCursorObjCSuperClassRef(ObjCInterfaceDecl *Super,
483                                               SourceLocation Loc,
484                                               CXTranslationUnit TU) {
485  assert(Super && TU && "Invalid arguments!");
486  void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
487  CXCursor C = { CXCursor_ObjCSuperClassRef, 0, { Super, RawLoc, TU } };
488  return C;
489}
490
491std::pair<ObjCInterfaceDecl *, SourceLocation>
492cxcursor::getCursorObjCSuperClassRef(CXCursor C) {
493  assert(C.kind == CXCursor_ObjCSuperClassRef);
494  return std::make_pair(static_cast<ObjCInterfaceDecl *>(C.data[0]),
495           SourceLocation::getFromRawEncoding(
496                                      reinterpret_cast<uintptr_t>(C.data[1])));
497}
498
499CXCursor cxcursor::MakeCursorObjCProtocolRef(const ObjCProtocolDecl *Proto,
500                                             SourceLocation Loc,
501                                             CXTranslationUnit TU) {
502  assert(Proto && TU && "Invalid arguments!");
503  void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
504  CXCursor C = { CXCursor_ObjCProtocolRef, 0, { (void*)Proto, RawLoc, TU } };
505  return C;
506}
507
508std::pair<ObjCProtocolDecl *, SourceLocation>
509cxcursor::getCursorObjCProtocolRef(CXCursor C) {
510  assert(C.kind == CXCursor_ObjCProtocolRef);
511  return std::make_pair(static_cast<ObjCProtocolDecl *>(C.data[0]),
512           SourceLocation::getFromRawEncoding(
513                                      reinterpret_cast<uintptr_t>(C.data[1])));
514}
515
516CXCursor cxcursor::MakeCursorObjCClassRef(const ObjCInterfaceDecl *Class,
517                                          SourceLocation Loc,
518                                          CXTranslationUnit TU) {
519  // 'Class' can be null for invalid code.
520  if (!Class)
521    return MakeCXCursorInvalid(CXCursor_InvalidCode);
522  assert(TU && "Invalid arguments!");
523  void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
524  CXCursor C = { CXCursor_ObjCClassRef, 0, { (void*)Class, RawLoc, TU } };
525  return C;
526}
527
528std::pair<ObjCInterfaceDecl *, SourceLocation>
529cxcursor::getCursorObjCClassRef(CXCursor C) {
530  assert(C.kind == CXCursor_ObjCClassRef);
531  return std::make_pair(static_cast<ObjCInterfaceDecl *>(C.data[0]),
532           SourceLocation::getFromRawEncoding(
533                                      reinterpret_cast<uintptr_t>(C.data[1])));
534}
535
536CXCursor cxcursor::MakeCursorTypeRef(const TypeDecl *Type, SourceLocation Loc,
537                                     CXTranslationUnit TU) {
538  assert(Type && TU && "Invalid arguments!");
539  void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
540  CXCursor C = { CXCursor_TypeRef, 0, { (void*)Type, RawLoc, TU } };
541  return C;
542}
543
544std::pair<TypeDecl *, SourceLocation>
545cxcursor::getCursorTypeRef(CXCursor C) {
546  assert(C.kind == CXCursor_TypeRef);
547  return std::make_pair(static_cast<TypeDecl *>(C.data[0]),
548           SourceLocation::getFromRawEncoding(
549                                      reinterpret_cast<uintptr_t>(C.data[1])));
550}
551
552CXCursor cxcursor::MakeCursorTemplateRef(const TemplateDecl *Template,
553                                         SourceLocation Loc,
554                                         CXTranslationUnit TU) {
555  assert(Template && TU && "Invalid arguments!");
556  void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
557  CXCursor C = { CXCursor_TemplateRef, 0, { (void*)Template, RawLoc, TU } };
558  return C;
559}
560
561std::pair<TemplateDecl *, SourceLocation>
562cxcursor::getCursorTemplateRef(CXCursor C) {
563  assert(C.kind == CXCursor_TemplateRef);
564  return std::make_pair(static_cast<TemplateDecl *>(C.data[0]),
565                        SourceLocation::getFromRawEncoding(
566                                       reinterpret_cast<uintptr_t>(C.data[1])));
567}
568
569CXCursor cxcursor::MakeCursorNamespaceRef(const NamedDecl *NS,
570                                          SourceLocation Loc,
571                                          CXTranslationUnit TU) {
572
573  assert(NS && (isa<NamespaceDecl>(NS) || isa<NamespaceAliasDecl>(NS)) && TU &&
574         "Invalid arguments!");
575  void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
576  CXCursor C = { CXCursor_NamespaceRef, 0, { (void*)NS, RawLoc, TU } };
577  return C;
578}
579
580std::pair<NamedDecl *, SourceLocation>
581cxcursor::getCursorNamespaceRef(CXCursor C) {
582  assert(C.kind == CXCursor_NamespaceRef);
583  return std::make_pair(static_cast<NamedDecl *>(C.data[0]),
584                        SourceLocation::getFromRawEncoding(
585                                       reinterpret_cast<uintptr_t>(C.data[1])));
586}
587
588CXCursor cxcursor::MakeCursorVariableRef(const VarDecl *Var, SourceLocation Loc,
589                                         CXTranslationUnit TU) {
590
591  assert(Var && TU && "Invalid arguments!");
592  void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
593  CXCursor C = { CXCursor_VariableRef, 0, { (void*)Var, RawLoc, TU } };
594  return C;
595}
596
597std::pair<VarDecl *, SourceLocation>
598cxcursor::getCursorVariableRef(CXCursor C) {
599  assert(C.kind == CXCursor_VariableRef);
600  return std::make_pair(static_cast<VarDecl *>(C.data[0]),
601                        SourceLocation::getFromRawEncoding(
602                          reinterpret_cast<uintptr_t>(C.data[1])));
603}
604
605CXCursor cxcursor::MakeCursorMemberRef(const FieldDecl *Field, SourceLocation Loc,
606                                       CXTranslationUnit TU) {
607
608  assert(Field && TU && "Invalid arguments!");
609  void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
610  CXCursor C = { CXCursor_MemberRef, 0, { (void*)Field, RawLoc, TU } };
611  return C;
612}
613
614std::pair<FieldDecl *, SourceLocation>
615cxcursor::getCursorMemberRef(CXCursor C) {
616  assert(C.kind == CXCursor_MemberRef);
617  return std::make_pair(static_cast<FieldDecl *>(C.data[0]),
618                        SourceLocation::getFromRawEncoding(
619                                       reinterpret_cast<uintptr_t>(C.data[1])));
620}
621
622CXCursor cxcursor::MakeCursorCXXBaseSpecifier(const CXXBaseSpecifier *B,
623                                              CXTranslationUnit TU){
624  CXCursor C = { CXCursor_CXXBaseSpecifier, 0, { (void*)B, 0, TU } };
625  return C;
626}
627
628CXXBaseSpecifier *cxcursor::getCursorCXXBaseSpecifier(CXCursor C) {
629  assert(C.kind == CXCursor_CXXBaseSpecifier);
630  return static_cast<CXXBaseSpecifier*>(C.data[0]);
631}
632
633CXCursor cxcursor::MakePreprocessingDirectiveCursor(SourceRange Range,
634                                                    CXTranslationUnit TU) {
635  CXCursor C = { CXCursor_PreprocessingDirective, 0,
636                 { reinterpret_cast<void *>(Range.getBegin().getRawEncoding()),
637                   reinterpret_cast<void *>(Range.getEnd().getRawEncoding()),
638                   TU }
639               };
640  return C;
641}
642
643SourceRange cxcursor::getCursorPreprocessingDirective(CXCursor C) {
644  assert(C.kind == CXCursor_PreprocessingDirective);
645  SourceRange Range = SourceRange(SourceLocation::getFromRawEncoding(
646                                      reinterpret_cast<uintptr_t> (C.data[0])),
647                     SourceLocation::getFromRawEncoding(
648                                      reinterpret_cast<uintptr_t> (C.data[1])));
649  ASTUnit *TU = getCursorASTUnit(C);
650  return TU->mapRangeFromPreamble(Range);
651}
652
653CXCursor cxcursor::MakeMacroDefinitionCursor(MacroDefinition *MI,
654                                             CXTranslationUnit TU) {
655  CXCursor C = { CXCursor_MacroDefinition, 0, { MI, 0, TU } };
656  return C;
657}
658
659MacroDefinition *cxcursor::getCursorMacroDefinition(CXCursor C) {
660  assert(C.kind == CXCursor_MacroDefinition);
661  return static_cast<MacroDefinition *>(C.data[0]);
662}
663
664CXCursor cxcursor::MakeMacroExpansionCursor(MacroExpansion *MI,
665                                            CXTranslationUnit TU) {
666  CXCursor C = { CXCursor_MacroExpansion, 0, { MI, 0, TU } };
667  return C;
668}
669
670MacroExpansion *cxcursor::getCursorMacroExpansion(CXCursor C) {
671  assert(C.kind == CXCursor_MacroExpansion);
672  return static_cast<MacroExpansion *>(C.data[0]);
673}
674
675CXCursor cxcursor::MakeInclusionDirectiveCursor(InclusionDirective *ID,
676                                                CXTranslationUnit TU) {
677  CXCursor C = { CXCursor_InclusionDirective, 0, { ID, 0, TU } };
678  return C;
679}
680
681InclusionDirective *cxcursor::getCursorInclusionDirective(CXCursor C) {
682  assert(C.kind == CXCursor_InclusionDirective);
683  return static_cast<InclusionDirective *>(C.data[0]);
684}
685
686CXCursor cxcursor::MakeCursorLabelRef(LabelStmt *Label, SourceLocation Loc,
687                                      CXTranslationUnit TU) {
688
689  assert(Label && TU && "Invalid arguments!");
690  void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
691  CXCursor C = { CXCursor_LabelRef, 0, { Label, RawLoc, TU } };
692  return C;
693}
694
695std::pair<LabelStmt*, SourceLocation>
696cxcursor::getCursorLabelRef(CXCursor C) {
697  assert(C.kind == CXCursor_LabelRef);
698  return std::make_pair(static_cast<LabelStmt *>(C.data[0]),
699                        SourceLocation::getFromRawEncoding(
700                                       reinterpret_cast<uintptr_t>(C.data[1])));
701}
702
703CXCursor cxcursor::MakeCursorOverloadedDeclRef(OverloadExpr *E,
704                                               CXTranslationUnit TU) {
705  assert(E && TU && "Invalid arguments!");
706  OverloadedDeclRefStorage Storage(E);
707  void *RawLoc = reinterpret_cast<void *>(E->getNameLoc().getRawEncoding());
708  CXCursor C = {
709                 CXCursor_OverloadedDeclRef, 0,
710                 { Storage.getOpaqueValue(), RawLoc, TU }
711               };
712  return C;
713}
714
715CXCursor cxcursor::MakeCursorOverloadedDeclRef(Decl *D,
716                                               SourceLocation Loc,
717                                               CXTranslationUnit TU) {
718  assert(D && TU && "Invalid arguments!");
719  void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
720  OverloadedDeclRefStorage Storage(D);
721  CXCursor C = {
722    CXCursor_OverloadedDeclRef, 0,
723    { Storage.getOpaqueValue(), RawLoc, TU }
724  };
725  return C;
726}
727
728CXCursor cxcursor::MakeCursorOverloadedDeclRef(TemplateName Name,
729                                               SourceLocation Loc,
730                                               CXTranslationUnit TU) {
731  assert(Name.getAsOverloadedTemplate() && TU && "Invalid arguments!");
732  void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
733  OverloadedDeclRefStorage Storage(Name.getAsOverloadedTemplate());
734  CXCursor C = {
735    CXCursor_OverloadedDeclRef, 0,
736    { Storage.getOpaqueValue(), RawLoc, TU }
737  };
738  return C;
739}
740
741std::pair<cxcursor::OverloadedDeclRefStorage, SourceLocation>
742cxcursor::getCursorOverloadedDeclRef(CXCursor C) {
743  assert(C.kind == CXCursor_OverloadedDeclRef);
744  return std::make_pair(OverloadedDeclRefStorage::getFromOpaqueValue(C.data[0]),
745                        SourceLocation::getFromRawEncoding(
746                                       reinterpret_cast<uintptr_t>(C.data[1])));
747}
748
749Decl *cxcursor::getCursorDecl(CXCursor Cursor) {
750  return (Decl *)Cursor.data[0];
751}
752
753Expr *cxcursor::getCursorExpr(CXCursor Cursor) {
754  return dyn_cast_or_null<Expr>(getCursorStmt(Cursor));
755}
756
757Stmt *cxcursor::getCursorStmt(CXCursor Cursor) {
758  if (Cursor.kind == CXCursor_ObjCSuperClassRef ||
759      Cursor.kind == CXCursor_ObjCProtocolRef ||
760      Cursor.kind == CXCursor_ObjCClassRef)
761    return 0;
762
763  return (Stmt *)Cursor.data[1];
764}
765
766Attr *cxcursor::getCursorAttr(CXCursor Cursor) {
767  return (Attr *)Cursor.data[1];
768}
769
770Decl *cxcursor::getCursorParentDecl(CXCursor Cursor) {
771  return (Decl *)Cursor.data[0];
772}
773
774ASTContext &cxcursor::getCursorContext(CXCursor Cursor) {
775  return getCursorASTUnit(Cursor)->getASTContext();
776}
777
778ASTUnit *cxcursor::getCursorASTUnit(CXCursor Cursor) {
779  CXTranslationUnit TU = static_cast<CXTranslationUnit>(Cursor.data[2]);
780  if (!TU)
781    return 0;
782  return static_cast<ASTUnit *>(TU->TUData);
783}
784
785CXTranslationUnit cxcursor::getCursorTU(CXCursor Cursor) {
786  return static_cast<CXTranslationUnit>(Cursor.data[2]);
787}
788
789static void CollectOverriddenMethodsRecurse(CXTranslationUnit TU,
790                                     ObjCContainerDecl *Container,
791                                     ObjCMethodDecl *Method,
792                                     SmallVectorImpl<CXCursor> &Methods,
793                                     bool MovedToSuper) {
794  if (!Container)
795    return;
796
797  // In categories look for overriden methods from protocols. A method from
798  // category is not "overriden" since it is considered as the "same" method
799  // (same USR) as the one from the interface.
800  if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
801    // Check whether we have a matching method at this category but only if we
802    // are at the super class level.
803    if (MovedToSuper)
804      if (ObjCMethodDecl *
805            Overridden = Container->getMethod(Method->getSelector(),
806                                              Method->isInstanceMethod()))
807        if (Method != Overridden) {
808          // We found an override at this category; there is no need to look
809          // into its protocols.
810          Methods.push_back(MakeCXCursor(Overridden, TU));
811          return;
812        }
813
814    for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
815                                          PEnd = Category->protocol_end();
816         P != PEnd; ++P)
817      CollectOverriddenMethodsRecurse(TU, *P, Method, Methods, MovedToSuper);
818    return;
819  }
820
821  // Check whether we have a matching method at this level.
822  if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
823                                                    Method->isInstanceMethod()))
824    if (Method != Overridden) {
825      // We found an override at this level; there is no need to look
826      // into other protocols or categories.
827      Methods.push_back(MakeCXCursor(Overridden, TU));
828      return;
829    }
830
831  if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
832    for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
833                                          PEnd = Protocol->protocol_end();
834         P != PEnd; ++P)
835      CollectOverriddenMethodsRecurse(TU, *P, Method, Methods, MovedToSuper);
836  }
837
838  if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
839    for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
840                                           PEnd = Interface->protocol_end();
841         P != PEnd; ++P)
842      CollectOverriddenMethodsRecurse(TU, *P, Method, Methods, MovedToSuper);
843
844    for (ObjCCategoryDecl *Category = Interface->getCategoryList();
845         Category; Category = Category->getNextClassCategory())
846      CollectOverriddenMethodsRecurse(TU, Category, Method, Methods,
847                                      MovedToSuper);
848
849    if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
850      return CollectOverriddenMethodsRecurse(TU, Super, Method, Methods,
851                                             /*MovedToSuper=*/true);
852  }
853}
854
855static inline void CollectOverriddenMethods(CXTranslationUnit TU,
856                                           ObjCContainerDecl *Container,
857                                           ObjCMethodDecl *Method,
858                                           SmallVectorImpl<CXCursor> &Methods) {
859  CollectOverriddenMethodsRecurse(TU, Container, Method, Methods,
860                                  /*MovedToSuper=*/false);
861}
862
863void cxcursor::getOverriddenCursors(CXCursor cursor,
864                                    SmallVectorImpl<CXCursor> &overridden) {
865  assert(clang_isDeclaration(cursor.kind));
866  Decl *D = getCursorDecl(cursor);
867  if (!D)
868    return;
869
870  // Handle C++ member functions.
871  CXTranslationUnit TU = getCursorTU(cursor);
872  if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
873    for (CXXMethodDecl::method_iterator
874              M = CXXMethod->begin_overridden_methods(),
875           MEnd = CXXMethod->end_overridden_methods();
876         M != MEnd; ++M)
877      overridden.push_back(MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU));
878    return;
879  }
880
881  ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
882  if (!Method)
883    return;
884
885  if (ObjCProtocolDecl *
886        ProtD = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext())) {
887    CollectOverriddenMethods(TU, ProtD, Method, overridden);
888
889  } else if (ObjCImplDecl *
890               IMD = dyn_cast<ObjCImplDecl>(Method->getDeclContext())) {
891    ObjCInterfaceDecl *ID = IMD->getClassInterface();
892    if (!ID)
893      return;
894    // Start searching for overridden methods using the method from the
895    // interface as starting point.
896    if (ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(),
897                                                  Method->isInstanceMethod()))
898      Method = IFaceMeth;
899    CollectOverriddenMethods(TU, ID, Method, overridden);
900
901  } else if (ObjCCategoryDecl *
902               CatD = dyn_cast<ObjCCategoryDecl>(Method->getDeclContext())) {
903    ObjCInterfaceDecl *ID = CatD->getClassInterface();
904    if (!ID)
905      return;
906    // Start searching for overridden methods using the method from the
907    // interface as starting point.
908    if (ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(),
909                                                  Method->isInstanceMethod()))
910      Method = IFaceMeth;
911    CollectOverriddenMethods(TU, ID, Method, overridden);
912
913  } else {
914    CollectOverriddenMethods(TU,
915                  dyn_cast_or_null<ObjCContainerDecl>(Method->getDeclContext()),
916                  Method, overridden);
917  }
918}
919
920std::pair<int, SourceLocation>
921cxcursor::getSelectorIdentifierIndexAndLoc(CXCursor cursor) {
922  if (cursor.kind == CXCursor_ObjCMessageExpr) {
923    if (cursor.xdata != -1)
924      return std::make_pair(cursor.xdata,
925                            cast<ObjCMessageExpr>(getCursorExpr(cursor))
926                                                ->getSelectorLoc(cursor.xdata));
927  } else if (cursor.kind == CXCursor_ObjCClassMethodDecl ||
928             cursor.kind == CXCursor_ObjCInstanceMethodDecl) {
929    if (cursor.xdata != -1)
930      return std::make_pair(cursor.xdata,
931                            cast<ObjCMethodDecl>(getCursorDecl(cursor))
932                                                ->getSelectorLoc(cursor.xdata));
933  }
934
935  return std::make_pair(-1, SourceLocation());
936}
937
938CXCursor cxcursor::getSelectorIdentifierCursor(int SelIdx, CXCursor cursor) {
939  CXCursor newCursor = cursor;
940
941  if (cursor.kind == CXCursor_ObjCMessageExpr) {
942    if (SelIdx == -1 ||
943        unsigned(SelIdx) >= cast<ObjCMessageExpr>(getCursorExpr(cursor))
944                                                         ->getNumSelectorLocs())
945      newCursor.xdata = -1;
946    else
947      newCursor.xdata = SelIdx;
948  } else if (cursor.kind == CXCursor_ObjCClassMethodDecl ||
949             cursor.kind == CXCursor_ObjCInstanceMethodDecl) {
950    if (SelIdx == -1 ||
951        unsigned(SelIdx) >= cast<ObjCMethodDecl>(getCursorDecl(cursor))
952                                                         ->getNumSelectorLocs())
953      newCursor.xdata = -1;
954    else
955      newCursor.xdata = SelIdx;
956  }
957
958  return newCursor;
959}
960
961CXCursor cxcursor::getTypeRefCursor(CXCursor cursor) {
962  if (cursor.kind != CXCursor_CallExpr)
963    return cursor;
964
965  if (cursor.xdata == 0)
966    return cursor;
967
968  Expr *E = getCursorExpr(cursor);
969  TypeSourceInfo *Type = 0;
970  if (CXXUnresolvedConstructExpr *
971        UnCtor = dyn_cast<CXXUnresolvedConstructExpr>(E)) {
972    Type = UnCtor->getTypeSourceInfo();
973  } else if (CXXTemporaryObjectExpr *Tmp = dyn_cast<CXXTemporaryObjectExpr>(E)){
974    Type = Tmp->getTypeSourceInfo();
975  }
976
977  if (!Type)
978    return cursor;
979
980  CXTranslationUnit TU = getCursorTU(cursor);
981  QualType Ty = Type->getType();
982  TypeLoc TL = Type->getTypeLoc();
983  SourceLocation Loc = TL.getBeginLoc();
984
985  if (const ElaboratedType *ElabT = Ty->getAs<ElaboratedType>()) {
986    Ty = ElabT->getNamedType();
987    ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(TL);
988    Loc = ElabTL.getNamedTypeLoc().getBeginLoc();
989  }
990
991  if (const TypedefType *Typedef = Ty->getAs<TypedefType>())
992    return MakeCursorTypeRef(Typedef->getDecl(), Loc, TU);
993  if (const TagType *Tag = Ty->getAs<TagType>())
994    return MakeCursorTypeRef(Tag->getDecl(), Loc, TU);
995  if (const TemplateTypeParmType *TemplP = Ty->getAs<TemplateTypeParmType>())
996    return MakeCursorTypeRef(TemplP->getDecl(), Loc, TU);
997
998  return cursor;
999}
1000
1001bool cxcursor::operator==(CXCursor X, CXCursor Y) {
1002  return X.kind == Y.kind && X.data[0] == Y.data[0] && X.data[1] == Y.data[1] &&
1003         X.data[2] == Y.data[2];
1004}
1005
1006// FIXME: Remove once we can model DeclGroups and their appropriate ranges
1007// properly in the ASTs.
1008bool cxcursor::isFirstInDeclGroup(CXCursor C) {
1009  assert(clang_isDeclaration(C.kind));
1010  return ((uintptr_t) (C.data[1])) != 0;
1011}
1012
1013//===----------------------------------------------------------------------===//
1014// libclang CXCursor APIs
1015//===----------------------------------------------------------------------===//
1016
1017extern "C" {
1018
1019int clang_Cursor_isNull(CXCursor cursor) {
1020  return clang_equalCursors(cursor, clang_getNullCursor());
1021}
1022
1023CXTranslationUnit clang_Cursor_getTranslationUnit(CXCursor cursor) {
1024  return getCursorTU(cursor);
1025}
1026
1027int clang_Cursor_getNumArguments(CXCursor C) {
1028  if (clang_isDeclaration(C.kind)) {
1029    Decl *D = cxcursor::getCursorDecl(C);
1030    if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
1031      return MD->param_size();
1032    if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
1033      return FD->param_size();
1034  }
1035
1036  return -1;
1037}
1038
1039CXCursor clang_Cursor_getArgument(CXCursor C, unsigned i) {
1040  if (clang_isDeclaration(C.kind)) {
1041    Decl *D = cxcursor::getCursorDecl(C);
1042    if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
1043      if (i < MD->param_size())
1044        return cxcursor::MakeCXCursor(MD->param_begin()[i],
1045                                      cxcursor::getCursorTU(C));
1046    } else if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
1047      if (i < FD->param_size())
1048        return cxcursor::MakeCXCursor(FD->param_begin()[i],
1049                                      cxcursor::getCursorTU(C));
1050    }
1051  }
1052
1053  return clang_getNullCursor();
1054}
1055
1056} // end: extern "C"
1057
1058//===----------------------------------------------------------------------===//
1059// CXCursorSet.
1060//===----------------------------------------------------------------------===//
1061
1062typedef llvm::DenseMap<CXCursor, unsigned> CXCursorSet_Impl;
1063
1064static inline CXCursorSet packCXCursorSet(CXCursorSet_Impl *setImpl) {
1065  return (CXCursorSet) setImpl;
1066}
1067static inline CXCursorSet_Impl *unpackCXCursorSet(CXCursorSet set) {
1068  return (CXCursorSet_Impl*) set;
1069}
1070namespace llvm {
1071template<> struct DenseMapInfo<CXCursor> {
1072public:
1073  static inline CXCursor getEmptyKey() {
1074    return MakeCXCursorInvalid(CXCursor_InvalidFile);
1075  }
1076  static inline CXCursor getTombstoneKey() {
1077    return MakeCXCursorInvalid(CXCursor_NoDeclFound);
1078  }
1079  static inline unsigned getHashValue(const CXCursor &cursor) {
1080    return llvm::DenseMapInfo<std::pair<void*,void*> >
1081      ::getHashValue(std::make_pair(cursor.data[0], cursor.data[1]));
1082  }
1083  static inline bool isEqual(const CXCursor &x, const CXCursor &y) {
1084    return x.kind == y.kind &&
1085           x.data[0] == y.data[0] &&
1086           x.data[1] == y.data[1];
1087  }
1088};
1089}
1090
1091extern "C" {
1092CXCursorSet clang_createCXCursorSet() {
1093  return packCXCursorSet(new CXCursorSet_Impl());
1094}
1095
1096void clang_disposeCXCursorSet(CXCursorSet set) {
1097  delete unpackCXCursorSet(set);
1098}
1099
1100unsigned clang_CXCursorSet_contains(CXCursorSet set, CXCursor cursor) {
1101  CXCursorSet_Impl *setImpl = unpackCXCursorSet(set);
1102  if (!setImpl)
1103    return 0;
1104  return setImpl->find(cursor) == setImpl->end();
1105}
1106
1107unsigned clang_CXCursorSet_insert(CXCursorSet set, CXCursor cursor) {
1108  // Do not insert invalid cursors into the set.
1109  if (cursor.kind >= CXCursor_FirstInvalid &&
1110      cursor.kind <= CXCursor_LastInvalid)
1111    return 1;
1112
1113  CXCursorSet_Impl *setImpl = unpackCXCursorSet(set);
1114  if (!setImpl)
1115    return 1;
1116  unsigned &entry = (*setImpl)[cursor];
1117  unsigned flag = entry == 0 ? 1 : 0;
1118  entry = 1;
1119  return flag;
1120}
1121
1122CXCompletionString clang_getCursorCompletionString(CXCursor cursor) {
1123  enum CXCursorKind kind = clang_getCursorKind(cursor);
1124  if (clang_isDeclaration(kind)) {
1125    Decl *decl = getCursorDecl(cursor);
1126    if (NamedDecl *namedDecl = dyn_cast_or_null<NamedDecl>(decl)) {
1127      ASTUnit *unit = getCursorASTUnit(cursor);
1128      CodeCompletionResult Result(namedDecl);
1129      CodeCompletionString *String
1130        = Result.CreateCodeCompletionString(unit->getASTContext(),
1131                                            unit->getPreprocessor(),
1132                                 unit->getCodeCompletionTUInfo().getAllocator(),
1133                                 unit->getCodeCompletionTUInfo());
1134      return String;
1135    }
1136  }
1137  else if (kind == CXCursor_MacroDefinition) {
1138    MacroDefinition *definition = getCursorMacroDefinition(cursor);
1139    const IdentifierInfo *MacroInfo = definition->getName();
1140    ASTUnit *unit = getCursorASTUnit(cursor);
1141    CodeCompletionResult Result(const_cast<IdentifierInfo *>(MacroInfo));
1142    CodeCompletionString *String
1143      = Result.CreateCodeCompletionString(unit->getASTContext(),
1144                                          unit->getPreprocessor(),
1145                                 unit->getCodeCompletionTUInfo().getAllocator(),
1146                                 unit->getCodeCompletionTUInfo());
1147    return String;
1148  }
1149  return NULL;
1150}
1151
1152} // end: extern "C"
1153