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

533 lines
21 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/action.h"
#include "toolchain/check/context.h"
#include "toolchain/check/control_flow.h"
#include "toolchain/check/convert.h"
#include "toolchain/check/core_identifier.h"
#include "toolchain/check/handle.h"
#include "toolchain/check/inst.h"
#include "toolchain/check/operator.h"
#include "toolchain/check/pointer_dereference.h"
#include "toolchain/check/type.h"
#include "toolchain/diagnostics/emitter.h"
#include "toolchain/parse/typed_nodes.h"
#include "toolchain/sem_ir/expr_info.h"
namespace Carbon::Check {
// Common logic for unary operator handlers.
static auto HandleUnaryOperator(Context& context, Parse::AnyExprId expr_node_id,
CoreIdentifier interface_name) -> bool {
auto operand_id = context.node_stack().PopExpr();
auto result_id = BuildUnaryOperator(
context, expr_node_id, {.interface_name = interface_name}, operand_id);
context.node_stack().Push(expr_node_id, result_id);
return true;
}
// Common logic for binary operator handlers.
static auto HandleBinaryOperator(Context& context,
Parse::AnyExprId expr_node_id,
CoreIdentifier interface_name,
CoreIdentifier op_name = CoreIdentifier::Op)
-> bool {
auto rhs_id = context.node_stack().PopExpr();
auto lhs_id = context.node_stack().PopExpr();
// All the `*With` binary operator interfaces take a single argument that is
// the type of the RHS operand. `as` has different rules and we don't call
// this function for it.
SemIR::InstId args[] = {
context.types().GetTypeInstId(context.insts().Get(rhs_id).type_id())};
auto result_id = BuildBinaryOperator(context, expr_node_id,
{.interface_name = interface_name,
.interface_args_ref = args,
.op_name = op_name},
lhs_id, rhs_id);
context.node_stack().Push(expr_node_id, result_id);
return true;
}
auto HandleParseNode(Context& context, Parse::InfixOperatorAmpId node_id)
-> bool {
// TODO: Facet type intersection may need to be handled directly.
return HandleBinaryOperator(context, node_id, CoreIdentifier::BitAndWith);
}
auto HandleParseNode(Context& context, Parse::InfixOperatorAmpEqualId node_id)
-> bool {
return HandleBinaryOperator(context, node_id,
CoreIdentifier::BitAndAssignWith);
}
auto HandleParseNode(Context& context, Parse::UnsafeModifierId node_id)
-> bool {
auto [rhs_node, rhs_id] = context.node_stack().PopExprWithNodeId();
context.node_stack().Push(node_id, rhs_id);
return true;
}
auto HandleParseNode(Context& context, Parse::InfixOperatorAsId node_id)
-> bool {
auto [rhs_node, rhs_id] = context.node_stack().PopExprWithNodeId();
auto [lhs_node, lhs_id] = context.node_stack().PopExprWithNodeId();
bool unsafe = context.parse_tree().node_kind(lhs_node) ==
Parse::NodeKind::UnsafeModifier;
auto rhs_type_id = ExprAsType(context, rhs_node, rhs_id).type_id;
context.node_stack().Push(
node_id,
ConvertForExplicitAs(context, node_id, lhs_id, rhs_type_id, unsafe));
return true;
}
auto HandleParseNode(Context& context, Parse::InfixOperatorCaretId node_id)
-> bool {
return HandleBinaryOperator(context, node_id, CoreIdentifier::BitXorWith);
}
auto HandleParseNode(Context& context, Parse::InfixOperatorCaretEqualId node_id)
-> bool {
return HandleBinaryOperator(context, node_id,
CoreIdentifier::BitXorAssignWith);
}
auto HandleParseNode(Context& context, Parse::InfixOperatorEqualId node_id)
-> bool {
// TODO: Switch to using assignment interface for most assignment. Some cases
// may need to be handled directly.
//
// return HandleBinaryOperator(context, node_id,
// CoreIdentifier::AssignWith);
auto [rhs_node, rhs_id] = context.node_stack().PopExprWithNodeId();
auto [lhs_node, lhs_id] = context.node_stack().PopExprWithNodeId();
auto lhs_type_id = context.insts().Get(lhs_id).type_id();
auto lhs_quals =
context.types().GetUnqualifiedTypeAndQualifiers(lhs_type_id).second;
if (auto lhs_cat = SemIR::GetExprCategory(context.sem_ir(), lhs_id);
(lhs_cat != SemIR::ExprCategory::Dependent &&
lhs_cat != SemIR::ExprCategory::DurableRef &&
lhs_cat != SemIR::ExprCategory::Error) ||
lhs_quals.HasAnyOf(SemIR::TypeQualifiers::Const)) {
CARBON_DIAGNOSTIC(AssignmentToNonAssignable, Error,
"expression is not assignable");
context.emitter().Emit(lhs_node, AssignmentToNonAssignable);
}
// TODO: Destroy the old value before reinitializing. This will require
// building the destruction code before we build the RHS subexpression.
rhs_id = InitializeExisting(context, node_id, lhs_id, rhs_id);
AddInst<SemIR::Assign>(context, node_id,
{.lhs_id = lhs_id, .rhs_id = rhs_id});
// We model assignment as an expression, so we need to push a value for
// it, even though it doesn't produce a value.
// TODO: Consider changing our parse tree to model assignment as a
// different kind of statement than an expression statement.
context.node_stack().Push(node_id, lhs_id);
return true;
}
auto HandleParseNode(Context& context, Parse::InfixOperatorEqualEqualId node_id)
-> bool {
return HandleBinaryOperator(context, node_id, CoreIdentifier::EqWith,
CoreIdentifier::Equal);
}
auto HandleParseNode(Context& context,
Parse::InfixOperatorExclaimEqualId node_id) -> bool {
return HandleBinaryOperator(context, node_id, CoreIdentifier::EqWith,
CoreIdentifier::NotEqual);
}
auto HandleParseNode(Context& context, Parse::InfixOperatorGreaterId node_id)
-> bool {
return HandleBinaryOperator(context, node_id, CoreIdentifier::OrderedWith,
CoreIdentifier::Greater);
}
auto HandleParseNode(Context& context,
Parse::InfixOperatorGreaterEqualId node_id) -> bool {
return HandleBinaryOperator(context, node_id, CoreIdentifier::OrderedWith,
CoreIdentifier::GreaterOrEquivalent);
}
auto HandleParseNode(Context& context,
Parse::InfixOperatorGreaterGreaterId node_id) -> bool {
return HandleBinaryOperator(context, node_id, CoreIdentifier::RightShiftWith);
}
auto HandleParseNode(Context& context,
Parse::InfixOperatorGreaterGreaterEqualId node_id)
-> bool {
return HandleBinaryOperator(context, node_id,
CoreIdentifier::RightShiftAssignWith);
}
auto HandleParseNode(Context& context, Parse::InfixOperatorLessId node_id)
-> bool {
return HandleBinaryOperator(context, node_id, CoreIdentifier::OrderedWith,
CoreIdentifier::Less);
}
auto HandleParseNode(Context& context, Parse::InfixOperatorLessEqualId node_id)
-> bool {
return HandleBinaryOperator(context, node_id, CoreIdentifier::OrderedWith,
CoreIdentifier::LessOrEquivalent);
}
auto HandleParseNode(Context& context,
Parse::InfixOperatorLessEqualGreaterId node_id) -> bool {
return context.TODO(node_id, "remove <=> operator that is not in the design");
}
auto HandleParseNode(Context& context, Parse::InfixOperatorLessLessId node_id)
-> bool {
return HandleBinaryOperator(context, node_id, CoreIdentifier::LeftShiftWith);
}
auto HandleParseNode(Context& context,
Parse::InfixOperatorLessLessEqualId node_id) -> bool {
return HandleBinaryOperator(context, node_id,
CoreIdentifier::LeftShiftAssignWith);
}
auto HandleParseNode(Context& context, Parse::InfixOperatorMinusId node_id)
-> bool {
return HandleBinaryOperator(context, node_id, CoreIdentifier::SubWith);
}
auto HandleParseNode(Context& context, Parse::InfixOperatorMinusEqualId node_id)
-> bool {
return HandleBinaryOperator(context, node_id, CoreIdentifier::SubAssignWith);
}
auto HandleParseNode(Context& context, Parse::InfixOperatorPercentId node_id)
-> bool {
return HandleBinaryOperator(context, node_id, CoreIdentifier::ModWith);
}
auto HandleParseNode(Context& context,
Parse::InfixOperatorPercentEqualId node_id) -> bool {
return HandleBinaryOperator(context, node_id, CoreIdentifier::ModAssignWith);
}
auto HandleParseNode(Context& context, Parse::InfixOperatorPipeId node_id)
-> bool {
return HandleBinaryOperator(context, node_id, CoreIdentifier::BitOrWith);
}
auto HandleParseNode(Context& context, Parse::InfixOperatorPipeEqualId node_id)
-> bool {
return HandleBinaryOperator(context, node_id,
CoreIdentifier::BitOrAssignWith);
}
auto HandleParseNode(Context& context, Parse::InfixOperatorPlusId node_id)
-> bool {
return HandleBinaryOperator(context, node_id, CoreIdentifier::AddWith);
}
auto HandleParseNode(Context& context, Parse::InfixOperatorPlusEqualId node_id)
-> bool {
return HandleBinaryOperator(context, node_id, CoreIdentifier::AddAssignWith);
}
auto HandleParseNode(Context& context, Parse::InfixOperatorSlashId node_id)
-> bool {
return HandleBinaryOperator(context, node_id, CoreIdentifier::DivWith);
}
auto HandleParseNode(Context& context, Parse::InfixOperatorSlashEqualId node_id)
-> bool {
return HandleBinaryOperator(context, node_id, CoreIdentifier::DivAssignWith);
}
auto HandleParseNode(Context& context, Parse::InfixOperatorStarId node_id)
-> bool {
return HandleBinaryOperator(context, node_id, CoreIdentifier::MulWith);
}
auto HandleParseNode(Context& context, Parse::InfixOperatorStarEqualId node_id)
-> bool {
return HandleBinaryOperator(context, node_id, CoreIdentifier::MulAssignWith);
}
auto HandleParseNode(Context& context, Parse::PostfixOperatorStarId node_id)
-> bool {
auto value_id = context.node_stack().PopExpr();
auto inner_type = ExprAsType(context, node_id, value_id);
AddInstAndPush<SemIR::PointerType>(
context, node_id,
{.type_id = SemIR::TypeType::TypeId, .pointee_id = inner_type.inst_id});
return true;
}
auto PerformAction(Context& context, SemIR::LocId loc_id,
SemIR::AddrOfAction action) -> SemIR::InstId {
auto value_id = action.lvalue_id;
// Only durable reference expressions can have their address taken.
switch (SemIR::GetExprCategory(context.sem_ir(), value_id)) {
case SemIR::ExprCategory::DurableRef:
case SemIR::ExprCategory::Error:
break;
default:
// TODO: If this is a dependent action the `loc_id` provided is not
// associated with a parse tree `node_id` and so we can't extract the
// token location for the `&` operator, which is the normal location to
// issue the error. Therefore deferred types will have the error in the
// less ideal location of the non-addressable expression. Repair to make
// these locations consistent.
CARBON_DIAGNOSTIC(AddrOfNonRef, Error,
"cannot take the address of non-reference expression");
auto diag_loc_id = loc_id.kind() == SemIR::LocId::Kind::NodeId
? LocIdForDiagnostics::TokenOnly(loc_id.node_id())
: LocIdForDiagnostics(loc_id);
context.emitter()
.Build(diag_loc_id, AddrOfNonRef)
.ExtraRange(value_id)
.Emit();
value_id = SemIR::ErrorInst::InstId;
break;
}
// TODO: Preserve spelling of type of operand where possible.
auto type_id = context.insts().Get(value_id).type_id();
auto type_inst_id = context.types().GetTypeInstId(type_id);
return AddInst<SemIR::AddrOf>(
context, loc_id,
SemIR::AddrOf{.type_id = GetPointerType(context, type_inst_id),
.lvalue_id = value_id});
}
auto HandleParseNode(Context& context, Parse::PrefixOperatorAmpId node_id)
-> bool {
auto value_id = context.node_stack().PopExpr();
auto loc_id = SemIR::LocId(node_id);
// Determine the expected type of the AddrOf instruction.
auto type_id = context.insts().Get(value_id).type_id();
auto type_inst_id = context.types().GetTypeInstId(type_id);
auto expected_type_id = GetPointerType(context, type_inst_id);
// If the value is still symbolic, defer checking until monomorphization.
auto inst_id = HandleAction<SemIR::AddrOfAction>(
context, loc_id, context.types().GetTypeInstId(expected_type_id),
{.type_id = SemIR::InstType::TypeId, .lvalue_id = value_id});
context.node_stack().Push(node_id, inst_id);
return true;
}
auto HandleParseNode(Context& context, Parse::PrefixOperatorCaretId node_id)
-> bool {
return HandleUnaryOperator(context, node_id, CoreIdentifier::BitComplement);
}
auto HandleParseNode(Context& context, Parse::PrefixOperatorConstId node_id)
-> bool {
auto value_id = context.node_stack().PopExpr();
// `const (const T)` is probably not what the developer intended.
// TODO: Detect `const (const T)*` and suggest moving the `*` inside the
// parentheses.
if (context.insts().Get(value_id).kind() == SemIR::ConstType::Kind) {
CARBON_DIAGNOSTIC(RepeatedConst, Warning,
"`const` applied repeatedly to the same type has no "
"additional effect");
context.emitter().Emit(node_id, RepeatedConst);
}
auto inner_type = ExprAsType(context, node_id, value_id);
AddInstAndPush<SemIR::ConstType>(
context, node_id,
{.type_id = SemIR::TypeType::TypeId, .inner_id = inner_type.inst_id});
return true;
}
auto HandleParseNode(Context& context, Parse::PrefixOperatorMinusId node_id)
-> bool {
return HandleUnaryOperator(context, node_id, CoreIdentifier::Negate);
}
auto HandleParseNode(Context& context,
Parse::PrefixOperatorMinusMinusId node_id) -> bool {
return HandleUnaryOperator(context, node_id, CoreIdentifier::Dec);
}
auto HandleParseNode(Context& context, Parse::PrefixOperatorNotId node_id)
-> bool {
auto value_id = context.node_stack().PopExpr();
value_id = ConvertToBoolValue(context, node_id, value_id);
AddInstAndPush<SemIR::UnaryOperatorNot>(
context, node_id,
{.type_id = context.insts().Get(value_id).type_id(),
.operand_id = value_id});
return true;
}
auto HandleParseNode(Context& context, Parse::PrefixOperatorPartialId node_id)
-> bool {
auto value_id = context.node_stack().PopExpr();
auto inner_type = ExprAsType(context, node_id, value_id);
auto class_type =
context.types().TryGetAs<SemIR::ClassType>(inner_type.type_id);
if (!class_type ||
context.classes().Get(class_type->class_id).inheritance_kind ==
SemIR::Class::InheritanceKind::Final) {
CARBON_DIAGNOSTIC(PartialOnFinal, Error,
"`partial` applied to final type {0}", SemIR::TypeId);
context.emitter().Emit(node_id, PartialOnFinal, inner_type.type_id);
}
AddInstAndPush<SemIR::PartialType>(
context, node_id,
{.type_id = SemIR::TypeType::TypeId, .inner_id = inner_type.inst_id});
return true;
}
auto HandleParseNode(Context& context, Parse::PrefixOperatorPlusPlusId node_id)
-> bool {
return HandleUnaryOperator(context, node_id, CoreIdentifier::Inc);
}
auto HandleParseNode(Context& context, Parse::PrefixOperatorRefId node_id)
-> bool {
auto expr_id = context.node_stack().PopExpr();
auto ref_id = AddInst<SemIR::RefTagExpr>(
context, node_id,
{.type_id = context.insts().Get(expr_id).type_id(), .expr_id = expr_id});
context.node_stack().Push(node_id, ref_id);
return true;
}
auto HandleParseNode(Context& context, Parse::PrefixOperatorStarId node_id)
-> bool {
auto base_id = context.node_stack().PopExpr();
auto deref_base_id = PerformPointerDereference(
context, node_id, base_id,
[&context, &node_id](SemIR::TypeId not_pointer_type_id) {
// TODO: Pass in the expression we're trying to dereference to produce a
// better diagnostic.
// TODO: Check for any facet here, rather than only a type.
if (not_pointer_type_id == SemIR::TypeType::TypeId) {
CARBON_DIAGNOSTIC(DerefOfType, Error,
"cannot dereference a type; to form a pointer "
"type, write the `*` after the pointee type");
context.emitter().Emit(LocIdForDiagnostics::TokenOnly(node_id),
DerefOfType);
return;
}
CARBON_DIAGNOSTIC(DerefOfNonPointer, Error,
"cannot dereference operand of non-pointer type {0}",
SemIR::TypeId);
context.emitter().Emit(LocIdForDiagnostics::TokenOnly(node_id),
DerefOfNonPointer, not_pointer_type_id);
});
context.node_stack().Push(node_id, deref_base_id);
return true;
}
// Adds the branch for a short circuit operand.
static auto HandleShortCircuitOperand(Context& context, Parse::NodeId node_id,
bool is_or) -> bool {
// Convert the condition to `bool`.
auto [cond_node, cond_value_id] = context.node_stack().PopExprWithNodeId();
cond_value_id = ConvertToBoolValue(context, node_id, cond_value_id);
auto bool_type_id = context.insts().Get(cond_value_id).type_id();
// Compute the branch value: the condition for `and`, inverted for `or`.
SemIR::InstId branch_value_id =
is_or ? AddInst<SemIR::UnaryOperatorNot>(
context, node_id,
{.type_id = bool_type_id, .operand_id = cond_value_id})
: cond_value_id;
auto short_circuit_result_id = AddInst<SemIR::BoolLiteral>(
context, node_id,
{.type_id = bool_type_id, .value = SemIR::BoolValue::From(is_or)});
// Create a block for the right-hand side and for the continuation.
auto rhs_block_id =
AddDominatedBlockAndBranchIf(context, node_id, branch_value_id);
auto end_block_id = AddDominatedBlockAndBranchWithArg(
context, node_id, short_circuit_result_id);
// Push the branch condition and result for use when handling the complete
// expression.
context.node_stack().Push(cond_node, branch_value_id);
context.node_stack().Push(cond_node, short_circuit_result_id);
// Push the resumption and the right-hand side blocks, and start emitting the
// right-hand operand.
context.inst_block_stack().Pop();
context.inst_block_stack().Push(end_block_id);
context.inst_block_stack().Push(rhs_block_id);
context.region_stack().AddToRegion(rhs_block_id, node_id);
// HandleShortCircuitOperator will follow, and doesn't need the operand on the
// node stack.
return true;
}
auto HandleParseNode(Context& context, Parse::ShortCircuitOperandAndId node_id)
-> bool {
return HandleShortCircuitOperand(context, node_id, /*is_or=*/false);
}
auto HandleParseNode(Context& context, Parse::ShortCircuitOperandOrId node_id)
-> bool {
return HandleShortCircuitOperand(context, node_id, /*is_or=*/true);
}
// Short circuit operator handling is uniform because the branching logic
// occurs during operand handling.
static auto HandleShortCircuitOperator(Context& context, Parse::NodeId node_id)
-> bool {
if (!context.scope_stack().IsInFunctionScope()) {
return context.TODO(node_id,
"Control flow expressions are currently only supported "
"inside functions.");
}
auto [rhs_node, rhs_id] = context.node_stack().PopExprWithNodeId();
auto short_circuit_result_id = context.node_stack().PopExpr();
auto branch_value_id = context.node_stack().PopExpr();
// The first operand is wrapped in a ShortCircuitOperand, which we
// already handled by creating a RHS block and a resumption block, which
// are the current block and its enclosing block.
rhs_id = ConvertToBoolValue(context, node_id, rhs_id);
// When the second operand is evaluated, the result of `and` and `or` is
// its value.
auto resume_block_id = context.inst_block_stack().PeekOrAdd(/*depth=*/1);
AddInst<SemIR::BranchWithArg>(
context, node_id, {.target_id = resume_block_id, .arg_id = rhs_id});
context.inst_block_stack().Pop();
context.region_stack().AddToRegion(resume_block_id, node_id);
// Collect the result from either the first or second operand.
auto result_id = AddInst<SemIR::BlockArg>(
context, node_id,
{.type_id = context.insts().Get(rhs_id).type_id(),
.block_id = resume_block_id});
SetBlockArgResultBeforeConstantUse(context, result_id, branch_value_id,
rhs_id, short_circuit_result_id);
context.node_stack().Push(node_id, result_id);
return true;
}
auto HandleParseNode(Context& context, Parse::ShortCircuitOperatorAndId node_id)
-> bool {
return HandleShortCircuitOperator(context, node_id);
}
auto HandleParseNode(Context& context, Parse::ShortCircuitOperatorOrId node_id)
-> bool {
return HandleShortCircuitOperator(context, node_id);
}
} // namespace Carbon::Check