Lines
98.73 %
Functions
97.3 %
Branches
100 %
use crate::ast::Expr;
use crate::compiler::CompileMode;
use crate::compiler::behaviour_oracle::{Outcome, observe_program};
use crate::reader::Reader;
use crate::runtime::SymbolTable;
use scripting_format::MAX_WIRE_LIST_DEPTH;
fn unlock(expr: Expr) -> Expr {
match expr {
Expr::Symbol(name) => Expr::Symbol(match name.as_str() {
"S-NEW" => "(STRUCT-NEW)".to_string(),
"S-P" => "(STRUCT-P)".to_string(),
"S-REF" => "(STRUCT-REF)".to_string(),
"S-SET" => "(STRUCT-SET)".to_string(),
"S-COPY" => "(STRUCT-COPY)".to_string(),
_ => name,
}),
Expr::List(items) => Expr::List(items.into_iter().map(unlock).collect()),
other => other,
}
/// Runs `source` in the empty-batch world with `PT` (field X) as layout `{pt}`
/// and `BOX` (field P) as layout `{box}`.
pub(super) fn run(source: &str) -> Outcome {
run_in(CompileMode::Eval, source)
pub(super) fn run_in(mode: CompileMode, source: &str) -> Outcome {
let mut symbols = SymbolTable::with_builtins_for_wasm();
let pt = symbols
.define_struct("PT", vec!["X".to_string()])
.expect("PT defines");
let boxed = symbols
.define_struct("BOX", vec!["P".to_string()])
.expect("BOX defines");
let source = source
.replace("{pt}", &pt.0.to_string())
.replace("{box}", &boxed.0.to_string());
let program = Reader::parse(&source)
.map(|mut program| {
program.exprs = program.exprs.into_iter().map(unlock).collect();
program
})
.map_err(|err| err.to_string());
let behaviours = observe_program(program, &mut symbols, mode, &[]).0;
behaviours[0].outcome.clone()
pub(super) fn value(outcome: Outcome) -> String {
match outcome {
Outcome::Value(text) => text,
other => panic!("expected a value, got {other:?}"),
#[test]
fn a_predicate_on_a_typed_non_struct_guards_a_dead_branch() {
assert_eq!(
value(run(&format!(
"(let ((n (length (list {NEW_PT})))) (if (s-p n {{pt}}) (s-ref n {{pt}} 0) n))"
))),
"Some(I32) [Struct(2), I64(1), I64(1)]"
);
const NEW_PT: &str = "(s-new {pt} 1)";
fn a_stored_field_reads_back() {
value(run("(let ((p (s-new {pt} 1))) (s-ref p {pt} 0))")),
fn every_value_kind_rides_a_slot() {
for (stored, shown) in [
("\"a\"", "Some(StringRef) [Array(1), I32(97)]"),
("nil", "Some(Bool) [Null]"),
("t", "Some(Bool) [T]"),
] {
let source = format!("(s-ref (s-new {{pt}} {stored}) {{pt}} 0)");
assert_eq!(value(run(&source)), shown, "{stored}");
fn the_setter_stores_and_returns_the_value() {
"(let ((p {NEW_PT})) (list (s-set p {{pt}} 0 7) (s-ref p {{pt}} 0)))"
"Some(PairRef(I32)) [Struct(2), I31(7), Struct(2), I31(7), Null]"
fn an_alias_sees_the_write() {
"(let* ((p {NEW_PT}) (q p)) (s-set q {{pt}} 0 5) (s-ref p {{pt}} 0))"
"Some(I32) [Struct(2), I64(5), I64(1)]"
fn a_copy_is_a_distinct_instance() {
"(let* ((p {NEW_PT}) (c (s-copy p {{pt}}))) (s-set c {{pt}} 0 2) \
(list (s-ref p {{pt}} 0) (s-ref c {{pt}} 0) (eq p c)))"
"Some(PairRef(AnyRef)) [Struct(2), I31(1), Struct(2), I31(2), Struct(2), Null, Null]"
fn eq_eql_and_equal_are_identity() {
"(let ((p {NEW_PT})) (list (eq p p) (eql p p) (eq p {NEW_PT}) (equal p {NEW_PT})))"
"Some(PairRef(Bool)) [Struct(2), T, Struct(2), T, Struct(2), Null, Struct(2), Null, Null]"
fn identity_holds_through_an_anyref() {
"(let ((p {NEW_PT})) (list (eq p (car (list p 1))) (eq (car (list p 1)) {NEW_PT})))"
"Some(PairRef(Bool)) [Struct(2), T, Struct(2), Null, Null]"
fn the_predicate_tells_layouts_and_other_values_apart() {
"(let ((p {NEW_PT})) (list (s-p p {{pt}}) (s-p p {{box}}) (s-p 5 {{pt}}) \
(s-p (car (list p 1)) {{pt}}) (s-p (car (list p 1)) {{box}}) (s-p (car (list nil p)) {{pt}})))"
"Some(PairRef(Bool)) [Struct(2), T, Struct(2), Null, Struct(2), Null, Struct(2), T, \
Struct(2), Null, Struct(2), Null, Null]"
fn an_instance_rides_a_list_and_comes_back_typed() {
"(let ((l (list {NEW_PT}))) (s-set (car l) {{pt}} 0 4) (s-ref (car l) {{pt}} 0))"
"Some(I32) [Struct(2), I64(4), I64(1)]"
fn an_anyref_holding_the_layout_reads_dynamically() {
"(let ((a (car (list {NEW_PT} 1)))) (s-set a {{pt}} 0 3) (s-ref a {{pt}} 0))"
"Some(I32) [Struct(2), I64(3), I64(1)]"
pub(super) fn failure(outcome: Outcome) -> String {
Outcome::RuntimeError(text) | Outcome::CompileError(text) => text,
other => panic!("expected a failure, got {other:?}"),
fn a_wrong_runtime_operand_is_a_catchable_type_error() {
for (operand, accessor, caught_as) in [
(
"(car (list 1 (s-new {box} 1)))",
"PT-X",
"Some(AnyRef) [I31(9)]",
),
"(car (list (s-new {box} 1) 1))",
"(car (list nil (s-new {pt} 1)))",
"Some(I32) [Struct(2), I64(9), I64(1)]",
let read = format!("(s-ref {operand} {{pt}} 0)");
assert!(
failure(run(&read)).contains(&format!("{accessor}: expected a PT")),
"{read}"
let caught = format!("(handler-case {read} (type-error (e) 9))");
assert_eq!(value(run(&caught)), caught_as, "{caught}");
fn the_setter_and_copier_name_themselves_in_the_error() {
let set = "(s-set (car (list 1 (s-new {pt} 1))) {pt} 0 2)";
assert!(failure(run(set)).contains("(SETF PT-X): expected a PT"));
let copy = "(s-copy (car (list 1 (s-new {pt} 1))) {pt})";
assert!(failure(run(copy)).contains("COPY-PT: expected a PT"));
fn the_value_is_evaluated_before_the_setter_checks_its_operand() {
let source = "(defvar g 0) \
(handler-case (s-set (car (list 1 (s-new {pt} 1))) {pt} 0 (setf g 5)) \
(type-error (e) g))";
assert_eq!(value(run(source)), "Some(I32) [Struct(2), I64(5), I64(1)]");
fn a_statically_wrong_operand_is_a_compile_error() {
for (source, message) in [
("(s-ref 5 {pt} 0)", "PT-X: expected a PT, got an i32"),
"(s-ref (s-new {box} 1) {pt} 0)",
"PT-X: expected a PT, got a BOX",
"(s-set \"a\" {pt} 0 1)",
"(SETF PT-X): expected a PT, got a string",
("(s-copy 5 {pt})", "COPY-PT: expected a PT, got an i32"),
assert!(failure(run(source)).contains(message), "{source}");
fn malformed_calls_are_compile_errors() {
("(s-new {pt})", "(STRUCT-NEW) expects 2 arguments, got 1"),
("(s-new)", "(STRUCT-NEW) expects 1 arguments, got 0"),
("(s-new 99 1)", "no struct layout 99"),
("(s-new x 1)", "expected an integer literal"),
("(s-ref (s-new {pt} 1) {pt} 3)", "PT has no field 3"),
"(s-ref (s-new {pt} 1) {pt})",
"(STRUCT-REF) expects 3 arguments, got 2",
("(s-p 5)", "(STRUCT-P) expects 2 arguments, got 1"),
"(s-set 5 {pt} 0)",
"(STRUCT-SET) expects 4 arguments, got 3",
("(s-copy 5)", "(STRUCT-COPY) expects 2 arguments, got 1"),
fn the_reader_never_spells_a_struct_native() {
let program = Reader::parse("((STRUCT-NEW) 0 1)").expect("parses");
let call = program.exprs.first().expect("one form");
let Expr::List(items) = call else {
panic!("not a list: {call:?}");
};
items.first(),
Some(&Expr::List(vec![Expr::symbol("STRUCT-NEW")]))
assert!(!failure(run("((STRUCT-NEW) {pt} 1)")).is_empty());
fn expected(mode: CompileMode, n: i64) -> String {
match mode {
CompileMode::Script => format!("Number(Index({n}))"),
CompileMode::Eval => format!("Some(I32) [Struct(2), I64({n}), I64(1)]"),
fn a_diverging_operand_leaves_the_native_unreached() {
for native in [
"(s-ref (error 'foo \"x\") {pt} 0)",
"(s-set (error 'foo \"x\") {pt} 0 1)",
"(s-copy (error 'foo \"x\") {pt})",
for mode in [CompileMode::Eval, CompileMode::Script] {
let caught = format!("(handler-case {native} (t (e) 1))");
assert_eq!(value(run_in(mode, &caught)), expected(mode, 1), "{caught}");
fn an_exiting_operand_leaves_the_native_unreached() {
"(s-ref (return-from b 7) {pt} 0)",
"(s-set (return-from b 7) {pt} 0 1)",
"(s-copy (return-from b 7) {pt})",
let block = format!("(block b {native})");
assert_eq!(value(run_in(mode, &block)), expected(mode, 7), "{block}");
pub(super) fn script(source: &str) -> String {
value(run_in(CompileMode::Script, source))
pub(super) fn num(n: i64) -> String {
format!("Number(Index({n}))")
fn pt(field: &str) -> String {
format!("Struct {{ name: \"PT\", fields: [(\"X\", {field})] }}")
fn a_struct_result_is_written_as_its_name_and_fields() {
assert_eq!(script("(s-new {pt} 8)"), pt(&num(8)));
assert_eq!(script("(s-new {pt} nil)"), pt("Nil"));
assert_eq!(script("(s-new {pt} t)"), pt("T"));
assert_eq!(script("(s-new {pt} \"a\")"), pt("String(\"a\")"));
script("(s-new {pt} '(1 2))"),
pt(&format!(
"Pair(Pair {{ car: {}, cdr: Pair(Pair {{ car: {}, cdr: Nil }}) }})",
num(1),
num(2)
))
fn a_nested_struct_is_written_inside_its_holder() {
let inner = pt(&num(8));
script("(s-new {box} (s-new {pt} 8))"),
format!("Struct {{ name: \"BOX\", fields: [(\"P\", {inner})] }}")
fn a_struct_in_a_list_or_an_anyref_is_written_in_place() {
let list = script("(list 1 (s-new {pt} 8) 2)");
list,
format!(
"Pair(Pair {{ car: {}, cdr: Pair(Pair {{ car: {inner}, cdr: Pair(Pair {{ car: {}, cdr: Nil }}) }}) }})",
)
assert_eq!(script("(car (list (s-new {pt} 8) 1))"), inner);
assert_eq!(script("(let ((a (car (list (s-new {pt} 8) 1)))) a)"), inner);
fn nested_levels(text: &str) -> usize {
text.matches("name: \"BOX\"").count()
fn a_struct_holding_itself_ends_in_the_depth_placeholder() {
let levels = MAX_WIRE_LIST_DEPTH;
for (source, expected) in [
"(let ((b (s-new {box} nil))) (s-set b {box} 0 b) b)",
levels,
"(let ((b (s-new {box} nil))) (s-set b {box} 0 b) (list b))",
levels - 1,
"(let ((b (s-new {box} nil))) (s-set b {box} 0 b) (car (list b 1)))",
"(let ((b (s-new {box} nil))) (s-set b {box} 0 (list b)) b)",
levels / 2,
let text = script(source);
let ends = text.matches("Symbol(\"#<...>\")").count();
assert_eq!((nested_levels(&text), ends), (expected, 1), "{source}");
fn nested_list_script(levels: usize) -> String {
let steps = vec!["1"; levels].join(" ");
script(&format!(
"(let ((l nil)) (dolist (i '({steps})) (setf l (list l))) l)"
fn a_list_nests_to_the_cap_and_one_deeper_ends_in_the_placeholder() {
for (levels, placeholders) in [
(MAX_WIRE_LIST_DEPTH - 1, 0),
(MAX_WIRE_LIST_DEPTH, 0),
(MAX_WIRE_LIST_DEPTH + 1, 1),
(MAX_WIRE_LIST_DEPTH + 8, 1),
let text = nested_list_script(levels);
assert_eq!(ends, placeholders, "{levels} levels: {text}");