diagnostic_emitter_test.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. struct Substitutions {
  19. std::string message;
  20. };
  21. static auto Format(const Substitutions& substitutions) -> std::string {
  22. // Work around a bug in Clang's unused const variable warning by marking it
  23. // used here with a no-op.
  24. static_cast<void>(ShortName);
  25. return llvm::formatv(Message.data(), substitutions.message).str();
  26. }
  27. };
  28. TEST(DiagTest, EmitErrors) {
  29. std::vector<std::string> reported;
  30. DiagnosticEmitter emitter([&](const Diagnostic& diagnostic) {
  31. EXPECT_THAT(diagnostic.short_name, Eq("fake-diagnostic"));
  32. reported.push_back(diagnostic.message);
  33. });
  34. emitter.EmitError<FakeDiagnostic>({.message = "M1"});
  35. emitter.EmitError<FakeDiagnostic>({.message = "M2"});
  36. EXPECT_THAT(reported, ElementsAre("M1", "M2"));
  37. }
  38. TEST(DiagTest, EmitWarnings) {
  39. std::vector<std::string> reported;
  40. DiagnosticEmitter emitter([&](const Diagnostic& diagnostic) {
  41. EXPECT_THAT(diagnostic.short_name, Eq("fake-diagnostic"));
  42. reported.push_back(diagnostic.message);
  43. });
  44. emitter.EmitWarningIf<FakeDiagnostic>(
  45. [](FakeDiagnostic::Substitutions& diagnostic) {
  46. diagnostic.message = "M1";
  47. return true;
  48. });
  49. emitter.EmitWarningIf<FakeDiagnostic>(
  50. [](FakeDiagnostic::Substitutions& diagnostic) {
  51. diagnostic.message = "M2";
  52. return false;
  53. });
  54. emitter.EmitWarningIf<FakeDiagnostic>(
  55. [](FakeDiagnostic::Substitutions& diagnostic) {
  56. diagnostic.message = "M3";
  57. return true;
  58. });
  59. EXPECT_THAT(reported, ElementsAre("M1", "M3"));
  60. }
  61. } // namespace
  62. } // namespace Carbon