Files
carbon-lang/toolchain/diagnostics/renderer.h
T
Chandler Carruth 0072b28129 Start every diagnostic with a single message attached to the code (#8102)
This is the final step in landing the _structural_ updates to diagnostic
rendering.

The key idea here is that we want the primary diagnostic to have a
message clearly explaining the problem and attached to the code that has
that problem. This should be the starting point for readers working to
address the issue, but is rendered attached to the code snippet in
question so errors are always "in context" of the code with the error.
Everything else in a diagnostic is an additional label attached to code
to explain or help the reader understand the problem in the primary
message.

Previously, `ContextScope` resulted in some confusion here, as
diagnostic consumers turned messages into labels and made the message in
the context scope the message. In essence, this isn't a scope with
context _for_ a diagnostic (with two exceptions that should probably
have been an `AnnotationScope`), but a context within `check` where we
have a preferred message for a diagnostic emitted by general purpose
code we call into. For example, "class was forward declared here" starts
as an error, and then consumers render it as a label to make the message
from the context scope the error. We also grew an `AnnotationScope` to
handle the contextual information we want to show for a diagnostic (what
I would have assumed `ContextScope` actually did).

Now we have a `Diagnoser`: code in `check` that can better explain the
problem than shared logic it is calling into passes a callback that
builds a caller-specific diagnostic. The callee then can attach relevant
labels and emit it. Diagnostics no longer store `contexts` and consumers
no longer need the logic to restructure things. We move all (but two) of
the old contexts to be normal messages emitted in this way, and we move
some diagnostics to become labels. Each of the new normal messages
corresponds to a new diagnostic kind as usual. Common code following
this pattern now _requires_ the `Diagnoser` to be passed (or emit
nothing), and this uncovered three places where an empty context was
used that made the rendered form miss key information. All three are
fixed with new diagnostics, one already covered by tests, and two with
TODOs to add test coverage.

We also completely remove the old `ContextScope` and
`CARBON_DIAGNOSTIC_CONTEXT` and rename `AnnotationScope` to
`ContextScope`. It is only used to attach information about when/where a
diagnostic occurred.

Labels also no longer have categories. What were `Primary` are now
`ExtraRange`s on the diagnostic rather than labels. Labels are now
always informational.

`DeclaredName` now narrows the range of a label when the range is a
declaration of a named entity to only be the range of that name. For
entities that don't have a declared name, the entire declaration remains
the range. The code building and emitting these diagnostics can skip
them if the declared location isn't distinct from the diagnostic
location.

Wording is largely unchanged here so we can just review the _structural_
change. #7991 iterates using this to improve locations and adds missing
labels. A subsequent PR will iterate on the wording to increasingly fit
within this structural model.

This is separated out as a way to review incrementally, and so that
subsequently we don't have to review wording improvements that only make
sense in a new structure that you cannot see yet. It seems easier to
look at the structure here even with awkward wording.

Assisted-by: Claude Code
2026-11-22 05:19:35 +00:00

139 lines
5.8 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
#ifndef CARBON_TOOLCHAIN_DIAGNOSTICS_RENDERER_H_
#define CARBON_TOOLCHAIN_DIAGNOSTICS_RENDERER_H_
#include <cstdint>
#include <string>
#include "common/ostream.h"
#include "common/terminal/capabilities.h"
#include "common/terminal/output_buffer_ref.h"
#include "llvm/ADT/ArrayRef.h"
#include "toolchain/diagnostics/diagnostic.h"
namespace Carbon::Diagnostics {
namespace Internal {
struct PreparedPart;
} // namespace Internal
// Which line numbers the framed form shows.
enum class LineNumbers : int8_t {
// Every line of source is numbered, and every location has its line and
// column.
All,
// Only the first location row that has a location keeps its line and
// column. The gutter has no numbers, and every other location shows only its
// file name.
First,
};
// Draws diagnostics for a terminal.
//
// A diagnostic renders as one frame holding a snippet of each file it points
// into. The message's text is placed under the range that is wrong and begins
// with the level word. Every label is placed under the range it is attached to.
// The message's ranges are underlined heavy and a label's light.
//
// ╭─┤ foo.carbon:19:3
// 1 │ fn Run0() {}
// · ──────┬─────
// · ╰──┤ calling function declared here
// ┆
// -> 19 │ Run0(1);
// · ━━━┳━━━
// · ┗━━┫ error: invalid arguments in function call
// ╰────
//
// With snippets off, each part of the diagnostic is one line, led by its
// location and the extent of its range:
//
// foo.carbon:19:3-9: error: invalid arguments in function call
// foo.carbon:1:1-12: note: calling function declared here
//
// See /toolchain/docs/diagnostics_rendering.md for the full form, the palette,
// and why it looks like this rather than like something else.
//
// The rendering is decided entirely by the capabilities passed in, so the same
// diagnostic renders the same way every time for a given terminal, and the
// default capabilities render plain ASCII. What a stream's capabilities
// actually are is `Terminal::Capabilities::Detect`'s to answer: notably it
// takes the character set from the locale whether or not a terminal is
// attached, since the locale is what says how bytes will be decoded.
class Renderer {
public:
// Renders for a terminal with `capabilities`. The default describes a stream
// with no terminal behind it: no color, no line drawing, and no width.
// Layout still fits one -- the width code is formatted to, plus the gutter
// -- so the rendering is decided by the diagnostic rather than by the
// environment the stream ends up in.
explicit Renderer(const Terminal::Capabilities& capabilities = {})
: capabilities_(capabilities) {}
// Renders `diagnostic`, appending the bytes that draw it to `out`. Each row
// ends in a newline, and no style is left set at the end.
auto Render(Terminal::OutputBufferRef out, const Diagnostic& diagnostic) const
-> void;
// Sets whether each message names the diagnostic kind that produced it. This
// is for tests, which match against the kind to prove they cover it.
auto set_include_kind(bool value) -> void { include_kind_ = value; }
// Sets whether diagnostics show snippets of the source they point at. With
// them off, every diagnostic takes the compact form: one line per part, led
// by its location and the extent of its range, positioned against nothing,
// which suits a build log.
auto set_snippets(bool value) -> void { snippets_ = value; }
// Sets which line numbers the framed form shows. The layout is the same
// either way.
//
// `LineNumbers::First` is for golden files. Adding a `CHECK` line changes the
// number of every source line below it, so a golden can only hold a line
// number as a `[[@LINE...]]` offset from its `CHECK` line. Autoupdate writes
// that offset for the first location row only: it doesn't rewrite gutter
// numbers, and a frame's `CHECK` lines are all in that row's file, so a
// location in another file has no offset from them.
auto set_line_numbers(LineNumbers value) -> void { line_numbers_ = value; }
auto set_capabilities(const Terminal::Capabilities& capabilities) -> void {
capabilities_ = capabilities;
}
private:
// Renders one line per part of the diagnostic, led by its location.
auto RenderCompact(Terminal::OutputBufferRef out,
llvm::ArrayRef<Internal::PreparedPart> parts) const
-> void;
// Renders the framed form into the geometry `Render` chose.
auto RenderFramed(Terminal::OutputBufferRef out,
llvm::MutableArrayRef<Internal::PreparedPart> parts,
int leading, Level level, int frame_x, int content_x,
int source_columns, int columns) const -> void;
Terminal::Capabilities capabilities_;
bool include_kind_ = false;
bool snippets_ = true;
LineNumbers line_numbers_ = LineNumbers::All;
};
// Returns `loc` as `<filename>:<line>:<column>`, with the parts that are
// unknown dropped from the right, and empty when even the filename is unknown.
auto FormatLocation(const Loc& loc) -> std::string;
// Writes the source snippet for `loc` to `out`, indented by `indent` columns
// and with no styling.
//
// This and `FormatLocation` are for crash handlers, which interleave a location
// and its source with text of their own rather than emitting a diagnostic. They
// share their layout with `Renderer` so that there is one implementation of it.
auto PrintSnippet(llvm::raw_ostream& out, const Loc& loc, int indent) -> void;
} // namespace Carbon::Diagnostics
#endif // CARBON_TOOLCHAIN_DIAGNOSTICS_RENDERER_H_