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
//! Encoders for WebAssembly components.
//!
//! This is an implementation of the in-progress [component
//! model proposal](https://github.com/WebAssembly/component-model/).

use crate::{encoders, GlobalType, MemoryType, RawSection, Section, TableType};

mod adapters;
mod aliases;
mod exports;
mod functions;
mod imports;
mod instances;
mod modules;
mod types;

pub use adapters::*;
pub use aliases::*;
pub use exports::*;
pub use functions::*;
pub use imports::*;
pub use instances::*;
pub use modules::*;
pub use types::*;

const INDEX_REF_INSTANCE: u8 = 0x00;
const INDEX_REF_MODULE: u8 = 0x01;
const INDEX_REF_FUNCTION: u8 = 0x02;
const INDEX_REF_TABLE: u8 = 0x03;
const INDEX_REF_MEMORY: u8 = 0x04;
const INDEX_REF_GLOBAL: u8 = 0x05;

const TYPE_REF_INSTANCE: u8 = 0x00;
const TYPE_REF_MODULE: u8 = 0x01;
const TYPE_REF_FUNCTION: u8 = 0x02;
const TYPE_REF_TABLE: u8 = 0x03;
const TYPE_REF_MEMORY: u8 = 0x04;
const TYPE_REF_GLOBAL: u8 = 0x05;
const TYPE_REF_ADAPTER_FUNCTION: u8 = 0x06;

const CANONICAL_OPTION_UTF8: u8 = 0x00;
const CANONICAL_OPTION_UTF16: u8 = 0x01;
const CANONICAL_OPTION_COMPACT_UTF16: u8 = 0x02;
const CANONICAL_OPTION_WITH_REALLOC: u8 = 0x03;
const CANONICAL_OPTION_WITH_FREE: u8 = 0x04;

/// A WebAssembly component section.
///
/// This trait marks sections that can be written to a `Component`.
///
/// Various builders defined in this crate already implement this trait, but you
/// can also implement it yourself for your own custom section builders, or use
/// `RawSection` to use a bunch of raw bytes as a section.
pub trait ComponentSection {
    /// This section's id.
    ///
    /// See `SectionId` for known section ids.
    fn id(&self) -> u8;

    /// Write this section's data and data length prefix into the given sink.
    fn encode<S>(&self, sink: &mut S)
    where
        S: Extend<u8>;
}

impl ComponentSection for RawSection<'_> {
    fn id(&self) -> u8 {
        self.id
    }

    fn encode<S>(&self, sink: &mut S)
    where
        S: Extend<u8>,
    {
        <Self as Section>::encode(self, sink);
    }
}

/// Represents a WebAssembly component that is being encoded.
#[derive(Clone, Debug)]
pub struct Component {
    bytes: Vec<u8>,
}

impl Component {
    /// Begin writing a new `Component`.
    pub fn new() -> Self {
        Self {
            bytes: vec![
                0x00, 0x61, 0x73, 0x6D, // magic (`\0asm`)
                0x0a, 0x00, 0x02, 0x00, // version
            ],
        }
    }

    /// Finish writing this component and extract ownership of the encoded bytes.
    pub fn finish(self) -> Vec<u8> {
        self.bytes
    }

    /// Write a section into this component.
    pub fn section(&mut self, section: &impl ComponentSection) -> &mut Self {
        self.bytes.push(section.id());
        section.encode(&mut self.bytes);
        self
    }
}

impl Default for Component {
    fn default() -> Self {
        Self::new()
    }
}

/// Known component section IDs.
///
/// Useful for implementing the `ComponentSection` trait, or for setting
/// `RawSection::id`.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
#[repr(u8)]
pub enum SectionId {
    /// The section is a custom section.
    Custom = 0,
    /// The section is a type section.
    Type = 1,
    /// The section is an import section.
    Import = 2,
    /// The section is a module section.
    Module = 3,
    /// The section is an instance section.
    Instance = 4,
    /// The section is an alias section.
    Alias = 5,
    /// The section is an export section.
    Export = 6,
    /// The section is a function section.
    Function = 7,
    /// The section is an adapter function section.
    AdapterFunction = 8,
}

impl From<SectionId> for u8 {
    #[inline]
    fn from(id: SectionId) -> u8 {
        id as u8
    }
}

/// Represents a reference to an index in a WebAssembly section.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum IndexRef {
    /// The reference is to an instance in the instance section.
    Instance(u32),
    /// The reference is to a module in the module section.
    Module(u32),
    /// The reference is to a function in the function section.
    Function(u32),
    /// The reference is to a table in the table section.
    Table(u32),
    /// The reference is to a memory in the memory section.
    Memory(u32),
    /// The reference is to a global in the global section.
    Global(u32),
}

