HTMLDiagnostics.cpp 17 KB

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