HTMLDiagnostics.cpp revision 263508
1//===--- HTMLDiagnostics.cpp - HTML Diagnostics for Paths ----*- C++ -*-===//
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 the HTMLDiagnostics object.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Decl.h"
17#include "clang/Basic/FileManager.h"
18#include "clang/Basic/SourceManager.h"
19#include "clang/Lex/Lexer.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Rewrite/Core/HTMLRewrite.h"
22#include "clang/Rewrite/Core/Rewriter.h"
23#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
24#include "llvm/Support/FileSystem.h"
25#include "llvm/Support/MemoryBuffer.h"
26#include "llvm/Support/Path.h"
27#include "llvm/Support/raw_ostream.h"
28
29using namespace clang;
30using namespace ento;
31
32//===----------------------------------------------------------------------===//
33// Boilerplate.
34//===----------------------------------------------------------------------===//
35
36namespace {
37
38class HTMLDiagnostics : public PathDiagnosticConsumer {
39  std::string Directory;
40  bool createdDir, noDir;
41  const Preprocessor &PP;
42public:
43  HTMLDiagnostics(const std::string& prefix, const Preprocessor &pp);
44
45  virtual ~HTMLDiagnostics() { FlushDiagnostics(NULL); }
46
47  virtual void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
48                                    FilesMade *filesMade);
49
50  virtual StringRef getName() const {
51    return "HTMLDiagnostics";
52  }
53
54  unsigned ProcessMacroPiece(raw_ostream &os,
55                             const PathDiagnosticMacroPiece& P,
56                             unsigned num);
57
58  void HandlePiece(Rewriter& R, FileID BugFileID,
59                   const PathDiagnosticPiece& P, unsigned num, unsigned max);
60
61  void HighlightRange(Rewriter& R, FileID BugFileID, SourceRange Range,
62                      const char *HighlightStart = "<span class=\"mrange\">",
63                      const char *HighlightEnd = "</span>");
64
65  void ReportDiag(const PathDiagnostic& D,
66                  FilesMade *filesMade);
67};
68
69} // end anonymous namespace
70
71HTMLDiagnostics::HTMLDiagnostics(const std::string& prefix,
72                                 const Preprocessor &pp)
73  : Directory(prefix), createdDir(false), noDir(false), PP(pp) {
74}
75
76void ento::createHTMLDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
77                                        PathDiagnosticConsumers &C,
78                                        const std::string& prefix,
79                                        const Preprocessor &PP) {
80  C.push_back(new HTMLDiagnostics(prefix, PP));
81}
82
83//===----------------------------------------------------------------------===//
84// Report processing.
85//===----------------------------------------------------------------------===//
86
87void HTMLDiagnostics::FlushDiagnosticsImpl(
88  std::vector<const PathDiagnostic *> &Diags,
89  FilesMade *filesMade) {
90  for (std::vector<const PathDiagnostic *>::iterator it = Diags.begin(),
91       et = Diags.end(); it != et; ++it) {
92    ReportDiag(**it, filesMade);
93  }
94}
95
96void HTMLDiagnostics::ReportDiag(const PathDiagnostic& D,
97                                 FilesMade *filesMade) {
98
99  // Create the HTML directory if it is missing.
100  if (!createdDir) {
101    createdDir = true;
102    bool existed;
103    if (llvm::error_code ec =
104            llvm::sys::fs::create_directories(Directory, existed)) {
105      llvm::errs() << "warning: could not create directory '"
106                   << Directory << "': " << ec.message() << '\n';
107
108      noDir = true;
109
110      return;
111    }
112  }
113
114  if (noDir)
115    return;
116
117  // First flatten out the entire path to make it easier to use.
118  PathPieces path = D.path.flatten(/*ShouldFlattenMacros=*/false);
119
120  // The path as already been prechecked that all parts of the path are
121  // from the same file and that it is non-empty.
122  const SourceManager &SMgr = (*path.begin())->getLocation().getManager();
123  assert(!path.empty());
124  FileID FID =
125    (*path.begin())->getLocation().asLocation().getExpansionLoc().getFileID();
126  assert(!FID.isInvalid());
127
128  // Create a new rewriter to generate HTML.
129  Rewriter R(const_cast<SourceManager&>(SMgr), PP.getLangOpts());
130
131  // Process the path.
132  unsigned n = path.size();
133  unsigned max = n;
134
135  for (PathPieces::const_reverse_iterator I = path.rbegin(),
136       E = path.rend();
137        I != E; ++I, --n)
138    HandlePiece(R, FID, **I, n, max);
139
140  // Add line numbers, header, footer, etc.
141
142  // unsigned FID = R.getSourceMgr().getMainFileID();
143  html::EscapeText(R, FID);
144  html::AddLineNumbers(R, FID);
145
146  // If we have a preprocessor, relex the file and syntax highlight.
147  // We might not have a preprocessor if we come from a deserialized AST file,
148  // for example.
149
150  html::SyntaxHighlight(R, FID, PP);
151  html::HighlightMacros(R, FID, PP);
152
153  // Get the full directory name of the analyzed file.
154
155  const FileEntry* Entry = SMgr.getFileEntryForID(FID);
156
157  // This is a cludge; basically we want to append either the full
158  // working directory if we have no directory information.  This is
159  // a work in progress.
160
161  llvm::SmallString<0> DirName;
162
163  if (llvm::sys::path::is_relative(Entry->getName())) {
164    llvm::sys::fs::current_path(DirName);
165    DirName += '/';
166  }
167
168  // Add the name of the file as an <h1> tag.
169
170  {
171    std::string s;
172    llvm::raw_string_ostream os(s);
173
174    os << "<!-- REPORTHEADER -->\n"
175      << "<h3>Bug Summary</h3>\n<table class=\"simpletable\">\n"
176          "<tr><td class=\"rowname\">File:</td><td>"
177      << html::EscapeText(DirName)
178      << html::EscapeText(Entry->getName())
179      << "</td></tr>\n<tr><td class=\"rowname\">Location:</td><td>"
180         "<a href=\"#EndPath\">line "
181      << (*path.rbegin())->getLocation().asLocation().getExpansionLineNumber()
182      << ", column "
183      << (*path.rbegin())->getLocation().asLocation().getExpansionColumnNumber()
184      << "</a></td></tr>\n"
185         "<tr><td class=\"rowname\">Description:</td><td>"
186      << D.getVerboseDescription() << "</td></tr>\n";
187
188    // Output any other meta data.
189
190    for (PathDiagnostic::meta_iterator I=D.meta_begin(), E=D.meta_end();
191         I!=E; ++I) {
192      os << "<tr><td></td><td>" << html::EscapeText(*I) << "</td></tr>\n";
193    }
194
195    os << "</table>\n<!-- REPORTSUMMARYEXTRA -->\n"
196          "<h3>Annotated Source Code</h3>\n";
197
198    R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
199  }
200
201  // Embed meta-data tags.
202  {
203    std::string s;
204    llvm::raw_string_ostream os(s);
205
206    StringRef BugDesc = D.getVerboseDescription();
207    if (!BugDesc.empty())
208      os << "\n<!-- BUGDESC " << BugDesc << " -->\n";
209
210    StringRef BugType = D.getBugType();
211    if (!BugType.empty())
212      os << "\n<!-- BUGTYPE " << BugType << " -->\n";
213
214    StringRef BugCategory = D.getCategory();
215    if (!BugCategory.empty())
216      os << "\n<!-- BUGCATEGORY " << BugCategory << " -->\n";
217
218    os << "\n<!-- BUGFILE " << DirName << Entry->getName() << " -->\n";
219
220    os << "\n<!-- BUGLINE "
221       << path.back()->getLocation().asLocation().getExpansionLineNumber()
222       << " -->\n";
223
224    os << "\n<!-- BUGCOLUMN "
225      << path.back()->getLocation().asLocation().getExpansionColumnNumber()
226      << " -->\n";
227
228    os << "\n<!-- BUGPATHLENGTH " << path.size() << " -->\n";
229
230    // Mark the end of the tags.
231    os << "\n<!-- BUGMETAEND -->\n";
232
233    // Insert the text.
234    R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
235  }
236
237  // Add CSS, header, and footer.
238
239  html::AddHeaderFooterInternalBuiltinCSS(R, FID, Entry->getName());
240
241  // Get the rewrite buffer.
242  const RewriteBuffer *Buf = R.getRewriteBufferFor(FID);
243
244  if (!Buf) {
245    llvm::errs() << "warning: no diagnostics generated for main file.\n";
246    return;
247  }
248
249  // Create a path for the target HTML file.
250  int FD;
251  SmallString<128> Model, ResultPath;
252  llvm::sys::path::append(Model, Directory, "report-%%%%%%.html");
253
254  if (llvm::error_code EC =
255          llvm::sys::fs::createUniqueFile(Model.str(), FD, ResultPath)) {
256    llvm::errs() << "warning: could not create file in '" << Directory
257                 << "': " << EC.message() << '\n';
258    return;
259  }
260
261  llvm::raw_fd_ostream os(FD, true);
262
263  if (filesMade)
264    filesMade->addDiagnostic(D, getName(),
265                             llvm::sys::path::filename(ResultPath));
266
267  // Emit the HTML to disk.
268  for (RewriteBuffer::iterator I = Buf->begin(), E = Buf->end(); I!=E; ++I)
269      os << *I;
270}
271
272void HTMLDiagnostics::HandlePiece(Rewriter& R, FileID BugFileID,
273                                  const PathDiagnosticPiece& P,
274                                  unsigned num, unsigned max) {
275
276  // For now, just draw a box above the line in question, and emit the
277  // warning.
278  FullSourceLoc Pos = P.getLocation().asLocation();
279
280  if (!Pos.isValid())
281    return;
282
283  SourceManager &SM = R.getSourceMgr();
284  assert(&Pos.getManager() == &SM && "SourceManagers are different!");
285  std::pair<FileID, unsigned> LPosInfo = SM.getDecomposedExpansionLoc(Pos);
286
287  if (LPosInfo.first != BugFileID)
288    return;
289
290  const llvm::MemoryBuffer *Buf = SM.getBuffer(LPosInfo.first);
291  const char* FileStart = Buf->getBufferStart();
292
293  // Compute the column number.  Rewind from the current position to the start
294  // of the line.
295  unsigned ColNo = SM.getColumnNumber(LPosInfo.first, LPosInfo.second);
296  const char *TokInstantiationPtr =Pos.getExpansionLoc().getCharacterData();
297  const char *LineStart = TokInstantiationPtr-ColNo;
298
299  // Compute LineEnd.
300  const char *LineEnd = TokInstantiationPtr;
301  const char* FileEnd = Buf->getBufferEnd();
302  while (*LineEnd != '\n' && LineEnd != FileEnd)
303    ++LineEnd;
304
305  // Compute the margin offset by counting tabs and non-tabs.
306  unsigned PosNo = 0;
307  for (const char* c = LineStart; c != TokInstantiationPtr; ++c)
308    PosNo += *c == '\t' ? 8 : 1;
309
310  // Create the html for the message.
311
312  const char *Kind = 0;
313  switch (P.getKind()) {
314  case PathDiagnosticPiece::Call:
315      llvm_unreachable("Calls should already be handled");
316  case PathDiagnosticPiece::Event:  Kind = "Event"; break;
317  case PathDiagnosticPiece::ControlFlow: Kind = "Control"; break;
318    // Setting Kind to "Control" is intentional.
319  case PathDiagnosticPiece::Macro: Kind = "Control"; break;
320  }
321
322  std::string sbuf;
323  llvm::raw_string_ostream os(sbuf);
324
325  os << "\n<tr><td class=\"num\"></td><td class=\"line\"><div id=\"";
326
327  if (num == max)
328    os << "EndPath";
329  else
330    os << "Path" << num;
331
332  os << "\" class=\"msg";
333  if (Kind)
334    os << " msg" << Kind;
335  os << "\" style=\"margin-left:" << PosNo << "ex";
336
337  // Output a maximum size.
338  if (!isa<PathDiagnosticMacroPiece>(P)) {
339    // Get the string and determining its maximum substring.
340    const std::string& Msg = P.getString();
341    unsigned max_token = 0;
342    unsigned cnt = 0;
343    unsigned len = Msg.size();
344
345    for (std::string::const_iterator I=Msg.begin(), E=Msg.end(); I!=E; ++I)
346      switch (*I) {
347      default:
348        ++cnt;
349        continue;
350      case ' ':
351      case '\t':
352      case '\n':
353        if (cnt > max_token) max_token = cnt;
354        cnt = 0;
355      }
356
357    if (cnt > max_token)
358      max_token = cnt;
359
360    // Determine the approximate size of the message bubble in em.
361    unsigned em;
362    const unsigned max_line = 120;
363
364    if (max_token >= max_line)
365      em = max_token / 2;
366    else {
367      unsigned characters = max_line;
368      unsigned lines = len / max_line;
369
370      if (lines > 0) {
371        for (; characters > max_token; --characters)
372          if (len / characters > lines) {
373            ++characters;
374            break;
375          }
376      }
377
378      em = characters / 2;
379    }
380
381    if (em < max_line/2)
382      os << "; max-width:" << em << "em";
383  }
384  else
385    os << "; max-width:100em";
386
387  os << "\">";
388
389  if (max > 1) {
390    os << "<table class=\"msgT\"><tr><td valign=\"top\">";
391    os << "<div class=\"PathIndex";
392    if (Kind) os << " PathIndex" << Kind;
393    os << "\">" << num << "</div>";
394
395    if (num > 1) {
396      os << "</td><td><div class=\"PathNav\"><a href=\"#Path"
397         << (num - 1)
398         << "\" title=\"Previous event ("
399         << (num - 1)
400         << ")\">&#x2190;</a></div></td>";
401    }
402
403    os << "</td><td>";
404  }
405
406  if (const PathDiagnosticMacroPiece *MP =
407        dyn_cast<PathDiagnosticMacroPiece>(&P)) {
408
409    os << "Within the expansion of the macro '";
410
411    // Get the name of the macro by relexing it.
412    {
413      FullSourceLoc L = MP->getLocation().asLocation().getExpansionLoc();
414      assert(L.isFileID());
415      StringRef BufferInfo = L.getBufferData();
416      std::pair<FileID, unsigned> LocInfo = L.getDecomposedLoc();
417      const char* MacroName = LocInfo.second + BufferInfo.data();
418      Lexer rawLexer(SM.getLocForStartOfFile(LocInfo.first), PP.getLangOpts(),
419                     BufferInfo.begin(), MacroName, BufferInfo.end());
420
421      Token TheTok;
422      rawLexer.LexFromRawLexer(TheTok);
423      for (unsigned i = 0, n = TheTok.getLength(); i < n; ++i)
424        os << MacroName[i];
425    }
426
427    os << "':\n";
428
429    if (max > 1) {
430      os << "</td>";
431      if (num < max) {
432        os << "<td><div class=\"PathNav\"><a href=\"#";
433        if (num == max - 1)
434          os << "EndPath";
435        else
436          os << "Path" << (num + 1);
437        os << "\" title=\"Next event ("
438        << (num + 1)
439        << ")\">&#x2192;</a></div></td>";
440      }
441
442      os << "</tr></table>";
443    }
444
445    // Within a macro piece.  Write out each event.
446    ProcessMacroPiece(os, *MP, 0);
447  }
448  else {
449    os << html::EscapeText(P.getString());
450
451    if (max > 1) {
452      os << "</td>";
453      if (num < max) {
454        os << "<td><div class=\"PathNav\"><a href=\"#";
455        if (num == max - 1)
456          os << "EndPath";
457        else
458          os << "Path" << (num + 1);
459        os << "\" title=\"Next event ("
460           << (num + 1)
461           << ")\">&#x2192;</a></div></td>";
462      }
463
464      os << "</tr></table>";
465    }
466  }
467
468  os << "</div></td></tr>";
469
470  // Insert the new html.
471  unsigned DisplayPos = LineEnd - FileStart;
472  SourceLocation Loc =
473    SM.getLocForStartOfFile(LPosInfo.first).getLocWithOffset(DisplayPos);
474
475  R.InsertTextBefore(Loc, os.str());
476
477  // Now highlight the ranges.
478  ArrayRef<SourceRange> Ranges = P.getRanges();
479  for (ArrayRef<SourceRange>::iterator I = Ranges.begin(),
480                                       E = Ranges.end(); I != E; ++I) {
481    HighlightRange(R, LPosInfo.first, *I);
482  }
483}
484
485static void EmitAlphaCounter(raw_ostream &os, unsigned n) {
486  unsigned x = n % ('z' - 'a');
487  n /= 'z' - 'a';
488
489  if (n > 0)
490    EmitAlphaCounter(os, n);
491
492  os << char('a' + x);
493}
494
495unsigned HTMLDiagnostics::ProcessMacroPiece(raw_ostream &os,
496                                            const PathDiagnosticMacroPiece& P,
497                                            unsigned num) {
498
499  for (PathPieces::const_iterator I = P.subPieces.begin(), E=P.subPieces.end();
500        I!=E; ++I) {
501
502    if (const PathDiagnosticMacroPiece *MP =
503          dyn_cast<PathDiagnosticMacroPiece>(*I)) {
504      num = ProcessMacroPiece(os, *MP, num);
505      continue;
506    }
507
508    if (PathDiagnosticEventPiece *EP = dyn_cast<PathDiagnosticEventPiece>(*I)) {
509      os << "<div class=\"msg msgEvent\" style=\"width:94%; "
510            "margin-left:5px\">"
511            "<table class=\"msgT\"><tr>"
512            "<td valign=\"top\"><div class=\"PathIndex PathIndexEvent\">";
513      EmitAlphaCounter(os, num++);
514      os << "</div></td><td valign=\"top\">"
515         << html::EscapeText(EP->getString())
516         << "</td></tr></table></div>\n";
517    }
518  }
519
520  return num;
521}
522
523void HTMLDiagnostics::HighlightRange(Rewriter& R, FileID BugFileID,
524                                     SourceRange Range,
525                                     const char *HighlightStart,
526                                     const char *HighlightEnd) {
527  SourceManager &SM = R.getSourceMgr();
528  const LangOptions &LangOpts = R.getLangOpts();
529
530  SourceLocation InstantiationStart = SM.getExpansionLoc(Range.getBegin());
531  unsigned StartLineNo = SM.getExpansionLineNumber(InstantiationStart);
532
533  SourceLocation InstantiationEnd = SM.getExpansionLoc(Range.getEnd());
534  unsigned EndLineNo = SM.getExpansionLineNumber(InstantiationEnd);
535
536  if (EndLineNo < StartLineNo)
537    return;
538
539  if (SM.getFileID(InstantiationStart) != BugFileID ||
540      SM.getFileID(InstantiationEnd) != BugFileID)
541    return;
542
543  // Compute the column number of the end.
544  unsigned EndColNo = SM.getExpansionColumnNumber(InstantiationEnd);
545  unsigned OldEndColNo = EndColNo;
546
547  if (EndColNo) {
548    // Add in the length of the token, so that we cover multi-char tokens.
549    EndColNo += Lexer::MeasureTokenLength(Range.getEnd(), SM, LangOpts)-1;
550  }
551
552  // Highlight the range.  Make the span tag the outermost tag for the
553  // selected range.
554
555  SourceLocation E =
556    InstantiationEnd.getLocWithOffset(EndColNo - OldEndColNo);
557
558  html::HighlightRange(R, InstantiationStart, E, HighlightStart, HighlightEnd);
559}
560