1 //===- 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 "CIndexDiagnostic.h"
16 #include "CIndexer.h"
17 #include "CLog.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"
24 #include "clang/AST/Attr.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/Basic/Diagnostic.h"
27 #include "clang/Basic/DiagnosticCategories.h"
28 #include "clang/Basic/DiagnosticIDs.h"
29 #include "clang/Basic/Stack.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Basic/Version.h"
32 #include "clang/Frontend/ASTUnit.h"
33 #include "clang/Frontend/CompilerInstance.h"
34 #include "clang/Index/CodegenNameGenerator.h"
35 #include "clang/Index/CommentToXML.h"
36 #include "clang/Lex/HeaderSearch.h"
37 #include "clang/Lex/Lexer.h"
38 #include "clang/Lex/PreprocessingRecord.h"
39 #include "clang/Lex/Preprocessor.h"
40 #include "llvm/ADT/Optional.h"
41 #include "llvm/ADT/STLExtras.h"
42 #include "llvm/ADT/StringSwitch.h"
43 #include "llvm/Config/llvm-config.h"
44 #include "llvm/Support/Compiler.h"
45 #include "llvm/Support/CrashRecoveryContext.h"
46 #include "llvm/Support/Format.h"
47 #include "llvm/Support/ManagedStatic.h"
48 #include "llvm/Support/MemoryBuffer.h"
49 #include "llvm/Support/Mutex.h"
50 #include "llvm/Support/Program.h"
51 #include "llvm/Support/SaveAndRestore.h"
52 #include "llvm/Support/Signals.h"
53 #include "llvm/Support/TargetSelect.h"
54 #include "llvm/Support/Threading.h"
55 #include "llvm/Support/Timer.h"
56 #include "llvm/Support/raw_ostream.h"
57
58 #if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
59 #define USE_DARWIN_THREADS
60 #endif
61
62 #ifdef USE_DARWIN_THREADS
63 #include <pthread.h>
64 #endif
65
66 using namespace clang;
67 using namespace clang::cxcursor;
68 using namespace clang::cxtu;
69 using namespace clang::cxindex;
70
MakeCXTranslationUnit(CIndexer * CIdx,std::unique_ptr<ASTUnit> AU)71 CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
72 std::unique_ptr<ASTUnit> AU) {
73 if (!AU)
74 return nullptr;
75 assert(CIdx);
76 CXTranslationUnit D = new CXTranslationUnitImpl();
77 D->CIdx = CIdx;
78 D->TheASTUnit = AU.release();
79 D->StringPool = new cxstring::CXStringPool();
80 D->Diagnostics = nullptr;
81 D->OverridenCursorsPool = createOverridenCXCursorsPool();
82 D->CommentToXML = nullptr;
83 D->ParsingOptions = 0;
84 D->Arguments = {};
85 return D;
86 }
87
isASTReadError(ASTUnit * AU)88 bool cxtu::isASTReadError(ASTUnit *AU) {
89 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
90 DEnd = AU->stored_diag_end();
91 D != DEnd; ++D) {
92 if (D->getLevel() >= DiagnosticsEngine::Error &&
93 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
94 diag::DiagCat_AST_Deserialization_Issue)
95 return true;
96 }
97 return false;
98 }
99
~CXTUOwner()100 cxtu::CXTUOwner::~CXTUOwner() {
101 if (TU)
102 clang_disposeTranslationUnit(TU);
103 }
104
105 /// Compare two source ranges to determine their relative position in
106 /// the translation unit.
RangeCompare(SourceManager & SM,SourceRange R1,SourceRange R2)107 static RangeComparisonResult RangeCompare(SourceManager &SM,
108 SourceRange R1,
109 SourceRange R2) {
110 assert(R1.isValid() && "First range is invalid?");
111 assert(R2.isValid() && "Second range is invalid?");
112 if (R1.getEnd() != R2.getBegin() &&
113 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
114 return RangeBefore;
115 if (R2.getEnd() != R1.getBegin() &&
116 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
117 return RangeAfter;
118 return RangeOverlap;
119 }
120
121 /// Determine if a source location falls within, before, or after a
122 /// a given source range.
LocationCompare(SourceManager & SM,SourceLocation L,SourceRange R)123 static RangeComparisonResult LocationCompare(SourceManager &SM,
124 SourceLocation L, SourceRange R) {
125 assert(R.isValid() && "First range is invalid?");
126 assert(L.isValid() && "Second range is invalid?");
127 if (L == R.getBegin() || L == R.getEnd())
128 return RangeOverlap;
129 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
130 return RangeBefore;
131 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
132 return RangeAfter;
133 return RangeOverlap;
134 }
135
136 /// Translate a Clang source range into a CIndex source range.
137 ///
138 /// Clang internally represents ranges where the end location points to the
139 /// start of the token at the end. However, for external clients it is more
140 /// useful to have a CXSourceRange be a proper half-open interval. This routine
141 /// does the appropriate translation.
translateSourceRange(const SourceManager & SM,const LangOptions & LangOpts,const CharSourceRange & R)142 CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
143 const LangOptions &LangOpts,
144 const CharSourceRange &R) {
145 // We want the last character in this location, so we will adjust the
146 // location accordingly.
147 SourceLocation EndLoc = R.getEnd();
148 bool IsTokenRange = R.isTokenRange();
149 if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc)) {
150 CharSourceRange Expansion = SM.getExpansionRange(EndLoc);
151 EndLoc = Expansion.getEnd();
152 IsTokenRange = Expansion.isTokenRange();
153 }
154 if (IsTokenRange && EndLoc.isValid()) {
155 unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
156 SM, LangOpts);
157 EndLoc = EndLoc.getLocWithOffset(Length);
158 }
159
160 CXSourceRange Result = {
161 { &SM, &LangOpts },
162 R.getBegin().getRawEncoding(),
163 EndLoc.getRawEncoding()
164 };
165 return Result;
166 }
167
168 //===----------------------------------------------------------------------===//
169 // Cursor visitor.
170 //===----------------------------------------------------------------------===//
171
172 static SourceRange getRawCursorExtent(CXCursor C);
173 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
174
175
CompareRegionOfInterest(SourceRange R)176 RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
177 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
178 }
179
180 /// Visit the given cursor and, if requested by the visitor,
181 /// its children.
182 ///
183 /// \param Cursor the cursor to visit.
184 ///
185 /// \param CheckedRegionOfInterest if true, then the caller already checked
186 /// that this cursor is within the region of interest.
187 ///
188 /// \returns true if the visitation should be aborted, false if it
189 /// should continue.
Visit(CXCursor Cursor,bool CheckedRegionOfInterest)190 bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
191 if (clang_isInvalid(Cursor.kind))
192 return false;
193
194 if (clang_isDeclaration(Cursor.kind)) {
195 const Decl *D = getCursorDecl(Cursor);
196 if (!D) {
197 assert(0 && "Invalid declaration cursor");
198 return true; // abort.
199 }
200
201 // Ignore implicit declarations, unless it's an objc method because
202 // currently we should report implicit methods for properties when indexing.
203 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
204 return false;
205 }
206
207 // If we have a range of interest, and this cursor doesn't intersect with it,
208 // we're done.
209 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
210 SourceRange Range = getRawCursorExtent(Cursor);
211 if (Range.isInvalid() || CompareRegionOfInterest(Range))
212 return false;
213 }
214
215 switch (Visitor(Cursor, Parent, ClientData)) {
216 case CXChildVisit_Break:
217 return true;
218
219 case CXChildVisit_Continue:
220 return false;
221
222 case CXChildVisit_Recurse: {
223 bool ret = VisitChildren(Cursor);
224 if (PostChildrenVisitor)
225 if (PostChildrenVisitor(Cursor, ClientData))
226 return true;
227 return ret;
228 }
229 }
230
231 llvm_unreachable("Invalid CXChildVisitResult!");
232 }
233
visitPreprocessedEntitiesInRange(SourceRange R,PreprocessingRecord & PPRec,CursorVisitor & Visitor)234 static bool visitPreprocessedEntitiesInRange(SourceRange R,
235 PreprocessingRecord &PPRec,
236 CursorVisitor &Visitor) {
237 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
238 FileID FID;
239
240 if (!Visitor.shouldVisitIncludedEntities()) {
241 // If the begin/end of the range lie in the same FileID, do the optimization
242 // where we skip preprocessed entities that do not come from the same FileID.
243 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
244 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
245 FID = FileID();
246 }
247
248 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
249 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
250 PPRec, FID);
251 }
252
visitFileRegion()253 bool CursorVisitor::visitFileRegion() {
254 if (RegionOfInterest.isInvalid())
255 return false;
256
257 ASTUnit *Unit = cxtu::getASTUnit(TU);
258 SourceManager &SM = Unit->getSourceManager();
259
260 std::pair<FileID, unsigned>
261 Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
262 End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
263
264 if (End.first != Begin.first) {
265 // If the end does not reside in the same file, try to recover by
266 // picking the end of the file of begin location.
267 End.first = Begin.first;
268 End.second = SM.getFileIDSize(Begin.first);
269 }
270
271 assert(Begin.first == End.first);
272 if (Begin.second > End.second)
273 return false;
274
275 FileID File = Begin.first;
276 unsigned Offset = Begin.second;
277 unsigned Length = End.second - Begin.second;
278
279 if (!VisitDeclsOnly && !VisitPreprocessorLast)
280 if (visitPreprocessedEntitiesInRegion())
281 return true; // visitation break.
282
283 if (visitDeclsFromFileRegion(File, Offset, Length))
284 return true; // visitation break.
285
286 if (!VisitDeclsOnly && VisitPreprocessorLast)
287 return visitPreprocessedEntitiesInRegion();
288
289 return false;
290 }
291
isInLexicalContext(Decl * D,DeclContext * DC)292 static bool isInLexicalContext(Decl *D, DeclContext *DC) {
293 if (!DC)
294 return false;
295
296 for (DeclContext *DeclDC = D->getLexicalDeclContext();
297 DeclDC; DeclDC = DeclDC->getLexicalParent()) {
298 if (DeclDC == DC)
299 return true;
300 }
301 return false;
302 }
303
visitDeclsFromFileRegion(FileID File,unsigned Offset,unsigned Length)304 bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
305 unsigned Offset, unsigned Length) {
306 ASTUnit *Unit = cxtu::getASTUnit(TU);
307 SourceManager &SM = Unit->getSourceManager();
308 SourceRange Range = RegionOfInterest;
309
310 SmallVector<Decl *, 16> Decls;
311 Unit->findFileRegionDecls(File, Offset, Length, Decls);
312
313 // If we didn't find any file level decls for the file, try looking at the
314 // file that it was included from.
315 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
316 bool Invalid = false;
317 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
318 if (Invalid)
319 return false;
320
321 SourceLocation Outer;
322 if (SLEntry.isFile())
323 Outer = SLEntry.getFile().getIncludeLoc();
324 else
325 Outer = SLEntry.getExpansion().getExpansionLocStart();
326 if (Outer.isInvalid())
327 return false;
328
329 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
330 Length = 0;
331 Unit->findFileRegionDecls(File, Offset, Length, Decls);
332 }
333
334 assert(!Decls.empty());
335
336 bool VisitedAtLeastOnce = false;
337 DeclContext *CurDC = nullptr;
338 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
339 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
340 Decl *D = *DIt;
341 if (D->getSourceRange().isInvalid())
342 continue;
343
344 if (isInLexicalContext(D, CurDC))
345 continue;
346
347 CurDC = dyn_cast<DeclContext>(D);
348
349 if (TagDecl *TD = dyn_cast<TagDecl>(D))
350 if (!TD->isFreeStanding())
351 continue;
352
353 RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
354 if (CompRes == RangeBefore)
355 continue;
356 if (CompRes == RangeAfter)
357 break;
358
359 assert(CompRes == RangeOverlap);
360 VisitedAtLeastOnce = true;
361
362 if (isa<ObjCContainerDecl>(D)) {
363 FileDI_current = &DIt;
364 FileDE_current = DE;
365 } else {
366 FileDI_current = nullptr;
367 }
368
369 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
370 return true; // visitation break.
371 }
372
373 if (VisitedAtLeastOnce)
374 return false;
375
376 // No Decls overlapped with the range. Move up the lexical context until there
377 // is a context that contains the range or we reach the translation unit
378 // level.
379 DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
380 : (*(DIt-1))->getLexicalDeclContext();
381
382 while (DC && !DC->isTranslationUnit()) {
383 Decl *D = cast<Decl>(DC);
384 SourceRange CurDeclRange = D->getSourceRange();
385 if (CurDeclRange.isInvalid())
386 break;
387
388 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
389 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
390 return true; // visitation break.
391 }
392
393 DC = D->getLexicalDeclContext();
394 }
395
396 return false;
397 }
398
visitPreprocessedEntitiesInRegion()399 bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
400 if (!AU->getPreprocessor().getPreprocessingRecord())
401 return false;
402
403 PreprocessingRecord &PPRec
404 = *AU->getPreprocessor().getPreprocessingRecord();
405 SourceManager &SM = AU->getSourceManager();
406
407 if (RegionOfInterest.isValid()) {
408 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
409 SourceLocation B = MappedRange.getBegin();
410 SourceLocation E = MappedRange.getEnd();
411
412 if (AU->isInPreambleFileID(B)) {
413 if (SM.isLoadedSourceLocation(E))
414 return visitPreprocessedEntitiesInRange(SourceRange(B, E),
415 PPRec, *this);
416
417 // Beginning of range lies in the preamble but it also extends beyond
418 // it into the main file. Split the range into 2 parts, one covering
419 // the preamble and another covering the main file. This allows subsequent
420 // calls to visitPreprocessedEntitiesInRange to accept a source range that
421 // lies in the same FileID, allowing it to skip preprocessed entities that
422 // do not come from the same FileID.
423 bool breaked =
424 visitPreprocessedEntitiesInRange(
425 SourceRange(B, AU->getEndOfPreambleFileID()),
426 PPRec, *this);
427 if (breaked) return true;
428 return visitPreprocessedEntitiesInRange(
429 SourceRange(AU->getStartOfMainFileID(), E),
430 PPRec, *this);
431 }
432
433 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
434 }
435
436 bool OnlyLocalDecls
437 = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
438
439 if (OnlyLocalDecls)
440 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
441 PPRec);
442
443 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
444 }
445
446 template<typename InputIterator>
visitPreprocessedEntities(InputIterator First,InputIterator Last,PreprocessingRecord & PPRec,FileID FID)447 bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
448 InputIterator Last,
449 PreprocessingRecord &PPRec,
450 FileID FID) {
451 for (; First != Last; ++First) {
452 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
453 continue;
454
455 PreprocessedEntity *PPE = *First;
456 if (!PPE)
457 continue;
458
459 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
460 if (Visit(MakeMacroExpansionCursor(ME, TU)))
461 return true;
462
463 continue;
464 }
465
466 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
467 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
468 return true;
469
470 continue;
471 }
472
473 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
474 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
475 return true;
476
477 continue;
478 }
479 }
480
481 return false;
482 }
483
484 /// Visit the children of the given cursor.
485 ///
486 /// \returns true if the visitation should be aborted, false if it
487 /// should continue.
VisitChildren(CXCursor Cursor)488 bool CursorVisitor::VisitChildren(CXCursor Cursor) {
489 if (clang_isReference(Cursor.kind) &&
490 Cursor.kind != CXCursor_CXXBaseSpecifier) {
491 // By definition, references have no children.
492 return false;
493 }
494
495 // Set the Parent field to Cursor, then back to its old value once we're
496 // done.
497 SetParentRAII SetParent(Parent, StmtParent, Cursor);
498
499 if (clang_isDeclaration(Cursor.kind)) {
500 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
501 if (!D)
502 return false;
503
504 return VisitAttributes(D) || Visit(D);
505 }
506
507 if (clang_isStatement(Cursor.kind)) {
508 if (const Stmt *S = getCursorStmt(Cursor))
509 return Visit(S);
510
511 return false;
512 }
513
514 if (clang_isExpression(Cursor.kind)) {
515 if (const Expr *E = getCursorExpr(Cursor))
516 return Visit(E);
517
518 return false;
519 }
520
521 if (clang_isTranslationUnit(Cursor.kind)) {
522 CXTranslationUnit TU = getCursorTU(Cursor);
523 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
524
525 int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
526 for (unsigned I = 0; I != 2; ++I) {
527 if (VisitOrder[I]) {
528 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
529 RegionOfInterest.isInvalid()) {
530 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
531 TLEnd = CXXUnit->top_level_end();
532 TL != TLEnd; ++TL) {
533 const Optional<bool> V = handleDeclForVisitation(*TL);
534 if (!V.hasValue())
535 continue;
536 return V.getValue();
537 }
538 } else if (VisitDeclContext(
539 CXXUnit->getASTContext().getTranslationUnitDecl()))
540 return true;
541 continue;
542 }
543
544 // Walk the preprocessing record.
545 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
546 visitPreprocessedEntitiesInRegion();
547 }
548
549 return false;
550 }
551
552 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
553 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
554 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
555 return Visit(BaseTSInfo->getTypeLoc());
556 }
557 }
558 }
559
560 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
561 const IBOutletCollectionAttr *A =
562 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
563 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
564 return Visit(cxcursor::MakeCursorObjCClassRef(
565 ObjT->getInterface(),
566 A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
567 }
568
569 // If pointing inside a macro definition, check if the token is an identifier
570 // that was ever defined as a macro. In such a case, create a "pseudo" macro
571 // expansion cursor for that token.
572 SourceLocation BeginLoc = RegionOfInterest.getBegin();
573 if (Cursor.kind == CXCursor_MacroDefinition &&
574 BeginLoc == RegionOfInterest.getEnd()) {
575 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
576 const MacroInfo *MI =
577 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
578 if (MacroDefinitionRecord *MacroDef =
579 checkForMacroInMacroDefinition(MI, Loc, TU))
580 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
581 }
582
583 // Nothing to visit at the moment.
584 return false;
585 }
586
VisitBlockDecl(BlockDecl * B)587 bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
588 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
589 if (Visit(TSInfo->getTypeLoc()))
590 return true;
591
592 if (Stmt *Body = B->getBody())
593 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
594
595 return false;
596 }
597
shouldVisitCursor(CXCursor Cursor)598 Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
599 if (RegionOfInterest.isValid()) {
600 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
601 if (Range.isInvalid())
602 return None;
603
604 switch (CompareRegionOfInterest(Range)) {
605 case RangeBefore:
606 // This declaration comes before the region of interest; skip it.
607 return None;
608
609 case RangeAfter:
610 // This declaration comes after the region of interest; we're done.
611 return false;
612
613 case RangeOverlap:
614 // This declaration overlaps the region of interest; visit it.
615 break;
616 }
617 }
618 return true;
619 }
620
VisitDeclContext(DeclContext * DC)621 bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
622 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
623
624 // FIXME: Eventually remove. This part of a hack to support proper
625 // iteration over all Decls contained lexically within an ObjC container.
626 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
627 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
628
629 for ( ; I != E; ++I) {
630 Decl *D = *I;
631 if (D->getLexicalDeclContext() != DC)
632 continue;
633 const Optional<bool> V = handleDeclForVisitation(D);
634 if (!V.hasValue())
635 continue;
636 return V.getValue();
637 }
638 return false;
639 }
640
handleDeclForVisitation(const Decl * D)641 Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
642 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
643
644 // Ignore synthesized ivars here, otherwise if we have something like:
645 // @synthesize prop = _prop;
646 // and '_prop' is not declared, we will encounter a '_prop' ivar before
647 // encountering the 'prop' synthesize declaration and we will think that
648 // we passed the region-of-interest.
649 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
650 if (ivarD->getSynthesize())
651 return None;
652 }
653
654 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
655 // declarations is a mismatch with the compiler semantics.
656 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
657 auto *ID = cast<ObjCInterfaceDecl>(D);
658 if (!ID->isThisDeclarationADefinition())
659 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
660
661 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
662 auto *PD = cast<ObjCProtocolDecl>(D);
663 if (!PD->isThisDeclarationADefinition())
664 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
665 }
666
667 const Optional<bool> V = shouldVisitCursor(Cursor);
668 if (!V.hasValue())
669 return None;
670 if (!V.getValue())
671 return false;
672 if (Visit(Cursor, true))
673 return true;
674 return None;
675 }
676
VisitTranslationUnitDecl(TranslationUnitDecl * D)677 bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
678 llvm_unreachable("Translation units are visited directly by Visit()");
679 }
680
VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl * D)681 bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
682 if (VisitTemplateParameters(D->getTemplateParameters()))
683 return true;
684
685 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
686 }
687
VisitTypeAliasDecl(TypeAliasDecl * D)688 bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
689 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
690 return Visit(TSInfo->getTypeLoc());
691
692 return false;
693 }
694
VisitTypedefDecl(TypedefDecl * D)695 bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
696 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
697 return Visit(TSInfo->getTypeLoc());
698
699 return false;
700 }
701
VisitTagDecl(TagDecl * D)702 bool CursorVisitor::VisitTagDecl(TagDecl *D) {
703 return VisitDeclContext(D);
704 }
705
VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl * D)706 bool CursorVisitor::VisitClassTemplateSpecializationDecl(
707 ClassTemplateSpecializationDecl *D) {
708 bool ShouldVisitBody = false;
709 switch (D->getSpecializationKind()) {
710 case TSK_Undeclared:
711 case TSK_ImplicitInstantiation:
712 // Nothing to visit
713 return false;
714
715 case TSK_ExplicitInstantiationDeclaration:
716 case TSK_ExplicitInstantiationDefinition:
717 break;
718
719 case TSK_ExplicitSpecialization:
720 ShouldVisitBody = true;
721 break;
722 }
723
724 // Visit the template arguments used in the specialization.
725 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
726 TypeLoc TL = SpecType->getTypeLoc();
727 if (TemplateSpecializationTypeLoc TSTLoc =
728 TL.getAs<TemplateSpecializationTypeLoc>()) {
729 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
730 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
731 return true;
732 }
733 }
734
735 return ShouldVisitBody && VisitCXXRecordDecl(D);
736 }
737
VisitClassTemplatePartialSpecializationDecl(ClassTemplatePartialSpecializationDecl * D)738 bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
739 ClassTemplatePartialSpecializationDecl *D) {
740 // FIXME: Visit the "outer" template parameter lists on the TagDecl
741 // before visiting these template parameters.
742 if (VisitTemplateParameters(D->getTemplateParameters()))
743 return true;
744
745 // Visit the partial specialization arguments.
746 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
747 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
748 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
749 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
750 return true;
751
752 return VisitCXXRecordDecl(D);
753 }
754
VisitTemplateTypeParmDecl(TemplateTypeParmDecl * D)755 bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
756 // Visit the default argument.
757 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
758 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
759 if (Visit(DefArg->getTypeLoc()))
760 return true;
761
762 return false;
763 }
764
VisitEnumConstantDecl(EnumConstantDecl * D)765 bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
766 if (Expr *Init = D->getInitExpr())
767 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
768 return false;
769 }
770
VisitDeclaratorDecl(DeclaratorDecl * DD)771 bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
772 unsigned NumParamList = DD->getNumTemplateParameterLists();
773 for (unsigned i = 0; i < NumParamList; i++) {
774 TemplateParameterList* Params = DD->getTemplateParameterList(i);
775 if (VisitTemplateParameters(Params))
776 return true;
777 }
778
779 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
780 if (Visit(TSInfo->getTypeLoc()))
781 return true;
782
783 // Visit the nested-name-specifier, if present.
784 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
785 if (VisitNestedNameSpecifierLoc(QualifierLoc))
786 return true;
787
788 return false;
789 }
790
HasTrailingReturnType(FunctionDecl * ND)791 static bool HasTrailingReturnType(FunctionDecl *ND) {
792 const QualType Ty = ND->getType();
793 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
794 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
795 return FT->hasTrailingReturn();
796 }
797
798 return false;
799 }
800
801 /// Compare two base or member initializers based on their source order.
CompareCXXCtorInitializers(CXXCtorInitializer * const * X,CXXCtorInitializer * const * Y)802 static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
803 CXXCtorInitializer *const *Y) {
804 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
805 }
806
VisitFunctionDecl(FunctionDecl * ND)807 bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
808 unsigned NumParamList = ND->getNumTemplateParameterLists();
809 for (unsigned i = 0; i < NumParamList; i++) {
810 TemplateParameterList* Params = ND->getTemplateParameterList(i);
811 if (VisitTemplateParameters(Params))
812 return true;
813 }
814
815 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
816 // Visit the function declaration's syntactic components in the order
817 // written. This requires a bit of work.
818 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
819 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
820 const bool HasTrailingRT = HasTrailingReturnType(ND);
821
822 // If we have a function declared directly (without the use of a typedef),
823 // visit just the return type. Otherwise, just visit the function's type
824 // now.
825 if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT &&
826 Visit(FTL.getReturnLoc())) ||
827 (!FTL && Visit(TL)))
828 return true;
829
830 // Visit the nested-name-specifier, if present.
831 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
832 if (VisitNestedNameSpecifierLoc(QualifierLoc))
833 return true;
834
835 // Visit the declaration name.
836 if (!isa<CXXDestructorDecl>(ND))
837 if (VisitDeclarationNameInfo(ND->getNameInfo()))
838 return true;
839
840 // FIXME: Visit explicitly-specified template arguments!
841
842 // Visit the function parameters, if we have a function type.
843 if (FTL && VisitFunctionTypeLoc(FTL, true))
844 return true;
845
846 // Visit the function's trailing return type.
847 if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc()))
848 return true;
849
850 // FIXME: Attributes?
851 }
852
853 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
854 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
855 // Find the initializers that were written in the source.
856 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
857 for (auto *I : Constructor->inits()) {
858 if (!I->isWritten())
859 continue;
860
861 WrittenInits.push_back(I);
862 }
863
864 // Sort the initializers in source order
865 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
866 &CompareCXXCtorInitializers);
867
868 // Visit the initializers in source order
869 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
870 CXXCtorInitializer *Init = WrittenInits[I];
871 if (Init->isAnyMemberInitializer()) {
872 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
873 Init->getMemberLocation(), TU)))
874 return true;
875 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
876 if (Visit(TInfo->getTypeLoc()))
877 return true;
878 }
879
880 // Visit the initializer value.
881 if (Expr *Initializer = Init->getInit())
882 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
883 return true;
884 }
885 }
886
887 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
888 return true;
889 }
890
891 return false;
892 }
893
VisitFieldDecl(FieldDecl * D)894 bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
895 if (VisitDeclaratorDecl(D))
896 return true;
897
898 if (Expr *BitWidth = D->getBitWidth())
899 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
900
901 if (Expr *Init = D->getInClassInitializer())
902 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
903
904 return false;
905 }
906
VisitVarDecl(VarDecl * D)907 bool CursorVisitor::VisitVarDecl(VarDecl *D) {
908 if (VisitDeclaratorDecl(D))
909 return true;
910
911 if (Expr *Init = D->getInit())
912 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
913
914 return false;
915 }
916
VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl * D)917 bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
918 if (VisitDeclaratorDecl(D))
919 return true;
920
921 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
922 if (Expr *DefArg = D->getDefaultArgument())
923 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
924
925 return false;
926 }
927
VisitFunctionTemplateDecl(FunctionTemplateDecl * D)928 bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
929 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
930 // before visiting these template parameters.
931 if (VisitTemplateParameters(D->getTemplateParameters()))
932 return true;
933
934 auto* FD = D->getTemplatedDecl();
935 return VisitAttributes(FD) || VisitFunctionDecl(FD);
936 }
937
VisitClassTemplateDecl(ClassTemplateDecl * D)938 bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
939 // FIXME: Visit the "outer" template parameter lists on the TagDecl
940 // before visiting these template parameters.
941 if (VisitTemplateParameters(D->getTemplateParameters()))
942 return true;
943
944 auto* CD = D->getTemplatedDecl();
945 return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
946 }
947
VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl * D)948 bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
949 if (VisitTemplateParameters(D->getTemplateParameters()))
950 return true;
951
952 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
953 VisitTemplateArgumentLoc(D->getDefaultArgument()))
954 return true;
955
956 return false;
957 }
958
VisitObjCTypeParamDecl(ObjCTypeParamDecl * D)959 bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
960 // Visit the bound, if it's explicit.
961 if (D->hasExplicitBound()) {
962 if (auto TInfo = D->getTypeSourceInfo()) {
963 if (Visit(TInfo->getTypeLoc()))
964 return true;
965 }
966 }
967
968 return false;
969 }
970
VisitObjCMethodDecl(ObjCMethodDecl * ND)971 bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
972 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
973 if (Visit(TSInfo->getTypeLoc()))
974 return true;
975
976 for (const auto *P : ND->parameters()) {
977 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
978 return true;
979 }
980
981 return ND->isThisDeclarationADefinition() &&
982 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
983 }
984
985 template <typename DeclIt>
addRangedDeclsInContainer(DeclIt * DI_current,DeclIt DE_current,SourceManager & SM,SourceLocation EndLoc,SmallVectorImpl<Decl * > & Decls)986 static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
987 SourceManager &SM, SourceLocation EndLoc,
988 SmallVectorImpl<Decl *> &Decls) {
989 DeclIt next = *DI_current;
990 while (++next != DE_current) {
991 Decl *D_next = *next;
992 if (!D_next)
993 break;
994 SourceLocation L = D_next->getBeginLoc();
995 if (!L.isValid())
996 break;
997 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
998 *DI_current = next;
999 Decls.push_back(D_next);
1000 continue;
1001 }
1002 break;
1003 }
1004 }
1005
VisitObjCContainerDecl(ObjCContainerDecl * D)1006 bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
1007 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
1008 // an @implementation can lexically contain Decls that are not properly
1009 // nested in the AST. When we identify such cases, we need to retrofit
1010 // this nesting here.
1011 if (!DI_current && !FileDI_current)
1012 return VisitDeclContext(D);
1013
1014 // Scan the Decls that immediately come after the container
1015 // in the current DeclContext. If any fall within the
1016 // container's lexical region, stash them into a vector
1017 // for later processing.
1018 SmallVector<Decl *, 24> DeclsInContainer;
1019 SourceLocation EndLoc = D->getSourceRange().getEnd();
1020 SourceManager &SM = AU->getSourceManager();
1021 if (EndLoc.isValid()) {
1022 if (DI_current) {
1023 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
1024 DeclsInContainer);
1025 } else {
1026 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1027 DeclsInContainer);
1028 }
1029 }
1030
1031 // The common case.
1032 if (DeclsInContainer.empty())
1033 return VisitDeclContext(D);
1034
1035 // Get all the Decls in the DeclContext, and sort them with the
1036 // additional ones we've collected. Then visit them.
1037 for (auto *SubDecl : D->decls()) {
1038 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1039 SubDecl->getBeginLoc().isInvalid())
1040 continue;
1041 DeclsInContainer.push_back(SubDecl);
1042 }
1043
1044 // Now sort the Decls so that they appear in lexical order.
1045 llvm::sort(DeclsInContainer,
1046 [&SM](Decl *A, Decl *B) {
1047 SourceLocation L_A = A->getBeginLoc();
1048 SourceLocation L_B = B->getBeginLoc();
1049 return L_A != L_B ? SM.isBeforeInTranslationUnit(L_A, L_B)
1050 : SM.isBeforeInTranslationUnit(A->getEndLoc(),
1051 B->getEndLoc());
1052 });
1053
1054 // Now visit the decls.
1055 for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1056 E = DeclsInContainer.end(); I != E; ++I) {
1057 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
1058 const Optional<bool> &V = shouldVisitCursor(Cursor);
1059 if (!V.hasValue())
1060 continue;
1061 if (!V.getValue())
1062 return false;
1063 if (Visit(Cursor, true))
1064 return true;
1065 }
1066 return false;
1067 }
1068
VisitObjCCategoryDecl(ObjCCategoryDecl * ND)1069 bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1070 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1071 TU)))
1072 return true;
1073
1074 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1075 return true;
1076
1077 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1078 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1079 E = ND->protocol_end(); I != E; ++I, ++PL)
1080 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1081 return true;
1082
1083 return VisitObjCContainerDecl(ND);
1084 }
1085
VisitObjCProtocolDecl(ObjCProtocolDecl * PID)1086 bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1087 if (!PID->isThisDeclarationADefinition())
1088 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1089
1090 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1091 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1092 E = PID->protocol_end(); I != E; ++I, ++PL)
1093 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1094 return true;
1095
1096 return VisitObjCContainerDecl(PID);
1097 }
1098
VisitObjCPropertyDecl(ObjCPropertyDecl * PD)1099 bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1100 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1101 return true;
1102
1103 // FIXME: This implements a workaround with @property declarations also being
1104 // installed in the DeclContext for the @interface. Eventually this code
1105 // should be removed.
1106 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1107 if (!CDecl || !CDecl->IsClassExtension())
1108 return false;
1109
1110 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1111 if (!ID)
1112 return false;
1113
1114 IdentifierInfo *PropertyId = PD->getIdentifier();
1115 ObjCPropertyDecl *prevDecl =
1116 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1117 PD->getQueryKind());
1118
1119 if (!prevDecl)
1120 return false;
1121
1122 // Visit synthesized methods since they will be skipped when visiting
1123 // the @interface.
1124 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1125 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1126 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1127 return true;
1128
1129 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1130 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1131 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1132 return true;
1133
1134 return false;
1135 }
1136
VisitObjCTypeParamList(ObjCTypeParamList * typeParamList)1137 bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1138 if (!typeParamList)
1139 return false;
1140
1141 for (auto *typeParam : *typeParamList) {
1142 // Visit the type parameter.
1143 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1144 return true;
1145 }
1146
1147 return false;
1148 }
1149
VisitObjCInterfaceDecl(ObjCInterfaceDecl * D)1150 bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1151 if (!D->isThisDeclarationADefinition()) {
1152 // Forward declaration is treated like a reference.
1153 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1154 }
1155
1156 // Objective-C type parameters.
1157 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1158 return true;
1159
1160 // Issue callbacks for super class.
1161 if (D->getSuperClass() &&
1162 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1163 D->getSuperClassLoc(),
1164 TU)))
1165 return true;
1166
1167 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1168 if (Visit(SuperClassTInfo->getTypeLoc()))
1169 return true;
1170
1171 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1172 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1173 E = D->protocol_end(); I != E; ++I, ++PL)
1174 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1175 return true;
1176
1177 return VisitObjCContainerDecl(D);
1178 }
1179
VisitObjCImplDecl(ObjCImplDecl * D)1180 bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1181 return VisitObjCContainerDecl(D);
1182 }
1183
VisitObjCCategoryImplDecl(ObjCCategoryImplDecl * D)1184 bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1185 // 'ID' could be null when dealing with invalid code.
1186 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1187 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1188 return true;
1189
1190 return VisitObjCImplDecl(D);
1191 }
1192
VisitObjCImplementationDecl(ObjCImplementationDecl * D)1193 bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1194 #if 0
1195 // Issue callbacks for super class.
1196 // FIXME: No source location information!
1197 if (D->getSuperClass() &&
1198 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1199 D->getSuperClassLoc(),
1200 TU)))
1201 return true;
1202 #endif
1203
1204 return VisitObjCImplDecl(D);
1205 }
1206
VisitObjCPropertyImplDecl(ObjCPropertyImplDecl * PD)1207 bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1208 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1209 if (PD->isIvarNameSpecified())
1210 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1211
1212 return false;
1213 }
1214
VisitNamespaceDecl(NamespaceDecl * D)1215 bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1216 return VisitDeclContext(D);
1217 }
1218
VisitNamespaceAliasDecl(NamespaceAliasDecl * D)1219 bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1220 // Visit nested-name-specifier.
1221 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1222 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1223 return true;
1224
1225 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1226 D->getTargetNameLoc(), TU));
1227 }
1228
VisitUsingDecl(UsingDecl * D)1229 bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1230 // Visit nested-name-specifier.
1231 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1232 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1233 return true;
1234 }
1235
1236 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1237 return true;
1238
1239 return VisitDeclarationNameInfo(D->getNameInfo());
1240 }
1241
VisitUsingDirectiveDecl(UsingDirectiveDecl * D)1242 bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1243 // Visit nested-name-specifier.
1244 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1245 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1246 return true;
1247
1248 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1249 D->getIdentLocation(), TU));
1250 }
1251
VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl * D)1252 bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1253 // Visit nested-name-specifier.
1254 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1255 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1256 return true;
1257 }
1258
1259 return VisitDeclarationNameInfo(D->getNameInfo());
1260 }
1261
VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl * D)1262 bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1263 UnresolvedUsingTypenameDecl *D) {
1264 // Visit nested-name-specifier.
1265 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1266 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1267 return true;
1268
1269 return false;
1270 }
1271
VisitStaticAssertDecl(StaticAssertDecl * D)1272 bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1273 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1274 return true;
1275 if (StringLiteral *Message = D->getMessage())
1276 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1277 return true;
1278 return false;
1279 }
1280
VisitFriendDecl(FriendDecl * D)1281 bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1282 if (NamedDecl *FriendD = D->getFriendDecl()) {
1283 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1284 return true;
1285 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1286 if (Visit(TI->getTypeLoc()))
1287 return true;
1288 }
1289 return false;
1290 }
1291
VisitDeclarationNameInfo(DeclarationNameInfo Name)1292 bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1293 switch (Name.getName().getNameKind()) {
1294 case clang::DeclarationName::Identifier:
1295 case clang::DeclarationName::CXXLiteralOperatorName:
1296 case clang::DeclarationName::CXXDeductionGuideName:
1297 case clang::DeclarationName::CXXOperatorName:
1298 case clang::DeclarationName::CXXUsingDirective:
1299 return false;
1300
1301 case clang::DeclarationName::CXXConstructorName:
1302 case clang::DeclarationName::CXXDestructorName:
1303 case clang::DeclarationName::CXXConversionFunctionName:
1304 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1305 return Visit(TSInfo->getTypeLoc());
1306 return false;
1307
1308 case clang::DeclarationName::ObjCZeroArgSelector:
1309 case clang::DeclarationName::ObjCOneArgSelector:
1310 case clang::DeclarationName::ObjCMultiArgSelector:
1311 // FIXME: Per-identifier location info?
1312 return false;
1313 }
1314
1315 llvm_unreachable("Invalid DeclarationName::Kind!");
1316 }
1317
VisitNestedNameSpecifier(NestedNameSpecifier * NNS,SourceRange Range)1318 bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1319 SourceRange Range) {
1320 // FIXME: This whole routine is a hack to work around the lack of proper
1321 // source information in nested-name-specifiers (PR5791). Since we do have
1322 // a beginning source location, we can visit the first component of the
1323 // nested-name-specifier, if it's a single-token component.
1324 if (!NNS)
1325 return false;
1326
1327 // Get the first component in the nested-name-specifier.
1328 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1329 NNS = Prefix;
1330
1331 switch (NNS->getKind()) {
1332 case NestedNameSpecifier::Namespace:
1333 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1334 TU));
1335
1336 case NestedNameSpecifier::NamespaceAlias:
1337 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1338 Range.getBegin(), TU));
1339
1340 case NestedNameSpecifier::TypeSpec: {
1341 // If the type has a form where we know that the beginning of the source
1342 // range matches up with a reference cursor. Visit the appropriate reference
1343 // cursor.
1344 const Type *T = NNS->getAsType();
1345 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1346 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1347 if (const TagType *Tag = dyn_cast<TagType>(T))
1348 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1349 if (const TemplateSpecializationType *TST
1350 = dyn_cast<TemplateSpecializationType>(T))
1351 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1352 break;
1353 }
1354
1355 case NestedNameSpecifier::TypeSpecWithTemplate:
1356 case NestedNameSpecifier::Global:
1357 case NestedNameSpecifier::Identifier:
1358 case NestedNameSpecifier::Super:
1359 break;
1360 }
1361
1362 return false;
1363 }
1364
1365 bool
VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier)1366 CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1367 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1368 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1369 Qualifiers.push_back(Qualifier);
1370
1371 while (!Qualifiers.empty()) {
1372 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1373 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1374 switch (NNS->getKind()) {
1375 case NestedNameSpecifier::Namespace:
1376 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1377 Q.getLocalBeginLoc(),
1378 TU)))
1379 return true;
1380
1381 break;
1382
1383 case NestedNameSpecifier::NamespaceAlias:
1384 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1385 Q.getLocalBeginLoc(),
1386 TU)))
1387 return true;
1388
1389 break;
1390
1391 case NestedNameSpecifier::TypeSpec:
1392 case NestedNameSpecifier::TypeSpecWithTemplate:
1393 if (Visit(Q.getTypeLoc()))
1394 return true;
1395
1396 break;
1397
1398 case NestedNameSpecifier::Global:
1399 case NestedNameSpecifier::Identifier:
1400 case NestedNameSpecifier::Super:
1401 break;
1402 }
1403 }
1404
1405 return false;
1406 }
1407
VisitTemplateParameters(const TemplateParameterList * Params)1408 bool CursorVisitor::VisitTemplateParameters(
1409 const TemplateParameterList *Params) {
1410 if (!Params)
1411 return false;
1412
1413 for (TemplateParameterList::const_iterator P = Params->begin(),
1414 PEnd = Params->end();
1415 P != PEnd; ++P) {
1416 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1417 return true;
1418 }
1419
1420 return false;
1421 }
1422
VisitTemplateName(TemplateName Name,SourceLocation Loc)1423 bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1424 switch (Name.getKind()) {
1425 case TemplateName::Template:
1426 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1427
1428 case TemplateName::OverloadedTemplate:
1429 // Visit the overloaded template set.
1430 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1431 return true;
1432
1433 return false;
1434
1435 case TemplateName::DependentTemplate:
1436 // FIXME: Visit nested-name-specifier.
1437 return false;
1438
1439 case TemplateName::QualifiedTemplate:
1440 // FIXME: Visit nested-name-specifier.
1441 return Visit(MakeCursorTemplateRef(
1442 Name.getAsQualifiedTemplateName()->getDecl(),
1443 Loc, TU));
1444
1445 case TemplateName::SubstTemplateTemplateParm:
1446 return Visit(MakeCursorTemplateRef(
1447 Name.getAsSubstTemplateTemplateParm()->getParameter(),
1448 Loc, TU));
1449
1450 case TemplateName::SubstTemplateTemplateParmPack:
1451 return Visit(MakeCursorTemplateRef(
1452 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1453 Loc, TU));
1454 }
1455
1456 llvm_unreachable("Invalid TemplateName::Kind!");
1457 }
1458
VisitTemplateArgumentLoc(const TemplateArgumentLoc & TAL)1459 bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1460 switch (TAL.getArgument().getKind()) {
1461 case TemplateArgument::Null:
1462 case TemplateArgument::Integral:
1463 case TemplateArgument::Pack:
1464 return false;
1465
1466 case TemplateArgument::Type:
1467 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1468 return Visit(TSInfo->getTypeLoc());
1469 return false;
1470
1471 case TemplateArgument::Declaration:
1472 if (Expr *E = TAL.getSourceDeclExpression())
1473 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1474 return false;
1475
1476 case TemplateArgument::NullPtr:
1477 if (Expr *E = TAL.getSourceNullPtrExpression())
1478 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1479 return false;
1480
1481 case TemplateArgument::Expression:
1482 if (Expr *E = TAL.getSourceExpression())
1483 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1484 return false;
1485
1486 case TemplateArgument::Template:
1487 case TemplateArgument::TemplateExpansion:
1488 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1489 return true;
1490
1491 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1492 TAL.getTemplateNameLoc());
1493 }
1494
1495 llvm_unreachable("Invalid TemplateArgument::Kind!");
1496 }
1497
VisitLinkageSpecDecl(LinkageSpecDecl * D)1498 bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1499 return VisitDeclContext(D);
1500 }
1501
VisitQualifiedTypeLoc(QualifiedTypeLoc TL)1502 bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1503 return Visit(TL.getUnqualifiedLoc());
1504 }
1505
VisitBuiltinTypeLoc(BuiltinTypeLoc TL)1506 bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1507 ASTContext &Context = AU->getASTContext();
1508
1509 // Some builtin types (such as Objective-C's "id", "sel", and
1510 // "Class") have associated declarations. Create cursors for those.
1511 QualType VisitType;
1512 switch (TL.getTypePtr()->getKind()) {
1513
1514 case BuiltinType::Void:
1515 case BuiltinType::NullPtr:
1516 case BuiltinType::Dependent:
1517 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1518 case BuiltinType::Id:
1519 #include "clang/Basic/OpenCLImageTypes.def"
1520 #define EXT_OPAQUE_TYPE(ExtTYpe, Id, Ext) \
1521 case BuiltinType::Id:
1522 #include "clang/Basic/OpenCLExtensionTypes.def"
1523 case BuiltinType::OCLSampler:
1524 case BuiltinType::OCLEvent:
1525 case BuiltinType::OCLClkEvent:
1526 case BuiltinType::OCLQueue:
1527 case BuiltinType::OCLReserveID:
1528 #define BUILTIN_TYPE(Id, SingletonId)
1529 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1530 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1531 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1532 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1533 #include "clang/AST/BuiltinTypes.def"
1534 break;
1535
1536 case BuiltinType::ObjCId:
1537 VisitType = Context.getObjCIdType();
1538 break;
1539
1540 case BuiltinType::ObjCClass:
1541 VisitType = Context.getObjCClassType();
1542 break;
1543
1544 case BuiltinType::ObjCSel:
1545 VisitType = Context.getObjCSelType();
1546 break;
1547 }
1548
1549 if (!VisitType.isNull()) {
1550 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1551 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1552 TU));
1553 }
1554
1555 return false;
1556 }
1557
VisitTypedefTypeLoc(TypedefTypeLoc TL)1558 bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1559 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1560 }
1561
VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL)1562 bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1563 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1564 }
1565
VisitTagTypeLoc(TagTypeLoc TL)1566 bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1567 if (TL.isDefinition())
1568 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1569
1570 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1571 }
1572
VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL)1573 bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1574 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1575 }
1576
VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL)1577 bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1578 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
1579 }
1580
VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL)1581 bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
1582 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU)))
1583 return true;
1584 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1585 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1586 TU)))
1587 return true;
1588 }
1589
1590 return false;
1591 }
1592
VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL)1593 bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1594 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1595 return true;
1596
1597 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1598 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1599 return true;
1600 }
1601
1602 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1603 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1604 TU)))
1605 return true;
1606 }
1607
1608 return false;
1609 }
1610
VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL)1611 bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1612 return Visit(TL.getPointeeLoc());
1613 }
1614
VisitParenTypeLoc(ParenTypeLoc TL)1615 bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1616 return Visit(TL.getInnerLoc());
1617 }
1618
VisitPointerTypeLoc(PointerTypeLoc TL)1619 bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1620 return Visit(TL.getPointeeLoc());
1621 }
1622
VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL)1623 bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1624 return Visit(TL.getPointeeLoc());
1625 }
1626
VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL)1627 bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1628 return Visit(TL.getPointeeLoc());
1629 }
1630
VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL)1631 bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1632 return Visit(TL.getPointeeLoc());
1633 }
1634
VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL)1635 bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1636 return Visit(TL.getPointeeLoc());
1637 }
1638
VisitAttributedTypeLoc(AttributedTypeLoc TL)1639 bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1640 return Visit(TL.getModifiedLoc());
1641 }
1642
VisitFunctionTypeLoc(FunctionTypeLoc TL,bool SkipResultType)1643 bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1644 bool SkipResultType) {
1645 if (!SkipResultType && Visit(TL.getReturnLoc()))
1646 return true;
1647
1648 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1649 if (Decl *D = TL.getParam(I))
1650 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1651 return true;
1652
1653 return false;
1654 }
1655
VisitArrayTypeLoc(ArrayTypeLoc TL)1656 bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1657 if (Visit(TL.getElementLoc()))
1658 return true;
1659
1660 if (Expr *Size = TL.getSizeExpr())
1661 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1662
1663 return false;
1664 }
1665
VisitDecayedTypeLoc(DecayedTypeLoc TL)1666 bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1667 return Visit(TL.getOriginalLoc());
1668 }
1669
VisitAdjustedTypeLoc(AdjustedTypeLoc TL)1670 bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1671 return Visit(TL.getOriginalLoc());
1672 }
1673
VisitDeducedTemplateSpecializationTypeLoc(DeducedTemplateSpecializationTypeLoc TL)1674 bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1675 DeducedTemplateSpecializationTypeLoc TL) {
1676 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1677 TL.getTemplateNameLoc()))
1678 return true;
1679
1680 return false;
1681 }
1682
VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL)1683 bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1684 TemplateSpecializationTypeLoc TL) {
1685 // Visit the template name.
1686 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1687 TL.getTemplateNameLoc()))
1688 return true;
1689
1690 // Visit the template arguments.
1691 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1692 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1693 return true;
1694
1695 return false;
1696 }
1697
VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL)1698 bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1699 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1700 }
1701
VisitTypeOfTypeLoc(TypeOfTypeLoc TL)1702 bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1703 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1704 return Visit(TSInfo->getTypeLoc());
1705
1706 return false;
1707 }
1708
VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL)1709 bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1710 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1711 return Visit(TSInfo->getTypeLoc());
1712
1713 return false;
1714 }
1715
VisitDependentNameTypeLoc(DependentNameTypeLoc TL)1716 bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1717 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
1718 }
1719
VisitDependentTemplateSpecializationTypeLoc(DependentTemplateSpecializationTypeLoc TL)1720 bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1721 DependentTemplateSpecializationTypeLoc TL) {
1722 // Visit the nested-name-specifier, if there is one.
1723 if (TL.getQualifierLoc() &&
1724 VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1725 return true;
1726
1727 // Visit the template arguments.
1728 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1729 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1730 return true;
1731
1732 return false;
1733 }
1734
VisitElaboratedTypeLoc(ElaboratedTypeLoc TL)1735 bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1736 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1737 return true;
1738
1739 return Visit(TL.getNamedTypeLoc());
1740 }
1741
VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL)1742 bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1743 return Visit(TL.getPatternLoc());
1744 }
1745
VisitDecltypeTypeLoc(DecltypeTypeLoc TL)1746 bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1747 if (Expr *E = TL.getUnderlyingExpr())
1748 return Visit(MakeCXCursor(E, StmtParent, TU));
1749
1750 return false;
1751 }
1752
VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL)1753 bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1754 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1755 }
1756
VisitAtomicTypeLoc(AtomicTypeLoc TL)1757 bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1758 return Visit(TL.getValueLoc());
1759 }
1760
VisitPipeTypeLoc(PipeTypeLoc TL)1761 bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1762 return Visit(TL.getValueLoc());
1763 }
1764
1765 #define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1766 bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1767 return Visit##PARENT##Loc(TL); \
1768 }
1769
DEFAULT_TYPELOC_IMPL(Complex,Type)1770 DEFAULT_TYPELOC_IMPL(Complex, Type)
1771 DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1772 DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1773 DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1774 DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1775 DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
1776 DEFAULT_TYPELOC_IMPL(DependentVector, Type)
1777 DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1778 DEFAULT_TYPELOC_IMPL(Vector, Type)
1779 DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1780 DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1781 DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1782 DEFAULT_TYPELOC_IMPL(Record, TagType)
1783 DEFAULT_TYPELOC_IMPL(Enum, TagType)
1784 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1785 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1786 DEFAULT_TYPELOC_IMPL(Auto, Type)
1787
1788 bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1789 // Visit the nested-name-specifier, if present.
1790 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1791 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1792 return true;
1793
1794 if (D->isCompleteDefinition()) {
1795 for (const auto &I : D->bases()) {
1796 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
1797 return true;
1798 }
1799 }
1800
1801 return VisitTagDecl(D);
1802 }
1803
VisitAttributes(Decl * D)1804 bool CursorVisitor::VisitAttributes(Decl *D) {
1805 for (const auto *I : D->attrs())
1806 if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes ||
1807 !I->isImplicit()) &&
1808 Visit(MakeCXCursor(I, D, TU)))
1809 return true;
1810
1811 return false;
1812 }
1813
1814 //===----------------------------------------------------------------------===//
1815 // Data-recursive visitor methods.
1816 //===----------------------------------------------------------------------===//
1817
1818 namespace {
1819 #define DEF_JOB(NAME, DATA, KIND)\
1820 class NAME : public VisitorJob {\
1821 public:\
1822 NAME(const DATA *d, CXCursor parent) : \
1823 VisitorJob(parent, VisitorJob::KIND, d) {} \
1824 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1825 const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
1826 };
1827
1828 DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1829 DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1830 DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1831 DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1832 DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1833 DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1834 DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1835 #undef DEF_JOB
1836
1837 class ExplicitTemplateArgsVisit : public VisitorJob {
1838 public:
ExplicitTemplateArgsVisit(const TemplateArgumentLoc * Begin,const TemplateArgumentLoc * End,CXCursor parent)1839 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1840 const TemplateArgumentLoc *End, CXCursor parent)
1841 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1842 End) {}
classof(const VisitorJob * VJ)1843 static bool classof(const VisitorJob *VJ) {
1844 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1845 }
begin() const1846 const TemplateArgumentLoc *begin() const {
1847 return static_cast<const TemplateArgumentLoc *>(data[0]);
1848 }
end()1849 const TemplateArgumentLoc *end() {
1850 return static_cast<const TemplateArgumentLoc *>(data[1]);
1851 }
1852 };
1853 class DeclVisit : public VisitorJob {
1854 public:
DeclVisit(const Decl * D,CXCursor parent,bool isFirst)1855 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) :
1856 VisitorJob(parent, VisitorJob::DeclVisitKind,
1857 D, isFirst ? (void*) 1 : (void*) nullptr) {}
classof(const VisitorJob * VJ)1858 static bool classof(const VisitorJob *VJ) {
1859 return VJ->getKind() == DeclVisitKind;
1860 }
get() const1861 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
isFirst() const1862 bool isFirst() const { return data[1] != nullptr; }
1863 };
1864 class TypeLocVisit : public VisitorJob {
1865 public:
TypeLocVisit(TypeLoc tl,CXCursor parent)1866 TypeLocVisit(TypeLoc tl, CXCursor parent) :
1867 VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1868 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1869
classof(const VisitorJob * VJ)1870 static bool classof(const VisitorJob *VJ) {
1871 return VJ->getKind() == TypeLocVisitKind;
1872 }
1873
get() const1874 TypeLoc get() const {
1875 QualType T = QualType::getFromOpaquePtr(data[0]);
1876 return TypeLoc(T, const_cast<void *>(data[1]));
1877 }
1878 };
1879
1880 class LabelRefVisit : public VisitorJob {
1881 public:
LabelRefVisit(LabelDecl * LD,SourceLocation labelLoc,CXCursor parent)1882 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1883 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1884 labelLoc.getPtrEncoding()) {}
1885
classof(const VisitorJob * VJ)1886 static bool classof(const VisitorJob *VJ) {
1887 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1888 }
get() const1889 const LabelDecl *get() const {
1890 return static_cast<const LabelDecl *>(data[0]);
1891 }
getLoc() const1892 SourceLocation getLoc() const {
1893 return SourceLocation::getFromPtrEncoding(data[1]); }
1894 };
1895
1896 class NestedNameSpecifierLocVisit : public VisitorJob {
1897 public:
NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier,CXCursor parent)1898 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1899 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1900 Qualifier.getNestedNameSpecifier(),
1901 Qualifier.getOpaqueData()) { }
1902
classof(const VisitorJob * VJ)1903 static bool classof(const VisitorJob *VJ) {
1904 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1905 }
1906
get() const1907 NestedNameSpecifierLoc get() const {
1908 return NestedNameSpecifierLoc(
1909 const_cast<NestedNameSpecifier *>(
1910 static_cast<const NestedNameSpecifier *>(data[0])),
1911 const_cast<void *>(data[1]));
1912 }
1913 };
1914
1915 class DeclarationNameInfoVisit : public VisitorJob {
1916 public:
DeclarationNameInfoVisit(const Stmt * S,CXCursor parent)1917 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
1918 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
classof(const VisitorJob * VJ)1919 static bool classof(const VisitorJob *VJ) {
1920 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1921 }
get() const1922 DeclarationNameInfo get() const {
1923 const Stmt *S = static_cast<const Stmt *>(data[0]);
1924 switch (S->getStmtClass()) {
1925 default:
1926 llvm_unreachable("Unhandled Stmt");
1927 case clang::Stmt::MSDependentExistsStmtClass:
1928 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1929 case Stmt::CXXDependentScopeMemberExprClass:
1930 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1931 case Stmt::DependentScopeDeclRefExprClass:
1932 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1933 case Stmt::OMPCriticalDirectiveClass:
1934 return cast<OMPCriticalDirective>(S)->getDirectiveName();
1935 }
1936 }
1937 };
1938 class MemberRefVisit : public VisitorJob {
1939 public:
MemberRefVisit(const FieldDecl * D,SourceLocation L,CXCursor parent)1940 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
1941 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1942 L.getPtrEncoding()) {}
classof(const VisitorJob * VJ)1943 static bool classof(const VisitorJob *VJ) {
1944 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1945 }
get() const1946 const FieldDecl *get() const {
1947 return static_cast<const FieldDecl *>(data[0]);
1948 }
getLoc() const1949 SourceLocation getLoc() const {
1950 return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1951 }
1952 };
1953 class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
1954 friend class OMPClauseEnqueue;
1955 VisitorWorkList &WL;
1956 CXCursor Parent;
1957 public:
EnqueueVisitor(VisitorWorkList & wl,CXCursor parent)1958 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1959 : WL(wl), Parent(parent) {}
1960
1961 void VisitAddrLabelExpr(const AddrLabelExpr *E);
1962 void VisitBlockExpr(const BlockExpr *B);
1963 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1964 void VisitCompoundStmt(const CompoundStmt *S);
VisitCXXDefaultArgExpr(const CXXDefaultArgExpr * E)1965 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1966 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1967 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1968 void VisitCXXNewExpr(const CXXNewExpr *E);
1969 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1970 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1971 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1972 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1973 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1974 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1975 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1976 void VisitCXXCatchStmt(const CXXCatchStmt *S);
1977 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
1978 void VisitDeclRefExpr(const DeclRefExpr *D);
1979 void VisitDeclStmt(const DeclStmt *S);
1980 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1981 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1982 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1983 void VisitForStmt(const ForStmt *FS);
1984 void VisitGotoStmt(const GotoStmt *GS);
1985 void VisitIfStmt(const IfStmt *If);
1986 void VisitInitListExpr(const InitListExpr *IE);
1987 void VisitMemberExpr(const MemberExpr *M);
1988 void VisitOffsetOfExpr(const OffsetOfExpr *E);
1989 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1990 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1991 void VisitOverloadExpr(const OverloadExpr *E);
1992 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1993 void VisitStmt(const Stmt *S);
1994 void VisitSwitchStmt(const SwitchStmt *S);
1995 void VisitWhileStmt(const WhileStmt *W);
1996 void VisitTypeTraitExpr(const TypeTraitExpr *E);
1997 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1998 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1999 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
2000 void VisitVAArgExpr(const VAArgExpr *E);
2001 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
2002 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
2003 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
2004 void VisitLambdaExpr(const LambdaExpr *E);
2005 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
2006 void VisitOMPLoopDirective(const OMPLoopDirective *D);
2007 void VisitOMPParallelDirective(const OMPParallelDirective *D);
2008 void VisitOMPSimdDirective(const OMPSimdDirective *D);
2009 void VisitOMPForDirective(const OMPForDirective *D);
2010 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
2011 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
2012 void VisitOMPSectionDirective(const OMPSectionDirective *D);
2013 void VisitOMPSingleDirective(const OMPSingleDirective *D);
2014 void VisitOMPMasterDirective(const OMPMasterDirective *D);
2015 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
2016 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
2017 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
2018 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
2019 void VisitOMPTaskDirective(const OMPTaskDirective *D);
2020 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
2021 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
2022 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
2023 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
2024 void
2025 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
2026 void VisitOMPCancelDirective(const OMPCancelDirective *D);
2027 void VisitOMPFlushDirective(const OMPFlushDirective *D);
2028 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
2029 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
2030 void VisitOMPTargetDirective(const OMPTargetDirective *D);
2031 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
2032 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
2033 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
2034 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
2035 void
2036 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
2037 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
2038 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
2039 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
2040 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
2041 void VisitOMPDistributeParallelForDirective(
2042 const OMPDistributeParallelForDirective *D);
2043 void VisitOMPDistributeParallelForSimdDirective(
2044 const OMPDistributeParallelForSimdDirective *D);
2045 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
2046 void VisitOMPTargetParallelForSimdDirective(
2047 const OMPTargetParallelForSimdDirective *D);
2048 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
2049 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
2050 void VisitOMPTeamsDistributeSimdDirective(
2051 const OMPTeamsDistributeSimdDirective *D);
2052 void VisitOMPTeamsDistributeParallelForSimdDirective(
2053 const OMPTeamsDistributeParallelForSimdDirective *D);
2054 void VisitOMPTeamsDistributeParallelForDirective(
2055 const OMPTeamsDistributeParallelForDirective *D);
2056 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
2057 void VisitOMPTargetTeamsDistributeDirective(
2058 const OMPTargetTeamsDistributeDirective *D);
2059 void VisitOMPTargetTeamsDistributeParallelForDirective(
2060 const OMPTargetTeamsDistributeParallelForDirective *D);
2061 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2062 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
2063 void VisitOMPTargetTeamsDistributeSimdDirective(
2064 const OMPTargetTeamsDistributeSimdDirective *D);
2065
2066 private:
2067 void AddDeclarationNameInfo(const Stmt *S);
2068 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
2069 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2070 unsigned NumTemplateArgs);
2071 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2072 void AddStmt(const Stmt *S);
2073 void AddDecl(const Decl *D, bool isFirst = true);
2074 void AddTypeLoc(TypeSourceInfo *TI);
2075 void EnqueueChildren(const Stmt *S);
2076 void EnqueueChildren(const OMPClause *S);
2077 };
2078 } // end anonyous namespace
2079
AddDeclarationNameInfo(const Stmt * S)2080 void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
2081 // 'S' should always be non-null, since it comes from the
2082 // statement we are visiting.
2083 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2084 }
2085
2086 void
AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier)2087 EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2088 if (Qualifier)
2089 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2090 }
2091
AddStmt(const Stmt * S)2092 void EnqueueVisitor::AddStmt(const Stmt *S) {
2093 if (S)
2094 WL.push_back(StmtVisit(S, Parent));
2095 }
AddDecl(const Decl * D,bool isFirst)2096 void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
2097 if (D)
2098 WL.push_back(DeclVisit(D, Parent, isFirst));
2099 }
AddExplicitTemplateArgs(const TemplateArgumentLoc * A,unsigned NumTemplateArgs)2100 void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2101 unsigned NumTemplateArgs) {
2102 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
2103 }
AddMemberRef(const FieldDecl * D,SourceLocation L)2104 void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
2105 if (D)
2106 WL.push_back(MemberRefVisit(D, L, Parent));
2107 }
AddTypeLoc(TypeSourceInfo * TI)2108 void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2109 if (TI)
2110 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2111 }
EnqueueChildren(const Stmt * S)2112 void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
2113 unsigned size = WL.size();
2114 for (const Stmt *SubStmt : S->children()) {
2115 AddStmt(SubStmt);
2116 }
2117 if (size == WL.size())
2118 return;
2119 // Now reverse the entries we just added. This will match the DFS
2120 // ordering performed by the worklist.
2121 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2122 std::reverse(I, E);
2123 }
2124 namespace {
2125 class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2126 EnqueueVisitor *Visitor;
2127 /// Process clauses with list of variables.
2128 template <typename T>
2129 void VisitOMPClauseList(T *Node);
2130 public:
OMPClauseEnqueue(EnqueueVisitor * Visitor)2131 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2132 #define OPENMP_CLAUSE(Name, Class) \
2133 void Visit##Class(const Class *C);
2134 #include "clang/Basic/OpenMPKinds.def"
2135 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
2136 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
2137 };
2138
VisitOMPClauseWithPreInit(const OMPClauseWithPreInit * C)2139 void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2140 const OMPClauseWithPreInit *C) {
2141 Visitor->AddStmt(C->getPreInitStmt());
2142 }
2143
VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate * C)2144 void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2145 const OMPClauseWithPostUpdate *C) {
2146 VisitOMPClauseWithPreInit(C);
2147 Visitor->AddStmt(C->getPostUpdateExpr());
2148 }
2149
VisitOMPIfClause(const OMPIfClause * C)2150 void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
2151 VisitOMPClauseWithPreInit(C);
2152 Visitor->AddStmt(C->getCondition());
2153 }
2154
VisitOMPFinalClause(const OMPFinalClause * C)2155 void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2156 Visitor->AddStmt(C->getCondition());
2157 }
2158
VisitOMPNumThreadsClause(const OMPNumThreadsClause * C)2159 void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
2160 VisitOMPClauseWithPreInit(C);
2161 Visitor->AddStmt(C->getNumThreads());
2162 }
2163
VisitOMPSafelenClause(const OMPSafelenClause * C)2164 void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2165 Visitor->AddStmt(C->getSafelen());
2166 }
2167
VisitOMPSimdlenClause(const OMPSimdlenClause * C)2168 void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2169 Visitor->AddStmt(C->getSimdlen());
2170 }
2171
VisitOMPCollapseClause(const OMPCollapseClause * C)2172 void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2173 Visitor->AddStmt(C->getNumForLoops());
2174 }
2175
VisitOMPDefaultClause(const OMPDefaultClause * C)2176 void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
2177
VisitOMPProcBindClause(const OMPProcBindClause * C)2178 void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2179
VisitOMPScheduleClause(const OMPScheduleClause * C)2180 void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
2181 VisitOMPClauseWithPreInit(C);
2182 Visitor->AddStmt(C->getChunkSize());
2183 }
2184
VisitOMPOrderedClause(const OMPOrderedClause * C)2185 void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2186 Visitor->AddStmt(C->getNumForLoops());
2187 }
2188
VisitOMPNowaitClause(const OMPNowaitClause *)2189 void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2190
VisitOMPUntiedClause(const OMPUntiedClause *)2191 void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2192
VisitOMPMergeableClause(const OMPMergeableClause *)2193 void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2194
VisitOMPReadClause(const OMPReadClause *)2195 void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2196
VisitOMPWriteClause(const OMPWriteClause *)2197 void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2198
VisitOMPUpdateClause(const OMPUpdateClause *)2199 void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2200
VisitOMPCaptureClause(const OMPCaptureClause *)2201 void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2202
VisitOMPSeqCstClause(const OMPSeqCstClause *)2203 void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2204
VisitOMPThreadsClause(const OMPThreadsClause *)2205 void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2206
VisitOMPSIMDClause(const OMPSIMDClause *)2207 void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2208
VisitOMPNogroupClause(const OMPNogroupClause *)2209 void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2210
VisitOMPUnifiedAddressClause(const OMPUnifiedAddressClause *)2211 void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2212 const OMPUnifiedAddressClause *) {}
2213
VisitOMPUnifiedSharedMemoryClause(const OMPUnifiedSharedMemoryClause *)2214 void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2215 const OMPUnifiedSharedMemoryClause *) {}
2216
VisitOMPReverseOffloadClause(const OMPReverseOffloadClause *)2217 void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2218 const OMPReverseOffloadClause *) {}
2219
VisitOMPDynamicAllocatorsClause(const OMPDynamicAllocatorsClause *)2220 void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2221 const OMPDynamicAllocatorsClause *) {}
2222
VisitOMPAtomicDefaultMemOrderClause(const OMPAtomicDefaultMemOrderClause *)2223 void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2224 const OMPAtomicDefaultMemOrderClause *) {}
2225
VisitOMPDeviceClause(const OMPDeviceClause * C)2226 void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2227 Visitor->AddStmt(C->getDevice());
2228 }
2229
VisitOMPNumTeamsClause(const OMPNumTeamsClause * C)2230 void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
2231 VisitOMPClauseWithPreInit(C);
2232 Visitor->AddStmt(C->getNumTeams());
2233 }
2234
VisitOMPThreadLimitClause(const OMPThreadLimitClause * C)2235 void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
2236 VisitOMPClauseWithPreInit(C);
2237 Visitor->AddStmt(C->getThreadLimit());
2238 }
2239
VisitOMPPriorityClause(const OMPPriorityClause * C)2240 void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2241 Visitor->AddStmt(C->getPriority());
2242 }
2243
VisitOMPGrainsizeClause(const OMPGrainsizeClause * C)2244 void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2245 Visitor->AddStmt(C->getGrainsize());
2246 }
2247
VisitOMPNumTasksClause(const OMPNumTasksClause * C)2248 void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2249 Visitor->AddStmt(C->getNumTasks());
2250 }
2251
VisitOMPHintClause(const OMPHintClause * C)2252 void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2253 Visitor->AddStmt(C->getHint());
2254 }
2255
2256 template<typename T>
VisitOMPClauseList(T * Node)2257 void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
2258 for (const auto *I : Node->varlists()) {
2259 Visitor->AddStmt(I);
2260 }
2261 }
2262
VisitOMPPrivateClause(const OMPPrivateClause * C)2263 void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
2264 VisitOMPClauseList(C);
2265 for (const auto *E : C->private_copies()) {
2266 Visitor->AddStmt(E);
2267 }
2268 }
VisitOMPFirstprivateClause(const OMPFirstprivateClause * C)2269 void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2270 const OMPFirstprivateClause *C) {
2271 VisitOMPClauseList(C);
2272 VisitOMPClauseWithPreInit(C);
2273 for (const auto *E : C->private_copies()) {
2274 Visitor->AddStmt(E);
2275 }
2276 for (const auto *E : C->inits()) {
2277 Visitor->AddStmt(E);
2278 }
2279 }
VisitOMPLastprivateClause(const OMPLastprivateClause * C)2280 void OMPClauseEnqueue::VisitOMPLastprivateClause(
2281 const OMPLastprivateClause *C) {
2282 VisitOMPClauseList(C);
2283 VisitOMPClauseWithPostUpdate(C);
2284 for (auto *E : C->private_copies()) {
2285 Visitor->AddStmt(E);
2286 }
2287 for (auto *E : C->source_exprs()) {
2288 Visitor->AddStmt(E);
2289 }
2290 for (auto *E : C->destination_exprs()) {
2291 Visitor->AddStmt(E);
2292 }
2293 for (auto *E : C->assignment_ops()) {
2294 Visitor->AddStmt(E);
2295 }
2296 }
VisitOMPSharedClause(const OMPSharedClause * C)2297 void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
2298 VisitOMPClauseList(C);
2299 }
VisitOMPReductionClause(const OMPReductionClause * C)2300 void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2301 VisitOMPClauseList(C);
2302 VisitOMPClauseWithPostUpdate(C);
2303 for (auto *E : C->privates()) {
2304 Visitor->AddStmt(E);
2305 }
2306 for (auto *E : C->lhs_exprs()) {
2307 Visitor->AddStmt(E);
2308 }
2309 for (auto *E : C->rhs_exprs()) {
2310 Visitor->AddStmt(E);
2311 }
2312 for (auto *E : C->reduction_ops()) {
2313 Visitor->AddStmt(E);
2314 }
2315 }
VisitOMPTaskReductionClause(const OMPTaskReductionClause * C)2316 void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2317 const OMPTaskReductionClause *C) {
2318 VisitOMPClauseList(C);
2319 VisitOMPClauseWithPostUpdate(C);
2320 for (auto *E : C->privates()) {
2321 Visitor->AddStmt(E);
2322 }
2323 for (auto *E : C->lhs_exprs()) {
2324 Visitor->AddStmt(E);
2325 }
2326 for (auto *E : C->rhs_exprs()) {
2327 Visitor->AddStmt(E);
2328 }
2329 for (auto *E : C->reduction_ops()) {
2330 Visitor->AddStmt(E);
2331 }
2332 }
VisitOMPInReductionClause(const OMPInReductionClause * C)2333 void OMPClauseEnqueue::VisitOMPInReductionClause(
2334 const OMPInReductionClause *C) {
2335 VisitOMPClauseList(C);
2336 VisitOMPClauseWithPostUpdate(C);
2337 for (auto *E : C->privates()) {
2338 Visitor->AddStmt(E);
2339 }
2340 for (auto *E : C->lhs_exprs()) {
2341 Visitor->AddStmt(E);
2342 }
2343 for (auto *E : C->rhs_exprs()) {
2344 Visitor->AddStmt(E);
2345 }
2346 for (auto *E : C->reduction_ops()) {
2347 Visitor->AddStmt(E);
2348 }
2349 for (auto *E : C->taskgroup_descriptors())
2350 Visitor->AddStmt(E);
2351 }
VisitOMPLinearClause(const OMPLinearClause * C)2352 void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2353 VisitOMPClauseList(C);
2354 VisitOMPClauseWithPostUpdate(C);
2355 for (const auto *E : C->privates()) {
2356 Visitor->AddStmt(E);
2357 }
2358 for (const auto *E : C->inits()) {
2359 Visitor->AddStmt(E);
2360 }
2361 for (const auto *E : C->updates()) {
2362 Visitor->AddStmt(E);
2363 }
2364 for (const auto *E : C->finals()) {
2365 Visitor->AddStmt(E);
2366 }
2367 Visitor->AddStmt(C->getStep());
2368 Visitor->AddStmt(C->getCalcStep());
2369 }
VisitOMPAlignedClause(const OMPAlignedClause * C)2370 void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2371 VisitOMPClauseList(C);
2372 Visitor->AddStmt(C->getAlignment());
2373 }
VisitOMPCopyinClause(const OMPCopyinClause * C)2374 void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2375 VisitOMPClauseList(C);
2376 for (auto *E : C->source_exprs()) {
2377 Visitor->AddStmt(E);
2378 }
2379 for (auto *E : C->destination_exprs()) {
2380 Visitor->AddStmt(E);
2381 }
2382 for (auto *E : C->assignment_ops()) {
2383 Visitor->AddStmt(E);
2384 }
2385 }
2386 void
VisitOMPCopyprivateClause(const OMPCopyprivateClause * C)2387 OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2388 VisitOMPClauseList(C);
2389 for (auto *E : C->source_exprs()) {
2390 Visitor->AddStmt(E);
2391 }
2392 for (auto *E : C->destination_exprs()) {
2393 Visitor->AddStmt(E);
2394 }
2395 for (auto *E : C->assignment_ops()) {
2396 Visitor->AddStmt(E);
2397 }
2398 }
VisitOMPFlushClause(const OMPFlushClause * C)2399 void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2400 VisitOMPClauseList(C);
2401 }
VisitOMPDependClause(const OMPDependClause * C)2402 void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2403 VisitOMPClauseList(C);
2404 }
VisitOMPMapClause(const OMPMapClause * C)2405 void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2406 VisitOMPClauseList(C);
2407 }
VisitOMPDistScheduleClause(const OMPDistScheduleClause * C)2408 void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2409 const OMPDistScheduleClause *C) {
2410 VisitOMPClauseWithPreInit(C);
2411 Visitor->AddStmt(C->getChunkSize());
2412 }
VisitOMPDefaultmapClause(const OMPDefaultmapClause *)2413 void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2414 const OMPDefaultmapClause * /*C*/) {}
VisitOMPToClause(const OMPToClause * C)2415 void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2416 VisitOMPClauseList(C);
2417 }
VisitOMPFromClause(const OMPFromClause * C)2418 void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2419 VisitOMPClauseList(C);
2420 }
VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause * C)2421 void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2422 VisitOMPClauseList(C);
2423 }
VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause * C)2424 void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2425 VisitOMPClauseList(C);
2426 }
2427 }
2428
EnqueueChildren(const OMPClause * S)2429 void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2430 unsigned size = WL.size();
2431 OMPClauseEnqueue Visitor(this);
2432 Visitor.Visit(S);
2433 if (size == WL.size())
2434 return;
2435 // Now reverse the entries we just added. This will match the DFS
2436 // ordering performed by the worklist.
2437 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2438 std::reverse(I, E);
2439 }
VisitAddrLabelExpr(const AddrLabelExpr * E)2440 void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
2441 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2442 }
VisitBlockExpr(const BlockExpr * B)2443 void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
2444 AddDecl(B->getBlockDecl());
2445 }
VisitCompoundLiteralExpr(const CompoundLiteralExpr * E)2446 void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2447 EnqueueChildren(E);
2448 AddTypeLoc(E->getTypeSourceInfo());
2449 }
VisitCompoundStmt(const CompoundStmt * S)2450 void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
2451 for (auto &I : llvm::reverse(S->body()))
2452 AddStmt(I);
2453 }
2454 void EnqueueVisitor::
VisitMSDependentExistsStmt(const MSDependentExistsStmt * S)2455 VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
2456 AddStmt(S->getSubStmt());
2457 AddDeclarationNameInfo(S);
2458 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2459 AddNestedNameSpecifierLoc(QualifierLoc);
2460 }
2461
2462 void EnqueueVisitor::
VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr * E)2463 VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
2464 if (E->hasExplicitTemplateArgs())
2465 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2466 AddDeclarationNameInfo(E);
2467 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2468 AddNestedNameSpecifierLoc(QualifierLoc);
2469 if (!E->isImplicitAccess())
2470 AddStmt(E->getBase());
2471 }
VisitCXXNewExpr(const CXXNewExpr * E)2472 void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
2473 // Enqueue the initializer , if any.
2474 AddStmt(E->getInitializer());
2475 // Enqueue the array size, if any.
2476 AddStmt(E->getArraySize());
2477 // Enqueue the allocated type.
2478 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2479 // Enqueue the placement arguments.
2480 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2481 AddStmt(E->getPlacementArg(I-1));
2482 }
VisitCXXOperatorCallExpr(const CXXOperatorCallExpr * CE)2483 void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
2484 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2485 AddStmt(CE->getArg(I-1));
2486 AddStmt(CE->getCallee());
2487 AddStmt(CE->getArg(0));
2488 }
VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr * E)2489 void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2490 const CXXPseudoDestructorExpr *E) {
2491 // Visit the name of the type being destroyed.
2492 AddTypeLoc(E->getDestroyedTypeInfo());
2493 // Visit the scope type that looks disturbingly like the nested-name-specifier
2494 // but isn't.
2495 AddTypeLoc(E->getScopeTypeInfo());
2496 // Visit the nested-name-specifier.
2497 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2498 AddNestedNameSpecifierLoc(QualifierLoc);
2499 // Visit base expression.
2500 AddStmt(E->getBase());
2501 }
VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr * E)2502 void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2503 const CXXScalarValueInitExpr *E) {
2504 AddTypeLoc(E->getTypeSourceInfo());
2505 }
VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr * E)2506 void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2507 const CXXTemporaryObjectExpr *E) {
2508 EnqueueChildren(E);
2509 AddTypeLoc(E->getTypeSourceInfo());
2510 }
VisitCXXTypeidExpr(const CXXTypeidExpr * E)2511 void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2512 EnqueueChildren(E);
2513 if (E->isTypeOperand())
2514 AddTypeLoc(E->getTypeOperandSourceInfo());
2515 }
2516
VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr * E)2517 void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2518 const CXXUnresolvedConstructExpr *E) {
2519 EnqueueChildren(E);
2520 AddTypeLoc(E->getTypeSourceInfo());
2521 }
VisitCXXUuidofExpr(const CXXUuidofExpr * E)2522 void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2523 EnqueueChildren(E);
2524 if (E->isTypeOperand())
2525 AddTypeLoc(E->getTypeOperandSourceInfo());
2526 }
2527
VisitCXXCatchStmt(const CXXCatchStmt * S)2528 void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
2529 EnqueueChildren(S);
2530 AddDecl(S->getExceptionDecl());
2531 }
2532
VisitCXXForRangeStmt(const CXXForRangeStmt * S)2533 void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
2534 AddStmt(S->getBody());
2535 AddStmt(S->getRangeInit());
2536 AddDecl(S->getLoopVariable());
2537 }
2538
VisitDeclRefExpr(const DeclRefExpr * DR)2539 void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
2540 if (DR->hasExplicitTemplateArgs())
2541 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
2542 WL.push_back(DeclRefExprParts(DR, Parent));
2543 }
VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr * E)2544 void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2545 const DependentScopeDeclRefExpr *E) {
2546 if (E->hasExplicitTemplateArgs())
2547 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2548 AddDeclarationNameInfo(E);
2549 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2550 }
VisitDeclStmt(const DeclStmt * S)2551 void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
2552 unsigned size = WL.size();
2553 bool isFirst = true;
2554 for (const auto *D : S->decls()) {
2555 AddDecl(D, isFirst);
2556 isFirst = false;
2557 }
2558 if (size == WL.size())
2559 return;
2560 // Now reverse the entries we just added. This will match the DFS
2561 // ordering performed by the worklist.
2562 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2563 std::reverse(I, E);
2564 }
VisitDesignatedInitExpr(const DesignatedInitExpr * E)2565 void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
2566 AddStmt(E->getInit());
2567 for (const DesignatedInitExpr::Designator &D :
2568 llvm::reverse(E->designators())) {
2569 if (D.isFieldDesignator()) {
2570 if (FieldDecl *Field = D.getField())
2571 AddMemberRef(Field, D.getFieldLoc());
2572 continue;
2573 }
2574 if (D.isArrayDesignator()) {
2575 AddStmt(E->getArrayIndex(D));
2576 continue;
2577 }
2578 assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2579 AddStmt(E->getArrayRangeEnd(D));
2580 AddStmt(E->getArrayRangeStart(D));
2581 }
2582 }
VisitExplicitCastExpr(const ExplicitCastExpr * E)2583 void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
2584 EnqueueChildren(E);
2585 AddTypeLoc(E->getTypeInfoAsWritten());
2586 }
VisitForStmt(const ForStmt * FS)2587 void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
2588 AddStmt(FS->getBody());
2589 AddStmt(FS->getInc());
2590 AddStmt(FS->getCond());
2591 AddDecl(FS->getConditionVariable());
2592 AddStmt(FS->getInit());
2593 }
VisitGotoStmt(const GotoStmt * GS)2594 void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
2595 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2596 }
VisitIfStmt(const IfStmt * If)2597 void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
2598 AddStmt(If->getElse());
2599 AddStmt(If->getThen());
2600 AddStmt(If->getCond());
2601 AddDecl(If->getConditionVariable());
2602 }
VisitInitListExpr(const InitListExpr * IE)2603 void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
2604 // We care about the syntactic form of the initializer list, only.
2605 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2606 IE = Syntactic;
2607 EnqueueChildren(IE);
2608 }
VisitMemberExpr(const MemberExpr * M)2609 void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
2610 WL.push_back(MemberExprParts(M, Parent));
2611
2612 // If the base of the member access expression is an implicit 'this', don't
2613 // visit it.
2614 // FIXME: If we ever want to show these implicit accesses, this will be
2615 // unfortunate. However, clang_getCursor() relies on this behavior.
2616 if (M->isImplicitAccess())
2617 return;
2618
2619 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2620 // real field that we are interested in.
2621 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2622 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2623 if (FD->isAnonymousStructOrUnion()) {
2624 AddStmt(SubME->getBase());
2625 return;
2626 }
2627 }
2628 }
2629
2630 AddStmt(M->getBase());
2631 }
VisitObjCEncodeExpr(const ObjCEncodeExpr * E)2632 void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
2633 AddTypeLoc(E->getEncodedTypeSourceInfo());
2634 }
VisitObjCMessageExpr(const ObjCMessageExpr * M)2635 void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
2636 EnqueueChildren(M);
2637 AddTypeLoc(M->getClassReceiverTypeInfo());
2638 }
VisitOffsetOfExpr(const OffsetOfExpr * E)2639 void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
2640 // Visit the components of the offsetof expression.
2641 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2642 const OffsetOfNode &Node = E->getComponent(I-1);
2643 switch (Node.getKind()) {
2644 case OffsetOfNode::Array:
2645 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2646 break;
2647 case OffsetOfNode::Field:
2648 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2649 break;
2650 case OffsetOfNode::Identifier:
2651 case OffsetOfNode::Base:
2652 continue;
2653 }
2654 }
2655 // Visit the type into which we're computing the offset.
2656 AddTypeLoc(E->getTypeSourceInfo());
2657 }
VisitOverloadExpr(const OverloadExpr * E)2658 void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
2659 if (E->hasExplicitTemplateArgs())
2660 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2661 WL.push_back(OverloadExprParts(E, Parent));
2662 }
VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr * E)2663 void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2664 const UnaryExprOrTypeTraitExpr *E) {
2665 EnqueueChildren(E);
2666 if (E->isArgumentType())
2667 AddTypeLoc(E->getArgumentTypeInfo());
2668 }
VisitStmt(const Stmt * S)2669 void EnqueueVisitor::VisitStmt(const Stmt *S) {
2670 EnqueueChildren(S);
2671 }
VisitSwitchStmt(const SwitchStmt * S)2672 void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
2673 AddStmt(S->getBody());
2674 AddStmt(S->getCond());
2675 AddDecl(S->getConditionVariable());
2676 }
2677
VisitWhileStmt(const WhileStmt * W)2678 void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
2679 AddStmt(W->getBody());
2680 AddStmt(W->getCond());
2681 AddDecl(W->getConditionVariable());
2682 }
2683
VisitTypeTraitExpr(const TypeTraitExpr * E)2684 void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
2685 for (unsigned I = E->getNumArgs(); I > 0; --I)
2686 AddTypeLoc(E->getArg(I-1));
2687 }
2688
VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr * E)2689 void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2690 AddTypeLoc(E->getQueriedTypeSourceInfo());
2691 }
2692
VisitExpressionTraitExpr(const ExpressionTraitExpr * E)2693 void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2694 EnqueueChildren(E);
2695 }
2696
VisitUnresolvedMemberExpr(const UnresolvedMemberExpr * U)2697 void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
2698 VisitOverloadExpr(U);
2699 if (!U->isImplicitAccess())
2700 AddStmt(U->getBase());
2701 }
VisitVAArgExpr(const VAArgExpr * E)2702 void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
2703 AddStmt(E->getSubExpr());
2704 AddTypeLoc(E->getWrittenTypeInfo());
2705 }
VisitSizeOfPackExpr(const SizeOfPackExpr * E)2706 void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2707 WL.push_back(SizeOfPackExprParts(E, Parent));
2708 }
VisitOpaqueValueExpr(const OpaqueValueExpr * E)2709 void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
2710 // If the opaque value has a source expression, just transparently
2711 // visit that. This is useful for (e.g.) pseudo-object expressions.
2712 if (Expr *SourceExpr = E->getSourceExpr())
2713 return Visit(SourceExpr);
2714 }
VisitLambdaExpr(const LambdaExpr * E)2715 void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
2716 AddStmt(E->getBody());
2717 WL.push_back(LambdaExprParts(E, Parent));
2718 }
VisitPseudoObjectExpr(const PseudoObjectExpr * E)2719 void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
2720 // Treat the expression like its syntactic form.
2721 Visit(E->getSyntacticForm());
2722 }
2723
VisitOMPExecutableDirective(const OMPExecutableDirective * D)2724 void EnqueueVisitor::VisitOMPExecutableDirective(
2725 const OMPExecutableDirective *D) {
2726 EnqueueChildren(D);
2727 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2728 E = D->clauses().end();
2729 I != E; ++I)
2730 EnqueueChildren(*I);
2731 }
2732
VisitOMPLoopDirective(const OMPLoopDirective * D)2733 void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2734 VisitOMPExecutableDirective(D);
2735 }
2736
VisitOMPParallelDirective(const OMPParallelDirective * D)2737 void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2738 VisitOMPExecutableDirective(D);
2739 }
2740
VisitOMPSimdDirective(const OMPSimdDirective * D)2741 void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
2742 VisitOMPLoopDirective(D);
2743 }
2744
VisitOMPForDirective(const OMPForDirective * D)2745 void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
2746 VisitOMPLoopDirective(D);
2747 }
2748
VisitOMPForSimdDirective(const OMPForSimdDirective * D)2749 void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2750 VisitOMPLoopDirective(D);
2751 }
2752
VisitOMPSectionsDirective(const OMPSectionsDirective * D)2753 void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2754 VisitOMPExecutableDirective(D);
2755 }
2756
VisitOMPSectionDirective(const OMPSectionDirective * D)2757 void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2758 VisitOMPExecutableDirective(D);
2759 }
2760
VisitOMPSingleDirective(const OMPSingleDirective * D)2761 void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2762 VisitOMPExecutableDirective(D);
2763 }
2764
VisitOMPMasterDirective(const OMPMasterDirective * D)2765 void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2766 VisitOMPExecutableDirective(D);
2767 }
2768
VisitOMPCriticalDirective(const OMPCriticalDirective * D)2769 void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2770 VisitOMPExecutableDirective(D);
2771 AddDeclarationNameInfo(D);
2772 }
2773
2774 void
VisitOMPParallelForDirective(const OMPParallelForDirective * D)2775 EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
2776 VisitOMPLoopDirective(D);
2777 }
2778
VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective * D)2779 void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2780 const OMPParallelForSimdDirective *D) {
2781 VisitOMPLoopDirective(D);
2782 }
2783
VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective * D)2784 void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2785 const OMPParallelSectionsDirective *D) {
2786 VisitOMPExecutableDirective(D);
2787 }
2788
VisitOMPTaskDirective(const OMPTaskDirective * D)2789 void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2790 VisitOMPExecutableDirective(D);
2791 }
2792
2793 void
VisitOMPTaskyieldDirective(const OMPTaskyieldDirective * D)2794 EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2795 VisitOMPExecutableDirective(D);
2796 }
2797
VisitOMPBarrierDirective(const OMPBarrierDirective * D)2798 void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2799 VisitOMPExecutableDirective(D);
2800 }
2801
VisitOMPTaskwaitDirective(const OMPTaskwaitDirective * D)2802 void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2803 VisitOMPExecutableDirective(D);
2804 }
2805
VisitOMPTaskgroupDirective(const OMPTaskgroupDirective * D)2806 void EnqueueVisitor::VisitOMPTaskgroupDirective(
2807 const OMPTaskgroupDirective *D) {
2808 VisitOMPExecutableDirective(D);
2809 if (const Expr *E = D->getReductionRef())
2810 VisitStmt(E);
2811 }
2812
VisitOMPFlushDirective(const OMPFlushDirective * D)2813 void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2814 VisitOMPExecutableDirective(D);
2815 }
2816
VisitOMPOrderedDirective(const OMPOrderedDirective * D)2817 void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2818 VisitOMPExecutableDirective(D);
2819 }
2820
VisitOMPAtomicDirective(const OMPAtomicDirective * D)2821 void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2822 VisitOMPExecutableDirective(D);
2823 }
2824
VisitOMPTargetDirective(const OMPTargetDirective * D)2825 void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2826 VisitOMPExecutableDirective(D);
2827 }
2828
VisitOMPTargetDataDirective(const OMPTargetDataDirective * D)2829 void EnqueueVisitor::VisitOMPTargetDataDirective(const
2830 OMPTargetDataDirective *D) {
2831 VisitOMPExecutableDirective(D);
2832 }
2833
VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective * D)2834 void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2835 const OMPTargetEnterDataDirective *D) {
2836 VisitOMPExecutableDirective(D);
2837 }
2838
VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective * D)2839 void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2840 const OMPTargetExitDataDirective *D) {
2841 VisitOMPExecutableDirective(D);
2842 }
2843
VisitOMPTargetParallelDirective(const OMPTargetParallelDirective * D)2844 void EnqueueVisitor::VisitOMPTargetParallelDirective(
2845 const OMPTargetParallelDirective *D) {
2846 VisitOMPExecutableDirective(D);
2847 }
2848
VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective * D)2849 void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2850 const OMPTargetParallelForDirective *D) {
2851 VisitOMPLoopDirective(D);
2852 }
2853
VisitOMPTeamsDirective(const OMPTeamsDirective * D)2854 void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2855 VisitOMPExecutableDirective(D);
2856 }
2857
VisitOMPCancellationPointDirective(const OMPCancellationPointDirective * D)2858 void EnqueueVisitor::VisitOMPCancellationPointDirective(
2859 const OMPCancellationPointDirective *D) {
2860 VisitOMPExecutableDirective(D);
2861 }
2862
VisitOMPCancelDirective(const OMPCancelDirective * D)2863 void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2864 VisitOMPExecutableDirective(D);
2865 }
2866
VisitOMPTaskLoopDirective(const OMPTaskLoopDirective * D)2867 void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2868 VisitOMPLoopDirective(D);
2869 }
2870
VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective * D)2871 void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2872 const OMPTaskLoopSimdDirective *D) {
2873 VisitOMPLoopDirective(D);
2874 }
2875
VisitOMPDistributeDirective(const OMPDistributeDirective * D)2876 void EnqueueVisitor::VisitOMPDistributeDirective(
2877 const OMPDistributeDirective *D) {
2878 VisitOMPLoopDirective(D);
2879 }
2880
VisitOMPDistributeParallelForDirective(const OMPDistributeParallelForDirective * D)2881 void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2882 const OMPDistributeParallelForDirective *D) {
2883 VisitOMPLoopDirective(D);
2884 }
2885
VisitOMPDistributeParallelForSimdDirective(const OMPDistributeParallelForSimdDirective * D)2886 void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2887 const OMPDistributeParallelForSimdDirective *D) {
2888 VisitOMPLoopDirective(D);
2889 }
2890
VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective * D)2891 void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2892 const OMPDistributeSimdDirective *D) {
2893 VisitOMPLoopDirective(D);
2894 }
2895
VisitOMPTargetParallelForSimdDirective(const OMPTargetParallelForSimdDirective * D)2896 void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2897 const OMPTargetParallelForSimdDirective *D) {
2898 VisitOMPLoopDirective(D);
2899 }
2900
VisitOMPTargetSimdDirective(const OMPTargetSimdDirective * D)2901 void EnqueueVisitor::VisitOMPTargetSimdDirective(
2902 const OMPTargetSimdDirective *D) {
2903 VisitOMPLoopDirective(D);
2904 }
2905
VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective * D)2906 void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2907 const OMPTeamsDistributeDirective *D) {
2908 VisitOMPLoopDirective(D);
2909 }
2910
VisitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective * D)2911 void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2912 const OMPTeamsDistributeSimdDirective *D) {
2913 VisitOMPLoopDirective(D);
2914 }
2915
VisitOMPTeamsDistributeParallelForSimdDirective(const OMPTeamsDistributeParallelForSimdDirective * D)2916 void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2917 const OMPTeamsDistributeParallelForSimdDirective *D) {
2918 VisitOMPLoopDirective(D);
2919 }
2920
VisitOMPTeamsDistributeParallelForDirective(const OMPTeamsDistributeParallelForDirective * D)2921 void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2922 const OMPTeamsDistributeParallelForDirective *D) {
2923 VisitOMPLoopDirective(D);
2924 }
2925
VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective * D)2926 void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2927 const OMPTargetTeamsDirective *D) {
2928 VisitOMPExecutableDirective(D);
2929 }
2930
VisitOMPTargetTeamsDistributeDirective(const OMPTargetTeamsDistributeDirective * D)2931 void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2932 const OMPTargetTeamsDistributeDirective *D) {
2933 VisitOMPLoopDirective(D);
2934 }
2935
VisitOMPTargetTeamsDistributeParallelForDirective(const OMPTargetTeamsDistributeParallelForDirective * D)2936 void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2937 const OMPTargetTeamsDistributeParallelForDirective *D) {
2938 VisitOMPLoopDirective(D);
2939 }
2940
VisitOMPTargetTeamsDistributeParallelForSimdDirective(const OMPTargetTeamsDistributeParallelForSimdDirective * D)2941 void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2942 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2943 VisitOMPLoopDirective(D);
2944 }
2945
VisitOMPTargetTeamsDistributeSimdDirective(const OMPTargetTeamsDistributeSimdDirective * D)2946 void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2947 const OMPTargetTeamsDistributeSimdDirective *D) {
2948 VisitOMPLoopDirective(D);
2949 }
2950
EnqueueWorkList(VisitorWorkList & WL,const Stmt * S)2951 void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
2952 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2953 }
2954
IsInRegionOfInterest(CXCursor C)2955 bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2956 if (RegionOfInterest.isValid()) {
2957 SourceRange Range = getRawCursorExtent(C);
2958 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2959 return false;
2960 }
2961 return true;
2962 }
2963
RunVisitorWorkList(VisitorWorkList & WL)2964 bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2965 while (!WL.empty()) {
2966 // Dequeue the worklist item.
2967 VisitorJob LI = WL.pop_back_val();
2968
2969 // Set the Parent field, then back to its old value once we're done.
2970 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2971
2972 switch (LI.getKind()) {
2973 case VisitorJob::DeclVisitKind: {
2974 const Decl *D = cast<DeclVisit>(&LI)->get();
2975 if (!D)
2976 continue;
2977
2978 // For now, perform default visitation for Decls.
2979 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2980 cast<DeclVisit>(&LI)->isFirst())))
2981 return true;
2982
2983 continue;
2984 }
2985 case VisitorJob::ExplicitTemplateArgsVisitKind: {
2986 for (const TemplateArgumentLoc &Arg :
2987 *cast<ExplicitTemplateArgsVisit>(&LI)) {
2988 if (VisitTemplateArgumentLoc(Arg))
2989 return true;
2990 }
2991 continue;
2992 }
2993 case VisitorJob::TypeLocVisitKind: {
2994 // Perform default visitation for TypeLocs.
2995 if (Visit(cast<TypeLocVisit>(&LI)->get()))
2996 return true;
2997 continue;
2998 }
2999 case VisitorJob::LabelRefVisitKind: {
3000 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
3001 if (LabelStmt *stmt = LS->getStmt()) {
3002 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3003 TU))) {
3004 return true;
3005 }
3006 }
3007 continue;
3008 }
3009
3010 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3011 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3012 if (VisitNestedNameSpecifierLoc(V->get()))
3013 return true;
3014 continue;
3015 }
3016
3017 case VisitorJob::DeclarationNameInfoVisitKind: {
3018 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3019 ->get()))
3020 return true;
3021 continue;
3022 }
3023 case VisitorJob::MemberRefVisitKind: {
3024 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3025 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3026 return true;
3027 continue;
3028 }
3029 case VisitorJob::StmtVisitKind: {
3030 const Stmt *S = cast<StmtVisit>(&LI)->get();
3031 if (!S)
3032 continue;
3033
3034 // Update the current cursor.
3035 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3036 if (!IsInRegionOfInterest(Cursor))
3037 continue;
3038 switch (Visitor(Cursor, Parent, ClientData)) {
3039 case CXChildVisit_Break: return true;
3040 case CXChildVisit_Continue: break;
3041 case CXChildVisit_Recurse:
3042 if (PostChildrenVisitor)
3043 WL.push_back(PostChildrenVisit(nullptr, Cursor));
3044 EnqueueWorkList(WL, S);
3045 break;
3046 }
3047 continue;
3048 }
3049 case VisitorJob::MemberExprPartsKind: {
3050 // Handle the other pieces in the MemberExpr besides the base.
3051 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
3052
3053 // Visit the nested-name-specifier
3054 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3055 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3056 return true;
3057
3058 // Visit the declaration name.
3059 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3060 return true;
3061
3062 // Visit the explicitly-specified template arguments, if any.
3063 if (M->hasExplicitTemplateArgs()) {
3064 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3065 *ArgEnd = Arg + M->getNumTemplateArgs();
3066 Arg != ArgEnd; ++Arg) {
3067 if (VisitTemplateArgumentLoc(*Arg))
3068 return true;
3069 }
3070 }
3071 continue;
3072 }
3073 case VisitorJob::DeclRefExprPartsKind: {
3074 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
3075 // Visit nested-name-specifier, if present.
3076 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3077 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3078 return true;
3079 // Visit declaration name.
3080 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3081 return true;
3082 continue;
3083 }
3084 case VisitorJob::OverloadExprPartsKind: {
3085 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
3086 // Visit the nested-name-specifier.
3087 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3088 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3089 return true;
3090 // Visit the declaration name.
3091 if (VisitDeclarationNameInfo(O->getNameInfo()))
3092 return true;
3093 // Visit the overloaded declaration reference.
3094 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3095 return true;
3096 continue;
3097 }
3098 case VisitorJob::SizeOfPackExprPartsKind: {
3099 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
3100 NamedDecl *Pack = E->getPack();
3101 if (isa<TemplateTypeParmDecl>(Pack)) {
3102 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3103 E->getPackLoc(), TU)))
3104 return true;
3105
3106 continue;
3107 }
3108
3109 if (isa<TemplateTemplateParmDecl>(Pack)) {
3110 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3111 E->getPackLoc(), TU)))
3112 return true;
3113
3114 continue;
3115 }
3116
3117 // Non-type template parameter packs and function parameter packs are
3118 // treated like DeclRefExpr cursors.
3119 continue;
3120 }
3121
3122 case VisitorJob::LambdaExprPartsKind: {
3123 // Visit captures.
3124 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
3125 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3126 CEnd = E->explicit_capture_end();
3127 C != CEnd; ++C) {
3128 // FIXME: Lambda init-captures.
3129 if (!C->capturesVariable())
3130 continue;
3131
3132 if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3133 C->getLocation(),
3134 TU)))
3135 return true;
3136 }
3137
3138 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3139 // Visit parameters and return type, if present.
3140 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3141 if (E->hasExplicitParameters()) {
3142 // Visit parameters.
3143 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3144 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
3145 return true;
3146 }
3147 if (E->hasExplicitResultType()) {
3148 // Visit result type.
3149 if (Visit(Proto.getReturnLoc()))
3150 return true;
3151 }
3152 }
3153 break;
3154 }
3155
3156 case VisitorJob::PostChildrenVisitKind:
3157 if (PostChildrenVisitor(Parent, ClientData))
3158 return true;
3159 break;
3160 }
3161 }
3162 return false;
3163 }
3164
Visit(const Stmt * S)3165 bool CursorVisitor::Visit(const Stmt *S) {
3166 VisitorWorkList *WL = nullptr;
3167 if (!WorkListFreeList.empty()) {
3168 WL = WorkListFreeList.back();
3169 WL->clear();
3170 WorkListFreeList.pop_back();
3171 }
3172 else {
3173 WL = new VisitorWorkList();
3174 WorkListCache.push_back(WL);
3175 }
3176 EnqueueWorkList(*WL, S);
3177 bool result = RunVisitorWorkList(*WL);
3178 WorkListFreeList.push_back(WL);
3179 return result;
3180 }
3181
3182 namespace {
3183 typedef SmallVector<SourceRange, 4> RefNamePieces;
buildPieces(unsigned NameFlags,bool IsMemberRefExpr,const DeclarationNameInfo & NI,SourceRange QLoc,const SourceRange * TemplateArgsLoc=nullptr)3184 RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3185 const DeclarationNameInfo &NI, SourceRange QLoc,
3186 const SourceRange *TemplateArgsLoc = nullptr) {
3187 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3188 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3189 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3190
3191 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3192
3193 RefNamePieces Pieces;
3194
3195 if (WantQualifier && QLoc.isValid())
3196 Pieces.push_back(QLoc);
3197
3198 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3199 Pieces.push_back(NI.getLoc());
3200
3201 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3202 Pieces.push_back(*TemplateArgsLoc);
3203
3204 if (Kind == DeclarationName::CXXOperatorName) {
3205 Pieces.push_back(SourceLocation::getFromRawEncoding(
3206 NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3207 Pieces.push_back(SourceLocation::getFromRawEncoding(
3208 NI.getInfo().CXXOperatorName.EndOpNameLoc));
3209 }
3210
3211 if (WantSinglePiece) {
3212 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3213 Pieces.clear();
3214 Pieces.push_back(R);
3215 }
3216
3217 return Pieces;
3218 }
3219 }
3220
3221 //===----------------------------------------------------------------------===//
3222 // Misc. API hooks.
3223 //===----------------------------------------------------------------------===//
3224
fatal_error_handler(void * user_data,const std::string & reason,bool gen_crash_diag)3225 static void fatal_error_handler(void *user_data, const std::string& reason,
3226 bool gen_crash_diag) {
3227 // Write the result out to stderr avoiding errs() because raw_ostreams can
3228 // call report_fatal_error.
3229 fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
3230 ::abort();
3231 }
3232
3233 namespace {
3234 struct RegisterFatalErrorHandler {
RegisterFatalErrorHandler__anon6db094c80511::RegisterFatalErrorHandler3235 RegisterFatalErrorHandler() {
3236 llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3237 }
3238 };
3239 }
3240
3241 static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3242
clang_createIndex(int excludeDeclarationsFromPCH,int displayDiagnostics)3243 CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3244 int displayDiagnostics) {
3245 // We use crash recovery to make some of our APIs more reliable, implicitly
3246 // enable it.
3247 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3248 llvm::CrashRecoveryContext::Enable();
3249
3250 // Look through the managed static to trigger construction of the managed
3251 // static which registers our fatal error handler. This ensures it is only
3252 // registered once.
3253 (void)*RegisterFatalErrorHandlerOnce;
3254
3255 // Initialize targets for clang module support.
3256 llvm::InitializeAllTargets();
3257 llvm::InitializeAllTargetMCs();
3258 llvm::InitializeAllAsmPrinters();
3259 llvm::InitializeAllAsmParsers();
3260
3261 CIndexer *CIdxr = new CIndexer();
3262
3263 if (excludeDeclarationsFromPCH)
3264 CIdxr->setOnlyLocalDecls();
3265 if (displayDiagnostics)
3266 CIdxr->setDisplayDiagnostics();
3267
3268 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3269 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3270 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3271 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3272 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3273 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3274
3275 return CIdxr;
3276 }
3277
clang_disposeIndex(CXIndex CIdx)3278 void clang_disposeIndex(CXIndex CIdx) {
3279 if (CIdx)
3280 delete static_cast<CIndexer *>(CIdx);
3281 }
3282
clang_CXIndex_setGlobalOptions(CXIndex CIdx,unsigned options)3283 void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3284 if (CIdx)
3285 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3286 }
3287
clang_CXIndex_getGlobalOptions(CXIndex CIdx)3288 unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3289 if (CIdx)
3290 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3291 return 0;
3292 }
3293
clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,const char * Path)3294 void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3295 const char *Path) {
3296 if (CIdx)
3297 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3298 }
3299
clang_toggleCrashRecovery(unsigned isEnabled)3300 void clang_toggleCrashRecovery(unsigned isEnabled) {
3301 if (isEnabled)
3302 llvm::CrashRecoveryContext::Enable();
3303 else
3304 llvm::CrashRecoveryContext::Disable();
3305 }
3306
clang_createTranslationUnit(CXIndex CIdx,const char * ast_filename)3307 CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3308 const char *ast_filename) {
3309 CXTranslationUnit TU;
3310 enum CXErrorCode Result =
3311 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
3312 (void)Result;
3313 assert((TU && Result == CXError_Success) ||
3314 (!TU && Result != CXError_Success));
3315 return TU;
3316 }
3317
clang_createTranslationUnit2(CXIndex CIdx,const char * ast_filename,CXTranslationUnit * out_TU)3318 enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3319 const char *ast_filename,
3320 CXTranslationUnit *out_TU) {
3321 if (out_TU)
3322 *out_TU = nullptr;
3323
3324 if (!CIdx || !ast_filename || !out_TU)
3325 return CXError_InvalidArguments;
3326
3327 LOG_FUNC_SECTION {
3328 *Log << ast_filename;
3329 }
3330
3331 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3332 FileSystemOptions FileSystemOpts;
3333
3334 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3335 CompilerInstance::createDiagnostics(new DiagnosticOptions());
3336 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
3337 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3338 ASTUnit::LoadEverything, Diags,
3339 FileSystemOpts, /*UseDebugInfo=*/false,
3340 CXXIdx->getOnlyLocalDecls(), None,
3341 /*CaptureDiagnostics=*/true,
3342 /*AllowPCHWithCompilerErrors=*/true,
3343 /*UserFilesAreVolatile=*/true);
3344 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
3345 return *out_TU ? CXError_Success : CXError_Failure;
3346 }
3347
clang_defaultEditingTranslationUnitOptions()3348 unsigned clang_defaultEditingTranslationUnitOptions() {
3349 return CXTranslationUnit_PrecompiledPreamble |
3350 CXTranslationUnit_CacheCompletionResults;
3351 }
3352
3353 CXTranslationUnit
clang_createTranslationUnitFromSourceFile(CXIndex CIdx,const char * source_filename,int num_command_line_args,const char * const * command_line_args,unsigned num_unsaved_files,struct CXUnsavedFile * unsaved_files)3354 clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3355 const char *source_filename,
3356 int num_command_line_args,
3357 const char * const *command_line_args,
3358 unsigned num_unsaved_files,
3359 struct CXUnsavedFile *unsaved_files) {
3360 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3361 return clang_parseTranslationUnit(CIdx, source_filename,
3362 command_line_args, num_command_line_args,
3363 unsaved_files, num_unsaved_files,
3364 Options);
3365 }
3366
3367 static CXErrorCode
clang_parseTranslationUnit_Impl(CXIndex CIdx,const char * source_filename,const char * const * command_line_args,int num_command_line_args,ArrayRef<CXUnsavedFile> unsaved_files,unsigned options,CXTranslationUnit * out_TU)3368 clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3369 const char *const *command_line_args,
3370 int num_command_line_args,
3371 ArrayRef<CXUnsavedFile> unsaved_files,
3372 unsigned options, CXTranslationUnit *out_TU) {
3373 // Set up the initial return values.
3374 if (out_TU)
3375 *out_TU = nullptr;
3376
3377 // Check arguments.
3378 if (!CIdx || !out_TU)
3379 return CXError_InvalidArguments;
3380
3381 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3382
3383 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3384 setThreadBackgroundPriority();
3385
3386 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
3387 bool CreatePreambleOnFirstParse =
3388 options & CXTranslationUnit_CreatePreambleOnFirstParse;
3389 // FIXME: Add a flag for modules.
3390 TranslationUnitKind TUKind
3391 = (options & (CXTranslationUnit_Incomplete |
3392 CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
3393 bool CacheCodeCompletionResults
3394 = options & CXTranslationUnit_CacheCompletionResults;
3395 bool IncludeBriefCommentsInCodeCompletion
3396 = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3397 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3398 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3399 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3400 if (options & CXTranslationUnit_SkipFunctionBodies) {
3401 SkipFunctionBodies =
3402 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3403 ? SkipFunctionBodiesScope::Preamble
3404 : SkipFunctionBodiesScope::PreambleAndMainFile;
3405 }
3406
3407 // Configure the diagnostics.
3408 IntrusiveRefCntPtr<DiagnosticsEngine>
3409 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
3410
3411 if (options & CXTranslationUnit_KeepGoing)
3412 Diags->setSuppressAfterFatalError(false);
3413
3414 // Recover resources if we crash before exiting this function.
3415 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3416 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
3417 DiagCleanup(Diags.get());
3418
3419 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3420 new std::vector<ASTUnit::RemappedFile>());
3421
3422 // Recover resources if we crash before exiting this function.
3423 llvm::CrashRecoveryContextCleanupRegistrar<
3424 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3425
3426 for (auto &UF : unsaved_files) {
3427 std::unique_ptr<llvm::MemoryBuffer> MB =
3428 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
3429 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
3430 }
3431
3432 std::unique_ptr<std::vector<const char *>> Args(
3433 new std::vector<const char *>());
3434
3435 // Recover resources if we crash before exiting this method.
3436 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3437 ArgsCleanup(Args.get());
3438
3439 // Since the Clang C library is primarily used by batch tools dealing with
3440 // (often very broken) source code, where spell-checking can have a
3441 // significant negative impact on performance (particularly when
3442 // precompiled headers are involved), we disable it by default.
3443 // Only do this if we haven't found a spell-checking-related argument.
3444 bool FoundSpellCheckingArgument = false;
3445 for (int I = 0; I != num_command_line_args; ++I) {
3446 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3447 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3448 FoundSpellCheckingArgument = true;
3449 break;
3450 }
3451 }
3452 Args->insert(Args->end(), command_line_args,
3453 command_line_args + num_command_line_args);
3454
3455 if (!FoundSpellCheckingArgument)
3456 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3457
3458 // The 'source_filename' argument is optional. If the caller does not
3459 // specify it then it is assumed that the source file is specified
3460 // in the actual argument list.
3461 // Put the source file after command_line_args otherwise if '-x' flag is
3462 // present it will be unused.
3463 if (source_filename)
3464 Args->push_back(source_filename);
3465
3466 // Do we need the detailed preprocessing record?
3467 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3468 Args->push_back("-Xclang");
3469 Args->push_back("-detailed-preprocessing-record");
3470 }
3471
3472 // Suppress any editor placeholder diagnostics.
3473 Args->push_back("-fallow-editor-placeholders");
3474
3475 unsigned NumErrors = Diags->getClient()->getNumErrors();
3476 std::unique_ptr<ASTUnit> ErrUnit;
3477 // Unless the user specified that they want the preamble on the first parse
3478 // set it up to be created on the first reparse. This makes the first parse
3479 // faster, trading for a slower (first) reparse.
3480 unsigned PrecompilePreambleAfterNParses =
3481 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
3482
3483 LibclangInvocationReporter InvocationReporter(
3484 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
3485 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3486 unsaved_files);
3487 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
3488 Args->data(), Args->data() + Args->size(),
3489 CXXIdx->getPCHContainerOperations(), Diags,
3490 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3491 /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
3492 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3493 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
3494 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
3495 /*UserFilesAreVolatile=*/true, ForSerialization,
3496 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3497 &ErrUnit));
3498
3499 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
3500 if (!Unit && !ErrUnit)
3501 return CXError_ASTReadError;
3502
3503 if (NumErrors != Diags->getClient()->getNumErrors()) {
3504 // Make sure to check that 'Unit' is non-NULL.
3505 if (CXXIdx->getDisplayDiagnostics())
3506 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3507 }
3508
3509 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3510 return CXError_ASTReadError;
3511
3512 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
3513 if (CXTranslationUnitImpl *TU = *out_TU) {
3514 TU->ParsingOptions = options;
3515 TU->Arguments.reserve(Args->size());
3516 for (const char *Arg : *Args)
3517 TU->Arguments.push_back(Arg);
3518 return CXError_Success;
3519 }
3520 return CXError_Failure;
3521 }
3522
3523 CXTranslationUnit
clang_parseTranslationUnit(CXIndex CIdx,const char * source_filename,const char * const * command_line_args,int num_command_line_args,struct CXUnsavedFile * unsaved_files,unsigned num_unsaved_files,unsigned options)3524 clang_parseTranslationUnit(CXIndex CIdx,
3525 const char *source_filename,
3526 const char *const *command_line_args,
3527 int num_command_line_args,
3528 struct CXUnsavedFile *unsaved_files,
3529 unsigned num_unsaved_files,
3530 unsigned options) {
3531 CXTranslationUnit TU;
3532 enum CXErrorCode Result = clang_parseTranslationUnit2(
3533 CIdx, source_filename, command_line_args, num_command_line_args,
3534 unsaved_files, num_unsaved_files, options, &TU);
3535 (void)Result;
3536 assert((TU && Result == CXError_Success) ||
3537 (!TU && Result != CXError_Success));
3538 return TU;
3539 }
3540
clang_parseTranslationUnit2(CXIndex CIdx,const char * source_filename,const char * const * command_line_args,int num_command_line_args,struct CXUnsavedFile * unsaved_files,unsigned num_unsaved_files,unsigned options,CXTranslationUnit * out_TU)3541 enum CXErrorCode clang_parseTranslationUnit2(
3542 CXIndex CIdx, const char *source_filename,
3543 const char *const *command_line_args, int num_command_line_args,
3544 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3545 unsigned options, CXTranslationUnit *out_TU) {
3546 SmallVector<const char *, 4> Args;
3547 Args.push_back("clang");
3548 Args.append(command_line_args, command_line_args + num_command_line_args);
3549 return clang_parseTranslationUnit2FullArgv(
3550 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3551 num_unsaved_files, options, out_TU);
3552 }
3553
clang_parseTranslationUnit2FullArgv(CXIndex CIdx,const char * source_filename,const char * const * command_line_args,int num_command_line_args,struct CXUnsavedFile * unsaved_files,unsigned num_unsaved_files,unsigned options,CXTranslationUnit * out_TU)3554 enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3555 CXIndex CIdx, const char *source_filename,
3556 const char *const *command_line_args, int num_command_line_args,
3557 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3558 unsigned options, CXTranslationUnit *out_TU) {
3559 LOG_FUNC_SECTION {
3560 *Log << source_filename << ": ";
3561 for (int i = 0; i != num_command_line_args; ++i)
3562 *Log << command_line_args[i] << " ";
3563 }
3564
3565 if (num_unsaved_files && !unsaved_files)
3566 return CXError_InvalidArguments;
3567
3568 CXErrorCode result = CXError_Failure;
3569 auto ParseTranslationUnitImpl = [=, &result] {
3570 result = clang_parseTranslationUnit_Impl(
3571 CIdx, source_filename, command_line_args, num_command_line_args,
3572 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3573 };
3574
3575 llvm::CrashRecoveryContext CRC;
3576
3577 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
3578 fprintf(stderr, "libclang: crash detected during parsing: {\n");
3579 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
3580 fprintf(stderr, " 'command_line_args' : [");
3581 for (int i = 0; i != num_command_line_args; ++i) {
3582 if (i)
3583 fprintf(stderr, ", ");
3584 fprintf(stderr, "'%s'", command_line_args[i]);
3585 }
3586 fprintf(stderr, "],\n");
3587 fprintf(stderr, " 'unsaved_files' : [");
3588 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3589 if (i)
3590 fprintf(stderr, ", ");
3591 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3592 unsaved_files[i].Length);
3593 }
3594 fprintf(stderr, "],\n");
3595 fprintf(stderr, " 'options' : %d,\n", options);
3596 fprintf(stderr, "}\n");
3597
3598 return CXError_Crashed;
3599 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3600 if (CXTranslationUnit *TU = out_TU)
3601 PrintLibclangResourceUsage(*TU);
3602 }
3603
3604 return result;
3605 }
3606
clang_Type_getObjCEncoding(CXType CT)3607 CXString clang_Type_getObjCEncoding(CXType CT) {
3608 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3609 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3610 std::string encoding;
3611 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3612 encoding);
3613
3614 return cxstring::createDup(encoding);
3615 }
3616
getMacroIdentifier(CXCursor C)3617 static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3618 if (C.kind == CXCursor_MacroDefinition) {
3619 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3620 return MDR->getName();
3621 } else if (C.kind == CXCursor_MacroExpansion) {
3622 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3623 return ME.getName();
3624 }
3625 return nullptr;
3626 }
3627
clang_Cursor_isMacroFunctionLike(CXCursor C)3628 unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3629 const IdentifierInfo *II = getMacroIdentifier(C);
3630 if (!II) {
3631 return false;
3632 }
3633 ASTUnit *ASTU = getCursorASTUnit(C);
3634 Preprocessor &PP = ASTU->getPreprocessor();
3635 if (const MacroInfo *MI = PP.getMacroInfo(II))
3636 return MI->isFunctionLike();
3637 return false;
3638 }
3639
clang_Cursor_isMacroBuiltin(CXCursor C)3640 unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3641 const IdentifierInfo *II = getMacroIdentifier(C);
3642 if (!II) {
3643 return false;
3644 }
3645 ASTUnit *ASTU = getCursorASTUnit(C);
3646 Preprocessor &PP = ASTU->getPreprocessor();
3647 if (const MacroInfo *MI = PP.getMacroInfo(II))
3648 return MI->isBuiltinMacro();
3649 return false;
3650 }
3651
clang_Cursor_isFunctionInlined(CXCursor C)3652 unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3653 const Decl *D = getCursorDecl(C);
3654 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3655 if (!FD) {
3656 return false;
3657 }
3658 return FD->isInlined();
3659 }
3660
getCFSTR_value(CallExpr * callExpr)3661 static StringLiteral* getCFSTR_value(CallExpr *callExpr) {
3662 if (callExpr->getNumArgs() != 1) {
3663 return nullptr;
3664 }
3665
3666 StringLiteral *S = nullptr;
3667 auto *arg = callExpr->getArg(0);
3668 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3669 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3670 auto *subExpr = I->getSubExprAsWritten();
3671
3672 if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3673 return nullptr;
3674 }
3675
3676 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3677 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3678 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3679 } else {
3680 return nullptr;
3681 }
3682 return S;
3683 }
3684
3685 struct ExprEvalResult {
3686 CXEvalResultKind EvalType;
3687 union {
3688 unsigned long long unsignedVal;
3689 long long intVal;
3690 double floatVal;
3691 char *stringVal;
3692 } EvalData;
3693 bool IsUnsignedInt;
~ExprEvalResultExprEvalResult3694 ~ExprEvalResult() {
3695 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3696 EvalType != CXEval_Int) {
3697 delete[] EvalData.stringVal;
3698 }
3699 }
3700 };
3701
clang_EvalResult_dispose(CXEvalResult E)3702 void clang_EvalResult_dispose(CXEvalResult E) {
3703 delete static_cast<ExprEvalResult *>(E);
3704 }
3705
clang_EvalResult_getKind(CXEvalResult E)3706 CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3707 if (!E) {
3708 return CXEval_UnExposed;
3709 }
3710 return ((ExprEvalResult *)E)->EvalType;
3711 }
3712
clang_EvalResult_getAsInt(CXEvalResult E)3713 int clang_EvalResult_getAsInt(CXEvalResult E) {
3714 return clang_EvalResult_getAsLongLong(E);
3715 }
3716
clang_EvalResult_getAsLongLong(CXEvalResult E)3717 long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
3718 if (!E) {
3719 return 0;
3720 }
3721 ExprEvalResult *Result = (ExprEvalResult*)E;
3722 if (Result->IsUnsignedInt)
3723 return Result->EvalData.unsignedVal;
3724 return Result->EvalData.intVal;
3725 }
3726
clang_EvalResult_isUnsignedInt(CXEvalResult E)3727 unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3728 return ((ExprEvalResult *)E)->IsUnsignedInt;
3729 }
3730
clang_EvalResult_getAsUnsigned(CXEvalResult E)3731 unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3732 if (!E) {
3733 return 0;
3734 }
3735
3736 ExprEvalResult *Result = (ExprEvalResult*)E;
3737 if (Result->IsUnsignedInt)
3738 return Result->EvalData.unsignedVal;
3739 return Result->EvalData.intVal;
3740 }
3741
clang_EvalResult_getAsDouble(CXEvalResult E)3742 double clang_EvalResult_getAsDouble(CXEvalResult E) {
3743 if (!E) {
3744 return 0;
3745 }
3746 return ((ExprEvalResult *)E)->EvalData.floatVal;
3747 }
3748
clang_EvalResult_getAsStr(CXEvalResult E)3749 const char* clang_EvalResult_getAsStr(CXEvalResult E) {
3750 if (!E) {
3751 return nullptr;
3752 }
3753 return ((ExprEvalResult *)E)->EvalData.stringVal;
3754 }
3755
evaluateExpr(Expr * expr,CXCursor C)3756 static const ExprEvalResult* evaluateExpr(Expr *expr, CXCursor C) {
3757 Expr::EvalResult ER;
3758 ASTContext &ctx = getCursorContext(C);
3759 if (!expr)
3760 return nullptr;
3761
3762 expr = expr->IgnoreParens();
3763 if (!expr->EvaluateAsRValue(ER, ctx))
3764 return nullptr;
3765
3766 QualType rettype;
3767 CallExpr *callExpr;
3768 auto result = llvm::make_unique<ExprEvalResult>();
3769 result->EvalType = CXEval_UnExposed;
3770 result->IsUnsignedInt = false;
3771
3772 if (ER.Val.isInt()) {
3773 result->EvalType = CXEval_Int;
3774
3775 auto& val = ER.Val.getInt();
3776 if (val.isUnsigned()) {
3777 result->IsUnsignedInt = true;
3778 result->EvalData.unsignedVal = val.getZExtValue();
3779 } else {
3780 result->EvalData.intVal = val.getExtValue();
3781 }
3782
3783 return result.release();
3784 }
3785
3786 if (ER.Val.isFloat()) {
3787 llvm::SmallVector<char, 100> Buffer;
3788 ER.Val.getFloat().toString(Buffer);
3789 std::string floatStr(Buffer.data(), Buffer.size());
3790 result->EvalType = CXEval_Float;
3791 bool ignored;
3792 llvm::APFloat apFloat = ER.Val.getFloat();
3793 apFloat.convert(llvm::APFloat::IEEEdouble(),
3794 llvm::APFloat::rmNearestTiesToEven, &ignored);
3795 result->EvalData.floatVal = apFloat.convertToDouble();
3796 return result.release();
3797 }
3798
3799 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3800 const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3801 auto *subExpr = I->getSubExprAsWritten();
3802 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3803 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
3804 const StringLiteral *StrE = nullptr;
3805 const ObjCStringLiteral *ObjCExpr;
3806 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
3807
3808 if (ObjCExpr) {
3809 StrE = ObjCExpr->getString();
3810 result->EvalType = CXEval_ObjCStrLiteral;
3811 } else {
3812 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
3813 result->EvalType = CXEval_StrLiteral;
3814 }
3815
3816 std::string strRef(StrE->getString().str());
3817 result->EvalData.stringVal = new char[strRef.size() + 1];
3818 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3819 strRef.size());
3820 result->EvalData.stringVal[strRef.size()] = '\0';
3821 return result.release();
3822 }
3823 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3824 expr->getStmtClass() == Stmt::StringLiteralClass) {
3825 const StringLiteral *StrE = nullptr;
3826 const ObjCStringLiteral *ObjCExpr;
3827 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
3828
3829 if (ObjCExpr) {
3830 StrE = ObjCExpr->getString();
3831 result->EvalType = CXEval_ObjCStrLiteral;
3832 } else {
3833 StrE = cast<StringLiteral>(expr);
3834 result->EvalType = CXEval_StrLiteral;
3835 }
3836
3837 std::string strRef(StrE->getString().str());
3838 result->EvalData.stringVal = new char[strRef.size() + 1];
3839 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3840 result->EvalData.stringVal[strRef.size()] = '\0';
3841 return result.release();
3842 }
3843
3844 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3845 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
3846
3847 rettype = CC->getType();
3848 if (rettype.getAsString() == "CFStringRef" &&
3849 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
3850
3851 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3852 StringLiteral *S = getCFSTR_value(callExpr);
3853 if (S) {
3854 std::string strLiteral(S->getString().str());
3855 result->EvalType = CXEval_CFStr;
3856
3857 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3858 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3859 strLiteral.size());
3860 result->EvalData.stringVal[strLiteral.size()] = '\0';
3861 return result.release();
3862 }
3863 }
3864
3865 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3866 callExpr = static_cast<CallExpr *>(expr);
3867 rettype = callExpr->getCallReturnType(ctx);
3868
3869 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3870 return nullptr;
3871
3872 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3873 if (callExpr->getNumArgs() == 1 &&
3874 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3875 return nullptr;
3876 } else if (rettype.getAsString() == "CFStringRef") {
3877
3878 StringLiteral *S = getCFSTR_value(callExpr);
3879 if (S) {
3880 std::string strLiteral(S->getString().str());
3881 result->EvalType = CXEval_CFStr;
3882 result->EvalData.stringVal = new char[strLiteral.size() + 1];
3883 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3884 strLiteral.size());
3885 result->EvalData.stringVal[strLiteral.size()] = '\0';
3886 return result.release();
3887 }
3888 }
3889 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3890 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3891 ValueDecl *V = D->getDecl();
3892 if (V->getKind() == Decl::Function) {
3893 std::string strName = V->getNameAsString();
3894 result->EvalType = CXEval_Other;
3895 result->EvalData.stringVal = new char[strName.size() + 1];
3896 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3897 result->EvalData.stringVal[strName.size()] = '\0';
3898 return result.release();
3899 }
3900 }
3901
3902 return nullptr;
3903 }
3904
evaluateDeclExpr(const Decl * D)3905 static const Expr *evaluateDeclExpr(const Decl *D) {
3906 if (!D)
3907 return nullptr;
3908 if (auto *Var = dyn_cast<VarDecl>(D))
3909 return Var->getInit();
3910 else if (auto *Field = dyn_cast<FieldDecl>(D))
3911 return Field->getInClassInitializer();
3912 return nullptr;
3913 }
3914
evaluateCompoundStmtExpr(const CompoundStmt * CS)3915 static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
3916 assert(CS && "invalid compound statement");
3917 for (auto *bodyIterator : CS->body()) {
3918 if (const auto *E = dyn_cast<Expr>(bodyIterator))
3919 return E;
3920 }
3921 return nullptr;
3922 }
3923
clang_Cursor_Evaluate(CXCursor C)3924 CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3925 if (const Expr *E =
3926 clang_getCursorKind(C) == CXCursor_CompoundStmt
3927 ? evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)))
3928 : evaluateDeclExpr(getCursorDecl(C)))
3929 return const_cast<CXEvalResult>(
3930 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
3931 return nullptr;
3932 }
3933
clang_Cursor_hasAttrs(CXCursor C)3934 unsigned clang_Cursor_hasAttrs(CXCursor C) {
3935 const Decl *D = getCursorDecl(C);
3936 if (!D) {
3937 return 0;
3938 }
3939
3940 if (D->hasAttrs()) {
3941 return 1;
3942 }
3943
3944 return 0;
3945 }
clang_defaultSaveOptions(CXTranslationUnit TU)3946 unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3947 return CXSaveTranslationUnit_None;
3948 }
3949
clang_saveTranslationUnit_Impl(CXTranslationUnit TU,const char * FileName,unsigned options)3950 static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3951 const char *FileName,
3952 unsigned options) {
3953 CIndexer *CXXIdx = TU->CIdx;
3954 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3955 setThreadBackgroundPriority();
3956
3957 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3958 return hadError ? CXSaveError_Unknown : CXSaveError_None;
3959 }
3960
clang_saveTranslationUnit(CXTranslationUnit TU,const char * FileName,unsigned options)3961 int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
3962 unsigned options) {
3963 LOG_FUNC_SECTION {
3964 *Log << TU << ' ' << FileName;
3965 }
3966
3967 if (isNotUsableTU(TU)) {
3968 LOG_BAD_TU(TU);
3969 return CXSaveError_InvalidTU;
3970 }
3971
3972 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3973 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3974 if (!CXXUnit->hasSema())
3975 return CXSaveError_InvalidTU;
3976
3977 CXSaveError result;
3978 auto SaveTranslationUnitImpl = [=, &result]() {
3979 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
3980 };
3981
3982 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
3983 SaveTranslationUnitImpl();
3984
3985 if (getenv("LIBCLANG_RESOURCE_USAGE"))
3986 PrintLibclangResourceUsage(TU);
3987
3988 return result;
3989 }
3990
3991 // We have an AST that has invalid nodes due to compiler errors.
3992 // Use a crash recovery thread for protection.
3993
3994 llvm::CrashRecoveryContext CRC;
3995
3996 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
3997 fprintf(stderr, "libclang: crash detected during AST saving: {\n");
3998 fprintf(stderr, " 'filename' : '%s'\n", FileName);
3999 fprintf(stderr, " 'options' : %d,\n", options);
4000 fprintf(stderr, "}\n");
4001
4002 return CXSaveError_Unknown;
4003
4004 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4005 PrintLibclangResourceUsage(TU);
4006 }
4007
4008 return result;
4009 }
4010
clang_disposeTranslationUnit(CXTranslationUnit CTUnit)4011 void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4012 if (CTUnit) {
4013 // If the translation unit has been marked as unsafe to free, just discard
4014 // it.
4015 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4016 if (Unit && Unit->isUnsafeToFree())
4017 return;
4018
4019 delete cxtu::getASTUnit(CTUnit);
4020 delete CTUnit->StringPool;
4021 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4022 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
4023 delete CTUnit->CommentToXML;
4024 delete CTUnit;
4025 }
4026 }
4027
clang_suspendTranslationUnit(CXTranslationUnit CTUnit)4028 unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4029 if (CTUnit) {
4030 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4031
4032 if (Unit && Unit->isUnsafeToFree())
4033 return false;
4034
4035 Unit->ResetForParse();
4036 return true;
4037 }
4038
4039 return false;
4040 }
4041
clang_defaultReparseOptions(CXTranslationUnit TU)4042 unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4043 return CXReparse_None;
4044 }
4045
4046 static CXErrorCode
clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,ArrayRef<CXUnsavedFile> unsaved_files,unsigned options)4047 clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4048 ArrayRef<CXUnsavedFile> unsaved_files,
4049 unsigned options) {
4050 // Check arguments.
4051 if (isNotUsableTU(TU)) {
4052 LOG_BAD_TU(TU);
4053 return CXError_InvalidArguments;
4054 }
4055
4056 // Reset the associated diagnostics.
4057 delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
4058 TU->Diagnostics = nullptr;
4059
4060 CIndexer *CXXIdx = TU->CIdx;
4061 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4062 setThreadBackgroundPriority();
4063
4064 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4065 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4066
4067 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4068 new std::vector<ASTUnit::RemappedFile>());
4069
4070 // Recover resources if we crash before exiting this function.
4071 llvm::CrashRecoveryContextCleanupRegistrar<
4072 std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
4073
4074 for (auto &UF : unsaved_files) {
4075 std::unique_ptr<llvm::MemoryBuffer> MB =
4076 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
4077 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
4078 }
4079
4080 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4081 *RemappedFiles.get()))
4082 return CXError_Success;
4083 if (isASTReadError(CXXUnit))
4084 return CXError_ASTReadError;
4085 return CXError_Failure;
4086 }
4087
clang_reparseTranslationUnit(CXTranslationUnit TU,unsigned num_unsaved_files,struct CXUnsavedFile * unsaved_files,unsigned options)4088 int clang_reparseTranslationUnit(CXTranslationUnit TU,
4089 unsigned num_unsaved_files,
4090 struct CXUnsavedFile *unsaved_files,
4091 unsigned options) {
4092 LOG_FUNC_SECTION {
4093 *Log << TU;
4094 }
4095
4096 if (num_unsaved_files && !unsaved_files)
4097 return CXError_InvalidArguments;
4098
4099 CXErrorCode result;
4100 auto ReparseTranslationUnitImpl = [=, &result]() {
4101 result = clang_reparseTranslationUnit_Impl(
4102 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4103 };
4104
4105 llvm::CrashRecoveryContext CRC;
4106
4107 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
4108 fprintf(stderr, "libclang: crash detected during reparsing\n");
4109 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
4110 return CXError_Crashed;
4111 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4112 PrintLibclangResourceUsage(TU);
4113
4114 return result;
4115 }
4116
4117
clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit)4118 CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
4119 if (isNotUsableTU(CTUnit)) {
4120 LOG_BAD_TU(CTUnit);
4121 return cxstring::createEmpty();
4122 }
4123
4124 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4125 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
4126 }
4127
clang_getTranslationUnitCursor(CXTranslationUnit TU)4128 CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
4129 if (isNotUsableTU(TU)) {
4130 LOG_BAD_TU(TU);
4131 return clang_getNullCursor();
4132 }
4133
4134 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4135 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4136 }
4137
clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit)4138 CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4139 if (isNotUsableTU(CTUnit)) {
4140 LOG_BAD_TU(CTUnit);
4141 return nullptr;
4142 }
4143
4144 CXTargetInfoImpl* impl = new CXTargetInfoImpl();
4145 impl->TranslationUnit = CTUnit;
4146 return impl;
4147 }
4148
clang_TargetInfo_getTriple(CXTargetInfo TargetInfo)4149 CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4150 if (!TargetInfo)
4151 return cxstring::createEmpty();
4152
4153 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4154 assert(!isNotUsableTU(CTUnit) &&
4155 "Unexpected unusable translation unit in TargetInfo");
4156
4157 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4158 std::string Triple =
4159 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4160 return cxstring::createDup(Triple);
4161 }
4162
clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo)4163 int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4164 if (!TargetInfo)
4165 return -1;
4166
4167 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4168 assert(!isNotUsableTU(CTUnit) &&
4169 "Unexpected unusable translation unit in TargetInfo");
4170
4171 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4172 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4173 }
4174
clang_TargetInfo_dispose(CXTargetInfo TargetInfo)4175 void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4176 if (!TargetInfo)
4177 return;
4178
4179 delete TargetInfo;
4180 }
4181
4182 //===----------------------------------------------------------------------===//
4183 // CXFile Operations.
4184 //===----------------------------------------------------------------------===//
4185
clang_getFileName(CXFile SFile)4186 CXString clang_getFileName(CXFile SFile) {
4187 if (!SFile)
4188 return cxstring::createNull();
4189
4190 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4191 return cxstring::createRef(FEnt->getName());
4192 }
4193
clang_getFileTime(CXFile SFile)4194 time_t clang_getFileTime(CXFile SFile) {
4195 if (!SFile)
4196 return 0;
4197
4198 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4199 return FEnt->getModificationTime();
4200 }
4201
clang_getFile(CXTranslationUnit TU,const char * file_name)4202 CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
4203 if (isNotUsableTU(TU)) {
4204 LOG_BAD_TU(TU);
4205 return nullptr;
4206 }
4207
4208 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4209
4210 FileManager &FMgr = CXXUnit->getFileManager();
4211 return const_cast<FileEntry *>(FMgr.getFile(file_name));
4212 }
4213
clang_getFileContents(CXTranslationUnit TU,CXFile file,size_t * size)4214 const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4215 size_t *size) {
4216 if (isNotUsableTU(TU)) {
4217 LOG_BAD_TU(TU);
4218 return nullptr;
4219 }
4220
4221 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4222 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4223 bool Invalid = true;
4224 llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
4225 if (Invalid) {
4226 if (size)
4227 *size = 0;
4228 return nullptr;
4229 }
4230 if (size)
4231 *size = buf->getBufferSize();
4232 return buf->getBufferStart();
4233 }
4234
clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,CXFile file)4235 unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4236 CXFile file) {
4237 if (isNotUsableTU(TU)) {
4238 LOG_BAD_TU(TU);
4239 return 0;
4240 }
4241
4242 if (!file)
4243 return 0;
4244
4245 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4246 FileEntry *FEnt = static_cast<FileEntry *>(file);
4247 return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4248 .isFileMultipleIncludeGuarded(FEnt);
4249 }
4250
clang_getFileUniqueID(CXFile file,CXFileUniqueID * outID)4251 int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4252 if (!file || !outID)
4253 return 1;
4254
4255 FileEntry *FEnt = static_cast<FileEntry *>(file);
4256 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4257 outID->data[0] = ID.getDevice();
4258 outID->data[1] = ID.getFile();
4259 outID->data[2] = FEnt->getModificationTime();
4260 return 0;
4261 }
4262
clang_File_isEqual(CXFile file1,CXFile file2)4263 int clang_File_isEqual(CXFile file1, CXFile file2) {
4264 if (file1 == file2)
4265 return true;
4266
4267 if (!file1 || !file2)
4268 return false;
4269
4270 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4271 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4272 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4273 }
4274
clang_File_tryGetRealPathName(CXFile SFile)4275 CXString clang_File_tryGetRealPathName(CXFile SFile) {
4276 if (!SFile)
4277 return cxstring::createNull();
4278
4279 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4280 return cxstring::createRef(FEnt->tryGetRealPathName());
4281 }
4282
4283 //===----------------------------------------------------------------------===//
4284 // CXCursor Operations.
4285 //===----------------------------------------------------------------------===//
4286
getDeclFromExpr(const Stmt * E)4287 static const Decl *getDeclFromExpr(const Stmt *E) {
4288 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
4289 return getDeclFromExpr(CE->getSubExpr());
4290
4291 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
4292 return RefExpr->getDecl();
4293 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
4294 return ME->getMemberDecl();
4295 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
4296 return RE->getDecl();
4297 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
4298 if (PRE->isExplicitProperty())
4299 return PRE->getExplicitProperty();
4300 // It could be messaging both getter and setter as in:
4301 // ++myobj.myprop;
4302 // in which case prefer to associate the setter since it is less obvious
4303 // from inspecting the source that the setter is going to get called.
4304 if (PRE->isMessagingSetter())
4305 return PRE->getImplicitPropertySetter();
4306 return PRE->getImplicitPropertyGetter();
4307 }
4308 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
4309 return getDeclFromExpr(POE->getSyntacticForm());
4310 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4311 if (Expr *Src = OVE->getSourceExpr())
4312 return getDeclFromExpr(Src);
4313
4314 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
4315 return getDeclFromExpr(CE->getCallee());
4316 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
4317 if (!CE->isElidable())
4318 return CE->getConstructor();
4319 if (const CXXInheritedCtorInitExpr *CE =
4320 dyn_cast<CXXInheritedCtorInitExpr>(E))
4321 return CE->getConstructor();
4322 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
4323 return OME->getMethodDecl();
4324
4325 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
4326 return PE->getProtocol();
4327 if (const SubstNonTypeTemplateParmPackExpr *NTTP
4328 = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4329 return NTTP->getParameterPack();
4330 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
4331 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4332 isa<ParmVarDecl>(SizeOfPack->getPack()))
4333 return SizeOfPack->getPack();
4334
4335 return nullptr;
4336 }
4337
getLocationFromExpr(const Expr * E)4338 static SourceLocation getLocationFromExpr(const Expr *E) {
4339 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
4340 return getLocationFromExpr(CE->getSubExpr());
4341
4342 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
4343 return /*FIXME:*/Msg->getLeftLoc();
4344 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4345 return DRE->getLocation();
4346 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
4347 return Member->getMemberLoc();
4348 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
4349 return Ivar->getLocation();
4350 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
4351 return SizeOfPack->getPackLoc();
4352 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
4353 return PropRef->getLocation();
4354
4355 return E->getBeginLoc();
4356 }
4357
4358 extern "C" {
4359
clang_visitChildren(CXCursor parent,CXCursorVisitor visitor,CXClientData client_data)4360 unsigned clang_visitChildren(CXCursor parent,
4361 CXCursorVisitor visitor,
4362 CXClientData client_data) {
4363 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4364 /*VisitPreprocessorLast=*/false);
4365 return CursorVis.VisitChildren(parent);
4366 }
4367
4368 #ifndef __has_feature
4369 #define __has_feature(x) 0
4370 #endif
4371 #if __has_feature(blocks)
4372 typedef enum CXChildVisitResult
4373 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4374
4375 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4376 CXClientData client_data) {
4377 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4378 return block(cursor, parent);
4379 }
4380 #else
4381 // If we are compiled with a compiler that doesn't have native blocks support,
4382 // define and call the block manually, so the
4383 typedef struct _CXChildVisitResult
4384 {
4385 void *isa;
4386 int flags;
4387 int reserved;
4388 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4389 CXCursor);
4390 } *CXCursorVisitorBlock;
4391
4392 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4393 CXClientData client_data) {
4394 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4395 return block->invoke(block, cursor, parent);
4396 }
4397 #endif
4398
4399
4400 unsigned clang_visitChildrenWithBlock(CXCursor parent,
4401 CXCursorVisitorBlock block) {
4402 return clang_visitChildren(parent, visitWithBlock, block);
4403 }
4404
4405 static CXString getDeclSpelling(const Decl *D) {
4406 if (!D)
4407 return cxstring::createEmpty();
4408
4409 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
4410 if (!ND) {
4411 if (const ObjCPropertyImplDecl *PropImpl =
4412 dyn_cast<ObjCPropertyImplDecl>(D))
4413 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4414 return cxstring::createDup(Property->getIdentifier()->getName());
4415
4416 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
4417 if (Module *Mod = ImportD->getImportedModule())
4418 return cxstring::createDup(Mod->getFullModuleName());
4419
4420 return cxstring::createEmpty();
4421 }
4422
4423 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
4424 return cxstring::createDup(OMD->getSelector().getAsString());
4425
4426 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
4427 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4428 // and returns different names. NamedDecl returns the class name and
4429 // ObjCCategoryImplDecl returns the category name.
4430 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
4431
4432 if (isa<UsingDirectiveDecl>(D))
4433 return cxstring::createEmpty();
4434
4435 SmallString<1024> S;
4436 llvm::raw_svector_ostream os(S);
4437 ND->printName(os);
4438
4439 return cxstring::createDup(os.str());
4440 }
4441
4442 CXString clang_getCursorSpelling(CXCursor C) {
4443 if (clang_isTranslationUnit(C.kind))
4444 return clang_getTranslationUnitSpelling(getCursorTU(C));
4445
4446 if (clang_isReference(C.kind)) {
4447 switch (C.kind) {
4448 case CXCursor_ObjCSuperClassRef: {
4449 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
4450 return cxstring::createRef(Super->getIdentifier()->getNameStart());
4451 }
4452 case CXCursor_ObjCClassRef: {
4453 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4454 return cxstring::createRef(Class->getIdentifier()->getNameStart());
4455 }
4456 case CXCursor_ObjCProtocolRef: {
4457 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
4458 assert(OID && "getCursorSpelling(): Missing protocol decl");
4459 return cxstring::createRef(OID->getIdentifier()->getNameStart());
4460 }
4461 case CXCursor_CXXBaseSpecifier: {
4462 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
4463 return cxstring::createDup(B->getType().getAsString());
4464 }
4465 case CXCursor_TypeRef: {
4466 const TypeDecl *Type = getCursorTypeRef(C).first;
4467 assert(Type && "Missing type decl");
4468
4469 return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
4470 getAsString());
4471 }
4472 case CXCursor_TemplateRef: {
4473 const TemplateDecl *Template = getCursorTemplateRef(C).first;
4474 assert(Template && "Missing template decl");
4475
4476 return cxstring::createDup(Template->getNameAsString());
4477 }
4478
4479 case CXCursor_NamespaceRef: {
4480 const NamedDecl *NS = getCursorNamespaceRef(C).first;
4481 assert(NS && "Missing namespace decl");
4482
4483 return cxstring::createDup(NS->getNameAsString());
4484 }
4485
4486 case CXCursor_MemberRef: {
4487 const FieldDecl *Field = getCursorMemberRef(C).first;
4488 assert(Field && "Missing member decl");
4489
4490 return cxstring::createDup(Field->getNameAsString());
4491 }
4492
4493 case CXCursor_LabelRef: {
4494 const LabelStmt *Label = getCursorLabelRef(C).first;
4495 assert(Label && "Missing label");
4496
4497 return cxstring::createRef(Label->getName());
4498 }
4499
4500 case CXCursor_OverloadedDeclRef: {
4501 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4502 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4503 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
4504 return cxstring::createDup(ND->getNameAsString());
4505 return cxstring::createEmpty();
4506 }
4507 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
4508 return cxstring::createDup(E->getName().getAsString());
4509 OverloadedTemplateStorage *Ovl
4510 = Storage.get<OverloadedTemplateStorage*>();
4511 if (Ovl->size() == 0)
4512 return cxstring::createEmpty();
4513 return cxstring::createDup((*Ovl->begin())->getNameAsString());
4514 }
4515
4516 case CXCursor_VariableRef: {
4517 const VarDecl *Var = getCursorVariableRef(C).first;
4518 assert(Var && "Missing variable decl");
4519
4520 return cxstring::createDup(Var->getNameAsString());
4521 }
4522
4523 default:
4524 return cxstring::createRef("<not implemented>");
4525 }
4526 }
4527
4528 if (clang_isExpression(C.kind)) {
4529 const Expr *E = getCursorExpr(C);
4530
4531 if (C.kind == CXCursor_ObjCStringLiteral ||
4532 C.kind == CXCursor_StringLiteral) {
4533 const StringLiteral *SLit;
4534 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4535 SLit = OSL->getString();
4536 } else {
4537 SLit = cast<StringLiteral>(E);
4538 }
4539 SmallString<256> Buf;
4540 llvm::raw_svector_ostream OS(Buf);
4541 SLit->outputString(OS);
4542 return cxstring::createDup(OS.str());
4543 }
4544
4545 const Decl *D = getDeclFromExpr(getCursorExpr(C));
4546 if (D)
4547 return getDeclSpelling(D);
4548 return cxstring::createEmpty();
4549 }
4550
4551 if (clang_isStatement(C.kind)) {
4552 const Stmt *S = getCursorStmt(C);
4553 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
4554 return cxstring::createRef(Label->getName());
4555
4556 return cxstring::createEmpty();
4557 }
4558
4559 if (C.kind == CXCursor_MacroExpansion)
4560 return cxstring::createRef(getCursorMacroExpansion(C).getName()
4561 ->getNameStart());
4562
4563 if (C.kind == CXCursor_MacroDefinition)
4564 return cxstring::createRef(getCursorMacroDefinition(C)->getName()
4565 ->getNameStart());
4566
4567 if (C.kind == CXCursor_InclusionDirective)
4568 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
4569
4570 if (clang_isDeclaration(C.kind))
4571 return getDeclSpelling(getCursorDecl(C));
4572
4573 if (C.kind == CXCursor_AnnotateAttr) {
4574 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
4575 return cxstring::createDup(AA->getAnnotation());
4576 }
4577
4578 if (C.kind == CXCursor_AsmLabelAttr) {
4579 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
4580 return cxstring::createDup(AA->getLabel());
4581 }
4582
4583 if (C.kind == CXCursor_PackedAttr) {
4584 return cxstring::createRef("packed");
4585 }
4586
4587 if (C.kind == CXCursor_VisibilityAttr) {
4588 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4589 switch (AA->getVisibility()) {
4590 case VisibilityAttr::VisibilityType::Default:
4591 return cxstring::createRef("default");
4592 case VisibilityAttr::VisibilityType::Hidden:
4593 return cxstring::createRef("hidden");
4594 case VisibilityAttr::VisibilityType::Protected:
4595 return cxstring::createRef("protected");
4596 }
4597 llvm_unreachable("unknown visibility type");
4598 }
4599
4600 return cxstring::createEmpty();
4601 }
4602
4603 CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4604 unsigned pieceIndex,
4605 unsigned options) {
4606 if (clang_Cursor_isNull(C))
4607 return clang_getNullRange();
4608
4609 ASTContext &Ctx = getCursorContext(C);
4610
4611 if (clang_isStatement(C.kind)) {
4612 const Stmt *S = getCursorStmt(C);
4613 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
4614 if (pieceIndex > 0)
4615 return clang_getNullRange();
4616 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4617 }
4618
4619 return clang_getNullRange();
4620 }
4621
4622 if (C.kind == CXCursor_ObjCMessageExpr) {
4623 if (const ObjCMessageExpr *
4624 ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4625 if (pieceIndex >= ME->getNumSelectorLocs())
4626 return clang_getNullRange();
4627 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4628 }
4629 }
4630
4631 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4632 C.kind == CXCursor_ObjCClassMethodDecl) {
4633 if (const ObjCMethodDecl *
4634 MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4635 if (pieceIndex >= MD->getNumSelectorLocs())
4636 return clang_getNullRange();
4637 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4638 }
4639 }
4640
4641 if (C.kind == CXCursor_ObjCCategoryDecl ||
4642 C.kind == CXCursor_ObjCCategoryImplDecl) {
4643 if (pieceIndex > 0)
4644 return clang_getNullRange();
4645 if (const ObjCCategoryDecl *
4646 CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4647 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
4648 if (const ObjCCategoryImplDecl *
4649 CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4650 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4651 }
4652
4653 if (C.kind == CXCursor_ModuleImportDecl) {
4654 if (pieceIndex > 0)
4655 return clang_getNullRange();
4656 if (const ImportDecl *ImportD =
4657 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
4658 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4659 if (!Locs.empty())
4660 return cxloc::translateSourceRange(Ctx,
4661 SourceRange(Locs.front(), Locs.back()));
4662 }
4663 return clang_getNullRange();
4664 }
4665
4666 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
4667 C.kind == CXCursor_ConversionFunction ||
4668 C.kind == CXCursor_FunctionDecl) {
4669 if (pieceIndex > 0)
4670 return clang_getNullRange();
4671 if (const FunctionDecl *FD =
4672 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4673 DeclarationNameInfo FunctionName = FD->getNameInfo();
4674 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4675 }
4676 return clang_getNullRange();
4677 }
4678
4679 // FIXME: A CXCursor_InclusionDirective should give the location of the
4680 // filename, but we don't keep track of this.
4681
4682 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4683 // but we don't keep track of this.
4684
4685 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4686 // but we don't keep track of this.
4687
4688 // Default handling, give the location of the cursor.
4689
4690 if (pieceIndex > 0)
4691 return clang_getNullRange();
4692
4693 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4694 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4695 return cxloc::translateSourceRange(Ctx, Loc);
4696 }
4697
4698 CXString clang_Cursor_getMangling(CXCursor C) {
4699 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4700 return cxstring::createEmpty();
4701
4702 // Mangling only works for functions and variables.
4703 const Decl *D = getCursorDecl(C);
4704 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4705 return cxstring::createEmpty();
4706
4707 ASTContext &Ctx = D->getASTContext();
4708 index::CodegenNameGenerator CGNameGen(Ctx);
4709 return cxstring::createDup(CGNameGen.getName(D));
4710 }
4711
4712 CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4713 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4714 return nullptr;
4715
4716 const Decl *D = getCursorDecl(C);
4717 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4718 return nullptr;
4719
4720 ASTContext &Ctx = D->getASTContext();
4721 index::CodegenNameGenerator CGNameGen(Ctx);
4722 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4723 return cxstring::createSet(Manglings);
4724 }
4725
4726 CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4727 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4728 return nullptr;
4729
4730 const Decl *D = getCursorDecl(C);
4731 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4732 return nullptr;
4733
4734 ASTContext &Ctx = D->getASTContext();
4735 index::CodegenNameGenerator CGNameGen(Ctx);
4736 std::vector<std::string> Manglings = CGNameGen.getAllManglings(D);
4737 return cxstring::createSet(Manglings);
4738 }
4739
4740 CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4741 if (clang_Cursor_isNull(C))
4742 return 0;
4743 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4744 }
4745
4746 void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4747 if (Policy)
4748 delete static_cast<PrintingPolicy *>(Policy);
4749 }
4750
4751 unsigned
4752 clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4753 enum CXPrintingPolicyProperty Property) {
4754 if (!Policy)
4755 return 0;
4756
4757 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4758 switch (Property) {
4759 case CXPrintingPolicy_Indentation:
4760 return P->Indentation;
4761 case CXPrintingPolicy_SuppressSpecifiers:
4762 return P->SuppressSpecifiers;
4763 case CXPrintingPolicy_SuppressTagKeyword:
4764 return P->SuppressTagKeyword;
4765 case CXPrintingPolicy_IncludeTagDefinition:
4766 return P->IncludeTagDefinition;
4767 case CXPrintingPolicy_SuppressScope:
4768 return P->SuppressScope;
4769 case CXPrintingPolicy_SuppressUnwrittenScope:
4770 return P->SuppressUnwrittenScope;
4771 case CXPrintingPolicy_SuppressInitializers:
4772 return P->SuppressInitializers;
4773 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4774 return P->ConstantArraySizeAsWritten;
4775 case CXPrintingPolicy_AnonymousTagLocations:
4776 return P->AnonymousTagLocations;
4777 case CXPrintingPolicy_SuppressStrongLifetime:
4778 return P->SuppressStrongLifetime;
4779 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4780 return P->SuppressLifetimeQualifiers;
4781 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4782 return P->SuppressTemplateArgsInCXXConstructors;
4783 case CXPrintingPolicy_Bool:
4784 return P->Bool;
4785 case CXPrintingPolicy_Restrict:
4786 return P->Restrict;
4787 case CXPrintingPolicy_Alignof:
4788 return P->Alignof;
4789 case CXPrintingPolicy_UnderscoreAlignof:
4790 return P->UnderscoreAlignof;
4791 case CXPrintingPolicy_UseVoidForZeroParams:
4792 return P->UseVoidForZeroParams;
4793 case CXPrintingPolicy_TerseOutput:
4794 return P->TerseOutput;
4795 case CXPrintingPolicy_PolishForDeclaration:
4796 return P->PolishForDeclaration;
4797 case CXPrintingPolicy_Half:
4798 return P->Half;
4799 case CXPrintingPolicy_MSWChar:
4800 return P->MSWChar;
4801 case CXPrintingPolicy_IncludeNewlines:
4802 return P->IncludeNewlines;
4803 case CXPrintingPolicy_MSVCFormatting:
4804 return P->MSVCFormatting;
4805 case CXPrintingPolicy_ConstantsAsWritten:
4806 return P->ConstantsAsWritten;
4807 case CXPrintingPolicy_SuppressImplicitBase:
4808 return P->SuppressImplicitBase;
4809 case CXPrintingPolicy_FullyQualifiedName:
4810 return P->FullyQualifiedName;
4811 }
4812
4813 assert(false && "Invalid CXPrintingPolicyProperty");
4814 return 0;
4815 }
4816
4817 void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4818 enum CXPrintingPolicyProperty Property,
4819 unsigned Value) {
4820 if (!Policy)
4821 return;
4822
4823 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4824 switch (Property) {
4825 case CXPrintingPolicy_Indentation:
4826 P->Indentation = Value;
4827 return;
4828 case CXPrintingPolicy_SuppressSpecifiers:
4829 P->SuppressSpecifiers = Value;
4830 return;
4831 case CXPrintingPolicy_SuppressTagKeyword:
4832 P->SuppressTagKeyword = Value;
4833 return;
4834 case CXPrintingPolicy_IncludeTagDefinition:
4835 P->IncludeTagDefinition = Value;
4836 return;
4837 case CXPrintingPolicy_SuppressScope:
4838 P->SuppressScope = Value;
4839 return;
4840 case CXPrintingPolicy_SuppressUnwrittenScope:
4841 P->SuppressUnwrittenScope = Value;
4842 return;
4843 case CXPrintingPolicy_SuppressInitializers:
4844 P->SuppressInitializers = Value;
4845 return;
4846 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4847 P->ConstantArraySizeAsWritten = Value;
4848 return;
4849 case CXPrintingPolicy_AnonymousTagLocations:
4850 P->AnonymousTagLocations = Value;
4851 return;
4852 case CXPrintingPolicy_SuppressStrongLifetime:
4853 P->SuppressStrongLifetime = Value;
4854 return;
4855 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4856 P->SuppressLifetimeQualifiers = Value;
4857 return;
4858 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4859 P->SuppressTemplateArgsInCXXConstructors = Value;
4860 return;
4861 case CXPrintingPolicy_Bool:
4862 P->Bool = Value;
4863 return;
4864 case CXPrintingPolicy_Restrict:
4865 P->Restrict = Value;
4866 return;
4867 case CXPrintingPolicy_Alignof:
4868 P->Alignof = Value;
4869 return;
4870 case CXPrintingPolicy_UnderscoreAlignof:
4871 P->UnderscoreAlignof = Value;
4872 return;
4873 case CXPrintingPolicy_UseVoidForZeroParams:
4874 P->UseVoidForZeroParams = Value;
4875 return;
4876 case CXPrintingPolicy_TerseOutput:
4877 P->TerseOutput = Value;
4878 return;
4879 case CXPrintingPolicy_PolishForDeclaration:
4880 P->PolishForDeclaration = Value;
4881 return;
4882 case CXPrintingPolicy_Half:
4883 P->Half = Value;
4884 return;
4885 case CXPrintingPolicy_MSWChar:
4886 P->MSWChar = Value;
4887 return;
4888 case CXPrintingPolicy_IncludeNewlines:
4889 P->IncludeNewlines = Value;
4890 return;
4891 case CXPrintingPolicy_MSVCFormatting:
4892 P->MSVCFormatting = Value;
4893 return;
4894 case CXPrintingPolicy_ConstantsAsWritten:
4895 P->ConstantsAsWritten = Value;
4896 return;
4897 case CXPrintingPolicy_SuppressImplicitBase:
4898 P->SuppressImplicitBase = Value;
4899 return;
4900 case CXPrintingPolicy_FullyQualifiedName:
4901 P->FullyQualifiedName = Value;
4902 return;
4903 }
4904
4905 assert(false && "Invalid CXPrintingPolicyProperty");
4906 }
4907
4908 CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
4909 if (clang_Cursor_isNull(C))
4910 return cxstring::createEmpty();
4911
4912 if (clang_isDeclaration(C.kind)) {
4913 const Decl *D = getCursorDecl(C);
4914 if (!D)
4915 return cxstring::createEmpty();
4916
4917 SmallString<128> Str;
4918 llvm::raw_svector_ostream OS(Str);
4919 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4920 D->print(OS, UserPolicy ? *UserPolicy
4921 : getCursorContext(C).getPrintingPolicy());
4922
4923 return cxstring::createDup(OS.str());
4924 }
4925
4926 return cxstring::createEmpty();
4927 }
4928
4929 CXString clang_getCursorDisplayName(CXCursor C) {
4930 if (!clang_isDeclaration(C.kind))
4931 return clang_getCursorSpelling(C);
4932
4933 const Decl *D = getCursorDecl(C);
4934 if (!D)
4935 return cxstring::createEmpty();
4936
4937 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
4938 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
4939 D = FunTmpl->getTemplatedDecl();
4940
4941 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
4942 SmallString<64> Str;
4943 llvm::raw_svector_ostream OS(Str);
4944 OS << *Function;
4945 if (Function->getPrimaryTemplate())
4946 OS << "<>";
4947 OS << "(";
4948 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
4949 if (I)
4950 OS << ", ";
4951 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4952 }
4953
4954 if (Function->isVariadic()) {
4955 if (Function->getNumParams())
4956 OS << ", ";
4957 OS << "...";
4958 }
4959 OS << ")";
4960 return cxstring::createDup(OS.str());
4961 }
4962
4963 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
4964 SmallString<64> Str;
4965 llvm::raw_svector_ostream OS(Str);
4966 OS << *ClassTemplate;
4967 OS << "<";
4968 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4969 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4970 if (I)
4971 OS << ", ";
4972
4973 NamedDecl *Param = Params->getParam(I);
4974 if (Param->getIdentifier()) {
4975 OS << Param->getIdentifier()->getName();
4976 continue;
4977 }
4978
4979 // There is no parameter name, which makes this tricky. Try to come up
4980 // with something useful that isn't too long.
4981 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4982 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4983 else if (NonTypeTemplateParmDecl *NTTP
4984 = dyn_cast<NonTypeTemplateParmDecl>(Param))
4985 OS << NTTP->getType().getAsString(Policy);
4986 else
4987 OS << "template<...> class";
4988 }
4989
4990 OS << ">";
4991 return cxstring::createDup(OS.str());
4992 }
4993
4994 if (const ClassTemplateSpecializationDecl *ClassSpec
4995 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
4996 // If the type was explicitly written, use that.
4997 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
4998 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
4999
5000 SmallString<128> Str;
5001 llvm::raw_svector_ostream OS(Str);
5002 OS << *ClassSpec;
5003 printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5004 Policy);
5005 return cxstring::createDup(OS.str());
5006 }
5007
5008 return clang_getCursorSpelling(C);
5009 }
5010
5011 CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5012 switch (Kind) {
5013 case CXCursor_FunctionDecl:
5014 return cxstring::createRef("FunctionDecl");
5015 case CXCursor_TypedefDecl:
5016 return cxstring::createRef("TypedefDecl");
5017 case CXCursor_EnumDecl:
5018 return cxstring::createRef("EnumDecl");
5019 case CXCursor_EnumConstantDecl:
5020 return cxstring::createRef("EnumConstantDecl");
5021 case CXCursor_StructDecl:
5022 return cxstring::createRef("StructDecl");
5023 case CXCursor_UnionDecl:
5024 return cxstring::createRef("UnionDecl");
5025 case CXCursor_ClassDecl:
5026 return cxstring::createRef("ClassDecl");
5027 case CXCursor_FieldDecl:
5028 return cxstring::createRef("FieldDecl");
5029 case CXCursor_VarDecl:
5030 return cxstring::createRef("VarDecl");
5031 case CXCursor_ParmDecl:
5032 return cxstring::createRef("ParmDecl");
5033 case CXCursor_ObjCInterfaceDecl:
5034 return cxstring::createRef("ObjCInterfaceDecl");
5035 case CXCursor_ObjCCategoryDecl:
5036 return cxstring::createRef("ObjCCategoryDecl");
5037 case CXCursor_ObjCProtocolDecl:
5038 return cxstring::createRef("ObjCProtocolDecl");
5039 case CXCursor_ObjCPropertyDecl:
5040 return cxstring::createRef("ObjCPropertyDecl");
5041 case CXCursor_ObjCIvarDecl:
5042 return cxstring::createRef("ObjCIvarDecl");
5043 case CXCursor_ObjCInstanceMethodDecl:
5044 return cxstring::createRef("ObjCInstanceMethodDecl");
5045 case CXCursor_ObjCClassMethodDecl:
5046 return cxstring::createRef("ObjCClassMethodDecl");
5047 case CXCursor_ObjCImplementationDecl:
5048 return cxstring::createRef("ObjCImplementationDecl");
5049 case CXCursor_ObjCCategoryImplDecl:
5050 return cxstring::createRef("ObjCCategoryImplDecl");
5051 case CXCursor_CXXMethod:
5052 return cxstring::createRef("CXXMethod");
5053 case CXCursor_UnexposedDecl:
5054 return cxstring::createRef("UnexposedDecl");
5055 case CXCursor_ObjCSuperClassRef:
5056 return cxstring::createRef("ObjCSuperClassRef");
5057 case CXCursor_ObjCProtocolRef:
5058 return cxstring::createRef("ObjCProtocolRef");
5059 case CXCursor_ObjCClassRef:
5060 return cxstring::createRef("ObjCClassRef");
5061 case CXCursor_TypeRef:
5062 return cxstring::createRef("TypeRef");
5063 case CXCursor_TemplateRef:
5064 return cxstring::createRef("TemplateRef");
5065 case CXCursor_NamespaceRef:
5066 return cxstring::createRef("NamespaceRef");
5067 case CXCursor_MemberRef:
5068 return cxstring::createRef("MemberRef");
5069 case CXCursor_LabelRef:
5070 return cxstring::createRef("LabelRef");
5071 case CXCursor_OverloadedDeclRef:
5072 return cxstring::createRef("OverloadedDeclRef");
5073 case CXCursor_VariableRef:
5074 return cxstring::createRef("VariableRef");
5075 case CXCursor_IntegerLiteral:
5076 return cxstring::createRef("IntegerLiteral");
5077 case CXCursor_FixedPointLiteral:
5078 return cxstring::createRef("FixedPointLiteral");
5079 case CXCursor_FloatingLiteral:
5080 return cxstring::createRef("FloatingLiteral");
5081 case CXCursor_ImaginaryLiteral:
5082 return cxstring::createRef("ImaginaryLiteral");
5083 case CXCursor_StringLiteral:
5084 return cxstring::createRef("StringLiteral");
5085 case CXCursor_CharacterLiteral:
5086 return cxstring::createRef("CharacterLiteral");
5087 case CXCursor_ParenExpr:
5088 return cxstring::createRef("ParenExpr");
5089 case CXCursor_UnaryOperator:
5090 return cxstring::createRef("UnaryOperator");
5091 case CXCursor_ArraySubscriptExpr:
5092 return cxstring::createRef("ArraySubscriptExpr");
5093 case CXCursor_OMPArraySectionExpr:
5094 return cxstring::createRef("OMPArraySectionExpr");
5095 case CXCursor_BinaryOperator:
5096 return cxstring::createRef("BinaryOperator");
5097 case CXCursor_CompoundAssignOperator:
5098 return cxstring::createRef("CompoundAssignOperator");
5099 case CXCursor_ConditionalOperator:
5100 return cxstring::createRef("ConditionalOperator");
5101 case CXCursor_CStyleCastExpr:
5102 return cxstring::createRef("CStyleCastExpr");
5103 case CXCursor_CompoundLiteralExpr:
5104 return cxstring::createRef("CompoundLiteralExpr");
5105 case CXCursor_InitListExpr:
5106 return cxstring::createRef("InitListExpr");
5107 case CXCursor_AddrLabelExpr:
5108 return cxstring::createRef("AddrLabelExpr");
5109 case CXCursor_StmtExpr:
5110 return cxstring::createRef("StmtExpr");
5111 case CXCursor_GenericSelectionExpr:
5112 return cxstring::createRef("GenericSelectionExpr");
5113 case CXCursor_GNUNullExpr:
5114 return cxstring::createRef("GNUNullExpr");
5115 case CXCursor_CXXStaticCastExpr:
5116 return cxstring::createRef("CXXStaticCastExpr");
5117 case CXCursor_CXXDynamicCastExpr:
5118 return cxstring::createRef("CXXDynamicCastExpr");
5119 case CXCursor_CXXReinterpretCastExpr:
5120 return cxstring::createRef("CXXReinterpretCastExpr");
5121 case CXCursor_CXXConstCastExpr:
5122 return cxstring::createRef("CXXConstCastExpr");
5123 case CXCursor_CXXFunctionalCastExpr:
5124 return cxstring::createRef("CXXFunctionalCastExpr");
5125 case CXCursor_CXXTypeidExpr:
5126 return cxstring::createRef("CXXTypeidExpr");
5127 case CXCursor_CXXBoolLiteralExpr:
5128 return cxstring::createRef("CXXBoolLiteralExpr");
5129 case CXCursor_CXXNullPtrLiteralExpr:
5130 return cxstring::createRef("CXXNullPtrLiteralExpr");
5131 case CXCursor_CXXThisExpr:
5132 return cxstring::createRef("CXXThisExpr");
5133 case CXCursor_CXXThrowExpr:
5134 return cxstring::createRef("CXXThrowExpr");
5135 case CXCursor_CXXNewExpr:
5136 return cxstring::createRef("CXXNewExpr");
5137 case CXCursor_CXXDeleteExpr:
5138 return cxstring::createRef("CXXDeleteExpr");
5139 case CXCursor_UnaryExpr:
5140 return cxstring::createRef("UnaryExpr");
5141 case CXCursor_ObjCStringLiteral:
5142 return cxstring::createRef("ObjCStringLiteral");
5143 case CXCursor_ObjCBoolLiteralExpr:
5144 return cxstring::createRef("ObjCBoolLiteralExpr");
5145 case CXCursor_ObjCAvailabilityCheckExpr:
5146 return cxstring::createRef("ObjCAvailabilityCheckExpr");
5147 case CXCursor_ObjCSelfExpr:
5148 return cxstring::createRef("ObjCSelfExpr");
5149 case CXCursor_ObjCEncodeExpr:
5150 return cxstring::createRef("ObjCEncodeExpr");
5151 case CXCursor_ObjCSelectorExpr:
5152 return cxstring::createRef("ObjCSelectorExpr");
5153 case CXCursor_ObjCProtocolExpr:
5154 return cxstring::createRef("ObjCProtocolExpr");
5155 case CXCursor_ObjCBridgedCastExpr:
5156 return cxstring::createRef("ObjCBridgedCastExpr");
5157 case CXCursor_BlockExpr:
5158 return cxstring::createRef("BlockExpr");
5159 case CXCursor_PackExpansionExpr:
5160 return cxstring::createRef("PackExpansionExpr");
5161 case CXCursor_SizeOfPackExpr:
5162 return cxstring::createRef("SizeOfPackExpr");
5163 case CXCursor_LambdaExpr:
5164 return cxstring::createRef("LambdaExpr");
5165 case CXCursor_UnexposedExpr:
5166 return cxstring::createRef("UnexposedExpr");
5167 case CXCursor_DeclRefExpr:
5168 return cxstring::createRef("DeclRefExpr");
5169 case CXCursor_MemberRefExpr:
5170 return cxstring::createRef("MemberRefExpr");
5171 case CXCursor_CallExpr:
5172 return cxstring::createRef("CallExpr");
5173 case CXCursor_ObjCMessageExpr:
5174 return cxstring::createRef("ObjCMessageExpr");
5175 case CXCursor_UnexposedStmt:
5176 return cxstring::createRef("UnexposedStmt");
5177 case CXCursor_DeclStmt:
5178 return cxstring::createRef("DeclStmt");
5179 case CXCursor_LabelStmt:
5180 return cxstring::createRef("LabelStmt");
5181 case CXCursor_CompoundStmt:
5182 return cxstring::createRef("CompoundStmt");
5183 case CXCursor_CaseStmt:
5184 return cxstring::createRef("CaseStmt");
5185 case CXCursor_DefaultStmt:
5186 return cxstring::createRef("DefaultStmt");
5187 case CXCursor_IfStmt:
5188 return cxstring::createRef("IfStmt");
5189 case CXCursor_SwitchStmt:
5190 return cxstring::createRef("SwitchStmt");
5191 case CXCursor_WhileStmt:
5192 return cxstring::createRef("WhileStmt");
5193 case CXCursor_DoStmt:
5194 return cxstring::createRef("DoStmt");
5195 case CXCursor_ForStmt:
5196 return cxstring::createRef("ForStmt");
5197 case CXCursor_GotoStmt:
5198 return cxstring::createRef("GotoStmt");
5199 case CXCursor_IndirectGotoStmt:
5200 return cxstring::createRef("IndirectGotoStmt");
5201 case CXCursor_ContinueStmt:
5202 return cxstring::createRef("ContinueStmt");
5203 case CXCursor_BreakStmt:
5204 return cxstring::createRef("BreakStmt");
5205 case CXCursor_ReturnStmt:
5206 return cxstring::createRef("ReturnStmt");
5207 case CXCursor_GCCAsmStmt:
5208 return cxstring::createRef("GCCAsmStmt");
5209 case CXCursor_MSAsmStmt:
5210 return cxstring::createRef("MSAsmStmt");
5211 case CXCursor_ObjCAtTryStmt:
5212 return cxstring::createRef("ObjCAtTryStmt");
5213 case CXCursor_ObjCAtCatchStmt:
5214 return cxstring::createRef("ObjCAtCatchStmt");
5215 case CXCursor_ObjCAtFinallyStmt:
5216 return cxstring::createRef("ObjCAtFinallyStmt");
5217 case CXCursor_ObjCAtThrowStmt:
5218 return cxstring::createRef("ObjCAtThrowStmt");
5219 case CXCursor_ObjCAtSynchronizedStmt:
5220 return cxstring::createRef("ObjCAtSynchronizedStmt");
5221 case CXCursor_ObjCAutoreleasePoolStmt:
5222 return cxstring::createRef("ObjCAutoreleasePoolStmt");
5223 case CXCursor_ObjCForCollectionStmt:
5224 return cxstring::createRef("ObjCForCollectionStmt");
5225 case CXCursor_CXXCatchStmt:
5226 return cxstring::createRef("CXXCatchStmt");
5227 case CXCursor_CXXTryStmt:
5228 return cxstring::createRef("CXXTryStmt");
5229 case CXCursor_CXXForRangeStmt:
5230 return cxstring::createRef("CXXForRangeStmt");
5231 case CXCursor_SEHTryStmt:
5232 return cxstring::createRef("SEHTryStmt");
5233 case CXCursor_SEHExceptStmt:
5234 return cxstring::createRef("SEHExceptStmt");
5235 case CXCursor_SEHFinallyStmt:
5236 return cxstring::createRef("SEHFinallyStmt");
5237 case CXCursor_SEHLeaveStmt:
5238 return cxstring::createRef("SEHLeaveStmt");
5239 case CXCursor_NullStmt:
5240 return cxstring::createRef("NullStmt");
5241 case CXCursor_InvalidFile:
5242 return cxstring::createRef("InvalidFile");
5243 case CXCursor_InvalidCode:
5244 return cxstring::createRef("InvalidCode");
5245 case CXCursor_NoDeclFound:
5246 return cxstring::createRef("NoDeclFound");
5247 case CXCursor_NotImplemented:
5248 return cxstring::createRef("NotImplemented");
5249 case CXCursor_TranslationUnit:
5250 return cxstring::createRef("TranslationUnit");
5251 case CXCursor_UnexposedAttr:
5252 return cxstring::createRef("UnexposedAttr");
5253 case CXCursor_IBActionAttr:
5254 return cxstring::createRef("attribute(ibaction)");
5255 case CXCursor_IBOutletAttr:
5256 return cxstring::createRef("attribute(iboutlet)");
5257 case CXCursor_IBOutletCollectionAttr:
5258 return cxstring::createRef("attribute(iboutletcollection)");
5259 case CXCursor_CXXFinalAttr:
5260 return cxstring::createRef("attribute(final)");
5261 case CXCursor_CXXOverrideAttr:
5262 return cxstring::createRef("attribute(override)");
5263 case CXCursor_AnnotateAttr:
5264 return cxstring::createRef("attribute(annotate)");
5265 case CXCursor_AsmLabelAttr:
5266 return cxstring::createRef("asm label");
5267 case CXCursor_PackedAttr:
5268 return cxstring::createRef("attribute(packed)");
5269 case CXCursor_PureAttr:
5270 return cxstring::createRef("attribute(pure)");
5271 case CXCursor_ConstAttr:
5272 return cxstring::createRef("attribute(const)");
5273 case CXCursor_NoDuplicateAttr:
5274 return cxstring::createRef("attribute(noduplicate)");
5275 case CXCursor_CUDAConstantAttr:
5276 return cxstring::createRef("attribute(constant)");
5277 case CXCursor_CUDADeviceAttr:
5278 return cxstring::createRef("attribute(device)");
5279 case CXCursor_CUDAGlobalAttr:
5280 return cxstring::createRef("attribute(global)");
5281 case CXCursor_CUDAHostAttr:
5282 return cxstring::createRef("attribute(host)");
5283 case CXCursor_CUDASharedAttr:
5284 return cxstring::createRef("attribute(shared)");
5285 case CXCursor_VisibilityAttr:
5286 return cxstring::createRef("attribute(visibility)");
5287 case CXCursor_DLLExport:
5288 return cxstring::createRef("attribute(dllexport)");
5289 case CXCursor_DLLImport:
5290 return cxstring::createRef("attribute(dllimport)");
5291 case CXCursor_NSReturnsRetained:
5292 return cxstring::createRef("attribute(ns_returns_retained)");
5293 case CXCursor_NSReturnsNotRetained:
5294 return cxstring::createRef("attribute(ns_returns_not_retained)");
5295 case CXCursor_NSReturnsAutoreleased:
5296 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5297 case CXCursor_NSConsumesSelf:
5298 return cxstring::createRef("attribute(ns_consumes_self)");
5299 case CXCursor_NSConsumed:
5300 return cxstring::createRef("attribute(ns_consumed)");
5301 case CXCursor_ObjCException:
5302 return cxstring::createRef("attribute(objc_exception)");
5303 case CXCursor_ObjCNSObject:
5304 return cxstring::createRef("attribute(NSObject)");
5305 case CXCursor_ObjCIndependentClass:
5306 return cxstring::createRef("attribute(objc_independent_class)");
5307 case CXCursor_ObjCPreciseLifetime:
5308 return cxstring::createRef("attribute(objc_precise_lifetime)");
5309 case CXCursor_ObjCReturnsInnerPointer:
5310 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5311 case CXCursor_ObjCRequiresSuper:
5312 return cxstring::createRef("attribute(objc_requires_super)");
5313 case CXCursor_ObjCRootClass:
5314 return cxstring::createRef("attribute(objc_root_class)");
5315 case CXCursor_ObjCSubclassingRestricted:
5316 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5317 case CXCursor_ObjCExplicitProtocolImpl:
5318 return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5319 case CXCursor_ObjCDesignatedInitializer:
5320 return cxstring::createRef("attribute(objc_designated_initializer)");
5321 case CXCursor_ObjCRuntimeVisible:
5322 return cxstring::createRef("attribute(objc_runtime_visible)");
5323 case CXCursor_ObjCBoxable:
5324 return cxstring::createRef("attribute(objc_boxable)");
5325 case CXCursor_FlagEnum:
5326 return cxstring::createRef("attribute(flag_enum)");
5327 case CXCursor_PreprocessingDirective:
5328 return cxstring::createRef("preprocessing directive");
5329 case CXCursor_MacroDefinition:
5330 return cxstring::createRef("macro definition");
5331 case CXCursor_MacroExpansion:
5332 return cxstring::createRef("macro expansion");
5333 case CXCursor_InclusionDirective:
5334 return cxstring::createRef("inclusion directive");
5335 case CXCursor_Namespace:
5336 return cxstring::createRef("Namespace");
5337 case CXCursor_LinkageSpec:
5338 return cxstring::createRef("LinkageSpec");
5339 case CXCursor_CXXBaseSpecifier:
5340 return cxstring::createRef("C++ base class specifier");
5341 case CXCursor_Constructor:
5342 return cxstring::createRef("CXXConstructor");
5343 case CXCursor_Destructor:
5344 return cxstring::createRef("CXXDestructor");
5345 case CXCursor_ConversionFunction:
5346 return cxstring::createRef("CXXConversion");
5347 case CXCursor_TemplateTypeParameter:
5348 return cxstring::createRef("TemplateTypeParameter");
5349 case CXCursor_NonTypeTemplateParameter:
5350 return cxstring::createRef("NonTypeTemplateParameter");
5351 case CXCursor_TemplateTemplateParameter:
5352 return cxstring::createRef("TemplateTemplateParameter");
5353 case CXCursor_FunctionTemplate:
5354 return cxstring::createRef("FunctionTemplate");
5355 case CXCursor_ClassTemplate:
5356 return cxstring::createRef("ClassTemplate");
5357 case CXCursor_ClassTemplatePartialSpecialization:
5358 return cxstring::createRef("ClassTemplatePartialSpecialization");
5359 case CXCursor_NamespaceAlias:
5360 return cxstring::createRef("NamespaceAlias");
5361 case CXCursor_UsingDirective:
5362 return cxstring::createRef("UsingDirective");
5363 case CXCursor_UsingDeclaration:
5364 return cxstring::createRef("UsingDeclaration");
5365 case CXCursor_TypeAliasDecl:
5366 return cxstring::createRef("TypeAliasDecl");
5367 case CXCursor_ObjCSynthesizeDecl:
5368 return cxstring::createRef("ObjCSynthesizeDecl");
5369 case CXCursor_ObjCDynamicDecl:
5370 return cxstring::createRef("ObjCDynamicDecl");
5371 case CXCursor_CXXAccessSpecifier:
5372 return cxstring::createRef("CXXAccessSpecifier");
5373 case CXCursor_ModuleImportDecl:
5374 return cxstring::createRef("ModuleImport");
5375 case CXCursor_OMPParallelDirective:
5376 return cxstring::createRef("OMPParallelDirective");
5377 case CXCursor_OMPSimdDirective:
5378 return cxstring::createRef("OMPSimdDirective");
5379 case CXCursor_OMPForDirective:
5380 return cxstring::createRef("OMPForDirective");
5381 case CXCursor_OMPForSimdDirective:
5382 return cxstring::createRef("OMPForSimdDirective");
5383 case CXCursor_OMPSectionsDirective:
5384 return cxstring::createRef("OMPSectionsDirective");
5385 case CXCursor_OMPSectionDirective:
5386 return cxstring::createRef("OMPSectionDirective");
5387 case CXCursor_OMPSingleDirective:
5388 return cxstring::createRef("OMPSingleDirective");
5389 case CXCursor_OMPMasterDirective:
5390 return cxstring::createRef("OMPMasterDirective");
5391 case CXCursor_OMPCriticalDirective:
5392 return cxstring::createRef("OMPCriticalDirective");
5393 case CXCursor_OMPParallelForDirective:
5394 return cxstring::createRef("OMPParallelForDirective");
5395 case CXCursor_OMPParallelForSimdDirective:
5396 return cxstring::createRef("OMPParallelForSimdDirective");
5397 case CXCursor_OMPParallelSectionsDirective:
5398 return cxstring::createRef("OMPParallelSectionsDirective");
5399 case CXCursor_OMPTaskDirective:
5400 return cxstring::createRef("OMPTaskDirective");
5401 case CXCursor_OMPTaskyieldDirective:
5402 return cxstring::createRef("OMPTaskyieldDirective");
5403 case CXCursor_OMPBarrierDirective:
5404 return cxstring::createRef("OMPBarrierDirective");
5405 case CXCursor_OMPTaskwaitDirective:
5406 return cxstring::createRef("OMPTaskwaitDirective");
5407 case CXCursor_OMPTaskgroupDirective:
5408 return cxstring::createRef("OMPTaskgroupDirective");
5409 case CXCursor_OMPFlushDirective:
5410 return cxstring::createRef("OMPFlushDirective");
5411 case CXCursor_OMPOrderedDirective:
5412 return cxstring::createRef("OMPOrderedDirective");
5413 case CXCursor_OMPAtomicDirective:
5414 return cxstring::createRef("OMPAtomicDirective");
5415 case CXCursor_OMPTargetDirective:
5416 return cxstring::createRef("OMPTargetDirective");
5417 case CXCursor_OMPTargetDataDirective:
5418 return cxstring::createRef("OMPTargetDataDirective");
5419 case CXCursor_OMPTargetEnterDataDirective:
5420 return cxstring::createRef("OMPTargetEnterDataDirective");
5421 case CXCursor_OMPTargetExitDataDirective:
5422 return cxstring::createRef("OMPTargetExitDataDirective");
5423 case CXCursor_OMPTargetParallelDirective:
5424 return cxstring::createRef("OMPTargetParallelDirective");
5425 case CXCursor_OMPTargetParallelForDirective:
5426 return cxstring::createRef("OMPTargetParallelForDirective");
5427 case CXCursor_OMPTargetUpdateDirective:
5428 return cxstring::createRef("OMPTargetUpdateDirective");
5429 case CXCursor_OMPTeamsDirective:
5430 return cxstring::createRef("OMPTeamsDirective");
5431 case CXCursor_OMPCancellationPointDirective:
5432 return cxstring::createRef("OMPCancellationPointDirective");
5433 case CXCursor_OMPCancelDirective:
5434 return cxstring::createRef("OMPCancelDirective");
5435 case CXCursor_OMPTaskLoopDirective:
5436 return cxstring::createRef("OMPTaskLoopDirective");
5437 case CXCursor_OMPTaskLoopSimdDirective:
5438 return cxstring::createRef("OMPTaskLoopSimdDirective");
5439 case CXCursor_OMPDistributeDirective:
5440 return cxstring::createRef("OMPDistributeDirective");
5441 case CXCursor_OMPDistributeParallelForDirective:
5442 return cxstring::createRef("OMPDistributeParallelForDirective");
5443 case CXCursor_OMPDistributeParallelForSimdDirective:
5444 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
5445 case CXCursor_OMPDistributeSimdDirective:
5446 return cxstring::createRef("OMPDistributeSimdDirective");
5447 case CXCursor_OMPTargetParallelForSimdDirective:
5448 return cxstring::createRef("OMPTargetParallelForSimdDirective");
5449 case CXCursor_OMPTargetSimdDirective:
5450 return cxstring::createRef("OMPTargetSimdDirective");
5451 case CXCursor_OMPTeamsDistributeDirective:
5452 return cxstring::createRef("OMPTeamsDistributeDirective");
5453 case CXCursor_OMPTeamsDistributeSimdDirective:
5454 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
5455 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5456 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
5457 case CXCursor_OMPTeamsDistributeParallelForDirective:
5458 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
5459 case CXCursor_OMPTargetTeamsDirective:
5460 return cxstring::createRef("OMPTargetTeamsDirective");
5461 case CXCursor_OMPTargetTeamsDistributeDirective:
5462 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
5463 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5464 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
5465 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5466 return cxstring::createRef(
5467 "OMPTargetTeamsDistributeParallelForSimdDirective");
5468 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5469 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
5470 case CXCursor_OverloadCandidate:
5471 return cxstring::createRef("OverloadCandidate");
5472 case CXCursor_TypeAliasTemplateDecl:
5473 return cxstring::createRef("TypeAliasTemplateDecl");
5474 case CXCursor_StaticAssert:
5475 return cxstring::createRef("StaticAssert");
5476 case CXCursor_FriendDecl:
5477 return cxstring::createRef("FriendDecl");
5478 }
5479
5480 llvm_unreachable("Unhandled CXCursorKind");
5481 }
5482
5483 struct GetCursorData {
5484 SourceLocation TokenBeginLoc;
5485 bool PointsAtMacroArgExpansion;
5486 bool VisitedObjCPropertyImplDecl;
5487 SourceLocation VisitedDeclaratorDeclStartLoc;
5488 CXCursor &BestCursor;
5489
5490 GetCursorData(SourceManager &SM,
5491 SourceLocation tokenBegin, CXCursor &outputCursor)
5492 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5493 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5494 VisitedObjCPropertyImplDecl = false;
5495 }
5496 };
5497
GetCursorVisitor(CXCursor cursor,CXCursor parent,CXClientData client_data)5498 static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5499 CXCursor parent,
5500 CXClientData client_data) {
5501 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5502 CXCursor *BestCursor = &Data->BestCursor;
5503
5504 // If we point inside a macro argument we should provide info of what the
5505 // token is so use the actual cursor, don't replace it with a macro expansion
5506 // cursor.
5507 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5508 return CXChildVisit_Recurse;
5509
5510 if (clang_isDeclaration(cursor.kind)) {
5511 // Avoid having the implicit methods override the property decls.
5512 if (const ObjCMethodDecl *MD
5513 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5514 if (MD->isImplicit())
5515 return CXChildVisit_Break;
5516
5517 } else if (const ObjCInterfaceDecl *ID
5518 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5519 // Check that when we have multiple @class references in the same line,
5520 // that later ones do not override the previous ones.
5521 // If we have:
5522 // @class Foo, Bar;
5523 // source ranges for both start at '@', so 'Bar' will end up overriding
5524 // 'Foo' even though the cursor location was at 'Foo'.
5525 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5526 BestCursor->kind == CXCursor_ObjCClassRef)
5527 if (const ObjCInterfaceDecl *PrevID
5528 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5529 if (PrevID != ID &&
5530 !PrevID->isThisDeclarationADefinition() &&
5531 !ID->isThisDeclarationADefinition())
5532 return CXChildVisit_Break;
5533 }
5534
5535 } else if (const DeclaratorDecl *DD
5536 = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5537 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5538 // Check that when we have multiple declarators in the same line,
5539 // that later ones do not override the previous ones.
5540 // If we have:
5541 // int Foo, Bar;
5542 // source ranges for both start at 'int', so 'Bar' will end up overriding
5543 // 'Foo' even though the cursor location was at 'Foo'.
5544 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5545 return CXChildVisit_Break;
5546 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5547
5548 } else if (const ObjCPropertyImplDecl *PropImp
5549 = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5550 (void)PropImp;
5551 // Check that when we have multiple @synthesize in the same line,
5552 // that later ones do not override the previous ones.
5553 // If we have:
5554 // @synthesize Foo, Bar;
5555 // source ranges for both start at '@', so 'Bar' will end up overriding
5556 // 'Foo' even though the cursor location was at 'Foo'.
5557 if (Data->VisitedObjCPropertyImplDecl)
5558 return CXChildVisit_Break;
5559 Data->VisitedObjCPropertyImplDecl = true;
5560 }
5561 }
5562
5563 if (clang_isExpression(cursor.kind) &&
5564 clang_isDeclaration(BestCursor->kind)) {
5565 if (const Decl *D = getCursorDecl(*BestCursor)) {
5566 // Avoid having the cursor of an expression replace the declaration cursor
5567 // when the expression source range overlaps the declaration range.
5568 // This can happen for C++ constructor expressions whose range generally
5569 // include the variable declaration, e.g.:
5570 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5571 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5572 D->getLocation() == Data->TokenBeginLoc)
5573 return CXChildVisit_Break;
5574 }
5575 }
5576
5577 // If our current best cursor is the construction of a temporary object,
5578 // don't replace that cursor with a type reference, because we want
5579 // clang_getCursor() to point at the constructor.
5580 if (clang_isExpression(BestCursor->kind) &&
5581 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5582 cursor.kind == CXCursor_TypeRef) {
5583 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5584 // as having the actual point on the type reference.
5585 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5586 return CXChildVisit_Recurse;
5587 }
5588
5589 // If we already have an Objective-C superclass reference, don't
5590 // update it further.
5591 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5592 return CXChildVisit_Break;
5593
5594 *BestCursor = cursor;
5595 return CXChildVisit_Recurse;
5596 }
5597
clang_getCursor(CXTranslationUnit TU,CXSourceLocation Loc)5598 CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
5599 if (isNotUsableTU(TU)) {
5600 LOG_BAD_TU(TU);
5601 return clang_getNullCursor();
5602 }
5603
5604 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5605 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5606
5607 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5608 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5609
5610 LOG_FUNC_SECTION {
5611 CXFile SearchFile;
5612 unsigned SearchLine, SearchColumn;
5613 CXFile ResultFile;
5614 unsigned ResultLine, ResultColumn;
5615 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5616 const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5617 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
5618
5619 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5620 nullptr);
5621 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
5622 &ResultColumn, nullptr);
5623 SearchFileName = clang_getFileName(SearchFile);
5624 ResultFileName = clang_getFileName(ResultFile);
5625 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5626 USR = clang_getCursorUSR(Result);
5627 *Log << llvm::format("(%s:%d:%d) = %s",
5628 clang_getCString(SearchFileName), SearchLine, SearchColumn,
5629 clang_getCString(KindSpelling))
5630 << llvm::format("(%s:%d:%d):%s%s",
5631 clang_getCString(ResultFileName), ResultLine, ResultColumn,
5632 clang_getCString(USR), IsDef);
5633 clang_disposeString(SearchFileName);
5634 clang_disposeString(ResultFileName);
5635 clang_disposeString(KindSpelling);
5636 clang_disposeString(USR);
5637
5638 CXCursor Definition = clang_getCursorDefinition(Result);
5639 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5640 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5641 CXString DefinitionKindSpelling
5642 = clang_getCursorKindSpelling(Definition.kind);
5643 CXFile DefinitionFile;
5644 unsigned DefinitionLine, DefinitionColumn;
5645 clang_getFileLocation(DefinitionLoc, &DefinitionFile,
5646 &DefinitionLine, &DefinitionColumn, nullptr);
5647 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
5648 *Log << llvm::format(" -> %s(%s:%d:%d)",
5649 clang_getCString(DefinitionKindSpelling),
5650 clang_getCString(DefinitionFileName),
5651 DefinitionLine, DefinitionColumn);
5652 clang_disposeString(DefinitionFileName);
5653 clang_disposeString(DefinitionKindSpelling);
5654 }
5655 }
5656
5657 return Result;
5658 }
5659
clang_getNullCursor(void)5660 CXCursor clang_getNullCursor(void) {
5661 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5662 }
5663
clang_equalCursors(CXCursor X,CXCursor Y)5664 unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
5665 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5666 // can't set consistently. For example, when visiting a DeclStmt we will set
5667 // it but we don't set it on the result of clang_getCursorDefinition for
5668 // a reference of the same declaration.
5669 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5670 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5671 // to provide that kind of info.
5672 if (clang_isDeclaration(X.kind))
5673 X.data[1] = nullptr;
5674 if (clang_isDeclaration(Y.kind))
5675 Y.data[1] = nullptr;
5676
5677 return X == Y;
5678 }
5679
clang_hashCursor(CXCursor C)5680 unsigned clang_hashCursor(CXCursor C) {
5681 unsigned Index = 0;
5682 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5683 Index = 1;
5684
5685 return llvm::DenseMapInfo<std::pair<unsigned, const void*> >::getHashValue(
5686 std::make_pair(C.kind, C.data[Index]));
5687 }
5688
clang_isInvalid(enum CXCursorKind K)5689 unsigned clang_isInvalid(enum CXCursorKind K) {
5690 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5691 }
5692
clang_isDeclaration(enum CXCursorKind K)5693 unsigned clang_isDeclaration(enum CXCursorKind K) {
5694 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
5695 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5696 }
5697
clang_isInvalidDeclaration(CXCursor C)5698 unsigned clang_isInvalidDeclaration(CXCursor C) {
5699 if (clang_isDeclaration(C.kind)) {
5700 if (const Decl *D = getCursorDecl(C))
5701 return D->isInvalidDecl();
5702 }
5703
5704 return 0;
5705 }
5706
clang_isReference(enum CXCursorKind K)5707 unsigned clang_isReference(enum CXCursorKind K) {
5708 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5709 }
5710
clang_isExpression(enum CXCursorKind K)5711 unsigned clang_isExpression(enum CXCursorKind K) {
5712 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5713 }
5714
clang_isStatement(enum CXCursorKind K)5715 unsigned clang_isStatement(enum CXCursorKind K) {
5716 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5717 }
5718
clang_isAttribute(enum CXCursorKind K)5719 unsigned clang_isAttribute(enum CXCursorKind K) {
5720 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5721 }
5722
clang_isTranslationUnit(enum CXCursorKind K)5723 unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5724 return K == CXCursor_TranslationUnit;
5725 }
5726
clang_isPreprocessing(enum CXCursorKind K)5727 unsigned clang_isPreprocessing(enum CXCursorKind K) {
5728 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5729 }
5730
clang_isUnexposed(enum CXCursorKind K)5731 unsigned clang_isUnexposed(enum CXCursorKind K) {
5732 switch (K) {
5733 case CXCursor_UnexposedDecl:
5734 case CXCursor_UnexposedExpr:
5735 case CXCursor_UnexposedStmt:
5736 case CXCursor_UnexposedAttr:
5737 return true;
5738 default:
5739 return false;
5740 }
5741 }
5742
clang_getCursorKind(CXCursor C)5743 CXCursorKind clang_getCursorKind(CXCursor C) {
5744 return C.kind;
5745 }
5746
clang_getCursorLocation(CXCursor C)5747 CXSourceLocation clang_getCursorLocation(CXCursor C) {
5748 if (clang_isReference(C.kind)) {
5749 switch (C.kind) {
5750 case CXCursor_ObjCSuperClassRef: {
5751 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
5752 = getCursorObjCSuperClassRef(C);
5753 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5754 }
5755
5756 case CXCursor_ObjCProtocolRef: {
5757 std::pair<const ObjCProtocolDecl *, SourceLocation> P
5758 = getCursorObjCProtocolRef(C);
5759 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5760 }
5761
5762 case CXCursor_ObjCClassRef: {
5763 std::pair<const ObjCInterfaceDecl *, SourceLocation> P
5764 = getCursorObjCClassRef(C);
5765 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5766 }
5767
5768 case CXCursor_TypeRef: {
5769 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
5770 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5771 }
5772
5773 case CXCursor_TemplateRef: {
5774 std::pair<const TemplateDecl *, SourceLocation> P =
5775 getCursorTemplateRef(C);
5776 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5777 }
5778
5779 case CXCursor_NamespaceRef: {
5780 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
5781 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5782 }
5783
5784 case CXCursor_MemberRef: {
5785 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
5786 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5787 }
5788
5789 case CXCursor_VariableRef: {
5790 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
5791 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5792 }
5793
5794 case CXCursor_CXXBaseSpecifier: {
5795 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
5796 if (!BaseSpec)
5797 return clang_getNullLocation();
5798
5799 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5800 return cxloc::translateSourceLocation(getCursorContext(C),
5801 TSInfo->getTypeLoc().getBeginLoc());
5802
5803 return cxloc::translateSourceLocation(getCursorContext(C),
5804 BaseSpec->getBeginLoc());
5805 }
5806
5807 case CXCursor_LabelRef: {
5808 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
5809 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
5810 }
5811
5812 case CXCursor_OverloadedDeclRef:
5813 return cxloc::translateSourceLocation(getCursorContext(C),
5814 getCursorOverloadedDeclRef(C).second);
5815
5816 default:
5817 // FIXME: Need a way to enumerate all non-reference cases.
5818 llvm_unreachable("Missed a reference kind");
5819 }
5820 }
5821
5822 if (clang_isExpression(C.kind))
5823 return cxloc::translateSourceLocation(getCursorContext(C),
5824 getLocationFromExpr(getCursorExpr(C)));
5825
5826 if (clang_isStatement(C.kind))
5827 return cxloc::translateSourceLocation(getCursorContext(C),
5828 getCursorStmt(C)->getBeginLoc());
5829
5830 if (C.kind == CXCursor_PreprocessingDirective) {
5831 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5832 return cxloc::translateSourceLocation(getCursorContext(C), L);
5833 }
5834
5835 if (C.kind == CXCursor_MacroExpansion) {
5836 SourceLocation L
5837 = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
5838 return cxloc::translateSourceLocation(getCursorContext(C), L);
5839 }
5840
5841 if (C.kind == CXCursor_MacroDefinition) {
5842 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5843 return cxloc::translateSourceLocation(getCursorContext(C), L);
5844 }
5845
5846 if (C.kind == CXCursor_InclusionDirective) {
5847 SourceLocation L
5848 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5849 return cxloc::translateSourceLocation(getCursorContext(C), L);
5850 }
5851
5852 if (clang_isAttribute(C.kind)) {
5853 SourceLocation L
5854 = cxcursor::getCursorAttr(C)->getLocation();
5855 return cxloc::translateSourceLocation(getCursorContext(C), L);
5856 }
5857
5858 if (!clang_isDeclaration(C.kind))
5859 return clang_getNullLocation();
5860
5861 const Decl *D = getCursorDecl(C);
5862 if (!D)
5863 return clang_getNullLocation();
5864
5865 SourceLocation Loc = D->getLocation();
5866 // FIXME: Multiple variables declared in a single declaration
5867 // currently lack the information needed to correctly determine their
5868 // ranges when accounting for the type-specifier. We use context
5869 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5870 // and if so, whether it is the first decl.
5871 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5872 if (!cxcursor::isFirstInDeclGroup(C))
5873 Loc = VD->getLocation();
5874 }
5875
5876 // For ObjC methods, give the start location of the method name.
5877 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
5878 Loc = MD->getSelectorStartLoc();
5879
5880 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
5881 }
5882
5883 } // end extern "C"
5884
getCursor(CXTranslationUnit TU,SourceLocation SLoc)5885 CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
5886 assert(TU);
5887
5888 // Guard against an invalid SourceLocation, or we may assert in one
5889 // of the following calls.
5890 if (SLoc.isInvalid())
5891 return clang_getNullCursor();
5892
5893 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5894
5895 // Translate the given source location to make it point at the beginning of
5896 // the token under the cursor.
5897 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
5898 CXXUnit->getASTContext().getLangOpts());
5899
5900 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5901 if (SLoc.isValid()) {
5902 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
5903 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
5904 /*VisitPreprocessorLast=*/true,
5905 /*VisitIncludedEntities=*/false,
5906 SourceLocation(SLoc));
5907 CursorVis.visitFileRegion();
5908 }
5909
5910 return Result;
5911 }
5912
getRawCursorExtent(CXCursor C)5913 static SourceRange getRawCursorExtent(CXCursor C) {
5914 if (clang_isReference(C.kind)) {
5915 switch (C.kind) {
5916 case CXCursor_ObjCSuperClassRef:
5917 return getCursorObjCSuperClassRef(C).second;
5918
5919 case CXCursor_ObjCProtocolRef:
5920 return getCursorObjCProtocolRef(C).second;
5921
5922 case CXCursor_ObjCClassRef:
5923 return getCursorObjCClassRef(C).second;
5924
5925 case CXCursor_TypeRef:
5926 return getCursorTypeRef(C).second;
5927
5928 case CXCursor_TemplateRef:
5929 return getCursorTemplateRef(C).second;
5930
5931 case CXCursor_NamespaceRef:
5932 return getCursorNamespaceRef(C).second;
5933
5934 case CXCursor_MemberRef:
5935 return getCursorMemberRef(C).second;
5936
5937 case CXCursor_CXXBaseSpecifier:
5938 return getCursorCXXBaseSpecifier(C)->getSourceRange();
5939
5940 case CXCursor_LabelRef:
5941 return getCursorLabelRef(C).second;
5942
5943 case CXCursor_OverloadedDeclRef:
5944 return getCursorOverloadedDeclRef(C).second;
5945
5946 case CXCursor_VariableRef:
5947 return getCursorVariableRef(C).second;
5948
5949 default:
5950 // FIXME: Need a way to enumerate all non-reference cases.
5951 llvm_unreachable("Missed a reference kind");
5952 }
5953 }
5954
5955 if (clang_isExpression(C.kind))
5956 return getCursorExpr(C)->getSourceRange();
5957
5958 if (clang_isStatement(C.kind))
5959 return getCursorStmt(C)->getSourceRange();
5960
5961 if (clang_isAttribute(C.kind))
5962 return getCursorAttr(C)->getRange();
5963
5964 if (C.kind == CXCursor_PreprocessingDirective)
5965 return cxcursor::getCursorPreprocessingDirective(C);
5966
5967 if (C.kind == CXCursor_MacroExpansion) {
5968 ASTUnit *TU = getCursorASTUnit(C);
5969 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
5970 return TU->mapRangeFromPreamble(Range);
5971 }
5972
5973 if (C.kind == CXCursor_MacroDefinition) {
5974 ASTUnit *TU = getCursorASTUnit(C);
5975 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5976 return TU->mapRangeFromPreamble(Range);
5977 }
5978
5979 if (C.kind == CXCursor_InclusionDirective) {
5980 ASTUnit *TU = getCursorASTUnit(C);
5981 SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5982 return TU->mapRangeFromPreamble(Range);
5983 }
5984
5985 if (C.kind == CXCursor_TranslationUnit) {
5986 ASTUnit *TU = getCursorASTUnit(C);
5987 FileID MainID = TU->getSourceManager().getMainFileID();
5988 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
5989 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
5990 return SourceRange(Start, End);
5991 }
5992
5993 if (clang_isDeclaration(C.kind)) {
5994 const Decl *D = cxcursor::getCursorDecl(C);
5995 if (!D)
5996 return SourceRange();
5997
5998 SourceRange R = D->getSourceRange();
5999 // FIXME: Multiple variables declared in a single declaration
6000 // currently lack the information needed to correctly determine their
6001 // ranges when accounting for the type-specifier. We use context
6002 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6003 // and if so, whether it is the first decl.
6004 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6005 if (!cxcursor::isFirstInDeclGroup(C))
6006 R.setBegin(VD->getLocation());
6007 }
6008 return R;
6009 }
6010 return SourceRange();
6011 }
6012
6013 /// Retrieves the "raw" cursor extent, which is then extended to include
6014 /// the decl-specifier-seq for declarations.
getFullCursorExtent(CXCursor C,SourceManager & SrcMgr)6015 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
6016 if (clang_isDeclaration(C.kind)) {
6017 const Decl *D = cxcursor::getCursorDecl(C);
6018 if (!D)
6019 return SourceRange();
6020
6021 SourceRange R = D->getSourceRange();
6022
6023 // Adjust the start of the location for declarations preceded by
6024 // declaration specifiers.
6025 SourceLocation StartLoc;
6026 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6027 if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
6028 StartLoc = TI->getTypeLoc().getBeginLoc();
6029 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
6030 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
6031 StartLoc = TI->getTypeLoc().getBeginLoc();
6032 }
6033
6034 if (StartLoc.isValid() && R.getBegin().isValid() &&
6035 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
6036 R.setBegin(StartLoc);
6037
6038 // FIXME: Multiple variables declared in a single declaration
6039 // currently lack the information needed to correctly determine their
6040 // ranges when accounting for the type-specifier. We use context
6041 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6042 // and if so, whether it is the first decl.
6043 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6044 if (!cxcursor::isFirstInDeclGroup(C))
6045 R.setBegin(VD->getLocation());
6046 }
6047
6048 return R;
6049 }
6050
6051 return getRawCursorExtent(C);
6052 }
6053
clang_getCursorExtent(CXCursor C)6054 CXSourceRange clang_getCursorExtent(CXCursor C) {
6055 SourceRange R = getRawCursorExtent(C);
6056 if (R.isInvalid())
6057 return clang_getNullRange();
6058
6059 return cxloc::translateSourceRange(getCursorContext(C), R);
6060 }
6061
clang_getCursorReferenced(CXCursor C)6062 CXCursor clang_getCursorReferenced(CXCursor C) {
6063 if (clang_isInvalid(C.kind))
6064 return clang_getNullCursor();
6065
6066 CXTranslationUnit tu = getCursorTU(C);
6067 if (clang_isDeclaration(C.kind)) {
6068 const Decl *D = getCursorDecl(C);
6069 if (!D)
6070 return clang_getNullCursor();
6071 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
6072 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
6073 if (const ObjCPropertyImplDecl *PropImpl =
6074 dyn_cast<ObjCPropertyImplDecl>(D))
6075 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6076 return MakeCXCursor(Property, tu);
6077
6078 return C;
6079 }
6080
6081 if (clang_isExpression(C.kind)) {
6082 const Expr *E = getCursorExpr(C);
6083 const Decl *D = getDeclFromExpr(E);
6084 if (D) {
6085 CXCursor declCursor = MakeCXCursor(D, tu);
6086 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6087 declCursor);
6088 return declCursor;
6089 }
6090
6091 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
6092 return MakeCursorOverloadedDeclRef(Ovl, tu);
6093
6094 return clang_getNullCursor();
6095 }
6096
6097 if (clang_isStatement(C.kind)) {
6098 const Stmt *S = getCursorStmt(C);
6099 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
6100 if (LabelDecl *label = Goto->getLabel())
6101 if (LabelStmt *labelS = label->getStmt())
6102 return MakeCXCursor(labelS, getCursorDecl(C), tu);
6103
6104 return clang_getNullCursor();
6105 }
6106
6107 if (C.kind == CXCursor_MacroExpansion) {
6108 if (const MacroDefinitionRecord *Def =
6109 getCursorMacroExpansion(C).getDefinition())
6110 return MakeMacroDefinitionCursor(Def, tu);
6111 }
6112
6113 if (!clang_isReference(C.kind))
6114 return clang_getNullCursor();
6115
6116 switch (C.kind) {
6117 case CXCursor_ObjCSuperClassRef:
6118 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
6119
6120 case CXCursor_ObjCProtocolRef: {
6121 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6122 if (const ObjCProtocolDecl *Def = Prot->getDefinition())
6123 return MakeCXCursor(Def, tu);
6124
6125 return MakeCXCursor(Prot, tu);
6126 }
6127
6128 case CXCursor_ObjCClassRef: {
6129 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6130 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
6131 return MakeCXCursor(Def, tu);
6132
6133 return MakeCXCursor(Class, tu);
6134 }
6135
6136 case CXCursor_TypeRef:
6137 return MakeCXCursor(getCursorTypeRef(C).first, tu );
6138
6139 case CXCursor_TemplateRef:
6140 return MakeCXCursor(getCursorTemplateRef(C).first, tu );
6141
6142 case CXCursor_NamespaceRef:
6143 return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
6144
6145 case CXCursor_MemberRef:
6146 return MakeCXCursor(getCursorMemberRef(C).first, tu );
6147
6148 case CXCursor_CXXBaseSpecifier: {
6149 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
6150 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6151 tu ));
6152 }
6153
6154 case CXCursor_LabelRef:
6155 // FIXME: We end up faking the "parent" declaration here because we
6156 // don't want to make CXCursor larger.
6157 return MakeCXCursor(getCursorLabelRef(C).first,
6158 cxtu::getASTUnit(tu)->getASTContext()
6159 .getTranslationUnitDecl(),
6160 tu);
6161
6162 case CXCursor_OverloadedDeclRef:
6163 return C;
6164
6165 case CXCursor_VariableRef:
6166 return MakeCXCursor(getCursorVariableRef(C).first, tu);
6167
6168 default:
6169 // We would prefer to enumerate all non-reference cursor kinds here.
6170 llvm_unreachable("Unhandled reference cursor kind");
6171 }
6172 }
6173
clang_getCursorDefinition(CXCursor C)6174 CXCursor clang_getCursorDefinition(CXCursor C) {
6175 if (clang_isInvalid(C.kind))
6176 return clang_getNullCursor();
6177
6178 CXTranslationUnit TU = getCursorTU(C);
6179
6180 bool WasReference = false;
6181 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6182 C = clang_getCursorReferenced(C);
6183 WasReference = true;
6184 }
6185
6186 if (C.kind == CXCursor_MacroExpansion)
6187 return clang_getCursorReferenced(C);
6188
6189 if (!clang_isDeclaration(C.kind))
6190 return clang_getNullCursor();
6191
6192 const Decl *D = getCursorDecl(C);
6193 if (!D)
6194 return clang_getNullCursor();
6195
6196 switch (D->getKind()) {
6197 // Declaration kinds that don't really separate the notions of
6198 // declaration and definition.
6199 case Decl::Namespace:
6200 case Decl::Typedef:
6201 case Decl::TypeAlias:
6202 case Decl::TypeAliasTemplate:
6203 case Decl::TemplateTypeParm:
6204 case Decl::EnumConstant:
6205 case Decl::Field:
6206 case Decl::Binding:
6207 case Decl::MSProperty:
6208 case Decl::IndirectField:
6209 case Decl::ObjCIvar:
6210 case Decl::ObjCAtDefsField:
6211 case Decl::ImplicitParam:
6212 case Decl::ParmVar:
6213 case Decl::NonTypeTemplateParm:
6214 case Decl::TemplateTemplateParm:
6215 case Decl::ObjCCategoryImpl:
6216 case Decl::ObjCImplementation:
6217 case Decl::AccessSpec:
6218 case Decl::LinkageSpec:
6219 case Decl::Export:
6220 case Decl::ObjCPropertyImpl:
6221 case Decl::FileScopeAsm:
6222 case Decl::StaticAssert:
6223 case Decl::Block:
6224 case Decl::Captured:
6225 case Decl::OMPCapturedExpr:
6226 case Decl::Label: // FIXME: Is this right??
6227 case Decl::ClassScopeFunctionSpecialization:
6228 case Decl::CXXDeductionGuide:
6229 case Decl::Import:
6230 case Decl::OMPThreadPrivate:
6231 case Decl::OMPDeclareReduction:
6232 case Decl::OMPRequires:
6233 case Decl::ObjCTypeParam:
6234 case Decl::BuiltinTemplate:
6235 case Decl::PragmaComment:
6236 case Decl::PragmaDetectMismatch:
6237 case Decl::UsingPack:
6238 return C;
6239
6240 // Declaration kinds that don't make any sense here, but are
6241 // nonetheless harmless.
6242 case Decl::Empty:
6243 case Decl::TranslationUnit:
6244 case Decl::ExternCContext:
6245 break;
6246
6247 // Declaration kinds for which the definition is not resolvable.
6248 case Decl::UnresolvedUsingTypename:
6249 case Decl::UnresolvedUsingValue:
6250 break;
6251
6252 case Decl::UsingDirective:
6253 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6254 TU);
6255
6256 case Decl::NamespaceAlias:
6257 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6258
6259 case Decl::Enum:
6260 case Decl::Record:
6261 case Decl::CXXRecord:
6262 case Decl::ClassTemplateSpecialization:
6263 case Decl::ClassTemplatePartialSpecialization:
6264 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6265 return MakeCXCursor(Def, TU);
6266 return clang_getNullCursor();
6267
6268 case Decl::Function:
6269 case Decl::CXXMethod:
6270 case Decl::CXXConstructor:
6271 case Decl::CXXDestructor:
6272 case Decl::CXXConversion: {
6273 const FunctionDecl *Def = nullptr;
6274 if (cast<FunctionDecl>(D)->getBody(Def))
6275 return MakeCXCursor(Def, TU);
6276 return clang_getNullCursor();
6277 }
6278
6279 case Decl::Var:
6280 case Decl::VarTemplateSpecialization:
6281 case Decl::VarTemplatePartialSpecialization:
6282 case Decl::Decomposition: {
6283 // Ask the variable if it has a definition.
6284 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
6285 return MakeCXCursor(Def, TU);
6286 return clang_getNullCursor();
6287 }
6288
6289 case Decl::FunctionTemplate: {
6290 const FunctionDecl *Def = nullptr;
6291 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6292 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6293 return clang_getNullCursor();
6294 }
6295
6296 case Decl::ClassTemplate: {
6297 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6298 ->getDefinition())
6299 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6300 TU);
6301 return clang_getNullCursor();
6302 }
6303
6304 case Decl::VarTemplate: {
6305 if (VarDecl *Def =
6306 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6307 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6308 return clang_getNullCursor();
6309 }
6310
6311 case Decl::Using:
6312 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
6313 D->getLocation(), TU);
6314
6315 case Decl::UsingShadow:
6316 case Decl::ConstructorUsingShadow:
6317 return clang_getCursorDefinition(
6318 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6319 TU));
6320
6321 case Decl::ObjCMethod: {
6322 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
6323 if (Method->isThisDeclarationADefinition())
6324 return C;
6325
6326 // Dig out the method definition in the associated
6327 // @implementation, if we have it.
6328 // FIXME: The ASTs should make finding the definition easier.
6329 if (const ObjCInterfaceDecl *Class
6330 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6331 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6332 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6333 Method->isInstanceMethod()))
6334 if (Def->isThisDeclarationADefinition())
6335 return MakeCXCursor(Def, TU);
6336
6337 return clang_getNullCursor();
6338 }
6339
6340 case Decl::ObjCCategory:
6341 if (ObjCCategoryImplDecl *Impl
6342 = cast<ObjCCategoryDecl>(D)->getImplementation())
6343 return MakeCXCursor(Impl, TU);
6344 return clang_getNullCursor();
6345
6346 case Decl::ObjCProtocol:
6347 if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
6348 return MakeCXCursor(Def, TU);
6349 return clang_getNullCursor();
6350
6351 case Decl::ObjCInterface: {
6352 // There are two notions of a "definition" for an Objective-C
6353 // class: the interface and its implementation. When we resolved a
6354 // reference to an Objective-C class, produce the @interface as
6355 // the definition; when we were provided with the interface,
6356 // produce the @implementation as the definition.
6357 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
6358 if (WasReference) {
6359 if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
6360 return MakeCXCursor(Def, TU);
6361 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6362 return MakeCXCursor(Impl, TU);
6363 return clang_getNullCursor();
6364 }
6365
6366 case Decl::ObjCProperty:
6367 // FIXME: We don't really know where to find the
6368 // ObjCPropertyImplDecls that implement this property.
6369 return clang_getNullCursor();
6370
6371 case Decl::ObjCCompatibleAlias:
6372 if (const ObjCInterfaceDecl *Class
6373 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
6374 if (const ObjCInterfaceDecl *Def = Class->getDefinition())
6375 return MakeCXCursor(Def, TU);
6376
6377 return clang_getNullCursor();
6378
6379 case Decl::Friend:
6380 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6381 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6382 return clang_getNullCursor();
6383
6384 case Decl::FriendTemplate:
6385 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6386 return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
6387 return clang_getNullCursor();
6388 }
6389
6390 return clang_getNullCursor();
6391 }
6392
clang_isCursorDefinition(CXCursor C)6393 unsigned clang_isCursorDefinition(CXCursor C) {
6394 if (!clang_isDeclaration(C.kind))
6395 return 0;
6396
6397 return clang_getCursorDefinition(C) == C;
6398 }
6399
clang_getCanonicalCursor(CXCursor C)6400 CXCursor clang_getCanonicalCursor(CXCursor C) {
6401 if (!clang_isDeclaration(C.kind))
6402 return C;
6403
6404 if (const Decl *D = getCursorDecl(C)) {
6405 if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
6406 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6407 return MakeCXCursor(CatD, getCursorTU(C));
6408
6409 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6410 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
6411 return MakeCXCursor(IFD, getCursorTU(C));
6412
6413 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6414 }
6415
6416 return C;
6417 }
6418
clang_Cursor_getObjCSelectorIndex(CXCursor cursor)6419 int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6420 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6421 }
6422
clang_getNumOverloadedDecls(CXCursor C)6423 unsigned clang_getNumOverloadedDecls(CXCursor C) {
6424 if (C.kind != CXCursor_OverloadedDeclRef)
6425 return 0;
6426
6427 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
6428 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
6429 return E->getNumDecls();
6430
6431 if (OverloadedTemplateStorage *S
6432 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6433 return S->size();
6434
6435 const Decl *D = Storage.get<const Decl *>();
6436 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
6437 return Using->shadow_size();
6438
6439 return 0;
6440 }
6441
clang_getOverloadedDecl(CXCursor cursor,unsigned index)6442 CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
6443 if (cursor.kind != CXCursor_OverloadedDeclRef)
6444 return clang_getNullCursor();
6445
6446 if (index >= clang_getNumOverloadedDecls(cursor))
6447 return clang_getNullCursor();
6448
6449 CXTranslationUnit TU = getCursorTU(cursor);
6450 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
6451 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
6452 return MakeCXCursor(E->decls_begin()[index], TU);
6453
6454 if (OverloadedTemplateStorage *S
6455 = Storage.dyn_cast<OverloadedTemplateStorage*>())
6456 return MakeCXCursor(S->begin()[index], TU);
6457
6458 const Decl *D = Storage.get<const Decl *>();
6459 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
6460 // FIXME: This is, unfortunately, linear time.
6461 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6462 std::advance(Pos, index);
6463 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6464 }
6465
6466 return clang_getNullCursor();
6467 }
6468
clang_getDefinitionSpellingAndExtent(CXCursor C,const char ** startBuf,const char ** endBuf,unsigned * startLine,unsigned * startColumn,unsigned * endLine,unsigned * endColumn)6469 void clang_getDefinitionSpellingAndExtent(CXCursor C,
6470 const char **startBuf,
6471 const char **endBuf,
6472 unsigned *startLine,
6473 unsigned *startColumn,
6474 unsigned *endLine,
6475 unsigned *endColumn) {
6476 assert(getCursorDecl(C) && "CXCursor has null decl");
6477 const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
6478 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6479
6480 SourceManager &SM = FD->getASTContext().getSourceManager();
6481 *startBuf = SM.getCharacterData(Body->getLBracLoc());
6482 *endBuf = SM.getCharacterData(Body->getRBracLoc());
6483 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6484 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6485 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6486 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6487 }
6488
6489
clang_getCursorReferenceNameRange(CXCursor C,unsigned NameFlags,unsigned PieceIndex)6490 CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
6491 unsigned PieceIndex) {
6492 RefNamePieces Pieces;
6493
6494 switch (C.kind) {
6495 case CXCursor_MemberRefExpr:
6496 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
6497 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6498 E->getQualifierLoc().getSourceRange());
6499 break;
6500
6501 case CXCursor_DeclRefExpr:
6502 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6503 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6504 Pieces =
6505 buildPieces(NameFlags, false, E->getNameInfo(),
6506 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6507 }
6508 break;
6509
6510 case CXCursor_CallExpr:
6511 if (const CXXOperatorCallExpr *OCE =
6512 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
6513 const Expr *Callee = OCE->getCallee();
6514 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
6515 Callee = ICE->getSubExpr();
6516
6517 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
6518 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6519 DRE->getQualifierLoc().getSourceRange());
6520 }
6521 break;
6522
6523 default:
6524 break;
6525 }
6526
6527 if (Pieces.empty()) {
6528 if (PieceIndex == 0)
6529 return clang_getCursorExtent(C);
6530 } else if (PieceIndex < Pieces.size()) {
6531 SourceRange R = Pieces[PieceIndex];
6532 if (R.isValid())
6533 return cxloc::translateSourceRange(getCursorContext(C), R);
6534 }
6535
6536 return clang_getNullRange();
6537 }
6538
clang_enableStackTraces(void)6539 void clang_enableStackTraces(void) {
6540 // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6541 llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
6542 }
6543
clang_executeOnThread(void (* fn)(void *),void * user_data,unsigned stack_size)6544 void clang_executeOnThread(void (*fn)(void*), void *user_data,
6545 unsigned stack_size) {
6546 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6547 }
6548
6549 //===----------------------------------------------------------------------===//
6550 // Token-based Operations.
6551 //===----------------------------------------------------------------------===//
6552
6553 /* CXToken layout:
6554 * int_data[0]: a CXTokenKind
6555 * int_data[1]: starting token location
6556 * int_data[2]: token length
6557 * int_data[3]: reserved
6558 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
6559 * otherwise unused.
6560 */
clang_getTokenKind(CXToken CXTok)6561 CXTokenKind clang_getTokenKind(CXToken CXTok) {
6562 return static_cast<CXTokenKind>(CXTok.int_data[0]);
6563 }
6564
clang_getTokenSpelling(CXTranslationUnit TU,CXToken CXTok)6565 CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
6566 switch (clang_getTokenKind(CXTok)) {
6567 case CXToken_Identifier:
6568 case CXToken_Keyword:
6569 // We know we have an IdentifierInfo*, so use that.
6570 return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
6571 ->getNameStart());
6572
6573 case CXToken_Literal: {
6574 // We have stashed the starting pointer in the ptr_data field. Use it.
6575 const char *Text = static_cast<const char *>(CXTok.ptr_data);
6576 return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
6577 }
6578
6579 case CXToken_Punctuation:
6580 case CXToken_Comment:
6581 break;
6582 }
6583
6584 if (isNotUsableTU(TU)) {
6585 LOG_BAD_TU(TU);
6586 return cxstring::createEmpty();
6587 }
6588
6589 // We have to find the starting buffer pointer the hard way, by
6590 // deconstructing the source location.
6591 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6592 if (!CXXUnit)
6593 return cxstring::createEmpty();
6594
6595 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6596 std::pair<FileID, unsigned> LocInfo
6597 = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6598 bool Invalid = false;
6599 StringRef Buffer
6600 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6601 if (Invalid)
6602 return cxstring::createEmpty();
6603
6604 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
6605 }
6606
clang_getTokenLocation(CXTranslationUnit TU,CXToken CXTok)6607 CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
6608 if (isNotUsableTU(TU)) {
6609 LOG_BAD_TU(TU);
6610 return clang_getNullLocation();
6611 }
6612
6613 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6614 if (!CXXUnit)
6615 return clang_getNullLocation();
6616
6617 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6618 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6619 }
6620
clang_getTokenExtent(CXTranslationUnit TU,CXToken CXTok)6621 CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
6622 if (isNotUsableTU(TU)) {
6623 LOG_BAD_TU(TU);
6624 return clang_getNullRange();
6625 }
6626
6627 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6628 if (!CXXUnit)
6629 return clang_getNullRange();
6630
6631 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6632 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6633 }
6634
getTokens(ASTUnit * CXXUnit,SourceRange Range,SmallVectorImpl<CXToken> & CXTokens)6635 static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
6636 SmallVectorImpl<CXToken> &CXTokens) {
6637 SourceManager &SourceMgr = CXXUnit->getSourceManager();
6638 std::pair<FileID, unsigned> BeginLocInfo
6639 = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
6640 std::pair<FileID, unsigned> EndLocInfo
6641 = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
6642
6643 // Cannot tokenize across files.
6644 if (BeginLocInfo.first != EndLocInfo.first)
6645 return;
6646
6647 // Create a lexer
6648 bool Invalid = false;
6649 StringRef Buffer
6650 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6651 if (Invalid)
6652 return;
6653
6654 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6655 CXXUnit->getASTContext().getLangOpts(),
6656 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6657 Lex.SetCommentRetentionState(true);
6658
6659 // Lex tokens until we hit the end of the range.
6660 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6661 Token Tok;
6662 bool previousWasAt = false;
6663 do {
6664 // Lex the next token
6665 Lex.LexFromRawLexer(Tok);
6666 if (Tok.is(tok::eof))
6667 break;
6668
6669 // Initialize the CXToken.
6670 CXToken CXTok;
6671
6672 // - Common fields
6673 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6674 CXTok.int_data[2] = Tok.getLength();
6675 CXTok.int_data[3] = 0;
6676
6677 // - Kind-specific fields
6678 if (Tok.isLiteral()) {
6679 CXTok.int_data[0] = CXToken_Literal;
6680 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
6681 } else if (Tok.is(tok::raw_identifier)) {
6682 // Lookup the identifier to determine whether we have a keyword.
6683 IdentifierInfo *II
6684 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6685
6686 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6687 CXTok.int_data[0] = CXToken_Keyword;
6688 }
6689 else {
6690 CXTok.int_data[0] = Tok.is(tok::identifier)
6691 ? CXToken_Identifier
6692 : CXToken_Keyword;
6693 }
6694 CXTok.ptr_data = II;
6695 } else if (Tok.is(tok::comment)) {
6696 CXTok.int_data[0] = CXToken_Comment;
6697 CXTok.ptr_data = nullptr;
6698 } else {
6699 CXTok.int_data[0] = CXToken_Punctuation;
6700 CXTok.ptr_data = nullptr;
6701 }
6702 CXTokens.push_back(CXTok);
6703 previousWasAt = Tok.is(tok::at);
6704 } while (Lex.getBufferLocation() < EffectiveBufferEnd);
6705 }
6706
clang_getToken(CXTranslationUnit TU,CXSourceLocation Location)6707 CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
6708 LOG_FUNC_SECTION {
6709 *Log << TU << ' ' << Location;
6710 }
6711
6712 if (isNotUsableTU(TU)) {
6713 LOG_BAD_TU(TU);
6714 return NULL;
6715 }
6716
6717 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6718 if (!CXXUnit)
6719 return NULL;
6720
6721 SourceLocation Begin = cxloc::translateSourceLocation(Location);
6722 if (Begin.isInvalid())
6723 return NULL;
6724 SourceManager &SM = CXXUnit->getSourceManager();
6725 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
6726 DecomposedEnd.second += Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
6727
6728 SourceLocation End = SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
6729
6730 SmallVector<CXToken, 32> CXTokens;
6731 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6732
6733 if (CXTokens.empty())
6734 return NULL;
6735
6736 CXTokens.resize(1);
6737 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6738
6739 memmove(Token, CXTokens.data(), sizeof(CXToken));
6740 return Token;
6741 }
6742
clang_tokenize(CXTranslationUnit TU,CXSourceRange Range,CXToken ** Tokens,unsigned * NumTokens)6743 void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
6744 CXToken **Tokens, unsigned *NumTokens) {
6745 LOG_FUNC_SECTION {
6746 *Log << TU << ' ' << Range;
6747 }
6748
6749 if (Tokens)
6750 *Tokens = nullptr;
6751 if (NumTokens)
6752 *NumTokens = 0;
6753
6754 if (isNotUsableTU(TU)) {
6755 LOG_BAD_TU(TU);
6756 return;
6757 }
6758
6759 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6760 if (!CXXUnit || !Tokens || !NumTokens)
6761 return;
6762
6763 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6764
6765 SourceRange R = cxloc::translateCXSourceRange(Range);
6766 if (R.isInvalid())
6767 return;
6768
6769 SmallVector<CXToken, 32> CXTokens;
6770 getTokens(CXXUnit, R, CXTokens);
6771
6772 if (CXTokens.empty())
6773 return;
6774
6775 *Tokens = static_cast<CXToken *>(
6776 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
6777 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6778 *NumTokens = CXTokens.size();
6779 }
6780
clang_disposeTokens(CXTranslationUnit TU,CXToken * Tokens,unsigned NumTokens)6781 void clang_disposeTokens(CXTranslationUnit TU,
6782 CXToken *Tokens, unsigned NumTokens) {
6783 free(Tokens);
6784 }
6785
6786 //===----------------------------------------------------------------------===//
6787 // Token annotation APIs.
6788 //===----------------------------------------------------------------------===//
6789
6790 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6791 CXCursor parent,
6792 CXClientData client_data);
6793 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6794 CXClientData client_data);
6795
6796 namespace {
6797 class AnnotateTokensWorker {
6798 CXToken *Tokens;
6799 CXCursor *Cursors;
6800 unsigned NumTokens;
6801 unsigned TokIdx;
6802 unsigned PreprocessingTokIdx;
6803 CursorVisitor AnnotateVis;
6804 SourceManager &SrcMgr;
6805 bool HasContextSensitiveKeywords;
6806
6807 struct PostChildrenAction {
6808 CXCursor cursor;
6809 enum Action { Invalid, Ignore, Postpone } action;
6810 };
6811 using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
6812
6813 struct PostChildrenInfo {
6814 CXCursor Cursor;
6815 SourceRange CursorRange;
6816 unsigned BeforeReachingCursorIdx;
6817 unsigned BeforeChildrenTokenIdx;
6818 PostChildrenActions ChildActions;
6819 };
6820 SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
6821
getTok(unsigned Idx)6822 CXToken &getTok(unsigned Idx) {
6823 assert(Idx < NumTokens);
6824 return Tokens[Idx];
6825 }
getTok(unsigned Idx) const6826 const CXToken &getTok(unsigned Idx) const {
6827 assert(Idx < NumTokens);
6828 return Tokens[Idx];
6829 }
MoreTokens() const6830 bool MoreTokens() const { return TokIdx < NumTokens; }
NextToken() const6831 unsigned NextToken() const { return TokIdx; }
AdvanceToken()6832 void AdvanceToken() { ++TokIdx; }
GetTokenLoc(unsigned tokI)6833 SourceLocation GetTokenLoc(unsigned tokI) {
6834 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
6835 }
isFunctionMacroToken(unsigned tokI) const6836 bool isFunctionMacroToken(unsigned tokI) const {
6837 return getTok(tokI).int_data[3] != 0;
6838 }
getFunctionMacroTokenLoc(unsigned tokI) const6839 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
6840 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
6841 }
6842
6843 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
6844 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
6845 SourceRange);
6846
6847 public:
AnnotateTokensWorker(CXToken * tokens,CXCursor * cursors,unsigned numTokens,CXTranslationUnit TU,SourceRange RegionOfInterest)6848 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
6849 CXTranslationUnit TU, SourceRange RegionOfInterest)
6850 : Tokens(tokens), Cursors(cursors),
6851 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
6852 AnnotateVis(TU,
6853 AnnotateTokensVisitor, this,
6854 /*VisitPreprocessorLast=*/true,
6855 /*VisitIncludedEntities=*/false,
6856 RegionOfInterest,
6857 /*VisitDeclsOnly=*/false,
6858 AnnotateTokensPostChildrenVisitor),
6859 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
6860 HasContextSensitiveKeywords(false) { }
6861
VisitChildren(CXCursor C)6862 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6863 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
6864 bool IsIgnoredChildCursor(CXCursor cursor) const;
6865 PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
6866
6867 bool postVisitChildren(CXCursor cursor);
6868 void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
6869 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
6870
6871 void AnnotateTokens();
6872
6873 /// Determine whether the annotator saw any cursors that have
6874 /// context-sensitive keywords.
hasContextSensitiveKeywords() const6875 bool hasContextSensitiveKeywords() const {
6876 return HasContextSensitiveKeywords;
6877 }
6878
~AnnotateTokensWorker()6879 ~AnnotateTokensWorker() {
6880 assert(PostChildrenInfos.empty());
6881 }
6882 };
6883 }
6884
AnnotateTokens()6885 void AnnotateTokensWorker::AnnotateTokens() {
6886 // Walk the AST within the region of interest, annotating tokens
6887 // along the way.
6888 AnnotateVis.visitFileRegion();
6889 }
6890
IsIgnoredChildCursor(CXCursor cursor) const6891 bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
6892 if (PostChildrenInfos.empty())
6893 return false;
6894
6895 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
6896 if (ChildAction.cursor == cursor &&
6897 ChildAction.action == PostChildrenAction::Ignore) {
6898 return true;
6899 }
6900 }
6901
6902 return false;
6903 }
6904
GetSubscriptOrCallOperator(CXCursor Cursor)6905 const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
6906 if (!clang_isExpression(Cursor.kind))
6907 return nullptr;
6908
6909 const Expr *E = getCursorExpr(Cursor);
6910 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
6911 const OverloadedOperatorKind Kind = OCE->getOperator();
6912 if (Kind == OO_Call || Kind == OO_Subscript)
6913 return OCE;
6914 }
6915
6916 return nullptr;
6917 }
6918
6919 AnnotateTokensWorker::PostChildrenActions
DetermineChildActions(CXCursor Cursor) const6920 AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
6921 PostChildrenActions actions;
6922
6923 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
6924 // visited before the arguments to the operator call. For the Call and
6925 // Subscript operator the range of this DeclRefExpr includes the whole call
6926 // expression, so that all tokens in that range would be mapped to the
6927 // operator function, including the tokens of the arguments. To avoid that,
6928 // ensure to visit this DeclRefExpr as last node.
6929 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
6930 const Expr *Callee = OCE->getCallee();
6931 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
6932 const Expr *SubExpr = ICE->getSubExpr();
6933 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
6934 const Decl *parentDecl = getCursorDecl(Cursor);
6935 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
6936
6937 // Visit the DeclRefExpr as last.
6938 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
6939 actions.push_back({cxChild, PostChildrenAction::Postpone});
6940
6941 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
6942 // wide range as the DeclRefExpr. We can skip visiting this entirely.
6943 cxChild = MakeCXCursor(ICE, parentDecl, TU);
6944 actions.push_back({cxChild, PostChildrenAction::Ignore});
6945 }
6946 }
6947 }
6948
6949 return actions;
6950 }
6951
updateCursorAnnotation(CXCursor & Cursor,const CXCursor & updateC)6952 static inline void updateCursorAnnotation(CXCursor &Cursor,
6953 const CXCursor &updateC) {
6954 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
6955 return;
6956 Cursor = updateC;
6957 }
6958
6959 /// It annotates and advances tokens with a cursor until the comparison
6960 //// between the cursor location and the source range is the same as
6961 /// \arg compResult.
6962 ///
6963 /// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6964 /// Pass RangeOverlap to annotate tokens inside a range.
annotateAndAdvanceTokens(CXCursor updateC,RangeComparisonResult compResult,SourceRange range)6965 void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6966 RangeComparisonResult compResult,
6967 SourceRange range) {
6968 while (MoreTokens()) {
6969 const unsigned I = NextToken();
6970 if (isFunctionMacroToken(I))
6971 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
6972 return;
6973
6974 SourceLocation TokLoc = GetTokenLoc(I);
6975 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
6976 updateCursorAnnotation(Cursors[I], updateC);
6977 AdvanceToken();
6978 continue;
6979 }
6980 break;
6981 }
6982 }
6983
6984 /// Special annotation handling for macro argument tokens.
6985 /// \returns true if it advanced beyond all macro tokens, false otherwise.
annotateAndAdvanceFunctionMacroTokens(CXCursor updateC,RangeComparisonResult compResult,SourceRange range)6986 bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
6987 CXCursor updateC,
6988 RangeComparisonResult compResult,
6989 SourceRange range) {
6990 assert(MoreTokens());
6991 assert(isFunctionMacroToken(NextToken()) &&
6992 "Should be called only for macro arg tokens");
6993
6994 // This works differently than annotateAndAdvanceTokens; because expanded
6995 // macro arguments can have arbitrary translation-unit source order, we do not
6996 // advance the token index one by one until a token fails the range test.
6997 // We only advance once past all of the macro arg tokens if all of them
6998 // pass the range test. If one of them fails we keep the token index pointing
6999 // at the start of the macro arg tokens so that the failing token will be
7000 // annotated by a subsequent annotation try.
7001
7002 bool atLeastOneCompFail = false;
7003
7004 unsigned I = NextToken();
7005 for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7006 SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7007 if (TokLoc.isFileID())
7008 continue; // not macro arg token, it's parens or comma.
7009 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
7010 if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7011 Cursors[I] = updateC;
7012 } else
7013 atLeastOneCompFail = true;
7014 }
7015
7016 if (atLeastOneCompFail)
7017 return false;
7018
7019 TokIdx = I; // All of the tokens were handled, advance beyond all of them.
7020 return true;
7021 }
7022
7023 enum CXChildVisitResult
Visit(CXCursor cursor,CXCursor parent)7024 AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
7025 SourceRange cursorRange = getRawCursorExtent(cursor);
7026 if (cursorRange.isInvalid())
7027 return CXChildVisit_Recurse;
7028
7029 if (IsIgnoredChildCursor(cursor))
7030 return CXChildVisit_Continue;
7031
7032 if (!HasContextSensitiveKeywords) {
7033 // Objective-C properties can have context-sensitive keywords.
7034 if (cursor.kind == CXCursor_ObjCPropertyDecl) {
7035 if (const ObjCPropertyDecl *Property
7036 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7037 HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7038 }
7039 // Objective-C methods can have context-sensitive keywords.
7040 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7041 cursor.kind == CXCursor_ObjCClassMethodDecl) {
7042 if (const ObjCMethodDecl *Method
7043 = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7044 if (Method->getObjCDeclQualifier())
7045 HasContextSensitiveKeywords = true;
7046 else {
7047 for (const auto *P : Method->parameters()) {
7048 if (P->getObjCDeclQualifier()) {
7049 HasContextSensitiveKeywords = true;
7050 break;
7051 }
7052 }
7053 }
7054 }
7055 }
7056 // C++ methods can have context-sensitive keywords.
7057 else if (cursor.kind == CXCursor_CXXMethod) {
7058 if (const CXXMethodDecl *Method
7059 = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7060 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7061 HasContextSensitiveKeywords = true;
7062 }
7063 }
7064 // C++ classes can have context-sensitive keywords.
7065 else if (cursor.kind == CXCursor_StructDecl ||
7066 cursor.kind == CXCursor_ClassDecl ||
7067 cursor.kind == CXCursor_ClassTemplate ||
7068 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
7069 if (const Decl *D = getCursorDecl(cursor))
7070 if (D->hasAttr<FinalAttr>())
7071 HasContextSensitiveKeywords = true;
7072 }
7073 }
7074
7075 // Don't override a property annotation with its getter/setter method.
7076 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7077 parent.kind == CXCursor_ObjCPropertyDecl)
7078 return CXChildVisit_Continue;
7079
7080 if (clang_isPreprocessing(cursor.kind)) {
7081 // Items in the preprocessing record are kept separate from items in
7082 // declarations, so we keep a separate token index.
7083 unsigned SavedTokIdx = TokIdx;
7084 TokIdx = PreprocessingTokIdx;
7085
7086 // Skip tokens up until we catch up to the beginning of the preprocessing
7087 // entry.
7088 while (MoreTokens()) {
7089 const unsigned I = NextToken();
7090 SourceLocation TokLoc = GetTokenLoc(I);
7091 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7092 case RangeBefore:
7093 AdvanceToken();
7094 continue;
7095 case RangeAfter:
7096 case RangeOverlap:
7097 break;
7098 }
7099 break;
7100 }
7101
7102 // Look at all of the tokens within this range.
7103 while (MoreTokens()) {
7104 const unsigned I = NextToken();
7105 SourceLocation TokLoc = GetTokenLoc(I);
7106 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
7107 case RangeBefore:
7108 llvm_unreachable("Infeasible");
7109 case RangeAfter:
7110 break;
7111 case RangeOverlap:
7112 // For macro expansions, just note where the beginning of the macro
7113 // expansion occurs.
7114 if (cursor.kind == CXCursor_MacroExpansion) {
7115 if (TokLoc == cursorRange.getBegin())
7116 Cursors[I] = cursor;
7117 AdvanceToken();
7118 break;
7119 }
7120 // We may have already annotated macro names inside macro definitions.
7121 if (Cursors[I].kind != CXCursor_MacroExpansion)
7122 Cursors[I] = cursor;
7123 AdvanceToken();
7124 continue;
7125 }
7126 break;
7127 }
7128
7129 // Save the preprocessing token index; restore the non-preprocessing
7130 // token index.
7131 PreprocessingTokIdx = TokIdx;
7132 TokIdx = SavedTokIdx;
7133 return CXChildVisit_Recurse;
7134 }
7135
7136 if (cursorRange.isInvalid())
7137 return CXChildVisit_Continue;
7138
7139 unsigned BeforeReachingCursorIdx = NextToken();
7140 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
7141 const enum CXCursorKind K = clang_getCursorKind(parent);
7142 const CXCursor updateC =
7143 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7144 // Attributes are annotated out-of-order, skip tokens until we reach it.
7145 clang_isAttribute(cursor.kind))
7146 ? clang_getNullCursor() : parent;
7147
7148 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
7149
7150 // Avoid having the cursor of an expression "overwrite" the annotation of the
7151 // variable declaration that it belongs to.
7152 // This can happen for C++ constructor expressions whose range generally
7153 // include the variable declaration, e.g.:
7154 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
7155 if (clang_isExpression(cursorK) && MoreTokens()) {
7156 const Expr *E = getCursorExpr(cursor);
7157 if (const Decl *D = getCursorDecl(cursor)) {
7158 const unsigned I = NextToken();
7159 if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7160 E->getBeginLoc() == D->getLocation() &&
7161 E->getBeginLoc() == GetTokenLoc(I)) {
7162 updateCursorAnnotation(Cursors[I], updateC);
7163 AdvanceToken();
7164 }
7165 }
7166 }
7167
7168 // Before recursing into the children keep some state that we are going
7169 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7170 // extra work after the child nodes are visited.
7171 // Note that we don't call VisitChildren here to avoid traversing statements
7172 // code-recursively which can blow the stack.
7173
7174 PostChildrenInfo Info;
7175 Info.Cursor = cursor;
7176 Info.CursorRange = cursorRange;
7177 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
7178 Info.BeforeChildrenTokenIdx = NextToken();
7179 Info.ChildActions = DetermineChildActions(cursor);
7180 PostChildrenInfos.push_back(Info);
7181
7182 return CXChildVisit_Recurse;
7183 }
7184
postVisitChildren(CXCursor cursor)7185 bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7186 if (PostChildrenInfos.empty())
7187 return false;
7188 const PostChildrenInfo &Info = PostChildrenInfos.back();
7189 if (!clang_equalCursors(Info.Cursor, cursor))
7190 return false;
7191
7192 HandlePostPonedChildCursors(Info);
7193
7194 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7195 const unsigned AfterChildren = NextToken();
7196 SourceRange cursorRange = Info.CursorRange;
7197
7198 // Scan the tokens that are at the end of the cursor, but are not captured
7199 // but the child cursors.
7200 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
7201
7202 // Scan the tokens that are at the beginning of the cursor, but are not
7203 // capture by the child cursors.
7204 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
7205 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7206 break;
7207
7208 Cursors[I] = cursor;
7209 }
7210
7211 // Attributes are annotated out-of-order, rewind TokIdx to when we first
7212 // encountered the attribute cursor.
7213 if (clang_isAttribute(cursor.kind))
7214 TokIdx = Info.BeforeReachingCursorIdx;
7215
7216 PostChildrenInfos.pop_back();
7217 return false;
7218 }
7219
HandlePostPonedChildCursors(const PostChildrenInfo & Info)7220 void AnnotateTokensWorker::HandlePostPonedChildCursors(
7221 const PostChildrenInfo &Info) {
7222 for (const auto &ChildAction : Info.ChildActions) {
7223 if (ChildAction.action == PostChildrenAction::Postpone) {
7224 HandlePostPonedChildCursor(ChildAction.cursor,
7225 Info.BeforeChildrenTokenIdx);
7226 }
7227 }
7228 }
7229
HandlePostPonedChildCursor(CXCursor Cursor,unsigned StartTokenIndex)7230 void AnnotateTokensWorker::HandlePostPonedChildCursor(
7231 CXCursor Cursor, unsigned StartTokenIndex) {
7232 const auto flags = CXNameRange_WantQualifier | CXNameRange_WantQualifier;
7233 unsigned I = StartTokenIndex;
7234
7235 // The bracket tokens of a Call or Subscript operator are mapped to
7236 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7237 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7238 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
7239 const CXSourceRange CXRefNameRange =
7240 clang_getCursorReferenceNameRange(Cursor, flags, RefNameRangeNr);
7241 if (clang_Range_isNull(CXRefNameRange))
7242 break; // All ranges handled.
7243
7244 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7245 while (I < NumTokens) {
7246 const SourceLocation TokenLocation = GetTokenLoc(I);
7247 if (!TokenLocation.isValid())
7248 break;
7249
7250 // Adapt the end range, because LocationCompare() reports
7251 // RangeOverlap even for the not-inclusive end location.
7252 const SourceLocation fixedEnd =
7253 RefNameRange.getEnd().getLocWithOffset(-1);
7254 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7255
7256 const RangeComparisonResult ComparisonResult =
7257 LocationCompare(SrcMgr, TokenLocation, RefNameRange);
7258
7259 if (ComparisonResult == RangeOverlap) {
7260 Cursors[I++] = Cursor;
7261 } else if (ComparisonResult == RangeBefore) {
7262 ++I; // Not relevant token, check next one.
7263 } else if (ComparisonResult == RangeAfter) {
7264 break; // All tokens updated for current range, check next.
7265 }
7266 }
7267 }
7268 }
7269
AnnotateTokensVisitor(CXCursor cursor,CXCursor parent,CXClientData client_data)7270 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7271 CXCursor parent,
7272 CXClientData client_data) {
7273 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
7274 }
7275
AnnotateTokensPostChildrenVisitor(CXCursor cursor,CXClientData client_data)7276 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7277 CXClientData client_data) {
7278 return static_cast<AnnotateTokensWorker*>(client_data)->
7279 postVisitChildren(cursor);
7280 }
7281
7282 namespace {
7283
7284 /// Uses the macro expansions in the preprocessing record to find
7285 /// and mark tokens that are macro arguments. This info is used by the
7286 /// AnnotateTokensWorker.
7287 class MarkMacroArgTokensVisitor {
7288 SourceManager &SM;
7289 CXToken *Tokens;
7290 unsigned NumTokens;
7291 unsigned CurIdx;
7292
7293 public:
MarkMacroArgTokensVisitor(SourceManager & SM,CXToken * tokens,unsigned numTokens)7294 MarkMacroArgTokensVisitor(SourceManager &SM,
7295 CXToken *tokens, unsigned numTokens)
7296 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7297
visit(CXCursor cursor,CXCursor parent)7298 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
7299 if (cursor.kind != CXCursor_MacroExpansion)
7300 return CXChildVisit_Continue;
7301
7302 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
7303 if (macroRange.getBegin() == macroRange.getEnd())
7304 return CXChildVisit_Continue; // it's not a function macro.
7305
7306 for (; CurIdx < NumTokens; ++CurIdx) {
7307 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7308 macroRange.getBegin()))
7309 break;
7310 }
7311
7312 if (CurIdx == NumTokens)
7313 return CXChildVisit_Break;
7314
7315 for (; CurIdx < NumTokens; ++CurIdx) {
7316 SourceLocation tokLoc = getTokenLoc(CurIdx);
7317 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
7318 break;
7319
7320 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
7321 }
7322
7323 if (CurIdx == NumTokens)
7324 return CXChildVisit_Break;
7325
7326 return CXChildVisit_Continue;
7327 }
7328
7329 private:
getTok(unsigned Idx)7330 CXToken &getTok(unsigned Idx) {
7331 assert(Idx < NumTokens);
7332 return Tokens[Idx];
7333 }
getTok(unsigned Idx) const7334 const CXToken &getTok(unsigned Idx) const {
7335 assert(Idx < NumTokens);
7336 return Tokens[Idx];
7337 }
7338
getTokenLoc(unsigned tokI)7339 SourceLocation getTokenLoc(unsigned tokI) {
7340 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
7341 }
7342
setFunctionMacroTokenLoc(unsigned tokI,SourceLocation loc)7343 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
7344 // The third field is reserved and currently not used. Use it here
7345 // to mark macro arg expanded tokens with their expanded locations.
7346 getTok(tokI).int_data[3] = loc.getRawEncoding();
7347 }
7348 };
7349
7350 } // end anonymous namespace
7351
7352 static CXChildVisitResult
MarkMacroArgTokensVisitorDelegate(CXCursor cursor,CXCursor parent,CXClientData client_data)7353 MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
7354 CXClientData client_data) {
7355 return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7356 parent);
7357 }
7358
7359 /// Used by \c annotatePreprocessorTokens.
7360 /// \returns true if lexing was finished, false otherwise.
lexNext(Lexer & Lex,Token & Tok,unsigned & NextIdx,unsigned NumTokens)7361 static bool lexNext(Lexer &Lex, Token &Tok,
7362 unsigned &NextIdx, unsigned NumTokens) {
7363 if (NextIdx >= NumTokens)
7364 return true;
7365
7366 ++NextIdx;
7367 Lex.LexFromRawLexer(Tok);
7368 return Tok.is(tok::eof);
7369 }
7370
annotatePreprocessorTokens(CXTranslationUnit TU,SourceRange RegionOfInterest,CXCursor * Cursors,CXToken * Tokens,unsigned NumTokens)7371 static void annotatePreprocessorTokens(CXTranslationUnit TU,
7372 SourceRange RegionOfInterest,
7373 CXCursor *Cursors,
7374 CXToken *Tokens,
7375 unsigned NumTokens) {
7376 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
7377
7378 Preprocessor &PP = CXXUnit->getPreprocessor();
7379 SourceManager &SourceMgr = CXXUnit->getSourceManager();
7380 std::pair<FileID, unsigned> BeginLocInfo
7381 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
7382 std::pair<FileID, unsigned> EndLocInfo
7383 = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
7384
7385 if (BeginLocInfo.first != EndLocInfo.first)
7386 return;
7387
7388 StringRef Buffer;
7389 bool Invalid = false;
7390 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7391 if (Buffer.empty() || Invalid)
7392 return;
7393
7394 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7395 CXXUnit->getASTContext().getLangOpts(),
7396 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7397 Buffer.end());
7398 Lex.SetCommentRetentionState(true);
7399
7400 unsigned NextIdx = 0;
7401 // Lex tokens in raw mode until we hit the end of the range, to avoid
7402 // entering #includes or expanding macros.
7403 while (true) {
7404 Token Tok;
7405 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7406 break;
7407 unsigned TokIdx = NextIdx-1;
7408 assert(Tok.getLocation() ==
7409 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
7410
7411 reprocess:
7412 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
7413 // We have found a preprocessing directive. Annotate the tokens
7414 // appropriately.
7415 //
7416 // FIXME: Some simple tests here could identify macro definitions and
7417 // #undefs, to provide specific cursor kinds for those.
7418
7419 SourceLocation BeginLoc = Tok.getLocation();
7420 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7421 break;
7422
7423 MacroInfo *MI = nullptr;
7424 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
7425 if (lexNext(Lex, Tok, NextIdx, NumTokens))
7426 break;
7427
7428 if (Tok.is(tok::raw_identifier)) {
7429 IdentifierInfo &II =
7430 PP.getIdentifierTable().get(Tok.getRawIdentifier());
7431 SourceLocation MappedTokLoc =
7432 CXXUnit->mapLocationToPreamble(Tok.getLocation());
7433 MI = getMacroInfo(II, MappedTokLoc, TU);
7434 }
7435 }
7436
7437 bool finished = false;
7438 do {
7439 if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
7440 finished = true;
7441 break;
7442 }
7443 // If we are in a macro definition, check if the token was ever a
7444 // macro name and annotate it if that's the case.
7445 if (MI) {
7446 SourceLocation SaveLoc = Tok.getLocation();
7447 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
7448 MacroDefinitionRecord *MacroDef =
7449 checkForMacroInMacroDefinition(MI, Tok, TU);
7450 Tok.setLocation(SaveLoc);
7451 if (MacroDef)
7452 Cursors[NextIdx - 1] =
7453 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
7454 }
7455 } while (!Tok.isAtStartOfLine());
7456
7457 unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7458 assert(TokIdx <= LastIdx);
7459 SourceLocation EndLoc =
7460 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7461 CXCursor Cursor =
7462 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
7463
7464 for (; TokIdx <= LastIdx; ++TokIdx)
7465 updateCursorAnnotation(Cursors[TokIdx], Cursor);
7466
7467 if (finished)
7468 break;
7469 goto reprocess;
7470 }
7471 }
7472 }
7473
7474 // This gets run a separate thread to avoid stack blowout.
clang_annotateTokensImpl(CXTranslationUnit TU,ASTUnit * CXXUnit,CXToken * Tokens,unsigned NumTokens,CXCursor * Cursors)7475 static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
7476 CXToken *Tokens, unsigned NumTokens,
7477 CXCursor *Cursors) {
7478 CIndexer *CXXIdx = TU->CIdx;
7479 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7480 setThreadBackgroundPriority();
7481
7482 // Determine the region of interest, which contains all of the tokens.
7483 SourceRange RegionOfInterest;
7484 RegionOfInterest.setBegin(
7485 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
7486 RegionOfInterest.setEnd(
7487 cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7488 Tokens[NumTokens-1])));
7489
7490 // Relex the tokens within the source range to look for preprocessing
7491 // directives.
7492 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
7493
7494 // If begin location points inside a macro argument, set it to the expansion
7495 // location so we can have the full context when annotating semantically.
7496 {
7497 SourceManager &SM = CXXUnit->getSourceManager();
7498 SourceLocation Loc =
7499 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7500 if (Loc.isMacroID())
7501 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7502 }
7503
7504 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7505 // Search and mark tokens that are macro argument expansions.
7506 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7507 Tokens, NumTokens);
7508 CursorVisitor MacroArgMarker(TU,
7509 MarkMacroArgTokensVisitorDelegate, &Visitor,
7510 /*VisitPreprocessorLast=*/true,
7511 /*VisitIncludedEntities=*/false,
7512 RegionOfInterest);
7513 MacroArgMarker.visitPreprocessedEntitiesInRegion();
7514 }
7515
7516 // Annotate all of the source locations in the region of interest that map to
7517 // a specific cursor.
7518 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
7519
7520 // FIXME: We use a ridiculous stack size here because the data-recursion
7521 // algorithm uses a large stack frame than the non-data recursive version,
7522 // and AnnotationTokensWorker currently transforms the data-recursion
7523 // algorithm back into a traditional recursion by explicitly calling
7524 // VisitChildren(). We will need to remove this explicit recursive call.
7525 W.AnnotateTokens();
7526
7527 // If we ran into any entities that involve context-sensitive keywords,
7528 // take another pass through the tokens to mark them as such.
7529 if (W.hasContextSensitiveKeywords()) {
7530 for (unsigned I = 0; I != NumTokens; ++I) {
7531 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7532 continue;
7533
7534 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7535 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7536 if (const ObjCPropertyDecl *Property
7537 = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7538 if (Property->getPropertyAttributesAsWritten() != 0 &&
7539 llvm::StringSwitch<bool>(II->getName())
7540 .Case("readonly", true)
7541 .Case("assign", true)
7542 .Case("unsafe_unretained", true)
7543 .Case("readwrite", true)
7544 .Case("retain", true)
7545 .Case("copy", true)
7546 .Case("nonatomic", true)
7547 .Case("atomic", true)
7548 .Case("getter", true)
7549 .Case("setter", true)
7550 .Case("strong", true)
7551 .Case("weak", true)
7552 .Case("class", true)
7553 .Default(false))
7554 Tokens[I].int_data[0] = CXToken_Keyword;
7555 }
7556 continue;
7557 }
7558
7559 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7560 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7561 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7562 if (llvm::StringSwitch<bool>(II->getName())
7563 .Case("in", true)
7564 .Case("out", true)
7565 .Case("inout", true)
7566 .Case("oneway", true)
7567 .Case("bycopy", true)
7568 .Case("byref", true)
7569 .Default(false))
7570 Tokens[I].int_data[0] = CXToken_Keyword;
7571 continue;
7572 }
7573
7574 if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7575 Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7576 Tokens[I].int_data[0] = CXToken_Keyword;
7577 continue;
7578 }
7579 }
7580 }
7581 }
7582
clang_annotateTokens(CXTranslationUnit TU,CXToken * Tokens,unsigned NumTokens,CXCursor * Cursors)7583 void clang_annotateTokens(CXTranslationUnit TU,
7584 CXToken *Tokens, unsigned NumTokens,
7585 CXCursor *Cursors) {
7586 if (isNotUsableTU(TU)) {
7587 LOG_BAD_TU(TU);
7588 return;
7589 }
7590 if (NumTokens == 0 || !Tokens || !Cursors) {
7591 LOG_FUNC_SECTION { *Log << "<null input>"; }
7592 return;
7593 }
7594
7595 LOG_FUNC_SECTION {
7596 *Log << TU << ' ';
7597 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
7598 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens-1]);
7599 *Log << clang_getRange(bloc, eloc);
7600 }
7601
7602 // Any token we don't specifically annotate will have a NULL cursor.
7603 CXCursor C = clang_getNullCursor();
7604 for (unsigned I = 0; I != NumTokens; ++I)
7605 Cursors[I] = C;
7606
7607 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
7608 if (!CXXUnit)
7609 return;
7610
7611 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
7612
7613 auto AnnotateTokensImpl = [=]() {
7614 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
7615 };
7616 llvm::CrashRecoveryContext CRC;
7617 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
7618 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
7619 }
7620 }
7621
7622 //===----------------------------------------------------------------------===//
7623 // Operations for querying linkage of a cursor.
7624 //===----------------------------------------------------------------------===//
7625
clang_getCursorLinkage(CXCursor cursor)7626 CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7627 if (!clang_isDeclaration(cursor.kind))
7628 return CXLinkage_Invalid;
7629
7630 const Decl *D = cxcursor::getCursorDecl(cursor);
7631 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7632 switch (ND->getLinkageInternal()) {
7633 case NoLinkage:
7634 case VisibleNoLinkage: return CXLinkage_NoLinkage;
7635 case ModuleInternalLinkage:
7636 case InternalLinkage: return CXLinkage_Internal;
7637 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
7638 case ModuleLinkage:
7639 case ExternalLinkage: return CXLinkage_External;
7640 };
7641
7642 return CXLinkage_Invalid;
7643 }
7644
7645 //===----------------------------------------------------------------------===//
7646 // Operations for querying visibility of a cursor.
7647 //===----------------------------------------------------------------------===//
7648
clang_getCursorVisibility(CXCursor cursor)7649 CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7650 if (!clang_isDeclaration(cursor.kind))
7651 return CXVisibility_Invalid;
7652
7653 const Decl *D = cxcursor::getCursorDecl(cursor);
7654 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7655 switch (ND->getVisibility()) {
7656 case HiddenVisibility: return CXVisibility_Hidden;
7657 case ProtectedVisibility: return CXVisibility_Protected;
7658 case DefaultVisibility: return CXVisibility_Default;
7659 };
7660
7661 return CXVisibility_Invalid;
7662 }
7663
7664 //===----------------------------------------------------------------------===//
7665 // Operations for querying language of a cursor.
7666 //===----------------------------------------------------------------------===//
7667
getDeclLanguage(const Decl * D)7668 static CXLanguageKind getDeclLanguage(const Decl *D) {
7669 if (!D)
7670 return CXLanguage_C;
7671
7672 switch (D->getKind()) {
7673 default:
7674 break;
7675 case Decl::ImplicitParam:
7676 case Decl::ObjCAtDefsField:
7677 case Decl::ObjCCategory:
7678 case Decl::ObjCCategoryImpl:
7679 case Decl::ObjCCompatibleAlias:
7680 case Decl::ObjCImplementation:
7681 case Decl::ObjCInterface:
7682 case Decl::ObjCIvar:
7683 case Decl::ObjCMethod:
7684 case Decl::ObjCProperty:
7685 case Decl::ObjCPropertyImpl:
7686 case Decl::ObjCProtocol:
7687 case Decl::ObjCTypeParam:
7688 return CXLanguage_ObjC;
7689 case Decl::CXXConstructor:
7690 case Decl::CXXConversion:
7691 case Decl::CXXDestructor:
7692 case Decl::CXXMethod:
7693 case Decl::CXXRecord:
7694 case Decl::ClassTemplate:
7695 case Decl::ClassTemplatePartialSpecialization:
7696 case Decl::ClassTemplateSpecialization:
7697 case Decl::Friend:
7698 case Decl::FriendTemplate:
7699 case Decl::FunctionTemplate:
7700 case Decl::LinkageSpec:
7701 case Decl::Namespace:
7702 case Decl::NamespaceAlias:
7703 case Decl::NonTypeTemplateParm:
7704 case Decl::StaticAssert:
7705 case Decl::TemplateTemplateParm:
7706 case Decl::TemplateTypeParm:
7707 case Decl::UnresolvedUsingTypename:
7708 case Decl::UnresolvedUsingValue:
7709 case Decl::Using:
7710 case Decl::UsingDirective:
7711 case Decl::UsingShadow:
7712 return CXLanguage_CPlusPlus;
7713 }
7714
7715 return CXLanguage_C;
7716 }
7717
getCursorAvailabilityForDecl(const Decl * D)7718 static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7719 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
7720 return CXAvailability_NotAvailable;
7721
7722 switch (D->getAvailability()) {
7723 case AR_Available:
7724 case AR_NotYetIntroduced:
7725 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7726 return getCursorAvailabilityForDecl(
7727 cast<Decl>(EnumConst->getDeclContext()));
7728 return CXAvailability_Available;
7729
7730 case AR_Deprecated:
7731 return CXAvailability_Deprecated;
7732
7733 case AR_Unavailable:
7734 return CXAvailability_NotAvailable;
7735 }
7736
7737 llvm_unreachable("Unknown availability kind!");
7738 }
7739
clang_getCursorAvailability(CXCursor cursor)7740 enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7741 if (clang_isDeclaration(cursor.kind))
7742 if (const Decl *D = cxcursor::getCursorDecl(cursor))
7743 return getCursorAvailabilityForDecl(D);
7744
7745 return CXAvailability_Available;
7746 }
7747
convertVersion(VersionTuple In)7748 static CXVersion convertVersion(VersionTuple In) {
7749 CXVersion Out = { -1, -1, -1 };
7750 if (In.empty())
7751 return Out;
7752
7753 Out.Major = In.getMajor();
7754
7755 Optional<unsigned> Minor = In.getMinor();
7756 if (Minor.hasValue())
7757 Out.Minor = *Minor;
7758 else
7759 return Out;
7760
7761 Optional<unsigned> Subminor = In.getSubminor();
7762 if (Subminor.hasValue())
7763 Out.Subminor = *Subminor;
7764
7765 return Out;
7766 }
7767
getCursorPlatformAvailabilityForDecl(const Decl * D,int * always_deprecated,CXString * deprecated_message,int * always_unavailable,CXString * unavailable_message,SmallVectorImpl<AvailabilityAttr * > & AvailabilityAttrs)7768 static void getCursorPlatformAvailabilityForDecl(
7769 const Decl *D, int *always_deprecated, CXString *deprecated_message,
7770 int *always_unavailable, CXString *unavailable_message,
7771 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
7772 bool HadAvailAttr = false;
7773 for (auto A : D->attrs()) {
7774 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
7775 HadAvailAttr = true;
7776 if (always_deprecated)
7777 *always_deprecated = 1;
7778 if (deprecated_message) {
7779 clang_disposeString(*deprecated_message);
7780 *deprecated_message = cxstring::createDup(Deprecated->getMessage());
7781 }
7782 continue;
7783 }
7784
7785 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
7786 HadAvailAttr = true;
7787 if (always_unavailable)
7788 *always_unavailable = 1;
7789 if (unavailable_message) {
7790 clang_disposeString(*unavailable_message);
7791 *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7792 }
7793 continue;
7794 }
7795
7796 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
7797 AvailabilityAttrs.push_back(Avail);
7798 HadAvailAttr = true;
7799 }
7800 }
7801
7802 if (!HadAvailAttr)
7803 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7804 return getCursorPlatformAvailabilityForDecl(
7805 cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7806 deprecated_message, always_unavailable, unavailable_message,
7807 AvailabilityAttrs);
7808
7809 if (AvailabilityAttrs.empty())
7810 return;
7811
7812 llvm::sort(AvailabilityAttrs,
7813 [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7814 return LHS->getPlatform()->getName() <
7815 RHS->getPlatform()->getName();
7816 });
7817 ASTContext &Ctx = D->getASTContext();
7818 auto It = std::unique(
7819 AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7820 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7821 if (LHS->getPlatform() != RHS->getPlatform())
7822 return false;
7823
7824 if (LHS->getIntroduced() == RHS->getIntroduced() &&
7825 LHS->getDeprecated() == RHS->getDeprecated() &&
7826 LHS->getObsoleted() == RHS->getObsoleted() &&
7827 LHS->getMessage() == RHS->getMessage() &&
7828 LHS->getReplacement() == RHS->getReplacement())
7829 return true;
7830
7831 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7832 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7833 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7834 return false;
7835
7836 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7837 LHS->setIntroduced(Ctx, RHS->getIntroduced());
7838
7839 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7840 LHS->setDeprecated(Ctx, RHS->getDeprecated());
7841 if (LHS->getMessage().empty())
7842 LHS->setMessage(Ctx, RHS->getMessage());
7843 if (LHS->getReplacement().empty())
7844 LHS->setReplacement(Ctx, RHS->getReplacement());
7845 }
7846
7847 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7848 LHS->setObsoleted(Ctx, RHS->getObsoleted());
7849 if (LHS->getMessage().empty())
7850 LHS->setMessage(Ctx, RHS->getMessage());
7851 if (LHS->getReplacement().empty())
7852 LHS->setReplacement(Ctx, RHS->getReplacement());
7853 }
7854
7855 return true;
7856 });
7857 AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
7858 }
7859
clang_getCursorPlatformAvailability(CXCursor cursor,int * always_deprecated,CXString * deprecated_message,int * always_unavailable,CXString * unavailable_message,CXPlatformAvailability * availability,int availability_size)7860 int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
7861 CXString *deprecated_message,
7862 int *always_unavailable,
7863 CXString *unavailable_message,
7864 CXPlatformAvailability *availability,
7865 int availability_size) {
7866 if (always_deprecated)
7867 *always_deprecated = 0;
7868 if (deprecated_message)
7869 *deprecated_message = cxstring::createEmpty();
7870 if (always_unavailable)
7871 *always_unavailable = 0;
7872 if (unavailable_message)
7873 *unavailable_message = cxstring::createEmpty();
7874
7875 if (!clang_isDeclaration(cursor.kind))
7876 return 0;
7877
7878 const Decl *D = cxcursor::getCursorDecl(cursor);
7879 if (!D)
7880 return 0;
7881
7882 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
7883 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7884 always_unavailable, unavailable_message,
7885 AvailabilityAttrs);
7886 for (const auto &Avail :
7887 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7888 .take_front(availability_size))) {
7889 availability[Avail.index()].Platform =
7890 cxstring::createDup(Avail.value()->getPlatform()->getName());
7891 availability[Avail.index()].Introduced =
7892 convertVersion(Avail.value()->getIntroduced());
7893 availability[Avail.index()].Deprecated =
7894 convertVersion(Avail.value()->getDeprecated());
7895 availability[Avail.index()].Obsoleted =
7896 convertVersion(Avail.value()->getObsoleted());
7897 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7898 availability[Avail.index()].Message =
7899 cxstring::createDup(Avail.value()->getMessage());
7900 }
7901
7902 return AvailabilityAttrs.size();
7903 }
7904
clang_disposeCXPlatformAvailability(CXPlatformAvailability * availability)7905 void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7906 clang_disposeString(availability->Platform);
7907 clang_disposeString(availability->Message);
7908 }
7909
clang_getCursorLanguage(CXCursor cursor)7910 CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7911 if (clang_isDeclaration(cursor.kind))
7912 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7913
7914 return CXLanguage_Invalid;
7915 }
7916
clang_getCursorTLSKind(CXCursor cursor)7917 CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7918 const Decl *D = cxcursor::getCursorDecl(cursor);
7919 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7920 switch (VD->getTLSKind()) {
7921 case VarDecl::TLS_None:
7922 return CXTLS_None;
7923 case VarDecl::TLS_Dynamic:
7924 return CXTLS_Dynamic;
7925 case VarDecl::TLS_Static:
7926 return CXTLS_Static;
7927 }
7928 }
7929
7930 return CXTLS_None;
7931 }
7932
7933 /// If the given cursor is the "templated" declaration
7934 /// describing a class or function template, return the class or
7935 /// function template.
maybeGetTemplateCursor(const Decl * D)7936 static const Decl *maybeGetTemplateCursor(const Decl *D) {
7937 if (!D)
7938 return nullptr;
7939
7940 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7941 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7942 return FunTmpl;
7943
7944 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
7945 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7946 return ClassTmpl;
7947
7948 return D;
7949 }
7950
7951
clang_Cursor_getStorageClass(CXCursor C)7952 enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7953 StorageClass sc = SC_None;
7954 const Decl *D = getCursorDecl(C);
7955 if (D) {
7956 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7957 sc = FD->getStorageClass();
7958 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7959 sc = VD->getStorageClass();
7960 } else {
7961 return CX_SC_Invalid;
7962 }
7963 } else {
7964 return CX_SC_Invalid;
7965 }
7966 switch (sc) {
7967 case SC_None:
7968 return CX_SC_None;
7969 case SC_Extern:
7970 return CX_SC_Extern;
7971 case SC_Static:
7972 return CX_SC_Static;
7973 case SC_PrivateExtern:
7974 return CX_SC_PrivateExtern;
7975 case SC_Auto:
7976 return CX_SC_Auto;
7977 case SC_Register:
7978 return CX_SC_Register;
7979 }
7980 llvm_unreachable("Unhandled storage class!");
7981 }
7982
clang_getCursorSemanticParent(CXCursor cursor)7983 CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
7984 if (clang_isDeclaration(cursor.kind)) {
7985 if (const Decl *D = getCursorDecl(cursor)) {
7986 const DeclContext *DC = D->getDeclContext();
7987 if (!DC)
7988 return clang_getNullCursor();
7989
7990 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
7991 getCursorTU(cursor));
7992 }
7993 }
7994
7995 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
7996 if (const Decl *D = getCursorDecl(cursor))
7997 return MakeCXCursor(D, getCursorTU(cursor));
7998 }
7999
8000 return clang_getNullCursor();
8001 }
8002
clang_getCursorLexicalParent(CXCursor cursor)8003 CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8004 if (clang_isDeclaration(cursor.kind)) {
8005 if (const Decl *D = getCursorDecl(cursor)) {
8006 const DeclContext *DC = D->getLexicalDeclContext();
8007 if (!DC)
8008 return clang_getNullCursor();
8009
8010 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
8011 getCursorTU(cursor));
8012 }
8013 }
8014
8015 // FIXME: Note that we can't easily compute the lexical context of a
8016 // statement or expression, so we return nothing.
8017 return clang_getNullCursor();
8018 }
8019
clang_getIncludedFile(CXCursor cursor)8020 CXFile clang_getIncludedFile(CXCursor cursor) {
8021 if (cursor.kind != CXCursor_InclusionDirective)
8022 return nullptr;
8023
8024 const InclusionDirective *ID = getCursorInclusionDirective(cursor);
8025 return const_cast<FileEntry *>(ID->getFile());
8026 }
8027
clang_Cursor_getObjCPropertyAttributes(CXCursor C,unsigned reserved)8028 unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
8029 if (C.kind != CXCursor_ObjCPropertyDecl)
8030 return CXObjCPropertyAttr_noattr;
8031
8032 unsigned Result = CXObjCPropertyAttr_noattr;
8033 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8034 ObjCPropertyDecl::PropertyAttributeKind Attr =
8035 PD->getPropertyAttributesAsWritten();
8036
8037 #define SET_CXOBJCPROP_ATTR(A) \
8038 if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8039 Result |= CXObjCPropertyAttr_##A
8040 SET_CXOBJCPROP_ATTR(readonly);
8041 SET_CXOBJCPROP_ATTR(getter);
8042 SET_CXOBJCPROP_ATTR(assign);
8043 SET_CXOBJCPROP_ATTR(readwrite);
8044 SET_CXOBJCPROP_ATTR(retain);
8045 SET_CXOBJCPROP_ATTR(copy);
8046 SET_CXOBJCPROP_ATTR(nonatomic);
8047 SET_CXOBJCPROP_ATTR(setter);
8048 SET_CXOBJCPROP_ATTR(atomic);
8049 SET_CXOBJCPROP_ATTR(weak);
8050 SET_CXOBJCPROP_ATTR(strong);
8051 SET_CXOBJCPROP_ATTR(unsafe_unretained);
8052 SET_CXOBJCPROP_ATTR(class);
8053 #undef SET_CXOBJCPROP_ATTR
8054
8055 return Result;
8056 }
8057
clang_Cursor_getObjCPropertyGetterName(CXCursor C)8058 CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8059 if (C.kind != CXCursor_ObjCPropertyDecl)
8060 return cxstring::createNull();
8061
8062 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8063 Selector sel = PD->getGetterName();
8064 if (sel.isNull())
8065 return cxstring::createNull();
8066
8067 return cxstring::createDup(sel.getAsString());
8068 }
8069
clang_Cursor_getObjCPropertySetterName(CXCursor C)8070 CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8071 if (C.kind != CXCursor_ObjCPropertyDecl)
8072 return cxstring::createNull();
8073
8074 const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8075 Selector sel = PD->getSetterName();
8076 if (sel.isNull())
8077 return cxstring::createNull();
8078
8079 return cxstring::createDup(sel.getAsString());
8080 }
8081
clang_Cursor_getObjCDeclQualifiers(CXCursor C)8082 unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8083 if (!clang_isDeclaration(C.kind))
8084 return CXObjCDeclQualifier_None;
8085
8086 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8087 const Decl *D = getCursorDecl(C);
8088 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8089 QT = MD->getObjCDeclQualifier();
8090 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8091 QT = PD->getObjCDeclQualifier();
8092 if (QT == Decl::OBJC_TQ_None)
8093 return CXObjCDeclQualifier_None;
8094
8095 unsigned Result = CXObjCDeclQualifier_None;
8096 if (QT & Decl::OBJC_TQ_In) Result |= CXObjCDeclQualifier_In;
8097 if (QT & Decl::OBJC_TQ_Inout) Result |= CXObjCDeclQualifier_Inout;
8098 if (QT & Decl::OBJC_TQ_Out) Result |= CXObjCDeclQualifier_Out;
8099 if (QT & Decl::OBJC_TQ_Bycopy) Result |= CXObjCDeclQualifier_Bycopy;
8100 if (QT & Decl::OBJC_TQ_Byref) Result |= CXObjCDeclQualifier_Byref;
8101 if (QT & Decl::OBJC_TQ_Oneway) Result |= CXObjCDeclQualifier_Oneway;
8102
8103 return Result;
8104 }
8105
clang_Cursor_isObjCOptional(CXCursor C)8106 unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8107 if (!clang_isDeclaration(C.kind))
8108 return 0;
8109
8110 const Decl *D = getCursorDecl(C);
8111 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8112 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8113 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8114 return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8115
8116 return 0;
8117 }
8118
clang_Cursor_isVariadic(CXCursor C)8119 unsigned clang_Cursor_isVariadic(CXCursor C) {
8120 if (!clang_isDeclaration(C.kind))
8121 return 0;
8122
8123 const Decl *D = getCursorDecl(C);
8124 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8125 return FD->isVariadic();
8126 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8127 return MD->isVariadic();
8128
8129 return 0;
8130 }
8131
clang_Cursor_isExternalSymbol(CXCursor C,CXString * language,CXString * definedIn,unsigned * isGenerated)8132 unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8133 CXString *language, CXString *definedIn,
8134 unsigned *isGenerated) {
8135 if (!clang_isDeclaration(C.kind))
8136 return 0;
8137
8138 const Decl *D = getCursorDecl(C);
8139
8140 if (auto *attr = D->getExternalSourceSymbolAttr()) {
8141 if (language)
8142 *language = cxstring::createDup(attr->getLanguage());
8143 if (definedIn)
8144 *definedIn = cxstring::createDup(attr->getDefinedIn());
8145 if (isGenerated)
8146 *isGenerated = attr->getGeneratedDeclaration();
8147 return 1;
8148 }
8149 return 0;
8150 }
8151
clang_Cursor_getCommentRange(CXCursor C)8152 CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8153 if (!clang_isDeclaration(C.kind))
8154 return clang_getNullRange();
8155
8156 const Decl *D = getCursorDecl(C);
8157 ASTContext &Context = getCursorContext(C);
8158 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8159 if (!RC)
8160 return clang_getNullRange();
8161
8162 return cxloc::translateSourceRange(Context, RC->getSourceRange());
8163 }
8164
clang_Cursor_getRawCommentText(CXCursor C)8165 CXString clang_Cursor_getRawCommentText(CXCursor C) {
8166 if (!clang_isDeclaration(C.kind))
8167 return cxstring::createNull();
8168
8169 const Decl *D = getCursorDecl(C);
8170 ASTContext &Context = getCursorContext(C);
8171 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8172 StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8173 StringRef();
8174
8175 // Don't duplicate the string because RawText points directly into source
8176 // code.
8177 return cxstring::createRef(RawText);
8178 }
8179
clang_Cursor_getBriefCommentText(CXCursor C)8180 CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8181 if (!clang_isDeclaration(C.kind))
8182 return cxstring::createNull();
8183
8184 const Decl *D = getCursorDecl(C);
8185 const ASTContext &Context = getCursorContext(C);
8186 const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8187
8188 if (RC) {
8189 StringRef BriefText = RC->getBriefText(Context);
8190
8191 // Don't duplicate the string because RawComment ensures that this memory
8192 // will not go away.
8193 return cxstring::createRef(BriefText);
8194 }
8195
8196 return cxstring::createNull();
8197 }
8198
clang_Cursor_getModule(CXCursor C)8199 CXModule clang_Cursor_getModule(CXCursor C) {
8200 if (C.kind == CXCursor_ModuleImportDecl) {
8201 if (const ImportDecl *ImportD =
8202 dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
8203 return ImportD->getImportedModule();
8204 }
8205
8206 return nullptr;
8207 }
8208
clang_getModuleForFile(CXTranslationUnit TU,CXFile File)8209 CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
8210 if (isNotUsableTU(TU)) {
8211 LOG_BAD_TU(TU);
8212 return nullptr;
8213 }
8214 if (!File)
8215 return nullptr;
8216 FileEntry *FE = static_cast<FileEntry *>(File);
8217
8218 ASTUnit &Unit = *cxtu::getASTUnit(TU);
8219 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8220 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8221
8222 return Header.getModule();
8223 }
8224
clang_Module_getASTFile(CXModule CXMod)8225 CXFile clang_Module_getASTFile(CXModule CXMod) {
8226 if (!CXMod)
8227 return nullptr;
8228 Module *Mod = static_cast<Module*>(CXMod);
8229 return const_cast<FileEntry *>(Mod->getASTFile());
8230 }
8231
clang_Module_getParent(CXModule CXMod)8232 CXModule clang_Module_getParent(CXModule CXMod) {
8233 if (!CXMod)
8234 return nullptr;
8235 Module *Mod = static_cast<Module*>(CXMod);
8236 return Mod->Parent;
8237 }
8238
clang_Module_getName(CXModule CXMod)8239 CXString clang_Module_getName(CXModule CXMod) {
8240 if (!CXMod)
8241 return cxstring::createEmpty();
8242 Module *Mod = static_cast<Module*>(CXMod);
8243 return cxstring::createDup(Mod->Name);
8244 }
8245
clang_Module_getFullName(CXModule CXMod)8246 CXString clang_Module_getFullName(CXModule CXMod) {
8247 if (!CXMod)
8248 return cxstring::createEmpty();
8249 Module *Mod = static_cast<Module*>(CXMod);
8250 return cxstring::createDup(Mod->getFullModuleName());
8251 }
8252
clang_Module_isSystem(CXModule CXMod)8253 int clang_Module_isSystem(CXModule CXMod) {
8254 if (!CXMod)
8255 return 0;
8256 Module *Mod = static_cast<Module*>(CXMod);
8257 return Mod->IsSystem;
8258 }
8259
clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,CXModule CXMod)8260 unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8261 CXModule CXMod) {
8262 if (isNotUsableTU(TU)) {
8263 LOG_BAD_TU(TU);
8264 return 0;
8265 }
8266 if (!CXMod)
8267 return 0;
8268 Module *Mod = static_cast<Module*>(CXMod);
8269 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8270 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8271 return TopHeaders.size();
8272 }
8273
clang_Module_getTopLevelHeader(CXTranslationUnit TU,CXModule CXMod,unsigned Index)8274 CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8275 CXModule CXMod, unsigned Index) {
8276 if (isNotUsableTU(TU)) {
8277 LOG_BAD_TU(TU);
8278 return nullptr;
8279 }
8280 if (!CXMod)
8281 return nullptr;
8282 Module *Mod = static_cast<Module*>(CXMod);
8283 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8284
8285 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8286 if (Index < TopHeaders.size())
8287 return const_cast<FileEntry *>(TopHeaders[Index]);
8288
8289 return nullptr;
8290 }
8291
8292 //===----------------------------------------------------------------------===//
8293 // C++ AST instrospection.
8294 //===----------------------------------------------------------------------===//
8295
clang_CXXConstructor_isDefaultConstructor(CXCursor C)8296 unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8297 if (!clang_isDeclaration(C.kind))
8298 return 0;
8299
8300 const Decl *D = cxcursor::getCursorDecl(C);
8301 const CXXConstructorDecl *Constructor =
8302 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8303 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8304 }
8305
clang_CXXConstructor_isCopyConstructor(CXCursor C)8306 unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8307 if (!clang_isDeclaration(C.kind))
8308 return 0;
8309
8310 const Decl *D = cxcursor::getCursorDecl(C);
8311 const CXXConstructorDecl *Constructor =
8312 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8313 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8314 }
8315
clang_CXXConstructor_isMoveConstructor(CXCursor C)8316 unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8317 if (!clang_isDeclaration(C.kind))
8318 return 0;
8319
8320 const Decl *D = cxcursor::getCursorDecl(C);
8321 const CXXConstructorDecl *Constructor =
8322 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8323 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8324 }
8325
clang_CXXConstructor_isConvertingConstructor(CXCursor C)8326 unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8327 if (!clang_isDeclaration(C.kind))
8328 return 0;
8329
8330 const Decl *D = cxcursor::getCursorDecl(C);
8331 const CXXConstructorDecl *Constructor =
8332 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8333 // Passing 'false' excludes constructors marked 'explicit'.
8334 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8335 }
8336
clang_CXXField_isMutable(CXCursor C)8337 unsigned clang_CXXField_isMutable(CXCursor C) {
8338 if (!clang_isDeclaration(C.kind))
8339 return 0;
8340
8341 if (const auto D = cxcursor::getCursorDecl(C))
8342 if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8343 return FD->isMutable() ? 1 : 0;
8344 return 0;
8345 }
8346
clang_CXXMethod_isPureVirtual(CXCursor C)8347 unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8348 if (!clang_isDeclaration(C.kind))
8349 return 0;
8350
8351 const Decl *D = cxcursor::getCursorDecl(C);
8352 const CXXMethodDecl *Method =
8353 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8354 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8355 }
8356
clang_CXXMethod_isConst(CXCursor C)8357 unsigned clang_CXXMethod_isConst(CXCursor C) {
8358 if (!clang_isDeclaration(C.kind))
8359 return 0;
8360
8361 const Decl *D = cxcursor::getCursorDecl(C);
8362 const CXXMethodDecl *Method =
8363 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8364 return (Method && Method->getTypeQualifiers().hasConst()) ? 1 : 0;
8365 }
8366
clang_CXXMethod_isDefaulted(CXCursor C)8367 unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8368 if (!clang_isDeclaration(C.kind))
8369 return 0;
8370
8371 const Decl *D = cxcursor::getCursorDecl(C);
8372 const CXXMethodDecl *Method =
8373 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8374 return (Method && Method->isDefaulted()) ? 1 : 0;
8375 }
8376
clang_CXXMethod_isStatic(CXCursor C)8377 unsigned clang_CXXMethod_isStatic(CXCursor C) {
8378 if (!clang_isDeclaration(C.kind))
8379 return 0;
8380
8381 const Decl *D = cxcursor::getCursorDecl(C);
8382 const CXXMethodDecl *Method =
8383 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8384 return (Method && Method->isStatic()) ? 1 : 0;
8385 }
8386
clang_CXXMethod_isVirtual(CXCursor C)8387 unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8388 if (!clang_isDeclaration(C.kind))
8389 return 0;
8390
8391 const Decl *D = cxcursor::getCursorDecl(C);
8392 const CXXMethodDecl *Method =
8393 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8394 return (Method && Method->isVirtual()) ? 1 : 0;
8395 }
8396
clang_CXXRecord_isAbstract(CXCursor C)8397 unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8398 if (!clang_isDeclaration(C.kind))
8399 return 0;
8400
8401 const auto *D = cxcursor::getCursorDecl(C);
8402 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8403 if (RD)
8404 RD = RD->getDefinition();
8405 return (RD && RD->isAbstract()) ? 1 : 0;
8406 }
8407
clang_EnumDecl_isScoped(CXCursor C)8408 unsigned clang_EnumDecl_isScoped(CXCursor C) {
8409 if (!clang_isDeclaration(C.kind))
8410 return 0;
8411
8412 const Decl *D = cxcursor::getCursorDecl(C);
8413 auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8414 return (Enum && Enum->isScoped()) ? 1 : 0;
8415 }
8416
8417 //===----------------------------------------------------------------------===//
8418 // Attribute introspection.
8419 //===----------------------------------------------------------------------===//
8420
clang_getIBOutletCollectionType(CXCursor C)8421 CXType clang_getIBOutletCollectionType(CXCursor C) {
8422 if (C.kind != CXCursor_IBOutletCollectionAttr)
8423 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8424
8425 const IBOutletCollectionAttr *A =
8426 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8427
8428 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
8429 }
8430
8431 //===----------------------------------------------------------------------===//
8432 // Inspecting memory usage.
8433 //===----------------------------------------------------------------------===//
8434
8435 typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
8436
createCXTUResourceUsageEntry(MemUsageEntries & entries,enum CXTUResourceUsageKind k,unsigned long amount)8437 static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8438 enum CXTUResourceUsageKind k,
8439 unsigned long amount) {
8440 CXTUResourceUsageEntry entry = { k, amount };
8441 entries.push_back(entry);
8442 }
8443
clang_getTUResourceUsageName(CXTUResourceUsageKind kind)8444 const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8445 const char *str = "";
8446 switch (kind) {
8447 case CXTUResourceUsage_AST:
8448 str = "ASTContext: expressions, declarations, and types";
8449 break;
8450 case CXTUResourceUsage_Identifiers:
8451 str = "ASTContext: identifiers";
8452 break;
8453 case CXTUResourceUsage_Selectors:
8454 str = "ASTContext: selectors";
8455 break;
8456 case CXTUResourceUsage_GlobalCompletionResults:
8457 str = "Code completion: cached global results";
8458 break;
8459 case CXTUResourceUsage_SourceManagerContentCache:
8460 str = "SourceManager: content cache allocator";
8461 break;
8462 case CXTUResourceUsage_AST_SideTables:
8463 str = "ASTContext: side tables";
8464 break;
8465 case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8466 str = "SourceManager: malloc'ed memory buffers";
8467 break;
8468 case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8469 str = "SourceManager: mmap'ed memory buffers";
8470 break;
8471 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8472 str = "ExternalASTSource: malloc'ed memory buffers";
8473 break;
8474 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8475 str = "ExternalASTSource: mmap'ed memory buffers";
8476 break;
8477 case CXTUResourceUsage_Preprocessor:
8478 str = "Preprocessor: malloc'ed memory";
8479 break;
8480 case CXTUResourceUsage_PreprocessingRecord:
8481 str = "Preprocessor: PreprocessingRecord";
8482 break;
8483 case CXTUResourceUsage_SourceManager_DataStructures:
8484 str = "SourceManager: data structures and tables";
8485 break;
8486 case CXTUResourceUsage_Preprocessor_HeaderSearch:
8487 str = "Preprocessor: header search tables";
8488 break;
8489 }
8490 return str;
8491 }
8492
clang_getCXTUResourceUsage(CXTranslationUnit TU)8493 CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
8494 if (isNotUsableTU(TU)) {
8495 LOG_BAD_TU(TU);
8496 CXTUResourceUsage usage = { (void*) nullptr, 0, nullptr };
8497 return usage;
8498 }
8499
8500 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8501 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
8502 ASTContext &astContext = astUnit->getASTContext();
8503
8504 // How much memory is used by AST nodes and types?
8505 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
8506 (unsigned long) astContext.getASTAllocatedMemory());
8507
8508 // How much memory is used by identifiers?
8509 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
8510 (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
8511
8512 // How much memory is used for selectors?
8513 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
8514 (unsigned long) astContext.Selectors.getTotalMemory());
8515
8516 // How much memory is used by ASTContext's side tables?
8517 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
8518 (unsigned long) astContext.getSideTableAllocatedMemory());
8519
8520 // How much memory is used for caching global code completion results?
8521 unsigned long completionBytes = 0;
8522 if (GlobalCodeCompletionAllocator *completionAllocator =
8523 astUnit->getCachedCompletionAllocator().get()) {
8524 completionBytes = completionAllocator->getTotalMemory();
8525 }
8526 createCXTUResourceUsageEntry(*entries,
8527 CXTUResourceUsage_GlobalCompletionResults,
8528 completionBytes);
8529
8530 // How much memory is being used by SourceManager's content cache?
8531 createCXTUResourceUsageEntry(*entries,
8532 CXTUResourceUsage_SourceManagerContentCache,
8533 (unsigned long) astContext.getSourceManager().getContentCacheSize());
8534
8535 // How much memory is being used by the MemoryBuffer's in SourceManager?
8536 const SourceManager::MemoryBufferSizes &srcBufs =
8537 astUnit->getSourceManager().getMemoryBufferSizes();
8538
8539 createCXTUResourceUsageEntry(*entries,
8540 CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8541 (unsigned long) srcBufs.malloc_bytes);
8542 createCXTUResourceUsageEntry(*entries,
8543 CXTUResourceUsage_SourceManager_Membuffer_MMap,
8544 (unsigned long) srcBufs.mmap_bytes);
8545 createCXTUResourceUsageEntry(*entries,
8546 CXTUResourceUsage_SourceManager_DataStructures,
8547 (unsigned long) astContext.getSourceManager()
8548 .getDataStructureSizes());
8549
8550 // How much memory is being used by the ExternalASTSource?
8551 if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8552 const ExternalASTSource::MemoryBufferSizes &sizes =
8553 esrc->getMemoryBufferSizes();
8554
8555 createCXTUResourceUsageEntry(*entries,
8556 CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8557 (unsigned long) sizes.malloc_bytes);
8558 createCXTUResourceUsageEntry(*entries,
8559 CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8560 (unsigned long) sizes.mmap_bytes);
8561 }
8562
8563 // How much memory is being used by the Preprocessor?
8564 Preprocessor &pp = astUnit->getPreprocessor();
8565 createCXTUResourceUsageEntry(*entries,
8566 CXTUResourceUsage_Preprocessor,
8567 pp.getTotalMemory());
8568
8569 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8570 createCXTUResourceUsageEntry(*entries,
8571 CXTUResourceUsage_PreprocessingRecord,
8572 pRec->getTotalMemory());
8573 }
8574
8575 createCXTUResourceUsageEntry(*entries,
8576 CXTUResourceUsage_Preprocessor_HeaderSearch,
8577 pp.getHeaderSearchInfo().getTotalMemory());
8578
8579 CXTUResourceUsage usage = { (void*) entries.get(),
8580 (unsigned) entries->size(),
8581 !entries->empty() ? &(*entries)[0] : nullptr };
8582 (void)entries.release();
8583 return usage;
8584 }
8585
clang_disposeCXTUResourceUsage(CXTUResourceUsage usage)8586 void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8587 if (usage.data)
8588 delete (MemUsageEntries*) usage.data;
8589 }
8590
clang_getSkippedRanges(CXTranslationUnit TU,CXFile file)8591 CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
8592 CXSourceRangeList *skipped = new CXSourceRangeList;
8593 skipped->count = 0;
8594 skipped->ranges = nullptr;
8595
8596 if (isNotUsableTU(TU)) {
8597 LOG_BAD_TU(TU);
8598 return skipped;
8599 }
8600
8601 if (!file)
8602 return skipped;
8603
8604 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8605 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8606 if (!ppRec)
8607 return skipped;
8608
8609 ASTContext &Ctx = astUnit->getASTContext();
8610 SourceManager &sm = Ctx.getSourceManager();
8611 FileEntry *fileEntry = static_cast<FileEntry *>(file);
8612 FileID wantedFileID = sm.translateFile(fileEntry);
8613 bool isMainFile = wantedFileID == sm.getMainFileID();
8614
8615 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8616 std::vector<SourceRange> wantedRanges;
8617 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8618 i != ei; ++i) {
8619 if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8620 wantedRanges.push_back(*i);
8621 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8622 wantedRanges.push_back(*i);
8623 }
8624
8625 skipped->count = wantedRanges.size();
8626 skipped->ranges = new CXSourceRange[skipped->count];
8627 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8628 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
8629
8630 return skipped;
8631 }
8632
clang_getAllSkippedRanges(CXTranslationUnit TU)8633 CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8634 CXSourceRangeList *skipped = new CXSourceRangeList;
8635 skipped->count = 0;
8636 skipped->ranges = nullptr;
8637
8638 if (isNotUsableTU(TU)) {
8639 LOG_BAD_TU(TU);
8640 return skipped;
8641 }
8642
8643 ASTUnit *astUnit = cxtu::getASTUnit(TU);
8644 PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8645 if (!ppRec)
8646 return skipped;
8647
8648 ASTContext &Ctx = astUnit->getASTContext();
8649
8650 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8651
8652 skipped->count = SkippedRanges.size();
8653 skipped->ranges = new CXSourceRange[skipped->count];
8654 for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
8655 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
8656
8657 return skipped;
8658 }
8659
clang_disposeSourceRangeList(CXSourceRangeList * ranges)8660 void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8661 if (ranges) {
8662 delete[] ranges->ranges;
8663 delete ranges;
8664 }
8665 }
8666
PrintLibclangResourceUsage(CXTranslationUnit TU)8667 void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8668 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8669 for (unsigned I = 0; I != Usage.numEntries; ++I)
8670 fprintf(stderr, " %s: %lu\n",
8671 clang_getTUResourceUsageName(Usage.entries[I].kind),
8672 Usage.entries[I].amount);
8673
8674 clang_disposeCXTUResourceUsage(Usage);
8675 }
8676
8677 //===----------------------------------------------------------------------===//
8678 // Misc. utility functions.
8679 //===----------------------------------------------------------------------===//
8680
8681 /// Default to using our desired 8 MB stack size on "safety" threads.
8682 static unsigned SafetyStackThreadSize = DesiredStackSize;
8683
8684 namespace clang {
8685
RunSafely(llvm::CrashRecoveryContext & CRC,llvm::function_ref<void ()> Fn,unsigned Size)8686 bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
8687 unsigned Size) {
8688 if (!Size)
8689 Size = GetSafetyThreadStackSize();
8690 if (Size && !getenv("LIBCLANG_NOTHREADS"))
8691 return CRC.RunSafelyOnThread(Fn, Size);
8692 return CRC.RunSafely(Fn);
8693 }
8694
GetSafetyThreadStackSize()8695 unsigned GetSafetyThreadStackSize() {
8696 return SafetyStackThreadSize;
8697 }
8698
SetSafetyThreadStackSize(unsigned Value)8699 void SetSafetyThreadStackSize(unsigned Value) {
8700 SafetyStackThreadSize = Value;
8701 }
8702
8703 }
8704
setThreadBackgroundPriority()8705 void clang::setThreadBackgroundPriority() {
8706 if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8707 return;
8708
8709 #ifdef USE_DARWIN_THREADS
8710 setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
8711 #endif
8712 }
8713
printDiagsToStderr(ASTUnit * Unit)8714 void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8715 if (!Unit)
8716 return;
8717
8718 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
8719 DEnd = Unit->stored_diag_end();
8720 D != DEnd; ++D) {
8721 CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
8722 CXString Msg = clang_formatDiagnostic(&Diag,
8723 clang_defaultDiagnosticDisplayOptions());
8724 fprintf(stderr, "%s\n", clang_getCString(Msg));
8725 clang_disposeString(Msg);
8726 }
8727 #ifdef _WIN32
8728 // On Windows, force a flush, since there may be multiple copies of
8729 // stderr and stdout in the file system, all with different buffers
8730 // but writing to the same device.
8731 fflush(stderr);
8732 #endif
8733 }
8734
getMacroInfo(const IdentifierInfo & II,SourceLocation MacroDefLoc,CXTranslationUnit TU)8735 MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8736 SourceLocation MacroDefLoc,
8737 CXTranslationUnit TU){
8738 if (MacroDefLoc.isInvalid() || !TU)
8739 return nullptr;
8740 if (!II.hadMacroDefinition())
8741 return nullptr;
8742
8743 ASTUnit *Unit = cxtu::getASTUnit(TU);
8744 Preprocessor &PP = Unit->getPreprocessor();
8745 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
8746 if (MD) {
8747 for (MacroDirective::DefInfo
8748 Def = MD->getDefinition(); Def; Def = Def.getPreviousDefinition()) {
8749 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8750 return Def.getMacroInfo();
8751 }
8752 }
8753
8754 return nullptr;
8755 }
8756
getMacroInfo(const MacroDefinitionRecord * MacroDef,CXTranslationUnit TU)8757 const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
8758 CXTranslationUnit TU) {
8759 if (!MacroDef || !TU)
8760 return nullptr;
8761 const IdentifierInfo *II = MacroDef->getName();
8762 if (!II)
8763 return nullptr;
8764
8765 return getMacroInfo(*II, MacroDef->getLocation(), TU);
8766 }
8767
8768 MacroDefinitionRecord *
checkForMacroInMacroDefinition(const MacroInfo * MI,const Token & Tok,CXTranslationUnit TU)8769 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
8770 CXTranslationUnit TU) {
8771 if (!MI || !TU)
8772 return nullptr;
8773 if (Tok.isNot(tok::raw_identifier))
8774 return nullptr;
8775
8776 if (MI->getNumTokens() == 0)
8777 return nullptr;
8778 SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8779 MI->getDefinitionEndLoc());
8780 ASTUnit *Unit = cxtu::getASTUnit(TU);
8781
8782 // Check that the token is inside the definition and not its argument list.
8783 SourceManager &SM = Unit->getSourceManager();
8784 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
8785 return nullptr;
8786 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
8787 return nullptr;
8788
8789 Preprocessor &PP = Unit->getPreprocessor();
8790 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8791 if (!PPRec)
8792 return nullptr;
8793
8794 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
8795 if (!II.hadMacroDefinition())
8796 return nullptr;
8797
8798 // Check that the identifier is not one of the macro arguments.
8799 if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
8800 return nullptr;
8801
8802 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
8803 if (!InnerMD)
8804 return nullptr;
8805
8806 return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
8807 }
8808
8809 MacroDefinitionRecord *
checkForMacroInMacroDefinition(const MacroInfo * MI,SourceLocation Loc,CXTranslationUnit TU)8810 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
8811 CXTranslationUnit TU) {
8812 if (Loc.isInvalid() || !MI || !TU)
8813 return nullptr;
8814
8815 if (MI->getNumTokens() == 0)
8816 return nullptr;
8817 ASTUnit *Unit = cxtu::getASTUnit(TU);
8818 Preprocessor &PP = Unit->getPreprocessor();
8819 if (!PP.getPreprocessingRecord())
8820 return nullptr;
8821 Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8822 Token Tok;
8823 if (PP.getRawToken(Loc, Tok))
8824 return nullptr;
8825
8826 return checkForMacroInMacroDefinition(MI, Tok, TU);
8827 }
8828
clang_getClangVersion()8829 CXString clang_getClangVersion() {
8830 return cxstring::createDup(getClangFullVersion());
8831 }
8832
operator <<(CXTranslationUnit TU)8833 Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8834 if (TU) {
8835 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
8836 LogOS << '<' << Unit->getMainFileName() << '>';
8837 if (Unit->isMainFileAST())
8838 LogOS << " (" << Unit->getASTFileName() << ')';
8839 return *this;
8840 }
8841 } else {
8842 LogOS << "<NULL TU>";
8843 }
8844 return *this;
8845 }
8846
operator <<(const FileEntry * FE)8847 Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8848 *this << FE->getName();
8849 return *this;
8850 }
8851
operator <<(CXCursor cursor)8852 Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8853 CXString cursorName = clang_getCursorDisplayName(cursor);
8854 *this << cursorName << "@" << clang_getCursorLocation(cursor);
8855 clang_disposeString(cursorName);
8856 return *this;
8857 }
8858
operator <<(CXSourceLocation Loc)8859 Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8860 CXFile File;
8861 unsigned Line, Column;
8862 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
8863 CXString FileName = clang_getFileName(File);
8864 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8865 clang_disposeString(FileName);
8866 return *this;
8867 }
8868
operator <<(CXSourceRange range)8869 Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8870 CXSourceLocation BLoc = clang_getRangeStart(range);
8871 CXSourceLocation ELoc = clang_getRangeEnd(range);
8872
8873 CXFile BFile;
8874 unsigned BLine, BColumn;
8875 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
8876
8877 CXFile EFile;
8878 unsigned ELine, EColumn;
8879 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
8880
8881 CXString BFileName = clang_getFileName(BFile);
8882 if (BFile == EFile) {
8883 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8884 BLine, BColumn, ELine, EColumn);
8885 } else {
8886 CXString EFileName = clang_getFileName(EFile);
8887 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8888 BLine, BColumn)
8889 << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8890 ELine, EColumn);
8891 clang_disposeString(EFileName);
8892 }
8893 clang_disposeString(BFileName);
8894 return *this;
8895 }
8896
operator <<(CXString Str)8897 Logger &cxindex::Logger::operator<<(CXString Str) {
8898 *this << clang_getCString(Str);
8899 return *this;
8900 }
8901
operator <<(const llvm::format_object_base & Fmt)8902 Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8903 LogOS << Fmt;
8904 return *this;
8905 }
8906
8907 static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8908
~Logger()8909 cxindex::Logger::~Logger() {
8910 llvm::sys::ScopedLock L(*LoggingMutex);
8911
8912 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8913
8914 raw_ostream &OS = llvm::errs();
8915 OS << "[libclang:" << Name << ':';
8916
8917 #ifdef USE_DARWIN_THREADS
8918 // TODO: Portability.
8919 mach_port_t tid = pthread_mach_thread_np(pthread_self());
8920 OS << tid << ':';
8921 #endif
8922
8923 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8924 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
8925 OS << Msg << '\n';
8926
8927 if (Trace) {
8928 llvm::sys::PrintStackTrace(OS);
8929 OS << "--------------------------------------------------\n";
8930 }
8931 }
8932
8933 #ifdef CLANG_TOOL_EXTRA_BUILD
8934 // This anchor is used to force the linker to link the clang-tidy plugin.
8935 extern volatile int ClangTidyPluginAnchorSource;
8936 static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8937 ClangTidyPluginAnchorSource;
8938
8939 // This anchor is used to force the linker to link the clang-include-fixer
8940 // plugin.
8941 extern volatile int ClangIncludeFixerPluginAnchorSource;
8942 static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8943 ClangIncludeFixerPluginAnchorSource;
8944 #endif
8945