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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
//! Parse the WIT binary representation into an [AST](crate::ast).

use crate::IRecordFieldType;
use crate::IRecordType;
use crate::IType;
use crate::{ast::*, interpreter::Instruction};
use nom::{
    error::{make_error, ErrorKind, ParseError},
    Err, IResult,
};
use std::{convert::TryFrom, str, sync::Arc};

/// Parse a type kind.
impl TryFrom<u8> for TypeKind {
    type Error = &'static str;

    fn try_from(code: u8) -> Result<Self, Self::Error> {
        Ok(match code {
            0x00 => Self::Function,
            0x01 => Self::Record,
            _ => return Err("Unknown type kind code."),
        })
    }
}

/// Parse an interface kind.
impl TryFrom<u8> for InterfaceKind {
    type Error = &'static str;

    fn try_from(code: u8) -> Result<Self, Self::Error> {
        Ok(match code {
            0x00 => Self::Type,
            0x01 => Self::Import,
            0x02 => Self::Adapter,
            0x03 => Self::Export,
            0x04 => Self::Implementation,
            0x05 => Self::Version,
            _ => return Err("Unknown interface kind code."),
        })
    }
}

/// Parse a byte.
fn byte<'input, E: ParseError<&'input [u8]>>(input: &'input [u8]) -> IResult<&'input [u8], u8, E> {
    if input.is_empty() {
        return Err(Err::Error(make_error(input, ErrorKind::Eof)));
    }

    Ok((&input[1..], input[0]))
}

/// Parse an unsigned Little Endian Based (LEB) with value no larger
/// than a 64-bits number. Read
/// [LEB128](https://en.wikipedia.org/wiki/LEB128) to learn more, or
/// the Variable Length Data Section from the [DWARF 4
/// standard](http://dwarfstd.org/doc/DWARF4.pdf).
fn uleb<'input, E: ParseError<&'input [u8]>>(input: &'input [u8]) -> IResult<&'input [u8], u64, E> {
    if input.is_empty() {
        return Err(Err::Error(make_error(input, ErrorKind::Eof)));
    }

    let (output, bytes) = match input.iter().position(|&byte| byte & 0x80 == 0) {
        Some(length) if length <= 8 => (&input[length + 1..], &input[..=length]),
        Some(_) => return Err(Err::Error(make_error(input, ErrorKind::TooLarge))),
        None => return Err(Err::Error(make_error(input, ErrorKind::Eof))),
    };

    Ok((
        output,
        bytes
            .iter()
            .rev()
            .fold(0, |acc, byte| (acc << 7) | u64::from(byte & 0x7f)),
    ))
}

fn record_field<'input, E: ParseError<&'input [u8]>>(
    mut input: &'input [u8],
) -> IResult<&'input [u8], IRecordFieldType, E> {
    if input.is_empty() {
        return Err(Err::Error(make_error(input, ErrorKind::Eof)));
    }

    consume!((input, name) = owned_string(input)?);
    consume!((input, ty) = ty(input)?);

    Ok((input, IRecordFieldType { name, ty }))
}

fn function_arg<'input, E: ParseError<&'input [u8]>>(
    mut input: &'input [u8],
) -> IResult<&'input [u8], FunctionArg, E> {
    if input.is_empty() {
        return Err(Err::Error(make_error(input, ErrorKind::Eof)));
    }

    consume!((input, name) = owned_string(input)?);
    consume!((input, ty) = ty(input)?);

    Ok((input, FunctionArg { name, ty }))
}

/// Parse an interface type.
fn ty<'input, E: ParseError<&'input [u8]>>(
    mut input: &'input [u8],
) -> IResult<&'input [u8], IType, E> {
    if input.is_empty() {
        return Err(Err::Error(make_error(input, ErrorKind::Eof)));
    }

    consume!((input, opcode) = byte(input)?);

    let ty = match opcode {
        0x0b => IType::Boolean,
        0x00 => IType::S8,
        0x01 => IType::S16,
        0x02 => IType::S32,
        0x03 => IType::S64,
        0x04 => IType::U8,
        0x05 => IType::U16,
        0x06 => IType::U32,
        0x07 => IType::U64,
        0x08 => IType::F32,
        0x09 => IType::F64,
        0x0a => IType::String,
        0x3c => IType::ByteArray,
        0x36 => {
            consume!((input, array_value_type) = ty(input)?);

            IType::Array(Box::new(array_value_type))
        }
        0x0c => IType::I32,
        0x0d => IType::I64,
        0x0e => {
            consume!((input, record_id) = uleb(input)?);

            IType::Record(record_id)
        }
        _ => return Err(Err::Error(make_error(input, ErrorKind::Alt))),
    };

    Ok((input, ty))
}

