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/AST/ASTContext.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "clang/Lex/Lexer.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang/Rewrite/Core/HTMLRewrite.h"
21 #include "clang/Rewrite/Core/Rewriter.h"
22 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
23 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
24 #include "clang/StaticAnalyzer/Core/IssueHash.h"
25 #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
26 #include "llvm/Support/Errc.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/raw_ostream.h"
33 using namespace clang;
36 //===----------------------------------------------------------------------===//
38 //===----------------------------------------------------------------------===//
42 class HTMLDiagnostics : public PathDiagnosticConsumer {
43 std::string Directory;
44 bool createdDir, noDir;
45 const Preprocessor &PP;
46 AnalyzerOptions &AnalyzerOpts;
48 HTMLDiagnostics(AnalyzerOptions &AnalyzerOpts, const std::string& prefix, const Preprocessor &pp);
50 ~HTMLDiagnostics() override { FlushDiagnostics(nullptr); }
52 void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
53 FilesMade *filesMade) override;
55 StringRef getName() const override {
56 return "HTMLDiagnostics";
59 unsigned ProcessMacroPiece(raw_ostream &os,
60 const PathDiagnosticMacroPiece& P,
63 void HandlePiece(Rewriter& R, FileID BugFileID,
64 const PathDiagnosticPiece& P, unsigned num, unsigned max);
66 void HighlightRange(Rewriter& R, FileID BugFileID, SourceRange Range,
67 const char *HighlightStart = "<span class=\"mrange\">",
68 const char *HighlightEnd = "</span>");
70 void ReportDiag(const PathDiagnostic& D,
71 FilesMade *filesMade);
74 } // end anonymous namespace
76 HTMLDiagnostics::HTMLDiagnostics(AnalyzerOptions &AnalyzerOpts,
77 const std::string& prefix,
78 const Preprocessor &pp)
79 : Directory(prefix), createdDir(false), noDir(false), PP(pp), AnalyzerOpts(AnalyzerOpts) {
82 void ento::createHTMLDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
83 PathDiagnosticConsumers &C,
84 const std::string& prefix,
85 const Preprocessor &PP) {
86 C.push_back(new HTMLDiagnostics(AnalyzerOpts, prefix, PP));
89 //===----------------------------------------------------------------------===//
91 //===----------------------------------------------------------------------===//
93 void HTMLDiagnostics::FlushDiagnosticsImpl(
94 std::vector<const PathDiagnostic *> &Diags,
95 FilesMade *filesMade) {
96 for (std::vector<const PathDiagnostic *>::iterator it = Diags.begin(),
97 et = Diags.end(); it != et; ++it) {
98 ReportDiag(**it, filesMade);
102 void HTMLDiagnostics::ReportDiag(const PathDiagnostic& D,
103 FilesMade *filesMade) {
105 // Create the HTML directory if it is missing.
108 if (std::error_code ec = llvm::sys::fs::create_directories(Directory)) {
109 llvm::errs() << "warning: could not create directory '"
110 << Directory << "': " << ec.message() << '\n';
121 // First flatten out the entire path to make it easier to use.
122 PathPieces path = D.path.flatten(/*ShouldFlattenMacros=*/false);
124 // The path as already been prechecked that all parts of the path are
125 // from the same file and that it is non-empty.
126 const SourceManager &SMgr = path.front()->getLocation().getManager();
127 assert(!path.empty());
129 path.front()->getLocation().asLocation().getExpansionLoc().getFileID();
130 assert(FID.isValid());
132 // Create a new rewriter to generate HTML.
133 Rewriter R(const_cast<SourceManager&>(SMgr), PP.getLangOpts());
135 // Get the function/method name
136 SmallString<128> declName("unknown");
138 if (const Decl *DeclWithIssue = D.getDeclWithIssue()) {
139 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DeclWithIssue)) {
140 declName = ND->getDeclName().getAsString();
143 if (const Stmt *Body = DeclWithIssue->getBody()) {
144 // Retrieve the relative position of the declaration which will be used
147 SMgr.getExpansionLoc(path.back()->getLocation().asLocation()),
149 FullSourceLoc FunL(SMgr.getExpansionLoc(Body->getLocStart()), SMgr);
150 offsetDecl = L.getExpansionLineNumber() - FunL.getExpansionLineNumber();
155 // Maintain the counts of extra note pieces separately.
156 unsigned TotalPieces = path.size();
157 unsigned TotalNotePieces =
158 std::count_if(path.begin(), path.end(),
159 [](const IntrusiveRefCntPtr<PathDiagnosticPiece> &p) {
160 return isa<PathDiagnosticNotePiece>(p.get());
163 unsigned TotalRegularPieces = TotalPieces - TotalNotePieces;
164 unsigned NumRegularPieces = TotalRegularPieces;
165 unsigned NumNotePieces = TotalNotePieces;
167 for (auto I = path.rbegin(), E = path.rend(); I != E; ++I) {
168 if (isa<PathDiagnosticNotePiece>(I->get())) {
169 // This adds diagnostic bubbles, but not navigation.
170 // Navigation through note pieces would be added later,
171 // as a separate pass through the piece list.
172 HandlePiece(R, FID, **I, NumNotePieces, TotalNotePieces);
175 HandlePiece(R, FID, **I, NumRegularPieces, TotalRegularPieces);
180 // Add line numbers, header, footer, etc.
182 // unsigned FID = R.getSourceMgr().getMainFileID();
183 html::EscapeText(R, FID);
184 html::AddLineNumbers(R, FID);
186 // If we have a preprocessor, relex the file and syntax highlight.
187 // We might not have a preprocessor if we come from a deserialized AST file,
190 html::SyntaxHighlight(R, FID, PP);
191 html::HighlightMacros(R, FID, PP);
193 // Get the full directory name of the analyzed file.
195 const FileEntry* Entry = SMgr.getFileEntryForID(FID);
197 // This is a cludge; basically we want to append either the full
198 // working directory if we have no directory information. This is
199 // a work in progress.
201 llvm::SmallString<0> DirName;
203 if (llvm::sys::path::is_relative(Entry->getName())) {
204 llvm::sys::fs::current_path(DirName);
208 int LineNumber = path.back()->getLocation().asLocation().getExpansionLineNumber();
209 int ColumnNumber = path.back()->getLocation().asLocation().getExpansionColumnNumber();
211 // Add the name of the file as an <h1> tag.
214 llvm::raw_string_ostream os(s);
216 os << "<!-- REPORTHEADER -->\n"
217 << "<h3>Bug Summary</h3>\n<table class=\"simpletable\">\n"
218 "<tr><td class=\"rowname\">File:</td><td>"
219 << html::EscapeText(DirName)
220 << html::EscapeText(Entry->getName())
221 << "</td></tr>\n<tr><td class=\"rowname\">Warning:</td><td>"
222 "<a href=\"#EndPath\">line "
227 << D.getVerboseDescription() << "</td></tr>\n";
229 // The navigation across the extra notes pieces.
230 unsigned NumExtraPieces = 0;
231 for (const auto &Piece : path) {
232 if (const auto *P = dyn_cast<PathDiagnosticNotePiece>(Piece.get())) {
234 P->getLocation().asLocation().getExpansionLineNumber();
236 P->getLocation().asLocation().getExpansionColumnNumber();
237 os << "<tr><td class=\"rowname\">Note:</td><td>"
238 << "<a href=\"#Note" << NumExtraPieces << "\">line "
239 << LineNumber << ", column " << ColumnNumber << "</a><br />"
240 << P->getString() << "</td></tr>";
245 // Output any other meta data.
247 for (PathDiagnostic::meta_iterator I=D.meta_begin(), E=D.meta_end();
249 os << "<tr><td></td><td>" << html::EscapeText(*I) << "</td></tr>\n";
252 os << "</table>\n<!-- REPORTSUMMARYEXTRA -->\n"
253 "<h3>Annotated Source Code</h3>\n";
255 R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
258 // Embed meta-data tags.
261 llvm::raw_string_ostream os(s);
263 StringRef BugDesc = D.getVerboseDescription();
264 if (!BugDesc.empty())
265 os << "\n<!-- BUGDESC " << BugDesc << " -->\n";
267 StringRef BugType = D.getBugType();
268 if (!BugType.empty())
269 os << "\n<!-- BUGTYPE " << BugType << " -->\n";
271 PathDiagnosticLocation UPDLoc = D.getUniqueingLoc();
272 FullSourceLoc L(SMgr.getExpansionLoc(UPDLoc.isValid()
273 ? UPDLoc.asLocation()
274 : D.getLocation().asLocation()),
276 const Decl *DeclWithIssue = D.getDeclWithIssue();
278 StringRef BugCategory = D.getCategory();
279 if (!BugCategory.empty())
280 os << "\n<!-- BUGCATEGORY " << BugCategory << " -->\n";
282 os << "\n<!-- BUGFILE " << DirName << Entry->getName() << " -->\n";
284 os << "\n<!-- FILENAME " << llvm::sys::path::filename(Entry->getName()) << " -->\n";
286 os << "\n<!-- FUNCTIONNAME " << declName << " -->\n";
288 os << "\n<!-- ISSUEHASHCONTENTOFLINEINCONTEXT "
289 << GetIssueHash(SMgr, L, D.getCheckName(), D.getBugType(), DeclWithIssue,
290 PP.getLangOpts()) << " -->\n";
292 os << "\n<!-- BUGLINE "
296 os << "\n<!-- BUGCOLUMN "
300 os << "\n<!-- BUGPATHLENGTH " << path.size() << " -->\n";
302 // Mark the end of the tags.
303 os << "\n<!-- BUGMETAEND -->\n";
306 R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
309 // Add CSS, header, and footer.
311 html::AddHeaderFooterInternalBuiltinCSS(R, FID, Entry->getName());
313 // Get the rewrite buffer.
314 const RewriteBuffer *Buf = R.getRewriteBufferFor(FID);
317 llvm::errs() << "warning: no diagnostics generated for main file.\n";
321 // Create a path for the target HTML file.
323 SmallString<128> Model, ResultPath;
325 if (!AnalyzerOpts.shouldWriteStableReportFilename()) {
326 llvm::sys::path::append(Model, Directory, "report-%%%%%%.html");
327 if (std::error_code EC =
328 llvm::sys::fs::make_absolute(Model)) {
329 llvm::errs() << "warning: could not make '" << Model
330 << "' absolute: " << EC.message() << '\n';
333 if (std::error_code EC =
334 llvm::sys::fs::createUniqueFile(Model, FD, ResultPath)) {
335 llvm::errs() << "warning: could not create file in '" << Directory
336 << "': " << EC.message() << '\n';
344 // Find a filename which is not already used
345 std::stringstream filename;
347 filename << "report-"
348 << llvm::sys::path::filename(Entry->getName()).str()
349 << "-" << declName.c_str()
351 << "-" << i << ".html";
352 llvm::sys::path::append(Model, Directory,
354 EC = llvm::sys::fs::openFileForWrite(Model,
356 llvm::sys::fs::F_RW |
357 llvm::sys::fs::F_Excl);
358 if (EC && EC != llvm::errc::file_exists) {
359 llvm::errs() << "warning: could not create file '" << Model
360 << "': " << EC.message() << '\n';
367 llvm::raw_fd_ostream os(FD, true);
370 filesMade->addDiagnostic(D, getName(),
371 llvm::sys::path::filename(ResultPath));
373 // Emit the HTML to disk.
374 for (RewriteBuffer::iterator I = Buf->begin(), E = Buf->end(); I!=E; ++I)
378 void HTMLDiagnostics::HandlePiece(Rewriter& R, FileID BugFileID,
379 const PathDiagnosticPiece& P,
380 unsigned num, unsigned max) {
382 // For now, just draw a box above the line in question, and emit the
384 FullSourceLoc Pos = P.getLocation().asLocation();
389 SourceManager &SM = R.getSourceMgr();
390 assert(&Pos.getManager() == &SM && "SourceManagers are different!");
391 std::pair<FileID, unsigned> LPosInfo = SM.getDecomposedExpansionLoc(Pos);
393 if (LPosInfo.first != BugFileID)
396 const llvm::MemoryBuffer *Buf = SM.getBuffer(LPosInfo.first);
397 const char* FileStart = Buf->getBufferStart();
399 // Compute the column number. Rewind from the current position to the start
401 unsigned ColNo = SM.getColumnNumber(LPosInfo.first, LPosInfo.second);
402 const char *TokInstantiationPtr =Pos.getExpansionLoc().getCharacterData();
403 const char *LineStart = TokInstantiationPtr-ColNo;
406 const char *LineEnd = TokInstantiationPtr;
407 const char* FileEnd = Buf->getBufferEnd();
408 while (*LineEnd != '\n' && LineEnd != FileEnd)
411 // Compute the margin offset by counting tabs and non-tabs.
413 for (const char* c = LineStart; c != TokInstantiationPtr; ++c)
414 PosNo += *c == '\t' ? 8 : 1;
416 // Create the html for the message.
418 const char *Kind = nullptr;
420 bool SuppressIndex = (max == 1);
421 switch (P.getKind()) {
422 case PathDiagnosticPiece::Call:
423 llvm_unreachable("Calls and extra notes should already be handled");
424 case PathDiagnosticPiece::Event: Kind = "Event"; break;
425 case PathDiagnosticPiece::ControlFlow: Kind = "Control"; break;
426 // Setting Kind to "Control" is intentional.
427 case PathDiagnosticPiece::Macro: Kind = "Control"; break;
428 case PathDiagnosticPiece::Note:
431 SuppressIndex = true;
436 llvm::raw_string_ostream os(sbuf);
438 os << "\n<tr><td class=\"num\"></td><td class=\"line\"><div id=\"";
447 os << "\" class=\"msg";
449 os << " msg" << Kind;
450 os << "\" style=\"margin-left:" << PosNo << "ex";
452 // Output a maximum size.
453 if (!isa<PathDiagnosticMacroPiece>(P)) {
454 // Get the string and determining its maximum substring.
455 const auto &Msg = P.getString();
456 unsigned max_token = 0;
458 unsigned len = Msg.size();
468 if (cnt > max_token) max_token = cnt;
475 // Determine the approximate size of the message bubble in em.
477 const unsigned max_line = 120;
479 if (max_token >= max_line)
482 unsigned characters = max_line;
483 unsigned lines = len / max_line;
486 for (; characters > max_token; --characters)
487 if (len / characters > lines) {
497 os << "; max-width:" << em << "em";
500 os << "; max-width:100em";
504 if (!SuppressIndex) {
505 os << "<table class=\"msgT\"><tr><td valign=\"top\">";
506 os << "<div class=\"PathIndex";
507 if (Kind) os << " PathIndex" << Kind;
508 os << "\">" << num << "</div>";
511 os << "</td><td><div class=\"PathNav\"><a href=\"#Path"
513 << "\" title=\"Previous event ("
515 << ")\">←</a></div></td>";
521 if (const PathDiagnosticMacroPiece *MP =
522 dyn_cast<PathDiagnosticMacroPiece>(&P)) {
524 os << "Within the expansion of the macro '";
526 // Get the name of the macro by relexing it.
528 FullSourceLoc L = MP->getLocation().asLocation().getExpansionLoc();
529 assert(L.isFileID());
530 StringRef BufferInfo = L.getBufferData();
531 std::pair<FileID, unsigned> LocInfo = L.getDecomposedLoc();
532 const char* MacroName = LocInfo.second + BufferInfo.data();
533 Lexer rawLexer(SM.getLocForStartOfFile(LocInfo.first), PP.getLangOpts(),
534 BufferInfo.begin(), MacroName, BufferInfo.end());
537 rawLexer.LexFromRawLexer(TheTok);
538 for (unsigned i = 0, n = TheTok.getLength(); i < n; ++i)
544 if (!SuppressIndex) {
547 os << "<td><div class=\"PathNav\"><a href=\"#";
551 os << "Path" << (num + 1);
552 os << "\" title=\"Next event ("
554 << ")\">→</a></div></td>";
557 os << "</tr></table>";
560 // Within a macro piece. Write out each event.
561 ProcessMacroPiece(os, *MP, 0);
564 os << html::EscapeText(P.getString());
566 if (!SuppressIndex) {
569 os << "<td><div class=\"PathNav\"><a href=\"#";
573 os << "Path" << (num + 1);
574 os << "\" title=\"Next event ("
576 << ")\">→</a></div></td>";
579 os << "</tr></table>";
583 os << "</div></td></tr>";
585 // Insert the new html.
586 unsigned DisplayPos = LineEnd - FileStart;
588 SM.getLocForStartOfFile(LPosInfo.first).getLocWithOffset(DisplayPos);
590 R.InsertTextBefore(Loc, os.str());
592 // Now highlight the ranges.
593 ArrayRef<SourceRange> Ranges = P.getRanges();
594 for (ArrayRef<SourceRange>::iterator I = Ranges.begin(),
595 E = Ranges.end(); I != E; ++I) {
596 HighlightRange(R, LPosInfo.first, *I);
600 static void EmitAlphaCounter(raw_ostream &os, unsigned n) {
601 unsigned x = n % ('z' - 'a');
605 EmitAlphaCounter(os, n);
610 unsigned HTMLDiagnostics::ProcessMacroPiece(raw_ostream &os,
611 const PathDiagnosticMacroPiece& P,
614 for (PathPieces::const_iterator I = P.subPieces.begin(), E=P.subPieces.end();
617 if (const PathDiagnosticMacroPiece *MP =
618 dyn_cast<PathDiagnosticMacroPiece>(*I)) {
619 num = ProcessMacroPiece(os, *MP, num);
623 if (PathDiagnosticEventPiece *EP = dyn_cast<PathDiagnosticEventPiece>(*I)) {
624 os << "<div class=\"msg msgEvent\" style=\"width:94%; "
626 "<table class=\"msgT\"><tr>"
627 "<td valign=\"top\"><div class=\"PathIndex PathIndexEvent\">";
628 EmitAlphaCounter(os, num++);
629 os << "</div></td><td valign=\"top\">"
630 << html::EscapeText(EP->getString())
631 << "</td></tr></table></div>\n";
638 void HTMLDiagnostics::HighlightRange(Rewriter& R, FileID BugFileID,
640 const char *HighlightStart,
641 const char *HighlightEnd) {
642 SourceManager &SM = R.getSourceMgr();
643 const LangOptions &LangOpts = R.getLangOpts();
645 SourceLocation InstantiationStart = SM.getExpansionLoc(Range.getBegin());
646 unsigned StartLineNo = SM.getExpansionLineNumber(InstantiationStart);
648 SourceLocation InstantiationEnd = SM.getExpansionLoc(Range.getEnd());
649 unsigned EndLineNo = SM.getExpansionLineNumber(InstantiationEnd);
651 if (EndLineNo < StartLineNo)
654 if (SM.getFileID(InstantiationStart) != BugFileID ||
655 SM.getFileID(InstantiationEnd) != BugFileID)
658 // Compute the column number of the end.
659 unsigned EndColNo = SM.getExpansionColumnNumber(InstantiationEnd);
660 unsigned OldEndColNo = EndColNo;
663 // Add in the length of the token, so that we cover multi-char tokens.
664 EndColNo += Lexer::MeasureTokenLength(Range.getEnd(), SM, LangOpts)-1;
667 // Highlight the range. Make the span tag the outermost tag for the
671 InstantiationEnd.getLocWithOffset(EndColNo - OldEndColNo);
673 html::HighlightRange(R, InstantiationStart, E, HighlightStart, HighlightEnd);