aboutsummaryrefslogtreecommitdiff
path: root/lib/Frontend/DocumentXML.cpp
blob: d92d4cb7b8deeab9cd96553066ac557fe9d12118 (plain) (blame)
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
//===--- DocumentXML.cpp - XML document for ASTs --------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the XML document class, which provides the means to
// dump out the AST in a XML form that exposes type details and other fields.
//
//===----------------------------------------------------------------------===//

#include "clang/Frontend/DocumentXML.h"
#include "clang/AST/Decl.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/ADT/StringExtras.h"

namespace clang {

//---------------------------------------------------------
DocumentXML::DocumentXML(const std::string& rootName, llvm::raw_ostream& out) :
  Out(out),
  Ctx(0),
  HasCurrentNodeSubNodes(false) {
  NodeStack.push(rootName);
  Out << "<?xml version=\"1.0\"?>\n<" << rootName;
}

//---------------------------------------------------------
DocumentXML& DocumentXML::addSubNode(const std::string& name) {
  if (!HasCurrentNodeSubNodes)
    Out << ">\n";
  NodeStack.push(name);
  HasCurrentNodeSubNodes = false;
  Indent();
  Out << "<" << NodeStack.top();
  return *this;
}

//---------------------------------------------------------
void DocumentXML::Indent() {
  for (size_t i = 0, e = (NodeStack.size() - 1) * 2; i < e; ++i)
    Out << ' ';
}

//---------------------------------------------------------
DocumentXML& DocumentXML::toParent() {
  assert(NodeStack.size() > 1 && "too much backtracking");

  if (HasCurrentNodeSubNodes) {
    Indent();
    Out << "</" << NodeStack.top() << ">\n";
  } else
    Out << "/>\n";
  NodeStack.pop();
  HasCurrentNodeSubNodes = true;
  return *this;
}

//---------------------------------------------------------
namespace {

enum tIdType { ID_NORMAL, ID_FILE, ID_LABEL, ID_LAST };

unsigned getNewId(tIdType idType) {
  static unsigned int idCounts[ID_LAST] = { 0 };
  return ++idCounts[idType];
}

//---------------------------------------------------------
inline std::string getPrefixedId(unsigned uId, tIdType idType) {
  static const char idPrefix[ID_LAST] = { '_', 'f', 'l' };
  char buffer[20];
  char* BufPtr = llvm::utohex_buffer(uId, buffer + 20);
  *--BufPtr = idPrefix[idType];
  return BufPtr;
}

//---------------------------------------------------------
template<class T, class V>
bool addToMap(T& idMap, const V& value, tIdType idType = ID_NORMAL) {
  typename T::iterator i = idMap.find(value);
  bool toAdd = i == idMap.end();
  if (toAdd)
    idMap.insert(typename T::value_type(value, getNewId(idType)));
  return toAdd;
}

} // anon NS


//---------------------------------------------------------
std::string DocumentXML::escapeString(const char* pStr,
                                      std::string::size_type len) {
  std::string value;
  value.reserve(len + 1);
  char buffer[16];
  for (unsigned i = 0; i < len; ++i) {
    switch (char C = pStr[i]) {
    default:
      if (isprint(C))
        value += C;
      else {
        sprintf(buffer, "\\%03o", C);
        value += buffer;
      }
      break;

    case '\n': value += "\\n"; break;
    case '\t': value += "\\t"; break;
    case '\a': value += "\\a"; break;
    case '\b': value += "\\b"; break;
    case '\r': value += "\\r"; break;

    case '&': value += "&amp;"; break;
    case '<': value += "&lt;"; break;
    case '>': value += "&gt;"; break;
    case '"': value += "&quot;"; break;
    case '\'':  value += "&apos;"; break;

    }
  }
  return value;
}

//---------------------------------------------------------
void DocumentXML::finalize() {
  assert(NodeStack.size() == 1 && "not completely backtracked");

  addSubNode("ReferenceSection");
  addSubNode("Types");

  for (XML::IdMap<QualType>::iterator i = Types.begin(), e = Types.end();
       i != e; ++i) {
    if (i->first.hasQualifiers()) {
      writeTypeToXML(i->first);
      addAttribute("id", getPrefixedId(i->second, ID_NORMAL));
      toParent();
    }
  }

  for (XML::IdMap<const Type*>::iterator i = BasicTypes.begin(),
         e = BasicTypes.end(); i != e; ++i) {
    writeTypeToXML(i->first);
    addAttribute("id", getPrefixedId(i->second, ID_NORMAL));
    toParent();
  }


  toParent().addSubNode("Contexts");

  for (XML::IdMap<const DeclContext*>::iterator i = Contexts.begin(),
         e = Contexts.end(); i != e; ++i) {
    addSubNode(i->first->getDeclKindName());
    addAttribute("id", getPrefixedId(i->second, ID_NORMAL));
    if (const NamedDecl *ND = dyn_cast<NamedDecl>(i->first))
      addAttribute("name", ND->getNameAsString());
    if (const TagDecl *TD = dyn_cast<TagDecl>(i->first))
      addAttribute("type", getPrefixedId(BasicTypes[TD->getTypeForDecl()], ID_NORMAL));
    else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(i->first))
      addAttribute("type", getPrefixedId(BasicTypes[FD->getType()->getAs<FunctionType>()], ID_NORMAL));

    if (const DeclContext* parent = i->first->getParent())
      addAttribute("context", parent);
    toParent();
  }

  toParent().addSubNode("Files");

