-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathWat.lean
More file actions
3063 lines (2919 loc) · 134 KB
/
Copy pathWat.lean
File metadata and controls
3063 lines (2919 loc) · 134 KB
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
import Interpreter.Wasm.Syntax
import Std.Data.HashMap
/-!
# WAT decoder
A small parser for the WebAssembly text format, targeting Wasm's AST.
Supported:
* `(module ...)` with any number of `(func ...)` definitions.
* `(type ...)`, `(export ...)`, `(import ...)`, `(table ...)`, `(memory ...)`,
`(global ...)`, `(elem ...)`, `(data ...)`, `(tag ...)`, `(start ...)` —
recognized at the module level and fully parsed into the resulting
`Wasm.Module`. Non-func imports (`(import … (memory|global|table …))`)
are parsed too: each becomes a placeholder decl at the low end of its
index space and is recorded in `importedGlobals`/`importedTables`/
`importedMemories` for later host substitution.
* Func headers may include `(type N)`, `(param ...)*`, `(result ...)*`,
`(local ...)*` in any order, with grouped or singleton declarations.
* Linear instruction stream and folded operand expressions
(`(i32.add (i32.const 1) (i32.const 2))`).
* Structured forms `block ... end`, `loop ... end`, `if ... else? ... end`,
plus folded `(block …)`, `(loop …)`, `(if …)` forms.
* `br N`, `br_if N`, `br_table … N`, `call N`, `return`, `drop`, `select`,
i32 / i64 numeric/comparison/bitwise/shift/rotate/conversion ops.
* Signed integer literals (`-`, `+`), hex (`0x…`/`0X…`) with mixed case, and
underscore separators (`1_000_000`, `0xa_0f_00_99`).
* Numeric indices and symbolic identifiers (`$L`).
* `(;0;)` block comments and `;;` line comments are stripped during tokenization.
Memory loads/stores, `memory.*`, globals, `call_indirect`, tables,
floats, and SIMD are all modelled and decode to real instructions.
Instructions from proposals the interpreter still doesn't model (e.g.
atomics/threads) are accepted lexically but lowered to
`Wasm.Instruction.unreachable` so the surrounding function still
type-checks. `local.tee i` is desugared to `[local.set i; local.get i]`. -/
namespace Wasm.Decoder.Wat
inductive Sexpr where
| atom (s : String)
| list (xs : List Sexpr)
deriving Inhabited, Repr
abbrev Err := String
private def isWatSpace (c : Char) : Bool :=
c = ' ' || c = '\t' || c = '\n' || c = '\r'
private def isAtomChar (c : Char) : Bool :=
¬ (isWatSpace c || c = '(' || c = ')')
private partial def dropLine : List Char → List Char
| [] => []
| '\n' :: r => '\n' :: r
| _ :: r => dropLine r
private partial def dropBlock : Nat → List Char → List Char
| _, [] => []
| depth, '(' :: ';' :: r => dropBlock (depth + 1) r
| 0, ';' :: ')' :: r => r
| depth + 1, ';' :: ')' :: r => dropBlock depth r
| depth, _ :: r => dropBlock depth r
private partial def copyString (cs : List Char) (acc : List Char) : List Char × List Char :=
match cs with
| [] => ([], acc)
| '"' :: rest => (rest, '"' :: acc)
| '\\' :: c :: rest => copyString rest (c :: '\\' :: acc)
| c :: rest => copyString rest (c :: acc)
private partial def stripCommentsAux (cs : List Char) (acc : List Char) : List Char :=
match cs with
| ';' :: ';' :: rest => stripCommentsAux (dropLine rest) acc
| '(' :: ';' :: rest => stripCommentsAux (dropBlock 0 rest) acc
| '"' :: rest =>
let (rest', acc') := copyString rest ('"' :: acc)
stripCommentsAux rest' acc'
| c :: rest => stripCommentsAux rest (c :: acc)
| [] => acc.reverse
private def stripComments (s : String) : String :=
String.ofList (stripCommentsAux s.toList [])
private partial def tokenizeAux (cs : List Char) (acc : List String) : List String :=
match cs with
| [] => acc.reverse
| c :: rest =>
if isWatSpace c then
tokenizeAux rest acc
else if c = '(' then
tokenizeAux rest ("(" :: acc)
else if c = ')' then
tokenizeAux rest (")" :: acc)
else if c = '"' then
let (body, rest') := readString rest []
tokenizeAux rest' (body :: acc)
else
let (atomChars, rest') := rest.span isAtomChar
let atom := String.ofList (c :: atomChars)
tokenizeAux rest' (atom :: acc)
where
readString : List Char → List Char → String × List Char
| [], acc => (String.ofList ('"' :: acc.reverse), [])
| '"' :: rest, acc =>
(String.ofList ('"' :: (acc.reverse ++ ['"'])), rest)
| '\\' :: c :: rest, acc => readString rest (c :: '\\' :: acc)
| c :: rest, acc => readString rest (c :: acc)
private def tokenize (s : String) : List String :=
tokenizeAux (stripComments s).toList []
partial def parseSexprs : List String → Except Err (List Sexpr × List String)
| [] => .ok ([], [])
| ")" :: rest => .ok ([], ")" :: rest)
| "(" :: rest => do
let (children, rest1) ← parseSexprs rest
match rest1 with
| ")" :: rest2 =>
let (siblings, rest3) ← parseSexprs rest2
.ok (Sexpr.list children :: siblings, rest3)
| _ => .error "unbalanced parens: missing ')'"
| tok :: rest => do
let (siblings, rest1) ← parseSexprs rest
.ok (Sexpr.atom tok :: siblings, rest1)
def parseAll (s : String) : Except Err (List Sexpr) := do
let (xs, rest) ← parseSexprs (tokenize s)
match rest with
| [] => .ok xs
| _ => .error "unexpected ')'"
private def fromHexString? (s : String) : Option Nat := Id.run do
if s.isEmpty then return none
let mut acc := 0
for c in s.toList do
let d := if c.isDigit then some (c.toNat - '0'.toNat)
else if 'a' ≤ c ∧ c ≤ 'f' then some (10 + c.toNat - 'a'.toNat)
else if 'A' ≤ c ∧ c ≤ 'F' then some (10 + c.toNat - 'A'.toNat)
else none
match d with
| none => return none
| some d => acc := acc * 16 + d
return some acc
private def stripUnderscores (s : String) : String :=
String.ofList (s.toList.filter (· ≠ '_'))
private def parseUnsignedNat (s : String) : Except Err Nat :=
if s.isEmpty then .error "empty integer literal"
else if s.startsWith "0x" || s.startsWith "0X" then
match fromHexString? (s.drop 2).toString with
| some n => .ok n
| none => .error s!"bad integer literal: {s}"
else
match s.toNat? with
| some n => .ok n
| none => .error s!"bad integer literal: {s}"
def parseU32 (s : String) : Except Err UInt32 := do
let n ← parseUnsignedNat s
if n ≥ 2 ^ 32 then .error s!"integer out of range: {s}"
else .ok (UInt32.ofNat n)
private def parseNat (s : String) : Except Err Nat := do
let v ← parseU32 s
.ok v.toNat
private def parseIntLiteral (s : String) (bits : Nat) : Except Err Nat := do
let (neg, body0) :=
if s.startsWith "-" then (true, (s.drop 1).toString)
else if s.startsWith "+" then (false, (s.drop 1).toString)
else (false, s)
let body := stripUnderscores body0
let n ← parseUnsignedNat body
let bound := 2 ^ bits
let halfBound := 2 ^ (bits - 1)
if neg then
if n > halfBound then .error s!"integer out of range: {s}"
else .ok ((bound - n) % bound)
else
if n ≥ bound then .error s!"integer out of range: {s}"
else .ok n
def parseI32 (s : String) : Except Err UInt32 := do
let n ← parseIntLiteral s 32
.ok (UInt32.ofNat n)
def parseI64 (s : String) : Except Err UInt64 := do
let n ← parseIntLiteral s 64
.ok (UInt64.ofNat n)
/-! ## Float literal parsing
`wasm-tools print` emits float constants as hex floats (`0x1.91eb86p+1`),
`inf`, `nan`, or `nan:0x…`; raw `.wat` may also use decimal (`3.14`, `1e10`).
A hex float is `mantissa · 2^exp`, which native `Float` reproduces exactly;
decimal goes through `Float.ofScientific` (correctly rounded). The `f32`
encoder rounds the `f64` magnitude to single precision — exact for every
value `wasm-tools` prints, since those round-trip. -/
private def floatMulPow2 : Float → Nat → Float
| x, 0 => x
| x, n + 1 => floatMulPow2 (x * 2.0) n
private def floatDivPow2 : Float → Nat → Float
| x, 0 => x
| x, n + 1 => floatDivPow2 (x / 2.0) n
private def floatScalePow2 (x : Float) (e : Int) : Float :=
if e ≥ 0 then floatMulPow2 x e.toNat else floatDivPow2 x (-e).toNat
private def parseDecExp (s : String) : Except Err Int :=
if s.isEmpty then .ok 0
else
let (neg, body) :=
if s.startsWith "-" then (true, (s.drop 1).toString)
else if s.startsWith "+" then (false, (s.drop 1).toString)
else (false, s)
match body.toNat? with
| some n => .ok (if neg then -(Int.ofNat n) else Int.ofNat n)
| none => .error s!"bad float exponent: {s}"
/-- Magnitude of a hex float `INT[.FRAC][p±EXP]` (no `0x`, no sign). -/
private def parseHexFloatMag (body : String) : Except Err Float := do
let (mant, expS) := match (body.replace "P" "p").splitOn "p" with
| [m] => (m, "")
| m :: e :: _ => (m, e)
| [] => ("", "")
let (intH, fracH) := match mant.splitOn "." with
| [i] => (i, "")
| i :: f :: _ => (i, f)
| [] => ("", "")
let m := (fromHexString? (intH ++ fracH)).getD 0
let e ← parseDecExp expS
.ok (floatScalePow2 (Float.ofNat m) (e - 4 * Int.ofNat fracH.length))
/-- Magnitude of a decimal float `INT[.FRAC][e±EXP]` (no sign). -/
private def parseDecFloatMag (body : String) : Except Err Float := do
let (mant, expS) := match (body.replace "E" "e").splitOn "e" with
| [m] => (m, "")
| m :: e :: _ => (m, e)
| [] => ("", "")
let (intP, fracP) := match mant.splitOn "." with
| [i] => (i, "")
| i :: f :: _ => (i, f)
| [] => ("", "")
let m := ((intP ++ fracP).toNat?).getD 0
let de ← parseDecExp expS
let exp := de - Int.ofNat fracP.length
.ok (Float.ofScientific m (exp < 0) exp.natAbs)
/-- Sign and width-independent body of a float literal. -/
private inductive FloatLitBody where
| finite (mag : Float)
| inf
| nan (payload : Option Nat)
private def classifyFloatLit (s : String) : Except Err (Bool × FloatLitBody) := do
let (neg, r0) :=
if s.startsWith "-" then (true, (s.drop 1).toString)
else if s.startsWith "+" then (false, (s.drop 1).toString)
else (false, s)
let r := stripUnderscores r0
if r == "inf" then .ok (neg, .inf)
else if r == "nan" || r == "nan:canonical" || r == "nan:arithmetic" then
.ok (neg, .nan none)
else if r.startsWith "nan:0x" then
match fromHexString? (r.drop 6).toString with
| some p => .ok (neg, .nan (some p))
| none => .error s!"bad nan payload: {s}"
else if r.startsWith "0x" || r.startsWith "0X" then
.ok (neg, .finite (← parseHexFloatMag (r.drop 2).toString))
else
.ok (neg, .finite (← parseDecFloatMag r))
/-- Parse a WAT `f64` literal into its 64-bit IEEE-754 encoding. -/
def parseF64Lit (s : String) : Except Err UInt64 := do
match (← classifyFloatLit s) with
| (neg, .finite mag) => .ok (if neg then (-mag).toBits else mag.toBits)
| (neg, .inf) => .ok (if neg then 0xFFF0000000000000 else 0x7FF0000000000000)
| (neg, .nan none) => .ok (if neg then 0xFFF8000000000000 else 0x7FF8000000000000)
| (neg, .nan (some p)) =>
let base : UInt64 := 0x7FF0000000000000 ||| UInt64.ofNat (p % 0x10000000000000)
.ok (if neg then base ||| 0x8000000000000000 else base)
/-- Parse a WAT `f32` literal into its 32-bit IEEE-754 encoding. -/
def parseF32Lit (s : String) : Except Err UInt32 := do
match (← classifyFloatLit s) with
| (neg, .finite mag) => .ok (if neg then (-mag).toFloat32.toBits else mag.toFloat32.toBits)
| (neg, .inf) => .ok (if neg then 0xFF800000 else 0x7F800000)
| (neg, .nan none) => .ok (if neg then 0xFFC00000 else 0x7FC00000)
| (neg, .nan (some p)) =>
let base : UInt32 := 0x7F800000 ||| UInt32.ofNat (p % 0x800000)
.ok (if neg then base ||| 0x80000000 else base)
/-- Decode a value-type atom. Numeric types and the two reference types
of wasm 2.0 (`funcref`, `externref`) are modelled directly. Types from
proposals the interpreter doesn't yet model (SIMD, GC) are accepted at
the decoder level — silently normalised to `i32` — so that modules
which include such types in *signatures* still decode. Functions whose
bodies actually touch those types will hit `unreachable` (because the
corresponding instructions are also lowered to `unreachable`), giving
the testsuite runner a chance to run any supported exports declared in
the same module. -/
private def atomToValueType? : String → Option Wasm.ValueType
| "i32" => some .i32
| "i64" => some .i64
| "f32" => some .f32
| "f64" => some .f64
| "funcref" => some .funcref
| "externref" => some .externref
| "exnref" => some .exnref
| "v128" => some .v128
-- GC managed reference types (GC proposal) collapse to the `anyref` slot.
| "anyref" => some .anyref
| "eqref" => some .anyref
| "i31ref" => some .anyref
| "structref" => some .anyref
| "arrayref" => some .anyref
| "nullref" => some .anyref
| "nullfuncref" => some .funcref
| "nullexternref" => some .externref
| _ => none
private def isNullFuncrefHeapType (ht : String) : Bool :=
ht == "func" || ht == "nofunc"
private def isNullExternrefHeapType (ht : String) : Bool :=
ht == "extern" || ht == "noextern"
/-- Decode a reference value-type written in list form, e.g.
`(ref func)`, `(ref null extern)`, `(ref $t)`. Symbolic and numeric heap
types refer to the type table — pre-GC those are function types, so they
map to `funcref`; GC heap types keep the `i32` placeholder used for
unmodelled proposals. -/
private def listToValueType (xs : List Sexpr) : Wasm.ValueType :=
match xs with
| [.atom "ref", .atom ht] | [.atom "ref", .atom "null", .atom ht] =>
if isNullFuncrefHeapType ht then .funcref
else if isNullExternrefHeapType ht then .externref
-- GC abstract heap types (GC proposal): a managed reference type, so its
-- zero is the managed null `anyref`.
else if ht == "any" || ht == "eq" || ht == "i31"
|| ht == "struct" || ht == "array" || ht == "none" then .anyref
-- A concrete `(ref $t)` / `(ref N)` in GC modules is overwhelmingly a
-- struct/array type; treat it as a managed reference so its zero is the
-- managed null. (Typed-funcref locals are set before use, so only the
-- unused zero-init differs.)
else if ht.startsWith "$" || ht.all Char.isDigit then .anyref
else .i32
| _ => .i32
/-- Resolve a `(type N)` reference on a block/loop/if to the signature
declared in the module's type table. Returns `none` if the index/id is
unknown or the entry's signature is outside our supported integer
subset; callers fall back to whatever inline `(param ...)` /
`(result ...)` annotations follow. Constructed by `parseFunc` and
threaded through `Ctx` so block/loop/if parsing can see the type table. -/
abbrev BlockTypeResolver :=
String → Option (List Wasm.ValueType × List Wasm.ValueType)
/-- Skip block/loop/if type annotations and collect explicit param/result
types. The block constructors `Wasm.Instruction.block` / `loop` / `iff`
carry only arities (`paramArity`, `resultArity`), so we throw away the
element types after counting them — but we *do* honour `(type N)`
references by consulting the module's type table via `resolveType`, so
a `block (type $sig)` whose entry declares non-zero arities is parsed
with the correct arities instead of silently degenerating to `0 0`. -/
private partial def skipBlockType (resolveType : BlockTypeResolver) :
List Wasm.ValueType → List Wasm.ValueType → List Sexpr →
List Wasm.ValueType × List Wasm.ValueType × List Sexpr
| ps, rs, .list (.atom "result" :: ts) :: r =>
let extra := ts.filterMap fun
| .atom a => atomToValueType? a
| .list l => some (listToValueType l)
skipBlockType resolveType ps (rs ++ extra) r
| ps, rs, .list (.atom "param" :: ts) :: r =>
let extra := ts.filterMap fun
| .atom a => atomToValueType? a
| .list l => some (listToValueType l)
skipBlockType resolveType (ps ++ extra) rs r
| ps, rs, .list (.atom "type" :: .atom ref :: _) :: r =>
-- A `(type N)` annotation adopts the type-table entry's signature as
-- the block's arity. wasm-tools commonly emits a redundant
-- `(type N) (param …) (result …)` triple where the inline forms
-- restate the resolved signature, so we also consume any trailing
-- `(param …)` / `(result …)` siblings to avoid double-counting.
-- If resolution fails, fall through to the inline accumulators.
match resolveType ref with
| some (resolvedPs, resolvedRs) =>
let r' := r.dropWhile fun
| .list (.atom "param" :: _) => true
| .list (.atom "result" :: _) => true
| _ => false
(resolvedPs, resolvedRs, r')
| none => skipBlockType resolveType ps rs r
| ps, rs, .list (.atom "type" :: _) :: r =>
-- Malformed `(type …)` form (no atom reference) — preserve the old
-- behaviour of silently advancing the token stream.
skipBlockType resolveType ps rs r
| ps, rs, .atom a :: r =>
match atomToValueType? a with
| some t => (ps, rs ++ [t], r)
| none => (ps, rs, .atom a :: r)
| ps, rs, xs => (ps, rs, xs)
/-- Pull an optional `$label` and any `(type N)` / `(param T*)` /
`(result T*)` annotations off the front of a block/loop/if's tokens.
Returns the label (if any), parameter arity, result arity, and the
remaining tokens. `resolveType` looks up `(type N)` references against
the module's type table; pass `fun _ => none` (or `Ctx.empty`'s default)
when no type table is available. -/
private def parseBlockHeader (resolveType : BlockTypeResolver) (xs : List Sexpr)
: Option String × Nat × Nat × List Sexpr :=
match xs with
| .atom a :: r =>
if a.startsWith "$" then
let (ps, rs, r') := skipBlockType resolveType [] [] r
(some (a.drop 1).toString, ps.length, rs.length, r')
else
let (ps, rs, r') := skipBlockType resolveType [] [] xs
(none, ps.length, rs.length, r')
| _ =>
let (ps, rs, r') := skipBlockType resolveType [] [] xs
(none, ps.length, rs.length, r')
/-- A module-level `(type (func …))` declaration: optional symbolic id and
the signature, if it has one we can model. Pulled up before `Ctx` so the
ctx can carry the collected type table for `call_indirect (type N)`
resolution. -/
private structure TypeEntry where
symId : Option String
sig : Option (List Wasm.ValueType × List Wasm.ValueType)
/-- GC composite type (struct/array/func) for this entry, if recognised
(GC proposal). Filled alongside `sig`. -/
comp : Option Wasm.CompositeType := none
/-- Unresolved `sub $super` reference, resolved to an index in
`parseModule` once the whole type table is known. -/
superRef : Option String := none
/-- For a struct type, the field names (`(field $x …)`), positionally;
`none` for anonymous fields. Used to resolve `struct.get $t $field`. -/
fieldNames : List (Option String) := []
/-- `false` when declared `(sub …)` without `final` (open for subtyping). -/
isFinal : Bool := true
deriving Inhabited
structure Ctx where
funcIds : Std.HashMap String Nat
localIds : Std.HashMap String Nat
globalIds : Std.HashMap String Nat := {}
labelNames : List (Option String) := []
/-- All `(type (func …))` declarations collected at module level, in
source order. Carries the symbolic id (if any) and signature so
`call_indirect (type $T)` can resolve to a numeric type index. -/
types : Array TypeEntry := #[]
/-- `$name → table index` for `(table $name ...)` declarations. The
testsuite almost always uses table 0 implicitly, but the form is
legal. -/
tableNames : Std.HashMap String Nat := {}
/-- `$name → element segment index` for `(elem $name ...)` declarations,
so `table.init` / `elem.drop` can resolve symbolic segment refs. -/
elemNames : Std.HashMap String Nat := {}
/-- `$name → memory index` for `(memory $name ...)` declarations
(multi-memory). -/
memNames : Std.HashMap String Nat := {}
/-- `$name → tag index` for `(tag $name ...)` declarations
(exception handling). -/
tagNames : Std.HashMap String Nat := {}
/-- Resolves `(type N)` / `(type $sig)` references on `block`/`loop`/`if`
to the parsed signature, so multi-value block-types declared via the
type table are decoded with their correct arity. Defaults to "always
none" — callers without a type table behave exactly as before. -/
resolveBlockType : BlockTypeResolver := fun _ => none
def Ctx.empty : Ctx := { funcIds := {}, localIds := {} }
def Ctx.pushLabel (ctx : Ctx) (name : Option String) : Ctx :=
{ ctx with labelNames := name :: ctx.labelNames }
private def resolveNamed (table : Std.HashMap String Nat) (kind : String)
(s : String) : Except Err Nat :=
if s.startsWith "$" then
match table[(s.drop 1).toString]? with
| some i => .ok i
| none => .error s!"unknown {kind} id: {s}"
else parseNat s
/-- Decode a `ref.null ht` heap-type immediate into the matching null-ref
push. Heap types from proposals we don't model decode to `unreachable`
(consistent with their other instructions). -/
private def refNullInstr (types : Array TypeEntry) (ht : String) : Wasm.Instruction :=
if isNullFuncrefHeapType ht then .refNull
else if isNullExternrefHeapType ht then .refNullExtern
-- GC abstract heap types (GC proposal): the null they denote is the
-- shared managed null `anyref`.
else if ht == "any" || ht == "eq" || ht == "i31"
|| ht == "struct" || ht == "array" || ht == "none" then .gc .refNullAny
-- Exception heap types (exception-handling proposal): the null they denote
-- is the null `exnref`.
else if ht == "exn" || ht == "noexn" then .refNullExn
-- Concrete heap types (`$t` / numeric): a struct/array type denotes the
-- managed null; a function type denotes the null funcref.
else if ht.startsWith "$" || ht.all Char.isDigit then
let idx? := if ht.startsWith "$" then
types.findIdx? (·.symId = some (ht.drop 1).toString)
else ht.toNat?
match idx?.bind (fun i => (types[i]?).bind (·.comp)) with
| some (.struct _) | some (.array _) => .gc .refNullAny
| _ => .refNull
else .unreachable
private def dropTrailingLabel : List Sexpr → List Sexpr
| .atom a :: r => if a.startsWith "$" then r else .atom a :: r
| xs => xs
private def resolveLabel (ctx : Ctx) (s : String) : Except Err Nat :=
if s.startsWith "$" then
let name := (s.drop 1).toString
match ctx.labelNames.findIdx? (fun n => n = some name) with
| some i => .ok i
| none => .error s!"unknown label id: {s}"
else parseNat s
/-- Parse a single bare-op atom (no immediate, no folded operands). -/
private def parsePlainOp : String → Except Err Wasm.Instruction
| "i32.add" => .ok .add
| "i32.sub" => .ok .sub
| "i32.mul" => .ok .mul
| "i32.div_u" => .ok .divU
| "i32.div_s" => .ok .divS
| "i32.rem_u" => .ok .remU
| "i32.rem_s" => .ok .remS
| "i32.eqz" => .ok .eqz
| "i32.eq" => .ok .eq
| "i32.ne" => .ok .ne
| "i32.lt_u" => .ok .ltU
| "i32.lt_s" => .ok .ltS
| "i32.gt_u" => .ok .gtU
| "i32.gt_s" => .ok .gtS
| "i32.le_u" => .ok .leU
| "i32.le_s" => .ok .leS
| "i32.ge_u" => .ok .geU
| "i32.ge_s" => .ok .geS
| "i32.and" => .ok .and
| "i32.or" => .ok .or
| "i32.xor" => .ok .xor
| "i32.shl" => .ok .shl
| "i32.shr_u" => .ok .shrU
| "i32.shr_s" => .ok .shrS
| "i32.rotl" => .ok .rotl
| "i32.rotr" => .ok .rotr
| "i32.clz" => .ok .clz
| "i32.ctz" => .ok .ctz
| "i32.popcnt" => .ok .popcnt
| "i64.add" => .ok .addI64
| "i64.sub" => .ok .subI64
| "i64.mul" => .ok .mulI64
| "i64.eq" => .ok .eqI64
| "i64.lt_s" => .ok .ltSI64
| "i64.gt_s" => .ok .gtSI64
| "i64.gt_u" => .ok .gtUI64
| "i64.lt_u" => .ok .ltUI64
| "i64.le_u" => .ok .leUI64
| "i64.le_s" => .ok .leSI64
| "i64.ge_u" => .ok .geUI64
| "i64.ge_s" => .ok .geSI64
| "i64.ne" => .ok .neI64
| "i64.eqz" => .ok .eqzI64
| "i64.div_u" => .ok .divUI64
| "i64.div_s" => .ok .divSI64
| "i64.rem_u" => .ok .remUI64
| "i64.rem_s" => .ok .remSI64
| "i64.and" => .ok .andI64
| "i64.or" => .ok .orI64
| "i64.xor" => .ok .xorI64
| "i64.shl" => .ok .shlI64
| "i64.shr_u" => .ok .shrUI64
| "i64.shr_s" => .ok .shrSI64
| "i64.rotl" => .ok .rotlI64
| "i64.rotr" => .ok .rotrI64
| "i64.clz" => .ok .clzI64
| "i64.ctz" => .ok .ctzI64
| "i64.popcnt" => .ok .popcntI64
| "i32.wrap_i64" => .ok .wrapI64
| "i64.extend_i32_s" => .ok .extendSI32
| "i64.extend_i32_u" => .ok .extendUI32
| "i32.extend8_s" => .ok .extend8S
| "i32.extend16_s" => .ok .extend16S
| "i64.extend8_s" => .ok .extend8SI64
| "i64.extend16_s" => .ok .extend16SI64
| "i64.extend32_s" => .ok .extend32SI64
| "drop" => .ok .drop
| "return" => .ok .ret
| "select" => .ok .select
| "nop" => .ok .nop
| "unreachable" => .ok .unreachable
-- f32 arithmetic / unary / comparison
| "f32.add" => .ok .f32Add
| "f32.sub" => .ok .f32Sub
| "f32.mul" => .ok .f32Mul
| "f32.div" => .ok .f32Div
| "f32.min" => .ok .f32Min
| "f32.max" => .ok .f32Max
| "f32.copysign" => .ok .f32Copysign
| "f32.abs" => .ok .f32Abs
| "f32.neg" => .ok .f32Neg
| "f32.sqrt" => .ok .f32Sqrt
| "f32.ceil" => .ok .f32Ceil
| "f32.floor" => .ok .f32Floor
| "f32.trunc" => .ok .f32Trunc
| "f32.nearest" => .ok .f32Nearest
| "f32.eq" => .ok .f32Eq
| "f32.ne" => .ok .f32Ne
| "f32.lt" => .ok .f32Lt
| "f32.gt" => .ok .f32Gt
| "f32.le" => .ok .f32Le
| "f32.ge" => .ok .f32Ge
-- f64 arithmetic / unary / comparison
| "f64.add" => .ok .f64Add
| "f64.sub" => .ok .f64Sub
| "f64.mul" => .ok .f64Mul
| "f64.div" => .ok .f64Div
| "f64.min" => .ok .f64Min
| "f64.max" => .ok .f64Max
| "f64.copysign" => .ok .f64Copysign
| "f64.abs" => .ok .f64Abs
| "f64.neg" => .ok .f64Neg
| "f64.sqrt" => .ok .f64Sqrt
| "f64.ceil" => .ok .f64Ceil
| "f64.floor" => .ok .f64Floor
| "f64.trunc" => .ok .f64Trunc
| "f64.nearest" => .ok .f64Nearest
| "f64.eq" => .ok .f64Eq
| "f64.ne" => .ok .f64Ne
| "f64.lt" => .ok .f64Lt
| "f64.gt" => .ok .f64Gt
| "f64.le" => .ok .f64Le
| "f64.ge" => .ok .f64Ge
-- integer → float
| "f32.convert_i32_s" => .ok .f32ConvertI32S
| "f32.convert_i32_u" => .ok .f32ConvertI32U
| "f32.convert_i64_s" => .ok .f32ConvertI64S
| "f32.convert_i64_u" => .ok .f32ConvertI64U
| "f64.convert_i32_s" => .ok .f64ConvertI32S
| "f64.convert_i32_u" => .ok .f64ConvertI32U
| "f64.convert_i64_s" => .ok .f64ConvertI64S
| "f64.convert_i64_u" => .ok .f64ConvertI64U
-- float → integer (trapping)
| "i32.trunc_f32_s" => .ok .i32TruncF32S
| "i32.trunc_f32_u" => .ok .i32TruncF32U
| "i32.trunc_f64_s" => .ok .i32TruncF64S
| "i32.trunc_f64_u" => .ok .i32TruncF64U
| "i64.trunc_f32_s" => .ok .i64TruncF32S
| "i64.trunc_f32_u" => .ok .i64TruncF32U
| "i64.trunc_f64_s" => .ok .i64TruncF64S
| "i64.trunc_f64_u" => .ok .i64TruncF64U
-- float → integer (saturating)
| "i32.trunc_sat_f32_s" => .ok .i32TruncSatF32S
| "i32.trunc_sat_f32_u" => .ok .i32TruncSatF32U
| "i32.trunc_sat_f64_s" => .ok .i32TruncSatF64S
| "i32.trunc_sat_f64_u" => .ok .i32TruncSatF64U
| "i64.trunc_sat_f32_s" => .ok .i64TruncSatF32S
| "i64.trunc_sat_f32_u" => .ok .i64TruncSatF32U
| "i64.trunc_sat_f64_s" => .ok .i64TruncSatF64S
| "i64.trunc_sat_f64_u" => .ok .i64TruncSatF64U
-- float ↔ float and bitwise reinterpret
| "f32.demote_f64" => .ok .f32DemoteF64
| "f64.promote_f32" => .ok .f64PromoteF32
| "i32.reinterpret_f32" => .ok .i32ReinterpretF32
| "i64.reinterpret_f64" => .ok .i64ReinterpretF64
| "f32.reinterpret_i32" => .ok .f32ReinterpretI32
| "f64.reinterpret_i64" => .ok .f64ReinterpretI64
| "ref.is_null" => .ok .refIsNull
-- GC reference instructions (GC proposal).
| "ref.i31" => .ok (.gc .refI31)
| "i31.get_s" => .ok (.gc .i31GetS)
| "i31.get_u" => .ok (.gc .i31GetU)
| "ref.eq" => .ok (.gc .refEq)
| op =>
-- Fallback for mnemonics not matched above (and not caught by
-- `simdOp?`): still-unmodelled proposals such as atomics/threads and
-- relaxed SIMD, plus stray leftovers from partly-modelled proposals
-- (reference types, tables, GC, exceptions, tail calls). Lower them to
-- `unreachable` so modules whose *signatures* or unrelated functions
-- touch these features still decode; a function that actually executes
-- such an instruction traps with "unreachable" instead of failing to
-- decode at all, which would cascade to every assert in the file.
if op.startsWith "f32." || op.startsWith "f64." || op.startsWith "v128."
|| op.startsWith "i8x16." || op.startsWith "i16x8." || op.startsWith "i32x4."
|| op.startsWith "i64x2." || op.startsWith "f32x4." || op.startsWith "f64x2."
|| op.startsWith "ref." || op.startsWith "table." || op.startsWith "elem."
|| op.startsWith "struct." || op.startsWith "array." || op.startsWith "i31."
|| op.startsWith "br_on_" || op.startsWith "extern."
|| op == "throw" || op == "throw_ref" || op == "rethrow" || op == "try"
|| op == "try_table" || op == "catch" || op == "catch_all" || op == "delegate"
|| op == "return_call" || op == "return_call_indirect" || op == "return_call_ref"
|| op == "call_ref" || op == "any.convert_extern"
|| op == "memory.atomic.notify" || op.startsWith "memory.atomic."
|| op.startsWith "atomic." then
.ok .unreachable
else
.error s!"unsupported instruction: {op}"
/-- Memory ops that take an offset immediate, mapped to their natural
alignment (byte width). `offset=`/`align=` attributes are parsed off the
token stream; `memOpToInstruction` then emits the real load/store. -/
private def isMemOp (op : String) : Option Nat :=
match op with
| "i32.load" => some 4
| "i32.load8_u" | "i32.load8_s" => some 1
| "i32.load16_u" | "i32.load16_s" => some 2
| "i32.store" => some 4
| "i32.store8" => some 1
| "i32.store16" => some 2
| "i64.load" => some 8
| "i64.load8_u" | "i64.load8_s" => some 1
| "i64.load16_u" | "i64.load16_s" => some 2
| "i64.load32_u" | "i64.load32_s" => some 4
| "i64.store" => some 8
| "i64.store8" => some 1
| "i64.store16" => some 2
| "i64.store32" => some 4
-- Float and SIMD memory ops (their offset=/align= attributes parsed the
-- same way); `memOpToInstruction` emits the matching real load/store.
| "f32.load" | "f32.store" => some 4
| "f64.load" | "f64.store" => some 8
| "v128.load" | "v128.store" => some 16
| "v128.load8x8_u" | "v128.load8x8_s" => some 8
| "v128.load16x4_u" | "v128.load16x4_s" => some 8
| "v128.load32x2_u" | "v128.load32x2_s" => some 8
| "v128.load8_splat" => some 1
| "v128.load16_splat" => some 2
| "v128.load32_splat" | "v128.load32_zero" => some 4
| "v128.load64_splat" | "v128.load64_zero" => some 8
| "v128.load8_lane" | "v128.store8_lane" => some 1
| "v128.load16_lane" | "v128.store16_lane" => some 2
| "v128.load32_lane" | "v128.store32_lane" => some 4
| "v128.load64_lane" | "v128.store64_lane" => some 8
| _ => none
private def parseEqImmediate (pref : String) (s : String) : Option Nat :=
if s.startsWith pref then
let body := stripUnderscores (s.drop pref.length).toString
match parseUnsignedNat body with
| .ok n => some n
| .error _ => none
else none
private def isPowerOfTwo (n : Nat) : Bool :=
n ≠ 0 && n &&& (n - 1) = 0
/-- Pull optional `offset=N` and `align=N` atoms off the front of `toks`.
Returns the parsed byte offset (default 0) and the remaining tokens. -/
private def consumeMemAttrs (natAlign : Nat) (toks : List Sexpr)
: Except Err (UInt32 × List Sexpr) :=
let rec loop (offset : UInt32) (toks : List Sexpr) : Except Err (UInt32 × List Sexpr) :=
match toks with
| .atom a :: r =>
match parseEqImmediate "offset=" a with
| some n => loop (UInt32.ofNat n) r
| none =>
match parseEqImmediate "align=" a with
| some n =>
if !isPowerOfTwo n then
.error s!"alignment must be a positive power of two: {a}"
else if n > natAlign then
.error s!"alignment must not exceed natural ({natAlign}): {a}"
else loop offset r
| none => .ok (offset, .atom a :: r)
| xs => .ok (offset, xs)
loop 0 toks
/-! ## SIMD mnemonic table
Shape-prefixed mnemonics (`i8x16.add`, `f64x2.pmin`, …) decode through
`simdOp?`; the per-shape availability of an op (e.g. `mul` only on
i16x8/i32x4/i64x2) is validation's concern, not the decoder's. -/
private def simdShapeOfPrefix? : String → Option Wasm.Simd.Shape
| "i8x16" => some .i8x16
| "i16x8" => some .i16x8
| "i32x4" => some .i32x4
| "i64x2" => some .i64x2
| "f32x4" => some .f32x4
| "f64x2" => some .f64x2
| _ => none
private def simdShapeIsFloat : Wasm.Simd.Shape → Bool
| .f32x4 | .f64x2 => true
| _ => false
private def simdICmp? : String → Option Wasm.Simd.ICmp
| "eq" => some .eq | "ne" => some .ne
| "lt_s" => some .ltS | "lt_u" => some .ltU
| "gt_s" => some .gtS | "gt_u" => some .gtU
| "le_s" => some .leS | "le_u" => some .leU
| "ge_s" => some .geS | "ge_u" => some .geU
| _ => none
private def simdFCmp? : String → Option Wasm.Simd.FCmp
| "eq" => some .eq | "ne" => some .ne
| "lt" => some .lt | "gt" => some .gt
| "le" => some .le | "ge" => some .ge
| _ => none
/-- Decode a no-immediate SIMD mnemonic. -/
private def simdOp? (op : String) : Option Wasm.Instruction :=
match op with
| "v128.not" => some (.vUnOp .not)
| "v128.and" => some (.vBinOp .and)
| "v128.andnot" => some (.vBinOp .andnot)
| "v128.or" => some (.vBinOp .or)
| "v128.xor" => some (.vBinOp .xor)
| "v128.bitselect" => some .vBitselect
| "v128.any_true" => some (.vTestOp .anyTrue)
| _ =>
match op.splitOn "." with
| [pre, name] =>
match simdShapeOfPrefix? pre with
| none => none
| some sh =>
let flt := simdShapeIsFloat sh
match name with
| "splat" => some (.vSplat sh)
| "all_true" => some (.vTestOp (.allTrue sh))
| "bitmask" => some (.vTestOp (.bitmask sh))
| "shl" => some (.vShiftOp (.shl sh))
| "shr_s" => some (.vShiftOp (.shrS sh))
| "shr_u" => some (.vShiftOp (.shrU sh))
| "neg" => some (.vUnOp (if flt then .fNeg sh else .intNeg sh))
| "abs" => some (.vUnOp (if flt then .fAbs sh else .intAbs sh))
| "popcnt" => some (.vUnOp .popcnt)
| "sqrt" => some (.vUnOp (.fSqrt sh))
| "ceil" => some (.vUnOp (.fCeil sh))
| "floor" => some (.vUnOp (.fFloor sh))
| "trunc" => some (.vUnOp (.fTrunc sh))
| "nearest" => some (.vUnOp (.fNearest sh))
| "add" => some (.vBinOp (if flt then .fAdd sh else .add sh))
| "sub" => some (.vBinOp (if flt then .fSub sh else .sub sh))
| "mul" => some (.vBinOp (if flt then .fMul sh else .mul sh))
| "div" => some (.vBinOp (.fDiv sh))
| "min" => some (.vBinOp (.fMin sh))
| "max" => some (.vBinOp (.fMax sh))
| "pmin" => some (.vBinOp (.fPmin sh))
| "pmax" => some (.vBinOp (.fPmax sh))
| "min_s" => some (.vBinOp (.minI sh true))
| "min_u" => some (.vBinOp (.minI sh false))
| "max_s" => some (.vBinOp (.maxI sh true))
| "max_u" => some (.vBinOp (.maxI sh false))
| "add_sat_s" => some (.vBinOp (.addSat sh true))
| "add_sat_u" => some (.vBinOp (.addSat sh false))
| "sub_sat_s" => some (.vBinOp (.subSat sh true))
| "sub_sat_u" => some (.vBinOp (.subSat sh false))
| "avgr_u" => some (.vBinOp (.avgrU sh))
| "swizzle" => some (.vBinOp .swizzle)
| "q15mulr_sat_s" => some (.vBinOp .q15mulrSatS)
| "dot_i16x8_s" => some (.vBinOp .dot)
| "demote_f64x2_zero" => some (.vUnOp .f32x4DemoteF64x2Zero)
| "promote_low_f32x4" => some (.vUnOp .f64x2PromoteLowF32x4)
| "trunc_sat_f32x4_s" => some (.vUnOp (.i32x4TruncSatF32x4 true))
| "trunc_sat_f32x4_u" => some (.vUnOp (.i32x4TruncSatF32x4 false))
| "trunc_sat_f64x2_s_zero" => some (.vUnOp (.i32x4TruncSatF64x2Zero true))
| "trunc_sat_f64x2_u_zero" => some (.vUnOp (.i32x4TruncSatF64x2Zero false))
| "convert_i32x4_s" => some (.vUnOp (.f32x4ConvertI32x4 true))
| "convert_i32x4_u" => some (.vUnOp (.f32x4ConvertI32x4 false))
| "convert_low_i32x4_s" => some (.vUnOp (.f64x2ConvertLowI32x4 true))
| "convert_low_i32x4_u" => some (.vUnOp (.f64x2ConvertLowI32x4 false))
-- Relaxed SIMD: deterministic choices coinciding with (or built
-- from) the non-relaxed semantics.
| "relaxed_swizzle" => some (.vBinOp .swizzle)
| "relaxed_min" => some (.vBinOp (.fMin sh))
| "relaxed_max" => some (.vBinOp (.fMax sh))
| "relaxed_q15mulr_s" => some (.vBinOp .q15mulrSatS)
| "relaxed_madd" => some (.vFma sh false)
| "relaxed_nmadd" => some (.vFma sh true)
| "relaxed_laneselect" => some .vBitselect
| "relaxed_trunc_f32x4_s" => some (.vUnOp (.i32x4TruncSatF32x4 true))
| "relaxed_trunc_f32x4_u" => some (.vUnOp (.i32x4TruncSatF32x4 false))
| "relaxed_trunc_f64x2_s_zero" => some (.vUnOp (.i32x4TruncSatF64x2Zero true))
| "relaxed_trunc_f64x2_u_zero" => some (.vUnOp (.i32x4TruncSatF64x2Zero false))
| "relaxed_dot_i8x16_i7x16_s" => some (.vBinOp .dotI8)
| "relaxed_dot_i8x16_i7x16_add_s" => some .vDotAdd
| _ =>
-- Suffix families: extend / extadd_pairwise / extmul / narrow /
-- comparisons. All encode signedness as a trailing `_s`/`_u`.
let signed := name.endsWith "_s"
if name.startsWith "extend_low_" || name.startsWith "extend_high_" then
some (.vUnOp (.extend sh (name.startsWith "extend_high_") signed))
else if name.startsWith "extadd_pairwise_" then
some (.vUnOp (.extaddPairwise sh signed))
else if name.startsWith "extmul_low_" || name.startsWith "extmul_high_" then
some (.vBinOp (.extmul sh (name.startsWith "extmul_high_") signed))
else if name.startsWith "narrow_" then
some (.vBinOp (.narrow sh signed))
else if flt then
(simdFCmp? name).map fun c => .vBinOp (.fcmp sh c)
else
(simdICmp? name).map fun c => .vBinOp (.cmp sh c)
| _ => none
/-- Parse the immediates of a `v128.const`: a shape atom followed by the
shape's lane count of literals. -/
private def parseV128Const (toks : List Sexpr)
: Except Err (BitVec 128 × List Sexpr) := do
match toks with
| .atom shapeName :: r =>
let sh ← match simdShapeOfPrefix? shapeName with
| some sh => .ok sh
| none => .error s!"v128.const: unknown shape `{shapeName}`"
let cnt := sh.laneCount
let mut lanes : List Nat := []
let mut rest := r
for _ in [0:cnt] do
match rest with
| .atom lit :: r' =>
let n : Nat ← match sh with
| .i8x16 => parseIntLiteral lit 8
| .i16x8 => parseIntLiteral lit 16
| .i32x4 => (·.toNat) <$> parseI32 lit
| .i64x2 => (·.toNat) <$> parseI64 lit
| .f32x4 => (·.toNat) <$> parseF32Lit lit
| .f64x2 => (·.toNat) <$> parseF64Lit lit
lanes := lanes ++ [n]
rest := r'
| _ => .error "v128.const: missing lane literal"
.ok (Wasm.Simd.ofLanes sh.laneBits lanes, rest)
| _ => .error "v128.const expects a shape immediate"
/-- Decode the lane-immediate SIMD ops (`extract_lane`, `replace_lane`):
returns the constructor to apply to the parsed lane index. -/
private def simdLaneOp? (op : String) : Option (Nat → Wasm.Instruction) :=
match op.splitOn "." with
| [pre, name] =>
match simdShapeOfPrefix? pre with
| none => none
| some sh =>
match name with
| "extract_lane" => some (.vExtractLane sh false)
| "extract_lane_s" => some (.vExtractLane sh true)
| "extract_lane_u" => some (.vExtractLane sh false)
| "replace_lane" => some (.vReplaceLane sh)
| _ => none
| _ => none
/-- Map a memory op name and byte offset to the appropriate instruction. -/
private def memOpToInstruction (op : String) (offset : UInt32) : Wasm.Instruction :=
match op with
| "i32.load" => .load32 offset
| "i32.load8_u" => .load8U offset
| "i32.load8_s" => .load8S offset
| "i32.load16_u" => .load16U offset
| "i32.load16_s" => .load16S offset
| "i32.store" => .store32 offset
| "i32.store8" => .store8 offset
| "i32.store16" => .store16 offset
| "i64.load" => .load64 offset
| "i64.store" => .store64 offset
| "i64.load8_u" => .load8UI64 offset
| "i64.load8_s" => .load8SI64 offset
| "i64.load16_u" => .load16UI64 offset
| "i64.load16_s" => .load16SI64 offset
| "i64.load32_u" => .load32UI64 offset
| "i64.load32_s" => .load32SI64 offset
| "i64.store8" => .store8I64 offset
| "i64.store16" => .store16I64 offset
| "i64.store32" => .store32I64 offset
| "f32.load" => .f32Load offset
| "f64.load" => .f64Load offset
| "f32.store" => .f32Store offset
| "f64.store" => .f64Store offset
| "v128.load" => .v128Load offset
| "v128.store" => .v128Store offset
| "v128.load8x8_s" => .v128LoadExt 8 true offset
| "v128.load8x8_u" => .v128LoadExt 8 false offset
| "v128.load16x4_s" => .v128LoadExt 16 true offset
| "v128.load16x4_u" => .v128LoadExt 16 false offset
| "v128.load32x2_s" => .v128LoadExt 32 true offset
| "v128.load32x2_u" => .v128LoadExt 32 false offset
| "v128.load8_splat" => .v128LoadSplat 8 offset
| "v128.load16_splat" => .v128LoadSplat 16 offset
| "v128.load32_splat" => .v128LoadSplat 32 offset
| "v128.load64_splat" => .v128LoadSplat 64 offset
| "v128.load32_zero" => .v128LoadZero 32 offset
| "v128.load64_zero" => .v128LoadZero 64 offset
| _ => .unreachable
/-- Map a lane-indexed v128 memory op (`v128.load8_lane` …) to its
instruction. Returns `none` for non-lane ops. -/
private def memLaneOpToInstruction (op : String) (offset : UInt32) (lane : Nat)
: Option Wasm.Instruction :=
match op with
| "v128.load8_lane" => some (.v128LoadLane 8 lane offset)
| "v128.load16_lane" => some (.v128LoadLane 16 lane offset)
| "v128.load32_lane" => some (.v128LoadLane 32 lane offset)
| "v128.load64_lane" => some (.v128LoadLane 64 lane offset)
| "v128.store8_lane" => some (.v128StoreLane 8 lane offset)
| "v128.store16_lane" => some (.v128StoreLane 16 lane offset)
| "v128.store32_lane" => some (.v128StoreLane 32 lane offset)
| "v128.store64_lane" => some (.v128StoreLane 64 lane offset)
| _ => none