/// Parse a record type.
fn record_type<'input, E: ParseError<&'input [u8]>>(
    input: &'input [u8],
) -> IResult<&'input [u8], IRecordType, E> {
    use crate::NEVec;

    let (output, name) = owned_string(input)?;
    let (output, fields) = list(output, record_field)?;

    Ok((
        output,
        IRecordType {
            name,
            fields: NEVec::new(fields).expect("Record must have at least one field, zero given."),
        },
    ))
}

/// Parse a UTF-8 string into &str.
fn string<'input, E: ParseError<&'input [u8]>>(
    input: &'input [u8],
) -> IResult<&'input [u8], &'input str, E> {
    if input.is_empty() {
        return Err(Err::Error(make_error(input, ErrorKind::Eof)));
    }

    let length = input[0] as usize;
    let input = &input[1..];

    if input.len() < length {
        return Err(Err::Error(make_error(input, ErrorKind::Eof)));
    }

    Ok((
        &input[length..],
        str::from_utf8(&input[..length])
            .map_err(|_| Err::Error(make_error(input, ErrorKind::Char)))?,
    ))
}

/// Parse a UTF-8 string into String.
fn owned_string<'input, E: ParseError<&'input [u8]>>(
    input: &'input [u8],
) -> IResult<&'input [u8], String, E> {
    if input.is_empty() {
        return Err(Err::Error(make_error(input, ErrorKind::Eof)));
    }

    let length = input[0] as usize;
    let input = &input[1..];

    if input.len() < length {
        return Err(Err::Error(make_error(input, ErrorKind::Eof)));
    }

    Ok((
        &input[length..],
        String::from_utf8(input[..length].to_vec())
            .map_err(|_| Err::Error(make_error(input, ErrorKind::Char)))?,
    ))
}

/// Parse a list, with an item parser.
#[allow(clippy::type_complexity)]
fn list<'input, I, E: ParseError<&'input [u8]>>(
    input: &'input [u8],
    item_parser: fn(&'input [u8]) -> IResult<&'input [u8], I, E>,
) -> IResult<&'input [u8], Vec<I>, E> {
    if input.is_empty() {
        return Err(Err::Error(make_error(input, ErrorKind::Eof)));
    }

    let length = input[0] as usize;
    let mut input = &input[1..];

    if input.len() < length {
        return Err(Err::Error(make_error(input, ErrorKind::Eof)));
    }

    let mut items = Vec::with_capacity(length as usize);

    for _ in 0..length {
        consume!((input, item) = item_parser(input)?);
        items.push(item);
    }

    Ok((input, items))
}

