wasm-bindgen-cli-support 0.2.128

Shared support for the wasm-bindgen-cli package, an internal dependency
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
use std::char;

use wasm_bindgen_shared::identifier::is_valid_ident;
use wasm_bindgen_shared::tys::*;

/// Which kind of per-monomorphisation binding a discovered descriptor function
/// asks for.
///
/// On the wire these are distinguished only by the length of the leading key
/// string: zero-length means [`Cast`](Self::Cast). Keeping that distinction in
/// the type rather than as an empty-`String` sentinel means the two cases can't
/// be confused, and in particular that the "a cast takes exactly one argument"
/// invariant in `bind_generic_imports` is a property of the `Cast` variant
/// rather than of an untyped string being empty.
///
/// The derived `Ord` orders `Cast` before every `Shim`, which is only used as a
/// deterministic tie-break; see `bind_generic_imports`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum GenericImportKey {
    /// A [`wbg_cast`](wasm_bindgen::__rt::wbg_cast) identity adapter. Needs no
    /// AST metadata: it is bound as JS that returns its single argument
    /// unchanged.
    Cast,
    /// A `#[wasm_bindgen(experimental_generic_mono)]` import. The string is the shim key
    /// identifying which generic-import AST entry supplies the JS binding
    /// metadata (name, kind, namespace, catch, ...).
    Shim(String),
}

