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