diagnostic_emitter_test.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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>(
  35. [](FakeDiagnostic::Substitutions& diagnostic) {
  36. diagnostic.message = "M1";
  37. });
  38. emitter.EmitError<FakeDiagnostic>(
  39. [](FakeDiagnostic::Substitutions& diagnostic) {
  40. diagnostic.message = "M2";
  41. });
  42. EXPECT_THAT(reported, ElementsAre("M1", "M2"));
  43. }
  44. TEST(DiagTest, EmitWarnings) {
  45. std::vector<std::string> reported;
  46. DiagnosticEmitter emitter([&](const Diagnostic& diagnostic) {
  47. EXPECT_THAT(diagnostic.short_name, Eq("fake-diagnostic"));
  48. reported.push_back(diagnostic.message);
  49. });
  50. emitter.EmitWarningIf<FakeDiagnostic>(
  51. [](FakeDiagnostic::Substitutions& diagnostic) {
  52. diagnostic.message = "M1";
  53. return true;
  54. });
  55. emitter.EmitWarningIf<FakeDiagnostic>(
  56. [](FakeDiagnostic::Substitutions& diagnostic) {
  57. diagnostic.message = "M2";
  58. return false;
  59. });
  60. emitter.EmitWarningIf<FakeDiagnostic>(
  61. [](FakeDiagnostic::Substitutions& diagnostic) {
  62. diagnostic.message = "M3";
  63. return true;
  64. });
  65. EXPECT_THAT(reported, ElementsAre("M1", "M3"));
  66. }
  67. } // namespace
  68. } // namespace Carbon