summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibWasm/Parser/Parser.cpp
blob: 51f72d99e18bc6f5f6d5980d849bd05bb87ad348 (plain)
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
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
/*
 * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/Debug.h>
#include <AK/LEB128.h>
#include <AK/MemoryStream.h>
#include <AK/ScopeGuard.h>
#include <AK/ScopeLogger.h>
#include <LibWasm/Types.h>

namespace Wasm {

ParseError with_eof_check(AK::Stream const& stream, ParseError error_if_not_eof)
{
    if (stream.is_eof())
        return ParseError::UnexpectedEof;
    return error_if_not_eof;
}

template<typename T>
static auto parse_vector(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger;
    if constexpr (requires { T::parse(stream); }) {
        using ResultT = typename decltype(T::parse(stream))::ValueType;
        auto count_or_error = stream.read_value<LEB128<size_t>>();
        if (count_or_error.is_error())
            return ParseResult<Vector<ResultT>> { with_eof_check(stream, ParseError::ExpectedSize) };
        size_t count = count_or_error.release_value();

        Vector<ResultT> entries;
        for (size_t i = 0; i < count; ++i) {
            auto result = T::parse(stream);
            if (result.is_error())
                return ParseResult<Vector<ResultT>> { result.error() };
            entries.append(result.release_value());
        }
        return ParseResult<Vector<ResultT>> { move(entries) };
    } else {
        auto count_or_error = stream.read_value<LEB128<size_t>>();
        if (count_or_error.is_error())
            return ParseResult<Vector<T>> { with_eof_check(stream, ParseError::ExpectedSize) };
        size_t count = count_or_error.release_value();

        Vector<T> entries;
        for (size_t i = 0; i < count; ++i) {
            if constexpr (IsSame<T, size_t>) {
                auto value_or_error = stream.read_value<LEB128<size_t>>();
                if (value_or_error.is_error())
                    return ParseResult<Vector<T>> { with_eof_check(stream, ParseError::ExpectedSize) };
                size_t value = value_or_error.release_value();
                entries.append(value);
            } else if constexpr (IsSame<T, ssize_t>) {
                auto value_or_error = stream.read_value<LEB128<ssize_t>>();
                if (value_or_error.is_error())
                    return ParseResult<Vector<T>> { with_eof_check(stream, ParseError::ExpectedSize) };
                ssize_t value = value_or_error.release_value();
                entries.append(value);
            } else if constexpr (IsSame<T, u8>) {
                if (count > Constants::max_allowed_vector_size)
                    return ParseResult<Vector<T>> { ParseError::HugeAllocationRequested };
                entries.resize(count);
                if (stream.read_entire_buffer({ entries.data(), entries.size() }).is_error())
                    return ParseResult<Vector<T>> { with_eof_check(stream, ParseError::InvalidInput) };
                break; // Note: We read this all in one go!
            }
        }
        return ParseResult<Vector<T>> { move(entries) };
    }
}

static ParseResult<DeprecatedString> parse_name(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger;
    auto data = parse_vector<u8>(stream);
    if (data.is_error())
        return data.error();

    return DeprecatedString::copy(data.value());
}

template<typename T>
struct ParseUntilAnyOfResult {
    u8 terminator { 0 };
    Vector<T> values;
};
template<typename T, u8... terminators, typename... Args>
static ParseResult<ParseUntilAnyOfResult<T>> parse_until_any_of(AK::Stream& stream, Args&... args)
requires(requires(AK::Stream& stream, Args... args) { T::parse(stream, args...); })
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger;
    ReconsumableStream new_stream { stream };

    ParseUntilAnyOfResult<T> result;
    for (;;) {
        auto byte_or_error = new_stream.read_value<u8>();
        if (byte_or_error.is_error())
            return with_eof_check(stream, ParseError::ExpectedValueOrTerminator);

        auto byte = byte_or_error.release_value();

        constexpr auto equals = [](auto&& a, auto&& b) { return a == b; };

        if ((... || equals(byte, terminators))) {
            result.terminator = byte;
            return result;
        }

        new_stream.unread({ &byte, 1 });
        auto parse_result = T::parse(new_stream, args...);
        if (parse_result.is_error())
            return parse_result.error();

        result.values.extend(parse_result.release_value());
    }
}

ParseResult<ValueType> ValueType::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("ValueType"sv);
    auto tag_or_error = stream.read_value<u8>();
    if (tag_or_error.is_error())
        return with_eof_check(stream, ParseError::ExpectedKindTag);

    auto tag = tag_or_error.release_value();

    switch (tag) {
    case Constants::i32_tag:
        return ValueType(I32);
    case Constants::i64_tag:
        return ValueType(I64);
    case Constants::f32_tag:
        return ValueType(F32);
    case Constants::f64_tag:
        return ValueType(F64);
    case Constants::function_reference_tag:
        return ValueType(FunctionReference);
    case Constants::extern_reference_tag:
        return ValueType(ExternReference);
    default:
        return with_eof_check(stream, ParseError::InvalidTag);
    }
}

ParseResult<ResultType> ResultType::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("ResultType"sv);
    auto types = parse_vector<ValueType>(stream);
    if (types.is_error())
        return types.error();
    return ResultType { types.release_value() };
}

ParseResult<FunctionType> FunctionType::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("FunctionType"sv);
    auto tag_or_error = stream.read_value<u8>();
    if (tag_or_error.is_error())
        return with_eof_check(stream, ParseError::ExpectedKindTag);

    auto tag = tag_or_error.release_value();

    if (tag != Constants::function_signature_tag) {
        dbgln("Expected 0x60, but found {:#x}", tag);
        return with_eof_check(stream, ParseError::InvalidTag);
    }

    auto parameters_result = parse_vector<ValueType>(stream);
    if (parameters_result.is_error())
        return parameters_result.error();
    auto results_result = parse_vector<ValueType>(stream);
    if (results_result.is_error())
        return results_result.error();

    return FunctionType { parameters_result.release_value(), results_result.release_value() };
}

ParseResult<Limits> Limits::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("Limits"sv);
    auto flag_or_error = stream.read_value<u8>();
    if (flag_or_error.is_error())
        return with_eof_check(stream, ParseError::ExpectedKindTag);

    auto flag = flag_or_error.release_value();

    if (flag > 1)
        return with_eof_check(stream, ParseError::InvalidTag);

    auto min_or_error = stream.read_value<LEB128<size_t>>();
    if (min_or_error.is_error())
        return with_eof_check(stream, ParseError::ExpectedSize);
    size_t min = min_or_error.release_value();

    Optional<u32> max;
    if (flag) {
        auto value_or_error = stream.read_value<LEB128<size_t>>();
        if (value_or_error.is_error())
            return with_eof_check(stream, ParseError::ExpectedSize);
        max = value_or_error.release_value();
    }

    return Limits { static_cast<u32>(min), move(max) };
}

ParseResult<MemoryType> MemoryType::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("MemoryType"sv);
    auto limits_result = Limits::parse(stream);
    if (limits_result.is_error())
        return limits_result.error();
    return MemoryType { limits_result.release_value() };
}

ParseResult<TableType> TableType::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("TableType"sv);
    auto type_result = ValueType::parse(stream);
    if (type_result.is_error())
        return type_result.error();
    if (!type_result.value().is_reference())
        return with_eof_check(stream, ParseError::InvalidType);
    auto limits_result = Limits::parse(stream);
    if (limits_result.is_error())
        return limits_result.error();
    return TableType { type_result.release_value(), limits_result.release_value() };
}

ParseResult<GlobalType> GlobalType::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("GlobalType"sv);
    auto type_result = ValueType::parse(stream);
    if (type_result.is_error())
        return type_result.error();

    auto mutable_or_error = stream.read_value<u8>();
    if (mutable_or_error.is_error())
        return with_eof_check(stream, ParseError::ExpectedKindTag);

    auto mutable_ = mutable_or_error.release_value();

    if (mutable_ > 1)
        return with_eof_check(stream, ParseError::InvalidTag);

    return GlobalType { type_result.release_value(), mutable_ == 0x01 };
}

ParseResult<BlockType> BlockType::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("BlockType"sv);
    auto kind_or_error = stream.read_value<u8>();
    if (kind_or_error.is_error())
        return with_eof_check(stream, ParseError::ExpectedKindTag);

    auto kind = kind_or_error.release_value();
    if (kind == Constants::empty_block_tag)
        return BlockType {};

    {
        auto value_stream = FixedMemoryStream::construct(ReadonlyBytes { &kind, 1 }).release_value_but_fixme_should_propagate_errors();
        if (auto value_type = ValueType::parse(*value_stream); !value_type.is_error())
            return BlockType { value_type.release_value() };
    }

    ReconsumableStream new_stream { stream };
    new_stream.unread({ &kind, 1 });

    auto index_value_or_error = stream.read_value<LEB128<ssize_t>>();
    if (index_value_or_error.is_error())
        return with_eof_check(stream, ParseError::ExpectedIndex);
    ssize_t index_value = index_value_or_error.release_value();

    if (index_value < 0) {
        dbgln("Invalid type index {}", index_value);
        return with_eof_check(stream, ParseError::InvalidIndex);
    }

    return BlockType { TypeIndex(index_value) };
}

ParseResult<Vector<Instruction>> Instruction::parse(AK::Stream& stream, InstructionPointer& ip)
{
    struct NestedInstructionState {
        Vector<Instruction> prior_instructions;
        OpCode opcode;
        BlockType block_type;
        InstructionPointer end_ip;
        Optional<InstructionPointer> else_ip;
    };
    Vector<NestedInstructionState, 4> nested_instructions;
    Vector<Instruction> resulting_instructions;

    do {
        ScopeLogger<WASM_BINPARSER_DEBUG> logger("Instruction"sv);
        auto byte_or_error = stream.read_value<u8>();
        if (byte_or_error.is_error())
            return with_eof_check(stream, ParseError::ExpectedKindTag);

        auto byte = byte_or_error.release_value();

        if (!nested_instructions.is_empty()) {
            auto& nested_structure = nested_instructions.last();
            if (byte == 0x0b) {
                // block/loop/if end
                nested_structure.end_ip = ip + (nested_structure.else_ip.has_value() ? 1 : 0);
                ++ip;

                // Transform op(..., instr*) -> op(...) instr* op(end(ip))
                auto instructions = move(nested_structure.prior_instructions);
                instructions.ensure_capacity(instructions.size() + 2 + resulting_instructions.size());
                instructions.append(Instruction { nested_structure.opcode, StructuredInstructionArgs { nested_structure.block_type, nested_structure.end_ip, nested_structure.else_ip } });
                instructions.extend(move(resulting_instructions));
                instructions.append(Instruction { Instructions::structured_end });
                resulting_instructions = move(instructions);
                nested_instructions.take_last();
                continue;
            }

            if (byte == 0x05) {
                // if...else

                // Transform op(..., instr*, instr*) -> op(...) instr* op(else(ip) instr* op(end(ip))
                resulting_instructions.append(Instruction { Instructions::structured_else });
                ++ip;
                nested_structure.else_ip = ip.value();
                continue;
            }
        }

        OpCode opcode { byte };
        ++ip;

        switch (opcode.value()) {
        case Instructions::block.value():
        case Instructions::loop.value():
        case Instructions::if_.value(): {
            auto block_type = BlockType::parse(stream);
            if (block_type.is_error())
                return block_type.error();

            nested_instructions.append({ move(resulting_instructions), opcode, block_type.release_value(), {}, {} });
            resulting_instructions = {};
            break;
        }
        case Instructions::br.value():
        case Instructions::br_if.value(): {
            // branches with a single label immediate
            auto index = GenericIndexParser<LabelIndex>::parse(stream);
            if (index.is_error())
                return index.error();

            resulting_instructions.append(Instruction { opcode, index.release_value() });
            break;
        }
        case Instructions::br_table.value(): {
            // br_table label* label
            auto labels = parse_vector<GenericIndexParser<LabelIndex>>(stream);
            if (labels.is_error())
                return labels.error();

            auto default_label = GenericIndexParser<LabelIndex>::parse(stream);
            if (default_label.is_error())
                return default_label.error();

            resulting_instructions.append(Instruction { opcode, TableBranchArgs { labels.release_value(), default_label.release_value() } });
            break;
        }
        case Instructions::call.value(): {
            // call function
            auto function_index = GenericIndexParser<FunctionIndex>::parse(stream);
            if (function_index.is_error())
                return function_index.error();

            resulting_instructions.append(Instruction { opcode, function_index.release_value() });
            break;
        }
        case Instructions::call_indirect.value(): {
            // call_indirect type table
            auto type_index = GenericIndexParser<TypeIndex>::parse(stream);
            if (type_index.is_error())
                return type_index.error();

            auto table_index = GenericIndexParser<TableIndex>::parse(stream);
            if (table_index.is_error())
                return table_index.error();

            resulting_instructions.append(Instruction { opcode, IndirectCallArgs { type_index.release_value(), table_index.release_value() } });
            break;
        }
        case Instructions::i32_load.value():
        case Instructions::i64_load.value():
        case Instructions::f32_load.value():
        case Instructions::f64_load.value():
        case Instructions::i32_load8_s.value():
        case Instructions::i32_load8_u.value():
        case Instructions::i32_load16_s.value():
        case Instructions::i32_load16_u.value():
        case Instructions::i64_load8_s.value():
        case Instructions::i64_load8_u.value():
        case Instructions::i64_load16_s.value():
        case Instructions::i64_load16_u.value():
        case Instructions::i64_load32_s.value():
        case Instructions::i64_load32_u.value():
        case Instructions::i32_store.value():
        case Instructions::i64_store.value():
        case Instructions::f32_store.value():
        case Instructions::f64_store.value():
        case Instructions::i32_store8.value():
        case Instructions::i32_store16.value():
        case Instructions::i64_store8.value():
        case Instructions::i64_store16.value():
        case Instructions::i64_store32.value(): {
            // op (align offset)
            auto align_or_error = stream.read_value<LEB128<size_t>>();
            if (align_or_error.is_error())
                return with_eof_check(stream, ParseError::InvalidInput);
            size_t align = align_or_error.release_value();

            auto offset_or_error = stream.read_value<LEB128<size_t>>();
            if (offset_or_error.is_error())
                return with_eof_check(stream, ParseError::InvalidInput);
            size_t offset = offset_or_error.release_value();

            resulting_instructions.append(Instruction { opcode, MemoryArgument { static_cast<u32>(align), static_cast<u32>(offset) } });
            break;
        }
        case Instructions::local_get.value():
        case Instructions::local_set.value():
        case Instructions::local_tee.value(): {
            auto index = GenericIndexParser<LocalIndex>::parse(stream);
            if (index.is_error())
                return index.error();

            resulting_instructions.append(Instruction { opcode, index.release_value() });
            break;
        }
        case Instructions::global_get.value():
        case Instructions::global_set.value(): {
            auto index = GenericIndexParser<GlobalIndex>::parse(stream);
            if (index.is_error())
                return index.error();

            resulting_instructions.append(Instruction { opcode, index.release_value() });
            break;
        }
        case Instructions::memory_size.value():
        case Instructions::memory_grow.value(): {
            // op 0x0
            // The zero is currently unused.
            auto unused_or_error = stream.read_value<u8>();
            if (unused_or_error.is_error())
                return with_eof_check(stream, ParseError::ExpectedKindTag);

            auto unused = unused_or_error.release_value();
            if (unused != 0x00) {
                dbgln("Invalid tag in memory_grow {}", unused);
                return with_eof_check(stream, ParseError::InvalidTag);
            }

            resulting_instructions.append(Instruction { opcode });
            break;
        }
        case Instructions::i32_const.value(): {
            auto value_or_error = stream.read_value<LEB128<i32>>();
            if (value_or_error.is_error())
                return with_eof_check(stream, ParseError::ExpectedSignedImmediate);
            i32 value = value_or_error.release_value();

            resulting_instructions.append(Instruction { opcode, value });
            break;
        }
        case Instructions::i64_const.value(): {
            // op literal
            auto value_or_error = stream.read_value<LEB128<i64>>();
            if (value_or_error.is_error())
                return with_eof_check(stream, ParseError::ExpectedSignedImmediate);
            i64 value = value_or_error.release_value();

            resulting_instructions.append(Instruction { opcode, value });
            break;
        }
        case Instructions::f32_const.value(): {
            // op literal
            LittleEndian<u32> value;
            if (stream.read_entire_buffer(value.bytes()).is_error())
                return with_eof_check(stream, ParseError::ExpectedFloatingImmediate);

            auto floating = bit_cast<float>(static_cast<u32>(value));
            resulting_instructions.append(Instruction { opcode, floating });
            break;
        }
        case Instructions::f64_const.value(): {
            // op literal
            LittleEndian<u64> value;
            if (stream.read_entire_buffer(value.bytes()).is_error())
                return with_eof_check(stream, ParseError::ExpectedFloatingImmediate);

            auto floating = bit_cast<double>(static_cast<u64>(value));
            resulting_instructions.append(Instruction { opcode, floating });
            break;
        }
        case Instructions::table_get.value():
        case Instructions::table_set.value(): {
            auto index = GenericIndexParser<TableIndex>::parse(stream);
            if (index.is_error())
                return index.error();

            resulting_instructions.append(Instruction { opcode, index.release_value() });
            break;
        }
        case Instructions::select_typed.value(): {
            auto types = parse_vector<ValueType>(stream);
            if (types.is_error())
                return types.error();

            resulting_instructions.append(Instruction { opcode, types.release_value() });
            break;
        }
        case Instructions::ref_null.value(): {
            auto type = ValueType::parse(stream);
            if (type.is_error())
                return type.error();
            if (!type.value().is_reference())
                return ParseError::InvalidType;

            resulting_instructions.append(Instruction { opcode, type.release_value() });
            break;
        }
        case Instructions::ref_func.value(): {
            auto index = GenericIndexParser<FunctionIndex>::parse(stream);
            if (index.is_error())
                return index.error();

            resulting_instructions.append(Instruction { opcode, index.release_value() });
            break;
        }
        case Instructions::ref_is_null.value():
        case Instructions::unreachable.value():
        case Instructions::nop.value():
        case Instructions::return_.value():
        case Instructions::drop.value():
        case Instructions::select.value():
        case Instructions::i32_eqz.value():
        case Instructions::i32_eq.value():
        case Instructions::i32_ne.value():
        case Instructions::i32_lts.value():
        case Instructions::i32_ltu.value():
        case Instructions::i32_gts.value():
        case Instructions::i32_gtu.value():
        case Instructions::i32_les.value():
        case Instructions::i32_leu.value():
        case Instructions::i32_ges.value():
        case Instructions::i32_geu.value():
        case Instructions::i64_eqz.value():
        case Instructions::i64_eq.value():
        case Instructions::i64_ne.value():
        case Instructions::i64_lts.value():
        case Instructions::i64_ltu.value():
        case Instructions::i64_gts.value():
        case Instructions::i64_gtu.value():
        case Instructions::i64_les.value():
        case Instructions::i64_leu.value():
        case Instructions::i64_ges.value():
        case Instructions::i64_geu.value():
        case Instructions::f32_eq.value():
        case Instructions::f32_ne.value():
        case Instructions::f32_lt.value():
        case Instructions::f32_gt.value():
        case Instructions::f32_le.value():
        case Instructions::f32_ge.value():
        case Instructions::f64_eq.value():
        case Instructions::f64_ne.value():
        case Instructions::f64_lt.value():
        case Instructions::f64_gt.value():
        case Instructions::f64_le.value():
        case Instructions::f64_ge.value():
        case Instructions::i32_clz.value():
        case Instructions::i32_ctz.value():
        case Instructions::i32_popcnt.value():
        case Instructions::i32_add.value():
        case Instructions::i32_sub.value():
        case Instructions::i32_mul.value():
        case Instructions::i32_divs.value():
        case Instructions::i32_divu.value():
        case Instructions::i32_rems.value():
        case Instructions::i32_remu.value():
        case Instructions::i32_and.value():
        case Instructions::i32_or.value():
        case Instructions::i32_xor.value():
        case Instructions::i32_shl.value():
        case Instructions::i32_shrs.value():
        case Instructions::i32_shru.value():
        case Instructions::i32_rotl.value():
        case Instructions::i32_rotr.value():
        case Instructions::i64_clz.value():
        case Instructions::i64_ctz.value():
        case Instructions::i64_popcnt.value():
        case Instructions::i64_add.value():
        case Instructions::i64_sub.value():
        case Instructions::i64_mul.value():
        case Instructions::i64_divs.value():
        case Instructions::i64_divu.value():
        case Instructions::i64_rems.value():
        case Instructions::i64_remu.value():
        case Instructions::i64_and.value():
        case Instructions::i64_or.value():
        case Instructions::i64_xor.value():
        case Instructions::i64_shl.value():
        case Instructions::i64_shrs.value():
        case Instructions::i64_shru.value():
        case Instructions::i64_rotl.value():
        case Instructions::i64_rotr.value():
        case Instructions::f32_abs.value():
        case Instructions::f32_neg.value():
        case Instructions::f32_ceil.value():
        case Instructions::f32_floor.value():
        case Instructions::f32_trunc.value():
        case Instructions::f32_nearest.value():
        case Instructions::f32_sqrt.value():
        case Instructions::f32_add.value():
        case Instructions::f32_sub.value():
        case Instructions::f32_mul.value():
        case Instructions::f32_div.value():
        case Instructions::f32_min.value():
        case Instructions::f32_max.value():
        case Instructions::f32_copysign.value():
        case Instructions::f64_abs.value():
        case Instructions::f64_neg.value():
        case Instructions::f64_ceil.value():
        case Instructions::f64_floor.value():
        case Instructions::f64_trunc.value():
        case Instructions::f64_nearest.value():
        case Instructions::f64_sqrt.value():
        case Instructions::f64_add.value():
        case Instructions::f64_sub.value():
        case Instructions::f64_mul.value():
        case Instructions::f64_div.value():
        case Instructions::f64_min.value():
        case Instructions::f64_max.value():
        case Instructions::f64_copysign.value():
        case Instructions::i32_wrap_i64.value():
        case Instructions::i32_trunc_sf32.value():
        case Instructions::i32_trunc_uf32.value():
        case Instructions::i32_trunc_sf64.value():
        case Instructions::i32_trunc_uf64.value():
        case Instructions::i64_extend_si32.value():
        case Instructions::i64_extend_ui32.value():
        case Instructions::i64_trunc_sf32.value():
        case Instructions::i64_trunc_uf32.value():
        case Instructions::i64_trunc_sf64.value():
        case Instructions::i64_trunc_uf64.value():
        case Instructions::f32_convert_si32.value():
        case Instructions::f32_convert_ui32.value():
        case Instructions::f32_convert_si64.value():
        case Instructions::f32_convert_ui64.value():
        case Instructions::f32_demote_f64.value():
        case Instructions::f64_convert_si32.value():
        case Instructions::f64_convert_ui32.value():
        case Instructions::f64_convert_si64.value():
        case Instructions::f64_convert_ui64.value():
        case Instructions::f64_promote_f32.value():
        case Instructions::i32_reinterpret_f32.value():
        case Instructions::i64_reinterpret_f64.value():
        case Instructions::f32_reinterpret_i32.value():
        case Instructions::f64_reinterpret_i64.value():
        case Instructions::i32_extend8_s.value():
        case Instructions::i32_extend16_s.value():
        case Instructions::i64_extend8_s.value():
        case Instructions::i64_extend16_s.value():
        case Instructions::i64_extend32_s.value():
            resulting_instructions.append(Instruction { opcode });
            break;
        case 0xfc: {
            // These are multibyte instructions.
            auto selector_or_error = stream.read_value<LEB128<u32>>();
            if (selector_or_error.is_error())
                return with_eof_check(stream, ParseError::InvalidInput);
            u32 selector = selector_or_error.release_value();
            switch (selector) {
            case Instructions::i32_trunc_sat_f32_s_second:
            case Instructions::i32_trunc_sat_f32_u_second:
            case Instructions::i32_trunc_sat_f64_s_second:
            case Instructions::i32_trunc_sat_f64_u_second:
            case Instructions::i64_trunc_sat_f32_s_second:
            case Instructions::i64_trunc_sat_f32_u_second:
            case Instructions::i64_trunc_sat_f64_s_second:
            case Instructions::i64_trunc_sat_f64_u_second:
                resulting_instructions.append(Instruction { OpCode { 0xfc00 | selector } });
                break;
            case Instructions::memory_init_second: {
                auto index = GenericIndexParser<DataIndex>::parse(stream);
                if (index.is_error())
                    return index.error();
                auto unused_or_error = stream.read_value<u8>();
                if (unused_or_error.is_error())
                    return with_eof_check(stream, ParseError::InvalidInput);

                auto unused = unused_or_error.release_value();
                if (unused != 0x00)
                    return ParseError::InvalidImmediate;
                resulting_instructions.append(Instruction { OpCode { 0xfc00 | selector }, index.release_value() });
                break;
            }
            case Instructions::data_drop_second: {
                auto index = GenericIndexParser<DataIndex>::parse(stream);
                if (index.is_error())
                    return index.error();
                resulting_instructions.append(Instruction { OpCode { 0xfc00 | selector }, index.release_value() });
                break;
            }
            case Instructions::memory_copy_second: {
                for (size_t i = 0; i < 2; ++i) {
                    auto unused_or_error = stream.read_value<u8>();
                    if (unused_or_error.is_error())
                        return with_eof_check(stream, ParseError::InvalidInput);

                    auto unused = unused_or_error.release_value();
                    if (unused != 0x00)
                        return ParseError::InvalidImmediate;
                }
                resulting_instructions.append(Instruction { OpCode { 0xfc00 | selector } });
                break;
            }
            case Instructions::memory_fill_second: {
                auto unused_or_error = stream.read_value<u8>();
                if (unused_or_error.is_error())
                    return with_eof_check(stream, ParseError::InvalidInput);

                auto unused = unused_or_error.release_value();
                if (unused != 0x00)
                    return ParseError::InvalidImmediate;
                resulting_instructions.append(Instruction { OpCode { 0xfc00 | selector } });
                break;
            }
            case Instructions::table_init_second: {
                auto element_index = GenericIndexParser<ElementIndex>::parse(stream);
                if (element_index.is_error())
                    return element_index.error();
                auto table_index = GenericIndexParser<TableIndex>::parse(stream);
                if (table_index.is_error())
                    return table_index.error();
                resulting_instructions.append(Instruction { OpCode { 0xfc00 | selector }, TableElementArgs { element_index.release_value(), table_index.release_value() } });
                break;
            }
            case Instructions::elem_drop_second: {
                auto element_index = GenericIndexParser<ElementIndex>::parse(stream);
                if (element_index.is_error())
                    return element_index.error();
                resulting_instructions.append(Instruction { OpCode { 0xfc00 | selector }, element_index.release_value() });
                break;
            }
            case Instructions::table_copy_second: {
                auto lhs = GenericIndexParser<TableIndex>::parse(stream);
                if (lhs.is_error())
                    return lhs.error();
                auto rhs = GenericIndexParser<TableIndex>::parse(stream);
                if (rhs.is_error())
                    return rhs.error();
                resulting_instructions.append(Instruction { OpCode { 0xfc00 | selector }, TableTableArgs { lhs.release_value(), rhs.release_value() } });
                break;
            }
            case Instructions::table_grow_second:
            case Instructions::table_size_second:
            case Instructions::table_fill_second: {
                auto index = GenericIndexParser<TableIndex>::parse(stream);
                if (index.is_error())
                    return index.error();
                resulting_instructions.append(Instruction { OpCode { 0xfc00 | selector }, index.release_value() });
                break;
            }
            default:
                return ParseError::UnknownInstruction;
            }
        }
        }
    } while (!nested_instructions.is_empty());

    return resulting_instructions;
}

ParseResult<CustomSection> CustomSection::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("CustomSection"sv);
    auto name = parse_name(stream);
    if (name.is_error())
        return name.error();

    ByteBuffer data_buffer;
    if (data_buffer.try_resize(64).is_error())
        return ParseError::OutOfMemory;

    while (!stream.is_eof()) {
        char buf[16];
        auto span_or_error = stream.read({ buf, 16 });
        if (span_or_error.is_error())
            break;
        auto size = span_or_error.release_value().size();
        if (size == 0)
            break;
        if (data_buffer.try_append(buf, size).is_error())
            return with_eof_check(stream, ParseError::HugeAllocationRequested);
    }

    return CustomSection(name.release_value(), move(data_buffer));
}

ParseResult<TypeSection> TypeSection::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("TypeSection"sv);
    auto types = parse_vector<FunctionType>(stream);
    if (types.is_error())
        return types.error();
    return TypeSection { types.release_value() };
}

ParseResult<ImportSection::Import> ImportSection::Import::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("Import"sv);
    auto module = parse_name(stream);
    if (module.is_error())
        return module.error();
    auto name = parse_name(stream);
    if (name.is_error())
        return name.error();
    auto tag_or_error = stream.read_value<u8>();
    if (tag_or_error.is_error())
        return with_eof_check(stream, ParseError::ExpectedKindTag);

    auto tag = tag_or_error.release_value();

    switch (tag) {
    case Constants::extern_function_tag: {
        auto index = GenericIndexParser<TypeIndex>::parse(stream);
        if (index.is_error())
            return index.error();
        return Import { module.release_value(), name.release_value(), index.release_value() };
    }
    case Constants::extern_table_tag:
        return parse_with_type<TableType>(stream, module, name);
    case Constants::extern_memory_tag:
        return parse_with_type<MemoryType>(stream, module, name);
    case Constants::extern_global_tag:
        return parse_with_type<GlobalType>(stream, module, name);
    default:
        return with_eof_check(stream, ParseError::InvalidTag);
    }
}

ParseResult<ImportSection> ImportSection::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("ImportSection"sv);
    auto imports = parse_vector<Import>(stream);
    if (imports.is_error())
        return imports.error();
    return ImportSection { imports.release_value() };
}

ParseResult<FunctionSection> FunctionSection::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("FunctionSection"sv);
    auto indices = parse_vector<size_t>(stream);
    if (indices.is_error())
        return indices.error();

    Vector<TypeIndex> typed_indices;
    typed_indices.ensure_capacity(indices.value().size());
    for (auto entry : indices.value())
        typed_indices.append(entry);

    return FunctionSection { move(typed_indices) };
}

ParseResult<TableSection::Table> TableSection::Table::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("Table"sv);
    auto type = TableType::parse(stream);
    if (type.is_error())
        return type.error();
    return Table { type.release_value() };
}

ParseResult<TableSection> TableSection::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("TableSection"sv);
    auto tables = parse_vector<Table>(stream);
    if (tables.is_error())
        return tables.error();
    return TableSection { tables.release_value() };
}

ParseResult<MemorySection::Memory> MemorySection::Memory::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("Memory"sv);
    auto type = MemoryType::parse(stream);
    if (type.is_error())
        return type.error();
    return Memory { type.release_value() };
}

ParseResult<MemorySection> MemorySection::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("MemorySection"sv);
    auto memories = parse_vector<Memory>(stream);
    if (memories.is_error())
        return memories.error();
    return MemorySection { memories.release_value() };
}

ParseResult<Expression> Expression::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("Expression"sv);
    InstructionPointer ip { 0 };
    auto instructions = parse_until_any_of<Instruction, 0x0b>(stream, ip);
    if (instructions.is_error())
        return instructions.error();

    return Expression { move(instructions.value().values) };
}

ParseResult<GlobalSection::Global> GlobalSection::Global::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("Global"sv);
    auto type = GlobalType::parse(stream);
    if (type.is_error())
        return type.error();
    auto exprs = Expression::parse(stream);
    if (exprs.is_error())
        return exprs.error();
    return Global { type.release_value(), exprs.release_value() };
}

ParseResult<GlobalSection> GlobalSection::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("GlobalSection"sv);
    auto result = parse_vector<Global>(stream);
    if (result.is_error())
        return result.error();
    return GlobalSection { result.release_value() };
}

ParseResult<ExportSection::Export> ExportSection::Export::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("Export"sv);
    auto name = parse_name(stream);
    if (name.is_error())
        return name.error();
    auto tag_or_error = stream.read_value<u8>();
    if (tag_or_error.is_error())
        return with_eof_check(stream, ParseError::ExpectedKindTag);

    auto tag = tag_or_error.release_value();

    auto index_or_error = stream.read_value<LEB128<size_t>>();
    if (index_or_error.is_error())
        return with_eof_check(stream, ParseError::ExpectedIndex);
    size_t index = index_or_error.release_value();

    switch (tag) {
    case Constants::extern_function_tag:
        return Export { name.release_value(), ExportDesc { FunctionIndex { index } } };
    case Constants::extern_table_tag:
        return Export { name.release_value(), ExportDesc { TableIndex { index } } };
    case Constants::extern_memory_tag:
        return Export { name.release_value(), ExportDesc { MemoryIndex { index } } };
    case Constants::extern_global_tag:
        return Export { name.release_value(), ExportDesc { GlobalIndex { index } } };
    default:
        return with_eof_check(stream, ParseError::InvalidTag);
    }
}

ParseResult<ExportSection> ExportSection::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("ExportSection"sv);
    auto result = parse_vector<Export>(stream);
    if (result.is_error())
        return result.error();
    return ExportSection { result.release_value() };
}

ParseResult<StartSection::StartFunction> StartSection::StartFunction::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("StartFunction"sv);
    auto index = GenericIndexParser<FunctionIndex>::parse(stream);
    if (index.is_error())
        return index.error();
    return StartFunction { index.release_value() };
}

ParseResult<StartSection> StartSection::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("StartSection"sv);
    auto result = StartFunction::parse(stream);
    if (result.is_error())
        return result.error();
    return StartSection { result.release_value() };
}

ParseResult<ElementSection::SegmentType0> ElementSection::SegmentType0::parse(AK::Stream& stream)
{
    auto expression = Expression::parse(stream);
    if (expression.is_error())
        return expression.error();
    auto indices = parse_vector<GenericIndexParser<FunctionIndex>>(stream);
    if (indices.is_error())
        return indices.error();

    return SegmentType0 { indices.release_value(), Active { 0, expression.release_value() } };
}

ParseResult<ElementSection::SegmentType1> ElementSection::SegmentType1::parse(AK::Stream& stream)
{
    auto kind_or_error = stream.read_value<u8>();
    if (kind_or_error.is_error())
        return with_eof_check(stream, ParseError::ExpectedKindTag);

    auto kind = kind_or_error.release_value();
    if (kind != 0)
        return ParseError::InvalidTag;
    auto indices = parse_vector<GenericIndexParser<FunctionIndex>>(stream);
    if (indices.is_error())
        return indices.error();

    return SegmentType1 { indices.release_value() };
}

ParseResult<ElementSection::SegmentType2> ElementSection::SegmentType2::parse(AK::Stream& stream)
{
    dbgln("Type 2");
    (void)stream;
    return ParseError::NotImplemented;
}

ParseResult<ElementSection::SegmentType3> ElementSection::SegmentType3::parse(AK::Stream& stream)
{
    dbgln("Type 3");
    (void)stream;
    return ParseError::NotImplemented;
}

ParseResult<ElementSection::SegmentType4> ElementSection::SegmentType4::parse(AK::Stream& stream)
{
    dbgln("Type 4");
    (void)stream;
    return ParseError::NotImplemented;
}

ParseResult<ElementSection::SegmentType5> ElementSection::SegmentType5::parse(AK::Stream& stream)
{
    dbgln("Type 5");
    (void)stream;
    return ParseError::NotImplemented;
}

ParseResult<ElementSection::SegmentType6> ElementSection::SegmentType6::parse(AK::Stream& stream)
{
    dbgln("Type 6");
    (void)stream;
    return ParseError::NotImplemented;
}

ParseResult<ElementSection::SegmentType7> ElementSection::SegmentType7::parse(AK::Stream& stream)
{
    dbgln("Type 7");
    (void)stream;
    return ParseError::NotImplemented;
}

ParseResult<ElementSection::Element> ElementSection::Element::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("Element"sv);
    auto tag_or_error = stream.read_value<u8>();
    if (tag_or_error.is_error())
        return with_eof_check(stream, ParseError::ExpectedKindTag);

    auto tag = tag_or_error.release_value();

    switch (tag) {
    case 0x00:
        if (auto result = SegmentType0::parse(stream); result.is_error()) {
            return result.error();
        } else {
            Vector<Instruction> instructions;
            for (auto& index : result.value().function_indices)
                instructions.empend(Instructions::ref_func, index);
            return Element { ValueType(ValueType::FunctionReference), { Expression { move(instructions) } }, move(result.value().mode) };
        }
    case 0x01:
        if (auto result = SegmentType1::parse(stream); result.is_error()) {
            return result.error();
        } else {
            Vector<Instruction> instructions;
            for (auto& index : result.value().function_indices)
                instructions.empend(Instructions::ref_func, index);
            return Element { ValueType(ValueType::FunctionReference), { Expression { move(instructions) } }, Passive {} };
        }
    case 0x02:
        if (auto result = SegmentType2::parse(stream); result.is_error()) {
            return result.error();
        } else {
            return ParseError::NotImplemented;
        }
    case 0x03:
        if (auto result = SegmentType3::parse(stream); result.is_error()) {
            return result.error();
        } else {
            return ParseError::NotImplemented;
        }
    case 0x04:
        if (auto result = SegmentType4::parse(stream); result.is_error()) {
            return result.error();
        } else {
            return ParseError::NotImplemented;
        }
    case 0x05:
        if (auto result = SegmentType5::parse(stream); result.is_error()) {
            return result.error();
        } else {
            return ParseError::NotImplemented;
        }
    case 0x06:
        if (auto result = SegmentType6::parse(stream); result.is_error()) {
            return result.error();
        } else {
            return ParseError::NotImplemented;
        }
    case 0x07:
        if (auto result = SegmentType7::parse(stream); result.is_error()) {
            return result.error();
        } else {
            return ParseError::NotImplemented;
        }
    default:
        return ParseError::InvalidTag;
    }
}

ParseResult<ElementSection> ElementSection::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("ElementSection"sv);
    auto result = parse_vector<Element>(stream);
    if (result.is_error())
        return result.error();
    return ElementSection { result.release_value() };
}

ParseResult<Locals> Locals::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("Locals"sv);
    auto count_or_error = stream.read_value<LEB128<size_t>>();
    if (count_or_error.is_error())
        return with_eof_check(stream, ParseError::InvalidSize);
    size_t count = count_or_error.release_value();

    if (count > Constants::max_allowed_function_locals_per_type)
        return with_eof_check(stream, ParseError::HugeAllocationRequested);

    auto type = ValueType::parse(stream);
    if (type.is_error())
        return type.error();

    return Locals { static_cast<u32>(count), type.release_value() };
}

ParseResult<CodeSection::Func> CodeSection::Func::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("Func"sv);
    auto locals = parse_vector<Locals>(stream);
    if (locals.is_error())
        return locals.error();
    auto body = Expression::parse(stream);
    if (body.is_error())
        return body.error();
    return Func { locals.release_value(), body.release_value() };
}

ParseResult<CodeSection::Code> CodeSection::Code::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("Code"sv);
    auto size_or_error = stream.read_value<LEB128<size_t>>();
    if (size_or_error.is_error())
        return with_eof_check(stream, ParseError::InvalidSize);
    size_t size = size_or_error.release_value();

    auto constrained_stream = ConstrainedStream { stream, size };

    auto func = Func::parse(constrained_stream);
    if (func.is_error())
        return func.error();

    return Code { static_cast<u32>(size), func.release_value() };
}

ParseResult<CodeSection> CodeSection::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("CodeSection"sv);
    auto result = parse_vector<Code>(stream);
    if (result.is_error())
        return result.error();
    return CodeSection { result.release_value() };
}

ParseResult<DataSection::Data> DataSection::Data::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("Data"sv);
    auto tag_or_error = stream.read_value<u8>();
    if (tag_or_error.is_error())
        return with_eof_check(stream, ParseError::ExpectedKindTag);

    auto tag = tag_or_error.release_value();

    if (tag > 0x02)
        return with_eof_check(stream, ParseError::InvalidTag);

    if (tag == 0x00) {
        auto expr = Expression::parse(stream);
        if (expr.is_error())
            return expr.error();
        auto init = parse_vector<u8>(stream);
        if (init.is_error())
            return init.error();
        return Data { Active { init.release_value(), { 0 }, expr.release_value() } };
    }
    if (tag == 0x01) {
        auto init = parse_vector<u8>(stream);
        if (init.is_error())
            return init.error();
        return Data { Passive { init.release_value() } };
    }
    if (tag == 0x02) {
        auto index = GenericIndexParser<MemoryIndex>::parse(stream);
        if (index.is_error())
            return index.error();
        auto expr = Expression::parse(stream);
        if (expr.is_error())
            return expr.error();
        auto init = parse_vector<u8>(stream);
        if (init.is_error())
            return init.error();
        return Data { Active { init.release_value(), index.release_value(), expr.release_value() } };
    }
    VERIFY_NOT_REACHED();
}

ParseResult<DataSection> DataSection::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("DataSection"sv);
    auto data = parse_vector<Data>(stream);
    if (data.is_error())
        return data.error();

    return DataSection { data.release_value() };
}

ParseResult<DataCountSection> DataCountSection::parse([[maybe_unused]] AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("DataCountSection"sv);
    auto value_or_error = stream.read_value<LEB128<u32>>();
    if (value_or_error.is_error()) {
        if (stream.is_eof()) {
            // The section simply didn't contain anything.
            return DataCountSection { {} };
        }
        return ParseError::ExpectedSize;
    }
    u32 value = value_or_error.release_value();

    return DataCountSection { value };
}

ParseResult<Module> Module::parse(AK::Stream& stream)
{
    ScopeLogger<WASM_BINPARSER_DEBUG> logger("Module"sv);
    u8 buf[4];
    if (stream.read_entire_buffer({ buf, 4 }).is_error())
        return with_eof_check(stream, ParseError::InvalidInput);
    if (Bytes { buf, 4 } != wasm_magic.span())
        return with_eof_check(stream, ParseError::InvalidModuleMagic);

    if (stream.read_entire_buffer({ buf, 4 }).is_error())
        return with_eof_check(stream, ParseError::InvalidInput);
    if (Bytes { buf, 4 } != wasm_version.span())
        return with_eof_check(stream, ParseError::InvalidModuleVersion);

    Vector<AnySection> sections;
    for (;;) {
        auto section_id_or_error = stream.read_value<u8>();
        if (stream.is_eof())
            break;
        if (section_id_or_error.is_error())
            return with_eof_check(stream, ParseError::ExpectedIndex);

        auto section_id = section_id_or_error.release_value();

        auto section_size_or_error = stream.read_value<LEB128<size_t>>();
        if (section_size_or_error.is_error())
            return with_eof_check(stream, ParseError::ExpectedSize);
        size_t section_size = section_size_or_error.release_value();

        auto section_stream = ConstrainedStream { stream, section_size };

        switch (section_id) {
        case CustomSection::section_id:
            sections.append(TRY(CustomSection::parse(section_stream)));
            continue;
        case TypeSection::section_id:
            sections.append(TRY(TypeSection::parse(section_stream)));
            continue;
        case ImportSection::section_id:
            sections.append(TRY(ImportSection::parse(section_stream)));
            continue;
        case FunctionSection::section_id:
            sections.append(TRY(FunctionSection::parse(section_stream)));
            continue;
        case TableSection::section_id:
            sections.append(TRY(TableSection::parse(section_stream)));
            continue;
        case MemorySection::section_id:
            sections.append(TRY(MemorySection::parse(section_stream)));
            continue;
        case GlobalSection::section_id:
            sections.append(TRY(GlobalSection::parse(section_stream)));
            continue;
        case ExportSection::section_id:
            sections.append(TRY(ExportSection::parse(section_stream)));
            continue;
        case StartSection::section_id:
            sections.append(TRY(StartSection::parse(section_stream)));
            continue;
        case ElementSection::section_id:
            sections.append(TRY(ElementSection::parse(section_stream)));
            continue;
        case CodeSection::section_id:
            sections.append(TRY(CodeSection::parse(section_stream)));
            continue;
        case DataSection::section_id:
            sections.append(TRY(DataSection::parse(section_stream)));
            continue;
        case DataCountSection::section_id:
            sections.append(TRY(DataCountSection::parse(section_stream)));
            continue;
        default:
            return with_eof_check(stream, ParseError::InvalidIndex);
        }
    }

    return Module { move(sections) };
}

bool Module::populate_sections()
{
    auto is_ok = true;
    FunctionSection const* function_section { nullptr };
    for_each_section_of_type<FunctionSection>([&](FunctionSection const& section) { function_section = &section; });
    for_each_section_of_type<CodeSection>([&](CodeSection const& section) {
        if (!function_section) {
            is_ok = false;
            return;
        }
        size_t index = 0;
        for (auto& entry : section.functions()) {
            if (function_section->types().size() <= index) {
                is_ok = false;
                return;
            }
            auto& type_index = function_section->types()[index];
            Vector<ValueType> locals;
            for (auto& local : entry.func().locals()) {
                for (size_t i = 0; i < local.n(); ++i)
                    locals.append(local.type());
            }
            m_functions.empend(type_index, move(locals), entry.func().body());
            ++index;
        }
    });
    return is_ok;
}

DeprecatedString parse_error_to_deprecated_string(ParseError error)
{
    switch (error) {
    case ParseError::UnexpectedEof:
        return "Unexpected end-of-file";
    case ParseError::ExpectedIndex:
        return "Expected a valid index value";
    case ParseError::ExpectedKindTag:
        return "Expected a valid kind tag";
    case ParseError::ExpectedSize:
        return "Expected a valid LEB128-encoded size";
    case ParseError::ExpectedValueOrTerminator:
        return "Expected either a terminator or a value";
    case ParseError::InvalidIndex:
        return "An index parsed was semantically invalid";
    case ParseError::InvalidInput:
        return "Input data contained invalid bytes";
    case ParseError::InvalidModuleMagic:
        return "Incorrect module magic (did not match \\0asm)";
    case ParseError::InvalidModuleVersion:
        return "Incorrect module version";
    case ParseError::InvalidSize:
        return "A parsed size did not make sense in context";
    case ParseError::InvalidTag:
        return "A parsed tag did not make sense in context";
    case ParseError::InvalidType:
        return "A parsed type did not make sense in context";
    case ParseError::NotImplemented:
        return "The parser encountered an unimplemented feature";
    case ParseError::HugeAllocationRequested:
        return "Parsing caused an attempt to allocate a very big chunk of memory, likely malformed data";
    case ParseError::OutOfMemory:
        return "The parser hit an OOM condition";
    case ParseError::ExpectedFloatingImmediate:
        return "Expected a floating point immediate";
    case ParseError::ExpectedSignedImmediate:
        return "Expected a signed integer immediate";
    case ParseError::InvalidImmediate:
        return "A parsed instruction immediate was invalid for the instruction it was used for";
    case ParseError::UnknownInstruction:
        return "A parsed instruction was not known to this parser";
    }
    return "Unknown error";
}
}