/// Parse an instruction with its arguments.
fn instruction<'input, E: ParseError<&'input [u8]>>(
    input: &'input [u8],
) -> IResult<&'input [u8], Instruction, E> {
    let (mut input, opcode) = byte(input)?;

    Ok(match opcode {
        0x00 => {
            consume!((input, argument_0) = uleb(input)?);

            (
                input,
                Instruction::ArgumentGet {
                    index: argument_0 as u32,
                },
            )
        }

        0x01 => {
            consume!((input, argument_0) = uleb(input)?);

            (
                input,
                Instruction::CallCore {
                    function_index: argument_0 as u32,
                },
            )
        }

        0x02 => (input, Instruction::S8FromI32),
        0x03 => (input, Instruction::S8FromI64),
        0x04 => (input, Instruction::S16FromI32),
        0x05 => (input, Instruction::S16FromI64),
        0x06 => (input, Instruction::S32FromI32),
        0x07 => (input, Instruction::S32FromI64),
        0x08 => (input, Instruction::S64FromI32),
        0x09 => (input, Instruction::S64FromI64),
        0x0a => (input, Instruction::I32FromS8),
        0x0b => (input, Instruction::I32FromS16),
        0x0c => (input, Instruction::I32FromS32),
        0x0d => (input, Instruction::I32FromS64),
        0x0e => (input, Instruction::I64FromS8),
        0x0f => (input, Instruction::I64FromS16),
        0x10 => (input, Instruction::I64FromS32),
        0x11 => (input, Instruction::I64FromS64),
        0x12 => (input, Instruction::U8FromI32),
        0x13 => (input, Instruction::U8FromI64),
        0x14 => (input, Instruction::U16FromI32),
        0x15 => (input, Instruction::U16FromI64),
        0x16 => (input, Instruction::U32FromI32),
        0x17 => (input, Instruction::U32FromI64),
        0x18 => (input, Instruction::U64FromI32),
        0x19 => (input, Instruction::U64FromI64),
        0x1a => (input, Instruction::I32FromU8),
        0x1b => (input, Instruction::I32FromU16),
        0x1c => (input, Instruction::I32FromU32),
        0x1d => (input, Instruction::I32FromU64),
        0x1e => (input, Instruction::I64FromU8),
        0x1f => (input, Instruction::I64FromU16),
        0x20 => (input, Instruction::I64FromU32),
        0x21 => (input, Instruction::I64FromU64),

        0x22 => (input, Instruction::StringLiftMemory),
        0x23 => (input, Instruction::StringLowerMemory),
        0x24 => (input, Instruction::StringSize),

        0x43 => (input, Instruction::ByteArrayLiftMemory),
        0x44 => (input, Instruction::ByteArrayLowerMemory),
        0x45 => (input, Instruction::ByteArraySize),

        0x37 => {
            consume!((input, value_type) = ty(input)?);

            (input, Instruction::ArrayLiftMemory { value_type })
        }
        0x38 => {
            consume!((input, value_type) = ty(input)?);

            (input, Instruction::ArrayLowerMemory { value_type })
        }
        0x3A => {
            consume!((input, record_type_id) = uleb(input)?);

            (
                input,
                Instruction::RecordLiftMemory {
                    record_type_id: record_type_id as u32,
                },
            )
        }
        0x3B => {
            consume!((input, record_type_id) = uleb(input)?);

            (
                input,
                Instruction::RecordLowerMemory {
                    record_type_id: record_type_id as u32,
                },
            )
        }

        0x34 => (input, Instruction::Dup),

        0x35 => (input, Instruction::Swap2),

        0x3E => (input, Instruction::BoolFromI32),
        0x3F => (input, Instruction::I32FromBool),

        0x40 => {
            consume!((input, value) = uleb(input)?);

            (
                input,
                Instruction::PushI32 {
                    value: value as i32,
                },
            )
        }

        0x41 => {
            consume!((input, value) = uleb(input)?);

            (
                input,
                Instruction::PushI64 {
                    value: value as i64,
                },
            )
        }

        _ => return Err(Err::Error(make_error(input, ErrorKind::Alt))),
    })
}

/// Parse a list of types.
fn types<'input, E: ParseError<&'input [u8]>>(
    mut input: &'input [u8],
) -> IResult<&'input [u8], Vec<Type>, E> {
    consume!((input, number_of_types) = uleb(input)?);

    let mut types = Vec::with_capacity(number_of_types as usize);

    for _ in 0..number_of_types {
        consume!((input, type_kind) = byte(input)?);

        let type_kind = TypeKind::try_from(type_kind)
            .map_err(|_| Err::Error(make_error(input, ErrorKind::Alt)))?;

        match type_kind {
            TypeKind::Function => {
                consume!((input, arguments) = list(input, function_arg)?);
                consume!((input, output_types) = list(input, ty)?);

                types.push(Type::Function {
                    arguments: Arc::new(arguments),
                    output_types: Arc::new(output_types),
                });
            }

            TypeKind::Record => {
                consume!((input, record_type) = record_type(input)?);

                types.push(Type::Record(Arc::new(record_type)));
            }
        }
    }

    Ok((input, types))
}

/// Parse a list of imports.
fn imports<'input, E: ParseError<&'input [u8]>>(
    mut input: &'input [u8],
) -> IResult<&'input [u8], Vec<Import>, E> {
    consume!((input, number_of_imports) = uleb(input)?);

    let mut imports = Vec::with_capacity(number_of_imports as usize);

    for _ in 0..number_of_imports {
        consume!((input, namespace) = string(input)?);
        consume!((input, name) = string(input)?);
        consume!((input, function_type) = uleb(input)?);

        imports.push(Import {
            namespace,
            name,
            function_type: function_type as u32,
        });
    }

    Ok((input, imports))
}