// `PartialOrd`/`Ord` exist so that a decoded descriptor can be used as a total
// tie-breaker when sorting (see `bind_generic_imports`). The order itself is
// arbitrary — it follows variant declaration order — and is not meaningful.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Descriptor {
    I8,
    U8,
    ClampedU8,
    I16,
    U16,
    I32,
    U32,
    I64,
    U64,
    I64AsF64,
    U64AsF64,
    I128,
    U128,
    F32,
    F64,
    Boolean,
    Function(Box<Function>),
    Closure(Box<Closure>),
    Ref(Box<Descriptor>),
    RefMut(Box<Descriptor>),
    Slice(Box<Descriptor>),
    Vector(Box<Descriptor>),
    CachedString,
    String,
    Externref,
    NamedExternref(String),
    Enum {
        name: String,
        hole: u32,
        unique_crate_identifier: String,
    },
    StringEnum {
        name: String,
        invalid: u32,
        hole: u32,
    },
    DynamicUnion {
        name: String,
        variant_types: Vec<Descriptor>,
    },
    RustStruct {
        name: String,
        unique_crate_identifier: String,
    },
    Char,
    Option(Box<Descriptor>),
    Result(Box<Descriptor>),
    Unit,
    NonNull,
    RawPointer,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Function {
    pub arguments: Vec<Descriptor>,
    pub shim_idx: u32,
    pub ret: Descriptor,
    pub inner_ret: Option<Descriptor>,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Closure {
    pub owned: bool,
    pub function: Function,
    pub mutable: bool,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum VectorKind {
    I8,
    U8,
    ClampedU8,
    I16,
    U16,
    I32,
    U32,
    I64,
    U64,
    F32,
    F64,
    String,
    Externref,
    NamedExternref(String),
}

impl Descriptor {
    pub fn decode(mut data: &[u32]) -> Descriptor {
        let descriptor = Descriptor::_decode(&mut data, false);
        assert!(data.is_empty(), "remaining data {data:?}");
        descriptor
    }

    /// Decode a per-monomorphisation generic-import descriptor stream.
    ///
    /// The stream is a length-prefixed `shim` key string (identifying which
    /// generic-import AST entry supplies the JS binding metadata) followed by
    /// the concrete `FUNCTION` signature for this monomorphisation. A
    /// zero-length key on the wire denotes a [`GenericImportKey::Cast`]; the
    /// wire format is unchanged by that being an enum here.
    pub fn decode_generic_import(mut data: &[u32]) -> (GenericImportKey, Descriptor) {
        let key = get_string(&mut data);
        let descriptor = Descriptor::_decode(&mut data, false);
        assert!(data.is_empty(), "remaining data {data:?}");
        let key = if key.is_empty() {
            GenericImportKey::Cast
        } else {
            GenericImportKey::Shim(key)
        };
        (key, descriptor)
    }

    fn _decode(data: &mut &[u32], clamped: bool) -> Descriptor {
        match get(data) {
            I8 => Descriptor::I8,
            I16 => Descriptor::I16,
            I32 => Descriptor::I32,
            I64 => Descriptor::I64,
            I64_AS_F64 => Descriptor::I64AsF64,
            I128 => Descriptor::I128,
            U8 if clamped => Descriptor::ClampedU8,
            U8 => Descriptor::U8,
            U16 => Descriptor::U16,
            U32 => Descriptor::U32,
            U64 => Descriptor::U64,
            U64_AS_F64 => Descriptor::U64AsF64,
            U128 => Descriptor::U128,
            F32 => Descriptor::F32,
            F64 => Descriptor::F64,
            BOOLEAN => Descriptor::Boolean,
            FUNCTION => Descriptor::Function(Box::new(Function::decode(data))),
            CLOSURE => Descriptor::Closure(Box::new(Closure::decode(data))),
            REF => Descriptor::Ref(Box::new(Descriptor::_decode(data, clamped))),
            REFMUT => Descriptor::RefMut(Box::new(Descriptor::_decode(data, clamped))),
            LONGREF => {
                // This descriptor basically just serves as a macro, where most things
                // become normal `Ref`s, but long refs to externrefs become owned.
                let contents = Descriptor::_decode(data, clamped);
                match contents {
                    Descriptor::Externref | Descriptor::NamedExternref(_) => contents,
                    _ => Descriptor::Ref(Box::new(contents)),
                }
            }
            SLICE => Descriptor::Slice(Box::new(Descriptor::_decode(data, clamped))),
            VECTOR => Descriptor::Vector(Box::new(Descriptor::_decode(data, clamped))),
            OPTIONAL => Descriptor::Option(Box::new(Descriptor::_decode(data, clamped))),
            RESULT => Descriptor::Result(Box::new(Descriptor::_decode(data, clamped))),
            CACHED_STRING => Descriptor::CachedString,
            STRING => Descriptor::String,
            EXTERNREF => Descriptor::Externref,
            ENUM => {
                let name = get_string(data);
                let hole = get(data);
                let unique_crate_identifier = get_string(data);
                Descriptor::Enum {
                    name,
                    hole,
                    unique_crate_identifier,
                }
            }
            STRING_ENUM => {
                let name = get_string(data);
                let variant_count = get(data);
                let invalid = variant_count;
                let hole = variant_count + 1;
                Descriptor::StringEnum {
                    name,
                    invalid,
                    hole,
                }
            }
            DYNAMIC_UNION => {
                let name = get_string(data);
                let type_count = get(data);
                let mut variant_types = Vec::new();
                for _ in 0..type_count {
                    variant_types.push(Descriptor::_decode(data, clamped));
                }
                Descriptor::DynamicUnion {
                    name,
                    variant_types,
                }
            }
            RUST_STRUCT => {
                let name = get_string(data);
                let unique_crate_identifier = get_string(data);
                Descriptor::RustStruct {
                    name,
                    unique_crate_identifier,
                }
            }
            NAMED_EXTERNREF => {
                let name = get_string(data);
                Descriptor::NamedExternref(name)
            }
            CHAR => Descriptor::Char,
            UNIT => Descriptor::Unit,
            CLAMPED => Descriptor::_decode(data, true),
            NONNULL => Descriptor::NonNull,
            RAW_POINTER => Descriptor::RawPointer,
            other => panic!("unknown descriptor: {other}"),
        }
    }

    /// Visit every struct/enum/externref type name embedded in this
    /// descriptor tree, so callers can rewrite names to their final JS
    /// identities (see `Context::resolve_descriptor` in `wit`). Rust types
    /// include their defining crate identifier; named externrefs do not.
    pub fn visit_named_types_mut<E>(
        &mut self,
        f: &mut impl FnMut(&mut String, Option<&str>) -> Result<(), E>,
    ) -> Result<(), E> {
        match self {
            Descriptor::Function(function) => function.visit_named_types_mut(f),
            Descriptor::Closure(closure) => closure.function.visit_named_types_mut(f),
            Descriptor::Ref(d)
            | Descriptor::RefMut(d)
            | Descriptor::Slice(d)
            | Descriptor::Vector(d)
            | Descriptor::Option(d)
            | Descriptor::Result(d) => d.visit_named_types_mut(f),
            // An externref has no defining crate, so a JS type whose name
            // matches an ambiguous all-`private` struct/enum name still hits
            // the ambiguity check even though it never refers to the Rust
            // type.
            Descriptor::NamedExternref(name) => f(name, None),
            Descriptor::Enum {
                name,
                unique_crate_identifier,
                ..
            }
            | Descriptor::RustStruct {
                name,
                unique_crate_identifier,
            } => f(name, Some(unique_crate_identifier)),
            Descriptor::DynamicUnion { variant_types, .. } => {
                for d in variant_types {
                    d.visit_named_types_mut(f)?;
                }
                Ok(())
            }
            _ => Ok(()),
        }
    }

    pub fn unwrap_function(self) -> Function {
        match self {
            Descriptor::Function(f) => *f,
            _ => panic!("not a function"),
        }
    }

    pub fn vector_kind(&self) -> Option<VectorKind> {
        let inner = match *self {
            Descriptor::String | Descriptor::CachedString => return Some(VectorKind::String),
            Descriptor::Vector(ref d) => &**d,
            Descriptor::Slice(ref d) => &**d,
            Descriptor::Ref(ref d) => match **d {
                Descriptor::Slice(ref d) => &**d,
                Descriptor::String | Descriptor::CachedString => return Some(VectorKind::String),
                _ => return None,
            },
            Descriptor::RefMut(ref d) => match **d {
                Descriptor::Slice(ref d) => &**d,
                _ => return None,
            },
            _ => return None,
        };
        match *inner {
            Descriptor::I8 => Some(VectorKind::I8),
            Descriptor::I16 => Some(VectorKind::I16),
            Descriptor::I32 => Some(VectorKind::I32),
            Descriptor::I64 | Descriptor::I64AsF64 => Some(VectorKind::I64),
            Descriptor::U8 => Some(VectorKind::U8),
            Descriptor::ClampedU8 => Some(VectorKind::ClampedU8),
            Descriptor::U16 => Some(VectorKind::U16),
            Descriptor::U32 => Some(VectorKind::U32),
            Descriptor::U64 | Descriptor::U64AsF64 => Some(VectorKind::U64),
            Descriptor::F32 => Some(VectorKind::F32),
            Descriptor::F64 => Some(VectorKind::F64),
            Descriptor::Externref => Some(VectorKind::Externref),
            Descriptor::NamedExternref(ref name)
            | Descriptor::RustStruct { ref name, .. }
            | Descriptor::Enum { ref name, .. } => Some(VectorKind::NamedExternref(name.clone())),
            _ => None,
        }
    }
}

fn get(a: &mut &[u32]) -> u32 {
    let ret = a[0];
    *a = &a[1..];
    ret
}

fn get_string(data: &mut &[u32]) -> String {
    (0..get(data))
        .map(|_| char::from_u32(get(data)).unwrap())
        .collect()
}

impl Closure {
    fn decode(data: &mut &[u32]) -> Closure {
        let [owned, mutable] = std::array::from_fn(|_| match get(data) {
            0 => false,
            1 => true,
            other => panic!("expected bool value, got {other}"),
        });
        assert_eq!(get(data), FUNCTION);
        Closure {
            owned,
            mutable,
            function: Function::decode(data),
        }
    }
}

#[test]
fn vector_kind_accepts_memory64_scalar_descriptors() {
    assert_eq!(
        Descriptor::Vector(Box::new(Descriptor::U64AsF64)).vector_kind(),
        Some(VectorKind::U64)
    );
    assert_eq!(
        Descriptor::Ref(Box::new(Descriptor::Slice(Box::new(Descriptor::I64AsF64)))).vector_kind(),
        Some(VectorKind::I64)
    );
}

impl Function {
    /// See [`Descriptor::visit_named_types_mut`].
    pub fn visit_named_types_mut<E>(
        &mut self,
        f: &mut impl FnMut(&mut String, Option<&str>) -> Result<(), E>,
    ) -> Result<(), E> {
        for d in &mut self.arguments {
            d.visit_named_types_mut(f)?;
        }
        self.ret.visit_named_types_mut(f)?;
        if let Some(d) = &mut self.inner_ret {
            d.visit_named_types_mut(f)?;
        }
        Ok(())
    }

    fn decode(data: &mut &[u32]) -> Function {
        let shim_idx = get(data);
        let arguments = (0..get(data))
            .map(|_| Descriptor::_decode(data, false))
            .collect::<Vec<_>>();
        Function {
            arguments,
            shim_idx,
            ret: Descriptor::_decode(data, false),
            inner_ret: Some(Descriptor::_decode(data, false)),
        }
    }
}

impl VectorKind {
    pub fn js_ty(&self) -> String {
        match *self {
            VectorKind::String => "string".to_string(),
            VectorKind::I8 => "Int8Array".to_string(),
            VectorKind::U8 => "Uint8Array".to_string(),
            VectorKind::ClampedU8 => "Uint8ClampedArray".to_string(),
            VectorKind::I16 => "Int16Array".to_string(),
            VectorKind::U16 => "Uint16Array".to_string(),
            VectorKind::I32 => "Int32Array".to_string(),
            VectorKind::U32 => "Uint32Array".to_string(),
            VectorKind::I64 => "BigInt64Array".to_string(),
            VectorKind::U64 => "BigUint64Array".to_string(),
            VectorKind::F32 => "Float32Array".to_string(),
            VectorKind::F64 => "Float64Array".to_string(),
            VectorKind::Externref => "any[]".to_string(),
            VectorKind::NamedExternref(ref name) => {
                if is_valid_ident(name.as_str()) {
                    format!("{name}[]")
                } else {
                    format!("({name})[]")
                }
            }
        }
    }

    pub fn size(&self) -> usize {
        match *self {
            VectorKind::String => 1,
            VectorKind::I8 => 1,
            VectorKind::U8 => 1,
            VectorKind::ClampedU8 => 1,
            VectorKind::I16 => 2,
            VectorKind::U16 => 2,
            VectorKind::I32 => 4,
            VectorKind::U32 => 4,
            VectorKind::I64 => 8,
            VectorKind::U64 => 8,
            VectorKind::F32 => 4,
            VectorKind::F64 => 8,
            VectorKind::Externref => 4,
            VectorKind::NamedExternref(_) => 4,
        }
    }
}