From f75064f1d26dc4860cca3779aa4340e654b06b21 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 02:10:15 +0000 Subject: [PATCH] psi: start each generic form's Identity goals from one checked table --- TASKS.md | 1 - .../psi/semantics/proofs/bounded/bounded.rs | 9 +- .../proofs/mathematical/mathematical.rs | 3 +- .../proofs/mathematical/signature.rs | 29 ++- .../semantics/proofs/mathematical/tests.rs | 48 ++++ .../src/compilation.rs | 16 +- .../src/identity_tables.rs | 235 ++++++++++++++++++ .../src/lib.rs | 1 + .../src/read/clause_terms.rs | 25 ++ .../src/read/record_parameters.rs | 1 + .../src/control_flow/joins.rs | 5 +- .../src/lib.rs | 38 ++- .../src/proofs/equality.rs | 224 +++++++++++++++-- .../src/proofs/laws.rs | 2 + .../src/tests/record_identity.rs | 1 + .../src/tests/semiring_identity.rs | 125 +++++++++- .../src/verdict.rs | 78 ++++-- .../representations/lowered-program/README.md | 19 +- .../lowered-program/mathematics.rs | 49 ++++ .../lowered-program/tables/contracts.rs | 6 + .../drafts/designs/proof_kernel_core_audit.md | 10 +- 21 files changed, 848 insertions(+), 77 deletions(-) create mode 100644 source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/identity_tables.rs diff --git a/TASKS.md b/TASKS.md index 94c80d732b6a..49cebac1ea5f 100644 --- a/TASKS.md +++ b/TASKS.md @@ -315,7 +315,6 @@ Find Rust owners in the [compiler map](source-rust/README.md#where-code-belongs) - [Proof kernel core audit](wiki/drafts/designs/proof_kernel_core_audit.md): what #2823 removed, the three general rules still needed, the changes to stage 05's clause readers and the build order. - Discharge the natural order's well-foundedness once and prove that the fuel a machine with [computed recursive descent](wiki/spec/language/termination.md#computed-recursive-arguments-in-proofs) is defined on suffices for every reachable call, so its laws hold independently of the bound. - Step 7 reads a quotient of mathematical data, proves equal classes for related representatives, checks `MereEquivalence` (including `IsMere` and Hedberg setness for plain data) and effectivity, and judges `Quotient::lift` and `Quotient::define` by their selected theorems. Ordinary programs store a quotient of custody-free copyable data as its representative. A clause may apply a lifted operation that the kernel's `lift` defines. A lift may compute, leave out or repeat its arguments. Still owed, each refused by name today: generic quotients, and laws over quotients of data that has storage (the signature states a record only of mathematical data, never one with a fixed-width field). [Audit, "Step 7 as built so far"](wiki/drafts/designs/proof_kernel_core_audit.md#plan-order) - - Put the abstract carriers, trait operations and cited laws of a generic machine's Identity goals in the [mathematical signature](source-rust/subsystems/compiler/source-to-psi/representations/lowered-program/README.md#the-mathematical-signature); `equality::discharge` still builds that table per obligation. - Extend alias-typed theorem parameters to accept evidence projected from bundles, as in `use_step::(7u8)`. Stage 05 refuses every `term.member` proof argument by name. A record field typed `step: NonzeroIsPositive` is a structural callable field, so `const U8_LAWS: Laws = Laws { step: nonzero_is_positive }` needs a callable ceiling and then fails constant evaluation ("Terminal result scalar is outside the compiler-owned vocabulary"). Which field type declares mathematical evidence instead is owner question 5 in [OWNER_QUESTIONS.md](OWNER_QUESTIONS.md#bundle-evidence-field-type). [Theorem proof parameters](wiki/spec/proofs/mathematical_bindings.md#logical-hypotheses-and-machine-use) - Extend the logical contract beyond fixed integer and Boolean subjects. Address integers fail first in typing: an alias `machine(n: usize) requires n == 1 ...` has "no complete structural type identity". After that, `IntegerType::minimum_value` answers nothing for `usize`, so its subject gets no carrier bound and even `n != 0` cannot give `n > 0`. Floats and data subjects have no denotation in `prepare_subjects` or `contract_subjects`. [Theorem proof parameters](wiki/spec/proofs/mathematical_bindings.md#logical-hypotheses-and-machine-use) diff --git a/source-rust/subsystems/compiler/psi/semantics/proofs/bounded/bounded.rs b/source-rust/subsystems/compiler/psi/semantics/proofs/bounded/bounded.rs index 8915b415d9ef..ecd5f451f24a 100644 --- a/source-rust/subsystems/compiler/psi/semantics/proofs/bounded/bounded.rs +++ b/source-rust/subsystems/compiler/psi/semantics/proofs/bounded/bounded.rs @@ -441,10 +441,11 @@ pub use mathematical_kernel::{ SignatureCheckError, Sort, Term, TermArena, TermHandle, argument_error_pair_pattern, assumption_closure, certificate_assumption_closure, check_signature, check_signature_with_attribution, check_type, convertible, convertible_retaining, - declare_inductive_family, declare_mutual_inductive_family, identity_substitution, infer_sort, - infer_type, instantiate, instantiate_levels, judgment_assumption_closure, quotient_scheme, - shift, substitute, universe_parameter_arity, verify_mathematical_certificate, - verify_mathematical_certificates, weak_head_normalize, weak_head_normalize_retaining, + declare_inductive_family, declare_mutual_inductive_family, extend_signature, + identity_substitution, infer_sort, infer_type, instantiate, instantiate_levels, + judgment_assumption_closure, quotient_scheme, shift, substitute, universe_parameter_arity, + verify_mathematical_certificate, verify_mathematical_certificates, weak_head_normalize, + weak_head_normalize_retaining, }; pub use predicate_denotation::{ CheckedPredicateDenotations, CheckedValueEquations, PredicateDenotationError, diff --git a/source-rust/subsystems/compiler/psi/semantics/proofs/mathematical/mathematical.rs b/source-rust/subsystems/compiler/psi/semantics/proofs/mathematical/mathematical.rs index 627ea1cacc84..eefc7cf3f1d0 100644 --- a/source-rust/subsystems/compiler/psi/semantics/proofs/mathematical/mathematical.rs +++ b/source-rust/subsystems/compiler/psi/semantics/proofs/mathematical/mathematical.rs @@ -50,7 +50,8 @@ pub use quotient::{ }; pub use signature::{ Declaration, DeclarationKind, Signature, SignatureCheckError, assumption_closure, - check_signature, check_signature_with_attribution, judgment_assumption_closure, + check_signature, check_signature_with_attribution, extend_signature, + judgment_assumption_closure, }; pub use substitution::{ instantiate, instantiate_levels, relocate_constants, shift, substitute, diff --git a/source-rust/subsystems/compiler/psi/semantics/proofs/mathematical/signature.rs b/source-rust/subsystems/compiler/psi/semantics/proofs/mathematical/signature.rs index b93aec7e3c09..3e79e7eb1e5c 100644 --- a/source-rust/subsystems/compiler/psi/semantics/proofs/mathematical/signature.rs +++ b/source-rust/subsystems/compiler/psi/semantics/proofs/mathematical/signature.rs @@ -213,8 +213,33 @@ pub fn check_signature_with_attribution( declarations: &[Declaration], budget: &mut Budget, ) -> Result { - let mut signature = Signature::new(); - let mut position = 0; + check_from(arena, Signature::new(), declarations, 0, budget) +} + +/// Checks `added` after `checked`, a signature this kernel already checked, +/// and returns the two as one signature. The declarations of `checked` are +/// not checked again, so a table checked once can be extended by each of its +/// users without repeating that work. A refusal's position counts from the +/// start of `checked`. +pub fn extend_signature( + arena: &mut TermArena, + checked: &Signature, + added: &[Declaration], + budget: &mut Budget, +) -> Result { + let start = checked.len(); + let mut declarations = checked.declarations().to_vec(); + declarations.extend_from_slice(added); + check_from(arena, checked.clone(), &declarations, start, budget) +} + +fn check_from( + arena: &mut TermArena, + mut signature: Signature, + declarations: &[Declaration], + mut position: usize, + budget: &mut Budget, +) -> Result { while position < declarations.len() { let declaration = &declarations[position]; match declaration.kind { diff --git a/source-rust/subsystems/compiler/psi/semantics/proofs/mathematical/tests.rs b/source-rust/subsystems/compiler/psi/semantics/proofs/mathematical/tests.rs index 2a80e78e062d..dee459bdaed2 100644 --- a/source-rust/subsystems/compiler/psi/semantics/proofs/mathematical/tests.rs +++ b/source-rust/subsystems/compiler/psi/semantics/proofs/mathematical/tests.rs @@ -1,3 +1,51 @@ +mod extended_signatures { + use super::{default_budget, type_sort}; + use crate::{CoreError, Declaration, Term, TermArena, check_signature, extend_signature}; + + /// A table checked once and extended by a user is the signature a whole + /// check gives, and the extension alone is judged: an ill-formed added + /// declaration is refused at its position in the whole signature. + #[test] + fn an_extension_checks_only_what_it_adds() { + let mut arena = TermArena::new(); + let universe = type_sort(&mut arena, 0); + let carrier = arena.insert(Term::Constant { + declaration: 0, + levels: vec![], + }); + let table = [Declaration::assumption(0, universe)]; + let checked = check_signature(&mut arena, &table, &mut default_budget()).unwrap(); + let added = [Declaration::assumption(0, carrier)]; + let extended = + extend_signature(&mut arena, &checked, &added, &mut default_budget()).unwrap(); + let whole = check_signature( + &mut arena, + &[table[0].clone(), added[0].clone()], + &mut default_budget(), + ) + .unwrap(); + assert_eq!(extended.declarations(), whole.declarations()); + // A value of the carrier is no type: declaring something of it is + // refused at position 2, after the table and the first addition. + let value = arena.insert(Term::Constant { + declaration: 1, + levels: vec![], + }); + let refused = extend_signature( + &mut arena, + &checked, + &[added[0].clone(), Declaration::assumption(0, value)], + &mut default_budget(), + ) + .unwrap_err(); + assert_eq!(refused.declaration, 2); + assert!( + matches!(refused.error, CoreError::NotASort { .. }), + "{refused:?}" + ); + } +} + mod conversion_judgments { use super::{ apply, default_budget, empty, lambda, pi, squash, squash_intro, two, two_one, two_zero, diff --git a/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/compilation.rs b/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/compilation.rs index ea91f3d4cec4..042083472b83 100644 --- a/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/compilation.rs +++ b/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/compilation.rs @@ -227,13 +227,15 @@ impl<'source> PreparedClosure<'source> { ), ) }; - let mathematics = match mathematics_result { - Ok(mathematics) => mathematics, - Err(mut refused) => { - further.append(&mut refused); - Default::default() - } - }; + let mut mathematics: terminal_check_tables::mathematics::MathematicalSignature = + match mathematics_result { + Ok(mathematics) => mathematics, + Err(mut refused) => { + further.append(&mut refused); + Default::default() + } + }; + mathematics.identities = crate::identity_tables::of_forms(&forms); LoweredCompilationWithSource { source, program: TerminalCompilation::Prepared(PreparedCompilation { diff --git a/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/identity_tables.rs b/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/identity_tables.rs new file mode 100644 index 000000000000..73383715fb9e --- /dev/null +++ b/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/identity_tables.rs @@ -0,0 +1,235 @@ +/* +The Identity table of each generic check form with const record parameters +(`terminal_check_tables::mathematics::IdentityTable`). + +Stage 06 proves an Identity goal of a generic machine in the kernel. Beyond +the machine's own inputs, what such a goal names is the same in every +obligation of the form: the abstract carriers, the trait operations of its +const record parameters and the laws those parameters' traits state. This +reader collects them once per form, so stage 06 declares and checks them once +and each obligation adds only what it names of its own inputs. + +The operations are the ones the clause reader applied, which each record +parameter's binding keeps with the carriers they were read at +(`StaticRecordBinding::applied`). The laws are the `ensures` equalities of +the machines that stand for the records' law requirements in the form's +module. A law is written over its own formals, structural formals first and +then scalar ones, which is the order in which a citation supplies them. A law +that requires something, or whose equality names anything of a formal but +the whole value, stays out of the table, and stage 06 refuses a citation of +it. +*/ + +use semantic_vocabulary::{ + ClauseCarrier, ClauseIdentity, ClauseOperand, MachineId, Proposition, ScalarTerm, +}; +use terminal_check_tables::compilation::GenericForms; +use terminal_check_tables::mathematics::{IdentityLaw, IdentityOperation, IdentityTable}; +use terminal_check_tables::program::Elaboration; +use terminal_psi::MachineContract; + +/// The Identity table of every check form in `forms` that has const record +/// parameters. +pub(crate) fn of_forms(forms: &[GenericForms]) -> Vec { + let mut tables = Vec::new(); + for (declaration, generic) in forms.iter().enumerate() { + let Ok(elaborations) = &generic.forms else { + continue; + }; + for (form, elaboration) in elaborations.iter().enumerate() { + let (Ok(declaration), Ok(form)) = (u32::try_from(declaration), u32::try_from(form)) + else { + continue; + }; + tables.extend(of_form(elaboration, (declaration, form))); + } + } + tables +} + +fn of_form(elaboration: &Elaboration, form: (u32, u32)) -> Option { + let bindings: Vec<_> = elaboration + .static_schemas + .iter() + .flat_map(|schema| &schema.bindings) + .collect(); + if bindings.is_empty() { + return None; + } + let mut table = IdentityTable { + form, + suppliers: Vec::new(), + carriers: Vec::new(), + operations: Vec::new(), + laws: Vec::new(), + }; + let mut instances = Vec::new(); + for binding in bindings { + if !table.suppliers.contains(&binding.parameter) { + table.suppliers.push(binding.parameter); + } + for applied in &binding.applied { + operation(&mut table, applied.clone()); + } + instances.extend( + binding + .members + .iter() + .flat_map(|member| member.instances.iter().map(|instance| instance.machine)), + ); + } + instances.sort_unstable(); + instances.dedup(); + for instance in instances { + let Some(contract) = elaboration + .module + .invocation_machine_contract(instance, None) + else { + continue; + }; + if !contract.requires.is_empty() { + continue; + } + for (clause, ensured) in contract.ensures.iter().enumerate() { + let (Some(identity), Ok(clause)) = + (identity(&ensured.proposition), u32::try_from(clause)) + else { + continue; + }; + let Some(law) = law(instance, clause, contract, identity) else { + continue; + }; + add_identity(&mut table, identity); + for &formal in &law.formals { + carrier(&mut table, formal); + } + table.laws.push(law); + } + } + Some(table) +} + +fn identity(proposition: &Proposition) -> Option<&ClauseIdentity> { + match proposition { + Proposition::DeclarationIdentity(identity) if !identity.is_float_meaning() => { + Some(identity) + } + _ => None, + } +} + +/// Adds the carriers and operations an Identity names. +fn add_identity(table: &mut IdentityTable, identity: &ClauseIdentity) { + for value in &identity.values { + carrier(table, value.carrier); + match &value.operand { + ClauseOperand::Application { + declaration, + arguments, + } => { + let domains = arguments + .iter() + .filter_map(|&argument| identity.values.get(argument as usize)) + .map(|argument| argument.carrier) + .collect(); + operation( + table, + IdentityOperation { + declaration: *declaration, + domains, + result: value.carrier, + }, + ); + } + ClauseOperand::Scalar(term) => { + carrier(table, ClauseCarrier::Scalar(term.scalar_type())) + } + ClauseOperand::Input(_) | ClauseOperand::Formal(_) | ClauseOperand::FloatMeaning(_) => { + } + } + } +} + +fn carrier(table: &mut IdentityTable, carrier: ClauseCarrier) { + if !table.carriers.contains(&carrier) { + table.carriers.push(carrier); + } +} + +fn operation(table: &mut IdentityTable, operation: IdentityOperation) { + for &domain in &operation.domains { + carrier(table, domain); + } + carrier(table, operation.result); + if !table.operations.contains(&operation) { + table.operations.push(operation); + } +} + +/// The law `identity` states, over the formals of `contract`: each whole +/// structural formal and each scalar formal written as its position among +/// them. `None` when the equality names anything else of a formal, any +/// other input, or leaves a formal out, since no citation could supply it. +fn law( + instance: MachineId, + clause: u32, + contract: &MachineContract, + identity: &ClauseIdentity, +) -> Option { + let structural = contract.structural_parameters.len(); + let count = structural + contract.parameters.len(); + let mut formals: Vec> = vec![None; count]; + let mut statement = identity.clone(); + for value in &mut statement.values { + let position = match &value.operand { + ClauseOperand::Input(input) => { + let position = contract + .structural_parameters + .iter() + .position(|formal| formal.place == input.root())?; + if !input.path().is_empty() { + return None; + } + position + } + ClauseOperand::Scalar(ScalarTerm::Value { id, .. }) => { + structural + + contract + .parameters + .iter() + .position(|formal| formal.id == *id)? + } + ClauseOperand::Scalar(term) if mentions_value(term) => return None, + ClauseOperand::Formal(_) => return None, + _ => continue, + }; + if formals[position] + .replace(value.carrier) + .is_some_and(|known| known != value.carrier) + { + return None; + } + value.operand = ClauseOperand::Formal(u32::try_from(position).ok()?); + } + Some(IdentityLaw { + instance, + clause, + formals: formals.into_iter().collect::>()?, + statement, + }) +} + +/// Whether a scalar term reads a value: a law's citation supplies only a +/// whole formal, so a law that computes with one is not in the table. +fn mentions_value(term: &ScalarTerm) -> bool { + match term { + ScalarTerm::Value { .. } => true, + ScalarTerm::DeclarationApplication { arguments, .. } => { + arguments.iter().any(mentions_value) + } + ScalarTerm::Boolean(_) | ScalarTerm::Integer { .. } | ScalarTerm::IeeeFloatLiteral(_) => { + false + } + _ => true, + } +} diff --git a/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/lib.rs b/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/lib.rs index 77e255c6bab5..918624a11cea 100644 --- a/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/lib.rs +++ b/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/lib.rs @@ -49,6 +49,7 @@ mod compilation; mod components; mod declare; mod lower; +mod identity_tables; mod mathematics; mod policy; mod publication; 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..99b6acf3937c 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 @@ -1921,6 +1921,31 @@ impl Program<'_> { }; let position = u32::try_from(values.len()) .map_err(|_| unavailable("clause term table overflow"))?; + // An operation of a const record parameter is the same function + // wherever a clause applies it, so its record keeps it once for + // the Identity table of a generic check form. + if let ClauseOperand::Application { + declaration, + arguments, + } = &operand + && let Some((index, generation)) = declaration.supplier + && let Some(binding) = self + .static_contracts + .record_binding_mut(symbols::SymbolHandle::from_parts(index, generation)) + { + let applied = terminal_check_tables::mathematics::IdentityOperation { + declaration: *declaration, + domains: arguments + .iter() + .filter_map(|&argument| values.get(argument as usize)) + .map(|argument| argument.carrier) + .collect(), + result: carrier, + }; + if !binding.account.applied.contains(&applied) { + binding.account.applied.push(applied); + } + } values.push(ClauseValue { carrier, operand }); if reading_scalar { let term = crate::body::scalar_clause_value(inferred).ok_or_else(|| { diff --git a/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/record_parameters.rs b/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/record_parameters.rs index f6924cfffc36..a9095d28e7f2 100644 --- a/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/record_parameters.rs +++ b/source-rust/subsystems/compiler/source-to-psi/pipeline/05_prepared-typed-trees-to-lowered-program/src/read/record_parameters.rs @@ -115,6 +115,7 @@ impl Program<'_> { owner: typed.symbols.get(parameter.symbol).parent, application, members, + applied: Vec::new(), }, signatures, }, diff --git a/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/control_flow/joins.rs b/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/control_flow/joins.rs index 14ebc72f771d..9864afe6fe6c 100644 --- a/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/control_flow/joins.rs +++ b/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/control_flow/joins.rs @@ -1025,7 +1025,7 @@ pub(crate) struct Machine<'view, 'analysis> { /// The machine's values the integer rules do not reach /// (`crate::Unreached`). pub(crate) unreached: &'view [ValueId], - pub(crate) law_instances: &'view [MachineId], + pub(crate) law_instances: crate::equality::LawScope<'view>, } /// Admits the declared join predicates and infers the others (`prepare`), @@ -1095,7 +1095,8 @@ pub(crate) fn check<'a>( point, obligation, clause, - machine.law_instances, + machine.law_instances.instances, + machine.law_instances.identities, &mut machine.storage.at_entry(references, tables), ) .map(Discharged::Identity); diff --git a/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/lib.rs b/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/lib.rs index 6862b0038b74..69957b395840 100644 --- a/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/lib.rs +++ b/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/lib.rs @@ -563,6 +563,9 @@ pub(crate) struct PreparedDischarge<'l> { inhabitation: terminal_semantics::inhabitation::Inhabitation, unreached: Unreached, law_instances: Vec, + /// The Identity table of a generic check form with const record + /// parameters, checked once; `None` for any other module. + identities: Option, theorems: Vec<(MachineId, &'l laws::LawJudgment)>, inferred_calls: entry_inputs::InferredCalls, inferred_results: Vec<(MachineId, u32, terminal_psi::ContractClause)>, @@ -571,6 +574,7 @@ pub(crate) struct PreparedDischarge<'l> { pub(crate) fn prepare_discharge<'l>( elaboration: &mut Elaboration, laws: &'l [laws::LawJudgment], + identities: Option<&terminal_check_tables::mathematics::IdentityTable>, activity: &mut ProofSearchActivity, ) -> Checked> { for boundary in &elaboration.module.interfaces.boundary_machines { @@ -690,11 +694,14 @@ pub(crate) fn prepare_discharge<'l>( .map(move |law| (id, law)) }) .collect(); + let identities = + identities.map(|table| equality::check_identity_table(&scope.source().module, table)); let (inferred_calls, inferred_results) = scope.into_inferred(); Ok(PreparedDischarge { inhabitation, unreached, law_instances, + identities, theorems, inferred_calls, inferred_results, @@ -715,6 +722,7 @@ pub(crate) fn finish_discharge<'m>( inhabitation, unreached, law_instances, + identities, theorems, inferred_calls, inferred_results, @@ -787,7 +795,10 @@ pub(crate) fn finish_discharge<'m>( &beyond, inputs.carried.map(|position| &carried[position]), inputs.branches, - &law_instances, + equality::LawScope { + instances: &law_instances, + identities: identities.as_ref(), + }, proved, &empty_contracts, &summaries, @@ -827,7 +838,7 @@ pub(crate) fn discharge_inner( verified_borrow_ends: Option<&VerifiedBorrowEnds>, activity: &mut ProofSearchActivity, ) -> Checked { - let prepared = prepare_discharge(elaboration, laws, activity)?; + let prepared = prepare_discharge(elaboration, laws, None, activity)?; let summaries = terminal_semantics::plain_affine::AffineSummaries::new(&elaboration.module); let discharged = finish_discharge( ElaborationView { @@ -948,7 +959,7 @@ fn machine( unreached: &[ValueId], carried: Option<&Carried<'_>>, branches: &[terminal_check_tables::program::Branch], - law_instances: &[MachineId], + law_instances: equality::LawScope<'_>, proved: &[(MachineId, &laws::LawJudgment)], empty_contracts: &terminal_semantics::inhabitation::TerminalContracts<'_>, summaries: &ModuleReplays<'_>, @@ -1000,7 +1011,7 @@ fn check_prepared_machine( tables: &mut MachineTables, unreached: &[ValueId], carried: Option<&Carried<'_>>, - law_instances: &[MachineId], + law_instances: equality::LawScope<'_>, proved: &[(MachineId, &laws::LawJudgment)], empty_contracts: &terminal_semantics::inhabitation::TerminalContracts<'_>, borrow_ends: Option<&[(EdgeId, PlaceId)]>, @@ -1179,7 +1190,8 @@ fn check_prepared_machine( row.created_at, obligation, clause, - law_instances, + law_instances.instances, + law_instances.identities, &mut at_exit, ) .map(Discharged::Identity) @@ -1193,7 +1205,8 @@ fn check_prepared_machine( row.created_at, obligation, clause, - law_instances, + law_instances.instances, + law_instances.identities, &mut storage.at_entry(references, tables), ) .map(Discharged::Identity), @@ -1770,7 +1783,7 @@ impl PreparedMachine<'_, '_> { tables: &mut MachineTables, decided: &mut [Option>], unreached: &[ValueId], - law_instances: &[MachineId], + law_instances: equality::LawScope<'_>, activity: &mut ProofSearchActivity, ) -> Checked> { joins::check( @@ -1806,7 +1819,16 @@ impl PreparedMachine<'_, '_> { let mut decided = (0..tables.obligations.len()) .map(|_| None) .collect::>(); - self.check_joins(tables, &mut decided, &beyond, &[], activity)?; + self.check_joins( + tables, + &mut decided, + &beyond, + equality::LawScope { + instances: &[], + identities: None, + }, + activity, + )?; Ok(beyond) } } diff --git a/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/proofs/equality.rs b/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/proofs/equality.rs index 51aa8c33d6f4..4d872020db29 100644 --- a/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/proofs/equality.rs +++ b/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/proofs/equality.rs @@ -2390,14 +2390,15 @@ fn search( use crate::{call_contracts, graph::Graph, hypotheses}; use proof_admission::{ - Declaration, Level, MathematicalCertificate, MathematicalCoreDecision, - MathematicalJudgmentReceipt, Sort, check_signature, + Declaration, DeclarationKind, Level, MathematicalCertificate, MathematicalCoreDecision, + MathematicalJudgmentReceipt, Signature, Sort, check_signature, extend_signature, }; use semantic_vocabulary::{ CanonicalStructuralPathSegment, ClauseCarrier, ClauseDeclaration, ClauseIdentity, ClauseOperand, MachineId, ObligationId, PlaceId, Proposition, ScalarTerm, StructuralFieldId, StructuralTypeId, TargetMachineCallable, }; +use terminal_check_tables::mathematics::IdentityTable; use terminal_check_tables::{ Checked, Construct, KnowledgeId, MachineTables, ProgramPoint, RefusalReason, UnprovedCause, }; @@ -2413,7 +2414,7 @@ pub struct Judgment { } /// What one declaration of an obligation's kernel signature stands for. -#[derive(PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] enum Named { Carrier(FieldCarrier), Input(PlaceId), @@ -2440,6 +2441,9 @@ enum FieldCarrier { enum LawInput { Structural(PlaceId), Scalar(semantic_vocabulary::ValueId), + /// Formal `k` of a law in a machine's Identity table, written + /// `ClauseOperand::Formal(k)`. + Formal(u32), } /// One field of a record denoted as the product of its fields. @@ -2451,6 +2455,7 @@ struct Field { } /// A record whose value is the tuple of its fields, in declaration order. +#[derive(Clone)] struct Product { record: StructuralTypeId, fields: Vec, @@ -2475,8 +2480,9 @@ impl From for Unproved { struct Declarations<'a> { module: &'a TerminalModule, machine: &'a TerminalMachine, - /// What each field of an input held at the goal point. - entry: &'a mut dyn crate::Bindings, + /// What each field of an input held at the goal point. A machine's + /// Identity table names no input, so it is read without one. + entry: Option<&'a mut dyn crate::Bindings>, /// The values the inputs' fields held at the goal point, as their terms /// state them. An equality of one of them can rebuild an input. contents: Vec, @@ -2487,13 +2493,109 @@ struct Declarations<'a> { /// Records whose carrier is being declared, so a record that contained /// itself would be refused rather than declared forever. declaring: Vec, + /// The const record parameters of the generic check form whose Identity + /// table the obligation starts from. The table holds every operation of + /// theirs and every law, so an obligation that names another is refused. + suppliers: Option>, +} + +/// A generic check form's Identity table, declared and checked by the kernel +/// once (`check_identity_table`). Each Identity obligation of the form starts +/// from a copy and adds only what it names of its own inputs. +pub(crate) struct CheckedIdentityTable { + suppliers: Vec<(u32, u32)>, + arena: TermArena, + /// The table's declarations, every one ordinary and checked by the + /// kernel together. + declarations: Vec, + entries: Vec<(Named, TermHandle)>, + products: Vec, +} + +/// A generic check form's Identity table, checked, or the reason it could +/// not be. +pub(crate) type IdentityTables = Result; + +/// The law instances of a module and, for a generic check form, its +/// machines' Identity tables: what an Identity obligation may cite and start +/// from. +#[derive(Clone, Copy)] +pub(crate) struct LawScope<'t> { + pub(crate) instances: &'t [MachineId], + pub(crate) identities: Option<&'t IdentityTables>, +} + +/// Declares and checks `table` in `module`, the module of its check form, +/// once. +pub(crate) fn check_identity_table( + module: &TerminalModule, + table: &IdentityTable, +) -> IdentityTables { + let machine = module + .machines + .first() + .ok_or("an Identity table for a module with no machine")?; + let mut declarations = Declarations::new(module, machine, None); + let read = (|| { + for &carrier in &table.carriers { + declarations.carrier(carrier)?; + } + for operation in &table.operations { + let result = declarations.carrier(operation.result)?; + declarations.operation(operation.declaration, result, &operation.domains)?; + } + for law in &table.laws { + let count = u32::try_from(law.formals.len()).map_err(|_| "too many law formals")?; + let binders: Vec<_> = (0..count).map(LawInput::Formal).collect(); + let mut statement = declarations.identity(&law.statement, &binders)?; + for &carrier in law.formals.iter().rev() { + let domain = declarations.carrier(carrier)?; + statement = declarations.arena.insert(Term::Pi { + domain, + codomain: statement, + }); + } + declarations.entry(Named::Law(law.instance, law.clause), statement)?; + } + Ok::<_, &'static str>(()) + })(); + read.map_err(|why| format!("the machine's Identity table cannot be declared: {why}"))?; + // A checked table is extended without being checked again, from its + // declarations alone, which holds only for ordinary declarations: an + // inductive one is checked with tables of its own. + if declarations + .signature + .iter() + .any(|declaration| !matches!(declaration.kind, DeclarationKind::Ordinary)) + { + return Err("the machine's Identity table declares an inductive type".to_owned()); + } + check_signature( + &mut declarations.arena, + &declarations.signature, + &mut Budget::default(), + ) + .map_err(|error| { + format!("mathematical kernel refused the machine's Identity table: {error:?}") + })?; + Ok(CheckedIdentityTable { + suppliers: table + .suppliers + .iter() + .map(|supplier| (supplier.arena_index(), supplier.generation())) + .collect(), + arena: declarations.arena, + declarations: declarations.signature, + entries: declarations.entries, + products: declarations.products, + }) } impl<'a> Declarations<'a> { fn new( module: &'a TerminalModule, machine: &'a TerminalMachine, - entry: &'a mut dyn crate::Bindings, + entry: Option<&'a mut dyn crate::Bindings>, ) -> Self { Self { module, @@ -2505,6 +2607,32 @@ impl<'a> Declarations<'a> { signature: Vec::new(), products: Vec::new(), declaring: Vec::new(), + suppliers: None, + } + } + + /// An obligation of `machine` starting from its checked Identity table. + fn from_table( + module: &'a TerminalModule, + machine: &'a TerminalMachine, + table: &CheckedIdentityTable, + entry: &'a mut dyn crate::Bindings, + ) -> Self { + Self { + module, + machine, + entry: Some(entry), + contents: Vec::new(), + arena: table.arena.clone(), + entries: table + .entries + .iter() + .map(|(key, term)| (key.clone(), *term)) + .collect(), + signature: table.declarations.clone(), + products: table.products.clone(), + declaring: Vec::new(), + suppliers: Some(table.suppliers.clone()), } } @@ -2527,6 +2655,24 @@ impl<'a> Declarations<'a> { key: Named, declaration: Declaration, ) -> Result { + // What the table holds is the same in every obligation, so an + // obligation that names another is refused, never given a + // declaration of its own. + if let Some(suppliers) = &self.suppliers { + match &key { + Named::Operation(declaration) + if declaration + .supplier + .is_some_and(|supplier| suppliers.contains(&supplier)) => + { + return Err("a trait operation that is not in the form's Identity table"); + } + Named::Law(..) => { + return Err("a cited law that is not in the form's Identity table"); + } + _ => {} + } + } let index = u32::try_from(self.signature.len()).map_err(|_| "signature exceeds its index width")?; let term = self.arena.insert(Term::Constant { @@ -2735,7 +2881,11 @@ impl<'a> Declarations<'a> { carrier: FieldCarrier, ) -> Result, &'static str> { if let FieldCarrier::Clause(ClauseCarrier::Scalar(scalar)) = carrier { - let Ok(held) = self.entry.field( + let entry = self + .entry + .as_deref_mut() + .ok_or("an Identity table names no input")?; + let Ok(held) = entry.field( semantic_vocabulary::ContentPlaceVersion::Current, root, path, @@ -2765,12 +2915,13 @@ impl<'a> Declarations<'a> { Ok(self.arena.tuple(&components)) } - fn application( + /// The entry of an applied declaration, a function from `domains` to + /// `result`. + fn operation( &mut self, declaration: ClauseDeclaration, result: TermHandle, domains: &[ClauseCarrier], - arguments: &[TermHandle], ) -> Result { let mut function_type = result; for &carrier in domains.iter().rev() { @@ -2780,7 +2931,17 @@ impl<'a> Declarations<'a> { codomain: function_type, }); } - let operation = self.entry(Named::Operation(declaration), function_type)?; + self.entry(Named::Operation(declaration), function_type) + } + + fn application( + &mut self, + declaration: ClauseDeclaration, + result: TermHandle, + domains: &[ClauseCarrier], + arguments: &[TermHandle], + ) -> Result { + let operation = self.operation(declaration, result, domains)?; Ok(self.arena.apply_arguments(operation, arguments)) } @@ -2870,6 +3031,16 @@ impl<'a> Declarations<'a> { .collect::>(); self.application(*declaration, ty, &domains, &operands)? } + ClauseOperand::Formal(formal) + if let Some(position) = binders + .iter() + .position(|binder| *binder == LawInput::Formal(*formal)) => + { + self.arena.insert(Term::Variable( + u32::try_from(binders.len() - position - 1) + .map_err(|_| "too many law formals")?, + )) + } ClauseOperand::Formal(_) | ClauseOperand::FloatMeaning(_) => { return Err("no whole-value mathematical input for this clause operand"); } @@ -3055,6 +3226,7 @@ pub(crate) fn discharge( obligation: ObligationId, goal: &ClauseIdentity, law_instances: &[MachineId], + identities: Option<&IdentityTables>, entry: &mut dyn crate::Bindings, ) -> Checked { let known = hypotheses(graph, tables, machine.id, obligation, point)?; @@ -3066,7 +3238,17 @@ pub(crate) fn discharge( why, ) }; - let mut declarations = Declarations::new(module, machine, entry); + // A machine of a generic check form with const record parameters + // starts from the form's Identity table, which the kernel checked once. + // Any other machine has no trait operation or law to share and declares + // what each obligation names. + let table = identities + .map(|table| table.as_ref().map_err(|why| unavailable(why))) + .transpose()?; + let mut declarations = match table { + Some(table) => Declarations::from_table(module, machine, table, entry), + None => Declarations::new(module, machine, Some(entry)), + }; let expected = declarations.identity(goal, &[]).map_err(unavailable)?; let mut proofs = Vec::new(); let mut citations = Vec::new(); @@ -3211,11 +3393,21 @@ pub(crate) fn discharge( ), ) }; - let signature = check_signature( - &mut declarations.arena, - &declarations.signature, - &mut budget, - ) + // Only what this obligation added after the table is checked here. + let signature = match table { + Some(table) => extend_signature( + &mut declarations.arena, + &Signature::from_declarations(table.declarations.clone()), + &declarations.signature[table.declarations.len()..], + &mut budget, + ) + .map_err(|refused| refused.error), + None => check_signature( + &mut declarations.arena, + &declarations.signature, + &mut budget, + ), + } .map_err(|error| kernel_error(error.into()))?; let mut context = Context::empty().with_signature(signature); for index in 0..premises.len() { diff --git a/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/proofs/laws.rs b/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/proofs/laws.rs index 6d8938d9d196..51a17425407e 100644 --- a/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/proofs/laws.rs +++ b/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/proofs/laws.rs @@ -256,6 +256,8 @@ fn judge_laws( licenses, integers, families, + // Each generic check form's tables are checked with its module. + identities: _, } = signature; let extras = Extras { integers, diff --git a/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/tests/record_identity.rs b/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/tests/record_identity.rs index 6ce7831f3792..a1771bd46524 100644 --- a/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/tests/record_identity.rs +++ b/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/tests/record_identity.rs @@ -450,6 +450,7 @@ fn records_with_reference_view_atomic_or_erased_fields_refuse_at_the_unproved_fi obligation, &goal, &[], + None, &mut storage.at_entry(&mut references, tables), ) else { panic!("{kind}: missing opaque field identity must be refused"); diff --git a/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/tests/semiring_identity.rs b/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/tests/semiring_identity.rs index 5b7db503fbf7..0a6861932dc9 100644 --- a/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/tests/semiring_identity.rs +++ b/source-rust/subsystems/compiler/source-to-psi/pipeline/06_lowered-program-to-checked-program/src/tests/semiring_identity.rs @@ -60,6 +60,14 @@ const CITED: &str = include_str!("../../tests/fixtures/semiring_identity/pass/ci const UNCITED: &str = include_str!("../../tests/fixtures/semiring_identity/fail/uncited/main.omg"); fn generic(source: &str) -> RouteVerdict { + generic_with_tables(source, |_| {}) +} + +/// `generic`, after `change` has edited the Identity tables stage 05 wrote. +fn generic_with_tables( + source: &str, + change: impl FnOnce(&mut Vec), +) -> RouteVerdict { let typed = super::build_purpose::frontier_with_core( source, "machine build_entry() {}", @@ -88,7 +96,13 @@ fn generic(source: &str) -> RouteVerdict { terminal_codec::TerminalPublication::Invocation, ) .unwrap(); - let mut parts = crate::judge_compilation(compilation.program).into_iter(); + let mut program = compilation.program; + if let terminal_check_tables::compilation::TerminalCompilation::Prepared(prepared) = + &mut program + { + change(&mut prepared.mathematics.identities); + } + let mut parts = crate::judge_compilation(program).into_iter(); let closure = parts.next().expect("package judgment").unwrap(); assert!(matches!(closure, RouteVerdict::Accepted(_)), "{closure:?}"); let form = parts.next().expect("generic machine judgment").unwrap(); @@ -103,6 +117,108 @@ fn semiring_identity_uses_the_cited_law() { assert_cited_semiring_identity(generic(CITED)); } +/// The generic machine's carrier `T`, the operation `Ring::add` and the law +/// `Ring::add_comm` are one table of the mathematical signature, which the +/// kernel checks once. The judged Identity starts from that table and adds +/// only the machine's two inputs. +#[test] +fn semiring_identity_starts_from_the_forms_identity_table() { + let mut table = None; + let verdict = generic_with_tables(CITED, |tables| { + let [only] = tables.as_slice() else { + panic!("one generic check form has one Identity table: {tables:?}"); + }; + table = Some(only.clone()); + }); + let table = table.unwrap(); + assert_eq!(table.suppliers.len(), 1, "{table:?}"); + assert!( + table + .carriers + .contains(&semantic_vocabulary::ClauseCarrier::Parameter(0)), + "{table:?}" + ); + let add = table + .operations + .iter() + .find(|operation| operation.domains.len() == 2) + .unwrap_or_else(|| panic!("the table declares `Ring::add`: {table:?}")); + assert_eq!( + add.declaration.supplier, + Some(( + table.suppliers[0].arena_index(), + table.suppliers[0].generation() + )) + ); + assert!(!table.laws.is_empty(), "{table:?}"); + let RouteVerdict::Accepted(closure) = verdict else { + panic!("{verdict:?}") + }; + let guarantees = verdicts(closure.elaboration(), closure.discharge(), 1, guarantee); + let [(_, Ok(Discharged::Identity(judgment)))] = guarantees.as_slice() else { + panic!("{guarantees:?}") + }; + let checked = terminal_codec::decode_mathematical_certificate(&judgment.certificate).unwrap(); + // Every declaration past the table is one of the machine's two inputs. + let declared = checked.certificate.signature.len(); + let table_declarations = declared - 2; + assert!( + checked.certificate.signature[table_declarations..] + .iter() + .all(proof_admission::Declaration::is_assumption) + ); + assert!(table_declarations > table.carriers.len() + table.operations.len()); +} + +/// The twin: the same program, with the law it cites missing from the +/// table. The obligation does not declare the law itself; it is refused. +#[test] +fn a_cited_law_missing_from_the_identity_table_is_refused() { + let verdict = generic_with_tables(CITED, |tables| tables[0].laws.clear()); + assert_refused_for( + verdict, + "a cited law that is not in the form's Identity table", + ); +} + +/// The twin for an operation: with `Ring::add` missing from the table, the +/// goal that applies it is refused rather than given a declaration of its own. +#[test] +fn a_trait_operation_missing_from_the_identity_table_is_refused() { + let verdict = generic_with_tables(CITED, |tables| { + tables[0].operations.clear(); + tables[0].laws.clear(); + }); + assert_refused_for( + verdict, + "a trait operation that is not in the form's Identity table", + ); +} + +/// The twin for a table the kernel does not accept: an operation declared at +/// a carrier the table never declared is refused for every Identity of the +/// form, with the reason. +#[test] +fn an_identity_table_the_kernel_refuses_refuses_the_forms_identities() { + let verdict = generic_with_tables(CITED, |tables| { + let table = &mut tables[0]; + let mut twice = table.operations[0].clone(); + twice.result = + semantic_vocabulary::ClauseCarrier::Scalar(semantic_vocabulary::ScalarType::Boolean); + table.operations.push(twice); + }); + assert_refused_for(verdict, "the machine's Identity table cannot be declared"); +} + +fn assert_refused_for(verdict: RouteVerdict, reason: &str) { + let text = format!("{verdict:?}"); + assert!( + !matches!(verdict, RouteVerdict::Accepted(_)), + "the guarantee must not be judged: {text}" + ); + assert!(text.contains(reason), "expected `{reason}`: {text}"); +} + fn assert_cited_semiring_identity(verdict: RouteVerdict) { let RouteVerdict::Accepted(closure) = verdict else { panic!("expected an accepted generic contract: {verdict:?}") @@ -392,15 +508,16 @@ fn an_erased_application_keeps_its_selected_semiring() { if requirement(&failure.kind) && failure.cause == UnprovedCause::NoDerivation)); } - #[test] fn a_type_definition_body_forms_identity_through_the_clause_reader() { - let verdict = generic(r#" + let verdict = generic( + r#" use {omega}/language/core/proof_clause_operation.omg; use {omega}/language/core/foundation.omg as proof; let same(x: u64): |proof|::Type<0> = |proof|::Identity::(|proof_clause_operation|::f(x), |proof_clause_operation|::f(x)); machine entry(x: u64, _fallback: T) ensures same(x) {} -"#); +"#, + ); let RouteVerdict::Accepted(closure) = verdict else { panic!("{verdict:?}"); }; 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..3cf4b2bcc84f 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 @@ -715,7 +715,8 @@ fn exceeded_reach( crate::ceilings::Permission::Entry( terminal_psi::TerminalCallableInvocation::Service(service), ) => module - .interfaces.services + .interfaces + .services .iter() .find(|declaration| declaration.id == *service) .and_then(|declaration| module.identities.text(declaration.identity)) @@ -946,7 +947,7 @@ pub(super) fn judge_owing_with_activity( activity: &mut crate::ProofSearchActivity, ) -> Checked { let mut further = Vec::new(); - match examine(elaborated, &[], &[], activity, &mut further) { + match examine(elaborated, &[], &[], None, activity, &mut further) { Ok(examined) => conclude(examined, applied, true, &mut further), Err(decided) => decided, } @@ -975,6 +976,7 @@ fn examine( elaborated: Checked, carried: &[crate::Carried<'_>], laws: &[crate::laws::LawJudgment], + identities: Option<&terminal_check_tables::mathematics::IdentityTable>, activity: &mut crate::ProofSearchActivity, further: &mut Vec, ) -> Result> { @@ -1020,7 +1022,7 @@ fn examine( crate::nominal_calls::validate(&elaboration).map_err(fall_back_or_defect)?; crate::static_reach::validate(&elaboration).map_err(fall_back_or_defect)?; crate::owned_cleanup::materialize(&mut elaboration).map_err(fall_back_or_defect)?; - let prepared = match crate::prepare_discharge(&mut elaboration, laws, activity) { + let prepared = match crate::prepare_discharge(&mut elaboration, laws, identities, activity) { Ok(prepared) => prepared, Err(refused) => { let summaries = @@ -1382,11 +1384,23 @@ fn conclude( // equality identifies the exact claim to underline on that path. let claim_site = match row.kind { ObligationKind::NormalGuarantee { clause, .. } - if elaboration.module.machine(machine) + if elaboration + .module + .machine(machine) .and_then(|body| body.ensures.get(clause as usize)) - .is_some_and(|row| matches!(row.proposition, semantic_vocabulary::Proposition::DeclarationIdentity(_))) => { - elaboration.names.get(machine).and_then(|names| names.ensures.get(clause as usize)) - .and_then(|text| text.source).map(SourceOrigin::Authored) + .is_some_and(|row| { + matches!( + row.proposition, + semantic_vocabulary::Proposition::DeclarationIdentity(_) + ) + }) => + { + elaboration + .names + .get(machine) + .and_then(|names| names.ensures.get(clause as usize)) + .and_then(|text| text.source) + .map(SourceOrigin::Authored) } _ => None, }; @@ -1639,11 +1653,8 @@ fn conclude( })?; if elaboration.module.identities.invocation_scope().is_some() { let inferred = std::mem::take(&mut discharged.inferred_results); - let results = crate::result_summaries::checked_results( - inferred, - &elaboration, - &discharged, - )?; + let results = + crate::result_summaries::checked_results(inferred, &elaboration, &discharged)?; elaboration .module .identities @@ -1749,7 +1760,8 @@ fn judge_compilation_with_activity_and_policy( } // Judge the compilation-wide laws before checking machines that cite them. - let mathematics = prepared.mathematics; + let mut mathematics = prepared.mathematics; + let identities = std::mem::take(&mut mathematics.identities); let signature = (!mathematics.is_empty()).then(|| crate::laws::judge_with_policy(mathematics, policy)); let laws = signature @@ -1760,6 +1772,7 @@ fn judge_compilation_with_activity_and_policy( prepared.forms, prepared.witnesses, laws, + &identities, activity, &mut further, ); @@ -1775,13 +1788,7 @@ fn judge_compilation_with_activity_and_policy( &examined_witnesses, ); let carried = carried(&closure, &forms, &witnesses, &prepared.specializations); - match examine( - Ok(closure), - &carried, - laws, - activity, - &mut further, - ) { + match examine(Ok(closure), &carried, laws, None, activity, &mut further) { Ok(examined) => conclude(examined, AppliedContracts::Undecided, true, &mut further), Err(decided) => decided, } @@ -1864,12 +1871,13 @@ fn examine_forms_and_witnesses( forms: Vec, witnesses: Vec>, laws: &[crate::laws::LawJudgment], + identities: &[terminal_check_tables::mathematics::IdentityTable], activity: &mut crate::ProofSearchActivity, further: &mut Vec, ) -> (Vec, Vec) { let (forms, examined) = if worker_budget::current_workers() == 1 || forms.is_empty() || witnesses.is_empty() { - let forms = examine_generic_forms(forms, laws, activity, further); + let forms = examine_generic_forms(forms, laws, identities, activity, further); let examined = examine_witnesses(witnesses, laws, activity); (forms, examined) } else { @@ -1877,7 +1885,15 @@ fn examine_forms_and_witnesses( let mut forms_activity = crate::ProofSearchActivity::default(); let mut witness_activity = crate::ProofSearchActivity::default(); let (forms, examined) = rayon::join( - || examine_generic_forms(forms, laws, &mut forms_activity, &mut forms_further), + || { + examine_generic_forms( + forms, + laws, + identities, + &mut forms_activity, + &mut forms_further, + ) + }, || examine_witnesses(witnesses, laws, &mut witness_activity), ); further.extend(forms_further); @@ -1980,7 +1996,7 @@ fn examine_witnesses( .into_iter() .map(|witness| { let mut further = Vec::new(); - let examined = examine(witness, &[], laws, activity, &mut further); + let examined = examine(witness, &[], laws, None, activity, &mut further); (examined, further) }) .collect(); @@ -1992,7 +2008,7 @@ fn examine_witnesses( .map(|witness| { let mut local_activity = crate::ProofSearchActivity::default(); let mut further = Vec::new(); - let examined = examine(witness, &[], laws, &mut local_activity, &mut further); + let examined = examine(witness, &[], laws, None, &mut local_activity, &mut further); ((examined, further), local_activity) }) .collect(); @@ -2236,12 +2252,13 @@ fn carried<'a>( fn examine_generic_forms( forms: Vec, laws: &[crate::laws::LawJudgment], + identities: &[terminal_check_tables::mathematics::IdentityTable], activity: &mut crate::ProofSearchActivity, further: &mut Vec, ) -> Vec { let count = forms.len(); let mut examined = Vec::new(); - for form in forms { + for (declaration, form) in forms.into_iter().enumerate() { let template = form.template; if form .applies @@ -2261,8 +2278,15 @@ fn examine_generic_forms( continue; } match form.forms { - Ok(forms) => examined.extend(forms.into_iter().map(|form| { - match examine(Ok(form), &[], laws, activity, further) { + Ok(forms) => examined.extend(forms.into_iter().enumerate().map(|(position, form)| { + // The Identity table stage 05 wrote for this form. + let table = identities.iter().find(|table| { + u32::try_from(declaration).is_ok_and(|declaration| { + u32::try_from(position) + .is_ok_and(|position| table.form == (declaration, position)) + }) + }); + match examine(Ok(form), &[], laws, table, activity, further) { Ok(examined) => GenericForm::Examined { template, examined }, Err(decided) => GenericForm::Decided(decided), } diff --git a/source-rust/subsystems/compiler/source-to-psi/representations/lowered-program/README.md b/source-rust/subsystems/compiler/source-to-psi/representations/lowered-program/README.md index aff894488e81..4a0a82b283d1 100644 --- a/source-rust/subsystems/compiler/source-to-psi/representations/lowered-program/README.md +++ b/source-rust/subsystems/compiler/source-to-psi/representations/lowered-program/README.md @@ -114,8 +114,23 @@ closure in `PreparedCompilation::mathematics`: declares it, and a distributivity law may regroup under the one-operation laws. A law of the right shape that satisfies no requirement licenses nothing. - -Stage 05 writes the table ([`read/signature.rs`](../../pipeline/05_prepared-typed-trees-to-lowered-program/src/read/signature.rs)). +- **Identity tables**: one per generic check form with const record + parameters (`IdentityTable`, keyed by the form's declaration and form + position). It holds what every Identity goal of the form names beyond its + own inputs: the carriers, the trait operations the clause reader applied + through the record parameters (`StaticRecordBinding::applied`) and the + laws those parameters' traits state. A law is the `ensures` equality of the + machine standing for a record's law requirement, written over its formals + (`ClauseOperand::Formal`), structural formals first. A law that requires + something, or names part of a formal, stays out, and a citation of it is + refused. Stage 06 checks the table once per form and starts each + obligation from it, adding only the obligation's own inputs + (`extend_signature`). An obligation that names a trait operation or a law + missing from its form's table is refused, and so is every Identity goal of + a form whose table the kernel refuses. + +Stage 05 writes the table ([`read/signature.rs`](../../pipeline/05_prepared-typed-trees-to-lowered-program/src/read/signature.rs); +Identity tables in [`identity_tables.rs`](../../pipeline/05_prepared-typed-trees-to-lowered-program/src/identity_tables.rs)). Stage 06 checks every declaration once with the kernel and judges each law ([`laws.rs`](../../pipeline/06_lowered-program-to-checked-program/src/laws.rs)). Once the compilation is accepted, stage 06 writes each data declaration, diff --git a/source-rust/subsystems/compiler/source-to-psi/representations/lowered-program/mathematics.rs b/source-rust/subsystems/compiler/source-to-psi/representations/lowered-program/mathematics.rs index 6d9cf0c94443..e6b83683f58d 100644 --- a/source-rust/subsystems/compiler/source-to-psi/representations/lowered-program/mathematics.rs +++ b/source-rust/subsystems/compiler/source-to-psi/representations/lowered-program/mathematics.rs @@ -31,6 +31,55 @@ pub struct MathematicalSignature { /// Each data declaration indexed by values, as the kernel's builder /// declared it. A law over one names it by its position here. pub families: Vec, + /// What the Identity goals of each generic check form with const + /// record parameters name that is the same in every one of its + /// obligations: the carriers its trait operations take and give, those + /// operations and the laws its machines may cite. Stage 06 declares and + /// checks each table once, and every Identity obligation of the form + /// starts from it. + pub identities: Vec, +} + +/// The Identity table of one generic check form. Its carriers and law +/// instances are identities of that form's module. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IdentityTable { + /// The check form: its generic declaration's position in + /// `PreparedCompilation::forms`, then its own among that declaration's + /// forms. + pub form: (u32, u32), + /// The form's const record parameters, the suppliers of its trait + /// operations. An Identity obligation that applies an operation of one of + /// them must find it here. + pub suppliers: Vec, + /// Every carrier the operations and laws name: the form's type + /// parameters and whatever data or scalars the operations take and give. + pub carriers: Vec, + pub operations: Vec, + pub laws: Vec, +} + +/// A trait operation, as a function from its domains to its result. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IdentityOperation { + pub declaration: semantic_vocabulary::ClauseDeclaration, + pub domains: Vec, + pub result: semantic_vocabulary::ClauseCarrier, +} + +/// One `ensures` equality of a law requirement of one of the form's const +/// record parameters. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IdentityLaw { + /// The machine that stands for the requirement in the form's module. + pub instance: semantic_vocabulary::MachineId, + /// Its position among that machine's `ensures` clauses. + pub clause: u32, + /// The carrier of each formal, structural formals first and then scalar + /// ones, as a citation supplies them. + pub formals: Vec, + /// The equality, with formal `k` written `ClauseOperand::Formal(k)`. + pub statement: semantic_vocabulary::ClauseIdentity, } /// The declarations of the integer vocabulary, by position. diff --git a/source-rust/subsystems/compiler/source-to-psi/representations/lowered-program/tables/contracts.rs b/source-rust/subsystems/compiler/source-to-psi/representations/lowered-program/tables/contracts.rs index 850089b64e7a..76079b214575 100644 --- a/source-rust/subsystems/compiler/source-to-psi/representations/lowered-program/tables/contracts.rs +++ b/source-rust/subsystems/compiler/source-to-psi/representations/lowered-program/tables/contracts.rs @@ -354,6 +354,11 @@ pub struct StaticRecordBinding { pub owner: SymbolHandle, pub application: String, pub members: Vec, + /// Each requirement of this record that a clause applies, as the clause + /// reader read it: the carriers of its operands and of its result. A + /// generic check form's Identity table declares each once + /// (`crate::mathematics::IdentityTable`). + pub applied: Vec, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -478,6 +483,7 @@ mod static_record_instance_tests { arguments: Vec::new(), }], }], + applied: Vec::new(), }; let first = binding(4, 11); let mut second = binding(5, 12); diff --git a/wiki/drafts/designs/proof_kernel_core_audit.md b/wiki/drafts/designs/proof_kernel_core_audit.md index 974a04717b1b..bb80d1e84ec8 100644 --- a/wiki/drafts/designs/proof_kernel_core_audit.md +++ b/wiki/drafts/designs/proof_kernel_core_audit.md @@ -989,9 +989,13 @@ none`, which a clause application now requires. What step 2 did not build: a receiver trusts the producer and does not replay carried certificates, so nothing would check a published one. A row for laws waits for a consumer that reads it. -- **One table for step 1's goals.** A generic machine's Identity goal still - gets its own table per obligation in `equality::discharge`. Only the - declarations over data that contains itself are in the shared signature. +- **One table for step 1's goals.** Built. Each generic check form with + const record parameters has one Identity table in the mathematical + signature: its carriers, the trait operations its clauses apply and the + laws its record parameters' traits state. Stage 06 checks it once and + `equality::discharge` extends it with each obligation's own inputs. + Concrete modules (closure, witnesses, arrivals) still declare their names + per obligation, since they have no trait operations to share. - **Projection, and fields of another type.** A field of a case is read only through the dispatch that binds it. Data whose case has a field of another type is refused, because that type has no carrier in the signature yet.