#include "clang/Frontend/TextDiagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/Support/SmallVectorMemoryBuffer.h"
#include "gtest/gtest.h"
using namespace llvm;
using namespace clang;
namespace {
static std::string PrintDiag(const DiagnosticOptions &Opts, FullSourceLoc Loc) {
std::string Out;
llvm::raw_string_ostream OS(Out);
clang::LangOptions LangOpts;
DiagnosticOptions *DiagOpts = new DiagnosticOptions(Opts);
TextDiagnostic Diag(OS, LangOpts, DiagOpts);
Diag.emitDiagnostic(Loc, DiagnosticsEngine::Level::Warning, "message",
{}, {});
OS.flush();
return Out;
}
TEST(TextDiagnostic, ShowLine) {
FileSystemOptions FSOpts;
FileManager FileMgr(FSOpts);
IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs);
DiagnosticsEngine DiagEngine(DiagID, new DiagnosticOptions,
new IgnoringDiagConsumer());
SourceManager SrcMgr(DiagEngine, FileMgr);
const llvm::StringRef file_path = "main.cpp";
const llvm::StringRef main_file_contents = "some\nsource\ncode\n";
const clang::FileEntryRef fe = FileMgr.getVirtualFileRef(
file_path,
static_cast<off_t>(main_file_contents.size()),
0);
llvm::SmallVector<char, 64> buffer;
buffer.append(main_file_contents.begin(), main_file_contents.end());
auto file_contents = std::make_unique<llvm::SmallVectorMemoryBuffer>(
std::move(buffer), file_path, false);
SrcMgr.overrideFileContents(fe, std::move(file_contents));
clang::FileID fid =
SrcMgr.createFileID(fe, SourceLocation(), clang::SrcMgr::C_User);
SrcMgr.setMainFileID(fid);
FullSourceLoc Loc(SrcMgr.translateLineCol(fid, 1, 2),
SrcMgr);
DiagnosticOptions DiagOpts;
DiagOpts.ShowLine = true;
DiagOpts.ShowColumn = true;
DiagOpts.ShowCarets = false;
EXPECT_EQ("main.cpp:1:2: warning: message\n", PrintDiag(DiagOpts, Loc));
DiagOpts.setFormat(TextDiagnosticFormat::Vi);
DiagOpts.ShowLine = false;
EXPECT_EQ("main.cpp +1:2: warning: message\n", PrintDiag(DiagOpts, Loc));
DiagOpts.setFormat(TextDiagnosticFormat::MSVC);
DiagOpts.ShowLine = false;
EXPECT_EQ("main.cpp(1,2): warning: message\n", PrintDiag(DiagOpts, Loc));
DiagOpts.setFormat(TextDiagnosticFormat::Clang);
DiagOpts.ShowLine = false;
EXPECT_EQ("main.cpp:2: warning: message\n", PrintDiag(DiagOpts, Loc));
DiagOpts.ShowLine = true;
DiagOpts.ShowColumn = false;
EXPECT_EQ("main.cpp:1: warning: message\n", PrintDiag(DiagOpts, Loc));
}
}