From dbb13bd149cb59cfe2e23c58237017390d0e2ad4 Mon Sep 17 00:00:00 2001 From: Jarod Castillo <43973221+Smotto@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:33:39 -0800 Subject: [PATCH] psi: support target-dependent constant array extents Programs can now use a constant initialized from a target layout query, such as `const SIZE: u64 = size_of::()`, as a fixed-array length across signatures, indexing, `.length` queries, array literals, and `requires` clauses. Previously, the source compiler deferred evaluating such constants until target closure, but the array-extent reader refused any named constant without an already-evaluated integer value. When a fixed-array extent names a constant marked `pending_target_observation`, stage 05 now lowers that extent to `ArrayExtent::Application` using the constant's retained scalar evaluation and carries the application through `CollectionExtent::Application`. Indexing, `.length` reads, zero-initialized locals, and contract clauses treat the application extent as a symbolic `ScalarTerm::Application`, so the lowered-form checker enforces bounds like `i < SIZE` without weakening any check. Array literals targeting an application-sized array retain a pending `ScalarPredicateCondition` asserting that the literal count equals the closed target extent, which deployment closure verifies before handing the closed literal geometry to Psi and native code. The Psi interpreter also now preserves `scalar_geometry` when a module has scalar applications without authored `target_layouts`. Added focused positive and negative twin tests in `source-rust/application/tests/computed_array_extent.rs` covering pass-through, default initialization, `.length`, guarded indexing, array literals, unproved indexing, out-of-bounds access, and mismatched literal length on both Psi and native `windows_x86_64`, and removed the completed bullet from `TASKS.md`. Gate: RC-SOURCE-SEMANTICS | target-dependent layout constants work as fixed-array extents through checking, Psi, and native execution Spec: wiki/spec/language/evaluation.md#target-dependent-applications Proof: mbx test -p omega --test computed_array_extent (7 passed, native/Psi agreement on windows_x86_64), mbx test -p lowered-program-to-checked-program --lib array_lengths (31 passed), mbx test -p terminal-wire --lib obligation_evidence (23 passed), mbx xtask check-boundary, mbx xtask check-rules, mbx clippy --no-deps on touched crates | clean (pre-existing unrelated clippy lint in untouched terminal-interpreter/instructions/execution.rs and test compile error in untouched build_dependency_provider_layouts.rs) Agent: Antigravity | Model: unknown | Effort: high | Tokens: 20.25M in (19.72M cached), 66.3k out | Steps: 88 | Time: 42m24s | Steers: 0 --- TASKS.md | 2 - .../tests/computed_array_extent.rs | 101 ++++++++++++++++++ .../src/target_lowering/scalar.rs | 10 +- .../selection/views_and_bytes.rs | 3 +- .../src/structural_inputs.rs | 7 +- .../wire/src/foundation_validation.rs | 47 ++++++-- .../artifact/wire/src/obligation_evidence.rs | 19 +++- .../descriptor_results/scalar_captures.rs | 25 +++-- .../descriptor_results/terminal_flow.rs | 39 ++++--- .../compiler/psi/semantics/src/lib.rs | 8 +- .../semantics/src/scalar_qualifications.rs | 24 +++-- .../psi/semantics/src/scalar_target_ranges.rs | 2 +- .../src/scalar_target_ranges/calls.rs | 95 ++++++++++++++++ .../psi/semantics/src/scalars/scalar_array.rs | 22 ++++ .../src/storage/collection_backing.rs | 8 ++ .../src/structural/primitive_place.rs | 24 ++++- .../src/structural_qualifications.rs | 8 +- .../src/lower/places.rs | 27 ++++- .../src/read/arrays.rs | 49 +++++++-- .../src/read/bytes.rs | 31 ++++-- .../src/read/clause_terms.rs | 52 ++++++++- .../src/read/constant_values.rs | 11 ++ .../src/read/contracts.rs | 1 + .../src/storage/places.rs | 11 +- .../src/storage/places/byte_views.rs | 33 +++++- .../src/storage/places/leaves.rs | 4 +- .../src/storage/places/log.rs | 23 ++++ .../src/verdict.rs | 34 ++++++ .../interpreter/embedding/program.rs | 8 +- .../interpreter/memory/bytes_and_views.rs | 3 +- 30 files changed, 644 insertions(+), 87 deletions(-) diff --git a/TASKS.md b/TASKS.md index 33f6e8c992e2..27b9935daa7c 100644 --- a/TASKS.md +++ b/TASKS.md @@ -20,8 +20,6 @@ Find Rust owners in the [compiler map](source-rust/README.md#where-code-belongs) - Carry the checked bounds of `size_of` and `align_of` through arithmetic on them and validate them at installation. Exercise [record geometry](samples/cli/probes/record_geometry), scalar and generic carriers, and the value form `align_of(view)`. - - Give an array extent that names a constant read from the target's layout the length each deployment closes, as in `const SIZE: u64 = size_of::(); machine sized(a: [u8; SIZE]) -> [u8; SIZE] { a }` ([evaluation.md](wiki/spec/language/evaluation.md#target-dependent-applications): an observation "can occupy any position available to an equivalent ordinary constant, including array length"). The [source driver](source-rust/subsystems/compiler/source-to-psi/driver/compile_time_invocations/constants/initializers.rs) leaves such a scalar constant unevaluated on purpose, and a scalar read of `SIZE` lowers to its retained application and runs, but the [array extent reader](source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/arrays.rs) refuses the extent ("array extent that names a constant with no evaluated array length"), under `omega --check` and standalone application execution alike. Lowering the extent to that application (`ArrayExtent::Application`) next stops at element reads and array literals, which accept only literal, const-parameter and stored-length extents ("index or literal of a non-array type"), so the application extent must also reach `CollectionExtent`, the checker and native layout. - - Require [type annotations on named locals](wiki/spec/language/ownership.md#local-type-annotations) in both source compilers. Migrate authored sources, positive examples and fixtures alongside enforcement. Reject a missing annotation on both an ordinary and a mutable local even with a typed initializer. Accept a typed copy retaining its domain and reject the same destination given a plain value. Preserve constant typing and generic argument inference. - Check a recursive walk that hands itself a smaller view, `clear_all(@mutable items[1..])` from a `head(items)` state under `terminates by items -> Slice::Length` ([termination.md](wiki/spec/language/termination.md#ranked-callees-on-projected-receivers): a traversal "may carry a changing node reference as an ordinary cursor parameter"). `core::for_each` and five walks in the [Hollow engine](samples/gui/dungeon_crawler/README.md) use this shape, so the sample builds on no target. Acceptance: Hollow's smoke test prints `PASS: dungeon campaign, collision, combat, pixels` with exit 0 on native and Psi for `windows_x86_64`, then the window opens, draws and takes keys on Windows. Branch `work/samples-hollow-windows-wip` (97742e0a411b, rebased on 02e751659eb5) holds the untested Windows window providers, the `tmp-repro/` programs and three `EXPERIMENT(hollow)` relaxations with no negative twins. Under them the shared walk passes the checker; its native build now stops at `SelectedOptimization(Liveness(Analysis(FunctionMismatch ..)))`, which clean main also gives a non-recursive store through a mutable view. The mutating walk and `for_each` stop at "call reference formation overlaps another activation of itself" in [reference results](source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/reference_results.rs), where the loop's one Loan row stands for every pass. Next: admit an exclusive reborrow only when its source is the previous pass's own result (here and in [checker loans](source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/places/loans.rs)), refuse an independent exclusive borrow kept across passes, and pin both with a positive/negative pair. diff --git a/source-rust/application/tests/computed_array_extent.rs b/source-rust/application/tests/computed_array_extent.rs index 9475ec981914..b4c79761fb8b 100644 --- a/source-rust/application/tests/computed_array_extent.rs +++ b/source-rust/application/tests/computed_array_extent.rs @@ -62,3 +62,104 @@ fn a_literal_initializer_supplies_its_declared_array_length() { let expected = std::fs::read_to_string(fixture("fail").join("expected.txt")).unwrap(); assert!(report.contains(expected.trim_end()), "{report}"); } + +fn target_const_array_program(literal: &str, last_index: u64) -> String { + format!( + r#"const SIZE: u64 = size_of::(); + +machine sized(a: [u8; SIZE]) -> [u8; SIZE] {{ a }} + +machine read_at(a: @[u8; SIZE], i: u64) -> u8 requires i < SIZE {{ + a[i] +}} + +machine make_literal() -> [u8; SIZE] {{ + {literal} +}} + +machine main() crashes Trap {{ + let zeroed: [u8; SIZE]; + let items: [u8; SIZE] = sized(make_literal()); + transition zeroed.length == SIZE && 0u64 < SIZE && {last_index}u64 < SIZE {{ + true -> check(@items), + false -> failed() + }} + machine check(items: @[u8; SIZE]) crashes Trap + requires 0u64 < SIZE && {last_index}u64 < SIZE + {{ + transition read_at(items, 0u64) == 10u8 && read_at(items, {last_index}u64) == 80u8 {{ + true -> done(), + false -> failed() + }} + }} + machine done() {{}} + machine failed() crashes Trap {{ crash Trap; }} +}} +"# + ) +} + +#[test] +fn target_layout_const_array_extent_checks_and_runs_on_native_and_psi() { + let source = target_const_array_program("[10u8, 20u8, 30u8, 40u8, 50u8, 60u8, 70u8, 80u8]", 7); + let (check_output, check_report) = invoke(&source, &["--check"]); + assert!(check_output.status.success(), "{check_report}"); + program::assert_silent_return(&source); +} + +#[test] +fn target_layout_const_array_extent_refuses_unproved_index() { + let source = r#"const SIZE: u64 = size_of::(); + +machine read_at(a: @[u8; SIZE], i: u64) -> u8 { + a[i] +} + +machine main() { + let zeroed: [u8; SIZE]; + let _: u8 = read_at(@zeroed, 0u64); +} +"#; + let (output, report) = invoke(source, &["--check"]); + assert!(!output.status.success(), "{report}"); + assert!( + report.contains("index") || report.contains("bounds") || report.contains("cannot prove"), + "expected index-bound refusal:\n{report}" + ); +} + +#[test] +fn target_layout_const_array_extent_refuses_out_of_bounds_index_at_closure() { + let source = target_const_array_program("[10u8, 20u8, 30u8, 40u8, 50u8, 60u8, 70u8, 80u8]", 8); + let (check_output, check_report) = invoke(&source, &["--check"]); + assert!(!check_output.status.success(), "{check_report}"); + assert!( + check_report.contains("scalar predicate is false"), + "expected target-closure predicate refusal:\n{check_report}" + ); + for engine in ["psi", "native"] { + let (output, report) = invoke(&source, &["run", "--engine", engine]); + assert!( + !output.status.success(), + "expected {engine} refusal for out-of-bounds index:\n{report}" + ); + } +} + +#[test] +fn target_layout_const_array_extent_refuses_mismatched_literal_length_at_closure() { + let source = target_const_array_program("[10u8, 20u8, 30u8]", 2); + let (check_output, check_report) = invoke(&source, &["--check"]); + assert!(!check_output.status.success(), "{check_report}"); + assert!( + check_report.contains("array literal length (3) matches target-dependent extent"), + "expected literal-extent mismatch refusal:\n{check_report}" + ); + for engine in ["psi", "native"] { + let (output, report) = invoke(&source, &["run", "--engine", engine]); + assert!( + !output.status.success(), + "expected {engine} refusal for mismatched literal length:\n{report}" + ); + } +} diff --git a/source-rust/subsystems/compiler/psi-to-native/pipeline/04_abstract-operations-to-target-operations/src/target_lowering/scalar.rs b/source-rust/subsystems/compiler/psi-to-native/pipeline/04_abstract-operations-to-target-operations/src/target_lowering/scalar.rs index b38d1435d9ee..88aa28cae21a 100644 --- a/source-rust/subsystems/compiler/psi-to-native/pipeline/04_abstract-operations-to-target-operations/src/target_lowering/scalar.rs +++ b/source-rust/subsystems/compiler/psi-to-native/pipeline/04_abstract-operations-to-target-operations/src/target_lowering/scalar.rs @@ -1364,7 +1364,8 @@ pub(crate) mod element_views { .and_then(|span| span.checked_add(8)) } terminal_semantics::CollectionExtent::StoredLength - | terminal_semantics::CollectionExtent::Parameter { .. } => None, + | terminal_semantics::CollectionExtent::Parameter { .. } + | terminal_semantics::CollectionExtent::Application(_) => None, } }) != Some(u64::from(collection.byte_size)) } @@ -1373,6 +1374,7 @@ pub(crate) mod element_views { terminal_semantics::CollectionExtent::StoredLength => 16, terminal_semantics::CollectionExtent::Fixed(_) => 8, terminal_semantics::CollectionExtent::Parameter { .. } + | terminal_semantics::CollectionExtent::Application(_) | terminal_semantics::CollectionExtent::LiveLength { .. } => { return Err(invalid()); } @@ -1415,7 +1417,11 @@ pub(crate) mod element_views { (None, terminal_semantics::CollectionExtent::LiveLength { .. }) => { (8, target_operations::TargetViewExtent::LiveLength) } - (None, terminal_semantics::CollectionExtent::Parameter { .. }) => { + ( + None, + terminal_semantics::CollectionExtent::Parameter { .. } + | terminal_semantics::CollectionExtent::Application(_), + ) => { return Err(invalid()); } (None, terminal_semantics::CollectionExtent::StoredLength) => { diff --git a/source-rust/subsystems/compiler/psi-to-native/pipeline/05_target-operations-to-selected-instructions/src/instruction_selection/selection/views_and_bytes.rs b/source-rust/subsystems/compiler/psi-to-native/pipeline/05_target-operations-to-selected-instructions/src/instruction_selection/selection/views_and_bytes.rs index 31610db7f6db..9dcf1163fb93 100644 --- a/source-rust/subsystems/compiler/psi-to-native/pipeline/05_target-operations-to-selected-instructions/src/instruction_selection/selection/views_and_bytes.rs +++ b/source-rust/subsystems/compiler/psi-to-native/pipeline/05_target-operations-to-selected-instructions/src/instruction_selection/selection/views_and_bytes.rs @@ -1885,7 +1885,8 @@ pub(crate) mod element_establishment { return Err(invalid()); } let length = match element_count { - terminal_semantics::CollectionExtent::Parameter { .. } => return Err(invalid()), + terminal_semantics::CollectionExtent::Parameter { .. } + | terminal_semantics::CollectionExtent::Application(_) => return Err(invalid()), terminal_semantics::CollectionExtent::Fixed(length) => { constant(builder, row, 8, length)? } diff --git a/source-rust/subsystems/compiler/psi-to-native/representations/target-operations/legalized-operations/src/structural_inputs.rs b/source-rust/subsystems/compiler/psi-to-native/representations/target-operations/legalized-operations/src/structural_inputs.rs index 35fdc0f1aa51..ff06db8c9413 100644 --- a/source-rust/subsystems/compiler/psi-to-native/representations/target-operations/legalized-operations/src/structural_inputs.rs +++ b/source-rust/subsystems/compiler/psi-to-native/representations/target-operations/legalized-operations/src/structural_inputs.rs @@ -1239,6 +1239,7 @@ pub mod structural_reference_input { } terminal_semantics::CollectionExtent::StoredLength => {} terminal_semantics::CollectionExtent::Parameter { .. } + | terminal_semantics::CollectionExtent::Application(_) | terminal_semantics::CollectionExtent::LiveLength { .. } => return None, } representation_source_stride = Some(source_layout.size); @@ -1318,7 +1319,11 @@ pub mod structural_reference_input { length, terminal_semantics::CollectionExtent::Fixed(length), ), - (None, terminal_semantics::CollectionExtent::Parameter { .. }) => return None, + ( + None, + terminal_semantics::CollectionExtent::Parameter { .. } + | terminal_semantics::CollectionExtent::Application(_), + ) => return None, (None, terminal_semantics::CollectionExtent::StoredLength) => { (0, 0, terminal_semantics::CollectionExtent::StoredLength) } diff --git a/source-rust/subsystems/compiler/psi/artifact/wire/src/foundation_validation.rs b/source-rust/subsystems/compiler/psi/artifact/wire/src/foundation_validation.rs index 88dc402be951..eb5de2a463da 100644 --- a/source-rust/subsystems/compiler/psi/artifact/wire/src/foundation_validation.rs +++ b/source-rust/subsystems/compiler/psi/artifact/wire/src/foundation_validation.rs @@ -5015,6 +5015,20 @@ pub(crate) mod scalar_applications { ); } } + for expected in terminal_semantics::array_extent_literal_conditions(module, machine) + .map_err(CodecError::MalformedStructuralFoundation)? + { + let ScalarConditionSubject::Declaration(owner) = expected.subject else { + return malformed( + "array extent literal condition has no exact declaration owner", + ); + }; + if !pending.contains(&owner) || !conditions.predicates().contains(&expected) { + return malformed( + "array literal lost its exact pending target extent condition", + ); + } + } if !module.scalars.scalar_applications.declarations().is_empty() { let types = terminal_semantics::SortedValueTypes::new( super::proof_values(machine) @@ -10242,8 +10256,17 @@ pub(crate) mod value_foundations { |element| scalar_index.constant_value(element), ) || !super::is_op_result_place(machine, operation, result) - || scalar_array_leaf_shape(module.types.structural_types.iter(), result.structural_type) - .is_none_or(|(_, count)| u64::try_from(elements.len()).ok() != Some(count)) + || match scalar_array_leaf_shape( + module.types.structural_types.iter(), + result.structural_type, + ) { + Some((_, count)) => u64::try_from(elements.len()).ok() != Some(count), + None => terminal_semantics::scalar_array_application_leaf( + module.types.structural_types.iter(), + result.structural_type, + ) + .is_none(), + } { return malformed("scalar array establishment has an invalid result shape"); } @@ -10252,6 +10275,11 @@ pub(crate) mod value_foundations { result.structural_type, ) .is_some_and(|(leaf, count)| count != 0 && leaf.scalar_restriction.is_some()) + || terminal_semantics::scalar_array_application_leaf( + module.types.structural_types.iter(), + result.structural_type, + ) + .is_some_and(|(leaf, _)| !elements.is_empty() && leaf.scalar_restriction.is_some()) { return malformed("scalar array initializer lacks receiving restriction obligations"); } @@ -10718,11 +10746,16 @@ pub(crate) mod value_foundations { .shape; let element = match shape { StructuralTypeShape::FixedArray { element, length } => { - let Some(length) = length.literal() else { - return malformed("array construction requires a closed element count"); - }; - if u64::try_from(elements.len()).ok() != Some(length) { - return malformed("array element count differs"); + match length { + terminal_psi::ArrayExtent::Literal(length) => { + if u64::try_from(elements.len()).ok() != Some(*length) { + return malformed("array element count differs"); + } + } + terminal_psi::ArrayExtent::Application(_) => {} + terminal_psi::ArrayExtent::Parameter { .. } => { + return malformed("array construction requires a closed element count"); + } } *element } diff --git a/source-rust/subsystems/compiler/psi/artifact/wire/src/obligation_evidence.rs b/source-rust/subsystems/compiler/psi/artifact/wire/src/obligation_evidence.rs index 9af2048c6ed6..3e6fad30056a 100644 --- a/source-rust/subsystems/compiler/psi/artifact/wire/src/obligation_evidence.rs +++ b/source-rust/subsystems/compiler/psi/artifact/wire/src/obligation_evidence.rs @@ -384,6 +384,7 @@ impl<'module> MachineEvidenceGoals<'module> { fn new( machine: &'module terminal_psi::TerminalMachine, structural_types: &'module [terminal_psi::StructuralTypeDeclaration], + scalar_applications: &'module terminal_psi::ScalarApplications, indexed_types: &mut Option>, ) -> Self { let types = terminal_semantics::SortedValueTypes::new( @@ -528,6 +529,11 @@ impl<'module> MachineEvidenceGoals<'module> { root, projection.path, types, + |application| { + scalar_applications + .declaration(application) + .and_then(|declaration| declaration.scalar_type()) + }, |prefix| { terminal_semantics::preceding_collection_length( preceding, @@ -614,7 +620,12 @@ impl<'module, 'seals> EvidenceSealValidator<'module, 'seals> { .iter() .filter(|machine| selected.binary_search(&machine.id).is_ok()) .map(|machine| { - MachineEvidenceGoals::new(machine, &module.types.structural_types, &mut indexed_types) + MachineEvidenceGoals::new( + machine, + &module.types.structural_types, + &module.scalars.scalar_applications, + &mut indexed_types, + ) }) .collect::>(); machines.sort_unstable_by_key(|row| row.machine.id); @@ -1309,7 +1320,8 @@ mod projection_tests { }, ), ]; - let goals = MachineEvidenceGoals::new(&body, &[], &mut None); + let empty_applications = terminal_psi::ScalarApplications::default(); + let goals = MachineEvidenceGoals::new(&body, &[], &empty_applications, &mut None); let obligation = ObligationId::new(number).unwrap(); let goal = goals .obligation(obligation) @@ -1578,7 +1590,8 @@ mod projection_tests { ]; // This API checks goal correspondence. Descriptor formation and // backing custody are the independent checker's separate obligations. - let goals = MachineEvidenceGoals::new(&body, &[], &mut None); + let empty_applications = terminal_psi::ScalarApplications::default(); + let goals = MachineEvidenceGoals::new(&body, &[], &empty_applications, &mut None); let seals = (1..=2) .map(|raw| { let obligation = ObligationId::new(raw).unwrap(); diff --git a/source-rust/subsystems/compiler/psi/semantics/src/descriptors/descriptor_results/scalar_captures.rs b/source-rust/subsystems/compiler/psi/semantics/src/descriptors/descriptor_results/scalar_captures.rs index 79e805cde896..c23fa672589e 100644 --- a/source-rust/subsystems/compiler/psi/semantics/src/descriptors/descriptor_results/scalar_captures.rs +++ b/source-rust/subsystems/compiler/psi/semantics/src/descriptors/descriptor_results/scalar_captures.rs @@ -438,15 +438,22 @@ pub(crate) fn scalar_storage_writes( .result .structural() .ok_or("scalar array initializer has no structural result")?; - for (ordinal, value) in elements.iter().enumerate() { - let path = crate::scalar_array_leaf_path( - module.types.structural_types.iter(), - result.structural_type, - u64::try_from(ordinal) - .map_err(|_| "scalar array initializer ordinal is too large")?, - ) - .ok_or("scalar array initializer has no declared scalar leaf")?; - write(result.place, &path, None, *value)?; + if crate::scalar_array_application_leaf( + module.types.structural_types.iter(), + result.structural_type, + ) + .is_none() + { + for (ordinal, value) in elements.iter().enumerate() { + let path = crate::scalar_array_leaf_path( + module.types.structural_types.iter(), + result.structural_type, + u64::try_from(ordinal) + .map_err(|_| "scalar array initializer ordinal is too large")?, + ) + .ok_or("scalar array initializer has no declared scalar leaf")?; + write(result.place, &path, None, *value)?; + } } } OperationKind::EstablishScalarCase { diff --git a/source-rust/subsystems/compiler/psi/semantics/src/descriptors/descriptor_results/terminal_flow.rs b/source-rust/subsystems/compiler/psi/semantics/src/descriptors/descriptor_results/terminal_flow.rs index 3f268652bb4a..8672c1e39c39 100644 --- a/source-rust/subsystems/compiler/psi/semantics/src/descriptors/descriptor_results/terminal_flow.rs +++ b/source-rust/subsystems/compiler/psi/semantics/src/descriptors/descriptor_results/terminal_flow.rs @@ -1328,20 +1328,27 @@ fn adapt_flow( } OperationKind::EstablishScalarArray { elements } => { let result = result?; - for (ordinal, value) in elements.iter().enumerate() { - let path = crate::scalar_array_leaf_path( - module.types.structural_types.iter(), - result.structural_type, - u64::try_from(ordinal).ok()?, - )?; - step.scalar_value_stores - .push((location(result.place, &path, None)?, *value)); - if let Some(value) = scalar_expressions.expression(*value) { - graph - .scalar_payload_writes - .entry(position) - .or_default() - .push((location(result.place, &path, None)?, value)); + if crate::scalar_array_application_leaf( + module.types.structural_types.iter(), + result.structural_type, + ) + .is_none() + { + for (ordinal, value) in elements.iter().enumerate() { + let path = crate::scalar_array_leaf_path( + module.types.structural_types.iter(), + result.structural_type, + u64::try_from(ordinal).ok()?, + )?; + step.scalar_value_stores + .push((location(result.place, &path, None)?, *value)); + if let Some(value) = scalar_expressions.expression(*value) { + graph + .scalar_payload_writes + .entry(position) + .or_default() + .push((location(result.place, &path, None)?, value)); + } } } } @@ -1359,6 +1366,10 @@ fn adapt_flow( } if usize::try_from(length).ok() == Some(elements.len()) => { (element, false) } + StructuralTypeShape::FixedArray { + element, + length: terminal_psi::ArrayExtent::Application(_), + } => (element, true), _ => return None, }; if stored { diff --git a/source-rust/subsystems/compiler/psi/semantics/src/lib.rs b/source-rust/subsystems/compiler/psi/semantics/src/lib.rs index ff8a64c573a0..d9735ab99783 100644 --- a/source-rust/subsystems/compiler/psi/semantics/src/lib.rs +++ b/source-rust/subsystems/compiler/psi/semantics/src/lib.rs @@ -38,7 +38,10 @@ pub mod reference_ends; pub mod references; pub mod scalar_qualifications; mod scalar_target_ranges; -pub use scalar_target_ranges::{TargetScalarRange, layout_call_conditions, target_scalar_ranges}; +pub use scalar_target_ranges::{ + TargetScalarRange, array_extent_literal_conditions, layout_call_conditions, + target_scalar_ranges, +}; pub mod scalars; pub mod static_reach; pub mod storage; @@ -221,7 +224,8 @@ pub use scalars::proof_bearing_scalar::{ }; pub use scalars::scalar_array::{ PackedArrayRole, packed_integer_array_type, packed_integer_unary_array_type, - scalar_array_leaf_declaration, scalar_array_leaf_path, scalar_array_leaf_shape, + scalar_array_application_leaf, scalar_array_leaf_declaration, scalar_array_leaf_path, + scalar_array_leaf_shape, }; pub use scalars::scalar_field_requirements::{ atomic_resident_requirement, scalar_field_accepts_literal, scalar_field_accepts_zero, diff --git a/source-rust/subsystems/compiler/psi/semantics/src/scalar_qualifications.rs b/source-rust/subsystems/compiler/psi/semantics/src/scalar_qualifications.rs index 2b7ced743c1c..4da16bb887ae 100644 --- a/source-rust/subsystems/compiler/psi/semantics/src/scalar_qualifications.rs +++ b/source-rust/subsystems/compiler/psi/semantics/src/scalar_qualifications.rs @@ -395,19 +395,23 @@ fn validate_machine_transfers( "scalar array initialization lost its storage declaration", ), )?; - let (leaf, count) = crate::scalar_array_leaf_declaration( + let leaf = if let Some((leaf, count)) = crate::scalar_array_leaf_declaration( module.types.structural_types.iter(), result.structural_type, - ) - .ok_or( - ScalarQualificationError::MalformedStructuralFoundation( - "scalar array has no exact primitive leaf declaration", - ), - )?; + ) { + if count != elements.len() as u64 { + return malformed("scalar array has a different declared leaf count"); + } + leaf + } else if let Some((leaf, _)) = crate::scalar_array_application_leaf( + module.types.structural_types.iter(), + result.structural_type, + ) { + leaf + } else { + return malformed("scalar array has no exact primitive leaf declaration"); + }; let expected = primitive_qualifications(module, leaf.id); - if count != elements.len() as u64 { - return malformed("scalar array has a different declared leaf count"); - } for element in elements { if declared.get(*element)?.qualifications != expected { return malformed( diff --git a/source-rust/subsystems/compiler/psi/semantics/src/scalar_target_ranges.rs b/source-rust/subsystems/compiler/psi/semantics/src/scalar_target_ranges.rs index 2f7234a26b1b..fbfb9d43eb55 100644 --- a/source-rust/subsystems/compiler/psi/semantics/src/scalar_target_ranges.rs +++ b/source-rust/subsystems/compiler/psi/semantics/src/scalar_target_ranges.rs @@ -1,7 +1,7 @@ //! Ground arithmetic that can be checked once the selected scalar values exist. mod calls; -pub use calls::layout_call_conditions; +pub use calls::{array_extent_literal_conditions, layout_call_conditions}; mod guards; mod storage; diff --git a/source-rust/subsystems/compiler/psi/semantics/src/scalar_target_ranges/calls.rs b/source-rust/subsystems/compiler/psi/semantics/src/scalar_target_ranges/calls.rs index 47500551727b..fb700e74b34c 100644 --- a/source-rust/subsystems/compiler/psi/semantics/src/scalar_target_ranges/calls.rs +++ b/source-rust/subsystems/compiler/psi/semantics/src/scalar_target_ranges/calls.rs @@ -85,3 +85,98 @@ pub fn layout_call_conditions( } Ok(conditions) } + +/// Reconstruct pending extent-equality conditions for array literals whose +/// target type has a target-dependent `ArrayExtent::Application`. +pub fn array_extent_literal_conditions( + module: &TerminalModule, + machine: &TerminalMachine, +) -> Result, &'static str> { + let applications = &module.scalars.scalar_applications; + if applications.declarations().is_empty() { + return Ok(Vec::new()); + } + let owner = applications + .proof_scope + .callable_declaration(TargetMachineCallable::Machine(machine.id)); + let index = OnceCell::new(); + let dominators = OnceCell::new(); + let storage = OnceCell::new(); + let branches = OnceCell::new(); + let mut conditions = Vec::new(); + for block in &machine.blocks { + let paths = OnceCell::new(); + for operation in &block.operations { + let count = match &operation.kind { + OperationKind::EstablishScalarArray { elements } => elements.len(), + OperationKind::EstablishStructuralArray { elements } => elements.len(), + _ => continue, + }; + let Some(result) = operation.result.structural() else { + continue; + }; + let Some(terminal_psi::StructuralTypeShape::FixedArray { + length: terminal_psi::ArrayExtent::Application(application), + .. + }) = module + .structural_type(result.structural_type) + .map(|declaration| &declaration.shape) + else { + continue; + }; + let scalar_type = applications + .declaration(*application) + .and_then(|declaration| declaration.scalar_type()) + .ok_or("array literal extent has no declared scalar application")?; + let Some(integer) = scalar_type.as_integer() else { + return Err("array literal extent is not an integer application"); + }; + let literal = u64::try_from(count) + .ok() + .and_then(|count| { + ScalarTerm::integer(integer, IntegerValue::Unsigned(u128::from(count))).ok() + }) + .ok_or("array literal count does not fit in its extent carrier")?; + let goal = Proposition::Equal( + ScalarTerm::Application { + application: *application, + scalar_type, + }, + literal, + ); + let condition = applications.layout_predicate( + owner, + || { + format!( + "array literal length ({count}) matches target-dependent extent in {:?}", + machine.id + ) + }, + &goal, + || { + paths + .get_or_init(|| { + let mut trace = GroundRange { + module, + index: index.get_or_init(|| MachineScalarIndex::new(machine)), + storage: &storage, + dominators: &dominators, + active: Vec::new(), + steps: Vec::new(), + remaining: 4096, + }; + trace.call_guards( + block.id, + branches.get_or_init(|| guards::branches(machine)), + ) + }) + .as_slice() + }, + )?; + if let Some(condition) = condition { + conditions.push(condition); + } + } + } + Ok(conditions) +} diff --git a/source-rust/subsystems/compiler/psi/semantics/src/scalars/scalar_array.rs b/source-rust/subsystems/compiler/psi/semantics/src/scalars/scalar_array.rs index 39ee1e61c290..95d14e4fbcf7 100644 --- a/source-rust/subsystems/compiler/psi/semantics/src/scalars/scalar_array.rs +++ b/source-rust/subsystems/compiler/psi/semantics/src/scalars/scalar_array.rs @@ -157,3 +157,25 @@ pub fn scalar_array_leaf_declaration<'types>( } None } + +/// Returns the primitive leaf declaration and extent application of a +/// one-dimensional fixed array whose length is a target-dependent scalar +/// application. +pub fn scalar_array_application_leaf<'types>( + types: impl Iterator + Clone, + root: StructuralTypeId, +) -> Option<( + &'types StructuralTypeDeclaration, + semantic_vocabulary::ScalarApplicationId, +)> { + let declaration = crate::structural_declaration(types.clone(), root)?; + let StructuralTypeShape::FixedArray { + element, + length: terminal_psi::ArrayExtent::Application(application), + } = declaration.shape + else { + return None; + }; + let leaf = crate::structural_declaration(types, element)?; + matches!(leaf.shape, StructuralTypeShape::PrimitiveScalar(_)).then_some((leaf, application)) +} diff --git a/source-rust/subsystems/compiler/psi/semantics/src/storage/collection_backing.rs b/source-rust/subsystems/compiler/psi/semantics/src/storage/collection_backing.rs index df55948161d4..94b1f8dc7e87 100644 --- a/source-rust/subsystems/compiler/psi/semantics/src/storage/collection_backing.rs +++ b/source-rust/subsystems/compiler/psi/semantics/src/storage/collection_backing.rs @@ -14,6 +14,7 @@ pub enum CollectionExtent { owner: semantic_vocabulary::MachineId, value: semantic_vocabulary::ValueId, }, + Application(semantic_vocabulary::ScalarApplicationId), Fixed(u64), LiveLength { capacity: u64, @@ -103,6 +104,13 @@ fn collection_shape_backing<'types>( extent: CollectionExtent::Parameter { owner, value }, storage: CollectionStorage::Inline, }), + StructuralTypeShape::FixedArray { + element: actual, + length: terminal_psi::ArrayExtent::Application(application), + } if actual == element => Some(CollectionBacking { + extent: CollectionExtent::Application(application), + storage: CollectionStorage::Inline, + }), StructuralTypeShape::ByteSequence(carrier) if types.clone().any(|declaration| { declaration.id == element diff --git a/source-rust/subsystems/compiler/psi/semantics/src/structural/primitive_place.rs b/source-rust/subsystems/compiler/psi/semantics/src/structural/primitive_place.rs index b31cc418015a..9f047a4ad5d8 100644 --- a/source-rust/subsystems/compiler/psi/semantics/src/structural/primitive_place.rs +++ b/source-rust/subsystems/compiler/psi/semantics/src/structural/primitive_place.rs @@ -1068,8 +1068,11 @@ fn walk_primitive_projection_with_policy<'a>( ( StructuralPathSegment::FixedIndex(index), StructuralTypeShape::FixedArray { element, length }, - ) if !matches!(length, terminal_psi::ArrayExtent::Parameter { .. }) - && length.literal().is_none_or(|length| *index < length) => + ) if !matches!( + length, + terminal_psi::ArrayExtent::Parameter { .. } + | terminal_psi::ArrayExtent::Application(_) + ) && length.literal().is_none_or(|length| *index < length) => { step( length @@ -1223,6 +1226,7 @@ pub fn visit_runtime_index_goals<'a>( root: StructuralTypeId, path: &[StructuralPathSegment], values: &impl crate::ValueTypes, + application_type: impl Fn(semantic_vocabulary::ScalarApplicationId) -> Option, mut measured_extent: impl FnMut(&[StructuralPathSegment]) -> Option, mut visit: impl FnMut(ObligationId, Proposition), ) -> Result<(), RuntimeIndexGoalError> { @@ -1271,6 +1275,22 @@ pub fn visit_runtime_index_goals<'a>( semantic_vocabulary::ScalarTerm::value(length, length_type), ) } + StructuralTypeShape::FixedArray { + length: terminal_psi::ArrayExtent::Application(application), + .. + } => { + let Some(length_type) = application_type(application) else { + error = RuntimeIndexGoalError::MissingExtent; + return false; + }; + scalar_index_bound( + semantic_vocabulary::ScalarTerm::value(index, carrier), + semantic_vocabulary::ScalarTerm::Application { + application, + scalar_type: length_type, + }, + ) + } StructuralTypeShape::ByteSequence(ByteSequenceCarrier::BoundedView { capacity, .. diff --git a/source-rust/subsystems/compiler/psi/semantics/src/structural_qualifications.rs b/source-rust/subsystems/compiler/psi/semantics/src/structural_qualifications.rs index a49fc0ec88a2..4ab664949cc4 100644 --- a/source-rust/subsystems/compiler/psi/semantics/src/structural_qualifications.rs +++ b/source-rust/subsystems/compiler/psi/semantics/src/structural_qualifications.rs @@ -679,7 +679,9 @@ impl<'a> DefaultRequirements<'a> { // zero vocabulary check permits only ungated primitive elements, // so there is no nested default clause to inventory here. StructuralTypeShape::FixedArray { - length: terminal_psi::ArrayExtent::Parameter { .. }, + length: + terminal_psi::ArrayExtent::Parameter { .. } + | terminal_psi::ArrayExtent::Application(_), .. } if zero => {} StructuralTypeShape::Record { fields, .. } => { @@ -1520,7 +1522,9 @@ fn zero_defaults_supported( } StructuralTypeShape::FixedArray { element, - length: terminal_psi::ArrayExtent::Parameter { .. }, + length: + terminal_psi::ArrayExtent::Parameter { .. } + | terminal_psi::ArrayExtent::Application(_), } => { let supported = types .binary_search_by_key(element, |row| row.id) diff --git a/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/lower/places.rs b/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/lower/places.rs index bd8d53568218..e7ff0867f3f9 100644 --- a/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/lower/places.rs +++ b/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/lower/places.rs @@ -164,7 +164,9 @@ fn zero_eligibility( } StorageShape::FixedArray { element, - length: terminal_psi::ArrayExtent::Parameter { .. }, + length: + terminal_psi::ArrayExtent::Parameter { .. } + | terminal_psi::ArrayExtent::Application(_), qualification: Qualification::NONE, } => { let element = types @@ -2089,6 +2091,15 @@ impl<'a> Lowering<'a> { qualification, CollectionExtent::Parameter { owner, value }, )), + StorageShape::FixedArray { + element, + qualification, + length: terminal_psi::ArrayExtent::Application(application), + } => Ok(( + element, + qualification, + CollectionExtent::Application(application), + )), StorageShape::ElementView { element, qualification, @@ -3991,10 +4002,16 @@ impl<'a> Lowering<'a> { ProgramPoint::AfterOperation(operation), Content::Overwritten, )?; - // A stored-length collection establishes its descriptor. The actual - // element operands remain on the constructor operation; they are not - // fixed-index source places beneath that descriptor. - if length == CollectionExtent::StoredLength { + // A stored-length collection establishes its descriptor, and an array + // with a symbolic or target-dependent extent has no fixed-index child + // places before closure. The element operands remain on the + // constructor operation. + if matches!( + length, + CollectionExtent::StoredLength + | CollectionExtent::Parameter { .. } + | CollectionExtent::Application(_) + ) { return Ok(Reached::Value((root, exact))); } for (index, operand) in operands.into_iter().enumerate() { diff --git a/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/arrays.rs b/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/arrays.rs index d588a80d618f..b9128917b827 100644 --- a/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/arrays.rs +++ b/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/arrays.rs @@ -118,7 +118,8 @@ impl Program<'_> { let StorageShape::FixedArray { element, qualification: Qualification::NONE, - length: ArrayExtent::Literal(_) | ArrayExtent::Parameter { .. }, + length: + ArrayExtent::Literal(_) | ArrayExtent::Parameter { .. } | ArrayExtent::Application(_), } = actual.shape else { return None; @@ -150,7 +151,10 @@ impl Program<'_> { StorageShape::FixedArray { element, qualification, - length: ArrayExtent::Literal(_) | ArrayExtent::Parameter { .. }, + length: + ArrayExtent::Literal(_) + | ArrayExtent::Parameter { .. } + | ArrayExtent::Application(_), } | StorageShape::ElementView { element, @@ -799,6 +803,15 @@ impl Program<'_> { value: *value, }, )), + StorageShape::FixedArray { + element, + qualification, + length: ArrayExtent::Application(application), + } => Ok(( + *element, + *qualification, + CollectionExtent::Application(*application), + )), StorageShape::ElementView { element, qualification, @@ -1006,12 +1019,34 @@ impl Program<'_> { ) } // The source driver evaluates a constant the request reaches - // before stage 04 freezes the trees. One still without a - // value waits on a deployment, or holds no array length. + // before stage 04 freezes the trees. One that observes the + // target's layout keeps its checked initializer as an + // application extent so each deployment closes its length. None if named_constant => { - return Err(unserved( - "array extent that names a constant with no evaluated array length", - )); + if let FixedArrayLength::ConstParameter { symbol, .. } = extent + && let Some(constant) = self.typed.const_declaration_by_symbol(*symbol) + && constant.pending_target_observation + && constant.evaluated_value.is_none() + { + let (application, scalar_type) = + self.deferred_scalar_constant(machine, constant)?; + if !matches!( + scalar_type, + ScalarType::Integer(integer) + if !integer.is_address() + && integer.sign() == IntegerSign::Unsigned + && integer.bits().is_some_and(|bits| bits <= 64) + ) { + return Err(unserved( + "array extent constant needs an unsigned carrier of at most 64 bits", + )); + } + ArrayExtent::Application(application) + } else { + return Err(unserved( + "array extent that names a constant with no evaluated array length", + )); + } } None => return Err(unserved("unresolved array extent")), } diff --git a/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/bytes.rs b/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/bytes.rs index 222a3c3b08d5..260a4ae6bfff 100644 --- a/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/bytes.rs +++ b/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/bytes.rs @@ -617,13 +617,30 @@ impl Program<'_> { ExpressionKind::Cast(Box::new(operand)) } } - terminal_psi::ArrayExtent::Application(_) => { - return Err(refuse_at( - machine, - Unserved::Expression( - "fixed-array length with an unresolved scalar application", - ), - )); + terminal_psi::ArrayExtent::Application(application) => { + let input_type = self + .scalar_applications + .scalar_type(application) + .ok_or_else(|| { + refuse_at( + machine, + Unserved::Expression( + "fixed-array length has no declared scalar application", + ), + ) + })?; + let input_value = ValueType::plain(input_type); + let operand = Expression { + call_context: None, + kind: ExpressionKind::ScalarApplication { application }, + result: Some(input_value), + source, + }; + if input_value == result { + operand.kind + } else { + ExpressionKind::Cast(Box::new(operand)) + } } }; return Ok(Expression { diff --git a/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/clause_terms.rs b/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/clause_terms.rs index 358546b0505a..4ba242b09421 100644 --- a/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/clause_terms.rs +++ b/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/clause_terms.rs @@ -457,6 +457,26 @@ impl Program<'_> { ExpressionNode::Name(path) if path.static_application.is_valid() => { return Err(unavailable("applied name used as a plain scalar term")); } + ExpressionNode::Name(path) + if self.typed.named_const_declaration(path).is_some_and(|constant| { + constant.pending_target_observation + && constant.evaluated_value.is_none() + }) => + { + let constant = self + .typed + .named_const_declaration(path) + .expect("checked deferred constant"); + let (application, scalar_type) = + self.deferred_scalar_constant(id, constant)?; + ( + ScalarTerm::Application { + application, + scalar_type, + }, + ValueType::plain(scalar_type), + ) + } // The reserved result, by the owner identity stage 02 // recorded, never by its spelling. calls_and_outcomes.md: // "The reserved result occurrence belongs to its contract @@ -572,10 +592,34 @@ impl Program<'_> { })? } } - terminal_psi::ArrayExtent::Application(_) => { - return Err(unavailable( - "fixed-array length with an unresolved scalar application", - )); + terminal_psi::ArrayExtent::Application(application) => { + let input_scalar = self + .scalar_applications + .scalar_type(application) + .ok_or_else(|| { + unavailable( + "fixed-array length has no declared scalar application", + ) + })?; + let ScalarType::Integer(input_type) = input_scalar else { + return Err(unavailable( + "fixed-array length application is not an integer", + )); + }; + let term = ScalarTerm::Application { + application, + scalar_type: input_scalar, + }; + if input_type == scalar_type { + term + } else { + ScalarTerm::integer_widen(input_type, scalar_type, term) + .map_err(|_| { + unavailable( + "fixed-array length has no count conversion", + ) + })? + } } } } else if shape.length_operation().is_some() { diff --git a/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/constant_values.rs b/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/constant_values.rs index 4d2eb00cdc0e..c3ce01629faa 100644 --- a/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/constant_values.rs +++ b/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/constant_values.rs @@ -69,6 +69,17 @@ impl ScalarApplications { )) } + pub(super) fn scalar_type( + &self, + application: semantic_vocabulary::ScalarApplicationId, + ) -> Option { + let index = usize::try_from(application.get().checked_sub(1)?).ok()?; + match self.sources.get(index)? { + ScalarApplicationSource::Layout(declaration) => declaration.scalar_type(), + ScalarApplicationSource::Evaluation { scalar_type, .. } => Some(*scalar_type), + } + } + pub(crate) fn published(&self) -> Result { if self.sources.len() != self.declarations.declarations().len() { return Err("scalar applications still await their exact evaluation entries"); diff --git a/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/contracts.rs b/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/contracts.rs index 9ffdd87d0da2..728a7fb4203b 100644 --- a/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/contracts.rs +++ b/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/contracts.rs @@ -1881,6 +1881,7 @@ impl Program<'_> { ( terminal_semantics::CollectionExtent::Fixed(_) | terminal_semantics::CollectionExtent::Parameter { .. } + | terminal_semantics::CollectionExtent::Application(_) | terminal_semantics::CollectionExtent::StoredLength, _, ) => { diff --git a/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/storage/places.rs b/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/storage/places.rs index 117f39cd0620..74b7d538f72d 100644 --- a/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/storage/places.rs +++ b/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/storage/places.rs @@ -2622,7 +2622,9 @@ impl<'a> Storage<'a> { } StructuralTypeShape::FixedArray { element, - length: terminal_psi::ArrayExtent::Parameter { .. }, + length: + terminal_psi::ArrayExtent::Parameter { .. } + | terminal_psi::ArrayExtent::Application(_), } if matches!(segment, Segment::RuntimeIndex { .. }) => element, StructuralTypeShape::ElementView { element, .. } if matches!(segment, Segment::RuntimeIndex { .. }) => @@ -2929,6 +2931,13 @@ impl<'a> Storage<'a> { root, projection.path, types, + |application| { + self.module + .scalars + .scalar_applications + .declaration(application) + .and_then(|declaration| declaration.scalar_type()) + }, |prefix| { terminal_semantics::preceding_collection_length( preceding, diff --git a/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/storage/places/byte_views.rs b/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/storage/places/byte_views.rs index e5e42163960f..3ef472d0e3f3 100644 --- a/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/storage/places/byte_views.rs +++ b/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/storage/places/byte_views.rs @@ -524,6 +524,7 @@ impl<'a> Storage<'a> { if matches!( backing.extent, terminal_semantics::CollectionExtent::Parameter { .. } + | terminal_semantics::CollectionExtent::Application(_) ) { let is_byte = is_plain_byte_element(self.declaration(element, concerns)?); if typed == is_byte @@ -1118,7 +1119,7 @@ impl<'a> Storage<'a> { let local_extent = match length { ArrayExtent::Literal(length) => *length != 0, ArrayExtent::Parameter { owner, .. } => *owner == self.machine, - ArrayExtent::Application(_) => false, + ArrayExtent::Application(_) => true, }; let matching_element = match element { Some(element) => *backing_element == element, @@ -1401,6 +1402,36 @@ value, if source_type == integer { return Ok(Some(input)); } return ScalarTerm::integer_widen(source_type, integer, input).map(Some).map_err(|_| self.foreign(concerns, "array extent cannot widen exactly to its descriptor length")); } + terminal_semantics::CollectionExtent::Application(application) => { + let source_type = self + .module + .scalars + .scalar_applications + .declaration(application) + .and_then(|declaration| declaration.scalar_type()) + .and_then(|scalar| scalar.as_integer()) + .ok_or_else(|| { + self.foreign( + concerns, + "array extent has no integer application", + ) + })?; + let input = ScalarTerm::Application { + application, + scalar_type: ScalarType::Integer(source_type), + }; + if source_type == integer { + return Ok(Some(input)); + } + return ScalarTerm::integer_widen(source_type, integer, input) + .map(Some) + .map_err(|_| { + self.foreign( + concerns, + "array extent cannot widen exactly to its descriptor length", + ) + }); + } terminal_semantics::CollectionExtent::LiveLength { .. } => { return Err(self .unsupported(concerns, "collection view has no captured length")); diff --git a/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/storage/places/leaves.rs b/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/storage/places/leaves.rs index 6ae882c66c98..4c81057fe8c8 100644 --- a/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/storage/places/leaves.rs +++ b/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/storage/places/leaves.rs @@ -157,7 +157,9 @@ impl Storage<'_> { // A symbolic array can be established whole without enumerating // N elements. Every selected read still owes its own index bound. StructuralTypeShape::FixedArray { - length: terminal_psi::ArrayExtent::Parameter { .. }, + length: + terminal_psi::ArrayExtent::Parameter { .. } + | terminal_psi::ArrayExtent::Application(_), .. } => { visit(state, at); diff --git a/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/storage/places/log.rs b/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/storage/places/log.rs index 3dd00ddef322..f44685a4bd13 100644 --- a/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/storage/places/log.rs +++ b/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/storage/places/log.rs @@ -309,6 +309,19 @@ impl<'a> Storage<'a> { OperationKind::EstablishScalarArray { elements } => { let root = fresh()?; rows.push((root.clone(), Stored::Established)); + let shape = &self + .declaration(self.root_type(root.root, concerns)?, concerns)? + .shape; + if matches!( + shape, + StructuralTypeShape::FixedArray { + length: terminal_psi::ArrayExtent::Parameter { .. } + | terminal_psi::ArrayExtent::Application(_), + .. + } + ) { + return Ok(rows); + } for (index, value) in elements.iter().enumerate() { let index = u64::try_from(index) .map_err(|_| self.foreign(concerns, "array element index exceeds u64"))?; @@ -333,6 +346,16 @@ impl<'a> Storage<'a> { // not inline storage with fixed-index child places. return Ok(rows); } + if matches!( + shape, + StructuralTypeShape::FixedArray { + length: terminal_psi::ArrayExtent::Parameter { .. } + | terminal_psi::ArrayExtent::Application(_), + .. + } + ) { + return Ok(rows); + } for (index, value) in elements.iter().enumerate() { let index = u64::try_from(index) .map_err(|_| self.foreign(concerns, "array element index exceeds u64"))?; diff --git a/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/verdict.rs b/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/verdict.rs index ce40490e3639..a0455367d1db 100644 --- a/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/verdict.rs +++ b/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/verdict.rs @@ -1607,6 +1607,40 @@ fn conclude( pending.push(owner); } } + let mut array_extent_conditions = Vec::new(); + for machine in &elaboration.module.machines { + let machine_conditions = + match terminal_semantics::array_extent_literal_conditions(&elaboration.module, machine) + { + Ok(conditions) => conditions, + Err(detail) => { + return fall_back_or_defect(refusal( + RefusalReason::ForeignIdentity, + machine.id, + Construct::Machine, + detail, + )); + } + }; + for condition in machine_conditions { + let terminal_psi::ScalarConditionSubject::Declaration(owner) = condition.subject else { + return fall_back_or_defect(refusal( + RefusalReason::ForeignIdentity, + machine.id, + Construct::Machine, + "array extent literal condition lost its declaration owner", + )); + }; + array_extent_conditions.push((owner, condition)); + } + } + let applications = &mut elaboration.module.scalars.scalar_applications; + for (owner, condition) in array_extent_conditions { + if !applications.conditions.predicates().contains(&condition) { + applications.conditions.insert_predicate(condition); + } + pending.push(owner); + } pending.sort_unstable(); pending.dedup(); applications diff --git a/source-rust/subsystems/interpreter/embedding/program.rs b/source-rust/subsystems/interpreter/embedding/program.rs index c2176c06cc43..18205aec3fb2 100644 --- a/source-rust/subsystems/interpreter/embedding/program.rs +++ b/source-rust/subsystems/interpreter/embedding/program.rs @@ -2594,14 +2594,14 @@ pub(crate) mod program { installation: Option<&crate::boundary::effects::TerminalRuntimeSupplies>, scalars: Option<&psi_scalar_applications::AdmittedScalarApplications>, ) -> std::sync::Arc> { - let Some(layouts) = installation.and_then(|supplies| supplies.target_layouts.as_ref()) - else { + let layouts = installation.and_then(|supplies| supplies.target_layouts.as_ref()); + if layouts.is_none() && scalars.is_none() { return std::sync::Arc::clone(&self.program); - }; + } std::sync::Arc::new(AdmittedTerminalProgram { identity: self.program.identity.clone(), catalogs: std::sync::Arc::clone(&self.program.catalogs), - target_layouts: Some(std::sync::Arc::clone(layouts)), + target_layouts: layouts.map(std::sync::Arc::clone), scalar_geometry: scalars.map(|scalars| std::sync::Arc::clone(scalars.geometry())), }) } diff --git a/source-rust/subsystems/interpreter/memory/bytes_and_views.rs b/source-rust/subsystems/interpreter/memory/bytes_and_views.rs index b331ac69d36d..912799765239 100644 --- a/source-rust/subsystems/interpreter/memory/bytes_and_views.rs +++ b/source-rust/subsystems/interpreter/memory/bytes_and_views.rs @@ -4356,7 +4356,8 @@ pub(crate) mod element_views { terminal_semantics::CollectionExtent::Fixed(length) => length, terminal_semantics::CollectionExtent::LiveLength { capacity } => capacity, terminal_semantics::CollectionExtent::StoredLength - | terminal_semantics::CollectionExtent::Parameter { .. } => { + | terminal_semantics::CollectionExtent::Parameter { .. } + | terminal_semantics::CollectionExtent::Application(_) => { return Err(malformed()); } };