  for (XML::IdMap<std::string>::iterator i = SourceFiles.begin(),
         e = SourceFiles.end(); i != e; ++i) {
    addSubNode("File");
    addAttribute("id", getPrefixedId(i->second, ID_FILE));
    addAttribute("name", escapeString(i->first.c_str(), i->first.size()));
    toParent();
  }

  toParent().toParent();

  // write the root closing node (which has always subnodes)
  Out << "</" << NodeStack.top() << ">\n";
}

//---------------------------------------------------------
void DocumentXML::addAttribute(const char* pAttributeName,
                               const QualType& pType) {
  addTypeRecursively(pType);
  addAttribute(pAttributeName, getPrefixedId(Types[pType], ID_NORMAL));
}

//---------------------------------------------------------
void DocumentXML::addPtrAttribute(const char* pAttributeName,
                                  const Type* pType) {
  addTypeRecursively(pType);
  addAttribute(pAttributeName, getPrefixedId(BasicTypes[pType], ID_NORMAL));
}

//---------------------------------------------------------
void DocumentXML::addTypeRecursively(const QualType& pType)
{
  if (addToMap(Types, pType))
  {
    addTypeRecursively(pType.getTypePtr());
    // beautifier: a non-qualified type shall be transparent
    if (!pType.hasQualifiers())
    {
      Types[pType] = BasicTypes[pType.getTypePtr()];
    }
  }
}

//---------------------------------------------------------
void DocumentXML::addTypeRecursively(const Type* pType)
{
  if (addToMap(BasicTypes, pType))
  {
    addParentTypes(pType);
/*
    // FIXME: doesn't work in the immediate streaming approach
    if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(pType))
    {
      addSubNode("VariableArraySizeExpression");
      PrintStmt(VAT->getSizeExpr());
      toParent();
    }
*/
  }
}

//---------------------------------------------------------
void DocumentXML::addPtrAttribute(const char* pName, const DeclContext* DC)
{
  addContextsRecursively(DC);
  addAttribute(pName, getPrefixedId(Contexts[DC], ID_NORMAL));
}

//---------------------------------------------------------
void DocumentXML::addPtrAttribute(const char* pAttributeName, const NamedDecl* D)
{
  if (const DeclContext* DC = dyn_cast<DeclContext>(D))
  {
    addContextsRecursively(DC);
    addAttribute(pAttributeName, getPrefixedId(Contexts[DC], ID_NORMAL));
  }
  else
  {
    addToMap(Decls, D);
    addAttribute(pAttributeName, getPrefixedId(Decls[D], ID_NORMAL));
  }
}

//---------------------------------------------------------
void DocumentXML::addPtrAttribute(const char* pName, const NamespaceDecl* D)
{
  addPtrAttribute(pName, static_cast<const DeclContext*>(D));
}

//---------------------------------------------------------
void DocumentXML::addContextsRecursively(const DeclContext *DC)
{
  if (DC != 0 && addToMap(Contexts, DC))
  {
    addContextsRecursively(DC->getParent());
  }
}

//---------------------------------------------------------
void DocumentXML::addSourceFileAttribute(const std::string& fileName)
{
  addToMap(SourceFiles, fileName, ID_FILE);
  addAttribute("file", getPrefixedId(SourceFiles[fileName], ID_FILE));
}


//---------------------------------------------------------
void DocumentXML::addPtrAttribute(const char* pName, const LabelStmt* L)
{
  addToMap(Labels, L, ID_LABEL);
  addAttribute(pName, getPrefixedId(Labels[L], ID_LABEL));
}


//---------------------------------------------------------
PresumedLoc DocumentXML::addLocation(const SourceLocation& Loc)
{
  SourceManager& SM = Ctx->getSourceManager();
  SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
  PresumedLoc PLoc;
  if (!SpellingLoc.isInvalid())
  {
    PLoc = SM.getPresumedLoc(SpellingLoc);
    addSourceFileAttribute(PLoc.getFilename());
    addAttribute("line", PLoc.getLine());
    addAttribute("col", PLoc.getColumn());
  }
  // else there is no error in some cases (eg. CXXThisExpr)
  return PLoc;
}

//---------------------------------------------------------
void DocumentXML::addLocationRange(const SourceRange& R)
{
  PresumedLoc PStartLoc = addLocation(R.getBegin());
  if (R.getBegin() != R.getEnd())
  {
    SourceManager& SM = Ctx->getSourceManager();
    SourceLocation SpellingLoc = SM.getSpellingLoc(R.getEnd());
    if (!SpellingLoc.isInvalid())
    {
      PresumedLoc PLoc = SM.getPresumedLoc(SpellingLoc);
      if (PStartLoc.isInvalid() ||
          strcmp(PLoc.getFilename(), PStartLoc.getFilename()) != 0) {
        addToMap(SourceFiles, PLoc.getFilename(), ID_FILE);
        addAttribute("endfile", PLoc.getFilename());
        addAttribute("endline", PLoc.getLine());
        addAttribute("endcol", PLoc.getColumn());
      } else if (PLoc.getLine() != PStartLoc.getLine()) {
        addAttribute("endline", PLoc.getLine());
        addAttribute("endcol", PLoc.getColumn());
      } else {
        addAttribute("endcol", PLoc.getColumn());
      }
    }
  }
}

//---------------------------------------------------------
void DocumentXML::PrintDecl(Decl *D)
{
  writeDeclToXML(D);
}

//---------------------------------------------------------
} // NS clang