Lines
100 %
Functions
Branches
use wasm_encoder::{Function, Instruction};
use wasmparser::{Parser, Payload};
use super::{CompileContext, global_export_name};
use crate::ast::{EntityKind, PairElement, StructId, WasmType};
fn runtime_types(ctx: &mut CompileContext) -> Vec<WasmType> {
let closure = ctx
.intern_closure_signature(&[WasmType::Ratio], WasmType::Ratio)
.unwrap();
vec![
WasmType::I32,
WasmType::Bool,
WasmType::Ratio,
WasmType::Commodity,
WasmType::StringRef,
WasmType::PairRef(PairElement::I32),
WasmType::EntityRef(EntityKind::Condition),
WasmType::StructRef(StructId(0)),
WasmType::Closure(closure),
WasmType::AnyRef,
]
}
fn validated_module(mut ctx: CompileContext) -> Vec<u8> {
ctx.add_should_apply(CompileContext::default_should_apply(), usize::MAX);
let mut process = Function::new([]);
process.instruction(&Instruction::End);
ctx.add_process(process);
let bytes = ctx.finish();
wasmparser::validate(&bytes).expect("module with runtime globals must validate");
bytes
fn mutable_globals(bytes: &[u8]) -> Vec<bool> {
Parser::new(0)
.parse_all(bytes)
.filter_map(Result::ok)
.filter_map(|payload| match payload {
Payload::GlobalSection(reader) => Some(reader),
_ => None,
})
.flat_map(|reader| reader.into_iter().filter_map(Result::ok))
.map(|global| global.ty.mutable)
.collect()
fn exported_globals(bytes: &[u8]) -> Vec<(String, u32)> {
Payload::ExportSection(reader) => Some(reader),
.filter(|export| export.kind == wasmparser::ExternalKind::Global)
.map(|export| (export.name.to_string(), export.index))
#[test]
fn the_export_name_of_a_global_is_its_index() {
assert_eq!(global_export_name(7), "g7");
fn a_runtime_global_of_every_type_is_a_valid_exported_mutable_global() {
let mut ctx = CompileContext::new_with_host_fns(&[]).unwrap();
let first = ctx.alloc_mutable_global(WasmType::I32).unwrap();
let types = runtime_types(&mut ctx);
for (offset, ty) in types.iter().enumerate() {
let idx = ctx.alloc_mutable_global(*ty).unwrap();
assert_eq!(idx, first + 1 + u32::try_from(offset).unwrap());
let bytes = validated_module(ctx);
let mutability = mutable_globals(&bytes);
assert_eq!(mutability.len(), types.len() + 2);
assert!(!mutability[0], "the exported $t singleton stays immutable");
assert!(mutability[1..].iter().all(|mutable| *mutable));
let exported = exported_globals(&bytes);
for idx in first..=first + u32::try_from(types.len()).unwrap() {
assert!(exported.contains(&(global_export_name(idx), idx)));
fn a_global_allocated_in_a_rolled_back_trial_keeps_the_index_space_monotonic() {
let snap = ctx.snapshot();
let doomed = ctx.alloc_mutable_global(WasmType::Ratio).unwrap();
ctx.restore(snap);
let retry = ctx.alloc_mutable_global(WasmType::Ratio).unwrap();
assert_eq!(retry, doomed + 1);
assert_eq!(mutable_globals(&bytes).len(), 3);