iter remove-mut-var-assign.1: atomic removal of mut/var/assign
mut/var/assign removed from AILang entirely and atomically. Deleted: Term::Mut/Term::Assign/struct MutVar; the three Form-A keywords + parse_mut/parse_assign + grammar EBNF; the 4 mut CheckError variants; the mut_scope_stack synth threading (param dropped from synth + every internal/external/test caller); the two lower_term arms; and every exhaustive no-_ Term::Mut/Term::Assign match arm across 17 source files — cut in lockstep with DESIGN.md, fixtures, the drift trio, carve-out and roadmap so the schema is honest at every commit. No catch-all wildcard introduced (verified). loop/recur + let/if are the surviving forms. The shared codegen alloca machinery survives (loop reuses it): mut_var_allocas renamed binder_allocas (representation-only, loop codegen byte-identical) and the shared Term::Lam escape guard simplified to !loop_stack.is_empty() with the loop half (LoopBinderCapturedByLambda) byte-equivalent. Feature-acceptance applied inverted: the removed feature fails clause 2 (redundant) and clause 3 (IS the iterated-mutable-state bug class). Behaviour preservation is executable: mut_counter/mut_sum_floats still print 55 after the faithful let/if rewrite. The removal is made executable by the new mut_removed_pin.rs (4 must-fail pins). Independent verification: cargo test --workspace 605/0, zero residual mut symbols in any crate source, loop/recur non-regression all green (55 / 500000500000 / infinite-compiles / the lambda_capturing_loop_binder pin), roundtrip_cli PASS. One DONE_WITH_CONCERNS: a 4th recurrence of the recon-undercount class (in-source mod tests + a drift-pin fn + 5 orphaned mut .ail.json carve-outs + a non-enumerated E0599); all resolved within implementer remit, no behaviour change. Milestone-close audit then fieldtest remain. spec docs/specs/2026-05-18-remove-mut-var-assign.md (grounding PASS) plan docs/plans/remove-mut-var-assign.1.md
This commit is contained in:
@@ -1513,37 +1513,6 @@ fn walk_term(
|
||||
walk_term(source, out, builtins, scope);
|
||||
walk_term(body, out, builtins, scope);
|
||||
}
|
||||
// Iter mut.1: each `var` introduces a new lexical binding;
|
||||
// its `init` is in the outer scope plus already-declared
|
||||
// vars; the body sees all of them. Mirrors `Term::Lam`'s
|
||||
// newly-bound roll-back convention.
|
||||
Term::Mut { vars, body } => {
|
||||
let mut newly = Vec::new();
|
||||
for v in vars {
|
||||
walk_term(&v.init, out, builtins, scope);
|
||||
if scope.insert(v.name.clone()) {
|
||||
newly.push(v.name.clone());
|
||||
}
|
||||
}
|
||||
walk_term(body, out, builtins, scope);
|
||||
for n in newly {
|
||||
scope.remove(&n);
|
||||
}
|
||||
}
|
||||
// Iter mut.1: the `value` is walked; the assigned `name` is
|
||||
// a use of an in-scope mut-var. If the user wrote an
|
||||
// out-of-scope assign, it surfaces as an unknown identifier
|
||||
// in the dep walk, which is acceptable for the CLI's
|
||||
// dependency view (typecheck would already have rejected).
|
||||
Term::Assign { name, value } => {
|
||||
if !name.contains('.')
|
||||
&& !scope.contains(name)
|
||||
&& !builtins.contains(name.as_str())
|
||||
{
|
||||
out.insert(name.clone());
|
||||
}
|
||||
walk_term(value, out, builtins, scope);
|
||||
}
|
||||
Term::Loop { binders, body } => {
|
||||
let mut newly = Vec::new();
|
||||
for b in binders {
|
||||
@@ -2765,44 +2734,6 @@ fn rewrite_def(
|
||||
changed,
|
||||
);
|
||||
}
|
||||
// Iter mut.1: rewrite types embedded in each `MutVar.ty`
|
||||
// (via `rewrite_type` — mut-vars carry full Type
|
||||
// annotations) and recurse into each var's `init` and
|
||||
// the block's body. `Term::Assign` has no embedded type.
|
||||
Term::Mut { vars, body } => {
|
||||
for v in vars {
|
||||
rewrite_type(
|
||||
&mut v.ty,
|
||||
owning_module,
|
||||
local_types,
|
||||
import_names,
|
||||
changed,
|
||||
);
|
||||
rewrite_term(
|
||||
&mut v.init,
|
||||
owning_module,
|
||||
local_types,
|
||||
import_names,
|
||||
changed,
|
||||
);
|
||||
}
|
||||
rewrite_term(
|
||||
body,
|
||||
owning_module,
|
||||
local_types,
|
||||
import_names,
|
||||
changed,
|
||||
);
|
||||
}
|
||||
Term::Assign { value, .. } => {
|
||||
rewrite_term(
|
||||
value,
|
||||
owning_module,
|
||||
local_types,
|
||||
import_names,
|
||||
changed,
|
||||
);
|
||||
}
|
||||
Term::Loop { binders, body } => {
|
||||
for b in binders {
|
||||
rewrite_type(
|
||||
|
||||
@@ -91,20 +91,9 @@ fn synthesised_print_uses_user_module_show_via_fallback() {
|
||||
Term::ReuseAs { source, body } => {
|
||||
contains_xmod_show_var(source) || contains_xmod_show_var(body)
|
||||
}
|
||||
// Iter mut.1: a `Term::Mut` cannot itself host a
|
||||
// `show_user_adt.show__<T>` reference (its body is a
|
||||
// mut-block, not a synthesised polymorphic call), but
|
||||
// recurse defensively so any nested reference inside a
|
||||
// var init / body / assign-value still surfaces.
|
||||
Term::Mut { vars, body } => {
|
||||
vars.iter().any(|v| contains_xmod_show_var(&v.init))
|
||||
|| contains_xmod_show_var(body)
|
||||
}
|
||||
Term::Assign { value, .. } => contains_xmod_show_var(value),
|
||||
// loop-recur iter 1: a `Term::Loop` cannot itself host a
|
||||
// synthesised cross-module reference, but recurse
|
||||
// defensively through binder inits / body / recur args,
|
||||
// mirroring the `Term::Mut` arm above.
|
||||
// defensively through binder inits / body / recur args.
|
||||
Term::Loop { binders, body } => {
|
||||
binders.iter().any(|b| contains_xmod_show_var(&b.init))
|
||||
|| contains_xmod_show_var(body)
|
||||
|
||||
@@ -187,48 +187,23 @@ fn check_ordering_match_post_migration_is_clean() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Property (RED — fieldtest mut-local F2): in non-JSON (human) mode,
|
||||
/// the human-stderr formatter prepends the diagnostic code exactly once
|
||||
/// as the canonical `[code]` bracket prefix (the cli-diag-human format).
|
||||
/// The four mut-local `CheckError` variants
|
||||
/// (`mut-assign-out-of-scope`, `assign-type-mismatch`,
|
||||
/// `mut-var-unsupported-type`, `mut-var-captured-by-lambda`) must NOT
|
||||
/// also embed `[code] ` inside their `thiserror` Display body, which
|
||||
/// would render the bracketed code TWICE in the user-visible stderr
|
||||
/// line (`error: [code] fn: [code] message`).
|
||||
/// Property: in non-JSON (human) mode, the human-stderr formatter
|
||||
/// prepends the diagnostic code exactly once as the canonical
|
||||
/// `[code]` bracket prefix (the cli-diag-human format). The
|
||||
/// `loop-binder-captured-by-lambda` `CheckError` Display body must
|
||||
/// NOT also embed `[code] ` inside its `thiserror` Display body,
|
||||
/// which would render the bracketed code TWICE in the user-visible
|
||||
/// stderr line (`error: [code] fn: [code] message`).
|
||||
///
|
||||
/// This pins the *observable* doubling on the real CLI human path
|
||||
/// (`crates/ail/src/main.rs` non-JSON `Cmd::Check` arm), not the raw
|
||||
/// Display string of one variant in isolation: it counts occurrences
|
||||
/// of the literal `[<code>]` token in the rendered stderr and requires
|
||||
/// exactly one. Drops to GREEN once the four Display bodies shed their
|
||||
/// leading `[<code>] ` prefix (the formatter's prefix then supplies it
|
||||
/// once). The non-mut variants are unaffected because they never
|
||||
/// embedded the bracket.
|
||||
/// Display string of the variant in isolation: it counts occurrences
|
||||
/// of the literal `[<code>]` token in the rendered stderr and
|
||||
/// requires exactly one (the formatter supplies it; the Display body
|
||||
/// must not also embed it).
|
||||
#[test]
|
||||
fn check_human_mode_renders_mut_diagnostic_code_exactly_once() {
|
||||
// (fixture filename, kebab diagnostic code) for the four mut-local
|
||||
// negative fixtures shipped by the mut-local milestone.
|
||||
fn check_human_mode_renders_loop_binder_diagnostic_code_exactly_once() {
|
||||
let cases = [
|
||||
(
|
||||
"test_mut_assign_out_of_scope.ail.json",
|
||||
"mut-assign-out-of-scope",
|
||||
),
|
||||
(
|
||||
"test_mut_assign_type_mismatch.ail.json",
|
||||
"assign-type-mismatch",
|
||||
),
|
||||
(
|
||||
"test_mut_var_unsupported_type.ail.json",
|
||||
"mut-var-unsupported-type",
|
||||
),
|
||||
(
|
||||
"test_mut_var_captured_by_lambda.ail.json",
|
||||
"mut-var-captured-by-lambda",
|
||||
),
|
||||
// Iter loop-recur.tidy: symmetric loop-binder-capture variant.
|
||||
// Its Display body is likewise bracket-`[code]`-free so the
|
||||
// human formatter supplies `[<code>]` exactly once.
|
||||
(
|
||||
"test_loop_binder_captured_by_lambda.ail.json",
|
||||
"loop-binder-captured-by-lambda",
|
||||
|
||||
@@ -2853,20 +2853,17 @@ fn str_clone_cross_realisation_uniform_abi() {
|
||||
assert_eq!(live, 0, "no leaked heap-Str slabs allowed; live={live}");
|
||||
}
|
||||
|
||||
/// Iter mut.3: `examples/mut_counter.ail` exercises `Term::Mut` +
|
||||
/// `Term::Assign` codegen with an `Int` mut-var. The body
|
||||
/// `(mut (var sum Int 0) (assign sum (sum_helper 1 10 0)) sum)`
|
||||
/// stores the helper's result into `sum`'s alloca and prints the
|
||||
/// loaded value. End-to-end gate for the entry-block-hoist /
|
||||
/// store / load lowering.
|
||||
/// `examples/mut_counter.ail` sums 1..10 via a tail-recursive
|
||||
/// `sum_helper` and prints the result. Behaviour-preservation gate:
|
||||
/// the fixture's value assertion stays `55` after the let/if rewrite,
|
||||
/// proving the rewrite loses no expressivity.
|
||||
#[test]
|
||||
fn mut_counter_prints_55() {
|
||||
let stdout = build_and_run("mut_counter.ail");
|
||||
assert_eq!(stdout.trim(), "55", "mut_counter must print 55, got {stdout:?}");
|
||||
}
|
||||
|
||||
/// Iter mut.3: Float twin of `mut_counter_prints_55`. The mut-var
|
||||
/// is `Float`, init is `0.0`, the recursive helper returns the
|
||||
/// Float twin of `mut_counter_prints_55`: `sum_helper` returns the
|
||||
/// sum 1.0+...+10.0 = 55.0. The polymorphic `print` routes through
|
||||
/// `Show Float.show` → `float_to_str`'s libc `%g` formatter, which
|
||||
/// strips the trailing `.0` — so the canonical stdout for Float
|
||||
|
||||
@@ -342,7 +342,6 @@ mod tests {
|
||||
let mut env = Env::default();
|
||||
install(&mut env);
|
||||
let mut locals: IndexMap<String, Type> = IndexMap::new();
|
||||
let mut mut_scope_stack: Vec<IndexMap<String, Type>> = Vec::new();
|
||||
let mut effects: BTreeSet<String> = BTreeSet::new();
|
||||
let mut subst = Subst::default();
|
||||
let mut counter: u32 = 0;
|
||||
@@ -350,13 +349,12 @@ mod tests {
|
||||
let mut free_fn_calls = Vec::new();
|
||||
let mut warnings: Vec<crate::diagnostic::Diagnostic> = Vec::new();
|
||||
// loop-recur iter 2: test helper synths one term from top-of-
|
||||
// body — fresh empty loop-stack (mirrors mut_scope_stack).
|
||||
// body — fresh empty loop-stack.
|
||||
let mut loop_stack: Vec<Vec<(String, Type)>> = Vec::new();
|
||||
let ty = crate::synth(
|
||||
t,
|
||||
&env,
|
||||
&mut locals,
|
||||
&mut mut_scope_stack,
|
||||
&mut loop_stack,
|
||||
&mut effects,
|
||||
"<test>",
|
||||
@@ -589,7 +587,6 @@ mod tests {
|
||||
let mut env = Env::default();
|
||||
install(&mut env);
|
||||
let mut locals: IndexMap<String, Type> = IndexMap::new();
|
||||
let mut mut_scope_stack: Vec<IndexMap<String, Type>> = Vec::new();
|
||||
let mut effects: BTreeSet<String> = BTreeSet::new();
|
||||
let mut subst = Subst::default();
|
||||
let mut counter: u32 = 0;
|
||||
@@ -597,13 +594,12 @@ mod tests {
|
||||
let mut free_fn_calls = Vec::new();
|
||||
let mut warnings: Vec<crate::diagnostic::Diagnostic> = Vec::new();
|
||||
// loop-recur iter 2: test helper synths one term from top-of-
|
||||
// body — fresh empty loop-stack (mirrors mut_scope_stack).
|
||||
// body — fresh empty loop-stack.
|
||||
let mut loop_stack: Vec<Vec<(String, Type)>> = Vec::new();
|
||||
let err = crate::synth(
|
||||
&term,
|
||||
&env,
|
||||
&mut locals,
|
||||
&mut mut_scope_stack,
|
||||
&mut loop_stack,
|
||||
&mut effects,
|
||||
"<test>",
|
||||
|
||||
+62
-689
File diff suppressed because it is too large
Load Diff
@@ -375,28 +375,6 @@ impl<'a> Lifter<'a> {
|
||||
source: Box::new(self.lift_in_term(source, locals, in_def)?),
|
||||
body: Box::new(self.lift_in_term(body, locals, in_def)?),
|
||||
}),
|
||||
// Iter mut.1: lift letrecs out of each var's init and the
|
||||
// body. Mut-vars cannot themselves participate in a
|
||||
// letrec capture set (letrec bodies are fn-typed and
|
||||
// mut-vars are scalar values), so the var bindings do
|
||||
// not extend `locals` for the lift walk.
|
||||
Term::Mut { vars, body } => Ok(Term::Mut {
|
||||
vars: vars
|
||||
.iter()
|
||||
.map(|v| {
|
||||
Ok(ailang_core::ast::MutVar {
|
||||
name: v.name.clone(),
|
||||
ty: v.ty.clone(),
|
||||
init: self.lift_in_term(&v.init, locals, in_def)?,
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?,
|
||||
body: Box::new(self.lift_in_term(body, locals, in_def)?),
|
||||
}),
|
||||
Term::Assign { name, value } => Ok(Term::Assign {
|
||||
name: name.clone(),
|
||||
value: Box::new(self.lift_in_term(value, locals, in_def)?),
|
||||
}),
|
||||
Term::Loop { binders, body } => Ok(Term::Loop {
|
||||
binders: binders
|
||||
.iter()
|
||||
@@ -739,15 +717,11 @@ impl<'a> Lifter<'a> {
|
||||
// (e.g. class-method-shadowed-by-fn) have already been
|
||||
// surfaced upstream by `check_workspace`. Discard here.
|
||||
let mut warnings_discarded: Vec<crate::diagnostic::Diagnostic> = Vec::new();
|
||||
// Iter mut.2: lift's letrec-capture synth re-entry walks one
|
||||
// term at a time, beginning from a top-of-body position; fresh
|
||||
// empty mut-scope stack is correct.
|
||||
let mut mut_scope_stack: Vec<indexmap::IndexMap<String, crate::Type>> = Vec::new();
|
||||
// loop-recur iter 2: lift's letrec-capture synth re-entry walks
|
||||
// one term at a time from a top-of-body position; fresh empty
|
||||
// loop-stack is correct (any `Term::Loop` pushes its own frame).
|
||||
let mut loop_stack: Vec<Vec<(String, crate::Type)>> = Vec::new();
|
||||
let ty = synth(t, &self.env, locals, &mut mut_scope_stack, &mut loop_stack, &mut effects, in_def, &mut subst, &mut counter, &mut residuals, &mut free_fn_calls, &mut warnings_discarded)?;
|
||||
let ty = synth(t, &self.env, locals, &mut loop_stack, &mut effects, in_def, &mut subst, &mut counter, &mut residuals, &mut free_fn_calls, &mut warnings_discarded)?;
|
||||
Ok(subst.apply(&ty))
|
||||
}
|
||||
}
|
||||
@@ -778,12 +752,6 @@ fn contains_any_letrec(m: &Module) -> bool {
|
||||
Term::Clone { value } => term_has_letrec(value),
|
||||
// Iter 18d.1: structural recursion through both children.
|
||||
Term::ReuseAs { source, body } => term_has_letrec(source) || term_has_letrec(body),
|
||||
// Iter mut.1: any var init or the body can contain a
|
||||
// letrec; the assign's value can too.
|
||||
Term::Mut { vars, body } => {
|
||||
vars.iter().any(|v| term_has_letrec(&v.init)) || term_has_letrec(body)
|
||||
}
|
||||
Term::Assign { value, .. } => term_has_letrec(value),
|
||||
Term::Loop { binders, body } => {
|
||||
binders.iter().any(|b| term_has_letrec(&b.init)) || term_has_letrec(body)
|
||||
}
|
||||
|
||||
@@ -592,23 +592,6 @@ impl<'a> Checker<'a> {
|
||||
// standard position rules.
|
||||
self.walk(body, pos);
|
||||
}
|
||||
// Iter mut.1: mut-vars are alloca-resident scalars (Int /
|
||||
// Float / Bool / Unit per spec §"Iteration mut.1") — they
|
||||
// are not RC-managed and do not participate in the
|
||||
// linearity analysis. Walk children defensively so any
|
||||
// RC-managed value referenced inside an init or the body
|
||||
// is still tracked.
|
||||
Term::Mut { vars, body } => {
|
||||
for v in vars {
|
||||
self.walk(&v.init, Position::Consume);
|
||||
}
|
||||
self.walk(body, pos);
|
||||
}
|
||||
Term::Assign { value, .. } => {
|
||||
// The assigned `name` is a mut-var (alloca slot, not
|
||||
// a tracked binder). Walk the `value` normally.
|
||||
self.walk(value, Position::Consume);
|
||||
}
|
||||
Term::Loop { binders, body } => {
|
||||
for b in binders {
|
||||
self.walk(&b.init, Position::Consume);
|
||||
@@ -804,8 +787,6 @@ fn make_reuse_as_source_not_bare_var(def: &str, source: &Term, body: &Term) -> D
|
||||
Term::Seq { .. } => "seq",
|
||||
Term::Clone { .. } => "clone",
|
||||
Term::ReuseAs { .. } => "reuse-as",
|
||||
Term::Mut { .. } => "mut",
|
||||
Term::Assign { .. } => "assign",
|
||||
Term::Loop { .. } => "loop",
|
||||
Term::Recur { .. } => "recur",
|
||||
};
|
||||
@@ -933,20 +914,6 @@ fn any_sub_binder_consumed_for(
|
||||
any_sub_binder_consumed_for(source, pname, uniq, def_name, ctors)
|
||||
|| any_sub_binder_consumed_for(body, pname, uniq, def_name, ctors)
|
||||
}
|
||||
// Iter mut.1: mut-vars are scalar (Int/Float/Bool/Unit) and
|
||||
// do not participate in the consume-tracking heuristic; the
|
||||
// surrounding analysis only cares about heap-typed param
|
||||
// consumption. Recurse into children defensively so any
|
||||
// genuine consume-of-`pname` inside a var init / body /
|
||||
// assign value still surfaces.
|
||||
Term::Mut { vars, body } => {
|
||||
vars.iter().any(|v| {
|
||||
any_sub_binder_consumed_for(&v.init, pname, uniq, def_name, ctors)
|
||||
}) || any_sub_binder_consumed_for(body, pname, uniq, def_name, ctors)
|
||||
}
|
||||
Term::Assign { value, .. } => {
|
||||
any_sub_binder_consumed_for(value, pname, uniq, def_name, ctors)
|
||||
}
|
||||
Term::Loop { binders, body } => {
|
||||
binders.iter().any(|b| {
|
||||
any_sub_binder_consumed_for(&b.init, pname, uniq, def_name, ctors)
|
||||
|
||||
@@ -713,19 +713,14 @@ pub fn collect_mono_targets(
|
||||
// discards warnings — typecheck has already run and surfaced any
|
||||
// shadow warnings; mono is a post-typecheck pass.
|
||||
let mut warnings_discarded: Vec<crate::diagnostic::Diagnostic> = Vec::new();
|
||||
// Iter mut.2: mono re-synth begins from top-of-body — empty
|
||||
// mut-scope, since any `Term::Mut` will push its own frame as the
|
||||
// walk descends.
|
||||
let mut mut_scope_stack: Vec<indexmap::IndexMap<String, crate::Type>> = Vec::new();
|
||||
// loop-recur iter 2: mono re-synth begins from top-of-body —
|
||||
// empty loop-stack (any `Term::Loop` pushes its own frame as the
|
||||
// walk descends), mirroring the fresh mut-scope above.
|
||||
// walk descends).
|
||||
let mut loop_stack: Vec<Vec<(String, crate::Type)>> = Vec::new();
|
||||
crate::synth(
|
||||
&f.body,
|
||||
&env,
|
||||
&mut locals,
|
||||
&mut mut_scope_stack,
|
||||
&mut loop_stack,
|
||||
&mut effects,
|
||||
&f.name,
|
||||
@@ -1235,19 +1230,6 @@ fn rewrite_mono_calls(
|
||||
rewrite_mono_calls(source, method_to_candidate_classes, poly_free_fns, poly_free_fn_ccounts, caller_module, ordered_targets, cursor, locals);
|
||||
rewrite_mono_calls(body, method_to_candidate_classes, poly_free_fns, poly_free_fn_ccounts, caller_module, ordered_targets, cursor, locals);
|
||||
}
|
||||
// Iter mut.1: visitor-shape recurse with mutable access.
|
||||
// Mut-vars do not declare class-method or poly-fn names; the
|
||||
// var inits, the body, and assign values can though, so walk
|
||||
// them in place.
|
||||
Term::Mut { vars, body } => {
|
||||
for v in vars.iter_mut() {
|
||||
rewrite_mono_calls(&mut v.init, method_to_candidate_classes, poly_free_fns, poly_free_fn_ccounts, caller_module, ordered_targets, cursor, locals);
|
||||
}
|
||||
rewrite_mono_calls(body, method_to_candidate_classes, poly_free_fns, poly_free_fn_ccounts, caller_module, ordered_targets, cursor, locals);
|
||||
}
|
||||
Term::Assign { value, .. } => {
|
||||
rewrite_mono_calls(value, method_to_candidate_classes, poly_free_fns, poly_free_fn_ccounts, caller_module, ordered_targets, cursor, locals);
|
||||
}
|
||||
Term::Loop { binders, body } => {
|
||||
for b in binders.iter_mut() {
|
||||
rewrite_mono_calls(&mut b.init, method_to_candidate_classes, poly_free_fns, poly_free_fn_ccounts, caller_module, ordered_targets, cursor, locals);
|
||||
@@ -1359,19 +1341,14 @@ pub(crate) fn collect_residuals_ordered(
|
||||
// discards warnings — typecheck has already run and surfaced any
|
||||
// shadow warnings; mono is a post-typecheck pass.
|
||||
let mut warnings_discarded: Vec<crate::diagnostic::Diagnostic> = Vec::new();
|
||||
// Iter mut.2: mono re-synth begins from top-of-body — empty
|
||||
// mut-scope, since any `Term::Mut` will push its own frame as the
|
||||
// walk descends.
|
||||
let mut mut_scope_stack: Vec<indexmap::IndexMap<String, crate::Type>> = Vec::new();
|
||||
// loop-recur iter 2: mono re-synth begins from top-of-body —
|
||||
// empty loop-stack (any `Term::Loop` pushes its own frame as the
|
||||
// walk descends), mirroring the fresh mut-scope above.
|
||||
// walk descends).
|
||||
let mut loop_stack: Vec<Vec<(String, crate::Type)>> = Vec::new();
|
||||
crate::synth(
|
||||
&f.body,
|
||||
&env,
|
||||
&mut locals,
|
||||
&mut mut_scope_stack,
|
||||
&mut loop_stack,
|
||||
&mut effects,
|
||||
&f.name,
|
||||
@@ -1625,19 +1602,6 @@ fn interleave_slots(
|
||||
interleave_slots(source, method_to_candidate_classes, poly_free_fns, poly_free_fn_ccounts, class_slots, free_fn_slots, class_cur, free_cur, locals, out);
|
||||
interleave_slots(body, method_to_candidate_classes, poly_free_fns, poly_free_fn_ccounts, class_slots, free_fn_slots, class_cur, free_cur, locals, out);
|
||||
}
|
||||
// Iter mut.1: visitor-shape recurse, symmetric to
|
||||
// `rewrite_mono_calls` above. Mut-vars themselves do not
|
||||
// contribute slots; their init and body terms (and assign
|
||||
// values) can.
|
||||
Term::Mut { vars, body } => {
|
||||
for v in vars {
|
||||
interleave_slots(&v.init, method_to_candidate_classes, poly_free_fns, poly_free_fn_ccounts, class_slots, free_fn_slots, class_cur, free_cur, locals, out);
|
||||
}
|
||||
interleave_slots(body, method_to_candidate_classes, poly_free_fns, poly_free_fn_ccounts, class_slots, free_fn_slots, class_cur, free_cur, locals, out);
|
||||
}
|
||||
Term::Assign { value, .. } => {
|
||||
interleave_slots(value, method_to_candidate_classes, poly_free_fns, poly_free_fn_ccounts, class_slots, free_fn_slots, class_cur, free_cur, locals, out);
|
||||
}
|
||||
Term::Loop { binders, body } => {
|
||||
for b in binders {
|
||||
interleave_slots(&b.init, method_to_candidate_classes, poly_free_fns, poly_free_fn_ccounts, class_slots, free_fn_slots, class_cur, free_cur, locals, out);
|
||||
|
||||
@@ -120,19 +120,6 @@ fn walk_term(t: &Term) -> Result<(), CheckError> {
|
||||
walk_term(source)?;
|
||||
walk_term(body)
|
||||
}
|
||||
// Iter mut.1: pre-desugar validation has nothing specific to
|
||||
// assert about mut blocks (the only invariant this pass
|
||||
// enforces today is "no Float in literal patterns" — mut
|
||||
// var inits are Terms, but they can hold any literal, and
|
||||
// patterns inside a body are visited via the normal
|
||||
// `Term::Match` arm). Recurse into children.
|
||||
Term::Mut { vars, body } => {
|
||||
for v in vars {
|
||||
walk_term(&v.init)?;
|
||||
}
|
||||
walk_term(body)
|
||||
}
|
||||
Term::Assign { value, .. } => walk_term(value),
|
||||
Term::Loop { binders, body } => {
|
||||
for b in binders {
|
||||
walk_term(&b.init)?;
|
||||
|
||||
@@ -253,18 +253,6 @@ impl<'a> Checker<'a> {
|
||||
self.walk(body);
|
||||
self.check_reuse_as(source, body);
|
||||
}
|
||||
// Iter mut.1: mut-vars are scalar (Int/Float/Bool/Unit)
|
||||
// and cannot host an allocating ctor body, so the
|
||||
// reuse-as path-ctor analysis has nothing to refine here.
|
||||
// Recurse defensively into children so any reuse-as
|
||||
// nested inside a var init or the body is still checked.
|
||||
Term::Mut { vars, body } => {
|
||||
for v in vars {
|
||||
self.walk(&v.init);
|
||||
}
|
||||
self.walk(body);
|
||||
}
|
||||
Term::Assign { value, .. } => self.walk(value),
|
||||
Term::Loop { binders, body } => {
|
||||
for b in binders {
|
||||
self.walk(&b.init);
|
||||
|
||||
@@ -336,22 +336,6 @@ impl<'a> Walker<'a> {
|
||||
self.walk(source, Position::Consume);
|
||||
self.walk(body, pos);
|
||||
}
|
||||
// Iter mut.1: mut-vars are alloca-resident scalars and
|
||||
// are NOT RC-tracked binders. They do not contribute to
|
||||
// uniqueness counts (the alloca slot is the per-fn
|
||||
// storage, not a heap allocation). Walk children
|
||||
// defensively so any RC-managed value passed through a
|
||||
// var init / body / assign-value still updates the
|
||||
// appropriate uniqueness counts.
|
||||
Term::Mut { vars, body } => {
|
||||
for v in vars {
|
||||
self.walk(&v.init, Position::Consume);
|
||||
}
|
||||
self.walk(body, pos);
|
||||
}
|
||||
Term::Assign { value, .. } => {
|
||||
self.walk(value, Position::Consume);
|
||||
}
|
||||
Term::Loop { binders, body } => {
|
||||
for b in binders {
|
||||
self.walk(&b.init, Position::Consume);
|
||||
|
||||
@@ -68,16 +68,13 @@ fn infinite_loop_typechecks_clean_no_termination_claim() {
|
||||
}
|
||||
|
||||
/// Property: a `Term::Lam` whose body captures a `Term::Loop` binder
|
||||
/// must be rejected at `ail check` with a dedicated diagnostic,
|
||||
/// symmetric to `mut-var-captured-by-lambda`. Loop binders are
|
||||
/// alloca-resident and cannot escape their loop frame (iter-3 reuses
|
||||
/// the `mut_var_allocas` registry, `std::mem::take`-emptied at the
|
||||
/// lambda boundary), exactly the mut-var escape rule. Today the
|
||||
/// escape guard inspects only `mut_scope_stack`; loop binders live
|
||||
/// in `locals`, so check passes (exit 0) and codegen panics
|
||||
/// `unreachable!()` at `crates/ailang-codegen/src/lambda.rs:102`.
|
||||
/// This test pins the FIXED contract — RED until the guard also
|
||||
/// rejects loop-binder captures.
|
||||
/// is rejected at `ail check` with the dedicated
|
||||
/// `loop-binder-captured-by-lambda` diagnostic. Loop binders are
|
||||
/// alloca-resident and cannot escape their loop frame (codegen
|
||||
/// registers them in the `binder_allocas` registry,
|
||||
/// `std::mem::take`-emptied at the lambda boundary); the `Term::Lam`
|
||||
/// escape guard rejects the capture at typecheck rather than letting
|
||||
/// codegen panic on type-correct input.
|
||||
#[test]
|
||||
fn lambda_capturing_loop_binder_emits_loop_binder_captured_by_lambda() {
|
||||
let codes = check_fixture("test_loop_binder_captured_by_lambda.ail.json");
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
//! Iter mut.2 (Task 6): pin tests that the five typecheck fixtures
|
||||
//! produce the expected diagnostic codes (or zero diagnostics for the
|
||||
//! positive nested-shadow case).
|
||||
//!
|
||||
//! Spec: `docs/specs/2026-05-15-mut-local.md` §"Testing strategy /
|
||||
//! Typecheck negative tests" — names each fixture and the diagnostic
|
||||
//! it must surface. The carve-out justification for landing these as
|
||||
//! `.ail.json` rather than `.ail` mirrors the post-form-a precedent
|
||||
//! (broken_unbound, test_22b2_*.ail.json) — negative typecheck
|
||||
//! fixtures live as canonical JSON so the diagnostic code is the
|
||||
//! load-bearing assertion, not the surface form.
|
||||
|
||||
use ailang_check::check_workspace;
|
||||
use ailang_surface::load_workspace;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn examples_dir() -> PathBuf {
|
||||
let manifest = env!("CARGO_MANIFEST_DIR");
|
||||
PathBuf::from(manifest)
|
||||
.parent().expect("CARGO_MANIFEST_DIR has a parent (crates/ailang-check)")
|
||||
.parent().expect("CARGO_MANIFEST_DIR has a grandparent (crates/)")
|
||||
.join("examples")
|
||||
}
|
||||
|
||||
/// Load the named fixture under `examples/`, run check_workspace, and
|
||||
/// return the diagnostic code list (one entry per Diagnostic).
|
||||
fn check_fixture(fixture_name: &str) -> Vec<String> {
|
||||
let path = examples_dir().join(fixture_name);
|
||||
let ws = load_workspace(&path)
|
||||
.unwrap_or_else(|e| panic!("workspace `{fixture_name}` must load: {e:?}"));
|
||||
let diags = check_workspace(&ws);
|
||||
diags.iter().map(|d| d.code.clone()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assign_out_of_scope_emits_mut_assign_out_of_scope() {
|
||||
let codes = check_fixture("test_mut_assign_out_of_scope.ail.json");
|
||||
assert_eq!(codes, vec!["mut-assign-out-of-scope".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assign_type_mismatch_emits_assign_type_mismatch() {
|
||||
let codes = check_fixture("test_mut_assign_type_mismatch.ail.json");
|
||||
assert_eq!(codes, vec!["assign-type-mismatch".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mut_var_str_type_emits_mut_var_unsupported_type() {
|
||||
let codes = check_fixture("test_mut_var_unsupported_type.ail.json");
|
||||
assert_eq!(codes, vec!["mut-var-unsupported-type".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assign_outside_mut_emits_mut_assign_out_of_scope() {
|
||||
let codes = check_fixture("test_mut_assign_outside_mut.ail.json");
|
||||
assert_eq!(codes, vec!["mut-assign-out-of-scope".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_shadow_typechecks_clean() {
|
||||
let codes = check_fixture("test_mut_nested_shadow_legal.ail.json");
|
||||
assert!(codes.is_empty(), "expected zero diagnostics, got {codes:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lambda_capturing_mut_var_emits_mut_var_captured_by_lambda() {
|
||||
let codes = check_fixture("test_mut_var_captured_by_lambda.ail.json");
|
||||
assert_eq!(codes, vec!["mut-var-captured-by-lambda".to_string()]);
|
||||
}
|
||||
@@ -190,17 +190,6 @@ fn walk(t: &Term, out: &mut NonEscapeSet) {
|
||||
walk(source, out);
|
||||
walk(body, out);
|
||||
}
|
||||
// Iter mut.1: mut-vars are alloca-resident scalars (Int /
|
||||
// Float / Bool / Unit) and never participate in heap escape.
|
||||
// Their `init` and `body` and assign `value` terms may still
|
||||
// contain Let-allocation candidates, so walk through.
|
||||
Term::Mut { vars, body } => {
|
||||
for v in vars {
|
||||
walk(&v.init, out);
|
||||
}
|
||||
walk(body, out);
|
||||
}
|
||||
Term::Assign { value, .. } => walk(value, out),
|
||||
Term::Loop { binders, body } => {
|
||||
for b in binders {
|
||||
walk(&b.init, out);
|
||||
@@ -389,23 +378,6 @@ fn escapes(t: &Term, tainted: &BTreeSet<String>, in_tail: bool) -> bool {
|
||||
}
|
||||
escapes(body, tainted, in_tail)
|
||||
}
|
||||
// Iter mut.1: mut-vars are alloca-resident scalars and do
|
||||
// not themselves contribute to heap escape. Var inits are
|
||||
// evaluated for side-effect (their values are stored into
|
||||
// allocas, not used as the block's value), so they are
|
||||
// walked in non-tail mode. The body IS the block's value,
|
||||
// so it inherits `in_tail`. An assign's value is stored
|
||||
// into an alloca, not used as a tail value — walk
|
||||
// non-tail.
|
||||
Term::Mut { vars, body } => {
|
||||
for v in vars {
|
||||
if escapes(&v.init, tainted, false) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
escapes(body, tainted, in_tail)
|
||||
}
|
||||
Term::Assign { value, .. } => escapes(value, tainted, false),
|
||||
Term::Loop { binders, body } => {
|
||||
for b in binders {
|
||||
if escapes(&b.init, tainted, false) {
|
||||
@@ -526,31 +498,6 @@ fn collect_free_vars(t: &Term, bound: &mut BTreeSet<String>, out: &mut BTreeSet<
|
||||
collect_free_vars(source, bound, out);
|
||||
collect_free_vars(body, bound, out);
|
||||
}
|
||||
// Iter mut.1: a mut-var name binds inside the block. Var
|
||||
// inits before the binding see the outer scope; later inits
|
||||
// and the body see the var as bound. Mirrors `Term::Let`'s
|
||||
// add-then-walk-then-remove pattern, extended over N vars.
|
||||
Term::Mut { vars, body } => {
|
||||
let mut newly: Vec<String> = Vec::new();
|
||||
for v in vars {
|
||||
collect_free_vars(&v.init, bound, out);
|
||||
if bound.insert(v.name.clone()) {
|
||||
newly.push(v.name.clone());
|
||||
}
|
||||
}
|
||||
collect_free_vars(body, bound, out);
|
||||
for n in newly {
|
||||
bound.remove(&n);
|
||||
}
|
||||
}
|
||||
// Iter mut.1: the assigned `name` is a free var unless
|
||||
// bound by an enclosing `Term::Mut`.
|
||||
Term::Assign { name, value } => {
|
||||
if !bound.contains(name) {
|
||||
out.insert(name.clone());
|
||||
}
|
||||
collect_free_vars(value, bound, out);
|
||||
}
|
||||
Term::Loop { binders, body } => {
|
||||
let mut newly: Vec<String> = Vec::new();
|
||||
for b in binders {
|
||||
|
||||
@@ -85,12 +85,11 @@ impl<'a> Emitter<'a> {
|
||||
// hard internal error is right.
|
||||
// Tuple: (name, outer_ssa, llvm_type, ail_type, optional_fn_sig).
|
||||
//
|
||||
// Iter mut.4-tidy: post-Task-2 the typechecker rejects
|
||||
// lambda-captures-of-mut-var via
|
||||
// `CheckError::MutVarCapturedByLambda`. Reaching the `None`
|
||||
// arm below means typecheck was skipped or a bug let the AST
|
||||
// through — both are bugs in upstream layers, so panic rather
|
||||
// than return an Internal error.
|
||||
// The typechecker rejects lambda-captures-of-loop-binder via
|
||||
// `CheckError::LoopBinderCapturedByLambda`. Reaching the
|
||||
// `None` arm below means typecheck was skipped or a bug let
|
||||
// the AST through — both are bugs in upstream layers, so
|
||||
// panic rather than return an Internal error.
|
||||
let mut cap_meta: Vec<(String, String, String, Type, Option<FnSig>)> = Vec::new();
|
||||
for c in &captures {
|
||||
let (_, outer_ssa, lty, ail_ty) = self
|
||||
@@ -100,7 +99,7 @@ impl<'a> Emitter<'a> {
|
||||
.find(|(n, _, _, _)| n == c)
|
||||
.unwrap_or_else(|| {
|
||||
unreachable!(
|
||||
"lambda capture `{c}` not in locals — typecheck should have rejected via MutVarCapturedByLambda",
|
||||
"lambda capture `{c}` not in locals — typecheck should have rejected via LoopBinderCapturedByLambda",
|
||||
)
|
||||
})
|
||||
.clone();
|
||||
@@ -135,19 +134,19 @@ impl<'a> Emitter<'a> {
|
||||
let saved_moved = std::mem::take(&mut self.moved_slots);
|
||||
// Iter mut.3: a lambda thunk is its own fn frame for the
|
||||
// mut-var bookkeeping introduced in iter mut.3 — the outer
|
||||
// fn's mut-vars are not in scope inside the thunk (a lambda
|
||||
// body cannot reference enclosing mut-vars; the spec
|
||||
// disallows capture of mut-vars by lambdas via the
|
||||
// `mut_var_allocas` map being thunk-local). Save and reset
|
||||
// the three fields so the thunk emits its own hoisted-
|
||||
// alloca block at the thunk's entry, not the outer fn's.
|
||||
let saved_mut_allocas = std::mem::take(&mut self.mut_var_allocas);
|
||||
// fn's loop binders are not in scope inside the thunk (a
|
||||
// lambda body cannot reference enclosing loop binders; the
|
||||
// typechecker rejects such captures, and the
|
||||
// `binder_allocas` map is thunk-local). Save and reset the
|
||||
// three fields so the thunk emits its own hoisted-alloca
|
||||
// block at the thunk's entry, not the outer fn's.
|
||||
let saved_binder_allocas = std::mem::take(&mut self.binder_allocas);
|
||||
// loop-recur iter 3: a lambda thunk is its own fn frame —
|
||||
// a `recur` cannot target a loop enclosing the lambda
|
||||
// (iter-2 typecheck already rejects it; codegen resets so
|
||||
// the thunk's own loops work and the outer frames cannot
|
||||
// leak in). Save + reset (mem::take empties the Vec),
|
||||
// restored below alongside the mut.3 triple.
|
||||
// restored below alongside the binder-alloca map.
|
||||
let saved_loop_frames = std::mem::take(&mut self.loop_frames);
|
||||
let saved_pending_allocas = std::mem::take(&mut self.pending_entry_allocas);
|
||||
let saved_entry_marker = self.entry_block_end_marker.take();
|
||||
@@ -233,10 +232,10 @@ impl<'a> Emitter<'a> {
|
||||
self.body.push_str("}\n\n");
|
||||
}
|
||||
|
||||
// Iter mut.3: splice any hoisted mut-var allocas into the
|
||||
// thunk's entry block at the marker captured during the
|
||||
// thunk's `start_block("entry")` above. Empty `pending` is
|
||||
// a no-op (the thunk had no `Term::Mut` in its body).
|
||||
// Splice any hoisted loop-binder allocas into the thunk's
|
||||
// entry block at the marker captured during the thunk's
|
||||
// `start_block("entry")` above. Empty `pending` is a no-op
|
||||
// (the thunk had no `Term::Loop` in its body).
|
||||
if !self.pending_entry_allocas.is_empty() {
|
||||
let marker = self.entry_block_end_marker.ok_or_else(|| {
|
||||
CodegenError::Internal(
|
||||
@@ -261,8 +260,8 @@ impl<'a> Emitter<'a> {
|
||||
self.non_escape = saved_non_escape;
|
||||
self.moved_slots = saved_moved;
|
||||
self.current_param_modes = saved_param_modes;
|
||||
// Iter mut.3: restore outer fn's mut-var bookkeeping.
|
||||
self.mut_var_allocas = saved_mut_allocas;
|
||||
// Restore outer fn's loop-binder bookkeeping.
|
||||
self.binder_allocas = saved_binder_allocas;
|
||||
self.loop_frames = saved_loop_frames;
|
||||
self.pending_entry_allocas = saved_pending_allocas;
|
||||
self.entry_block_end_marker = saved_entry_marker;
|
||||
@@ -475,44 +474,6 @@ impl<'a> Emitter<'a> {
|
||||
Self::collect_captures(source, bound, captures, captures_set, builtins, top_level);
|
||||
Self::collect_captures(body, bound, captures, captures_set, builtins, top_level);
|
||||
}
|
||||
// Iter mut.1: a mut-var name binds inside the block. Var
|
||||
// inits before the binding see the outer scope; later
|
||||
// inits and the body see the var as bound. Mut-vars
|
||||
// cannot be captured by an inner lambda — the typecheck
|
||||
// pass rejects this via `CheckError::MutVarCapturedByLambda`
|
||||
// (added in mut.4-tidy). For the capture-collection scan
|
||||
// the var bindings are tracked identically to let-bound
|
||||
// names.
|
||||
Term::Mut { vars, body } => {
|
||||
let mut newly_bound: Vec<String> = Vec::new();
|
||||
for v in vars {
|
||||
Self::collect_captures(&v.init, bound, captures, captures_set, builtins, top_level);
|
||||
if bound.insert(v.name.clone()) {
|
||||
newly_bound.push(v.name.clone());
|
||||
}
|
||||
}
|
||||
Self::collect_captures(body, bound, captures, captures_set, builtins, top_level);
|
||||
for n in newly_bound {
|
||||
bound.remove(&n);
|
||||
}
|
||||
}
|
||||
Term::Assign { name, value, .. } => {
|
||||
// The assigned `name` is a use of a mut-var binding.
|
||||
// If it is bound in scope (it should be, by spec), it
|
||||
// is not a capture. Otherwise — well-formed inputs do
|
||||
// not produce this case (the typecheck pass at mut.2
|
||||
// rejects it via `MutAssignOutOfScope`); we
|
||||
// conservatively treat it as a possible capture so an
|
||||
// ill-formed input still flows through codegen.
|
||||
if !bound.contains(name)
|
||||
&& !builtins.contains(name.as_str())
|
||||
&& !top_level.contains(name)
|
||||
&& captures_set.insert(name.clone())
|
||||
{
|
||||
captures.push(name.clone());
|
||||
}
|
||||
Self::collect_captures(value, bound, captures, captures_set, builtins, top_level);
|
||||
}
|
||||
Term::Loop { binders, body } => {
|
||||
let mut newly_bound: Vec<String> = Vec::new();
|
||||
for b in binders {
|
||||
|
||||
@@ -715,36 +715,31 @@ struct Emitter<'a> {
|
||||
/// handed off ownership" signal that makes the dec safe.
|
||||
current_param_modes: BTreeMap<String, ParamMode>,
|
||||
/// Per-fn map of name → (alloca SSA name, AIL element type) for
|
||||
/// the two alloca-resident binding classes. Populated on entry
|
||||
/// to a `Term::Mut` block (iter mut.3 — mut-vars) AND on entry
|
||||
/// to a `Term::Loop` (iter loop-recur.3 — loop binders ride the
|
||||
/// same alloca representation; the `Term::Loop` arm inserts each
|
||||
/// binder here and `recur` stores into the slot). Entries are
|
||||
/// alloca-resident loop binders. Populated on entry to a
|
||||
/// `Term::Loop` (iter loop-recur.3): the `Term::Loop` arm inserts
|
||||
/// each binder here and `recur` stores into the slot. Entries are
|
||||
/// removed (or restored to their prior binding) on block exit.
|
||||
/// Consulted by the `Term::Var` arm of `lower_term` before
|
||||
/// `self.locals` — the single load path serving both classes.
|
||||
/// Note: only the mut-var half mirrors a typecheck-side
|
||||
/// `mut_scope_stack`; loop binders are tracked typecheck-side in
|
||||
/// the ordinary `locals` plus `loop_stack` (positional), not in
|
||||
/// `mut_scope_stack` — the shared codegen map is a
|
||||
/// `self.locals` — the single load path for loop binders. Loop
|
||||
/// binders are tracked typecheck-side in the ordinary `locals`
|
||||
/// plus `loop_stack` (positional); this codegen map is a
|
||||
/// representation detail, not a scope-precedence claim.
|
||||
mut_var_allocas: BTreeMap<String, (String, Type)>,
|
||||
binder_allocas: BTreeMap<String, (String, Type)>,
|
||||
/// loop-recur iter 3: stack of enclosing `Term::Loop` codegen
|
||||
/// frames. Each frame is `(header_block_label, binder_slots)`
|
||||
/// where `binder_slots` is `(binder_name, alloca_ssa, llvm_ty)`
|
||||
/// in declaration order. Pushed on `Term::Loop` body entry,
|
||||
/// popped on exit; `Term::Recur` reads `.last()` for its target
|
||||
/// header + the binder allocas to store into. Saved/reset/
|
||||
/// restored at the lambda-lowering boundary exactly as the
|
||||
/// mut.3 `mut_var_allocas` triple (a `recur` cannot cross a
|
||||
/// lambda boundary).
|
||||
/// restored at the lambda-lowering boundary alongside
|
||||
/// `binder_allocas` (a `recur` cannot cross a lambda boundary).
|
||||
loop_frames: Vec<(String, Vec<(String, String, String)>)>,
|
||||
/// Iter mut.3: side buffer for `alloca` instructions emitted
|
||||
/// during body lowering but hoisted to the fn's entry block.
|
||||
/// Flushed once into `self.body` at `entry_block_end_marker`
|
||||
/// after `lower_term` completes. Entry-block placement is
|
||||
/// what makes the allocas mem2reg-eligible regardless of how
|
||||
/// deeply nested the originating `Term::Mut` block is.
|
||||
/// Side buffer for `alloca` instructions emitted during body
|
||||
/// lowering but hoisted to the fn's entry block. Flushed once
|
||||
/// into `self.body` at `entry_block_end_marker` after
|
||||
/// `lower_term` completes. Entry-block placement is what makes
|
||||
/// the loop-binder allocas mem2reg-eligible regardless of how
|
||||
/// deeply nested the originating `Term::Loop` is.
|
||||
pending_entry_allocas: String,
|
||||
/// Iter mut.3: byte position in `self.body` immediately after
|
||||
/// the `entry:\n` label, captured during `start_block("entry")`
|
||||
@@ -868,7 +863,7 @@ impl<'a> Emitter<'a> {
|
||||
closure_drops: BTreeMap::new(),
|
||||
moved_slots: BTreeMap::new(),
|
||||
current_param_modes: BTreeMap::new(),
|
||||
mut_var_allocas: BTreeMap::new(),
|
||||
binder_allocas: BTreeMap::new(),
|
||||
loop_frames: Vec::new(),
|
||||
pending_entry_allocas: String::new(),
|
||||
entry_block_end_marker: None,
|
||||
@@ -1070,11 +1065,11 @@ impl<'a> Emitter<'a> {
|
||||
// consulted by `lower_match`'s Iter A gate to skip arm-close
|
||||
// pattern-binder dec when the scrutinee is a non-Own param.
|
||||
self.current_param_modes.clear();
|
||||
// Iter mut.3: per-fn-body mut-var bookkeeping. The map is
|
||||
// populated/restored by the `Term::Mut` arm of `lower_term`;
|
||||
// Per-fn-body loop-binder bookkeeping. The map is
|
||||
// populated/restored by the `Term::Loop` arm of `lower_term`;
|
||||
// the side buffer collects alloca instructions for hoisting;
|
||||
// the marker is captured by `start_block("entry")` below.
|
||||
self.mut_var_allocas.clear();
|
||||
self.binder_allocas.clear();
|
||||
self.pending_entry_allocas.clear();
|
||||
self.entry_block_end_marker = None;
|
||||
for (i, pname) in f.params.iter().enumerate() {
|
||||
@@ -1394,15 +1389,14 @@ impl<'a> Emitter<'a> {
|
||||
self.block_terminated = true;
|
||||
return Ok(("0".into(), "i8".into()));
|
||||
}
|
||||
// Iter mut.3: mut-vars take precedence over let-bound
|
||||
// / param resolutions, symmetric to the typecheck-side
|
||||
// mut-scope-stack walk in `synth`'s `Term::Var` arm.
|
||||
// Shadowing across nested mut blocks is handled by the
|
||||
// `Term::Mut` arm's push-and-restore on the BTreeMap
|
||||
// entry, so a single `get` suffices here (the entry
|
||||
// visible at this point is the innermost binding).
|
||||
// Loop binders take precedence over let-bound / param
|
||||
// resolutions. Shadowing across nested loops is
|
||||
// handled by the `Term::Loop` arm's push-and-restore
|
||||
// on the BTreeMap entry, so a single `get` suffices
|
||||
// here (the entry visible at this point is the
|
||||
// innermost binding).
|
||||
if let Some((alloca_name, ail_ty)) =
|
||||
self.mut_var_allocas.get(name).cloned()
|
||||
self.binder_allocas.get(name).cloned()
|
||||
{
|
||||
let llvm_ty = llvm_type(&ail_ty)?;
|
||||
let load_ssa = self.fresh_ssa();
|
||||
@@ -1763,107 +1757,11 @@ impl<'a> Emitter<'a> {
|
||||
};
|
||||
self.lower_reuse_as_rc(source, body_type_name, body_ctor, body_args)
|
||||
}
|
||||
// Iter mut.3: lowering of a `Term::Mut` block. Each var
|
||||
// gets an `alloca` emitted into the entry-block side
|
||||
// buffer (hoisted; mem2reg-eligible regardless of nesting
|
||||
// depth) plus a `store` of its init at the current body
|
||||
// position. The map binding (name → alloca, AIL type) is
|
||||
// installed AFTER the init is lowered, mirroring the
|
||||
// typecheck-side ordering in `synth`'s `Term::Mut` arm:
|
||||
// a var's own init does NOT see its own binding (uses
|
||||
// the outer scope plus any earlier vars of the same
|
||||
// block, which ARE bound because we install them as we
|
||||
// go through the loop). On block exit we restore the
|
||||
// prior binding (if any) — innermost-wins shadowing
|
||||
// across nested mut blocks.
|
||||
Term::Mut { vars, body } => {
|
||||
let mut saved: Vec<(String, Option<(String, Type)>)> = Vec::new();
|
||||
for v in vars {
|
||||
let alloca_name = format!("%mut_{}_{}", v.name, self.fresh_id());
|
||||
let llvm_ty = llvm_type(&v.ty)?;
|
||||
// Hoisted alloca — goes into the side buffer,
|
||||
// spliced into the entry block at the end of
|
||||
// emit_fn.
|
||||
self.pending_entry_allocas.push_str(&format!(
|
||||
" {alloca_name} = alloca {llvm_ty}\n"
|
||||
));
|
||||
// Init runs in the outer scope plus any vars
|
||||
// already pushed into `saved` (i.e. earlier vars
|
||||
// of this same `Term::Mut`), mirroring the
|
||||
// typecheck-side ordering at lib.rs:3578.
|
||||
let (init_ssa, init_ty) = self.lower_term(&v.init)?;
|
||||
if init_ty != llvm_ty {
|
||||
return Err(CodegenError::Internal(format!(
|
||||
"Term::Mut var `{}`: init LLVM type {init_ty} != declared {llvm_ty}",
|
||||
v.name
|
||||
)));
|
||||
}
|
||||
self.body.push_str(&format!(
|
||||
" store {llvm_ty} {init_ssa}, ptr {alloca_name}\n"
|
||||
));
|
||||
let prior = self
|
||||
.mut_var_allocas
|
||||
.insert(v.name.clone(), (alloca_name, v.ty.clone()));
|
||||
saved.push((v.name.clone(), prior));
|
||||
}
|
||||
let body_result = self.lower_term(body);
|
||||
// Restore prior bindings — done unconditionally so an
|
||||
// error during body lowering doesn't leak inner-frame
|
||||
// entries into the outer scope (defensive; `lower_term`
|
||||
// returns `Result`, and we propagate after restoring).
|
||||
for (name, prior) in saved.into_iter().rev() {
|
||||
match prior {
|
||||
Some(p) => {
|
||||
self.mut_var_allocas.insert(name, p);
|
||||
}
|
||||
None => {
|
||||
self.mut_var_allocas.remove(&name);
|
||||
}
|
||||
}
|
||||
}
|
||||
body_result
|
||||
}
|
||||
// Iter mut.3: lowering of a `Term::Assign`. Resolves the
|
||||
// target name through `mut_var_allocas` (the typecheck
|
||||
// pass has already pinned the lexical-scope invariant,
|
||||
// so a miss here is an internal error — the assign would
|
||||
// have been rejected with `MutAssignOutOfScope`). The
|
||||
// assign's static type is Unit; we return the canonical
|
||||
// Unit SSA form `("0", "i8")` matching `Literal::Unit`
|
||||
// in this same `match` (line ~1289).
|
||||
Term::Assign { name, value } => {
|
||||
let (alloca_name, ail_ty) = self
|
||||
.mut_var_allocas
|
||||
.get(name)
|
||||
.cloned()
|
||||
.ok_or_else(|| {
|
||||
CodegenError::Internal(format!(
|
||||
"Term::Assign `{name}` reached codegen without a mut-var alloca \
|
||||
— typecheck should have rejected this earlier"
|
||||
))
|
||||
})?;
|
||||
let llvm_ty = llvm_type(&ail_ty)?;
|
||||
let (value_ssa, value_ty) = self.lower_term(value)?;
|
||||
if value_ty != llvm_ty {
|
||||
return Err(CodegenError::Internal(format!(
|
||||
"Term::Assign `{name}`: value LLVM type {value_ty} != declared {llvm_ty}"
|
||||
)));
|
||||
}
|
||||
self.body.push_str(&format!(
|
||||
" store {llvm_ty} {value_ssa}, ptr {alloca_name}\n"
|
||||
));
|
||||
Ok(("0".into(), "i8".into()))
|
||||
}
|
||||
// loop-recur iter 1: real codegen (loop-header block,
|
||||
// per-binder phi, back-edge br) lands in iter 3. This
|
||||
// iter stubs the dispatch so the workspace compiles; no
|
||||
// loop/recur program is codegen'd in iter 1. Mirrors
|
||||
// mut.1's lower_term stub.
|
||||
Term::Loop { binders, body } => {
|
||||
// loop-recur iter 3: loop binders are loop-carried
|
||||
// values lowered as entry-block allocas (the mut.3
|
||||
// values lowered as entry-block allocas (the
|
||||
// `pending_entry_allocas` mechanism) registered in
|
||||
// `mut_var_allocas` so the existing `Term::Var` load
|
||||
// `binder_allocas` so the existing `Term::Var` load
|
||||
// path resolves them with zero new Var code
|
||||
// (representation-sharing; Boss calls 1+2). The loop
|
||||
// header is a fresh block reached by an
|
||||
@@ -1896,7 +1794,7 @@ impl<'a> Emitter<'a> {
|
||||
" store {llvm_ty} {init_ssa}, ptr {alloca_name}\n"
|
||||
));
|
||||
let prior = self
|
||||
.mut_var_allocas
|
||||
.binder_allocas
|
||||
.insert(b.name.clone(), (alloca_name.clone(), b.ty.clone()));
|
||||
saved.push((b.name.clone(), prior));
|
||||
frame_slots.push((b.name.clone(), alloca_name, llvm_ty));
|
||||
@@ -1906,15 +1804,15 @@ impl<'a> Emitter<'a> {
|
||||
self.start_block(&header);
|
||||
let body_result = self.lower_term(body);
|
||||
self.loop_frames.pop();
|
||||
// Restore prior bindings unconditionally (mirrors the
|
||||
// mut.3 `Term::Mut` arm — defensive on the `?` path).
|
||||
// Restore prior bindings unconditionally (defensive
|
||||
// on the `?` path).
|
||||
for (name, prior) in saved.into_iter().rev() {
|
||||
match prior {
|
||||
Some(p) => {
|
||||
self.mut_var_allocas.insert(name, p);
|
||||
self.binder_allocas.insert(name, p);
|
||||
}
|
||||
None => {
|
||||
self.mut_var_allocas.remove(&name);
|
||||
self.binder_allocas.remove(&name);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1924,11 +1822,10 @@ impl<'a> Emitter<'a> {
|
||||
// loop-recur iter 3: re-enter the innermost
|
||||
// enclosing loop. Typecheck (iter 2) pinned arity ==
|
||||
// binder count and per-arg type == binder type, so a
|
||||
// miss/mismatch here is an internal error (the
|
||||
// `Term::Assign`-arm precedent). ALL args are lowered
|
||||
// to SSA values BEFORE any store, so a recur arg that
|
||||
// reads a binder sees its OLD value (recur is a
|
||||
// simultaneous positional rebind, e.g.
|
||||
// miss/mismatch here is an internal error. ALL args
|
||||
// are lowered to SSA values BEFORE any store, so a
|
||||
// recur arg that reads a binder sees its OLD value
|
||||
// (recur is a simultaneous positional rebind, e.g.
|
||||
// `(recur (+ acc i) (+ i 1))`). The back-edge `br` is
|
||||
// a block terminator: set `block_terminated` at
|
||||
// recur's OWN emit site (the parallel setter — Boss
|
||||
@@ -1937,8 +1834,7 @@ impl<'a> Emitter<'a> {
|
||||
// exactly like a tail-app block. recur never falls
|
||||
// through; its value is never used — return the
|
||||
// canonical Unit/dead SSA (`("0","i8")`, the
|
||||
// `Term::Assign` / both-if-branches-terminated
|
||||
// precedent).
|
||||
// both-if-branches-terminated precedent).
|
||||
let (header, slots) = self
|
||||
.loop_frames
|
||||
.last()
|
||||
@@ -3011,7 +2907,7 @@ impl<'a> Emitter<'a> {
|
||||
return Ok(ty.clone());
|
||||
}
|
||||
}
|
||||
if let Some((_, ail_ty)) = self.mut_var_allocas.get(name) {
|
||||
if let Some((_, ail_ty)) = self.binder_allocas.get(name) {
|
||||
return Ok(ail_ty.clone());
|
||||
}
|
||||
if let Some((_, _, _, ail)) =
|
||||
@@ -3228,19 +3124,10 @@ impl<'a> Emitter<'a> {
|
||||
// type. The source is dropped at codegen.
|
||||
self.synth_with_extras(body, extras)
|
||||
}
|
||||
// Iter mut.1: `Term::Mut`'s static type is the body's
|
||||
// static type (spec §"JSON-AST schema"). `Term::Assign`'s
|
||||
// is Unit (spec §"Form A surface"). These won't be hit
|
||||
// along the shipping codegen path because the dispatcher
|
||||
// at `lower_term` stubs both — but `synth_with_extras`
|
||||
// is exhaustive on Term so the arms must exist.
|
||||
Term::Mut { body, .. } => self.synth_with_extras(body, extras),
|
||||
Term::Assign { .. } => Ok(Type::unit()),
|
||||
// loop-recur iter 1: a Term::Loop's static type is the
|
||||
// body's type (mirror Term::Mut). Term::Recur does not
|
||||
// fall through; a Unit stub is safe — this arm is never
|
||||
// hit on the shipping path because lower_term stubs
|
||||
// Loop/Recur, and iter 1 codegens no loop/recur program.
|
||||
// A `Term::Loop`'s static type is the body's type.
|
||||
// `Term::Recur` does not fall through; a Unit stub is
|
||||
// safe (recur transfers control and never produces a
|
||||
// value at its own position).
|
||||
Term::Loop { body, .. } => self.synth_with_extras(body, extras),
|
||||
Term::Recur { .. } => Ok(Type::unit()),
|
||||
}
|
||||
|
||||
+10
-119
@@ -513,33 +513,6 @@ pub enum Term {
|
||||
source: Box<Term>,
|
||||
body: Box<Term>,
|
||||
},
|
||||
/// Iter mut.1: local mutable-state block. `vars` declares zero or
|
||||
/// more lexically-scoped mutable bindings (initialised in order);
|
||||
/// `body` is a single Term evaluated in scope of all vars. The
|
||||
/// block's static type is `body`'s static type. `vars` stays
|
||||
/// present in canonical JSON even when empty (no
|
||||
/// `skip_serializing_if` — the field is part of the shape).
|
||||
///
|
||||
/// Typecheck and codegen recognition land in iters mut.2 / mut.3;
|
||||
/// in iter mut.1 the dispatch entry points (`synth` in
|
||||
/// `ailang-check`, `lower_term` in `ailang-codegen`) stub these
|
||||
/// variants with `CheckError::Internal` / `CodegenError::Internal`
|
||||
/// respectively per spec `docs/specs/2026-05-15-mut-local.md`
|
||||
/// §"Iteration mut.1".
|
||||
Mut {
|
||||
vars: Vec<MutVar>,
|
||||
body: Box<Term>,
|
||||
},
|
||||
/// Iter mut.1: in-block update of a mut-var. Only legal as a
|
||||
/// sub-term of a `Term::Mut` whose `vars` includes a var with the
|
||||
/// same `name`. Static type is Unit. The lexical-scope invariant
|
||||
/// is enforced at typecheck (iter mut.2,
|
||||
/// `CheckError::MutAssignOutOfScope`); codegen relies on it (iter
|
||||
/// mut.3).
|
||||
Assign {
|
||||
name: String,
|
||||
value: Box<Term>,
|
||||
},
|
||||
/// loop-recur iter 1: a strict iteration block. `binders`
|
||||
/// declares one or more loop parameters (name, type, init),
|
||||
/// evaluated in order on loop entry; `body` is evaluated with
|
||||
@@ -547,8 +520,8 @@ pub enum Term {
|
||||
/// the iteration that exits via a non-`recur` branch. Strictly
|
||||
/// additive: pre-existing fixtures hash bit-identically because
|
||||
/// none carry the `"t":"loop"` tag. `binders` has no
|
||||
/// `skip_serializing_if` (mirrors `Term::Mut.vars` — the field
|
||||
/// is part of the shape). Typecheck (loop-recur.2): `synth`
|
||||
/// `skip_serializing_if` — the field is part of the shape.
|
||||
/// Typecheck (loop-recur.2): `synth`
|
||||
/// types each binder init, the loop's type is the body's type;
|
||||
/// `recur` arity/type is checked positionally via `loop_stack`
|
||||
/// and `verify_loop_body` enforces `recur`-in-tail-position; a
|
||||
@@ -587,42 +560,12 @@ pub struct Arm {
|
||||
pub body: Term,
|
||||
}
|
||||
|
||||
/// Iter mut.1: a mutable binding inside [`Term::Mut`]. Lives as a
|
||||
/// nested field of `Term::Mut`, not as a standalone `Term` variant —
|
||||
/// mut-vars are not first-class values (they cannot escape the
|
||||
/// enclosing `Term::Mut` scope; see
|
||||
/// `docs/specs/2026-05-15-mut-local.md` §"Why three AST nodes, not
|
||||
/// one fused construct").
|
||||
///
|
||||
/// The JSON field for `ty` is `"type"`, mirroring the spec's schema
|
||||
/// (`{ "name": "<id>", "type": Type, "init": Term }`). Derives match
|
||||
/// [`Arm`]'s for cross-tree consistency.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct MutVar {
|
||||
/// The mut-var's lexical name. Within the enclosing `Term::Mut`,
|
||||
/// a `Term::Var { name }` resolves to this binding (innermost-wins
|
||||
/// shadowing per spec §"Term::Var resolution"); a
|
||||
/// `Term::Assign { name, .. }` updates it.
|
||||
pub name: String,
|
||||
/// The mut-var's declared type. Restricted to
|
||||
/// `{ Int, Float, Bool, Unit }` in this milestone — the typecheck
|
||||
/// pass (iter mut.2) rejects other choices with
|
||||
/// `CheckError::UnsupportedMutVarType`.
|
||||
#[serde(rename = "type")]
|
||||
pub ty: Type,
|
||||
/// Initial value. Evaluated in the outer scope plus the
|
||||
/// already-declared vars of the same `Term::Mut` (vars are
|
||||
/// initialised in declaration order).
|
||||
pub init: Term,
|
||||
}
|
||||
|
||||
/// loop-recur iter 1: one binder of a [`Term::Loop`]. Mirrors
|
||||
/// [`MutVar`]'s `(name, type, init)` triple exactly so the Form-A
|
||||
/// surface vocabulary is shared (`(NAME TYPE INIT)`); it is a
|
||||
/// nested field of `Term::Loop`, not a first-class `Term` (loop
|
||||
/// binders cannot escape the enclosing loop). `recur` rebinds these
|
||||
/// positionally per iteration. The `ty` JSON field is `"type"`,
|
||||
/// matching `MutVar` and the spec schema.
|
||||
/// loop-recur iter 1: one binder of a [`Term::Loop`]. The
|
||||
/// `(name, type, init)` triple is the Form-A surface vocabulary
|
||||
/// `(NAME TYPE INIT)`; it is a nested field of `Term::Loop`, not a
|
||||
/// first-class `Term` (loop binders cannot escape the enclosing
|
||||
/// loop). `recur` rebinds these positionally per iteration. The
|
||||
/// `ty` JSON field is `"type"`, matching the spec schema.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct LoopBinder {
|
||||
/// The binder's lexical name. Within the enclosing `Term::Loop`,
|
||||
@@ -952,61 +895,9 @@ fn is_false(b: &bool) -> bool {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Iter mut.1: pin the canonical-bytes shape of an empty-`vars`
|
||||
/// `Term::Mut`. Spec `docs/specs/2026-05-15-mut-local.md`
|
||||
/// §"Canonical-form invariants" requires the `vars` array to stay
|
||||
/// present in canonical JSON rather than being omitted; a future
|
||||
/// addition of `skip_serializing_if = "Vec::is_empty"` to the
|
||||
/// field would silently break this property and is the failure
|
||||
/// mode this pin protects against.
|
||||
#[test]
|
||||
fn term_mut_empty_vars_serialises_with_explicit_vars_field() {
|
||||
let t = Term::Mut {
|
||||
vars: Vec::new(),
|
||||
body: Box::new(Term::Lit {
|
||||
lit: Literal::Int { value: 0 },
|
||||
}),
|
||||
};
|
||||
let bytes = serde_json::to_string(&t).expect("serialise");
|
||||
assert_eq!(
|
||||
bytes,
|
||||
r#"{"t":"mut","vars":[],"body":{"t":"lit","lit":{"kind":"int","value":0}}}"#,
|
||||
);
|
||||
}
|
||||
|
||||
/// Iter mut.1: round-trip a `Term::Assign` through JSON.
|
||||
/// Pins the canonical-form shape `{ "t": "assign", "name": ..., "value": ... }`.
|
||||
#[test]
|
||||
fn term_assign_round_trips_through_json() {
|
||||
let t = Term::Assign {
|
||||
name: "x".into(),
|
||||
value: Box::new(Term::Lit {
|
||||
lit: Literal::Int { value: 42 },
|
||||
}),
|
||||
};
|
||||
let bytes = serde_json::to_string(&t).expect("serialise");
|
||||
assert_eq!(
|
||||
bytes,
|
||||
r#"{"t":"assign","name":"x","value":{"t":"lit","lit":{"kind":"int","value":42}}}"#,
|
||||
);
|
||||
let back: Term = serde_json::from_str(&bytes).expect("deserialise");
|
||||
match back {
|
||||
Term::Assign { name, value } => {
|
||||
assert_eq!(name, "x");
|
||||
match *value {
|
||||
Term::Lit {
|
||||
lit: Literal::Int { value: 42 },
|
||||
} => {}
|
||||
other => panic!("inner literal mismatch: {other:?}"),
|
||||
}
|
||||
}
|
||||
other => panic!("variant mismatch: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// loop-recur iter 1: pin the canonical-bytes shape of a
|
||||
/// `Term::Loop` with one binder. Mirrors the mut-empty-vars pin:
|
||||
/// `binders` stays present (no `skip_serializing_if`).
|
||||
/// `Term::Loop` with one binder: `binders` stays present in
|
||||
/// canonical JSON (no `skip_serializing_if`).
|
||||
#[test]
|
||||
fn term_loop_one_binder_serialises_with_explicit_binders_field() {
|
||||
let t = Term::Loop {
|
||||
|
||||
@@ -346,23 +346,6 @@ fn collect_used_in_term(t: &Term, used: &mut BTreeSet<String>) {
|
||||
collect_used_in_term(source, used);
|
||||
collect_used_in_term(body, used);
|
||||
}
|
||||
Term::Mut { vars, body } => {
|
||||
// Iter mut.1: mut-var declarations introduce source-level
|
||||
// names — track them so a generated fresh-name cannot
|
||||
// accidentally collide with one. Then recurse into each
|
||||
// var's `init` and the block's body.
|
||||
for v in vars {
|
||||
used.insert(v.name.clone());
|
||||
collect_used_in_term(&v.init, used);
|
||||
}
|
||||
collect_used_in_term(body, used);
|
||||
}
|
||||
Term::Assign { name, value } => {
|
||||
// Iter mut.1: the assigned `name` is a *use* of the
|
||||
// mut-var; record it and recurse into `value`.
|
||||
used.insert(name.clone());
|
||||
collect_used_in_term(value, used);
|
||||
}
|
||||
Term::Loop { binders, body } => {
|
||||
for b in binders {
|
||||
used.insert(b.name.clone());
|
||||
@@ -568,47 +551,12 @@ impl Desugarer {
|
||||
source: Box::new(self.desugar_term(source, scope)),
|
||||
body: Box::new(self.desugar_term(body, scope)),
|
||||
},
|
||||
Term::Mut { vars, body } => {
|
||||
// Iter mut.1: structural recursion. Each `var`'s `init`
|
||||
// is evaluated in scope of the outer environment plus
|
||||
// the *already-declared* vars of the same `Term::Mut`
|
||||
// (spec §"Iteration mut.2" — first-class scoping
|
||||
// formally lands at typecheck). For desugar's purposes
|
||||
// we extend the scope per-var with a `LetBound`
|
||||
// sentinel so a generated fresh name does not collide
|
||||
// with mut-var names; the LetRec lifter does not
|
||||
// consult mut-vars (mut-vars cannot appear in let-rec
|
||||
// capture sets — letrec lifting happens before
|
||||
// typecheck of the mut body).
|
||||
let mut inner = scope.clone();
|
||||
let new_vars: Vec<MutVar> = vars
|
||||
.iter()
|
||||
.map(|v| {
|
||||
let init = self.desugar_term(&v.init, &inner);
|
||||
inner.insert(v.name.clone(), ScopeEntry::LetBound);
|
||||
MutVar {
|
||||
name: v.name.clone(),
|
||||
ty: v.ty.clone(),
|
||||
init,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
Term::Mut {
|
||||
vars: new_vars,
|
||||
body: Box::new(self.desugar_term(body, &inner)),
|
||||
}
|
||||
}
|
||||
Term::Assign { name, value } => Term::Assign {
|
||||
name: name.clone(),
|
||||
value: Box::new(self.desugar_term(value, scope)),
|
||||
},
|
||||
Term::Loop { binders, body } => {
|
||||
// loop-recur iter 1: structural recursion mirroring
|
||||
// the Term::Mut arm. Each binder's init is desugared
|
||||
// in scope of the outer env plus already-declared
|
||||
// binders; the body sees all binders. The LetBound
|
||||
// sentinel keeps generated fresh names off binder
|
||||
// names.
|
||||
// loop-recur iter 1: structural recursion. Each
|
||||
// binder's init is desugared in scope of the outer env
|
||||
// plus already-declared binders; the body sees all
|
||||
// binders. The LetBound sentinel keeps generated fresh
|
||||
// names off binder names.
|
||||
let mut inner = scope.clone();
|
||||
let new_binders: Vec<LoopBinder> = binders
|
||||
.iter()
|
||||
@@ -1254,33 +1202,10 @@ pub fn free_vars_in_term(t: &Term, bound: &BTreeSet<String>, out: &mut BTreeSet<
|
||||
free_vars_in_term(source, bound, out);
|
||||
free_vars_in_term(body, bound, out);
|
||||
}
|
||||
Term::Mut { vars, body } => {
|
||||
// Iter mut.1: a mut-var name binds inside the block. Each
|
||||
// `var`'s `init` is evaluated in scope of the OUTER
|
||||
// environment plus the already-declared vars (init order
|
||||
// matches declaration order); the body is in scope of all
|
||||
// vars. Mirrors the `Term::Let` pattern but generalised
|
||||
// across N vars.
|
||||
let mut b = bound.clone();
|
||||
for v in vars {
|
||||
free_vars_in_term(&v.init, &b, out);
|
||||
b.insert(v.name.clone());
|
||||
}
|
||||
free_vars_in_term(body, &b, out);
|
||||
}
|
||||
Term::Assign { name, value } => {
|
||||
// Iter mut.1: the assigned `name` is a free var unless
|
||||
// bound by an enclosing `Term::Mut`. The value is walked
|
||||
// as usual.
|
||||
if !bound.contains(name) {
|
||||
out.insert(name.clone());
|
||||
}
|
||||
free_vars_in_term(value, bound, out);
|
||||
}
|
||||
Term::Loop { binders, body } => {
|
||||
// loop-recur iter 1: binder names bind inside the loop —
|
||||
// each init sees the outer env plus already-declared
|
||||
// binders; the body sees all. Mirrors the Term::Mut arm.
|
||||
// binders; the body sees all.
|
||||
let mut b = bound.clone();
|
||||
for bd in binders {
|
||||
free_vars_in_term(&bd.init, &b, out);
|
||||
@@ -1437,60 +1362,10 @@ pub fn subst_var(t: &Term, from: &str, to: &str) -> Term {
|
||||
source: Box::new(subst_var(source, from, to)),
|
||||
body: Box::new(subst_var(body, from, to)),
|
||||
},
|
||||
Term::Mut { vars, body } => {
|
||||
// Iter mut.1: mut-vars lexically shadow outer names. Walk
|
||||
// each var's `init` substituting only if no earlier var in
|
||||
// the same block already shadows `from`; once a var named
|
||||
// `from` is declared, subsequent inits AND the body see
|
||||
// that var, so substitution must stop.
|
||||
let mut shadowed = false;
|
||||
let new_vars: Vec<MutVar> = vars
|
||||
.iter()
|
||||
.map(|v| {
|
||||
let init = if shadowed {
|
||||
v.init.clone()
|
||||
} else {
|
||||
subst_var(&v.init, from, to)
|
||||
};
|
||||
if v.name == from {
|
||||
shadowed = true;
|
||||
}
|
||||
MutVar {
|
||||
name: v.name.clone(),
|
||||
ty: v.ty.clone(),
|
||||
init,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let body_rw = if shadowed {
|
||||
(**body).clone()
|
||||
} else {
|
||||
subst_var(body, from, to)
|
||||
};
|
||||
Term::Mut {
|
||||
vars: new_vars,
|
||||
body: Box::new(body_rw),
|
||||
}
|
||||
}
|
||||
Term::Assign { name, value } => Term::Assign {
|
||||
// Iter mut.1: substitute inside `value`; the `name` field
|
||||
// refers to a mut-var declared by an enclosing
|
||||
// `Term::Mut`. Renaming it here without renaming the
|
||||
// declaration would break the scope link. The desugar
|
||||
// pass's `subst_var` is used only to rewrite let-rec
|
||||
// captures (KnownType / LetBound / MatchArm — never
|
||||
// mut-vars), so leaving the `name` untouched is
|
||||
// semantically correct: any `from` that matches the
|
||||
// assigned `name` is in a different namespace by
|
||||
// construction.
|
||||
name: name.clone(),
|
||||
value: Box::new(subst_var(value, from, to)),
|
||||
},
|
||||
Term::Loop { binders, body } => {
|
||||
// loop-recur iter 1: binders lexically shadow outer
|
||||
// names, symmetric to the Term::Mut arm — once a binder
|
||||
// named `from` is declared, later inits and the body
|
||||
// stop being substituted.
|
||||
// names — once a binder named `from` is declared, later
|
||||
// inits and the body stop being substituted.
|
||||
let mut shadowed = false;
|
||||
let new_binders: Vec<LoopBinder> = binders
|
||||
.iter()
|
||||
@@ -1644,26 +1519,6 @@ pub fn subst_call_with_extras(t: &Term, name: &str, lifted: &str, extras: &[Stri
|
||||
source: Box::new(subst_call_with_extras(source, name, lifted, extras)),
|
||||
body: Box::new(subst_call_with_extras(body, name, lifted, extras)),
|
||||
},
|
||||
Term::Mut { vars, body } => Term::Mut {
|
||||
// Iter mut.1: structural recursion through each var's
|
||||
// `init` and the block's body. Mut-var declarations
|
||||
// cannot shadow a top-level fn name (mut-vars are
|
||||
// first-order scalars, fns are not assignable), so the
|
||||
// call-substitution sees through the block uniformly.
|
||||
vars: vars
|
||||
.iter()
|
||||
.map(|v| MutVar {
|
||||
name: v.name.clone(),
|
||||
ty: v.ty.clone(),
|
||||
init: subst_call_with_extras(&v.init, name, lifted, extras),
|
||||
})
|
||||
.collect(),
|
||||
body: Box::new(subst_call_with_extras(body, name, lifted, extras)),
|
||||
},
|
||||
Term::Assign { name: assign_name, value } => Term::Assign {
|
||||
name: assign_name.clone(),
|
||||
value: Box::new(subst_call_with_extras(value, name, lifted, extras)),
|
||||
},
|
||||
Term::Loop { binders, body } => Term::Loop {
|
||||
binders: binders
|
||||
.iter()
|
||||
@@ -1735,24 +1590,6 @@ pub fn find_non_callee_use(t: &Term, name: &str) -> Option<Term> {
|
||||
Term::ReuseAs { source, body } => {
|
||||
find_non_callee_use(source, name).or_else(|| find_non_callee_use(body, name))
|
||||
}
|
||||
// Iter mut.1: scan each var's init plus the body. Mut-vars
|
||||
// are first-order scalars and never appear in callee position,
|
||||
// so any matching `Term::Var` inside a mut block is non-callee
|
||||
// by construction.
|
||||
Term::Mut { vars, body } => vars
|
||||
.iter()
|
||||
.find_map(|v| find_non_callee_use(&v.init, name))
|
||||
.or_else(|| find_non_callee_use(body, name)),
|
||||
// Iter mut.1: the assigned `name` is a non-callee *use* of
|
||||
// the mut-var; if it matches the searched name, surface the
|
||||
// node itself. Otherwise recurse into the value.
|
||||
Term::Assign { name: assign_name, value } => {
|
||||
if assign_name == name {
|
||||
Some(t.clone())
|
||||
} else {
|
||||
find_non_callee_use(value, name)
|
||||
}
|
||||
}
|
||||
Term::Loop { binders, body } => binders
|
||||
.iter()
|
||||
.find_map(|b| find_non_callee_use(&b.init, name))
|
||||
@@ -1802,11 +1639,6 @@ mod tests {
|
||||
}
|
||||
Term::Clone { value } => any_nested_ctor(value),
|
||||
Term::ReuseAs { source, body } => any_nested_ctor(source) || any_nested_ctor(body),
|
||||
// Iter mut.1: scan each var's init plus the body.
|
||||
Term::Mut { vars, body } => {
|
||||
vars.iter().any(|v| any_nested_ctor(&v.init)) || any_nested_ctor(body)
|
||||
}
|
||||
Term::Assign { value, .. } => any_nested_ctor(value),
|
||||
Term::Loop { binders, body } => {
|
||||
binders.iter().any(|b| any_nested_ctor(&b.init)) || any_nested_ctor(body)
|
||||
}
|
||||
@@ -1836,11 +1668,6 @@ mod tests {
|
||||
Term::LetRec { .. } => true,
|
||||
Term::Clone { value } => any_let_rec(value),
|
||||
Term::ReuseAs { source, body } => any_let_rec(source) || any_let_rec(body),
|
||||
// Iter mut.1: scan each var's init plus the body.
|
||||
Term::Mut { vars, body } => {
|
||||
vars.iter().any(|v| any_let_rec(&v.init)) || any_let_rec(body)
|
||||
}
|
||||
Term::Assign { value, .. } => any_let_rec(value),
|
||||
Term::Loop { binders, body } => {
|
||||
binders.iter().any(|b| any_let_rec(&b.init)) || any_let_rec(body)
|
||||
}
|
||||
@@ -2961,11 +2788,6 @@ mod tests {
|
||||
}
|
||||
Term::Clone { value } => any_lit_pattern(value),
|
||||
Term::ReuseAs { source, body } => any_lit_pattern(source) || any_lit_pattern(body),
|
||||
// Iter mut.1: scan each var's init plus the body.
|
||||
Term::Mut { vars, body } => {
|
||||
vars.iter().any(|v| any_lit_pattern(&v.init)) || any_lit_pattern(body)
|
||||
}
|
||||
Term::Assign { value, .. } => any_lit_pattern(value),
|
||||
Term::Loop { binders, body } => {
|
||||
binders.iter().any(|b| any_lit_pattern(&b.init)) || any_lit_pattern(body)
|
||||
}
|
||||
|
||||
@@ -1247,18 +1247,6 @@ where
|
||||
walk_term_embedded_types(source, f)?;
|
||||
walk_term_embedded_types(body, f)
|
||||
}
|
||||
// Iter mut.1: each `MutVar.ty` is an embedded type — walk
|
||||
// it. Then recurse into each var's `init` and the block's
|
||||
// body. `Term::Assign` carries no embedded type; recurse
|
||||
// into its `value` only.
|
||||
Term::Mut { vars, body } => {
|
||||
for v in vars {
|
||||
walk_type(&v.ty, f)?;
|
||||
walk_term_embedded_types(&v.init, f)?;
|
||||
}
|
||||
walk_term_embedded_types(body, f)
|
||||
}
|
||||
Term::Assign { value, .. } => walk_term_embedded_types(value, f),
|
||||
Term::Loop { binders, body } => {
|
||||
for b in binders {
|
||||
walk_type(&b.ty, f)?;
|
||||
@@ -1394,17 +1382,6 @@ where
|
||||
walk_term(source, f)?;
|
||||
walk_term(body, f)
|
||||
}
|
||||
// Iter mut.1: `Term::Ctor.type_name` is the only string this
|
||||
// walker reports — mut-vars carry no Ctor-type strings. Just
|
||||
// recurse into each var's `init` and the body, and into
|
||||
// assign's `value`.
|
||||
Term::Mut { vars, body } => {
|
||||
for v in vars {
|
||||
walk_term(&v.init, f)?;
|
||||
}
|
||||
walk_term(body, f)
|
||||
}
|
||||
Term::Assign { value, .. } => walk_term(value, f),
|
||||
Term::Loop { binders, body } => {
|
||||
for b in binders {
|
||||
walk_term(&b.init, f)?;
|
||||
|
||||
@@ -3,16 +3,9 @@
|
||||
//! under `examples/*.ail.json` after milestone close. The list is
|
||||
//! hardcoded; any change is a deliberate, brainstorm-level decision.
|
||||
//!
|
||||
//! Eighteen carve-outs post iter loop-recur.tidy (2026-05-18):
|
||||
//! Twelve carve-outs:
|
||||
//! - §C4 (a) subject-matter: 7 fixtures from form-a.1 milestone
|
||||
//! close (canonical-form rejection / unbound / class-def rejection).
|
||||
//! - Iter mut.2: 5 negative typecheck fixtures for the new mut /
|
||||
//! var / assign forms. The diagnostic code is the load-bearing
|
||||
//! assertion (mut-assign-out-of-scope, assign-type-mismatch,
|
||||
//! mut-var-unsupported-type) — mirroring the §C4(a) negative-
|
||||
//! fixture convention. The positive nested-shadow case is a
|
||||
//! .ail.json carve-out for symmetry with its negative siblings
|
||||
//! (the driver tests all five from one helper).
|
||||
//! - §C4 (b) compile-time-embed: retired 2026-05-14 by milestone
|
||||
//! prelude-decouple; the prelude is now embedded as `prelude.ail`
|
||||
//! in `ailang-surface` and parsed at compile time via
|
||||
@@ -21,12 +14,11 @@
|
||||
//! four `Recur*` diagnostics (recur-outside-loop /
|
||||
//! recur-arity-mismatch / recur-type-mismatch /
|
||||
//! recur-not-in-tail-position) — the diagnostic code is the
|
||||
//! load-bearing assertion, mirroring the §C4(a) / mut.2
|
||||
//! load-bearing assertion, mirroring the §C4(a)
|
||||
//! negative-fixture convention.
|
||||
//! - loop-recur iter loop-recur.tidy: 1 negative typecheck fixture
|
||||
//! for the lambda-capture-of-loop-binder rejection
|
||||
//! (loop-binder-captured-by-lambda) — symmetric to the mut.4-tidy
|
||||
//! `test_mut_var_captured_by_lambda.ail.json` carve-out.
|
||||
//! (loop-binder-captured-by-lambda).
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
@@ -39,14 +31,6 @@ const EXPECTED: &[&str] = &[
|
||||
"test_ct1_bad_qualifier.ail.json",
|
||||
"test_ct1_bare_xmod_rejected.ail.json",
|
||||
"test_ct1_qualified_class_rejected.ail.json",
|
||||
// Iter mut.2 — negative typecheck fixtures + positive shadow-pin
|
||||
"test_mut_assign_out_of_scope.ail.json",
|
||||
"test_mut_assign_outside_mut.ail.json",
|
||||
"test_mut_assign_type_mismatch.ail.json",
|
||||
"test_mut_nested_shadow_legal.ail.json",
|
||||
"test_mut_var_unsupported_type.ail.json",
|
||||
// Iter mut.4-tidy — lambda-capture-of-mut-var rejection
|
||||
"test_mut_var_captured_by_lambda.ail.json",
|
||||
// Iter loop-recur.tidy — lambda-capture-of-loop-binder rejection
|
||||
"test_loop_binder_captured_by_lambda.ail.json",
|
||||
// loop-recur iter 2 — negative typecheck fixtures
|
||||
|
||||
@@ -137,20 +137,6 @@ fn design_md_anchors_every_term_variant() {
|
||||
body: Box::new(Term::Var { name: "y".into() }),
|
||||
},
|
||||
),
|
||||
(
|
||||
r#""t": "mut""#,
|
||||
Term::Mut {
|
||||
vars: Vec::new(),
|
||||
body: Box::new(Term::Lit { lit: Literal::Unit }),
|
||||
},
|
||||
),
|
||||
(
|
||||
r#""t": "assign""#,
|
||||
Term::Assign {
|
||||
name: "x".into(),
|
||||
value: Box::new(Term::Lit { lit: Literal::Unit }),
|
||||
},
|
||||
),
|
||||
(
|
||||
r#""t": "loop""#,
|
||||
Term::Loop {
|
||||
@@ -181,8 +167,6 @@ fn design_md_anchors_every_term_variant() {
|
||||
Term::Seq { .. } => "seq",
|
||||
Term::Clone { .. } => "clone",
|
||||
Term::ReuseAs { .. } => "reuse-as",
|
||||
Term::Mut { .. } => "mut",
|
||||
Term::Assign { .. } => "assign",
|
||||
Term::Loop { .. } => "loop",
|
||||
Term::Recur { .. } => "recur",
|
||||
};
|
||||
@@ -444,19 +428,3 @@ fn data_model_section_is_bounded() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn design_md_documents_the_accumulator_over_iteration_idiom() {
|
||||
let design = std::fs::read_to_string(
|
||||
concat!(env!("CARGO_MANIFEST_DIR"), "/../../docs/DESIGN.md"),
|
||||
)
|
||||
.expect("read DESIGN.md");
|
||||
assert!(
|
||||
design.contains("Accumulator-over-iteration shape (documented idiom, not an enforced rule)"),
|
||||
"the F1/F4 documented-idiom note must not be silently dropped from DESIGN.md"
|
||||
);
|
||||
assert!(
|
||||
design.contains("examples/mut_counter.ail is the reference")
|
||||
|| design.contains("`examples/mut_counter.ail` is the reference"),
|
||||
"the F1/F4 note must keep pointing at the canonical fallback fixture"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -47,8 +47,6 @@ enum VariantTag {
|
||||
TermSeq,
|
||||
TermClone,
|
||||
TermReuseAs,
|
||||
TermMut,
|
||||
TermAssign,
|
||||
TermLoop,
|
||||
TermRecur,
|
||||
// Pattern
|
||||
@@ -96,8 +94,6 @@ const EXPECTED_VARIANTS: &[VariantTag] = &[
|
||||
VariantTag::TermSeq,
|
||||
VariantTag::TermClone,
|
||||
VariantTag::TermReuseAs,
|
||||
VariantTag::TermMut,
|
||||
VariantTag::TermAssign,
|
||||
VariantTag::TermLoop,
|
||||
VariantTag::TermRecur,
|
||||
VariantTag::PatternWild,
|
||||
@@ -236,18 +232,6 @@ fn visit_term(t: &Term, observed: &mut HashSet<VariantTag>) {
|
||||
visit_term(source, observed);
|
||||
visit_term(body, observed);
|
||||
}
|
||||
Term::Mut { vars, body } => {
|
||||
observed.insert(VariantTag::TermMut);
|
||||
for v in vars {
|
||||
visit_type(&v.ty, observed);
|
||||
visit_term(&v.init, observed);
|
||||
}
|
||||
visit_term(body, observed);
|
||||
}
|
||||
Term::Assign { value, .. } => {
|
||||
observed.insert(VariantTag::TermAssign);
|
||||
visit_term(value, observed);
|
||||
}
|
||||
Term::Loop { binders, body } => {
|
||||
observed.insert(VariantTag::TermLoop);
|
||||
for b in binders {
|
||||
|
||||
@@ -114,20 +114,6 @@ fn spec_mentions_every_term_variant() {
|
||||
body: Box::new(Term::Var { name: "y".into() }),
|
||||
},
|
||||
),
|
||||
(
|
||||
"(mut",
|
||||
Term::Mut {
|
||||
vars: Vec::new(),
|
||||
body: Box::new(Term::Lit { lit: Literal::Unit }),
|
||||
},
|
||||
),
|
||||
(
|
||||
"(assign",
|
||||
Term::Assign {
|
||||
name: "x".into(),
|
||||
value: Box::new(Term::Lit { lit: Literal::Unit }),
|
||||
},
|
||||
),
|
||||
(
|
||||
"(loop",
|
||||
Term::Loop {
|
||||
@@ -160,8 +146,6 @@ fn spec_mentions_every_term_variant() {
|
||||
Term::Seq { .. } => "seq",
|
||||
Term::Clone { .. } => "clone",
|
||||
Term::ReuseAs { .. } => "reuse-as",
|
||||
Term::Mut { .. } => "mut",
|
||||
Term::Assign { .. } => "assign",
|
||||
Term::Loop { .. } => "loop",
|
||||
Term::Recur { .. } => "recur",
|
||||
};
|
||||
|
||||
@@ -906,35 +906,6 @@ fn write_term_prec(out: &mut String, t: &Term, level: usize, parent_prec: u8, ow
|
||||
out.push_str(&body_buf);
|
||||
}
|
||||
}
|
||||
Term::Mut { vars, body } => {
|
||||
// Iter mut.1: prose-side minimal-correctness rendering for
|
||||
// the `(mut ...)` block. The prose-form for mut blocks is
|
||||
// not yet fully designed (the prose surface predates this
|
||||
// milestone); render the block as `mut { var <name>: <ty>
|
||||
// = <init>; ...; <body> }` so a reader can see the shape
|
||||
// without overcommitting to a final prose syntax. Refined
|
||||
// in a follow-on prose iter once the LLM-author signal
|
||||
// arrives.
|
||||
out.push_str("mut {\n");
|
||||
for v in vars {
|
||||
indent(out, level + 1);
|
||||
out.push_str("var ");
|
||||
out.push_str(&v.name);
|
||||
out.push_str(" = ");
|
||||
write_term(out, &v.init, level + 1, owning_module);
|
||||
out.push_str(";\n");
|
||||
}
|
||||
indent(out, level + 1);
|
||||
write_term(out, body, level + 1, owning_module);
|
||||
out.push('\n');
|
||||
indent(out, level);
|
||||
out.push('}');
|
||||
}
|
||||
Term::Assign { name, value } => {
|
||||
out.push_str(name);
|
||||
out.push_str(" := ");
|
||||
write_term(out, value, level, owning_module);
|
||||
}
|
||||
Term::Loop { binders, body } => {
|
||||
out.push_str("loop(");
|
||||
for (i, b) in binders.iter().enumerate() {
|
||||
@@ -1133,33 +1104,6 @@ fn count_free_var(name: &str, t: &Term) -> usize {
|
||||
}
|
||||
Term::Clone { value } => count_free_var(name, value),
|
||||
Term::ReuseAs { source, body } => count_free_var(name, source) + count_free_var(name, body),
|
||||
// Iter mut.1: a `Term::Mut` whose `vars` includes a name
|
||||
// matching `name` shadows the outer binding for both later
|
||||
// var inits and the body. Var inits before the shadowing one
|
||||
// still see the outer `name`.
|
||||
Term::Mut { vars, body } => {
|
||||
let mut total = 0usize;
|
||||
let mut shadowed = false;
|
||||
for v in vars {
|
||||
if !shadowed {
|
||||
total += count_free_var(name, &v.init);
|
||||
}
|
||||
if v.name == name {
|
||||
shadowed = true;
|
||||
}
|
||||
}
|
||||
if !shadowed {
|
||||
total += count_free_var(name, body);
|
||||
}
|
||||
total
|
||||
}
|
||||
// Iter mut.1: the assigned `name` field is a use of the
|
||||
// mut-var binding (which may or may not be `name`); the
|
||||
// value is recursed.
|
||||
Term::Assign { name: assign_name, value } => {
|
||||
let n_use = if assign_name == name { 1 } else { 0 };
|
||||
n_use + count_free_var(name, value)
|
||||
}
|
||||
// loop-recur iter 1: a binder named `name` shadows the outer
|
||||
// binding for later binder inits and the body. Inits before
|
||||
// the shadowing binder still see the outer `name`.
|
||||
@@ -1293,50 +1237,9 @@ fn subst_var_with_term(t: &Term, name: &str, replacement: &Term) -> Term {
|
||||
source: Box::new(subst_var_with_term(source, name, replacement)),
|
||||
body: Box::new(subst_var_with_term(body, name, replacement)),
|
||||
},
|
||||
// Iter mut.1: lexical-shadow semantics for mut-vars symmetric
|
||||
// to `count_free_var` above: once a var named `name` is
|
||||
// declared, neither later inits nor the body should be
|
||||
// loop-recur iter 1: lexical-shadow semantics — once a binder
|
||||
// named `name` is declared, later inits and the body are not
|
||||
// rewritten.
|
||||
Term::Mut { vars, body } => {
|
||||
let mut shadowed = false;
|
||||
let new_vars: Vec<ailang_core::ast::MutVar> = vars
|
||||
.iter()
|
||||
.map(|v| {
|
||||
let init = if shadowed {
|
||||
v.init.clone()
|
||||
} else {
|
||||
subst_var_with_term(&v.init, name, replacement)
|
||||
};
|
||||
if v.name == name {
|
||||
shadowed = true;
|
||||
}
|
||||
ailang_core::ast::MutVar {
|
||||
name: v.name.clone(),
|
||||
ty: v.ty.clone(),
|
||||
init,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let body_rw = if shadowed {
|
||||
(**body).clone()
|
||||
} else {
|
||||
subst_var_with_term(body, name, replacement)
|
||||
};
|
||||
Term::Mut {
|
||||
vars: new_vars,
|
||||
body: Box::new(body_rw),
|
||||
}
|
||||
}
|
||||
// Iter mut.1: substitute only inside `value`. The `name`
|
||||
// field is a binding reference (cf. the desugar.rs
|
||||
// `subst_var` arm).
|
||||
Term::Assign { name: assign_name, value } => Term::Assign {
|
||||
name: assign_name.clone(),
|
||||
value: Box::new(subst_var_with_term(value, name, replacement)),
|
||||
},
|
||||
// loop-recur iter 1: lexical-shadow semantics symmetric to
|
||||
// count_free_var — once a binder named `name` is declared,
|
||||
// later inits and the body are not rewritten.
|
||||
Term::Loop { binders, body } => {
|
||||
let mut shadowed = false;
|
||||
let new_binders: Vec<ailang_core::ast::LoopBinder> = binders
|
||||
|
||||
@@ -40,7 +40,6 @@
|
||||
//! | app-term | tail-app-term | match-term | ctor-term
|
||||
//! | do-term | tail-do-term | seq-term | lam-term | if-term
|
||||
//! | let-term | let-rec-term | clone-term | reuse-as-term
|
||||
//! | mut-term | assign-term
|
||||
//! var-ref ::= ident ; reserved: true/false → bool-lit
|
||||
//! int-lit ::= integer ; numeric atom
|
||||
//! str-lit ::= string ; string atom
|
||||
@@ -67,9 +66,6 @@
|
||||
//! "(" "in" term ")" ")"
|
||||
//! clone-term ::= "(" "clone" term ")" ; Iter 18c.1
|
||||
//! reuse-as-term ::= "(" "reuse-as" term term ")" ; Iter 18d.1
|
||||
//! mut-term ::= "(" "mut" var-decl* term+ ")" ; Iter mut.1
|
||||
//! var-decl ::= "(" "var" ident type term ")" ; legal only inside mut-term
|
||||
//! assign-term ::= "(" "assign" ident term ")" ; Iter mut.1; legal only inside mut-term
|
||||
//!
|
||||
//! pattern ::= pat-var | pat-ctor | pat-lit | pat-wild
|
||||
//! pat-var ::= ident
|
||||
@@ -1210,8 +1206,6 @@ impl<'a> Parser<'a> {
|
||||
"let-rec" => self.parse_let_rec(),
|
||||
"clone" => self.parse_clone(),
|
||||
"reuse-as" => self.parse_reuse_as(),
|
||||
"mut" => self.parse_mut(),
|
||||
"assign" => self.parse_assign(),
|
||||
"loop" => self.parse_loop(),
|
||||
"recur" => self.parse_recur(),
|
||||
other => {
|
||||
@@ -1221,8 +1215,8 @@ impl<'a> Parser<'a> {
|
||||
message: format!(
|
||||
"unknown term head `{other}`; expected one of \
|
||||
`app`, `tail-app`, `lam`, `let`, `let-rec`, `if`, `match`, `do`, \
|
||||
`tail-do`, `seq`, `term-ctor`, `clone`, `reuse-as`, `mut`, \
|
||||
`assign`, `loop`, `recur`, `lit-unit`"
|
||||
`tail-do`, `seq`, `term-ctor`, `clone`, `reuse-as`, \
|
||||
`loop`, `recur`, `lit-unit`"
|
||||
),
|
||||
pos,
|
||||
})
|
||||
@@ -1574,82 +1568,11 @@ impl<'a> Parser<'a> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Iter mut.1: `(mut (var NAME TYPE INIT)* BODY_TERM+)` — local
|
||||
/// mutable-state block. Reads zero or more `(var ...)` entries
|
||||
/// off the front of the body, then ≥ 1 trailing terms. The
|
||||
/// trailing sequence is right-folded into `Term::Seq` with the
|
||||
/// final term as the seed (so the JSON-AST always sees a single
|
||||
/// `body: Term`). Spec `docs/specs/2026-05-15-mut-local.md`
|
||||
/// §"Form A surface" + §"Canonical-form invariants".
|
||||
fn parse_mut(&mut self) -> Result<Term, ParseError> {
|
||||
let head_pos = self.peek().map(|t| t.span.start).unwrap_or(0);
|
||||
self.expect_lparen("mut-term")?;
|
||||
self.expect_keyword("mut")?;
|
||||
|
||||
// Pull off all leading (var NAME TYPE INIT) entries.
|
||||
let mut vars: Vec<ailang_core::ast::MutVar> = Vec::new();
|
||||
while matches!(self.peek_head_ident(), Some("var")) {
|
||||
self.expect_lparen("mut-var")?;
|
||||
self.expect_keyword("var")?;
|
||||
let name = self.expect_ident("mut-var-name")?;
|
||||
let ty = self.parse_type()?;
|
||||
let init = self.parse_term()?;
|
||||
self.expect_rparen("mut-var")?;
|
||||
vars.push(ailang_core::ast::MutVar { name, ty, init });
|
||||
}
|
||||
|
||||
// Then read ≥ 1 trailing body terms. Right-fold into Seq
|
||||
// with the final term as the seed.
|
||||
let mut body_stmts: Vec<Term> = Vec::new();
|
||||
while !matches!(self.peek(), Some(Token { tok: Tok::RParen, .. })) {
|
||||
body_stmts.push(self.parse_term()?);
|
||||
}
|
||||
if body_stmts.is_empty() {
|
||||
return Err(ParseError::Production {
|
||||
production: "mut-term",
|
||||
message: "(mut ...) requires at least one body expression after vars".into(),
|
||||
pos: head_pos,
|
||||
});
|
||||
}
|
||||
self.expect_rparen("mut-term")?;
|
||||
|
||||
let mut body = body_stmts.pop().expect("non-empty after the check above");
|
||||
while let Some(s) = body_stmts.pop() {
|
||||
body = Term::Seq {
|
||||
lhs: Box::new(s),
|
||||
rhs: Box::new(body),
|
||||
};
|
||||
}
|
||||
Ok(Term::Mut {
|
||||
vars,
|
||||
body: Box::new(body),
|
||||
})
|
||||
}
|
||||
|
||||
/// Iter mut.1: `(assign NAME VALUE)` — in-block update of a
|
||||
/// mut-var. Positional shape: name then value. The lexical-scope
|
||||
/// rule ("legal only inside a `(mut ...)` whose `vars` includes
|
||||
/// a var with the same `name`") is enforced at typecheck
|
||||
/// (mut.2, `CheckError::MutAssignOutOfScope`); the parser
|
||||
/// accepts the shape unconditionally.
|
||||
fn parse_assign(&mut self) -> Result<Term, ParseError> {
|
||||
self.expect_lparen("assign-term")?;
|
||||
self.expect_keyword("assign")?;
|
||||
let name = self.expect_ident("assign-name")?;
|
||||
let value = self.parse_term()?;
|
||||
self.expect_rparen("assign-term")?;
|
||||
Ok(Term::Assign {
|
||||
name,
|
||||
value: Box::new(value),
|
||||
})
|
||||
}
|
||||
|
||||
/// loop-recur iter 1: `(loop (NAME TYPE INIT)* BODY_TERM+)` —
|
||||
/// strict iteration block. Reads zero or more `(NAME TYPE INIT)`
|
||||
/// binder triples (bare, no leading keyword — unlike `(var ...)`,
|
||||
/// the loop binder triple has no `var` keyword), then ≥ 1
|
||||
/// trailing terms right-folded into `Term::Seq` (mirrors
|
||||
/// `parse_mut`). The binder/body boundary is disambiguated by the
|
||||
/// binder triples (bare, no leading keyword), then ≥ 1
|
||||
/// trailing terms right-folded into `Term::Seq`. The binder/body
|
||||
/// boundary is disambiguated by the
|
||||
/// inner head: a binder's first inner token is an ident NAME
|
||||
/// (never a term-head keyword), whereas a parenthesised body form
|
||||
/// (`(if …)`, `(recur …)`, `(app …)`, …) opens with a term-head
|
||||
@@ -1673,8 +1596,6 @@ impl<'a> Parser<'a> {
|
||||
| "let-rec"
|
||||
| "clone"
|
||||
| "reuse-as"
|
||||
| "mut"
|
||||
| "assign"
|
||||
| "loop"
|
||||
| "recur"
|
||||
)
|
||||
@@ -2594,89 +2515,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Iter mut.1: `(mut 0)` parses as a `Term::Mut` with empty `vars`
|
||||
/// and an `Int 0` body. Spec
|
||||
/// `docs/specs/2026-05-15-mut-local.md` §"Canonical-form
|
||||
/// invariants" — the empty-vars form is a legal degenerate case
|
||||
/// the schema accepts uniformly.
|
||||
#[test]
|
||||
fn parses_empty_mut_with_int_body() {
|
||||
let t = parse_term("(mut 0)").expect("parse");
|
||||
match t {
|
||||
Term::Mut { vars, body } => {
|
||||
assert!(vars.is_empty(), "vars should be empty, got {vars:?}");
|
||||
match *body {
|
||||
Term::Lit { lit: Literal::Int { value: 0 } } => {}
|
||||
other => panic!("expected Lit Int 0, got {other:?}"),
|
||||
}
|
||||
}
|
||||
other => panic!("expected Term::Mut, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Iter mut.1: `(mut (var x ...) (assign x ...) x)` parses with
|
||||
/// the trailing statement-and-final-expression sequence right-
|
||||
/// folded into a `Term::Seq`. The schema's `Term::Mut.body` is
|
||||
/// always a single Term; multi-statement bodies are folded
|
||||
/// through `Seq` at parse time.
|
||||
#[test]
|
||||
fn parses_mut_with_one_var_and_one_assign_and_final() {
|
||||
let src = "(mut (var x (con Int) 0) (assign x (app + x 1)) x)";
|
||||
let t = parse_term(src).expect("parse");
|
||||
match t {
|
||||
Term::Mut { vars, body } => {
|
||||
assert_eq!(vars.len(), 1, "expected exactly one var");
|
||||
assert_eq!(vars[0].name, "x");
|
||||
match *body {
|
||||
Term::Seq { lhs, rhs } => {
|
||||
match *lhs {
|
||||
Term::Assign { name, .. } => assert_eq!(name, "x"),
|
||||
other => panic!("expected Assign as Seq.lhs, got {other:?}"),
|
||||
}
|
||||
match *rhs {
|
||||
Term::Var { name } => assert_eq!(name, "x"),
|
||||
other => panic!("expected Var x as Seq.rhs, got {other:?}"),
|
||||
}
|
||||
}
|
||||
other => panic!("expected Seq as Mut.body, got {other:?}"),
|
||||
}
|
||||
}
|
||||
other => panic!("expected Term::Mut, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Iter mut.1: `(mut)` with neither vars nor body is rejected at
|
||||
/// parse — the spec's §"Canonical-form invariants" mandates at
|
||||
/// least one body expression after the `var` entries.
|
||||
#[test]
|
||||
fn rejects_mut_with_no_body() {
|
||||
let err = parse_term("(mut)").expect_err("must reject empty mut");
|
||||
let msg = format!("{err}");
|
||||
assert!(
|
||||
msg.contains("mut"),
|
||||
"diagnostic should mention `mut`, got: {msg}"
|
||||
);
|
||||
assert!(
|
||||
msg.contains("body") || msg.contains("expression"),
|
||||
"diagnostic should mention the missing body, got: {msg}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Iter mut.1: `(mut (var x ...))` declares a var but has no
|
||||
/// trailing body expression — also rejected (the rule is "≥ 0
|
||||
/// vars followed by ≥ 1 body terms"; zero body terms is the
|
||||
/// rejection trigger).
|
||||
#[test]
|
||||
fn rejects_mut_with_only_vars_no_final_expression() {
|
||||
let err = parse_term("(mut (var x (con Int) 0))")
|
||||
.expect_err("must reject vars-only mut");
|
||||
let msg = format!("{err}");
|
||||
assert!(
|
||||
msg.contains("body") || msg.contains("expression"),
|
||||
"diagnostic should mention missing body, got: {msg}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_loop_and_recur_round_trip_via_term() {
|
||||
let src = "(loop (acc (con Int) 0) (i (con Int) 1) (if (app > i n) acc (recur (app + acc i) (app + i 1))))";
|
||||
|
||||
@@ -548,57 +548,10 @@ fn write_term(out: &mut String, t: &Term, level: usize) {
|
||||
write_term(out, body, level);
|
||||
out.push(')');
|
||||
}
|
||||
Term::Mut { vars, body } => {
|
||||
// Iter mut.1: print as
|
||||
// `(mut (var NAME TYPE INIT)* STMT* FINAL_EXPR)`
|
||||
// where the body's right-spine of `Term::Seq` is walked
|
||||
// and each lhs is printed as a top-level statement; the
|
||||
// terminal expression (the rightmost non-Seq term) is the
|
||||
// block's value. This is the inverse of the parser's
|
||||
// right-fold over the trailing sequence.
|
||||
out.push_str("(mut");
|
||||
for v in vars {
|
||||
out.push_str(" (var ");
|
||||
out.push_str(&v.name);
|
||||
out.push(' ');
|
||||
write_type(out, &v.ty);
|
||||
out.push(' ');
|
||||
write_term(out, &v.init, level);
|
||||
out.push(')');
|
||||
}
|
||||
let mut cursor: &Term = body;
|
||||
loop {
|
||||
match cursor {
|
||||
Term::Seq { lhs, rhs } => {
|
||||
out.push(' ');
|
||||
write_term(out, lhs, level);
|
||||
cursor = rhs;
|
||||
}
|
||||
other => {
|
||||
out.push(' ');
|
||||
write_term(out, other, level);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(')');
|
||||
}
|
||||
Term::Assign { name, value } => {
|
||||
// Iter mut.1: print as `(assign NAME VALUE)`. Legal only
|
||||
// inside a `Term::Mut.body`; the parser enforces the
|
||||
// structural rule, the typechecker (mut.2) enforces the
|
||||
// scope rule.
|
||||
out.push_str("(assign ");
|
||||
out.push_str(name);
|
||||
out.push(' ');
|
||||
write_term(out, value, level);
|
||||
out.push(')');
|
||||
}
|
||||
Term::Loop { binders, body } => {
|
||||
// loop-recur iter 1: print as
|
||||
// `(loop (NAME TYPE INIT)* STMT* FINAL_EXPR)`
|
||||
// — inverse of parse_loop's binder read + Seq right-fold,
|
||||
// mirroring the Term::Mut printer.
|
||||
// — inverse of parse_loop's binder read + Seq right-fold.
|
||||
out.push_str("(loop");
|
||||
for b in binders {
|
||||
out.push_str(" (");
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
//! Pins the mut/var/assign removal: the keyword no longer parses and
|
||||
//! the canonical JSON tag is an unknown serde variant. RED until the
|
||||
//! Task-2 atomic cut lands.
|
||||
use ailang_surface::parse;
|
||||
|
||||
#[test]
|
||||
fn mut_keyword_is_rejected_by_form_a_parse() {
|
||||
let src = "(module m (fn f (type (fn-type (params) (ret (con Int)))) (params) (body (mut (var x (con Int) 0) (assign x (app + x 1)) x))))";
|
||||
let r = parse(src);
|
||||
assert!(r.is_err(), "mut keyword must no longer parse, got Ok");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assign_keyword_is_rejected_by_form_a_parse() {
|
||||
let src = "(module m (fn f (type (fn-type (params) (ret (con Int)))) (params) (body (assign x 1))))";
|
||||
assert!(parse(src).is_err(), "assign keyword must no longer parse, got Ok");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_tag_mut_is_unknown_serde_variant() {
|
||||
let j = r#"{"t":"mut","vars":[],"body":{"t":"lit","lit":{"kind":"int","value":0}}}"#;
|
||||
let r: Result<ailang_core::ast::Term, _> = serde_json::from_str(j);
|
||||
assert!(r.is_err(), "{{\"t\":\"mut\"}} must be an unknown variant, got Ok");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_tag_assign_is_unknown_serde_variant() {
|
||||
let j = r#"{"t":"assign","name":"x","value":{"t":"lit","lit":{"kind":"int","value":1}}}"#;
|
||||
let r: Result<ailang_core::ast::Term, _> = serde_json::from_str(j);
|
||||
assert!(r.is_err(), "{{\"t\":\"assign\"}} must be an unknown variant, got Ok");
|
||||
}
|
||||
Reference in New Issue
Block a user