/// Parse a list of adapters.
fn adapters<'input, E: ParseError<&'input [u8]>>(
    mut input: &'input [u8],
) -> IResult<&'input [u8], Vec<Adapter>, E> {
    consume!((input, number_of_adapters) = uleb(input)?);

    let mut adapters = Vec::with_capacity(number_of_adapters as usize);

    for _ in 0..number_of_adapters {
        consume!((input, function_type) = uleb(input)?);
        consume!((input, instructions) = list(input, instruction)?);

        adapters.push(Adapter {
            function_type: function_type as u32,
            instructions,
        });
    }

    Ok((input, adapters))
}

/// Parse a list of exports.
fn exports<'input, E: ParseError<&'input [u8]>>(
    mut input: &'input [u8],
) -> IResult<&'input [u8], Vec<Export>, E> {
    consume!((input, number_of_exports) = uleb(input)?);

    let mut exports = Vec::with_capacity(number_of_exports as usize);

    for _ in 0..number_of_exports {
        consume!((input, name) = string(input)?);
        consume!((input, function_type) = uleb(input)?);

        exports.push(Export {
            name,
            function_type: function_type as u32,
        });
    }

    Ok((input, exports))
}

/// Parse a list of implementations.
fn implementations<'input, E: ParseError<&'input [u8]>>(
    mut input: &'input [u8],
) -> IResult<&'input [u8], Vec<Implementation>, E> {
    consume!((input, number_of_implementations) = uleb(input)?);

    let mut implementations = Vec::with_capacity(number_of_implementations as usize);

    for _ in 0..number_of_implementations {
        consume!((input, core_function_type) = uleb(input)?);
        consume!((input, adapter_function_type) = uleb(input)?);

        implementations.push(Implementation {
            core_function_type: core_function_type as u32,
            adapter_function_type: adapter_function_type as u32,
        });
    }

    Ok((input, implementations))
}

/// Parse complete interfaces.
fn interfaces<'input, E: ParseError<&'input [u8]>>(
    bytes: &'input [u8],
) -> IResult<&'input [u8], Interfaces, E> {
    let mut input = bytes;

    let mut all_versions = vec![];
    let mut all_types = vec![];
    let mut all_imports = vec![];
    let mut all_adapters = vec![];
    let mut all_exports = vec![];
    let mut all_implementations = vec![];

    while !input.is_empty() {
        consume!((input, interface_kind) = byte(input)?);

        let interface_kind = InterfaceKind::try_from(interface_kind)
            .map_err(|_| Err::Error(make_error(input, ErrorKind::Alt)))?;

        match interface_kind {
            InterfaceKind::Version => {
                consume!((input, new_version) = string(input)?);
                all_versions.push(new_version);
            }
            InterfaceKind::Type => {
                consume!((input, mut new_types) = types(input)?);
                all_types.append(&mut new_types);
            }

            InterfaceKind::Import => {
                consume!((input, mut new_imports) = imports(input)?);
                all_imports.append(&mut new_imports);
            }

            InterfaceKind::Adapter => {
                consume!((input, mut new_adapters) = adapters(input)?);
                all_adapters.append(&mut new_adapters);
            }

            InterfaceKind::Export => {
                consume!((input, mut new_exports) = exports(input)?);
                all_exports.append(&mut new_exports);
            }

            InterfaceKind::Implementation => {
                consume!((input, mut new_implementations) = implementations(input)?);
                all_implementations.append(&mut new_implementations)
            }
        }
    }

    let version = try_into_version(all_versions).map_err(|e| Err::Error(make_error(input, e)))?;

    Ok((
        input,
        Interfaces {
            version,
            types: all_types,
            imports: all_imports,
            adapters: all_adapters,
            exports: all_exports,
            implementations: all_implementations,
        },
    ))
}

fn try_into_version(versions: Vec<&str>) -> Result<semver::Version, ErrorKind> {
    use std::str::FromStr;

    if versions.is_empty() {
        return Err(ErrorKind::NoneOf);
    }

    if versions.len() != 1 {
        return Err(ErrorKind::Many0);
    }

    let version = semver::Version::from_str(&versions[0]).map_err(|_| ErrorKind::IsNot)?;

    Ok(version)
}

