summaryrefslogtreecommitdiff
path: root/clang/tools/libclang/CIndexInclusionStack.cpp
blob: 848ca31a5e32b04380596db7f52cb5c3894faad4 (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//===- CIndexInclusionStack.cpp - Clang-C Source Indexing Library ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a callback mechanism for clients to get the inclusion
// stack from a translation unit.
//
//===----------------------------------------------------------------------===//

#include "CIndexer.h"
#include "CXTranslationUnit.h"
#include "CXSourceLocation.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/Frontend/ASTUnit.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;

extern "C" {
void clang_getInclusions(CXTranslationUnit TU, CXInclusionVisitor CB,
                         CXClientData clientData) {
  
  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
  SourceManager &SM = CXXUnit->getSourceManager();
  ASTContext &Ctx = CXXUnit->getASTContext();

  SmallVector<CXSourceLocation, 10> InclusionStack;
  unsigned n =  SM.local_sloc_entry_size();

  // In the case where all the SLocEntries are in an external source, traverse
  // those SLocEntries as well.  This is the case where we are looking
  // at the inclusion stack of an AST/PCH file.
  const SrcMgr::SLocEntry &(SourceManager::*Getter)(unsigned, bool*) const;
  if (n == 1) {
    Getter = &SourceManager::getLoadedSLocEntry;
    n = SM.loaded_sloc_entry_size();
  } else
    Getter = &SourceManager::getLocalSLocEntry;

  for (unsigned i = 0 ; i < n ; ++i) {
    bool Invalid = false;
    const SrcMgr::SLocEntry &SL = (SM.*Getter)(i, &Invalid);
    
    if (!SL.isFile() || Invalid)
      continue;

    const SrcMgr::FileInfo &FI = SL.getFile();
    if (!FI.getContentCache()->OrigEntry)
      continue;
    
    // Build the inclusion stack.
    SourceLocation L = FI.getIncludeLoc();
    InclusionStack.clear();
    while (L.isValid()) {
      PresumedLoc PLoc = SM.getPresumedLoc(L);
      InclusionStack.push_back(cxloc::translateSourceLocation(Ctx, L));
      L = PLoc.isValid()? PLoc.getIncludeLoc() : SourceLocation();
    }
            
    // Callback to the client.
    // FIXME: We should have a function to construct CXFiles.
    CB((CXFile) FI.getContentCache()->OrigEntry, 
       InclusionStack.data(), InclusionStack.size(), clientData);
  }    
}
} // end extern C