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