hyperlight-component-util 0.15.0

Shared implementation for the procedural macros that generate Hyperlight host and guest bindings from component types
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
/*
Copyright 2025 The Hyperlight Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */

/// Elaborated component model types
///
/// This has the basic type definitions for the elaborated types. They
/// correspond roughly to the "Elaborated Types" section in the
/// specification.
use crate::structure::*;

#[derive(Debug, Clone, PartialEq, Copy)]
pub struct Name<'a> {
    pub name: &'a str,
}

#[derive(Debug, Clone, PartialEq, Copy)]
pub enum IntWidth {
    I8,
    I16,
    I32,
    I64,
}
impl IntWidth {
    pub fn width(self) -> u8 {
        match self {
            IntWidth::I8 => 8,
            IntWidth::I16 => 16,
            IntWidth::I32 => 32,
            IntWidth::I64 => 64,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Copy)]
pub enum FloatWidth {
    F32,
    F64,
}
impl FloatWidth {
    pub fn width(self) -> u8 {
        match self {
            FloatWidth::F32 => 32,
            FloatWidth::F64 => 64,
        }
    }
}

/// recordfield_e in the specification
#[derive(Debug, Clone)]
pub struct RecordField<'a> {
    pub name: Name<'a>,
    pub ty: Value<'a>,
}

/// variantcase_e in the specification
#[derive(Debug, Clone)]
pub struct VariantCase<'a> {
    pub name: Name<'a>,
    pub ty: Option<Value<'a>>,
}

