blob: 8b29bb4d7391655b15a382e477b3938b54d449e5 [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) {
Argyrios Kyrtzidisd1d9df62013-01-08 18:23:28 +00003865 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
3866 // can't set consistently. For example, when visiting a DeclStmt we will set
3867 // it but we don't set it on the result of clang_getCursorDefinition for
3868 // a reference of the same declaration.
3869 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
3870 // when visiting a DeclStmt currently, the AST should be enhanced to be able
3871 // to provide that kind of info.
3872 if (clang_isDeclaration(X.kind))
3873 X.data[1] = 0;
3874 if (clang_isDeclaration(Y.kind))
3875 Y.data[1] = 0;
3876
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003877 return X == Y;
3878}
3879
3880unsigned clang_hashCursor(CXCursor C) {
3881 unsigned Index = 0;
3882 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3883 Index = 1;
3884
3885 return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3886 std::make_pair(C.kind, C.data[Index]));
3887}
3888
3889unsigned clang_isInvalid(enum CXCursorKind K) {
3890 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3891}
3892
3893unsigned clang_isDeclaration(enum CXCursorKind K) {
3894 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
3895 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
3896}
3897
3898unsigned clang_isReference(enum CXCursorKind K) {
3899 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3900}
3901
3902unsigned clang_isExpression(enum CXCursorKind K) {
3903 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3904}
3905
3906unsigned clang_isStatement(enum CXCursorKind K) {
3907 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3908}
3909
3910unsigned clang_isAttribute(enum CXCursorKind K) {
3911 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3912}
3913
3914unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3915 return K == CXCursor_TranslationUnit;
3916}
3917
3918unsigned clang_isPreprocessing(enum CXCursorKind K) {
3919 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3920}
3921
3922unsigned clang_isUnexposed(enum CXCursorKind K) {
3923 switch (K) {
3924 case CXCursor_UnexposedDecl:
3925 case CXCursor_UnexposedExpr:
3926 case CXCursor_UnexposedStmt:
3927 case CXCursor_UnexposedAttr:
3928 return true;
3929 default:
3930 return false;
3931 }
3932}
3933
3934CXCursorKind clang_getCursorKind(CXCursor C) {
3935 return C.kind;
3936}
3937
3938CXSourceLocation clang_getCursorLocation(CXCursor C) {
3939 if (clang_isReference(C.kind)) {
3940 switch (C.kind) {
3941 case CXCursor_ObjCSuperClassRef: {
3942 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3943 = getCursorObjCSuperClassRef(C);
3944 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3945 }
3946
3947 case CXCursor_ObjCProtocolRef: {
3948 std::pair<ObjCProtocolDecl *, SourceLocation> P
3949 = getCursorObjCProtocolRef(C);
3950 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3951 }
3952
3953 case CXCursor_ObjCClassRef: {
3954 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3955 = getCursorObjCClassRef(C);
3956 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3957 }
3958
3959 case CXCursor_TypeRef: {
3960 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
3961 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3962 }
3963
3964 case CXCursor_TemplateRef: {
3965 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3966 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3967 }
3968
3969 case CXCursor_NamespaceRef: {
3970 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3971 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3972 }
3973
3974 case CXCursor_MemberRef: {
3975 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3976 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3977 }
3978
3979 case CXCursor_VariableRef: {
3980 std::pair<VarDecl *, SourceLocation> P = getCursorVariableRef(C);
3981 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3982 }
3983
3984 case CXCursor_CXXBaseSpecifier: {
3985 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3986 if (!BaseSpec)
3987 return clang_getNullLocation();
3988
3989 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3990 return cxloc::translateSourceLocation(getCursorContext(C),
3991 TSInfo->getTypeLoc().getBeginLoc());
3992
3993 return cxloc::translateSourceLocation(getCursorContext(C),
3994 BaseSpec->getLocStart());
3995 }
3996
3997 case CXCursor_LabelRef: {
3998 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3999 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
4000 }
4001
4002 case CXCursor_OverloadedDeclRef:
4003 return cxloc::translateSourceLocation(getCursorContext(C),
4004 getCursorOverloadedDeclRef(C).second);
4005
4006 default:
4007 // FIXME: Need a way to enumerate all non-reference cases.
4008 llvm_unreachable("Missed a reference kind");
4009 }
4010 }
4011
4012 if (clang_isExpression(C.kind))
4013 return cxloc::translateSourceLocation(getCursorContext(C),
4014 getLocationFromExpr(getCursorExpr(C)));
4015
4016 if (clang_isStatement(C.kind))
4017 return cxloc::translateSourceLocation(getCursorContext(C),
4018 getCursorStmt(C)->getLocStart());
4019
4020 if (C.kind == CXCursor_PreprocessingDirective) {
4021 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
4022 return cxloc::translateSourceLocation(getCursorContext(C), L);
4023 }
4024
4025 if (C.kind == CXCursor_MacroExpansion) {
4026 SourceLocation L
Argyrios Kyrtzidis664b06f2013-01-07 19:16:25 +00004027 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004028 return cxloc::translateSourceLocation(getCursorContext(C), L);
4029 }
4030
4031 if (C.kind == CXCursor_MacroDefinition) {
4032 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
4033 return cxloc::translateSourceLocation(getCursorContext(C), L);
4034 }
4035
4036 if (C.kind == CXCursor_InclusionDirective) {
4037 SourceLocation L
4038 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
4039 return cxloc::translateSourceLocation(getCursorContext(C), L);
4040 }
4041
4042 if (!clang_isDeclaration(C.kind))
4043 return clang_getNullLocation();
4044
4045 Decl *D = getCursorDecl(C);
4046 if (!D)
4047 return clang_getNullLocation();
4048
4049 SourceLocation Loc = D->getLocation();
4050 // FIXME: Multiple variables declared in a single declaration
4051 // currently lack the information needed to correctly determine their
4052 // ranges when accounting for the type-specifier. We use context
4053 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4054 // and if so, whether it is the first decl.
4055 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4056 if (!cxcursor::isFirstInDeclGroup(C))
4057 Loc = VD->getLocation();
4058 }
4059
4060 // For ObjC methods, give the start location of the method name.
4061 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4062 Loc = MD->getSelectorStartLoc();
4063
4064 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
4065}
4066
4067} // end extern "C"
4068
4069CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
4070 assert(TU);
4071
4072 // Guard against an invalid SourceLocation, or we may assert in one
4073 // of the following calls.
4074 if (SLoc.isInvalid())
4075 return clang_getNullCursor();
4076
4077 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4078
4079 // Translate the given source location to make it point at the beginning of
4080 // the token under the cursor.
4081 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
4082 CXXUnit->getASTContext().getLangOpts());
4083
4084 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
4085 if (SLoc.isValid()) {
4086 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
4087 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
4088 /*VisitPreprocessorLast=*/true,
4089 /*VisitIncludedEntities=*/false,
4090 SourceLocation(SLoc));
4091 CursorVis.visitFileRegion();
4092 }
4093
4094 return Result;
4095}
4096
4097static SourceRange getRawCursorExtent(CXCursor C) {
4098 if (clang_isReference(C.kind)) {
4099 switch (C.kind) {
4100 case CXCursor_ObjCSuperClassRef:
4101 return getCursorObjCSuperClassRef(C).second;
4102
4103 case CXCursor_ObjCProtocolRef:
4104 return getCursorObjCProtocolRef(C).second;
4105
4106 case CXCursor_ObjCClassRef:
4107 return getCursorObjCClassRef(C).second;
4108
4109 case CXCursor_TypeRef:
4110 return getCursorTypeRef(C).second;
4111
4112 case CXCursor_TemplateRef:
4113 return getCursorTemplateRef(C).second;
4114
4115 case CXCursor_NamespaceRef:
4116 return getCursorNamespaceRef(C).second;
4117
4118 case CXCursor_MemberRef:
4119 return getCursorMemberRef(C).second;
4120
4121 case CXCursor_CXXBaseSpecifier:
4122 return getCursorCXXBaseSpecifier(C)->getSourceRange();
4123
4124 case CXCursor_LabelRef:
4125 return getCursorLabelRef(C).second;
4126
4127 case CXCursor_OverloadedDeclRef:
4128 return getCursorOverloadedDeclRef(C).second;
4129
4130 case CXCursor_VariableRef:
4131 return getCursorVariableRef(C).second;
4132
4133 default:
4134 // FIXME: Need a way to enumerate all non-reference cases.
4135 llvm_unreachable("Missed a reference kind");
4136 }
4137 }
4138
4139 if (clang_isExpression(C.kind))
4140 return getCursorExpr(C)->getSourceRange();
4141
4142 if (clang_isStatement(C.kind))
4143 return getCursorStmt(C)->getSourceRange();
4144
4145 if (clang_isAttribute(C.kind))
4146 return getCursorAttr(C)->getRange();
4147
4148 if (C.kind == CXCursor_PreprocessingDirective)
4149 return cxcursor::getCursorPreprocessingDirective(C);
4150
4151 if (C.kind == CXCursor_MacroExpansion) {
4152 ASTUnit *TU = getCursorASTUnit(C);
Argyrios Kyrtzidis664b06f2013-01-07 19:16:25 +00004153 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004154 return TU->mapRangeFromPreamble(Range);
4155 }
4156
4157 if (C.kind == CXCursor_MacroDefinition) {
4158 ASTUnit *TU = getCursorASTUnit(C);
4159 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
4160 return TU->mapRangeFromPreamble(Range);
4161 }
4162
4163 if (C.kind == CXCursor_InclusionDirective) {
4164 ASTUnit *TU = getCursorASTUnit(C);
4165 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
4166 return TU->mapRangeFromPreamble(Range);
4167 }
4168
4169 if (C.kind == CXCursor_TranslationUnit) {
4170 ASTUnit *TU = getCursorASTUnit(C);
4171 FileID MainID = TU->getSourceManager().getMainFileID();
4172 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
4173 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
4174 return SourceRange(Start, End);
4175 }
4176
4177 if (clang_isDeclaration(C.kind)) {
4178 Decl *D = cxcursor::getCursorDecl(C);
4179 if (!D)
4180 return SourceRange();
4181
4182 SourceRange R = D->getSourceRange();
4183 // FIXME: Multiple variables declared in a single declaration
4184 // currently lack the information needed to correctly determine their
4185 // ranges when accounting for the type-specifier. We use context
4186 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4187 // and if so, whether it is the first decl.
4188 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4189 if (!cxcursor::isFirstInDeclGroup(C))
4190 R.setBegin(VD->getLocation());
4191 }
4192 return R;
4193 }
4194 return SourceRange();
4195}
4196
4197/// \brief Retrieves the "raw" cursor extent, which is then extended to include
4198/// the decl-specifier-seq for declarations.
4199static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
4200 if (clang_isDeclaration(C.kind)) {
4201 Decl *D = cxcursor::getCursorDecl(C);
4202 if (!D)
4203 return SourceRange();
4204
4205 SourceRange R = D->getSourceRange();
4206
4207 // Adjust the start of the location for declarations preceded by
4208 // declaration specifiers.
4209 SourceLocation StartLoc;
4210 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4211 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4212 StartLoc = TI->getTypeLoc().getLocStart();
4213 } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4214 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4215 StartLoc = TI->getTypeLoc().getLocStart();
4216 }
4217
4218 if (StartLoc.isValid() && R.getBegin().isValid() &&
4219 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4220 R.setBegin(StartLoc);
4221
4222 // FIXME: Multiple variables declared in a single declaration
4223 // currently lack the information needed to correctly determine their
4224 // ranges when accounting for the type-specifier. We use context
4225 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4226 // and if so, whether it is the first decl.
4227 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4228 if (!cxcursor::isFirstInDeclGroup(C))
4229 R.setBegin(VD->getLocation());
4230 }
4231
4232 return R;
4233 }
4234
4235 return getRawCursorExtent(C);
4236}
4237
4238extern "C" {
4239
4240CXSourceRange clang_getCursorExtent(CXCursor C) {
4241 SourceRange R = getRawCursorExtent(C);
4242 if (R.isInvalid())
4243 return clang_getNullRange();
4244
4245 return cxloc::translateSourceRange(getCursorContext(C), R);
4246}
4247
4248CXCursor clang_getCursorReferenced(CXCursor C) {
4249 if (clang_isInvalid(C.kind))
4250 return clang_getNullCursor();
4251
4252 CXTranslationUnit tu = getCursorTU(C);
4253 if (clang_isDeclaration(C.kind)) {
4254 Decl *D = getCursorDecl(C);
4255 if (!D)
4256 return clang_getNullCursor();
4257 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
4258 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
4259 if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
4260 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4261 return MakeCXCursor(Property, tu);
4262
4263 return C;
4264 }
4265
4266 if (clang_isExpression(C.kind)) {
4267 Expr *E = getCursorExpr(C);
4268 Decl *D = getDeclFromExpr(E);
4269 if (D) {
4270 CXCursor declCursor = MakeCXCursor(D, tu);
4271 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4272 declCursor);
4273 return declCursor;
4274 }
4275
4276 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
4277 return MakeCursorOverloadedDeclRef(Ovl, tu);
4278
4279 return clang_getNullCursor();
4280 }
4281
4282 if (clang_isStatement(C.kind)) {
4283 Stmt *S = getCursorStmt(C);
4284 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
4285 if (LabelDecl *label = Goto->getLabel())
4286 if (LabelStmt *labelS = label->getStmt())
4287 return MakeCXCursor(labelS, getCursorDecl(C), tu);
4288
4289 return clang_getNullCursor();
4290 }
4291
4292 if (C.kind == CXCursor_MacroExpansion) {
Argyrios Kyrtzidis664b06f2013-01-07 19:16:25 +00004293 if (MacroDefinition *Def = getCursorMacroExpansion(C).getDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004294 return MakeMacroDefinitionCursor(Def, tu);
4295 }
4296
4297 if (!clang_isReference(C.kind))
4298 return clang_getNullCursor();
4299
4300 switch (C.kind) {
4301 case CXCursor_ObjCSuperClassRef:
4302 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
4303
4304 case CXCursor_ObjCProtocolRef: {
4305 ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
4306 if (ObjCProtocolDecl *Def = Prot->getDefinition())
4307 return MakeCXCursor(Def, tu);
4308
4309 return MakeCXCursor(Prot, tu);
4310 }
4311
4312 case CXCursor_ObjCClassRef: {
4313 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4314 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4315 return MakeCXCursor(Def, tu);
4316
4317 return MakeCXCursor(Class, tu);
4318 }
4319
4320 case CXCursor_TypeRef:
4321 return MakeCXCursor(getCursorTypeRef(C).first, tu );
4322
4323 case CXCursor_TemplateRef:
4324 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
4325
4326 case CXCursor_NamespaceRef:
4327 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
4328
4329 case CXCursor_MemberRef:
4330 return MakeCXCursor(getCursorMemberRef(C).first, tu );
4331
4332 case CXCursor_CXXBaseSpecifier: {
4333 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4334 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
4335 tu ));
4336 }
4337
4338 case CXCursor_LabelRef:
4339 // FIXME: We end up faking the "parent" declaration here because we
4340 // don't want to make CXCursor larger.
4341 return MakeCXCursor(getCursorLabelRef(C).first,
4342 static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4343 .getTranslationUnitDecl(),
4344 tu);
4345
4346 case CXCursor_OverloadedDeclRef:
4347 return C;
4348
4349 case CXCursor_VariableRef:
4350 return MakeCXCursor(getCursorVariableRef(C).first, tu);
4351
4352 default:
4353 // We would prefer to enumerate all non-reference cursor kinds here.
4354 llvm_unreachable("Unhandled reference cursor kind");
4355 }
4356}
4357
4358CXCursor clang_getCursorDefinition(CXCursor C) {
4359 if (clang_isInvalid(C.kind))
4360 return clang_getNullCursor();
4361
4362 CXTranslationUnit TU = getCursorTU(C);
4363
4364 bool WasReference = false;
4365 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
4366 C = clang_getCursorReferenced(C);
4367 WasReference = true;
4368 }
4369
4370 if (C.kind == CXCursor_MacroExpansion)
4371 return clang_getCursorReferenced(C);
4372
4373 if (!clang_isDeclaration(C.kind))
4374 return clang_getNullCursor();
4375
4376 Decl *D = getCursorDecl(C);
4377 if (!D)
4378 return clang_getNullCursor();
4379
4380 switch (D->getKind()) {
4381 // Declaration kinds that don't really separate the notions of
4382 // declaration and definition.
4383 case Decl::Namespace:
4384 case Decl::Typedef:
4385 case Decl::TypeAlias:
4386 case Decl::TypeAliasTemplate:
4387 case Decl::TemplateTypeParm:
4388 case Decl::EnumConstant:
4389 case Decl::Field:
4390 case Decl::IndirectField:
4391 case Decl::ObjCIvar:
4392 case Decl::ObjCAtDefsField:
4393 case Decl::ImplicitParam:
4394 case Decl::ParmVar:
4395 case Decl::NonTypeTemplateParm:
4396 case Decl::TemplateTemplateParm:
4397 case Decl::ObjCCategoryImpl:
4398 case Decl::ObjCImplementation:
4399 case Decl::AccessSpec:
4400 case Decl::LinkageSpec:
4401 case Decl::ObjCPropertyImpl:
4402 case Decl::FileScopeAsm:
4403 case Decl::StaticAssert:
4404 case Decl::Block:
4405 case Decl::Label: // FIXME: Is this right??
4406 case Decl::ClassScopeFunctionSpecialization:
4407 case Decl::Import:
4408 return C;
4409
4410 // Declaration kinds that don't make any sense here, but are
4411 // nonetheless harmless.
4412 case Decl::TranslationUnit:
4413 break;
4414
4415 // Declaration kinds for which the definition is not resolvable.
4416 case Decl::UnresolvedUsingTypename:
4417 case Decl::UnresolvedUsingValue:
4418 break;
4419
4420 case Decl::UsingDirective:
4421 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
4422 TU);
4423
4424 case Decl::NamespaceAlias:
4425 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
4426
4427 case Decl::Enum:
4428 case Decl::Record:
4429 case Decl::CXXRecord:
4430 case Decl::ClassTemplateSpecialization:
4431 case Decl::ClassTemplatePartialSpecialization:
4432 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
4433 return MakeCXCursor(Def, TU);
4434 return clang_getNullCursor();
4435
4436 case Decl::Function:
4437 case Decl::CXXMethod:
4438 case Decl::CXXConstructor:
4439 case Decl::CXXDestructor:
4440 case Decl::CXXConversion: {
4441 const FunctionDecl *Def = 0;
4442 if (cast<FunctionDecl>(D)->getBody(Def))
4443 return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
4444 return clang_getNullCursor();
4445 }
4446
4447 case Decl::Var: {
4448 // Ask the variable if it has a definition.
4449 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
4450 return MakeCXCursor(Def, TU);
4451 return clang_getNullCursor();
4452 }
4453
4454 case Decl::FunctionTemplate: {
4455 const FunctionDecl *Def = 0;
4456 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
4457 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
4458 return clang_getNullCursor();
4459 }
4460
4461 case Decl::ClassTemplate: {
4462 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
4463 ->getDefinition())
4464 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
4465 TU);
4466 return clang_getNullCursor();
4467 }
4468
4469 case Decl::Using:
4470 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
4471 D->getLocation(), TU);
4472
4473 case Decl::UsingShadow:
4474 return clang_getCursorDefinition(
4475 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
4476 TU));
4477
4478 case Decl::ObjCMethod: {
4479 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4480 if (Method->isThisDeclarationADefinition())
4481 return C;
4482
4483 // Dig out the method definition in the associated
4484 // @implementation, if we have it.
4485 // FIXME: The ASTs should make finding the definition easier.
4486 if (ObjCInterfaceDecl *Class
4487 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4488 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4489 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4490 Method->isInstanceMethod()))
4491 if (Def->isThisDeclarationADefinition())
4492 return MakeCXCursor(Def, TU);
4493
4494 return clang_getNullCursor();
4495 }
4496
4497 case Decl::ObjCCategory:
4498 if (ObjCCategoryImplDecl *Impl
4499 = cast<ObjCCategoryDecl>(D)->getImplementation())
4500 return MakeCXCursor(Impl, TU);
4501 return clang_getNullCursor();
4502
4503 case Decl::ObjCProtocol:
4504 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
4505 return MakeCXCursor(Def, TU);
4506 return clang_getNullCursor();
4507
4508 case Decl::ObjCInterface: {
4509 // There are two notions of a "definition" for an Objective-C
4510 // class: the interface and its implementation. When we resolved a
4511 // reference to an Objective-C class, produce the @interface as
4512 // the definition; when we were provided with the interface,
4513 // produce the @implementation as the definition.
4514 ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
4515 if (WasReference) {
4516 if (ObjCInterfaceDecl *Def = IFace->getDefinition())
4517 return MakeCXCursor(Def, TU);
4518 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
4519 return MakeCXCursor(Impl, TU);
4520 return clang_getNullCursor();
4521 }
4522
4523 case Decl::ObjCProperty:
4524 // FIXME: We don't really know where to find the
4525 // ObjCPropertyImplDecls that implement this property.
4526 return clang_getNullCursor();
4527
4528 case Decl::ObjCCompatibleAlias:
4529 if (ObjCInterfaceDecl *Class
4530 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4531 if (ObjCInterfaceDecl *Def = Class->getDefinition())
4532 return MakeCXCursor(Def, TU);
4533
4534 return clang_getNullCursor();
4535
4536 case Decl::Friend:
4537 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
4538 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
4539 return clang_getNullCursor();
4540
4541 case Decl::FriendTemplate:
4542 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
4543 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
4544 return clang_getNullCursor();
4545 }
4546
4547 return clang_getNullCursor();
4548}
4549
4550unsigned clang_isCursorDefinition(CXCursor C) {
4551 if (!clang_isDeclaration(C.kind))
4552 return 0;
4553
4554 return clang_getCursorDefinition(C) == C;
4555}
4556
4557CXCursor clang_getCanonicalCursor(CXCursor C) {
4558 if (!clang_isDeclaration(C.kind))
4559 return C;
4560
4561 if (Decl *D = getCursorDecl(C)) {
4562 if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4563 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4564 return MakeCXCursor(CatD, getCursorTU(C));
4565
4566 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4567 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4568 return MakeCXCursor(IFD, getCursorTU(C));
4569
4570 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
4571 }
4572
4573 return C;
4574}
4575
4576int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
4577 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
4578}
4579
4580unsigned clang_getNumOverloadedDecls(CXCursor C) {
4581 if (C.kind != CXCursor_OverloadedDeclRef)
4582 return 0;
4583
4584 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4585 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4586 return E->getNumDecls();
4587
4588 if (OverloadedTemplateStorage *S
4589 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4590 return S->size();
4591
4592 Decl *D = Storage.get<Decl*>();
4593 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
4594 return Using->shadow_size();
4595
4596 return 0;
4597}
4598
4599CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
4600 if (cursor.kind != CXCursor_OverloadedDeclRef)
4601 return clang_getNullCursor();
4602
4603 if (index >= clang_getNumOverloadedDecls(cursor))
4604 return clang_getNullCursor();
4605
4606 CXTranslationUnit TU = getCursorTU(cursor);
4607 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4608 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4609 return MakeCXCursor(E->decls_begin()[index], TU);
4610
4611 if (OverloadedTemplateStorage *S
4612 = Storage.dyn_cast<OverloadedTemplateStorage*>())
4613 return MakeCXCursor(S->begin()[index], TU);
4614
4615 Decl *D = Storage.get<Decl*>();
4616 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4617 // FIXME: This is, unfortunately, linear time.
4618 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4619 std::advance(Pos, index);
4620 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
4621 }
4622
4623 return clang_getNullCursor();
4624}
4625
4626void clang_getDefinitionSpellingAndExtent(CXCursor C,
4627 const char **startBuf,
4628 const char **endBuf,
4629 unsigned *startLine,
4630 unsigned *startColumn,
4631 unsigned *endLine,
4632 unsigned *endColumn) {
4633 assert(getCursorDecl(C) && "CXCursor has null decl");
4634 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
4635 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4636 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
4637
4638 SourceManager &SM = FD->getASTContext().getSourceManager();
4639 *startBuf = SM.getCharacterData(Body->getLBracLoc());
4640 *endBuf = SM.getCharacterData(Body->getRBracLoc());
4641 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4642 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4643 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4644 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4645}
4646
4647
4648CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4649 unsigned PieceIndex) {
4650 RefNamePieces Pieces;
4651
4652 switch (C.kind) {
4653 case CXCursor_MemberRefExpr:
4654 if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4655 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4656 E->getQualifierLoc().getSourceRange());
4657 break;
4658
4659 case CXCursor_DeclRefExpr:
4660 if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4661 Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4662 E->getQualifierLoc().getSourceRange(),
4663 E->getOptionalExplicitTemplateArgs());
4664 break;
4665
4666 case CXCursor_CallExpr:
4667 if (CXXOperatorCallExpr *OCE =
4668 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4669 Expr *Callee = OCE->getCallee();
4670 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4671 Callee = ICE->getSubExpr();
4672
4673 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4674 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4675 DRE->getQualifierLoc().getSourceRange());
4676 }
4677 break;
4678
4679 default:
4680 break;
4681 }
4682
4683 if (Pieces.empty()) {
4684 if (PieceIndex == 0)
4685 return clang_getCursorExtent(C);
4686 } else if (PieceIndex < Pieces.size()) {
4687 SourceRange R = Pieces[PieceIndex];
4688 if (R.isValid())
4689 return cxloc::translateSourceRange(getCursorContext(C), R);
4690 }
4691
4692 return clang_getNullRange();
4693}
4694
4695void clang_enableStackTraces(void) {
4696 llvm::sys::PrintStackTraceOnErrorSignal();
4697}
4698
4699void clang_executeOnThread(void (*fn)(void*), void *user_data,
4700 unsigned stack_size) {
4701 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4702}
4703
4704} // end: extern "C"
4705
4706//===----------------------------------------------------------------------===//
4707// Token-based Operations.
4708//===----------------------------------------------------------------------===//
4709
4710/* CXToken layout:
4711 * int_data[0]: a CXTokenKind
4712 * int_data[1]: starting token location
4713 * int_data[2]: token length
4714 * int_data[3]: reserved
4715 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
4716 * otherwise unused.
4717 */
4718extern "C" {
4719
4720CXTokenKind clang_getTokenKind(CXToken CXTok) {
4721 return static_cast<CXTokenKind>(CXTok.int_data[0]);
4722}
4723
4724CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4725 switch (clang_getTokenKind(CXTok)) {
4726 case CXToken_Identifier:
4727 case CXToken_Keyword:
4728 // We know we have an IdentifierInfo*, so use that.
4729 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4730 ->getNameStart());
4731
4732 case CXToken_Literal: {
4733 // We have stashed the starting pointer in the ptr_data field. Use it.
4734 const char *Text = static_cast<const char *>(CXTok.ptr_data);
4735 return createCXString(StringRef(Text, CXTok.int_data[2]));
4736 }
4737
4738 case CXToken_Punctuation:
4739 case CXToken_Comment:
4740 break;
4741 }
4742
4743 // We have to find the starting buffer pointer the hard way, by
4744 // deconstructing the source location.
4745 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4746 if (!CXXUnit)
4747 return createCXString("");
4748
4749 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4750 std::pair<FileID, unsigned> LocInfo
4751 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
4752 bool Invalid = false;
4753 StringRef Buffer
4754 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4755 if (Invalid)
4756 return createCXString("");
4757
4758 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
4759}
4760
4761CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
4762 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4763 if (!CXXUnit)
4764 return clang_getNullLocation();
4765
4766 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4767 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4768}
4769
4770CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
4771 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4772 if (!CXXUnit)
4773 return clang_getNullRange();
4774
4775 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
4776 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4777}
4778
4779static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4780 SmallVectorImpl<CXToken> &CXTokens) {
4781 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4782 std::pair<FileID, unsigned> BeginLocInfo
4783 = SourceMgr.getDecomposedLoc(Range.getBegin());
4784 std::pair<FileID, unsigned> EndLocInfo
4785 = SourceMgr.getDecomposedLoc(Range.getEnd());
4786
4787 // Cannot tokenize across files.
4788 if (BeginLocInfo.first != EndLocInfo.first)
4789 return;
4790
4791 // Create a lexer
4792 bool Invalid = false;
4793 StringRef Buffer
4794 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4795 if (Invalid)
4796 return;
4797
4798 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4799 CXXUnit->getASTContext().getLangOpts(),
4800 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
4801 Lex.SetCommentRetentionState(true);
4802
4803 // Lex tokens until we hit the end of the range.
4804 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
4805 Token Tok;
4806 bool previousWasAt = false;
4807 do {
4808 // Lex the next token
4809 Lex.LexFromRawLexer(Tok);
4810 if (Tok.is(tok::eof))
4811 break;
4812
4813 // Initialize the CXToken.
4814 CXToken CXTok;
4815
4816 // - Common fields
4817 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4818 CXTok.int_data[2] = Tok.getLength();
4819 CXTok.int_data[3] = 0;
4820
4821 // - Kind-specific fields
4822 if (Tok.isLiteral()) {
4823 CXTok.int_data[0] = CXToken_Literal;
4824 CXTok.ptr_data = (void *)Tok.getLiteralData();
4825 } else if (Tok.is(tok::raw_identifier)) {
4826 // Lookup the identifier to determine whether we have a keyword.
4827 IdentifierInfo *II
4828 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
4829
4830 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
4831 CXTok.int_data[0] = CXToken_Keyword;
4832 }
4833 else {
4834 CXTok.int_data[0] = Tok.is(tok::identifier)
4835 ? CXToken_Identifier
4836 : CXToken_Keyword;
4837 }
4838 CXTok.ptr_data = II;
4839 } else if (Tok.is(tok::comment)) {
4840 CXTok.int_data[0] = CXToken_Comment;
4841 CXTok.ptr_data = 0;
4842 } else {
4843 CXTok.int_data[0] = CXToken_Punctuation;
4844 CXTok.ptr_data = 0;
4845 }
4846 CXTokens.push_back(CXTok);
4847 previousWasAt = Tok.is(tok::at);
4848 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
4849}
4850
4851void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4852 CXToken **Tokens, unsigned *NumTokens) {
4853 if (Tokens)
4854 *Tokens = 0;
4855 if (NumTokens)
4856 *NumTokens = 0;
4857
4858 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4859 if (!CXXUnit || !Tokens || !NumTokens)
4860 return;
4861
4862 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4863
4864 SourceRange R = cxloc::translateCXSourceRange(Range);
4865 if (R.isInvalid())
4866 return;
4867
4868 SmallVector<CXToken, 32> CXTokens;
4869 getTokens(CXXUnit, R, CXTokens);
4870
4871 if (CXTokens.empty())
4872 return;
4873
4874 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4875 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4876 *NumTokens = CXTokens.size();
4877}
4878
4879void clang_disposeTokens(CXTranslationUnit TU,
4880 CXToken *Tokens, unsigned NumTokens) {
4881 free(Tokens);
4882}
4883
4884} // end: extern "C"
4885
4886//===----------------------------------------------------------------------===//
4887// Token annotation APIs.
4888//===----------------------------------------------------------------------===//
4889
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004890static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4891 CXCursor parent,
4892 CXClientData client_data);
4893static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
4894 CXClientData client_data);
4895
4896namespace {
4897class AnnotateTokensWorker {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004898 CXToken *Tokens;
4899 CXCursor *Cursors;
4900 unsigned NumTokens;
4901 unsigned TokIdx;
4902 unsigned PreprocessingTokIdx;
4903 CursorVisitor AnnotateVis;
4904 SourceManager &SrcMgr;
4905 bool HasContextSensitiveKeywords;
4906
4907 struct PostChildrenInfo {
4908 CXCursor Cursor;
4909 SourceRange CursorRange;
4910 unsigned BeforeChildrenTokenIdx;
4911 };
4912 llvm::SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
4913
4914 bool MoreTokens() const { return TokIdx < NumTokens; }
4915 unsigned NextToken() const { return TokIdx; }
4916 void AdvanceToken() { ++TokIdx; }
4917 SourceLocation GetTokenLoc(unsigned tokI) {
4918 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4919 }
4920 bool isFunctionMacroToken(unsigned tokI) const {
4921 return Tokens[tokI].int_data[3] != 0;
4922 }
4923 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
4924 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4925 }
4926
4927 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
4928 void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4929 SourceRange);
4930
4931public:
Argyrios Kyrtzidisc059f892013-01-07 19:16:30 +00004932 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004933 CXTranslationUnit tu, SourceRange RegionOfInterest)
Argyrios Kyrtzidisc059f892013-01-07 19:16:30 +00004934 : Tokens(tokens), Cursors(cursors),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004935 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
4936 AnnotateVis(tu,
4937 AnnotateTokensVisitor, this,
4938 /*VisitPreprocessorLast=*/true,
4939 /*VisitIncludedEntities=*/false,
4940 RegionOfInterest,
4941 /*VisitDeclsOnly=*/false,
4942 AnnotateTokensPostChildrenVisitor),
4943 SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4944 HasContextSensitiveKeywords(false) { }
4945
4946 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
4947 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
4948 bool postVisitChildren(CXCursor cursor);
4949 void AnnotateTokens();
4950
4951 /// \brief Determine whether the annotator saw any cursors that have
4952 /// context-sensitive keywords.
4953 bool hasContextSensitiveKeywords() const {
4954 return HasContextSensitiveKeywords;
4955 }
4956
4957 ~AnnotateTokensWorker() {
4958 assert(PostChildrenInfos.empty());
4959 }
4960};
4961}
4962
4963void AnnotateTokensWorker::AnnotateTokens() {
4964 // Walk the AST within the region of interest, annotating tokens
4965 // along the way.
4966 AnnotateVis.visitFileRegion();
Argyrios Kyrtzidisc059f892013-01-07 19:16:30 +00004967}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004968
Argyrios Kyrtzidisc059f892013-01-07 19:16:30 +00004969static inline void updateCursorAnnotation(CXCursor &Cursor,
4970 const CXCursor &updateC) {
4971 if (clang_isInvalid(updateC.kind) || clang_isPreprocessing(Cursor.kind))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004972 return;
Argyrios Kyrtzidisc059f892013-01-07 19:16:30 +00004973 Cursor = updateC;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004974}
4975
4976/// \brief It annotates and advances tokens with a cursor until the comparison
4977//// between the cursor location and the source range is the same as
4978/// \arg compResult.
4979///
4980/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4981/// Pass RangeOverlap to annotate tokens inside a range.
4982void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4983 RangeComparisonResult compResult,
4984 SourceRange range) {
4985 while (MoreTokens()) {
4986 const unsigned I = NextToken();
4987 if (isFunctionMacroToken(I))
4988 return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
4989
4990 SourceLocation TokLoc = GetTokenLoc(I);
4991 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
Argyrios Kyrtzidisc059f892013-01-07 19:16:30 +00004992 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004993 AdvanceToken();
4994 continue;
4995 }
4996 break;
4997 }
4998}
4999
5000/// \brief Special annotation handling for macro argument tokens.
5001void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
5002 CXCursor updateC,
5003 RangeComparisonResult compResult,
5004 SourceRange range) {
5005 assert(MoreTokens());
5006 assert(isFunctionMacroToken(NextToken()) &&
5007 "Should be called only for macro arg tokens");
5008
5009 // This works differently than annotateAndAdvanceTokens; because expanded
5010 // macro arguments can have arbitrary translation-unit source order, we do not
5011 // advance the token index one by one until a token fails the range test.
5012 // We only advance once past all of the macro arg tokens if all of them
5013 // pass the range test. If one of them fails we keep the token index pointing
5014 // at the start of the macro arg tokens so that the failing token will be
5015 // annotated by a subsequent annotation try.
5016
5017 bool atLeastOneCompFail = false;
5018
5019 unsigned I = NextToken();
5020 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
5021 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
5022 if (TokLoc.isFileID())
5023 continue; // not macro arg token, it's parens or comma.
5024 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
5025 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
5026 Cursors[I] = updateC;
5027 } else
5028 atLeastOneCompFail = true;
5029 }
5030
5031 if (!atLeastOneCompFail)
5032 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
5033}
5034
5035enum CXChildVisitResult
5036AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005037 SourceRange cursorRange = getRawCursorExtent(cursor);
5038 if (cursorRange.isInvalid())
5039 return CXChildVisit_Recurse;
5040
5041 if (!HasContextSensitiveKeywords) {
5042 // Objective-C properties can have context-sensitive keywords.
5043 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
5044 if (ObjCPropertyDecl *Property
5045 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
5046 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
5047 }
5048 // Objective-C methods can have context-sensitive keywords.
5049 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
5050 cursor.kind == CXCursor_ObjCClassMethodDecl) {
5051 if (ObjCMethodDecl *Method
5052 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5053 if (Method->getObjCDeclQualifier())
5054 HasContextSensitiveKeywords = true;
5055 else {
5056 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
5057 PEnd = Method->param_end();
5058 P != PEnd; ++P) {
5059 if ((*P)->getObjCDeclQualifier()) {
5060 HasContextSensitiveKeywords = true;
5061 break;
5062 }
5063 }
5064 }
5065 }
5066 }
5067 // C++ methods can have context-sensitive keywords.
5068 else if (cursor.kind == CXCursor_CXXMethod) {
5069 if (CXXMethodDecl *Method
5070 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
5071 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
5072 HasContextSensitiveKeywords = true;
5073 }
5074 }
5075 // C++ classes can have context-sensitive keywords.
5076 else if (cursor.kind == CXCursor_StructDecl ||
5077 cursor.kind == CXCursor_ClassDecl ||
5078 cursor.kind == CXCursor_ClassTemplate ||
5079 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
5080 if (Decl *D = getCursorDecl(cursor))
5081 if (D->hasAttr<FinalAttr>())
5082 HasContextSensitiveKeywords = true;
5083 }
5084 }
5085
5086 if (clang_isPreprocessing(cursor.kind)) {
5087 // Items in the preprocessing record are kept separate from items in
5088 // declarations, so we keep a separate token index.
5089 unsigned SavedTokIdx = TokIdx;
5090 TokIdx = PreprocessingTokIdx;
5091
5092 // Skip tokens up until we catch up to the beginning of the preprocessing
5093 // entry.
5094 while (MoreTokens()) {
5095 const unsigned I = NextToken();
5096 SourceLocation TokLoc = GetTokenLoc(I);
5097 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5098 case RangeBefore:
5099 AdvanceToken();
5100 continue;
5101 case RangeAfter:
5102 case RangeOverlap:
5103 break;
5104 }
5105 break;
5106 }
5107
5108 // Look at all of the tokens within this range.
5109 while (MoreTokens()) {
5110 const unsigned I = NextToken();
5111 SourceLocation TokLoc = GetTokenLoc(I);
5112 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5113 case RangeBefore:
5114 llvm_unreachable("Infeasible");
5115 case RangeAfter:
5116 break;
5117 case RangeOverlap:
Argyrios Kyrtzidisc059f892013-01-07 19:16:30 +00005118 // We may have already annotated macro names inside macro definitions.
5119 if (Cursors[I].kind != CXCursor_MacroExpansion)
5120 Cursors[I] = cursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005121 AdvanceToken();
5122 // For macro expansions, just note where the beginning of the macro
5123 // expansion occurs.
5124 if (cursor.kind == CXCursor_MacroExpansion)
5125 break;
5126 continue;
5127 }
5128 break;
5129 }
5130
5131 // Save the preprocessing token index; restore the non-preprocessing
5132 // token index.
5133 PreprocessingTokIdx = TokIdx;
5134 TokIdx = SavedTokIdx;
5135 return CXChildVisit_Recurse;
5136 }
5137
5138 if (cursorRange.isInvalid())
5139 return CXChildVisit_Continue;
5140
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005141 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005142 const enum CXCursorKind K = clang_getCursorKind(parent);
5143 const CXCursor updateC =
5144 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
5145 ? clang_getNullCursor() : parent;
5146
5147 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
5148
5149 // Avoid having the cursor of an expression "overwrite" the annotation of the
5150 // variable declaration that it belongs to.
5151 // This can happen for C++ constructor expressions whose range generally
5152 // include the variable declaration, e.g.:
5153 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
5154 if (clang_isExpression(cursorK)) {
5155 Expr *E = getCursorExpr(cursor);
5156 if (Decl *D = getCursorParentDecl(cursor)) {
5157 const unsigned I = NextToken();
5158 if (E->getLocStart().isValid() && D->getLocation().isValid() &&
5159 E->getLocStart() == D->getLocation() &&
5160 E->getLocStart() == GetTokenLoc(I)) {
Argyrios Kyrtzidisc059f892013-01-07 19:16:30 +00005161 updateCursorAnnotation(Cursors[I], updateC);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005162 AdvanceToken();
5163 }
5164 }
5165 }
5166
5167 // Before recursing into the children keep some state that we are going
5168 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
5169 // extra work after the child nodes are visited.
5170 // Note that we don't call VisitChildren here to avoid traversing statements
5171 // code-recursively which can blow the stack.
5172
5173 PostChildrenInfo Info;
5174 Info.Cursor = cursor;
5175 Info.CursorRange = cursorRange;
5176 Info.BeforeChildrenTokenIdx = NextToken();
5177 PostChildrenInfos.push_back(Info);
5178
5179 return CXChildVisit_Recurse;
5180}
5181
5182bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
5183 if (PostChildrenInfos.empty())
5184 return false;
5185 const PostChildrenInfo &Info = PostChildrenInfos.back();
5186 if (!clang_equalCursors(Info.Cursor, cursor))
5187 return false;
5188
5189 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
5190 const unsigned AfterChildren = NextToken();
5191 SourceRange cursorRange = Info.CursorRange;
5192
5193 // Scan the tokens that are at the end of the cursor, but are not captured
5194 // but the child cursors.
5195 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
5196
5197 // Scan the tokens that are at the beginning of the cursor, but are not
5198 // capture by the child cursors.
5199 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5200 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5201 break;
5202
5203 Cursors[I] = cursor;
5204 }
5205
5206 PostChildrenInfos.pop_back();
5207 return false;
5208}
5209
5210static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5211 CXCursor parent,
5212 CXClientData client_data) {
5213 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5214}
5215
5216static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
5217 CXClientData client_data) {
5218 return static_cast<AnnotateTokensWorker*>(client_data)->
5219 postVisitChildren(cursor);
5220}
5221
5222namespace {
5223
5224/// \brief Uses the macro expansions in the preprocessing record to find
5225/// and mark tokens that are macro arguments. This info is used by the
5226/// AnnotateTokensWorker.
5227class MarkMacroArgTokensVisitor {
5228 SourceManager &SM;
5229 CXToken *Tokens;
5230 unsigned NumTokens;
5231 unsigned CurIdx;
5232
5233public:
5234 MarkMacroArgTokensVisitor(SourceManager &SM,
5235 CXToken *tokens, unsigned numTokens)
5236 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
5237
5238 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5239 if (cursor.kind != CXCursor_MacroExpansion)
5240 return CXChildVisit_Continue;
5241
Argyrios Kyrtzidis664b06f2013-01-07 19:16:25 +00005242 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005243 if (macroRange.getBegin() == macroRange.getEnd())
5244 return CXChildVisit_Continue; // it's not a function macro.
5245
5246 for (; CurIdx < NumTokens; ++CurIdx) {
5247 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5248 macroRange.getBegin()))
5249 break;
5250 }
5251
5252 if (CurIdx == NumTokens)
5253 return CXChildVisit_Break;
5254
5255 for (; CurIdx < NumTokens; ++CurIdx) {
5256 SourceLocation tokLoc = getTokenLoc(CurIdx);
5257 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5258 break;
5259
5260 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
5261 }
5262
5263 if (CurIdx == NumTokens)
5264 return CXChildVisit_Break;
5265
5266 return CXChildVisit_Continue;
5267 }
5268
5269private:
5270 SourceLocation getTokenLoc(unsigned tokI) {
5271 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5272 }
5273
5274 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
5275 // The third field is reserved and currently not used. Use it here
5276 // to mark macro arg expanded tokens with their expanded locations.
5277 Tokens[tokI].int_data[3] = loc.getRawEncoding();
5278 }
5279};
5280
5281} // end anonymous namespace
5282
5283static CXChildVisitResult
5284MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5285 CXClientData client_data) {
5286 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5287 parent);
5288}
5289
5290namespace {
5291 struct clang_annotateTokens_Data {
5292 CXTranslationUnit TU;
5293 ASTUnit *CXXUnit;
5294 CXToken *Tokens;
5295 unsigned NumTokens;
5296 CXCursor *Cursors;
5297 };
5298}
5299
Argyrios Kyrtzidisc059f892013-01-07 19:16:30 +00005300/// \brief Used by \c annotatePreprocessorTokens.
5301/// \returns true if lexing was finished, false otherwise.
5302static bool lexNext(Lexer &Lex, Token &Tok,
5303 unsigned &NextIdx, unsigned NumTokens) {
5304 if (NextIdx >= NumTokens)
5305 return true;
5306
5307 ++NextIdx;
5308 Lex.LexFromRawLexer(Tok);
5309 if (Tok.is(tok::eof))
5310 return true;
5311
5312 return false;
5313}
5314
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005315static void annotatePreprocessorTokens(CXTranslationUnit TU,
5316 SourceRange RegionOfInterest,
Argyrios Kyrtzidisc059f892013-01-07 19:16:30 +00005317 CXCursor *Cursors,
5318 CXToken *Tokens,
5319 unsigned NumTokens) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005320 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5321
Argyrios Kyrtzidis3453bf72013-01-07 19:16:32 +00005322 Preprocessor &PP = CXXUnit->getPreprocessor();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005323 SourceManager &SourceMgr = CXXUnit->getSourceManager();
5324 std::pair<FileID, unsigned> BeginLocInfo
5325 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5326 std::pair<FileID, unsigned> EndLocInfo
5327 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5328
5329 if (BeginLocInfo.first != EndLocInfo.first)
5330 return;
5331
5332 StringRef Buffer;
5333 bool Invalid = false;
5334 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5335 if (Buffer.empty() || Invalid)
5336 return;
5337
5338 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
5339 CXXUnit->getASTContext().getLangOpts(),
5340 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5341 Buffer.end());
5342 Lex.SetCommentRetentionState(true);
5343
Argyrios Kyrtzidisc059f892013-01-07 19:16:30 +00005344 unsigned NextIdx = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005345 // Lex tokens in raw mode until we hit the end of the range, to avoid
5346 // entering #includes or expanding macros.
5347 while (true) {
5348 Token Tok;
Argyrios Kyrtzidisc059f892013-01-07 19:16:30 +00005349 if (lexNext(Lex, Tok, NextIdx, NumTokens))
5350 break;
5351 unsigned TokIdx = NextIdx-1;
5352 assert(Tok.getLocation() ==
5353 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005354
5355 reprocess:
5356 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
Argyrios Kyrtzidisc059f892013-01-07 19:16:30 +00005357 // We have found a preprocessing directive. Annotate the tokens
5358 // appropriately.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005359 //
5360 // FIXME: Some simple tests here could identify macro definitions and
5361 // #undefs, to provide specific cursor kinds for those.
Argyrios Kyrtzidisc059f892013-01-07 19:16:30 +00005362
5363 SourceLocation BeginLoc = Tok.getLocation();
Argyrios Kyrtzidis3453bf72013-01-07 19:16:32 +00005364 if (lexNext(Lex, Tok, NextIdx, NumTokens))
5365 break;
5366
5367 MacroInfo *MI = 0;
5368 if (Tok.is(tok::raw_identifier) &&
5369 StringRef(Tok.getRawIdentifierData(), Tok.getLength()) == "define") {
5370 if (lexNext(Lex, Tok, NextIdx, NumTokens))
5371 break;
5372
5373 if (Tok.is(tok::raw_identifier)) {
5374 StringRef Name(Tok.getRawIdentifierData(), Tok.getLength());
5375 IdentifierInfo &II = PP.getIdentifierTable().get(Name);
5376 SourceLocation MappedTokLoc =
5377 CXXUnit->mapLocationToPreamble(Tok.getLocation());
5378 MI = getMacroInfo(II, MappedTokLoc, TU);
5379 }
5380 }
5381
Argyrios Kyrtzidisc059f892013-01-07 19:16:30 +00005382 bool finished = false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005383 do {
Argyrios Kyrtzidisc059f892013-01-07 19:16:30 +00005384 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
5385 finished = true;
5386 break;
5387 }
Argyrios Kyrtzidis3453bf72013-01-07 19:16:32 +00005388 // If we are in a macro definition, check if the token was ever a
5389 // macro name and annotate it if that's the case.
5390 if (MI) {
5391 SourceLocation SaveLoc = Tok.getLocation();
5392 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
5393 MacroDefinition *MacroDef = checkForMacroInMacroDefinition(MI,Tok,TU);
5394 Tok.setLocation(SaveLoc);
5395 if (MacroDef)
5396 Cursors[NextIdx-1] = MakeMacroExpansionCursor(MacroDef,
5397 Tok.getLocation(), TU);
5398 }
Argyrios Kyrtzidisc059f892013-01-07 19:16:30 +00005399 } while (!Tok.isAtStartOfLine());
5400
5401 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
5402 assert(TokIdx <= LastIdx);
5403 SourceLocation EndLoc =
5404 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
5405 CXCursor Cursor =
5406 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
5407
5408 for (; TokIdx <= LastIdx; ++TokIdx)
Argyrios Kyrtzidis3453bf72013-01-07 19:16:32 +00005409 updateCursorAnnotation(Cursors[TokIdx], Cursor);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005410
Argyrios Kyrtzidisc059f892013-01-07 19:16:30 +00005411 if (finished)
5412 break;
5413 goto reprocess;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005414 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005415 }
5416}
5417
5418// This gets run a separate thread to avoid stack blowout.
5419static void clang_annotateTokensImpl(void *UserData) {
5420 CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5421 ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5422 CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5423 const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5424 CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5425
5426 CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
5427 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
5428 setThreadBackgroundPriority();
5429
5430 // Determine the region of interest, which contains all of the tokens.
5431 SourceRange RegionOfInterest;
5432 RegionOfInterest.setBegin(
5433 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5434 RegionOfInterest.setEnd(
5435 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5436 Tokens[NumTokens-1])));
5437
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005438 // Relex the tokens within the source range to look for preprocessing
5439 // directives.
Argyrios Kyrtzidisc059f892013-01-07 19:16:30 +00005440 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005441
5442 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5443 // Search and mark tokens that are macro argument expansions.
5444 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5445 Tokens, NumTokens);
5446 CursorVisitor MacroArgMarker(TU,
5447 MarkMacroArgTokensVisitorDelegate, &Visitor,
5448 /*VisitPreprocessorLast=*/true,
5449 /*VisitIncludedEntities=*/false,
5450 RegionOfInterest);
5451 MacroArgMarker.visitPreprocessedEntitiesInRegion();
5452 }
5453
5454 // Annotate all of the source locations in the region of interest that map to
5455 // a specific cursor.
Argyrios Kyrtzidisc059f892013-01-07 19:16:30 +00005456 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005457
5458 // FIXME: We use a ridiculous stack size here because the data-recursion
5459 // algorithm uses a large stack frame than the non-data recursive version,
5460 // and AnnotationTokensWorker currently transforms the data-recursion
5461 // algorithm back into a traditional recursion by explicitly calling
5462 // VisitChildren(). We will need to remove this explicit recursive call.
5463 W.AnnotateTokens();
5464
5465 // If we ran into any entities that involve context-sensitive keywords,
5466 // take another pass through the tokens to mark them as such.
5467 if (W.hasContextSensitiveKeywords()) {
5468 for (unsigned I = 0; I != NumTokens; ++I) {
5469 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5470 continue;
5471
5472 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5473 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5474 if (ObjCPropertyDecl *Property
5475 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5476 if (Property->getPropertyAttributesAsWritten() != 0 &&
5477 llvm::StringSwitch<bool>(II->getName())
5478 .Case("readonly", true)
5479 .Case("assign", true)
5480 .Case("unsafe_unretained", true)
5481 .Case("readwrite", true)
5482 .Case("retain", true)
5483 .Case("copy", true)
5484 .Case("nonatomic", true)
5485 .Case("atomic", true)
5486 .Case("getter", true)
5487 .Case("setter", true)
5488 .Case("strong", true)
5489 .Case("weak", true)
5490 .Default(false))
5491 Tokens[I].int_data[0] = CXToken_Keyword;
5492 }
5493 continue;
5494 }
5495
5496 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5497 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5498 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5499 if (llvm::StringSwitch<bool>(II->getName())
5500 .Case("in", true)
5501 .Case("out", true)
5502 .Case("inout", true)
5503 .Case("oneway", true)
5504 .Case("bycopy", true)
5505 .Case("byref", true)
5506 .Default(false))
5507 Tokens[I].int_data[0] = CXToken_Keyword;
5508 continue;
5509 }
5510
5511 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5512 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5513 Tokens[I].int_data[0] = CXToken_Keyword;
5514 continue;
5515 }
5516 }
5517 }
5518}
5519
5520extern "C" {
5521
5522void clang_annotateTokens(CXTranslationUnit TU,
5523 CXToken *Tokens, unsigned NumTokens,
5524 CXCursor *Cursors) {
5525
5526 if (NumTokens == 0 || !Tokens || !Cursors)
5527 return;
5528
5529 // Any token we don't specifically annotate will have a NULL cursor.
5530 CXCursor C = clang_getNullCursor();
5531 for (unsigned I = 0; I != NumTokens; ++I)
5532 Cursors[I] = C;
5533
5534 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5535 if (!CXXUnit)
5536 return;
5537
5538 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5539
5540 clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
5541 llvm::CrashRecoveryContext CRC;
5542 if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
5543 GetSafetyThreadStackSize() * 2)) {
5544 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5545 }
5546}
5547
5548} // end: extern "C"
5549
5550//===----------------------------------------------------------------------===//
5551// Operations for querying linkage of a cursor.
5552//===----------------------------------------------------------------------===//
5553
5554extern "C" {
5555CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
5556 if (!clang_isDeclaration(cursor.kind))
5557 return CXLinkage_Invalid;
5558
5559 Decl *D = cxcursor::getCursorDecl(cursor);
5560 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5561 switch (ND->getLinkage()) {
5562 case NoLinkage: return CXLinkage_NoLinkage;
5563 case InternalLinkage: return CXLinkage_Internal;
5564 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5565 case ExternalLinkage: return CXLinkage_External;
5566 };
5567
5568 return CXLinkage_Invalid;
5569}
5570} // end: extern "C"
5571
5572//===----------------------------------------------------------------------===//
5573// Operations for querying language of a cursor.
5574//===----------------------------------------------------------------------===//
5575
5576static CXLanguageKind getDeclLanguage(const Decl *D) {
5577 if (!D)
5578 return CXLanguage_C;
5579
5580 switch (D->getKind()) {
5581 default:
5582 break;
5583 case Decl::ImplicitParam:
5584 case Decl::ObjCAtDefsField:
5585 case Decl::ObjCCategory:
5586 case Decl::ObjCCategoryImpl:
5587 case Decl::ObjCCompatibleAlias:
5588 case Decl::ObjCImplementation:
5589 case Decl::ObjCInterface:
5590 case Decl::ObjCIvar:
5591 case Decl::ObjCMethod:
5592 case Decl::ObjCProperty:
5593 case Decl::ObjCPropertyImpl:
5594 case Decl::ObjCProtocol:
5595 return CXLanguage_ObjC;
5596 case Decl::CXXConstructor:
5597 case Decl::CXXConversion:
5598 case Decl::CXXDestructor:
5599 case Decl::CXXMethod:
5600 case Decl::CXXRecord:
5601 case Decl::ClassTemplate:
5602 case Decl::ClassTemplatePartialSpecialization:
5603 case Decl::ClassTemplateSpecialization:
5604 case Decl::Friend:
5605 case Decl::FriendTemplate:
5606 case Decl::FunctionTemplate:
5607 case Decl::LinkageSpec:
5608 case Decl::Namespace:
5609 case Decl::NamespaceAlias:
5610 case Decl::NonTypeTemplateParm:
5611 case Decl::StaticAssert:
5612 case Decl::TemplateTemplateParm:
5613 case Decl::TemplateTypeParm:
5614 case Decl::UnresolvedUsingTypename:
5615 case Decl::UnresolvedUsingValue:
5616 case Decl::Using:
5617 case Decl::UsingDirective:
5618 case Decl::UsingShadow:
5619 return CXLanguage_CPlusPlus;
5620 }
5621
5622 return CXLanguage_C;
5623}
5624
5625extern "C" {
5626
5627enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5628 if (clang_isDeclaration(cursor.kind))
5629 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
5630 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
5631 return CXAvailability_Available;
5632
5633 switch (D->getAvailability()) {
5634 case AR_Available:
5635 case AR_NotYetIntroduced:
5636 return CXAvailability_Available;
5637
5638 case AR_Deprecated:
5639 return CXAvailability_Deprecated;
5640
5641 case AR_Unavailable:
5642 return CXAvailability_NotAvailable;
5643 }
5644 }
5645
5646 return CXAvailability_Available;
5647}
5648
5649static CXVersion convertVersion(VersionTuple In) {
5650 CXVersion Out = { -1, -1, -1 };
5651 if (In.empty())
5652 return Out;
5653
5654 Out.Major = In.getMajor();
5655
5656 if (llvm::Optional<unsigned> Minor = In.getMinor())
5657 Out.Minor = *Minor;
5658 else
5659 return Out;
5660
5661 if (llvm::Optional<unsigned> Subminor = In.getSubminor())
5662 Out.Subminor = *Subminor;
5663
5664 return Out;
5665}
5666
5667int clang_getCursorPlatformAvailability(CXCursor cursor,
5668 int *always_deprecated,
5669 CXString *deprecated_message,
5670 int *always_unavailable,
5671 CXString *unavailable_message,
5672 CXPlatformAvailability *availability,
5673 int availability_size) {
5674 if (always_deprecated)
5675 *always_deprecated = 0;
5676 if (deprecated_message)
5677 *deprecated_message = cxstring::createCXString("", /*DupString=*/false);
5678 if (always_unavailable)
5679 *always_unavailable = 0;
5680 if (unavailable_message)
5681 *unavailable_message = cxstring::createCXString("", /*DupString=*/false);
5682
5683 if (!clang_isDeclaration(cursor.kind))
5684 return 0;
5685
5686 Decl *D = cxcursor::getCursorDecl(cursor);
5687 if (!D)
5688 return 0;
5689
5690 int N = 0;
5691 for (Decl::attr_iterator A = D->attr_begin(), AEnd = D->attr_end(); A != AEnd;
5692 ++A) {
5693 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
5694 if (always_deprecated)
5695 *always_deprecated = 1;
5696 if (deprecated_message)
5697 *deprecated_message = cxstring::createCXString(Deprecated->getMessage());
5698 continue;
5699 }
5700
5701 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
5702 if (always_unavailable)
5703 *always_unavailable = 1;
5704 if (unavailable_message) {
5705 *unavailable_message
5706 = cxstring::createCXString(Unavailable->getMessage());
5707 }
5708 continue;
5709 }
5710
5711 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(*A)) {
5712 if (N < availability_size) {
5713 availability[N].Platform
5714 = cxstring::createCXString(Avail->getPlatform()->getName());
5715 availability[N].Introduced = convertVersion(Avail->getIntroduced());
5716 availability[N].Deprecated = convertVersion(Avail->getDeprecated());
5717 availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
5718 availability[N].Unavailable = Avail->getUnavailable();
5719 availability[N].Message = cxstring::createCXString(Avail->getMessage());
5720 }
5721 ++N;
5722 }
5723 }
5724
5725 return N;
5726}
5727
5728void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
5729 clang_disposeString(availability->Platform);
5730 clang_disposeString(availability->Message);
5731}
5732
5733CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5734 if (clang_isDeclaration(cursor.kind))
5735 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5736
5737 return CXLanguage_Invalid;
5738}
5739
5740 /// \brief If the given cursor is the "templated" declaration
5741 /// descibing a class or function template, return the class or
5742 /// function template.
5743static Decl *maybeGetTemplateCursor(Decl *D) {
5744 if (!D)
5745 return 0;
5746
5747 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5748 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5749 return FunTmpl;
5750
5751 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5752 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5753 return ClassTmpl;
5754
5755 return D;
5756}
5757
5758CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5759 if (clang_isDeclaration(cursor.kind)) {
5760 if (Decl *D = getCursorDecl(cursor)) {
5761 DeclContext *DC = D->getDeclContext();
5762 if (!DC)
5763 return clang_getNullCursor();
5764
5765 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5766 getCursorTU(cursor));
5767 }
5768 }
5769
5770 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5771 if (Decl *D = getCursorDecl(cursor))
5772 return MakeCXCursor(D, getCursorTU(cursor));
5773 }
5774
5775 return clang_getNullCursor();
5776}
5777
5778CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5779 if (clang_isDeclaration(cursor.kind)) {
5780 if (Decl *D = getCursorDecl(cursor)) {
5781 DeclContext *DC = D->getLexicalDeclContext();
5782 if (!DC)
5783 return clang_getNullCursor();
5784
5785 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5786 getCursorTU(cursor));
5787 }
5788 }
5789
5790 // FIXME: Note that we can't easily compute the lexical context of a
5791 // statement or expression, so we return nothing.
5792 return clang_getNullCursor();
5793}
5794
5795CXFile clang_getIncludedFile(CXCursor cursor) {
5796 if (cursor.kind != CXCursor_InclusionDirective)
5797 return 0;
5798
5799 InclusionDirective *ID = getCursorInclusionDirective(cursor);
5800 return (void *)ID->getFile();
5801}
5802
5803CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
5804 if (!clang_isDeclaration(C.kind))
5805 return clang_getNullRange();
5806
5807 const Decl *D = getCursorDecl(C);
5808 ASTContext &Context = getCursorContext(C);
5809 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
5810 if (!RC)
5811 return clang_getNullRange();
5812
5813 return cxloc::translateSourceRange(Context, RC->getSourceRange());
5814}
5815
5816CXString clang_Cursor_getRawCommentText(CXCursor C) {
5817 if (!clang_isDeclaration(C.kind))
5818 return createCXString((const char *) NULL);
5819
5820 const Decl *D = getCursorDecl(C);
5821 ASTContext &Context = getCursorContext(C);
5822 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
5823 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
5824 StringRef();
5825
5826 // Don't duplicate the string because RawText points directly into source
5827 // code.
5828 return createCXString(RawText, false);
5829}
5830
5831CXString clang_Cursor_getBriefCommentText(CXCursor C) {
5832 if (!clang_isDeclaration(C.kind))
5833 return createCXString((const char *) NULL);
5834
5835 const Decl *D = getCursorDecl(C);
5836 const ASTContext &Context = getCursorContext(C);
5837 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
5838
5839 if (RC) {
5840 StringRef BriefText = RC->getBriefText(Context);
5841
5842 // Don't duplicate the string because RawComment ensures that this memory
5843 // will not go away.
5844 return createCXString(BriefText, false);
5845 }
5846
5847 return createCXString((const char *) NULL);
5848}
5849
5850CXComment clang_Cursor_getParsedComment(CXCursor C) {
5851 if (!clang_isDeclaration(C.kind))
5852 return cxcomment::createCXComment(NULL, NULL);
5853
5854 const Decl *D = getCursorDecl(C);
5855 const ASTContext &Context = getCursorContext(C);
5856 const comments::FullComment *FC = Context.getCommentForDecl(D, /*PP=*/ NULL);
5857
5858 return cxcomment::createCXComment(FC, getCursorTU(C));
5859}
5860
5861CXModule clang_Cursor_getModule(CXCursor C) {
5862 if (C.kind == CXCursor_ModuleImportDecl) {
5863 if (ImportDecl *ImportD = dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
5864 return ImportD->getImportedModule();
5865 }
5866
5867 return 0;
5868}
5869
5870CXModule clang_Module_getParent(CXModule CXMod) {
5871 if (!CXMod)
5872 return 0;
5873 Module *Mod = static_cast<Module*>(CXMod);
5874 return Mod->Parent;
5875}
5876
5877CXString clang_Module_getName(CXModule CXMod) {
5878 if (!CXMod)
5879 return createCXString("");
5880 Module *Mod = static_cast<Module*>(CXMod);
5881 return createCXString(Mod->Name);
5882}
5883
5884CXString clang_Module_getFullName(CXModule CXMod) {
5885 if (!CXMod)
5886 return createCXString("");
5887 Module *Mod = static_cast<Module*>(CXMod);
5888 return createCXString(Mod->getFullModuleName());
5889}
5890
5891unsigned clang_Module_getNumTopLevelHeaders(CXModule CXMod) {
5892 if (!CXMod)
5893 return 0;
5894 Module *Mod = static_cast<Module*>(CXMod);
5895 return Mod->TopHeaders.size();
5896}
5897
5898CXFile clang_Module_getTopLevelHeader(CXModule CXMod, unsigned Index) {
5899 if (!CXMod)
5900 return 0;
5901 Module *Mod = static_cast<Module*>(CXMod);
5902
5903 if (Index < Mod->TopHeaders.size())
5904 return const_cast<FileEntry *>(Mod->TopHeaders[Index]);
5905
5906 return 0;
5907}
5908
5909} // end: extern "C"
5910
5911//===----------------------------------------------------------------------===//
5912// C++ AST instrospection.
5913//===----------------------------------------------------------------------===//
5914
5915extern "C" {
5916unsigned clang_CXXMethod_isStatic(CXCursor C) {
5917 if (!clang_isDeclaration(C.kind))
5918 return 0;
5919
5920 CXXMethodDecl *Method = 0;
5921 Decl *D = cxcursor::getCursorDecl(C);
5922 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5923 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5924 else
5925 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5926 return (Method && Method->isStatic()) ? 1 : 0;
5927}
5928
5929unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5930 if (!clang_isDeclaration(C.kind))
5931 return 0;
5932
5933 CXXMethodDecl *Method = 0;
5934 Decl *D = cxcursor::getCursorDecl(C);
5935 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5936 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5937 else
5938 Method = dyn_cast_or_null<CXXMethodDecl>(D);
5939 return (Method && Method->isVirtual()) ? 1 : 0;
5940}
5941} // end: extern "C"
5942
5943//===----------------------------------------------------------------------===//
5944// Attribute introspection.
5945//===----------------------------------------------------------------------===//
5946
5947extern "C" {
5948CXType clang_getIBOutletCollectionType(CXCursor C) {
5949 if (C.kind != CXCursor_IBOutletCollectionAttr)
5950 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
5951
5952 IBOutletCollectionAttr *A =
5953 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5954
5955 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
5956}
5957} // end: extern "C"
5958
5959//===----------------------------------------------------------------------===//
5960// Inspecting memory usage.
5961//===----------------------------------------------------------------------===//
5962
5963typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
5964
5965static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5966 enum CXTUResourceUsageKind k,
5967 unsigned long amount) {
5968 CXTUResourceUsageEntry entry = { k, amount };
5969 entries.push_back(entry);
5970}
5971
5972extern "C" {
5973
5974const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
5975 const char *str = "";
5976 switch (kind) {
5977 case CXTUResourceUsage_AST:
5978 str = "ASTContext: expressions, declarations, and types";
5979 break;
5980 case CXTUResourceUsage_Identifiers:
5981 str = "ASTContext: identifiers";
5982 break;
5983 case CXTUResourceUsage_Selectors:
5984 str = "ASTContext: selectors";
5985 break;
5986 case CXTUResourceUsage_GlobalCompletionResults:
5987 str = "Code completion: cached global results";
5988 break;
5989 case CXTUResourceUsage_SourceManagerContentCache:
5990 str = "SourceManager: content cache allocator";
5991 break;
5992 case CXTUResourceUsage_AST_SideTables:
5993 str = "ASTContext: side tables";
5994 break;
5995 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5996 str = "SourceManager: malloc'ed memory buffers";
5997 break;
5998 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5999 str = "SourceManager: mmap'ed memory buffers";
6000 break;
6001 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
6002 str = "ExternalASTSource: malloc'ed memory buffers";
6003 break;
6004 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
6005 str = "ExternalASTSource: mmap'ed memory buffers";
6006 break;
6007 case CXTUResourceUsage_Preprocessor:
6008 str = "Preprocessor: malloc'ed memory";
6009 break;
6010 case CXTUResourceUsage_PreprocessingRecord:
6011 str = "Preprocessor: PreprocessingRecord";
6012 break;
6013 case CXTUResourceUsage_SourceManager_DataStructures:
6014 str = "SourceManager: data structures and tables";
6015 break;
6016 case CXTUResourceUsage_Preprocessor_HeaderSearch:
6017 str = "Preprocessor: header search tables";
6018 break;
6019 }
6020 return str;
6021}
6022
6023CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
6024 if (!TU) {
6025 CXTUResourceUsage usage = { (void*) 0, 0, 0 };
6026 return usage;
6027 }
6028
6029 ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
6030 OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
6031 ASTContext &astContext = astUnit->getASTContext();
6032
6033 // How much memory is used by AST nodes and types?
6034 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
6035 (unsigned long) astContext.getASTAllocatedMemory());
6036
6037 // How much memory is used by identifiers?
6038 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
6039 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
6040
6041 // How much memory is used for selectors?
6042 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
6043 (unsigned long) astContext.Selectors.getTotalMemory());
6044
6045 // How much memory is used by ASTContext's side tables?
6046 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
6047 (unsigned long) astContext.getSideTableAllocatedMemory());
6048
6049 // How much memory is used for caching global code completion results?
6050 unsigned long completionBytes = 0;
6051 if (GlobalCodeCompletionAllocator *completionAllocator =
6052 astUnit->getCachedCompletionAllocator().getPtr()) {
6053 completionBytes = completionAllocator->getTotalMemory();
6054 }
6055 createCXTUResourceUsageEntry(*entries,
6056 CXTUResourceUsage_GlobalCompletionResults,
6057 completionBytes);
6058
6059 // How much memory is being used by SourceManager's content cache?
6060 createCXTUResourceUsageEntry(*entries,
6061 CXTUResourceUsage_SourceManagerContentCache,
6062 (unsigned long) astContext.getSourceManager().getContentCacheSize());
6063
6064 // How much memory is being used by the MemoryBuffer's in SourceManager?
6065 const SourceManager::MemoryBufferSizes &srcBufs =
6066 astUnit->getSourceManager().getMemoryBufferSizes();
6067
6068 createCXTUResourceUsageEntry(*entries,
6069 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
6070 (unsigned long) srcBufs.malloc_bytes);
6071 createCXTUResourceUsageEntry(*entries,
6072 CXTUResourceUsage_SourceManager_Membuffer_MMap,
6073 (unsigned long) srcBufs.mmap_bytes);
6074 createCXTUResourceUsageEntry(*entries,
6075 CXTUResourceUsage_SourceManager_DataStructures,
6076 (unsigned long) astContext.getSourceManager()
6077 .getDataStructureSizes());
6078
6079 // How much memory is being used by the ExternalASTSource?
6080 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
6081 const ExternalASTSource::MemoryBufferSizes &sizes =
6082 esrc->getMemoryBufferSizes();
6083
6084 createCXTUResourceUsageEntry(*entries,
6085 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
6086 (unsigned long) sizes.malloc_bytes);
6087 createCXTUResourceUsageEntry(*entries,
6088 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
6089 (unsigned long) sizes.mmap_bytes);
6090 }
6091
6092 // How much memory is being used by the Preprocessor?
6093 Preprocessor &pp = astUnit->getPreprocessor();
6094 createCXTUResourceUsageEntry(*entries,
6095 CXTUResourceUsage_Preprocessor,
6096 pp.getTotalMemory());
6097
6098 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
6099 createCXTUResourceUsageEntry(*entries,
6100 CXTUResourceUsage_PreprocessingRecord,
6101 pRec->getTotalMemory());
6102 }
6103
6104 createCXTUResourceUsageEntry(*entries,
6105 CXTUResourceUsage_Preprocessor_HeaderSearch,
6106 pp.getHeaderSearchInfo().getTotalMemory());
6107
6108 CXTUResourceUsage usage = { (void*) entries.get(),
6109 (unsigned) entries->size(),
6110 entries->size() ? &(*entries)[0] : 0 };
6111 entries.take();
6112 return usage;
6113}
6114
6115void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
6116 if (usage.data)
6117 delete (MemUsageEntries*) usage.data;
6118}
6119
6120} // end extern "C"
6121
6122void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
6123 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
6124 for (unsigned I = 0; I != Usage.numEntries; ++I)
6125 fprintf(stderr, " %s: %lu\n",
6126 clang_getTUResourceUsageName(Usage.entries[I].kind),
6127 Usage.entries[I].amount);
6128
6129 clang_disposeCXTUResourceUsage(Usage);
6130}
6131
6132//===----------------------------------------------------------------------===//
6133// Misc. utility functions.
6134//===----------------------------------------------------------------------===//
6135
6136/// Default to using an 8 MB stack size on "safety" threads.
6137static unsigned SafetyStackThreadSize = 8 << 20;
6138
6139namespace clang {
6140
6141bool RunSafely(llvm::CrashRecoveryContext &CRC,
6142 void (*Fn)(void*), void *UserData,
6143 unsigned Size) {
6144 if (!Size)
6145 Size = GetSafetyThreadStackSize();
6146 if (Size)
6147 return CRC.RunSafelyOnThread(Fn, UserData, Size);
6148 return CRC.RunSafely(Fn, UserData);
6149}
6150
6151unsigned GetSafetyThreadStackSize() {
6152 return SafetyStackThreadSize;
6153}
6154
6155void SetSafetyThreadStackSize(unsigned Value) {
6156 SafetyStackThreadSize = Value;
6157}
6158
6159}
6160
6161void clang::setThreadBackgroundPriority() {
6162 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
6163 return;
6164
6165 // FIXME: Move to llvm/Support and make it cross-platform.
6166#ifdef __APPLE__
6167 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
6168#endif
6169}
6170
6171void cxindex::printDiagsToStderr(ASTUnit *Unit) {
6172 if (!Unit)
6173 return;
6174
6175 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
6176 DEnd = Unit->stored_diag_end();
6177 D != DEnd; ++D) {
6178 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOpts());
6179 CXString Msg = clang_formatDiagnostic(&Diag,
6180 clang_defaultDiagnosticDisplayOptions());
6181 fprintf(stderr, "%s\n", clang_getCString(Msg));
6182 clang_disposeString(Msg);
6183 }
6184#ifdef LLVM_ON_WIN32
6185 // On Windows, force a flush, since there may be multiple copies of
6186 // stderr and stdout in the file system, all with different buffers
6187 // but writing to the same device.
6188 fflush(stderr);
6189#endif
6190}
6191
Argyrios Kyrtzidis664b06f2013-01-07 19:16:25 +00006192MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
6193 SourceLocation MacroDefLoc,
6194 CXTranslationUnit TU){
6195 if (MacroDefLoc.isInvalid() || !TU)
6196 return 0;
Argyrios Kyrtzidis664b06f2013-01-07 19:16:25 +00006197 if (!II.hadMacroDefinition())
6198 return 0;
6199
Argyrios Kyrtzidisc059f892013-01-07 19:16:30 +00006200 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
6201 Preprocessor &PP = Unit->getPreprocessor();
Argyrios Kyrtzidis664b06f2013-01-07 19:16:25 +00006202 MacroInfo *MI = PP.getMacroInfoHistory(const_cast<IdentifierInfo*>(&II));
6203 while (MI) {
6204 if (MacroDefLoc == MI->getDefinitionLoc())
6205 return MI;
6206 MI = MI->getPreviousDefinition();
6207 }
6208
6209 return 0;
6210}
6211
6212MacroInfo *cxindex::getMacroInfo(MacroDefinition *MacroDef,
6213 CXTranslationUnit TU) {
6214 if (!MacroDef || !TU)
6215 return 0;
6216 const IdentifierInfo *II = MacroDef->getName();
6217 if (!II)
6218 return 0;
6219
6220 return getMacroInfo(*II, MacroDef->getLocation(), TU);
6221}
6222
6223MacroDefinition *cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI,
6224 const Token &Tok,
6225 CXTranslationUnit TU) {
6226 if (!MI || !TU)
6227 return 0;
6228 if (Tok.isNot(tok::raw_identifier))
6229 return 0;
6230
6231 if (MI->getNumTokens() == 0)
6232 return 0;
6233 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
6234 MI->getDefinitionEndLoc());
6235 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
6236
6237 // Check that the token is inside the definition and not its argument list.
6238 SourceManager &SM = Unit->getSourceManager();
6239 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
6240 return 0;
6241 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
6242 return 0;
6243
6244 Preprocessor &PP = Unit->getPreprocessor();
6245 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
6246 if (!PPRec)
6247 return 0;
6248
6249 StringRef Name(Tok.getRawIdentifierData(), Tok.getLength());
6250 IdentifierInfo &II = PP.getIdentifierTable().get(Name);
6251 if (!II.hadMacroDefinition())
6252 return 0;
6253
6254 // Check that the identifier is not one of the macro arguments.
6255 if (std::find(MI->arg_begin(), MI->arg_end(), &II) != MI->arg_end())
6256 return 0;
6257
6258 MacroInfo *InnerMI = PP.getMacroInfoHistory(&II);
6259 if (!InnerMI)
6260 return 0;
6261
6262 return PPRec->findMacroDefinition(InnerMI);
6263}
6264
6265MacroDefinition *cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI,
6266 SourceLocation Loc,
6267 CXTranslationUnit TU) {
6268 if (Loc.isInvalid() || !MI || !TU)
6269 return 0;
6270
6271 if (MI->getNumTokens() == 0)
6272 return 0;
6273 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
6274 Preprocessor &PP = Unit->getPreprocessor();
6275 if (!PP.getPreprocessingRecord())
6276 return 0;
6277 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
6278 Token Tok;
6279 if (PP.getRawToken(Loc, Tok))
6280 return 0;
6281
6282 return checkForMacroInMacroDefinition(MI, Tok, TU);
6283}
6284
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006285extern "C" {
6286
6287CXString clang_getClangVersion() {
6288 return createCXString(getClangFullVersion());
6289}
6290
6291} // end: extern "C"
6292