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