Files
carbon-lang/toolchain/check/modifiers.cpp
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

254 lines
10 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/check/modifiers.h"
#include <optional>
#include "toolchain/check/decl_introducer_state.h"
namespace Carbon::Check {
// Builds the diagnostic for DiagnoseNotAllowed.
template <typename... TokenKinds>
static auto StartDiagnoseNotAllowed(
Context& context,
const Diagnostics::DiagnosticBase<TokenKinds...>& diagnostic_base,
Parse::NodeId modifier_node, Lex::TokenKind declaration_kind)
-> DiagnosticBuilder {
if constexpr (sizeof...(TokenKinds) == 0) {
return context.emitter().Build(modifier_node, diagnostic_base);
} else if constexpr (sizeof...(TokenKinds) == 1) {
return context.emitter().Build(modifier_node, diagnostic_base,
context.token_kind(modifier_node));
} else {
static_assert(sizeof...(TokenKinds) == 2);
return context.emitter().Build(modifier_node, diagnostic_base,
context.token_kind(modifier_node),
declaration_kind);
}
}
// Diagnoses that a modifier wasn't allowed. Handles adding context when
// possible.
//
// The diagnostic can take up to two TokenKinds: the modifier kind, and the
// declaration kind.
template <typename... TokenKinds>
static auto DiagnoseNotAllowed(
Context& context,
const Diagnostics::DiagnosticBase<TokenKinds...>& diagnostic_base,
Parse::NodeId modifier_node, Lex::TokenKind decl_kind,
SemIR::LocId context_loc_id) -> void {
auto diag = StartDiagnoseNotAllowed(context, diagnostic_base, modifier_node,
decl_kind);
if (context_loc_id.has_value()) {
CARBON_DIAGNOSTIC_LABEL(ModifierNotInContext, "containing definition here");
diag.Attach(context_loc_id, ModifierNotInContext);
}
diag.Emit();
}
// Returns the KeywordModifierSet corresponding to the ModifierOrder entry.
static auto ModifierOrderAsSet(ModifierOrder order) -> KeywordModifierSet {
switch (order) {
case ModifierOrder::Access:
return KeywordModifierSet::Access;
case ModifierOrder::Extern:
return KeywordModifierSet::Extern;
case ModifierOrder::Extend:
return KeywordModifierSet::Extend;
case ModifierOrder::Decl:
return KeywordModifierSet::Decl;
case ModifierOrder::Static:
return KeywordModifierSet::Static;
case ModifierOrder::Evaluation:
return KeywordModifierSet::Evaluation;
}
}
// Like `LimitModifiersOnDecl`, except says which modifiers are forbidden, and a
// `context_string` (and optional `context_loc_id`) specifying the context in
// which those modifiers are forbidden.
//
// See DiagnoseNotAllowed for details regarding diagnostic_base.
template <typename DiagnosticBaseT>
static auto ForbidModifiersOnDecl(
Context& context, const DiagnosticBaseT& diagnostic_base,
DeclIntroducerState& introducer, KeywordModifierSet forbidden,
SemIR::LocId context_loc_id = SemIR::LocId::None) -> void {
auto not_allowed = introducer.modifier_set & forbidden;
if (not_allowed.empty()) {
return;
}
for (auto order_index = 0;
order_index <= static_cast<int8_t>(ModifierOrder::Last); ++order_index) {
auto order = static_cast<ModifierOrder>(order_index);
if (not_allowed.HasAnyOf(ModifierOrderAsSet(order))) {
DiagnoseNotAllowed(context, diagnostic_base,
introducer.modifier_node_id(order), introducer.kind,
context_loc_id);
introducer.set_modifier_node_id(order, Parse::NodeId::None);
}
}
introducer.modifier_set.Remove(forbidden);
}
auto LimitModifiersOnDecl(Context& context, DeclIntroducerState& introducer,
KeywordModifierSet allowed) -> void {
CARBON_DIAGNOSTIC(ModifierNotAllowedOnDeclaration, Error,
"`{0}` not allowed on `{1}` declaration", Lex::TokenKind,
Lex::TokenKind);
ForbidModifiersOnDecl(context, ModifierNotAllowedOnDeclaration, introducer,
~allowed);
}
auto LimitModifiersOnNotDefinition(Context& context,
DeclIntroducerState& introducer,
KeywordModifierSet allowed) -> void {
CARBON_DIAGNOSTIC(
ModifierOnlyAllowedOnDefinition, Error,
"`{0}` not allowed on `{1}` forward declaration, only definition",
Lex::TokenKind, Lex::TokenKind);
ForbidModifiersOnDecl(context, ModifierOnlyAllowedOnDefinition, introducer,
~allowed);
}
auto CheckAccessModifiersOnDecl(Context& context,
DeclIntroducerState& introducer,
std::optional<SemIR::Inst> parent_scope_inst)
-> void {
CARBON_DIAGNOSTIC(ModifierProtectedNotAllowed, Error,
"`protected` not allowed; requires class scope");
if (parent_scope_inst) {
if (parent_scope_inst->Is<SemIR::Namespace>()) {
// TODO: This assumes that namespaces can only be declared at file scope.
// If we add support for non-file-scope namespaces, we will need to check
// the parents of the target scope to determine whether we're at file
// scope.
ForbidModifiersOnDecl(context, ModifierProtectedNotAllowed, introducer,
KeywordModifierSet::Protected);
return;
}
if (parent_scope_inst->Is<SemIR::ClassDecl>()) {
// Both `private` and `protected` allowed in a class definition.
return;
}
}
// Otherwise neither `private` nor `protected` allowed.
ForbidModifiersOnDecl(context, ModifierProtectedNotAllowed, introducer,
KeywordModifierSet::Protected);
CARBON_DIAGNOSTIC(ModifierPrivateNotAllowed, Error,
"`private` not allowed; requires class or file scope");
ForbidModifiersOnDecl(context, ModifierPrivateNotAllowed, introducer,
KeywordModifierSet::Private);
}
auto CheckMethodModifiersOnFunction(
Context& context, DeclIntroducerState& introducer,
SemIR::InstId parent_scope_inst_id,
std::optional<SemIR::Inst> parent_scope_inst) -> void {
if (parent_scope_inst) {
if (auto class_decl = parent_scope_inst->TryAs<SemIR::ClassDecl>()) {
auto inheritance_kind =
context.classes().Get(class_decl->class_id).inheritance_kind;
if (inheritance_kind == SemIR::Class::Final) {
CARBON_DIAGNOSTIC(
ModifierVirtualNotAllowed, Error,
"`virtual` not allowed; requires `abstract` or `base` class scope");
ForbidModifiersOnDecl(context, ModifierVirtualNotAllowed, introducer,
KeywordModifierSet::Virtual,
SemIR::LocId(parent_scope_inst_id));
}
if (inheritance_kind != SemIR::Class::Abstract) {
CARBON_DIAGNOSTIC(
ModifierAbstractNotAllowed, Error,
"`abstract` not allowed; requires `abstract` class scope");
ForbidModifiersOnDecl(context, ModifierAbstractNotAllowed, introducer,
KeywordModifierSet::Abstract,
SemIR::LocId(parent_scope_inst_id));
}
return;
}
}
CARBON_DIAGNOSTIC(ModifierRequiresClass, Error,
"`{0}` not allowed; requires class scope", Lex::TokenKind);
ForbidModifiersOnDecl(context, ModifierRequiresClass, introducer,
KeywordModifierSet::Method);
}
auto RestrictExternModifierOnDecl(Context& context,
DeclIntroducerState& introducer,
std::optional<SemIR::Inst> parent_scope_inst,
bool is_definition) -> void {
if (!introducer.modifier_set.HasAnyOf(KeywordModifierSet::Extern)) {
return;
}
if (parent_scope_inst && !parent_scope_inst->Is<SemIR::Namespace>()) {
CARBON_DIAGNOSTIC(ModifierExternNotAllowed, Error,
"`{0}` not allowed; requires file or namespace scope",
Lex::TokenKind);
ForbidModifiersOnDecl(context, ModifierExternNotAllowed, introducer,
KeywordModifierSet::Extern);
// Treat as unset.
introducer.extern_library = SemIR::LibraryNameId::None;
return;
}
if (introducer.extern_library == context.sem_ir().library_id()) {
// This prints an error for `extern library`, but doesn't drop it because we
// assume there is some other, correct value that we just don't know here.
CARBON_DIAGNOSTIC(ExternLibraryIsCurrentLibrary, Error,
"`extern library` cannot specify the current library");
context.emitter().Emit(introducer.modifier_node_id(ModifierOrder::Extern),
ExternLibraryIsCurrentLibrary);
introducer.extern_library = SemIR::LibraryNameId::Error;
// Right now this can produce both this and the below diagnostic.
}
if (is_definition && introducer.extern_library.has_value()) {
CARBON_DIAGNOSTIC(ExternLibraryOnDefinition, Error,
"a library cannot be provided for an `extern` modifier "
"on a definition");
context.emitter().Emit(introducer.modifier_node_id(ModifierOrder::Extern),
ExternLibraryOnDefinition);
}
}
auto RequireDefaultFinalOnlyInInterfaces(Context& context,
DeclIntroducerState& introducer,
SemIR::NameScopeId parent_scope_id,
bool is_definition) -> void {
// Both `default` and `final` allowed in an interface definition.
if (!context.name_scopes().InstIs<SemIR::InterfaceWithSelfDecl>(
parent_scope_id)) {
CARBON_DIAGNOSTIC(ModifierRequiresInterface, Error,
"`{0}` not allowed; requires interface scope",
Lex::TokenKind);
ForbidModifiersOnDecl(context, ModifierRequiresInterface, introducer,
KeywordModifierSet::Interface);
return;
}
// TODO: remove and check that final/default declarations have a definition by
// the end of the file.
if (!is_definition) {
CARBON_DIAGNOSTIC(
ModifierFinalRequiresDefaultImpl, Error,
"TODO: `{0}` modifier currently requires an inline definition",
Lex::TokenKind);
ForbidModifiersOnDecl(context, ModifierFinalRequiresDefaultImpl, introducer,
KeywordModifierSet::Interface);
}
}
} // namespace Carbon::Check