Lines
100 %
Functions
Branches
//! The fixpoint against the observable behaviour of the programs it emits.
use crate::compiler::CompileMode;
use crate::compiler::behaviour_oracle::{Outcome, observe};
use crate::{HostFnSpec, WasmType};
fn outcomes(source: &str) -> Vec<Outcome> {
observe(source, CompileMode::Script, &[])
.0
.into_iter()
.map(|behaviour| behaviour.outcome)
.collect()
}
/// The ratio `numer/denom`, in both worlds.
fn ratio(numer: i64, denom: i64) -> Vec<Outcome> {
let text = format!("Number(Scalar(Ratio {{ numer: {numer}, denom: {denom} }}))");
vec![Outcome::Value(text); 2]
fn index(n: i64) -> Vec<Outcome> {
vec![Outcome::Value(format!("Number(Index({n}))")); 2]
/// The first pass guesses `i32` and observes a closure whose signature it
/// interned itself; the second pass must re-intern that signature rather
/// than reuse an id the rollback dropped.
#[test]
fn a_closure_return_type_survives_the_pass_rollback() {
let source = "(let* ((idx (entity-count)))
(defun f (n) (let ((g (lambda (y) (* y 1/1)))) (when (> n 0) (f (- n 1))) g))
(let ((h (f idx))) (funcall h 1/2)))";
assert_eq!(outcomes(source), ratio(1, 2));
/// A helper queued while the body compiles must not take the body's
/// code-section slot.
fn a_lambda_inside_the_body_keeps_its_own_code_slot() {
(defun f (n) (let ((g (lambda (y) (* y 2/1)))) (when (> n 0) (f (- n 1))) (funcall g 1/2)))
(f idx))";
assert_eq!(outcomes(source), ratio(1, 1));
/// `ev` runs inside `od`'s pass, so its body is queued first; each must
/// still land in its own code slot. The worlds answer 1 and 0, so `ev` sees
/// 4 and 3.
fn mutually_recursive_monomorphs_keep_their_own_code_slots() {
let hosts = [
HostFnSpec::new("rpc-protocol-version", "nomi", "rpc_protocol_version")
.returns(WasmType::I32),
];
let source = "(defun ev (k) (if (= k 0) t (od (- k 1))))
(defun od (k) (if (= k 0) nil (ev (- k 1))))
(ev (+ (rpc-protocol-version) 3))";
let outcomes: Vec<Outcome> = observe(source, CompileMode::Eval, &hosts)
.collect();
let answer = |truth: &str| Outcome::Value(format!("Some(AnyRef) [{truth}]"));
assert_eq!(outcomes, vec![answer("T"), answer("Null")]);
/// The helper is a separate wasm function: it takes the cell that backs the
/// assigned global as a parameter, so it reads what the unit stored last.
fn a_helper_reads_the_cell_of_an_assigned_global() {
let source = "(defparameter *k* 2)
(defun f (n) (if (= n 0) 1 (* *k* (f (- n 1)))))
(setf *k* 3)
(f (+ (rpc-protocol-version) 2))";
let outcomes: Vec<Outcome> = observe(source, CompileMode::Script, &hosts)
let value = |n: i64| Outcome::Value(format!("Number(Index({n}))"));
assert_eq!(outcomes, vec![value(27), value(9)]);
/// `ev` and `od` each wrap the call to the other in `depth` blocks that
/// disagree with their tail, so every block is unsettled in the first pass.
fn mutual_recursion_around_a_nest(depth: usize) -> String {
let nest = |callee: &str| {
(1..=depth)
.rev()
.fold(format!("({callee} (- k 1))"), |inner, level| {
format!(
"(block b{level} (if (> (rpc-protocol-version) 0) (return-from b{level} 1)) {inner})"
)
})
};
"(defun ev (k) (if (= k 0) 1/2 {})) (defun od (k) (if (= k 0) 1/2 {})) (ev (+ (rpc-protocol-version) 3))",
nest("od"),
nest("ev")
fn block_passes(depth: usize) -> (Vec<Outcome>, u64) {
let (behaviours, stats) = observe(
&mutual_recursion_around_a_nest(depth),
CompileMode::Eval,
&hosts,
);
let outcomes = behaviours.into_iter().map(|b| b.outcome).collect();
(outcomes, stats.block_passes_total)
/// A function body is compiled apart from the blocks around its call, and a
/// discarded pass hands its blocks' joins to the next, so a deeper nest costs
/// proportionally more block passes, not quadratically more.
fn block_passes_around_mutual_recursion_grow_linearly() {
let (shallow_outcomes, shallow) = block_passes(4);
let (deep_outcomes, deep) = block_passes(6);
let answers = vec![
Outcome::Value("Some(AnyRef) [I31(1)]".to_string()),
Outcome::Value("Some(AnyRef) [Struct(2), I64(1), I64(2)]".to_string()),
assert_eq!(
(shallow_outcomes, deep_outcomes),
(answers.clone(), answers)
assert_eq!((shallow, deep), (88, 132));
/// A nest deeper than the shared recursion ceiling is a structured resource
/// error in both worlds, never a native stack overflow.
fn a_deep_block_nest_around_mutual_recursion_ends_in_a_resource_error() {
for depth in [16, 20, 40] {
let (outcomes, _) = block_passes(depth);
assert_eq!(outcomes.len(), 2, "depth {depth}");
for outcome in outcomes {
assert!(
matches!(&outcome, Outcome::CompileError(message) if message.contains("shared budget")),
"depth {depth}: {outcome:?}"
/// The resource error is reached with the stack to spare: half the default
/// test thread's.
fn a_deep_block_nest_ends_in_a_resource_error_on_a_one_mib_stack() {
let handle = std::thread::Builder::new()
.stack_size(1024 * 1024)
.spawn(|| [16, 20, 40].map(|depth| block_passes(depth).0).concat())
.expect("spawn bounded-stack thread");
let outcomes = handle.join().expect("must not overflow the stack");
assert_eq!(outcomes.len(), 6);
"{outcome:?}"
fn helper_names_differ_by_slot_type_and_pair_element() {
use super::next_monomorph_helper_name;
use crate::ast::PairElement;
use crate::compiler::context::monomorph::{MonomorphKey, Slot};
let key = |ty| MonomorphKey {
name: "f".to_string(),
definition: 1,
epoch: 0,
params: vec![WasmType::I32],
closures: vec![None],
slots: vec![Slot {
name: "x".to_string(),
ty,
cell: false,
}],
let name = |ty| next_monomorph_helper_name(&key(ty), &[WasmType::I32]);
assert_ne!(name(WasmType::I32), name(WasmType::Ratio));
assert_ne!(
name(WasmType::PairRef(PairElement::I32)),
name(WasmType::PairRef(PairElement::Ratio))
const WALK: &str = "(defun walk (f n) (if (= n 0) 0 (+ (funcall f n) (walk f (- n 1)))))";
const WALK_SCALAR: &str =
"(defun walk (f n) (if (= n 0/1) 0/1 (+ (funcall f n) (walk f (- n 1/1)))))";
fn a_recursive_defun_passes_its_lambda_parameter_on() {
let source =
format!("{WALK_SCALAR} (walk (lambda (k) k) (index->scalar (+ 3 (entity-count))))");
assert_eq!(outcomes(&source).first(), ratio(6, 1).first());
fn two_lambdas_of_one_signature_get_their_own_helpers() {
let source = format!(
"{WALK_SCALAR} (let ((n (index->scalar (+ 2 (entity-count))))) \
(+ (walk (lambda (k) k) n) (walk (lambda (k) (* k 2/1)) n)))"
assert_eq!(outcomes(&source).first(), ratio(9, 1).first());
fn a_defun_calls_its_lambda_parameter() {
let source = "(defun app (f v) (funcall f v)) (app (lambda (x) (+ x 1)) 4)";
assert_eq!(outcomes(source), index(5));
fn an_index_count_into_a_lambda_parameter_compiles_the_lambda_for_it() {
let source = format!("{WALK} (walk (lambda (k) k) (+ 3 (entity-count)))");
assert_eq!(outcomes(&source).first(), index(6).first());
fn a_function_in_head_position_wins_over_a_closure_parameter() {
let source = "(defun f (x) 100) (defun app (f v) (f v)) (app (lambda (x) (+ x 1)) 4)";
assert_eq!(outcomes(source), index(100));
fn a_function_argument_the_body_never_uses_is_not_compiled() {
outcomes("(defun k (f v) v) (k (lambda (x) (car x)) 4)"),
index(4)
fn funcall_reaches_a_closure_variable_named_like_a_function() {
let source = "(defun f (x) 100) (let ((f (lambda (x) (+ x 1)))) (funcall f 4))";
fn an_intermediate_binding_keeps_the_function_head() {
let source = "(defun f (x) 100) (defun app (f v) (f v)) (let ((f 3)) (app (lambda (x) 2) 4))";
fn a_macro_expanding_to_funcall_of_the_parameter_lifts_it() {
let source = "(defmacro call-it (v) (list 'funcall 'f v)) \
(defun app (f v) (call-it v)) (app (lambda (x) (+ x 1)) 4)";