forked from WebAssembly/exception-handling
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharrange.ml
566 lines (473 loc) · 15.8 KB
/
arrange.ml
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
open Source
open Ast
open Script
open Values
open Types
open Sexpr
(* Generic formatting *)
let nat n = I32.to_string_u (I32.of_int_u n)
let nat32 = I32.to_string_u
let add_hex_char buf c = Printf.bprintf buf "\\%02x" (Char.code c)
let add_char buf = function
| '\n' -> Buffer.add_string buf "\\n"
| '\t' -> Buffer.add_string buf "\\t"
| '\"' -> Buffer.add_string buf "\\\""
| '\\' -> Buffer.add_string buf "\\\\"
| c when '\x20' <= c && c < '\x7f' -> Buffer.add_char buf c
| c -> add_hex_char buf c
let add_unicode_char buf = function
| (0x09 | 0x0a) as uc -> add_char buf (Char.chr uc)
| uc when 0x20 <= uc && uc < 0x7f -> add_char buf (Char.chr uc)
| uc -> Printf.bprintf buf "\\u{%02x}" uc
let string_with iter add_char s =
let buf = Buffer.create 256 in
Buffer.add_char buf '\"';
iter (add_char buf) s;
Buffer.add_char buf '\"';
Buffer.contents buf
let bytes = string_with String.iter add_hex_char
let string = string_with String.iter add_char
let name = string_with List.iter add_unicode_char
let list_of_opt = function None -> [] | Some x -> [x]
let list f xs = List.map f xs
let listi f xs = List.mapi f xs
let opt f xo = list f (list_of_opt xo)
let tab head f xs = if xs = [] then [] else [Node (head, list f xs)]
let atom f x = Atom (f x)
let break_bytes s =
let ss = Lib.String.breakup s 16 in
list (atom bytes) ss
let break_string s =
let ss, s' = Lib.List.split_last (Lib.String.split s '\n') in
list (atom string) (List.map (fun s -> s ^ "\n") ss @ [s'])
(* Types *)
let num_type t = string_of_num_type t
let ref_type t = string_of_ref_type t
let refed_type t = string_of_refed_type t
let value_type t = string_of_value_type t
let decls kind ts = tab kind (atom value_type) ts
let func_type (FuncType (ins, out)) =
Node ("func", decls "param" ins @ decls "result" out)
let struct_type = func_type
let limits nat {min; max} =
String.concat " " (nat min :: opt nat max)
let global_type = function
| GlobalType (t, Immutable) -> atom string_of_value_type t
| GlobalType (t, Mutable) -> Node ("mut", [atom string_of_value_type t])
let pack_size = function
| Pack8 -> "8"
| Pack16 -> "16"
| Pack32 -> "32"
let extension = function
| SX -> "_s"
| ZX -> "_u"
(* Operators *)
module IntOp =
struct
open Ast.IntOp
let testop xx = function
| Eqz -> "eqz"
let relop xx = function
| Eq -> "eq"
| Ne -> "ne"
| LtS -> "lt_s"
| LtU -> "lt_u"
| GtS -> "gt_s"
| GtU -> "gt_u"
| LeS -> "le_s"
| LeU -> "le_u"
| GeS -> "ge_s"
| GeU -> "ge_u"
let unop xx = function
| Clz -> "clz"
| Ctz -> "ctz"
| Popcnt -> "popcnt"
| ExtendS sz -> "extend" ^ pack_size sz ^ "_s"
let binop xx = function
| Add -> "add"
| Sub -> "sub"
| Mul -> "mul"
| DivS -> "div_s"
| DivU -> "div_u"
| RemS -> "rem_s"
| RemU -> "rem_u"
| And -> "and"
| Or -> "or"
| Xor -> "xor"
| Shl -> "shl"
| ShrS -> "shr_s"
| ShrU -> "shr_u"
| Rotl -> "rotl"
| Rotr -> "rotr"
let cvtop xx = function
| ExtendSI32 -> "extend_i32_s"
| ExtendUI32 -> "extend_i32_u"
| WrapI64 -> "wrap_i64"
| TruncSF32 -> "trunc_f32_s"
| TruncUF32 -> "trunc_f32_u"
| TruncSF64 -> "trunc_f64_s"
| TruncUF64 -> "trunc_f64_u"
| TruncSatSF32 -> "trunc_sat_f32_s"
| TruncSatUF32 -> "trunc_sat_f32_u"
| TruncSatSF64 -> "trunc_sat_f64_s"
| TruncSatUF64 -> "trunc_sat_f64_u"
| ReinterpretFloat -> "reinterpret_f" ^ xx
end
module FloatOp =
struct
open Ast.FloatOp
let testop xx = fun _ -> assert false
let relop xx = function
| Eq -> "eq"
| Ne -> "ne"
| Lt -> "lt"
| Gt -> "gt"
| Le -> "le"
| Ge -> "ge"
let unop xx = function
| Neg -> "neg"
| Abs -> "abs"
| Ceil -> "ceil"
| Floor -> "floor"
| Trunc -> "trunc"
| Nearest -> "nearest"
| Sqrt -> "sqrt"
let binop xx = function
| Add -> "add"
| Sub -> "sub"
| Mul -> "mul"
| Div -> "div"
| Min -> "min"
| Max -> "max"
| CopySign -> "copysign"
let cvtop xx = function
| ConvertSI32 -> "convert_i32_s"
| ConvertUI32 -> "convert_i32_u"
| ConvertSI64 -> "convert_i64_s"
| ConvertUI64 -> "convert_i64_u"
| PromoteF32 -> "promote_f32"
| DemoteF64 -> "demote_f64"
| ReinterpretInt -> "reinterpret_i" ^ xx
end
let oper (intop, floatop) op =
num_type (type_of_num op) ^ "." ^
(match op with
| I32 o -> intop "32" o
| I64 o -> intop "64" o
| F32 o -> floatop "32" o
| F64 o -> floatop "64" o
)
let unop = oper (IntOp.unop, FloatOp.unop)
let binop = oper (IntOp.binop, FloatOp.binop)
let testop = oper (IntOp.testop, FloatOp.testop)
let relop = oper (IntOp.relop, FloatOp.relop)
let cvtop = oper (IntOp.cvtop, FloatOp.cvtop)
let memop name {ty; align; offset; _} sz =
num_type ty ^ "." ^ name ^
(if offset = 0l then "" else " offset=" ^ nat32 offset) ^
(if 1 lsl align = sz then "" else " align=" ^ nat (1 lsl align))
let loadop op =
match op.sz with
| None -> memop "load" op (size op.ty)
| Some (sz, ext) ->
memop ("load" ^ pack_size sz ^ extension ext) op (packed_size sz)
let storeop op =
match op.sz with
| None -> memop "store" op (size op.ty)
| Some sz -> memop ("store" ^ pack_size sz) op (packed_size sz)
(* Expressions *)
let var x = nat32 x.it
let num v = string_of_num v.it
let constop v = num_type (type_of_num v.it) ^ ".const"
let block_type = function
| VarBlockType x -> [Node ("type " ^ var x, [])]
| ValBlockType ts -> decls "result" (list_of_opt ts)
let rec instr e =
let head, inner =
match e.it with
| Unreachable -> "unreachable", []
| Nop -> "nop", []
| Drop -> "drop", []
| Select None -> "select", []
| Select (Some []) -> "select", [Node ("result", [])]
| Select (Some ts) -> "select", decls "result" ts
| Block (bt, es) -> "block", block_type bt @ list instr es
| Loop (bt, es) -> "loop", block_type bt @ list instr es
| If (bt, es1, es2) ->
"if", block_type bt @
[Node ("then", list instr es1); Node ("else", list instr es2)]
| Br x -> "br " ^ var x, []
| BrIf x -> "br_if " ^ var x, []
| BrTable (xs, x) ->
"br_table " ^ String.concat " " (list var (xs @ [x])), []
| Return -> "return", []
| Call x -> "call " ^ var x, []
| CallIndirect (x, y) ->
"call_indirect " ^ var x, [Node ("type " ^ var y, [])]
| LocalGet x -> "local.get " ^ var x, []
| LocalSet x -> "local.set " ^ var x, []
| LocalTee x -> "local.tee " ^ var x, []
| GlobalGet x -> "global.get " ^ var x, []
| GlobalSet x -> "global.set " ^ var x, []
| TableGet x -> "table.get " ^ var x, []
| TableSet x -> "table.set " ^ var x, []
| TableSize x -> "table.size " ^ var x, []
| TableGrow x -> "table.grow " ^ var x, []
| TableFill x -> "table.fill " ^ var x, []
| TableCopy (x, y) -> "table.copy " ^ var x ^ " " ^ var y, []
| TableInit (x, y) -> "table.init " ^ var x ^ " " ^ var y, []
| ElemDrop x -> "elem.drop " ^ var x, []
| Load op -> loadop op, []
| Store op -> storeop op, []
| MemorySize -> "memory.size", []
| MemoryGrow -> "memory.grow", []
| MemoryFill -> "memory.fill", []
| MemoryCopy -> "memory.copy", []
| MemoryInit x -> "memory.init " ^ var x, []
| DataDrop x -> "data.drop " ^ var x, []
| RefNull t -> "ref.null", [Atom (refed_type t)]
| RefIsNull -> "ref.is_null", []
| RefFunc x -> "ref.func " ^ var x, []
| Const n -> constop n ^ " " ^ num n, []
| Test op -> testop op, []
| Compare op -> relop op, []
| Unary op -> unop op, []
| Binary op -> binop op, []
| Convert op -> cvtop op, []
| TryCatch (bt, es, ct, ca) ->
let catch (tag, es) = Node ("catch " ^ var tag, list instr es) in
let catch_all = match ca with
| Some es -> [Node ("catch_all", list instr es)]
| None -> [] in
let handler = list catch ct @ catch_all in
"try", block_type bt @ [Node ("do", list instr es)] @ handler
| TryDelegate (bt, es, x) ->
let delegate = [Node ("delegate " ^ var x, [])] in
"try", block_type bt @ [Node ("do", list instr es)] @ delegate
| Throw x -> "throw " ^ var x, []
| Rethrow x -> "rethrow " ^ var x, []
in Node (head, inner)
let const head c =
match c.it with
| [e] -> instr e
| es -> Node (head, list instr c.it)
(* Functions *)
let func_with_name name f =
let {ftype; locals; body} = f.it in
Node ("func" ^ name,
[Node ("type " ^ var ftype, [])] @
decls "local" locals @
list instr body
)
let func_with_index off i f =
func_with_name (" $" ^ nat (off + i)) f
let func f =
func_with_name "" f
let start x = Node ("start " ^ var x, [])
(* Tables & memories *)
let table off i tab =
let {ttype = TableType (lim, t)} = tab.it in
Node ("table $" ^ nat (off + i) ^ " " ^ limits nat32 lim,
[atom ref_type t]
)
let memory off i mem =
let {mtype = MemoryType lim} = mem.it in
Node ("memory $" ^ nat (off + i) ^ " " ^ limits nat32 lim, [])
let is_elem_kind = function
| FuncRefType -> true
| _ -> false
let elem_kind = function
| FuncRefType -> "func"
| _ -> assert false
let is_elem_index e =
match e.it with
| [{it = RefFunc _; _}] -> true
| _ -> false
let elem_index e =
match e.it with
| [{it = RefFunc x; _}] -> atom var x
| _ -> assert false
let segment_mode category mode =
match mode.it with
| Passive -> []
| Active {index; offset} ->
(if index.it = 0l then [] else [Node (category, [atom var index])]) @
[const "offset" offset]
| Declarative -> [Atom "declare"]
let elem i seg =
let {etype; einit; emode} = seg.it in
Node ("elem $" ^ nat i,
segment_mode "table" emode @
if is_elem_kind etype && List.for_all is_elem_index einit then
atom elem_kind etype :: list elem_index einit
else
atom ref_type etype :: list (const "item") einit
)
let data i seg =
let {dinit; dmode} = seg.it in
Node ("data $" ^ nat i, segment_mode "memory" dmode @ break_bytes dinit)
(* Tags *)
let tag_with_name name (t : tag) =
Node ("tag" ^ name,
[Node ("type " ^ var (t.it.tgtype), [])]
)
let tag_with_index off i t =
tag_with_name (" $" ^ nat (off + i)) t
(* Modules *)
let typedef i ty =
Node ("type $" ^ nat i, [struct_type ty.it])
let import_desc fx tx mx tgx gx d =
match d.it with
| FuncImport x ->
incr fx; Node ("func $" ^ nat (!fx - 1), [Node ("type", [atom var x])])
| TableImport t ->
incr tx; table 0 (!tx - 1) ({ttype = t} @@ d.at)
| MemoryImport t ->
incr mx; memory 0 (!mx - 1) ({mtype = t} @@ d.at)
| GlobalImport t ->
incr gx; Node ("global $" ^ nat (!gx - 1), [global_type t])
| TagImport x ->
incr tgx; Node ("tag $" ^ nat (!tgx - 1), [Node ("type", [atom var x])])
let import fx tx mx ex gx im =
let {module_name; item_name; idesc} = im.it in
Node ("import",
[atom name module_name; atom name item_name; import_desc fx tx mx ex gx idesc]
)
let export_desc d =
match d.it with
| FuncExport x -> Node ("func", [atom var x])
| TableExport x -> Node ("table", [atom var x])
| MemoryExport x -> Node ("memory", [atom var x])
| TagExport x -> Node ("tag", [atom var x])
| GlobalExport x -> Node ("global", [atom var x])
let export ex =
let {name = n; edesc} = ex.it in
Node ("export", [atom name n; export_desc edesc])
let global off i g =
let {gtype; ginit} = g.it in
Node ("global $" ^ nat (off + i), global_type gtype :: list instr ginit.it)
(* Modules *)
let var_opt = function
| None -> ""
| Some x -> " " ^ x.it
let module_with_var_opt x_opt m =
let fx = ref 0 in
let tx = ref 0 in
let mx = ref 0 in
let tgx = ref 0 in
let gx = ref 0 in
let imports = list (import fx tx mx tgx gx) m.it.imports in
Node ("module" ^ var_opt x_opt,
listi typedef m.it.types @
imports @
listi (table !tx) m.it.tables @
listi (memory !mx) m.it.memories @
listi (tag_with_index !tgx) m.it.tags @
listi (global !gx) m.it.globals @
listi (func_with_index !fx) m.it.funcs @
list export m.it.exports @
opt start m.it.start @
listi elem m.it.elems @
listi data m.it.datas
)
let binary_module_with_var_opt x_opt bs =
Node ("module" ^ var_opt x_opt ^ " binary", break_bytes bs)
let quoted_module_with_var_opt x_opt s =
Node ("module" ^ var_opt x_opt ^ " quote", break_string s)
let module_ = module_with_var_opt None
(* Scripts *)
let literal mode lit =
match lit.it with
| Num (Values.I32 i) ->
let f = if mode = `Binary then I32.to_hex_string else I32.to_string_s in
Node ("i32.const " ^ f i, [])
| Num (Values.I64 i) ->
let f = if mode = `Binary then I64.to_hex_string else I64.to_string_s in
Node ("i64.const " ^ f i, [])
| Num (Values.F32 z) ->
let f = if mode = `Binary then F32.to_hex_string else F32.to_string in
Node ("f32.const " ^ f z, [])
| Num (Values.F64 z) ->
let f = if mode = `Binary then F64.to_hex_string else F64.to_string in
Node ("f64.const " ^ f z, [])
| Ref (NullRef t) ->
Node ("ref.null " ^ refed_type t, [])
| Ref (ExternRef n) ->
Node ("ref.extern " ^ nat32 n, [])
| Ref _ ->
assert false
let definition mode x_opt def =
try
match mode with
| `Textual ->
let rec unquote def =
match def.it with
| Textual m -> m
| Encoded (_, bs) -> Decode.decode "" bs
| Quoted (_, s) -> unquote (Parse.string_to_module s)
in module_with_var_opt x_opt (unquote def)
| `Binary ->
let rec unquote def =
match def.it with
| Textual m -> Encode.encode m
| Encoded (_, bs) -> Encode.encode (Decode.decode "" bs)
| Quoted (_, s) -> unquote (Parse.string_to_module s)
in binary_module_with_var_opt x_opt (unquote def)
| `Original ->
match def.it with
| Textual m -> module_with_var_opt x_opt m
| Encoded (_, bs) -> binary_module_with_var_opt x_opt bs
| Quoted (_, s) -> quoted_module_with_var_opt x_opt s
with Parse.Syntax _ ->
quoted_module_with_var_opt x_opt "<invalid module>"
let access x_opt n =
String.concat " " [var_opt x_opt; name n]
let action mode act =
match act.it with
| Invoke (x_opt, name, lits) ->
Node ("invoke" ^ access x_opt name, List.map (literal mode) lits)
| Get (x_opt, name) ->
Node ("get" ^ access x_opt name, [])
let nan = function
| CanonicalNan -> "nan:canonical"
| ArithmeticNan -> "nan:arithmetic"
let result mode res =
match res.it with
| LitResult lit -> literal mode lit
| NanResult nanop ->
(match nanop.it with
| Values.I32 _ | Values.I64 _ -> assert false
| Values.F32 n -> Node ("f32.const " ^ nan n, [])
| Values.F64 n -> Node ("f64.const " ^ nan n, [])
)
| RefResult t -> Node ("ref." ^ refed_type t, [])
let assertion mode ass =
match ass.it with
| AssertMalformed (def, re) ->
(match mode, def.it with
| `Binary, Quoted _ -> []
| _ ->
[Node ("assert_malformed", [definition `Original None def; Atom (string re)])]
)
| AssertInvalid (def, re) ->
[Node ("assert_invalid", [definition mode None def; Atom (string re)])]
| AssertUnlinkable (def, re) ->
[Node ("assert_unlinkable", [definition mode None def; Atom (string re)])]
| AssertUninstantiable (def, re) ->
[Node ("assert_trap", [definition mode None def; Atom (string re)])]
| AssertReturn (act, results) ->
[Node ("assert_return", action mode act :: List.map (result mode) results)]
| AssertTrap (act, re) ->
[Node ("assert_trap", [action mode act; Atom (string re)])]
| AssertException act ->
[Node ("assert_exception", [action mode act])]
| AssertExhaustion (act, re) ->
[Node ("assert_exhaustion", [action mode act; Atom (string re)])]
let command mode cmd =
match cmd.it with
| Module (x_opt, def) -> [definition mode x_opt def]
| Register (n, x_opt) -> [Node ("register " ^ name n ^ var_opt x_opt, [])]
| Action act -> [action mode act]
| Assertion ass -> assertion mode ass
| Meta _ -> assert false
let script mode scr = Lib.List.concat_map (command mode) scr