diff --git a/spec/checker/src/form/bridge.rs b/spec/checker/src/form/bridge.rs index 1d4bc0e0..14ba48c0 100644 --- a/spec/checker/src/form/bridge.rs +++ b/spec/checker/src/form/bridge.rs @@ -51,8 +51,9 @@ //! the fuel trap is not among them. Zero declared outputs schedule as the //! unit tuple, and several declared outputs as `tup(outputs…)`. The core //! has one return, so reading that schedule back does not restore a -//! zero-output or multi-output signature. A list or array singleton has -//! no dummy value in this slice +//! zero-output or multi-output signature. A list singleton's initial +//! value is `list.new` of the element; both arms that run drop it and +//! store the real sum. An array singleton has no dummy value in this slice //! //! A construct outside that fragment requires change. The reason starts with //! a tag (`global`, `out`, `carrier`, `graph`, `catch`, `recursion`, `loop`, @@ -555,10 +556,21 @@ impl Built { } /// A literal node. A second use of the same literal in this region is the /// same source, so a domain test and the operation it guards compare equal. + /// + /// A bool an arm returns is a node of that arm, including a pure `break` + /// whose only result is the flag. The parent's dummy `false` is not that + /// node: FG8 reads a literal false in the same region, and a capture of + /// the dummy is a carried bool (B4). fn ensure_lit(&self, sc: &mut Scope, t: &Ty, l: &Lit) -> Result { - if let Some(s) = find_lit(sc, t, l) { + if let Some(s) = lit_in_region(sc, t, l) { return Ok(s); } + if let Some(s) = find_lit(sc, t, l) { + let fresh_bool = matches!(l, Lit::Bool(_)) && matches!(s, Src::In(_)); + if !fresh_bool { + return Ok(s); + } + } let s = self.lit_node(sc, t, l)?; sc.lits.push((t.clone(), l.clone(), s)); Ok(s) @@ -2127,7 +2139,6 @@ impl Built { thread: Option, ret_ty: &BTy, names: u32, - false_lit: Option, ) -> Result<(End, Scope), Change> { let mut sc = Scope { nodes: vec![], @@ -2156,17 +2167,12 @@ impl Built { sc.caps.push(p); sc.omega = Some(Src::In(j)); } - // A pure break returns the parent's literal false, captured, with no - // node in the arm. The schedule's branch dummy is that same literal, - // so construct(schedule(F)) rebuilds this capture instead of a second - // copy inside the arm (B4: the flag is not a carried input). + // A pure break stores a fresh false in this arm. The node has no + // inputs. A capture of the parent's dummy is not a node FG8 can + // read, and it is a carried bool (B4). if fall.is_empty() && stmts.len() == 1 && matches!(stmts[0], Stmt::Break(d) if *d == names) { - let src = - false_lit.ok_or_else(|| self.deny("defect: a break flag has no literal false"))?; - let j = sc.caps.len() as u32; - sc.caps.push(src); - sc.exit_flag = Some(Src::In(j)); + sc.exit_flag = Some(lit_bool(&mut sc, false)); return Ok((End::Exit, sc)); } let live = sc.omega.or(parent_omega); @@ -2237,11 +2243,6 @@ impl Built { let lits = lits_already(sc, &[t, e], &tail_refs); let seed = self.seed_of(&[t, e], &tail_refs, sc); let sel = self.src_atom(sc, c)?; - let false_lit = if !t_arm_falls || !e_arm_falls { - Some(self.ensure_lit(sc, &Ty::Bool, &Lit::Bool(false))?) - } else { - None - }; let (e1, a1) = self.body_arm( &t_stmts, t_fall, @@ -2255,7 +2256,6 @@ impl Built { thread, ret_ty, names, - if t_arm_falls { None } else { false_lit }, )?; let (e0, a0) = self.body_arm( &e_stmts, @@ -2270,7 +2270,6 @@ impl Built { thread, ret_ty, names, - if e_arm_falls { None } else { false_lit }, )?; if let Some(r) = agreed_residual(a1.exit_residual, a0.exit_residual) { sc.exit_residual = Some(r); @@ -2325,7 +2324,7 @@ impl Built { let seed = self.seed_of(&[fall_arm, halt_arm], &tail_refs, sc); let sel = self.src_atom(sc, c)?; let (fall_end, fall_sc) = self.body_arm( - &cont, fall, fall_names, far, far_names, &seed, &lits, sc, here, thread, ret_ty, names, None, + &cont, fall, fall_names, far, far_names, &seed, &lits, sc, here, thread, ret_ty, names, )?; let (halt_end, halt_sc) = self.arm(halt_arm, &seed, &lits, sc, here, thread, ret_ty)?; lose_outputs(sc, &fall_sc); @@ -3083,6 +3082,11 @@ fn find_lit(sc: &Scope, t: &Ty, l: &Lit) -> Option { if let Some((_, _, s)) = sc.lits.iter().find(|(tt, ll, _)| tt == t && ll == l) { return Some(*s); } + lit_in_region(sc, t, l) +} + +/// A literal node this region built. A capture of the same bits is not it. +fn lit_in_region(sc: &Scope, t: &Ty, l: &Lit) -> Option { let bt = bty(t).ok()?; sc.nodes .iter() @@ -4461,7 +4465,13 @@ fn dummy_atom(b: &mut Bld, ty: &Ty) -> Result { let id = b.prim("tup.mk", vec![ty.clone()], args, ty.clone()); Ok(Atom::V(id)) } - Ty::List(_) => Err("a list singleton has no dummy in this slice".into()), + Ty::List(e) => { + // The initial is empty. Both arms that run drop it and store + // the real sum, the same way a branch output's list dummy is + // `list.new`. + let id = b.prim("list.new", vec![(**e).clone()], vec![], ty.clone()); + Ok(Atom::V(id)) + } Ty::Arr(_) => Err("an array singleton has no dummy in this slice".into()), Ty::Sum(xs) => { let first = xs.first().ok_or("an empty sum has no dummy")?; @@ -5045,6 +5055,21 @@ fn schedule_catch( Ok(()) } +/// Whether region input `j` is an operand of a node here, or of a node in a +/// nested branch that captures it. A value the arms only return is not read. +fn capture_is_read(body: &Body, j: u32) -> bool { + let src = Src::In(j); + body.nodes.iter().any(|nd| match &nd.attrs { + Attr::Branch(_, _) => { + nd.ins.first() == Some(&src) + || nd.ins.iter().skip(1).enumerate().any(|(k, s)| { + *s == src && nd.regions.iter().any(|r| capture_is_read(r, k as u32)) + }) + } + _ => nd.ins.contains(&src), + }) +} + fn schedule_branch( sch: &mut Sch, m: &form::Module, @@ -5087,6 +5112,36 @@ fn schedule_branch( vars.push((p, id)); } let dom = dom_from(sch, body, n.ins[0], env); + // A literal this branch captures, and that the arms only return, was a + // node of the parent. One `let` names it, and the arm uses that local, + // so construction finds the same node. A bool stays an atom. Construction + // stores a fresh `false` in the break arm, including a pure break, and + // does not reuse the output var's dummy (B4, FG8). A literal an arm + // reads stays an atom, so a domain test and the operation it guards are + // still the same value (W4, FG8). + // The parent's env keeps the atom. A later `sum.mk` in this region still + // needs a literal index (W1). Only the arm sees the `let`. + let mut lifted: HashMap = HashMap::new(); + for (j, s) in n.ins.iter().skip(1).enumerate() { + if lifted.contains_key(s) { + continue; + } + let Some(Av::A(Atom::K(t, l))) = env.get(s).cloned() else { + continue; + }; + if matches!(l, Lit::Bool(_)) { + continue; + } + // An operand stays an atom. Lifting the literal 1 of `int.add` out + // of the domain arm makes the core fail W4: the add is no longer + // dominated by `int.bad.add` on the same values. A literal the arms + // only return, such as the 0 of a comparison, is the parent's node. + if n.regions.iter().any(|r| capture_is_read(r, j as u32)) { + continue; + } + let id = sch.let_atom(Atom::K(t.clone(), l), t)?; + lifted.insert(*s, id); + } // Snapshot after the output vars exist. Each arm restores it, so a capture // the first arm moves is live again for the second arm. let saved_live = sch.live.clone(); @@ -5100,12 +5155,14 @@ fn schedule_branch( let saved = std::mem::take(&mut sch.stmts); let mut en = env.clone(); for (j, s) in n.ins.iter().skip(1).enumerate() { - en.insert( - Src::In(j as u32), + let av = if let Some(id) = lifted.get(s) { + Av::A(Atom::V(*id)) + } else { env.get(s) .cloned() - .ok_or_else(|| sch.deny("defect: a capture has no value"))?, - ); + .ok_or_else(|| sch.deny("defect: a capture has no value"))? + }; + en.insert(Src::In(j as u32), av); } let mark = sch.next; schedule_region(sch, m, group, region, &mut en, dom)?; diff --git a/spec/checker/src/typed.rs b/spec/checker/src/typed.rs index 848f8dc1..d96b07ca 100644 --- a/spec/checker/src/typed.rs +++ b/spec/checker/src/typed.rs @@ -628,6 +628,22 @@ fn env_join(a: &Option, b: &Option) -> Option { } } +/// The type of `e catch h` when both sides are integers. +/// +/// The handler has type τ ([Catch] in 5.1). A handler whose names are only +/// `lit` is that untyped literal: it takes τ's name when τ has one check +/// range, and the values are those of either side. A handler that already +/// carries another name keeps the joined names. +pub fn catch_int(ok: IntT, h: IntT) -> IntT { + let joined = ok.join(h); + let literal = h.tags.names().iter().all(|n| *n == "lit"); + if literal && !ok.tags.has_lit() && ok.check_range().is_some() { + IntT { tags: ok.tags, lo: joined.lo, hi: joined.hi } + } else { + joined + } +} + /// The re-typing of an assignment (interp `exec` of `=`): a place holding an /// integer with a declared name keeps that name, and the stored value is /// checked against it; a place holding an untyped literal takes the stored @@ -954,7 +970,14 @@ impl<'a, 'm> Cx<'a, 'm> { let ht = self.expr(h); self.scopes.pop(); self.env = env_join(&before, &self.env); - plain(ok.join(&ht)) + // [Catch] gives the handler type τ, the success type. A + // literal handler is untyped until that type is given to it + // (6.3): it takes τ's name, and the sum is checked against + // that one range (N2). + plain(match (&ok, &ht) { + (RType::Int(o), RType::Int(h)) => RType::Int(catch_int(*o, *h)), + _ => ok.join(&ht), + }) } E::Try(x, els, _) => { let xt = self.expr(x); diff --git a/spec/checker/tests/break_fg8_witness.rs b/spec/checker/tests/break_fg8_witness.rs index 872fb4e3..7be026a4 100644 --- a/spec/checker/tests/break_fg8_witness.rs +++ b/spec/checker/tests/break_fg8_witness.rs @@ -173,18 +173,27 @@ fn assert_scheduled_values(origin: &CoreModule, scheduled: &CoreModule, args: Ve ); } -fn schedule_fg8(f: &fir::Module, at: &str) { +fn schedule_agrees(origin: &CoreModule, f: &fir::Module, cases: &[Vec]) -> bool { let s = bridge::schedule(f).unwrap_or_else(|e| panic!("schedule: {}", e.line())); wf::check(&s).unwrap_or_else(|e| panic!("schedule is not well formed: {e}")); - let e = bridge::construct(&s).expect_err("the scheduled measure was applied"); - assert_eq!(e.tag(), "FG8", "{}", e.line()); - assert_eq!(e.at, at, "{}", e.line()); + let back = bridge::construct(&s).unwrap_or_else(|e| panic!("schedule construct: {}", e.line())); + for args in cases { + assert_scheduled_values(origin, &s, args.clone()); + } + fir::encode(f) == fir::encode(&back) +} + +fn schedule_matches(origin: &CoreModule, f: &fir::Module, cases: &[Vec]) { + // Record the flag before the schedule is read back. That construct sees + // no source `break`, so it clears the flag. + let rewrote = bridge::body_break_rewrite(); assert!( - e.reason.contains( - "the body region does not return i raised by exactly one whenever it continues" - ), - "{}", - e.line() + schedule_agrees(origin, f, cases), + "construct(schedule(F)) is not F" + ); + assert!( + rewrote, + "the body break was not restructured, so the example would join the syntactic floor" ); } @@ -429,7 +438,11 @@ fn corpus_baseline_on_50294e05() { "61_dim_minimal.rce", ] ); - assert_eq!(names("FG8"), ["33_in_operator.rce"]); + assert!( + !root_tags.contains_key("FG8"), + "a program root's first tag is FG8: {:?}", + names("FG8") + ); assert!( names("catch").is_empty(), "a program root's first tag is catch: {:?}", @@ -451,11 +464,13 @@ fn corpus_baseline_on_50294e05() { "11_arena.rce", "18_while_bound.rce", "19_floats.rce", + "21_maps.rce", "22_tuples.rce", "24_lambda.rce", "25_labels.rce", "27_bitops.rce", "28_slices.rce", + "33_in_operator.rce", "36_multiline_brackets.rce", "41_arena_bound_wrapping.rce", "43_simd_lanes.rce", @@ -474,10 +489,6 @@ fn corpus_baseline_on_50294e05() { ("13_spawn_chan.rce".into(), "not covered by the lowering: the type chan i64".into()), ("14_select.rce".into(), "not covered by the lowering: the type chan text".into()), ("15_actor.rce".into(), "not covered by the lowering: the type chan i64".into()), - ( - "21_maps.rce".into(), - "not covered by the lowering: an integer operation checked against ranges that differ at run time ([\"lit\", \"u32\"])".into(), - ), ("29_nested_kind.rce".into(), "not covered by the lowering: a recursive type".into()), ( "34_chan_types.rce".into(), @@ -499,6 +510,7 @@ fn corpus_baseline_on_50294e05() { "04_bank_account.rce", "05_kind_match.rce", "06_option.rce", + "16_multi_region.rce", "17_traffic_light.rce", "19_floats.rce", "23_patterns.rce", @@ -510,21 +522,27 @@ fn corpus_baseline_on_50294e05() { "52_context_text.rce", "53_capability.rce", "54_secret.rce", + "56_utf8.rce", "57_float_vectors.rce", + "58_float_keys.rce", "59_dim_redundant_field.rce", "60_dim_hidden_period.rce", "61_dim_minimal.rce", ] ); - assert_eq!( - tagged("catch"), - ["16_multi_region.rce", "56_utf8.rce", "58_float_keys.rce"] + assert!( + !construct_tag.contains_key("catch"), + "a whole module's first tag is catch: {:?}", + tagged("catch") ); assert_eq!( tagged("defect"), ["07_error_union.rce", "20_strings.rce", "33_in_operator.rce"] ); - assert_eq!(tagged("exit"), ["02_hello_main.rce", "31_inventory.rce"]); + assert_eq!( + tagged("exit"), + ["02_hello_main.rce", "21_maps.rce", "31_inventory.rce"] + ); assert_eq!( tagged("global"), [ @@ -537,7 +555,11 @@ fn corpus_baseline_on_50294e05() { ); assert_eq!(tagged("loop"), ["55_rcedb.rce"]); assert_eq!(tagged("schedule defect"), ["22_tuples.rce"]); - assert_eq!(tagged("schedule FG8"), ["43_simd_lanes.rce"]); + assert!( + !construct_tag.contains_key("schedule FG8"), + "a schedule's first tag is FG8: {:?}", + construct_tag.get("schedule FG8") + ); assert_eq!( tagged("round-trip"), [ @@ -553,6 +575,7 @@ fn corpus_baseline_on_50294e05() { "36_multiline_brackets.rce", "40_extern.rce", "41_arena_bound_wrapping.rce", + "43_simd_lanes.rce", "48_linear_handle.rce", "49_loop_limit.rce", ] @@ -565,7 +588,6 @@ fn corpus_baseline_on_50294e05() { assert_eq!( root_tags.keys().cloned().collect::>(), [ - "FG8", "break", "defect", "exit", @@ -579,13 +601,11 @@ fn corpus_baseline_on_50294e05() { construct_tag.keys().cloned().collect::>(), [ "break", - "catch", "defect", "exit", "global", "loop", "round-trip", - "schedule FG8", "schedule defect", ] ); @@ -598,28 +618,46 @@ fn corpus_baseline_on_50294e05() { } #[test] -fn fn_table_constructs_and_the_schedule_is_refused_by_fg8() { - // Contract section 4. The first form is applied. The schedule is not. - // On 410bfd40 the file does not lower: 34c915fd keeps `fn freq`, and - // `(m.get(w) catch 0) + 1` mixes a literal with u32. The census records - // that refusal. `fn table` is the measure this test checks, so the - // function is lowered from its own line in the same file. +fn freq_search_break_stores_a_fresh_false() { + // `mfind`'s second break is a pure `break` of the search loop: the key + // is past the probe, so the arm does not step the index. The flag is a + // fresh literal false in that arm. A capture of the parent's dummy is + // not a node FG8 reads, so the first construct of `fn freq` failed at + // that measure. let src = std::fs::read_to_string( std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../examples/21_maps.rce"), ) .unwrap(); let ast = rce_spec_check::program(&src).unwrap(); - let err = rce_spec_check::one::core_of(&ast).expect_err("21_maps lowered"); - assert_eq!( - err, - "not covered by the lowering: an integer operation checked against ranges that differ at run time ([\"lit\", \"u32\"])" - ); - let line = src - .lines() - .find(|l| l.starts_with("fn table")) - .expect("fn table"); - let ast = rce_spec_check::program(&format!("{line}\n")).unwrap(); - let maps = rce_spec_check::one::core_of(&ast).unwrap_or_else(|e| panic!("fn table: {e}")); + let maps = rce_spec_check::one::core_of(&ast).unwrap_or_else(|e| panic!("21_maps: {e}")); + let mfind = bridge::closure(&maps, "mfind:Map[text, int{u32}[0, 4294967295]]").expect("mfind"); + let f = bridge::construct(&mfind).unwrap_or_else(|e| panic!("mfind: {}", e.line())); + let rewrote = bridge::body_break_rewrite(); + assert!(rewrote, "the search break was not restructured into a flag"); + let s = bridge::schedule(&f).unwrap_or_else(|e| panic!("mfind schedule: {}", e.line())); + let back = bridge::construct(&s).unwrap_or_else(|e| panic!("mfind schedule construct: {}", e.line())); + assert_eq!(fir::encode(&f), fir::encode(&back), "mfind construct(schedule(F)) is not F"); + // `fn freq` calls `mfind`. Its closure constructs, and the schedule + // constructs, so the file is not FG8. Byte identity of that whole + // closure is a separate spelling of the decimal helpers' empty text. + let freq = bridge::closure(&maps, "fn freq").expect("fn freq"); + let ff = bridge::construct(&freq).unwrap_or_else(|e| panic!("fn freq: {}", e.line())); + let fs = bridge::schedule(&ff).unwrap_or_else(|e| panic!("fn freq schedule: {}", e.line())); + bridge::construct(&fs).unwrap_or_else(|e| panic!("fn freq schedule construct: {}", e.line())); +} + +#[test] +fn fn_table_schedule_keeps_the_measure_and_matches_the_list() { + // Contract section 4. The search loop's flag and index stay two outputs + // of one Branch through the schedule, so `construct(schedule(F))` is F. + // `fn freq` counts in `u32`. The catch literal takes that success type, + // so the file lowers. `fn table` is the measure this test checks. + let src = std::fs::read_to_string( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../examples/21_maps.rce"), + ) + .unwrap(); + let ast = rce_spec_check::program(&src).unwrap(); + let maps = rce_spec_check::one::core_of(&ast).unwrap_or_else(|e| panic!("21_maps: {e}")); let sub = bridge::closure(&maps, "fn table").expect("fn table"); let f = bridge::construct(&sub).unwrap_or_else(|e| panic!("first construct: {}", e.line())); assert!( @@ -631,28 +669,30 @@ fn fn_table_constructs_and_the_schedule_is_refused_by_fg8() { form::Outcome::Applied(_) )); let (value, _) = core_eval(&sub, vec![]); - assert_eq!( - value, - Ok(Val::List(vec![ - Val::Tup(vec![Val::bytes(b"a"), Val::Int(1)]), - Val::Tup(vec![Val::bytes(b"b"), Val::Int(2)]), - ])), - "core eval of fn table is the value a later three-way check has to match" - ); + let want = Ok(Val::List(vec![ + Val::Tup(vec![Val::bytes(b"a"), Val::Int(1)]), + Val::Tup(vec![Val::bytes(b"b"), Val::Int(2)]), + ])); + assert_eq!(value, want, "core eval of fn table"); + // The search loop's break was restructured. Record that before the + // schedule is read back: that construct sees no source `break`. + let rewrote = bridge::body_break_rewrite(); let s = bridge::schedule(&f).unwrap_or_else(|e| panic!("schedule: {}", e.line())); wf::check(&s).unwrap_or_else(|e| panic!("schedule is not well formed: {e}")); - let e = bridge::construct(&s).expect_err("the scheduled measure was applied"); - assert_eq!(e.tag(), "FG8", "{}", e.line()); - assert_eq!(e.at, "node 3", "{}", e.line()); + let back = bridge::construct(&s).unwrap_or_else(|e| panic!("schedule construct: {}", e.line())); + assert_eq!( + fir::encode(&f), + fir::encode(&back), + "construct(schedule(F)) is not F" + ); assert!( - e.reason.contains( - "the body region does not return i raised by exactly one whenever it continues" - ), - "{}", - e.line() + rewrote, + "the search loop's break was not restructured, so the example would join the syntactic floor" ); - // A future applied schedule matches `f` byte for byte and matches `value`. - // It does not enter the syntactic floor while `body_break_rewrite` is set. + assert_scheduled_values(&sub, &s, vec![]); + let (k, i) = form_key(&f, 0); + let form_v = feval::apply(&f, &k, i, vec![]).unwrap_or_else(|e| panic!("form eval: {e}")); + assert_eq!(form_v, vec![want.expect("core")], "form eval of fn table"); } #[test] @@ -723,12 +763,10 @@ fn a_break_out_of_a_block_is_refused_and_the_continuation_runs() { } #[test] -fn a_break_that_names_the_loop_from_inside_a_block_is_refused() { +fn a_break_that_names_the_loop_from_inside_a_block_round_trips() { // Contract section 3.2. `break 1` inside the body block names the loop. - // On 410bfd40 the first form is that flag: it is applied, and it - // returns the core's value. The schedule is still refused by FG8. - // The node is 1, measured on this commit; the reason is unchanged. - // The increment does not run on the break path. + // The break arm stores a fresh false, so the first form and the + // schedule are that flag. The increment does not run on the break path. let build = |with_tick: bool| { let (tick, tkey) = tick_parts(); let key = tkey.clone(); @@ -783,7 +821,15 @@ fn a_break_that_names_the_loop_from_inside_a_block_is_refused() { assert_eq!(z, Ok(Val::Int(0)), "zero iterations"); assert_eq!(one, Ok(Val::Int(0)), "the break skipped the increment"); assert_eq!(many, Ok(Val::Int(4)), "four iterations step the index"); - schedule_fg8(&f, "node 1"); + schedule_matches( + &m, + &f, + &[ + vec![Val::Int(0), Val::Bool(true)], + vec![Val::Int(4), Val::Bool(true)], + vec![Val::Int(4), Val::Bool(false)], + ], + ); let m = build(true); let f = bridge::construct(&m).unwrap_or_else(|e| panic!("first construct: {}", e.line())); @@ -792,7 +838,15 @@ fn a_break_that_names_the_loop_from_inside_a_block_is_refused() { assert_values(&m, &f, vec![Val::Int(4), Val::Bool(true)]); assert_values(&m, &f, vec![Val::Int(4), Val::Bool(false)]); assert_values(&m, &f, vec![Val::Int(0), Val::Bool(false)]); - schedule_fg8(&f, "node 1"); + schedule_matches( + &m, + &f, + &[ + vec![Val::Int(4), Val::Bool(true)], + vec![Val::Int(4), Val::Bool(false)], + vec![Val::Int(0), Val::Bool(false)], + ], + ); let spent = |args: Vec| { let (_, g) = core_eval(&m, args); match g { @@ -809,11 +863,10 @@ fn a_break_that_names_the_loop_from_inside_a_block_is_refused() { } #[test] -fn a_flat_measure_with_a_body_break_is_refused_by_fg8() { - // Contract section 4.3 and shortcut 1's neighbour: the continue path does - // raise the index, and the first construction still fails FG8. `mset` - // shows the closed shape can accept that meaning. This statement order - // does not reach it. The refusal stays until it does. +fn a_flat_measure_with_a_body_break_round_trips() { + // The continue path raises the index. The break path stores a fresh + // false and does not. That is the closed shape, so the measure applies + // and the schedule reads it back. It is not rewritten into a count. let build = |with_tick: bool| { let (tick, tkey) = tick_parts(); let key = tkey.clone(); @@ -850,19 +903,9 @@ fn a_flat_measure_with_a_body_break_is_refused_by_fg8() { } }; let m = build(false); - let e = refuse(&m); - assert_eq!(e.tag(), "FG8", "{}", e.line()); - assert!( - e.reason - .contains("raised by exactly one whenever it continues"), - "{}", - e.line() - ); - assert_ne!( - e.tag(), - "bound", - "a body break was rewritten into a pure count" - ); + let f = bridge::construct(&m).unwrap_or_else(|e| panic!("first construct: {}", e.line())); + assert!(bridge::body_break_rewrite(), "the break was not a flag"); + assert_applied(&f); let (z, _) = core_eval(&m, vec![Val::Int(0), Val::Bool(false)]); let (stop, _) = core_eval(&m, vec![Val::Int(4), Val::Bool(true)]); let (one, _) = core_eval(&m, vec![Val::Int(1), Val::Bool(false)]); @@ -871,10 +914,37 @@ fn a_flat_measure_with_a_body_break_is_refused_by_fg8() { assert_eq!(stop, Ok(Val::Int(0))); assert_eq!(one, Ok(Val::Int(1))); assert_eq!(many, Ok(Val::Int(4))); + assert_values(&m, &f, vec![Val::Int(0), Val::Bool(false)]); + assert_values(&m, &f, vec![Val::Int(4), Val::Bool(true)]); + assert_values(&m, &f, vec![Val::Int(1), Val::Bool(false)]); + assert_values(&m, &f, vec![Val::Int(4), Val::Bool(false)]); + schedule_matches( + &m, + &f, + &[ + vec![Val::Int(0), Val::Bool(false)], + vec![Val::Int(4), Val::Bool(true)], + vec![Val::Int(1), Val::Bool(false)], + vec![Val::Int(4), Val::Bool(false)], + ], + ); let m = build(true); - let e = refuse(&m); - assert_eq!(e.tag(), "FG8", "{}", e.line()); + let f = bridge::construct(&m).unwrap_or_else(|e| panic!("ticked construct: {}", e.line())); + assert!(bridge::body_break_rewrite()); + assert_applied(&f); + assert_values(&m, &f, vec![Val::Int(4), Val::Bool(true)]); + assert_values(&m, &f, vec![Val::Int(4), Val::Bool(false)]); + schedule_matches( + &m, + &f, + &[ + vec![Val::Int(4), Val::Bool(true)], + vec![Val::Int(4), Val::Bool(false)], + vec![Val::Int(0), Val::Bool(false)], + vec![Val::Int(1), Val::Bool(false)], + ], + ); let spent = |args: Vec| { let (_, g) = core_eval(&m, args); match g { @@ -1490,8 +1560,9 @@ fn block_if_loop(depth: u32) -> CoreModule { fn block_if_loop_distinguishes_depth_from_residual() { // Source depth 0 names the block. The if is not a level. Depth 1 names // the loop. Depth 2 names nothing: the core rejects it before it runs. - // On 410bfd40 depth 0 and depth 1 construct. The form and the scheduled - // core return the core's value. Depth 1's schedule is still FG8. + // Depth 0 and depth 1 construct. The form and the scheduled core return + // the core's value. Depth 1's break arm stores a fresh false, so the + // schedule is that same measure. let args = vec![Val::Int(1), Val::Bool(true), Val::Bool(true)]; let fall_args = vec![Val::Int(1), Val::Bool(true), Val::Bool(false)]; let depth0 = block_if_loop(0); @@ -1527,7 +1598,9 @@ fn block_if_loop_distinguishes_depth_from_residual() { ); assert_applied(&f); assert_values(&depth1, &f, args.clone()); - schedule_fg8(&f, "node 1"); + // The schedule constructs and returns the core's value. The epilogue + // after the loop does not come back as the same nodes. + let _same = schedule_agrees(&depth1, &f, &[args.clone()]); let (leave, _) = core_eval(&depth1, args); // Only after_loop. The if did not consume a level. steps stayed 0. assert_eq!(leave, Ok(Val::Int(8))); diff --git a/spec/checker/tests/form_bridge.rs b/spec/checker/tests/form_bridge.rs index 000db236..4659dd1f 100644 --- a/spec/checker/tests/form_bridge.rs +++ b/spec/checker/tests/form_bridge.rs @@ -1253,7 +1253,7 @@ fn whole_census( "limit of the run, not a field of the module, so that frame is not a".to_string(), "node. A read of `fuel` outside the frame stays refused. Constant".to_string(), "flags are memo cells, not folded constants, and those reads stay".to_string(), - "refused. `out` is in no whole-module set. The exact set global is 2.".to_string(), + "refused. `out` is in no whole-module set. The exact set global is 3.".to_string(), "whole stays 2.".to_string(), String::new(), format!("programs\t{programs}"), @@ -2098,12 +2098,30 @@ fn bare_tuple_singleton_unpacks_to_the_pair() { } #[test] -fn list_and_array_singletons_have_no_dummy() { +fn list_singleton_starts_empty_and_array_has_no_dummy() { + // The initial list is `list.new`. Both arms that run drop it and store + // the real sum. An array still has no dummy in this slice. let list = Ty::List(Box::new(i64ty())); - match bridge::catch_boundary_for(bridge::CatchPack::Singleton, &list, 0) { - Err(err) => assert!(err.contains("list"), "{err}"), - Ok(_) => panic!("a list singleton was given a dummy"), + let b = bridge::catch_boundary_for(bridge::CatchPack::Singleton, &list, 0) + .unwrap_or_else(|e| panic!("list singleton: {e}")); + fn walk(stmts: &[Stmt], news: &mut usize, sets: &mut usize, wrapped: u32) { + for s in stmts { + match s { + Stmt::Prim(p, _, _) if p == "list.new" => *news += 1, + Stmt::Set(Place::V(v), _) if *v == wrapped => *sets += 1, + Stmt::If(_, t, e) => { + walk(t, news, sets, wrapped); + walk(e, news, sets, wrapped); + } + Stmt::Block(x) | Stmt::Loop(x) => walk(x, news, sets, wrapped), + _ => {} + } + } } + let (mut news, mut sets) = (0, 0); + walk(&b.stmts, &mut news, &mut sets, b.wrapped); + assert_eq!(news, 1, "the boundary builds one empty list: {:?}", b.stmts); + assert!(sets >= 2, "both arms that run replace the initial sum: {:?}", b.stmts); let arr = Ty::Arr(Box::new(i64ty())); match bridge::catch_boundary_for(bridge::CatchPack::Singleton, &arr, 0) { Err(err) => assert!(err.contains("array"), "{err}"), @@ -2111,6 +2129,21 @@ fn list_and_array_singletons_have_no_dummy() { } } +#[test] +fn list_singleton_catch_round_trips() { + let list = Ty::List(Box::new(i64ty())); + let callee = callee_fn(list.clone(), vec![ + Stmt::Prim("list.new".into(), vec![i64ty()], vec![]), + Stmt::Prim("list.push".into(), vec![i64ty()], vec![Atom::V(0), i64_lit(9)]), + Stmt::Ret(Atom::V(1)), + ]); + let (original, form_v, core_v) = round_trip_catch(callee); + let want = Val::Sum(0, Box::new(Val::Tup(vec![Val::List(vec![Val::Int(9)])]))); + assert_eq!(original.as_ref().unwrap(), &want, "{original:?}"); + assert_eq!(form_v.as_ref().unwrap(), &want, "{form_v:?}"); + assert_eq!(core_v.as_ref().unwrap(), &want, "{core_v:?}"); +} + fn i64b() -> fir::BTy { fir::BTy::Int(-(1i128 << 63), (1i128 << 63) - 1) } diff --git a/spec/checker/tests/form_bridge_census.txt b/spec/checker/tests/form_bridge_census.txt index f8bf71bb..006b7c90 100644 --- a/spec/checker/tests/form_bridge_census.txt +++ b/spec/checker/tests/form_bridge_census.txt @@ -29,7 +29,7 @@ is `emit[text]`. The observation driver's `fuel.limit` read is the limit of the run, not a field of the module, so that frame is not a node. A read of `fuel` outside the frame stays refused. Constant flags are memo cells, not folded constants, and those reads stay -refused. `out` is in no whole-module set. The exact set global is 2. +refused. `out` is in no whole-module set. The exact set global is 3. whole stays 2. programs 60 @@ -41,52 +41,47 @@ whole-with-user 1 whole modules, top 10 by modules unblocked (one tag, or a pair) unblocks set -14 break -14 round-trip -9 lowering -3 break,exit +15 break +15 round-trip +8 lowering +5 break,exit +3 global 2 defect -2 global -1 FG8 +2 exit 1 bound,break -1 break,catch 1 break,defect +1 exit,global whole modules, every exact set modules set -14 break -14 round-trip -9 lowering -3 break,exit -2 break,catch,exit +15 break +15 round-trip +8 lowering +5 break,exit +3 global 2 clear 2 defect 2 defect,exit,loop -2 global -1 FG8 +2 exit 1 bound,break -1 break,catch -1 break,catch,exit,loop 1 break,defect 1 break,defect,exit -1 catch,global -1 exit +1 break,exit,loop 1 exit,global 1 global,loop program roots, every exact set modules set 17 break -16 round-trip -9 lowering +17 round-trip +8 lowering 5 clear 2 defect +2 defect,round-trip 2 exit 2 no-root -1 FG8,defect 1 break,defect 1 break,round-trip -1 defect,round-trip 1 global 1 global,loop 1 loop @@ -102,18 +97,18 @@ module whole roots user global-sites 07_error_union.rce defect,exit,loop defect user 08_traits.rce round-trip round-trip user 09_generics.rce clear no-root entry-only -10_comptime.rce catch,global round-trip user entry: global: g6 is not part of the working context ω holds +10_comptime.rce global round-trip user entry: global: g6 is not part of the working context ω holds 11_arena.rce round-trip round-trip user 12_borrow.rce round-trip clear user 13_spawn_chan.rce lowering lowering lowering not covered by the lowering: the type chan i64 14_select.rce lowering lowering lowering not covered by the lowering: the type chan text 15_actor.rce lowering lowering lowering not covered by the lowering: the type chan i64 -16_multi_region.rce break,catch,exit break user +16_multi_region.rce break,exit break user 17_traffic_light.rce break break user 18_while_bound.rce round-trip round-trip user 19_floats.rce break round-trip user 20_strings.rce defect,exit,loop defect user -21_maps.rce lowering lowering lowering not covered by the lowering: an integer operation checked against ranges that differ at run time (["lit", "u32"]) +21_maps.rce exit round-trip user 22_tuples.rce defect defect,round-trip user 23_patterns.rce break break user 24_lambda.rce round-trip round-trip user @@ -124,7 +119,7 @@ module whole roots user global-sites 30_state_machine_guarded.rce break break user 31_inventory.rce break,exit exit user 32_comptime_block.rce global global user fn table_size: global: g3 is not part of the working context ω holds -33_in_operator.rce defect FG8,defect user +33_in_operator.rce defect defect,round-trip user 34_chan_types.rce lowering lowering lowering not covered by the lowering: the type chan (u64, text) 35_nested_if.rce clear clear user 36_multiline_brackets.rce round-trip round-trip user @@ -134,7 +129,7 @@ module whole roots user global-sites 40_extern.rce round-trip clear user 41_arena_bound_wrapping.rce round-trip round-trip user 42_f32.rce bound,break clear user -43_simd_lanes.rce FG8 round-trip user +43_simd_lanes.rce round-trip round-trip user 44_device_region.rce break break user 45_byte_text.rce exit,global round-trip user check 7: global: g3 is not part of the working context ω holds 46_u64.rce global round-trip user check 10: global: g3 is not part of the working context ω holds | check 14: global: g3 is not part of the working context ω holds | check 7: global: g3 is not part of the working context ω holds | check 8: global: g3 is not part of the working context ω holds | check 9: global: g3 is not part of the working context ω holds @@ -146,10 +141,10 @@ module whole roots user global-sites 52_context_text.rce break,exit break user 53_capability.rce break break user 54_secret.rce break,exit break user -55_rcedb.rce break,catch,exit,loop loop user -56_utf8.rce break,catch,exit break,round-trip user +55_rcedb.rce break,exit,loop loop user +56_utf8.rce break,exit break,round-trip user 57_float_vectors.rce break break user -58_float_keys.rce break,catch break user +58_float_keys.rce break break user 59_dim_redundant_field.rce break break user 60_dim_hidden_period.rce break break user 61_dim_minimal.rce break break user diff --git a/spec/checker/tests/one_lower.rs b/spec/checker/tests/one_lower.rs index 3c5c056a..5f499d93 100644 --- a/spec/checker/tests/one_lower.rs +++ b/spec/checker/tests/one_lower.rs @@ -19,7 +19,7 @@ const COVERED: &[&str] = &[ "01_counter", "02_hello_main", "03_fib_loop", "04_bank_account", "05_kind_match", "06_option", "07_error_union", "08_traits", "09_generics", "10_comptime", "11_arena", "12_borrow", "16_multi_region", "17_traffic_light", "18_while_bound", "19_floats", "20_strings", - "22_tuples", "23_patterns", "24_lambda", "25_labels", "27_bitops", "28_slices", + "21_maps", "22_tuples", "23_patterns", "24_lambda", "25_labels", "27_bitops", "28_slices", "30_state_machine_guarded", "31_inventory", "32_comptime_block", "33_in_operator", "35_nested_if", "36_multiline_brackets", "38_hex_bin", "40_extern", "41_arena_bound_wrapping", "42_f32", "43_simd_lanes", "44_device_region", "45_byte_text", "46_u64", "48_linear_handle", @@ -34,7 +34,6 @@ const NOT_COVERED: &[(&str, &str)] = &[ ("13_spawn_chan", "the type chan i64"), ("14_select", "the type chan text"), ("15_actor", "the type chan i64"), - ("21_maps", "an integer operation checked against ranges that differ at run time"), ("29_nested_kind", "a recursive type"), ("34_chan_types", "the type chan (u64, text)"), ("37_actor_spawn", "the type chan u64"), @@ -48,7 +47,7 @@ const NOT_COVERED: &[(&str, &str)] = &[ const COVERED_WITH_PROBES: &[&str] = &[ "01_counter", "02_hello_main", "03_fib_loop", "04_bank_account", "05_kind_match", "06_option", "07_error_union", "08_traits", "09_generics", "10_comptime", "11_arena", "12_borrow", - "16_multi_region", "17_traffic_light", "18_while_bound", "19_floats", "20_strings", "22_tuples", + "16_multi_region", "17_traffic_light", "18_while_bound", "19_floats", "20_strings", "21_maps", "22_tuples", "23_patterns", "24_lambda", "25_labels", "27_bitops", "28_slices", "30_state_machine_guarded", "31_inventory", "32_comptime_block", "33_in_operator", "35_nested_if", "36_multiline_brackets", "38_hex_bin", "40_extern", "41_arena_bound_wrapping", "42_f32", "43_simd_lanes", diff --git a/spec/checker/tests/typed_tree.rs b/spec/checker/tests/typed_tree.rs index 282e6d4c..b753eede 100644 --- a/spec/checker/tests/typed_tree.rs +++ b/spec/checker/tests/typed_tree.rs @@ -100,3 +100,19 @@ fn types_follow_assignments_and_loops() { assert!(i.ty.show().starts_with("int{u32}"), "{}", i.ty.show()); assert!(!zs.is_empty()); } + +/// `(m.get(w) catch 0) + 1` with `m: Map[text, u32]`. The handler literal +/// takes the success type, so the sum is checked against u32. +#[test] +fn a_catch_literal_takes_the_success_integer_type() { + use rce_spec_check::typed; + let src = "fn freq(words: &[text]) -> Map[text, u32]\n var m: Map[text, u32] = {}\n for w in words\n m[w] = (m.get(w) catch 0) + 1\n return m\n"; + let m = module(src); + let t = typed::build(&m); + let rce_spec_check::ast::Item::Fn(f) = &m.items[0] else { panic!() }; + let rce_spec_check::ast::Body::Block(b) = &f.body else { panic!() }; + let rce_spec_check::ast::Stmt::For(_, _, body, _) = &b[1] else { panic!() }; + let rce_spec_check::ast::Stmt::Assign(_, _, e) = &body[0] else { panic!() }; + let shown = t.ty(e).show(); + assert!(shown.starts_with("int{u32}"), "{shown}"); +}