diagnostic_emitter_test.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "diagnostics/diagnostic_emitter.h"
  5. #include "gmock/gmock.h"
  6. #include "gtest/gtest.h"
  7. #include "llvm/ADT/StringRef.h"
  8. #include "llvm/Support/FormatVariadic.h"
  9. namespace Carbon {
  10. namespace {
  11. using ::testing::ElementsAre;
  12. using ::testing::Eq;
  13. struct FakeDiagnostic {
  14. static constexpr llvm::StringLiteral ShortName = "fake-diagnostic";
  15. // TODO: consider ways to put the Message into `format` to allow dynamic
  16. // selection of the message.
  17. static constexpr llvm::StringLiteral Message = "{0}";
  18. std::string message;
  19. auto Format() -> std::string {
  20. // Work around a bug in Clang's unused const variable warning by marking it
  21. // used here with a no-op.
  22. static_cast<void>(ShortName);
  23. return llvm::formatv(Message.data(), message).str();
  24. }
  25. };
  26. TEST(DiagTest, EmitErrors) {
  27. std::vector<std::string> reported;
  28. DiagnosticEmitter emitter([&](const Diagnostic& diagnostic) {
  29. EXPECT_THAT(diagnostic.short_name, Eq("fake-diagnostic"));
  30. reported.push_back(diagnostic.message);
  31. });
  32. emitter.EmitError<FakeDiagnostic>({.message = "M1"});
  33. emitter.EmitError<FakeDiagnostic>({.message = "M2"});
  34. EXPECT_THAT(reported, ElementsAre("M1", "M2"));
  35. }
  36. TEST(DiagTest, EmitWarnings) {
  37. std::vector<std::string> reported;
  38. DiagnosticEmitter emitter([&](const Diagnostic& diagnostic) {
  39. EXPECT_THAT(diagnostic.short_name, Eq("fake-diagnostic"));
  40. reported.push_back(diagnostic.message);
  41. });
  42. emitter.EmitWarningIf<FakeDiagnostic>([](FakeDiagnostic& diagnostic) {
  43. diagnostic.message = "M1";
  44. return true;
  45. });
  46. emitter.EmitWarningIf<FakeDiagnostic>([](FakeDiagnostic& diagnostic) {
  47. diagnostic.message = "M2";
  48. return false;
  49. });
  50. emitter.EmitWarningIf<FakeDiagnostic>([](FakeDiagnostic& diagnostic) {
  51. diagnostic.message = "M3";
  52. return true;
  53. });
  54. EXPECT_THAT(reported, ElementsAre("M1", "M3"));
  55. }
  56. } // namespace
  57. } // namespace Carbon