VerifyDiagnosticConsumer.cpp [plain text]
#include "clang/Frontend/VerifyDiagnosticConsumer.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/TextDiagnosticBuffer.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/Regex.h"
#include "llvm/Support/raw_ostream.h"
#include <climits>
using namespace clang;
VerifyDiagnosticConsumer::VerifyDiagnosticConsumer(DiagnosticsEngine &_Diags)
: Diags(_Diags), PrimaryClient(Diags.getClient()),
OwnsPrimaryClient(Diags.ownsClient()),
Buffer(new TextDiagnosticBuffer()), CurrentPreprocessor(0)
{
Diags.takeClient();
}
VerifyDiagnosticConsumer::~VerifyDiagnosticConsumer() {
CheckDiagnostics();
Diags.takeClient();
if (OwnsPrimaryClient)
delete PrimaryClient;
}
void VerifyDiagnosticConsumer::BeginSourceFile(const LangOptions &LangOpts,
const Preprocessor *PP) {
CurrentPreprocessor = const_cast<Preprocessor*>(PP);
PrimaryClient->BeginSourceFile(LangOpts, PP);
}
void VerifyDiagnosticConsumer::EndSourceFile() {
CheckDiagnostics();
PrimaryClient->EndSourceFile();
CurrentPreprocessor = 0;
}
void VerifyDiagnosticConsumer::HandleDiagnostic(
DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) {
if (FirstErrorFID.isInvalid() && Info.hasSourceManager()) {
const SourceManager &SM = Info.getSourceManager();
FirstErrorFID = SM.getFileID(Info.getLocation());
}
Buffer->HandleDiagnostic(DiagLevel, Info);
}
typedef TextDiagnosticBuffer::DiagList DiagList;
typedef TextDiagnosticBuffer::const_iterator const_diag_iterator;
namespace {
class Directive {
public:
static Directive* Create(bool RegexKind, const SourceLocation &Location,
const std::string &Text, unsigned Count);
public:
static const unsigned OneOrMoreCount = UINT_MAX;
SourceLocation Location;
const std::string Text;
unsigned Count;
virtual ~Directive() { }
virtual bool isValid(std::string &Error) = 0;
virtual bool Match(const std::string &S) = 0;
protected:
Directive(const SourceLocation &Location, const std::string &Text,
unsigned Count)
: Location(Location), Text(Text), Count(Count) { }
private:
Directive(const Directive&); void operator=(const Directive&); };
class StandardDirective : public Directive {
public:
StandardDirective(const SourceLocation &Location, const std::string &Text,
unsigned Count)
: Directive(Location, Text, Count) { }
virtual bool isValid(std::string &Error) {
return true;
}
virtual bool Match(const std::string &S) {
return S.find(Text) != std::string::npos;
}
};
class RegexDirective : public Directive {
public:
RegexDirective(const SourceLocation &Location, const std::string &Text,
unsigned Count)
: Directive(Location, Text, Count), Regex(Text) { }
virtual bool isValid(std::string &Error) {
if (Regex.isValid(Error))
return true;
return false;
}
virtual bool Match(const std::string &S) {
return Regex.match(S);
}
private:
llvm::Regex Regex;
};
typedef std::vector<Directive*> DirectiveList;
struct ExpectedData {
DirectiveList Errors;
DirectiveList Warnings;
DirectiveList Notes;
~ExpectedData() {
DirectiveList* Lists[] = { &Errors, &Warnings, &Notes, 0 };
for (DirectiveList **PL = Lists; *PL; ++PL) {
DirectiveList * const L = *PL;
for (DirectiveList::iterator I = L->begin(), E = L->end(); I != E; ++I)
delete *I;
}
}
};
class ParseHelper
{
public:
ParseHelper(const char *Begin, const char *End)
: Begin(Begin), End(End), C(Begin), P(Begin), PEnd(NULL) { }
bool Next(StringRef S) {
P = C;
PEnd = C + S.size();
if (PEnd > End)
return false;
return !memcmp(P, S.data(), S.size());
}
bool Next(unsigned &N) {
unsigned TMP = 0;
P = C;
for (; P < End && P[0] >= '0' && P[0] <= '9'; ++P) {
TMP *= 10;
TMP += P[0] - '0';
}
if (P == C)
return false;
PEnd = P;
N = TMP;
return true;
}
bool Search(StringRef S) {
P = std::search(C, End, S.begin(), S.end());
PEnd = P + S.size();
return P != End;
}
bool Advance() {
C = PEnd;
return C < End;
}
void SkipWhitespace() {
for (; C < End && isspace(*C); ++C)
;
}
bool Done() {
return !(C < End);
}
const char * const Begin; const char * const End; const char *C; const char *P;
private:
const char *PEnd; };
}
static void ParseDirective(const char *CommentStart, unsigned CommentLen,
ExpectedData &ED, Preprocessor &PP,
SourceLocation Pos) {
for (ParseHelper PH(CommentStart, CommentStart+CommentLen); !PH.Done();) {
if (!PH.Search("expected"))
break;
PH.Advance();
if (!PH.Next("-"))
continue;
PH.Advance();
DirectiveList* DL = NULL;
if (PH.Next("error"))
DL = &ED.Errors;
else if (PH.Next("warning"))
DL = &ED.Warnings;
else if (PH.Next("note"))
DL = &ED.Notes;
else
continue;
PH.Advance();
bool RegexKind = false;
const char* KindStr = "string";
if (PH.Next("-re")) {
PH.Advance();
RegexKind = true;
KindStr = "regex";
}
PH.SkipWhitespace();
unsigned Count = 1;
if (PH.Next(Count))
PH.Advance();
else if (PH.Next("+")) {
Count = Directive::OneOrMoreCount;
PH.Advance();
}
PH.SkipWhitespace();
if (!PH.Next("{{")) {
PP.Diag(Pos.getLocWithOffset(PH.C-PH.Begin),
diag::err_verify_missing_start) << KindStr;
continue;
}
PH.Advance();
const char* const ContentBegin = PH.C;
if (!PH.Search("}}")) {
PP.Diag(Pos.getLocWithOffset(PH.C-PH.Begin),
diag::err_verify_missing_end) << KindStr;
continue;
}
const char* const ContentEnd = PH.P; PH.Advance();
std::string Text;
StringRef NewlineStr = "\\n";
StringRef Content(ContentBegin, ContentEnd-ContentBegin);
size_t CPos = 0;
size_t FPos;
while ((FPos = Content.find(NewlineStr, CPos)) != StringRef::npos) {
Text += Content.substr(CPos, FPos-CPos);
Text += '\n';
CPos = FPos + NewlineStr.size();
}
if (Text.empty())
Text.assign(ContentBegin, ContentEnd);
Directive *D = Directive::Create(RegexKind, Pos, Text, Count);
std::string Error;
if (D->isValid(Error))
DL->push_back(D);
else {
PP.Diag(Pos.getLocWithOffset(ContentBegin-PH.Begin),
diag::err_verify_invalid_content)
<< KindStr << Error;
}
}
}
static void FindExpectedDiags(Preprocessor &PP, ExpectedData &ED, FileID FID) {
if (FID.isInvalid())
return;
SourceManager& SM = PP.getSourceManager();
const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID);
Lexer RawLex(FID, FromFile, SM, PP.getLangOptions());
RawLex.SetCommentRetentionState(true);
Token Tok;
Tok.setKind(tok::comment);
while (Tok.isNot(tok::eof)) {
RawLex.Lex(Tok);
if (!Tok.is(tok::comment)) continue;
std::string Comment = PP.getSpelling(Tok);
if (Comment.empty()) continue;
ParseDirective(&Comment[0], Comment.size(), ED, PP, Tok.getLocation());
};
}
static unsigned PrintProblem(DiagnosticsEngine &Diags, SourceManager *SourceMgr,
const_diag_iterator diag_begin,
const_diag_iterator diag_end,
const char *Kind, bool Expected) {
if (diag_begin == diag_end) return 0;
SmallString<256> Fmt;
llvm::raw_svector_ostream OS(Fmt);
for (const_diag_iterator I = diag_begin, E = diag_end; I != E; ++I) {
if (I->first.isInvalid() || !SourceMgr)
OS << "\n (frontend)";
else
OS << "\n Line " << SourceMgr->getPresumedLineNumber(I->first);
OS << ": " << I->second;
}
Diags.Report(diag::err_verify_inconsistent_diags)
<< Kind << !Expected << OS.str();
return std::distance(diag_begin, diag_end);
}
static unsigned PrintProblem(DiagnosticsEngine &Diags, SourceManager *SourceMgr,
DirectiveList &DL, const char *Kind,
bool Expected) {
if (DL.empty())
return 0;
SmallString<256> Fmt;
llvm::raw_svector_ostream OS(Fmt);
for (DirectiveList::iterator I = DL.begin(), E = DL.end(); I != E; ++I) {
Directive& D = **I;
if (D.Location.isInvalid() || !SourceMgr)
OS << "\n (frontend)";
else
OS << "\n Line " << SourceMgr->getPresumedLineNumber(D.Location);
OS << ": " << D.Text;
}
Diags.Report(diag::err_verify_inconsistent_diags)
<< Kind << !Expected << OS.str();
return DL.size();
}
static unsigned CheckLists(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
const char *Label,
DirectiveList &Left,
const_diag_iterator d2_begin,
const_diag_iterator d2_end) {
DirectiveList LeftOnly;
DiagList Right(d2_begin, d2_end);
for (DirectiveList::iterator I = Left.begin(), E = Left.end(); I != E; ++I) {
Directive& D = **I;
unsigned LineNo1 = SourceMgr.getPresumedLineNumber(D.Location);
bool FoundOnce = false;
for (unsigned i = 0; i < D.Count; ++i) {
DiagList::iterator II, IE;
for (II = Right.begin(), IE = Right.end(); II != IE; ++II) {
unsigned LineNo2 = SourceMgr.getPresumedLineNumber(II->first);
if (LineNo1 != LineNo2)
continue;
const std::string &RightText = II->second;
if (D.Match(RightText))
break;
}
if (II == IE) {
if (D.Count == D.OneOrMoreCount) {
if (!FoundOnce)
LeftOnly.push_back(*I);
break;
}
LeftOnly.push_back(*I);
} else {
Right.erase(II);
FoundOnce = true;
}
}
}
unsigned num = PrintProblem(Diags, &SourceMgr, LeftOnly, Label, true);
num += PrintProblem(Diags, &SourceMgr, Right.begin(), Right.end(),
Label, false);
return num;
}
static unsigned CheckResults(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
const TextDiagnosticBuffer &Buffer,
ExpectedData &ED) {
unsigned NumProblems = 0;
NumProblems += CheckLists(Diags, SourceMgr, "error", ED.Errors,
Buffer.err_begin(), Buffer.err_end());
NumProblems += CheckLists(Diags, SourceMgr, "warning", ED.Warnings,
Buffer.warn_begin(), Buffer.warn_end());
NumProblems += CheckLists(Diags, SourceMgr, "note", ED.Notes,
Buffer.note_begin(), Buffer.note_end());
return NumProblems;
}
void VerifyDiagnosticConsumer::CheckDiagnostics() {
ExpectedData ED;
bool OwnsCurClient = Diags.ownsClient();
DiagnosticConsumer *CurClient = Diags.takeClient();
Diags.setClient(PrimaryClient, false);
if (CurrentPreprocessor) {
SourceManager &SM = CurrentPreprocessor->getSourceManager();
FindExpectedDiags(*CurrentPreprocessor, ED, SM.getMainFileID());
if (!FirstErrorFID.isInvalid() && FirstErrorFID != SM.getMainFileID()
&& (!SM.getFileEntryForID(FirstErrorFID)
|| (SM.getFileEntryForID(FirstErrorFID) !=
SM.getFileEntryForID(SM.getMainFileID())))) {
FindExpectedDiags(*CurrentPreprocessor, ED, FirstErrorFID);
FirstErrorFID = FileID();
}
NumErrors += CheckResults(Diags, SM, *Buffer, ED);
} else {
NumErrors += (PrintProblem(Diags, 0,
Buffer->err_begin(), Buffer->err_end(),
"error", false) +
PrintProblem(Diags, 0,
Buffer->warn_begin(), Buffer->warn_end(),
"warn", false) +
PrintProblem(Diags, 0,
Buffer->note_begin(), Buffer->note_end(),
"note", false));
}
Diags.takeClient();
Diags.setClient(CurClient, OwnsCurClient);
Buffer.reset(new TextDiagnosticBuffer());
}
DiagnosticConsumer *
VerifyDiagnosticConsumer::clone(DiagnosticsEngine &Diags) const {
if (!Diags.getClient())
Diags.setClient(PrimaryClient->clone(Diags));
return new VerifyDiagnosticConsumer(Diags);
}
Directive* Directive::Create(bool RegexKind, const SourceLocation &Location,
const std::string &Text, unsigned Count) {
if (RegexKind)
return new RegexDirective(Location, Text, Count);
return new StandardDirective(Location, Text, Count);
}