HTMLDiagnostics.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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/Driver/PathDiagnosticClients.h"
  14. #include "clang/Analysis/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 "llvm/Support/Compiler.h"
  23. #include "llvm/Support/MemoryBuffer.h"
  24. #include "llvm/Support/Streams.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. #include "llvm/System/Path.h"
  27. #include <fstream>
  28. using namespace clang;
  29. //===----------------------------------------------------------------------===//
  30. // Boilerplate.
  31. //===----------------------------------------------------------------------===//
  32. namespace {
  33. class VISIBILITY_HIDDEN HTMLDiagnostics : public PathDiagnosticClient {
  34. llvm::sys::Path Directory, FilePrefix;
  35. bool createdDir, noDir;
  36. Preprocessor* PP;
  37. PreprocessorFactory* PPF;
  38. std::vector<const PathDiagnostic*> BatchedDiags;
  39. public:
  40. HTMLDiagnostics(const std::string& prefix, Preprocessor* pp,
  41. PreprocessorFactory* ppf);
  42. virtual ~HTMLDiagnostics();
  43. virtual void HandlePathDiagnostic(const PathDiagnostic* D);
  44. void HandlePiece(Rewriter& R, FileID BugFileID,
  45. const PathDiagnosticPiece& P, unsigned num, unsigned max);
  46. void HighlightRange(Rewriter& R, FileID BugFileID, SourceRange Range);
  47. void ReportDiag(const PathDiagnostic& D);
  48. };
  49. } // end anonymous namespace
  50. HTMLDiagnostics::HTMLDiagnostics(const std::string& prefix, Preprocessor* pp,
  51. PreprocessorFactory* ppf)
  52. : Directory(prefix), FilePrefix(prefix), createdDir(false), noDir(false),
  53. PP(pp), PPF(ppf) {
  54. // All html files begin with "report"
  55. FilePrefix.appendComponent("report");
  56. }
  57. PathDiagnosticClient*
  58. clang::CreateHTMLDiagnosticClient(const std::string& prefix, Preprocessor* PP,
  59. PreprocessorFactory* PPF) {
  60. return new HTMLDiagnostics(prefix, PP, PPF);
  61. }
  62. //===----------------------------------------------------------------------===//
  63. // Report processing.
  64. //===----------------------------------------------------------------------===//
  65. void HTMLDiagnostics::HandlePathDiagnostic(const PathDiagnostic* D) {
  66. if (!D)
  67. return;
  68. if (D->empty()) {
  69. delete D;
  70. return;
  71. }
  72. BatchedDiags.push_back(D);
  73. }
  74. HTMLDiagnostics::~HTMLDiagnostics() {
  75. while (!BatchedDiags.empty()) {
  76. const PathDiagnostic* D = BatchedDiags.back();
  77. BatchedDiags.pop_back();
  78. ReportDiag(*D);
  79. delete D;
  80. }
  81. }
  82. void HTMLDiagnostics::ReportDiag(const PathDiagnostic& D) {
  83. // Create the HTML directory if it is missing.
  84. if (!createdDir) {
  85. createdDir = true;
  86. std::string ErrorMsg;
  87. Directory.createDirectoryOnDisk(true, &ErrorMsg);
  88. if (!Directory.isDirectory()) {
  89. llvm::cerr << "warning: could not create directory '"
  90. << Directory.toString() << "'\n"
  91. << "reason: " << ErrorMsg << '\n';
  92. noDir = true;
  93. return;
  94. }
  95. }
  96. if (noDir)
  97. return;
  98. SourceManager &SMgr = D.begin()->getLocation().getManager();
  99. FileID FID;
  100. // Verify that the entire path is from the same FileID.
  101. for (PathDiagnostic::const_iterator I = D.begin(), E = D.end(); I != E; ++I) {
  102. FullSourceLoc L = I->getLocation().getInstantiationLoc();
  103. if (FID.isInvalid()) {
  104. FID = SMgr.getFileID(L);
  105. } else if (SMgr.getFileID(L) != FID)
  106. return; // FIXME: Emit a warning?
  107. // Check the source ranges.
  108. for (PathDiagnosticPiece::range_iterator RI=I->ranges_begin(),
  109. RE=I->ranges_end(); RI!=RE; ++RI) {
  110. SourceLocation L = SMgr.getInstantiationLoc(RI->getBegin());
  111. if (!L.isFileID() || SMgr.getFileID(L) != FID)
  112. return; // FIXME: Emit a warning?
  113. L = SMgr.getInstantiationLoc(RI->getEnd());
  114. if (!L.isFileID() || SMgr.getFileID(L) != FID)
  115. return; // FIXME: Emit a warning?
  116. }
  117. }
  118. if (FID.isInvalid())
  119. return; // FIXME: Emit a warning?
  120. // Create a new rewriter to generate HTML.
  121. Rewriter R(SMgr);
  122. // Process the path.
  123. unsigned n = D.size();
  124. unsigned max = n;
  125. for (PathDiagnostic::const_reverse_iterator I=D.rbegin(), E=D.rend();
  126. I!=E; ++I, --n) {
  127. HandlePiece(R, FID, *I, n, max);
  128. }
  129. // Add line numbers, header, footer, etc.
  130. // unsigned FID = R.getSourceMgr().getMainFileID();
  131. html::EscapeText(R, FID);
  132. html::AddLineNumbers(R, FID);
  133. // If we have a preprocessor, relex the file and syntax highlight.
  134. // We might not have a preprocessor if we come from a deserialized AST file,
  135. // for example.
  136. if (PP) html::SyntaxHighlight(R, FID, *PP);
  137. // FIXME: We eventually want to use PPF to create a fresh Preprocessor,
  138. // once we have worked out the bugs.
  139. //
  140. // if (PPF) html::HighlightMacros(R, FID, *PPF);
  141. //
  142. if (PP) html::HighlightMacros(R, FID, *PP);
  143. // Get the full directory name of the analyzed file.
  144. const FileEntry* Entry = SMgr.getFileEntryForID(FID);
  145. // This is a cludge; basically we want to append either the full
  146. // working directory if we have no directory information. This is
  147. // a work in progress.
  148. std::string DirName = "";
  149. if (!llvm::sys::Path(Entry->getName()).isAbsolute()) {
  150. llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
  151. DirName = P.toString() + "/";
  152. }
  153. // Add the name of the file as an <h1> tag.
  154. {
  155. std::string s;
  156. llvm::raw_string_ostream os(s);
  157. os << "<!-- REPORTHEADER -->\n"
  158. << "<h3>Bug Summary</h3>\n<table class=\"simpletable\">\n"
  159. "<tr><td class=\"rowname\">File:</td><td>"
  160. << html::EscapeText(DirName)
  161. << html::EscapeText(Entry->getName())
  162. << "</td></tr>\n<tr><td class=\"rowname\">Location:</td><td>"
  163. "<a href=\"#EndPath\">line "
  164. << (*D.rbegin()).getLocation().getInstantiationLineNumber()
  165. << ", column "
  166. << (*D.rbegin()).getLocation().getInstantiationColumnNumber()
  167. << "</a></td></tr>\n"
  168. "<tr><td class=\"rowname\">Description:</td><td>"
  169. << D.getDescription() << "</td></tr>\n";
  170. // Output any other meta data.
  171. for (PathDiagnostic::meta_iterator I=D.meta_begin(), E=D.meta_end();
  172. I!=E; ++I) {
  173. os << "<tr><td></td><td>" << html::EscapeText(*I) << "</td></tr>\n";
  174. }
  175. os << "</table>\n<!-- REPORTSUMMARYEXTRA -->\n"
  176. "<h3>Annotated Source Code</h3>\n";
  177. R.InsertStrBefore(SMgr.getLocForStartOfFile(FID), os.str());
  178. }
  179. // Embed meta-data tags.
  180. const std::string& BugDesc = D.getDescription();
  181. if (!BugDesc.empty()) {
  182. std::string s;
  183. llvm::raw_string_ostream os(s);
  184. os << "\n<!-- BUGDESC " << BugDesc << " -->\n";
  185. R.InsertStrBefore(SMgr.getLocForStartOfFile(FID), os.str());
  186. }
  187. const std::string& BugCategory = D.getCategory();
  188. if (!BugCategory.empty()) {
  189. std::string s;
  190. llvm::raw_string_ostream os(s);
  191. os << "\n<!-- BUGCATEGORY " << BugCategory << " -->\n";
  192. R.InsertStrBefore(SMgr.getLocForStartOfFile(FID), os.str());
  193. }
  194. {
  195. std::string s;
  196. llvm::raw_string_ostream os(s);
  197. os << "\n<!-- BUGFILE " << DirName << Entry->getName() << " -->\n";
  198. R.InsertStrBefore(SMgr.getLocForStartOfFile(FID), os.str());
  199. }
  200. {
  201. std::string s;
  202. llvm::raw_string_ostream os(s);
  203. os << "\n<!-- BUGLINE "
  204. << D.back()->getLocation().getInstantiationLineNumber() << " -->\n";
  205. R.InsertStrBefore(SMgr.getLocForStartOfFile(FID), os.str());
  206. }
  207. {
  208. std::string s;
  209. llvm::raw_string_ostream os(s);
  210. os << "\n<!-- BUGPATHLENGTH " << D.size() << " -->\n";
  211. R.InsertStrBefore(SMgr.getLocForStartOfFile(FID), os.str());
  212. }
  213. // Add CSS, header, and footer.
  214. html::AddHeaderFooterInternalBuiltinCSS(R, FID, Entry->getName());
  215. // Get the rewrite buffer.
  216. const RewriteBuffer *Buf = R.getRewriteBufferFor(FID);
  217. if (!Buf) {
  218. llvm::cerr << "warning: no diagnostics generated for main file.\n";
  219. return;
  220. }
  221. // Create the stream to write out the HTML.
  222. std::ofstream os;
  223. {
  224. // Create a path for the target HTML file.
  225. llvm::sys::Path F(FilePrefix);
  226. F.makeUnique(false, NULL);
  227. // Rename the file with an HTML extension.
  228. llvm::sys::Path H(F);
  229. H.appendSuffix("html");
  230. F.renamePathOnDisk(H, NULL);
  231. os.open(H.toString().c_str());
  232. if (!os) {
  233. llvm::cerr << "warning: could not create file '" << F.toString() << "'\n";
  234. return;
  235. }
  236. }
  237. // Emit the HTML to disk.
  238. for (RewriteBuffer::iterator I = Buf->begin(), E = Buf->end(); I!=E; ++I)
  239. os << *I;
  240. }
  241. void HTMLDiagnostics::HandlePiece(Rewriter& R, FileID BugFileID,
  242. const PathDiagnosticPiece& P,
  243. unsigned num, unsigned max) {
  244. // For now, just draw a box above the line in question, and emit the
  245. // warning.
  246. FullSourceLoc Pos = P.getLocation();
  247. if (!Pos.isValid())
  248. return;
  249. SourceManager &SM = R.getSourceMgr();
  250. FullSourceLoc LPos = Pos.getInstantiationLoc();
  251. FileID FID = SM.getFileID(LPos);
  252. assert(&LPos.getManager() == &SM && "SourceManagers are different!");
  253. if (SM.getFileID(LPos) != BugFileID)
  254. return;
  255. const llvm::MemoryBuffer *Buf = SM.getBuffer(FID);
  256. const char* FileStart = Buf->getBufferStart();
  257. // Compute the column number. Rewind from the current position to the start
  258. // of the line.
  259. unsigned ColNo = LPos.getColumnNumber();
  260. const char *TokInstantiationPtr = LPos.getCharacterData();
  261. const char *LineStart = TokInstantiationPtr-ColNo;
  262. // Only compute LineEnd if we display below a line.
  263. const char *LineEnd = TokInstantiationPtr;
  264. if (P.getDisplayHint() == PathDiagnosticPiece::Below) {
  265. const char* FileEnd = Buf->getBufferEnd();
  266. while (*LineEnd != '\n' && LineEnd != FileEnd)
  267. ++LineEnd;
  268. }
  269. // Compute the margin offset by counting tabs and non-tabs.
  270. unsigned PosNo = 0;
  271. for (const char* c = LineStart; c != TokInstantiationPtr; ++c)
  272. PosNo += *c == '\t' ? 8 : 1;
  273. // Create the html for the message.
  274. {
  275. // Get the string and determining its maximum substring.
  276. const std::string& Msg = P.getString();
  277. unsigned max_token = 0;
  278. unsigned cnt = 0;
  279. unsigned len = Msg.size();
  280. for (std::string::const_iterator I=Msg.begin(), E=Msg.end(); I!=E; ++I)
  281. switch (*I) {
  282. default:
  283. ++cnt;
  284. continue;
  285. case ' ':
  286. case '\t':
  287. case '\n':
  288. if (cnt > max_token) max_token = cnt;
  289. cnt = 0;
  290. }
  291. if (cnt > max_token) max_token = cnt;
  292. // Next, determine the approximate size of the message bubble in em.
  293. unsigned em;
  294. const unsigned max_line = 120;
  295. if (max_token >= max_line)
  296. em = max_token / 2;
  297. else {
  298. unsigned characters = max_line;
  299. unsigned lines = len / max_line;
  300. if (lines > 0) {
  301. for (; characters > max_token; --characters)
  302. if (len / characters > lines) {
  303. ++characters;
  304. break;
  305. }
  306. }
  307. em = characters / 2;
  308. }
  309. // Now generate the message bubble.
  310. std::string s;
  311. llvm::raw_string_ostream os(s);
  312. os << "\n<tr><td class=\"num\"></td><td class=\"line\"><div id=\"";
  313. if (num == max)
  314. os << "EndPath";
  315. else
  316. os << "Path" << num;
  317. os << "\" class=\"msg\" style=\"margin-left:" << PosNo << "ex";
  318. if (em < max_line/2) os << "; max-width:" << em << "em";
  319. os << "\">";
  320. if (max > 1)
  321. os << "<span class=\"PathIndex\">[" << num << "]</span> ";
  322. os << html::EscapeText(Msg) << "</div></td></tr>";
  323. // Insert the new html.
  324. unsigned DisplayPos;
  325. switch (P.getDisplayHint()) {
  326. default: assert(0 && "Unhandled hint.");
  327. case PathDiagnosticPiece::Above:
  328. DisplayPos = LineStart - FileStart;
  329. break;
  330. case PathDiagnosticPiece::Below:
  331. DisplayPos = LineEnd - FileStart;
  332. break;
  333. }
  334. SourceLocation Loc =
  335. SM.getLocForStartOfFile(FID).getFileLocWithOffset(DisplayPos);
  336. R.InsertStrBefore(Loc, os.str());
  337. }
  338. // Now highlight the ranges.
  339. for (const SourceRange *I = P.ranges_begin(), *E = P.ranges_end();
  340. I != E; ++I)
  341. HighlightRange(R, FID, *I);
  342. }
  343. void HTMLDiagnostics::HighlightRange(Rewriter& R, FileID BugFileID,
  344. SourceRange Range) {
  345. SourceManager& SM = R.getSourceMgr();
  346. SourceLocation InstantiationStart = SM.getInstantiationLoc(Range.getBegin());
  347. unsigned StartLineNo = SM.getLineNumber(InstantiationStart);
  348. SourceLocation InstantiationEnd = SM.getInstantiationLoc(Range.getEnd());
  349. unsigned EndLineNo = SM.getLineNumber(InstantiationEnd);
  350. if (EndLineNo < StartLineNo)
  351. return;
  352. if (SM.getFileID(InstantiationStart) != BugFileID ||
  353. SM.getFileID(InstantiationEnd) != BugFileID)
  354. return;
  355. // Compute the column number of the end.
  356. unsigned EndColNo = SM.getColumnNumber(InstantiationEnd);
  357. unsigned OldEndColNo = EndColNo;
  358. if (EndColNo) {
  359. // Add in the length of the token, so that we cover multi-char tokens.
  360. EndColNo += Lexer::MeasureTokenLength(Range.getEnd(), SM) - 1;
  361. }
  362. // Highlight the range. Make the span tag the outermost tag for the
  363. // selected range.
  364. SourceLocation E =
  365. InstantiationEnd.getFileLocWithOffset(EndColNo - OldEndColNo);
  366. html::HighlightRange(R, InstantiationStart, E,
  367. "<span class=\"mrange\">", "</span>");
  368. }