#include "clang/Frontend/TextDiagnostic.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Lex/Lexer.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Locale.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
using namespace clang;
static const enum raw_ostream::Colors noteColor =
raw_ostream::BLACK;
static const enum raw_ostream::Colors remarkColor =
raw_ostream::BLUE;
static const enum raw_ostream::Colors fixitColor =
raw_ostream::GREEN;
static const enum raw_ostream::Colors caretColor =
raw_ostream::GREEN;
static const enum raw_ostream::Colors warningColor =
raw_ostream::MAGENTA;
static const enum raw_ostream::Colors templateColor =
raw_ostream::CYAN;
static const enum raw_ostream::Colors errorColor = raw_ostream::RED;
static const enum raw_ostream::Colors fatalColor = raw_ostream::RED;
static const enum raw_ostream::Colors savedColor =
raw_ostream::SAVEDCOLOR;
static void applyTemplateHighlighting(raw_ostream &OS, StringRef Str,
bool &Normal, bool Bold) {
while (true) {
size_t Pos = Str.find(ToggleHighlight);
OS << Str.slice(0, Pos);
if (Pos == StringRef::npos)
break;
Str = Str.substr(Pos + 1);
if (Normal)
OS.changeColor(templateColor, true);
else {
OS.resetColor();
if (Bold)
OS.changeColor(savedColor, true);
}
Normal = !Normal;
}
}
const unsigned WordWrapIndentation = 6;
static int bytesSincePreviousTabOrLineBegin(StringRef SourceLine, size_t i) {
int bytes = 0;
while (0<i) {
if (SourceLine[--i]=='\t')
break;
++bytes;
}
return bytes;
}
static std::pair<SmallString<16>, bool>
printableTextForNextCharacter(StringRef SourceLine, size_t *i,
unsigned TabStop) {
assert(i && "i must not be null");
assert(*i<SourceLine.size() && "must point to a valid index");
if (SourceLine[*i]=='\t') {
assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
"Invalid -ftabstop value");
unsigned col = bytesSincePreviousTabOrLineBegin(SourceLine, *i);
unsigned NumSpaces = TabStop - col%TabStop;
assert(0 < NumSpaces && NumSpaces <= TabStop
&& "Invalid computation of space amt");
++(*i);
SmallString<16> expandedTab;
expandedTab.assign(NumSpaces, ' ');
return std::make_pair(expandedTab, true);
}
unsigned char const *begin, *end;
begin = reinterpret_cast<unsigned char const *>(&*(SourceLine.begin() + *i));
end = begin + (SourceLine.size() - *i);
if (llvm::isLegalUTF8Sequence(begin, end)) {
llvm::UTF32 c;
llvm::UTF32 *cptr = &c;
unsigned char const *original_begin = begin;
unsigned char const *cp_end =
begin + llvm::getNumBytesForUTF8(SourceLine[*i]);
llvm::ConversionResult res = llvm::ConvertUTF8toUTF32(
&begin, cp_end, &cptr, cptr + 1, llvm::strictConversion);
(void)res;
assert(llvm::conversionOK == res);
assert(0 < begin-original_begin
&& "we must be further along in the string now");
*i += begin-original_begin;
if (!llvm::sys::locale::isPrint(c)) {
SmallString<16> expandedCP("<U+>");
while (c) {
expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(c%16));
c/=16;
}
while (expandedCP.size() < 8)
expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(0));
return std::make_pair(expandedCP, false);
}
return std::make_pair(SmallString<16>(original_begin, cp_end), true);
}
SmallString<16> expandedByte("<XX>");
unsigned char byte = SourceLine[*i];
expandedByte[1] = llvm::hexdigit(byte / 16);
expandedByte[2] = llvm::hexdigit(byte % 16);
++(*i);
return std::make_pair(expandedByte, false);
}
static void expandTabs(std::string &SourceLine, unsigned TabStop) {
size_t i = SourceLine.size();
while (i>0) {
i--;
if (SourceLine[i]!='\t')
continue;
size_t tmp_i = i;
std::pair<SmallString<16>,bool> res
= printableTextForNextCharacter(SourceLine, &tmp_i, TabStop);
SourceLine.replace(i, 1, res.first.c_str());
}
}
static void byteToColumn(StringRef SourceLine, unsigned TabStop,
SmallVectorImpl<int> &out) {
out.clear();
if (SourceLine.empty()) {
out.resize(1u,0);
return;
}
out.resize(SourceLine.size()+1, -1);
int columns = 0;
size_t i = 0;
while (i<SourceLine.size()) {
out[i] = columns;
std::pair<SmallString<16>,bool> res
= printableTextForNextCharacter(SourceLine, &i, TabStop);
columns += llvm::sys::locale::columnWidth(res.first);
}
out.back() = columns;
}
static void columnToByte(StringRef SourceLine, unsigned TabStop,
SmallVectorImpl<int> &out) {
out.clear();
if (SourceLine.empty()) {
out.resize(1u, 0);
return;
}
int columns = 0;
size_t i = 0;
while (i<SourceLine.size()) {
out.resize(columns+1, -1);
out.back() = i;
std::pair<SmallString<16>,bool> res
= printableTextForNextCharacter(SourceLine, &i, TabStop);
columns += llvm::sys::locale::columnWidth(res.first);
}
out.resize(columns+1, -1);
out.back() = i;
}
namespace {
struct SourceColumnMap {
SourceColumnMap(StringRef SourceLine, unsigned TabStop)
: m_SourceLine(SourceLine) {
::byteToColumn(SourceLine, TabStop, m_byteToColumn);
::columnToByte(SourceLine, TabStop, m_columnToByte);
assert(m_byteToColumn.size()==SourceLine.size()+1);
assert(0 < m_byteToColumn.size() && 0 < m_columnToByte.size());
assert(m_byteToColumn.size()
== static_cast<unsigned>(m_columnToByte.back()+1));
assert(static_cast<unsigned>(m_byteToColumn.back()+1)
== m_columnToByte.size());
}
int columns() const { return m_byteToColumn.back(); }
int bytes() const { return m_columnToByte.back(); }
int byteToColumn(int n) const {
assert(0<=n && n<static_cast<int>(m_byteToColumn.size()));
return m_byteToColumn[n];
}
int byteToContainingColumn(int N) const {
assert(0 <= N && N < static_cast<int>(m_byteToColumn.size()));
while (m_byteToColumn[N] == -1)
--N;
return m_byteToColumn[N];
}
int columnToByte(int n) const {
assert(0<=n && n<static_cast<int>(m_columnToByte.size()));
return m_columnToByte[n];
}
int startOfNextColumn(int N) const {
assert(0 <= N && N < static_cast<int>(m_byteToColumn.size() - 1));
while (byteToColumn(++N) == -1) {}
return N;
}
int startOfPreviousColumn(int N) const {
assert(0 < N && N < static_cast<int>(m_byteToColumn.size()));
while (byteToColumn(--N) == -1) {}
return N;
}
StringRef getSourceLine() const {
return m_SourceLine;
}
private:
const std::string m_SourceLine;
SmallVector<int,200> m_byteToColumn;
SmallVector<int,200> m_columnToByte;
};
}
static void selectInterestingSourceRegion(std::string &SourceLine,
std::string &CaretLine,
std::string &FixItInsertionLine,
unsigned Columns,
const SourceColumnMap &map) {
unsigned CaretColumns = CaretLine.size();
unsigned FixItColumns = llvm::sys::locale::columnWidth(FixItInsertionLine);
unsigned MaxColumns = std::max(static_cast<unsigned>(map.columns()),
std::max(CaretColumns, FixItColumns));
if (MaxColumns <= Columns)
return;
assert(CaretLine.end() ==
llvm::find_if(CaretLine, [](char c) { return c < ' ' || '~' < c; }));
unsigned CaretStart = 0, CaretEnd = CaretLine.size();
for (; CaretStart != CaretEnd; ++CaretStart)
if (!isWhitespace(CaretLine[CaretStart]))
break;
for (; CaretEnd != CaretStart; --CaretEnd)
if (!isWhitespace(CaretLine[CaretEnd - 1]))
break;
if (!FixItInsertionLine.empty()) {
unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
for (; FixItStart != FixItEnd; ++FixItStart)
if (!isWhitespace(FixItInsertionLine[FixItStart]))
break;
for (; FixItEnd != FixItStart; --FixItEnd)
if (!isWhitespace(FixItInsertionLine[FixItEnd - 1]))
break;
unsigned FixItStartCol = FixItStart;
unsigned FixItEndCol
= llvm::sys::locale::columnWidth(FixItInsertionLine.substr(0, FixItEnd));
CaretStart = std::min(FixItStartCol, CaretStart);
CaretEnd = std::max(FixItEndCol, CaretEnd);
}
while (static_cast<int>(CaretEnd) < map.columns() &&
-1 == map.columnToByte(CaretEnd))
++CaretEnd;
assert((static_cast<int>(CaretStart) > map.columns() ||
-1!=map.columnToByte(CaretStart)) &&
"CaretStart must not point to a column in the middle of a source"
" line character");
assert((static_cast<int>(CaretEnd) > map.columns() ||
-1!=map.columnToByte(CaretEnd)) &&
"CaretEnd must not point to a column in the middle of a source line"
" character");
unsigned SourceStart = map.columnToByte(std::min<unsigned>(CaretStart,
map.columns()));
unsigned SourceEnd = map.columnToByte(std::min<unsigned>(CaretEnd,
map.columns()));
unsigned CaretColumnsOutsideSource = CaretEnd-CaretStart
- (map.byteToColumn(SourceEnd)-map.byteToColumn(SourceStart));
char const *front_ellipse = " ...";
char const *front_space = " ";
char const *back_ellipse = "...";
unsigned ellipses_space = strlen(front_ellipse) + strlen(back_ellipse);
unsigned TargetColumns = Columns;
if (TargetColumns > ellipses_space+CaretColumnsOutsideSource)
TargetColumns -= ellipses_space+CaretColumnsOutsideSource;
while (SourceStart>0 || SourceEnd<SourceLine.size()) {
bool ExpandedRegion = false;
if (SourceStart>0) {
unsigned NewStart = map.startOfPreviousColumn(SourceStart);
while (NewStart && isWhitespace(SourceLine[NewStart]))
NewStart = map.startOfPreviousColumn(NewStart);
while (NewStart) {
unsigned Prev = map.startOfPreviousColumn(NewStart);
if (isWhitespace(SourceLine[Prev]))
break;
NewStart = Prev;
}
assert(map.byteToColumn(NewStart) != -1);
unsigned NewColumns = map.byteToColumn(SourceEnd) -
map.byteToColumn(NewStart);
if (NewColumns <= TargetColumns) {
SourceStart = NewStart;
ExpandedRegion = true;
}
}
if (SourceEnd<SourceLine.size()) {
unsigned NewEnd = map.startOfNextColumn(SourceEnd);
while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd]))
NewEnd = map.startOfNextColumn(NewEnd);
while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd]))
NewEnd = map.startOfNextColumn(NewEnd);
assert(map.byteToColumn(NewEnd) != -1);
unsigned NewColumns = map.byteToColumn(NewEnd) -
map.byteToColumn(SourceStart);
if (NewColumns <= TargetColumns) {
SourceEnd = NewEnd;
ExpandedRegion = true;
}
}
if (!ExpandedRegion)
break;
}
CaretStart = map.byteToColumn(SourceStart);
CaretEnd = map.byteToColumn(SourceEnd) + CaretColumnsOutsideSource;
assert(CaretStart!=(unsigned)-1 && CaretEnd!=(unsigned)-1 &&
SourceStart!=(unsigned)-1 && SourceEnd!=(unsigned)-1);
assert(SourceStart <= SourceEnd);
assert(CaretStart <= CaretEnd);
unsigned BackColumnsRemoved
= map.byteToColumn(SourceLine.size())-map.byteToColumn(SourceEnd);
unsigned FrontColumnsRemoved = CaretStart;
unsigned ColumnsKept = CaretEnd-CaretStart;
assert(FrontColumnsRemoved+ColumnsKept+BackColumnsRemoved > Columns);
if (BackColumnsRemoved > strlen(back_ellipse))
SourceLine.replace(SourceEnd, std::string::npos, back_ellipse);
if (FrontColumnsRemoved+ColumnsKept <= Columns)
return;
if (FrontColumnsRemoved > strlen(front_ellipse)) {
SourceLine.replace(0, SourceStart, front_ellipse);
CaretLine.replace(0, CaretStart, front_space);
if (!FixItInsertionLine.empty())
FixItInsertionLine.replace(0, CaretStart, front_space);
}
}
static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
while (Idx < Length && isWhitespace(Str[Idx]))
++Idx;
return Idx;
}
static inline char findMatchingPunctuation(char c) {
switch (c) {
case '\'': return '\'';
case '`': return '\'';
case '"': return '"';
case '(': return ')';
case '[': return ']';
case '{': return '}';
default: break;
}
return 0;
}
static unsigned findEndOfWord(unsigned Start, StringRef Str,
unsigned Length, unsigned Column,
unsigned Columns) {
assert(Start < Str.size() && "Invalid start position!");
unsigned End = Start + 1;
if (End == Str.size())
return End;
char EndPunct = findMatchingPunctuation(Str[Start]);
if (!EndPunct) {
while (End < Length && !isWhitespace(Str[End]))
++End;
return End;
}
SmallString<16> PunctuationEndStack;
PunctuationEndStack.push_back(EndPunct);
while (End < Length && !PunctuationEndStack.empty()) {
if (Str[End] == PunctuationEndStack.back())
PunctuationEndStack.pop_back();
else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
PunctuationEndStack.push_back(SubEndPunct);
++End;
}
while (End < Length && !isWhitespace(Str[End]))
++End;
unsigned PunctWordLength = End - Start;
if ( Column + PunctWordLength <= Columns ||
PunctWordLength < Columns/3)
return End;
return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
}
static bool printWordWrapped(raw_ostream &OS, StringRef Str,
unsigned Columns,
unsigned Column = 0,
bool Bold = false,
unsigned Indentation = WordWrapIndentation) {
const unsigned Length = std::min(Str.find('\n'), Str.size());
bool TextNormal = true;
SmallString<16> IndentStr;
IndentStr.assign(Indentation, ' ');
bool Wrapped = false;
for (unsigned WordStart = 0, WordEnd; WordStart < Length;
WordStart = WordEnd) {
WordStart = skipWhitespace(WordStart, Str, Length);
if (WordStart == Length)
break;
WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
unsigned WordLength = WordEnd - WordStart;
if (Column + WordLength < Columns) {
if (WordStart) {
OS << ' ';
Column += 1;
}
applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
TextNormal, Bold);
Column += WordLength;
continue;
}
OS << '\n';
OS.write(&IndentStr[0], Indentation);
applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
TextNormal, Bold);
Column = Indentation + WordLength;
Wrapped = true;
}
applyTemplateHighlighting(OS, Str.substr(Length), TextNormal, Bold);
assert(TextNormal && "Text highlighted at end of diagnostic message.");
return Wrapped;
}
TextDiagnostic::TextDiagnostic(raw_ostream &OS,
const LangOptions &LangOpts,
DiagnosticOptions *DiagOpts)
: DiagnosticRenderer(LangOpts, DiagOpts), OS(OS) {}
TextDiagnostic::~TextDiagnostic() {}
void TextDiagnostic::emitDiagnosticMessage(
FullSourceLoc Loc, PresumedLoc PLoc, DiagnosticsEngine::Level Level,
StringRef Message, ArrayRef<clang::CharSourceRange> Ranges,
DiagOrStoredDiag D) {
uint64_t StartOfLocationInfo = OS.tell();
if (Loc.isValid())
emitDiagnosticLoc(Loc, PLoc, Level, Ranges);
if (DiagOpts->ShowColors)
OS.resetColor();
if (DiagOpts->ShowLevel)
printDiagnosticLevel(OS, Level, DiagOpts->ShowColors);
printDiagnosticMessage(OS,
Level == DiagnosticsEngine::Note,
Message, OS.tell() - StartOfLocationInfo,
DiagOpts->MessageLength, DiagOpts->ShowColors);
}
void
TextDiagnostic::printDiagnosticLevel(raw_ostream &OS,
DiagnosticsEngine::Level Level,
bool ShowColors) {
if (ShowColors) {
switch (Level) {
case DiagnosticsEngine::Ignored:
llvm_unreachable("Invalid diagnostic type");
case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break;
case DiagnosticsEngine::Remark: OS.changeColor(remarkColor, true); break;
case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break;
case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break;
}
}
switch (Level) {
case DiagnosticsEngine::Ignored:
llvm_unreachable("Invalid diagnostic type");
case DiagnosticsEngine::Note: OS << "note: "; break;
case DiagnosticsEngine::Remark: OS << "remark: "; break;
case DiagnosticsEngine::Warning: OS << "warning: "; break;
case DiagnosticsEngine::Error: OS << "error: "; break;
case DiagnosticsEngine::Fatal: OS << "fatal error: "; break;
}
if (ShowColors)
OS.resetColor();
}
void TextDiagnostic::printDiagnosticMessage(raw_ostream &OS,
bool IsSupplemental,
StringRef Message,
unsigned CurrentColumn,
unsigned Columns, bool ShowColors) {
bool Bold = false;
if (ShowColors && !IsSupplemental) {
OS.changeColor(savedColor, true);
Bold = true;
}
if (Columns)
printWordWrapped(OS, Message, Columns, CurrentColumn, Bold);
else {
bool Normal = true;
applyTemplateHighlighting(OS, Message, Normal, Bold);
assert(Normal && "Formatting should have returned to normal");
}
if (ShowColors)
OS.resetColor();
OS << '\n';
}
void TextDiagnostic::emitFilename(StringRef Filename, const SourceManager &SM) {
#ifdef _WIN32
SmallString<4096> TmpFilename;
#endif
if (DiagOpts->AbsolutePath) {
auto File = SM.getFileManager().getFile(Filename);
if (File) {
#ifdef _WIN32
TmpFilename = (*File)->getName();
llvm::sys::fs::make_absolute(TmpFilename);
llvm::sys::path::native(TmpFilename);
llvm::sys::path::remove_dots(TmpFilename, true);
Filename = StringRef(TmpFilename.data(), TmpFilename.size());
#else
Filename = SM.getFileManager().getCanonicalName(*File);
#endif
}
}
OS << Filename;
}
void TextDiagnostic::emitDiagnosticLoc(FullSourceLoc Loc, PresumedLoc PLoc,
DiagnosticsEngine::Level Level,
ArrayRef<CharSourceRange> Ranges) {
if (PLoc.isInvalid()) {
FileID FID = Loc.getFileID();
if (FID.isValid()) {
if (const FileEntry *FE = Loc.getFileEntry()) {
emitFilename(FE->getName(), Loc.getManager());
OS << ": ";
}
}
return;
}
unsigned LineNo = PLoc.getLine();
if (!DiagOpts->ShowLocation)
return;
if (DiagOpts->ShowColors)
OS.changeColor(savedColor, true);
emitFilename(PLoc.getFilename(), Loc.getManager());
switch (DiagOpts->getFormat()) {
case DiagnosticOptions::SARIF:
case DiagnosticOptions::Clang:
if (DiagOpts->ShowLine)
OS << ':' << LineNo;
break;
case DiagnosticOptions::MSVC: OS << '(' << LineNo; break;
case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
}
if (DiagOpts->ShowColumn)
if (unsigned ColNo = PLoc.getColumn()) {
if (DiagOpts->getFormat() == DiagnosticOptions::MSVC) {
OS << ',';
if (LangOpts.MSCompatibilityVersion &&
!LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2012))
ColNo--;
} else
OS << ':';
OS << ColNo;
}
switch (DiagOpts->getFormat()) {
case DiagnosticOptions::SARIF:
case DiagnosticOptions::Clang:
case DiagnosticOptions::Vi: OS << ':'; break;
case DiagnosticOptions::MSVC:
OS << ')';
if (LangOpts.MSCompatibilityVersion &&
!LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2015))
OS << ' ';
OS << ':';
break;
}
if (DiagOpts->ShowSourceRanges && !Ranges.empty()) {
FileID CaretFileID = Loc.getExpansionLoc().getFileID();
bool PrintedRange = false;
for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
RE = Ranges.end();
RI != RE; ++RI) {
if (!RI->isValid()) continue;
auto &SM = Loc.getManager();
SourceLocation B = SM.getExpansionLoc(RI->getBegin());
CharSourceRange ERange = SM.getExpansionRange(RI->getEnd());
SourceLocation E = ERange.getEnd();
bool IsTokenRange = ERange.isTokenRange();
std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
continue;
unsigned TokSize = 0;
if (IsTokenRange)
TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
FullSourceLoc BF(B, SM), EF(E, SM);
OS << '{'
<< BF.getLineNumber() << ':' << BF.getColumnNumber() << '-'
<< EF.getLineNumber() << ':' << (EF.getColumnNumber() + TokSize)
<< '}';
PrintedRange = true;
}
if (PrintedRange)
OS << ':';
}
OS << ' ';
}
void TextDiagnostic::emitIncludeLocation(FullSourceLoc Loc, PresumedLoc PLoc) {
if (DiagOpts->ShowLocation && PLoc.isValid())
OS << "In file included from " << PLoc.getFilename() << ':'
<< PLoc.getLine() << ":\n";
else
OS << "In included file:\n";
}
void TextDiagnostic::emitImportLocation(FullSourceLoc Loc, PresumedLoc PLoc,
StringRef ModuleName) {
if (DiagOpts->ShowLocation && PLoc.isValid())
OS << "In module '" << ModuleName << "' imported from "
<< PLoc.getFilename() << ':' << PLoc.getLine() << ":\n";
else
OS << "In module '" << ModuleName << "':\n";
}
void TextDiagnostic::emitBuildingModuleLocation(FullSourceLoc Loc,
PresumedLoc PLoc,
StringRef ModuleName) {
if (DiagOpts->ShowLocation && PLoc.isValid())
OS << "While building module '" << ModuleName << "' imported from "
<< PLoc.getFilename() << ':' << PLoc.getLine() << ":\n";
else
OS << "While building module '" << ModuleName << "':\n";
}
static llvm::Optional<std::pair<unsigned, unsigned>>
findLinesForRange(const CharSourceRange &R, FileID FID,
const SourceManager &SM) {
if (!R.isValid()) return None;
SourceLocation Begin = R.getBegin();
SourceLocation End = R.getEnd();
if (SM.getFileID(Begin) != FID || SM.getFileID(End) != FID)
return None;
return std::make_pair(SM.getExpansionLineNumber(Begin),
SM.getExpansionLineNumber(End));
}
static std::pair<unsigned, unsigned>
maybeAddRange(std::pair<unsigned, unsigned> A, std::pair<unsigned, unsigned> B,
unsigned MaxRange) {
unsigned Slack = MaxRange - (A.second - A.first + 1);
if (Slack == 0)
return A;
unsigned Min = std::min(A.first, B.first);
unsigned Max = std::max(A.second, B.second);
if (Max - Min + 1 <= MaxRange)
return {Min, Max};
if ((B.first > A.first && B.first - A.first + 1 > MaxRange) ||
(B.second < A.second && A.second - B.second + 1 > MaxRange))
return A;
A.second = std::min(A.second + (Slack + 1) / 2, Max);
Slack = MaxRange - (A.second - A.first + 1);
A.first = std::max(Min + Slack, A.first) - Slack;
A.second = std::min(A.first + MaxRange - 1, Max);
return A;
}
static void highlightRange(const CharSourceRange &R,
unsigned LineNo, FileID FID,
const SourceColumnMap &map,
std::string &CaretLine,
const SourceManager &SM,
const LangOptions &LangOpts) {
if (!R.isValid()) return;
SourceLocation Begin = R.getBegin();
SourceLocation End = R.getEnd();
unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
return;
unsigned EndLineNo = SM.getExpansionLineNumber(End);
if (EndLineNo < LineNo || SM.getFileID(End) != FID)
return;
unsigned StartColNo = 0;
if (StartLineNo == LineNo) {
StartColNo = SM.getExpansionColumnNumber(Begin);
if (StartColNo) --StartColNo; }
unsigned EndColNo = map.getSourceLine().size();
if (EndLineNo == LineNo) {
EndColNo = SM.getExpansionColumnNumber(End);
if (EndColNo) {
--EndColNo;
if (R.isTokenRange())
EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
} else {
EndColNo = CaretLine.size();
}
}
assert(StartColNo <= EndColNo && "Invalid range!");
if (R.isTokenRange()) {
while (StartColNo < map.getSourceLine().size() &&
(map.getSourceLine()[StartColNo] == ' ' ||
map.getSourceLine()[StartColNo] == '\t'))
StartColNo = map.startOfNextColumn(StartColNo);
if (EndColNo > map.getSourceLine().size())
EndColNo = map.getSourceLine().size();
while (EndColNo &&
(map.getSourceLine()[EndColNo-1] == ' ' ||
map.getSourceLine()[EndColNo-1] == '\t'))
EndColNo = map.startOfPreviousColumn(EndColNo);
if (StartColNo > EndColNo) {
assert(StartLineNo != EndLineNo && "trying to highlight whitespace");
StartColNo = EndColNo;
}
}
assert(StartColNo <= map.getSourceLine().size() && "Invalid range!");
assert(EndColNo <= map.getSourceLine().size() && "Invalid range!");
StartColNo = map.byteToContainingColumn(StartColNo);
EndColNo = map.byteToContainingColumn(EndColNo);
assert(StartColNo <= EndColNo && "Invalid range!");
if (CaretLine.size() < EndColNo)
CaretLine.resize(EndColNo,' ');
std::fill(CaretLine.begin()+StartColNo,CaretLine.begin()+EndColNo,'~');
}
static std::string buildFixItInsertionLine(FileID FID,
unsigned LineNo,
const SourceColumnMap &map,
ArrayRef<FixItHint> Hints,
const SourceManager &SM,
const DiagnosticOptions *DiagOpts) {
std::string FixItInsertionLine;
if (Hints.empty() || !DiagOpts->ShowFixits)
return FixItInsertionLine;
unsigned PrevHintEndCol = 0;
for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
I != E; ++I) {
if (!I->CodeToInsert.empty()) {
std::pair<FileID, unsigned> HintLocInfo
= SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
if (FID == HintLocInfo.first &&
LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) &&
StringRef(I->CodeToInsert).find_first_of("\n\r") == StringRef::npos) {
unsigned HintByteOffset
= SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second) - 1;
assert(HintByteOffset < static_cast<unsigned>(map.bytes())+1);
unsigned HintCol = map.byteToContainingColumn(HintByteOffset);
if (HintCol < PrevHintEndCol)
HintCol = PrevHintEndCol + 1;
unsigned NewFixItLineSize = FixItInsertionLine.size() +
(HintCol - PrevHintEndCol) + I->CodeToInsert.size();
if (NewFixItLineSize > FixItInsertionLine.size())
FixItInsertionLine.resize(NewFixItLineSize, ' ');
std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
FixItInsertionLine.end() - I->CodeToInsert.size());
PrevHintEndCol =
HintCol + llvm::sys::locale::columnWidth(I->CodeToInsert);
}
}
}
expandTabs(FixItInsertionLine, DiagOpts->TabStop);
return FixItInsertionLine;
}
void TextDiagnostic::emitSnippetAndCaret(
FullSourceLoc Loc, DiagnosticsEngine::Level Level,
SmallVectorImpl<CharSourceRange> &Ranges, ArrayRef<FixItHint> Hints) {
assert(Loc.isValid() && "must have a valid source location here");
assert(Loc.isFileID() && "must have a file location here");
if (!DiagOpts->ShowCarets)
return;
if (Loc == LastLoc && Ranges.empty() && Hints.empty() &&
(LastLevel != DiagnosticsEngine::Note || Level == LastLevel))
return;
std::pair<FileID, unsigned> LocInfo = Loc.getDecomposedLoc();
FileID FID = LocInfo.first;
const SourceManager &SM = Loc.getManager();
bool Invalid = false;
StringRef BufData = Loc.getBufferData(&Invalid);
if (Invalid)
return;
unsigned CaretLineNo = Loc.getLineNumber();
unsigned CaretColNo = Loc.getColumnNumber();
static const size_t MaxLineLengthToPrint = 4096;
if (CaretColNo > MaxLineLengthToPrint)
return;
const unsigned MaxLines = DiagOpts->SnippetLineLimit;
std::pair<unsigned, unsigned> Lines = {CaretLineNo, CaretLineNo};
for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
E = Ranges.end();
I != E; ++I)
if (auto OptionalRange = findLinesForRange(*I, FID, SM))
Lines = maybeAddRange(Lines, *OptionalRange, MaxLines);
for (unsigned LineNo = Lines.first; LineNo != Lines.second + 1; ++LineNo) {
const char *BufStart = BufData.data();
const char *BufEnd = BufStart + BufData.size();
const char *LineStart =
BufStart +
SM.getDecomposedLoc(SM.translateLineCol(FID, LineNo, 1)).second;
if (LineStart == BufEnd)
break;
const char *LineEnd = LineStart;
while (*LineEnd != '\n' && *LineEnd != '\r' && LineEnd != BufEnd)
++LineEnd;
if (size_t(LineEnd - LineStart) > MaxLineLengthToPrint)
return;
StringRef Line(LineStart, LineEnd - LineStart);
while (!Line.empty() && Line.back() == '\0' &&
(LineNo != CaretLineNo || Line.size() > CaretColNo))
Line = Line.drop_back();
std::string SourceLine(Line.begin(), Line.end());
const SourceColumnMap sourceColMap(SourceLine, DiagOpts->TabStop);
std::string CaretLine(sourceColMap.columns(), ' ');
for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
E = Ranges.end();
I != E; ++I)
highlightRange(*I, LineNo, FID, sourceColMap, CaretLine, SM, LangOpts);
if (CaretLineNo == LineNo) {
CaretColNo = sourceColMap.byteToContainingColumn(CaretColNo - 1);
if (CaretLine.size() < CaretColNo + 1)
CaretLine.resize(CaretColNo + 1, ' ');
CaretLine[CaretColNo] = '^';
}
std::string FixItInsertionLine = buildFixItInsertionLine(
FID, LineNo, sourceColMap, Hints, SM, DiagOpts.get());
unsigned Columns = DiagOpts->MessageLength;
if (Columns)
selectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
Columns, sourceColMap);
if (DiagOpts->ShowSourceRanges) {
SourceLine = ' ' + SourceLine;
CaretLine = ' ' + CaretLine;
}
while (!CaretLine.empty() && CaretLine[CaretLine.size() - 1] == ' ')
CaretLine.erase(CaretLine.end() - 1);
emitSnippet(SourceLine);
if (!CaretLine.empty()) {
if (DiagOpts->ShowColors)
OS.changeColor(caretColor, true);
OS << CaretLine << '\n';
if (DiagOpts->ShowColors)
OS.resetColor();
}
if (!FixItInsertionLine.empty()) {
if (DiagOpts->ShowColors)
OS.changeColor(fixitColor, false);
if (DiagOpts->ShowSourceRanges)
OS << ' ';
OS << FixItInsertionLine << '\n';
if (DiagOpts->ShowColors)
OS.resetColor();
}
}
emitParseableFixits(Hints, SM);
}
void TextDiagnostic::emitSnippet(StringRef line) {
if (line.empty())
return;
size_t i = 0;
std::string to_print;
bool print_reversed = false;
while (i<line.size()) {
std::pair<SmallString<16>,bool> res
= printableTextForNextCharacter(line, &i, DiagOpts->TabStop);
bool was_printable = res.second;
if (DiagOpts->ShowColors && was_printable == print_reversed) {
if (print_reversed)
OS.reverseColor();
OS << to_print;
to_print.clear();
if (DiagOpts->ShowColors)
OS.resetColor();
}
print_reversed = !was_printable;
to_print += res.first.str();
}
if (print_reversed && DiagOpts->ShowColors)
OS.reverseColor();
OS << to_print;
if (print_reversed && DiagOpts->ShowColors)
OS.resetColor();
OS << '\n';
}
void TextDiagnostic::emitParseableFixits(ArrayRef<FixItHint> Hints,
const SourceManager &SM) {
if (!DiagOpts->ShowParseableFixits)
return;
for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
I != E; ++I) {
if (I->RemoveRange.isInvalid() ||
I->RemoveRange.getBegin().isMacroID() ||
I->RemoveRange.getEnd().isMacroID())
return;
}
for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
I != E; ++I) {
SourceLocation BLoc = I->RemoveRange.getBegin();
SourceLocation ELoc = I->RemoveRange.getEnd();
std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
if (I->RemoveRange.isTokenRange())
EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
if (PLoc.isInvalid())
break;
OS << "fix-it:\"";
OS.write_escaped(PLoc.getFilename());
OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
<< ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
<< '-' << SM.getLineNumber(EInfo.first, EInfo.second)
<< ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
<< "}:\"";
OS.write_escaped(I->CodeToInsert);
OS << "\"\n";
}
}