HTMLDiagnostics.cpp 15 KB

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