Lines
98.85 %
Functions
100 %
Branches
//! Nested BLOCK joins (0014 slice 4.3b): a discarded pass hands each nested
//! block its join, so every block compiles at most twice however deep.
use super::compile_block_for_stack;
use crate::ast::{Expr, WasmType};
use crate::compiler::CompileMode;
use crate::compiler::behaviour_oracle::{Outcome, observe};
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::compile_for_stack;
use crate::compiler::observations::{Leaf, ObservedBlock, StructuralType};
use crate::compiler::stats::CompileStats;
use crate::error::Result;
use crate::host_fn::HostFnSpec;
use crate::reader::Reader;
use crate::runtime::SymbolTable;
const TEST: &str = "(> (rpc-protocol-version) 0)";
fn hosts() -> [HostFnSpec; 1] {
[
HostFnSpec::new("rpc-protocol-version", "nomi", "rpc_protocol_version")
.returns(WasmType::I32),
]
}
fn run(source: &str) -> (Vec<Outcome>, (u64, u64)) {
let (behaviours, stats) = observe(source, CompileMode::Eval, &hosts());
let outcomes = behaviours.into_iter().map(|b| b.outcome).collect();
(outcomes, passes(stats))
fn passes(stats: CompileStats) -> (u64, u64) {
(stats.block_passes_max, stats.block_passes_total)
/// The value in the empty-batch world, where every exit is taken, and in the
/// ledger world, where none is.
fn values(outcomes: &[Outcome]) -> Vec<&str> {
outcomes
.iter()
.map(|outcome| match outcome {
Outcome::Value(v) => v.as_str(),
_ => "not a value",
})
.collect()
const HALF: &str = "Some(Ratio) [Struct(2), I64(1), I64(2)]";
const ONE: &str = "Some(Ratio) [Struct(2), I64(1), I64(1)]";
/// `depth` blocks, each with a literal `1` exit, around a `1/2` tail.
fn nest(depth: usize) -> String {
(1..=depth).rev().fold("1/2".to_string(), |inner, level| {
format!("(block b{level} (if {TEST} (return-from b{level} 1)) {inner})")
#[test]
fn nested_blocks_whose_arms_disagree_compile_twice_each() {
let (outcomes, passes) = run(&nest(2));
assert_eq!(values(&outcomes), [ONE, HALF]);
assert_eq!(passes, (2, 4));
fn a_deep_nest_takes_two_passes_per_block() {
let (outcomes, passes) = run(&nest(12));
assert_eq!(passes, (2, 24));
fn a_settled_block_is_recompiled_for_an_unsettled_nested_one() {
let (outcomes, passes) = run(&format!(
"(block a (block b (if {TEST} (return-from b 1)) 1/2))"
));
fn nested_blocks_whose_arms_agree_take_one_pass_each() {
"(block a (block b (if {TEST} (return-from b 1)) 2))"
assert_eq!(
values(&outcomes),
"Some(I32) [Struct(2), I64(1), I64(1)]",
"Some(I32) [Struct(2), I64(2), I64(1)]"
);
assert_eq!(passes, (1, 2));
fn a_literal_exit_that_is_a_block_takes_its_join_in_the_second_pass() {
"(block a (if {TEST} (return-from a 1/2)) (block c 1))"
assert_eq!(values(&outcomes), [HALF, ONE]);
fn ratio_join(name: &str, body_len: usize) -> ObservedBlock {
join(name, body_len, Leaf::Ratio)
fn join(name: &str, body_len: usize, result: Leaf) -> ObservedBlock {
ObservedBlock {
name: name.to_string(),
body_len,
join: StructuralType {
arrows: vec![],
result,
},
/// Compiles each source BLOCK in turn while `expected` is the observed list,
/// returning each result type and the passes each took.
fn compile_expecting(
expected: Vec<ObservedBlock>,
sources: &[String],
) -> Result<Vec<(WasmType, u64)>> {
let mut ctx = CompileContext::new_with_host_fns(&hosts())?;
let mut symbols = SymbolTable::with_builtins_for_wasm();
symbols.register_host_fns(&hosts());
let mut emit = FunctionEmitter::new();
ctx.expecting_block_joins(expected, |ctx| {
sources
.map(|source| {
let before = ctx.compile_stats().block_passes_total;
let ty =
compile_block_for_stack(ctx, &mut emit, &mut symbols, &block_args(source))?;
Ok((ty, ctx.compile_stats().block_passes_total - before))
fn block_args(source: &str) -> Vec<Expr> {
match Reader::parse(source).map(|program| program.exprs.into_iter().next()) {
Ok(Some(Expr::List(elems))) => elems.into_iter().skip(1).collect(),
other => panic!("a BLOCK form: {other:?}"),
fn unsettled(name: &str) -> String {
format!("(block {name} (if {TEST} (return-from {name} 1)) 1/2)")
fn an_expected_join_lets_its_block_compile_once() {
let compiled = compile_expecting(vec![ratio_join("B", 2)], &[unsettled("b")]);
assert_eq!(compiled.expect("compile"), vec![(WasmType::Ratio, 1)]);
fn a_key_mismatch_falls_back_to_two_passes_and_keeps_the_join_for_its_block() {
let compiled = compile_expecting(vec![ratio_join("C", 2)], &[unsettled("b"), unsettled("c")]);
compiled.expect("compile"),
vec![(WasmType::Ratio, 2), (WasmType::Ratio, 1)]
fn a_body_length_mismatch_falls_back_to_two_passes() {
let compiled = compile_expecting(vec![ratio_join("B", 3)], &[unsettled("b")]);
assert_eq!(compiled.expect("compile"), vec![(WasmType::Ratio, 2)]);
fn a_stale_join_is_discarded_and_the_block_recompiles_at_its_own() {
let compiled = compile_expecting(vec![join("B", 2, Leaf::I32)], &[unsettled("b")]);
fn a_fallback_second_pass_expects_its_own_joins_and_then_the_outer_ones_resume() {
let two_nested = format!(
"(block y (if {TEST} (return-from y 1)) {} {})",
unsettled("z1"),
unsettled("z2")
let compiled = compile_expecting(
vec![ratio_join("X", 2), ratio_join("W", 2)],
&[unsettled("x"), two_nested, unsettled("w")],
vec![
(WasmType::Ratio, 1),
(WasmType::Ratio, 6),
(WasmType::Ratio, 1)
/// Every arm an integer literal, so the block is an index.
const INDEX_VICTIM: &str = "(block b (if (> (rpc-protocol-version) 0) (return-from b 3)) 1)";
fn a_stale_ratio_join_does_not_settle_an_index_block() {
let compiled = compile_expecting(vec![ratio_join("B", 2)], &[INDEX_VICTIM.to_string()]);
assert_eq!(compiled.expect("compile"), vec![(WasmType::I32, 2)]);
/// Compiles `source`, one form, while `expected` is the observed list.
fn compile_form_expecting(expected: Vec<ObservedBlock>, source: &str) -> Result<WasmType> {
let form = Reader::parse(source)?
.exprs
.into_iter()
.next()
.expect("one form");
compile_for_stack(ctx, &mut emit, &mut symbols, &form)
fn a_stale_ratio_join_leaves_an_enclosing_division_an_index_division() {
let division = format!("(let ((v {INDEX_VICTIM})) (/ v 3))");
let ty = compile_form_expecting(vec![ratio_join("B", 2)], &division);
assert_eq!(ty.expect("compile"), WasmType::I32);
fn a_stale_index_join_beside_a_fraction_is_a_mix() {
let sum = format!("(+ 1/2 {INDEX_VICTIM})");
let err = compile_form_expecting(vec![join("B", 2, Leaf::I32)], &sum).expect_err("a mix");
assert!(
err.to_string()
.contains("+ cannot mix an index (count) with a scalar"),
"{err}"
fn a_failed_block_closes_its_probe() {
let failing = format!(
"(block a (block c {} (+ 1/2 (rpc-protocol-version))))",
unsettled("b")
let mut ctx = CompileContext::new_with_host_fns(&hosts()).expect("context");
let compiled =
compile_block_for_stack(&mut ctx, &mut emit, &mut symbols, &block_args(&failing));
assert!(compiled.is_err_and(|err| err.to_string().contains("scalar")));
assert!(!ctx.open_block_probe().is_open());