submilli-engine 0.3.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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! Repository's ordinary imported-class layout and per-store vtable.
use crate::runtime::host::{abi_arg, abi_result};
use wasmtime::{
    ArrayRef, ArrayRefPre, Caller, Engine, FieldType, Finality, Func, FuncType, Global, GlobalType,
    HeapType, Linker, Mutability, RecGroupBuilder, RefType, Result, Rooted, StorageType, Store,
    StructRef, StructRefPre, StructType, Val, ValType,
};

use super::MODULE_NAME;
use crate::runtime::StoreData;
use crate::runtime::host::{fatal_host_error, register_host_fn_async, write_submilli_string};
use crate::runtime::intrinsic_types::{IntrinsicTypes, build_intrinsic_types, intrinsic_types};
use crate::runtime::prelude::iterator::as_struct;

#[derive(Clone)]
struct RepositoryClass {
    instance_type: StructType,
    vtable: Global,
    field_names: Global,
}

// Class vtable slots follow the declaration's sorted method names.
const METHODS: [&str; 14] = [
    "add",
    "addRemote",
    "branches",
    "commit",
    "createBranch",
    "diff",
    "fetch",
    "log",
    "pull",
    "remotes",
    "setRemoteUrl",
    "show",
    "status",
    "switchBranch",
];

pub(crate) fn install(linker: &mut Linker<StoreData>, store: &mut Store<StoreData>) -> Result<()> {
    let engine = store.engine().clone();
    let intr = build_intrinsic_types(&engine)?;
    let key = crate::mangle::package_symbol(MODULE_NAME, "Repository");
    let mut methods = Vec::new();
    for name in METHODS {
        let symbol = crate::mangle::extend(&key, name);
        let wasmtime::Extern::Func(method) =
            linker.get(&mut *store, MODULE_NAME, symbol.as_str())?
        else {
            wasmtime::bail!("git: missing class method");
        };
        methods.push(method);
    }
    let method_types = methods
        .iter()
        .map(|method| method.ty(&*store))
        .collect::<Vec<_>>();
    let (vtable_type, instance_type) = class_types(&engine, &intr, method_types)?;
    let vtable = make_vtable(store, vtable_type, methods)?;
    let field_names = make_field_names(store, &intr)?;
    linker.define(
        &mut *store,
        MODULE_NAME,
        crate::codegen::classes::vtable_global_export_name(&key).as_str(),
        vtable,
    )?;
    let class = RepositoryClass {
        instance_type: instance_type.clone(),
        vtable,
        field_names,
    };
    install_factories(linker, &engine, &intr, &class)?;
    install_constructor(linker, &engine, &intr, class)
}

fn class_types(
    engine: &Engine,
    intr: &IntrinsicTypes,
    methods: Vec<FuncType>,
) -> Result<(StructType, StructType)> {
    let mut builder = RecGroupBuilder::new(engine);
    let vtable_label = builder.declare_struct();
    let instance_label = builder.declare_struct();
    let mut def = builder.define_struct(vtable_label);
    def.finality(Finality::NonFinal);
    def.supertype(intr.class_vtable.clone());
    for ty in [
        &intr.to_string_fn,
        &intr.to_json_fn,
        &intr.equals_fn,
        &intr.hash_fn,
    ] {
        def.field(ref_field(ty.clone().into(), false));
    }
    def.field(ref_field(intr.class_vtable.clone().into(), true));
    def.field(FieldType::new(
        Mutability::Const,
        StorageType::ValType(ValType::I32),
    ));
    for ty in methods {
        def.field(ref_field(ty.into(), false));
    }
    def.finish();
    let mut def = builder.define_struct(instance_label);
    def.finality(Finality::NonFinal);
    def.supertype(intr.object_shape.clone());
    def.forward_ref_field(vtable_label)
        .mutability(Mutability::Const)
        .nullable(false)
        .finish();
    def.field(FieldType::new(
        Mutability::Var,
        StorageType::ValType(ValType::Ref(RefType::new(
            false,
            intr.field_names.clone().into(),
        ))),
    ));
    def.field(FieldType::new(
        Mutability::Var,
        StorageType::ValType(ValType::Ref(RefType::new(
            false,
            intr.object_fields.clone().into(),
        ))),
    ));
    def.field(wasmtime::FieldType::new(
        wasmtime::Mutability::Var,
        wasmtime::StorageType::ValType(ValType::Ref(RefType::ANYREF)),
    ));
    def.field(FieldType::new(
        Mutability::Var,
        StorageType::ValType(ValType::I64),
    ));
    def.finish();
    // Each lookup uses this builder's handle and declared kind. A successful
    // build preserves both, and no mutation occurs before lookup.
    let group = builder.build().map_err(fatal_host_error)?;
    Ok((
        group
            .get_struct(vtable_label)
            .expect("git class: declared vtable type is missing"),
        group
            .get_struct(instance_label)
            .expect("git class: declared instance type is missing"),
    ))
}

