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