From 9437179b9e9e6cbc11967a6d4c22f89345d168a3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Vouillon?= <jerome.vouillon@gmail.com>
Date: Tue, 20 Aug 2024 23:17:13 +0200
Subject: [PATCH] Emit try_table instruction

---
 compiler/lib/wasm/wa_wasm_output.ml | 11 ++++++-----
 compiler/lib/wasm/wa_wat_output.ml  | 17 ++++++-----------
 2 files changed, 12 insertions(+), 16 deletions(-)

diff --git a/compiler/lib/wasm/wa_wasm_output.ml b/compiler/lib/wasm/wa_wasm_output.ml
index a9980a245..a1ef4f731 100644
--- a/compiler/lib/wasm/wa_wasm_output.ml
+++ b/compiler/lib/wasm/wa_wasm_output.ml
@@ -630,15 +630,16 @@ end = struct
         output_byte ch 0x0B
     | Try (typ, l, catches) ->
         Feature.require exception_handling;
-        output_byte ch 0x06;
+        output_byte ch 0x1f;
         output_blocktype st.type_names ch typ;
-        List.iter ~f:(fun i' -> output_instruction st ch i') l;
+        output_uint ch (List.length catches);
         List.iter
-          ~f:(fun (tag, l, ty) ->
-            output_byte ch 0x07;
+          ~f:(fun (tag, l, _) ->
+            output_byte ch 0x00;
             output_uint ch (Hashtbl.find st.tag_names tag);
-            output_instruction st ch (Br (l + 1, Some (Pop ty))))
+            output_uint ch l)
           catches;
+        List.iter ~f:(fun i' -> output_instruction st ch i') l;
         output_byte ch 0X0B
 
   and output_instruction st ch i =
diff --git a/compiler/lib/wasm/wa_wat_output.ml b/compiler/lib/wasm/wa_wat_output.ml
index e921d23ec..6382a318d 100644
--- a/compiler/lib/wasm/wa_wat_output.ml
+++ b/compiler/lib/wasm/wa_wat_output.ml
@@ -444,18 +444,13 @@ let expression_or_instructions ctx st in_function =
         ]
     | Try (ty, body, catches) ->
         [ List
-            (Atom "try"
+            (Atom "try_table"
             :: (block_type st ty
-               @ List (Atom "do" :: instructions body)
-                 :: List.map
-                      ~f:(fun (tag, i, ty) ->
-                        List
-                          (Atom "catch"
-                          :: index st.tag_names tag
-                          :: (instruction
-                                (Wa_ast.Event Wa_code_generation.hidden_location)
-                             @ instruction (Wa_ast.Br (i + 1, Some (Pop ty))))))
-                      catches))
+               @ List.map
+                   ~f:(fun (tag, i, _ty) ->
+                     List [ Atom "catch"; index st.tag_names tag; Atom (string_of_int i) ])
+                   catches
+               @ instructions body))
         ]
   and instruction i =
     match i with