crates.sage_ir.inference.subtyping_and_coercion

Subtyping preserves representation; coercion is an explicit conversion. A successful subtype relation requires source and target to have the same memory layout and introduces no runtime conversion. A coercion is selected only at a coercion site, may change layout, and is materialized in the completed Typed IR. Never-to-any belongs only to the coercion relation.

Read in specification context · design/crates/sage_ir/inference.sage

Implementation

Implemented crates/sage-ir/src/check/expr.rs:42–47

sage_ir::check::expr · lib:sage_ir

#![allow(unused)]
fn main() {
    // {anchor}`crates.sage_ir.inference.subtyping_and_coercion`
    async fn check_with_expected(
        &self,
        cx: &InferCtx<'_, 'db>,
        scope: &Scope<'db>,
        expected: Ptr<Ty<'db>>,

}

See more source ↗

Implemented crates/sage-ir/src/check/finalize.rs:244–249

sage_ir::check::finalize · lib:sage_ir

#![allow(unused)]
fn main() {
            // {anchor}`crates.sage_ir.inference.subtyping_and_coercion`
            TyExprData::NeverToAny(operand) => {
                let operand = self.copy_expr(operand);
                if matches!(self.target[finalized_ty], Ty::Never) {
                    self.target[operand].data
                } else {

}

See more source ↗

Implemented crates/sage-ir/src/check/infer/skeleton.rs:54–59

sage_ir::check::infer::skeleton · lib:sage_ir

#![allow(unused)]
fn main() {
// {anchor}`crates.sage_ir.inference.subtyping_and_coercion`
// {anchor}`crates.sage_ir.types.aliases.identity`
pub fn decompose<'db>(stash: &Stash, ty: Ptr<Ty<'db>>) -> Decomposed<'db> {
    match stash[ty] {
        Ty::Bool => leaf(Skeleton::Bool),
        Ty::Char => leaf(Skeleton::Char),

}

See more source ↗

Implemented crates/sage-ir/src/check/infer/unify.rs:294–299

sage_ir::check::infer::unify · lib:sage_ir

#![allow(unused)]
fn main() {
    // {anchor}`crates.sage_ir.inference.subtyping_and_coercion`
    let left_decomposed = decompose(stash, left);
    let right_decomposed = decompose(stash, right);
    if left_decomposed.skeleton != right_decomposed.skeleton
        || left_decomposed.children.len() != right_decomposed.children.len()
    {

}

See more source ↗

Implemented crates/sage-ir/src/check/infer_ctx.rs:897–902

sage_ir::check::infer_ctx · lib:sage_ir

#![allow(unused)]
fn main() {
    // {anchor}`crates.sage_ir.inference.subtyping_and_coercion`
    pub fn coerce_expr(
        &self,
        expr: Ptr<TyExpr<'db>>,
        target: Ptr<Ty<'db>>,
        span: RelativeSpan,

}

See more source ↗

Implemented crates/sage-ir/src/local_syms/fns.rs:336–341

sage_ir::local_syms::fns · lib:sage_ir

#![allow(unused)]
fn main() {
            // {anchor}`crates.sage_ir.inference.subtyping_and_coercion`
            let body_span = cx.stash()[expr].span;
            match cx.coerce_expr(expr, imported.ret, body_span) {
                Ok(coerced) => coerced,
                Err(error) => {
                    let error = if let Some(ret_ptr) = cst.ret {

}

See more source ↗

Tests and review

Indexed tests and the implementation-completeness and test-adequacy review; no test run is implied.

TODO sage_meta::todo::inference_subtyping_and_coercion

crates/sage-meta/tests/semantic_spec.rs · test:semantic_spec

#![allow(unused)]
fn main() {
#[test]
    #[sage::test(crates.sage_ir.inference.subtyping_and_coercion)]
    fn inference_subtyping_and_coercion() {
        // TODO: Complete the claim-specific verification matrix:
        // Source-driven integration tests reject never-to-any beneath invariant type constructors, accept
        // it at a top-level coercion site, and inspect the completed Typed IR to show that the accepted
        // coercion is explicit. Focused relation tests cover every implemented subtype and coercion rule
        // and demonstrate that subtype success preserves layout.
    }
}

See more source ↗

Implemented sage_test_harness::generic_never_coercions_follow_other_arguments_in_either_order

crates/sage-test-harness/tests/inference.rs · test:inference

#![allow(unused)]
fn main() {
#[test]
#[sage::test(crates.sage_ir.inference.subtyping_and_coercion)]
fn generic_never_coercions_follow_other_arguments_in_either_order() {
    compile_test! {
        source: indoc! {r#"
            fn pair<T>(first: T, second: T) {}
            fn single<T>(value: T) {}
            fn example() {
                pair(loop {}, true); //# ty
                pair(true, loop {}); //# ty
                single(loop {}); //# ty
            }
        "#},
        observations: expect![[r#"
            src/lib.rs: path `pair`
              type: fn(bool, bool) -> ()
            src/lib.rs: block `{}`
              type: ()
            src/lib.rs: loop `loop {}`
              type: !
            src/lib.rs: coercion `loop {}`
              type: bool
            src/lib.rs: literal `true`
              type: bool
            src/lib.rs: call `pair(loop {}, true)`
              type: ()
            src/lib.rs: path `pair`
              type: fn(bool, bool) -> ()
            src/lib.rs: literal `true`
              type: bool
            src/lib.rs: block `{}`
              type: ()
            src/lib.rs: loop `loop {}`
              type: !
            src/lib.rs: coercion `loop {}`
              type: bool
            src/lib.rs: call `pair(true, loop {})`
              type: ()
            src/lib.rs: path `single`
              type: fn(!) -> ()
            src/lib.rs: block `{}`
              type: ()
            src/lib.rs: loop `loop {}`
              type: !
            src/lib.rs: call `single(loop {})`
              type: ()
        "#]],
    }
}
}

See more source ↗

Implemented sage_test_harness::never_to_any_is_not_subtyping_beneath_mutable_references

crates/sage-test-harness/tests/inference.rs · test:inference

#![allow(unused)]
fn main() {
#[test]
#[sage::test(crates.sage_ir.inference.subtyping_and_coercion)]
fn never_to_any_is_not_subtyping_beneath_mutable_references() {
    // rustc additionally feature-gates ! in parameter types. Sage accepts that
    // syntax but cannot yet parse feature(never_type); both still report the
    // distinct subtype mismatch at the return expression.
    compile_test! {
        source: indoc! {r#"
            fn invalid(value: &mut !) -> &mut u32 { //# ERROR if rustc
                value //# ERROR
            }
        "#},
        diagnostics: expect![[r#"
            error: type mismatch: expected `u32`, found `!`
             --> src/lib.rs:1:39
              |
            1 |   fn invalid(value: &mut !) -> &mut u32 { //# ERROR if rustc
              |  ______________________________--------_^
              | |                              |
              | |                              expected `u32` because of return type
            2 | |     value //# ERROR
            3 | | }
              | | ^
              | |_|
              |   found `!`"#]],
    }
}
}

See more source ↗

Implemented sage_test_harness::top_level_never_coercion_preserves_source_and_result_types

crates/sage-test-harness/tests/inference.rs · test:inference

#![allow(unused)]
fn main() {
#[test]
#[sage::test(crates.sage_ir.inference.subtyping_and_coercion)]
fn top_level_never_coercion_preserves_source_and_result_types() {
    compile_test! {
        source: indoc! {r#"
            fn diverge() -> u32 {
                loop {} //# ty
            }
            fn still_never() -> ! {
                loop {} //# ty
            }
        "#},
        observations: expect![[r#"
            src/lib.rs: block `{}`
              type: ()
            src/lib.rs: loop `loop {}`
              type: !
            src/lib.rs: coercion `loop {}`
              type: u32
            src/lib.rs: block `{}`
              type: ()
            src/lib.rs: loop `loop {}`
              type: !
        "#]],
    }
}
}

See more source ↗

Review: Accepted · Codex /root/final_quality.

Reviewed the full subtyping_and_coercion claim, all six ordinary implementation entries, three ordinary annotated tests and one TODO test. Requirements: subtype success preserves representation and adds no conversion; coercion occurs at a coercion site, can change representation, and is explicit in completed Typed IR; never-to-any is coercion only. This assessment is limited to the core relation/coercion paths and associated tests. It does not evaluate the separately authored unary-dereference behavior in expr.rs; no selected test or relation-path dependency required that behavior.

Implementation: InferCtx::require_sub first canonicalizes operands, accepts equal roots, recursively relates shared-reference referents, uses equality for mutable-reference referents, and otherwise requires equality. There is no never-to-any arm. unify_in_probe compares skeleton and child arity before recursively unifying children, so Never differs from integer/other constructors and cannot be smuggled beneath invariant references. skeleton.rs preserves constructor identity, reference mutability, array constants, tuple/function arity and nominal/alias identities. The currently represented subtype rules therefore preserve structural representation rather than inserting a runtime conversion; this is not a claim of a complete Rust variance or layout-analysis engine.

InferCtx::coerce_expr checks top-level source Never with a non-Never target, otherwise invokes require_sub. At a never coercion it allocates TyExprData::NeverToAny with the target type while retaining the operand and its source type. For a block tail it recurses to the tail and creates a correctly typed block. Expected-expression checking in expr.rs invokes the coercion helper after synthesis; function body completion in fns.rs invokes it against the declared return type and retains contextual diagnostics on failure. Unknown targets are deferred rather than immediately unified to Never, allowing later arguments to constrain them; default_deferred_never_targets chooses Never only for still-unconstrained targets. finalize.rs copies NeverToAny into the completed tree, removing the wrapper when the finalized target itself is Never. Non-coercing subtype success returns the original expression. These inspected paths distinguish representation-preserving relation from explicit conversion.

Test adequacy: never_to_any_is_not_subtyping_beneath_mutable_references supplies source &mut ! -> &mut u32 and expects the concrete Sage mismatch. Its rustc-only marker accounts for the separate feature gate on never parameter syntax while the shared marker requires the return mismatch; that qualification is visible in the body. top_level_never_coercion_preserves_source_and_result_types expects both a loop typed ! and a separate coercion typed u32 for a u32-returning function, while the !-returning function has only the original never loop. generic_never_coercions_follow_other_arguments_in_either_order expects pair(loop {}, true) and pair(true, loop {}) both to instantiate bool parameters and expose explicit bool coercion nodes, while single(loop {}) resolves to fn(!) without a redundant conversion. These assertions distinguish source and result types and guard premature fallback/order sensitivity.

Captured compile-test helpers show real isolated source projects, production Sage body queries, diagnostic matching and exact expectation comparisons; the observer emits coercion rows only for completed TyExprData::NeverToAny nodes and retains the original operand row. FrozenType renders actual checked types, not expected answers. Captured rustc execution/output validation confirms independent compiler diagnostic checks; no rustc or test invocation was made in this review. Source observation/correlation dependencies were also captured. The snapshots are substantive assertions, not just annotation or test-name evidence.

The associated TODO inference_subtyping_and_coercion retains the full rule matrix and layout evidence. Its never/invariant/core scenarios now have partial ordinary coverage, but it still calls for focused relation tests covering every implemented subtype/coercion rule and demonstrating layout preservation. It contains no assertions and is not counted as completed verification. Completing that remaining matrix requires representative source-level constructors and relation-level cases, including nested/shared-reference rules and failure paths, with explicit typed-tree observations at conversion sites. No claim is made that all Rust coercions or a general layout engine already exist. No new suspected defect was identified in the reviewed core paths.

Commands executed: fresh review start with coordinator instructions, source and all associated-test inspection, review read captures of inference design and compile harness/observer/source/type/rustc helpers. No tests or build executed, no source edits. Central suite results are separate evidence. No requested edits; broad relation/layout verification remains explicitly deferred.

Browse crates anchors

139 anchors

Specification anchors and declared coverage
AnchorImplementationTests
crates (139)114 Implemented37 TODO2 N/A74 Implemented107 TODO
crates.sage_inspector (15)13 Implemented1 TODO2 N/A3 Implemented15 TODO
crates.sage_inspector.inspection (15)13 Implemented1 TODO2 N/A3 Implemented15 TODO
balanced_tracesImplementedTODO
canonical_ownershipImplementedImplementedTODO
derive_reflectionImplementedImplementedTODO
detail_free_indexImplementedTODO
deterministic_traceImplementedTODO
durable_navigationN/ATODO
generic_browserN/ATODO
owned_reflectionImplementedImplementedTODO
product_availabilityImplementedTODO
revision_and_demandImplementedTODO
semantic_phase_boundaryImplementedTODO
source_evidenceImplementedTODO
typed_serviceImplementedTODO
unknown_workImplementedTODOTODO
workspace_actorImplementedTODO
crates.sage_ir (90)67 Implemented34 TODO40 Implemented88 TODO
crates.sage_ir.checking (12)12 Implemented3 TODO5 Implemented12 TODO
crates.sage_ir.checking.body (5)5 Implemented2 TODO3 Implemented5 TODO
elaborationImplementedImplementedTODO
expected_typesImplementedTODOTODO
interface_dependenciesImplementedImplementedTODO
isolated_completionImplementedImplementedTODO
operator_callsImplementedTODOTODO
identity_mintingImplementedTODO
owned_productsImplementedImplementedTODO
crates.sage_ir.checking.signature (4)4 Implemented1 TODO1 Implemented4 TODO
body_independenceImplementedTODO
narrow_detailImplementedTODOTODO
owner_binderImplementedImplementedTODO
storageImplementedTODO
symbol_keyed_interfacesImplementedTODO
crates.sage_ir.crate (9)9 TODO9 TODO
explicit_restrictionsTODOTODO
identity_before_detailTODOTODO
incremental_evidenceTODOTODO
narrow_demandsTODOTODO
reexecution_and_invalidationTODOTODO
represented_completenessTODOTODO
restrictions_and_gapsTODOTODO
semantic_query_boundariesTODOTODO
terminal_incompletenessTODOTODO
crates.sage_ir.inference (8)8 Implemented6 Implemented8 TODO
atomic_checkingImplementedImplementedTODO
body_local_quiescenceImplementedImplementedTODO
canonical_boundaryImplementedImplementedTODO
completed_body_boundaryImplementedTODO
numeric_domainsImplementedImplementedTODO
subtyping_and_coercionImplementedImplementedTODO
terminal_obligationsImplementedTODO
transaction_isolationImplementedImplementedTODO
crates.sage_ir.metadata (4)4 Implemented1 TODO4 TODO
explicit_incompletenessImplementedTODO
keyed_reuseImplementedTODOTODO
product_boundariesImplementedTODO
provider_authorityImplementedTODO
crates.sage_ir.modules (8)7 Implemented1 TODO4 Implemented8 TODO
crates.sage_ir.modules.expand (4)4 Implemented2 Implemented4 TODO
completenessImplementedImplementedTODO
dependenciesImplementedTODO
direct_membersImplementedTODO
recursion_and_fixpointImplementedImplementedTODO
crates.sage_ir.modules.parse (4)3 Implemented1 TODO2 Implemented4 TODO
dependenciesImplementedTODO
detail_firewallImplementedImplementedTODO
recovery_completenessTODOTODO
syntax_identitiesImplementedImplementedTODO
crates.sage_ir.resolution (5)5 Implemented1 TODO3 Implemented4 TODO
crates.sage_ir.resolution.lookup (5)5 Implemented1 TODO3 Implemented4 TODO
completenessImplementedTODOImplementedTODO
dependenciesImplementedTODO
expansion_import_ambiguityImplementedImplemented
identity_onlyImplementedTODO
precedenceImplementedImplementedTODO
crates.sage_ir.solver (9)7 Implemented7 TODO5 Implemented9 TODO
alternative_isolationImplementedTODOImplementedTODO
bounded_completenessImplementedTODOTODO
candidate_completenessImplementedTODO
canonical_cyclesTODOTODO
canonical_outputsImplementedImplementedTODO
local_index_firewallTODOTODO
normalization_demandImplementedTODOImplementedTODO
schedule_independenceImplementedTODOImplementedTODO
shared_final_resultImplementedTODOImplementedTODO
crates.sage_ir.symbols (8)8 Implemented4 Implemented7 TODO
associated_identityImplementedImplemented
associated_interfacesImplementedTODO
body_interfacesImplementedImplementedTODO
definition_identityImplementedTODO
external_fact_queriesImplementedTODO
external_identityImplementedTODO
kind_wrappersImplementedImplementedTODO
local_identityImplementedImplementedTODO
crates.sage_ir.types (27)16 Implemented12 TODO13 Implemented27 TODO
crates.sage_ir.types.aliases (2)1 Implemented1 TODO1 Implemented2 TODO
identityImplementedImplementedTODO
revelationTODOTODO
crates.sage_ir.types.binder (1)1 Implemented1 TODO1 Implemented1 TODO
owner_parametersImplementedTODOImplementedTODO
crates.sage_ir.types.body (13)4 Implemented9 TODO3 Implemented13 TODO
awaitTODOTODO
closuresTODOTODO
conditional_patternsTODOTODO
coroutinesTODOTODO
diagnosed_recoveryImplementedImplementedTODO
elaboratedTODOImplementedTODO
for_iterationTODOTODO
indexingTODOTODO
macro_expansionTODOTODO
no_inferenceImplementedImplementedTODO
resolved_referencesImplementedTODO
try_residualTODOTODO
typed_provenanceImplementedTODO
crates.sage_ir.types.calls (2)1 Implemented1 TODO1 Implemented2 TODO
dispatch_familiesTODOTODO
selected_semanticsImplementedImplementedTODO
crates.sage_ir.types.lifetimes (2)2 Implemented2 Implemented2 TODO
dummyImplementedImplementedTODO
unchecked_borrowsImplementedImplementedTODO
crates.sage_ir.types.operators (2)2 Implemented1 Implemented2 TODO
lazy_control_flowImplementedTODO
trait_callsImplementedImplementedTODO
scoped_identitiesImplementedTODO
crates.sage_ir.types.spans (4)4 Implemented4 Implemented4 TODO
generated_identityImplementedImplementedTODO
item_originImplementedImplementedTODO
offset_reuseImplementedImplementedTODO
relative_compositionImplementedImplementedTODO
crates.sage_oracle_harness (4)4 Implemented2 TODO1 Implemented4 TODO
crates.sage_oracle_harness.crate (4)4 Implemented2 TODO1 Implemented4 TODO
deterministic_emissionImplementedTODO
exact_comparisonImplementedTODOImplementedTODO
fixed_projectionImplementedTODO
independent_coverageImplementedTODOTODO
crates.sage_stash (5)5 Implemented5 Implemented
crates.sage_stash.storage (5)5 Implemented5 Implemented
handle_ownershipImplementedImplemented
immutable_entriesImplementedImplemented
query_valueImplementedImplemented
rooted_equalityImplementedImplemented
typed_interningImplementedImplemented
crates.sage_test_harness (25)25 Implemented25 Implemented
crates.sage_test_harness.compile_tests (25)25 Implemented25 Implemented
annotation_validationImplementedImplemented
blessing_gateImplementedImplemented
callsite_updatesImplementedImplemented
checking_scopeImplementedImplemented
compiler_conditionsImplementedImplemented
completed_typesImplementedImplemented
coordinatesImplementedImplemented
dependenciesImplementedImplemented
diagnostic_countsImplementedImplemented
diagnostic_locationsImplementedImplemented
editionImplementedImplemented
fixturesImplementedImplemented
grouped_observationsImplementedImplemented
invocationImplementedImplemented
production_executionImplementedImplemented
project_isolationImplementedImplemented
query_captureImplementedImplemented
query_projectionImplementedImplemented
renderingImplementedImplemented
resolved_symbolsImplementedImplemented
review_visibilityImplementedImplemented
rustc_executionImplementedImplemented
rustc_lintsImplementedImplemented
starting_expressionsImplementedImplemented
target_lineImplementedImplemented