clang  8.0.0svn
HTMLDiagnostics.cpp
Go to the documentation of this file.
1 //===- HTMLDiagnostics.cpp - HTML Diagnostics for Paths -------------------===//
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 
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclBase.h"
16 #include "clang/AST/Stmt.h"
18 #include "clang/Basic/LLVM.h"
21 #include "clang/Lex/Lexer.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "clang/Lex/Token.h"
30 #include "llvm/ADT/ArrayRef.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/StringRef.h"
33 #include "llvm/ADT/iterator_range.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/Errc.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/FileSystem.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include <algorithm>
42 #include <cassert>
43 #include <map>
44 #include <memory>
45 #include <set>
46 #include <sstream>
47 #include <string>
48 #include <system_error>
49 #include <utility>
50 #include <vector>
51 
52 using namespace clang;
53 using namespace ento;
54 
55 //===----------------------------------------------------------------------===//
56 // Boilerplate.
57 //===----------------------------------------------------------------------===//
58 
59 namespace {
60 
61 class HTMLDiagnostics : public PathDiagnosticConsumer {
62  std::string Directory;
63  bool createdDir = false;
64  bool noDir = false;
65  const Preprocessor &PP;
66  AnalyzerOptions &AnalyzerOpts;
67  const bool SupportsCrossFileDiagnostics;
68 
69 public:
70  HTMLDiagnostics(AnalyzerOptions &AnalyzerOpts,
71  const std::string& prefix,
72  const Preprocessor &pp,
73  bool supportsMultipleFiles)
74  : Directory(prefix), PP(pp), AnalyzerOpts(AnalyzerOpts),
75  SupportsCrossFileDiagnostics(supportsMultipleFiles) {}
76 
77  ~HTMLDiagnostics() override { FlushDiagnostics(nullptr); }
78 
79  void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
80  FilesMade *filesMade) override;
81 
82  StringRef getName() const override {
83  return "HTMLDiagnostics";
84  }
85 
86  bool supportsCrossFileDiagnostics() const override {
87  return SupportsCrossFileDiagnostics;
88  }
89 
90  unsigned ProcessMacroPiece(raw_ostream &os,
91  const PathDiagnosticMacroPiece& P,
92  unsigned num);
93 
94  void HandlePiece(Rewriter& R, FileID BugFileID,
95  const PathDiagnosticPiece& P, unsigned num, unsigned max);
96 
97  void HighlightRange(Rewriter& R, FileID BugFileID, SourceRange Range,
98  const char *HighlightStart = "<span class=\"mrange\">",
99  const char *HighlightEnd = "</span>");
100 
101  void ReportDiag(const PathDiagnostic& D,
102  FilesMade *filesMade);
103 
104  // Generate the full HTML report
105  std::string GenerateHTML(const PathDiagnostic& D, Rewriter &R,
106  const SourceManager& SMgr, const PathPieces& path,
107  const char *declName);
108 
109  // Add HTML header/footers to file specified by FID
110  void FinalizeHTML(const PathDiagnostic& D, Rewriter &R,
111  const SourceManager& SMgr, const PathPieces& path,
112  FileID FID, const FileEntry *Entry, const char *declName);
113 
114  // Rewrite the file specified by FID with HTML formatting.
115  void RewriteFile(Rewriter &R, const PathPieces& path, FileID FID);
116 
117 
118 private:
119  /// \return Javascript for displaying shortcuts help;
120  StringRef showHelpJavascript();
121 
122  /// \return Javascript for navigating the HTML report using j/k keys.
123  StringRef generateKeyboardNavigationJavascript();
124 
125  /// \return JavaScript for an option to only show relevant lines.
126  std::string showRelevantLinesJavascript(
127  const PathDiagnostic &D, const PathPieces &path);
128 
129  /// Write executed lines from \p D in JSON format into \p os.
130  void dumpCoverageData(const PathDiagnostic &D,
131  const PathPieces &path,
132  llvm::raw_string_ostream &os);
133 };
134 
135 } // namespace
136 
137 void ento::createHTMLDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
139  const std::string& prefix,
140  const Preprocessor &PP) {
141  C.push_back(new HTMLDiagnostics(AnalyzerOpts, prefix, PP, true));
142 }
143 
144 void ento::createHTMLSingleFileDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
146  const std::string& prefix,
147  const Preprocessor &PP) {
148  C.push_back(new HTMLDiagnostics(AnalyzerOpts, prefix, PP, false));
149 }
150 
151 //===----------------------------------------------------------------------===//
152 // Report processing.
153 //===----------------------------------------------------------------------===//
154 
155 void HTMLDiagnostics::FlushDiagnosticsImpl(
156  std::vector<const PathDiagnostic *> &Diags,
157  FilesMade *filesMade) {
158  for (const auto Diag : Diags)
159  ReportDiag(*Diag, filesMade);
160 }
161 
162 void HTMLDiagnostics::ReportDiag(const PathDiagnostic& D,
163  FilesMade *filesMade) {
164  // Create the HTML directory if it is missing.
165  if (!createdDir) {
166  createdDir = true;
167  if (std::error_code ec = llvm::sys::fs::create_directories(Directory)) {
168  llvm::errs() << "warning: could not create directory '"
169  << Directory << "': " << ec.message() << '\n';
170  noDir = true;
171  return;
172  }
173  }
174 
175  if (noDir)
176  return;
177 
178  // First flatten out the entire path to make it easier to use.
179  PathPieces path = D.path.flatten(/*ShouldFlattenMacros=*/false);
180 
181  // The path as already been prechecked that the path is non-empty.
182  assert(!path.empty());
183  const SourceManager &SMgr = path.front()->getLocation().getManager();
184 
185  // Create a new rewriter to generate HTML.
186  Rewriter R(const_cast<SourceManager&>(SMgr), PP.getLangOpts());
187 
188  // The file for the first path element is considered the main report file, it
189  // will usually be equivalent to SMgr.getMainFileID(); however, it might be a
190  // header when -analyzer-opt-analyze-headers is used.
191  FileID ReportFile = path.front()->getLocation().asLocation().getExpansionLoc().getFileID();
192 
193  // Get the function/method name
194  SmallString<128> declName("unknown");
195  int offsetDecl = 0;
196  if (const Decl *DeclWithIssue = D.getDeclWithIssue()) {
197  if (const auto *ND = dyn_cast<NamedDecl>(DeclWithIssue))
198  declName = ND->getDeclName().getAsString();
199 
200  if (const Stmt *Body = DeclWithIssue->getBody()) {
201  // Retrieve the relative position of the declaration which will be used
202  // for the file name
203  FullSourceLoc L(
204  SMgr.getExpansionLoc(path.back()->getLocation().asLocation()),
205  SMgr);
206  FullSourceLoc FunL(SMgr.getExpansionLoc(Body->getBeginLoc()), SMgr);
207  offsetDecl = L.getExpansionLineNumber() - FunL.getExpansionLineNumber();
208  }
209  }
210 
211  std::string report = GenerateHTML(D, R, SMgr, path, declName.c_str());
212  if (report.empty()) {
213  llvm::errs() << "warning: no diagnostics generated for main file.\n";
214  return;
215  }
216 
217  // Create a path for the target HTML file.
218  int FD;
219  SmallString<128> Model, ResultPath;
220 
221  if (!AnalyzerOpts.ShouldWriteStableReportFilename) {
222  llvm::sys::path::append(Model, Directory, "report-%%%%%%.html");
223  if (std::error_code EC =
224  llvm::sys::fs::make_absolute(Model)) {
225  llvm::errs() << "warning: could not make '" << Model
226  << "' absolute: " << EC.message() << '\n';
227  return;
228  }
229  if (std::error_code EC =
230  llvm::sys::fs::createUniqueFile(Model, FD, ResultPath)) {
231  llvm::errs() << "warning: could not create file in '" << Directory
232  << "': " << EC.message() << '\n';
233  return;
234  }
235  } else {
236  int i = 1;
237  std::error_code EC;
238  do {
239  // Find a filename which is not already used
240  const FileEntry* Entry = SMgr.getFileEntryForID(ReportFile);
241  std::stringstream filename;
242  Model = "";
243  filename << "report-"
244  << llvm::sys::path::filename(Entry->getName()).str()
245  << "-" << declName.c_str()
246  << "-" << offsetDecl
247  << "-" << i << ".html";
248  llvm::sys::path::append(Model, Directory,
249  filename.str());
250  EC = llvm::sys::fs::openFileForReadWrite(
251  Model, FD, llvm::sys::fs::CD_CreateNew, llvm::sys::fs::OF_None);
252  if (EC && EC != llvm::errc::file_exists) {
253  llvm::errs() << "warning: could not create file '" << Model
254  << "': " << EC.message() << '\n';
255  return;
256  }
257  i++;
258  } while (EC);
259  }
260 
261  llvm::raw_fd_ostream os(FD, true);
262 
263  if (filesMade)
264  filesMade->addDiagnostic(D, getName(),
265  llvm::sys::path::filename(ResultPath));
266 
267  // Emit the HTML to disk.
268  os << report;
269 }
270 
271 std::string HTMLDiagnostics::GenerateHTML(const PathDiagnostic& D, Rewriter &R,
272  const SourceManager& SMgr, const PathPieces& path, const char *declName) {
273  // Rewrite source files as HTML for every new file the path crosses
274  std::vector<FileID> FileIDs;
275  for (auto I : path) {
276  FileID FID = I->getLocation().asLocation().getExpansionLoc().getFileID();
277  if (std::find(FileIDs.begin(), FileIDs.end(), FID) != FileIDs.end())
278  continue;
279 
280  FileIDs.push_back(FID);
281  RewriteFile(R, path, FID);
282  }
283 
284  if (SupportsCrossFileDiagnostics && FileIDs.size() > 1) {
285  // Prefix file names, anchor tags, and nav cursors to every file
286  for (auto I = FileIDs.begin(), E = FileIDs.end(); I != E; I++) {
287  std::string s;
288  llvm::raw_string_ostream os(s);
289 
290  if (I != FileIDs.begin())
291  os << "<hr class=divider>\n";
292 
293  os << "<div id=File" << I->getHashValue() << ">\n";
294 
295  // Left nav arrow
296  if (I != FileIDs.begin())
297  os << "<div class=FileNav><a href=\"#File" << (I - 1)->getHashValue()
298  << "\">&#x2190;</a></div>";
299 
300  os << "<h4 class=FileName>" << SMgr.getFileEntryForID(*I)->getName()
301  << "</h4>\n";
302 
303  // Right nav arrow
304  if (I + 1 != E)
305  os << "<div class=FileNav><a href=\"#File" << (I + 1)->getHashValue()
306  << "\">&#x2192;</a></div>";
307 
308  os << "</div>\n";
309 
310  R.InsertTextBefore(SMgr.getLocForStartOfFile(*I), os.str());
311  }
312 
313  // Append files to the main report file in the order they appear in the path
314  for (auto I : llvm::make_range(FileIDs.begin() + 1, FileIDs.end())) {
315  std::string s;
316  llvm::raw_string_ostream os(s);
317 
318  const RewriteBuffer *Buf = R.getRewriteBufferFor(I);
319  for (auto BI : *Buf)
320  os << BI;
321 
322  R.InsertTextAfter(SMgr.getLocForEndOfFile(FileIDs[0]), os.str());
323  }
324  }
325 
326  const RewriteBuffer *Buf = R.getRewriteBufferFor(FileIDs[0]);
327  if (!Buf)
328  return {};
329 
330  // Add CSS, header, and footer.
331  FileID FID =
332  path.back()->getLocation().asLocation().getExpansionLoc().getFileID();
333  const FileEntry* Entry = SMgr.getFileEntryForID(FID);
334  FinalizeHTML(D, R, SMgr, path, FileIDs[0], Entry, declName);
335 
336  std::string file;
337  llvm::raw_string_ostream os(file);
338  for (auto BI : *Buf)
339  os << BI;
340 
341  return os.str();
342 }
343 
344 void HTMLDiagnostics::dumpCoverageData(
345  const PathDiagnostic &D,
346  const PathPieces &path,
347  llvm::raw_string_ostream &os) {
348 
349  const FilesToLineNumsMap &ExecutedLines = D.getExecutedLines();
350 
351  os << "var relevant_lines = {";
352  for (auto I = ExecutedLines.begin(),
353  E = ExecutedLines.end(); I != E; ++I) {
354  if (I != ExecutedLines.begin())
355  os << ", ";
356 
357  os << "\"" << I->first.getHashValue() << "\": {";
358  for (unsigned LineNo : I->second) {
359  if (LineNo != *(I->second.begin()))
360  os << ", ";
361 
362  os << "\"" << LineNo << "\": 1";
363  }
364  os << "}";
365  }
366 
367  os << "};";
368 }
369 
370 std::string HTMLDiagnostics::showRelevantLinesJavascript(
371  const PathDiagnostic &D, const PathPieces &path) {
372  std::string s;
373  llvm::raw_string_ostream os(s);
374  os << "<script type='text/javascript'>\n";
375  dumpCoverageData(D, path, os);
376  os << R"<<<(
377 
378 var filterCounterexample = function (hide) {
379  var tables = document.getElementsByClassName("code");
380  for (var t=0; t<tables.length; t++) {
381  var table = tables[t];
382  var file_id = table.getAttribute("data-fileid");
383  var lines_in_fid = relevant_lines[file_id];
384  if (!lines_in_fid) {
385  lines_in_fid = {};
386  }
387  var lines = table.getElementsByClassName("codeline");
388  for (var i=0; i<lines.length; i++) {
389  var el = lines[i];
390  var lineNo = el.getAttribute("data-linenumber");
391  if (!lines_in_fid[lineNo]) {
392  if (hide) {
393  el.setAttribute("hidden", "");
394  } else {
395  el.removeAttribute("hidden");
396  }
397  }
398  }
399  }
400 }
401 
402 window.addEventListener("keydown", function (event) {
403  if (event.defaultPrevented) {
404  return;
405  }
406  if (event.key == "S") {
407  var checked = document.getElementsByName("showCounterexample")[0].checked;
408  filterCounterexample(!checked);
409  document.getElementsByName("showCounterexample")[0].checked = !checked;
410  } else {
411  return;
412  }
413  event.preventDefault();
414 }, true);
415 
416 document.addEventListener("DOMContentLoaded", function() {
417  document.querySelector('input[name="showCounterexample"]').onchange=
418  function (event) {
419  filterCounterexample(this.checked);
420  };
421 });
422 </script>
423 
424 <form>
425  <input type="checkbox" name="showCounterexample" id="showCounterexample" />
426  <label for="showCounterexample">
427  Show only relevant lines
428  </label>
429 </form>
430 )<<<";
431 
432  return os.str();
433 }
434 
435 void HTMLDiagnostics::FinalizeHTML(const PathDiagnostic& D, Rewriter &R,
436  const SourceManager& SMgr, const PathPieces& path, FileID FID,
437  const FileEntry *Entry, const char *declName) {
438  // This is a cludge; basically we want to append either the full
439  // working directory if we have no directory information. This is
440  // a work in progress.
441 
442  llvm::SmallString<0> DirName;
443 
444  if (llvm::sys::path::is_relative(Entry->getName())) {
445  llvm::sys::fs::current_path(DirName);
446  DirName += '/';
447  }
448 
449  int LineNumber = path.back()->getLocation().asLocation().getExpansionLineNumber();
450  int ColumnNumber = path.back()->getLocation().asLocation().getExpansionColumnNumber();
451 
452  R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), showHelpJavascript());
453 
455  generateKeyboardNavigationJavascript());
456 
457  // Checkbox and javascript for filtering the output to the counterexample.
459  showRelevantLinesJavascript(D, path));
460 
461  // Add the name of the file as an <h1> tag.
462  {
463  std::string s;
464  llvm::raw_string_ostream os(s);
465 
466  os << "<!-- REPORTHEADER -->\n"
467  << "<h3>Bug Summary</h3>\n<table class=\"simpletable\">\n"
468  "<tr><td class=\"rowname\">File:</td><td>"
469  << html::EscapeText(DirName)
470  << html::EscapeText(Entry->getName())
471  << "</td></tr>\n<tr><td class=\"rowname\">Warning:</td><td>"
472  "<a href=\"#EndPath\">line "
473  << LineNumber
474  << ", column "
475  << ColumnNumber
476  << "</a><br />"
477  << D.getVerboseDescription() << "</td></tr>\n";
478 
479  // The navigation across the extra notes pieces.
480  unsigned NumExtraPieces = 0;
481  for (const auto &Piece : path) {
482  if (const auto *P = dyn_cast<PathDiagnosticNotePiece>(Piece.get())) {
483  int LineNumber =
484  P->getLocation().asLocation().getExpansionLineNumber();
485  int ColumnNumber =
486  P->getLocation().asLocation().getExpansionColumnNumber();
487  os << "<tr><td class=\"rowname\">Note:</td><td>"
488  << "<a href=\"#Note" << NumExtraPieces << "\">line "
489  << LineNumber << ", column " << ColumnNumber << "</a><br />"
490  << P->getString() << "</td></tr>";
491  ++NumExtraPieces;
492  }
493  }
494 
495  // Output any other meta data.
496 
497  for (PathDiagnostic::meta_iterator I = D.meta_begin(), E = D.meta_end();
498  I != E; ++I) {
499  os << "<tr><td></td><td>" << html::EscapeText(*I) << "</td></tr>\n";
500  }
501 
502  os << R"<<<(
503 </table>
504 <!-- REPORTSUMMARYEXTRA -->
505 <h3>Annotated Source Code</h3>
506 <p>Press <a href="#" onclick="toggleHelp(); return false;">'?'</a>
507  to see keyboard shortcuts</p>
508 <input type="checkbox" class="spoilerhider" id="showinvocation" />
509 <label for="showinvocation" >Show analyzer invocation</label>
510 <div class="spoiler">clang -cc1 )<<<";
511  os << html::EscapeText(AnalyzerOpts.FullCompilerInvocation);
512  os << R"<<<(
513 </div>
514 <div id='tooltiphint' hidden="true">
515  <p>Keyboard shortcuts: </p>
516  <ul>
517  <li>Use 'j/k' keys for keyboard navigation</li>
518  <li>Use 'Shift+S' to show/hide relevant lines</li>
519  <li>Use '?' to toggle this window</li>
520  </ul>
521  <a href="#" onclick="toggleHelp(); return false;">Close</a>
522 </div>
523 )<<<";
524  R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
525  }
526 
527  // Embed meta-data tags.
528  {
529  std::string s;
530  llvm::raw_string_ostream os(s);
531 
532  StringRef BugDesc = D.getVerboseDescription();
533  if (!BugDesc.empty())
534  os << "\n<!-- BUGDESC " << BugDesc << " -->\n";
535 
536  StringRef BugType = D.getBugType();
537  if (!BugType.empty())
538  os << "\n<!-- BUGTYPE " << BugType << " -->\n";
539 
540  PathDiagnosticLocation UPDLoc = D.getUniqueingLoc();
541  FullSourceLoc L(SMgr.getExpansionLoc(UPDLoc.isValid()
542  ? UPDLoc.asLocation()
543  : D.getLocation().asLocation()),
544  SMgr);
545  const Decl *DeclWithIssue = D.getDeclWithIssue();
546 
547  StringRef BugCategory = D.getCategory();
548  if (!BugCategory.empty())
549  os << "\n<!-- BUGCATEGORY " << BugCategory << " -->\n";
550 
551  os << "\n<!-- BUGFILE " << DirName << Entry->getName() << " -->\n";
552 
553  os << "\n<!-- FILENAME " << llvm::sys::path::filename(Entry->getName()) << " -->\n";
554 
555  os << "\n<!-- FUNCTIONNAME " << declName << " -->\n";
556 
557  os << "\n<!-- ISSUEHASHCONTENTOFLINEINCONTEXT "
558  << GetIssueHash(SMgr, L, D.getCheckName(), D.getBugType(), DeclWithIssue,
559  PP.getLangOpts()) << " -->\n";
560 
561  os << "\n<!-- BUGLINE "
562  << LineNumber
563  << " -->\n";
564 
565  os << "\n<!-- BUGCOLUMN "
566  << ColumnNumber
567  << " -->\n";
568 
569  os << "\n<!-- BUGPATHLENGTH " << path.size() << " -->\n";
570 
571  // Mark the end of the tags.
572  os << "\n<!-- BUGMETAEND -->\n";
573 
574  // Insert the text.
575  R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
576  }
577 
579 }
580 
581 StringRef HTMLDiagnostics::showHelpJavascript() {
582  return R"<<<(
583 <script type='text/javascript'>
584 
585 var toggleHelp = function() {
586  var hint = document.querySelector("#tooltiphint");
587  var attributeName = "hidden";
588  if (hint.hasAttribute(attributeName)) {
589  hint.removeAttribute(attributeName);
590  } else {
591  hint.setAttribute("hidden", "true");
592  }
593 };
594 window.addEventListener("keydown", function (event) {
595  if (event.defaultPrevented) {
596  return;
597  }
598  if (event.key == "?") {
599  toggleHelp();
600  } else {
601  return;
602  }
603  event.preventDefault();
604 });
605 </script>
606 )<<<";
607 }
608 
609 void HTMLDiagnostics::RewriteFile(Rewriter &R,
610  const PathPieces& path, FileID FID) {
611  // Process the path.
612  // Maintain the counts of extra note pieces separately.
613  unsigned TotalPieces = path.size();
614  unsigned TotalNotePieces =
615  std::count_if(path.begin(), path.end(),
616  [](const std::shared_ptr<PathDiagnosticPiece> &p) {
617  return isa<PathDiagnosticNotePiece>(*p);
618  });
619 
620  unsigned TotalRegularPieces = TotalPieces - TotalNotePieces;
621  unsigned NumRegularPieces = TotalRegularPieces;
622  unsigned NumNotePieces = TotalNotePieces;
623 
624  for (auto I = path.rbegin(), E = path.rend(); I != E; ++I) {
625  if (isa<PathDiagnosticNotePiece>(I->get())) {
626  // This adds diagnostic bubbles, but not navigation.
627  // Navigation through note pieces would be added later,
628  // as a separate pass through the piece list.
629  HandlePiece(R, FID, **I, NumNotePieces, TotalNotePieces);
630  --NumNotePieces;
631  } else {
632  HandlePiece(R, FID, **I, NumRegularPieces, TotalRegularPieces);
633  --NumRegularPieces;
634  }
635  }
636 
637  // Add line numbers, header, footer, etc.
638 
639  html::EscapeText(R, FID);
640  html::AddLineNumbers(R, FID);
641 
642  // If we have a preprocessor, relex the file and syntax highlight.
643  // We might not have a preprocessor if we come from a deserialized AST file,
644  // for example.
645 
646  html::SyntaxHighlight(R, FID, PP);
647  html::HighlightMacros(R, FID, PP);
648 }
649 
650 void HTMLDiagnostics::HandlePiece(Rewriter& R, FileID BugFileID,
651  const PathDiagnosticPiece& P,
652  unsigned num, unsigned max) {
653  // For now, just draw a box above the line in question, and emit the
654  // warning.
655  FullSourceLoc Pos = P.getLocation().asLocation();
656 
657  if (!Pos.isValid())
658  return;
659 
661  assert(&Pos.getManager() == &SM && "SourceManagers are different!");
662  std::pair<FileID, unsigned> LPosInfo = SM.getDecomposedExpansionLoc(Pos);
663 
664  if (LPosInfo.first != BugFileID)
665  return;
666 
667  const llvm::MemoryBuffer *Buf = SM.getBuffer(LPosInfo.first);
668  const char* FileStart = Buf->getBufferStart();
669 
670  // Compute the column number. Rewind from the current position to the start
671  // of the line.
672  unsigned ColNo = SM.getColumnNumber(LPosInfo.first, LPosInfo.second);
673  const char *TokInstantiationPtr =Pos.getExpansionLoc().getCharacterData();
674  const char *LineStart = TokInstantiationPtr-ColNo;
675 
676  // Compute LineEnd.
677  const char *LineEnd = TokInstantiationPtr;
678  const char* FileEnd = Buf->getBufferEnd();
679  while (*LineEnd != '\n' && LineEnd != FileEnd)
680  ++LineEnd;
681 
682  // Compute the margin offset by counting tabs and non-tabs.
683  unsigned PosNo = 0;
684  for (const char* c = LineStart; c != TokInstantiationPtr; ++c)
685  PosNo += *c == '\t' ? 8 : 1;
686 
687  // Create the html for the message.
688 
689  const char *Kind = nullptr;
690  bool IsNote = false;
691  bool SuppressIndex = (max == 1);
692  switch (P.getKind()) {
694  llvm_unreachable("Calls and extra notes should already be handled");
695  case PathDiagnosticPiece::Event: Kind = "Event"; break;
696  case PathDiagnosticPiece::ControlFlow: Kind = "Control"; break;
697  // Setting Kind to "Control" is intentional.
698  case PathDiagnosticPiece::Macro: Kind = "Control"; break;
700  Kind = "Note";
701  IsNote = true;
702  SuppressIndex = true;
703  break;
704  }
705 
706  std::string sbuf;
707  llvm::raw_string_ostream os(sbuf);
708 
709  os << "\n<tr><td class=\"num\"></td><td class=\"line\"><div id=\"";
710 
711  if (IsNote)
712  os << "Note" << num;
713  else if (num == max)
714  os << "EndPath";
715  else
716  os << "Path" << num;
717 
718  os << "\" class=\"msg";
719  if (Kind)
720  os << " msg" << Kind;
721  os << "\" style=\"margin-left:" << PosNo << "ex";
722 
723  // Output a maximum size.
724  if (!isa<PathDiagnosticMacroPiece>(P)) {
725  // Get the string and determining its maximum substring.
726  const auto &Msg = P.getString();
727  unsigned max_token = 0;
728  unsigned cnt = 0;
729  unsigned len = Msg.size();
730 
731  for (char C : Msg)
732  switch (C) {
733  default:
734  ++cnt;
735  continue;
736  case ' ':
737  case '\t':
738  case '\n':
739  if (cnt > max_token) max_token = cnt;
740  cnt = 0;
741  }
742 
743  if (cnt > max_token)
744  max_token = cnt;
745 
746  // Determine the approximate size of the message bubble in em.
747  unsigned em;
748  const unsigned max_line = 120;
749 
750  if (max_token >= max_line)
751  em = max_token / 2;
752  else {
753  unsigned characters = max_line;
754  unsigned lines = len / max_line;
755 
756  if (lines > 0) {
757  for (; characters > max_token; --characters)
758  if (len / characters > lines) {
759  ++characters;
760  break;
761  }
762  }
763 
764  em = characters / 2;
765  }
766 
767  if (em < max_line/2)
768  os << "; max-width:" << em << "em";
769  }
770  else
771  os << "; max-width:100em";
772 
773  os << "\">";
774 
775  if (!SuppressIndex) {
776  os << "<table class=\"msgT\"><tr><td valign=\"top\">";
777  os << "<div class=\"PathIndex";
778  if (Kind) os << " PathIndex" << Kind;
779  os << "\">" << num << "</div>";
780 
781  if (num > 1) {
782  os << "</td><td><div class=\"PathNav\"><a href=\"#Path"
783  << (num - 1)
784  << "\" title=\"Previous event ("
785  << (num - 1)
786  << ")\">&#x2190;</a></div></td>";
787  }
788 
789  os << "</td><td>";
790  }
791 
792  if (const auto *MP = dyn_cast<PathDiagnosticMacroPiece>(&P)) {
793  os << "Within the expansion of the macro '";
794 
795  // Get the name of the macro by relexing it.
796  {
797  FullSourceLoc L = MP->getLocation().asLocation().getExpansionLoc();
798  assert(L.isFileID());
799  StringRef BufferInfo = L.getBufferData();
800  std::pair<FileID, unsigned> LocInfo = L.getDecomposedLoc();
801  const char* MacroName = LocInfo.second + BufferInfo.data();
802  Lexer rawLexer(SM.getLocForStartOfFile(LocInfo.first), PP.getLangOpts(),
803  BufferInfo.begin(), MacroName, BufferInfo.end());
804 
805  Token TheTok;
806  rawLexer.LexFromRawLexer(TheTok);
807  for (unsigned i = 0, n = TheTok.getLength(); i < n; ++i)
808  os << MacroName[i];
809  }
810 
811  os << "':\n";
812 
813  if (!SuppressIndex) {
814  os << "</td>";
815  if (num < max) {
816  os << "<td><div class=\"PathNav\"><a href=\"#";
817  if (num == max - 1)
818  os << "EndPath";
819  else
820  os << "Path" << (num + 1);
821  os << "\" title=\"Next event ("
822  << (num + 1)
823  << ")\">&#x2192;</a></div></td>";
824  }
825 
826  os << "</tr></table>";
827  }
828 
829  // Within a macro piece. Write out each event.
830  ProcessMacroPiece(os, *MP, 0);
831  }
832  else {
833  os << html::EscapeText(P.getString());
834 
835  if (!SuppressIndex) {
836  os << "</td>";
837  if (num < max) {
838  os << "<td><div class=\"PathNav\"><a href=\"#";
839  if (num == max - 1)
840  os << "EndPath";
841  else
842  os << "Path" << (num + 1);
843  os << "\" title=\"Next event ("
844  << (num + 1)
845  << ")\">&#x2192;</a></div></td>";
846  }
847 
848  os << "</tr></table>";
849  }
850  }
851 
852  os << "</div></td></tr>";
853 
854  // Insert the new html.
855  unsigned DisplayPos = LineEnd - FileStart;
856  SourceLocation Loc =
857  SM.getLocForStartOfFile(LPosInfo.first).getLocWithOffset(DisplayPos);
858 
859  R.InsertTextBefore(Loc, os.str());
860 
861  // Now highlight the ranges.
862  ArrayRef<SourceRange> Ranges = P.getRanges();
863  for (const auto &Range : Ranges)
864  HighlightRange(R, LPosInfo.first, Range);
865 }
866 
867 static void EmitAlphaCounter(raw_ostream &os, unsigned n) {
868  unsigned x = n % ('z' - 'a');
869  n /= 'z' - 'a';
870 
871  if (n > 0)
872  EmitAlphaCounter(os, n);
873 
874  os << char('a' + x);
875 }
876 
877 unsigned HTMLDiagnostics::ProcessMacroPiece(raw_ostream &os,
878  const PathDiagnosticMacroPiece& P,
879  unsigned num) {
880  for (const auto &subPiece : P.subPieces) {
881  if (const auto *MP = dyn_cast<PathDiagnosticMacroPiece>(subPiece.get())) {
882  num = ProcessMacroPiece(os, *MP, num);
883  continue;
884  }
885 
886  if (const auto *EP = dyn_cast<PathDiagnosticEventPiece>(subPiece.get())) {
887  os << "<div class=\"msg msgEvent\" style=\"width:94%; "
888  "margin-left:5px\">"
889  "<table class=\"msgT\"><tr>"
890  "<td valign=\"top\"><div class=\"PathIndex PathIndexEvent\">";
891  EmitAlphaCounter(os, num++);
892  os << "</div></td><td valign=\"top\">"
893  << html::EscapeText(EP->getString())
894  << "</td></tr></table></div>\n";
895  }
896  }
897 
898  return num;
899 }
900 
902  SourceRange Range,
903  const char *HighlightStart,
904  const char *HighlightEnd) {
905  SourceManager &SM = R.getSourceMgr();
906  const LangOptions &LangOpts = R.getLangOpts();
907 
908  SourceLocation InstantiationStart = SM.getExpansionLoc(Range.getBegin());
909  unsigned StartLineNo = SM.getExpansionLineNumber(InstantiationStart);
910 
911  SourceLocation InstantiationEnd = SM.getExpansionLoc(Range.getEnd());
912  unsigned EndLineNo = SM.getExpansionLineNumber(InstantiationEnd);
913 
914  if (EndLineNo < StartLineNo)
915  return;
916 
917  if (SM.getFileID(InstantiationStart) != BugFileID ||
918  SM.getFileID(InstantiationEnd) != BugFileID)
919  return;
920 
921  // Compute the column number of the end.
922  unsigned EndColNo = SM.getExpansionColumnNumber(InstantiationEnd);
923  unsigned OldEndColNo = EndColNo;
924 
925  if (EndColNo) {
926  // Add in the length of the token, so that we cover multi-char tokens.
927  EndColNo += Lexer::MeasureTokenLength(Range.getEnd(), SM, LangOpts)-1;
928  }
929 
930  // Highlight the range. Make the span tag the outermost tag for the
931  // selected range.
932 
933  SourceLocation E =
934  InstantiationEnd.getLocWithOffset(EndColNo - OldEndColNo);
935 
936  html::HighlightRange(R, InstantiationStart, E, HighlightStart, HighlightEnd);
937 }
938 
939 StringRef HTMLDiagnostics::generateKeyboardNavigationJavascript() {
940  return R"<<<(
941 <script type='text/javascript'>
942 var digitMatcher = new RegExp("[0-9]+");
943 
944 document.addEventListener("DOMContentLoaded", function() {
945  document.querySelectorAll(".PathNav > a").forEach(
946  function(currentValue, currentIndex) {
947  var hrefValue = currentValue.getAttribute("href");
948  currentValue.onclick = function() {
949  scrollTo(document.querySelector(hrefValue));
950  return false;
951  };
952  });
953 });
954 
955 var findNum = function() {
956  var s = document.querySelector(".selected");
957  if (!s || s.id == "EndPath") {
958  return 0;
959  }
960  var out = parseInt(digitMatcher.exec(s.id)[0]);
961  return out;
962 };
963 
964 var scrollTo = function(el) {
965  document.querySelectorAll(".selected").forEach(function(s) {
966  s.classList.remove("selected");
967  });
968  el.classList.add("selected");
969  window.scrollBy(0, el.getBoundingClientRect().top -
970  (window.innerHeight / 2));
971 }
972 
973 var move = function(num, up, numItems) {
974  if (num == 1 && up || num == numItems - 1 && !up) {
975  return 0;
976  } else if (num == 0 && up) {
977  return numItems - 1;
978  } else if (num == 0 && !up) {
979  return 1 % numItems;
980  }
981  return up ? num - 1 : num + 1;
982 }
983 
984 var numToId = function(num) {
985  if (num == 0) {
986  return document.getElementById("EndPath")
987  }
988  return document.getElementById("Path" + num);
989 };
990 
991 var navigateTo = function(up) {
992  var numItems = document.querySelectorAll(
993  ".line > .msgEvent, .line > .msgControl").length;
994  var currentSelected = findNum();
995  var newSelected = move(currentSelected, up, numItems);
996  var newEl = numToId(newSelected, numItems);
997 
998  // Scroll element into center.
999  scrollTo(newEl);
1000 };
1001 
1002 window.addEventListener("keydown", function (event) {
1003  if (event.defaultPrevented) {
1004  return;
1005  }
1006  if (event.key == "j") {
1007  navigateTo(/*up=*/false);
1008  } else if (event.key == "k") {
1009  navigateTo(/*up=*/true);
1010  } else {
1011  return;
1012  }
1013  event.preventDefault();
1014 }, true);
1015 </script>
1016  )<<<";
1017 }
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file. ...
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens...
Definition: Lexer.h:77
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
SourceLocation getLocForEndOfFile(FileID FID) const
Return the source location corresponding to the last byte of the specified file.
Defines the clang::FileManager interface and associated types.
FullSourceLoc getExpansionLoc() const
Stmt - This represents one statement.
Definition: Stmt.h:66
Defines the SourceManager interface.
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:87
StringRef P
unsigned getColumnNumber(FileID FID, unsigned FilePos, bool *Invalid=nullptr) const
Return the column # for the specified file position.
llvm::SmallString< 32 > GetIssueHash(const SourceManager &SM, FullSourceLoc &IssueLoc, llvm::StringRef CheckerName, llvm::StringRef BugType, const Decl *D, const LangOptions &LangOpts)
Get an MD5 hash to help identify bugs.
RewriteBuffer - As code is rewritten, SourceBuffer&#39;s from the original input with modifications get a...
Definition: RewriteBuffer.h:26
std::string getName(ArrayRef< StringRef > Parts) const
Get the platform-specific name separator.
void HighlightMacros(Rewriter &R, FileID FID, const Preprocessor &PP)
HighlightMacros - This uses the macro table state from the end of the file, to reexpand macros and in...
void AddLineNumbers(Rewriter &R, FileID FID)
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:50
const LangOptions & getLangOpts() const
Definition: Preprocessor.h:815
std::pair< FileID, unsigned > getDecomposedExpansionLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
SourceManager & getSourceMgr() const
Definition: Rewriter.h:67
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID...
std::string FullCompilerInvocation
Store full compiler invocation for reproducible instructions in the generated report.
void SyntaxHighlight(Rewriter &R, FileID FID, const Preprocessor &PP)
SyntaxHighlight - Relex the specified FileID and annotate the HTML with information about keywords...
return Out str()
std::pair< FileID, unsigned > getDecomposedLoc() const
Decompose the specified location into a raw FileID + Offset pair.
static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
MeasureTokenLength - Relex the token at the specified location and return its length in bytes in the ...
Definition: Lexer.cpp:436
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
static void EmitAlphaCounter(raw_ostream &os, unsigned n)
const char * getCharacterData(bool *Invalid=nullptr) const
Defines the clang::Preprocessor interface.
const SourceManager & getManager() const
SourceLocation getEnd() const
std::map< FileID, std::set< unsigned > > FilesToLineNumsMap
File IDs mapped to sets of line numbers.
unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
const SourceManager & SM
Definition: Format.cpp:1490
Kind
llvm::MemoryBuffer * getBuffer(FileID FID, SourceLocation Loc, bool *Invalid=nullptr) const
Return the buffer for the specified FileID.
Encodes a location in the source.
StringRef getName() const
Definition: FileManager.h:86
std::vector< PathDiagnosticConsumer * > PathDiagnosticConsumers
void EscapeText(Rewriter &R, FileID FID, bool EscapeSpaces=false, bool ReplaceTabs=false)
EscapeText - HTMLize a specified file so that special characters are are translated so that they are ...
bool InsertTextAfter(SourceLocation Loc, StringRef Str)
InsertTextAfter - Insert the specified string at the specified location in the original buffer...
Definition: Rewriter.h:104
Cached information about one file (either on disk or in the virtual file system). ...
Definition: FileManager.h:60
std::deque< std::string >::const_iterator meta_iterator
const RewriteBuffer * getRewriteBufferFor(FileID FID) const
getRewriteBufferFor - Return the rewrite buffer for the specified FileID.
Definition: Rewriter.h:172
StringRef getBufferData(bool *Invalid=nullptr) const
Return a StringRef to the source buffer data for the specified FileID.
bool InsertTextBefore(SourceLocation Loc, StringRef Str)
InsertText - Insert the specified string at the specified location in the original buffer...
Definition: Rewriter.h:117
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
unsigned getExpansionColumnNumber(SourceLocation Loc, bool *Invalid=nullptr) const
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
void AddHeaderFooterInternalBuiltinCSS(Rewriter &R, FileID FID, StringRef title)
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
const LangOptions & getLangOpts() const
Definition: Rewriter.h:68
Stores options for the analyzer from the command line.
Rewriter - This is the main interface to the rewrite buffers.
Definition: Rewriter.h:33
Defines the clang::SourceLocation class and associated facilities.
void HighlightRange(Rewriter &R, SourceLocation B, SourceLocation E, const char *StartTag, const char *EndTag, bool IsTokenRange=true)
HighlightRange - Highlight a range in the source code with the specified start/end tags...
Definition: HTMLRewrite.cpp:32
A SourceLocation and its associated SourceManager.
__DEVICE__ int max(int __a, int __b)
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
This class handles loading and caching of source files into memory.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:125