Files
carbon-lang/toolchain/parse/node_ids.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

236 lines
8.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
#ifndef CARBON_TOOLCHAIN_PARSE_NODE_IDS_H_
#define CARBON_TOOLCHAIN_PARSE_NODE_IDS_H_
#include "toolchain/base/index_base.h"
#include "toolchain/lex/token_index.h"
#include "toolchain/parse/node_category.h"
#include "toolchain/parse/node_kind.h"
namespace Carbon::Parse {
// Represents an invalid node id of any type
struct NoneNodeId {};
// A lightweight handle representing a node in the tree.
//
// Objects of this type are small and cheap to copy and store. They don't
// contain any of the information about the node, and serve as a handle that
// can be used with the underlying tree to query for detailed information.
struct NodeId : public IdBase<NodeId> {
static constexpr llvm::StringLiteral Label = "node";
// We give NodeId a bit in addition to TokenIndex in order to account for
// virtual nodes, where a token may produce two nodes.
static constexpr int32_t Bits = Lex::TokenIndex::Bits + 1;
// The maximum ID, non-inclusive.
static constexpr int Max = 1 << Bits;
// A node ID with no value.
static constexpr NoneNodeId None;
constexpr explicit NodeId(int32_t index) : IdBase(index) {
CARBON_DCHECK(index < Max, "Index out of range: {0}", index);
}
explicit(false) constexpr NodeId(NoneNodeId /*none*/) : IdBase(NoneIndex) {}
};
// For looking up the type associated with a given id type.
template <typename T>
struct NodeForId;
// `<KindName>Id` is a typed version of `NodeId` that references a node of kind
// `<KindName>`:
template <const NodeKind& K>
struct NodeIdForKind : public NodeId {
// NOLINTNEXTLINE(readability-identifier-naming)
static const NodeKind& Kind;
// Provide a factory function for construction from `NodeId`. This doesn't
// validate the type, so it's unsafe.
static constexpr auto UnsafeMake(NodeId node_id) -> NodeIdForKind {
return NodeIdForKind(node_id);
}
explicit(false) constexpr NodeIdForKind(NoneNodeId /*none*/)
: NodeId(NoneIndex) {}
private:
// Private to prevent accidental explicit construction from an untyped
// NodeId.
explicit constexpr NodeIdForKind(NodeId node_id) : NodeId(node_id) {}
};
template <const NodeKind& K>
const NodeKind& NodeIdForKind<K>::Kind = K;
#define CARBON_PARSE_NODE_KIND(KindName) \
using KindName##Id = NodeIdForKind<NodeKind::KindName>;
#include "toolchain/parse/node_kind.def"
// NodeId that matches any NodeKind whose `category()` overlaps with `Category`.
template <NodeCategory::RawEnumType Category>
struct NodeIdInCategory : public NodeId {
// Provide a factory function for construction from `NodeId`. This doesn't
// validate the type, so it's unsafe.
static constexpr auto UnsafeMake(NodeId node_id) -> NodeIdInCategory {
return NodeIdInCategory(node_id);
}
// Support conversion from `NodeIdForKind<Kind>` if Kind's category
// overlaps with `Category`.
template <const NodeKind& Kind>
explicit(false) NodeIdInCategory(NodeIdForKind<Kind> node_id)
: NodeId(node_id) {
CARBON_CHECK(Kind.category().HasAnyOf(Category));
}
explicit(false) constexpr NodeIdInCategory(NoneNodeId /*none*/)
: NodeId(NoneIndex) {}
private:
// Private to prevent accidental explicit construction from an untyped
// NodeId.
explicit constexpr NodeIdInCategory(NodeId node_id) : NodeId(node_id) {}
};
// Aliases for `NodeIdInCategory` to describe particular categories of nodes.
using AnyDeclId = NodeIdInCategory<NodeCategory::Decl>;
using AnyExprId = NodeIdInCategory<NodeCategory::Expr>;
using AnyImplAsId = NodeIdInCategory<NodeCategory::ImplAs>;
using AnyMemberAccessId =
NodeIdInCategory<NodeCategory::MemberName | NodeCategory::MemberExpr |
NodeCategory::IntConst>;
using AnyModifierId = NodeIdInCategory<NodeCategory::Modifier>;
using AnyPatternId =
NodeIdInCategory<NodeCategory::Pattern | NodeCategory::Expr>;
using AnyStatementId =
NodeIdInCategory<NodeCategory::Statement | NodeCategory::Decl>;
using AnyRequireImplsId = NodeIdInCategory<NodeCategory::RequireImpls>;
using AnyRequirementId = NodeIdInCategory<NodeCategory::Requirement>;
using AnyObserveOperatorId = NodeIdInCategory<NodeCategory::ObserveOperator>;
using AnyObserveOperandId =
NodeIdInCategory<NodeCategory::Expr | NodeCategory::ObserveOperator>;
using AnyNonExprNameId = NodeIdInCategory<NodeCategory::NonExprName>;
using AnyPackageNameId = NodeIdInCategory<NodeCategory::PackageName>;
using AnyReturnSpecifierId = NodeIdInCategory<NodeCategory::ReturnSpecifier>;
namespace Internal {
template <typename T>
concept IsNodeKind = std::same_as<std::remove_cvref_t<T>, NodeKind> ||
std::same_as<std::remove_cvref_t<T>, NodeKind::Definition>;
template <typename T>
concept IsTypedNode = requires {
{ T::Kind } -> IsNodeKind;
};
} // namespace Internal
// NodeId with kind that matches one of the `T::Kind`s.
template <typename... T>
requires(sizeof...(T) >= 2 && (Internal::IsTypedNode<T> && ...))
struct NodeIdOneOf : public NodeId {
private:
// True if `OtherT` is one of `T`.
template <typename OtherT>
static constexpr bool Contains = (std::is_same<OtherT, T>{} || ...);
// True if `NodeIdOneOf<SubsetT...>` is a subset of this `NodeIdOneOf`.
template <typename Unused>
static constexpr bool IsSubset = false;
template <typename... SubsetT>
static constexpr bool IsSubset<NodeIdOneOf<SubsetT...>> =
(Contains<SubsetT> && ...);
// Private to prevent accidental explicit construction from an untyped
// NodeId.
explicit constexpr NodeIdOneOf(NodeId node_id) : NodeId(node_id) {}
public:
// Provide a factory function for construction from `NodeId`. This doesn't
// validate the type, so it's unsafe.
static constexpr auto UnsafeMake(NodeId node_id) -> NodeIdOneOf {
return NodeIdOneOf(node_id);
}
template <const NodeKind& Kind>
requires(Contains<NodeIdForKind<Kind>>)
explicit(false) NodeIdOneOf(NodeIdForKind<Kind> node_id) : NodeId(node_id) {}
template <typename OtherNodeIdOneOf>
requires(IsSubset<OtherNodeIdOneOf>)
explicit(false) NodeIdOneOf(OtherNodeIdOneOf node_id) : NodeId(node_id) {}
explicit(false) constexpr NodeIdOneOf(NoneNodeId /*none*/)
: NodeId(NoneIndex) {}
};
using AnyClassDeclId =
NodeIdOneOf<ClassDeclId, ClassDefinitionStartId,
// TODO: This may be wrong? But we have choice types produce a
// class, so they are a form of class decls. This avoids
// duplicating all of SemIR::ClassDecl.
ChoiceDefinitionStartId>;
using AnyFunctionDeclId =
NodeIdOneOf<FunctionDeclId, FunctionDefinitionStartId,
FunctionTerseDefinitionStartId,
BuiltinFunctionDefinitionStartId, LambdaDefinitionStartId,
LambdaTerseDefinitionStartId>;
using AnyFunctionDefinitionStartId =
NodeIdOneOf<FunctionDefinitionStartId, FunctionTerseDefinitionStartId>;
using AnyFunctionDefinitionId =
NodeIdOneOf<FunctionDefinitionId, FunctionTerseDefinitionId,
BuiltinFunctionDefinitionId>;
using AnyLambdaDefinitionStartId =
NodeIdOneOf<LambdaDefinitionStartId, LambdaTerseDefinitionStartId>;
using AnyImplDeclId = NodeIdOneOf<ImplDeclId, ImplDefinitionStartId>;
using AnyInterfaceDeclId =
NodeIdOneOf<InterfaceDeclId, InterfaceDefinitionStartId>;
using AnyNamedConstraintDeclId =
NodeIdOneOf<NamedConstraintDeclId, NamedConstraintDefinitionStartId>;
using AnyNamespaceId =
NodeIdOneOf<NamespaceId, ImportDeclId, LibraryDeclId, PackageDeclId>;
using AnyPackagingDeclId =
NodeIdOneOf<ImportDeclId, LibraryDeclId, PackageDeclId>;
using AnyPointerDeferenceExprId =
NodeIdOneOf<PrefixOperatorStarId, PointerMemberAccessExprId>;
using AnyRuntimeBindingPatternName =
NodeIdOneOf<IdentifierNameNotBeforeSignatureId, SelfValueNameId,
UnderscoreNameId>;
using AnyPrimitiveFormIdId =
NodeIdOneOf<RefPrimitiveFormId, VarPrimitiveFormId, ValPrimitiveFormId>;
using AnyTerseFunctionDefinitionId =
NodeIdOneOf<FunctionTerseDefinitionId, LambdaTerseDefinitionId>;
// NodeId with kind that is anything but T::Kind.
template <typename T>
struct NodeIdNot : public NodeId {
constexpr explicit NodeIdNot(NodeId node_id) : NodeId(node_id) {}
explicit(false) constexpr NodeIdNot(NoneNodeId /*none*/)
: NodeId(NoneIndex) {}
};
// Note that the support for extracting these types using the `Tree::Extract*`
// functions is defined in `extract.cpp`.
// How much of a node's source a diagnostic location for it covers.
enum class LocExtent : int8_t {
// Every token descending from the node.
Subtree,
// The node's own token alone.
Token,
// The last name among the node's direct children, which for a declaration
// is the name it declares: a qualifier's name is a child of the qualifier.
// A node with no name among its direct children, such as an `impl`, covers
// its subtree.
DeclaredName,
};
} // namespace Carbon::Parse
#endif // CARBON_TOOLCHAIN_PARSE_NODE_IDS_H_