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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
//! Writes the AST into bytes representing WIT with its binary format.

use crate::ast::*;
use crate::interpreter::Instruction;

use it_to_bytes::ToBytes;

use std::io;
use std::io::Write;

/// Encode a `TypeKind` into bytes.
impl<W> ToBytes<W> for TypeKind
where
    W: Write,
{
    fn to_bytes(&self, writer: &mut W) -> io::Result<()> {
        match self {
            TypeKind::Function => 0x00_u8.to_bytes(writer),
            TypeKind::Record => 0x01_u8.to_bytes(writer),
        }
    }
}

/// Encode an `InterfaceKind` into bytes.
impl<W> ToBytes<W> for InterfaceKind
where
    W: Write,
{
    fn to_bytes(&self, writer: &mut W) -> io::Result<()> {
        match self {
            Self::Type => 0x00_u8.to_bytes(writer),
            Self::Import => 0x01_u8.to_bytes(writer),
            Self::Adapter => 0x02_u8.to_bytes(writer),
            Self::Export => 0x03_u8.to_bytes(writer),
            Self::Implementation => 0x04_u8.to_bytes(writer),
        }
    }
}

impl<W> ToBytes<W> for FunctionArg
where
    W: Write,
{
    fn to_bytes(&self, writer: &mut W) -> io::Result<()> {
        self.name.to_bytes(writer)?;
        self.ty.to_bytes(writer)
    }
}

/// Encode a `Type` into bytes.
///
/// Decoder is in `decoders::binary::types`.
impl<W> ToBytes<W> for Type
where
    W: Write,
{
    fn to_bytes(&self, writer: &mut W) -> io::Result<()> {
        match self {
            Type::Function {
                arguments,
                output_types,
            } => {
                TypeKind::Function.to_bytes(writer)?;
                arguments.to_bytes(writer)?;
                output_types.to_bytes(writer)?;
            }

            Type::Record(record_type) => {
                TypeKind::Record.to_bytes(writer)?;
                record_type.to_bytes(writer)?;
            }
        }

        Ok(())
    }
}

/// Encode an `Import` into bytes.
///
/// Decoder is in `decoders::binary::imports`.
impl<W> ToBytes<W> for Import<'_>
where
    W: Write,
{
    fn to_bytes(&self, writer: &mut W) -> io::Result<()> {
        self.namespace.to_bytes(writer)?;
        self.name.to_bytes(writer)?;
        (self.function_type as u64).to_bytes(writer)?;

        Ok(())
    }
}

/// Encode an `Adapter` into bytes.
///
/// Decoder is in `decoders::binary::adapters`.
impl<W> ToBytes<W> for Adapter
where
    W: Write,
{
    fn to_bytes(&self, writer: &mut W) -> io::Result<()> {
        (self.function_type as u64).to_bytes(writer)?;
        self.instructions.to_bytes(writer)?;

        Ok(())
    }
}

/// Encode an `Export` into bytes.
///
/// Decoder is in `decoders::binary::exports`.
impl<W> ToBytes<W> for Export<'_>
where
    W: Write,
{
    fn to_bytes(&self, writer: &mut W) -> io::Result<()> {
        self.name.to_bytes(writer)?;
        (self.function_type as u64).to_bytes(writer)?;

        Ok(())
    }
}

/// Encode an `Implementation` into bytes.
///
/// Decoder is in `decoders::binary::implementations`.
impl<W> ToBytes<W> for Implementation
where
    W: Write,
{
    fn to_bytes(&self, writer: &mut W) -> io::Result<()> {
        (self.core_function_type as u64).to_bytes(writer)?;
        (self.adapter_function_type as u64).to_bytes(writer)?;

        Ok(())
    }
}

