HTMLDiagnostics.cpp 18 KB

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