submilli-engine 0.5.0

Compiles Submilli programs, a TypeScript subset, to WebAssembly and runs them under capability policy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! Runtime string-key operations on the shared object carrier.
use wasmtime::{Caller, FuncType, HeapType, Linker, RefType, Val, ValType};

use super::{
    ctor_key, field_array, field_is_present, field_is_private, is_accessor_slot, shape_arrays,
};
use crate::runtime::StoreData;
use crate::runtime::fuel;
use crate::runtime::host::{register_host_fn, register_host_fn_async, write_submilli_array_struct};
use crate::runtime::prelude::collection::FIELD_NAME;
use crate::runtime::prelude::keep::KeptValues;
use crate::runtime::prelude::vtable::read_string_units;
use crate::runtime::prelude::{MODULE_NAME, declare_method};
use crate::{PackageDeclaration, Param, Type};

struct Property {
    slot: u32,
    name: Val,
    value: Val,
}

fn find(
    caller: &mut Caller<'_, StoreData>,
    object: &Val,
    key: &[u16],
    accessor: bool,
) -> wasmtime::Result<Option<Property>> {
    let Some((names, values)) = shape_arrays(caller, object)? else {
        return Err(crate::runtime::host::throw_host_error(
            caller,
            crate::runtime::host::type_error("property receiver must be an object"),
        ));
    };
    let object = super::super::iterator::as_struct(caller, object, "property receiver")?;
    let Some(slot) = super::index::lookup(caller, &object, key, accessor, true)? else {
        return Ok(None);
    };
    Ok(Some(Property {
        slot,
        name: names.get(&mut *caller, slot)?,
        value: values.get(&mut *caller, slot)?,
    }))
}

fn accessor_key(prefix: &str, key: &[u16]) -> wasmtime::Result<Vec<u16>> {
    let capacity = key
        .len()
        .checked_add(prefix.len())
        .ok_or_else(|| crate::runtime::host::fatal_host_error("property key size overflow"))?;
    let mut result = Vec::new();
    result
        .try_reserve_exact(capacity)
        .map_err(crate::runtime::host::fatal_host_error)?;
    result.extend(prefix.encode_utf16());
    result.extend_from_slice(key);
    Ok(result)
}

pub(super) async fn get(
    caller: &mut Caller<'_, StoreData>,
    object: &Val,
    name: &Val,
) -> wasmtime::Result<Val> {
    let key = read_string_units(caller, name, FIELD_NAME)?;
    if let Some(property) = find(caller, object, &key, false)? {
        if !field_is_present(caller, &property.name, &property.value)? {
            return super::super::undefined::value(caller);
        }
        return checked_data_value(caller, object, property.slot, property.value).await;
    }
    if let Some(property) = find(caller, object, &accessor_key("get ", &key)?, true)? {
        return super::super::closure::read(caller, &property.value, "property getter")?
            .call_with_receiver(caller, *object, &[])
            .await;
    }
    super::super::undefined::value(caller)
}

/// Hidden payload rows retain concrete class validators across structural views.
/// Insertion preserves one guard per named slot plus the row's generic context.
async fn checked_data_value(
    caller: &mut Caller<'_, StoreData>,
    object: &Val,
    slot: u32,
    mut value: Val,
) -> wasmtime::Result<Val> {
    let Some((names, fields)) = shape_arrays(caller, object)? else {
        return Err(crate::runtime::host::fatal_host_error(
            "internal error: class field guard lost its object carrier",
        ));
    };
    let named_len = names.len(&mut *caller)?;
    let total = fields.len(&mut *caller)?;
    let width = named_len.checked_add(1).ok_or_else(|| {
        crate::runtime::host::fatal_host_error("class field guard row width overflow")
    })?;
    let hidden = total.checked_sub(named_len).ok_or_else(|| {
        crate::runtime::host::fatal_host_error("class field payload is shorter than its names")
    })?;
    if slot >= named_len || hidden % width != 0 {
        return Err(crate::runtime::host::fatal_host_error(
            "malformed class field guard rows",
        ));
    }
    for row in (named_len..total).step_by(width as usize) {
        let guard = fields.get(&mut *caller, row + slot)?;
        if !matches!(guard, Val::AnyRef(None)) {
            value = super::super::closure::read(caller, &guard, "class field guard")?
                .call(caller, &[value])
                .await?;
        }
    }
    Ok(value)
}