/// Parse a sequence of bytes, expecting it to be a valid WIT binary
/// representation, into an [`Interfaces`](crate::ast::Interfaces)
/// structure.
///
/// # Example
///
/// ```rust
/// use wasmer_interface_types::{
///     ast::{Adapter, Export, Implementation, Import, Interfaces, Type},
///     decoders::binary::parse,
///     interpreter::Instruction,
///     types::IType,
/// };
///
/// let input = &[
///     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
/// ];
/// let output = Ok((
///     &[] as &[u8],
///     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,
///         }],
///     },
/// ));
///
/// assert_eq!(parse::<()>(input), output);
/// ```
pub fn parse<'input, E: ParseError<&'input [u8]>>(
    bytes: &'input [u8],
) -> IResult<&'input [u8], Interfaces, E> {
    interfaces(bytes)
}

#[cfg(test)]
mod tests {
    use super::*;
    use nom::{error, Err};

    #[test]
    fn test_byte() {
        let input = &[0x01, 0x02, 0x03];
        let output = Ok((&[0x02, 0x03][..], 0x01u8));

        assert_eq!(byte::<()>(input), output);
    }

    #[test]
    fn test_uleb_1_byte() {
        let input = &[0x01, 0x02, 0x03];
        let output = Ok((&[0x02, 0x03][..], 0x01u64));

        assert_eq!(uleb::<()>(input), output);
    }

    #[test]
    fn test_uleb_3_bytes() {
        let input = &[0xfc, 0xff, 0x01, 0x02];
        let output = Ok((&[0x02][..], 0x7ffcu64));

        assert_eq!(uleb::<()>(input), output);
    }

    // Examples from Figure 22 of [DWARF 4
    // standard](http://dwarfstd.org/doc/DWARF4.pdf).
    #[test]
    fn test_uleb_from_dwarf_standard() {
        macro_rules! assert_uleb {
            ($to_parse:expr => $expected_result:expr) => {
                assert_eq!(uleb::<()>($to_parse), Ok((&[][..], $expected_result)));
            };
        }

        assert_uleb!(&[2u8] => 2u64);
        assert_uleb!(&[127u8] => 127u64);
        assert_uleb!(&[0x80, 1u8] => 128u64);
        assert_uleb!(&[1u8 | 0x80, 1] => 129u64);
        assert_uleb!(&[2u8 | 0x80, 1] => 130u64);
        assert_uleb!(&[57u8 | 0x80, 100] => 12857u64);
    }

    #[test]
    fn test_uleb_eof() {
        let input = &[0x80];

        assert_eq!(
            uleb::<(&[u8], error::ErrorKind)>(input),
            Err(Err::Error((&input[..], error::ErrorKind::Eof))),
        );
    }

    #[test]
    fn test_uleb_overflow() {
        let input = &[
            0x01 | 0x80,
            0x02 | 0x80,
            0x03 | 0x80,
            0x04 | 0x80,
            0x05 | 0x80,
            0x06 | 0x80,
            0x07 | 0x80,
            0x08 | 0x80,
            0x09 | 0x80,
            0x0a,
        ];

        assert_eq!(
            uleb::<(&[u8], error::ErrorKind)>(input),
            Err(Err::Error((&input[..], error::ErrorKind::TooLarge))),
        );
    }

    #[test]
    fn test_ty() {
        let input = &[
            0x0f, // list of 15 items
            0x00, // S8
            0x01, // S16
            0x02, // S32
            0x03, // S64
            0x04, // U8
            0x05, // U16
            0x06, // U32
            0x07, // U64
            0x08, // F32
            0x09, // F64
            0x0a, // String
            0x0b, // Anyref
            0x0c, // I32
            0x0d, // I64
            0x0e, 0x01, 0x02, // Record
            0x01,
        ];
        let output = Ok((
            &[0x01][..],
            vec![
                IType::S8,
                IType::S16,
                IType::S32,
                IType::S64,
                IType::U8,
                IType::U16,
                IType::U32,
                IType::U64,
                IType::F32,
                IType::F64,
                IType::String,
                IType::Anyref,
                IType::I32,
                IType::I64,
                IType::Record(RecordType {
                    fields: vec1![IType::S32],
                }),
            ],
        ));

        assert_eq!(list::<_, ()>(input, ty), output);
    }

