HTMLDiagnostics.cpp 17 KB

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