impl IndexRef {
    pub(crate) fn encode(&self, bytes: &mut Vec<u8>) {
        match self {
            IndexRef::Instance(index) => {
                bytes.push(INDEX_REF_INSTANCE);
                bytes.extend(encoders::u32(*index));
            }
            IndexRef::Module(index) => {
                bytes.push(INDEX_REF_MODULE);
                bytes.extend(encoders::u32(*index));
            }
            IndexRef::Function(index) => {
                bytes.push(INDEX_REF_FUNCTION);
                bytes.extend(encoders::u32(*index));
            }
            IndexRef::Table(index) => {
                bytes.push(INDEX_REF_TABLE);
                bytes.extend(encoders::u32(*index));
            }
            IndexRef::Memory(index) => {
                bytes.push(INDEX_REF_MEMORY);
                bytes.extend(encoders::u32(*index));
            }
            IndexRef::Global(index) => {
                bytes.push(INDEX_REF_GLOBAL);
                bytes.extend(encoders::u32(*index));
            }
        }
    }
}

/// Represents a reference to a type definition.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TypeRef {
    /// The definition is an instance.
    ///
    /// The value is an index in the types index space.
    /// The index must be to an instance type.
    Instance(u32),
    /// The definition is a module.
    ///
    /// The value is an index in the types index space.
    /// The index must be to a module type.
    Module(u32),
    /// The definition is a core wasm function.
    ///
    /// The value is an index in the types index space.
    /// The index must be to a function type.
    Function(u32),
    /// The definition is a core wasm table.
    Table(TableType),
    /// The definition is a core wasm memory.
    Memory(MemoryType),
    /// The definition is a core wasm global.
    Global(GlobalType),
    /// The definition is an adapter function.
    ///
    /// The value is an index in the types index space.
    /// The index must be to an adapter function type.
    AdapterFunction(u32),
}

impl TypeRef {
    pub(crate) fn encode(&self, bytes: &mut Vec<u8>) {
        match self {
            Self::Instance(index) => {
                bytes.push(TYPE_REF_INSTANCE);
                bytes.extend(encoders::u32(*index));
            }
            Self::Module(index) => {
                bytes.push(TYPE_REF_MODULE);
                bytes.extend(encoders::u32(*index));
            }
            Self::Function(index) => {
                bytes.push(TYPE_REF_FUNCTION);
                bytes.extend(encoders::u32(*index));
            }
            Self::Table(ty) => {
                bytes.push(TYPE_REF_TABLE);
                ty.encode(bytes);
            }
            Self::Memory(ty) => {
                bytes.push(TYPE_REF_MEMORY);
                ty.encode(bytes);
            }
            Self::Global(ty) => {
                bytes.push(TYPE_REF_GLOBAL);
                ty.encode(bytes);
            }
            Self::AdapterFunction(index) => {
                bytes.push(TYPE_REF_ADAPTER_FUNCTION);
                bytes.extend(encoders::u32(*index));
            }
        }
    }
}

impl From<TableType> for TypeRef {
    fn from(t: TableType) -> Self {
        Self::Table(t)
    }
}

impl From<MemoryType> for TypeRef {
    fn from(t: MemoryType) -> Self {
        Self::Memory(t)
    }
}

impl From<GlobalType> for TypeRef {
    fn from(t: GlobalType) -> Self {
        Self::Global(t)
    }
}

/// Represents options for canonical functions and adapter functions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CanonicalOption {
    /// The string types in the function signature are UTF-8 encoded.
    UTF8,
    /// The string types in the function signature are UTF-16 encoded.
    UTF16,
    /// The string types in the function signature are compact UTF-16 encoded.
    CompactUTF16,
    /// Specifies the function to use to reallocate memory.
    WithRealloc(u32),
    /// Specifies the function to use to free memory.
    WithFree(u32),
}

impl CanonicalOption {
    pub(crate) fn encode(&self, bytes: &mut Vec<u8>) {
        match self {
            Self::UTF8 => bytes.push(CANONICAL_OPTION_UTF8),
            Self::UTF16 => bytes.push(CANONICAL_OPTION_UTF16),
            Self::CompactUTF16 => bytes.push(CANONICAL_OPTION_COMPACT_UTF16),
            Self::WithRealloc(index) => {
                bytes.push(CANONICAL_OPTION_WITH_REALLOC);
                bytes.extend(encoders::u32(*index));
            }
            Self::WithFree(index) => {
                bytes.push(CANONICAL_OPTION_WITH_FREE);
                bytes.extend(encoders::u32(*index));
            }
        }
    }
}

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

    #[test]
    fn it_encodes_an_empty_component() {
        let bytes = Component::new().finish();
        assert_eq!(
            bytes,
            [0x00, 'a' as u8, 's' as u8, 'm' as u8, 0x0a, 0x00, 0x02, 0x00]
        );
    }
}