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