blob: 51ed343f528b55853806c10a90e8ff79e642b8ff [file] [log] [blame]
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
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 implements the main API hooks in the Clang-C Source Indexing
11// library.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CIndexer.h"
16#include "CIndexDiagnostic.h"
17#include "CXComment.h"
18#include "CXCursor.h"
19#include "CXSourceLocation.h"
20#include "CXString.h"
21#include "CXTranslationUnit.h"
22#include "CXType.h"
23#include "CursorVisitor.h"
Fariborz Jahanian88b95212012-12-18 23:02:59 +000024#include "SimpleFormatContext.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000025#include "clang/AST/StmtVisitor.h"
26#include "clang/Basic/Diagnostic.h"
27#include "clang/Basic/Version.h"
28#include "clang/Frontend/ASTUnit.h"
29#include "clang/Frontend/CompilerInstance.h"
30#include "clang/Frontend/FrontendDiagnostic.h"
31#include "clang/Lex/HeaderSearch.h"
32#include "clang/Lex/Lexer.h"
33#include "clang/Lex/PreprocessingRecord.h"
34#include "clang/Lex/Preprocessor.h"
35#include "llvm/ADT/Optional.h"
36#include "llvm/ADT/STLExtras.h"
37#include "llvm/ADT/StringSwitch.h"
38#include "llvm/Support/Compiler.h"
39#include "llvm/Support/CrashRecoveryContext.h"
40#include "llvm/Support/MemoryBuffer.h"
41#include "llvm/Support/Mutex.h"
42#include "llvm/Support/PrettyStackTrace.h"
43#include "llvm/Support/Program.h"
44#include "llvm/Support/SaveAndRestore.h"
45#include "llvm/Support/Signals.h"
46#include "llvm/Support/Threading.h"
47#include "llvm/Support/Timer.h"
48#include "llvm/Support/raw_ostream.h"
49
50using namespace clang;
51using namespace clang::cxcursor;
52using namespace clang::cxstring;
53using namespace clang::cxtu;
54using namespace clang::cxindex;
55
56CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *TU) {
57 if (!TU)
58 return 0;
59 CXTranslationUnit D = new CXTranslationUnitImpl();
60 D->CIdx = CIdx;
61 D->TUData = TU;
62 D->StringPool = createCXStringPool();
63 D->Diagnostics = 0;
64 D->OverridenCursorsPool = createOverridenCXCursorsPool();
Fariborz Jahanian88b95212012-12-18 23:02:59 +000065 D->FormatContext = 0;
66 D->FormatInMemoryUniqueId = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +000067 return D;
68}
69
70cxtu::CXTUOwner::~CXTUOwner() {
71 if (TU)
72 clang_disposeTranslationUnit(TU);
73}
74
75/// \brief Compare two source ranges to determine their relative position in
76/// the translation unit.
77static RangeComparisonResult RangeCompare(SourceManager &SM,
78 SourceRange R1,
79 SourceRange R2) {
80 assert(R1.isValid() && "First range is invalid?");
81 assert(R2.isValid() && "Second range is invalid?");
82 if (R1.getEnd() != R2.getBegin() &&
83 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
84 return RangeBefore;
85 if (R2.getEnd() != R1.getBegin() &&
86 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
87 return RangeAfter;
88 return RangeOverlap;
89}
90
91/// \brief Determine if a source location falls within, before, or after a
92/// a given source range.
93static RangeComparisonResult LocationCompare(SourceManager &SM,
94 SourceLocation L, SourceRange R) {
95 assert(R.isValid() && "First range is invalid?");
96 assert(L.isValid() && "Second range is invalid?");
97 if (L == R.getBegin() || L == R.getEnd())
98 return RangeOverlap;
99 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
100 return RangeBefore;
101 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
102 return RangeAfter;
103 return RangeOverlap;
104}
105
106/// \brief Translate a Clang source range into a CIndex source range.
107///
108/// Clang internally represents ranges where the end location points to the
109/// start of the token at the end. However, for external clients it is more
110/// useful to have a CXSourceRange be a proper half-open interval. This routine
111/// does the appropriate translation.
112CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
113 const LangOptions &LangOpts,
114 const CharSourceRange &R) {
115 // We want the last character in this location, so we will adjust the
116 // location accordingly.
117 SourceLocation EndLoc = R.getEnd();
118 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
119 EndLoc = SM.getExpansionRange(EndLoc).second;
120 if (R.isTokenRange() && !EndLoc.isInvalid()) {
121 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
122 SM, LangOpts);
123 EndLoc = EndLoc.getLocWithOffset(Length);
124 }
125
126 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
127 R.getBegin().getRawEncoding(),
128 EndLoc.getRawEncoding() };
129 return Result;
130}
131
132//===----------------------------------------------------------------------===//
133// Cursor visitor.
134//===----------------------------------------------------------------------===//
135
136static SourceRange getRawCursorExtent(CXCursor C);
137static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
138
139
140RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
141 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
142}
143
144/// \brief Visit the given cursor and, if requested by the visitor,
145/// its children.
146///
147/// \param Cursor the cursor to visit.
148///
149/// \param CheckedRegionOfInterest if true, then the caller already checked
150/// that this cursor is within the region of interest.
151///
152/// \returns true if the visitation should be aborted, false if it
153/// should continue.
154bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
155 if (clang_isInvalid(Cursor.kind))
156 return false;
157
158 if (clang_isDeclaration(Cursor.kind)) {
159 Decl *D = getCursorDecl(Cursor);
160 if (!D) {
161 assert(0 && "Invalid declaration cursor");
162 return true; // abort.
163 }
164
165 // Ignore implicit declarations, unless it's an objc method because
166 // currently we should report implicit methods for properties when indexing.
167 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
168 return false;
169 }
170
171 // If we have a range of interest, and this cursor doesn't intersect with it,
172 // we're done.
173 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
174 SourceRange Range = getRawCursorExtent(Cursor);
175 if (Range.isInvalid() || CompareRegionOfInterest(Range))
176 return false;
177 }
178
179 switch (Visitor(Cursor, Parent, ClientData)) {
180 case CXChildVisit_Break:
181 return true;
182
183 case CXChildVisit_Continue:
184 return false;
185
186 case CXChildVisit_Recurse: {
187 bool ret = VisitChildren(Cursor);
188 if (PostChildrenVisitor)
189 if (PostChildrenVisitor(Cursor, ClientData))
190 return true;
191 return ret;
192 }
193 }
194
195 llvm_unreachable("Invalid CXChildVisitResult!");
196}
197
198static bool visitPreprocessedEntitiesInRange(SourceRange R,
199 PreprocessingRecord &PPRec,
200 CursorVisitor &Visitor) {
201 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
202 FileID FID;
203
204 if (!Visitor.shouldVisitIncludedEntities()) {
205 // If the begin/end of the range lie in the same FileID, do the optimization
206 // where we skip preprocessed entities that do not come from the same FileID.
207 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
208 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
209 FID = FileID();
210 }
211
212 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
213 Entities = PPRec.getPreprocessedEntitiesInRange(R);
214 return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
215 PPRec, FID);
216}
217
218void CursorVisitor::visitFileRegion() {
219 if (RegionOfInterest.isInvalid())
220 return;
221
222 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
223 SourceManager &SM = Unit->getSourceManager();
224
225 std::pair<FileID, unsigned>
226 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
227 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
228
229 if (End.first != Begin.first) {
230 // If the end does not reside in the same file, try to recover by
231 // picking the end of the file of begin location.
232 End.first = Begin.first;
233 End.second = SM.getFileIDSize(Begin.first);
234 }
235
236 assert(Begin.first == End.first);
237 if (Begin.second > End.second)
238 return;
239
240 FileID File = Begin.first;
241 unsigned Offset = Begin.second;
242 unsigned Length = End.second - Begin.second;
243
244 if (!VisitDeclsOnly && !VisitPreprocessorLast)
245 if (visitPreprocessedEntitiesInRegion())
246 return; // visitation break.
247
248 visitDeclsFromFileRegion(File, Offset, Length);
249
250 if (!VisitDeclsOnly && VisitPreprocessorLast)
251 visitPreprocessedEntitiesInRegion();
252}
253
254static bool isInLexicalContext(Decl *D, DeclContext *DC) {
255 if (!DC)
256 return false;
257
258 for (DeclContext *DeclDC = D->getLexicalDeclContext();
259 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
260 if (DeclDC == DC)
261 return true;
262 }
263 return false;
264}
265
266void CursorVisitor::visitDeclsFromFileRegion(FileID File,
267 unsigned Offset, unsigned Length) {
268 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
269 SourceManager &SM = Unit->getSourceManager();
270 SourceRange Range = RegionOfInterest;
271
272 SmallVector<Decl *, 16> Decls;
273 Unit->findFileRegionDecls(File, Offset, Length, Decls);
274
275 // If we didn't find any file level decls for the file, try looking at the
276 // file that it was included from.
277 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
278 bool Invalid = false;
279 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
280 if (Invalid)
281 return;
282
283 SourceLocation Outer;
284 if (SLEntry.isFile())
285 Outer = SLEntry.getFile().getIncludeLoc();
286 else
287 Outer = SLEntry.getExpansion().getExpansionLocStart();
288 if (Outer.isInvalid())
289 return;
290
291 llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
292 Length = 0;
293 Unit->findFileRegionDecls(File, Offset, Length, Decls);
294 }
295
296 assert(!Decls.empty());
297
298 bool VisitedAtLeastOnce = false;
299 DeclContext *CurDC = 0;
300 SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
301 for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
302 Decl *D = *DIt;
303 if (D->getSourceRange().isInvalid())
304 continue;
305
306 if (isInLexicalContext(D, CurDC))
307 continue;
308
309 CurDC = dyn_cast<DeclContext>(D);
310
311 if (TagDecl *TD = dyn_cast<TagDecl>(D))
312 if (!TD->isFreeStanding())
313 continue;
314
315 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
316 if (CompRes == RangeBefore)
317 continue;
318 if (CompRes == RangeAfter)
319 break;
320
321 assert(CompRes == RangeOverlap);
322 VisitedAtLeastOnce = true;
323
324 if (isa<ObjCContainerDecl>(D)) {
325 FileDI_current = &DIt;
326 FileDE_current = DE;
327 } else {
328 FileDI_current = 0;
329 }
330
331 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
332 break;
333 }
334
335 if (VisitedAtLeastOnce)
336 return;
337
338 // No Decls overlapped with the range. Move up the lexical context until there
339 // is a context that contains the range or we reach the translation unit
340 // level.
341 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
342 : (*(DIt-1))->getLexicalDeclContext();
343
344 while (DC && !DC->isTranslationUnit()) {
345 Decl *D = cast<Decl>(DC);
346 SourceRange CurDeclRange = D->getSourceRange();
347 if (CurDeclRange.isInvalid())
348 break;
349
350 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
351 Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
352 break;
353 }
354
355 DC = D->getLexicalDeclContext();
356 }
357}
358
359bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
360 if (!AU->getPreprocessor().getPreprocessingRecord())
361 return false;
362
363 PreprocessingRecord &PPRec
364 = *AU->getPreprocessor().getPreprocessingRecord();
365 SourceManager &SM = AU->getSourceManager();
366
367 if (RegionOfInterest.isValid()) {
368 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
369 SourceLocation B = MappedRange.getBegin();
370 SourceLocation E = MappedRange.getEnd();
371
372 if (AU->isInPreambleFileID(B)) {
373 if (SM.isLoadedSourceLocation(E))
374 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
375 PPRec, *this);
376
377 // Beginning of range lies in the preamble but it also extends beyond
378 // it into the main file. Split the range into 2 parts, one covering
379 // the preamble and another covering the main file. This allows subsequent
380 // calls to visitPreprocessedEntitiesInRange to accept a source range that
381 // lies in the same FileID, allowing it to skip preprocessed entities that
382 // do not come from the same FileID.
383 bool breaked =
384 visitPreprocessedEntitiesInRange(
385 SourceRange(B, AU->getEndOfPreambleFileID()),
386 PPRec, *this);
387 if (breaked) return true;
388 return visitPreprocessedEntitiesInRange(
389 SourceRange(AU->getStartOfMainFileID(), E),
390 PPRec, *this);
391 }
392
393 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
394 }
395
396 bool OnlyLocalDecls
397 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
398
399 if (OnlyLocalDecls)
400 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
401 PPRec);
402
403 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
404}
405
406template<typename InputIterator>
407bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
408 InputIterator Last,
409 PreprocessingRecord &PPRec,
410 FileID FID) {
411 for (; First != Last; ++First) {
412 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
413 continue;
414
415 PreprocessedEntity *PPE = *First;
416 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
417 if (Visit(MakeMacroExpansionCursor(ME, TU)))
418 return true;
419
420 continue;
421 }
422
423 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
424 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
425 return true;
426
427 continue;
428 }
429
430 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
431 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
432 return true;
433
434 continue;
435 }
436 }
437
438 return false;
439}
440
441/// \brief Visit the children of the given cursor.
442///
443/// \returns true if the visitation should be aborted, false if it
444/// should continue.
445bool CursorVisitor::VisitChildren(CXCursor Cursor) {
446 if (clang_isReference(Cursor.kind) &&
447 Cursor.kind != CXCursor_CXXBaseSpecifier) {
448 // By definition, references have no children.
449 return false;
450 }
451
452 // Set the Parent field to Cursor, then back to its old value once we're
453 // done.
454 SetParentRAII SetParent(Parent, StmtParent, Cursor);
455
456 if (clang_isDeclaration(Cursor.kind)) {
457 Decl *D = getCursorDecl(Cursor);
458 if (!D)
459 return false;
460
461 return VisitAttributes(D) || Visit(D);
462 }
463
464 if (clang_isStatement(Cursor.kind)) {
465 if (Stmt *S = getCursorStmt(Cursor))
466 return Visit(S);
467
468 return false;
469 }
470
471 if (clang_isExpression(Cursor.kind)) {
472 if (Expr *E = getCursorExpr(Cursor))
473 return Visit(E);
474
475 return false;
476 }
477
478 if (clang_isTranslationUnit(Cursor.kind)) {
479 CXTranslationUnit tu = getCursorTU(Cursor);
480 ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
481
482 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
483 for (unsigned I = 0; I != 2; ++I) {
484 if (VisitOrder[I]) {
485 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
486 RegionOfInterest.isInvalid()) {
487 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
488 TLEnd = CXXUnit->top_level_end();
489 TL != TLEnd; ++TL) {
490 if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
491 return true;
492 }
493 } else if (VisitDeclContext(
494 CXXUnit->getASTContext().getTranslationUnitDecl()))
495 return true;
496 continue;
497 }
498
499 // Walk the preprocessing record.
500 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
501 visitPreprocessedEntitiesInRegion();
502 }
503
504 return false;
505 }
506
507 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
508 if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
509 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
510 return Visit(BaseTSInfo->getTypeLoc());
511 }
512 }
513 }
514
515 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
516 IBOutletCollectionAttr *A =
517 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
518 if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
519 return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
520 A->getInterfaceLoc(), TU));
521 }
522
Argyrios Kyrtzidis664b06f2013-01-07 19:16:25 +0000523 // If pointing inside a macro definition, check if the token is an identifier
524 // that was ever defined as a macro. In such a case, create a "pseudo" macro
525 // expansion cursor for that token.
526 SourceLocation BeginLoc = RegionOfInterest.getBegin();
527 if (Cursor.kind == CXCursor_MacroDefinition &&
528 BeginLoc == RegionOfInterest.getEnd()) {
529 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
530 MacroInfo *MI = getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor),TU);
531 if (MacroDefinition *MacroDef =
532 checkForMacroInMacroDefinition(MI, Loc, TU))
533 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
534 }
535
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000536 // Nothing to visit at the moment.
537 return false;
538}
539
540bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
541 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
542 if (Visit(TSInfo->getTypeLoc()))
543 return true;
544
545 if (Stmt *Body = B->getBody())
546 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
547
548 return false;
549}
550
551llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
552 if (RegionOfInterest.isValid()) {
553 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
554 if (Range.isInvalid())
555 return llvm::Optional<bool>();
556
557 switch (CompareRegionOfInterest(Range)) {
558 case RangeBefore:
559 // This declaration comes before the region of interest; skip it.
560 return llvm::Optional<bool>();
561
562 case RangeAfter:
563 // This declaration comes after the region of interest; we're done.
564 return false;
565
566 case RangeOverlap:
567 // This declaration overlaps the region of interest; visit it.
568 break;
569 }
570 }
571 return true;
572}
573
574bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
575 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
576
577 // FIXME: Eventually remove. This part of a hack to support proper
578 // iteration over all Decls contained lexically within an ObjC container.
579 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
580 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
581
582 for ( ; I != E; ++I) {
583 Decl *D = *I;
584 if (D->getLexicalDeclContext() != DC)
585 continue;
586 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
587
588 // Ignore synthesized ivars here, otherwise if we have something like:
589 // @synthesize prop = _prop;
590 // and '_prop' is not declared, we will encounter a '_prop' ivar before
591 // encountering the 'prop' synthesize declaration and we will think that
592 // we passed the region-of-interest.
593 if (ObjCIvarDecl *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
594 if (ivarD->getSynthesize())
595 continue;
596 }
597
598 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
599 // declarations is a mismatch with the compiler semantics.
600 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
601 ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D);
602 if (!ID->isThisDeclarationADefinition())
603 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
604
605 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
606 ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
607 if (!PD->isThisDeclarationADefinition())
608 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
609 }
610
611 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
612 if (!V.hasValue())
613 continue;
614 if (!V.getValue())
615 return false;
616 if (Visit(Cursor, true))
617 return true;
618 }
619 return false;
620}
621
622bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
623 llvm_unreachable("Translation units are visited directly by Visit()");
624}
625
626bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
627 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
628 return Visit(TSInfo->getTypeLoc());
629
630 return false;
631}
632
633bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
634 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
635 return Visit(TSInfo->getTypeLoc());
636
637 return false;
638}
639
640bool CursorVisitor::VisitTagDecl(TagDecl *D) {
641 return VisitDeclContext(D);
642}
643
644bool CursorVisitor::VisitClassTemplateSpecializationDecl(
645 ClassTemplateSpecializationDecl *D) {
646 bool ShouldVisitBody = false;
647 switch (D->getSpecializationKind()) {
648 case TSK_Undeclared:
649 case TSK_ImplicitInstantiation:
650 // Nothing to visit
651 return false;
652
653 case TSK_ExplicitInstantiationDeclaration:
654 case TSK_ExplicitInstantiationDefinition:
655 break;
656
657 case TSK_ExplicitSpecialization:
658 ShouldVisitBody = true;
659 break;
660 }
661
662 // Visit the template arguments used in the specialization.
663 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
664 TypeLoc TL = SpecType->getTypeLoc();
665 if (TemplateSpecializationTypeLoc *TSTLoc
666 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
667 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
668 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
669 return true;
670 }
671 }
672
673 if (ShouldVisitBody && VisitCXXRecordDecl(D))
674 return true;
675
676 return false;
677}
678
679bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
680 ClassTemplatePartialSpecializationDecl *D) {
681 // FIXME: Visit the "outer" template parameter lists on the TagDecl
682 // before visiting these template parameters.
683 if (VisitTemplateParameters(D->getTemplateParameters()))
684 return true;
685
686 // Visit the partial specialization arguments.
687 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
688 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
689 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
690 return true;
691
692 return VisitCXXRecordDecl(D);
693}
694
695bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
696 // Visit the default argument.
697 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
698 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
699 if (Visit(DefArg->getTypeLoc()))
700 return true;
701
702 return false;
703}
704
705bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
706 if (Expr *Init = D->getInitExpr())
707 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
708 return false;
709}
710
711bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
712 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
713 if (Visit(TSInfo->getTypeLoc()))
714 return true;
715
716 // Visit the nested-name-specifier, if present.
717 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
718 if (VisitNestedNameSpecifierLoc(QualifierLoc))
719 return true;
720
721 return false;
722}
723
724/// \brief Compare two base or member initializers based on their source order.
725static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
726 CXXCtorInitializer const * const *X
727 = static_cast<CXXCtorInitializer const * const *>(Xp);
728 CXXCtorInitializer const * const *Y
729 = static_cast<CXXCtorInitializer const * const *>(Yp);
730
731 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
732 return -1;
733 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
734 return 1;
735 else
736 return 0;
737}
738
739bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
740 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
741 // Visit the function declaration's syntactic components in the order
742 // written. This requires a bit of work.
743 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
744 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
745
746 // If we have a function declared directly (without the use of a typedef),
747 // visit just the return type. Otherwise, just visit the function's type
748 // now.
749 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
750 (!FTL && Visit(TL)))
751 return true;
752
753 // Visit the nested-name-specifier, if present.
754 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
755 if (VisitNestedNameSpecifierLoc(QualifierLoc))
756 return true;
757
758 // Visit the declaration name.
759 if (VisitDeclarationNameInfo(ND->getNameInfo()))
760 return true;
761
762 // FIXME: Visit explicitly-specified template arguments!
763
764 // Visit the function parameters, if we have a function type.
765 if (FTL && VisitFunctionTypeLoc(*FTL, true))
766 return true;
767
Bill Wendlingad017fa2012-12-20 19:22:21 +0000768 // FIXME: Attributes?
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000769 }
770
771 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
772 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
773 // Find the initializers that were written in the source.
774 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
775 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
776 IEnd = Constructor->init_end();
777 I != IEnd; ++I) {
778 if (!(*I)->isWritten())
779 continue;
780
781 WrittenInits.push_back(*I);
782 }
783
784 // Sort the initializers in source order
785 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
786 &CompareCXXCtorInitializers);
787
788 // Visit the initializers in source order
789 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
790 CXXCtorInitializer *Init = WrittenInits[I];
791 if (Init->isAnyMemberInitializer()) {
792 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
793 Init->getMemberLocation(), TU)))
794 return true;
795 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
796 if (Visit(TInfo->getTypeLoc()))
797 return true;
798 }
799
800 // Visit the initializer value.
801 if (Expr *Initializer = Init->getInit())
802 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
803 return true;
804 }
805 }
806
807 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
808 return true;
809 }
810
811 return false;
812}
813
814bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
815 if (VisitDeclaratorDecl(D))
816 return true;
817
818 if (Expr *BitWidth = D->getBitWidth())
819 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
820
821 return false;
822}
823
824bool CursorVisitor::VisitVarDecl(VarDecl *D) {
825 if (VisitDeclaratorDecl(D))
826 return true;
827
828 if (Expr *Init = D->getInit())
829 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
830
831 return false;
832}
833
834bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
835 if (VisitDeclaratorDecl(D))
836 return true;
837
838 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
839 if (Expr *DefArg = D->getDefaultArgument())
840 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
841
842 return false;
843}
844
845bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
846 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
847 // before visiting these template parameters.
848 if (VisitTemplateParameters(D->getTemplateParameters()))
849 return true;
850
851 return VisitFunctionDecl(D->getTemplatedDecl());
852}
853
854bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
855 // FIXME: Visit the "outer" template parameter lists on the TagDecl
856 // before visiting these template parameters.
857 if (VisitTemplateParameters(D->getTemplateParameters()))
858 return true;
859
860 return VisitCXXRecordDecl(D->getTemplatedDecl());
861}
862
863bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
864 if (VisitTemplateParameters(D->getTemplateParameters()))
865 return true;
866
867 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
868 VisitTemplateArgumentLoc(D->getDefaultArgument()))
869 return true;
870
871 return false;
872}
873
874bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
875 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
876 if (Visit(TSInfo->getTypeLoc()))
877 return true;
878
879 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
880 PEnd = ND->param_end();
881 P != PEnd; ++P) {
882 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
883 return true;
884 }
885
886 if (ND->isThisDeclarationADefinition() &&
887 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
888 return true;
889
890 return false;
891}
892
893template <typename DeclIt>
894static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
895 SourceManager &SM, SourceLocation EndLoc,
896 SmallVectorImpl<Decl *> &Decls) {
897 DeclIt next = *DI_current;
898 while (++next != DE_current) {
899 Decl *D_next = *next;
900 if (!D_next)
901 break;
902 SourceLocation L = D_next->getLocStart();
903 if (!L.isValid())
904 break;
905 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
906 *DI_current = next;
907 Decls.push_back(D_next);
908 continue;
909 }
910 break;
911 }
912}
913
914namespace {
915 struct ContainerDeclsSort {
916 SourceManager &SM;
917 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
918 bool operator()(Decl *A, Decl *B) {
919 SourceLocation L_A = A->getLocStart();
920 SourceLocation L_B = B->getLocStart();
921 assert(L_A.isValid() && L_B.isValid());
922 return SM.isBeforeInTranslationUnit(L_A, L_B);
923 }
924 };
925}
926
927bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
928 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
929 // an @implementation can lexically contain Decls that are not properly
930 // nested in the AST. When we identify such cases, we need to retrofit
931 // this nesting here.
932 if (!DI_current && !FileDI_current)
933 return VisitDeclContext(D);
934
935 // Scan the Decls that immediately come after the container
936 // in the current DeclContext. If any fall within the
937 // container's lexical region, stash them into a vector
938 // for later processing.
939 SmallVector<Decl *, 24> DeclsInContainer;
940 SourceLocation EndLoc = D->getSourceRange().getEnd();
941 SourceManager &SM = AU->getSourceManager();
942 if (EndLoc.isValid()) {
943 if (DI_current) {
944 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
945 DeclsInContainer);
946 } else {
947 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
948 DeclsInContainer);
949 }
950 }
951
952 // The common case.
953 if (DeclsInContainer.empty())
954 return VisitDeclContext(D);
955
956 // Get all the Decls in the DeclContext, and sort them with the
957 // additional ones we've collected. Then visit them.
958 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
959 I!=E; ++I) {
960 Decl *subDecl = *I;
961 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
962 subDecl->getLocStart().isInvalid())
963 continue;
964 DeclsInContainer.push_back(subDecl);
965 }
966
967 // Now sort the Decls so that they appear in lexical order.
968 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
969 ContainerDeclsSort(SM));
970
971 // Now visit the decls.
972 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
973 E = DeclsInContainer.end(); I != E; ++I) {
974 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
975 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
976 if (!V.hasValue())
977 continue;
978 if (!V.getValue())
979 return false;
980 if (Visit(Cursor, true))
981 return true;
982 }
983 return false;
984}
985
986bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
987 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
988 TU)))
989 return true;
990
991 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
992 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
993 E = ND->protocol_end(); I != E; ++I, ++PL)
994 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
995 return true;
996
997 return VisitObjCContainerDecl(ND);
998}
999
1000bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1001 if (!PID->isThisDeclarationADefinition())
1002 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1003
1004 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1005 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1006 E = PID->protocol_end(); I != E; ++I, ++PL)
1007 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1008 return true;
1009
1010 return VisitObjCContainerDecl(PID);
1011}
1012
1013bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1014 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1015 return true;
1016
1017 // FIXME: This implements a workaround with @property declarations also being
1018 // installed in the DeclContext for the @interface. Eventually this code
1019 // should be removed.
1020 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1021 if (!CDecl || !CDecl->IsClassExtension())
1022 return false;
1023
1024 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1025 if (!ID)
1026 return false;
1027
1028 IdentifierInfo *PropertyId = PD->getIdentifier();
1029 ObjCPropertyDecl *prevDecl =
1030 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1031
1032 if (!prevDecl)
1033 return false;
1034
1035 // Visit synthesized methods since they will be skipped when visiting
1036 // the @interface.
1037 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1038 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1039 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1040 return true;
1041
1042 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1043 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1044 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1045 return true;
1046
1047 return false;
1048}
1049
1050bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1051 if (!D->isThisDeclarationADefinition()) {
1052 // Forward declaration is treated like a reference.
1053 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1054 }
1055
1056 // Issue callbacks for super class.
1057 if (D->getSuperClass() &&
1058 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1059 D->getSuperClassLoc(),
1060 TU)))
1061 return true;
1062
1063 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1064 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1065 E = D->protocol_end(); I != E; ++I, ++PL)
1066 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1067 return true;
1068
1069 return VisitObjCContainerDecl(D);
1070}
1071
1072bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1073 return VisitObjCContainerDecl(D);
1074}
1075
1076bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1077 // 'ID' could be null when dealing with invalid code.
1078 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1079 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1080 return true;
1081
1082 return VisitObjCImplDecl(D);
1083}
1084
1085bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1086#if 0
1087 // Issue callbacks for super class.
1088 // FIXME: No source location information!
1089 if (D->getSuperClass() &&
1090 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1091 D->getSuperClassLoc(),
1092 TU)))
1093 return true;
1094#endif
1095
1096 return VisitObjCImplDecl(D);
1097}
1098
1099bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1100 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1101 if (PD->isIvarNameSpecified())
1102 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1103
1104 return false;
1105}
1106
1107bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1108 return VisitDeclContext(D);
1109}
1110
1111bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1112 // Visit nested-name-specifier.
1113 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1114 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1115 return true;
1116
1117 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1118 D->getTargetNameLoc(), TU));
1119}
1120
1121bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1122 // Visit nested-name-specifier.
1123 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1124 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1125 return true;
1126 }
1127
1128 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1129 return true;
1130
1131 return VisitDeclarationNameInfo(D->getNameInfo());
1132}
1133
1134bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1135 // Visit nested-name-specifier.
1136 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1137 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1138 return true;
1139
1140 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1141 D->getIdentLocation(), TU));
1142}
1143
1144bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1145 // Visit nested-name-specifier.
1146 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1147 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1148 return true;
1149 }
1150
1151 return VisitDeclarationNameInfo(D->getNameInfo());
1152}
1153
1154bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1155 UnresolvedUsingTypenameDecl *D) {
1156 // Visit nested-name-specifier.
1157 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1158 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1159 return true;
1160
1161 return false;
1162}
1163
1164bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1165 switch (Name.getName().getNameKind()) {
1166 case clang::DeclarationName::Identifier:
1167 case clang::DeclarationName::CXXLiteralOperatorName:
1168 case clang::DeclarationName::CXXOperatorName:
1169 case clang::DeclarationName::CXXUsingDirective:
1170 return false;
1171
1172 case clang::DeclarationName::CXXConstructorName:
1173 case clang::DeclarationName::CXXDestructorName:
1174 case clang::DeclarationName::CXXConversionFunctionName:
1175 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1176 return Visit(TSInfo->getTypeLoc());
1177 return false;
1178
1179 case clang::DeclarationName::ObjCZeroArgSelector:
1180 case clang::DeclarationName::ObjCOneArgSelector:
1181 case clang::DeclarationName::ObjCMultiArgSelector:
1182 // FIXME: Per-identifier location info?
1183 return false;
1184 }
1185
1186 llvm_unreachable("Invalid DeclarationName::Kind!");
1187}
1188
1189bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1190 SourceRange Range) {
1191 // FIXME: This whole routine is a hack to work around the lack of proper
1192 // source information in nested-name-specifiers (PR5791). Since we do have
1193 // a beginning source location, we can visit the first component of the
1194 // nested-name-specifier, if it's a single-token component.
1195 if (!NNS)
1196 return false;
1197
1198 // Get the first component in the nested-name-specifier.
1199 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1200 NNS = Prefix;
1201
1202 switch (NNS->getKind()) {
1203 case NestedNameSpecifier::Namespace:
1204 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1205 TU));
1206
1207 case NestedNameSpecifier::NamespaceAlias:
1208 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1209 Range.getBegin(), TU));
1210
1211 case NestedNameSpecifier::TypeSpec: {
1212 // If the type has a form where we know that the beginning of the source
1213 // range matches up with a reference cursor. Visit the appropriate reference
1214 // cursor.
1215 const Type *T = NNS->getAsType();
1216 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1217 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1218 if (const TagType *Tag = dyn_cast<TagType>(T))
1219 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1220 if (const TemplateSpecializationType *TST
1221 = dyn_cast<TemplateSpecializationType>(T))
1222 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1223 break;
1224 }
1225
1226 case NestedNameSpecifier::TypeSpecWithTemplate:
1227 case NestedNameSpecifier::Global:
1228 case NestedNameSpecifier::Identifier:
1229 break;
1230 }
1231
1232 return false;
1233}
1234
1235bool
1236CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1237 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1238 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1239 Qualifiers.push_back(Qualifier);
1240
1241 while (!Qualifiers.empty()) {
1242 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1243 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1244 switch (NNS->getKind()) {
1245 case NestedNameSpecifier::Namespace:
1246 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1247 Q.getLocalBeginLoc(),
1248 TU)))
1249 return true;
1250
1251 break;
1252
1253 case NestedNameSpecifier::NamespaceAlias:
1254 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1255 Q.getLocalBeginLoc(),
1256 TU)))
1257 return true;
1258
1259 break;
1260
1261 case NestedNameSpecifier::TypeSpec:
1262 case NestedNameSpecifier::TypeSpecWithTemplate:
1263 if (Visit(Q.getTypeLoc()))
1264 return true;
1265
1266 break;
1267
1268 case NestedNameSpecifier::Global:
1269 case NestedNameSpecifier::Identifier:
1270 break;
1271 }
1272 }
1273
1274 return false;
1275}
1276
1277bool CursorVisitor::VisitTemplateParameters(
1278 const TemplateParameterList *Params) {
1279 if (!Params)
1280 return false;
1281
1282 for (TemplateParameterList::const_iterator P = Params->begin(),
1283 PEnd = Params->end();
1284 P != PEnd; ++P) {
1285 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1286 return true;
1287 }
1288
1289 return false;
1290}
1291
1292bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1293 switch (Name.getKind()) {
1294 case TemplateName::Template:
1295 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1296
1297 case TemplateName::OverloadedTemplate:
1298 // Visit the overloaded template set.
1299 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1300 return true;
1301
1302 return false;
1303
1304 case TemplateName::DependentTemplate:
1305 // FIXME: Visit nested-name-specifier.
1306 return false;
1307
1308 case TemplateName::QualifiedTemplate:
1309 // FIXME: Visit nested-name-specifier.
1310 return Visit(MakeCursorTemplateRef(
1311 Name.getAsQualifiedTemplateName()->getDecl(),
1312 Loc, TU));
1313
1314 case TemplateName::SubstTemplateTemplateParm:
1315 return Visit(MakeCursorTemplateRef(
1316 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1317 Loc, TU));
1318
1319 case TemplateName::SubstTemplateTemplateParmPack:
1320 return Visit(MakeCursorTemplateRef(
1321 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1322 Loc, TU));
1323 }
1324
1325 llvm_unreachable("Invalid TemplateName::Kind!");
1326}
1327
1328bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1329 switch (TAL.getArgument().getKind()) {
1330 case TemplateArgument::Null:
1331 case TemplateArgument::Integral:
1332 case TemplateArgument::Pack:
1333 return false;
1334
1335 case TemplateArgument::Type:
1336 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1337 return Visit(TSInfo->getTypeLoc());
1338 return false;
1339
1340 case TemplateArgument::Declaration:
1341 if (Expr *E = TAL.getSourceDeclExpression())
1342 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1343 return false;
1344
1345 case TemplateArgument::NullPtr:
1346 if (Expr *E = TAL.getSourceNullPtrExpression())
1347 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1348 return false;
1349
1350 case TemplateArgument::Expression:
1351 if (Expr *E = TAL.getSourceExpression())
1352 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1353 return false;
1354
1355 case TemplateArgument::Template:
1356 case TemplateArgument::TemplateExpansion:
1357 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1358 return true;
1359
1360 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1361 TAL.getTemplateNameLoc());
1362 }
1363
1364 llvm_unreachable("Invalid TemplateArgument::Kind!");
1365}
1366
1367bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1368 return VisitDeclContext(D);
1369}
1370
1371bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1372 return Visit(TL.getUnqualifiedLoc());
1373}
1374
1375bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1376 ASTContext &Context = AU->getASTContext();
1377
1378 // Some builtin types (such as Objective-C's "id", "sel", and
1379 // "Class") have associated declarations. Create cursors for those.
1380 QualType VisitType;
1381 switch (TL.getTypePtr()->getKind()) {
1382
1383 case BuiltinType::Void:
1384 case BuiltinType::NullPtr:
1385 case BuiltinType::Dependent:
Guy Benyeib13621d2012-12-18 14:38:23 +00001386 case BuiltinType::OCLImage1d:
1387 case BuiltinType::OCLImage1dArray:
1388 case BuiltinType::OCLImage1dBuffer:
1389 case BuiltinType::OCLImage2d:
1390 case BuiltinType::OCLImage2dArray:
1391 case BuiltinType::OCLImage3d:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001392#define BUILTIN_TYPE(Id, SingletonId)
1393#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1394#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1395#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1396#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1397#include "clang/AST/BuiltinTypes.def"
1398 break;
1399
1400 case BuiltinType::ObjCId:
1401 VisitType = Context.getObjCIdType();
1402 break;
1403
1404 case BuiltinType::ObjCClass:
1405 VisitType = Context.getObjCClassType();
1406 break;
1407
1408 case BuiltinType::ObjCSel:
1409 VisitType = Context.getObjCSelType();
1410 break;
1411 }
1412
1413 if (!VisitType.isNull()) {
1414 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1415 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1416 TU));
1417 }
1418
1419 return false;
1420}
1421
1422bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1423 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1424}
1425
1426bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1427 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1428}
1429
1430bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1431 if (TL.isDefinition())
1432 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1433
1434 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1435}
1436
1437bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1438 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1439}
1440
1441bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1442 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1443 return true;
1444
1445 return false;
1446}
1447
1448bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1449 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1450 return true;
1451
1452 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1453 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1454 TU)))
1455 return true;
1456 }
1457
1458 return false;
1459}
1460
1461bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1462 return Visit(TL.getPointeeLoc());
1463}
1464
1465bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1466 return Visit(TL.getInnerLoc());
1467}
1468
1469bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1470 return Visit(TL.getPointeeLoc());
1471}
1472
1473bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1474 return Visit(TL.getPointeeLoc());
1475}
1476
1477bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1478 return Visit(TL.getPointeeLoc());
1479}
1480
1481bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1482 return Visit(TL.getPointeeLoc());
1483}
1484
1485bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1486 return Visit(TL.getPointeeLoc());
1487}
1488
1489bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1490 return Visit(TL.getModifiedLoc());
1491}
1492
1493bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1494 bool SkipResultType) {
1495 if (!SkipResultType && Visit(TL.getResultLoc()))
1496 return true;
1497
1498 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1499 if (Decl *D = TL.getArg(I))
1500 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1501 return true;
1502
1503 return false;
1504}
1505
1506bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1507 if (Visit(TL.getElementLoc()))
1508 return true;
1509
1510 if (Expr *Size = TL.getSizeExpr())
1511 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1512
1513 return false;
1514}
1515
1516bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1517 TemplateSpecializationTypeLoc TL) {
1518 // Visit the template name.
1519 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1520 TL.getTemplateNameLoc()))
1521 return true;
1522
1523 // Visit the template arguments.
1524 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1525 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1526 return true;
1527
1528 return false;
1529}
1530
1531bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1532 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1533}
1534
1535bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1536 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1537 return Visit(TSInfo->getTypeLoc());
1538
1539 return false;
1540}
1541
1542bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1543 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1544 return Visit(TSInfo->getTypeLoc());
1545
1546 return false;
1547}
1548
1549bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1550 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1551 return true;
1552
1553 return false;
1554}
1555
1556bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1557 DependentTemplateSpecializationTypeLoc TL) {
1558 // Visit the nested-name-specifier, if there is one.
1559 if (TL.getQualifierLoc() &&
1560 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1561 return true;
1562
1563 // Visit the template arguments.
1564 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1565 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1566 return true;
1567
1568 return false;
1569}
1570
1571bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1572 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1573 return true;
1574
1575 return Visit(TL.getNamedTypeLoc());
1576}
1577
1578bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1579 return Visit(TL.getPatternLoc());
1580}
1581
1582bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1583 if (Expr *E = TL.getUnderlyingExpr())
1584 return Visit(MakeCXCursor(E, StmtParent, TU));
1585
1586 return false;
1587}
1588
1589bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1590 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1591}
1592
1593bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1594 return Visit(TL.getValueLoc());
1595}
1596
1597#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1598bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1599 return Visit##PARENT##Loc(TL); \
1600}
1601
1602DEFAULT_TYPELOC_IMPL(Complex, Type)
1603DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1604DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1605DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1606DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1607DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1608DEFAULT_TYPELOC_IMPL(Vector, Type)
1609DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1610DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1611DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1612DEFAULT_TYPELOC_IMPL(Record, TagType)
1613DEFAULT_TYPELOC_IMPL(Enum, TagType)
1614DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1615DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1616DEFAULT_TYPELOC_IMPL(Auto, Type)
1617
1618bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1619 // Visit the nested-name-specifier, if present.
1620 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1621 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1622 return true;
1623
1624 if (D->isCompleteDefinition()) {
1625 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1626 E = D->bases_end(); I != E; ++I) {
1627 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1628 return true;
1629 }
1630 }
1631
1632 return VisitTagDecl(D);
1633}
1634
1635bool CursorVisitor::VisitAttributes(Decl *D) {
1636 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1637 i != e; ++i)
1638 if (Visit(MakeCXCursor(*i, D, TU)))
1639 return true;
1640
1641 return false;
1642}
1643
1644//===----------------------------------------------------------------------===//
1645// Data-recursive visitor methods.
1646//===----------------------------------------------------------------------===//
1647
1648namespace {
1649#define DEF_JOB(NAME, DATA, KIND)\
1650class NAME : public VisitorJob {\
1651public:\
1652 NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1653 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1654 DATA *get() const { return static_cast<DATA*>(data[0]); }\
1655};
1656
1657DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1658DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1659DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1660DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1661DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
1662 ExplicitTemplateArgsVisitKind)
1663DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1664DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1665DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1666#undef DEF_JOB
1667
1668class DeclVisit : public VisitorJob {
1669public:
1670 DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1671 VisitorJob(parent, VisitorJob::DeclVisitKind,
1672 d, isFirst ? (void*) 1 : (void*) 0) {}
1673 static bool classof(const VisitorJob *VJ) {
1674 return VJ->getKind() == DeclVisitKind;
1675 }
1676 Decl *get() const { return static_cast<Decl*>(data[0]); }
1677 bool isFirst() const { return data[1] ? true : false; }
1678};
1679class TypeLocVisit : public VisitorJob {
1680public:
1681 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1682 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1683 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1684
1685 static bool classof(const VisitorJob *VJ) {
1686 return VJ->getKind() == TypeLocVisitKind;
1687 }
1688
1689 TypeLoc get() const {
1690 QualType T = QualType::getFromOpaquePtr(data[0]);
1691 return TypeLoc(T, data[1]);
1692 }
1693};
1694
1695class LabelRefVisit : public VisitorJob {
1696public:
1697 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1698 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1699 labelLoc.getPtrEncoding()) {}
1700
1701 static bool classof(const VisitorJob *VJ) {
1702 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1703 }
1704 LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
1705 SourceLocation getLoc() const {
1706 return SourceLocation::getFromPtrEncoding(data[1]); }
1707};
1708
1709class NestedNameSpecifierLocVisit : public VisitorJob {
1710public:
1711 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1712 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1713 Qualifier.getNestedNameSpecifier(),
1714 Qualifier.getOpaqueData()) { }
1715
1716 static bool classof(const VisitorJob *VJ) {
1717 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1718 }
1719
1720 NestedNameSpecifierLoc get() const {
1721 return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1722 data[1]);
1723 }
1724};
1725
1726class DeclarationNameInfoVisit : public VisitorJob {
1727public:
1728 DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1729 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1730 static bool classof(const VisitorJob *VJ) {
1731 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1732 }
1733 DeclarationNameInfo get() const {
1734 Stmt *S = static_cast<Stmt*>(data[0]);
1735 switch (S->getStmtClass()) {
1736 default:
1737 llvm_unreachable("Unhandled Stmt");
1738 case clang::Stmt::MSDependentExistsStmtClass:
1739 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1740 case Stmt::CXXDependentScopeMemberExprClass:
1741 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1742 case Stmt::DependentScopeDeclRefExprClass:
1743 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1744 }
1745 }
1746};
1747class MemberRefVisit : public VisitorJob {
1748public:
1749 MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1750 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1751 L.getPtrEncoding()) {}
1752 static bool classof(const VisitorJob *VJ) {
1753 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1754 }
1755 FieldDecl *get() const {
1756 return static_cast<FieldDecl*>(data[0]);
1757 }
1758 SourceLocation getLoc() const {
1759 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1760 }
1761};
1762class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1763 VisitorWorkList &WL;
1764 CXCursor Parent;
1765public:
1766 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1767 : WL(wl), Parent(parent) {}
1768
1769 void VisitAddrLabelExpr(AddrLabelExpr *E);
1770 void VisitBlockExpr(BlockExpr *B);
1771 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
1772 void VisitCompoundStmt(CompoundStmt *S);
1773 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1774 void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
1775 void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
1776 void VisitCXXNewExpr(CXXNewExpr *E);
1777 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
1778 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
1779 void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
1780 void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
1781 void VisitCXXTypeidExpr(CXXTypeidExpr *E);
1782 void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
1783 void VisitCXXUuidofExpr(CXXUuidofExpr *E);
1784 void VisitCXXCatchStmt(CXXCatchStmt *S);
1785 void VisitDeclRefExpr(DeclRefExpr *D);
1786 void VisitDeclStmt(DeclStmt *S);
1787 void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
1788 void VisitDesignatedInitExpr(DesignatedInitExpr *E);
1789 void VisitExplicitCastExpr(ExplicitCastExpr *E);
1790 void VisitForStmt(ForStmt *FS);
1791 void VisitGotoStmt(GotoStmt *GS);
1792 void VisitIfStmt(IfStmt *If);
1793 void VisitInitListExpr(InitListExpr *IE);
1794 void VisitMemberExpr(MemberExpr *M);
1795 void VisitOffsetOfExpr(OffsetOfExpr *E);
1796 void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
1797 void VisitObjCMessageExpr(ObjCMessageExpr *M);
1798 void VisitOverloadExpr(OverloadExpr *E);
1799 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
1800 void VisitStmt(Stmt *S);
1801 void VisitSwitchStmt(SwitchStmt *S);
1802 void VisitWhileStmt(WhileStmt *W);
1803 void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
1804 void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
1805 void VisitTypeTraitExpr(TypeTraitExpr *E);
1806 void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
1807 void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
1808 void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1809 void VisitVAArgExpr(VAArgExpr *E);
1810 void VisitSizeOfPackExpr(SizeOfPackExpr *E);
1811 void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1812 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
1813 void VisitLambdaExpr(LambdaExpr *E);
1814
1815private:
1816 void AddDeclarationNameInfo(Stmt *S);
1817 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
1818 void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
1819 void AddMemberRef(FieldDecl *D, SourceLocation L);
1820 void AddStmt(Stmt *S);
1821 void AddDecl(Decl *D, bool isFirst = true);
1822 void AddTypeLoc(TypeSourceInfo *TI);
1823 void EnqueueChildren(Stmt *S);
1824};
1825} // end anonyous namespace
1826
1827void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1828 // 'S' should always be non-null, since it comes from the
1829 // statement we are visiting.
1830 WL.push_back(DeclarationNameInfoVisit(S, Parent));
1831}
1832
1833void
1834EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1835 if (Qualifier)
1836 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1837}
1838
1839void EnqueueVisitor::AddStmt(Stmt *S) {
1840 if (S)
1841 WL.push_back(StmtVisit(S, Parent));
1842}
1843void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
1844 if (D)
1845 WL.push_back(DeclVisit(D, Parent, isFirst));
1846}
1847void EnqueueVisitor::
1848 AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
1849 if (A)
1850 WL.push_back(ExplicitTemplateArgsVisit(
1851 const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
1852}
1853void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1854 if (D)
1855 WL.push_back(MemberRefVisit(D, L, Parent));
1856}
1857void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1858 if (TI)
1859 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1860 }
1861void EnqueueVisitor::EnqueueChildren(Stmt *S) {
1862 unsigned size = WL.size();
1863 for (Stmt::child_range Child = S->children(); Child; ++Child) {
1864 AddStmt(*Child);
1865 }
1866 if (size == WL.size())
1867 return;
1868 // Now reverse the entries we just added. This will match the DFS
1869 // ordering performed by the worklist.
1870 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1871 std::reverse(I, E);
1872}
1873void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1874 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1875}
1876void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1877 AddDecl(B->getBlockDecl());
1878}
1879void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1880 EnqueueChildren(E);
1881 AddTypeLoc(E->getTypeSourceInfo());
1882}
1883void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1884 for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1885 E = S->body_rend(); I != E; ++I) {
1886 AddStmt(*I);
1887 }
1888}
1889void EnqueueVisitor::
1890VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1891 AddStmt(S->getSubStmt());
1892 AddDeclarationNameInfo(S);
1893 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1894 AddNestedNameSpecifierLoc(QualifierLoc);
1895}
1896
1897void EnqueueVisitor::
1898VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1899 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1900 AddDeclarationNameInfo(E);
1901 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1902 AddNestedNameSpecifierLoc(QualifierLoc);
1903 if (!E->isImplicitAccess())
1904 AddStmt(E->getBase());
1905}
1906void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1907 // Enqueue the initializer , if any.
1908 AddStmt(E->getInitializer());
1909 // Enqueue the array size, if any.
1910 AddStmt(E->getArraySize());
1911 // Enqueue the allocated type.
1912 AddTypeLoc(E->getAllocatedTypeSourceInfo());
1913 // Enqueue the placement arguments.
1914 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1915 AddStmt(E->getPlacementArg(I-1));
1916}
1917void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
1918 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1919 AddStmt(CE->getArg(I-1));
1920 AddStmt(CE->getCallee());
1921 AddStmt(CE->getArg(0));
1922}
1923void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1924 // Visit the name of the type being destroyed.
1925 AddTypeLoc(E->getDestroyedTypeInfo());
1926 // Visit the scope type that looks disturbingly like the nested-name-specifier
1927 // but isn't.
1928 AddTypeLoc(E->getScopeTypeInfo());
1929 // Visit the nested-name-specifier.
1930 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1931 AddNestedNameSpecifierLoc(QualifierLoc);
1932 // Visit base expression.
1933 AddStmt(E->getBase());
1934}
1935void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1936 AddTypeLoc(E->getTypeSourceInfo());
1937}
1938void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1939 EnqueueChildren(E);
1940 AddTypeLoc(E->getTypeSourceInfo());
1941}
1942void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1943 EnqueueChildren(E);
1944 if (E->isTypeOperand())
1945 AddTypeLoc(E->getTypeOperandSourceInfo());
1946}
1947
1948void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1949 *E) {
1950 EnqueueChildren(E);
1951 AddTypeLoc(E->getTypeSourceInfo());
1952}
1953void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1954 EnqueueChildren(E);
1955 if (E->isTypeOperand())
1956 AddTypeLoc(E->getTypeOperandSourceInfo());
1957}
1958
1959void EnqueueVisitor::VisitCXXCatchStmt(CXXCatchStmt *S) {
1960 EnqueueChildren(S);
1961 AddDecl(S->getExceptionDecl());
1962}
1963
1964void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
1965 if (DR->hasExplicitTemplateArgs()) {
1966 AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1967 }
1968 WL.push_back(DeclRefExprParts(DR, Parent));
1969}
1970void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1971 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1972 AddDeclarationNameInfo(E);
1973 AddNestedNameSpecifierLoc(E->getQualifierLoc());
1974}
1975void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1976 unsigned size = WL.size();
1977 bool isFirst = true;
1978 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1979 D != DEnd; ++D) {
1980 AddDecl(*D, isFirst);
1981 isFirst = false;
1982 }
1983 if (size == WL.size())
1984 return;
1985 // Now reverse the entries we just added. This will match the DFS
1986 // ordering performed by the worklist.
1987 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1988 std::reverse(I, E);
1989}
1990void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1991 AddStmt(E->getInit());
1992 typedef DesignatedInitExpr::Designator Designator;
1993 for (DesignatedInitExpr::reverse_designators_iterator
1994 D = E->designators_rbegin(), DEnd = E->designators_rend();
1995 D != DEnd; ++D) {
1996 if (D->isFieldDesignator()) {
1997 if (FieldDecl *Field = D->getField())
1998 AddMemberRef(Field, D->getFieldLoc());
1999 continue;
2000 }
2001 if (D->isArrayDesignator()) {
2002 AddStmt(E->getArrayIndex(*D));
2003 continue;
2004 }
2005 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
2006 AddStmt(E->getArrayRangeEnd(*D));
2007 AddStmt(E->getArrayRangeStart(*D));
2008 }
2009}
2010void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
2011 EnqueueChildren(E);
2012 AddTypeLoc(E->getTypeInfoAsWritten());
2013}
2014void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
2015 AddStmt(FS->getBody());
2016 AddStmt(FS->getInc());
2017 AddStmt(FS->getCond());
2018 AddDecl(FS->getConditionVariable());
2019 AddStmt(FS->getInit());
2020}
2021void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
2022 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2023}
2024void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
2025 AddStmt(If->getElse());
2026 AddStmt(If->getThen());
2027 AddStmt(If->getCond());
2028 AddDecl(If->getConditionVariable());
2029}
2030void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
2031 // We care about the syntactic form of the initializer list, only.
2032 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2033 IE = Syntactic;
2034 EnqueueChildren(IE);
2035}
2036void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
2037 WL.push_back(MemberExprParts(M, Parent));
2038
2039 // If the base of the member access expression is an implicit 'this', don't
2040 // visit it.
2041 // FIXME: If we ever want to show these implicit accesses, this will be
2042 // unfortunate. However, clang_getCursor() relies on this behavior.
2043 if (!M->isImplicitAccess())
2044 AddStmt(M->getBase());
2045}
2046void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2047 AddTypeLoc(E->getEncodedTypeSourceInfo());
2048}
2049void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2050 EnqueueChildren(M);
2051 AddTypeLoc(M->getClassReceiverTypeInfo());
2052}
2053void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2054 // Visit the components of the offsetof expression.
2055 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2056 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2057 const OffsetOfNode &Node = E->getComponent(I-1);
2058 switch (Node.getKind()) {
2059 case OffsetOfNode::Array:
2060 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2061 break;
2062 case OffsetOfNode::Field:
2063 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2064 break;
2065 case OffsetOfNode::Identifier:
2066 case OffsetOfNode::Base:
2067 continue;
2068 }
2069 }
2070 // Visit the type into which we're computing the offset.
2071 AddTypeLoc(E->getTypeSourceInfo());
2072}
2073void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
2074 AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
2075 WL.push_back(OverloadExprParts(E, Parent));
2076}
2077void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2078 UnaryExprOrTypeTraitExpr *E) {
2079 EnqueueChildren(E);
2080 if (E->isArgumentType())
2081 AddTypeLoc(E->getArgumentTypeInfo());
2082}
2083void EnqueueVisitor::VisitStmt(Stmt *S) {
2084 EnqueueChildren(S);
2085}
2086void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2087 AddStmt(S->getBody());
2088 AddStmt(S->getCond());
2089 AddDecl(S->getConditionVariable());
2090}
2091
2092void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2093 AddStmt(W->getBody());
2094 AddStmt(W->getCond());
2095 AddDecl(W->getConditionVariable());
2096}
2097
2098void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2099 AddTypeLoc(E->getQueriedTypeSourceInfo());
2100}
2101
2102void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
2103 AddTypeLoc(E->getRhsTypeSourceInfo());
2104 AddTypeLoc(E->getLhsTypeSourceInfo());
2105}
2106
2107void EnqueueVisitor::VisitTypeTraitExpr(TypeTraitExpr *E) {
2108 for (unsigned I = E->getNumArgs(); I > 0; --I)
2109 AddTypeLoc(E->getArg(I-1));
2110}
2111
2112void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2113 AddTypeLoc(E->getQueriedTypeSourceInfo());
2114}
2115
2116void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2117 EnqueueChildren(E);
2118}
2119
2120void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2121 VisitOverloadExpr(U);
2122 if (!U->isImplicitAccess())
2123 AddStmt(U->getBase());
2124}
2125void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2126 AddStmt(E->getSubExpr());
2127 AddTypeLoc(E->getWrittenTypeInfo());
2128}
2129void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2130 WL.push_back(SizeOfPackExprParts(E, Parent));
2131}
2132void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2133 // If the opaque value has a source expression, just transparently
2134 // visit that. This is useful for (e.g.) pseudo-object expressions.
2135 if (Expr *SourceExpr = E->getSourceExpr())
2136 return Visit(SourceExpr);
2137}
2138void EnqueueVisitor::VisitLambdaExpr(LambdaExpr *E) {
2139 AddStmt(E->getBody());
2140 WL.push_back(LambdaExprParts(E, Parent));
2141}
2142void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2143 // Treat the expression like its syntactic form.
2144 Visit(E->getSyntacticForm());
2145}
2146
2147void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
2148 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2149}
2150
2151bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2152 if (RegionOfInterest.isValid()) {
2153 SourceRange Range = getRawCursorExtent(C);
2154 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2155 return false;
2156 }
2157 return true;
2158}
2159
2160bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2161 while (!WL.empty()) {
2162 // Dequeue the worklist item.
2163 VisitorJob LI = WL.back();
2164 WL.pop_back();
2165
2166 // Set the Parent field, then back to its old value once we're done.
2167 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2168
2169 switch (LI.getKind()) {
2170 case VisitorJob::DeclVisitKind: {
2171 Decl *D = cast<DeclVisit>(&LI)->get();
2172 if (!D)
2173 continue;
2174
2175 // For now, perform default visitation for Decls.
2176 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2177 cast<DeclVisit>(&LI)->isFirst())))
2178 return true;
2179
2180 continue;
2181 }
2182 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2183 const ASTTemplateArgumentListInfo *ArgList =
2184 cast<ExplicitTemplateArgsVisit>(&LI)->get();
2185 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2186 *ArgEnd = Arg + ArgList->NumTemplateArgs;
2187 Arg != ArgEnd; ++Arg) {
2188 if (VisitTemplateArgumentLoc(*Arg))
2189 return true;
2190 }
2191 continue;
2192 }
2193 case VisitorJob::TypeLocVisitKind: {
2194 // Perform default visitation for TypeLocs.
2195 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2196 return true;
2197 continue;
2198 }
2199 case VisitorJob::LabelRefVisitKind: {
2200 LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
2201 if (LabelStmt *stmt = LS->getStmt()) {
2202 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2203 TU))) {
2204 return true;
2205 }
2206 }
2207 continue;
2208 }
2209
2210 case VisitorJob::NestedNameSpecifierLocVisitKind: {
2211 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2212 if (VisitNestedNameSpecifierLoc(V->get()))
2213 return true;
2214 continue;
2215 }
2216
2217 case VisitorJob::DeclarationNameInfoVisitKind: {
2218 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2219 ->get()))
2220 return true;
2221 continue;
2222 }
2223 case VisitorJob::MemberRefVisitKind: {
2224 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2225 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2226 return true;
2227 continue;
2228 }
2229 case VisitorJob::StmtVisitKind: {
2230 Stmt *S = cast<StmtVisit>(&LI)->get();
2231 if (!S)
2232 continue;
2233
2234 // Update the current cursor.
2235 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2236 if (!IsInRegionOfInterest(Cursor))
2237 continue;
2238 switch (Visitor(Cursor, Parent, ClientData)) {
2239 case CXChildVisit_Break: return true;
2240 case CXChildVisit_Continue: break;
2241 case CXChildVisit_Recurse:
2242 if (PostChildrenVisitor)
2243 WL.push_back(PostChildrenVisit(0, Cursor));
2244 EnqueueWorkList(WL, S);
2245 break;
2246 }
2247 continue;
2248 }
2249 case VisitorJob::MemberExprPartsKind: {
2250 // Handle the other pieces in the MemberExpr besides the base.
2251 MemberExpr *M = cast<MemberExprParts>(&LI)->get();
2252
2253 // Visit the nested-name-specifier
2254 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2255 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2256 return true;
2257
2258 // Visit the declaration name.
2259 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2260 return true;
2261
2262 // Visit the explicitly-specified template arguments, if any.
2263 if (M->hasExplicitTemplateArgs()) {
2264 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2265 *ArgEnd = Arg + M->getNumTemplateArgs();
2266 Arg != ArgEnd; ++Arg) {
2267 if (VisitTemplateArgumentLoc(*Arg))
2268 return true;
2269 }
2270 }
2271 continue;
2272 }
2273 case VisitorJob::DeclRefExprPartsKind: {
2274 DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
2275 // Visit nested-name-specifier, if present.
2276 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2277 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2278 return true;
2279 // Visit declaration name.
2280 if (VisitDeclarationNameInfo(DR->getNameInfo()))
2281 return true;
2282 continue;
2283 }
2284 case VisitorJob::OverloadExprPartsKind: {
2285 OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
2286 // Visit the nested-name-specifier.
2287 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2288 if (VisitNestedNameSpecifierLoc(QualifierLoc))
2289 return true;
2290 // Visit the declaration name.
2291 if (VisitDeclarationNameInfo(O->getNameInfo()))
2292 return true;
2293 // Visit the overloaded declaration reference.
2294 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2295 return true;
2296 continue;
2297 }
2298 case VisitorJob::SizeOfPackExprPartsKind: {
2299 SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2300 NamedDecl *Pack = E->getPack();
2301 if (isa<TemplateTypeParmDecl>(Pack)) {
2302 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2303 E->getPackLoc(), TU)))
2304 return true;
2305
2306 continue;
2307 }
2308
2309 if (isa<TemplateTemplateParmDecl>(Pack)) {
2310 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2311 E->getPackLoc(), TU)))
2312 return true;
2313
2314 continue;
2315 }
2316
2317 // Non-type template parameter packs and function parameter packs are
2318 // treated like DeclRefExpr cursors.
2319 continue;
2320 }
2321
2322 case VisitorJob::LambdaExprPartsKind: {
2323 // Visit captures.
2324 LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
2325 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2326 CEnd = E->explicit_capture_end();
2327 C != CEnd; ++C) {
2328 if (C->capturesThis())
2329 continue;
2330
2331 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2332 C->getLocation(),
2333 TU)))
2334 return true;
2335 }
2336
2337 // Visit parameters and return type, if present.
2338 if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2339 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2340 if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2341 // Visit the whole type.
2342 if (Visit(TL))
2343 return true;
2344 } else if (isa<FunctionProtoTypeLoc>(TL)) {
2345 FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
2346 if (E->hasExplicitParameters()) {
2347 // Visit parameters.
2348 for (unsigned I = 0, N = Proto.getNumArgs(); I != N; ++I)
2349 if (Visit(MakeCXCursor(Proto.getArg(I), TU)))
2350 return true;
2351 } else {
2352 // Visit result type.
2353 if (Visit(Proto.getResultLoc()))
2354 return true;
2355 }
2356 }
2357 }
2358 break;
2359 }
2360
2361 case VisitorJob::PostChildrenVisitKind:
2362 if (PostChildrenVisitor(Parent, ClientData))
2363 return true;
2364 break;
2365 }
2366 }
2367 return false;
2368}
2369
2370bool CursorVisitor::Visit(Stmt *S) {
2371 VisitorWorkList *WL = 0;
2372 if (!WorkListFreeList.empty()) {
2373 WL = WorkListFreeList.back();
2374 WL->clear();
2375 WorkListFreeList.pop_back();
2376 }
2377 else {
2378 WL = new VisitorWorkList();
2379 WorkListCache.push_back(WL);
2380 }
2381 EnqueueWorkList(*WL, S);
2382 bool result = RunVisitorWorkList(*WL);
2383 WorkListFreeList.push_back(WL);
2384 return result;
2385}
2386
2387namespace {
2388typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2389RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2390 const DeclarationNameInfo &NI,
2391 const SourceRange &QLoc,
2392 const ASTTemplateArgumentListInfo *TemplateArgs = 0){
2393 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2394 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2395 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2396
2397 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2398
2399 RefNamePieces Pieces;
2400
2401 if (WantQualifier && QLoc.isValid())
2402 Pieces.push_back(QLoc);
2403
2404 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2405 Pieces.push_back(NI.getLoc());
2406
2407 if (WantTemplateArgs && TemplateArgs)
2408 Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2409 TemplateArgs->RAngleLoc));
2410
2411 if (Kind == DeclarationName::CXXOperatorName) {
2412 Pieces.push_back(SourceLocation::getFromRawEncoding(
2413 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2414 Pieces.push_back(SourceLocation::getFromRawEncoding(
2415 NI.getInfo().CXXOperatorName.EndOpNameLoc));
2416 }
2417
2418 if (WantSinglePiece) {
2419 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2420 Pieces.clear();
2421 Pieces.push_back(R);
2422 }
2423
2424 return Pieces;
2425}
2426}
2427
2428//===----------------------------------------------------------------------===//
2429// Misc. API hooks.
2430//===----------------------------------------------------------------------===//
2431
2432static llvm::sys::Mutex EnableMultithreadingMutex;
2433static bool EnabledMultithreading;
2434
2435static void fatal_error_handler(void *user_data, const std::string& reason) {
2436 // Write the result out to stderr avoiding errs() because raw_ostreams can
2437 // call report_fatal_error.
2438 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
2439 ::abort();
2440}
2441
2442extern "C" {
2443CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2444 int displayDiagnostics) {
2445 // Disable pretty stack trace functionality, which will otherwise be a very
2446 // poor citizen of the world and set up all sorts of signal handlers.
2447 llvm::DisablePrettyStackTrace = true;
2448
2449 // We use crash recovery to make some of our APIs more reliable, implicitly
2450 // enable it.
2451 llvm::CrashRecoveryContext::Enable();
2452
2453 // Enable support for multithreading in LLVM.
2454 {
2455 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2456 if (!EnabledMultithreading) {
2457 llvm::install_fatal_error_handler(fatal_error_handler, 0);
2458 llvm::llvm_start_multithreaded();
2459 EnabledMultithreading = true;
2460 }
2461 }
2462
2463 CIndexer *CIdxr = new CIndexer();
2464 if (excludeDeclarationsFromPCH)
2465 CIdxr->setOnlyLocalDecls();
2466 if (displayDiagnostics)
2467 CIdxr->setDisplayDiagnostics();
2468
2469 if (getenv("LIBCLANG_BGPRIO_INDEX"))
2470 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2471 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
2472 if (getenv("LIBCLANG_BGPRIO_EDIT"))
2473 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2474 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
2475
2476 return CIdxr;
2477}
2478
2479void clang_disposeIndex(CXIndex CIdx) {
2480 if (CIdx)
2481 delete static_cast<CIndexer *>(CIdx);
2482}
2483
2484void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
2485 if (CIdx)
2486 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
2487}
2488
2489unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
2490 if (CIdx)
2491 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
2492 return 0;
2493}
2494
2495void clang_toggleCrashRecovery(unsigned isEnabled) {
2496 if (isEnabled)
2497 llvm::CrashRecoveryContext::Enable();
2498 else
2499 llvm::CrashRecoveryContext::Disable();
2500}
2501
2502CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
2503 const char *ast_filename) {
2504 if (!CIdx)
2505 return 0;
2506
2507 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2508 FileSystemOptions FileSystemOpts;
2509
2510 IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
2511 ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
2512 CXXIdx->getOnlyLocalDecls(),
2513 0, 0,
2514 /*CaptureDiagnostics=*/true,
2515 /*AllowPCHWithCompilerErrors=*/true,
2516 /*UserFilesAreVolatile=*/true);
2517 return MakeCXTranslationUnit(CXXIdx, TU);
2518}
2519
2520unsigned clang_defaultEditingTranslationUnitOptions() {
2521 return CXTranslationUnit_PrecompiledPreamble |
2522 CXTranslationUnit_CacheCompletionResults;
2523}
2524
2525CXTranslationUnit
2526clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2527 const char *source_filename,
2528 int num_command_line_args,
2529 const char * const *command_line_args,
2530 unsigned num_unsaved_files,
2531 struct CXUnsavedFile *unsaved_files) {
2532 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
2533 return clang_parseTranslationUnit(CIdx, source_filename,
2534 command_line_args, num_command_line_args,
2535 unsaved_files, num_unsaved_files,
2536 Options);
2537}
2538
2539struct ParseTranslationUnitInfo {
2540 CXIndex CIdx;
2541 const char *source_filename;
2542 const char *const *command_line_args;
2543 int num_command_line_args;
2544 struct CXUnsavedFile *unsaved_files;
2545 unsigned num_unsaved_files;
2546 unsigned options;
2547 CXTranslationUnit result;
2548};
2549static void clang_parseTranslationUnit_Impl(void *UserData) {
2550 ParseTranslationUnitInfo *PTUI =
2551 static_cast<ParseTranslationUnitInfo*>(UserData);
2552 CXIndex CIdx = PTUI->CIdx;
2553 const char *source_filename = PTUI->source_filename;
2554 const char * const *command_line_args = PTUI->command_line_args;
2555 int num_command_line_args = PTUI->num_command_line_args;
2556 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2557 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2558 unsigned options = PTUI->options;
2559 PTUI->result = 0;
2560
2561 if (!CIdx)
2562 return;
2563
2564 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2565
2566 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
2567 setThreadBackgroundPriority();
2568
2569 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
2570 // FIXME: Add a flag for modules.
2571 TranslationUnitKind TUKind
2572 = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
2573 bool CacheCodeCompetionResults
2574 = options & CXTranslationUnit_CacheCompletionResults;
2575 bool IncludeBriefCommentsInCodeCompletion
2576 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
2577 bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
2578 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
2579
2580 // Configure the diagnostics.
2581 IntrusiveRefCntPtr<DiagnosticsEngine>
2582 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions,
2583 num_command_line_args,
2584 command_line_args));
2585
2586 // Recover resources if we crash before exiting this function.
2587 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2588 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
2589 DiagCleanup(Diags.getPtr());
2590
2591 OwningPtr<std::vector<ASTUnit::RemappedFile> >
2592 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2593
2594 // Recover resources if we crash before exiting this function.
2595 llvm::CrashRecoveryContextCleanupRegistrar<
2596 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2597
2598 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2599 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2600 const llvm::MemoryBuffer *Buffer
2601 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2602 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2603 Buffer));
2604 }
2605
2606 OwningPtr<std::vector<const char *> >
2607 Args(new std::vector<const char*>());
2608
2609 // Recover resources if we crash before exiting this method.
2610 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2611 ArgsCleanup(Args.get());
2612
2613 // Since the Clang C library is primarily used by batch tools dealing with
2614 // (often very broken) source code, where spell-checking can have a
2615 // significant negative impact on performance (particularly when
2616 // precompiled headers are involved), we disable it by default.
2617 // Only do this if we haven't found a spell-checking-related argument.
2618 bool FoundSpellCheckingArgument = false;
2619 for (int I = 0; I != num_command_line_args; ++I) {
2620 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2621 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2622 FoundSpellCheckingArgument = true;
2623 break;
2624 }
2625 }
2626 if (!FoundSpellCheckingArgument)
2627 Args->push_back("-fno-spell-checking");
2628
2629 Args->insert(Args->end(), command_line_args,
2630 command_line_args + num_command_line_args);
2631
2632 // The 'source_filename' argument is optional. If the caller does not
2633 // specify it then it is assumed that the source file is specified
2634 // in the actual argument list.
2635 // Put the source file after command_line_args otherwise if '-x' flag is
2636 // present it will be unused.
2637 if (source_filename)
2638 Args->push_back(source_filename);
2639
2640 // Do we need the detailed preprocessing record?
2641 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
2642 Args->push_back("-Xclang");
2643 Args->push_back("-detailed-preprocessing-record");
2644 }
2645
2646 unsigned NumErrors = Diags->getClient()->getNumErrors();
2647 OwningPtr<ASTUnit> ErrUnit;
2648 OwningPtr<ASTUnit> Unit(
2649 ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2650 /* vector::data() not portable */,
2651 Args->size() ? (&(*Args)[0] + Args->size()) :0,
2652 Diags,
2653 CXXIdx->getClangResourcesPath(),
2654 CXXIdx->getOnlyLocalDecls(),
2655 /*CaptureDiagnostics=*/true,
2656 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
2657 RemappedFiles->size(),
2658 /*RemappedFilesKeepOriginalName=*/true,
2659 PrecompilePreamble,
2660 TUKind,
2661 CacheCodeCompetionResults,
2662 IncludeBriefCommentsInCodeCompletion,
2663 /*AllowPCHWithCompilerErrors=*/true,
2664 SkipFunctionBodies,
2665 /*UserFilesAreVolatile=*/true,
2666 ForSerialization,
2667 &ErrUnit));
2668
2669 if (NumErrors != Diags->getClient()->getNumErrors()) {
2670 // Make sure to check that 'Unit' is non-NULL.
2671 if (CXXIdx->getDisplayDiagnostics())
2672 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
2673 }
2674
2675 PTUI->result = MakeCXTranslationUnit(CXXIdx, Unit.take());
2676}
2677CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2678 const char *source_filename,
2679 const char * const *command_line_args,
2680 int num_command_line_args,
2681 struct CXUnsavedFile *unsaved_files,
2682 unsigned num_unsaved_files,
2683 unsigned options) {
2684 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2685 num_command_line_args, unsaved_files,
2686 num_unsaved_files, options, 0 };
2687 llvm::CrashRecoveryContext CRC;
2688
2689 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
2690 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2691 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2692 fprintf(stderr, " 'command_line_args' : [");
2693 for (int i = 0; i != num_command_line_args; ++i) {
2694 if (i)
2695 fprintf(stderr, ", ");
2696 fprintf(stderr, "'%s'", command_line_args[i]);
2697 }
2698 fprintf(stderr, "],\n");
2699 fprintf(stderr, " 'unsaved_files' : [");
2700 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2701 if (i)
2702 fprintf(stderr, ", ");
2703 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2704 unsaved_files[i].Length);
2705 }
2706 fprintf(stderr, "],\n");
2707 fprintf(stderr, " 'options' : %d,\n", options);
2708 fprintf(stderr, "}\n");
2709
2710 return 0;
2711 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2712 PrintLibclangResourceUsage(PTUI.result);
2713 }
2714
2715 return PTUI.result;
2716}
2717
2718unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2719 return CXSaveTranslationUnit_None;
2720}
2721
2722namespace {
2723
2724struct SaveTranslationUnitInfo {
2725 CXTranslationUnit TU;
2726 const char *FileName;
2727 unsigned options;
2728 CXSaveError result;
2729};
2730
2731}
2732
2733static void clang_saveTranslationUnit_Impl(void *UserData) {
2734 SaveTranslationUnitInfo *STUI =
2735 static_cast<SaveTranslationUnitInfo*>(UserData);
2736
2737 CIndexer *CXXIdx = (CIndexer*)STUI->TU->CIdx;
2738 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
2739 setThreadBackgroundPriority();
2740
2741 bool hadError = static_cast<ASTUnit *>(STUI->TU->TUData)->Save(STUI->FileName);
2742 STUI->result = hadError ? CXSaveError_Unknown : CXSaveError_None;
2743}
2744
2745int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2746 unsigned options) {
2747 if (!TU)
2748 return CXSaveError_InvalidTU;
2749
2750 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2751 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2752 if (!CXXUnit->hasSema())
2753 return CXSaveError_InvalidTU;
2754
2755 SaveTranslationUnitInfo STUI = { TU, FileName, options, CXSaveError_None };
2756
2757 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
2758 getenv("LIBCLANG_NOTHREADS")) {
2759 clang_saveTranslationUnit_Impl(&STUI);
2760
2761 if (getenv("LIBCLANG_RESOURCE_USAGE"))
2762 PrintLibclangResourceUsage(TU);
2763
2764 return STUI.result;
2765 }
2766
2767 // We have an AST that has invalid nodes due to compiler errors.
2768 // Use a crash recovery thread for protection.
2769
2770 llvm::CrashRecoveryContext CRC;
2771
2772 if (!RunSafely(CRC, clang_saveTranslationUnit_Impl, &STUI)) {
2773 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
2774 fprintf(stderr, " 'filename' : '%s'\n", FileName);
2775 fprintf(stderr, " 'options' : %d,\n", options);
2776 fprintf(stderr, "}\n");
2777
2778 return CXSaveError_Unknown;
2779
2780 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2781 PrintLibclangResourceUsage(TU);
2782 }
2783
2784 return STUI.result;
2785}
2786
2787void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
2788 if (CTUnit) {
2789 // If the translation unit has been marked as unsafe to free, just discard
2790 // it.
2791 if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
2792 return;
2793
2794 delete static_cast<ASTUnit *>(CTUnit->TUData);
2795 disposeCXStringPool(CTUnit->StringPool);
2796 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
2797 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
Fariborz Jahanian88b95212012-12-18 23:02:59 +00002798 delete static_cast<SimpleFormatContext*>(CTUnit->FormatContext);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002799 delete CTUnit;
2800 }
2801}
2802
2803unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2804 return CXReparse_None;
2805}
2806
2807struct ReparseTranslationUnitInfo {
2808 CXTranslationUnit TU;
2809 unsigned num_unsaved_files;
2810 struct CXUnsavedFile *unsaved_files;
2811 unsigned options;
2812 int result;
2813};
2814
2815static void clang_reparseTranslationUnit_Impl(void *UserData) {
2816 ReparseTranslationUnitInfo *RTUI =
2817 static_cast<ReparseTranslationUnitInfo*>(UserData);
2818 CXTranslationUnit TU = RTUI->TU;
2819
2820 // Reset the associated diagnostics.
2821 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2822 TU->Diagnostics = 0;
2823
2824 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2825 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2826 unsigned options = RTUI->options;
2827 (void) options;
2828 RTUI->result = 1;
2829
2830 if (!TU)
2831 return;
2832
2833 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
2834 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
2835 setThreadBackgroundPriority();
2836
2837 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2838 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2839
2840 OwningPtr<std::vector<ASTUnit::RemappedFile> >
2841 RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2842
2843 // Recover resources if we crash before exiting this function.
2844 llvm::CrashRecoveryContextCleanupRegistrar<
2845 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2846
2847 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2848 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2849 const llvm::MemoryBuffer *Buffer
2850 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2851 RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2852 Buffer));
2853 }
2854
2855 if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2856 RemappedFiles->size()))
2857 RTUI->result = 0;
2858}
2859
2860int clang_reparseTranslationUnit(CXTranslationUnit TU,
2861 unsigned num_unsaved_files,
2862 struct CXUnsavedFile *unsaved_files,
2863 unsigned options) {
2864 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2865 options, 0 };
2866
2867 if (getenv("LIBCLANG_NOTHREADS")) {
2868 clang_reparseTranslationUnit_Impl(&RTUI);
2869 return RTUI.result;
2870 }
2871
2872 llvm::CrashRecoveryContext CRC;
2873
2874 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
2875 fprintf(stderr, "libclang: crash detected during reparsing\n");
2876 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
2877 return 1;
2878 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2879 PrintLibclangResourceUsage(TU);
2880
2881 return RTUI.result;
2882}
2883
2884
2885CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
2886 if (!CTUnit)
2887 return createCXString("");
2888
2889 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
2890 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
2891}
2892
2893CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
2894 ASTUnit *CXXUnit = static_cast<ASTUnit*>(TU->TUData);
2895 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
2896}
2897
2898} // end: extern "C"
2899
2900//===----------------------------------------------------------------------===//
2901// CXFile Operations.
2902//===----------------------------------------------------------------------===//
2903
2904extern "C" {
2905CXString clang_getFileName(CXFile SFile) {
2906 if (!SFile)
2907 return createCXString((const char*)NULL);
2908
2909 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2910 return createCXString(FEnt->getName());
2911}
2912
2913time_t clang_getFileTime(CXFile SFile) {
2914 if (!SFile)
2915 return 0;
2916
2917 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2918 return FEnt->getModificationTime();
2919}
2920
2921CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2922 if (!tu)
2923 return 0;
2924
2925 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2926
2927 FileManager &FMgr = CXXUnit->getFileManager();
2928 return const_cast<FileEntry *>(FMgr.getFile(file_name));
2929}
2930
2931unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2932 if (!tu || !file)
2933 return 0;
2934
2935 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2936 FileEntry *FEnt = static_cast<FileEntry *>(file);
2937 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2938 .isFileMultipleIncludeGuarded(FEnt);
2939}
2940
2941} // end: extern "C"
2942
2943//===----------------------------------------------------------------------===//
2944// CXCursor Operations.
2945//===----------------------------------------------------------------------===//
2946
2947static Decl *getDeclFromExpr(Stmt *E) {
2948 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2949 return getDeclFromExpr(CE->getSubExpr());
2950
2951 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2952 return RefExpr->getDecl();
2953 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2954 return ME->getMemberDecl();
2955 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2956 return RE->getDecl();
2957 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
2958 if (PRE->isExplicitProperty())
2959 return PRE->getExplicitProperty();
2960 // It could be messaging both getter and setter as in:
2961 // ++myobj.myprop;
2962 // in which case prefer to associate the setter since it is less obvious
2963 // from inspecting the source that the setter is going to get called.
2964 if (PRE->isMessagingSetter())
2965 return PRE->getImplicitPropertySetter();
2966 return PRE->getImplicitPropertyGetter();
2967 }
2968 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2969 return getDeclFromExpr(POE->getSyntacticForm());
2970 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2971 if (Expr *Src = OVE->getSourceExpr())
2972 return getDeclFromExpr(Src);
2973
2974 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2975 return getDeclFromExpr(CE->getCallee());
2976 if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
2977 if (!CE->isElidable())
2978 return CE->getConstructor();
2979 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2980 return OME->getMethodDecl();
2981
2982 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2983 return PE->getProtocol();
2984 if (SubstNonTypeTemplateParmPackExpr *NTTP
2985 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2986 return NTTP->getParameterPack();
2987 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2988 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2989 isa<ParmVarDecl>(SizeOfPack->getPack()))
2990 return SizeOfPack->getPack();
2991
2992 return 0;
2993}
2994
2995static SourceLocation getLocationFromExpr(Expr *E) {
2996 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2997 return getLocationFromExpr(CE->getSubExpr());
2998
2999 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
3000 return /*FIXME:*/Msg->getLeftLoc();
3001 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3002 return DRE->getLocation();
3003 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
3004 return Member->getMemberLoc();
3005 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
3006 return Ivar->getLocation();
3007 if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
3008 return SizeOfPack->getPackLoc();
3009 if (ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
3010 return PropRef->getLocation();
3011
3012 return E->getLocStart();
3013}
3014
3015extern "C" {
3016
3017unsigned clang_visitChildren(CXCursor parent,
3018 CXCursorVisitor visitor,
3019 CXClientData client_data) {
3020 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
3021 /*VisitPreprocessorLast=*/false);
3022 return CursorVis.VisitChildren(parent);
3023}
3024
3025#ifndef __has_feature
3026#define __has_feature(x) 0
3027#endif
3028#if __has_feature(blocks)
3029typedef enum CXChildVisitResult
3030 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
3031
3032static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3033 CXClientData client_data) {
3034 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3035 return block(cursor, parent);
3036}
3037#else
3038// If we are compiled with a compiler that doesn't have native blocks support,
3039// define and call the block manually, so the
3040typedef struct _CXChildVisitResult
3041{
3042 void *isa;
3043 int flags;
3044 int reserved;
3045 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
3046 CXCursor);
3047} *CXCursorVisitorBlock;
3048
3049static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
3050 CXClientData client_data) {
3051 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3052 return block->invoke(block, cursor, parent);
3053}
3054#endif
3055
3056
3057unsigned clang_visitChildrenWithBlock(CXCursor parent,
3058 CXCursorVisitorBlock block) {
3059 return clang_visitChildren(parent, visitWithBlock, block);
3060}
3061
3062static CXString getDeclSpelling(Decl *D) {
3063 if (!D)
3064 return createCXString("");
3065
3066 NamedDecl *ND = dyn_cast<NamedDecl>(D);
3067 if (!ND) {
3068 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
3069 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3070 return createCXString(Property->getIdentifier()->getName());
3071
3072 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
3073 if (Module *Mod = ImportD->getImportedModule())
3074 return createCXString(Mod->getFullModuleName());
3075
3076 return createCXString("");
3077 }
3078
3079 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
3080 return createCXString(OMD->getSelector().getAsString());
3081
3082 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3083 // No, this isn't the same as the code below. getIdentifier() is non-virtual
3084 // and returns different names. NamedDecl returns the class name and
3085 // ObjCCategoryImplDecl returns the category name.
3086 return createCXString(CIMP->getIdentifier()->getNameStart());
3087
3088 if (isa<UsingDirectiveDecl>(D))
3089 return createCXString("");
3090
3091 SmallString<1024> S;
3092 llvm::raw_svector_ostream os(S);
3093 ND->printName(os);
3094
3095 return createCXString(os.str());
3096}
3097
3098CXString clang_getCursorSpelling(CXCursor C) {
3099 if (clang_isTranslationUnit(C.kind))
3100 return clang_getTranslationUnitSpelling(
3101 static_cast<CXTranslationUnit>(C.data[2]));
3102
3103 if (clang_isReference(C.kind)) {
3104 switch (C.kind) {
3105 case CXCursor_ObjCSuperClassRef: {
3106 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
3107 return createCXString(Super->getIdentifier()->getNameStart());
3108 }
3109 case CXCursor_ObjCClassRef: {
3110 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
3111 return createCXString(Class->getIdentifier()->getNameStart());
3112 }
3113 case CXCursor_ObjCProtocolRef: {
3114 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
3115 assert(OID && "getCursorSpelling(): Missing protocol decl");
3116 return createCXString(OID->getIdentifier()->getNameStart());
3117 }
3118 case CXCursor_CXXBaseSpecifier: {
3119 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3120 return createCXString(B->getType().getAsString());
3121 }
3122 case CXCursor_TypeRef: {
3123 TypeDecl *Type = getCursorTypeRef(C).first;
3124 assert(Type && "Missing type decl");
3125
3126 return createCXString(getCursorContext(C).getTypeDeclType(Type).
3127 getAsString());
3128 }
3129 case CXCursor_TemplateRef: {
3130 TemplateDecl *Template = getCursorTemplateRef(C).first;
3131 assert(Template && "Missing template decl");
3132
3133 return createCXString(Template->getNameAsString());
3134 }
3135
3136 case CXCursor_NamespaceRef: {
3137 NamedDecl *NS = getCursorNamespaceRef(C).first;
3138 assert(NS && "Missing namespace decl");
3139
3140 return createCXString(NS->getNameAsString());
3141 }
3142
3143 case CXCursor_MemberRef: {
3144 FieldDecl *Field = getCursorMemberRef(C).first;
3145 assert(Field && "Missing member decl");
3146
3147 return createCXString(Field->getNameAsString());
3148 }
3149
3150 case CXCursor_LabelRef: {
3151 LabelStmt *Label = getCursorLabelRef(C).first;
3152 assert(Label && "Missing label");
3153
3154 return createCXString(Label->getName());
3155 }
3156
3157 case CXCursor_OverloadedDeclRef: {
3158 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3159 if (Decl *D = Storage.dyn_cast<Decl *>()) {
3160 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3161 return createCXString(ND->getNameAsString());
3162 return createCXString("");
3163 }
3164 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3165 return createCXString(E->getName().getAsString());
3166 OverloadedTemplateStorage *Ovl
3167 = Storage.get<OverloadedTemplateStorage*>();
3168 if (Ovl->size() == 0)
3169 return createCXString("");
3170 return createCXString((*Ovl->begin())->getNameAsString());
3171 }
3172
3173 case CXCursor_VariableRef: {
3174 VarDecl *Var = getCursorVariableRef(C).first;
3175 assert(Var && "Missing variable decl");
3176
3177 return createCXString(Var->getNameAsString());
3178 }
3179
3180 default:
3181 return createCXString("<not implemented>");
3182 }
3183 }
3184
3185 if (clang_isExpression(C.kind)) {
3186 Decl *D = getDeclFromExpr(getCursorExpr(C));
3187 if (D)
3188 return getDeclSpelling(D);
3189 return createCXString("");
3190 }
3191
3192 if (clang_isStatement(C.kind)) {
3193 Stmt *S = getCursorStmt(C);
3194 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
3195 return createCXString(Label->getName());
3196
3197 return createCXString("");
3198 }
3199
3200 if (C.kind == CXCursor_MacroExpansion)
Argyrios Kyrtzidis664b06f2013-01-07 19:16:25 +00003201 return createCXString(getCursorMacroExpansion(C).getName()
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003202 ->getNameStart());
3203
3204 if (C.kind == CXCursor_MacroDefinition)
3205 return createCXString(getCursorMacroDefinition(C)->getName()
3206 ->getNameStart());
3207
3208 if (C.kind == CXCursor_InclusionDirective)
3209 return createCXString(getCursorInclusionDirective(C)->getFileName());
3210
3211 if (clang_isDeclaration(C.kind))
3212 return getDeclSpelling(getCursorDecl(C));
3213
3214 if (C.kind == CXCursor_AnnotateAttr) {
3215 AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3216 return createCXString(AA->getAnnotation());
3217 }
3218
3219 if (C.kind == CXCursor_AsmLabelAttr) {
3220 AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3221 return createCXString(AA->getLabel());
3222 }
3223
3224 return createCXString("");
3225}
3226
3227CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
3228 unsigned pieceIndex,
3229 unsigned options) {
3230 if (clang_Cursor_isNull(C))
3231 return clang_getNullRange();
3232
3233 ASTContext &Ctx = getCursorContext(C);
3234
3235 if (clang_isStatement(C.kind)) {
3236 Stmt *S = getCursorStmt(C);
3237 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
3238 if (pieceIndex > 0)
3239 return clang_getNullRange();
3240 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
3241 }
3242
3243 return clang_getNullRange();
3244 }
3245
3246 if (C.kind == CXCursor_ObjCMessageExpr) {
3247 if (ObjCMessageExpr *
3248 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
3249 if (pieceIndex >= ME->getNumSelectorLocs())
3250 return clang_getNullRange();
3251 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
3252 }
3253 }
3254
3255 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
3256 C.kind == CXCursor_ObjCClassMethodDecl) {
3257 if (ObjCMethodDecl *
3258 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
3259 if (pieceIndex >= MD->getNumSelectorLocs())
3260 return clang_getNullRange();
3261 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
3262 }
3263 }
3264
3265 if (C.kind == CXCursor_ObjCCategoryDecl ||
3266 C.kind == CXCursor_ObjCCategoryImplDecl) {
3267 if (pieceIndex > 0)
3268 return clang_getNullRange();
3269 if (ObjCCategoryDecl *
3270 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
3271 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
3272 if (ObjCCategoryImplDecl *
3273 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
3274 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
3275 }
3276
3277 if (C.kind == CXCursor_ModuleImportDecl) {
3278 if (pieceIndex > 0)
3279 return clang_getNullRange();
3280 if (ImportDecl *ImportD = dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
3281 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
3282 if (!Locs.empty())
3283 return cxloc::translateSourceRange(Ctx,
3284 SourceRange(Locs.front(), Locs.back()));
3285 }
3286 return clang_getNullRange();
3287 }
3288
3289 // FIXME: A CXCursor_InclusionDirective should give the location of the
3290 // filename, but we don't keep track of this.
3291
3292 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
3293 // but we don't keep track of this.
3294
3295 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
3296 // but we don't keep track of this.
3297
3298 // Default handling, give the location of the cursor.
3299
3300 if (pieceIndex > 0)
3301 return clang_getNullRange();
3302
3303 CXSourceLocation CXLoc = clang_getCursorLocation(C);
3304 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
3305 return cxloc::translateSourceRange(Ctx, Loc);
3306}
3307
3308CXString clang_getCursorDisplayName(CXCursor C) {
3309 if (!clang_isDeclaration(C.kind))
3310 return clang_getCursorSpelling(C);
3311
3312 Decl *D = getCursorDecl(C);
3313 if (!D)
3314 return createCXString("");
3315
3316 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
3317 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3318 D = FunTmpl->getTemplatedDecl();
3319
3320 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3321 SmallString<64> Str;
3322 llvm::raw_svector_ostream OS(Str);
3323 OS << *Function;
3324 if (Function->getPrimaryTemplate())
3325 OS << "<>";
3326 OS << "(";
3327 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3328 if (I)
3329 OS << ", ";
3330 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3331 }
3332
3333 if (Function->isVariadic()) {
3334 if (Function->getNumParams())
3335 OS << ", ";
3336 OS << "...";
3337 }
3338 OS << ")";
3339 return createCXString(OS.str());
3340 }
3341
3342 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3343 SmallString<64> Str;
3344 llvm::raw_svector_ostream OS(Str);
3345 OS << *ClassTemplate;
3346 OS << "<";
3347 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3348 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3349 if (I)
3350 OS << ", ";
3351
3352 NamedDecl *Param = Params->getParam(I);
3353 if (Param->getIdentifier()) {
3354 OS << Param->getIdentifier()->getName();
3355 continue;
3356 }
3357
3358 // There is no parameter name, which makes this tricky. Try to come up
3359 // with something useful that isn't too long.
3360 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3361 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3362 else if (NonTypeTemplateParmDecl *NTTP
3363 = dyn_cast<NonTypeTemplateParmDecl>(Param))
3364 OS << NTTP->getType().getAsString(Policy);
3365 else
3366 OS << "template<...> class";
3367 }
3368
3369 OS << ">";
3370 return createCXString(OS.str());
3371 }
3372
3373 if (ClassTemplateSpecializationDecl *ClassSpec
3374 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3375 // If the type was explicitly written, use that.
3376 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3377 return createCXString(TSInfo->getType().getAsString(Policy));
3378
3379 SmallString<64> Str;
3380 llvm::raw_svector_ostream OS(Str);
3381 OS << *ClassSpec;
3382 OS << TemplateSpecializationType::PrintTemplateArgumentList(
3383 ClassSpec->getTemplateArgs().data(),
3384 ClassSpec->getTemplateArgs().size(),
3385 Policy);
3386 return createCXString(OS.str());
3387 }
3388
3389 return clang_getCursorSpelling(C);
3390}
3391
3392CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
3393 switch (Kind) {
3394 case CXCursor_FunctionDecl:
3395 return createCXString("FunctionDecl");
3396 case CXCursor_TypedefDecl:
3397 return createCXString("TypedefDecl");
3398 case CXCursor_EnumDecl:
3399 return createCXString("EnumDecl");
3400 case CXCursor_EnumConstantDecl:
3401 return createCXString("EnumConstantDecl");
3402 case CXCursor_StructDecl:
3403 return createCXString("StructDecl");
3404 case CXCursor_UnionDecl:
3405 return createCXString("UnionDecl");
3406 case CXCursor_ClassDecl:
3407 return createCXString("ClassDecl");
3408 case CXCursor_FieldDecl:
3409 return createCXString("FieldDecl");
3410 case CXCursor_VarDecl:
3411 return createCXString("VarDecl");
3412 case CXCursor_ParmDecl:
3413 return createCXString("ParmDecl");
3414 case CXCursor_ObjCInterfaceDecl:
3415 return createCXString("ObjCInterfaceDecl");
3416 case CXCursor_ObjCCategoryDecl:
3417 return createCXString("ObjCCategoryDecl");
3418 case CXCursor_ObjCProtocolDecl:
3419 return createCXString("ObjCProtocolDecl");
3420 case CXCursor_ObjCPropertyDecl:
3421 return createCXString("ObjCPropertyDecl");
3422 case CXCursor_ObjCIvarDecl:
3423 return createCXString("ObjCIvarDecl");
3424 case CXCursor_ObjCInstanceMethodDecl:
3425 return createCXString("ObjCInstanceMethodDecl");
3426 case CXCursor_ObjCClassMethodDecl:
3427 return createCXString("ObjCClassMethodDecl");
3428 case CXCursor_ObjCImplementationDecl:
3429 return createCXString("ObjCImplementationDecl");
3430 case CXCursor_ObjCCategoryImplDecl:
3431 return createCXString("ObjCCategoryImplDecl");
3432 case CXCursor_CXXMethod:
3433 return createCXString("CXXMethod");
3434 case CXCursor_UnexposedDecl:
3435 return createCXString("UnexposedDecl");
3436 case CXCursor_ObjCSuperClassRef:
3437 return createCXString("ObjCSuperClassRef");
3438 case CXCursor_ObjCProtocolRef:
3439 return createCXString("ObjCProtocolRef");
3440 case CXCursor_ObjCClassRef:
3441 return createCXString("ObjCClassRef");
3442 case CXCursor_TypeRef:
3443 return createCXString("TypeRef");
3444 case CXCursor_TemplateRef:
3445 return createCXString("TemplateRef");
3446 case CXCursor_NamespaceRef:
3447 return createCXString("NamespaceRef");
3448 case CXCursor_MemberRef:
3449 return createCXString("MemberRef");
3450 case CXCursor_LabelRef:
3451 return createCXString("LabelRef");
3452 case CXCursor_OverloadedDeclRef:
3453 return createCXString("OverloadedDeclRef");
3454 case CXCursor_VariableRef:
3455 return createCXString("VariableRef");
3456 case CXCursor_IntegerLiteral:
3457 return createCXString("IntegerLiteral");
3458 case CXCursor_FloatingLiteral:
3459 return createCXString("FloatingLiteral");
3460 case CXCursor_ImaginaryLiteral:
3461 return createCXString("ImaginaryLiteral");
3462 case CXCursor_StringLiteral:
3463 return createCXString("StringLiteral");
3464 case CXCursor_CharacterLiteral:
3465 return createCXString("CharacterLiteral");
3466 case CXCursor_ParenExpr:
3467 return createCXString("ParenExpr");
3468 case CXCursor_UnaryOperator:
3469 return createCXString("UnaryOperator");
3470 case CXCursor_ArraySubscriptExpr:
3471 return createCXString("ArraySubscriptExpr");
3472 case CXCursor_BinaryOperator:
3473 return createCXString("BinaryOperator");
3474 case CXCursor_CompoundAssignOperator:
3475 return createCXString("CompoundAssignOperator");
3476 case CXCursor_ConditionalOperator:
3477 return createCXString("ConditionalOperator");
3478 case CXCursor_CStyleCastExpr:
3479 return createCXString("CStyleCastExpr");
3480 case CXCursor_CompoundLiteralExpr:
3481 return createCXString("CompoundLiteralExpr");
3482 case CXCursor_InitListExpr:
3483 return createCXString("InitListExpr");
3484 case CXCursor_AddrLabelExpr:
3485 return createCXString("AddrLabelExpr");
3486 case CXCursor_StmtExpr:
3487 return createCXString("StmtExpr");
3488 case CXCursor_GenericSelectionExpr:
3489 return createCXString("GenericSelectionExpr");
3490 case CXCursor_GNUNullExpr:
3491 return createCXString("GNUNullExpr");
3492 case CXCursor_CXXStaticCastExpr:
3493 return createCXString("CXXStaticCastExpr");
3494 case CXCursor_CXXDynamicCastExpr:
3495 return createCXString("CXXDynamicCastExpr");
3496 case CXCursor_CXXReinterpretCastExpr:
3497 return createCXString("CXXReinterpretCastExpr");
3498 case CXCursor_CXXConstCastExpr:
3499 return createCXString("CXXConstCastExpr");
3500 case CXCursor_CXXFunctionalCastExpr:
3501 return createCXString("CXXFunctionalCastExpr");
3502 case CXCursor_CXXTypeidExpr:
3503 return createCXString("CXXTypeidExpr");
3504 case CXCursor_CXXBoolLiteralExpr:
3505 return createCXString("CXXBoolLiteralExpr");
3506 case CXCursor_CXXNullPtrLiteralExpr:
3507 return createCXString("CXXNullPtrLiteralExpr");
3508 case CXCursor_CXXThisExpr:
3509 return createCXString("CXXThisExpr");
3510 case CXCursor_CXXThrowExpr:
3511 return createCXString("CXXThrowExpr");
3512 case CXCursor_CXXNewExpr:
3513 return createCXString("CXXNewExpr");
3514 case CXCursor_CXXDeleteExpr:
3515 return createCXString("CXXDeleteExpr");
3516 case CXCursor_UnaryExpr:
3517 return createCXString("UnaryExpr");
3518 case CXCursor_ObjCStringLiteral:
3519 return createCXString("ObjCStringLiteral");
3520 case CXCursor_ObjCBoolLiteralExpr:
3521 return createCXString("ObjCBoolLiteralExpr");
3522 case CXCursor_ObjCEncodeExpr:
3523 return createCXString("ObjCEncodeExpr");
3524 case CXCursor_ObjCSelectorExpr:
3525 return createCXString("ObjCSelectorExpr");
3526 case CXCursor_ObjCProtocolExpr:
3527 return createCXString("ObjCProtocolExpr");
3528 case CXCursor_ObjCBridgedCastExpr:
3529 return createCXString("ObjCBridgedCastExpr");
3530 case CXCursor_BlockExpr:
3531 return createCXString("BlockExpr");
3532 case CXCursor_PackExpansionExpr:
3533 return createCXString("PackExpansionExpr");
3534 case CXCursor_SizeOfPackExpr:
3535 return createCXString("SizeOfPackExpr");
3536 case CXCursor_LambdaExpr:
3537 return createCXString("LambdaExpr");
3538 case CXCursor_UnexposedExpr:
3539 return createCXString("UnexposedExpr");
3540 case CXCursor_DeclRefExpr:
3541 return createCXString("DeclRefExpr");
3542 case CXCursor_MemberRefExpr:
3543 return createCXString("MemberRefExpr");
3544 case CXCursor_CallExpr:
3545 return createCXString("CallExpr");
3546 case CXCursor_ObjCMessageExpr:
3547 return createCXString("ObjCMessageExpr");
3548 case CXCursor_UnexposedStmt:
3549 return createCXString("UnexposedStmt");
3550 case CXCursor_DeclStmt:
3551 return createCXString("DeclStmt");
3552 case CXCursor_LabelStmt:
3553 return createCXString("LabelStmt");
3554 case CXCursor_CompoundStmt:
3555 return createCXString("CompoundStmt");
3556 case CXCursor_CaseStmt:
3557 return createCXString("CaseStmt");
3558 case CXCursor_DefaultStmt:
3559 return createCXString("DefaultStmt");
3560 case CXCursor_IfStmt:
3561 return createCXString("IfStmt");
3562 case CXCursor_SwitchStmt:
3563 return createCXString("SwitchStmt");
3564 case CXCursor_WhileStmt:
3565 return createCXString("WhileStmt");
3566 case CXCursor_DoStmt:
3567 return createCXString("DoStmt");
3568 case CXCursor_ForStmt:
3569 return createCXString("ForStmt");
3570 case CXCursor_GotoStmt:
3571 return createCXString("GotoStmt");
3572 case CXCursor_IndirectGotoStmt:
3573 return createCXString("IndirectGotoStmt");
3574 case CXCursor_ContinueStmt:
3575 return createCXString("ContinueStmt");
3576 case CXCursor_BreakStmt:
3577 return createCXString("BreakStmt");
3578 case CXCursor_ReturnStmt:
3579 return createCXString("ReturnStmt");
3580 case CXCursor_GCCAsmStmt:
3581 return createCXString("GCCAsmStmt");
3582 case CXCursor_MSAsmStmt:
3583 return createCXString("MSAsmStmt");
3584 case CXCursor_ObjCAtTryStmt:
3585 return createCXString("ObjCAtTryStmt");
3586 case CXCursor_ObjCAtCatchStmt:
3587 return createCXString("ObjCAtCatchStmt");
3588 case CXCursor_ObjCAtFinallyStmt:
3589 return createCXString("ObjCAtFinallyStmt");
3590 case CXCursor_ObjCAtThrowStmt:
3591 return createCXString("ObjCAtThrowStmt");
3592 case CXCursor_ObjCAtSynchronizedStmt:
3593 return createCXString("ObjCAtSynchronizedStmt");
3594 case CXCursor_ObjCAutoreleasePoolStmt:
3595 return createCXString("ObjCAutoreleasePoolStmt");
3596 case CXCursor_ObjCForCollectionStmt:
3597 return createCXString("ObjCForCollectionStmt");
3598 case CXCursor_CXXCatchStmt:
3599 return createCXString("CXXCatchStmt");
3600 case CXCursor_CXXTryStmt:
3601 return createCXString("CXXTryStmt");
3602 case CXCursor_CXXForRangeStmt:
3603 return createCXString("CXXForRangeStmt");
3604 case CXCursor_SEHTryStmt:
3605 return createCXString("SEHTryStmt");
3606 case CXCursor_SEHExceptStmt:
3607 return createCXString("SEHExceptStmt");
3608 case CXCursor_SEHFinallyStmt:
3609 return createCXString("SEHFinallyStmt");
3610 case CXCursor_NullStmt:
3611 return createCXString("NullStmt");
3612 case CXCursor_InvalidFile:
3613 return createCXString("InvalidFile");
3614 case CXCursor_InvalidCode:
3615 return createCXString("InvalidCode");
3616 case CXCursor_NoDeclFound:
3617 return createCXString("NoDeclFound");
3618 case CXCursor_NotImplemented:
3619 return createCXString("NotImplemented");
3620 case CXCursor_TranslationUnit:
3621 return createCXString("TranslationUnit");
3622 case CXCursor_UnexposedAttr:
3623 return createCXString("UnexposedAttr");
3624 case CXCursor_IBActionAttr:
3625 return createCXString("attribute(ibaction)");
3626 case CXCursor_IBOutletAttr:
3627 return createCXString("attribute(iboutlet)");
3628 case CXCursor_IBOutletCollectionAttr:
3629 return createCXString("attribute(iboutletcollection)");
3630 case CXCursor_CXXFinalAttr:
3631 return createCXString("attribute(final)");
3632 case CXCursor_CXXOverrideAttr:
3633 return createCXString("attribute(override)");
3634 case CXCursor_AnnotateAttr:
3635 return createCXString("attribute(annotate)");
3636 case CXCursor_AsmLabelAttr:
3637 return createCXString("asm label");
3638 case CXCursor_PreprocessingDirective:
3639 return createCXString("preprocessing directive");
3640 case CXCursor_MacroDefinition:
3641 return createCXString("macro definition");
3642 case CXCursor_MacroExpansion:
3643 return createCXString("macro expansion");
3644 case CXCursor_InclusionDirective:
3645 return createCXString("inclusion directive");
3646 case CXCursor_Namespace:
3647 return createCXString("Namespace");
3648 case CXCursor_LinkageSpec:
3649 return createCXString("LinkageSpec");
3650 case CXCursor_CXXBaseSpecifier:
3651 return createCXString("C++ base class specifier");
3652 case CXCursor_Constructor:
3653 return createCXString("CXXConstructor");
3654 case CXCursor_Destructor:
3655 return createCXString("CXXDestructor");
3656 case CXCursor_ConversionFunction:
3657 return createCXString("CXXConversion");
3658 case CXCursor_TemplateTypeParameter:
3659 return createCXString("TemplateTypeParameter");
3660 case CXCursor_NonTypeTemplateParameter:
3661 return createCXString("NonTypeTemplateParameter");
3662 case CXCursor_TemplateTemplateParameter:
3663 return createCXString("TemplateTemplateParameter");
3664 case CXCursor_FunctionTemplate:
3665 return createCXString("FunctionTemplate");
3666 case CXCursor_ClassTemplate:
3667 return createCXString("ClassTemplate");
3668 case CXCursor_ClassTemplatePartialSpecialization:
3669 return createCXString("ClassTemplatePartialSpecialization");
3670 case CXCursor_NamespaceAlias:
3671 return createCXString("NamespaceAlias");
3672 case CXCursor_UsingDirective:
3673 return createCXString("UsingDirective");
3674 case CXCursor_UsingDeclaration:
3675 return createCXString("UsingDeclaration");
3676 case CXCursor_TypeAliasDecl:
3677 return createCXString("TypeAliasDecl");
3678 case CXCursor_ObjCSynthesizeDecl:
3679 return createCXString("ObjCSynthesizeDecl");
3680 case CXCursor_ObjCDynamicDecl:
3681 return createCXString("ObjCDynamicDecl");
3682 case CXCursor_CXXAccessSpecifier:
3683 return createCXString("CXXAccessSpecifier");
3684 case CXCursor_ModuleImportDecl:
3685 return createCXString("ModuleImport");
3686 }
3687
3688 llvm_unreachable("Unhandled CXCursorKind");
3689}
3690
3691struct GetCursorData {
3692 SourceLocation TokenBeginLoc;
3693 bool PointsAtMacroArgExpansion;
3694 bool VisitedObjCPropertyImplDecl;
3695 SourceLocation VisitedDeclaratorDeclStartLoc;
3696 CXCursor &BestCursor;
3697
3698 GetCursorData(SourceManager &SM,
3699 SourceLocation tokenBegin, CXCursor &outputCursor)
3700 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3701 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3702 VisitedObjCPropertyImplDecl = false;
3703 }
3704};
3705
3706static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3707 CXCursor parent,
3708 CXClientData client_data) {
3709 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3710 CXCursor *BestCursor = &Data->BestCursor;
3711
3712 // If we point inside a macro argument we should provide info of what the
3713 // token is so use the actual cursor, don't replace it with a macro expansion
3714 // cursor.
3715 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3716 return CXChildVisit_Recurse;
3717
3718 if (clang_isDeclaration(cursor.kind)) {
3719 // Avoid having the implicit methods override the property decls.
3720 if (ObjCMethodDecl *MD
3721 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
3722 if (MD->isImplicit())
3723 return CXChildVisit_Break;
3724
3725 } else if (ObjCInterfaceDecl *ID
3726 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
3727 // Check that when we have multiple @class references in the same line,
3728 // that later ones do not override the previous ones.
3729 // If we have:
3730 // @class Foo, Bar;
3731 // source ranges for both start at '@', so 'Bar' will end up overriding
3732 // 'Foo' even though the cursor location was at 'Foo'.
3733 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
3734 BestCursor->kind == CXCursor_ObjCClassRef)
3735 if (ObjCInterfaceDecl *PrevID
3736 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
3737 if (PrevID != ID &&
3738 !PrevID->isThisDeclarationADefinition() &&
3739 !ID->isThisDeclarationADefinition())
3740 return CXChildVisit_Break;
3741 }
3742
3743 } else if (DeclaratorDecl *DD
3744 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
3745 SourceLocation StartLoc = DD->getSourceRange().getBegin();
3746 // Check that when we have multiple declarators in the same line,
3747 // that later ones do not override the previous ones.
3748 // If we have:
3749 // int Foo, Bar;
3750 // source ranges for both start at 'int', so 'Bar' will end up overriding
3751 // 'Foo' even though the cursor location was at 'Foo'.
3752 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
3753 return CXChildVisit_Break;
3754 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
3755
3756 } else if (ObjCPropertyImplDecl *PropImp
3757 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
3758 (void)PropImp;
3759 // Check that when we have multiple @synthesize in the same line,
3760 // that later ones do not override the previous ones.
3761 // If we have:
3762 // @synthesize Foo, Bar;
3763 // source ranges for both start at '@', so 'Bar' will end up overriding
3764 // 'Foo' even though the cursor location was at 'Foo'.
3765 if (Data->VisitedObjCPropertyImplDecl)
3766 return CXChildVisit_Break;
3767 Data->VisitedObjCPropertyImplDecl = true;
3768 }
3769 }
3770
3771 if (clang_isExpression(cursor.kind) &&
3772 clang_isDeclaration(BestCursor->kind)) {
3773 if (Decl *D = getCursorDecl(*BestCursor)) {
3774 // Avoid having the cursor of an expression replace the declaration cursor
3775 // when the expression source range overlaps the declaration range.
3776 // This can happen for C++ constructor expressions whose range generally
3777 // include the variable declaration, e.g.:
3778 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3779 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3780 D->getLocation() == Data->TokenBeginLoc)
3781 return CXChildVisit_Break;
3782 }
3783 }
3784
3785 // If our current best cursor is the construction of a temporary object,
3786 // don't replace that cursor with a type reference, because we want
3787 // clang_getCursor() to point at the constructor.
3788 if (clang_isExpression(BestCursor->kind) &&
3789 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3790 cursor.kind == CXCursor_TypeRef) {
3791 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3792 // as having the actual point on the type reference.
3793 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
3794 return CXChildVisit_Recurse;
3795 }
3796
3797 *BestCursor = cursor;
3798 return CXChildVisit_Recurse;
3799}
3800
3801CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3802 if (!TU)
3803 return clang_getNullCursor();
3804
3805 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3806 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3807
3808 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
3809 CXCursor Result = cxcursor::getCursor(TU, SLoc);
3810
3811 bool Logging = getenv("LIBCLANG_LOGGING");
3812 if (Logging) {
3813 CXFile SearchFile;
3814 unsigned SearchLine, SearchColumn;
3815 CXFile ResultFile;
3816 unsigned ResultLine, ResultColumn;
3817 CXString SearchFileName, ResultFileName, KindSpelling, USR;
3818 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
3819 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3820
3821 clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3822 clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3823 &ResultColumn, 0);
3824 SearchFileName = clang_getFileName(SearchFile);
3825 ResultFileName = clang_getFileName(ResultFile);
3826 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3827 USR = clang_getCursorUSR(Result);
3828 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
3829 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3830 clang_getCString(KindSpelling),
3831 clang_getCString(ResultFileName), ResultLine, ResultColumn,
3832 clang_getCString(USR), IsDef);
3833 clang_disposeString(SearchFileName);
3834 clang_disposeString(ResultFileName);
3835 clang_disposeString(KindSpelling);
3836 clang_disposeString(USR);
3837
3838 CXCursor Definition = clang_getCursorDefinition(Result);
3839 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3840 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3841 CXString DefinitionKindSpelling
3842 = clang_getCursorKindSpelling(Definition.kind);
3843 CXFile DefinitionFile;
3844 unsigned DefinitionLine, DefinitionColumn;
3845 clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3846 &DefinitionLine, &DefinitionColumn, 0);
3847 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3848 fprintf(stderr, " -> %s(%s:%d:%d)\n",
3849 clang_getCString(DefinitionKindSpelling),
3850 clang_getCString(DefinitionFileName),
3851 DefinitionLine, DefinitionColumn);
3852 clang_disposeString(DefinitionFileName);
3853 clang_disposeString(DefinitionKindSpelling);
3854 }
3855 }
3856
3857 return Result;
3858}
3859
3860CXCursor clang_getNullCursor(void) {
3861 return MakeCXCursorInvalid(CXCursor_InvalidFile);
3862}
3863
3864unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
3865 return X == Y;
3866}
3867
3868unsigned clang_hashCursor(CXCursor C) {
3869 unsigned Index = 0;
3870 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3871 Index = 1;
3872
3873 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3874 std::make_pair(C.kind, C.data[Index]));
3875}
3876
3877unsigned clang_isInvalid(enum CXCursorKind K) {
3878 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3879}
3880
3881unsigned clang_isDeclaration(enum CXCursorKind K) {
3882 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
3883 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
3884}
3885
3886unsigned clang_isReference(enum CXCursorKind K) {
3887 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3888}
3889
3890unsigned clang_isExpression(enum CXCursorKind K) {
3891 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3892}
3893
3894unsigned clang_isStatement(enum CXCursorKind K) {
3895 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3896}
3897
3898unsigned clang_isAttribute(enum CXCursorKind K) {
3899 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3900}
3901
3902unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3903 return K == CXCursor_TranslationUnit;
3904}
3905
3906unsigned clang_isPreprocessing(enum CXCursorKind K) {
3907 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3908}
3909
3910unsigned clang_isUnexposed(enum CXCursorKind K) {
3911 switch (K) {
3912 case CXCursor_UnexposedDecl:
3913 case CXCursor_UnexposedExpr:
3914 case CXCursor_UnexposedStmt:
3915 case CXCursor_UnexposedAttr:
3916 return true;
3917 default:
3918 return false;
3919 }
3920}
3921
3922CXCursorKind clang_getCursorKind(CXCursor C) {
3923 return C.kind;
3924}
3925
3926CXSourceLocation clang_getCursorLocation(CXCursor C) {
3927 if (clang_isReference(C.kind)) {
3928 switch (C.kind) {
3929 case CXCursor_ObjCSuperClassRef: {
3930 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3931 = getCursorObjCSuperClassRef(C);
3932 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3933 }
3934
3935 case CXCursor_ObjCProtocolRef: {
3936 std::pair<ObjCProtocolDecl *, SourceLocation> P
3937 = getCursorObjCProtocolRef(C);
3938 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3939 }
3940
3941 case CXCursor_ObjCClassRef: {
3942 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3943 = getCursorObjCClassRef(C);
3944 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3945 }
3946
3947 case CXCursor_TypeRef: {
3948 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
3949 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3950 }
3951
3952 case CXCursor_TemplateRef: {
3953 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3954 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3955 }
3956
3957 case CXCursor_NamespaceRef: {
3958 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3959 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3960 }
3961
3962 case CXCursor_MemberRef: {
3963 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3964 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3965 }
3966
3967 case CXCursor_VariableRef: {
3968 std::pair<VarDecl *, SourceLocation> P = getCursorVariableRef(C);
3969 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3970 }
3971
3972 case CXCursor_CXXBaseSpecifier: {
3973 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3974 if (!BaseSpec)
3975 return clang_getNullLocation();
3976
3977 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3978 return cxloc::translateSourceLocation(getCursorContext(C),
3979 TSInfo->getTypeLoc().getBeginLoc());
3980
3981 return cxloc::translateSourceLocation(getCursorContext(C),
3982 BaseSpec->getLocStart());
3983 }
3984
3985 case CXCursor_LabelRef: {
3986 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3987 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3988 }
3989
3990 case CXCursor_OverloadedDeclRef:
3991 return cxloc::translateSourceLocation(getCursorContext(C),
3992 getCursorOverloadedDeclRef(C).second);
3993
3994 default:
3995 // FIXME: Need a way to enumerate all non-reference cases.
3996 llvm_unreachable("Missed a reference kind");
3997 }
3998 }
3999
4000 if (clang_isExpression(C.kind))
4001 return cxloc::translateSourceLocation(getCursorContext(C),
4002 getLocationFromExpr(getCursorExpr(C)));
4003
4004 if (clang_isStatement(C.kind))
4005 return cxloc::translateSourceLocation(getCursorContext(C),
4006 getCursorStmt(C)->getLocStart());
4007
4008 if (C.kind == CXCursor_PreprocessingDirective) {
4009 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
4010 return cxloc::translateSourceLocation(getCursorContext(C), L);
4011 }
4012
4013 if (C.kind == CXCursor_MacroExpansion) {
4014 SourceLocation L
Argyrios Kyrtzidis664b06f2013-01-07 19:16:25 +00004015 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004016 return cxloc::translateSourceLocation(getCursorContext(C), L);
4017 }
4018
4019 if (C.kind == CXCursor_MacroDefinition) {
4020 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
4021 return cxloc::translateSourceLocation(getCursorContext(C), L);
4022 }
4023
4024 if (C.kind == CXCursor_InclusionDirective) {
4025 SourceLocation L
4026 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
4027 return cxloc::translateSourceLocation(getCursorContext(C), L);
4028 }
4029
4030 if (!clang_isDeclaration(C.kind))
4031 return clang_getNullLocation();
4032
4033 Decl *D = getCursorDecl(C);
4034 if (!D)
4035 return clang_getNullLocation();
4036
4037 SourceLocation Loc = D->getLocation();
4038 // FIXME: Multiple variables declared in a single declaration
4039 // currently lack the information needed to correctly determine their
4040 // ranges when accounting for the type-specifier. We use context
4041 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4042 // and if so, whether it is the first decl.
4043 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4044 if (!cxcursor::isFirstInDeclGroup(C))
4045 Loc = VD->getLocation();
4046 }
4047
4048 // For ObjC methods, give the start location of the method name.
4049 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4050 Loc = MD->getSelectorStartLoc();
4051
4052 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
4053}
4054
4055} // end extern "C"
4056
4057CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
4058 assert(TU);
4059
4060 // Guard against an invalid SourceLocation, or we may assert in one
4061 // of the following calls.
4062 if (SLoc.isInvalid())
4063 return clang_getNullCursor();
4064
4065 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4066
4067 // Translate the given source location to make it point at the beginning of
4068 // the token under the cursor.
4069 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
4070 CXXUnit->getASTContext().getLangOpts());
4071
4072 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
4073 if (SLoc.isValid()) {
4074 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
4075 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
4076 /*VisitPreprocessorLast=*/true,
4077 /*VisitIncludedEntities=*/false,
4078 SourceLocation(SLoc));
4079 CursorVis.visitFileRegion();
4080 }
4081
4082 return Result;
4083}
4084
4085static SourceRange getRawCursorExtent(CXCursor C) {
4086 if (clang_isReference(C.kind)) {
4087 switch (C.kind) {
4088 case CXCursor_ObjCSuperClassRef:
4089 return getCursorObjCSuperClassRef(C).second;
4090
4091 case CXCursor_ObjCProtocolRef:
4092 return getCursorObjCProtocolRef(C).second;
4093
4094 case CXCursor_ObjCClassRef:
4095 return getCursorObjCClassRef(C).second;
4096
4097 case CXCursor_TypeRef:
4098 return getCursorTypeRef(C).second;
4099
4100 case CXCursor_TemplateRef:
4101 return getCursorTemplateRef(C).second;
4102
4103 case CXCursor_NamespaceRef:
4104 return getCursorNamespaceRef(C).second;
4105
4106 case CXCursor_MemberRef:
4107 return getCursorMemberRef(C).second;
4108
4109 case CXCursor_CXXBaseSpecifier:
4110 return getCursorCXXBaseSpecifier(C)->getSourceRange();
4111
4112 case CXCursor_LabelRef:
4113 return getCursorLabelRef(C).second;
4114
4115 case CXCursor_OverloadedDeclRef:
4116 return getCursorOverloadedDeclRef(C).second;
4117
4118 case CXCursor_VariableRef:
4119 return getCursorVariableRef(C).second;
4120
4121 default:
4122 // FIXME: Need a way to enumerate all non-reference cases.
4123 llvm_unreachable("Missed a reference kind");
4124 }
4125 }
4126
4127 if (clang_isExpression(C.kind))
4128 return getCursorExpr(C)->getSourceRange();
4129
4130 if (clang_isStatement(C.kind))
4131 return getCursorStmt(C)->getSourceRange();
4132
4133 if (clang_isAttribute(C.kind))
4134 return getCursorAttr(C)->getRange();
4135
4136 if (C.kind == CXCursor_PreprocessingDirective)
4137 return cxcursor::getCursorPreprocessingDirective(C);
4138
4139 if (C.kind == CXCursor_MacroExpansion) {
4140 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis664b06f2013-01-07 19:16:25 +00004141 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004142 return TU->mapRangeFromPreamble(Range);
4143 }
4144
4145 if (C.kind == CXCursor_MacroDefinition) {
4146 ASTUnit *TU = getCursorASTUnit(C);
4147 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
4148 return TU->mapRangeFromPreamble(Range);
4149 }
4150
4151 if (C.kind == CXCursor_InclusionDirective) {
4152 ASTUnit *TU = getCursorASTUnit(C);
4153 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
4154 return TU->mapRangeFromPreamble(Range);
4155 }
4156
4157 if (C.kind == CXCursor_TranslationUnit) {
4158 ASTUnit *TU = getCursorASTUnit(C);
4159 FileID MainID = TU->getSourceManager().getMainFileID();
4160 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
4161 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
4162 return SourceRange(Start, End);
4163 }
4164
4165 if (clang_isDeclaration(C.kind)) {
4166 Decl *D = cxcursor::getCursorDecl(C);
4167 if (!D)
4168 return SourceRange();
4169
4170 SourceRange R = D->getSourceRange();
4171 // FIXME: Multiple variables declared in a single declaration
4172 // currently lack the information needed to correctly determine their
4173 // ranges when accounting for the type-specifier. We use context
4174 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4175 // and if so, whether it is the first decl.
4176 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4177 if (!cxcursor::isFirstInDeclGroup(C))
4178 R.setBegin(VD->getLocation());
4179 }
4180 return R;
4181 }
4182 return SourceRange();
4183}
4184
4185/// \brief Retrieves the "raw" cursor extent, which is then extended to include
4186/// the decl-specifier-seq for declarations.
4187static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
4188 if (clang_isDeclaration(C.kind)) {
4189 Decl *D = cxcursor::getCursorDecl(C);
4190 if (!D)
4191 return SourceRange();
4192
4193 SourceRange R = D->getSourceRange();
4194
4195 // Adjust the start of the location for declarations preceded by
4196 // declaration specifiers.
4197 SourceLocation StartLoc;
4198 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4199 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4200 StartLoc = TI->getTypeLoc().getLocStart();
4201 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4202 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4203 StartLoc = TI->getTypeLoc().getLocStart();
4204 }
4205
4206 if (StartLoc.isValid() && R.getBegin().isValid() &&
4207 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4208 R.setBegin(StartLoc);
4209
4210 // FIXME: Multiple variables declared in a single declaration
4211 // currently lack the information needed to correctly determine their
4212 // ranges when accounting for the type-specifier. We use context
4213 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4214 // and if so, whether it is the first decl.
4215 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4216 if (!cxcursor::isFirstInDeclGroup(C))
4217 R.setBegin(VD->getLocation());
4218 }
4219
4220 return R;
4221 }
4222
4223 return getRawCursorExtent(C);
4224}
4225
4226extern "C" {
4227
4228CXSourceRange clang_getCursorExtent(CXCursor C) {
4229 SourceRange R = getRawCursorExtent(C);
4230 if (R.isInvalid())
4231 return clang_getNullRange();
4232
4233 return cxloc::translateSourceRange(getCursorContext(C), R);
4234}
4235
4236CXCursor clang_getCursorReferenced(CXCursor C) {
4237 if (clang_isInvalid(C.kind))
4238 return clang_getNullCursor();
4239
4240 CXTranslationUnit tu = getCursorTU(C);
4241 if (clang_isDeclaration(C.kind)) {
4242 Decl *D = getCursorDecl(C);
4243 if (!D)
4244 return clang_getNullCursor();
4245 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
4246 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
4247 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
4248 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4249 return MakeCXCursor(Property, tu);
4250
4251 return C;
4252 }
4253
4254 if (clang_isExpression(C.kind)) {
4255 Expr *E = getCursorExpr(C);
4256 Decl *D = getDeclFromExpr(E);
4257 if (D) {
4258 CXCursor declCursor = MakeCXCursor(D, tu);
4259 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4260 declCursor);
4261 return declCursor;
4262 }
4263
4264 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
4265 return MakeCursorOverloadedDeclRef(Ovl, tu);
4266
4267 return clang_getNullCursor();
4268 }
4269
4270 if (clang_isStatement(C.kind)) {
4271 Stmt *S = getCursorStmt(C);
4272 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
4273 if (LabelDecl *label = Goto->getLabel())
4274 if (LabelStmt *labelS = label->getStmt())
4275 return MakeCXCursor(labelS, getCursorDecl(C), tu);
4276
4277 return clang_getNullCursor();
4278 }
4279
4280 if (C.kind == CXCursor_MacroExpansion) {
Argyrios Kyrtzidis664b06f2013-01-07 19:16:25 +00004281 if (MacroDefinition *Def = getCursorMacroExpansion(C).getDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004282 return MakeMacroDefinitionCursor(Def, tu);
4283 }
4284
4285 if (!clang_isReference(C.kind))
4286 return clang_getNullCursor();
4287
4288 switch (C.kind) {
4289 case CXCursor_ObjCSuperClassRef:
4290 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
4291
4292 case CXCursor_ObjCProtocolRef: {
4293 ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
4294 if (ObjCProtocolDecl *Def = Prot->getDefinition())
4295 return MakeCXCursor(Def, tu);
4296
4297 return MakeCXCursor(Prot, tu);
4298 }
4299
4300 case CXCursor_ObjCClassRef: {
4301 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4302 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4303 return MakeCXCursor(Def, tu);
4304
4305 return MakeCXCursor(Class, tu);
4306 }
4307
4308 case CXCursor_TypeRef:
4309 return MakeCXCursor(getCursorTypeRef(C).first, tu );
4310
4311 case CXCursor_TemplateRef:
4312 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
4313
4314 case CXCursor_NamespaceRef:
4315 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
4316
4317 case CXCursor_MemberRef:
4318 return MakeCXCursor(getCursorMemberRef(C).first, tu );
4319
4320 case CXCursor_CXXBaseSpecifier: {
4321 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4322 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
4323 tu ));
4324 }
4325
4326 case CXCursor_LabelRef:
4327 // FIXME: We end up faking the "parent" declaration here because we
4328 // don't want to make CXCursor larger.
4329 return MakeCXCursor(getCursorLabelRef(C).first,
4330 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4331 .getTranslationUnitDecl(),
4332 tu);
4333
4334 case CXCursor_OverloadedDeclRef:
4335 return C;
4336
4337 case CXCursor_VariableRef:
4338 return MakeCXCursor(getCursorVariableRef(C).first, tu);
4339
4340 default:
4341 // We would prefer to enumerate all non-reference cursor kinds here.
4342 llvm_unreachable("Unhandled reference cursor kind");
4343 }
4344}
4345
4346CXCursor clang_getCursorDefinition(CXCursor C) {
4347 if (clang_isInvalid(C.kind))
4348 return clang_getNullCursor();
4349
4350 CXTranslationUnit TU = getCursorTU(C);
4351
4352 bool WasReference = false;
4353 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
4354 C = clang_getCursorReferenced(C);
4355 WasReference = true;
4356 }
4357
4358 if (C.kind == CXCursor_MacroExpansion)
4359 return clang_getCursorReferenced(C);
4360
4361 if (!clang_isDeclaration(C.kind))
4362 return clang_getNullCursor();
4363
4364 Decl *D = getCursorDecl(C);
4365 if (!D)
4366 return clang_getNullCursor();
4367
4368 switch (D->getKind()) {
4369 // Declaration kinds that don't really separate the notions of
4370 // declaration and definition.
4371 case Decl::Namespace:
4372 case Decl::Typedef:
4373 case Decl::TypeAlias:
4374 case Decl::TypeAliasTemplate:
4375 case Decl::TemplateTypeParm:
4376 case Decl::EnumConstant:
4377 case Decl::Field:
4378 case Decl::IndirectField:
4379 case Decl::ObjCIvar:
4380 case Decl::ObjCAtDefsField:
4381 case Decl::ImplicitParam:
4382 case Decl::ParmVar:
4383 case Decl::NonTypeTemplateParm:
4384 case Decl::TemplateTemplateParm:
4385 case Decl::ObjCCategoryImpl:
4386 case Decl::ObjCImplementation:
4387 case Decl::AccessSpec:
4388 case Decl::LinkageSpec:
4389 case Decl::ObjCPropertyImpl:
4390 case Decl::FileScopeAsm:
4391 case Decl::StaticAssert:
4392 case Decl::Block:
4393 case Decl::Label: // FIXME: Is this right??
4394 case Decl::ClassScopeFunctionSpecialization:
4395 case Decl::Import:
4396 return C;
4397
4398 // Declaration kinds that don't make any sense here, but are
4399 // nonetheless harmless.
4400 case Decl::TranslationUnit:
4401 break;
4402
4403 // Declaration kinds for which the definition is not resolvable.
4404 case Decl::UnresolvedUsingTypename:
4405 case Decl::UnresolvedUsingValue:
4406 break;
4407
4408 case Decl::UsingDirective:
4409 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
4410 TU);
4411
4412 case Decl::NamespaceAlias:
4413 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
4414
4415 case Decl::Enum:
4416 case Decl::Record:
4417 case Decl::CXXRecord:
4418 case Decl::ClassTemplateSpecialization:
4419 case Decl::ClassTemplatePartialSpecialization:
4420 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
4421 return MakeCXCursor(Def, TU);
4422 return clang_getNullCursor();
4423
4424 case Decl::Function:
4425 case Decl::CXXMethod:
4426 case Decl::CXXConstructor:
4427 case Decl::CXXDestructor:
4428 case Decl::CXXConversion: {
4429 const FunctionDecl *Def = 0;
4430 if (cast<FunctionDecl>(D)->getBody(Def))
4431 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
4432 return clang_getNullCursor();
4433 }
4434
4435 case Decl::Var: {
4436 // Ask the variable if it has a definition.
4437 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
4438 return MakeCXCursor(Def, TU);
4439 return clang_getNullCursor();
4440 }
4441
4442 case Decl::FunctionTemplate: {
4443 const FunctionDecl *Def = 0;
4444 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
4445 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
4446 return clang_getNullCursor();
4447 }
4448
4449 case Decl::ClassTemplate: {
4450 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
4451 ->getDefinition())
4452 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
4453 TU);
4454 return clang_getNullCursor();
4455 }
4456
4457 case Decl::Using:
4458 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
4459 D->getLocation(), TU);
4460
4461 case Decl::UsingShadow:
4462 return clang_getCursorDefinition(
4463 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
4464 TU));
4465
4466 case Decl::ObjCMethod: {
4467 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4468 if (Method->isThisDeclarationADefinition())
4469 return C;
4470
4471 // Dig out the method definition in the associated
4472 // @implementation, if we have it.
4473 // FIXME: The ASTs should make finding the definition easier.
4474 if (ObjCInterfaceDecl *Class
4475 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4476 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4477 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4478 Method->isInstanceMethod()))
4479 if (Def->isThisDeclarationADefinition())
4480 return MakeCXCursor(Def, TU);
4481
4482 return clang_getNullCursor();
4483 }
4484
4485 case Decl::ObjCCategory:
4486 if (ObjCCategoryImplDecl *Impl
4487 = cast<ObjCCategoryDecl>(D)->getImplementation())
4488 return MakeCXCursor(Impl, TU);
4489 return clang_getNullCursor();
4490
4491 case Decl::ObjCProtocol:
4492 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
4493 return MakeCXCursor(Def, TU);
4494 return clang_getNullCursor();
4495
4496 case Decl::ObjCInterface: {
4497 // There are two notions of a "definition" for an Objective-C
4498 // class: the interface and its implementation. When we resolved a
4499 // reference to an Objective-C class, produce the @interface as
4500 // the definition; when we were provided with the interface,
4501 // produce the @implementation as the definition.
4502 ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
4503 if (WasReference) {
4504 if (ObjCInterfaceDecl *Def = IFace->getDefinition())
4505 return MakeCXCursor(Def, TU);
4506 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
4507 return MakeCXCursor(Impl, TU);
4508 return clang_getNullCursor();
4509 }
4510
4511 case Decl::ObjCProperty:
4512 // FIXME: We don't really know where to find the
4513 // ObjCPropertyImplDecls that implement this property.
4514 return clang_getNullCursor();
4515
4516 case Decl::ObjCCompatibleAlias:
4517 if (ObjCInterfaceDecl *Class
4518 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4519 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4520 return MakeCXCursor(Def, TU);
4521
4522 return clang_getNullCursor();
4523
4524 case Decl::Friend:
4525 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
4526 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
4527 return clang_getNullCursor();
4528
4529 case Decl::FriendTemplate:
4530 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
4531 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
4532 return clang_getNullCursor();
4533 }
4534
4535 return clang_getNullCursor();
4536}
4537
4538unsigned clang_isCursorDefinition(CXCursor C) {
4539 if (!clang_isDeclaration(C.kind))
4540 return 0;
4541
4542 return clang_getCursorDefinition(C) == C;
4543}
4544
4545CXCursor clang_getCanonicalCursor(CXCursor C) {
4546 if (!clang_isDeclaration(C.kind))
4547 return C;
4548
4549 if (Decl *D = getCursorDecl(C)) {
4550 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4551 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4552 return MakeCXCursor(CatD, getCursorTU(C));
4553
4554 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4555 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4556 return MakeCXCursor(IFD, getCursorTU(C));
4557
4558 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
4559 }
4560
4561 return C;
4562}
4563
4564int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
4565 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
4566}
4567
4568unsigned clang_getNumOverloadedDecls(CXCursor C) {
4569 if (C.kind != CXCursor_OverloadedDeclRef)
4570 return 0;
4571
4572 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4573 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4574 return E->getNumDecls();
4575
4576 if (OverloadedTemplateStorage *S
4577 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4578 return S->size();
4579
4580 Decl *D = Storage.get<Decl*>();
4581 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
4582 return Using->shadow_size();
4583
4584 return 0;
4585}
4586
4587CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
4588 if (cursor.kind != CXCursor_OverloadedDeclRef)
4589 return clang_getNullCursor();
4590
4591 if (index >= clang_getNumOverloadedDecls(cursor))
4592 return clang_getNullCursor();
4593
4594 CXTranslationUnit TU = getCursorTU(cursor);
4595 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4596 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4597 return MakeCXCursor(E->decls_begin()[index], TU);
4598
4599 if (OverloadedTemplateStorage *S
4600 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4601 return MakeCXCursor(S->begin()[index], TU);
4602
4603 Decl *D = Storage.get<Decl*>();
4604 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4605 // FIXME: This is, unfortunately, linear time.
4606 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4607 std::advance(Pos, index);
4608 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
4609 }
4610
4611 return clang_getNullCursor();
4612}
4613
4614void clang_getDefinitionSpellingAndExtent(CXCursor C,
4615 const char **startBuf,
4616 const char **endBuf,
4617 unsigned *startLine,
4618 unsigned *startColumn,
4619 unsigned *endLine,
4620 unsigned *endColumn) {
4621 assert(getCursorDecl(C) && "CXCursor has null decl");
4622 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
4623 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4624 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
4625
4626 SourceManager &SM = FD->getASTContext().getSourceManager();
4627 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4628 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4629 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4630 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4631 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4632 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4633}
4634
4635
4636CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4637 unsigned PieceIndex) {
4638 RefNamePieces Pieces;
4639
4640 switch (C.kind) {
4641 case CXCursor_MemberRefExpr:
4642 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4643 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4644 E->getQualifierLoc().getSourceRange());
4645 break;
4646
4647 case CXCursor_DeclRefExpr:
4648 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4649 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4650 E->getQualifierLoc().getSourceRange(),
4651 E->getOptionalExplicitTemplateArgs());
4652 break;
4653
4654 case CXCursor_CallExpr:
4655 if (CXXOperatorCallExpr *OCE =
4656 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4657 Expr *Callee = OCE->getCallee();
4658 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4659 Callee = ICE->getSubExpr();
4660
4661 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4662 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4663 DRE->getQualifierLoc().getSourceRange());
4664 }
4665 break;
4666
4667 default:
4668 break;
4669 }
4670
4671 if (Pieces.empty()) {
4672 if (PieceIndex == 0)
4673 return clang_getCursorExtent(C);
4674 } else if (PieceIndex < Pieces.size()) {
4675 SourceRange R = Pieces[PieceIndex];
4676 if (R.isValid())
4677 return cxloc::translateSourceRange(getCursorContext(C), R);
4678 }
4679
4680 return clang_getNullRange();
4681}
4682
4683void clang_enableStackTraces(void) {
4684 llvm::sys::PrintStackTraceOnErrorSignal();
4685}
4686
4687void clang_executeOnThread(void (*fn)(void*), void *user_data,
4688 unsigned stack_size) {
4689 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4690}
4691
4692} // end: extern "C"
4693
4694//===----------------------------------------------------------------------===//
4695// Token-based Operations.
4696//===----------------------------------------------------------------------===//
4697
4698/* CXToken layout:
4699 * int_data[0]: a CXTokenKind
4700 * int_data[1]: starting token location
4701 * int_data[2]: token length
4702 * int_data[3]: reserved
4703 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
4704 * otherwise unused.
4705 */
4706extern "C" {
4707
4708CXTokenKind clang_getTokenKind(CXToken CXTok) {
4709 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4710}
4711
4712CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4713 switch (clang_getTokenKind(CXTok)) {
4714 case CXToken_Identifier:
4715 case CXToken_Keyword:
4716 // We know we have an IdentifierInfo*, so use that.
4717 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4718 ->getNameStart());
4719
4720 case CXToken_Literal: {
4721 // We have stashed the starting pointer in the ptr_data field. Use it.
4722 const char *Text = static_cast<const char *>(CXTok.ptr_data);
4723 return createCXString(StringRef(Text, CXTok.int_data[2]));
4724 }
4725
4726 case CXToken_Punctuation:
4727 case CXToken_Comment:
4728 break;
4729 }
4730
4731 // We have to find the starting buffer pointer the hard way, by
4732 // deconstructing the source location.
4733 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4734 if (!CXXUnit)
4735 return createCXString("");
4736
4737 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4738 std::pair<FileID, unsigned> LocInfo
4739 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
4740 bool Invalid = false;
4741 StringRef Buffer
4742 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4743 if (Invalid)
4744 return createCXString("");
4745
4746 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
4747}
4748
4749CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
4750 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4751 if (!CXXUnit)
4752 return clang_getNullLocation();
4753
4754 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4755 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4756}
4757
4758CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
4759 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4760 if (!CXXUnit)
4761 return clang_getNullRange();
4762
4763 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
4764 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4765}
4766
4767static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4768 SmallVectorImpl<CXToken> &CXTokens) {
4769 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4770 std::pair<FileID, unsigned> BeginLocInfo
4771 = SourceMgr.getDecomposedLoc(Range.getBegin());
4772 std::pair<FileID, unsigned> EndLocInfo
4773 = SourceMgr.getDecomposedLoc(Range.getEnd());
4774
4775 // Cannot tokenize across files.
4776 if (BeginLocInfo.first != EndLocInfo.first)
4777 return;
4778
4779 // Create a lexer
4780 bool Invalid = false;
4781 StringRef Buffer
4782 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4783 if (Invalid)
4784 return;
4785
4786 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4787 CXXUnit->getASTContext().getLangOpts(),
4788 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
4789 Lex.SetCommentRetentionState(true);
4790
4791 // Lex tokens until we hit the end of the range.
4792 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
4793 Token Tok;
4794 bool previousWasAt = false;
4795 do {
4796 // Lex the next token
4797 Lex.LexFromRawLexer(Tok);
4798 if (Tok.is(tok::eof))
4799 break;
4800
4801 // Initialize the CXToken.
4802 CXToken CXTok;
4803
4804 // - Common fields
4805 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4806 CXTok.int_data[2] = Tok.getLength();
4807 CXTok.int_data[3] = 0;
4808
4809 // - Kind-specific fields
4810 if (Tok.isLiteral()) {
4811 CXTok.int_data[0] = CXToken_Literal;
4812 CXTok.ptr_data = (void *)Tok.getLiteralData();
4813 } else if (Tok.is(tok::raw_identifier)) {
4814 // Lookup the identifier to determine whether we have a keyword.
4815 IdentifierInfo *II
4816 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
4817
4818 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
4819 CXTok.int_data[0] = CXToken_Keyword;
4820 }
4821 else {
4822 CXTok.int_data[0] = Tok.is(tok::identifier)
4823 ? CXToken_Identifier
4824 : CXToken_Keyword;
4825 }
4826 CXTok.ptr_data = II;
4827 } else if (Tok.is(tok::comment)) {
4828 CXTok.int_data[0] = CXToken_Comment;
4829 CXTok.ptr_data = 0;
4830 } else {
4831 CXTok.int_data[0] = CXToken_Punctuation;
4832 CXTok.ptr_data = 0;
4833 }
4834 CXTokens.push_back(CXTok);
4835 previousWasAt = Tok.is(tok::at);
4836 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
4837}
4838
4839void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4840 CXToken **Tokens, unsigned *NumTokens) {
4841 if (Tokens)
4842 *Tokens = 0;
4843 if (NumTokens)
4844 *NumTokens = 0;
4845
4846 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4847 if (!CXXUnit || !Tokens || !NumTokens)
4848 return;
4849
4850 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4851
4852 SourceRange R = cxloc::translateCXSourceRange(Range);
4853 if (R.isInvalid())
4854 return;
4855
4856 SmallVector<CXToken, 32> CXTokens;
4857 getTokens(CXXUnit, R, CXTokens);
4858
4859 if (CXTokens.empty())
4860 return;
4861
4862 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4863 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4864 *NumTokens = CXTokens.size();
4865}
4866
4867void clang_disposeTokens(CXTranslationUnit TU,
4868 CXToken *Tokens, unsigned NumTokens) {
4869 free(Tokens);
4870}
4871
4872} // end: extern "C"
4873
4874//===----------------------------------------------------------------------===//
4875// Token annotation APIs.
4876//===----------------------------------------------------------------------===//
4877
4878typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
4879static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4880 CXCursor parent,
4881 CXClientData client_data);
4882static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
4883 CXClientData client_data);
4884
4885namespace {
4886class AnnotateTokensWorker {
4887 AnnotateTokensData &Annotated;
4888 CXToken *Tokens;
4889 CXCursor *Cursors;
4890 unsigned NumTokens;
4891 unsigned TokIdx;
4892 unsigned PreprocessingTokIdx;
4893 CursorVisitor AnnotateVis;
4894 SourceManager &SrcMgr;
4895 bool HasContextSensitiveKeywords;
4896
4897 struct PostChildrenInfo {
4898 CXCursor Cursor;
4899 SourceRange CursorRange;
4900 unsigned BeforeChildrenTokenIdx;
4901 };
4902 llvm::SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
4903
4904 bool MoreTokens() const { return TokIdx < NumTokens; }
4905 unsigned NextToken() const { return TokIdx; }
4906 void AdvanceToken() { ++TokIdx; }
4907 SourceLocation GetTokenLoc(unsigned tokI) {
4908 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4909 }
4910 bool isFunctionMacroToken(unsigned tokI) const {
4911 return Tokens[tokI].int_data[3] != 0;
4912 }
4913 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
4914 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4915 }
4916
4917 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
4918 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4919 SourceRange);
4920
4921public:
4922 AnnotateTokensWorker(AnnotateTokensData &annotated,
4923 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
4924 CXTranslationUnit tu, SourceRange RegionOfInterest)
4925 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
4926 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
4927 AnnotateVis(tu,
4928 AnnotateTokensVisitor, this,
4929 /*VisitPreprocessorLast=*/true,
4930 /*VisitIncludedEntities=*/false,
4931 RegionOfInterest,
4932 /*VisitDeclsOnly=*/false,
4933 AnnotateTokensPostChildrenVisitor),
4934 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4935 HasContextSensitiveKeywords(false) { }
4936
4937 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
4938 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
4939 bool postVisitChildren(CXCursor cursor);
4940 void AnnotateTokens();
4941
4942 /// \brief Determine whether the annotator saw any cursors that have
4943 /// context-sensitive keywords.
4944 bool hasContextSensitiveKeywords() const {
4945 return HasContextSensitiveKeywords;
4946 }
4947
4948 ~AnnotateTokensWorker() {
4949 assert(PostChildrenInfos.empty());
4950 }
4951};
4952}
4953
4954void AnnotateTokensWorker::AnnotateTokens() {
4955 // Walk the AST within the region of interest, annotating tokens
4956 // along the way.
4957 AnnotateVis.visitFileRegion();
4958
4959 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4960 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4961 if (Pos != Annotated.end() && !clang_isPreprocessing(Cursors[I].kind))
4962 Cursors[I] = Pos->second;
4963 }
4964
4965 // Finish up annotating any tokens left.
4966 if (!MoreTokens())
4967 return;
4968
4969 const CXCursor &C = clang_getNullCursor();
4970 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4971 if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4972 continue;
4973
4974 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4975 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
4976 }
4977}
4978
4979/// \brief It annotates and advances tokens with a cursor until the comparison
4980//// between the cursor location and the source range is the same as
4981/// \arg compResult.
4982///
4983/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4984/// Pass RangeOverlap to annotate tokens inside a range.
4985void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4986 RangeComparisonResult compResult,
4987 SourceRange range) {
4988 while (MoreTokens()) {
4989 const unsigned I = NextToken();
4990 if (isFunctionMacroToken(I))
4991 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
4992
4993 SourceLocation TokLoc = GetTokenLoc(I);
4994 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4995 Cursors[I] = updateC;
4996 AdvanceToken();
4997 continue;
4998 }
4999 break;
5000 }
5001}
5002
5003/// \brief Special annotation handling for macro argument tokens.
5004void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
5005 CXCursor updateC,
5006 RangeComparisonResult compResult,
5007 SourceRange range) {
5008 assert(MoreTokens());
5009 assert(isFunctionMacroToken(NextToken()) &&
5010 "Should be called only for macro arg tokens");
5011
5012 // This works differently than annotateAndAdvanceTokens; because expanded
5013 // macro arguments can have arbitrary translation-unit source order, we do not
5014 // advance the token index one by one until a token fails the range test.
5015 // We only advance once past all of the macro arg tokens if all of them
5016 // pass the range test. If one of them fails we keep the token index pointing
5017 // at the start of the macro arg tokens so that the failing token will be
5018 // annotated by a subsequent annotation try.
5019
5020 bool atLeastOneCompFail = false;
5021
5022 unsigned I = NextToken();
5023 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
5024 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
5025 if (TokLoc.isFileID())
5026 continue; // not macro arg token, it's parens or comma.
5027 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
5028 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
5029 Cursors[I] = updateC;
5030 } else
5031 atLeastOneCompFail = true;
5032 }
5033
5034 if (!atLeastOneCompFail)
5035 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
5036}
5037
5038enum CXChildVisitResult
5039AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
5040 CXSourceLocation Loc = clang_getCursorLocation(cursor);
5041 SourceRange cursorRange = getRawCursorExtent(cursor);
5042 if (cursorRange.isInvalid())
5043 return CXChildVisit_Recurse;
5044
5045 if (!HasContextSensitiveKeywords) {
5046 // Objective-C properties can have context-sensitive keywords.
5047 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
5048 if (ObjCPropertyDecl *Property
5049 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
5050 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
5051 }
5052 // Objective-C methods can have context-sensitive keywords.
5053 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
5054 cursor.kind == CXCursor_ObjCClassMethodDecl) {
5055 if (ObjCMethodDecl *Method
5056 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5057 if (Method->getObjCDeclQualifier())
5058 HasContextSensitiveKeywords = true;
5059 else {
5060 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
5061 PEnd = Method->param_end();
5062 P != PEnd; ++P) {
5063 if ((*P)->getObjCDeclQualifier()) {
5064 HasContextSensitiveKeywords = true;
5065 break;
5066 }
5067 }
5068 }
5069 }
5070 }
5071 // C++ methods can have context-sensitive keywords.
5072 else if (cursor.kind == CXCursor_CXXMethod) {
5073 if (CXXMethodDecl *Method
5074 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
5075 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
5076 HasContextSensitiveKeywords = true;
5077 }
5078 }
5079 // C++ classes can have context-sensitive keywords.
5080 else if (cursor.kind == CXCursor_StructDecl ||
5081 cursor.kind == CXCursor_ClassDecl ||
5082 cursor.kind == CXCursor_ClassTemplate ||
5083 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
5084 if (Decl *D = getCursorDecl(cursor))
5085 if (D->hasAttr<FinalAttr>())
5086 HasContextSensitiveKeywords = true;
5087 }
5088 }
5089
5090 if (clang_isPreprocessing(cursor.kind)) {
5091 // Items in the preprocessing record are kept separate from items in
5092 // declarations, so we keep a separate token index.
5093 unsigned SavedTokIdx = TokIdx;
5094 TokIdx = PreprocessingTokIdx;
5095
5096 // Skip tokens up until we catch up to the beginning of the preprocessing
5097 // entry.
5098 while (MoreTokens()) {
5099 const unsigned I = NextToken();
5100 SourceLocation TokLoc = GetTokenLoc(I);
5101 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5102 case RangeBefore:
5103 AdvanceToken();
5104 continue;
5105 case RangeAfter:
5106 case RangeOverlap:
5107 break;
5108 }
5109 break;
5110 }
5111
5112 // Look at all of the tokens within this range.
5113 while (MoreTokens()) {
5114 const unsigned I = NextToken();
5115 SourceLocation TokLoc = GetTokenLoc(I);
5116 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5117 case RangeBefore:
5118 llvm_unreachable("Infeasible");
5119 case RangeAfter:
5120 break;
5121 case RangeOverlap:
5122 Cursors[I] = cursor;
5123 AdvanceToken();
5124 // For macro expansions, just note where the beginning of the macro
5125 // expansion occurs.
5126 if (cursor.kind == CXCursor_MacroExpansion)
5127 break;
5128 continue;
5129 }
5130 break;
5131 }
5132
5133 // Save the preprocessing token index; restore the non-preprocessing
5134 // token index.
5135 PreprocessingTokIdx = TokIdx;
5136 TokIdx = SavedTokIdx;
5137 return CXChildVisit_Recurse;
5138 }
5139
5140 if (cursorRange.isInvalid())
5141 return CXChildVisit_Continue;
5142
5143 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
5144
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005145 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005146
5147 // If the location of the cursor occurs within a macro instantiation, record
5148 // the spelling location of the cursor in our annotation map. We can then
5149 // paper over the token labelings during a post-processing step to try and
5150 // get cursor mappings for tokens that are the *arguments* of a macro
5151 // instantiation.
5152 if (L.isMacroID()) {
5153 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
5154 // Only invalidate the old annotation if it isn't part of a preprocessing
5155 // directive. Here we assume that the default construction of CXCursor
5156 // results in CXCursor.kind being an initialized value (i.e., 0). If
5157 // this isn't the case, we can fix by doing lookup + insertion.
5158
5159 CXCursor &oldC = Annotated[rawEncoding];
5160 if (!clang_isPreprocessing(oldC.kind))
5161 oldC = cursor;
5162 }
5163
5164 const enum CXCursorKind K = clang_getCursorKind(parent);
5165 const CXCursor updateC =
5166 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
5167 ? clang_getNullCursor() : parent;
5168
5169 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
5170
5171 // Avoid having the cursor of an expression "overwrite" the annotation of the
5172 // variable declaration that it belongs to.
5173 // This can happen for C++ constructor expressions whose range generally
5174 // include the variable declaration, e.g.:
5175 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
5176 if (clang_isExpression(cursorK)) {
5177 Expr *E = getCursorExpr(cursor);
5178 if (Decl *D = getCursorParentDecl(cursor)) {
5179 const unsigned I = NextToken();
5180 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
5181 E->getLocStart() == D->getLocation() &&
5182 E->getLocStart() == GetTokenLoc(I)) {
5183 Cursors[I] = updateC;
5184 AdvanceToken();
5185 }
5186 }
5187 }
5188
5189 // Before recursing into the children keep some state that we are going
5190 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
5191 // extra work after the child nodes are visited.
5192 // Note that we don't call VisitChildren here to avoid traversing statements
5193 // code-recursively which can blow the stack.
5194
5195 PostChildrenInfo Info;
5196 Info.Cursor = cursor;
5197 Info.CursorRange = cursorRange;
5198 Info.BeforeChildrenTokenIdx = NextToken();
5199 PostChildrenInfos.push_back(Info);
5200
5201 return CXChildVisit_Recurse;
5202}
5203
5204bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
5205 if (PostChildrenInfos.empty())
5206 return false;
5207 const PostChildrenInfo &Info = PostChildrenInfos.back();
5208 if (!clang_equalCursors(Info.Cursor, cursor))
5209 return false;
5210
5211 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
5212 const unsigned AfterChildren = NextToken();
5213 SourceRange cursorRange = Info.CursorRange;
5214
5215 // Scan the tokens that are at the end of the cursor, but are not captured
5216 // but the child cursors.
5217 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
5218
5219 // Scan the tokens that are at the beginning of the cursor, but are not
5220 // capture by the child cursors.
5221 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5222 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5223 break;
5224
5225 Cursors[I] = cursor;
5226 }
5227
5228 PostChildrenInfos.pop_back();
5229 return false;
5230}
5231
5232static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5233 CXCursor parent,
5234 CXClientData client_data) {
5235 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5236}
5237
5238static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
5239 CXClientData client_data) {
5240 return static_cast<AnnotateTokensWorker*>(client_data)->
5241 postVisitChildren(cursor);
5242}
5243
5244namespace {
5245
5246/// \brief Uses the macro expansions in the preprocessing record to find
5247/// and mark tokens that are macro arguments. This info is used by the
5248/// AnnotateTokensWorker.
5249class MarkMacroArgTokensVisitor {
5250 SourceManager &SM;
5251 CXToken *Tokens;
5252 unsigned NumTokens;
5253 unsigned CurIdx;
5254
5255public:
5256 MarkMacroArgTokensVisitor(SourceManager &SM,
5257 CXToken *tokens, unsigned numTokens)
5258 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
5259
5260 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5261 if (cursor.kind != CXCursor_MacroExpansion)
5262 return CXChildVisit_Continue;
5263
Argyrios Kyrtzidis664b06f2013-01-07 19:16:25 +00005264 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005265 if (macroRange.getBegin() == macroRange.getEnd())
5266 return CXChildVisit_Continue; // it's not a function macro.
5267
5268 for (; CurIdx < NumTokens; ++CurIdx) {
5269 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5270 macroRange.getBegin()))
5271 break;
5272 }
5273
5274 if (CurIdx == NumTokens)
5275 return CXChildVisit_Break;
5276
5277 for (; CurIdx < NumTokens; ++CurIdx) {
5278 SourceLocation tokLoc = getTokenLoc(CurIdx);
5279 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5280 break;
5281
5282 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
5283 }
5284
5285 if (CurIdx == NumTokens)
5286 return CXChildVisit_Break;
5287
5288 return CXChildVisit_Continue;
5289 }
5290
5291private:
5292 SourceLocation getTokenLoc(unsigned tokI) {
5293 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5294 }
5295
5296 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
5297 // The third field is reserved and currently not used. Use it here
5298 // to mark macro arg expanded tokens with their expanded locations.
5299 Tokens[tokI].int_data[3] = loc.getRawEncoding();
5300 }
5301};
5302
5303} // end anonymous namespace
5304
5305static CXChildVisitResult
5306MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5307 CXClientData client_data) {
5308 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5309 parent);
5310}
5311
5312namespace {
5313 struct clang_annotateTokens_Data {
5314 CXTranslationUnit TU;
5315 ASTUnit *CXXUnit;
5316 CXToken *Tokens;
5317 unsigned NumTokens;
5318 CXCursor *Cursors;
5319 };
5320}
5321
5322static void annotatePreprocessorTokens(CXTranslationUnit TU,
5323 SourceRange RegionOfInterest,
5324 AnnotateTokensData &Annotated) {
5325 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5326
5327 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5328 std::pair<FileID, unsigned> BeginLocInfo
5329 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5330 std::pair<FileID, unsigned> EndLocInfo
5331 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5332
5333 if (BeginLocInfo.first != EndLocInfo.first)
5334 return;
5335
5336 StringRef Buffer;
5337 bool Invalid = false;
5338 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5339 if (Buffer.empty() || Invalid)
5340 return;
5341
5342 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
5343 CXXUnit->getASTContext().getLangOpts(),
5344 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5345 Buffer.end());
5346 Lex.SetCommentRetentionState(true);
5347
5348 // Lex tokens in raw mode until we hit the end of the range, to avoid
5349 // entering #includes or expanding macros.
5350 while (true) {
5351 Token Tok;
5352 Lex.LexFromRawLexer(Tok);
5353
5354 reprocess:
5355 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5356 // We have found a preprocessing directive. Gobble it up so that we
5357 // don't see it while preprocessing these tokens later, but keep track
5358 // of all of the token locations inside this preprocessing directive so
5359 // that we can annotate them appropriately.
5360 //
5361 // FIXME: Some simple tests here could identify macro definitions and
5362 // #undefs, to provide specific cursor kinds for those.
5363 SmallVector<SourceLocation, 32> Locations;
5364 do {
5365 Locations.push_back(Tok.getLocation());
5366 Lex.LexFromRawLexer(Tok);
5367 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5368
5369 using namespace cxcursor;
5370 CXCursor Cursor
5371 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5372 Locations.back()),
5373 TU);
5374 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5375 Annotated[Locations[I].getRawEncoding()] = Cursor;
5376 }
5377
5378 if (Tok.isAtStartOfLine())
5379 goto reprocess;
5380
5381 continue;
5382 }
5383
5384 if (Tok.is(tok::eof))
5385 break;
5386 }
5387}
5388
5389// This gets run a separate thread to avoid stack blowout.
5390static void clang_annotateTokensImpl(void *UserData) {
5391 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5392 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5393 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5394 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5395 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5396
5397 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
5398 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
5399 setThreadBackgroundPriority();
5400
5401 // Determine the region of interest, which contains all of the tokens.
5402 SourceRange RegionOfInterest;
5403 RegionOfInterest.setBegin(
5404 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5405 RegionOfInterest.setEnd(
5406 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5407 Tokens[NumTokens-1])));
5408
5409 // A mapping from the source locations found when re-lexing or traversing the
5410 // region of interest to the corresponding cursors.
5411 AnnotateTokensData Annotated;
5412
5413 // Relex the tokens within the source range to look for preprocessing
5414 // directives.
5415 annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
5416
5417 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5418 // Search and mark tokens that are macro argument expansions.
5419 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5420 Tokens, NumTokens);
5421 CursorVisitor MacroArgMarker(TU,
5422 MarkMacroArgTokensVisitorDelegate, &Visitor,
5423 /*VisitPreprocessorLast=*/true,
5424 /*VisitIncludedEntities=*/false,
5425 RegionOfInterest);
5426 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5427 }
5428
5429 // Annotate all of the source locations in the region of interest that map to
5430 // a specific cursor.
5431 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5432 TU, RegionOfInterest);
5433
5434 // FIXME: We use a ridiculous stack size here because the data-recursion
5435 // algorithm uses a large stack frame than the non-data recursive version,
5436 // and AnnotationTokensWorker currently transforms the data-recursion
5437 // algorithm back into a traditional recursion by explicitly calling
5438 // VisitChildren(). We will need to remove this explicit recursive call.
5439 W.AnnotateTokens();
5440
5441 // If we ran into any entities that involve context-sensitive keywords,
5442 // take another pass through the tokens to mark them as such.
5443 if (W.hasContextSensitiveKeywords()) {
5444 for (unsigned I = 0; I != NumTokens; ++I) {
5445 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5446 continue;
5447
5448 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5449 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5450 if (ObjCPropertyDecl *Property
5451 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5452 if (Property->getPropertyAttributesAsWritten() != 0 &&
5453 llvm::StringSwitch<bool>(II->getName())
5454 .Case("readonly", true)
5455 .Case("assign", true)
5456 .Case("unsafe_unretained", true)
5457 .Case("readwrite", true)
5458 .Case("retain", true)
5459 .Case("copy", true)
5460 .Case("nonatomic", true)
5461 .Case("atomic", true)
5462 .Case("getter", true)
5463 .Case("setter", true)
5464 .Case("strong", true)
5465 .Case("weak", true)
5466 .Default(false))
5467 Tokens[I].int_data[0] = CXToken_Keyword;
5468 }
5469 continue;
5470 }
5471
5472 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5473 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5474 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5475 if (llvm::StringSwitch<bool>(II->getName())
5476 .Case("in", true)
5477 .Case("out", true)
5478 .Case("inout", true)
5479 .Case("oneway", true)
5480 .Case("bycopy", true)
5481 .Case("byref", true)
5482 .Default(false))
5483 Tokens[I].int_data[0] = CXToken_Keyword;
5484 continue;
5485 }
5486
5487 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5488 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5489 Tokens[I].int_data[0] = CXToken_Keyword;
5490 continue;
5491 }
5492 }
5493 }
5494}
5495
5496extern "C" {
5497
5498void clang_annotateTokens(CXTranslationUnit TU,
5499 CXToken *Tokens, unsigned NumTokens,
5500 CXCursor *Cursors) {
5501
5502 if (NumTokens == 0 || !Tokens || !Cursors)
5503 return;
5504
5505 // Any token we don't specifically annotate will have a NULL cursor.
5506 CXCursor C = clang_getNullCursor();
5507 for (unsigned I = 0; I != NumTokens; ++I)
5508 Cursors[I] = C;
5509
5510 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5511 if (!CXXUnit)
5512 return;
5513
5514 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5515
5516 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
5517 llvm::CrashRecoveryContext CRC;
5518 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
5519 GetSafetyThreadStackSize() * 2)) {
5520 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5521 }
5522}
5523
5524} // end: extern "C"
5525
5526//===----------------------------------------------------------------------===//
5527// Operations for querying linkage of a cursor.
5528//===----------------------------------------------------------------------===//
5529
5530extern "C" {
5531CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
5532 if (!clang_isDeclaration(cursor.kind))
5533 return CXLinkage_Invalid;
5534
5535 Decl *D = cxcursor::getCursorDecl(cursor);
5536 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5537 switch (ND->getLinkage()) {
5538 case NoLinkage: return CXLinkage_NoLinkage;
5539 case InternalLinkage: return CXLinkage_Internal;
5540 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5541 case ExternalLinkage: return CXLinkage_External;
5542 };
5543
5544 return CXLinkage_Invalid;
5545}
5546} // end: extern "C"
5547
5548//===----------------------------------------------------------------------===//
5549// Operations for querying language of a cursor.
5550//===----------------------------------------------------------------------===//
5551
5552static CXLanguageKind getDeclLanguage(const Decl *D) {
5553 if (!D)
5554 return CXLanguage_C;
5555
5556 switch (D->getKind()) {
5557 default:
5558 break;
5559 case Decl::ImplicitParam:
5560 case Decl::ObjCAtDefsField:
5561 case Decl::ObjCCategory:
5562 case Decl::ObjCCategoryImpl:
5563 case Decl::ObjCCompatibleAlias:
5564 case Decl::ObjCImplementation:
5565 case Decl::ObjCInterface:
5566 case Decl::ObjCIvar:
5567 case Decl::ObjCMethod:
5568 case Decl::ObjCProperty:
5569 case Decl::ObjCPropertyImpl:
5570 case Decl::ObjCProtocol:
5571 return CXLanguage_ObjC;
5572 case Decl::CXXConstructor:
5573 case Decl::CXXConversion:
5574 case Decl::CXXDestructor:
5575 case Decl::CXXMethod:
5576 case Decl::CXXRecord:
5577 case Decl::ClassTemplate:
5578 case Decl::ClassTemplatePartialSpecialization:
5579 case Decl::ClassTemplateSpecialization:
5580 case Decl::Friend:
5581 case Decl::FriendTemplate:
5582 case Decl::FunctionTemplate:
5583 case Decl::LinkageSpec:
5584 case Decl::Namespace:
5585 case Decl::NamespaceAlias:
5586 case Decl::NonTypeTemplateParm:
5587 case Decl::StaticAssert:
5588 case Decl::TemplateTemplateParm:
5589 case Decl::TemplateTypeParm:
5590 case Decl::UnresolvedUsingTypename:
5591 case Decl::UnresolvedUsingValue:
5592 case Decl::Using:
5593 case Decl::UsingDirective:
5594 case Decl::UsingShadow:
5595 return CXLanguage_CPlusPlus;
5596 }
5597
5598 return CXLanguage_C;
5599}
5600
5601extern "C" {
5602
5603enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5604 if (clang_isDeclaration(cursor.kind))
5605 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
5606 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
5607 return CXAvailability_Available;
5608
5609 switch (D->getAvailability()) {
5610 case AR_Available:
5611 case AR_NotYetIntroduced:
5612 return CXAvailability_Available;
5613
5614 case AR_Deprecated:
5615 return CXAvailability_Deprecated;
5616
5617 case AR_Unavailable:
5618 return CXAvailability_NotAvailable;
5619 }
5620 }
5621
5622 return CXAvailability_Available;
5623}
5624
5625static CXVersion convertVersion(VersionTuple In) {
5626 CXVersion Out = { -1, -1, -1 };
5627 if (In.empty())
5628 return Out;
5629
5630 Out.Major = In.getMajor();
5631
5632 if (llvm::Optional<unsigned> Minor = In.getMinor())
5633 Out.Minor = *Minor;
5634 else
5635 return Out;
5636
5637 if (llvm::Optional<unsigned> Subminor = In.getSubminor())
5638 Out.Subminor = *Subminor;
5639
5640 return Out;
5641}
5642
5643int clang_getCursorPlatformAvailability(CXCursor cursor,
5644 int *always_deprecated,
5645 CXString *deprecated_message,
5646 int *always_unavailable,
5647 CXString *unavailable_message,
5648 CXPlatformAvailability *availability,
5649 int availability_size) {
5650 if (always_deprecated)
5651 *always_deprecated = 0;
5652 if (deprecated_message)
5653 *deprecated_message = cxstring::createCXString("", /*DupString=*/false);
5654 if (always_unavailable)
5655 *always_unavailable = 0;
5656 if (unavailable_message)
5657 *unavailable_message = cxstring::createCXString("", /*DupString=*/false);
5658
5659 if (!clang_isDeclaration(cursor.kind))
5660 return 0;
5661
5662 Decl *D = cxcursor::getCursorDecl(cursor);
5663 if (!D)
5664 return 0;
5665
5666 int N = 0;
5667 for (Decl::attr_iterator A = D->attr_begin(), AEnd = D->attr_end(); A != AEnd;
5668 ++A) {
5669 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
5670 if (always_deprecated)
5671 *always_deprecated = 1;
5672 if (deprecated_message)
5673 *deprecated_message = cxstring::createCXString(Deprecated->getMessage());
5674 continue;
5675 }
5676
5677 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
5678 if (always_unavailable)
5679 *always_unavailable = 1;
5680 if (unavailable_message) {
5681 *unavailable_message
5682 = cxstring::createCXString(Unavailable->getMessage());
5683 }
5684 continue;
5685 }
5686
5687 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(*A)) {
5688 if (N < availability_size) {
5689 availability[N].Platform
5690 = cxstring::createCXString(Avail->getPlatform()->getName());
5691 availability[N].Introduced = convertVersion(Avail->getIntroduced());
5692 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
5693 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
5694 availability[N].Unavailable = Avail->getUnavailable();
5695 availability[N].Message = cxstring::createCXString(Avail->getMessage());
5696 }
5697 ++N;
5698 }
5699 }
5700
5701 return N;
5702}
5703
5704void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
5705 clang_disposeString(availability->Platform);
5706 clang_disposeString(availability->Message);
5707}
5708
5709CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5710 if (clang_isDeclaration(cursor.kind))
5711 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5712
5713 return CXLanguage_Invalid;
5714}
5715
5716 /// \brief If the given cursor is the "templated" declaration
5717 /// descibing a class or function template, return the class or
5718 /// function template.
5719static Decl *maybeGetTemplateCursor(Decl *D) {
5720 if (!D)
5721 return 0;
5722
5723 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5724 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5725 return FunTmpl;
5726
5727 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5728 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5729 return ClassTmpl;
5730
5731 return D;
5732}
5733
5734CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5735 if (clang_isDeclaration(cursor.kind)) {
5736 if (Decl *D = getCursorDecl(cursor)) {
5737 DeclContext *DC = D->getDeclContext();
5738 if (!DC)
5739 return clang_getNullCursor();
5740
5741 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5742 getCursorTU(cursor));
5743 }
5744 }
5745
5746 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5747 if (Decl *D = getCursorDecl(cursor))
5748 return MakeCXCursor(D, getCursorTU(cursor));
5749 }
5750
5751 return clang_getNullCursor();
5752}
5753
5754CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5755 if (clang_isDeclaration(cursor.kind)) {
5756 if (Decl *D = getCursorDecl(cursor)) {
5757 DeclContext *DC = D->getLexicalDeclContext();
5758 if (!DC)
5759 return clang_getNullCursor();
5760
5761 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5762 getCursorTU(cursor));
5763 }
5764 }
5765
5766 // FIXME: Note that we can't easily compute the lexical context of a
5767 // statement or expression, so we return nothing.
5768 return clang_getNullCursor();
5769}
5770
5771CXFile clang_getIncludedFile(CXCursor cursor) {
5772 if (cursor.kind != CXCursor_InclusionDirective)
5773 return 0;
5774
5775 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5776 return (void *)ID->getFile();
5777}
5778
5779CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
5780 if (!clang_isDeclaration(C.kind))
5781 return clang_getNullRange();
5782
5783 const Decl *D = getCursorDecl(C);
5784 ASTContext &Context = getCursorContext(C);
5785 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
5786 if (!RC)
5787 return clang_getNullRange();
5788
5789 return cxloc::translateSourceRange(Context, RC->getSourceRange());
5790}
5791
5792CXString clang_Cursor_getRawCommentText(CXCursor C) {
5793 if (!clang_isDeclaration(C.kind))
5794 return createCXString((const char *) NULL);
5795
5796 const Decl *D = getCursorDecl(C);
5797 ASTContext &Context = getCursorContext(C);
5798 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
5799 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
5800 StringRef();
5801
5802 // Don't duplicate the string because RawText points directly into source
5803 // code.
5804 return createCXString(RawText, false);
5805}
5806
5807CXString clang_Cursor_getBriefCommentText(CXCursor C) {
5808 if (!clang_isDeclaration(C.kind))
5809 return createCXString((const char *) NULL);
5810
5811 const Decl *D = getCursorDecl(C);
5812 const ASTContext &Context = getCursorContext(C);
5813 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
5814
5815 if (RC) {
5816 StringRef BriefText = RC->getBriefText(Context);
5817
5818 // Don't duplicate the string because RawComment ensures that this memory
5819 // will not go away.
5820 return createCXString(BriefText, false);
5821 }
5822
5823 return createCXString((const char *) NULL);
5824}
5825
5826CXComment clang_Cursor_getParsedComment(CXCursor C) {
5827 if (!clang_isDeclaration(C.kind))
5828 return cxcomment::createCXComment(NULL, NULL);
5829
5830 const Decl *D = getCursorDecl(C);
5831 const ASTContext &Context = getCursorContext(C);
5832 const comments::FullComment *FC = Context.getCommentForDecl(D, /*PP=*/ NULL);
5833
5834 return cxcomment::createCXComment(FC, getCursorTU(C));
5835}
5836
5837CXModule clang_Cursor_getModule(CXCursor C) {
5838 if (C.kind == CXCursor_ModuleImportDecl) {
5839 if (ImportDecl *ImportD = dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
5840 return ImportD->getImportedModule();
5841 }
5842
5843 return 0;
5844}
5845
5846CXModule clang_Module_getParent(CXModule CXMod) {
5847 if (!CXMod)
5848 return 0;
5849 Module *Mod = static_cast<Module*>(CXMod);
5850 return Mod->Parent;
5851}
5852
5853CXString clang_Module_getName(CXModule CXMod) {
5854 if (!CXMod)
5855 return createCXString("");
5856 Module *Mod = static_cast<Module*>(CXMod);
5857 return createCXString(Mod->Name);
5858}
5859
5860CXString clang_Module_getFullName(CXModule CXMod) {
5861 if (!CXMod)
5862 return createCXString("");
5863 Module *Mod = static_cast<Module*>(CXMod);
5864 return createCXString(Mod->getFullModuleName());
5865}
5866
5867unsigned clang_Module_getNumTopLevelHeaders(CXModule CXMod) {
5868 if (!CXMod)
5869 return 0;
5870 Module *Mod = static_cast<Module*>(CXMod);
5871 return Mod->TopHeaders.size();
5872}
5873
5874CXFile clang_Module_getTopLevelHeader(CXModule CXMod, unsigned Index) {
5875 if (!CXMod)
5876 return 0;
5877 Module *Mod = static_cast<Module*>(CXMod);
5878
5879 if (Index < Mod->TopHeaders.size())
5880 return const_cast<FileEntry *>(Mod->TopHeaders[Index]);
5881
5882 return 0;
5883}
5884
5885} // end: extern "C"
5886
5887//===----------------------------------------------------------------------===//
5888// C++ AST instrospection.
5889//===----------------------------------------------------------------------===//
5890
5891extern "C" {
5892unsigned clang_CXXMethod_isStatic(CXCursor C) {
5893 if (!clang_isDeclaration(C.kind))
5894 return 0;
5895
5896 CXXMethodDecl *Method = 0;
5897 Decl *D = cxcursor::getCursorDecl(C);
5898 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5899 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5900 else
5901 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5902 return (Method && Method->isStatic()) ? 1 : 0;
5903}
5904
5905unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5906 if (!clang_isDeclaration(C.kind))
5907 return 0;
5908
5909 CXXMethodDecl *Method = 0;
5910 Decl *D = cxcursor::getCursorDecl(C);
5911 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5912 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5913 else
5914 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5915 return (Method && Method->isVirtual()) ? 1 : 0;
5916}
5917} // end: extern "C"
5918
5919//===----------------------------------------------------------------------===//
5920// Attribute introspection.
5921//===----------------------------------------------------------------------===//
5922
5923extern "C" {
5924CXType clang_getIBOutletCollectionType(CXCursor C) {
5925 if (C.kind != CXCursor_IBOutletCollectionAttr)
5926 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
5927
5928 IBOutletCollectionAttr *A =
5929 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5930
5931 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
5932}
5933} // end: extern "C"
5934
5935//===----------------------------------------------------------------------===//
5936// Inspecting memory usage.
5937//===----------------------------------------------------------------------===//
5938
5939typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
5940
5941static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5942 enum CXTUResourceUsageKind k,
5943 unsigned long amount) {
5944 CXTUResourceUsageEntry entry = { k, amount };
5945 entries.push_back(entry);
5946}
5947
5948extern "C" {
5949
5950const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
5951 const char *str = "";
5952 switch (kind) {
5953 case CXTUResourceUsage_AST:
5954 str = "ASTContext: expressions, declarations, and types";
5955 break;
5956 case CXTUResourceUsage_Identifiers:
5957 str = "ASTContext: identifiers";
5958 break;
5959 case CXTUResourceUsage_Selectors:
5960 str = "ASTContext: selectors";
5961 break;
5962 case CXTUResourceUsage_GlobalCompletionResults:
5963 str = "Code completion: cached global results";
5964 break;
5965 case CXTUResourceUsage_SourceManagerContentCache:
5966 str = "SourceManager: content cache allocator";
5967 break;
5968 case CXTUResourceUsage_AST_SideTables:
5969 str = "ASTContext: side tables";
5970 break;
5971 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5972 str = "SourceManager: malloc'ed memory buffers";
5973 break;
5974 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5975 str = "SourceManager: mmap'ed memory buffers";
5976 break;
5977 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5978 str = "ExternalASTSource: malloc'ed memory buffers";
5979 break;
5980 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5981 str = "ExternalASTSource: mmap'ed memory buffers";
5982 break;
5983 case CXTUResourceUsage_Preprocessor:
5984 str = "Preprocessor: malloc'ed memory";
5985 break;
5986 case CXTUResourceUsage_PreprocessingRecord:
5987 str = "Preprocessor: PreprocessingRecord";
5988 break;
5989 case CXTUResourceUsage_SourceManager_DataStructures:
5990 str = "SourceManager: data structures and tables";
5991 break;
5992 case CXTUResourceUsage_Preprocessor_HeaderSearch:
5993 str = "Preprocessor: header search tables";
5994 break;
5995 }
5996 return str;
5997}
5998
5999CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
6000 if (!TU) {
6001 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
6002 return usage;
6003 }
6004
6005 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
6006 OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
6007 ASTContext &astContext = astUnit->getASTContext();
6008
6009 // How much memory is used by AST nodes and types?
6010 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
6011 (unsigned long) astContext.getASTAllocatedMemory());
6012
6013 // How much memory is used by identifiers?
6014 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
6015 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
6016
6017 // How much memory is used for selectors?
6018 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
6019 (unsigned long) astContext.Selectors.getTotalMemory());
6020
6021 // How much memory is used by ASTContext's side tables?
6022 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
6023 (unsigned long) astContext.getSideTableAllocatedMemory());
6024
6025 // How much memory is used for caching global code completion results?
6026 unsigned long completionBytes = 0;
6027 if (GlobalCodeCompletionAllocator *completionAllocator =
6028 astUnit->getCachedCompletionAllocator().getPtr()) {
6029 completionBytes = completionAllocator->getTotalMemory();
6030 }
6031 createCXTUResourceUsageEntry(*entries,
6032 CXTUResourceUsage_GlobalCompletionResults,
6033 completionBytes);
6034
6035 // How much memory is being used by SourceManager's content cache?
6036 createCXTUResourceUsageEntry(*entries,
6037 CXTUResourceUsage_SourceManagerContentCache,
6038 (unsigned long) astContext.getSourceManager().getContentCacheSize());
6039
6040 // How much memory is being used by the MemoryBuffer's in SourceManager?
6041 const SourceManager::MemoryBufferSizes &srcBufs =
6042 astUnit->getSourceManager().getMemoryBufferSizes();
6043
6044 createCXTUResourceUsageEntry(*entries,
6045 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
6046 (unsigned long) srcBufs.malloc_bytes);
6047 createCXTUResourceUsageEntry(*entries,
6048 CXTUResourceUsage_SourceManager_Membuffer_MMap,
6049 (unsigned long) srcBufs.mmap_bytes);
6050 createCXTUResourceUsageEntry(*entries,
6051 CXTUResourceUsage_SourceManager_DataStructures,
6052 (unsigned long) astContext.getSourceManager()
6053 .getDataStructureSizes());
6054
6055 // How much memory is being used by the ExternalASTSource?
6056 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
6057 const ExternalASTSource::MemoryBufferSizes &sizes =
6058 esrc->getMemoryBufferSizes();
6059
6060 createCXTUResourceUsageEntry(*entries,
6061 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
6062 (unsigned long) sizes.malloc_bytes);
6063 createCXTUResourceUsageEntry(*entries,
6064 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
6065 (unsigned long) sizes.mmap_bytes);
6066 }
6067
6068 // How much memory is being used by the Preprocessor?
6069 Preprocessor &pp = astUnit->getPreprocessor();
6070 createCXTUResourceUsageEntry(*entries,
6071 CXTUResourceUsage_Preprocessor,
6072 pp.getTotalMemory());
6073
6074 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
6075 createCXTUResourceUsageEntry(*entries,
6076 CXTUResourceUsage_PreprocessingRecord,
6077 pRec->getTotalMemory());
6078 }
6079
6080 createCXTUResourceUsageEntry(*entries,
6081 CXTUResourceUsage_Preprocessor_HeaderSearch,
6082 pp.getHeaderSearchInfo().getTotalMemory());
6083
6084 CXTUResourceUsage usage = { (void*) entries.get(),
6085 (unsigned) entries->size(),
6086 entries->size() ? &(*entries)[0] : 0 };
6087 entries.take();
6088 return usage;
6089}
6090
6091void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
6092 if (usage.data)
6093 delete (MemUsageEntries*) usage.data;
6094}
6095
6096} // end extern "C"
6097
6098void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
6099 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
6100 for (unsigned I = 0; I != Usage.numEntries; ++I)
6101 fprintf(stderr, " %s: %lu\n",
6102 clang_getTUResourceUsageName(Usage.entries[I].kind),
6103 Usage.entries[I].amount);
6104
6105 clang_disposeCXTUResourceUsage(Usage);
6106}
6107
6108//===----------------------------------------------------------------------===//
6109// Misc. utility functions.
6110//===----------------------------------------------------------------------===//
6111
6112/// Default to using an 8 MB stack size on "safety" threads.
6113static unsigned SafetyStackThreadSize = 8 << 20;
6114
6115namespace clang {
6116
6117bool RunSafely(llvm::CrashRecoveryContext &CRC,
6118 void (*Fn)(void*), void *UserData,
6119 unsigned Size) {
6120 if (!Size)
6121 Size = GetSafetyThreadStackSize();
6122 if (Size)
6123 return CRC.RunSafelyOnThread(Fn, UserData, Size);
6124 return CRC.RunSafely(Fn, UserData);
6125}
6126
6127unsigned GetSafetyThreadStackSize() {
6128 return SafetyStackThreadSize;
6129}
6130
6131void SetSafetyThreadStackSize(unsigned Value) {
6132 SafetyStackThreadSize = Value;
6133}
6134
6135}
6136
6137void clang::setThreadBackgroundPriority() {
6138 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
6139 return;
6140
6141 // FIXME: Move to llvm/Support and make it cross-platform.
6142#ifdef __APPLE__
6143 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
6144#endif
6145}
6146
6147void cxindex::printDiagsToStderr(ASTUnit *Unit) {
6148 if (!Unit)
6149 return;
6150
6151 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
6152 DEnd = Unit->stored_diag_end();
6153 D != DEnd; ++D) {
6154 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOpts());
6155 CXString Msg = clang_formatDiagnostic(&Diag,
6156 clang_defaultDiagnosticDisplayOptions());
6157 fprintf(stderr, "%s\n", clang_getCString(Msg));
6158 clang_disposeString(Msg);
6159 }
6160#ifdef LLVM_ON_WIN32
6161 // On Windows, force a flush, since there may be multiple copies of
6162 // stderr and stdout in the file system, all with different buffers
6163 // but writing to the same device.
6164 fflush(stderr);
6165#endif
6166}
6167
Argyrios Kyrtzidis664b06f2013-01-07 19:16:25 +00006168MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
6169 SourceLocation MacroDefLoc,
6170 CXTranslationUnit TU){
6171 if (MacroDefLoc.isInvalid() || !TU)
6172 return 0;
6173
6174 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
6175 Preprocessor &PP = Unit->getPreprocessor();
6176 if (!II.hadMacroDefinition())
6177 return 0;
6178
6179 MacroInfo *MI = PP.getMacroInfoHistory(const_cast<IdentifierInfo*>(&II));
6180 while (MI) {
6181 if (MacroDefLoc == MI->getDefinitionLoc())
6182 return MI;
6183 MI = MI->getPreviousDefinition();
6184 }
6185
6186 return 0;
6187}
6188
6189MacroInfo *cxindex::getMacroInfo(MacroDefinition *MacroDef,
6190 CXTranslationUnit TU) {
6191 if (!MacroDef || !TU)
6192 return 0;
6193 const IdentifierInfo *II = MacroDef->getName();
6194 if (!II)
6195 return 0;
6196
6197 return getMacroInfo(*II, MacroDef->getLocation(), TU);
6198}
6199
6200MacroDefinition *cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI,
6201 const Token &Tok,
6202 CXTranslationUnit TU) {
6203 if (!MI || !TU)
6204 return 0;
6205 if (Tok.isNot(tok::raw_identifier))
6206 return 0;
6207
6208 if (MI->getNumTokens() == 0)
6209 return 0;
6210 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
6211 MI->getDefinitionEndLoc());
6212 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
6213
6214 // Check that the token is inside the definition and not its argument list.
6215 SourceManager &SM = Unit->getSourceManager();
6216 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
6217 return 0;
6218 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
6219 return 0;
6220
6221 Preprocessor &PP = Unit->getPreprocessor();
6222 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
6223 if (!PPRec)
6224 return 0;
6225
6226 StringRef Name(Tok.getRawIdentifierData(), Tok.getLength());
6227 IdentifierInfo &II = PP.getIdentifierTable().get(Name);
6228 if (!II.hadMacroDefinition())
6229 return 0;
6230
6231 // Check that the identifier is not one of the macro arguments.
6232 if (std::find(MI->arg_begin(), MI->arg_end(), &II) != MI->arg_end())
6233 return 0;
6234
6235 MacroInfo *InnerMI = PP.getMacroInfoHistory(&II);
6236 if (!InnerMI)
6237 return 0;
6238
6239 return PPRec->findMacroDefinition(InnerMI);
6240}
6241
6242MacroDefinition *cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI,
6243 SourceLocation Loc,
6244 CXTranslationUnit TU) {
6245 if (Loc.isInvalid() || !MI || !TU)
6246 return 0;
6247
6248 if (MI->getNumTokens() == 0)
6249 return 0;
6250 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
6251 Preprocessor &PP = Unit->getPreprocessor();
6252 if (!PP.getPreprocessingRecord())
6253 return 0;
6254 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
6255 Token Tok;
6256 if (PP.getRawToken(Loc, Tok))
6257 return 0;
6258
6259 return checkForMacroInMacroDefinition(MI, Tok, TU);
6260}
6261
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006262extern "C" {
6263
6264CXString clang_getClangVersion() {
6265 return createCXString(getClangFullVersion());
6266}
6267
6268} // end: extern "C"
6269