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