(install
 (section lib)
 (package wasm_of_ocaml-compiler)
 (files
  (glob_files *.wat)
  (glob_files runtime-*.wasm)
  runtime.js))

(rule
 (target binaryen-version-check)
 (deps check_binaryen.ml (universe))
 (action
  (progn
   (run ocaml %{deps})
   (with-stdout-to
    %{target}
    (echo "ok")))))

(rule
 (target runtime-standard.wasm)
 (deps
  binaryen-version-check
  args
  zstd-impl.wasm
  blake2-impl.wasm
  (glob_files *.wat))
 (action
  (run
   ../../compiler/bin-wasm_of_ocaml/wasmoo_link_wasm.exe
   --binaryen=-g
   --binaryen-opt=-O3
   --set=effects=jspi
   --disable=wasi
   --allowed-imports=bindings,Math,js,wasm:js-string,wasm:text-encoder,wasm:text-decoder
   %{target}
   zstd:zstd-impl.wasm
   blake2:blake2-impl.wasm
   %{read-lines:args})))

(rule
 (target runtime-cps.wasm)
 (deps
  binaryen-version-check
  args
  zstd-impl.wasm
  blake2-impl.wasm
  (glob_files *.wat))
 (action
  (run
   ../../compiler/bin-wasm_of_ocaml/wasmoo_link_wasm.exe
   --binaryen=-g
   --binaryen-opt=-O3
   --set=effects=cps
   --disable=wasi
   --allowed-imports=bindings,Math,js,wasm:js-string,wasm:text-encoder,wasm:text-decoder
   %{target}
   zstd:zstd-impl.wasm
   blake2:blake2-impl.wasm
   %{read-lines:args})))

(rule
 (target runtime-wasi.wasm)
 (deps
  args
  (glob_files *.wat)
  libc.wasm
  zstd-impl.wasm
  blake2-impl.wasm)
 (action
  (run
   ../../compiler/bin-wasm_of_ocaml/wasmoo_link_wasm.exe
   --binaryen=-g
   --binaryen-opt=-O3
   --set=effects=disabled
   --enable=wasi
   --allowed-imports=wasi_snapshot_preview1,OCaml
   %{target}
   libc:libc.wasm
   zstd:zstd-impl.wasm
   blake2:blake2-impl.wasm
   %{read-lines:args})))

(rule
 (target runtime-cps-wasi.wasm)
 (deps
  args
  (glob_files *.wat)
  libc.wasm
  zstd-impl.wasm
  blake2-impl.wasm)
 (action
  (run
   ../../compiler/bin-wasm_of_ocaml/wasmoo_link_wasm.exe
   --binaryen=-g
   --binaryen-opt=-O3
   --set=effects=cps
   --enable=wasi
   %{target}
   libc:libc.wasm
   zstd:zstd-impl.wasm
   blake2:blake2-impl.wasm
   %{read-lines:args})))

(rule
 (target args)
 (deps
  args.ml
  (glob_files *.wat))
 (action
  (with-stdout-to
   %{target}
   (run ocaml %{deps}))))

; libc.wasm, zstd-impl.wasm and blake2-impl.wasm are compiled from C sources
; with the wasi-sdk, which we run via docker. Normal builds use the committed
; .wasm files as-is and never need docker: each rebuild rule lives in a vendored
; subdirectory ('libc', 'zstd', 'blake2'), which dune excludes from @all. After
; editing the corresponding sources, regenerate the .wasm on demand (docker
; required) with one of:
;   dune build @runtime/wasm/recompile-libc
;   dune build @runtime/wasm/recompile-zstd
;   dune build @runtime/wasm/recompile-blake2

(vendored_dirs libc zstd blake2)

(alias
 (name recompile-libc)
 (deps libc/libc.wasm))

(alias
 (name recompile-zstd)
 (deps zstd/zstd-impl.wasm))

(alias
 (name recompile-blake2)
 (deps blake2/blake2-impl.wasm))
