Lines
98.46 %
Functions
85.37 %
Branches
100 %
use std::sync::{Arc, Mutex};
use scripting::host::ExecutionState;
use scripting::runtime::compile_wat;
use scripting_format::{
DEBUG_VALUE_DATA_SIZE, DebugValueData, ENTITY_HEADER_SIZE, EntityFlags, EntityHeader,
EntityType, OUTPUT_HEADER_SIZE, Operation, OutputHeader, TAG_DATA_SIZE, TagData, ValueType,
};
use wasmtime::{AnyRef, Linker, Rooted, Store};
use super::super::CompileMode;
use super::graph::{self, Node};
use super::{
Behaviour, EPOCH_DEADLINE, Logged, Outcome, WORLDS, engine, observe, runtime_error,
script_result, without_byte_offset,
use crate::ast::WasmType;
use crate::host_fn::HostFnSpec;
fn run(source: &str, mode: CompileMode) -> Vec<Behaviour> {
observe(source, mode, &[]).0
}
fn outcomes(behaviours: &[Behaviour]) -> Vec<Outcome> {
behaviours.iter().map(|b| b.outcome.clone()).collect()
fn value(text: &str) -> Outcome {
Outcome::Value(text.to_string())
#[test]
fn a_validation_error_is_observed_without_its_byte_offset() {
assert_eq!(
without_byte_offset(
"type mismatch: expected (ref null $type), found anyref (at offset 0xe46)"
),
"type mismatch: expected (ref null $type), found anyref"
);
without_byte_offset("bad (at offset 0x1f) then more"),
"bad then more"
for untouched in [
"division by zero",
"x (at offset 0xzz)",
"x (at offset 0x12",
] {
assert_eq!(without_byte_offset(untouched), untouched);
fn every_world_is_observed() {
let behaviours = run("5", CompileMode::Script);
let worlds: Vec<_> = behaviours.iter().map(|b| b.world).collect();
assert_eq!(worlds, ["empty batch", "ledger batch"]);
fn a_value_is_observed_in_each_mode() {
outcomes(&run("(+ 1 2)", CompileMode::Script)),
vec![value("Number(Index(3))"); 2]
outcomes(&run("(+ 1 2)", CompileMode::Eval)),
vec![value("Some(I32) [Struct(2), I64(3), I64(1)]"); 2]
fn an_eval_value_keeps_what_the_host_rendering_loses() {
let list = run(
"(do ((i 0 (+ i 1)) (acc nil (cons i acc))) ((= i 2) acc))",
CompileMode::Eval,
let string = run("\"(1 0)\"", CompileMode::Eval);
(&list[0].outcome, &string[0].outcome),
(
&value("Some(PairRef(I32)) [Struct(2), I31(1), Struct(2), I31(0), Null]"),
&value("Some(StringRef) [Array(5), I32(40), I32(49), I32(32), I32(48), I32(41)]")
)
let index = run("1", CompileMode::Eval);
let scalar = run("(index->scalar 1)", CompileMode::Eval);
(&index[0].outcome, &scalar[0].outcome),
&value("Some(I32) [Struct(2), I64(1), I64(1)]"),
&value("Some(Ratio) [Struct(2), I64(1), I64(1)]")
fn the_ledger_batch_drives_entity_count() {
outcomes(&run("(entity-count)", CompileMode::Script)),
[value("Number(Index(0))"), value("Number(Index(9))")]
fn each_world_answers_the_host_fns_its_own_way() {
let hosts = [
HostFnSpec::new("rpc-protocol-version", "nomi", "rpc_protocol_version")
.returns(WasmType::I32),
];
let (behaviours, _) = observe("(+ (rpc-protocol-version) 1)", CompileMode::Eval, &hosts);
outcomes(&behaviours),
[
value("Some(I32) [Struct(2), I64(2), I64(1)]"),
value("Some(I32) [Struct(2), I64(1), I64(1)]")
]
fn entity_writes_are_behaviour() {
let food = run(
"(create-tag (primary-entity-idx) \"category\" \"food\") 1",
CompileMode::Script,
let transport = run(
"(create-tag (primary-entity-idx) \"category\" \"transportation\") 1",
assert_eq!(food[1].outcome, transport[1].outcome);
assert!(food[1].effects.iter().any(|e| e.contains("\"food\"")));
assert_ne!(food[1], transport[1]);
fn printed_output_keeps_its_order_and_severity() {
let script = run("(print \"x\") (print 1 2) 5", CompileMode::Script);
let text = |s: &str| Logged::Text(s.to_string());
assert_eq!(script[0].output, [(0, text("x")), (0, text("1 2"))]);
let eval = run("(progn (print \"x\") 7)", CompileMode::Eval);
assert_eq!(eval[0].output, [(0, text("x"))]);
fn a_printed_whole_scalar_keeps_its_denominator_on_both_surfaces() {
let cases = [
("(print 2/1)", "2/1"),
("(display 2/1)", "2/1"),
("(print 7 2/1)", "7 2/1"),
("(print '(2/1 3))", "(2/1 3)"),
("(print 2)", "2"),
for (source, printed) in cases {
for mode in [CompileMode::Script, CompileMode::Eval] {
let behaviour = run(&format!("(progn {source} 0)"), mode);
assert_eq!(behaviour[0].output, [(0, text(printed))], "{source}");
type Log = Vec<(u32, Logged)>;
/// Runs a module that logs twice where production would drop the message
/// and asks for two uuids: the log it captured and the uuid bytes.
fn log_and_uuids() -> Result<(Log, Vec<u8>), String> {
let engine = engine()?;
let module = compile_wat(
engine,
r#"(module
(import "env" "log" (func $log (param i32 i32 i32)))
(import "env" "generate_uuid" (func $uuid (param i32)))
(memory (export "memory") 1)
(data (i32.const 0) "ok\ff")
(func (export "go")
(call $log (i32.const 3) (i32.const 0) (i32.const 2))
(call $log (i32.const 0) (i32.const 2) (i32.const 1))
(call $log (i32.const 2) (i32.const 65535) (i32.const 2))
(call $uuid (i32.const 16))
(call $uuid (i32.const 32))))"#,
.map_err(|err| err.to_string())?;
let output = Arc::new(Mutex::new(Vec::new()));
let mut store = Store::new(engine, ExecutionState::new(0, 0, 0));
store.set_epoch_deadline(EPOCH_DEADLINE);
let instance = WORLDS[0]
.linker(engine, &module, &output)
.and_then(|linker| linker.instantiate(&mut store, &module))
.and_then(|instance| {
instance
.get_typed_func::<(), ()>(&mut store, "go")?
.call(&mut store, ())?;
Ok(instance)
})
let memory = instance
.get_memory(&mut store, "memory")
.ok_or("no memory")?;
let uuids = memory.data(&store).get(16..48).ok_or("no uuids")?.to_vec();
let logged = output.lock().map_err(|err| err.to_string())?.clone();
Ok((logged, uuids))
/// A `log` the hosts would drop is still recorded, and uuids are
/// deterministic.
fn the_host_records_what_production_drops() {
let mut ids = vec![0; 32];
ids[15] = 1;
ids[31] = 2;
log_and_uuids(),
Ok((
vec![
(3, Logged::Text("ok".to_string())),
(0, Logged::InvalidUtf8(vec![0xff])),
(2, Logged::Unreadable)
],
ids
))
fn process_runs_unless_should_apply_answers_zero() {
let two = run(
"(defun should-apply () 2) (print \"ran\") 7",
assert_eq!(two[0].applies, Some(2));
assert_eq!(two[0].output, [(0, Logged::Text("ran".to_string()))]);
let zero = run(
"(defun should-apply () 0) (print \"ran\") 7",
(zero[0].applies, &zero[0].outcome, zero[0].output.len()),
(Some(0), &Outcome::NotApplied, 0)
fn an_absent_result_is_not_a_malformed_one() {
let mut empty = OutputHeader::new(0).to_bytes()[..OUTPUT_HEADER_SIZE].to_vec();
empty.resize(256, 0);
script_result(&empty),
(Outcome::NoValue("no output entities"), Vec::new())
assert!(matches!(
script_result(&[0; 8]),
(Outcome::Malformed(_), effects) if effects.is_empty()
));
fn huge_list(first: u32) -> Vec<Behaviour> {
run(
&format!("(do ((i {first} (+ i 1)) (acc nil (cons i acc))) ((= i 40000) acc))"),
/// The walk stays bounded, and a value it cannot observe fails the
/// comparison instead of matching.
fn a_huge_value_is_unobservable_and_matches_nothing() {
let (one, two) = (huge_list(0), huge_list(1));
assert!(
matches!(&one[0].outcome, Outcome::Unobservable(why) if why.contains("budget")),
"{:?}",
one[0].outcome
assert_ne!(one[0], two[0]);
assert_ne!(one[0], one[0].clone());
/// A struct of an array and a null, with the array's length chosen.
fn array_in_struct(len: u32) -> Result<Vec<Node>, String> {
&format!(
(type $bytes (array (mut i8)))
(type $pair (struct (field anyref) (field anyref)))
(func (export "value") (result anyref)
(struct.new $pair
(array.new_default $bytes (i32.const {len}))
(ref.null any)))
(func (export "t") (result anyref) (struct.new_default $pair)))"#
let instance = Linker::new(engine)
.instantiate(&mut store, &module)
let mut call = |name: &str| {
.get_typed_func::<(), Option<Rooted<AnyRef>>>(&mut store, name)
.and_then(|func| func.call(&mut store, ()))
.map_err(|err| err.to_string())
let (t, value) = (call("t")?, call("value")?);
let t = t.ok_or("no t")?;
graph::observe(&mut store, &t, value)
/// Children are refused before they are queued: the struct, the array and
/// the null leave room for exactly `MAX_NODES - 3` elements.
fn an_array_past_the_budget_is_refused_before_it_is_queued() {
assert_eq!(array_in_struct(65_533).map(|nodes| nodes.len()), Ok(65_536));
array_in_struct(65_534),
Err("an array of 65534 children exceeds the 65536-node budget".to_string())
/// An output region holding a created `category` tag, then a debug list
/// that never ends.
fn tag_then_unterminated_list(value: &str) -> Vec<u8> {
let name = "category";
let mut region = vec![0u8; 512];
let end = region.len();
let name_at = end - name.len();
let value_at = name_at - value.len();
region[name_at..].copy_from_slice(name.as_bytes());
region[value_at..name_at].copy_from_slice(value.as_bytes());
let mut header = OutputHeader::new(0);
header.output_entity_count = 2;
header.strings_offset = u32::try_from(end).unwrap_or(u32::MAX);
let mut bytes = header.to_bytes()[..OUTPUT_HEADER_SIZE].to_vec();
let tag_size = u32::try_from(TAG_DATA_SIZE).unwrap_or(u32::MAX);
bytes.extend_from_slice(
&EntityHeader::new(
EntityType::Tag,
Operation::Create,
EntityFlags::make(false, false),
[7; 16],
0,
tag_size,
.to_bytes(),
&TagData {
name_offset: u32::try_from(end - name_at).unwrap_or(u32::MAX),
value_offset: u32::try_from(end - value_at).unwrap_or(u32::MAX),
name_len: u16::try_from(name.len()).unwrap_or(u16::MAX),
value_len: u16::try_from(value.len()).unwrap_or(u16::MAX),
reserved: [0; 4],
let data_offset = u32::try_from(bytes.len() + ENTITY_HEADER_SIZE).unwrap_or(u32::MAX);
let debug_size = u32::try_from(DEBUG_VALUE_DATA_SIZE).unwrap_or(u32::MAX);
EntityType::DebugValue,
Operation::Nop,
[0; 16],
-1,
data_offset,
debug_size,
&DebugValueData {
value_type: ValueType::List as u8,
reserved: [0; 7],
data1: 0,
data2: 0,
region[..bytes.len()].copy_from_slice(&bytes);
region
/// A malformed result never erases writes that parsed.
fn a_malformed_result_keeps_the_parsed_writes() {
let (food, food_effects) = script_result(&tag_then_unterminated_list("food"));
let (transport, transport_effects) =
script_result(&tag_then_unterminated_list("transportation"));
assert_eq!(food, Outcome::Malformed("unterminated list".to_string()));
assert_eq!(food, transport);
food_effects[0].contains("value: \"food\""),
"{food_effects:?}"
assert!(transport_effects[0].contains("value: \"transportation\""));
assert_ne!(food_effects, transport_effects);
fn a_raised_condition_is_its_code_and_message() {
run("(error 'boom \"bad\")", mode)[0].outcome,
Outcome::RuntimeError("BOOM: bad".to_string())
fn a_compile_error_is_its_text() {
run("(=)", CompileMode::Eval)[0].outcome,
Outcome::CompileError("Compile error: = requires at least 1 argument".to_string())
fn a_trap_is_named_by_its_kind_alone() {
let trap = wasmtime::Trap::UnreachableCodeReached;
let err =
wasmtime::Error::new(trap).context("error while executing at wasm backtrace:\n 0: 0x1234");
assert_eq!(runtime_error(&err), Outcome::RuntimeError(trap.to_string()));