HTMLDiagnostics.cpp 18 KB

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