fn ref_field(heap: HeapType, nullable: bool) -> FieldType {
    FieldType::new(
        Mutability::Const,
        StorageType::ValType(ValType::Ref(RefType::new(nullable, heap))),
    )
}

fn make_vtable(store: &mut Store<StoreData>, ty: StructType, methods: Vec<Func>) -> Result<Global> {
    let opaque = store
        .data()
        .host_abi
        .as_ref()
        .ok_or_else(|| fatal_host_error("git class: prelude is not installed"))?
        .opaque_vtable;
    let value = opaque.get(&mut *store);
    let Val::AnyRef(Some(value)) = value else {
        wasmtime::bail!("missing opaque vtable")
    };
    let opaque = value.unwrap_struct(&mut *store)?;
    // Like guest classes, JSON contains field data, never class identity.
    let object = store
        .data()
        .host_abi
        .as_ref()
        .ok_or_else(|| fatal_host_error("git class: prelude is not installed"))?
        .object_vtable;
    let Val::AnyRef(Some(value)) = object.get(&mut *store) else {
        wasmtime::bail!("missing object vtable")
    };
    let object = value.unwrap_struct(&mut *store)?;
    let mut slots = vec![
        opaque.field(&mut *store, 0)?,
        object.field(&mut *store, 1)?,
        opaque.field(&mut *store, 2)?,
        opaque.field(&mut *store, 3)?,
        Val::AnyRef(None),
        Val::I32(1),
    ];
    slots.extend(methods.into_iter().map(|method| Val::FuncRef(Some(method))));
    let pre = StructRefPre::new(&mut *store, ty.clone());
    let vtable = StructRef::new(&mut *store, &pre, &slots)?;
    Global::new(
        &mut *store,
        GlobalType::new(
            ValType::Ref(RefType::new(false, ty.into())),
            Mutability::Const,
        ),
        Val::AnyRef(Some(vtable.to_anyref())),
    )
}

fn make_field_names(store: &mut Store<StoreData>, intr: &IntrinsicTypes) -> Result<Global> {
    let string_vtable = store
        .data()
        .host_abi
        .as_ref()
        .ok_or_else(|| fatal_host_error("git class: prelude is not installed"))?
        .string_vtable;
    let vtable = string_vtable.get(&mut *store);
    let raw = write_submilli_string(&mut *store, "path")?;
    let name_type = private_field_name_type(store.engine(), intr)?;
    let pre = StructRefPre::new(&mut *store, name_type);
    let name = StructRef::new(
        &mut *store,
        &pre,
        &[
            vtable,
            Val::AnyRef(Some(raw.to_anyref())),
            Val::I64(0),
            Val::I32(1),
            Val::I32(1),
        ],
    )?;
    let pre = ArrayRefPre::new(&mut *store, intr.field_names.clone());
    let names = ArrayRef::new_fixed(&mut *store, &pre, &[Val::AnyRef(Some(name.to_anyref()))])?;
    Global::new(
        &mut *store,
        GlobalType::new(
            ValType::Ref(RefType::new(false, intr.field_names.clone().into())),
            Mutability::Const,
        ),
        Val::AnyRef(Some(names.to_anyref())),
    )
}

/// Match the compiler's marked-name layout: presence followed by privacy.
fn private_field_name_type(engine: &Engine, intr: &IntrinsicTypes) -> Result<StructType> {
    let mut fields: Vec<_> = intr.string.fields().collect();
    fields.push(FieldType::new(
        Mutability::Var,
        StorageType::ValType(ValType::I32),
    ));
    fields.push(FieldType::new(
        Mutability::Const,
        StorageType::ValType(ValType::I32),
    ));
    crate::runtime::gc_singleton::singleton_struct(
        engine,
        Finality::Final,
        Some(intr.string.clone()),
        fields,
    )
}