/// Encode an `Interfaces` into bytes.
///
/// Decoder is `decoders::binary::parse`.
impl<W> ToBytes<W> for Interfaces<'_>
where
    W: Write,
{
    fn to_bytes(&self, writer: &mut W) -> io::Result<()> {
        if !self.types.is_empty() {
            InterfaceKind::Type.to_bytes(writer)?;
            self.types.to_bytes(writer)?;
        }

        if !self.imports.is_empty() {
            InterfaceKind::Import.to_bytes(writer)?;
            self.imports.to_bytes(writer)?;
        }

        if !self.adapters.is_empty() {
            InterfaceKind::Adapter.to_bytes(writer)?;
            self.adapters.to_bytes(writer)?;
        }

        if !self.exports.is_empty() {
            InterfaceKind::Export.to_bytes(writer)?;
            self.exports.to_bytes(writer)?;
        }

        if !self.implementations.is_empty() {
            InterfaceKind::Implementation.to_bytes(writer)?;
            self.implementations.to_bytes(writer)?;
        }

        Ok(())
    }
}

/// Encode an `Instruction` into bytes.
///
/// Decoder is `decoders::binary::instruction`.
impl<W> ToBytes<W> for Instruction
where
    W: Write,
{
    fn to_bytes(&self, writer: &mut W) -> io::Result<()> {
        match self {
            Instruction::ArgumentGet { index } => {
                0x00_u8.to_bytes(writer)?;
                (*index as u64).to_bytes(writer)?;
            }

            Instruction::CallCore { function_index } => {
                0x01_u8.to_bytes(writer)?;
                (*function_index as u64).to_bytes(writer)?;
            }

            Instruction::S8FromI32 => 0x02_u8.to_bytes(writer)?,
            Instruction::S8FromI64 => 0x03_u8.to_bytes(writer)?,
            Instruction::S16FromI32 => 0x04_u8.to_bytes(writer)?,
            Instruction::S16FromI64 => 0x05_u8.to_bytes(writer)?,
            Instruction::S32FromI32 => 0x06_u8.to_bytes(writer)?,
            Instruction::S32FromI64 => 0x07_u8.to_bytes(writer)?,
            Instruction::S64FromI32 => 0x08_u8.to_bytes(writer)?,
            Instruction::S64FromI64 => 0x09_u8.to_bytes(writer)?,
            Instruction::I32FromS8 => 0x0a_u8.to_bytes(writer)?,
            Instruction::I32FromS16 => 0x0b_u8.to_bytes(writer)?,
            Instruction::I32FromS32 => 0x0c_u8.to_bytes(writer)?,
            Instruction::I32FromS64 => 0x0d_u8.to_bytes(writer)?,
            Instruction::I64FromS8 => 0x0e_u8.to_bytes(writer)?,
            Instruction::I64FromS16 => 0x0f_u8.to_bytes(writer)?,
            Instruction::I64FromS32 => 0x10_u8.to_bytes(writer)?,
            Instruction::I64FromS64 => 0x11_u8.to_bytes(writer)?,
            Instruction::U8FromI32 => 0x12_u8.to_bytes(writer)?,
            Instruction::U8FromI64 => 0x13_u8.to_bytes(writer)?,
            Instruction::U16FromI32 => 0x14_u8.to_bytes(writer)?,
            Instruction::U16FromI64 => 0x15_u8.to_bytes(writer)?,
            Instruction::U32FromI32 => 0x16_u8.to_bytes(writer)?,
            Instruction::U32FromI64 => 0x17_u8.to_bytes(writer)?,
            Instruction::U64FromI32 => 0x18_u8.to_bytes(writer)?,
            Instruction::U64FromI64 => 0x19_u8.to_bytes(writer)?,
            Instruction::I32FromU8 => 0x1a_u8.to_bytes(writer)?,
            Instruction::I32FromU16 => 0x1b_u8.to_bytes(writer)?,
            Instruction::I32FromU32 => 0x1c_u8.to_bytes(writer)?,
            Instruction::I32FromU64 => 0x1d_u8.to_bytes(writer)?,
            Instruction::I64FromU8 => 0x1e_u8.to_bytes(writer)?,
            Instruction::I64FromU16 => 0x1f_u8.to_bytes(writer)?,
            Instruction::I64FromU32 => 0x20_u8.to_bytes(writer)?,
            Instruction::I64FromU64 => 0x21_u8.to_bytes(writer)?,

            Instruction::StringLiftMemory => 0x22_u8.to_bytes(writer)?,
            Instruction::StringLowerMemory => 0x23_u8.to_bytes(writer)?,
            Instruction::StringSize => 0x24_u8.to_bytes(writer)?,

            Instruction::ArrayLiftMemory { value_type } => {
                0x37_u8.to_bytes(writer)?;
                value_type.to_bytes(writer)?
            }
            Instruction::ArrayLowerMemory { value_type } => {
                0x38_u8.to_bytes(writer)?;
                value_type.to_bytes(writer)?
            }
            /*
            Instruction::ArraySize => 0x39_u8.to_bytes(writer)?,
            Instruction::RecordLift { type_index } => {
                0x25_u8.to_bytes(writer)?;
                (*type_index as u64).to_bytes(writer)?
            }
            Instruction::RecordLower { type_index } => {
                0x26_u8.to_bytes(writer)?;
                (*type_index as u64).to_bytes(writer)?
            }
             */
            Instruction::RecordLiftMemory {
                record_type_id: type_index,
            } => {
                0x3A_u8.to_bytes(writer)?;
                (*type_index as u64).to_bytes(writer)?
            }
            Instruction::RecordLowerMemory {
                record_type_id: type_index,
            } => {
                0x3B_u8.to_bytes(writer)?;
                (*type_index as u64).to_bytes(writer)?
            }
            Instruction::Dup => 0x34_u8.to_bytes(writer)?,
            Instruction::Swap2 => 0x35_u8.to_bytes(writer)?,
        }

        Ok(())
    }
}

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

    macro_rules! assert_to_bytes {
        ($expr:expr, $expected_output:expr) => {{
            let mut output = vec![];

            $expr.to_bytes(&mut output).expect(concat!(
                "Unable to encode the expression `",
                stringify!($expr),
                "` to bytes."
            ));

            assert_eq!(output.as_slice(), &$expected_output[..]);
        }};
    }

    #[test]
    fn test_u8() {
        assert_to_bytes!(0x01_u8, &[0x01]);
    }

    #[test]
    fn test_uleb_1_byte() {
        assert_to_bytes!(0x01_u64, &[0x01]);
    }

    #[test]
    fn test_uleb_3_bytes() {
        assert_to_bytes!(0x7ffc_u64, &[0xfc, 0xff, 0x01]);
    }

    // Examples from Figure 22 of [DWARF 4
    // standard](http://dwarfstd.org/doc/DWARF4.pdf).
    #[test]
    fn test_uleb_from_dward_standard() {
        assert_to_bytes!(2u64, &[2u8]);
        assert_to_bytes!(127u64, &[127u8]);
        assert_to_bytes!(128u64, &[0x80, 1u8]);
        assert_to_bytes!(129u64, &[1u8 | 0x80, 1]);
        assert_to_bytes!(130u64, &[2u8 | 0x80, 1]);
        assert_to_bytes!(12857u64, &[57u8 | 0x80, 100]);
    }

    #[test]
    fn test_empty_str() {
        assert_to_bytes!("", &[0x00]);
    }

    #[test]
    fn test_str() {
        assert_to_bytes!("abc", &[0x03, 0x61, 0x62, 0x63]);
    }

    #[test]
    fn test_empty_vec() {
        assert_to_bytes!(Vec::<u8>::new(), &[0x00]);
    }

    #[test]
    fn test_vec() {
        assert_to_bytes!(
            vec!["a", "b", "c"],
            &[
                0x03, // list of 3 items
                0x01, // string of 1 byte
                0x61, // "a"
                0x01, // string of 1 byte
                0x62, // "b"
                0x01, // string of 1 byte
                0x63, // "c"
            ]
        );
    }

    #[test]
    fn test_interface_type() {
        assert_to_bytes!(IType::S8, &[0x00]);
        assert_to_bytes!(IType::S16, &[0x01]);
        assert_to_bytes!(IType::S32, &[0x02]);
        assert_to_bytes!(IType::S64, &[0x03]);
        assert_to_bytes!(IType::U8, &[0x04]);
        assert_to_bytes!(IType::U16, &[0x05]);
        assert_to_bytes!(IType::U32, &[0x06]);
        assert_to_bytes!(IType::U64, &[0x07]);
        assert_to_bytes!(IType::F32, &[0x08]);
        assert_to_bytes!(IType::F64, &[0x09]);
        assert_to_bytes!(IType::String, &[0x0a]);
        assert_to_bytes!(IType::Anyref, &[0x0b]);
        assert_to_bytes!(IType::I32, &[0x0c]);
        assert_to_bytes!(IType::I64, &[0x0d]);
        assert_to_bytes!(
            IType::Record(RecordType {
                fields: vec1![IType::String]
            }),
            &[0x0e, 0x01, 0x0a]
        );
    }

    #[test]
    fn test_record_type() {
        assert_to_bytes!(
            RecordType {
                fields: vec1![IType::String]
            },
            &[
                0x01, // 1 field
                0x0a, // String
            ]
        );
        assert_to_bytes!(
            RecordType {
                fields: vec1![IType::String, IType::I32]
            },
            &[
                0x02, // 2 fields
                0x0a, // String
                0x0c, // I32
            ]
        );
        assert_to_bytes!(
            RecordType {
                fields: vec1![
                    IType::String,
                    IType::Record(RecordType {
                        fields: vec1![IType::I32, IType::I32],
                    }),
                    IType::F64,
                ],
            },
            &[
                0x03, // 3 fields
                0x0a, // String
                0x0e, // Record
                0x02, // 2 fields
                0x0c, // I32
                0x0c, // I32
                0x09, // F64
            ]
        );
    }

    #[test]
    fn test_interface_kind() {
        assert_to_bytes!(InterfaceKind::Type, &[0x00]);
        assert_to_bytes!(InterfaceKind::Import, &[0x01]);
        assert_to_bytes!(InterfaceKind::Adapter, &[0x02]);
        assert_to_bytes!(InterfaceKind::Export, &[0x03]);
        assert_to_bytes!(InterfaceKind::Implementation, &[0x04]);
    }

    #[test]
    fn test_export() {
        assert_to_bytes!(
            Export {
                name: "abc",
                function_type: 0,
            },
            &[
                0x03, // string of length 3
                0x61, // "a"
                0x62, // "b"
                0x63, // "c"
                0x00, // function type
            ]
        );
    }

    #[test]
    fn test_type_function() {
        assert_to_bytes!(
            Type::Function {
                inputs: vec![IType::I32, IType::I64],
                outputs: vec![IType::S32],
            },
            &[
                0x00, // function type
                0x02, // list of 2 items
                0x0c, // I32
                0x0d, // I64
                0x01, // list of 1 items
                0x02, // I64
            ]
        );
    }

    #[test]
    fn test_type_record() {
        assert_to_bytes!(
            Type::Record(RecordType {
                fields: vec1![IType::I32, IType::I64],
            }),
            &[
                0x01, // record type
                0x02, // list of 2 items
                0x0c, // I32
                0x0d, // I64
            ]
        );
    }

    #[test]
    fn test_import() {
        assert_to_bytes!(
            Import {
                namespace: "a",
                name: "b",
                function_type: 0,
            },
            &[
                0x01, // string of length 1
                0x61, // "a"
                0x01, // string of length 1
                0x62, // "b"
                0x00, // signature typr
            ]
        );
    }

    #[test]
    fn test_adapter() {
        assert_to_bytes!(
            Adapter {
                function_type: 0,
                instructions: vec![Instruction::ArgumentGet { index: 1 }],
            },
            &[
                0x00, // function type
                0x01, // list of 1 item
                0x00, 0x01, // ArgumentGet { index: 1 }
            ]
        );
    }

    #[test]
    fn test_interfaces() {
        assert_to_bytes!(
            Interfaces {
                types: vec![Type::Function {
                    inputs: vec![IType::S8],
                    outputs: vec![IType::S16],
                }],
                imports: vec![Import {
                    namespace: "ab",
                    name: "c",
                    function_type: 0,
                }],
                adapters: vec![Adapter {
                    function_type: 0,
                    instructions: vec![Instruction::ArgumentGet { index: 1 }],
                }],
                exports: vec![Export {
                    name: "ab",
                    function_type: 1,
                }],
                implementations: vec![Implementation {
                    core_function_type: 2,
                    adapter_function_type: 3,
                }],
            },
            &[
                0x00, // type section
                0x01, // 1 type
                0x00, // function type
                0x01, // list of 1 item
                0x00, // S8
                0x01, // list of 1 item
                0x01, // S16
                //
                0x01, // import section
                0x01, // 1 import
                0x02, // string of 2 bytes
                0x61, 0x62, // "a", "b"
                0x01, // string of 1 byte
                0x63, // "c"
                0x00, // signature type
                //
                0x02, // adapter section
                0x01, // 1 adapter
                0x00, // function type
                0x01, // list of 1 item
                0x00, 0x01, // ArgumentGet { index: 1 }
                //
                0x03, // export section
                0x01, // 1 export
                0x02, // string of 2 bytes
                0x61, 0x62, // "a", "b"
                0x01, // function type
                //
                0x04, // implementation section
                0x01, // 1 implementation
                0x02, // core function type
                0x03, // adapter function type
            ]
        );
    }

    #[test]
    fn test_instructions() {
        assert_to_bytes!(
            vec![
                Instruction::ArgumentGet { index: 1 },
                Instruction::CallCore { function_index: 1 },
                Instruction::S8FromI32,
                Instruction::S8FromI64,
                Instruction::S16FromI32,
                Instruction::S16FromI64,
                Instruction::S32FromI32,
                Instruction::S32FromI64,
                Instruction::S64FromI32,
                Instruction::S64FromI64,
                Instruction::I32FromS8,
                Instruction::I32FromS16,
                Instruction::I32FromS32,
                Instruction::I32FromS64,
                Instruction::I64FromS8,
                Instruction::I64FromS16,
                Instruction::I64FromS32,
                Instruction::I64FromS64,
                Instruction::U8FromI32,
                Instruction::U8FromI64,
                Instruction::U16FromI32,
                Instruction::U16FromI64,
                Instruction::U32FromI32,
                Instruction::U32FromI64,
                Instruction::U64FromI32,
                Instruction::U64FromI64,
                Instruction::I32FromU8,
                Instruction::I32FromU16,
                Instruction::I32FromU32,
                Instruction::I32FromU64,
                Instruction::I64FromU8,
                Instruction::I64FromU16,
                Instruction::I64FromU32,
                Instruction::I64FromU64,
                Instruction::StringLiftMemory,
                Instruction::StringLowerMemory,
                Instruction::StringSize,
                Instruction::RecordLift { type_index: 1 },
                Instruction::RecordLower { type_index: 1 },
            ],
            &[
                0x27, // list of 39 items
                0x00, 0x01, // ArgumentGet { index: 1 }
                0x01, 0x01, // CallCore { function_index: 1 }
                0x02, // S8FromI32
                0x03, // S8FromI64
                0x04, // S16FromI32
                0x05, // S16FromI64
                0x06, // S32FromI32
                0x07, // S32FromI64
                0x08, // S64FromI32
                0x09, // S64FromI64
                0x0a, // I32FromS8
                0x0b, // I32FromS16
                0x0c, // I32FromS32
                0x0d, // I32FromS64
                0x0e, // I64FromS8
                0x0f, // I64FromS16
                0x10, // I64FromS32
                0x11, // I64FromS64
                0x12, // U8FromI32
                0x13, // U8FromI64
                0x14, // U16FromI32
                0x15, // U16FromI64
                0x16, // U32FromI32
                0x17, // U32FromI64
                0x18, // U64FromI32
                0x19, // U64FromI64
                0x1a, // I32FromU8
                0x1b, // I32FromU16
                0x1c, // I32FromU32
                0x1d, // I32FromU64
                0x1e, // I64FromU8
                0x1f, // I64FromU16
                0x20, // I64FromU32
                0x21, // I64FromU64
                0x22, // StringLiftMemory
                0x23, // StringLowerMemory
                0x24, // StringSize
                0x025, 0x01, // RecordLift { type_index: 1 }
                0x026, 0x01, // RecordLower { type_index: 1 }
            ]
        );
    }
}