pub(super) async fn set(
    caller: &mut Caller<'_, StoreData>,
    object: &Val,
    name: &Val,
    value: &Val,
) -> wasmtime::Result<()> {
    let key = read_string_units(caller, name, FIELD_NAME)?;
    if shape_arrays(caller, object)?.is_none() {
        return set_builtin_property(caller, object, &key, value);
    }
    if let Some(property) = find(caller, object, &key, false)? {
        let object = super::super::iterator::as_struct(caller, object, "property receiver")?;
        let values = field_array(caller, &object, 2)?;
        values.set(&mut *caller, property.slot, *value)?;
        let marker = super::super::iterator::as_struct(caller, &property.name, "field name")?;
        if marker.ty(&*caller)?.fields().count() > 3
            && matches!(marker.field(&mut *caller, 3)?, Val::I32(0))
        {
            marker.set_field(&mut *caller, 3, Val::I32(1))?;
        }
        return Ok(());
    }
    if let Some(property) = find(caller, object, &accessor_key("set ", &key)?, true)? {
        super::super::closure::read(caller, &property.value, "property setter")?
            .call_with_receiver(caller, *object, &[*value])
            .await?;
        return Ok(());
    }
    if find(caller, object, &accessor_key("get ", &key)?, true)?.is_some() {
        return Err(crate::runtime::host::throw_host_error(
            caller,
            crate::runtime::host::type_error("cannot write a getter-only property"),
        ));
    }
    super::insert_field(caller, object, name, value)
}

/// A write through a structural view of a built-in value: the properties the
/// prelude declares writable go to their host setters, and any other write
/// throws a `TypeError`. JavaScript throws the same for a read-only property
/// (`size`) but would add a new one; a built-in here has no room for it.
fn set_builtin_property(
    caller: &mut Caller<'_, StoreData>,
    object: &Val,
    key: &[u16],
    value: &Val,
) -> wasmtime::Result<()> {
    let name = String::from_utf16_lossy(key);
    let intr = crate::runtime::intrinsic_types::intrinsic_types(&mut *caller)?;
    let (array, regex) = (intr.array.clone(), intr.regex.clone());
    let is_a = |caller: &mut Caller<'_, StoreData>, ty: &wasmtime::StructType| match object {
        Val::AnyRef(Some(any)) => match any.as_struct(&mut *caller)? {
            Some(st) => st.matches_ty(&*caller, ty),
            None => Ok(false),
        },
        _ => Ok(false),
    };
    let result = if name == "length" && is_a(caller, &array)? {
        let length = crate::runtime::host::read_boxed_number(caller, value, "Array#length")?;
        super::super::array::set_length(caller, object, length)
    } else if name == "lastIndex" && is_a(caller, &regex)? {
        let index = crate::runtime::host::read_boxed_number(caller, value, "RegExp#lastIndex")?;
        super::super::regex::set_last_index(caller, object, index)
    } else {
        Err(crate::runtime::host::type_error(format!(
            "Cannot set property '{name}' of a built-in value"
        )))
    };
    result.map_err(|error| crate::runtime::host::throw_host_error(caller, error))
}

pub(super) fn has(
    caller: &mut Caller<'_, StoreData>,
    object: &Val,
    name: &Val,
) -> wasmtime::Result<bool> {
    let key = read_string_units(caller, name, FIELD_NAME)?;
    if let Some(property) = find(caller, object, &key, false)? {
        return field_is_present(caller, &property.name, &property.value);
    }
    Ok(
        find(caller, object, &accessor_key("get ", &key)?, true)?.is_some()
            || find(caller, object, &accessor_key("set ", &key)?, true)?.is_some(),
    )
}

