diagnostic_consumer.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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/diagnostic_consumer.h"
  5. #include <algorithm>
  6. #include <cstdint>
  7. namespace Carbon {
  8. auto StreamDiagnosticConsumer::HandleDiagnostic(Diagnostic diagnostic) -> void {
  9. if (printed_diagnostic_) {
  10. *stream_ << "\n";
  11. } else {
  12. printed_diagnostic_ = true;
  13. }
  14. for (const auto& message : diagnostic.messages) {
  15. *stream_ << message.location.filename;
  16. if (message.location.line_number > 0) {
  17. *stream_ << ":" << message.location.line_number;
  18. if (message.location.column_number > 0) {
  19. *stream_ << ":" << message.location.column_number;
  20. }
  21. }
  22. *stream_ << ": ";
  23. if (message.level == DiagnosticLevel::Error) {
  24. *stream_ << "ERROR: ";
  25. }
  26. *stream_ << message.format_fn(message) << "\n";
  27. if (message.location.column_number > 0) {
  28. *stream_ << message.location.line << "\n";
  29. stream_->indent(message.location.column_number - 1);
  30. *stream_ << "^";
  31. int underline_length = std::max(0, message.location.length - 1);
  32. // We want to ensure that we don't underline past the end of the line in
  33. // case of a multiline token.
  34. // TODO: revisit this once we can reference multiple ranges on multiple
  35. // lines in a single diagnostic message.
  36. underline_length = std::min(
  37. underline_length, static_cast<int32_t>(message.location.line.size()) -
  38. message.location.column_number);
  39. for (int i = 0; i < underline_length; ++i) {
  40. *stream_ << "~";
  41. }
  42. *stream_ << "\n";
  43. }
  44. }
  45. }
  46. auto ConsoleDiagnosticConsumer() -> DiagnosticConsumer& {
  47. static auto* consumer = new StreamDiagnosticConsumer(llvm::errs());
  48. return *consumer;
  49. }
  50. } // namespace Carbon