diagnostic_emitter_test.cpp 2.4 KB

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