    #[test]
    fn test_record_type() {
        let input = &[
            0x03, // list of 3 items
            0x01, // 1 field
            0x0a, // String
            0x02, // 2 fields
            0x0a, // String
            0x0c, // I32
            0x03, // 3 fields
            0x0a, // String
            0x0e, // Record
            0x02, // 2 fields
            0x0c, // I32
            0x0c, // I32
            0x09, // F64
            0x01,
        ];
        let output = Ok((
            &[0x01][..],
            vec![
                RecordType {
                    fields: vec1![IType::String],
                },
                RecordType {
                    fields: vec1![IType::String, IType::I32],
                },
                RecordType {
                    fields: vec1![
                        IType::String,
                        IType::Record(RecordType {
                            fields: vec1![IType::I32, IType::I32],
                        }),
                        IType::F64,
                    ],
                },
            ],
        ));

        assert_eq!(list::<_, ()>(input, record_type), output);
    }

    #[test]
    fn test_string() {
        let input = &[
            0x03, // string of 3 bytes
            0x61, // "a"
            0x62, // "b"
            0x63, // "c"
            0x64, 0x65,
        ];
        let output = Ok((&[0x64, 0x65][..], "abc"));

        assert_eq!(string::<()>(input), output);
    }

    #[test]
    fn test_list() {
        let input = &[
            0x02, // list of 2 items
            0x01, // string of 1 byte
            0x61, // "a"
            0x02, // string of 2 bytes
            0x62, // "b"
            0x63, // "c"
            0x07,
        ];
        let output = Ok((&[0x07][..], vec!["a", "bc"]));

        assert_eq!(list::<_, ()>(input, string), output);
    }

    #[test]
    fn test_instructions() {
        let input = &[
            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
            0x25, 0x01, // RecordLift { type_index: 1 },
            0x26, 0x01, // RecordLower { type_index: 1 },
            0x0a,
        ];
        let output = Ok((
            &[0x0a][..],
            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 },

                 */
            ],
        ));

        assert_eq!(list::<_, ()>(input, instruction), output);
    }

    #[test]
    fn test_exports() {
        let input = &[
            0x02, // 2 exports
            0x02, // string of 2 bytes
            0x61, 0x62, // "a", "b"
            0x01, // function type
            0x02, // string of 2 bytes
            0x63, 0x64, // "c", "d"
            0x02, // function type
        ];
        let output = Ok((
            &[] as &[u8],
            vec![
                Export {
                    name: "ab",
                    function_type: 1,
                },
                Export {
                    name: "cd",
                    function_type: 2,
                },
            ],
        ));

        assert_eq!(exports::<()>(input), output);
    }

    #[test]
    fn test_types() {
        let input = &[
            0x02, // 2 type
            0x00, // function type
            0x02, // list of 2 items
            0x02, // S32
            0x02, // S32
            0x01, // list of 2 items
            0x02, // S32
            0x01, // record type
            0x02, // list of 2 items
            0x02, // S32
            0x02, // S32
        ];
        let output = Ok((
            &[] as &[u8],
            vec![
                Type::Function {
                    inputs: vec![IType::S32, IType::S32],
                    outputs: vec![IType::S32],
                },
                Type::Record(RecordType {
                    fields: vec1![IType::S32, IType::S32],
                }),
            ],
        ));

        assert_eq!(types::<()>(input), output);
    }

    #[test]
    fn test_imports() {
        let input = &[
            0x02, // 2 imports
            0x01, // string of 1 byte
            0x61, // "a"
            0x01, // string of 1 byte
            0x62, // "b"
            0x01, // signature type
            0x01, // string of 1 byte
            0x63, // "c"
            0x01, // string of 1 byte
            0x64, // "d"
            0x02, // signature type
        ];
        let output = Ok((
            &[] as &[u8],
            vec![
                Import {
                    namespace: "a",
                    name: "b",
                    function_type: 1,
                },
                Import {
                    namespace: "c",
                    name: "d",
                    function_type: 2,
                },
            ],
        ));

        assert_eq!(imports::<()>(input), output);
    }

    #[test]
    fn test_adapters() {
        let input = &[
            0x01, // 1 adapters
            0x00, // function type
            0x01, // list of 1 item
            0x00, 0x01, // ArgumentGet { index: 1 }
        ];
        let output = Ok((
            &[] as &[u8],
            vec![Adapter {
                function_type: 0,
                instructions: vec![Instruction::ArgumentGet { index: 1 }],
            }],
        ));

        assert_eq!(adapters::<()>(input), output);
    }

    #[test]
    fn test_parse() {
        let input = &[
            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
        ];
        let output = Ok((
            &[] as &[u8],
            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,
                }],
            },
        ));

        assert_eq!(interfaces::<()>(input), output);
    }
}