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