/// How a slot appears among a record's values; `None` when it has no entry
/// (a private field, an absent optional field, or a setter alone).
enum RecordEntry {
    Getter,
    Data,
}

/// The `"get "` prefix of a getter's slot name.
const GETTER_PREFIX: [u16; 4] = [b'g' as u16, b'e' as u16, b't' as u16, b' ' as u16];

fn record_entry(
    caller: &mut Caller<'_, StoreData>,
    name: &Val,
    value: &Val,
) -> wasmtime::Result<Option<RecordEntry>> {
    if field_is_private(caller, name)? {
        return Ok(None);
    }
    if is_accessor_slot(caller, name)? {
        let getter = read_string_units(caller, name, FIELD_NAME)?.starts_with(&GETTER_PREFIX);
        return Ok(getter.then_some(RecordEntry::Getter));
    }
    Ok(field_is_present(caller, name, value)?.then_some(RecordEntry::Data))
}

async fn values(caller: &mut Caller<'_, StoreData>, object: &Val) -> wasmtime::Result<Val> {
    let Some((names, fields)) = shape_arrays(caller, object)? else {
        return Ok(Val::AnyRef(None));
    };
    let count = super::field_count(caller, object)?;
    // A getter's result is held by nothing while the next getter runs.
    let mut result = KeptValues::with_capacity(caller, count as usize)?;
    for slot in 0..count {
        let name = names.get(&mut *caller, slot)?;
        let value = fields.get(&mut *caller, slot)?;
        match record_entry(caller, &name, &value)? {
            Some(RecordEntry::Getter) => {
                let got = super::super::closure::read(caller, &value, "record getter")?
                    .call_with_receiver(caller, *object, &[])
                    .await?;
                result.push(caller, got)?;
            }
            Some(RecordEntry::Data) => {
                let checked = checked_data_value(caller, object, slot, value).await?;
                result.push(caller, checked)?;
            }
            None => {}
        }
    }
    Ok(Val::AnyRef(Some(
        write_submilli_array_struct(caller, result.values())?.to_anyref(),
    )))
}

/// The JSON-quoted keys of the first `count` values `#recordValues` returned,
/// which name a failed record cast's entries. A record check asks once, when
/// it first renders a path: on a failure, including a rejected union
/// alternative, or before a recursive validator call. A passing cast of a
/// record without either never walks its keys.
///
/// The keys are read after `#recordValues` ran the record's getters, so a getter
/// that makes an absent optional field present shifts the keys after it. The
/// result always holds `count` keys, so the cast never reads past its end: if
/// the walk finds fewer entries, the rest are named by their positions.
fn quoted_keys(
    caller: &mut Caller<'_, StoreData>,
    object: &Val,
    count: f64,
) -> wasmtime::Result<Val> {
    let Some((names, fields)) = shape_arrays(caller, object)? else {
        return Err(crate::runtime::host::fatal_host_error(
            "record keys of a value that is not an object",
        ));
    };
    let slots = super::field_count(caller, object)?;
    fuel::charge(&mut *caller, fuel::ELEM, u64::from(slots))?;
    // `count` is the length of the values array, and the cast reads a key for
    // each of its positions, so the result always holds exactly `count` keys.
    let wanted = count as usize;
    let mut keys = KeptValues::with_capacity(caller, wanted)?;
    for slot in 0..slots {
        if keys.values().len() >= wanted {
            break;
        }
        let name = names.get(&mut *caller, slot)?;
        let value = fields.get(&mut *caller, slot)?;
        let Some(entry) = record_entry(caller, &name, &value)? else {
            continue;
        };
        let units = read_string_units(caller, &name, FIELD_NAME)?;
        let key = match entry {
            RecordEntry::Getter => units.get(GETTER_PREFIX.len()..).unwrap_or_default(),
            RecordEntry::Data => &units,
        };
        let quoted = crate::runtime::prelude::vtable::quote_string(caller, key)?;
        keys.push(caller, quoted)?;
    }
    while keys.values().len() < wanted {
        let position: Vec<u16> = keys.values().len().to_string().encode_utf16().collect();
        let quoted = crate::runtime::prelude::vtable::quote_string(caller, &position)?;
        keys.push(caller, quoted)?;
    }
    Ok(Val::AnyRef(Some(
        write_submilli_array_struct(caller, keys.values())?.to_anyref(),
    )))
}

