26 #include "llvm/Support/Errc.h" 27 #include "llvm/Support/FileSystem.h" 28 #include "llvm/Support/MemoryBuffer.h" 29 #include "llvm/Support/Path.h" 30 #include "llvm/Support/raw_ostream.h" 33 using namespace clang;
43 std::string Directory;
44 bool createdDir, noDir;
47 const bool SupportsCrossFileDiagnostics;
50 const std::string& prefix,
52 bool supportsMultipleFiles);
54 ~HTMLDiagnostics()
override { FlushDiagnostics(
nullptr); }
56 void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
57 FilesMade *filesMade)
override;
59 StringRef getName()
const override {
60 return "HTMLDiagnostics";
63 bool supportsCrossFileDiagnostics()
const override {
64 return SupportsCrossFileDiagnostics;
67 unsigned ProcessMacroPiece(raw_ostream &os,
75 const char *HighlightStart =
"<span class=\"mrange\">",
76 const char *HighlightEnd =
"</span>");
79 FilesMade *filesMade);
84 const char *declName);
96 std::string generateKeyboardNavigationJavascript();
102 const std::string& prefix,
104 bool supportsMultipleFiles)
109 AnalyzerOpts(AnalyzerOpts),
110 SupportsCrossFileDiagnostics(supportsMultipleFiles) {}
114 const std::string& prefix,
116 C.push_back(
new HTMLDiagnostics(AnalyzerOpts, prefix, PP,
true));
119 void ento::createHTMLSingleFileDiagnosticConsumer(
AnalyzerOptions &AnalyzerOpts,
121 const std::string& prefix,
123 C.push_back(
new HTMLDiagnostics(AnalyzerOpts, prefix, PP,
false));
130 void HTMLDiagnostics::FlushDiagnosticsImpl(
131 std::vector<const PathDiagnostic *> &Diags,
132 FilesMade *filesMade) {
133 for (std::vector<const PathDiagnostic *>::iterator it = Diags.begin(),
134 et = Diags.end(); it != et; ++it) {
140 FilesMade *filesMade) {
145 if (std::error_code ec = llvm::sys::fs::create_directories(Directory)) {
146 llvm::errs() <<
"warning: could not create directory '" 147 << Directory <<
"': " << ec.message() <<
'\n';
162 assert(!path.empty());
163 const SourceManager &SMgr = path.front()->getLocation().getManager();
171 FileID ReportFile = path.front()->getLocation().asLocation().getExpansionLoc().getFileID();
177 if (
const NamedDecl *ND = dyn_cast<NamedDecl>(DeclWithIssue))
178 declName = ND->getDeclName().getAsString();
180 if (
const Stmt *Body = DeclWithIssue->getBody()) {
184 SMgr.getExpansionLoc(path.back()->getLocation().asLocation()),
186 FullSourceLoc FunL(SMgr.getExpansionLoc(Body->getLocStart()), SMgr);
187 offsetDecl = L.getExpansionLineNumber() - FunL.getExpansionLineNumber();
191 std::string report = GenerateHTML(D, R, SMgr, path, declName.c_str());
192 if (report.empty()) {
193 llvm::errs() <<
"warning: no diagnostics generated for main file.\n";
202 llvm::sys::path::append(Model, Directory,
"report-%%%%%%.html");
203 if (std::error_code EC =
204 llvm::sys::fs::make_absolute(Model)) {
205 llvm::errs() <<
"warning: could not make '" << Model
206 <<
"' absolute: " << EC.message() <<
'\n';
209 if (std::error_code EC =
210 llvm::sys::fs::createUniqueFile(Model, FD, ResultPath)) {
211 llvm::errs() <<
"warning: could not create file in '" << Directory
212 <<
"': " << EC.message() <<
'\n';
221 const FileEntry* Entry = SMgr.getFileEntryForID(ReportFile);
222 std::stringstream filename;
224 filename <<
"report-" 225 << llvm::sys::path::filename(Entry->
getName()).str()
226 <<
"-" << declName.c_str()
228 <<
"-" << i <<
".html";
229 llvm::sys::path::append(Model, Directory,
231 EC = llvm::sys::fs::openFileForWrite(Model,
233 llvm::sys::fs::F_RW |
234 llvm::sys::fs::F_Excl);
235 if (EC && EC != llvm::errc::file_exists) {
236 llvm::errs() <<
"warning: could not create file '" << Model
237 <<
"': " << EC.message() <<
'\n';
244 llvm::raw_fd_ostream os(FD,
true);
247 filesMade->addDiagnostic(D, getName(),
248 llvm::sys::path::filename(ResultPath));
258 std::vector<FileID> FileIDs;
259 for (
auto I : path) {
260 FileID FID = I->getLocation().asLocation().getExpansionLoc().getFileID();
261 if (std::find(FileIDs.begin(), FileIDs.end(), FID) != FileIDs.end())
264 FileIDs.push_back(FID);
265 RewriteFile(R, SMgr, path, FID);
268 if (SupportsCrossFileDiagnostics && FileIDs.size() > 1) {
270 for (
auto I = FileIDs.begin(), E = FileIDs.end(); I != E; I++) {
272 llvm::raw_string_ostream os(s);
274 if (I != FileIDs.begin())
275 os <<
"<hr class=divider>\n";
277 os <<
"<div id=File" << I->getHashValue() <<
">\n";
280 if (I != FileIDs.begin())
281 os <<
"<div class=FileNav><a href=\"#File" << (I - 1)->getHashValue()
282 <<
"\">←</a></div>";
289 os <<
"<div class=FileNav><a href=\"#File" << (I + 1)->getHashValue()
290 <<
"\">→</a></div>";
298 for (
auto I : llvm::make_range(FileIDs.begin() + 1, FileIDs.end())) {
300 llvm::raw_string_ostream os(s);
316 FinalizeHTML(D, R, SMgr, path, FileIDs[0], Entry, declName);
319 llvm::raw_string_ostream os(file);
328 const FileEntry *Entry,
const char *declName) {
335 if (llvm::sys::path::is_relative(Entry->
getName())) {
336 llvm::sys::fs::current_path(DirName);
340 int LineNumber = path.back()->getLocation().asLocation().getExpansionLineNumber();
341 int ColumnNumber = path.back()->getLocation().asLocation().getExpansionColumnNumber();
344 generateKeyboardNavigationJavascript());
349 llvm::raw_string_ostream os(s);
351 os <<
"<!-- REPORTHEADER -->\n" 352 <<
"<h3>Bug Summary</h3>\n<table class=\"simpletable\">\n" 353 "<tr><td class=\"rowname\">File:</td><td>" 356 <<
"</td></tr>\n<tr><td class=\"rowname\">Warning:</td><td>" 357 "<a href=\"#EndPath\">line " 365 unsigned NumExtraPieces = 0;
366 for (
const auto &Piece : path) {
367 if (
const auto *
P = dyn_cast<PathDiagnosticNotePiece>(Piece.get())) {
369 P->getLocation().asLocation().getExpansionLineNumber();
371 P->getLocation().asLocation().getExpansionColumnNumber();
372 os <<
"<tr><td class=\"rowname\">Note:</td><td>" 373 <<
"<a href=\"#Note" << NumExtraPieces <<
"\">line " 374 << LineNumber <<
", column " << ColumnNumber <<
"</a><br />" 375 <<
P->getString() <<
"</td></tr>";
389 <!-- REPORTSUMMARYEXTRA --> 390 <h3>Annotated Source Code</h3> 391 <p><span class='macro'>[?] 392 <span class='expansion'>Use j/k keys for keyboard navigation</span> 402 llvm::raw_string_ostream os(s);
405 if (!BugDesc.empty())
406 os <<
"\n<!-- BUGDESC " << BugDesc <<
" -->\n";
409 if (!BugType.empty())
410 os <<
"\n<!-- BUGTYPE " << BugType <<
" -->\n";
420 if (!BugCategory.empty())
421 os <<
"\n<!-- BUGCATEGORY " << BugCategory <<
" -->\n";
423 os <<
"\n<!-- BUGFILE " << DirName << Entry->
getName() <<
" -->\n";
425 os <<
"\n<!-- FILENAME " << llvm::sys::path::filename(Entry->
getName()) <<
" -->\n";
427 os <<
"\n<!-- FUNCTIONNAME " << declName <<
" -->\n";
429 os <<
"\n<!-- ISSUEHASHCONTENTOFLINEINCONTEXT " 433 os <<
"\n<!-- BUGLINE " 437 os <<
"\n<!-- BUGCOLUMN " 441 os <<
"\n<!-- BUGPATHLENGTH " << path.size() <<
" -->\n";
444 os <<
"\n<!-- BUGMETAEND -->\n";
457 unsigned TotalPieces = path.size();
458 unsigned TotalNotePieces =
459 std::count_if(path.begin(), path.end(),
460 [](
const std::shared_ptr<PathDiagnosticPiece> &p) {
461 return isa<PathDiagnosticNotePiece>(*p);
464 unsigned TotalRegularPieces = TotalPieces - TotalNotePieces;
465 unsigned NumRegularPieces = TotalRegularPieces;
466 unsigned NumNotePieces = TotalNotePieces;
468 for (
auto I = path.rbegin(), E = path.rend(); I != E; ++I) {
469 if (isa<PathDiagnosticNotePiece>(I->get())) {
473 HandlePiece(R, FID, **I, NumNotePieces, TotalNotePieces);
476 HandlePiece(R, FID, **I, NumRegularPieces, TotalRegularPieces);
496 unsigned num,
unsigned max) {
506 assert(&Pos.
getManager() == &SM &&
"SourceManagers are different!");
509 if (LPosInfo.first != BugFileID)
512 const llvm::MemoryBuffer *Buf = SM.
getBuffer(LPosInfo.first);
513 const char* FileStart = Buf->getBufferStart();
519 const char *LineStart = TokInstantiationPtr-ColNo;
522 const char *LineEnd = TokInstantiationPtr;
523 const char* FileEnd = Buf->getBufferEnd();
524 while (*LineEnd !=
'\n' && LineEnd != FileEnd)
529 for (
const char* c = LineStart; c != TokInstantiationPtr; ++c)
530 PosNo += *c ==
'\t' ? 8 : 1;
534 const char *
Kind =
nullptr;
536 bool SuppressIndex = (max == 1);
539 llvm_unreachable(
"Calls and extra notes should already be handled");
547 SuppressIndex =
true;
552 llvm::raw_string_ostream os(sbuf);
554 os <<
"\n<tr><td class=\"num\"></td><td class=\"line\"><div id=\"";
563 os <<
"\" class=\"msg";
565 os <<
" msg" <<
Kind;
566 os <<
"\" style=\"margin-left:" << PosNo <<
"ex";
569 if (!isa<PathDiagnosticMacroPiece>(P)) {
572 unsigned max_token = 0;
574 unsigned len = Msg.size();
584 if (cnt > max_token) max_token = cnt;
593 const unsigned max_line = 120;
595 if (max_token >= max_line)
598 unsigned characters = max_line;
599 unsigned lines = len / max_line;
602 for (; characters > max_token; --characters)
603 if (len / characters > lines) {
613 os <<
"; max-width:" << em <<
"em";
616 os <<
"; max-width:100em";
620 if (!SuppressIndex) {
621 os <<
"<table class=\"msgT\"><tr><td valign=\"top\">";
622 os <<
"<div class=\"PathIndex";
623 if (Kind) os <<
" PathIndex" <<
Kind;
624 os <<
"\">" << num <<
"</div>";
627 os <<
"</td><td><div class=\"PathNav\"><a href=\"#Path" 629 <<
"\" title=\"Previous event (" 631 <<
")\">←</a></div></td>";
638 dyn_cast<PathDiagnosticMacroPiece>(&P)) {
640 os <<
"Within the expansion of the macro '";
648 const char* MacroName = LocInfo.second + BufferInfo.data();
650 BufferInfo.begin(), MacroName, BufferInfo.end());
653 rawLexer.LexFromRawLexer(TheTok);
654 for (
unsigned i = 0, n = TheTok.getLength(); i < n; ++i)
660 if (!SuppressIndex) {
663 os <<
"<td><div class=\"PathNav\"><a href=\"#";
667 os <<
"Path" << (num + 1);
668 os <<
"\" title=\"Next event (" 670 <<
")\">→</a></div></td>";
673 os <<
"</tr></table>";
677 ProcessMacroPiece(os, *MP, 0);
682 if (!SuppressIndex) {
685 os <<
"<td><div class=\"PathNav\"><a href=\"#";
689 os <<
"Path" << (num + 1);
690 os <<
"\" title=\"Next event (" 692 <<
")\">→</a></div></td>";
695 os <<
"</tr></table>";
699 os <<
"</div></td></tr>";
702 unsigned DisplayPos = LineEnd - FileStart;
711 E = Ranges.end(); I != E; ++I) {
717 unsigned x = n % (
'z' -
'a');
726 unsigned HTMLDiagnostics::ProcessMacroPiece(raw_ostream &os,
734 dyn_cast<PathDiagnosticMacroPiece>(I->get())) {
735 num = ProcessMacroPiece(os, *MP, num);
740 dyn_cast<PathDiagnosticEventPiece>(I->get())) {
741 os <<
"<div class=\"msg msgEvent\" style=\"width:94%; " 743 "<table class=\"msgT\"><tr>" 744 "<td valign=\"top\"><div class=\"PathIndex PathIndexEvent\">";
746 os <<
"</div></td><td valign=\"top\">" 748 <<
"</td></tr></table></div>\n";
757 const char *HighlightStart,
758 const char *HighlightEnd) {
768 if (EndLineNo < StartLineNo)
771 if (SM.
getFileID(InstantiationStart) != BugFileID ||
772 SM.
getFileID(InstantiationEnd) != BugFileID)
777 unsigned OldEndColNo = EndColNo;
793 std::string HTMLDiagnostics::generateKeyboardNavigationJavascript() {
795 <script type='text/javascript'> 796 var digitMatcher = new RegExp("[0-9]+"); 798 document.addEventListener("DOMContentLoaded", function() { 799 document.querySelectorAll(".PathNav > a").forEach( 800 function(currentValue, currentIndex) { 801 var hrefValue = currentValue.getAttribute("href"); 802 currentValue.onclick = function() { 803 scrollTo(document.querySelector(hrefValue)); 809 var findNum = function() { 810 var s = document.querySelector(".selected"); 811 if (!s || s.id == "EndPath") { 814 var out = parseInt(digitMatcher.exec(s.id)[0]); 818 var scrollTo = function(el) { 819 document.querySelectorAll(".selected").forEach(function(s) { 820 s.classList.remove("selected"); 822 el.classList.add("selected"); 823 window.scrollBy(0, el.getBoundingClientRect().top - 824 (window.innerHeight / 2)); 827 var move = function(num, up, numItems) { 828 if (num == 1 && up || num == numItems - 1 && !up) { 830 } else if (num == 0 && up) { 832 } else if (num == 0 && !up) { 835 return up ? num - 1 : num + 1; 838 var numToId = function(num) { 840 return document.getElementById("EndPath") 842 return document.getElementById("Path" + num); 845 var navigateTo = function(up) { 846 var numItems = document.querySelectorAll(".line > .msg").length; 847 var currentSelected = findNum(); 848 var newSelected = move(currentSelected, up, numItems); 849 var newEl = numToId(newSelected, numItems); 851 // Scroll element into center. 855 window.addEventListener("keydown", function (event) { 856 if (event.defaultPrevented) { 859 if (event.key == "j") { 860 navigateTo(/*up=*/false); 861 } else if (event.key == "k") { 862 navigateTo(/*up=*/true); 866 event.preventDefault(); SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file. ...
Defines the clang::ASTContext interface.
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens...
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.
std::deque< std::string >::const_iterator meta_iterator
FullSourceLoc getExpansionLoc() const
Stmt - This represents one statement.
Defines the SourceManager interface.
Decl - This represents one declaration (or definition), e.g.
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's from the original input with modifications get a...
meta_iterator meta_begin() const
PathDiagnosticLocation getLocation() const
PathDiagnostic - PathDiagnostic objects represent a single path-sensitive diagnostic.
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)
StringRef getVerboseDescription() const
Token - This structure provides full information about a lexed token.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
const LangOptions & getLangOpts() const
std::pair< FileID, unsigned > getDecomposedExpansionLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
SourceManager & getSourceMgr() const
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID...
StringRef getBugType() const
meta_iterator meta_end() const
void SyntaxHighlight(Rewriter &R, FileID FID, const Preprocessor &PP)
SyntaxHighlight - Relex the specified FileID and annotate the HTML with information about keywords...
StringRef getCheckName() const
virtual PathDiagnosticLocation getLocation() const =0
bool shouldWriteStableReportFilename()
Returns whether or not the report filename should be random or not.
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 ...
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.
PathDiagnosticLocation getUniqueingLoc() const
Get the location on which the report should be uniqued.
const SourceManager & getManager() const
SourceLocation getEnd() const
unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
static void ReportDiag(raw_ostream &o, const PathDiagnosticPiece &P, const FIDMap &FM, const SourceManager &SM, const LangOptions &LangOpts)
PathPieces flatten(bool ShouldFlattenMacros) const
StringRef getCategory() const
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
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...
Cached information about one file (either on disk or in the virtual file system). ...
const RewriteBuffer * getRewriteBufferFor(FileID FID) const
getRewriteBufferFor - Return the rewrite buffer for the specified FileID.
FullSourceLoc asLocation() const
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...
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
unsigned getExpansionColumnNumber(SourceLocation Loc, bool *Invalid=nullptr) const
ArrayRef< SourceRange > getRanges() const
Return the SourceRanges associated with this PathDiagnosticPiece.
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
char __ovld __cnfn max(char x, char y)
Returns y if x < y, otherwise it returns x.
Rewriter - This is the main interface to the rewrite buffers.
A SourceLocation and its associated SourceManager.
A trivial tuple used to represent a source range.
NamedDecl - This represents a decl with a name.
StringRef getString() const
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.
const Decl * getDeclWithIssue() const
Return the semantic context where an issue occurred.
void HighlightRange(Rewriter &R, SourceLocation B, SourceLocation E, const char *StartTag, const char *EndTag)
HighlightRange - Highlight a range in the source code with the specified start/end tags...