blob: b93bb6f94253b49d0a790394fc36cebd043c9ac2 [file] [log] [blame]
Ted Kremenek16b55a72010-01-26 19:31:51 +00001//===- CIndexInclusionStack.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 defines a callback mechanism for clients to get the inclusion
11// stack from a translation unit.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CIndexer.h"
16#include "CXSourceLocation.h"
17#include "clang/AST/DeclVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000018#include "clang/Frontend/ASTUnit.h"
Ted Kremenek16b55a72010-01-26 19:31:51 +000019#include "llvm/ADT/SmallString.h"
20#include "llvm/Support/raw_ostream.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000021using namespace clang;
Ted Kremenek16b55a72010-01-26 19:31:51 +000022
23extern "C" {
24void clang_getInclusions(CXTranslationUnit TU, CXInclusionVisitor CB,
25 CXClientData clientData) {
26
Ted Kremeneka60ed472010-11-16 08:15:36 +000027 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
Ted Kremenek16b55a72010-01-26 19:31:51 +000028 SourceManager &SM = CXXUnit->getSourceManager();
29 ASTContext &Ctx = CXXUnit->getASTContext();
30
31 llvm::SmallVector<CXSourceLocation, 10> InclusionStack;
32 unsigned i = SM.sloc_loaded_entry_size();
33 unsigned n = SM.sloc_entry_size();
34
35 // In the case where all the SLocEntries are in an external source, traverse
36 // those SLocEntries as well. This is the case where we are looking
37 // at the inclusion stack of an AST/PCH file.
38 if (i >= n)
39 i = 0;
40
41 for ( ; i < n ; ++i) {
42
43 const SrcMgr::SLocEntry &SL = SM.getSLocEntry(i);
44
45 if (!SL.isFile())
46 continue;
47
48 const SrcMgr::FileInfo &FI = SL.getFile();
49 if (!FI.getContentCache()->Entry)
50 continue;
51
52 // Build the inclusion stack.
53 SourceLocation L = FI.getIncludeLoc();
54 InclusionStack.clear();
55 while (L.isValid()) {
56 PresumedLoc PLoc = SM.getPresumedLoc(L);
57 InclusionStack.push_back(cxloc::translateSourceLocation(Ctx, L));
Douglas Gregorcb7b1e12010-11-12 07:15:47 +000058 L = PLoc.isValid()? PLoc.getIncludeLoc() : SourceLocation();
Ted Kremenek16b55a72010-01-26 19:31:51 +000059 }
60
61 // Callback to the client.
62 // FIXME: We should have a function to construct CXFiles.
63 CB((CXFile) FI.getContentCache()->Entry,
64 InclusionStack.data(), InclusionStack.size(), clientData);
65 }
66}
67} // end extern C