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 "clang/StaticAnalyzer/Core/CheckerManager.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/raw_ostream.h"
31 using namespace clang;
34 //===----------------------------------------------------------------------===//
36 //===----------------------------------------------------------------------===//
40 class HTMLDiagnostics : public PathDiagnosticConsumer {
41 std::string Directory;
42 bool createdDir, noDir;
43 const Preprocessor &PP;
44 AnalyzerOptions &AnalyzerOpts;
46 HTMLDiagnostics(AnalyzerOptions &AnalyzerOpts, const std::string& prefix, const Preprocessor &pp);
48 ~HTMLDiagnostics() override { FlushDiagnostics(nullptr); }
50 void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
51 FilesMade *filesMade) override;
53 StringRef getName() const override {
54 return "HTMLDiagnostics";
57 unsigned ProcessMacroPiece(raw_ostream &os,
58 const PathDiagnosticMacroPiece& P,
61 void HandlePiece(Rewriter& R, FileID BugFileID,
62 const PathDiagnosticPiece& P, unsigned num, unsigned max);
64 void HighlightRange(Rewriter& R, FileID BugFileID, SourceRange Range,
65 const char *HighlightStart = "<span class=\"mrange\">",
66 const char *HighlightEnd = "</span>");
68 void ReportDiag(const PathDiagnostic& D,
69 FilesMade *filesMade);
72 } // end anonymous namespace
74 HTMLDiagnostics::HTMLDiagnostics(AnalyzerOptions &AnalyzerOpts,
75 const std::string& prefix,
76 const Preprocessor &pp)
77 : Directory(prefix), createdDir(false), noDir(false), PP(pp), AnalyzerOpts(AnalyzerOpts) {
80 void ento::createHTMLDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
81 PathDiagnosticConsumers &C,
82 const std::string& prefix,
83 const Preprocessor &PP) {
84 C.push_back(new HTMLDiagnostics(AnalyzerOpts, prefix, PP));
87 //===----------------------------------------------------------------------===//
89 //===----------------------------------------------------------------------===//
91 void HTMLDiagnostics::FlushDiagnosticsImpl(
92 std::vector<const PathDiagnostic *> &Diags,
93 FilesMade *filesMade) {
94 for (std::vector<const PathDiagnostic *>::iterator it = Diags.begin(),
95 et = Diags.end(); it != et; ++it) {
96 ReportDiag(**it, filesMade);
100 void HTMLDiagnostics::ReportDiag(const PathDiagnostic& D,
101 FilesMade *filesMade) {
103 // Create the HTML directory if it is missing.
106 if (std::error_code ec = llvm::sys::fs::create_directories(Directory)) {
107 llvm::errs() << "warning: could not create directory '"
108 << Directory << "': " << ec.message() << '\n';
119 // First flatten out the entire path to make it easier to use.
120 PathPieces path = D.path.flatten(/*ShouldFlattenMacros=*/false);
122 // The path as already been prechecked that all parts of the path are
123 // from the same file and that it is non-empty.
124 const SourceManager &SMgr = (*path.begin())->getLocation().getManager();
125 assert(!path.empty());
127 (*path.begin())->getLocation().asLocation().getExpansionLoc().getFileID();
128 assert(!FID.isInvalid());
130 // Create a new rewriter to generate HTML.
131 Rewriter R(const_cast<SourceManager&>(SMgr), PP.getLangOpts());
133 // Get the function/method name
134 SmallString<128> declName("unknown");
136 if (const Decl *DeclWithIssue = D.getDeclWithIssue()) {
137 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DeclWithIssue)) {
138 declName = ND->getDeclName().getAsString();
141 if (const Stmt *Body = DeclWithIssue->getBody()) {
142 // Retrieve the relative position of the declaration which will be used
145 SMgr.getExpansionLoc((*path.rbegin())->getLocation().asLocation()),
147 FullSourceLoc FunL(SMgr.getExpansionLoc(Body->getLocStart()), SMgr);
148 offsetDecl = L.getExpansionLineNumber() - FunL.getExpansionLineNumber();
153 unsigned n = path.size();
156 for (PathPieces::const_reverse_iterator I = path.rbegin(),
159 HandlePiece(R, FID, **I, n, max);
161 // Add line numbers, header, footer, etc.
163 // unsigned FID = R.getSourceMgr().getMainFileID();
164 html::EscapeText(R, FID);
165 html::AddLineNumbers(R, FID);
167 // If we have a preprocessor, relex the file and syntax highlight.
168 // We might not have a preprocessor if we come from a deserialized AST file,
171 html::SyntaxHighlight(R, FID, PP);
172 html::HighlightMacros(R, FID, PP);
174 // Get the full directory name of the analyzed file.
176 const FileEntry* Entry = SMgr.getFileEntryForID(FID);
178 // This is a cludge; basically we want to append either the full
179 // working directory if we have no directory information. This is
180 // a work in progress.
182 llvm::SmallString<0> DirName;
184 if (llvm::sys::path::is_relative(Entry->getName())) {
185 llvm::sys::fs::current_path(DirName);
189 int LineNumber = (*path.rbegin())->getLocation().asLocation().getExpansionLineNumber();
190 int ColumnNumber = (*path.rbegin())->getLocation().asLocation().getExpansionColumnNumber();
192 // Add the name of the file as an <h1> tag.
196 llvm::raw_string_ostream os(s);
198 os << "<!-- REPORTHEADER -->\n"
199 << "<h3>Bug Summary</h3>\n<table class=\"simpletable\">\n"
200 "<tr><td class=\"rowname\">File:</td><td>"
201 << html::EscapeText(DirName)
202 << html::EscapeText(Entry->getName())
203 << "</td></tr>\n<tr><td class=\"rowname\">Location:</td><td>"
204 "<a href=\"#EndPath\">line "
208 << "</a></td></tr>\n"
209 "<tr><td class=\"rowname\">Description:</td><td>"
210 << D.getVerboseDescription() << "</td></tr>\n";
212 // Output any other meta data.
214 for (PathDiagnostic::meta_iterator I=D.meta_begin(), E=D.meta_end();
216 os << "<tr><td></td><td>" << html::EscapeText(*I) << "</td></tr>\n";
219 os << "</table>\n<!-- REPORTSUMMARYEXTRA -->\n"
220 "<h3>Annotated Source Code</h3>\n";
222 R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
225 // Embed meta-data tags.
228 llvm::raw_string_ostream os(s);
230 StringRef BugDesc = D.getVerboseDescription();
231 if (!BugDesc.empty())
232 os << "\n<!-- BUGDESC " << BugDesc << " -->\n";
234 StringRef BugType = D.getBugType();
235 if (!BugType.empty())
236 os << "\n<!-- BUGTYPE " << BugType << " -->\n";
238 StringRef BugCategory = D.getCategory();
239 if (!BugCategory.empty())
240 os << "\n<!-- BUGCATEGORY " << BugCategory << " -->\n";
242 os << "\n<!-- BUGFILE " << DirName << Entry->getName() << " -->\n";
244 os << "\n<!-- FILENAME " << llvm::sys::path::filename(Entry->getName()) << " -->\n";
246 os << "\n<!-- FUNCTIONNAME " << declName << " -->\n";
248 os << "\n<!-- BUGLINE "
252 os << "\n<!-- BUGCOLUMN "
256 os << "\n<!-- BUGPATHLENGTH " << path.size() << " -->\n";
258 // Mark the end of the tags.
259 os << "\n<!-- BUGMETAEND -->\n";
262 R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
265 // Add CSS, header, and footer.
267 html::AddHeaderFooterInternalBuiltinCSS(R, FID, Entry->getName());
269 // Get the rewrite buffer.
270 const RewriteBuffer *Buf = R.getRewriteBufferFor(FID);
273 llvm::errs() << "warning: no diagnostics generated for main file.\n";
277 // Create a path for the target HTML file.
279 SmallString<128> Model, ResultPath;
281 if (!AnalyzerOpts.shouldWriteStableReportFilename()) {
282 llvm::sys::path::append(Model, Directory, "report-%%%%%%.html");
284 if (std::error_code EC =
285 llvm::sys::fs::createUniqueFile(Model, FD, ResultPath)) {
286 llvm::errs() << "warning: could not create file in '" << Directory
287 << "': " << EC.message() << '\n';
295 // Find a filename which is not already used
296 std::stringstream filename;
298 filename << "report-"
299 << llvm::sys::path::filename(Entry->getName()).str()
300 << "-" << declName.c_str()
302 << "-" << i << ".html";
303 llvm::sys::path::append(Model, Directory,
305 EC = llvm::sys::fs::openFileForWrite(Model,
307 llvm::sys::fs::F_RW |
308 llvm::sys::fs::F_Excl);
309 if (EC && EC != std::errc::file_exists) {
310 llvm::errs() << "warning: could not create file '" << Model
311 << "': " << EC.message() << '\n';
318 llvm::raw_fd_ostream os(FD, true);
321 filesMade->addDiagnostic(D, getName(),
322 llvm::sys::path::filename(ResultPath));
324 // Emit the HTML to disk.
325 for (RewriteBuffer::iterator I = Buf->begin(), E = Buf->end(); I!=E; ++I)
329 void HTMLDiagnostics::HandlePiece(Rewriter& R, FileID BugFileID,
330 const PathDiagnosticPiece& P,
331 unsigned num, unsigned max) {
333 // For now, just draw a box above the line in question, and emit the
335 FullSourceLoc Pos = P.getLocation().asLocation();
340 SourceManager &SM = R.getSourceMgr();
341 assert(&Pos.getManager() == &SM && "SourceManagers are different!");
342 std::pair<FileID, unsigned> LPosInfo = SM.getDecomposedExpansionLoc(Pos);
344 if (LPosInfo.first != BugFileID)
347 const llvm::MemoryBuffer *Buf = SM.getBuffer(LPosInfo.first);
348 const char* FileStart = Buf->getBufferStart();
350 // Compute the column number. Rewind from the current position to the start
352 unsigned ColNo = SM.getColumnNumber(LPosInfo.first, LPosInfo.second);
353 const char *TokInstantiationPtr =Pos.getExpansionLoc().getCharacterData();
354 const char *LineStart = TokInstantiationPtr-ColNo;
357 const char *LineEnd = TokInstantiationPtr;
358 const char* FileEnd = Buf->getBufferEnd();
359 while (*LineEnd != '\n' && LineEnd != FileEnd)
362 // Compute the margin offset by counting tabs and non-tabs.
364 for (const char* c = LineStart; c != TokInstantiationPtr; ++c)
365 PosNo += *c == '\t' ? 8 : 1;
367 // Create the html for the message.
369 const char *Kind = nullptr;
370 switch (P.getKind()) {
371 case PathDiagnosticPiece::Call:
372 llvm_unreachable("Calls should already be handled");
373 case PathDiagnosticPiece::Event: Kind = "Event"; break;
374 case PathDiagnosticPiece::ControlFlow: Kind = "Control"; break;
375 // Setting Kind to "Control" is intentional.
376 case PathDiagnosticPiece::Macro: Kind = "Control"; break;
380 llvm::raw_string_ostream os(sbuf);
382 os << "\n<tr><td class=\"num\"></td><td class=\"line\"><div id=\"";
389 os << "\" class=\"msg";
391 os << " msg" << Kind;
392 os << "\" style=\"margin-left:" << PosNo << "ex";
394 // Output a maximum size.
395 if (!isa<PathDiagnosticMacroPiece>(P)) {
396 // Get the string and determining its maximum substring.
397 const std::string& Msg = P.getString();
398 unsigned max_token = 0;
400 unsigned len = Msg.size();
402 for (std::string::const_iterator I=Msg.begin(), E=Msg.end(); I!=E; ++I)
410 if (cnt > max_token) max_token = cnt;
417 // Determine the approximate size of the message bubble in em.
419 const unsigned max_line = 120;
421 if (max_token >= max_line)
424 unsigned characters = max_line;
425 unsigned lines = len / max_line;
428 for (; characters > max_token; --characters)
429 if (len / characters > lines) {
439 os << "; max-width:" << em << "em";
442 os << "; max-width:100em";
447 os << "<table class=\"msgT\"><tr><td valign=\"top\">";
448 os << "<div class=\"PathIndex";
449 if (Kind) os << " PathIndex" << Kind;
450 os << "\">" << num << "</div>";
453 os << "</td><td><div class=\"PathNav\"><a href=\"#Path"
455 << "\" title=\"Previous event ("
457 << ")\">←</a></div></td>";
463 if (const PathDiagnosticMacroPiece *MP =
464 dyn_cast<PathDiagnosticMacroPiece>(&P)) {
466 os << "Within the expansion of the macro '";
468 // Get the name of the macro by relexing it.
470 FullSourceLoc L = MP->getLocation().asLocation().getExpansionLoc();
471 assert(L.isFileID());
472 StringRef BufferInfo = L.getBufferData();
473 std::pair<FileID, unsigned> LocInfo = L.getDecomposedLoc();
474 const char* MacroName = LocInfo.second + BufferInfo.data();
475 Lexer rawLexer(SM.getLocForStartOfFile(LocInfo.first), PP.getLangOpts(),
476 BufferInfo.begin(), MacroName, BufferInfo.end());
479 rawLexer.LexFromRawLexer(TheTok);
480 for (unsigned i = 0, n = TheTok.getLength(); i < n; ++i)
489 os << "<td><div class=\"PathNav\"><a href=\"#";
493 os << "Path" << (num + 1);
494 os << "\" title=\"Next event ("
496 << ")\">→</a></div></td>";
499 os << "</tr></table>";
502 // Within a macro piece. Write out each event.
503 ProcessMacroPiece(os, *MP, 0);
506 os << html::EscapeText(P.getString());
511 os << "<td><div class=\"PathNav\"><a href=\"#";
515 os << "Path" << (num + 1);
516 os << "\" title=\"Next event ("
518 << ")\">→</a></div></td>";
521 os << "</tr></table>";
525 os << "</div></td></tr>";
527 // Insert the new html.
528 unsigned DisplayPos = LineEnd - FileStart;
530 SM.getLocForStartOfFile(LPosInfo.first).getLocWithOffset(DisplayPos);
532 R.InsertTextBefore(Loc, os.str());
534 // Now highlight the ranges.
535 ArrayRef<SourceRange> Ranges = P.getRanges();
536 for (ArrayRef<SourceRange>::iterator I = Ranges.begin(),
537 E = Ranges.end(); I != E; ++I) {
538 HighlightRange(R, LPosInfo.first, *I);
542 static void EmitAlphaCounter(raw_ostream &os, unsigned n) {
543 unsigned x = n % ('z' - 'a');
547 EmitAlphaCounter(os, n);
552 unsigned HTMLDiagnostics::ProcessMacroPiece(raw_ostream &os,
553 const PathDiagnosticMacroPiece& P,
556 for (PathPieces::const_iterator I = P.subPieces.begin(), E=P.subPieces.end();
559 if (const PathDiagnosticMacroPiece *MP =
560 dyn_cast<PathDiagnosticMacroPiece>(*I)) {
561 num = ProcessMacroPiece(os, *MP, num);
565 if (PathDiagnosticEventPiece *EP = dyn_cast<PathDiagnosticEventPiece>(*I)) {
566 os << "<div class=\"msg msgEvent\" style=\"width:94%; "
568 "<table class=\"msgT\"><tr>"
569 "<td valign=\"top\"><div class=\"PathIndex PathIndexEvent\">";
570 EmitAlphaCounter(os, num++);
571 os << "</div></td><td valign=\"top\">"
572 << html::EscapeText(EP->getString())
573 << "</td></tr></table></div>\n";
580 void HTMLDiagnostics::HighlightRange(Rewriter& R, FileID BugFileID,
582 const char *HighlightStart,
583 const char *HighlightEnd) {
584 SourceManager &SM = R.getSourceMgr();
585 const LangOptions &LangOpts = R.getLangOpts();
587 SourceLocation InstantiationStart = SM.getExpansionLoc(Range.getBegin());
588 unsigned StartLineNo = SM.getExpansionLineNumber(InstantiationStart);
590 SourceLocation InstantiationEnd = SM.getExpansionLoc(Range.getEnd());
591 unsigned EndLineNo = SM.getExpansionLineNumber(InstantiationEnd);
593 if (EndLineNo < StartLineNo)
596 if (SM.getFileID(InstantiationStart) != BugFileID ||
597 SM.getFileID(InstantiationEnd) != BugFileID)
600 // Compute the column number of the end.
601 unsigned EndColNo = SM.getExpansionColumnNumber(InstantiationEnd);
602 unsigned OldEndColNo = EndColNo;
605 // Add in the length of the token, so that we cover multi-char tokens.
606 EndColNo += Lexer::MeasureTokenLength(Range.getEnd(), SM, LangOpts)-1;
609 // Highlight the range. Make the span tag the outermost tag for the
613 InstantiationEnd.getLocWithOffset(EndColNo - OldEndColNo);
615 html::HighlightRange(R, InstantiationStart, E, HighlightStart, HighlightEnd);