initial experiment - generating a simple wasm function

This commit is contained in:
Jeremy Penner 2024-05-21 21:43:02 -04:00
commit 3a84af5840
8 changed files with 1241 additions and 0 deletions

24
.gitignore vendored Normal file
View file

@ -0,0 +1,24 @@
node_modules/
/target
/checkouts
/src/gen
pom.xml
pom.xml.asc
*.iml
*.jar
*.log
.shadow-cljs
.idea
.lein-*
.nrepl-*
.DS_Store
.hgignore
.hg/
.calva
experiment/js
.clj-kondo
.lsp

1145
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

8
package.json Normal file
View file

@ -0,0 +1,8 @@
{
"name": "tock",
"version": "0.0.1",
"private": true,
"devDependencies": {
"shadow-cljs": "2.28.6"
}
}

9
public/index.html Normal file
View file

@ -0,0 +1,9 @@
<html>
<head>
<title>Hello, world!</title>
<script src="/js/main.js"></script>
</head>
<body>
Hello!!
</body>
</html>

BIN
public/release.wasm Normal file

Binary file not shown.

BIN
public/test-debug.wasm Normal file

Binary file not shown.

20
shadow-cljs.edn Normal file
View file

@ -0,0 +1,20 @@
;; shadow-cljs configuration
{:source-paths
["src/dev"
"src/main"
"src/test"]
:dependencies
[[io.helins/wasm "0.0.0-alpha3"] ; https://cljdoc.org/d/io.helins/wasm/0.0.0-alpha3/doc/readme
[io.helins/binf "1.1.0"]
[metosin/malli "0.16.1"] ; https://github.com/metosin/malli
[meander/epsilon "0.0.650"] ; https://github.com/noprompt/meander
[org.clojure/tools.reader "1.4.2"] ; https://github.com/clojure/tools.reader
[binaryage/devtools "1.0.7"]]
:builds
{:experiment {:target :browser
:output-dir "experiment/js"
:modules {:main {:init-fn tock.experiment/main}}}}
:dev-http {8909 ["experiment" "public"]}}

View file

@ -0,0 +1,35 @@
(ns tock.experiment
(:require [helins.wasm :as wasm]
[helins.wasm.ir :as ir]
[helins.wasm.bin :as op]
[helins.binf :as binf]
[helins.binf.string :as binf.string]
;; [malli.core :as malli]
[malli.util]))
(def test-wasm
(-> (wasm/ctx)
(ir/assoc-type (ir/type-signature {} [[op/numtype-i32 op/numtype-i32] [op/numtype-i32]]))
(ir/assoc-func (ir/func {} 0))
(assoc-in [:wasm/codesec 0] (ir/func' {} [] [[op/local-get 0] [op/local-get 1] [op/i32-add]]))
(assoc-in [:wasm/exportsec :wasm.export/func 0] [(ir/export' {} (binf.string/encode "add"))])))
(defn decompile-url [url]
(-> (js/fetch url)
(.then #(.arrayBuffer %))
(.then #(let [v (binf/view %)]
(binf/endian-set v :little-endian)
(wasm/decompile v)))))
(defn instantiate-wasm [wasm importObject]
(-> (wasm/compile wasm)
(binf/backing-buffer)
(js/WebAssembly.instantiate importObject)))
#_{:clj-kondo/ignore [:clojure-lsp/unused-public-var]}
(defn main []
(js/console.log test-wasm)
(-> (instantiate-wasm test-wasm #js {})
(.then #(js/console.log (-> % (.-instance) (.-exports) (.add 1 2)))))
(-> (decompile-url "release.wasm")
(.then #(js/console.log (-> % :wasm/exportsec :wasm.export/func (get 0))))))