Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion TASKS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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::<U8_LAWS.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)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -213,8 +213,33 @@ pub fn check_signature_with_attribution(
declarations: &[Declaration],
budget: &mut Budget,
) -> Result<Signature, SignatureCheckError> {
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<Signature, SignatureCheckError> {
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<Signature, SignatureCheckError> {
while position < declarations.len() {
let declaration = &declarations[position];
match declaration.kind {
Expand Down
Original file line number Diff line number Diff line change
@@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
@@ -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<IdentityTable> {
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<IdentityTable> {
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<IdentityLaw> {
let structural = contract.structural_parameters.len();
let count = structural + contract.parameters.len();
let mut formals: Vec<Option<ClauseCarrier>> = 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::<Option<_>>()?,
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,
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ mod compilation;
mod components;
mod declare;
mod lower;
mod identity_tables;
mod mathematics;
mod policy;
mod publication;
Expand Down
Loading
Loading