fn install_factories(
    linker: &mut Linker<StoreData>,
    engine: &wasmtime::Engine,
    intr: &IntrinsicTypes,
    class: &RepositoryClass,
) -> Result<()> {
    let string = ValType::Ref(RefType::new(
        false,
        HeapType::ConcreteStruct(intr.string.clone()),
    ));
    let options = ValType::Ref(RefType::new(
        true,
        HeapType::ConcreteStruct(intr.object.clone()),
    ));
    let repository_result = ValType::Ref(RefType::new(
        false,
        HeapType::ConcreteStruct(class.instance_type.clone()),
    ));
    register_host_fn_async(
        linker,
        MODULE_NAME,
        crate::mangle::static_member(
            &crate::mangle::package_symbol(MODULE_NAME, "Repository"),
            "open",
        ),
        FuncType::new(engine, [string.clone()], [repository_result.clone()]),
        false,
        {
            let class = class.clone();
            move |caller, params, results| {
                let class = class.clone();
                Box::pin(async move {
                    let path = super::invoke(caller, "open", false, params).await?;
                    *abi_result(results, 0)? = new_instance(caller, &class, path)?;
                    Ok(())
                })
            }
        },
    )?;
    register_host_fn_async(
        linker,
        MODULE_NAME,
        crate::mangle::static_member(
            &crate::mangle::package_symbol(MODULE_NAME, "Repository"),
            "init",
        ),
        FuncType::new(
            engine,
            [string.clone(), options.clone()],
            [repository_result.clone()],
        ),
        false,
        {
            let class = class.clone();
            move |caller, params, results| {
                let class = class.clone();
                Box::pin(async move {
                    let path = super::invoke(caller, "init", false, params).await?;
                    *abi_result(results, 0)? = new_instance(caller, &class, path)?;
                    Ok(())
                })
            }
        },
    )?;
    register_host_fn_async(
        linker,
        MODULE_NAME,
        crate::mangle::static_member(
            &crate::mangle::package_symbol(MODULE_NAME, "Repository"),
            "clone",
        ),
        FuncType::new(
            engine,
            [string.clone(), string.clone(), options.clone()],
            [repository_result.clone()],
        ),
        false,
        {
            let class = class.clone();
            move |caller, params, results| {
                let class = class.clone();
                Box::pin(async move {
                    let path = super::invoke(caller, "clone", false, params).await?;
                    *abi_result(results, 0)? = new_instance(caller, &class, path)?;
                    Ok(())
                })
            }
        },
    )?;
    Ok(())
}

fn install_constructor(
    linker: &mut Linker<StoreData>,
    engine: &Engine,
    intr: &IntrinsicTypes,
    class: RepositoryClass,
) -> Result<()> {
    let key = crate::mangle::package_symbol(MODULE_NAME, "Repository");
    let string = ValType::Ref(RefType::new(false, intr.string.clone().into()));
    register_host_fn_async(
        linker,
        MODULE_NAME,
        crate::mangle::extend(&key, "constructor"),
        FuncType::new(
            engine,
            [string.clone()],
            [ValType::Ref(RefType::new(
                false,
                class.instance_type.clone().into(),
            ))],
        ),
        false,
        move |caller, params, results| {
            let class = class.clone();
            Box::pin(async move {
                let path = super::invoke(caller, "open", false, params).await?;
                *abi_result(results, 0)? = new_instance(caller, &class, path)?;
                Ok(())
            })
        },
    )?;
    register_host_fn_async(
        linker,
        MODULE_NAME,
        crate::mangle::extend(&key, "constructor_init"),
        FuncType::new(
            engine,
            [
                ValType::Ref(RefType::new(false, intr.object.clone().into())),
                string,
            ],
            [],
        ),
        false,
        |caller, params, _results| {
            Box::pin(async move {
                let path = super::invoke(caller, "open", false, &params[1..]).await?;
                payload(caller, abi_arg(params, 0)?)?.set(&mut *caller, 0, path)?;
                Ok(())
            })
        },
    )
}

fn payload(caller: &mut Caller<'_, StoreData>, receiver: &Val) -> Result<Rooted<ArrayRef>> {
    let instance = as_struct(caller, receiver, "Repository")?;
    let fields = instance.field(&mut *caller, 2)?;
    match fields {
        Val::AnyRef(Some(value)) => value.unwrap_array(&mut *caller),
        _ => wasmtime::bail!("git: invalid repository payload"),
    }
}

pub(super) fn path(caller: &mut Caller<'_, StoreData>, receiver: &Val) -> Result<Val> {
    payload(caller, receiver)?.get(&mut *caller, 0)
}

fn new_instance(
    caller: &mut Caller<'_, StoreData>,
    class: &RepositoryClass,
    path: Val,
) -> Result<Val> {
    let intr = intrinsic_types(&mut *caller)?;
    let pre = ArrayRefPre::new(&mut *caller, intr.object_fields.clone());
    let fields = ArrayRef::new_fixed(&mut *caller, &pre, &[path])?;
    let vtable = class.vtable.get(&mut *caller);
    let names = class.field_names.get(&mut *caller);
    let pre = StructRefPre::new(&mut *caller, class.instance_type.clone());
    let instance = StructRef::new(
        &mut *caller,
        &pre,
        &[
            vtable,
            names,
            Val::AnyRef(Some(fields.to_anyref())),
            Val::AnyRef(None),
            Val::I64(0),
        ],
    )?;
    Ok(Val::AnyRef(Some(instance.to_anyref())))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn git_class_setup_without_prelude_returns_fatal_error() {
        let config = crate::RuntimeConfig::default();
        let engine = config.engine().unwrap();
        let intr = build_intrinsic_types(&engine).unwrap();
        let mut store = config
            .store(&engine, StoreData::with_vfs(crate::runtime::Vfs::none()))
            .unwrap();
        let error = make_field_names(&mut store, &intr).unwrap_err();
        assert!(error.is::<crate::runtime::host::FatalHostError>());
        let error = make_vtable(&mut store, intr.class_vtable, vec![]).unwrap_err();
        assert!(error.is::<crate::runtime::host::FatalHostError>());
    }
}