HTMLDiagnostics.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  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/AST/ASTContext.h"
  14. #include "clang/AST/Decl.h"
  15. #include "clang/Basic/FileManager.h"
  16. #include "clang/Basic/SourceManager.h"
  17. #include "clang/Lex/Lexer.h"
  18. #include "clang/Lex/Preprocessor.h"
  19. #include "clang/Rewrite/Core/HTMLRewrite.h"
  20. #include "clang/Rewrite/Core/Rewriter.h"
  21. #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
  22. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  23. #include "clang/StaticAnalyzer/Core/IssueHash.h"
  24. #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
  25. #include "llvm/Support/Errc.h"
  26. #include "llvm/Support/FileSystem.h"
  27. #include "llvm/Support/MemoryBuffer.h"
  28. #include "llvm/Support/Path.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include <sstream>
  31. using namespace clang;
  32. using namespace ento;
  33. //===----------------------------------------------------------------------===//
  34. // Boilerplate.
  35. //===----------------------------------------------------------------------===//
  36. namespace {
  37. class HTMLDiagnostics : public PathDiagnosticConsumer {
  38. std::string Directory;
  39. bool createdDir, noDir;
  40. const Preprocessor &PP;
  41. AnalyzerOptions &AnalyzerOpts;
  42. const bool SupportsCrossFileDiagnostics;
  43. public:
  44. HTMLDiagnostics(AnalyzerOptions &AnalyzerOpts,
  45. const std::string& prefix,
  46. const Preprocessor &pp,
  47. bool supportsMultipleFiles);
  48. ~HTMLDiagnostics() override { FlushDiagnostics(nullptr); }
  49. void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
  50. FilesMade *filesMade) override;
  51. StringRef getName() const override {
  52. return "HTMLDiagnostics";
  53. }
  54. bool supportsCrossFileDiagnostics() const override {
  55. return SupportsCrossFileDiagnostics;
  56. }
  57. unsigned ProcessMacroPiece(raw_ostream &os,
  58. const PathDiagnosticMacroPiece& P,
  59. unsigned num);
  60. void HandlePiece(Rewriter& R, FileID BugFileID,
  61. const PathDiagnosticPiece& P, unsigned num, unsigned max);
  62. void HighlightRange(Rewriter& R, FileID BugFileID, SourceRange Range,
  63. const char *HighlightStart = "<span class=\"mrange\">",
  64. const char *HighlightEnd = "</span>");
  65. void ReportDiag(const PathDiagnostic& D,
  66. FilesMade *filesMade);
  67. // Generate the full HTML report
  68. std::string GenerateHTML(const PathDiagnostic& D, Rewriter &R,
  69. const SourceManager& SMgr, const PathPieces& path,
  70. const char *declName);
  71. // Add HTML header/footers to file specified by FID
  72. void FinalizeHTML(const PathDiagnostic& D, Rewriter &R,
  73. const SourceManager& SMgr, const PathPieces& path,
  74. FileID FID, const FileEntry *Entry, const char *declName);
  75. // Rewrite the file specified by FID with HTML formatting.
  76. void RewriteFile(Rewriter &R, const SourceManager& SMgr,
  77. const PathPieces& path, FileID FID);
  78. };
  79. } // end anonymous namespace
  80. HTMLDiagnostics::HTMLDiagnostics(AnalyzerOptions &AnalyzerOpts,
  81. const std::string& prefix,
  82. const Preprocessor &pp,
  83. bool supportsMultipleFiles)
  84. : Directory(prefix),
  85. createdDir(false),
  86. noDir(false),
  87. PP(pp),
  88. AnalyzerOpts(AnalyzerOpts),
  89. SupportsCrossFileDiagnostics(supportsMultipleFiles) {}
  90. void ento::createHTMLDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
  91. PathDiagnosticConsumers &C,
  92. const std::string& prefix,
  93. const Preprocessor &PP) {
  94. C.push_back(new HTMLDiagnostics(AnalyzerOpts, prefix, PP, true));
  95. }
  96. void ento::createHTMLSingleFileDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
  97. PathDiagnosticConsumers &C,
  98. const std::string& prefix,
  99. const Preprocessor &PP) {
  100. C.push_back(new HTMLDiagnostics(AnalyzerOpts, prefix, PP, false));
  101. }
  102. //===----------------------------------------------------------------------===//
  103. // Report processing.
  104. //===----------------------------------------------------------------------===//
  105. void HTMLDiagnostics::FlushDiagnosticsImpl(
  106. std::vector<const PathDiagnostic *> &Diags,
  107. FilesMade *filesMade) {
  108. for (std::vector<const PathDiagnostic *>::iterator it = Diags.begin(),
  109. et = Diags.end(); it != et; ++it) {
  110. ReportDiag(**it, filesMade);
  111. }
  112. }
  113. void HTMLDiagnostics::ReportDiag(const PathDiagnostic& D,
  114. FilesMade *filesMade) {
  115. // Create the HTML directory if it is missing.
  116. if (!createdDir) {
  117. createdDir = true;
  118. if (std::error_code ec = llvm::sys::fs::create_directories(Directory)) {
  119. llvm::errs() << "warning: could not create directory '"
  120. << Directory << "': " << ec.message() << '\n';
  121. noDir = true;
  122. return;
  123. }
  124. }
  125. if (noDir)
  126. return;
  127. // First flatten out the entire path to make it easier to use.
  128. PathPieces path = D.path.flatten(/*ShouldFlattenMacros=*/false);
  129. // The path as already been prechecked that the path is non-empty.
  130. assert(!path.empty());
  131. const SourceManager &SMgr = path.front()->getLocation().getManager();
  132. // Create a new rewriter to generate HTML.
  133. Rewriter R(const_cast<SourceManager&>(SMgr), PP.getLangOpts());
  134. // The file for the first path element is considered the main report file, it
  135. // will usually be equivalent to SMgr.getMainFileID(); however, it might be a
  136. // header when -analyzer-opt-analyze-headers is used.
  137. FileID ReportFile = path.front()->getLocation().asLocation().getExpansionLoc().getFileID();
  138. // Get the function/method name
  139. SmallString<128> declName("unknown");
  140. int offsetDecl = 0;
  141. if (const Decl *DeclWithIssue = D.getDeclWithIssue()) {
  142. if (const NamedDecl *ND = dyn_cast<NamedDecl>(DeclWithIssue))
  143. declName = ND->getDeclName().getAsString();
  144. if (const Stmt *Body = DeclWithIssue->getBody()) {
  145. // Retrieve the relative position of the declaration which will be used
  146. // for the file name
  147. FullSourceLoc L(
  148. SMgr.getExpansionLoc(path.back()->getLocation().asLocation()),
  149. SMgr);
  150. FullSourceLoc FunL(SMgr.getExpansionLoc(Body->getLocStart()), SMgr);
  151. offsetDecl = L.getExpansionLineNumber() - FunL.getExpansionLineNumber();
  152. }
  153. }
  154. std::string report = GenerateHTML(D, R, SMgr, path, declName.c_str());
  155. if (report.empty()) {
  156. llvm::errs() << "warning: no diagnostics generated for main file.\n";
  157. return;
  158. }
  159. // Create a path for the target HTML file.
  160. int FD;
  161. SmallString<128> Model, ResultPath;
  162. if (!AnalyzerOpts.shouldWriteStableReportFilename()) {
  163. llvm::sys::path::append(Model, Directory, "report-%%%%%%.html");
  164. if (std::error_code EC =
  165. llvm::sys::fs::make_absolute(Model)) {
  166. llvm::errs() << "warning: could not make '" << Model
  167. << "' absolute: " << EC.message() << '\n';
  168. return;
  169. }
  170. if (std::error_code EC =
  171. llvm::sys::fs::createUniqueFile(Model, FD, ResultPath)) {
  172. llvm::errs() << "warning: could not create file in '" << Directory
  173. << "': " << EC.message() << '\n';
  174. return;
  175. }
  176. } else {
  177. int i = 1;
  178. std::error_code EC;
  179. do {
  180. // Find a filename which is not already used
  181. const FileEntry* Entry = SMgr.getFileEntryForID(ReportFile);
  182. std::stringstream filename;
  183. Model = "";
  184. filename << "report-"
  185. << llvm::sys::path::filename(Entry->getName()).str()
  186. << "-" << declName.c_str()
  187. << "-" << offsetDecl
  188. << "-" << i << ".html";
  189. llvm::sys::path::append(Model, Directory,
  190. filename.str());
  191. EC = llvm::sys::fs::openFileForWrite(Model,
  192. FD,
  193. llvm::sys::fs::F_RW |
  194. llvm::sys::fs::F_Excl);
  195. if (EC && EC != llvm::errc::file_exists) {
  196. llvm::errs() << "warning: could not create file '" << Model
  197. << "': " << EC.message() << '\n';
  198. return;
  199. }
  200. i++;
  201. } while (EC);
  202. }
  203. llvm::raw_fd_ostream os(FD, true);
  204. if (filesMade)
  205. filesMade->addDiagnostic(D, getName(),
  206. llvm::sys::path::filename(ResultPath));
  207. // Emit the HTML to disk.
  208. os << report;
  209. }
  210. std::string HTMLDiagnostics::GenerateHTML(const PathDiagnostic& D, Rewriter &R,
  211. const SourceManager& SMgr, const PathPieces& path, const char *declName) {
  212. // Rewrite source files as HTML for every new file the path crosses
  213. std::vector<FileID> FileIDs;
  214. for (auto I : path) {
  215. FileID FID = I->getLocation().asLocation().getExpansionLoc().getFileID();
  216. if (std::find(FileIDs.begin(), FileIDs.end(), FID) != FileIDs.end())
  217. continue;
  218. FileIDs.push_back(FID);
  219. RewriteFile(R, SMgr, path, FID);
  220. }
  221. if (SupportsCrossFileDiagnostics && FileIDs.size() > 1) {
  222. // Prefix file names, anchor tags, and nav cursors to every file
  223. for (auto I = FileIDs.begin(), E = FileIDs.end(); I != E; I++) {
  224. std::string s;
  225. llvm::raw_string_ostream os(s);
  226. if (I != FileIDs.begin())
  227. os << "<hr class=divider>\n";
  228. os << "<div id=File" << I->getHashValue() << ">\n";
  229. // Left nav arrow
  230. if (I != FileIDs.begin())
  231. os << "<div class=FileNav><a href=\"#File" << (I - 1)->getHashValue()
  232. << "\">&#x2190;</a></div>";
  233. os << "<h4 class=FileName>" << SMgr.getFileEntryForID(*I)->getName()
  234. << "</h4>\n";
  235. // Right nav arrow
  236. if (I + 1 != E)
  237. os << "<div class=FileNav><a href=\"#File" << (I + 1)->getHashValue()
  238. << "\">&#x2192;</a></div>";
  239. os << "</div>\n";
  240. R.InsertTextBefore(SMgr.getLocForStartOfFile(*I), os.str());
  241. }
  242. // Append files to the main report file in the order they appear in the path
  243. for (auto I : llvm::make_range(FileIDs.begin() + 1, FileIDs.end())) {
  244. std::string s;
  245. llvm::raw_string_ostream os(s);
  246. const RewriteBuffer *Buf = R.getRewriteBufferFor(I);
  247. for (auto BI : *Buf)
  248. os << BI;
  249. R.InsertTextAfter(SMgr.getLocForEndOfFile(FileIDs[0]), os.str());
  250. }
  251. }
  252. const RewriteBuffer *Buf = R.getRewriteBufferFor(FileIDs[0]);
  253. if (!Buf)
  254. return "";
  255. // Add CSS, header, and footer.
  256. const FileEntry* Entry = SMgr.getFileEntryForID(FileIDs[0]);
  257. FinalizeHTML(D, R, SMgr, path, FileIDs[0], Entry, declName);
  258. std::string file;
  259. llvm::raw_string_ostream os(file);
  260. for (auto BI : *Buf)
  261. os << BI;
  262. return os.str();
  263. }
  264. void HTMLDiagnostics::FinalizeHTML(const PathDiagnostic& D, Rewriter &R,
  265. const SourceManager& SMgr, const PathPieces& path, FileID FID,
  266. const FileEntry *Entry, const char *declName) {
  267. // This is a cludge; basically we want to append either the full
  268. // working directory if we have no directory information. This is
  269. // a work in progress.
  270. llvm::SmallString<0> DirName;
  271. if (llvm::sys::path::is_relative(Entry->getName())) {
  272. llvm::sys::fs::current_path(DirName);
  273. DirName += '/';
  274. }
  275. int LineNumber = path.back()->getLocation().asLocation().getExpansionLineNumber();
  276. int ColumnNumber = path.back()->getLocation().asLocation().getExpansionColumnNumber();
  277. // Add the name of the file as an <h1> tag.
  278. {
  279. std::string s;
  280. llvm::raw_string_ostream os(s);
  281. os << "<!-- REPORTHEADER -->\n"
  282. << "<h3>Bug Summary</h3>\n<table class=\"simpletable\">\n"
  283. "<tr><td class=\"rowname\">File:</td><td>"
  284. << html::EscapeText(DirName)
  285. << html::EscapeText(Entry->getName())
  286. << "</td></tr>\n<tr><td class=\"rowname\">Warning:</td><td>"
  287. "<a href=\"#EndPath\">line "
  288. << LineNumber
  289. << ", column "
  290. << ColumnNumber
  291. << "</a><br />"
  292. << D.getVerboseDescription() << "</td></tr>\n";
  293. // The navigation across the extra notes pieces.
  294. unsigned NumExtraPieces = 0;
  295. for (const auto &Piece : path) {
  296. if (const auto *P = dyn_cast<PathDiagnosticNotePiece>(Piece.get())) {
  297. int LineNumber =
  298. P->getLocation().asLocation().getExpansionLineNumber();
  299. int ColumnNumber =
  300. P->getLocation().asLocation().getExpansionColumnNumber();
  301. os << "<tr><td class=\"rowname\">Note:</td><td>"
  302. << "<a href=\"#Note" << NumExtraPieces << "\">line "
  303. << LineNumber << ", column " << ColumnNumber << "</a><br />"
  304. << P->getString() << "</td></tr>";
  305. ++NumExtraPieces;
  306. }
  307. }
  308. // Output any other meta data.
  309. for (PathDiagnostic::meta_iterator I=D.meta_begin(), E=D.meta_end();
  310. I!=E; ++I) {
  311. os << "<tr><td></td><td>" << html::EscapeText(*I) << "</td></tr>\n";
  312. }
  313. os << "</table>\n<!-- REPORTSUMMARYEXTRA -->\n"
  314. "<h3>Annotated Source Code</h3>\n";
  315. R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
  316. }
  317. // Embed meta-data tags.
  318. {
  319. std::string s;
  320. llvm::raw_string_ostream os(s);
  321. StringRef BugDesc = D.getVerboseDescription();
  322. if (!BugDesc.empty())
  323. os << "\n<!-- BUGDESC " << BugDesc << " -->\n";
  324. StringRef BugType = D.getBugType();
  325. if (!BugType.empty())
  326. os << "\n<!-- BUGTYPE " << BugType << " -->\n";
  327. PathDiagnosticLocation UPDLoc = D.getUniqueingLoc();
  328. FullSourceLoc L(SMgr.getExpansionLoc(UPDLoc.isValid()
  329. ? UPDLoc.asLocation()
  330. : D.getLocation().asLocation()),
  331. SMgr);
  332. const Decl *DeclWithIssue = D.getDeclWithIssue();
  333. StringRef BugCategory = D.getCategory();
  334. if (!BugCategory.empty())
  335. os << "\n<!-- BUGCATEGORY " << BugCategory << " -->\n";
  336. os << "\n<!-- BUGFILE " << DirName << Entry->getName() << " -->\n";
  337. os << "\n<!-- FILENAME " << llvm::sys::path::filename(Entry->getName()) << " -->\n";
  338. os << "\n<!-- FUNCTIONNAME " << declName << " -->\n";
  339. os << "\n<!-- ISSUEHASHCONTENTOFLINEINCONTEXT "
  340. << GetIssueHash(SMgr, L, D.getCheckName(), D.getBugType(), DeclWithIssue,
  341. PP.getLangOpts()) << " -->\n";
  342. os << "\n<!-- BUGLINE "
  343. << LineNumber
  344. << " -->\n";
  345. os << "\n<!-- BUGCOLUMN "
  346. << ColumnNumber
  347. << " -->\n";
  348. os << "\n<!-- BUGPATHLENGTH " << path.size() << " -->\n";
  349. // Mark the end of the tags.
  350. os << "\n<!-- BUGMETAEND -->\n";
  351. // Insert the text.
  352. R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
  353. }
  354. html::AddHeaderFooterInternalBuiltinCSS(R, FID, Entry->getName());
  355. }
  356. void HTMLDiagnostics::RewriteFile(Rewriter &R, const SourceManager& SMgr,
  357. const PathPieces& path, FileID FID) {
  358. // Process the path.
  359. // Maintain the counts of extra note pieces separately.
  360. unsigned TotalPieces = path.size();
  361. unsigned TotalNotePieces =
  362. std::count_if(path.begin(), path.end(),
  363. [](const std::shared_ptr<PathDiagnosticPiece> &p) {
  364. return isa<PathDiagnosticNotePiece>(*p);
  365. });
  366. unsigned TotalRegularPieces = TotalPieces - TotalNotePieces;
  367. unsigned NumRegularPieces = TotalRegularPieces;
  368. unsigned NumNotePieces = TotalNotePieces;
  369. for (auto I = path.rbegin(), E = path.rend(); I != E; ++I) {
  370. if (isa<PathDiagnosticNotePiece>(I->get())) {
  371. // This adds diagnostic bubbles, but not navigation.
  372. // Navigation through note pieces would be added later,
  373. // as a separate pass through the piece list.
  374. HandlePiece(R, FID, **I, NumNotePieces, TotalNotePieces);
  375. --NumNotePieces;
  376. } else {
  377. HandlePiece(R, FID, **I, NumRegularPieces, TotalRegularPieces);
  378. --NumRegularPieces;
  379. }
  380. }
  381. // Add line numbers, header, footer, etc.
  382. html::EscapeText(R, FID);
  383. html::AddLineNumbers(R, FID);
  384. // If we have a preprocessor, relex the file and syntax highlight.
  385. // We might not have a preprocessor if we come from a deserialized AST file,
  386. // for example.
  387. html::SyntaxHighlight(R, FID, PP);
  388. html::HighlightMacros(R, FID, PP);
  389. }
  390. void HTMLDiagnostics::HandlePiece(Rewriter& R, FileID BugFileID,
  391. const PathDiagnosticPiece& P,
  392. unsigned num, unsigned max) {
  393. // For now, just draw a box above the line in question, and emit the
  394. // warning.
  395. FullSourceLoc Pos = P.getLocation().asLocation();
  396. if (!Pos.isValid())
  397. return;
  398. SourceManager &SM = R.getSourceMgr();
  399. assert(&Pos.getManager() == &SM && "SourceManagers are different!");
  400. std::pair<FileID, unsigned> LPosInfo = SM.getDecomposedExpansionLoc(Pos);
  401. if (LPosInfo.first != BugFileID)
  402. return;
  403. const llvm::MemoryBuffer *Buf = SM.getBuffer(LPosInfo.first);
  404. const char* FileStart = Buf->getBufferStart();
  405. // Compute the column number. Rewind from the current position to the start
  406. // of the line.
  407. unsigned ColNo = SM.getColumnNumber(LPosInfo.first, LPosInfo.second);
  408. const char *TokInstantiationPtr =Pos.getExpansionLoc().getCharacterData();
  409. const char *LineStart = TokInstantiationPtr-ColNo;
  410. // Compute LineEnd.
  411. const char *LineEnd = TokInstantiationPtr;
  412. const char* FileEnd = Buf->getBufferEnd();
  413. while (*LineEnd != '\n' && LineEnd != FileEnd)
  414. ++LineEnd;
  415. // Compute the margin offset by counting tabs and non-tabs.
  416. unsigned PosNo = 0;
  417. for (const char* c = LineStart; c != TokInstantiationPtr; ++c)
  418. PosNo += *c == '\t' ? 8 : 1;
  419. // Create the html for the message.
  420. const char *Kind = nullptr;
  421. bool IsNote = false;
  422. bool SuppressIndex = (max == 1);
  423. switch (P.getKind()) {
  424. case PathDiagnosticPiece::Call:
  425. llvm_unreachable("Calls and extra notes should already be handled");
  426. case PathDiagnosticPiece::Event: Kind = "Event"; break;
  427. case PathDiagnosticPiece::ControlFlow: Kind = "Control"; break;
  428. // Setting Kind to "Control" is intentional.
  429. case PathDiagnosticPiece::Macro: Kind = "Control"; break;
  430. case PathDiagnosticPiece::Note:
  431. Kind = "Note";
  432. IsNote = true;
  433. SuppressIndex = true;
  434. break;
  435. }
  436. std::string sbuf;
  437. llvm::raw_string_ostream os(sbuf);
  438. os << "\n<tr><td class=\"num\"></td><td class=\"line\"><div id=\"";
  439. if (IsNote)
  440. os << "Note" << num;
  441. else if (num == max)
  442. os << "EndPath";
  443. else
  444. os << "Path" << num;
  445. os << "\" class=\"msg";
  446. if (Kind)
  447. os << " msg" << Kind;
  448. os << "\" style=\"margin-left:" << PosNo << "ex";
  449. // Output a maximum size.
  450. if (!isa<PathDiagnosticMacroPiece>(P)) {
  451. // Get the string and determining its maximum substring.
  452. const auto &Msg = P.getString();
  453. unsigned max_token = 0;
  454. unsigned cnt = 0;
  455. unsigned len = Msg.size();
  456. for (char C : Msg)
  457. switch (C) {
  458. default:
  459. ++cnt;
  460. continue;
  461. case ' ':
  462. case '\t':
  463. case '\n':
  464. if (cnt > max_token) max_token = cnt;
  465. cnt = 0;
  466. }
  467. if (cnt > max_token)
  468. max_token = cnt;
  469. // Determine the approximate size of the message bubble in em.
  470. unsigned em;
  471. const unsigned max_line = 120;
  472. if (max_token >= max_line)
  473. em = max_token / 2;
  474. else {
  475. unsigned characters = max_line;
  476. unsigned lines = len / max_line;
  477. if (lines > 0) {
  478. for (; characters > max_token; --characters)
  479. if (len / characters > lines) {
  480. ++characters;
  481. break;
  482. }
  483. }
  484. em = characters / 2;
  485. }
  486. if (em < max_line/2)
  487. os << "; max-width:" << em << "em";
  488. }
  489. else
  490. os << "; max-width:100em";
  491. os << "\">";
  492. if (!SuppressIndex) {
  493. os << "<table class=\"msgT\"><tr><td valign=\"top\">";
  494. os << "<div class=\"PathIndex";
  495. if (Kind) os << " PathIndex" << Kind;
  496. os << "\">" << num << "</div>";
  497. if (num > 1) {
  498. os << "</td><td><div class=\"PathNav\"><a href=\"#Path"
  499. << (num - 1)
  500. << "\" title=\"Previous event ("
  501. << (num - 1)
  502. << ")\">&#x2190;</a></div></td>";
  503. }
  504. os << "</td><td>";
  505. }
  506. if (const PathDiagnosticMacroPiece *MP =
  507. dyn_cast<PathDiagnosticMacroPiece>(&P)) {
  508. os << "Within the expansion of the macro '";
  509. // Get the name of the macro by relexing it.
  510. {
  511. FullSourceLoc L = MP->getLocation().asLocation().getExpansionLoc();
  512. assert(L.isFileID());
  513. StringRef BufferInfo = L.getBufferData();
  514. std::pair<FileID, unsigned> LocInfo = L.getDecomposedLoc();
  515. const char* MacroName = LocInfo.second + BufferInfo.data();
  516. Lexer rawLexer(SM.getLocForStartOfFile(LocInfo.first), PP.getLangOpts(),
  517. BufferInfo.begin(), MacroName, BufferInfo.end());
  518. Token TheTok;
  519. rawLexer.LexFromRawLexer(TheTok);
  520. for (unsigned i = 0, n = TheTok.getLength(); i < n; ++i)
  521. os << MacroName[i];
  522. }
  523. os << "':\n";
  524. if (!SuppressIndex) {
  525. os << "</td>";
  526. if (num < max) {
  527. os << "<td><div class=\"PathNav\"><a href=\"#";
  528. if (num == max - 1)
  529. os << "EndPath";
  530. else
  531. os << "Path" << (num + 1);
  532. os << "\" title=\"Next event ("
  533. << (num + 1)
  534. << ")\">&#x2192;</a></div></td>";
  535. }
  536. os << "</tr></table>";
  537. }
  538. // Within a macro piece. Write out each event.
  539. ProcessMacroPiece(os, *MP, 0);
  540. }
  541. else {
  542. os << html::EscapeText(P.getString());
  543. if (!SuppressIndex) {
  544. os << "</td>";
  545. if (num < max) {
  546. os << "<td><div class=\"PathNav\"><a href=\"#";
  547. if (num == max - 1)
  548. os << "EndPath";
  549. else
  550. os << "Path" << (num + 1);
  551. os << "\" title=\"Next event ("
  552. << (num + 1)
  553. << ")\">&#x2192;</a></div></td>";
  554. }
  555. os << "</tr></table>";
  556. }
  557. }
  558. os << "</div></td></tr>";
  559. // Insert the new html.
  560. unsigned DisplayPos = LineEnd - FileStart;
  561. SourceLocation Loc =
  562. SM.getLocForStartOfFile(LPosInfo.first).getLocWithOffset(DisplayPos);
  563. R.InsertTextBefore(Loc, os.str());
  564. // Now highlight the ranges.
  565. ArrayRef<SourceRange> Ranges = P.getRanges();
  566. for (ArrayRef<SourceRange>::iterator I = Ranges.begin(),
  567. E = Ranges.end(); I != E; ++I) {
  568. HighlightRange(R, LPosInfo.first, *I);
  569. }
  570. }
  571. static void EmitAlphaCounter(raw_ostream &os, unsigned n) {
  572. unsigned x = n % ('z' - 'a');
  573. n /= 'z' - 'a';
  574. if (n > 0)
  575. EmitAlphaCounter(os, n);
  576. os << char('a' + x);
  577. }
  578. unsigned HTMLDiagnostics::ProcessMacroPiece(raw_ostream &os,
  579. const PathDiagnosticMacroPiece& P,
  580. unsigned num) {
  581. for (PathPieces::const_iterator I = P.subPieces.begin(), E=P.subPieces.end();
  582. I!=E; ++I) {
  583. if (const PathDiagnosticMacroPiece *MP =
  584. dyn_cast<PathDiagnosticMacroPiece>(I->get())) {
  585. num = ProcessMacroPiece(os, *MP, num);
  586. continue;
  587. }
  588. if (PathDiagnosticEventPiece *EP =
  589. dyn_cast<PathDiagnosticEventPiece>(I->get())) {
  590. os << "<div class=\"msg msgEvent\" style=\"width:94%; "
  591. "margin-left:5px\">"
  592. "<table class=\"msgT\"><tr>"
  593. "<td valign=\"top\"><div class=\"PathIndex PathIndexEvent\">";
  594. EmitAlphaCounter(os, num++);
  595. os << "</div></td><td valign=\"top\">"
  596. << html::EscapeText(EP->getString())
  597. << "</td></tr></table></div>\n";
  598. }
  599. }
  600. return num;
  601. }
  602. void HTMLDiagnostics::HighlightRange(Rewriter& R, FileID BugFileID,
  603. SourceRange Range,
  604. const char *HighlightStart,
  605. const char *HighlightEnd) {
  606. SourceManager &SM = R.getSourceMgr();
  607. const LangOptions &LangOpts = R.getLangOpts();
  608. SourceLocation InstantiationStart = SM.getExpansionLoc(Range.getBegin());
  609. unsigned StartLineNo = SM.getExpansionLineNumber(InstantiationStart);
  610. SourceLocation InstantiationEnd = SM.getExpansionLoc(Range.getEnd());
  611. unsigned EndLineNo = SM.getExpansionLineNumber(InstantiationEnd);
  612. if (EndLineNo < StartLineNo)
  613. return;
  614. if (SM.getFileID(InstantiationStart) != BugFileID ||
  615. SM.getFileID(InstantiationEnd) != BugFileID)
  616. return;
  617. // Compute the column number of the end.
  618. unsigned EndColNo = SM.getExpansionColumnNumber(InstantiationEnd);
  619. unsigned OldEndColNo = EndColNo;
  620. if (EndColNo) {
  621. // Add in the length of the token, so that we cover multi-char tokens.
  622. EndColNo += Lexer::MeasureTokenLength(Range.getEnd(), SM, LangOpts)-1;
  623. }
  624. // Highlight the range. Make the span tag the outermost tag for the
  625. // selected range.
  626. SourceLocation E =
  627. InstantiationEnd.getLocWithOffset(EndColNo - OldEndColNo);
  628. html::HighlightRange(R, InstantiationStart, E, HighlightStart, HighlightEnd);
  629. }