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 llvm::sys::Path Directory, FilePrefix;
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), FilePrefix(prefix), createdDir(false), noDir(false),
75 // All html files begin with "report"
76 FilePrefix.appendComponent("report");
79 void ento::createHTMLDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
80 PathDiagnosticConsumers &C,
81 const std::string& prefix,
82 const Preprocessor &PP) {
83 C.push_back(new HTMLDiagnostics(prefix, PP));
86 //===----------------------------------------------------------------------===//
88 //===----------------------------------------------------------------------===//
90 void HTMLDiagnostics::FlushDiagnosticsImpl(
91 std::vector<const PathDiagnostic *> &Diags,
92 FilesMade *filesMade) {
93 for (std::vector<const PathDiagnostic *>::iterator it = Diags.begin(),
94 et = Diags.end(); it != et; ++it) {
95 ReportDiag(**it, filesMade);
99 void HTMLDiagnostics::ReportDiag(const PathDiagnostic& D,
100 FilesMade *filesMade) {
102 // Create the HTML directory if it is missing.
105 std::string ErrorMsg;
106 Directory.createDirectoryOnDisk(true, &ErrorMsg);
109 if (llvm::sys::fs::is_directory(Directory.str(), IsDirectory) ||
111 llvm::errs() << "warning: could not create directory '"
112 << Directory.str() << "'\n"
113 << "reason: " << ErrorMsg << '\n';
124 // First flatten out the entire path to make it easier to use.
125 PathPieces path = D.path.flatten(/*ShouldFlattenMacros=*/false);
127 // The path as already been prechecked that all parts of the path are
128 // from the same file and that it is non-empty.
129 const SourceManager &SMgr = (*path.begin())->getLocation().getManager();
130 assert(!path.empty());
132 (*path.begin())->getLocation().asLocation().getExpansionLoc().getFileID();
133 assert(!FID.isInvalid());
135 // Create a new rewriter to generate HTML.
136 Rewriter R(const_cast<SourceManager&>(SMgr), PP.getLangOpts());
139 unsigned n = path.size();
142 for (PathPieces::const_reverse_iterator I = path.rbegin(),
145 HandlePiece(R, FID, **I, n, max);
147 // Add line numbers, header, footer, etc.
149 // unsigned FID = R.getSourceMgr().getMainFileID();
150 html::EscapeText(R, FID);
151 html::AddLineNumbers(R, FID);
153 // If we have a preprocessor, relex the file and syntax highlight.
154 // We might not have a preprocessor if we come from a deserialized AST file,
157 html::SyntaxHighlight(R, FID, PP);
158 html::HighlightMacros(R, FID, PP);
160 // Get the full directory name of the analyzed file.
162 const FileEntry* Entry = SMgr.getFileEntryForID(FID);
164 // This is a cludge; basically we want to append either the full
165 // working directory if we have no directory information. This is
166 // a work in progress.
168 std::string DirName = "";
170 if (llvm::sys::path::is_relative(Entry->getName())) {
171 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
172 DirName = P.str() + "/";
175 // Add the name of the file as an <h1> tag.
179 llvm::raw_string_ostream os(s);
181 os << "<!-- REPORTHEADER -->\n"
182 << "<h3>Bug Summary</h3>\n<table class=\"simpletable\">\n"
183 "<tr><td class=\"rowname\">File:</td><td>"
184 << html::EscapeText(DirName)
185 << html::EscapeText(Entry->getName())
186 << "</td></tr>\n<tr><td class=\"rowname\">Location:</td><td>"
187 "<a href=\"#EndPath\">line "
188 << (*path.rbegin())->getLocation().asLocation().getExpansionLineNumber()
190 << (*path.rbegin())->getLocation().asLocation().getExpansionColumnNumber()
191 << "</a></td></tr>\n"
192 "<tr><td class=\"rowname\">Description:</td><td>"
193 << D.getVerboseDescription() << "</td></tr>\n";
195 // Output any other meta data.
197 for (PathDiagnostic::meta_iterator I=D.meta_begin(), E=D.meta_end();
199 os << "<tr><td></td><td>" << html::EscapeText(*I) << "</td></tr>\n";
202 os << "</table>\n<!-- REPORTSUMMARYEXTRA -->\n"
203 "<h3>Annotated Source Code</h3>\n";
205 R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
208 // Embed meta-data tags.
211 llvm::raw_string_ostream os(s);
213 StringRef BugDesc = D.getVerboseDescription();
214 if (!BugDesc.empty())
215 os << "\n<!-- BUGDESC " << BugDesc << " -->\n";
217 StringRef BugType = D.getBugType();
218 if (!BugType.empty())
219 os << "\n<!-- BUGTYPE " << BugType << " -->\n";
221 StringRef BugCategory = D.getCategory();
222 if (!BugCategory.empty())
223 os << "\n<!-- BUGCATEGORY " << BugCategory << " -->\n";
225 os << "\n<!-- BUGFILE " << DirName << Entry->getName() << " -->\n";
227 os << "\n<!-- BUGLINE "
228 << path.back()->getLocation().asLocation().getExpansionLineNumber()
231 os << "\n<!-- BUGPATHLENGTH " << path.size() << " -->\n";
233 // Mark the end of the tags.
234 os << "\n<!-- BUGMETAEND -->\n";
237 R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
240 // Add CSS, header, and footer.
242 html::AddHeaderFooterInternalBuiltinCSS(R, FID, Entry->getName());
244 // Get the rewrite buffer.
245 const RewriteBuffer *Buf = R.getRewriteBufferFor(FID);
248 llvm::errs() << "warning: no diagnostics generated for main file.\n";
252 // Create a path for the target HTML file.
253 llvm::sys::Path F(FilePrefix);
254 F.makeUnique(false, NULL);
256 // Rename the file with an HTML extension.
257 llvm::sys::Path H(F);
258 H.appendSuffix("html");
259 F.renamePathOnDisk(H, NULL);
261 std::string ErrorMsg;
262 llvm::raw_fd_ostream os(H.c_str(), ErrorMsg);
264 if (!ErrorMsg.empty()) {
265 llvm::errs() << "warning: could not create file '" << F.str()
271 filesMade->addDiagnostic(D, getName(), llvm::sys::path::filename(H.str()));
274 // Emit the HTML to disk.
275 for (RewriteBuffer::iterator I = Buf->begin(), E = Buf->end(); I!=E; ++I)
279 void HTMLDiagnostics::HandlePiece(Rewriter& R, FileID BugFileID,
280 const PathDiagnosticPiece& P,
281 unsigned num, unsigned max) {
283 // For now, just draw a box above the line in question, and emit the
285 FullSourceLoc Pos = P.getLocation().asLocation();
290 SourceManager &SM = R.getSourceMgr();
291 assert(&Pos.getManager() == &SM && "SourceManagers are different!");
292 std::pair<FileID, unsigned> LPosInfo = SM.getDecomposedExpansionLoc(Pos);
294 if (LPosInfo.first != BugFileID)
297 const llvm::MemoryBuffer *Buf = SM.getBuffer(LPosInfo.first);
298 const char* FileStart = Buf->getBufferStart();
300 // Compute the column number. Rewind from the current position to the start
302 unsigned ColNo = SM.getColumnNumber(LPosInfo.first, LPosInfo.second);
303 const char *TokInstantiationPtr =Pos.getExpansionLoc().getCharacterData();
304 const char *LineStart = TokInstantiationPtr-ColNo;
307 const char *LineEnd = TokInstantiationPtr;
308 const char* FileEnd = Buf->getBufferEnd();
309 while (*LineEnd != '\n' && LineEnd != FileEnd)
312 // Compute the margin offset by counting tabs and non-tabs.
314 for (const char* c = LineStart; c != TokInstantiationPtr; ++c)
315 PosNo += *c == '\t' ? 8 : 1;
317 // Create the html for the message.
319 const char *Kind = 0;
320 switch (P.getKind()) {
321 case PathDiagnosticPiece::Call:
322 llvm_unreachable("Calls should already be handled");
323 case PathDiagnosticPiece::Event: Kind = "Event"; break;
324 case PathDiagnosticPiece::ControlFlow: Kind = "Control"; break;
325 // Setting Kind to "Control" is intentional.
326 case PathDiagnosticPiece::Macro: Kind = "Control"; break;
330 llvm::raw_string_ostream os(sbuf);
332 os << "\n<tr><td class=\"num\"></td><td class=\"line\"><div id=\"";
339 os << "\" class=\"msg";
341 os << " msg" << Kind;
342 os << "\" style=\"margin-left:" << PosNo << "ex";
344 // Output a maximum size.
345 if (!isa<PathDiagnosticMacroPiece>(P)) {
346 // Get the string and determining its maximum substring.
347 const std::string& Msg = P.getString();
348 unsigned max_token = 0;
350 unsigned len = Msg.size();
352 for (std::string::const_iterator I=Msg.begin(), E=Msg.end(); I!=E; ++I)
360 if (cnt > max_token) max_token = cnt;
367 // Determine the approximate size of the message bubble in em.
369 const unsigned max_line = 120;
371 if (max_token >= max_line)
374 unsigned characters = max_line;
375 unsigned lines = len / max_line;
378 for (; characters > max_token; --characters)
379 if (len / characters > lines) {
389 os << "; max-width:" << em << "em";
392 os << "; max-width:100em";
397 os << "<table class=\"msgT\"><tr><td valign=\"top\">";
398 os << "<div class=\"PathIndex";
399 if (Kind) os << " PathIndex" << Kind;
400 os << "\">" << num << "</div>";
403 os << "</td><td><div class=\"PathNav\"><a href=\"#Path"
405 << "\" title=\"Previous event ("
407 << ")\">←</a></div></td>";
413 if (const PathDiagnosticMacroPiece *MP =
414 dyn_cast<PathDiagnosticMacroPiece>(&P)) {
416 os << "Within the expansion of the macro '";
418 // Get the name of the macro by relexing it.
420 FullSourceLoc L = MP->getLocation().asLocation().getExpansionLoc();
421 assert(L.isFileID());
422 StringRef BufferInfo = L.getBufferData();
423 std::pair<FileID, unsigned> LocInfo = L.getDecomposedLoc();
424 const char* MacroName = LocInfo.second + BufferInfo.data();
425 Lexer rawLexer(SM.getLocForStartOfFile(LocInfo.first), PP.getLangOpts(),
426 BufferInfo.begin(), MacroName, BufferInfo.end());
429 rawLexer.LexFromRawLexer(TheTok);
430 for (unsigned i = 0, n = TheTok.getLength(); i < n; ++i)
439 os << "<td><div class=\"PathNav\"><a href=\"#";
443 os << "Path" << (num + 1);
444 os << "\" title=\"Next event ("
446 << ")\">→</a></div></td>";
449 os << "</tr></table>";
452 // Within a macro piece. Write out each event.
453 ProcessMacroPiece(os, *MP, 0);
456 os << html::EscapeText(P.getString());
461 os << "<td><div class=\"PathNav\"><a href=\"#";
465 os << "Path" << (num + 1);
466 os << "\" title=\"Next event ("
468 << ")\">→</a></div></td>";
471 os << "</tr></table>";
475 os << "</div></td></tr>";
477 // Insert the new html.
478 unsigned DisplayPos = LineEnd - FileStart;
480 SM.getLocForStartOfFile(LPosInfo.first).getLocWithOffset(DisplayPos);
482 R.InsertTextBefore(Loc, os.str());
484 // Now highlight the ranges.
485 ArrayRef<SourceRange> Ranges = P.getRanges();
486 for (ArrayRef<SourceRange>::iterator I = Ranges.begin(),
487 E = Ranges.end(); I != E; ++I) {
488 HighlightRange(R, LPosInfo.first, *I);
492 static void EmitAlphaCounter(raw_ostream &os, unsigned n) {
493 unsigned x = n % ('z' - 'a');
497 EmitAlphaCounter(os, n);
502 unsigned HTMLDiagnostics::ProcessMacroPiece(raw_ostream &os,
503 const PathDiagnosticMacroPiece& P,
506 for (PathPieces::const_iterator I = P.subPieces.begin(), E=P.subPieces.end();
509 if (const PathDiagnosticMacroPiece *MP =
510 dyn_cast<PathDiagnosticMacroPiece>(*I)) {
511 num = ProcessMacroPiece(os, *MP, num);
515 if (PathDiagnosticEventPiece *EP = dyn_cast<PathDiagnosticEventPiece>(*I)) {
516 os << "<div class=\"msg msgEvent\" style=\"width:94%; "
518 "<table class=\"msgT\"><tr>"
519 "<td valign=\"top\"><div class=\"PathIndex PathIndexEvent\">";
520 EmitAlphaCounter(os, num++);
521 os << "</div></td><td valign=\"top\">"
522 << html::EscapeText(EP->getString())
523 << "</td></tr></table></div>\n";
530 void HTMLDiagnostics::HighlightRange(Rewriter& R, FileID BugFileID,
532 const char *HighlightStart,
533 const char *HighlightEnd) {
534 SourceManager &SM = R.getSourceMgr();
535 const LangOptions &LangOpts = R.getLangOpts();
537 SourceLocation InstantiationStart = SM.getExpansionLoc(Range.getBegin());
538 unsigned StartLineNo = SM.getExpansionLineNumber(InstantiationStart);
540 SourceLocation InstantiationEnd = SM.getExpansionLoc(Range.getEnd());
541 unsigned EndLineNo = SM.getExpansionLineNumber(InstantiationEnd);
543 if (EndLineNo < StartLineNo)
546 if (SM.getFileID(InstantiationStart) != BugFileID ||
547 SM.getFileID(InstantiationEnd) != BugFileID)
550 // Compute the column number of the end.
551 unsigned EndColNo = SM.getExpansionColumnNumber(InstantiationEnd);
552 unsigned OldEndColNo = EndColNo;
555 // Add in the length of the token, so that we cover multi-char tokens.
556 EndColNo += Lexer::MeasureTokenLength(Range.getEnd(), SM, LangOpts)-1;
559 // Highlight the range. Make the span tag the outermost tag for the
563 InstantiationEnd.getLocWithOffset(EndColNo - OldEndColNo);
565 html::HighlightRange(R, InstantiationStart, E, HighlightStart, HighlightEnd);