1 //===--- HTMLDiagnostics.cpp - HTML Diagnostics for Paths ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the HTMLDiagnostics object.
12 //===----------------------------------------------------------------------===//
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"
29 using namespace clang;
32 //===----------------------------------------------------------------------===//
34 //===----------------------------------------------------------------------===//
38 class HTMLDiagnostics : public PathDiagnosticConsumer {
39 std::string Directory;
40 bool createdDir, noDir;
41 const Preprocessor &PP;
43 HTMLDiagnostics(const std::string& prefix, const Preprocessor &pp);
45 virtual ~HTMLDiagnostics() { FlushDiagnostics(NULL); }
47 virtual void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
48 FilesMade *filesMade);
50 virtual StringRef getName() const {
51 return "HTMLDiagnostics";
54 unsigned ProcessMacroPiece(raw_ostream &os,
55 const PathDiagnosticMacroPiece& P,
58 void HandlePiece(Rewriter& R, FileID BugFileID,
59 const PathDiagnosticPiece& P, unsigned num, unsigned max);
61 void HighlightRange(Rewriter& R, FileID BugFileID, SourceRange Range,
62 const char *HighlightStart = "<span class=\"mrange\">",
63 const char *HighlightEnd = "</span>");
65 void ReportDiag(const PathDiagnostic& D,
66 FilesMade *filesMade);
69 } // end anonymous namespace
71 HTMLDiagnostics::HTMLDiagnostics(const std::string& prefix,
72 const Preprocessor &pp)
73 : Directory(prefix), createdDir(false), noDir(false), PP(pp) {
76 void ento::createHTMLDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
77 PathDiagnosticConsumers &C,
78 const std::string& prefix,
79 const Preprocessor &PP) {
80 C.push_back(new HTMLDiagnostics(prefix, PP));
83 //===----------------------------------------------------------------------===//
85 //===----------------------------------------------------------------------===//
87 void 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);
96 void HTMLDiagnostics::ReportDiag(const PathDiagnostic& D,
97 FilesMade *filesMade) {
99 // Create the HTML directory if it is missing.
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';
117 // First flatten out the entire path to make it easier to use.
118 PathPieces path = D.path.flatten(/*ShouldFlattenMacros=*/false);
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());
125 (*path.begin())->getLocation().asLocation().getExpansionLoc().getFileID();
126 assert(!FID.isInvalid());
128 // Create a new rewriter to generate HTML.
129 Rewriter R(const_cast<SourceManager&>(SMgr), PP.getLangOpts());
132 unsigned n = path.size();
135 for (PathPieces::const_reverse_iterator I = path.rbegin(),
138 HandlePiece(R, FID, **I, n, max);
140 // Add line numbers, header, footer, etc.
142 // unsigned FID = R.getSourceMgr().getMainFileID();
143 html::EscapeText(R, FID);
144 html::AddLineNumbers(R, FID);
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,
150 html::SyntaxHighlight(R, FID, PP);
151 html::HighlightMacros(R, FID, PP);
153 // Get the full directory name of the analyzed file.
155 const FileEntry* Entry = SMgr.getFileEntryForID(FID);
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.
161 llvm::SmallString<0> DirName;
163 if (llvm::sys::path::is_relative(Entry->getName())) {
164 llvm::sys::fs::current_path(DirName);
168 // Add the name of the file as an <h1> tag.
172 llvm::raw_string_ostream os(s);
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()
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";
188 // Output any other meta data.
190 for (PathDiagnostic::meta_iterator I=D.meta_begin(), E=D.meta_end();
192 os << "<tr><td></td><td>" << html::EscapeText(*I) << "</td></tr>\n";
195 os << "</table>\n<!-- REPORTSUMMARYEXTRA -->\n"
196 "<h3>Annotated Source Code</h3>\n";
198 R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
201 // Embed meta-data tags.
204 llvm::raw_string_ostream os(s);
206 StringRef BugDesc = D.getVerboseDescription();
207 if (!BugDesc.empty())
208 os << "\n<!-- BUGDESC " << BugDesc << " -->\n";
210 StringRef BugType = D.getBugType();
211 if (!BugType.empty())
212 os << "\n<!-- BUGTYPE " << BugType << " -->\n";
214 StringRef BugCategory = D.getCategory();
215 if (!BugCategory.empty())
216 os << "\n<!-- BUGCATEGORY " << BugCategory << " -->\n";
218 os << "\n<!-- BUGFILE " << DirName << Entry->getName() << " -->\n";
220 os << "\n<!-- BUGLINE "
221 << path.back()->getLocation().asLocation().getExpansionLineNumber()
224 os << "\n<!-- BUGCOLUMN "
225 << path.back()->getLocation().asLocation().getExpansionColumnNumber()
228 os << "\n<!-- BUGPATHLENGTH " << path.size() << " -->\n";
230 // Mark the end of the tags.
231 os << "\n<!-- BUGMETAEND -->\n";
234 R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
237 // Add CSS, header, and footer.
239 html::AddHeaderFooterInternalBuiltinCSS(R, FID, Entry->getName());
241 // Get the rewrite buffer.
242 const RewriteBuffer *Buf = R.getRewriteBufferFor(FID);
245 llvm::errs() << "warning: no diagnostics generated for main file.\n";
249 // Create a path for the target HTML file.
251 SmallString<128> Model, ResultPath;
252 llvm::sys::path::append(Model, Directory, "report-%%%%%%.html");
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';
261 llvm::raw_fd_ostream os(FD, true);
264 filesMade->addDiagnostic(D, getName(),
265 llvm::sys::path::filename(ResultPath));
267 // Emit the HTML to disk.
268 for (RewriteBuffer::iterator I = Buf->begin(), E = Buf->end(); I!=E; ++I)
272 void HTMLDiagnostics::HandlePiece(Rewriter& R, FileID BugFileID,
273 const PathDiagnosticPiece& P,
274 unsigned num, unsigned max) {
276 // For now, just draw a box above the line in question, and emit the
278 FullSourceLoc Pos = P.getLocation().asLocation();
283 SourceManager &SM = R.getSourceMgr();
284 assert(&Pos.getManager() == &SM && "SourceManagers are different!");
285 std::pair<FileID, unsigned> LPosInfo = SM.getDecomposedExpansionLoc(Pos);
287 if (LPosInfo.first != BugFileID)
290 const llvm::MemoryBuffer *Buf = SM.getBuffer(LPosInfo.first);
291 const char* FileStart = Buf->getBufferStart();
293 // Compute the column number. Rewind from the current position to the start
295 unsigned ColNo = SM.getColumnNumber(LPosInfo.first, LPosInfo.second);
296 const char *TokInstantiationPtr =Pos.getExpansionLoc().getCharacterData();
297 const char *LineStart = TokInstantiationPtr-ColNo;
300 const char *LineEnd = TokInstantiationPtr;
301 const char* FileEnd = Buf->getBufferEnd();
302 while (*LineEnd != '\n' && LineEnd != FileEnd)
305 // Compute the margin offset by counting tabs and non-tabs.
307 for (const char* c = LineStart; c != TokInstantiationPtr; ++c)
308 PosNo += *c == '\t' ? 8 : 1;
310 // Create the html for the message.
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;
323 llvm::raw_string_ostream os(sbuf);
325 os << "\n<tr><td class=\"num\"></td><td class=\"line\"><div id=\"";
332 os << "\" class=\"msg";
334 os << " msg" << Kind;
335 os << "\" style=\"margin-left:" << PosNo << "ex";
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;
343 unsigned len = Msg.size();
345 for (std::string::const_iterator I=Msg.begin(), E=Msg.end(); I!=E; ++I)
353 if (cnt > max_token) max_token = cnt;
360 // Determine the approximate size of the message bubble in em.
362 const unsigned max_line = 120;
364 if (max_token >= max_line)
367 unsigned characters = max_line;
368 unsigned lines = len / max_line;
371 for (; characters > max_token; --characters)
372 if (len / characters > lines) {
382 os << "; max-width:" << em << "em";
385 os << "; max-width:100em";
390 os << "<table class=\"msgT\"><tr><td valign=\"top\">";
391 os << "<div class=\"PathIndex";
392 if (Kind) os << " PathIndex" << Kind;
393 os << "\">" << num << "</div>";
396 os << "</td><td><div class=\"PathNav\"><a href=\"#Path"
398 << "\" title=\"Previous event ("
400 << ")\">←</a></div></td>";
406 if (const PathDiagnosticMacroPiece *MP =
407 dyn_cast<PathDiagnosticMacroPiece>(&P)) {
409 os << "Within the expansion of the macro '";
411 // Get the name of the macro by relexing it.
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());
422 rawLexer.LexFromRawLexer(TheTok);
423 for (unsigned i = 0, n = TheTok.getLength(); i < n; ++i)
432 os << "<td><div class=\"PathNav\"><a href=\"#";
436 os << "Path" << (num + 1);
437 os << "\" title=\"Next event ("
439 << ")\">→</a></div></td>";
442 os << "</tr></table>";
445 // Within a macro piece. Write out each event.
446 ProcessMacroPiece(os, *MP, 0);
449 os << html::EscapeText(P.getString());
454 os << "<td><div class=\"PathNav\"><a href=\"#";
458 os << "Path" << (num + 1);
459 os << "\" title=\"Next event ("
461 << ")\">→</a></div></td>";
464 os << "</tr></table>";
468 os << "</div></td></tr>";
470 // Insert the new html.
471 unsigned DisplayPos = LineEnd - FileStart;
473 SM.getLocForStartOfFile(LPosInfo.first).getLocWithOffset(DisplayPos);
475 R.InsertTextBefore(Loc, os.str());
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);
485 static void EmitAlphaCounter(raw_ostream &os, unsigned n) {
486 unsigned x = n % ('z' - 'a');
490 EmitAlphaCounter(os, n);
495 unsigned HTMLDiagnostics::ProcessMacroPiece(raw_ostream &os,
496 const PathDiagnosticMacroPiece& P,
499 for (PathPieces::const_iterator I = P.subPieces.begin(), E=P.subPieces.end();
502 if (const PathDiagnosticMacroPiece *MP =
503 dyn_cast<PathDiagnosticMacroPiece>(*I)) {
504 num = ProcessMacroPiece(os, *MP, num);
508 if (PathDiagnosticEventPiece *EP = dyn_cast<PathDiagnosticEventPiece>(*I)) {
509 os << "<div class=\"msg msgEvent\" style=\"width:94%; "
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";
523 void HTMLDiagnostics::HighlightRange(Rewriter& R, FileID BugFileID,
525 const char *HighlightStart,
526 const char *HighlightEnd) {
527 SourceManager &SM = R.getSourceMgr();
528 const LangOptions &LangOpts = R.getLangOpts();
530 SourceLocation InstantiationStart = SM.getExpansionLoc(Range.getBegin());
531 unsigned StartLineNo = SM.getExpansionLineNumber(InstantiationStart);
533 SourceLocation InstantiationEnd = SM.getExpansionLoc(Range.getEnd());
534 unsigned EndLineNo = SM.getExpansionLineNumber(InstantiationEnd);
536 if (EndLineNo < StartLineNo)
539 if (SM.getFileID(InstantiationStart) != BugFileID ||
540 SM.getFileID(InstantiationEnd) != BugFileID)
543 // Compute the column number of the end.
544 unsigned EndColNo = SM.getExpansionColumnNumber(InstantiationEnd);
545 unsigned OldEndColNo = 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;
552 // Highlight the range. Make the span tag the outermost tag for the
556 InstantiationEnd.getLocWithOffset(EndColNo - OldEndColNo);
558 html::HighlightRange(R, InstantiationStart, E, HighlightStart, HighlightEnd);