pub(super) fn install(linker: &mut Linker<StoreData>) -> wasmtime::Result<()> {
    let engine = linker.engine().clone();
    let intr = crate::runtime::intrinsic_types::build_intrinsic_types(&engine)?;
    let object = ValType::Ref(RefType::new(true, HeapType::ConcreteStruct(intr.object)));
    let string = ValType::Ref(RefType::new(false, HeapType::ConcreteStruct(intr.string)));
    for name in ["#getField", "#setField", "#recordValues"] {
        let mut params = vec![object.clone()];
        if name != "#recordValues" {
            params.push(string.clone());
        }
        if name == "#setField" {
            params.push(object.clone());
        }
        let results = if name == "#setField" {
            vec![]
        } else {
            vec![object.clone()]
        };
        register_host_fn_async(
            linker,
            MODULE_NAME,
            ctor_key(name),
            FuncType::new(&engine, params, results),
            move |caller, params, results| {
                Box::pin(async move {
                    match (name, params, results) {
                        ("#getField", [object, key], [result]) => {
                            *result = get(caller, object, key).await?;
                        }
                        ("#setField", [object, key, value], []) => {
                            set(caller, object, key, value).await?;
                        }
                        ("#recordValues", [object], [result]) => {
                            *result = values(caller, object).await?;
                        }
                        _ => {
                            return Err(crate::runtime::host::fatal_host_error(
                                "invalid dynamic object host ABI",
                            ));
                        }
                    }
                    Ok(())
                })
            },
        )?;
    }
    register_host_fn(
        linker,
        MODULE_NAME,
        ctor_key("#quotedRecordKeys"),
        FuncType::new(&engine, [object.clone(), ValType::F64], [object.clone()]),
        |caller, params, results| {
            let ([object, Val::F64(count)], [result]) = (params, results) else {
                return Err(crate::runtime::host::fatal_host_error(
                    "invalid record keys host ABI",
                ));
            };
            *result = quoted_keys(caller, object, f64::from_bits(*count))?;
            Ok(())
        },
    )?;
    register_host_fn(
        linker,
        MODULE_NAME,
        ctor_key("#hasField"),
        FuncType::new(&engine, [object, string], [ValType::I32]),
        |caller, params, results| {
            let ([object, key], [result]) = (params, results) else {
                return Err(crate::runtime::host::fatal_host_error(
                    "invalid property presence host ABI",
                ));
            };
            *result = Val::I32(i32::from(has(caller, object, key)?));
            Ok(())
        },
    )
}

pub(super) fn declare(defs: &mut PackageDeclaration) {
    for name in ["#getField", "#setField", "#recordValues", "#hasField"] {
        let mut params = vec![Param::new("object", Type::Unknown)];
        if name != "#recordValues" {
            params.push(Param::new("key", Type::String));
        }
        if name == "#setField" {
            params.push(Param::new("value", Type::Unknown));
        }
        let ret = match name {
            "#setField" => Type::Void,
            "#hasField" => Type::Boolean,
            _ => Type::Unknown,
        };
        declare_method(defs, name, ctor_key(name), params, ret);
    }
    declare_method(
        defs,
        "#quotedRecordKeys",
        ctor_key("#quotedRecordKeys"),
        vec![
            Param::new("object", Type::Unknown),
            Param::new("count", Type::Number),
        ],
        Type::Unknown,
    );
}