consumer.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 "toolchain/diagnostics/consumer.h"
  5. #include <algorithm>
  6. #include <cstdint>
  7. namespace Carbon::Diagnostics {
  8. auto StreamConsumer::HandleDiagnostic(Diagnostic diagnostic) -> void {
  9. if (printed_diagnostic_) {
  10. *stream_ << "\n";
  11. } else {
  12. printed_diagnostic_ = true;
  13. }
  14. auto message_level = [&, first = true](const Message& m) mutable {
  15. if (m.level >= Level::SoftContext && std::exchange(first, false)) {
  16. return diagnostic.level;
  17. }
  18. return std::min(Level::Note, m.level);
  19. };
  20. for (const auto& message : diagnostic.messages) {
  21. message.loc.FormatLocation(*stream_);
  22. switch (message_level(message)) {
  23. case Level::Error:
  24. *stream_ << "error: ";
  25. break;
  26. case Level::Warning:
  27. *stream_ << "warning: ";
  28. break;
  29. case Level::Note:
  30. *stream_ << "note: ";
  31. break;
  32. case Level::LocationInfo:
  33. break;
  34. case Level::SoftContext:
  35. case Level::Context:
  36. CARBON_FATAL("Context messages are presented as a different level");
  37. }
  38. *stream_ << message.Format();
  39. if (include_diagnostic_kind_) {
  40. *stream_ << " [" << message.kind << "]";
  41. }
  42. *stream_ << "\n";
  43. // Don't include a snippet for location information to keep this diagnostic
  44. // more visually associated with the following diagnostic that it describes
  45. // and to better match C++ compilers.
  46. if (message.level != Level::LocationInfo) {
  47. message.loc.FormatSnippet(*stream_);
  48. }
  49. }
  50. }
  51. auto ConsoleConsumer() -> Consumer& {
  52. static auto* consumer = new StreamConsumer(&llvm::errs());
  53. return *consumer;
  54. }
  55. } // namespace Carbon::Diagnostics