#include "clang/Frontend/SARIFDiagnosticPrinter.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/Sarif.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/DiagnosticRenderer.h"
#include "clang/Frontend/SARIFDiagnostic.h"
#include "clang/Lex/Lexer.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/JSON.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
namespace clang {
SARIFDiagnosticPrinter::SARIFDiagnosticPrinter(raw_ostream &OS,
DiagnosticOptions *Diags)
: OS(OS), DiagOpts(Diags) {}
void SARIFDiagnosticPrinter::BeginSourceFile(const LangOptions &LO,
const Preprocessor *PP) {
assert(hasSarifWriter() && "Writer not set!");
assert(!SARIFDiag && "SARIFDiagnostic already set.");
SARIFDiag = std::make_unique<SARIFDiagnostic>(OS, LO, &*DiagOpts, &*Writer);
Writer->createRun("clang", Prefix);
}
void SARIFDiagnosticPrinter::EndSourceFile() {
assert(SARIFDiag && "SARIFDiagnostic has not been set.");
Writer->endRun();
llvm::json::Value Value(Writer->createDocument());
OS << "\n" << Value << "\n\n";
OS.flush();
SARIFDiag.reset();
}
void SARIFDiagnosticPrinter::HandleDiagnostic(DiagnosticsEngine::Level Level,
const Diagnostic &Info) {
assert(SARIFDiag && "SARIFDiagnostic has not been set.");
DiagnosticConsumer::HandleDiagnostic(Level, Info);
SmallString<100> OutStr;
Info.FormatDiagnostic(OutStr);
llvm::raw_svector_ostream DiagMessageStream(OutStr);
if (Info.getLocation().isInvalid()) {
return;
}
assert(DiagOpts && "Unexpected diagnostic without options set");
assert(Info.hasSourceManager() &&
"Unexpected diagnostic with no source manager");
SARIFDiag->emitDiagnostic(
FullSourceLoc(Info.getLocation(), Info.getSourceManager()), Level,
DiagMessageStream.str(), Info.getRanges(), Info.getFixItHints(), &Info);
}
}