/// valtype_e in the specification
#[derive(Debug, Clone)]
pub enum Value<'a> {
    Bool,
    S(IntWidth),
    U(IntWidth),
    F(FloatWidth),
    Char,
    String,
    List(Box<Value<'a>>),
    FixList(Box<Value<'a>>, u32),
    Record(Vec<RecordField<'a>>),
    Tuple(Vec<Value<'a>>),
    Flags(Vec<Name<'a>>),
    Variant(Vec<VariantCase<'a>>),
    Enum(Vec<Name<'a>>),
    Option(Box<Value<'a>>),
    Result(Box<Option<Value<'a>>>, Box<Option<Value<'a>>>),
    Own(Handleable),
    Borrow(Handleable),
    /// This records that a type variable was once here, and is used
    /// to enforce export namedness checks.
    Var(Option<Tyvar>, Box<Value<'a>>),
}

/// Global resource identifier
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ResourceId {
    pub(super) id: u32,
}

/// To make certain substitutions easier, free type variables are
/// divided into Universal and Existential variables.  Each is
/// represented by a pair of indices: the first index is an index into
/// [`Ctx::parents()`], specifying parent context has the variable
/// definition in it, and the second is an index into that context's
/// [`Ctx::uvars`] or [`Ctx::evars`].
#[derive(Debug, Clone)]
pub enum FreeTyvar {
    U(u32, u32),
    E(u32, u32),
}

/// We explicitly distinguish between bound type variables, which are
/// can only only present on types that are themselves inside a
/// [`QualifiedInstance`] or [`Component`], and free type variables
/// that are used while constructing or deconstructing such a type in
/// a [`Ctx`].
#[derive(Debug, Clone)]
pub enum Tyvar {
    /// A bound type variable as a de Bruijn index (0 is the innermost
    /// binder)
    Bound(u32),
    /// A free type variable, whose bounds/other information are
    /// stored in the context
    Free(FreeTyvar),
}

#[derive(Debug, Clone)]
pub struct Param<'a> {
    pub name: Name<'a>,
    pub ty: Value<'a>,
}

pub type Result<'a> = Option<Value<'a>>;

/// functype_e in the specification
#[derive(Debug, Clone)]
pub struct Func<'a> {
    pub params: Vec<Param<'a>>,
    pub result: Result<'a>,
}

/// In the spec, this does not exist, but a validation rule ensures an
/// invariant that certain deftype_e s are of this form.
#[derive(Debug, Clone)]
pub enum Handleable {
    Var(Tyvar),
    Resource(ResourceId),
}

/// deftype_e in the specification
#[derive(Debug, Clone)]
pub enum Defined<'a> {
    Handleable(Handleable),
    Value(Value<'a>),
    Func(Func<'a>),
    Instance(QualifiedInstance<'a>),
    Component(Component<'a>),
}

/// typebound_e in the specification
#[derive(Debug, Clone)]
pub enum TypeBound<'a> {
    Eq(Defined<'a>),
    SubResource,
}

/// The name of an import or export of the current
/// component/context. Not in the spec; only used for
/// [`BoundedTyvar::origin`] below.
///
/// Any string present in one of these should also be present in an
/// [`ExternDecl::kebab_name`] in a relevant place.
#[derive(Debug, Clone, PartialEq)]
pub enum ImportExport<'a> {
    Import(&'a str),
    Export(&'a str),
}
impl<'a> ImportExport<'a> {
    pub fn name(&self) -> &'a str {
        match self {
            ImportExport::Import(s) => s,
            ImportExport::Export(s) => s,
        }
    }
    pub fn imported(&self) -> bool {
        match self {
            ImportExport::Import(_) => true,
            ImportExport::Export(_) => false,
        }
    }
}

/// An (optional) path through the imports/exports of a current
/// component/context. Not in the spec; only used for
/// [`BoundedTyvar::origin`] below.
#[derive(Default, Debug, Clone, PartialEq)]
pub struct TyvarOrigin<'a> {
    /// Note that the most recent (closest) element is last
    pub path: Option<Vec<ImportExport<'a>>>,
}

impl<'a> TyvarOrigin<'a> {
    pub fn new() -> Self {
        TyvarOrigin { path: Some(vec![]) }
    }
    pub fn push(&self, x: Option<ImportExport<'a>>) -> Self {
        match (&self.path, x) {
            (None, _) => TyvarOrigin { path: None },
            (_, None) => self.clone(),
            (Some(xs), Some(x)) => {
                let mut xs = xs.clone();
                xs.push(x);
                TyvarOrigin { path: Some(xs) }
            }
        }
    }
    pub fn matches<I: Iterator<Item = &'a ImportExport<'a>>>(&self, path: I) -> bool {
        self.path
            .as_ref()
            .map(|p| p.iter().rev().eq(path))
            .unwrap_or(false)
    }
    pub fn is_local<
        I: DoubleEndedIterator<Item = &'a ImportExport<'a>>
            + ExactSizeIterator<Item = &'a ImportExport<'a>>,
    >(
        &self,
        path: I,
    ) -> Option<Vec<ImportExport<'a>>> {
        let other = path.rev().skip(1).rev();
        let path = self.path.as_ref()?;
        let path = path.iter();
        let mut path = path.rev();
        for elem in other {
            match path.next() {
                None => break,
                Some(oe) if oe != elem => return None,
                _ => (),
            }
        }
        Some(path.cloned().collect())
    }
    pub fn last_name(&self) -> Option<&'a str> {
        self.path
            .as_ref()
            .and_then(|x| x.first())
            .map(|ie| ie.name())
    }
    pub fn is_imported(&self) -> bool {
        let Some(p) = &self.path else {
            return false;
        };
        p[p.len() - 1].imported()
    }
}

/// boundedtyvar_e in the spec
///
/// Because we use a de Bruijn representation of type indices, this is
/// only the type_bound - which variable it is binding is implicit in
/// its position in the list.
#[derive(Debug, Clone)]
pub struct BoundedTyvar<'a> {
    /// This is not important for typechecking, but is used to keep
    /// track of where a type variable originated from in order to
    /// decide on a canonical name to be used in bindings
    /// generation.
    pub origin: TyvarOrigin<'a>,
    pub bound: TypeBound<'a>,
}

impl<'a> BoundedTyvar<'a> {
    pub fn new(bound: TypeBound<'a>) -> Self {
        BoundedTyvar {
            origin: TyvarOrigin::new(),
            bound,
        }
    }
    pub fn push_origin(&self, x: Option<ImportExport<'a>>) -> Self {
        BoundedTyvar {
            origin: self.origin.push(x),
            ..self.clone()
        }
    }
}

/// externdesc_e in the specification
#[derive(Debug, Clone)]
pub enum ExternDesc<'a> {
    CoreModule(CoreModule<'a>),
    Func(Func<'a>),
    /* TODO: First-class values (when the spec gets them) */
    Type(Defined<'a>),
    /// This uses an [`Instance`] rather than a [`QualifiedInstance`]
    /// because the instance's evars need to be propagated up to the
    /// surrounding component/instance (so that e.g. `alias`ing them
    /// and using them in another import/export is possible).
    Instance(Instance<'a>),
    Component(Component<'a>),
}

/// Merely a convenience for [`Ctx::resolve_alias`]
#[derive(Debug, Clone)]
pub enum CoreOrComponentExternDesc<'a> {
    Core(CoreExternDesc),
    Component(ExternDesc<'a>),
}

/// externdecl_e in the specification
#[derive(Debug, Clone)]
pub struct ExternDecl<'a> {
    pub kebab_name: &'a str,
    pub desc: ExternDesc<'a>,
}

/// `instancetype_e` in the specification.
///
/// An "opened" instance, whose existential variables are recorded in
/// some surrounding context.
#[derive(Debug, Clone)]
pub struct Instance<'a> {
    pub exports: Vec<ExternDecl<'a>>,
}

/// This is an instance together with its existential variables. This
/// concept doesn't exist as a named syntax class in the specification, but
/// is the payload of the instance case of `deftype_e` and the output
/// of the instance declaration inference judgement.
#[derive(Debug, Clone)]
pub struct QualifiedInstance<'a> {
    /// Existential variables produced by this instance (which may be
    /// referred to by [`exports`](Instance::exports)). These are stored in
    /// "outside-in" order that matches how they would be written on
    /// paper: de Bruijn index Bound(0) in the imports is the last
    /// element in the list, and later elements can depend on earlier
    /// ones.
    pub evars: Vec<BoundedTyvar<'a>>,
    pub unqualified: Instance<'a>,
}

/// componenttype_e in the specification
#[derive(Debug, Clone)]
pub struct Component<'a> {
    /// Universal variables over which this component is parameterized
    /// (which may be referred to by `imports`). These are stored in
    /// "outside-in" order that matches how they would be written on
    /// paper: de Bruijn index Bound(0) in the imports is the last
    /// element in the list, and later elements can depend on earlier
    /// ones.
    pub uvars: Vec<BoundedTyvar<'a>>,
    pub imports: Vec<ExternDecl<'a>>,
    /// Since we already have [`QualifiedInstance`], we use that to
    /// keep track of both the evars and the actual instance, unlike
    /// in the spec; this is quite natural, since during inference the
    /// evars are generated by the exports. However, they conceptually
    /// belong here as much as there: instantiating a component should
    /// add them to the context as non-imported uvars and produce an
    /// [`Instance`], rather than a [`QualifiedInstance`] directly.
    pub instance: QualifiedInstance<'a>,
}

// core:importdecl in the specification is wasmparser::Import

/// core:importdesc in the specification
#[derive(Debug, Clone)]
pub enum CoreExternDesc {
    Func(wasmparser::FuncType),
    Table(wasmparser::TableType),
    Memory(wasmparser::MemoryType),
    Global(wasmparser::GlobalType),
}

/// core:exportdecl in the specification
#[derive(Debug, Clone)]
pub struct CoreExportDecl<'a> {
    pub name: Name<'a>,
    pub desc: CoreExternDesc,
}

// core:functype is wasmparser::FuncType

/// core:instancetype_e in the specification
#[derive(Debug, Clone)]
pub struct CoreInstance<'a> {
    pub exports: Vec<CoreExportDecl<'a>>,
}

/// core:moduletype_e in the specification
#[derive(Debug, Clone)]
pub struct CoreModule<'a> {
    pub _imports: Vec<wasmparser::Import<'a>>,
    pub _exports: Vec<CoreExportDecl<'a>>,
}

/// core:deftype_e in the specification
#[derive(Debug, Clone)]
pub enum CoreDefined<'a> {
    Func(wasmparser::FuncType),
    Module(CoreModule<'a>),
}

/// gamma_c in the specification
#[derive(Default, Debug, Clone)]
pub struct CoreCtx<'a> {
    pub types: Vec<CoreDefined<'a>>,
    pub funcs: Vec<wasmparser::FuncType>,
    pub modules: Vec<CoreModule<'a>>,
    pub instances: Vec<CoreInstance<'a>>,
    pub tables: Vec<wasmparser::TableType>,
    pub mems: Vec<wasmparser::MemoryType>,
    pub globals: Vec<wasmparser::GlobalType>,
}

impl<'a> CoreCtx<'a> {
    pub fn new() -> Self {
        CoreCtx {
            types: Vec::new(),
            funcs: Vec::new(),
            modules: Vec::new(),
            instances: Vec::new(),
            tables: Vec::new(),
            mems: Vec::new(),
            globals: Vec::new(),
        }
    }
}

/// resourcetype_e in the specification
#[derive(Debug, Clone)]
pub struct Resource {
    // One day, there will be a `rep` field here...
    pub _dtor: Option<FuncIdx>,
}

/// gamma in the specification
#[derive(Debug, Clone)]
pub struct Ctx<'p, 'a> {
    pub parent: Option<&'p Ctx<'p, 'a>>,
    pub outer_boundary: bool,
    pub core: CoreCtx<'a>,
    /// Universally-quantified variables, specifying for each the
    /// known bound and whether or not it was imported. Uvars can come
    /// from imports or component instantiations; only the imported
    /// ones can be allowed to escape in the type of a components
    /// exports/imports, since only those can be named outside of the
    /// component itself.
    pub uvars: Vec<(BoundedTyvar<'a>, bool)>,
    /// Existentially-quantified variables, specifying for each the
    /// known bound and, if it was locally defined, the type which
    /// instantiates it.
    pub evars: Vec<(BoundedTyvar<'a>, Option<Defined<'a>>)>,
    pub rtypes: Vec<Resource>,
    pub types: Vec<Defined<'a>>,
    pub components: Vec<Component<'a>>,
    pub instances: Vec<Instance<'a>>,
    pub funcs: Vec<Func<'a>>,
}

impl<'p, 'a> Ctx<'p, 'a> {
    pub fn new<'c>(parent: Option<&'p Ctx<'c, 'a>>, outer_boundary: bool) -> Self {
        Ctx {
            parent,
            outer_boundary,
            core: CoreCtx::new(),
            uvars: Vec::new(),
            evars: Vec::new(),
            rtypes: Vec::new(),
            types: Vec::new(),
            components: Vec::new(),
            instances: Vec::new(),
            funcs: Vec::new(),
        }
    }
}

pub struct CtxParentIterator<'i, 'p: 'i, 'a: 'i> {
    ctx: Option<&'i Ctx<'p, 'a>>,
}
impl<'i, 'p, 'a> Iterator for CtxParentIterator<'i, 'p, 'a> {
    type Item = &'i Ctx<'p, 'a>;
    fn next(&mut self) -> Option<Self::Item> {
        match self.ctx {
            Some(ctx) => {
                self.ctx = ctx.parent;
                Some(ctx)
            }
            None => None,
        }
    }
}

impl<'p, 'a> Ctx<'p, 'a> {
    pub fn parents<'i>(&'i self) -> CtxParentIterator<'i, 'p, 'a> {
        CtxParentIterator { ctx: Some(self) }
    }
}