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

213 lines
7.7 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_CHECK_CHECK_UNIT_H_
#define CARBON_TOOLCHAIN_CHECK_CHECK_UNIT_H_
#include "common/map.h"
#include "llvm/ADT/SmallVector.h"
#include "toolchain/check/check.h"
#include "toolchain/check/context.h"
#include "toolchain/check/diagnostic_emitter.h"
#include "toolchain/parse/node_ids.h"
#include "toolchain/sem_ir/ids.h"
namespace clang {
class CompilerInvocation;
}
namespace Carbon::SemIR {
class CppDomain;
} // namespace Carbon::SemIR
namespace Carbon::Check {
struct UnitAndImports;
// A file's imports corresponding to a single package, for
// `UnitAndImports::package_imports`.
struct PackageImports {
// A given import within the file, with its destination.
struct Import {
Parse::Tree::PackagingNames names;
UnitAndImports* unit_info;
};
// Use the constructor so that the SmallVector is only constructed
// as-needed.
explicit PackageImports(PackageNameId package_id,
Parse::AnyPackagingDeclId node_id)
: package_id(package_id), node_id(node_id) {}
// The identifier of the imported package.
PackageNameId package_id;
// The first `package` or `import` declaration in the file, which declared the
// package's identifier (even if the import failed). Used for associating
// diagnostics not specific to a single import.
Parse::AnyPackagingDeclId node_id;
// The associated `import` instruction. Has a value after a file is checked.
SemIR::InstId import_decl_id = SemIR::InstId::None;
// Whether there's an import that failed to load.
bool has_load_error = false;
// The list of valid imports.
llvm::SmallVector<Import> imports;
};
// Contains information accumulated while checking a `Unit` (primarily import
// information), in addition to the `Unit` itself.
struct UnitAndImports {
// Converts a `NodeId` to a diagnostic location for `UnitAndImports`.
class NodeEmitter : public Diagnostics::Emitter<Parse::NodeId> {
public:
explicit NodeEmitter(Diagnostics::Consumer* consumer,
Parse::GetTreeAndSubtreesFn tree_and_subtrees_getter)
: Emitter(consumer),
tree_and_subtrees_getter_(tree_and_subtrees_getter) {}
protected:
auto ConvertLoc(Parse::NodeId node_id, ContextFnT /*context_fn*/) const
-> Diagnostics::ConvertedLoc override {
return tree_and_subtrees_getter_().NodeToDiagnosticLoc(
node_id, Parse::LocExtent::Subtree);
}
private:
Parse::GetTreeAndSubtreesFn tree_and_subtrees_getter_;
};
explicit UnitAndImports(Unit* unit,
Parse::GetTreeAndSubtreesFn tree_and_subtrees_getter)
: unit(unit),
err_tracker(*unit->consumer),
emitter(&err_tracker, tree_and_subtrees_getter) {}
auto parse_tree() -> const Parse::Tree& { return unit->sem_ir->parse_tree(); }
auto source() -> const SourceBuffer& {
return parse_tree().tokens().source();
}
Unit* unit;
// Emitter information.
Diagnostics::ErrorTrackingConsumer err_tracker;
NodeEmitter emitter;
// List of the outgoing imports. If a package includes unavailable library
// imports, it has an entry with has_load_error set. Invalid imports (for
// example, `import Main;`) aren't added because they won't add identifiers to
// name lookup.
llvm::SmallVector<PackageImports> package_imports;
// A map of the package names to the outgoing imports above.
Map<PackageNameId, int32_t> package_imports_map;
// List of the `import Cpp` imports.
llvm::SmallVector<Parse::Tree::PackagingNames> cpp_imports;
// The C++ domain for this unit.
SemIR::CppDomain* cpp_domain = nullptr;
// The remaining number of imports which must be checked before this unit can
// be processed.
int32_t imports_remaining = 0;
// A list of incoming imports. This will be empty for `impl` files, because
// imports only touch `api` files.
llvm::SmallVector<UnitAndImports*> incoming_imports;
// The corresponding `api` unit if this is an `impl` file. The entry should
// also be in the corresponding `PackageImports`.
UnitAndImports* api_for_impl = nullptr;
// Whether the unit has been checked.
bool is_checked = false;
};
// Handles checking of a single unit. Requires that all dependencies have been
// checked.
//
// This mainly splits out the single-unit logic from the higher level cross-unit
// logic in check.cpp.
class CheckUnit {
public:
// `unit_and_imports` and `tree_and_subtrees_getters` must be non-null.
// `vlog_stream` is optional.
explicit CheckUnit(
UnitAndImports* unit_and_imports,
const Parse::GetTreeAndSubtreesStore* tree_and_subtrees_getters,
llvm::raw_ostream* vlog_stream, bool mangle_string_fingerprint = false);
// Produces and checks the IR for the provided unit.
auto Run() -> void;
private:
using CheckIRIdToIntStore = FixedSizeValueStore<SemIR::CheckIRId, int>;
// Add imports to the root block.
auto InitPackageScopeAndImports() -> void;
// Collects direct imports, for CollectTransitiveImports.
auto CollectDirectImports(llvm::SmallVector<SemIR::ImportIR>& results,
CheckIRIdToIntStore& ir_to_result_index,
SemIR::InstId import_decl_id,
const PackageImports& imports, bool is_local)
-> void;
// Collects transitive imports, handling deduplication. These will be unified
// between local_imports and api_imports.
auto CollectTransitiveImports(SemIR::InstId import_decl_id,
const PackageImports* local_imports,
const PackageImports* api_imports)
-> llvm::SmallVector<SemIR::ImportIR>;
// Imports the current package.
auto ImportCurrentPackage(SemIR::InstId package_inst_id,
SemIR::TypeId namespace_type_id) -> void;
// Imports all other Carbon packages (excluding the current package).
auto ImportOtherPackages(SemIR::TypeId namespace_type_id) -> void;
// Checks that each required declaration is available. This applies for
// declarations that should exist in an owning library, for which an extern
// declaration exists that assigns ownership to the current API.
auto CheckRequiredDeclarations() -> void;
// Checks that each required definition is available. If the definition can be
// generated by resolving a specific, does so, otherwise emits a diagnostic
// for each declaration in `context.definitions_required_by_decl()` and
// `context.definitions_required_by_use()` that doesn't have a definition.
// Each call clears both vectors.
//
// The C++ AST fragment may not be finalized if an element in
// `context.definitions_required_by_use()` is resolved by calling this
// function. This function returns true if an element was resolved, and false
// otherwise.
[[nodiscard]] auto CheckRequiredDefinitions() -> bool;
// Re-run every impl lookup with a concrete result and make sure they find the
// same witnesses.
auto CheckPoisonedConcreteImplLookupQueries() -> void;
// Look for `impl` declarations that are invalid.
auto CheckImpls() -> void;
// Does work after processing the parse tree, such as finishing the IR and
// checking for missing contents.
auto FinishRun() -> void;
// Loops over all nodes in the tree. On some errors, this may return early,
// for example if an unrecoverable state is encountered.
auto ProcessNodeIds() -> bool;
UnitAndImports* unit_and_imports_;
Parse::GetTreeAndSubtreesFn tree_and_subtrees_getter_;
DiagnosticEmitter emitter_;
Context context_;
};
} // namespace Carbon::Check
#endif // CARBON_TOOLCHAIN_CHECK_CHECK_UNIT_H_