From 0fce1be73350a76169bff26e13de84ecd9adee3d Mon Sep 17 00:00:00 2001 From: Jarod Castillo <43973221+Smotto@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:28:53 -0800 Subject: [PATCH] psi: admit shared scalar recasts of fields and borrowed scalars Shared scalar representation recasts of record fields and borrowed scalars (such as `@cell.other as @i8` and `byte as @i8`) now check, run in Psi, and agree with native Windows x86_64 execution. Previously, the compiler refused every such recast during descriptor replay or returned-reference analysis, and native code generation encoded the source scalar's storage codec rather than the target view's codec. Three gaps in the shared representation-view path caused these failures: - In `locations.rs` (`descriptor_location_with`, `view_element_descriptor_prefix`, `resolved_path_with`, and `resolved_tip_with`), walking a `RepresentationView` segment required a preceding structural type declaration, which failed whenever the prefix ended at an inline scalar field. Handling `RepresentationView` before requiring a structural declaration (matching `primitive_place.rs` while still rejecting case namespaces, opaque types, references, and atomic cells) preserves the descriptor's origin account. - In `descriptor_regions.rs` (`append_projection` and `reference_sources_for_leaves`), returned reference origins did not admit `StructuralPathSegment::RepresentationView`, causing machines returning `@cell.other as @i8` or `byte as @i8` to fail returned-origin construction. - In `instruction_selection/selection/inputs.rs`, `EstablishReference` stored `storage.stored_scalar` (for example `u8`, unsigned) as the scalar reference's runtime codec instead of the presented `semantic_scalar` (`i8`, signed) for same-width recasts, causing `LoadEncodedScalar` on x86_64 to zero-extend `0xFF` to `255` instead of sign-extending it to `-1`. Unproved recasts to targets with invalid bit patterns (such as `@cell.other as @bool` or `byte as @bool`) remain refused, and competing writes while a recast view is live still reject. Updated `representation_views::scalar_reference_recasts_keep_their_backing_and_presented_fields` (replacing its temporary refusal assertion with acceptance, Psi execution, and competing-write rejection), added `shared_scalar_recasts_of_fields_and_borrowed_scalars_read_and_return_views` with negative twins, added `shared_scalar_recasts_of_fields_and_borrowed_scalars_agree_natively_and_in_psi` in `domain_access_field_observations.rs`, and removed the resolved sentences from `TASKS.md`. Gate: RC-SOURCE-SEMANTICS | Shared scalar representation recasts of fields and borrowed scalars check, run in Psi, and agree natively on Windows x86_64 Spec: wiki/spec/layouts/recasts.md#shared-and-mutable-views Proof: mbx test -p terminal-semantics --lib (332 passed), mbx test -p lowered-program-to-checked-program --lib representation_views (11 passed, updated scalar_reference_recasts_keep_their_backing_and_presented_fields from temporary refusal check to acceptance + Psi execution), mbx test -p omega --test domain_access_field_observations shared_scalar_recasts_of_fields_and_borrowed_scalars_agree_natively_and_in_psi (passed, native Windows x86_64 + Psi), mbx clippy --no-deps on touched crates, mbx xtask fmt --check --base origin/main, mbx xtask check-rules, mbx xtask check-boundary | clean (unrelated pre-existing errors in omega tests data_layout_queries.rs and build_dependency_provider_layouts.rs on --all-targets; domain_access_field_observations clean) Agent: Antigravity | Model: unknown | Effort: high | Tokens: 10.81M in (10.51M cached), 43.5k out | Steps: 62 | Time: 36m41s | Steers: 0 --- TASKS.md | 2 +- .../tests/domain_access_field_observations.rs | 45 +++++ .../instruction_selection/selection/inputs.rs | 13 +- .../descriptor_lifetimes/locations.rs | 167 ++++++++++++------ .../reference_origins/descriptor_regions.rs | 4 +- .../src/tests/representation_views.rs | 115 ++++++++++-- 6 files changed, 273 insertions(+), 73 deletions(-) diff --git a/TASKS.md b/TASKS.md index 33f6e8c992e2..638e712d74a0 100644 --- a/TASKS.md +++ b/TASKS.md @@ -33,7 +33,7 @@ Find Rust owners in the [compiler map](source-rust/README.md#where-code-belongs) - **CANONICALIZE-SCALAR-RANGE-CONTRACTS.** Complete [scalar range contracts](wiki/spec/language/domains.md#declaration-and-membership). - Prove field and case bounds at construction, on writes, on return of a field loan and after array updates. - - Check and lower scalar-field loans across case fields, recursive records/references, calls, joins, and [recasts](wiki/spec/layouts/recasts.md). Every shared scalar recast of a field or borrowed scalar is refused today, although [recasts.md](wiki/spec/layouts/recasts.md#shared-and-mutable-views) admits each (every `u8` representation is a valid `i8`): reading `let seen: @i8 = @cell.other as @i8; $seen` ("reference descriptor has no current origin account", also on [crash_entry_boolean_view/field](samples/cli/facts/crash_entry_boolean_view/field/main.omg) and `/local`), returning `@cell.other as @i8` from `machine view(cell: @Cell) -> @i8` ("call reference result has no complete contents inventory"), and returning `byte as @i8` for `byte: @u8` ("call dynamic returned view has an unsupported backing projection"). Returning `@cell.other` uncast runs. + - Check and lower scalar-field loans across case fields, recursive records/references, calls, joins, and proof-gated [recasts](wiki/spec/layouts/recasts.md) such as [crash_entry_boolean_view](samples/cli/facts/crash_entry_boolean_view/field/main.omg). - Qualify migrated [range-contract customers](wiki/drafts/designs/range_suffix_migration.md) with their original results, including the filesystem programs under **FILESYSTEM-PLATFORM-SERVICES**. - **STATIC-MACHINE-MIGRATION.** (covers **NAMED-IMPLEMENTATION-CONFORMANCE-MIGRATION**, **TRAIT-IMPLEMENTATION-SOURCE-MIGRATION**) Finish static machines, implementations, `dropped by` and [callback reach](wiki/drafts/designs/deferred_callback_reach.md). diff --git a/source-rust/application/tests/domain_access_field_observations.rs b/source-rust/application/tests/domain_access_field_observations.rs index 5b228bf00bd1..50b448bb0e46 100644 --- a/source-rust/application/tests/domain_access_field_observations.rs +++ b/source-rust/application/tests/domain_access_field_observations.rs @@ -135,3 +135,48 @@ machine main() crashes Trap { } "#); } + +#[test] +fn shared_scalar_recasts_of_fields_and_borrowed_scalars_agree_natively_and_in_psi() { + program::assert_silent_return( + r#"data Cell [copy] { head: u8; other: u8; } +machine read_field(cell: @Cell) -> i8 { + let seen: @i8 = @cell.other as @i8; + $seen +} +machine view_field(cell: @Cell) -> @i8 { + @cell.other as @i8 +} +machine view_byte(byte: @u8) -> @i8 { + byte as @i8 +} +machine flag_byte(flag: @bool) -> u8 { + let seen: @u8 = flag as @u8; + $seen +} +machine main() crashes Trap { + let cell: Cell = Cell { head: 1u8, other: 255u8 }; + let local_seen: @i8 = @cell.other as @i8; + let from_field: @i8 = view_field(@cell); + let byte: u8 = 254u8; + let from_byte: @i8 = view_byte(@byte); + let flag: bool = true; + let word_bits: u32 = 1065353216u32; + let as_float: @f32 = @word_bits as @f32; + let one: f32 = $as_float; + let back_bits: @u32 = @one as @u32; + transition read_field(@cell) == -1i8 + && $local_seen == -1i8 + && $from_field == -1i8 + && $from_byte == -2i8 + && flag_byte(@flag) == 1u8 + && $back_bits == 1065353216u32 { + true -> done(), + false -> wrong() + } + machine done() {} + machine wrong() { crash Trap; } +} +"#, + ); +} diff --git a/source-rust/subsystems/compiler/psi-to-native/pipeline/05_target-operations-to-selected-instructions/src/instruction_selection/selection/inputs.rs b/source-rust/subsystems/compiler/psi-to-native/pipeline/05_target-operations-to-selected-instructions/src/instruction_selection/selection/inputs.rs index 2810d6c39e8f..5af9e4375cae 100644 --- a/source-rust/subsystems/compiler/psi-to-native/pipeline/05_target-operations-to-selected-instructions/src/instruction_selection/selection/inputs.rs +++ b/source-rust/subsystems/compiler/psi-to-native/pipeline/05_target-operations-to-selected-instructions/src/instruction_selection/selection/inputs.rs @@ -4295,9 +4295,16 @@ pub(crate) mod reference_input { load_pointer |= placed.is_some_and(|backing| backing.resident_source().is_some()); let load_codec = storage.is_none() && semantic_scalar.is_some() && load_pointer; let codec = match storage { - Some(storage) => storage - .stored_scalar - .and_then(runtime_abi::ScalarStorageCodec::from_scalar), + Some(storage) => storage.stored_scalar.and_then(|stored| { + // A same-width scalar representation view reinterprets the + // backing bits under the presented scalar's codec (for + // example, sign-extending `u8` bits read through `@i8`). + let presented = semantic_scalar.filter(|logical| { + terminal_semantics::reference_storage_byte_width(stored) + == terminal_semantics::reference_storage_byte_width(*logical) + }); + runtime_abi::ScalarStorageCodec::from_scalar(presented.unwrap_or(stored)) + }), None if !load_codec && semantic_scalar.is_some() => { projected_scalar_codec(projection_root, projection_path, declarations) } diff --git a/source-rust/subsystems/compiler/psi/semantics/src/descriptors/descriptor_lifetimes/locations.rs b/source-rust/subsystems/compiler/psi/semantics/src/descriptors/descriptor_lifetimes/locations.rs index ba81f80f9da4..cfc5ee3b733f 100644 --- a/source-rust/subsystems/compiler/psi/semantics/src/descriptors/descriptor_lifetimes/locations.rs +++ b/source-rust/subsystems/compiler/psi/semantics/src/descriptors/descriptor_lifetimes/locations.rs @@ -286,22 +286,38 @@ fn descriptor_location_with<'a, L: crate::StructuralDeclarations<'a>>( let mut tip = Some(root_type); let mut case_fields = None; for segment in path { + if let StructuralPathSegment::RepresentationView { + structural_type, + stored_scalar, + } = segment + { + if case_fields.is_some() + || tip.is_some_and(|root| { + types.unique(root).is_none_or(|declaration| { + matches!( + declaration.shape, + StructuralTypeShape::Opaque + | StructuralTypeShape::Reference { .. } + | StructuralTypeShape::AtomicCell(_) + ) + }) + }) + { + return None; + } + tip = Some( + types + .representation_view(*structural_type, *stored_scalar)? + .id, + ); + result.path.push(DescriptorPathSegment::RepresentationView { + structural_type: *structural_type, + stored_scalar: *stored_scalar, + }); + continue; + } let declaration = types.unique(tip?)?; let canonical = match segment { - StructuralPathSegment::RepresentationView { - structural_type, - stored_scalar, - } if case_fields.is_none() => { - tip = Some( - types - .representation_view(*structural_type, *stored_scalar)? - .id, - ); - DescriptorPathSegment::RepresentationView { - structural_type: *structural_type, - stored_scalar: *stored_scalar, - } - } StructuralPathSegment::Referent if case_fields.is_none() => { let StructuralTypeShape::Reference { referent, .. } = declaration.shape else { @@ -451,6 +467,37 @@ pub fn view_element_descriptor_prefix( let mut case_fields = None; let mut element = None; for (position, segment) in path.iter().enumerate() { + if let DescriptorPathSegment::RepresentationView { + structural_type, + stored_scalar, + } = segment + { + if case_fields.is_some() { + return Err("a loan path has no exact typed projection"); + } + if let Some(root) = tip { + let owner = declaration(types, root) + .ok_or("a loan path has no exact structural declaration")?; + if matches!( + owner.shape, + StructuralTypeShape::Opaque + | StructuralTypeShape::Reference { .. } + | StructuralTypeShape::AtomicCell(_) + ) { + return Err("a loan path has no exact typed projection"); + } + } + tip = Some( + crate::representation_view_declaration( + types.iter(), + *structural_type, + *stored_scalar, + ) + .ok_or("a loan presentation has no exact declaration")? + .id, + ); + continue; + } let owner = declaration(types, tip.ok_or("a loan path crosses a scalar leaf")?) .ok_or("a loan path has no exact structural declaration")?; if case_fields.is_none() @@ -510,18 +557,6 @@ pub fn view_element_descriptor_prefix( _ => return Err("a loan index has no array or view owner"), } } - DescriptorPathSegment::RepresentationView { - structural_type, - stored_scalar, - } if case_fields.is_none() => Some( - crate::representation_view_declaration( - types.iter(), - *structural_type, - *stored_scalar, - ) - .ok_or("a loan presentation has no exact declaration")? - .id, - ), // Extent observations name the descriptor's storage, not // its separately borrowed bytes. DescriptorPathSegment::Extent => return Ok(element), @@ -572,22 +607,38 @@ fn resolved_path_with<'a, L: crate::StructuralDeclarations<'a>>( let mut tip = Some(root_type); let mut case_fields = None; for segment in path { + if let DescriptorPathSegment::RepresentationView { + structural_type, + stored_scalar, + } = segment + { + if case_fields.is_some() + || tip.is_some_and(|root| { + types.unique(root).is_none_or(|declaration| { + matches!( + declaration.shape, + StructuralTypeShape::Opaque + | StructuralTypeShape::Reference { .. } + | StructuralTypeShape::AtomicCell(_) + ) + }) + }) + { + return None; + } + tip = Some( + types + .representation_view(*structural_type, *stored_scalar)? + .id, + ); + result.push(StructuralPathSegment::RepresentationView { + structural_type: *structural_type, + stored_scalar: *stored_scalar, + }); + continue; + } let declaration = types.unique(tip?)?; result.push(match segment { - DescriptorPathSegment::RepresentationView { - structural_type, - stored_scalar, - } if case_fields.is_none() => { - tip = Some( - types - .representation_view(*structural_type, *stored_scalar)? - .id, - ); - StructuralPathSegment::RepresentationView { - structural_type: *structural_type, - stored_scalar: *stored_scalar, - } - } DescriptorPathSegment::Referent if case_fields.is_none() => { let StructuralTypeShape::Reference { referent, .. } = declaration.shape else { @@ -662,18 +713,34 @@ fn resolved_tip_with<'a, L: crate::StructuralDeclarations<'a>>( let mut tip = Some(root_type); let mut case_fields = None; for (index, segment) in path.iter().enumerate() { + if let DescriptorPathSegment::RepresentationView { + structural_type, + stored_scalar, + } = segment + { + if case_fields.is_some() + || tip.is_some_and(|root| { + types.unique(root).is_none_or(|declaration| { + matches!( + declaration.shape, + StructuralTypeShape::Opaque + | StructuralTypeShape::Reference { .. } + | StructuralTypeShape::AtomicCell(_) + ) + }) + }) + { + return None; + } + tip = Some( + types + .representation_view(*structural_type, *stored_scalar)? + .id, + ); + continue; + } let declaration = types.unique(tip?)?; match segment { - DescriptorPathSegment::RepresentationView { - structural_type, - stored_scalar, - } if case_fields.is_none() => { - tip = Some( - types - .representation_view(*structural_type, *stored_scalar)? - .id, - ); - } DescriptorPathSegment::Referent if case_fields.is_none() => { let StructuralTypeShape::Reference { referent, .. } = declaration.shape else { return None; diff --git a/source-rust/subsystems/compiler/psi/semantics/src/references/reference_origins/descriptor_regions.rs b/source-rust/subsystems/compiler/psi/semantics/src/references/reference_origins/descriptor_regions.rs index 65cca6ab9274..fd17c0a0cc5e 100644 --- a/source-rust/subsystems/compiler/psi/semantics/src/references/reference_origins/descriptor_regions.rs +++ b/source-rust/subsystems/compiler/psi/semantics/src/references/reference_origins/descriptor_regions.rs @@ -384,6 +384,7 @@ fn reference_sources_for_leaves( | StructuralPathSegment::Case(_) | StructuralPathSegment::FixedIndex(_) | StructuralPathSegment::Referent + | StructuralPathSegment::RepresentationView { .. } ) ) }) { @@ -533,7 +534,8 @@ fn append_projection( StructuralPathSegment::Field(_) | StructuralPathSegment::Case(_) | StructuralPathSegment::FixedIndex(_) - | StructuralPathSegment::Referent => { + | StructuralPathSegment::Referent + | StructuralPathSegment::RepresentationView { .. } => { path.push(ReferenceOriginProjection::Exact(segment.clone())) } _ => return Err("dynamic returned view has an unsupported backing projection"), diff --git a/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/tests/representation_views.rs b/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/tests/representation_views.rs index 09ea8d9edf2c..43beb52f78f4 100644 --- a/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/tests/representation_views.rs +++ b/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/tests/representation_views.rs @@ -75,18 +75,16 @@ machine entry() crashes Trap { terminal_codec::TerminalPublication::Invocation, )) }; - // `signed` and `unsigned` return the referenced scalar, which - // `wiki/spec/language/expressions.md`, "Explicit dereference", requires - // to be written `$value`. With that spelling the storage-flow replay - // cannot yet account for the origin of `scalar` in `entry`, so the - // program is refused rather than accepted. `TASKS.md`, - // STATE-LOCAL-VALUE-FRONTIER, owns accepting it and restoring the - // execution check this test made before. - let verdict = judge_source(source); - assert!( - matches!(&verdict, Ok(RouteVerdict::FallBack(refusal)) - if refusal.detail == "reference descriptor has no current origin account in machine `entry`"), - "same-width views are refused at the origin of `scalar` until the replay accounts for it: {verdict:?}" + let accepted = match judge_source(source) { + Ok(RouteVerdict::Accepted(accepted)) => accepted, + verdict => panic!("same-width scalar recasts must be accepted: {verdict:?}"), + }; + accepted.publish_invocation().unwrap(); + assert_eq!( + super::stored_references::run(source), + Ok(terminal_interpreter::TerminalExecutionStatus::Complete( + terminal_interpreter::TerminalExecutionResult::Unit + )) ); // A shared representation still freezes the original storage. Changing @@ -95,17 +93,98 @@ machine entry() crashes Trap { "let value: @i64 = @bits as @i64;", "let value: @i64 = @bits as @i64; overwrite(@mutable bits);", ); - // Until the replay accounts for `scalar`, the same refusal reaches this - // twin before its write conflict is judged; it must never be accepted. let refused = judge_source(&competing); assert!( - matches!(&refused, Ok(RouteVerdict::Rejected { conflicts, .. }) if !conflicts.is_empty()) - || matches!(&refused, Ok(RouteVerdict::FallBack(refusal)) - if refusal.detail == "reference descriptor has no current origin account in machine `entry`"), - "{refused:?}" + matches!(&refused, Ok(RouteVerdict::Rejected { conflicts, .. }) if !conflicts.is_empty()), + "a competing write while a shared scalar recast is live must reject: {refused:?}" ); } +#[test] +fn shared_scalar_recasts_of_fields_and_borrowed_scalars_read_and_return_views() { + let source = r#" +data Cell [copy] { head: u8; other: u8; } +machine read_field(cell: @Cell) -> i8 { + let seen: @i8 = @cell.other as @i8; + $seen +} +machine view_field(cell: @Cell) -> @i8 { + @cell.other as @i8 +} +machine view_byte(byte: @u8) -> @i8 { + byte as @i8 +} +machine flag_byte(flag: @bool) -> u8 { + let seen: @u8 = flag as @u8; + $seen +} +machine entry() crashes Trap { + let cell: Cell = Cell { head: 1u8, other: 255u8 }; + let local_seen: @i8 = @cell.other as @i8; + let from_field: @i8 = view_field(@cell); + let byte: u8 = 254u8; + let from_byte: @i8 = view_byte(@byte); + let flag: bool = true; + transition read_field(@cell) == -1i8 + && $local_seen == -1i8 + && $from_field == -1i8 + && $from_byte == -2i8 + && flag_byte(@flag) == 1u8 { + true -> done(), + false -> bad() + } + machine done() {} + machine bad() { crash Trap; } +} +"#; + assert_eq!( + super::stored_references::run(source), + Ok(terminal_interpreter::TerminalExecutionStatus::Complete( + terminal_interpreter::TerminalExecutionResult::Unit + )) + ); + + // Negative twins: every u8 representation is not a valid bool, so an + // unproved `@bool` recast of a `u8` field or borrowed `u8` must be refused. + let unproved_field_bool = r#" +data Cell [copy] { other: u8; } +machine view_bool(cell: @Cell) -> bool { + let seen: @bool = @cell.other as @bool; + $seen +} +"#; + assert_ne!( + verdict(unproved_field_bool), + "accepted", + "an unproved @u8 -> @bool field recast must never be accepted" + ); + + let unproved_byte_bool = r#" +machine view_bool(byte: @u8) -> @bool { + byte as @bool +} +"#; + assert_ne!( + verdict(unproved_byte_bool), + "accepted", + "an unproved @u8 -> @bool parameter recast must never be accepted" + ); + + // Negative twin: a returned scalar recast still freezes its source storage. + let competing = r#" +data Cell [copy] { head: u8; other: u8; } +machine view_field(cell: @Cell) -> @i8 { @cell.other as @i8 } +machine clobber(cell: @mutable Cell) { cell.other = 0u8; } +machine entry() -> i8 { + let mutable cell: Cell = Cell { head: 1u8, other: 255u8 }; + let view: @i8 = view_field(@cell); + clobber(@mutable cell); + $view +} +"#; + assert_eq!(verdict(competing), "rejected"); +} + #[test] fn a_shared_call_can_retain_a_domain_of_the_actual_place() { let source = |domains: &str| {