Files
carbon-lang/toolchain/diagnostics/diagnostic_consumer.cpp
T
Jon Ross-Perkins 8907948242 Refactor diagnostic_emitter.h into multiple files. (#3800)
This is to make it easier to locate various diagnostic types. I was
thinking to separately rename DiagnosticLocationTranslator to
DiagnosticTranslator, because it's now handling some type translations.

This is mostly keeping classes in one place, but FormatFn handling is
moved from DiagnosticMessage to DiagnosticEmitter for a cleaner
dependency graph where DiagnosticTypeForArg is concerned.
2024-03-21 17:02:55 +00:00

58 lines
1.9 KiB
C++

// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "toolchain/diagnostics/diagnostic_consumer.h"
#include <algorithm>
#include <cstdint>
namespace Carbon {
auto StreamDiagnosticConsumer::HandleDiagnostic(Diagnostic diagnostic) -> void {
std::string prefix;
if (diagnostic.level == DiagnosticLevel::Error) {
prefix = "ERROR: ";
}
Print(diagnostic.message, prefix);
for (const auto& note : diagnostic.notes) {
Print(note, "");
}
}
auto StreamDiagnosticConsumer::Print(const DiagnosticMessage& message,
llvm::StringRef prefix) -> void {
*stream_ << message.location.filename;
if (message.location.line_number > 0) {
*stream_ << ":" << message.location.line_number;
if (message.location.column_number > 0) {
*stream_ << ":" << message.location.column_number;
}
}
*stream_ << ": " << prefix << message.format_fn(message) << "\n";
if (message.location.column_number > 0) {
*stream_ << message.location.line << "\n";
stream_->indent(message.location.column_number - 1);
*stream_ << "^";
int underline_length = std::max(0, message.location.length - 1);
// We want to ensure that we don't underline past the end of the line in
// case of a multiline token.
// TODO: revisit this once we can reference multiple ranges on multiple
// lines in a single diagnostic message.
underline_length = std::min(
underline_length, static_cast<int32_t>(message.location.line.size()) -
message.location.column_number);
for (int i = 0; i < underline_length; ++i) {
*stream_ << "~";
}
*stream_ << "\n";
}
}
auto ConsoleDiagnosticConsumer() -> DiagnosticConsumer& {
static auto* consumer = new StreamDiagnosticConsumer(llvm::errs());
return *consumer;
}
} // namespace Carbon