Hack to workaround deficiency in ObjC ASTs. Functions and variables may be declared
[clang.git] / tools / libclang / CIndex.cpp
blobf4cae89f8fc92482a800b58f9e724eb1be7a8ce4
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.
13 //===----------------------------------------------------------------------===//
15 #include "CIndexer.h"
16 #include "CXCursor.h"
17 #include "CXType.h"
18 #include "CXSourceLocation.h"
19 #include "CIndexDiagnostic.h"
21 #include "clang/Basic/Version.h"
23 #include "clang/AST/DeclVisitor.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeLocVisitor.h"
26 #include "clang/Basic/Diagnostic.h"
27 #include "clang/Frontend/ASTUnit.h"
28 #include "clang/Frontend/CompilerInstance.h"
29 #include "clang/Frontend/FrontendDiagnostic.h"
30 #include "clang/Lex/Lexer.h"
31 #include "clang/Lex/PreprocessingRecord.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/Optional.h"
35 #include "clang/Analysis/Support/SaveAndRestore.h"
36 #include "llvm/Support/CrashRecoveryContext.h"
37 #include "llvm/Support/PrettyStackTrace.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Support/Timer.h"
41 #include "llvm/System/Mutex.h"
42 #include "llvm/System/Program.h"
43 #include "llvm/System/Signals.h"
44 #include "llvm/System/Threading.h"
46 // Needed to define L_TMPNAM on some systems.
47 #include <cstdio>
49 using namespace clang;
50 using namespace clang::cxcursor;
51 using namespace clang::cxstring;
53 /// \brief The result of comparing two source ranges.
54 enum RangeComparisonResult {
55 /// \brief Either the ranges overlap or one of the ranges is invalid.
56 RangeOverlap,
58 /// \brief The first range ends before the second range starts.
59 RangeBefore,
61 /// \brief The first range starts after the second range ends.
62 RangeAfter
65 /// \brief Compare two source ranges to determine their relative position in
66 /// the translation unit.
67 static RangeComparisonResult RangeCompare(SourceManager &SM,
68 SourceRange R1,
69 SourceRange R2) {
70 assert(R1.isValid() && "First range is invalid?");
71 assert(R2.isValid() && "Second range is invalid?");
72 if (R1.getEnd() != R2.getBegin() &&
73 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
74 return RangeBefore;
75 if (R2.getEnd() != R1.getBegin() &&
76 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
77 return RangeAfter;
78 return RangeOverlap;
81 /// \brief Determine if a source location falls within, before, or after a
82 /// a given source range.
83 static RangeComparisonResult LocationCompare(SourceManager &SM,
84 SourceLocation L, SourceRange R) {
85 assert(R.isValid() && "First range is invalid?");
86 assert(L.isValid() && "Second range is invalid?");
87 if (L == R.getBegin() || L == R.getEnd())
88 return RangeOverlap;
89 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
90 return RangeBefore;
91 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
92 return RangeAfter;
93 return RangeOverlap;
96 /// \brief Translate a Clang source range into a CIndex source range.
97 ///
98 /// Clang internally represents ranges where the end location points to the
99 /// start of the token at the end. However, for external clients it is more
100 /// useful to have a CXSourceRange be a proper half-open interval. This routine
101 /// does the appropriate translation.
102 CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
103 const LangOptions &LangOpts,
104 const CharSourceRange &R) {
105 // We want the last character in this location, so we will adjust the
106 // location accordingly.
107 // FIXME: How do do this with a macro instantiation location?
108 SourceLocation EndLoc = R.getEnd();
109 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
110 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
111 EndLoc = EndLoc.getFileLocWithOffset(Length);
114 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
115 R.getBegin().getRawEncoding(),
116 EndLoc.getRawEncoding() };
117 return Result;
120 //===----------------------------------------------------------------------===//
121 // Cursor visitor.
122 //===----------------------------------------------------------------------===//
124 namespace {
126 // Cursor visitor.
127 class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
128 public TypeLocVisitor<CursorVisitor, bool>,
129 public StmtVisitor<CursorVisitor, bool>
131 /// \brief The translation unit we are traversing.
132 ASTUnit *TU;
134 /// \brief The parent cursor whose children we are traversing.
135 CXCursor Parent;
137 /// \brief The declaration that serves at the parent of any statement or
138 /// expression nodes.
139 Decl *StmtParent;
141 /// \brief The visitor function.
142 CXCursorVisitor Visitor;
144 /// \brief The opaque client data, to be passed along to the visitor.
145 CXClientData ClientData;
147 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
148 // to the visitor. Declarations with a PCH level greater than this value will
149 // be suppressed.
150 unsigned MaxPCHLevel;
152 /// \brief When valid, a source range to which the cursor should restrict
153 /// its search.
154 SourceRange RegionOfInterest;
156 // FIXME: Eventually remove. This part of a hack to support proper
157 // iteration over all Decls contained lexically within an ObjC container.
158 DeclContext::decl_iterator *DI_current;
159 DeclContext::decl_iterator DE_current;
161 using DeclVisitor<CursorVisitor, bool>::Visit;
162 using TypeLocVisitor<CursorVisitor, bool>::Visit;
163 using StmtVisitor<CursorVisitor, bool>::Visit;
165 /// \brief Determine whether this particular source range comes before, comes
166 /// after, or overlaps the region of interest.
168 /// \param R a half-open source range retrieved from the abstract syntax tree.
169 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
171 class SetParentRAII {
172 CXCursor &Parent;
173 Decl *&StmtParent;
174 CXCursor OldParent;
176 public:
177 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
178 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
180 Parent = NewParent;
181 if (clang_isDeclaration(Parent.kind))
182 StmtParent = getCursorDecl(Parent);
185 ~SetParentRAII() {
186 Parent = OldParent;
187 if (clang_isDeclaration(Parent.kind))
188 StmtParent = getCursorDecl(Parent);
192 public:
193 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
194 unsigned MaxPCHLevel,
195 SourceRange RegionOfInterest = SourceRange())
196 : TU(TU), Visitor(Visitor), ClientData(ClientData),
197 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
198 DI_current(0)
200 Parent.kind = CXCursor_NoDeclFound;
201 Parent.data[0] = 0;
202 Parent.data[1] = 0;
203 Parent.data[2] = 0;
204 StmtParent = 0;
207 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
209 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
210 getPreprocessedEntities();
212 bool VisitChildren(CXCursor Parent);
214 // Declaration visitors
215 bool VisitAttributes(Decl *D);
216 bool VisitBlockDecl(BlockDecl *B);
217 bool VisitCXXRecordDecl(CXXRecordDecl *D);
218 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
219 bool VisitDeclContext(DeclContext *DC);
220 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
221 bool VisitTypedefDecl(TypedefDecl *D);
222 bool VisitTagDecl(TagDecl *D);
223 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
224 bool VisitClassTemplatePartialSpecializationDecl(
225 ClassTemplatePartialSpecializationDecl *D);
226 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
227 bool VisitEnumConstantDecl(EnumConstantDecl *D);
228 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
229 bool VisitFunctionDecl(FunctionDecl *ND);
230 bool VisitFieldDecl(FieldDecl *D);
231 bool VisitVarDecl(VarDecl *);
232 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
233 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
234 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
235 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
236 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
237 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
238 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
239 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
240 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
241 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
242 bool VisitObjCImplDecl(ObjCImplDecl *D);
243 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
244 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
245 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
246 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
247 bool VisitObjCClassDecl(ObjCClassDecl *D);
248 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
249 bool VisitNamespaceDecl(NamespaceDecl *D);
250 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
251 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
252 bool VisitUsingDecl(UsingDecl *D);
253 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
254 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
256 // Name visitor
257 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
258 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
260 // Template visitors
261 bool VisitTemplateParameters(const TemplateParameterList *Params);
262 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
263 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
265 // Type visitors
266 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
267 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
268 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
269 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
270 bool VisitTagTypeLoc(TagTypeLoc TL);
271 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
272 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
273 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
274 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
275 bool VisitPointerTypeLoc(PointerTypeLoc TL);
276 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
277 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
278 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
279 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
280 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
281 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
282 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
283 // FIXME: Implement visitors here when the unimplemented TypeLocs get
284 // implemented
285 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
286 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
288 // Statement visitors
289 bool VisitStmt(Stmt *S);
290 bool VisitDeclStmt(DeclStmt *S);
291 bool VisitGotoStmt(GotoStmt *S);
292 bool VisitIfStmt(IfStmt *S);
293 bool VisitSwitchStmt(SwitchStmt *S);
294 bool VisitCaseStmt(CaseStmt *S);
295 bool VisitWhileStmt(WhileStmt *S);
296 bool VisitForStmt(ForStmt *S);
298 // Expression visitors
299 bool VisitDeclRefExpr(DeclRefExpr *E);
300 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
301 bool VisitBlockExpr(BlockExpr *B);
302 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
303 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
304 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
305 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
306 bool VisitOffsetOfExpr(OffsetOfExpr *E);
307 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
308 bool VisitMemberExpr(MemberExpr *E);
309 bool VisitAddrLabelExpr(AddrLabelExpr *E);
310 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
311 bool VisitVAArgExpr(VAArgExpr *E);
312 bool VisitInitListExpr(InitListExpr *E);
313 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
314 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
315 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
316 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
317 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
318 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
319 bool VisitCXXNewExpr(CXXNewExpr *E);
320 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
321 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
322 bool VisitOverloadExpr(OverloadExpr *E);
323 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
324 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
325 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
326 bool VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
329 } // end anonymous namespace
331 static SourceRange getRawCursorExtent(CXCursor C);
333 RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
334 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
337 /// \brief Visit the given cursor and, if requested by the visitor,
338 /// its children.
340 /// \param Cursor the cursor to visit.
342 /// \param CheckRegionOfInterest if true, then the caller already checked that
343 /// this cursor is within the region of interest.
345 /// \returns true if the visitation should be aborted, false if it
346 /// should continue.
347 bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
348 if (clang_isInvalid(Cursor.kind))
349 return false;
351 if (clang_isDeclaration(Cursor.kind)) {
352 Decl *D = getCursorDecl(Cursor);
353 assert(D && "Invalid declaration cursor");
354 if (D->getPCHLevel() > MaxPCHLevel)
355 return false;
357 if (D->isImplicit())
358 return false;
361 // If we have a range of interest, and this cursor doesn't intersect with it,
362 // we're done.
363 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
364 SourceRange Range = getRawCursorExtent(Cursor);
365 if (Range.isInvalid() || CompareRegionOfInterest(Range))
366 return false;
369 switch (Visitor(Cursor, Parent, ClientData)) {
370 case CXChildVisit_Break:
371 return true;
373 case CXChildVisit_Continue:
374 return false;
376 case CXChildVisit_Recurse:
377 return VisitChildren(Cursor);
380 return false;
383 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
384 CursorVisitor::getPreprocessedEntities() {
385 PreprocessingRecord &PPRec
386 = *TU->getPreprocessor().getPreprocessingRecord();
388 bool OnlyLocalDecls
389 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
391 // There is no region of interest; we have to walk everything.
392 if (RegionOfInterest.isInvalid())
393 return std::make_pair(PPRec.begin(OnlyLocalDecls),
394 PPRec.end(OnlyLocalDecls));
396 // Find the file in which the region of interest lands.
397 SourceManager &SM = TU->getSourceManager();
398 std::pair<FileID, unsigned> Begin
399 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
400 std::pair<FileID, unsigned> End
401 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
403 // The region of interest spans files; we have to walk everything.
404 if (Begin.first != End.first)
405 return std::make_pair(PPRec.begin(OnlyLocalDecls),
406 PPRec.end(OnlyLocalDecls));
408 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
409 = TU->getPreprocessedEntitiesByFile();
410 if (ByFileMap.empty()) {
411 // Build the mapping from files to sets of preprocessed entities.
412 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
413 EEnd = PPRec.end(OnlyLocalDecls);
414 E != EEnd; ++E) {
415 std::pair<FileID, unsigned> P
416 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
417 ByFileMap[P.first].push_back(*E);
421 return std::make_pair(ByFileMap[Begin.first].begin(),
422 ByFileMap[Begin.first].end());
425 /// \brief Visit the children of the given cursor.
427 /// \returns true if the visitation should be aborted, false if it
428 /// should continue.
429 bool CursorVisitor::VisitChildren(CXCursor Cursor) {
430 if (clang_isReference(Cursor.kind)) {
431 // By definition, references have no children.
432 return false;
435 // Set the Parent field to Cursor, then back to its old value once we're
436 // done.
437 SetParentRAII SetParent(Parent, StmtParent, Cursor);
439 if (clang_isDeclaration(Cursor.kind)) {
440 Decl *D = getCursorDecl(Cursor);
441 assert(D && "Invalid declaration cursor");
442 return VisitAttributes(D) || Visit(D);
445 if (clang_isStatement(Cursor.kind))
446 return Visit(getCursorStmt(Cursor));
447 if (clang_isExpression(Cursor.kind))
448 return Visit(getCursorExpr(Cursor));
450 if (clang_isTranslationUnit(Cursor.kind)) {
451 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
452 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
453 RegionOfInterest.isInvalid()) {
454 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
455 TLEnd = CXXUnit->top_level_end();
456 TL != TLEnd; ++TL) {
457 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
458 return true;
460 } else if (VisitDeclContext(
461 CXXUnit->getASTContext().getTranslationUnitDecl()))
462 return true;
464 // Walk the preprocessing record.
465 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
466 // FIXME: Once we have the ability to deserialize a preprocessing record,
467 // do so.
468 PreprocessingRecord::iterator E, EEnd;
469 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
470 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
471 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
472 return true;
474 continue;
477 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
478 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
479 return true;
481 continue;
484 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
485 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
486 return true;
488 continue;
492 return false;
495 // Nothing to visit at the moment.
496 return false;
499 bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
500 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
501 return true;
503 if (Stmt *Body = B->getBody())
504 return Visit(MakeCXCursor(Body, StmtParent, TU));
506 return false;
509 llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
510 if (RegionOfInterest.isValid()) {
511 SourceRange Range = getRawCursorExtent(Cursor);
512 if (Range.isInvalid())
513 return llvm::Optional<bool>();
515 switch (CompareRegionOfInterest(Range)) {
516 case RangeBefore:
517 // This declaration comes before the region of interest; skip it.
518 return llvm::Optional<bool>();
520 case RangeAfter:
521 // This declaration comes after the region of interest; we're done.
522 return false;
524 case RangeOverlap:
525 // This declaration overlaps the region of interest; visit it.
526 break;
529 return true;
532 bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
533 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
535 // FIXME: Eventually remove. This part of a hack to support proper
536 // iteration over all Decls contained lexically within an ObjC container.
537 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
538 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
540 for ( ; I != E; ++I) {
541 Decl *D = *I;
542 if (D->getLexicalDeclContext() != DC)
543 continue;
544 CXCursor Cursor = MakeCXCursor(D, TU);
545 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
546 if (!V.hasValue())
547 continue;
548 if (!V.getValue())
549 return false;
550 if (Visit(Cursor, true))
551 return true;
553 return false;
556 bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
557 llvm_unreachable("Translation units are visited directly by Visit()");
558 return false;
561 bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
562 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
563 return Visit(TSInfo->getTypeLoc());
565 return false;
568 bool CursorVisitor::VisitTagDecl(TagDecl *D) {
569 return VisitDeclContext(D);
572 bool CursorVisitor::VisitClassTemplateSpecializationDecl(
573 ClassTemplateSpecializationDecl *D) {
574 bool ShouldVisitBody = false;
575 switch (D->getSpecializationKind()) {
576 case TSK_Undeclared:
577 case TSK_ImplicitInstantiation:
578 // Nothing to visit
579 return false;
581 case TSK_ExplicitInstantiationDeclaration:
582 case TSK_ExplicitInstantiationDefinition:
583 break;
585 case TSK_ExplicitSpecialization:
586 ShouldVisitBody = true;
587 break;
590 // Visit the template arguments used in the specialization.
591 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
592 TypeLoc TL = SpecType->getTypeLoc();
593 if (TemplateSpecializationTypeLoc *TSTLoc
594 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
595 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
596 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
597 return true;
601 if (ShouldVisitBody && VisitCXXRecordDecl(D))
602 return true;
604 return false;
607 bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
608 ClassTemplatePartialSpecializationDecl *D) {
609 // FIXME: Visit the "outer" template parameter lists on the TagDecl
610 // before visiting these template parameters.
611 if (VisitTemplateParameters(D->getTemplateParameters()))
612 return true;
614 // Visit the partial specialization arguments.
615 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
616 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
617 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
618 return true;
620 return VisitCXXRecordDecl(D);
623 bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
624 // Visit the default argument.
625 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
626 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
627 if (Visit(DefArg->getTypeLoc()))
628 return true;
630 return false;
633 bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
634 if (Expr *Init = D->getInitExpr())
635 return Visit(MakeCXCursor(Init, StmtParent, TU));
636 return false;
639 bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
640 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
641 if (Visit(TSInfo->getTypeLoc()))
642 return true;
644 return false;
647 /// \brief Compare two base or member initializers based on their source order.
648 static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
649 CXXBaseOrMemberInitializer const * const *X
650 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
651 CXXBaseOrMemberInitializer const * const *Y
652 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
654 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
655 return -1;
656 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
657 return 1;
658 else
659 return 0;
662 bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
663 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
664 // Visit the function declaration's syntactic components in the order
665 // written. This requires a bit of work.
666 TypeLoc TL = TSInfo->getTypeLoc();
667 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
669 // If we have a function declared directly (without the use of a typedef),
670 // visit just the return type. Otherwise, just visit the function's type
671 // now.
672 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
673 (!FTL && Visit(TL)))
674 return true;
676 // Visit the nested-name-specifier, if present.
677 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
678 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
679 return true;
681 // Visit the declaration name.
682 if (VisitDeclarationNameInfo(ND->getNameInfo()))
683 return true;
685 // FIXME: Visit explicitly-specified template arguments!
687 // Visit the function parameters, if we have a function type.
688 if (FTL && VisitFunctionTypeLoc(*FTL, true))
689 return true;
691 // FIXME: Attributes?
694 if (ND->isThisDeclarationADefinition()) {
695 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
696 // Find the initializers that were written in the source.
697 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
698 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
699 IEnd = Constructor->init_end();
700 I != IEnd; ++I) {
701 if (!(*I)->isWritten())
702 continue;
704 WrittenInits.push_back(*I);
707 // Sort the initializers in source order
708 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
709 &CompareCXXBaseOrMemberInitializers);
711 // Visit the initializers in source order
712 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
713 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
714 if (Init->isMemberInitializer()) {
715 if (Visit(MakeCursorMemberRef(Init->getMember(),
716 Init->getMemberLocation(), TU)))
717 return true;
718 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
719 if (Visit(BaseInfo->getTypeLoc()))
720 return true;
723 // Visit the initializer value.
724 if (Expr *Initializer = Init->getInit())
725 if (Visit(MakeCXCursor(Initializer, ND, TU)))
726 return true;
730 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
731 return true;
734 return false;
737 bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
738 if (VisitDeclaratorDecl(D))
739 return true;
741 if (Expr *BitWidth = D->getBitWidth())
742 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
744 return false;
747 bool CursorVisitor::VisitVarDecl(VarDecl *D) {
748 if (VisitDeclaratorDecl(D))
749 return true;
751 if (Expr *Init = D->getInit())
752 return Visit(MakeCXCursor(Init, StmtParent, TU));
754 return false;
757 bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
758 if (VisitDeclaratorDecl(D))
759 return true;
761 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
762 if (Expr *DefArg = D->getDefaultArgument())
763 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
765 return false;
768 bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
769 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
770 // before visiting these template parameters.
771 if (VisitTemplateParameters(D->getTemplateParameters()))
772 return true;
774 return VisitFunctionDecl(D->getTemplatedDecl());
777 bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
778 // FIXME: Visit the "outer" template parameter lists on the TagDecl
779 // before visiting these template parameters.
780 if (VisitTemplateParameters(D->getTemplateParameters()))
781 return true;
783 return VisitCXXRecordDecl(D->getTemplatedDecl());
786 bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
787 if (VisitTemplateParameters(D->getTemplateParameters()))
788 return true;
790 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
791 VisitTemplateArgumentLoc(D->getDefaultArgument()))
792 return true;
794 return false;
797 bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
798 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
799 if (Visit(TSInfo->getTypeLoc()))
800 return true;
802 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
803 PEnd = ND->param_end();
804 P != PEnd; ++P) {
805 if (Visit(MakeCXCursor(*P, TU)))
806 return true;
809 if (ND->isThisDeclarationADefinition() &&
810 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
811 return true;
813 return false;
816 namespace {
817 struct ContainerDeclsSort {
818 SourceManager &SM;
819 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
820 bool operator()(Decl *A, Decl *B) {
821 SourceLocation L_A = A->getLocStart();
822 SourceLocation L_B = B->getLocStart();
823 assert(L_A.isValid() && L_B.isValid());
824 return SM.isBeforeInTranslationUnit(L_A, L_B);
829 bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
830 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
831 // an @implementation can lexically contain Decls that are not properly
832 // nested in the AST. When we identify such cases, we need to retrofit
833 // this nesting here.
834 if (!DI_current)
835 return VisitDeclContext(D);
837 // Scan the Decls that immediately come after the container
838 // in the current DeclContext. If any fall within the
839 // container's lexical region, stash them into a vector
840 // for later processing.
841 llvm::SmallVector<Decl *, 24> DeclsInContainer;
842 SourceLocation EndLoc = D->getSourceRange().getEnd();
843 SourceManager &SM = TU->getSourceManager();
844 if (EndLoc.isValid()) {
845 DeclContext::decl_iterator next = *DI_current;
846 while (++next != DE_current) {
847 Decl *D_next = *next;
848 if (!D_next)
849 break;
850 SourceLocation L = D_next->getLocStart();
851 if (!L.isValid())
852 break;
853 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
854 *DI_current = next;
855 DeclsInContainer.push_back(D_next);
856 continue;
858 break;
862 // The common case.
863 if (DeclsInContainer.empty())
864 return VisitDeclContext(D);
866 // Get all the Decls in the DeclContext, and sort them with the
867 // additional ones we've collected. Then visit them.
868 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
869 I!=E; ++I) {
870 Decl *subDecl = *I;
871 if (!subDecl || subDecl->getLexicalDeclContext() != D)
872 continue;
873 DeclsInContainer.push_back(subDecl);
876 // Now sort the Decls so that they appear in lexical order.
877 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
878 ContainerDeclsSort(SM));
880 // Now visit the decls.
881 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
882 E = DeclsInContainer.end(); I != E; ++I) {
883 CXCursor Cursor = MakeCXCursor(*I, TU);
884 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
885 if (!V.hasValue())
886 continue;
887 if (!V.getValue())
888 return false;
889 if (Visit(Cursor, true))
890 return true;
892 return false;
895 bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
896 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
897 TU)))
898 return true;
900 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
901 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
902 E = ND->protocol_end(); I != E; ++I, ++PL)
903 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
904 return true;
906 return VisitObjCContainerDecl(ND);
909 bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
910 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
911 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
912 E = PID->protocol_end(); I != E; ++I, ++PL)
913 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
914 return true;
916 return VisitObjCContainerDecl(PID);
919 bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
920 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
921 return true;
923 // FIXME: This implements a workaround with @property declarations also being
924 // installed in the DeclContext for the @interface. Eventually this code
925 // should be removed.
926 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
927 if (!CDecl || !CDecl->IsClassExtension())
928 return false;
930 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
931 if (!ID)
932 return false;
934 IdentifierInfo *PropertyId = PD->getIdentifier();
935 ObjCPropertyDecl *prevDecl =
936 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
938 if (!prevDecl)
939 return false;
941 // Visit synthesized methods since they will be skipped when visiting
942 // the @interface.
943 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
944 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
945 if (Visit(MakeCXCursor(MD, TU)))
946 return true;
948 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
949 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
950 if (Visit(MakeCXCursor(MD, TU)))
951 return true;
953 return false;
956 bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
957 // Issue callbacks for super class.
958 if (D->getSuperClass() &&
959 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
960 D->getSuperClassLoc(),
961 TU)))
962 return true;
964 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
965 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
966 E = D->protocol_end(); I != E; ++I, ++PL)
967 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
968 return true;
970 return VisitObjCContainerDecl(D);
973 bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
974 return VisitObjCContainerDecl(D);
977 bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
978 // 'ID' could be null when dealing with invalid code.
979 if (ObjCInterfaceDecl *ID = D->getClassInterface())
980 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
981 return true;
983 return VisitObjCImplDecl(D);
986 bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
987 #if 0
988 // Issue callbacks for super class.
989 // FIXME: No source location information!
990 if (D->getSuperClass() &&
991 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
992 D->getSuperClassLoc(),
993 TU)))
994 return true;
995 #endif
997 return VisitObjCImplDecl(D);
1000 bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1001 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1002 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1003 E = D->protocol_end();
1004 I != E; ++I, ++PL)
1005 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1006 return true;
1008 return false;
1011 bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1012 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1013 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1014 return true;
1016 return false;
1019 bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1020 return VisitDeclContext(D);
1023 bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1024 // Visit nested-name-specifier.
1025 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1026 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1027 return true;
1029 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1030 D->getTargetNameLoc(), TU));
1033 bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1034 // Visit nested-name-specifier.
1035 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1036 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1037 return true;
1039 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1040 return true;
1042 return VisitDeclarationNameInfo(D->getNameInfo());
1045 bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1046 // Visit nested-name-specifier.
1047 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1048 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1049 return true;
1051 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1052 D->getIdentLocation(), TU));
1055 bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1056 // Visit nested-name-specifier.
1057 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1058 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1059 return true;
1061 return VisitDeclarationNameInfo(D->getNameInfo());
1064 bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1065 UnresolvedUsingTypenameDecl *D) {
1066 // Visit nested-name-specifier.
1067 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1068 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1069 return true;
1071 return false;
1074 bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1075 switch (Name.getName().getNameKind()) {
1076 case clang::DeclarationName::Identifier:
1077 case clang::DeclarationName::CXXLiteralOperatorName:
1078 case clang::DeclarationName::CXXOperatorName:
1079 case clang::DeclarationName::CXXUsingDirective:
1080 return false;
1082 case clang::DeclarationName::CXXConstructorName:
1083 case clang::DeclarationName::CXXDestructorName:
1084 case clang::DeclarationName::CXXConversionFunctionName:
1085 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1086 return Visit(TSInfo->getTypeLoc());
1087 return false;
1089 case clang::DeclarationName::ObjCZeroArgSelector:
1090 case clang::DeclarationName::ObjCOneArgSelector:
1091 case clang::DeclarationName::ObjCMultiArgSelector:
1092 // FIXME: Per-identifier location info?
1093 return false;
1096 return false;
1099 bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1100 SourceRange Range) {
1101 // FIXME: This whole routine is a hack to work around the lack of proper
1102 // source information in nested-name-specifiers (PR5791). Since we do have
1103 // a beginning source location, we can visit the first component of the
1104 // nested-name-specifier, if it's a single-token component.
1105 if (!NNS)
1106 return false;
1108 // Get the first component in the nested-name-specifier.
1109 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1110 NNS = Prefix;
1112 switch (NNS->getKind()) {
1113 case NestedNameSpecifier::Namespace:
1114 // FIXME: The token at this source location might actually have been a
1115 // namespace alias, but we don't model that. Lame!
1116 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1117 TU));
1119 case NestedNameSpecifier::TypeSpec: {
1120 // If the type has a form where we know that the beginning of the source
1121 // range matches up with a reference cursor. Visit the appropriate reference
1122 // cursor.
1123 Type *T = NNS->getAsType();
1124 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1125 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1126 if (const TagType *Tag = dyn_cast<TagType>(T))
1127 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1128 if (const TemplateSpecializationType *TST
1129 = dyn_cast<TemplateSpecializationType>(T))
1130 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1131 break;
1134 case NestedNameSpecifier::TypeSpecWithTemplate:
1135 case NestedNameSpecifier::Global:
1136 case NestedNameSpecifier::Identifier:
1137 break;
1140 return false;
1143 bool CursorVisitor::VisitTemplateParameters(
1144 const TemplateParameterList *Params) {
1145 if (!Params)
1146 return false;
1148 for (TemplateParameterList::const_iterator P = Params->begin(),
1149 PEnd = Params->end();
1150 P != PEnd; ++P) {
1151 if (Visit(MakeCXCursor(*P, TU)))
1152 return true;
1155 return false;
1158 bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1159 switch (Name.getKind()) {
1160 case TemplateName::Template:
1161 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1163 case TemplateName::OverloadedTemplate:
1164 // Visit the overloaded template set.
1165 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1166 return true;
1168 return false;
1170 case TemplateName::DependentTemplate:
1171 // FIXME: Visit nested-name-specifier.
1172 return false;
1174 case TemplateName::QualifiedTemplate:
1175 // FIXME: Visit nested-name-specifier.
1176 return Visit(MakeCursorTemplateRef(
1177 Name.getAsQualifiedTemplateName()->getDecl(),
1178 Loc, TU));
1181 return false;
1184 bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1185 switch (TAL.getArgument().getKind()) {
1186 case TemplateArgument::Null:
1187 case TemplateArgument::Integral:
1188 return false;
1190 case TemplateArgument::Pack:
1191 // FIXME: Implement when variadic templates come along.
1192 return false;
1194 case TemplateArgument::Type:
1195 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1196 return Visit(TSInfo->getTypeLoc());
1197 return false;
1199 case TemplateArgument::Declaration:
1200 if (Expr *E = TAL.getSourceDeclExpression())
1201 return Visit(MakeCXCursor(E, StmtParent, TU));
1202 return false;
1204 case TemplateArgument::Expression:
1205 if (Expr *E = TAL.getSourceExpression())
1206 return Visit(MakeCXCursor(E, StmtParent, TU));
1207 return false;
1209 case TemplateArgument::Template:
1210 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1211 TAL.getTemplateNameLoc());
1214 return false;
1217 bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1218 return VisitDeclContext(D);
1221 bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1222 return Visit(TL.getUnqualifiedLoc());
1225 bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1226 ASTContext &Context = TU->getASTContext();
1228 // Some builtin types (such as Objective-C's "id", "sel", and
1229 // "Class") have associated declarations. Create cursors for those.
1230 QualType VisitType;
1231 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
1232 case BuiltinType::Void:
1233 case BuiltinType::Bool:
1234 case BuiltinType::Char_U:
1235 case BuiltinType::UChar:
1236 case BuiltinType::Char16:
1237 case BuiltinType::Char32:
1238 case BuiltinType::UShort:
1239 case BuiltinType::UInt:
1240 case BuiltinType::ULong:
1241 case BuiltinType::ULongLong:
1242 case BuiltinType::UInt128:
1243 case BuiltinType::Char_S:
1244 case BuiltinType::SChar:
1245 case BuiltinType::WChar:
1246 case BuiltinType::Short:
1247 case BuiltinType::Int:
1248 case BuiltinType::Long:
1249 case BuiltinType::LongLong:
1250 case BuiltinType::Int128:
1251 case BuiltinType::Float:
1252 case BuiltinType::Double:
1253 case BuiltinType::LongDouble:
1254 case BuiltinType::NullPtr:
1255 case BuiltinType::Overload:
1256 case BuiltinType::Dependent:
1257 break;
1259 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
1260 break;
1262 case BuiltinType::ObjCId:
1263 VisitType = Context.getObjCIdType();
1264 break;
1266 case BuiltinType::ObjCClass:
1267 VisitType = Context.getObjCClassType();
1268 break;
1270 case BuiltinType::ObjCSel:
1271 VisitType = Context.getObjCSelType();
1272 break;
1275 if (!VisitType.isNull()) {
1276 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1277 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1278 TU));
1281 return false;
1284 bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1285 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1288 bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1289 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1292 bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1293 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1296 bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1297 // FIXME: We can't visit the template type parameter, because there's
1298 // no context information with which we can match up the depth/index in the
1299 // type to the appropriate
1300 return false;
1303 bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1304 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1305 return true;
1307 return false;
1310 bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1311 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1312 return true;
1314 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1315 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1316 TU)))
1317 return true;
1320 return false;
1323 bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1324 return Visit(TL.getPointeeLoc());
1327 bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1328 return Visit(TL.getPointeeLoc());
1331 bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1332 return Visit(TL.getPointeeLoc());
1335 bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1336 return Visit(TL.getPointeeLoc());
1339 bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1340 return Visit(TL.getPointeeLoc());
1343 bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1344 return Visit(TL.getPointeeLoc());
1347 bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1348 bool SkipResultType) {
1349 if (!SkipResultType && Visit(TL.getResultLoc()))
1350 return true;
1352 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1353 if (Decl *D = TL.getArg(I))
1354 if (Visit(MakeCXCursor(D, TU)))
1355 return true;
1357 return false;
1360 bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1361 if (Visit(TL.getElementLoc()))
1362 return true;
1364 if (Expr *Size = TL.getSizeExpr())
1365 return Visit(MakeCXCursor(Size, StmtParent, TU));
1367 return false;
1370 bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1371 TemplateSpecializationTypeLoc TL) {
1372 // Visit the template name.
1373 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1374 TL.getTemplateNameLoc()))
1375 return true;
1377 // Visit the template arguments.
1378 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1379 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1380 return true;
1382 return false;
1385 bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1386 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1389 bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1390 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1391 return Visit(TSInfo->getTypeLoc());
1393 return false;
1396 bool CursorVisitor::VisitStmt(Stmt *S) {
1397 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1398 Child != ChildEnd; ++Child) {
1399 if (Stmt *C = *Child)
1400 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1401 return true;
1404 return false;
1407 bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1408 // Specially handle CaseStmts because they can be nested, e.g.:
1410 // case 1:
1411 // case 2:
1413 // In this case the second CaseStmt is the child of the first. Walking
1414 // these recursively can blow out the stack.
1415 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1416 while (true) {
1417 // Set the Parent field to Cursor, then back to its old value once we're
1418 // done.
1419 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1421 if (Stmt *LHS = S->getLHS())
1422 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1423 return true;
1424 if (Stmt *RHS = S->getRHS())
1425 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1426 return true;
1427 if (Stmt *SubStmt = S->getSubStmt()) {
1428 if (!isa<CaseStmt>(SubStmt))
1429 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1431 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1432 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1433 Cursor = MakeCXCursor(CS, StmtParent, TU);
1434 if (RegionOfInterest.isValid()) {
1435 SourceRange Range = CS->getSourceRange();
1436 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1437 return false;
1440 switch (Visitor(Cursor, Parent, ClientData)) {
1441 case CXChildVisit_Break: return true;
1442 case CXChildVisit_Continue: return false;
1443 case CXChildVisit_Recurse:
1444 // Perform tail-recursion manually.
1445 S = CS;
1446 continue;
1449 return false;
1453 bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
1454 bool isFirst = true;
1455 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1456 D != DEnd; ++D) {
1457 if (*D && Visit(MakeCXCursor(*D, TU, isFirst)))
1458 return true;
1459 isFirst = false;
1462 return false;
1465 bool CursorVisitor::VisitGotoStmt(GotoStmt *S) {
1466 return Visit(MakeCursorLabelRef(S->getLabel(), S->getLabelLoc(), TU));
1469 bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1470 if (VarDecl *Var = S->getConditionVariable()) {
1471 if (Visit(MakeCXCursor(Var, TU)))
1472 return true;
1475 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1476 return true;
1477 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1478 return true;
1479 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1480 return true;
1482 return false;
1485 bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1486 if (VarDecl *Var = S->getConditionVariable()) {
1487 if (Visit(MakeCXCursor(Var, TU)))
1488 return true;
1491 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1492 return true;
1493 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1494 return true;
1496 return false;
1499 bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1500 if (VarDecl *Var = S->getConditionVariable()) {
1501 if (Visit(MakeCXCursor(Var, TU)))
1502 return true;
1505 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1506 return true;
1507 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1508 return true;
1510 return false;
1513 bool CursorVisitor::VisitForStmt(ForStmt *S) {
1514 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1515 return true;
1516 if (VarDecl *Var = S->getConditionVariable()) {
1517 if (Visit(MakeCXCursor(Var, TU)))
1518 return true;
1521 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1522 return true;
1523 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1524 return true;
1525 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1526 return true;
1528 return false;
1531 bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1532 // Visit nested-name-specifier, if present.
1533 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1534 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1535 return true;
1537 // Visit declaration name.
1538 if (VisitDeclarationNameInfo(E->getNameInfo()))
1539 return true;
1541 // Visit explicitly-specified template arguments.
1542 if (E->hasExplicitTemplateArgs()) {
1543 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1544 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1545 *ArgEnd = Arg + Args.NumTemplateArgs;
1546 Arg != ArgEnd; ++Arg)
1547 if (VisitTemplateArgumentLoc(*Arg))
1548 return true;
1551 return false;
1554 bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1555 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1556 return true;
1558 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1559 return true;
1561 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1562 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1563 return true;
1565 return false;
1568 bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1569 if (D->isDefinition()) {
1570 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1571 E = D->bases_end(); I != E; ++I) {
1572 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1573 return true;
1577 return VisitTagDecl(D);
1581 bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1582 return Visit(B->getBlockDecl());
1585 bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1586 // Visit the type into which we're computing an offset.
1587 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1588 return true;
1590 // Visit the components of the offsetof expression.
1591 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1592 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1593 const OffsetOfNode &Node = E->getComponent(I);
1594 switch (Node.getKind()) {
1595 case OffsetOfNode::Array:
1596 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1597 StmtParent, TU)))
1598 return true;
1599 break;
1601 case OffsetOfNode::Field:
1602 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1603 TU)))
1604 return true;
1605 break;
1607 case OffsetOfNode::Identifier:
1608 case OffsetOfNode::Base:
1609 continue;
1613 return false;
1616 bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1617 if (E->isArgumentType()) {
1618 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1619 return Visit(TSInfo->getTypeLoc());
1621 return false;
1624 return VisitExpr(E);
1627 bool CursorVisitor::VisitMemberExpr(MemberExpr *E) {
1628 // Visit the base expression.
1629 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1630 return true;
1632 // Visit the nested-name-specifier
1633 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1634 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1635 return true;
1637 // Visit the declaration name.
1638 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1639 return true;
1641 // Visit the explicitly-specified template arguments, if any.
1642 if (E->hasExplicitTemplateArgs()) {
1643 for (const TemplateArgumentLoc *Arg = E->getTemplateArgs(),
1644 *ArgEnd = Arg + E->getNumTemplateArgs();
1645 Arg != ArgEnd;
1646 ++Arg) {
1647 if (VisitTemplateArgumentLoc(*Arg))
1648 return true;
1652 return false;
1655 bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1656 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1657 if (Visit(TSInfo->getTypeLoc()))
1658 return true;
1660 return VisitCastExpr(E);
1663 bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1664 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1665 if (Visit(TSInfo->getTypeLoc()))
1666 return true;
1668 return VisitExpr(E);
1671 bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1672 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1675 bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1676 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1677 Visit(E->getArgTInfo2()->getTypeLoc());
1680 bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1681 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1682 return true;
1684 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1687 bool CursorVisitor::VisitInitListExpr(InitListExpr *E) {
1688 // We care about the syntactic form of the initializer list, only.
1689 if (InitListExpr *Syntactic = E->getSyntacticForm())
1690 return VisitExpr(Syntactic);
1692 return VisitExpr(E);
1695 bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1696 // Visit the designators.
1697 typedef DesignatedInitExpr::Designator Designator;
1698 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1699 DEnd = E->designators_end();
1700 D != DEnd; ++D) {
1701 if (D->isFieldDesignator()) {
1702 if (FieldDecl *Field = D->getField())
1703 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1704 return true;
1706 continue;
1709 if (D->isArrayDesignator()) {
1710 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1711 return true;
1713 continue;
1716 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1717 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1718 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1719 return true;
1722 // Visit the initializer value itself.
1723 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1726 bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1727 if (E->isTypeOperand()) {
1728 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1729 return Visit(TSInfo->getTypeLoc());
1731 return false;
1734 return VisitExpr(E);
1737 bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1738 if (E->isTypeOperand()) {
1739 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1740 return Visit(TSInfo->getTypeLoc());
1742 return false;
1745 return VisitExpr(E);
1748 bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1749 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1750 return Visit(TSInfo->getTypeLoc());
1752 return VisitExpr(E);
1755 bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1756 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1757 return Visit(TSInfo->getTypeLoc());
1759 return false;
1762 bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1763 // Visit placement arguments.
1764 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1765 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1766 return true;
1768 // Visit the allocated type.
1769 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1770 if (Visit(TSInfo->getTypeLoc()))
1771 return true;
1773 // Visit the array size, if any.
1774 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1775 return true;
1777 // Visit the initializer or constructor arguments.
1778 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1779 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1780 return true;
1782 return false;
1785 bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1786 // Visit base expression.
1787 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1788 return true;
1790 // Visit the nested-name-specifier.
1791 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1792 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1793 return true;
1795 // Visit the scope type that looks disturbingly like the nested-name-specifier
1796 // but isn't.
1797 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1798 if (Visit(TSInfo->getTypeLoc()))
1799 return true;
1801 // Visit the name of the type being destroyed.
1802 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1803 if (Visit(TSInfo->getTypeLoc()))
1804 return true;
1806 return false;
1809 bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1810 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1813 bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
1814 // Visit the nested-name-specifier.
1815 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1816 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1817 return true;
1819 // Visit the declaration name.
1820 if (VisitDeclarationNameInfo(E->getNameInfo()))
1821 return true;
1823 // Visit the overloaded declaration reference.
1824 if (Visit(MakeCursorOverloadedDeclRef(E, TU)))
1825 return true;
1827 // Visit the explicitly-specified template arguments.
1828 if (const ExplicitTemplateArgumentList *ArgList
1829 = E->getOptionalExplicitTemplateArgs()) {
1830 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1831 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1832 Arg != ArgEnd; ++Arg) {
1833 if (VisitTemplateArgumentLoc(*Arg))
1834 return true;
1838 return false;
1841 bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1842 DependentScopeDeclRefExpr *E) {
1843 // Visit the nested-name-specifier.
1844 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1845 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1846 return true;
1848 // Visit the declaration name.
1849 if (VisitDeclarationNameInfo(E->getNameInfo()))
1850 return true;
1852 // Visit the explicitly-specified template arguments.
1853 if (const ExplicitTemplateArgumentList *ArgList
1854 = E->getOptionalExplicitTemplateArgs()) {
1855 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1856 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1857 Arg != ArgEnd; ++Arg) {
1858 if (VisitTemplateArgumentLoc(*Arg))
1859 return true;
1863 return false;
1866 bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1867 CXXUnresolvedConstructExpr *E) {
1868 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1869 if (Visit(TSInfo->getTypeLoc()))
1870 return true;
1872 return VisitExpr(E);
1875 bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1876 CXXDependentScopeMemberExpr *E) {
1877 // Visit the base expression, if there is one.
1878 if (!E->isImplicitAccess() &&
1879 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1880 return true;
1882 // Visit the nested-name-specifier.
1883 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1884 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1885 return true;
1887 // Visit the declaration name.
1888 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1889 return true;
1891 // Visit the explicitly-specified template arguments.
1892 if (const ExplicitTemplateArgumentList *ArgList
1893 = E->getOptionalExplicitTemplateArgs()) {
1894 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1895 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1896 Arg != ArgEnd; ++Arg) {
1897 if (VisitTemplateArgumentLoc(*Arg))
1898 return true;
1902 return false;
1905 bool CursorVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
1906 // Visit the base expression, if there is one.
1907 if (!E->isImplicitAccess() &&
1908 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1909 return true;
1911 return VisitOverloadExpr(E);
1914 bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
1915 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1916 if (Visit(TSInfo->getTypeLoc()))
1917 return true;
1919 return VisitExpr(E);
1922 bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1923 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1927 bool CursorVisitor::VisitAttributes(Decl *D) {
1928 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1929 i != e; ++i)
1930 if (Visit(MakeCXCursor(*i, D, TU)))
1931 return true;
1933 return false;
1936 static llvm::sys::Mutex EnableMultithreadingMutex;
1937 static bool EnabledMultithreading;
1939 extern "C" {
1940 CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1941 int displayDiagnostics) {
1942 // Disable pretty stack trace functionality, which will otherwise be a very
1943 // poor citizen of the world and set up all sorts of signal handlers.
1944 llvm::DisablePrettyStackTrace = true;
1946 // We use crash recovery to make some of our APIs more reliable, implicitly
1947 // enable it.
1948 llvm::CrashRecoveryContext::Enable();
1950 // Enable support for multithreading in LLVM.
1952 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
1953 if (!EnabledMultithreading) {
1954 llvm::llvm_start_multithreaded();
1955 EnabledMultithreading = true;
1959 CIndexer *CIdxr = new CIndexer();
1960 if (excludeDeclarationsFromPCH)
1961 CIdxr->setOnlyLocalDecls();
1962 if (displayDiagnostics)
1963 CIdxr->setDisplayDiagnostics();
1964 return CIdxr;
1967 void clang_disposeIndex(CXIndex CIdx) {
1968 if (CIdx)
1969 delete static_cast<CIndexer *>(CIdx);
1972 CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
1973 const char *ast_filename) {
1974 if (!CIdx)
1975 return 0;
1977 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1979 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1980 return ASTUnit::LoadFromASTFile(ast_filename, Diags,
1981 CXXIdx->getOnlyLocalDecls(),
1982 0, 0, true);
1985 unsigned clang_defaultEditingTranslationUnitOptions() {
1986 return CXTranslationUnit_PrecompiledPreamble |
1987 CXTranslationUnit_CacheCompletionResults |
1988 CXTranslationUnit_CXXPrecompiledPreamble;
1991 CXTranslationUnit
1992 clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1993 const char *source_filename,
1994 int num_command_line_args,
1995 const char * const *command_line_args,
1996 unsigned num_unsaved_files,
1997 struct CXUnsavedFile *unsaved_files) {
1998 return clang_parseTranslationUnit(CIdx, source_filename,
1999 command_line_args, num_command_line_args,
2000 unsaved_files, num_unsaved_files,
2001 CXTranslationUnit_DetailedPreprocessingRecord);
2004 struct ParseTranslationUnitInfo {
2005 CXIndex CIdx;
2006 const char *source_filename;
2007 const char *const *command_line_args;
2008 int num_command_line_args;
2009 struct CXUnsavedFile *unsaved_files;
2010 unsigned num_unsaved_files;
2011 unsigned options;
2012 CXTranslationUnit result;
2014 static void clang_parseTranslationUnit_Impl(void *UserData) {
2015 ParseTranslationUnitInfo *PTUI =
2016 static_cast<ParseTranslationUnitInfo*>(UserData);
2017 CXIndex CIdx = PTUI->CIdx;
2018 const char *source_filename = PTUI->source_filename;
2019 const char * const *command_line_args = PTUI->command_line_args;
2020 int num_command_line_args = PTUI->num_command_line_args;
2021 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2022 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2023 unsigned options = PTUI->options;
2024 PTUI->result = 0;
2026 if (!CIdx)
2027 return;
2029 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2031 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
2032 bool CompleteTranslationUnit
2033 = ((options & CXTranslationUnit_Incomplete) == 0);
2034 bool CacheCodeCompetionResults
2035 = options & CXTranslationUnit_CacheCompletionResults;
2036 bool CXXPrecompilePreamble
2037 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2038 bool CXXChainedPCH
2039 = options & CXTranslationUnit_CXXChainedPCH;
2041 // Configure the diagnostics.
2042 DiagnosticOptions DiagOpts;
2043 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2044 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
2046 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2047 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2048 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2049 const llvm::MemoryBuffer *Buffer
2050 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2051 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2052 Buffer));
2055 llvm::SmallVector<const char *, 16> Args;
2057 // The 'source_filename' argument is optional. If the caller does not
2058 // specify it then it is assumed that the source file is specified
2059 // in the actual argument list.
2060 if (source_filename)
2061 Args.push_back(source_filename);
2063 // Since the Clang C library is primarily used by batch tools dealing with
2064 // (often very broken) source code, where spell-checking can have a
2065 // significant negative impact on performance (particularly when
2066 // precompiled headers are involved), we disable it by default.
2067 // Only do this if we haven't found a spell-checking-related argument.
2068 bool FoundSpellCheckingArgument = false;
2069 for (int I = 0; I != num_command_line_args; ++I) {
2070 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2071 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2072 FoundSpellCheckingArgument = true;
2073 break;
2076 if (!FoundSpellCheckingArgument)
2077 Args.push_back("-fno-spell-checking");
2079 Args.insert(Args.end(), command_line_args,
2080 command_line_args + num_command_line_args);
2082 // Do we need the detailed preprocessing record?
2083 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
2084 Args.push_back("-Xclang");
2085 Args.push_back("-detailed-preprocessing-record");
2088 unsigned NumErrors = Diags->getNumErrors();
2089 llvm::OwningPtr<ASTUnit> Unit(
2090 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2091 Diags,
2092 CXXIdx->getClangResourcesPath(),
2093 CXXIdx->getOnlyLocalDecls(),
2094 RemappedFiles.data(),
2095 RemappedFiles.size(),
2096 /*CaptureDiagnostics=*/true,
2097 PrecompilePreamble,
2098 CompleteTranslationUnit,
2099 CacheCodeCompetionResults,
2100 CXXPrecompilePreamble,
2101 CXXChainedPCH));
2103 if (NumErrors != Diags->getNumErrors()) {
2104 // Make sure to check that 'Unit' is non-NULL.
2105 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2106 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2107 DEnd = Unit->stored_diag_end();
2108 D != DEnd; ++D) {
2109 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2110 CXString Msg = clang_formatDiagnostic(&Diag,
2111 clang_defaultDiagnosticDisplayOptions());
2112 fprintf(stderr, "%s\n", clang_getCString(Msg));
2113 clang_disposeString(Msg);
2115 #ifdef LLVM_ON_WIN32
2116 // On Windows, force a flush, since there may be multiple copies of
2117 // stderr and stdout in the file system, all with different buffers
2118 // but writing to the same device.
2119 fflush(stderr);
2120 #endif
2124 PTUI->result = Unit.take();
2126 CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2127 const char *source_filename,
2128 const char * const *command_line_args,
2129 int num_command_line_args,
2130 struct CXUnsavedFile *unsaved_files,
2131 unsigned num_unsaved_files,
2132 unsigned options) {
2133 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2134 num_command_line_args, unsaved_files, num_unsaved_files,
2135 options, 0 };
2136 llvm::CrashRecoveryContext CRC;
2138 if (!CRC.RunSafely(clang_parseTranslationUnit_Impl, &PTUI)) {
2139 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2140 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2141 fprintf(stderr, " 'command_line_args' : [");
2142 for (int i = 0; i != num_command_line_args; ++i) {
2143 if (i)
2144 fprintf(stderr, ", ");
2145 fprintf(stderr, "'%s'", command_line_args[i]);
2147 fprintf(stderr, "],\n");
2148 fprintf(stderr, " 'unsaved_files' : [");
2149 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2150 if (i)
2151 fprintf(stderr, ", ");
2152 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2153 unsaved_files[i].Length);
2155 fprintf(stderr, "],\n");
2156 fprintf(stderr, " 'options' : %d,\n", options);
2157 fprintf(stderr, "}\n");
2159 return 0;
2162 return PTUI.result;
2165 unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2166 return CXSaveTranslationUnit_None;
2169 int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2170 unsigned options) {
2171 if (!TU)
2172 return 1;
2174 return static_cast<ASTUnit *>(TU)->Save(FileName);
2177 void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
2178 if (CTUnit) {
2179 // If the translation unit has been marked as unsafe to free, just discard
2180 // it.
2181 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2182 return;
2184 delete static_cast<ASTUnit *>(CTUnit);
2188 unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2189 return CXReparse_None;
2192 struct ReparseTranslationUnitInfo {
2193 CXTranslationUnit TU;
2194 unsigned num_unsaved_files;
2195 struct CXUnsavedFile *unsaved_files;
2196 unsigned options;
2197 int result;
2200 static void clang_reparseTranslationUnit_Impl(void *UserData) {
2201 ReparseTranslationUnitInfo *RTUI =
2202 static_cast<ReparseTranslationUnitInfo*>(UserData);
2203 CXTranslationUnit TU = RTUI->TU;
2204 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2205 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2206 unsigned options = RTUI->options;
2207 (void) options;
2208 RTUI->result = 1;
2210 if (!TU)
2211 return;
2213 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2214 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2216 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2217 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2218 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2219 const llvm::MemoryBuffer *Buffer
2220 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2221 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2222 Buffer));
2225 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2226 RTUI->result = 0;
2229 int clang_reparseTranslationUnit(CXTranslationUnit TU,
2230 unsigned num_unsaved_files,
2231 struct CXUnsavedFile *unsaved_files,
2232 unsigned options) {
2233 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2234 options, 0 };
2235 llvm::CrashRecoveryContext CRC;
2237 if (!CRC.RunSafely(clang_reparseTranslationUnit_Impl, &RTUI)) {
2238 fprintf(stderr, "libclang: crash detected during reparsing\n");
2239 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2240 return 1;
2244 return RTUI.result;
2248 CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
2249 if (!CTUnit)
2250 return createCXString("");
2252 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
2253 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
2256 CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
2257 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
2258 return Result;
2261 } // end: extern "C"
2263 //===----------------------------------------------------------------------===//
2264 // CXSourceLocation and CXSourceRange Operations.
2265 //===----------------------------------------------------------------------===//
2267 extern "C" {
2268 CXSourceLocation clang_getNullLocation() {
2269 CXSourceLocation Result = { { 0, 0 }, 0 };
2270 return Result;
2273 unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
2274 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2275 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2276 loc1.int_data == loc2.int_data);
2279 CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2280 CXFile file,
2281 unsigned line,
2282 unsigned column) {
2283 if (!tu || !file)
2284 return clang_getNullLocation();
2286 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2287 SourceLocation SLoc
2288 = CXXUnit->getSourceManager().getLocation(
2289 static_cast<const FileEntry *>(file),
2290 line, column);
2291 if (SLoc.isInvalid()) return clang_getNullLocation();
2293 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2296 CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2297 CXFile file,
2298 unsigned offset) {
2299 if (!tu || !file)
2300 return clang_getNullLocation();
2302 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2303 SourceLocation Start
2304 = CXXUnit->getSourceManager().getLocation(
2305 static_cast<const FileEntry *>(file),
2306 1, 1);
2307 if (Start.isInvalid()) return clang_getNullLocation();
2309 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2311 if (SLoc.isInvalid()) return clang_getNullLocation();
2313 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2316 CXSourceRange clang_getNullRange() {
2317 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2318 return Result;
2321 CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2322 if (begin.ptr_data[0] != end.ptr_data[0] ||
2323 begin.ptr_data[1] != end.ptr_data[1])
2324 return clang_getNullRange();
2326 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
2327 begin.int_data, end.int_data };
2328 return Result;
2331 void clang_getInstantiationLocation(CXSourceLocation location,
2332 CXFile *file,
2333 unsigned *line,
2334 unsigned *column,
2335 unsigned *offset) {
2336 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2338 if (!location.ptr_data[0] || Loc.isInvalid()) {
2339 if (file)
2340 *file = 0;
2341 if (line)
2342 *line = 0;
2343 if (column)
2344 *column = 0;
2345 if (offset)
2346 *offset = 0;
2347 return;
2350 const SourceManager &SM =
2351 *static_cast<const SourceManager*>(location.ptr_data[0]);
2352 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
2354 if (file)
2355 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2356 if (line)
2357 *line = SM.getInstantiationLineNumber(InstLoc);
2358 if (column)
2359 *column = SM.getInstantiationColumnNumber(InstLoc);
2360 if (offset)
2361 *offset = SM.getDecomposedLoc(InstLoc).second;
2364 CXSourceLocation clang_getRangeStart(CXSourceRange range) {
2365 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
2366 range.begin_int_data };
2367 return Result;
2370 CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
2371 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
2372 range.end_int_data };
2373 return Result;
2376 } // end: extern "C"
2378 //===----------------------------------------------------------------------===//
2379 // CXFile Operations.
2380 //===----------------------------------------------------------------------===//
2382 extern "C" {
2383 CXString clang_getFileName(CXFile SFile) {
2384 if (!SFile)
2385 return createCXString(NULL);
2387 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2388 return createCXString(FEnt->getName());
2391 time_t clang_getFileTime(CXFile SFile) {
2392 if (!SFile)
2393 return 0;
2395 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2396 return FEnt->getModificationTime();
2399 CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2400 if (!tu)
2401 return 0;
2403 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2405 FileManager &FMgr = CXXUnit->getFileManager();
2406 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
2407 return const_cast<FileEntry *>(File);
2410 } // end: extern "C"
2412 //===----------------------------------------------------------------------===//
2413 // CXCursor Operations.
2414 //===----------------------------------------------------------------------===//
2416 static Decl *getDeclFromExpr(Stmt *E) {
2417 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2418 return getDeclFromExpr(CE->getSubExpr());
2420 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2421 return RefExpr->getDecl();
2422 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2423 return RefExpr->getDecl();
2424 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2425 return ME->getMemberDecl();
2426 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2427 return RE->getDecl();
2428 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2429 return PRE->getProperty();
2431 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2432 return getDeclFromExpr(CE->getCallee());
2433 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2434 return OME->getMethodDecl();
2436 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2437 return PE->getProtocol();
2439 return 0;
2442 static SourceLocation getLocationFromExpr(Expr *E) {
2443 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2444 return /*FIXME:*/Msg->getLeftLoc();
2445 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2446 return DRE->getLocation();
2447 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2448 return RefExpr->getLocation();
2449 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2450 return Member->getMemberLoc();
2451 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2452 return Ivar->getLocation();
2453 return E->getLocStart();
2456 extern "C" {
2458 unsigned clang_visitChildren(CXCursor parent,
2459 CXCursorVisitor visitor,
2460 CXClientData client_data) {
2461 ASTUnit *CXXUnit = getCursorASTUnit(parent);
2463 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2464 CXXUnit->getMaxPCHLevel());
2465 return CursorVis.VisitChildren(parent);
2468 static CXString getDeclSpelling(Decl *D) {
2469 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2470 if (!ND)
2471 return createCXString("");
2473 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
2474 return createCXString(OMD->getSelector().getAsString());
2476 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2477 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2478 // and returns different names. NamedDecl returns the class name and
2479 // ObjCCategoryImplDecl returns the category name.
2480 return createCXString(CIMP->getIdentifier()->getNameStart());
2482 if (isa<UsingDirectiveDecl>(D))
2483 return createCXString("");
2485 llvm::SmallString<1024> S;
2486 llvm::raw_svector_ostream os(S);
2487 ND->printName(os);
2489 return createCXString(os.str());
2492 CXString clang_getCursorSpelling(CXCursor C) {
2493 if (clang_isTranslationUnit(C.kind))
2494 return clang_getTranslationUnitSpelling(C.data[2]);
2496 if (clang_isReference(C.kind)) {
2497 switch (C.kind) {
2498 case CXCursor_ObjCSuperClassRef: {
2499 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
2500 return createCXString(Super->getIdentifier()->getNameStart());
2502 case CXCursor_ObjCClassRef: {
2503 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
2504 return createCXString(Class->getIdentifier()->getNameStart());
2506 case CXCursor_ObjCProtocolRef: {
2507 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
2508 assert(OID && "getCursorSpelling(): Missing protocol decl");
2509 return createCXString(OID->getIdentifier()->getNameStart());
2511 case CXCursor_CXXBaseSpecifier: {
2512 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2513 return createCXString(B->getType().getAsString());
2515 case CXCursor_TypeRef: {
2516 TypeDecl *Type = getCursorTypeRef(C).first;
2517 assert(Type && "Missing type decl");
2519 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2520 getAsString());
2522 case CXCursor_TemplateRef: {
2523 TemplateDecl *Template = getCursorTemplateRef(C).first;
2524 assert(Template && "Missing template decl");
2526 return createCXString(Template->getNameAsString());
2529 case CXCursor_NamespaceRef: {
2530 NamedDecl *NS = getCursorNamespaceRef(C).first;
2531 assert(NS && "Missing namespace decl");
2533 return createCXString(NS->getNameAsString());
2536 case CXCursor_MemberRef: {
2537 FieldDecl *Field = getCursorMemberRef(C).first;
2538 assert(Field && "Missing member decl");
2540 return createCXString(Field->getNameAsString());
2543 case CXCursor_LabelRef: {
2544 LabelStmt *Label = getCursorLabelRef(C).first;
2545 assert(Label && "Missing label");
2547 return createCXString(Label->getID()->getName());
2550 case CXCursor_OverloadedDeclRef: {
2551 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2552 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2553 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2554 return createCXString(ND->getNameAsString());
2555 return createCXString("");
2557 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2558 return createCXString(E->getName().getAsString());
2559 OverloadedTemplateStorage *Ovl
2560 = Storage.get<OverloadedTemplateStorage*>();
2561 if (Ovl->size() == 0)
2562 return createCXString("");
2563 return createCXString((*Ovl->begin())->getNameAsString());
2566 default:
2567 return createCXString("<not implemented>");
2571 if (clang_isExpression(C.kind)) {
2572 Decl *D = getDeclFromExpr(getCursorExpr(C));
2573 if (D)
2574 return getDeclSpelling(D);
2575 return createCXString("");
2578 if (clang_isStatement(C.kind)) {
2579 Stmt *S = getCursorStmt(C);
2580 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2581 return createCXString(Label->getID()->getName());
2583 return createCXString("");
2586 if (C.kind == CXCursor_MacroInstantiation)
2587 return createCXString(getCursorMacroInstantiation(C)->getName()
2588 ->getNameStart());
2590 if (C.kind == CXCursor_MacroDefinition)
2591 return createCXString(getCursorMacroDefinition(C)->getName()
2592 ->getNameStart());
2594 if (C.kind == CXCursor_InclusionDirective)
2595 return createCXString(getCursorInclusionDirective(C)->getFileName());
2597 if (clang_isDeclaration(C.kind))
2598 return getDeclSpelling(getCursorDecl(C));
2600 return createCXString("");
2603 CXString clang_getCursorDisplayName(CXCursor C) {
2604 if (!clang_isDeclaration(C.kind))
2605 return clang_getCursorSpelling(C);
2607 Decl *D = getCursorDecl(C);
2608 if (!D)
2609 return createCXString("");
2611 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2612 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2613 D = FunTmpl->getTemplatedDecl();
2615 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2616 llvm::SmallString<64> Str;
2617 llvm::raw_svector_ostream OS(Str);
2618 OS << Function->getNameAsString();
2619 if (Function->getPrimaryTemplate())
2620 OS << "<>";
2621 OS << "(";
2622 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2623 if (I)
2624 OS << ", ";
2625 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2628 if (Function->isVariadic()) {
2629 if (Function->getNumParams())
2630 OS << ", ";
2631 OS << "...";
2633 OS << ")";
2634 return createCXString(OS.str());
2637 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2638 llvm::SmallString<64> Str;
2639 llvm::raw_svector_ostream OS(Str);
2640 OS << ClassTemplate->getNameAsString();
2641 OS << "<";
2642 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2643 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2644 if (I)
2645 OS << ", ";
2647 NamedDecl *Param = Params->getParam(I);
2648 if (Param->getIdentifier()) {
2649 OS << Param->getIdentifier()->getName();
2650 continue;
2653 // There is no parameter name, which makes this tricky. Try to come up
2654 // with something useful that isn't too long.
2655 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2656 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2657 else if (NonTypeTemplateParmDecl *NTTP
2658 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2659 OS << NTTP->getType().getAsString(Policy);
2660 else
2661 OS << "template<...> class";
2664 OS << ">";
2665 return createCXString(OS.str());
2668 if (ClassTemplateSpecializationDecl *ClassSpec
2669 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2670 // If the type was explicitly written, use that.
2671 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2672 return createCXString(TSInfo->getType().getAsString(Policy));
2674 llvm::SmallString<64> Str;
2675 llvm::raw_svector_ostream OS(Str);
2676 OS << ClassSpec->getNameAsString();
2677 OS << TemplateSpecializationType::PrintTemplateArgumentList(
2678 ClassSpec->getTemplateArgs().getFlatArgumentList(),
2679 ClassSpec->getTemplateArgs().flat_size(),
2680 Policy);
2681 return createCXString(OS.str());
2684 return clang_getCursorSpelling(C);
2687 CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
2688 switch (Kind) {
2689 case CXCursor_FunctionDecl:
2690 return createCXString("FunctionDecl");
2691 case CXCursor_TypedefDecl:
2692 return createCXString("TypedefDecl");
2693 case CXCursor_EnumDecl:
2694 return createCXString("EnumDecl");
2695 case CXCursor_EnumConstantDecl:
2696 return createCXString("EnumConstantDecl");
2697 case CXCursor_StructDecl:
2698 return createCXString("StructDecl");
2699 case CXCursor_UnionDecl:
2700 return createCXString("UnionDecl");
2701 case CXCursor_ClassDecl:
2702 return createCXString("ClassDecl");
2703 case CXCursor_FieldDecl:
2704 return createCXString("FieldDecl");
2705 case CXCursor_VarDecl:
2706 return createCXString("VarDecl");
2707 case CXCursor_ParmDecl:
2708 return createCXString("ParmDecl");
2709 case CXCursor_ObjCInterfaceDecl:
2710 return createCXString("ObjCInterfaceDecl");
2711 case CXCursor_ObjCCategoryDecl:
2712 return createCXString("ObjCCategoryDecl");
2713 case CXCursor_ObjCProtocolDecl:
2714 return createCXString("ObjCProtocolDecl");
2715 case CXCursor_ObjCPropertyDecl:
2716 return createCXString("ObjCPropertyDecl");
2717 case CXCursor_ObjCIvarDecl:
2718 return createCXString("ObjCIvarDecl");
2719 case CXCursor_ObjCInstanceMethodDecl:
2720 return createCXString("ObjCInstanceMethodDecl");
2721 case CXCursor_ObjCClassMethodDecl:
2722 return createCXString("ObjCClassMethodDecl");
2723 case CXCursor_ObjCImplementationDecl:
2724 return createCXString("ObjCImplementationDecl");
2725 case CXCursor_ObjCCategoryImplDecl:
2726 return createCXString("ObjCCategoryImplDecl");
2727 case CXCursor_CXXMethod:
2728 return createCXString("CXXMethod");
2729 case CXCursor_UnexposedDecl:
2730 return createCXString("UnexposedDecl");
2731 case CXCursor_ObjCSuperClassRef:
2732 return createCXString("ObjCSuperClassRef");
2733 case CXCursor_ObjCProtocolRef:
2734 return createCXString("ObjCProtocolRef");
2735 case CXCursor_ObjCClassRef:
2736 return createCXString("ObjCClassRef");
2737 case CXCursor_TypeRef:
2738 return createCXString("TypeRef");
2739 case CXCursor_TemplateRef:
2740 return createCXString("TemplateRef");
2741 case CXCursor_NamespaceRef:
2742 return createCXString("NamespaceRef");
2743 case CXCursor_MemberRef:
2744 return createCXString("MemberRef");
2745 case CXCursor_LabelRef:
2746 return createCXString("LabelRef");
2747 case CXCursor_OverloadedDeclRef:
2748 return createCXString("OverloadedDeclRef");
2749 case CXCursor_UnexposedExpr:
2750 return createCXString("UnexposedExpr");
2751 case CXCursor_BlockExpr:
2752 return createCXString("BlockExpr");
2753 case CXCursor_DeclRefExpr:
2754 return createCXString("DeclRefExpr");
2755 case CXCursor_MemberRefExpr:
2756 return createCXString("MemberRefExpr");
2757 case CXCursor_CallExpr:
2758 return createCXString("CallExpr");
2759 case CXCursor_ObjCMessageExpr:
2760 return createCXString("ObjCMessageExpr");
2761 case CXCursor_UnexposedStmt:
2762 return createCXString("UnexposedStmt");
2763 case CXCursor_LabelStmt:
2764 return createCXString("LabelStmt");
2765 case CXCursor_InvalidFile:
2766 return createCXString("InvalidFile");
2767 case CXCursor_InvalidCode:
2768 return createCXString("InvalidCode");
2769 case CXCursor_NoDeclFound:
2770 return createCXString("NoDeclFound");
2771 case CXCursor_NotImplemented:
2772 return createCXString("NotImplemented");
2773 case CXCursor_TranslationUnit:
2774 return createCXString("TranslationUnit");
2775 case CXCursor_UnexposedAttr:
2776 return createCXString("UnexposedAttr");
2777 case CXCursor_IBActionAttr:
2778 return createCXString("attribute(ibaction)");
2779 case CXCursor_IBOutletAttr:
2780 return createCXString("attribute(iboutlet)");
2781 case CXCursor_IBOutletCollectionAttr:
2782 return createCXString("attribute(iboutletcollection)");
2783 case CXCursor_PreprocessingDirective:
2784 return createCXString("preprocessing directive");
2785 case CXCursor_MacroDefinition:
2786 return createCXString("macro definition");
2787 case CXCursor_MacroInstantiation:
2788 return createCXString("macro instantiation");
2789 case CXCursor_InclusionDirective:
2790 return createCXString("inclusion directive");
2791 case CXCursor_Namespace:
2792 return createCXString("Namespace");
2793 case CXCursor_LinkageSpec:
2794 return createCXString("LinkageSpec");
2795 case CXCursor_CXXBaseSpecifier:
2796 return createCXString("C++ base class specifier");
2797 case CXCursor_Constructor:
2798 return createCXString("CXXConstructor");
2799 case CXCursor_Destructor:
2800 return createCXString("CXXDestructor");
2801 case CXCursor_ConversionFunction:
2802 return createCXString("CXXConversion");
2803 case CXCursor_TemplateTypeParameter:
2804 return createCXString("TemplateTypeParameter");
2805 case CXCursor_NonTypeTemplateParameter:
2806 return createCXString("NonTypeTemplateParameter");
2807 case CXCursor_TemplateTemplateParameter:
2808 return createCXString("TemplateTemplateParameter");
2809 case CXCursor_FunctionTemplate:
2810 return createCXString("FunctionTemplate");
2811 case CXCursor_ClassTemplate:
2812 return createCXString("ClassTemplate");
2813 case CXCursor_ClassTemplatePartialSpecialization:
2814 return createCXString("ClassTemplatePartialSpecialization");
2815 case CXCursor_NamespaceAlias:
2816 return createCXString("NamespaceAlias");
2817 case CXCursor_UsingDirective:
2818 return createCXString("UsingDirective");
2819 case CXCursor_UsingDeclaration:
2820 return createCXString("UsingDeclaration");
2823 llvm_unreachable("Unhandled CXCursorKind");
2824 return createCXString(NULL);
2827 enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2828 CXCursor parent,
2829 CXClientData client_data) {
2830 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
2831 *BestCursor = cursor;
2832 return CXChildVisit_Recurse;
2835 CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2836 if (!TU)
2837 return clang_getNullCursor();
2839 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2840 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2842 // Translate the given source location to make it point at the beginning of
2843 // the token under the cursor.
2844 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
2846 // Guard against an invalid SourceLocation, or we may assert in one
2847 // of the following calls.
2848 if (SLoc.isInvalid())
2849 return clang_getNullCursor();
2851 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2852 CXXUnit->getASTContext().getLangOptions());
2854 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
2855 if (SLoc.isValid()) {
2856 // FIXME: Would be great to have a "hint" cursor, then walk from that
2857 // hint cursor upward until we find a cursor whose source range encloses
2858 // the region of interest, rather than starting from the translation unit.
2859 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
2860 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
2861 Decl::MaxPCHLevel, SourceLocation(SLoc));
2862 CursorVis.VisitChildren(Parent);
2864 return Result;
2867 CXCursor clang_getNullCursor(void) {
2868 return MakeCXCursorInvalid(CXCursor_InvalidFile);
2871 unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
2872 return X == Y;
2875 unsigned clang_isInvalid(enum CXCursorKind K) {
2876 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
2879 unsigned clang_isDeclaration(enum CXCursorKind K) {
2880 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
2883 unsigned clang_isReference(enum CXCursorKind K) {
2884 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
2887 unsigned clang_isExpression(enum CXCursorKind K) {
2888 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
2891 unsigned clang_isStatement(enum CXCursorKind K) {
2892 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
2895 unsigned clang_isTranslationUnit(enum CXCursorKind K) {
2896 return K == CXCursor_TranslationUnit;
2899 unsigned clang_isPreprocessing(enum CXCursorKind K) {
2900 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
2903 unsigned clang_isUnexposed(enum CXCursorKind K) {
2904 switch (K) {
2905 case CXCursor_UnexposedDecl:
2906 case CXCursor_UnexposedExpr:
2907 case CXCursor_UnexposedStmt:
2908 case CXCursor_UnexposedAttr:
2909 return true;
2910 default:
2911 return false;
2915 CXCursorKind clang_getCursorKind(CXCursor C) {
2916 return C.kind;
2919 CXSourceLocation clang_getCursorLocation(CXCursor C) {
2920 if (clang_isReference(C.kind)) {
2921 switch (C.kind) {
2922 case CXCursor_ObjCSuperClassRef: {
2923 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2924 = getCursorObjCSuperClassRef(C);
2925 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2928 case CXCursor_ObjCProtocolRef: {
2929 std::pair<ObjCProtocolDecl *, SourceLocation> P
2930 = getCursorObjCProtocolRef(C);
2931 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2934 case CXCursor_ObjCClassRef: {
2935 std::pair<ObjCInterfaceDecl *, SourceLocation> P
2936 = getCursorObjCClassRef(C);
2937 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2940 case CXCursor_TypeRef: {
2941 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
2942 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2945 case CXCursor_TemplateRef: {
2946 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
2947 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2950 case CXCursor_NamespaceRef: {
2951 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
2952 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2955 case CXCursor_MemberRef: {
2956 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
2957 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
2960 case CXCursor_CXXBaseSpecifier: {
2961 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
2962 if (!BaseSpec)
2963 return clang_getNullLocation();
2965 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
2966 return cxloc::translateSourceLocation(getCursorContext(C),
2967 TSInfo->getTypeLoc().getBeginLoc());
2969 return cxloc::translateSourceLocation(getCursorContext(C),
2970 BaseSpec->getSourceRange().getBegin());
2973 case CXCursor_LabelRef: {
2974 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
2975 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
2978 case CXCursor_OverloadedDeclRef:
2979 return cxloc::translateSourceLocation(getCursorContext(C),
2980 getCursorOverloadedDeclRef(C).second);
2982 default:
2983 // FIXME: Need a way to enumerate all non-reference cases.
2984 llvm_unreachable("Missed a reference kind");
2988 if (clang_isExpression(C.kind))
2989 return cxloc::translateSourceLocation(getCursorContext(C),
2990 getLocationFromExpr(getCursorExpr(C)));
2992 if (clang_isStatement(C.kind))
2993 return cxloc::translateSourceLocation(getCursorContext(C),
2994 getCursorStmt(C)->getLocStart());
2996 if (C.kind == CXCursor_PreprocessingDirective) {
2997 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
2998 return cxloc::translateSourceLocation(getCursorContext(C), L);
3001 if (C.kind == CXCursor_MacroInstantiation) {
3002 SourceLocation L
3003 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
3004 return cxloc::translateSourceLocation(getCursorContext(C), L);
3007 if (C.kind == CXCursor_MacroDefinition) {
3008 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3009 return cxloc::translateSourceLocation(getCursorContext(C), L);
3012 if (C.kind == CXCursor_InclusionDirective) {
3013 SourceLocation L
3014 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3015 return cxloc::translateSourceLocation(getCursorContext(C), L);
3018 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
3019 return clang_getNullLocation();
3021 Decl *D = getCursorDecl(C);
3022 SourceLocation Loc = D->getLocation();
3023 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3024 Loc = Class->getClassLoc();
3025 // FIXME: Multiple variables declared in a single declaration
3026 // currently lack the information needed to correctly determine their
3027 // ranges when accounting for the type-specifier. We use context
3028 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3029 // and if so, whether it is the first decl.
3030 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3031 if (!cxcursor::isFirstInDeclGroup(C))
3032 Loc = VD->getLocation();
3035 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
3038 } // end extern "C"
3040 static SourceRange getRawCursorExtent(CXCursor C) {
3041 if (clang_isReference(C.kind)) {
3042 switch (C.kind) {
3043 case CXCursor_ObjCSuperClassRef:
3044 return getCursorObjCSuperClassRef(C).second;
3046 case CXCursor_ObjCProtocolRef:
3047 return getCursorObjCProtocolRef(C).second;
3049 case CXCursor_ObjCClassRef:
3050 return getCursorObjCClassRef(C).second;
3052 case CXCursor_TypeRef:
3053 return getCursorTypeRef(C).second;
3055 case CXCursor_TemplateRef:
3056 return getCursorTemplateRef(C).second;
3058 case CXCursor_NamespaceRef:
3059 return getCursorNamespaceRef(C).second;
3061 case CXCursor_MemberRef:
3062 return getCursorMemberRef(C).second;
3064 case CXCursor_CXXBaseSpecifier:
3065 return getCursorCXXBaseSpecifier(C)->getSourceRange();
3067 case CXCursor_LabelRef:
3068 return getCursorLabelRef(C).second;
3070 case CXCursor_OverloadedDeclRef:
3071 return getCursorOverloadedDeclRef(C).second;
3073 default:
3074 // FIXME: Need a way to enumerate all non-reference cases.
3075 llvm_unreachable("Missed a reference kind");
3079 if (clang_isExpression(C.kind))
3080 return getCursorExpr(C)->getSourceRange();
3082 if (clang_isStatement(C.kind))
3083 return getCursorStmt(C)->getSourceRange();
3085 if (C.kind == CXCursor_PreprocessingDirective)
3086 return cxcursor::getCursorPreprocessingDirective(C);
3088 if (C.kind == CXCursor_MacroInstantiation)
3089 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
3091 if (C.kind == CXCursor_MacroDefinition)
3092 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
3094 if (C.kind == CXCursor_InclusionDirective)
3095 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3097 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3098 Decl *D = cxcursor::getCursorDecl(C);
3099 SourceRange R = D->getSourceRange();
3100 // FIXME: Multiple variables declared in a single declaration
3101 // currently lack the information needed to correctly determine their
3102 // ranges when accounting for the type-specifier. We use context
3103 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3104 // and if so, whether it is the first decl.
3105 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3106 if (!cxcursor::isFirstInDeclGroup(C))
3107 R.setBegin(VD->getLocation());
3109 return R;
3111 return SourceRange();}
3113 extern "C" {
3115 CXSourceRange clang_getCursorExtent(CXCursor C) {
3116 SourceRange R = getRawCursorExtent(C);
3117 if (R.isInvalid())
3118 return clang_getNullRange();
3120 return cxloc::translateSourceRange(getCursorContext(C), R);
3123 CXCursor clang_getCursorReferenced(CXCursor C) {
3124 if (clang_isInvalid(C.kind))
3125 return clang_getNullCursor();
3127 ASTUnit *CXXUnit = getCursorASTUnit(C);
3128 if (clang_isDeclaration(C.kind)) {
3129 Decl *D = getCursorDecl(C);
3130 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3131 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3132 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3133 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3134 if (ObjCForwardProtocolDecl *Protocols
3135 = dyn_cast<ObjCForwardProtocolDecl>(D))
3136 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3138 return C;
3141 if (clang_isExpression(C.kind)) {
3142 Expr *E = getCursorExpr(C);
3143 Decl *D = getDeclFromExpr(E);
3144 if (D)
3145 return MakeCXCursor(D, CXXUnit);
3147 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3148 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3150 return clang_getNullCursor();
3153 if (clang_isStatement(C.kind)) {
3154 Stmt *S = getCursorStmt(C);
3155 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3156 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3157 getCursorASTUnit(C));
3159 return clang_getNullCursor();
3162 if (C.kind == CXCursor_MacroInstantiation) {
3163 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3164 return MakeMacroDefinitionCursor(Def, CXXUnit);
3167 if (!clang_isReference(C.kind))
3168 return clang_getNullCursor();
3170 switch (C.kind) {
3171 case CXCursor_ObjCSuperClassRef:
3172 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
3174 case CXCursor_ObjCProtocolRef: {
3175 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
3177 case CXCursor_ObjCClassRef:
3178 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
3180 case CXCursor_TypeRef:
3181 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
3183 case CXCursor_TemplateRef:
3184 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3186 case CXCursor_NamespaceRef:
3187 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3189 case CXCursor_MemberRef:
3190 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3192 case CXCursor_CXXBaseSpecifier: {
3193 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3194 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3195 CXXUnit));
3198 case CXCursor_LabelRef:
3199 // FIXME: We end up faking the "parent" declaration here because we
3200 // don't want to make CXCursor larger.
3201 return MakeCXCursor(getCursorLabelRef(C).first,
3202 CXXUnit->getASTContext().getTranslationUnitDecl(),
3203 CXXUnit);
3205 case CXCursor_OverloadedDeclRef:
3206 return C;
3208 default:
3209 // We would prefer to enumerate all non-reference cursor kinds here.
3210 llvm_unreachable("Unhandled reference cursor kind");
3211 break;
3215 return clang_getNullCursor();
3218 CXCursor clang_getCursorDefinition(CXCursor C) {
3219 if (clang_isInvalid(C.kind))
3220 return clang_getNullCursor();
3222 ASTUnit *CXXUnit = getCursorASTUnit(C);
3224 bool WasReference = false;
3225 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
3226 C = clang_getCursorReferenced(C);
3227 WasReference = true;
3230 if (C.kind == CXCursor_MacroInstantiation)
3231 return clang_getCursorReferenced(C);
3233 if (!clang_isDeclaration(C.kind))
3234 return clang_getNullCursor();
3236 Decl *D = getCursorDecl(C);
3237 if (!D)
3238 return clang_getNullCursor();
3240 switch (D->getKind()) {
3241 // Declaration kinds that don't really separate the notions of
3242 // declaration and definition.
3243 case Decl::Namespace:
3244 case Decl::Typedef:
3245 case Decl::TemplateTypeParm:
3246 case Decl::EnumConstant:
3247 case Decl::Field:
3248 case Decl::ObjCIvar:
3249 case Decl::ObjCAtDefsField:
3250 case Decl::ImplicitParam:
3251 case Decl::ParmVar:
3252 case Decl::NonTypeTemplateParm:
3253 case Decl::TemplateTemplateParm:
3254 case Decl::ObjCCategoryImpl:
3255 case Decl::ObjCImplementation:
3256 case Decl::AccessSpec:
3257 case Decl::LinkageSpec:
3258 case Decl::ObjCPropertyImpl:
3259 case Decl::FileScopeAsm:
3260 case Decl::StaticAssert:
3261 case Decl::Block:
3262 return C;
3264 // Declaration kinds that don't make any sense here, but are
3265 // nonetheless harmless.
3266 case Decl::TranslationUnit:
3267 break;
3269 // Declaration kinds for which the definition is not resolvable.
3270 case Decl::UnresolvedUsingTypename:
3271 case Decl::UnresolvedUsingValue:
3272 break;
3274 case Decl::UsingDirective:
3275 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3276 CXXUnit);
3278 case Decl::NamespaceAlias:
3279 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
3281 case Decl::Enum:
3282 case Decl::Record:
3283 case Decl::CXXRecord:
3284 case Decl::ClassTemplateSpecialization:
3285 case Decl::ClassTemplatePartialSpecialization:
3286 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
3287 return MakeCXCursor(Def, CXXUnit);
3288 return clang_getNullCursor();
3290 case Decl::Function:
3291 case Decl::CXXMethod:
3292 case Decl::CXXConstructor:
3293 case Decl::CXXDestructor:
3294 case Decl::CXXConversion: {
3295 const FunctionDecl *Def = 0;
3296 if (cast<FunctionDecl>(D)->getBody(Def))
3297 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
3298 return clang_getNullCursor();
3301 case Decl::Var: {
3302 // Ask the variable if it has a definition.
3303 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3304 return MakeCXCursor(Def, CXXUnit);
3305 return clang_getNullCursor();
3308 case Decl::FunctionTemplate: {
3309 const FunctionDecl *Def = 0;
3310 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
3311 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
3312 return clang_getNullCursor();
3315 case Decl::ClassTemplate: {
3316 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
3317 ->getDefinition())
3318 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
3319 CXXUnit);
3320 return clang_getNullCursor();
3323 case Decl::Using:
3324 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3325 D->getLocation(), CXXUnit);
3327 case Decl::UsingShadow:
3328 return clang_getCursorDefinition(
3329 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
3330 CXXUnit));
3332 case Decl::ObjCMethod: {
3333 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3334 if (Method->isThisDeclarationADefinition())
3335 return C;
3337 // Dig out the method definition in the associated
3338 // @implementation, if we have it.
3339 // FIXME: The ASTs should make finding the definition easier.
3340 if (ObjCInterfaceDecl *Class
3341 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3342 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3343 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3344 Method->isInstanceMethod()))
3345 if (Def->isThisDeclarationADefinition())
3346 return MakeCXCursor(Def, CXXUnit);
3348 return clang_getNullCursor();
3351 case Decl::ObjCCategory:
3352 if (ObjCCategoryImplDecl *Impl
3353 = cast<ObjCCategoryDecl>(D)->getImplementation())
3354 return MakeCXCursor(Impl, CXXUnit);
3355 return clang_getNullCursor();
3357 case Decl::ObjCProtocol:
3358 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3359 return C;
3360 return clang_getNullCursor();
3362 case Decl::ObjCInterface:
3363 // There are two notions of a "definition" for an Objective-C
3364 // class: the interface and its implementation. When we resolved a
3365 // reference to an Objective-C class, produce the @interface as
3366 // the definition; when we were provided with the interface,
3367 // produce the @implementation as the definition.
3368 if (WasReference) {
3369 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3370 return C;
3371 } else if (ObjCImplementationDecl *Impl
3372 = cast<ObjCInterfaceDecl>(D)->getImplementation())
3373 return MakeCXCursor(Impl, CXXUnit);
3374 return clang_getNullCursor();
3376 case Decl::ObjCProperty:
3377 // FIXME: We don't really know where to find the
3378 // ObjCPropertyImplDecls that implement this property.
3379 return clang_getNullCursor();
3381 case Decl::ObjCCompatibleAlias:
3382 if (ObjCInterfaceDecl *Class
3383 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3384 if (!Class->isForwardDecl())
3385 return MakeCXCursor(Class, CXXUnit);
3387 return clang_getNullCursor();
3389 case Decl::ObjCForwardProtocol:
3390 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3391 D->getLocation(), CXXUnit);
3393 case Decl::ObjCClass:
3394 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
3395 CXXUnit);
3397 case Decl::Friend:
3398 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
3399 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
3400 return clang_getNullCursor();
3402 case Decl::FriendTemplate:
3403 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
3404 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
3405 return clang_getNullCursor();
3408 return clang_getNullCursor();
3411 unsigned clang_isCursorDefinition(CXCursor C) {
3412 if (!clang_isDeclaration(C.kind))
3413 return 0;
3415 return clang_getCursorDefinition(C) == C;
3418 unsigned clang_getNumOverloadedDecls(CXCursor C) {
3419 if (C.kind != CXCursor_OverloadedDeclRef)
3420 return 0;
3422 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3423 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3424 return E->getNumDecls();
3426 if (OverloadedTemplateStorage *S
3427 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3428 return S->size();
3430 Decl *D = Storage.get<Decl*>();
3431 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3432 return Using->getNumShadowDecls();
3433 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3434 return Classes->size();
3435 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3436 return Protocols->protocol_size();
3438 return 0;
3441 CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
3442 if (cursor.kind != CXCursor_OverloadedDeclRef)
3443 return clang_getNullCursor();
3445 if (index >= clang_getNumOverloadedDecls(cursor))
3446 return clang_getNullCursor();
3448 ASTUnit *Unit = getCursorASTUnit(cursor);
3449 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3450 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3451 return MakeCXCursor(E->decls_begin()[index], Unit);
3453 if (OverloadedTemplateStorage *S
3454 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3455 return MakeCXCursor(S->begin()[index], Unit);
3457 Decl *D = Storage.get<Decl*>();
3458 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3459 // FIXME: This is, unfortunately, linear time.
3460 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3461 std::advance(Pos, index);
3462 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3465 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3466 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3468 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3469 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3471 return clang_getNullCursor();
3474 void clang_getDefinitionSpellingAndExtent(CXCursor C,
3475 const char **startBuf,
3476 const char **endBuf,
3477 unsigned *startLine,
3478 unsigned *startColumn,
3479 unsigned *endLine,
3480 unsigned *endColumn) {
3481 assert(getCursorDecl(C) && "CXCursor has null decl");
3482 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
3483 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3484 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
3486 SourceManager &SM = FD->getASTContext().getSourceManager();
3487 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3488 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3489 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3490 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3491 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3492 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3495 void clang_enableStackTraces(void) {
3496 llvm::sys::PrintStackTraceOnErrorSignal();
3499 } // end: extern "C"
3501 //===----------------------------------------------------------------------===//
3502 // Token-based Operations.
3503 //===----------------------------------------------------------------------===//
3505 /* CXToken layout:
3506 * int_data[0]: a CXTokenKind
3507 * int_data[1]: starting token location
3508 * int_data[2]: token length
3509 * int_data[3]: reserved
3510 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
3511 * otherwise unused.
3513 extern "C" {
3515 CXTokenKind clang_getTokenKind(CXToken CXTok) {
3516 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3519 CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3520 switch (clang_getTokenKind(CXTok)) {
3521 case CXToken_Identifier:
3522 case CXToken_Keyword:
3523 // We know we have an IdentifierInfo*, so use that.
3524 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3525 ->getNameStart());
3527 case CXToken_Literal: {
3528 // We have stashed the starting pointer in the ptr_data field. Use it.
3529 const char *Text = static_cast<const char *>(CXTok.ptr_data);
3530 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
3533 case CXToken_Punctuation:
3534 case CXToken_Comment:
3535 break;
3538 // We have to find the starting buffer pointer the hard way, by
3539 // deconstructing the source location.
3540 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3541 if (!CXXUnit)
3542 return createCXString("");
3544 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3545 std::pair<FileID, unsigned> LocInfo
3546 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
3547 bool Invalid = false;
3548 llvm::StringRef Buffer
3549 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3550 if (Invalid)
3551 return createCXString("");
3553 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
3556 CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3557 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3558 if (!CXXUnit)
3559 return clang_getNullLocation();
3561 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3562 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3565 CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3566 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3567 if (!CXXUnit)
3568 return clang_getNullRange();
3570 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
3571 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3574 void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3575 CXToken **Tokens, unsigned *NumTokens) {
3576 if (Tokens)
3577 *Tokens = 0;
3578 if (NumTokens)
3579 *NumTokens = 0;
3581 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3582 if (!CXXUnit || !Tokens || !NumTokens)
3583 return;
3585 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3587 SourceRange R = cxloc::translateCXSourceRange(Range);
3588 if (R.isInvalid())
3589 return;
3591 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3592 std::pair<FileID, unsigned> BeginLocInfo
3593 = SourceMgr.getDecomposedLoc(R.getBegin());
3594 std::pair<FileID, unsigned> EndLocInfo
3595 = SourceMgr.getDecomposedLoc(R.getEnd());
3597 // Cannot tokenize across files.
3598 if (BeginLocInfo.first != EndLocInfo.first)
3599 return;
3601 // Create a lexer
3602 bool Invalid = false;
3603 llvm::StringRef Buffer
3604 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
3605 if (Invalid)
3606 return;
3608 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3609 CXXUnit->getASTContext().getLangOptions(),
3610 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
3611 Lex.SetCommentRetentionState(true);
3613 // Lex tokens until we hit the end of the range.
3614 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
3615 llvm::SmallVector<CXToken, 32> CXTokens;
3616 Token Tok;
3617 bool previousWasAt = false;
3618 do {
3619 // Lex the next token
3620 Lex.LexFromRawLexer(Tok);
3621 if (Tok.is(tok::eof))
3622 break;
3624 // Initialize the CXToken.
3625 CXToken CXTok;
3627 // - Common fields
3628 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3629 CXTok.int_data[2] = Tok.getLength();
3630 CXTok.int_data[3] = 0;
3632 // - Kind-specific fields
3633 if (Tok.isLiteral()) {
3634 CXTok.int_data[0] = CXToken_Literal;
3635 CXTok.ptr_data = (void *)Tok.getLiteralData();
3636 } else if (Tok.is(tok::identifier)) {
3637 // Lookup the identifier to determine whether we have a keyword.
3638 std::pair<FileID, unsigned> LocInfo
3639 = SourceMgr.getDecomposedLoc(Tok.getLocation());
3640 bool Invalid = false;
3641 llvm::StringRef Buf
3642 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3643 if (Invalid)
3644 return;
3646 const char *StartPos = Buf.data() + LocInfo.second;
3647 IdentifierInfo *II
3648 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
3650 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
3651 CXTok.int_data[0] = CXToken_Keyword;
3653 else {
3654 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3655 CXToken_Identifier
3656 : CXToken_Keyword;
3658 CXTok.ptr_data = II;
3659 } else if (Tok.is(tok::comment)) {
3660 CXTok.int_data[0] = CXToken_Comment;
3661 CXTok.ptr_data = 0;
3662 } else {
3663 CXTok.int_data[0] = CXToken_Punctuation;
3664 CXTok.ptr_data = 0;
3666 CXTokens.push_back(CXTok);
3667 previousWasAt = Tok.is(tok::at);
3668 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
3670 if (CXTokens.empty())
3671 return;
3673 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3674 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3675 *NumTokens = CXTokens.size();
3678 void clang_disposeTokens(CXTranslationUnit TU,
3679 CXToken *Tokens, unsigned NumTokens) {
3680 free(Tokens);
3683 } // end: extern "C"
3685 //===----------------------------------------------------------------------===//
3686 // Token annotation APIs.
3687 //===----------------------------------------------------------------------===//
3689 typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
3690 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3691 CXCursor parent,
3692 CXClientData client_data);
3693 namespace {
3694 class AnnotateTokensWorker {
3695 AnnotateTokensData &Annotated;
3696 CXToken *Tokens;
3697 CXCursor *Cursors;
3698 unsigned NumTokens;
3699 unsigned TokIdx;
3700 unsigned PreprocessingTokIdx;
3701 CursorVisitor AnnotateVis;
3702 SourceManager &SrcMgr;
3704 bool MoreTokens() const { return TokIdx < NumTokens; }
3705 unsigned NextToken() const { return TokIdx; }
3706 void AdvanceToken() { ++TokIdx; }
3707 SourceLocation GetTokenLoc(unsigned tokI) {
3708 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3711 public:
3712 AnnotateTokensWorker(AnnotateTokensData &annotated,
3713 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3714 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
3715 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
3716 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
3717 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3718 Decl::MaxPCHLevel, RegionOfInterest),
3719 SrcMgr(CXXUnit->getSourceManager()) {}
3721 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
3722 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
3723 void AnnotateTokens(CXCursor parent);
3727 void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3728 // Walk the AST within the region of interest, annotating tokens
3729 // along the way.
3730 VisitChildren(parent);
3732 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3733 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3734 if (Pos != Annotated.end() &&
3735 (clang_isInvalid(Cursors[I].kind) ||
3736 Pos->second.kind != CXCursor_PreprocessingDirective))
3737 Cursors[I] = Pos->second;
3740 // Finish up annotating any tokens left.
3741 if (!MoreTokens())
3742 return;
3744 const CXCursor &C = clang_getNullCursor();
3745 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3746 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3747 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
3751 enum CXChildVisitResult
3752 AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
3753 CXSourceLocation Loc = clang_getCursorLocation(cursor);
3754 SourceRange cursorRange = getRawCursorExtent(cursor);
3755 if (cursorRange.isInvalid())
3756 return CXChildVisit_Recurse;
3758 if (clang_isPreprocessing(cursor.kind)) {
3759 // For macro instantiations, just note where the beginning of the macro
3760 // instantiation occurs.
3761 if (cursor.kind == CXCursor_MacroInstantiation) {
3762 Annotated[Loc.int_data] = cursor;
3763 return CXChildVisit_Recurse;
3766 // Items in the preprocessing record are kept separate from items in
3767 // declarations, so we keep a separate token index.
3768 unsigned SavedTokIdx = TokIdx;
3769 TokIdx = PreprocessingTokIdx;
3771 // Skip tokens up until we catch up to the beginning of the preprocessing
3772 // entry.
3773 while (MoreTokens()) {
3774 const unsigned I = NextToken();
3775 SourceLocation TokLoc = GetTokenLoc(I);
3776 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3777 case RangeBefore:
3778 AdvanceToken();
3779 continue;
3780 case RangeAfter:
3781 case RangeOverlap:
3782 break;
3784 break;
3787 // Look at all of the tokens within this range.
3788 while (MoreTokens()) {
3789 const unsigned I = NextToken();
3790 SourceLocation TokLoc = GetTokenLoc(I);
3791 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3792 case RangeBefore:
3793 assert(0 && "Infeasible");
3794 case RangeAfter:
3795 break;
3796 case RangeOverlap:
3797 Cursors[I] = cursor;
3798 AdvanceToken();
3799 continue;
3801 break;
3804 // Save the preprocessing token index; restore the non-preprocessing
3805 // token index.
3806 PreprocessingTokIdx = TokIdx;
3807 TokIdx = SavedTokIdx;
3808 return CXChildVisit_Recurse;
3811 if (cursorRange.isInvalid())
3812 return CXChildVisit_Continue;
3814 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3816 // Adjust the annotated range based specific declarations.
3817 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3818 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
3819 Decl *D = cxcursor::getCursorDecl(cursor);
3820 // Don't visit synthesized ObjC methods, since they have no syntatic
3821 // representation in the source.
3822 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3823 if (MD->isSynthesized())
3824 return CXChildVisit_Continue;
3826 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
3827 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
3828 TypeLoc TL = TI->getTypeLoc();
3829 SourceLocation TLoc = TL.getSourceRange().getBegin();
3830 if (TLoc.isValid() && L.isValid() &&
3831 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
3832 cursorRange.setBegin(TLoc);
3837 // If the location of the cursor occurs within a macro instantiation, record
3838 // the spelling location of the cursor in our annotation map. We can then
3839 // paper over the token labelings during a post-processing step to try and
3840 // get cursor mappings for tokens that are the *arguments* of a macro
3841 // instantiation.
3842 if (L.isMacroID()) {
3843 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
3844 // Only invalidate the old annotation if it isn't part of a preprocessing
3845 // directive. Here we assume that the default construction of CXCursor
3846 // results in CXCursor.kind being an initialized value (i.e., 0). If
3847 // this isn't the case, we can fix by doing lookup + insertion.
3849 CXCursor &oldC = Annotated[rawEncoding];
3850 if (!clang_isPreprocessing(oldC.kind))
3851 oldC = cursor;
3854 const enum CXCursorKind K = clang_getCursorKind(parent);
3855 const CXCursor updateC =
3856 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
3857 ? clang_getNullCursor() : parent;
3859 while (MoreTokens()) {
3860 const unsigned I = NextToken();
3861 SourceLocation TokLoc = GetTokenLoc(I);
3862 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3863 case RangeBefore:
3864 Cursors[I] = updateC;
3865 AdvanceToken();
3866 continue;
3867 case RangeAfter:
3868 case RangeOverlap:
3869 break;
3871 break;
3874 // Visit children to get their cursor information.
3875 const unsigned BeforeChildren = NextToken();
3876 VisitChildren(cursor);
3877 const unsigned AfterChildren = NextToken();
3879 // Adjust 'Last' to the last token within the extent of the cursor.
3880 while (MoreTokens()) {
3881 const unsigned I = NextToken();
3882 SourceLocation TokLoc = GetTokenLoc(I);
3883 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3884 case RangeBefore:
3885 assert(0 && "Infeasible");
3886 case RangeAfter:
3887 break;
3888 case RangeOverlap:
3889 Cursors[I] = updateC;
3890 AdvanceToken();
3891 continue;
3893 break;
3895 const unsigned Last = NextToken();
3897 // Scan the tokens that are at the beginning of the cursor, but are not
3898 // capture by the child cursors.
3900 // For AST elements within macros, rely on a post-annotate pass to
3901 // to correctly annotate the tokens with cursors. Otherwise we can
3902 // get confusing results of having tokens that map to cursors that really
3903 // are expanded by an instantiation.
3904 if (L.isMacroID())
3905 cursor = clang_getNullCursor();
3907 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
3908 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
3909 break;
3911 Cursors[I] = cursor;
3913 // Scan the tokens that are at the end of the cursor, but are not captured
3914 // but the child cursors.
3915 for (unsigned I = AfterChildren; I != Last; ++I)
3916 Cursors[I] = cursor;
3918 TokIdx = Last;
3919 return CXChildVisit_Continue;
3922 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3923 CXCursor parent,
3924 CXClientData client_data) {
3925 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
3928 extern "C" {
3930 void clang_annotateTokens(CXTranslationUnit TU,
3931 CXToken *Tokens, unsigned NumTokens,
3932 CXCursor *Cursors) {
3934 if (NumTokens == 0 || !Tokens || !Cursors)
3935 return;
3937 // Any token we don't specifically annotate will have a NULL cursor.
3938 CXCursor C = clang_getNullCursor();
3939 for (unsigned I = 0; I != NumTokens; ++I)
3940 Cursors[I] = C;
3942 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3943 if (!CXXUnit)
3944 return;
3946 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3948 // Determine the region of interest, which contains all of the tokens.
3949 SourceRange RegionOfInterest;
3950 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
3951 clang_getTokenLocation(TU, Tokens[0])));
3952 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
3953 clang_getTokenLocation(TU,
3954 Tokens[NumTokens - 1])));
3956 // A mapping from the source locations found when re-lexing or traversing the
3957 // region of interest to the corresponding cursors.
3958 AnnotateTokensData Annotated;
3960 // Relex the tokens within the source range to look for preprocessing
3961 // directives.
3962 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3963 std::pair<FileID, unsigned> BeginLocInfo
3964 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
3965 std::pair<FileID, unsigned> EndLocInfo
3966 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
3968 llvm::StringRef Buffer;
3969 bool Invalid = false;
3970 if (BeginLocInfo.first == EndLocInfo.first &&
3971 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
3972 !Invalid) {
3973 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3974 CXXUnit->getASTContext().getLangOptions(),
3975 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
3976 Buffer.end());
3977 Lex.SetCommentRetentionState(true);
3979 // Lex tokens in raw mode until we hit the end of the range, to avoid
3980 // entering #includes or expanding macros.
3981 while (true) {
3982 Token Tok;
3983 Lex.LexFromRawLexer(Tok);
3985 reprocess:
3986 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
3987 // We have found a preprocessing directive. Gobble it up so that we
3988 // don't see it while preprocessing these tokens later, but keep track of
3989 // all of the token locations inside this preprocessing directive so that
3990 // we can annotate them appropriately.
3992 // FIXME: Some simple tests here could identify macro definitions and
3993 // #undefs, to provide specific cursor kinds for those.
3994 std::vector<SourceLocation> Locations;
3995 do {
3996 Locations.push_back(Tok.getLocation());
3997 Lex.LexFromRawLexer(Tok);
3998 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
4000 using namespace cxcursor;
4001 CXCursor Cursor
4002 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4003 Locations.back()),
4004 CXXUnit);
4005 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4006 Annotated[Locations[I].getRawEncoding()] = Cursor;
4009 if (Tok.isAtStartOfLine())
4010 goto reprocess;
4012 continue;
4015 if (Tok.is(tok::eof))
4016 break;
4020 // Annotate all of the source locations in the region of interest that map to
4021 // a specific cursor.
4022 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4023 CXXUnit, RegionOfInterest);
4024 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
4026 } // end: extern "C"
4028 //===----------------------------------------------------------------------===//
4029 // Operations for querying linkage of a cursor.
4030 //===----------------------------------------------------------------------===//
4032 extern "C" {
4033 CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
4034 if (!clang_isDeclaration(cursor.kind))
4035 return CXLinkage_Invalid;
4037 Decl *D = cxcursor::getCursorDecl(cursor);
4038 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4039 switch (ND->getLinkage()) {
4040 case NoLinkage: return CXLinkage_NoLinkage;
4041 case InternalLinkage: return CXLinkage_Internal;
4042 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4043 case ExternalLinkage: return CXLinkage_External;
4046 return CXLinkage_Invalid;
4048 } // end: extern "C"
4050 //===----------------------------------------------------------------------===//
4051 // Operations for querying language of a cursor.
4052 //===----------------------------------------------------------------------===//
4054 static CXLanguageKind getDeclLanguage(const Decl *D) {
4055 switch (D->getKind()) {
4056 default:
4057 break;
4058 case Decl::ImplicitParam:
4059 case Decl::ObjCAtDefsField:
4060 case Decl::ObjCCategory:
4061 case Decl::ObjCCategoryImpl:
4062 case Decl::ObjCClass:
4063 case Decl::ObjCCompatibleAlias:
4064 case Decl::ObjCForwardProtocol:
4065 case Decl::ObjCImplementation:
4066 case Decl::ObjCInterface:
4067 case Decl::ObjCIvar:
4068 case Decl::ObjCMethod:
4069 case Decl::ObjCProperty:
4070 case Decl::ObjCPropertyImpl:
4071 case Decl::ObjCProtocol:
4072 return CXLanguage_ObjC;
4073 case Decl::CXXConstructor:
4074 case Decl::CXXConversion:
4075 case Decl::CXXDestructor:
4076 case Decl::CXXMethod:
4077 case Decl::CXXRecord:
4078 case Decl::ClassTemplate:
4079 case Decl::ClassTemplatePartialSpecialization:
4080 case Decl::ClassTemplateSpecialization:
4081 case Decl::Friend:
4082 case Decl::FriendTemplate:
4083 case Decl::FunctionTemplate:
4084 case Decl::LinkageSpec:
4085 case Decl::Namespace:
4086 case Decl::NamespaceAlias:
4087 case Decl::NonTypeTemplateParm:
4088 case Decl::StaticAssert:
4089 case Decl::TemplateTemplateParm:
4090 case Decl::TemplateTypeParm:
4091 case Decl::UnresolvedUsingTypename:
4092 case Decl::UnresolvedUsingValue:
4093 case Decl::Using:
4094 case Decl::UsingDirective:
4095 case Decl::UsingShadow:
4096 return CXLanguage_CPlusPlus;
4099 return CXLanguage_C;
4102 extern "C" {
4104 enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4105 if (clang_isDeclaration(cursor.kind))
4106 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4107 if (D->hasAttr<UnavailableAttr>() ||
4108 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4109 return CXAvailability_Available;
4111 if (D->hasAttr<DeprecatedAttr>())
4112 return CXAvailability_Deprecated;
4115 return CXAvailability_Available;
4118 CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4119 if (clang_isDeclaration(cursor.kind))
4120 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4122 return CXLanguage_Invalid;
4125 CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4126 if (clang_isDeclaration(cursor.kind)) {
4127 if (Decl *D = getCursorDecl(cursor)) {
4128 DeclContext *DC = D->getDeclContext();
4129 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4133 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4134 if (Decl *D = getCursorDecl(cursor))
4135 return MakeCXCursor(D, getCursorASTUnit(cursor));
4138 return clang_getNullCursor();
4141 CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4142 if (clang_isDeclaration(cursor.kind)) {
4143 if (Decl *D = getCursorDecl(cursor)) {
4144 DeclContext *DC = D->getLexicalDeclContext();
4145 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4149 // FIXME: Note that we can't easily compute the lexical context of a
4150 // statement or expression, so we return nothing.
4151 return clang_getNullCursor();
4154 static void CollectOverriddenMethods(DeclContext *Ctx,
4155 ObjCMethodDecl *Method,
4156 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4157 if (!Ctx)
4158 return;
4160 // If we have a class or category implementation, jump straight to the
4161 // interface.
4162 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4163 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4165 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4166 if (!Container)
4167 return;
4169 // Check whether we have a matching method at this level.
4170 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4171 Method->isInstanceMethod()))
4172 if (Method != Overridden) {
4173 // We found an override at this level; there is no need to look
4174 // into other protocols or categories.
4175 Methods.push_back(Overridden);
4176 return;
4179 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4180 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4181 PEnd = Protocol->protocol_end();
4182 P != PEnd; ++P)
4183 CollectOverriddenMethods(*P, Method, Methods);
4186 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4187 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4188 PEnd = Category->protocol_end();
4189 P != PEnd; ++P)
4190 CollectOverriddenMethods(*P, Method, Methods);
4193 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4194 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4195 PEnd = Interface->protocol_end();
4196 P != PEnd; ++P)
4197 CollectOverriddenMethods(*P, Method, Methods);
4199 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4200 Category; Category = Category->getNextClassCategory())
4201 CollectOverriddenMethods(Category, Method, Methods);
4203 // We only look into the superclass if we haven't found anything yet.
4204 if (Methods.empty())
4205 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4206 return CollectOverriddenMethods(Super, Method, Methods);
4210 void clang_getOverriddenCursors(CXCursor cursor,
4211 CXCursor **overridden,
4212 unsigned *num_overridden) {
4213 if (overridden)
4214 *overridden = 0;
4215 if (num_overridden)
4216 *num_overridden = 0;
4217 if (!overridden || !num_overridden)
4218 return;
4220 if (!clang_isDeclaration(cursor.kind))
4221 return;
4223 Decl *D = getCursorDecl(cursor);
4224 if (!D)
4225 return;
4227 // Handle C++ member functions.
4228 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4229 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4230 *num_overridden = CXXMethod->size_overridden_methods();
4231 if (!*num_overridden)
4232 return;
4234 *overridden = new CXCursor [*num_overridden];
4235 unsigned I = 0;
4236 for (CXXMethodDecl::method_iterator
4237 M = CXXMethod->begin_overridden_methods(),
4238 MEnd = CXXMethod->end_overridden_methods();
4239 M != MEnd; (void)++M, ++I)
4240 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4241 return;
4244 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4245 if (!Method)
4246 return;
4248 // Handle Objective-C methods.
4249 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4250 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4252 if (Methods.empty())
4253 return;
4255 *num_overridden = Methods.size();
4256 *overridden = new CXCursor [Methods.size()];
4257 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4258 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4261 void clang_disposeOverriddenCursors(CXCursor *overridden) {
4262 delete [] overridden;
4265 CXFile clang_getIncludedFile(CXCursor cursor) {
4266 if (cursor.kind != CXCursor_InclusionDirective)
4267 return 0;
4269 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4270 return (void *)ID->getFile();
4273 } // end: extern "C"
4276 //===----------------------------------------------------------------------===//
4277 // C++ AST instrospection.
4278 //===----------------------------------------------------------------------===//
4280 extern "C" {
4281 unsigned clang_CXXMethod_isStatic(CXCursor C) {
4282 if (!clang_isDeclaration(C.kind))
4283 return 0;
4285 CXXMethodDecl *Method = 0;
4286 Decl *D = cxcursor::getCursorDecl(C);
4287 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4288 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4289 else
4290 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4291 return (Method && Method->isStatic()) ? 1 : 0;
4294 } // end: extern "C"
4296 //===----------------------------------------------------------------------===//
4297 // Attribute introspection.
4298 //===----------------------------------------------------------------------===//
4300 extern "C" {
4301 CXType clang_getIBOutletCollectionType(CXCursor C) {
4302 if (C.kind != CXCursor_IBOutletCollectionAttr)
4303 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4305 IBOutletCollectionAttr *A =
4306 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4308 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4310 } // end: extern "C"
4312 //===----------------------------------------------------------------------===//
4313 // CXString Operations.
4314 //===----------------------------------------------------------------------===//
4316 extern "C" {
4317 const char *clang_getCString(CXString string) {
4318 return string.Spelling;
4321 void clang_disposeString(CXString string) {
4322 if (string.MustFreeString && string.Spelling)
4323 free((void*)string.Spelling);
4326 } // end: extern "C"
4328 namespace clang { namespace cxstring {
4329 CXString createCXString(const char *String, bool DupString){
4330 CXString Str;
4331 if (DupString) {
4332 Str.Spelling = strdup(String);
4333 Str.MustFreeString = 1;
4334 } else {
4335 Str.Spelling = String;
4336 Str.MustFreeString = 0;
4338 return Str;
4341 CXString createCXString(llvm::StringRef String, bool DupString) {
4342 CXString Result;
4343 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4344 char *Spelling = (char *)malloc(String.size() + 1);
4345 memmove(Spelling, String.data(), String.size());
4346 Spelling[String.size()] = 0;
4347 Result.Spelling = Spelling;
4348 Result.MustFreeString = 1;
4349 } else {
4350 Result.Spelling = String.data();
4351 Result.MustFreeString = 0;
4353 return Result;
4357 //===----------------------------------------------------------------------===//
4358 // Misc. utility functions.
4359 //===----------------------------------------------------------------------===//
4361 extern "C" {
4363 CXString clang_getClangVersion() {
4364 return createCXString(getClangFullVersion());
4367 } // end: extern "C"