Skip to content

JavaScript FFI for the emscripten target: JSVal, callbacks, browser targets - #5

Open
dmjio wants to merge 118 commits into
masterfrom
jsval
Open

dmjio wants to merge 118 commits into
masterfrom
jsval

Conversation

@dmjio

@dmjio dmjio commented Oct 4, 2026 •

Copy link
Copy Markdown
Member

Adds a JavaScript FFI to MicroHs for the emscripten target, in the style of GHC's WebAssembly backend, together with the runtime changes that JavaScript callbacks and the browser need. The goal is to compile browser applications (miso in particular) with MicroHs.

master is at upstream augustss/MicroHs master (d756fa92, "More testing fixes") and jsval is rebased onto it, so this PR is exactly the fork's 22 commits:

  • 0cbadda8 JavaScript FFI for the emscripten target: JSVal, callbacks, browser targets
  • 622113d2 JavaScript FFI: fixes from review
  • 3c131b43 config.h: imath only without GMP
  • 20ea518d runtest: depend on the compiler it runs
  • 22842268 JavaScript FFI: drop the threadDelay timer when the runtime stops
  • 2733fd0a JavaScript FFI: pass Word arguments unsigned
  • 4bb6bdf7 GHC.Wasm.Prim: keep a leading U+FEFF when converting a string to JavaScript
  • edbd0d40 Regen
  • 589d412e Drop the quickjs target
  • 3829cfd4 Define main_finish after mhs_main, where its body came from
  • 9b3b623e tests/JSExportBlocked: print the result as one string
  • 5ea466a3 README: structure the JavaScript FFI section
  • eeaba3c1 JavaScript FFI: a trap while main runs marks the runtime as stopped
  • 218ecd47 JavaScript FFI: a freed result is the callback's error, not the runtime's
  • e1b02c7b FFI: escape ? in the C string of a JavaScript import
  • 7aab5811 JavaScript FFI: js_exn_string and js_free_jsval are ordinary C functions
  • 5459c2ea Regen
  • 40955527 Control.Exception.Internal: guards in peekUTF8 (hlint)
  • 23a6ddbe README: traps stop the runtime too; a freed callback result
  • f36f60e1 Regen
  • 556acfc4 mhs.conf.in, README: the two families of emscripten targets
  • 1a0ce4ba hlint: [prog] in Tester.parseTests, otherwise in peekUTF8

Excluding generated/mhs.c and generated/base.pkg (regenerated, see Notes for merging), the diff against upstream is 42 files, +2358 −121; without the tests and the README it is 16 files, +1523 −106, of which src/runtime/eval.c is +975 −30.

Contents

What it solves

Calling JavaScript from Haskell. Before this, a MicroHs program compiled with emscripten could only reach JavaScript through C. Now JavaScript code is written inline in a foreign import javascript, with the arguments as $1, $2, ..., as in GHC's WebAssembly backend:

foreign import javascript "$1 + $2"                            add     :: Int -> Int -> Int
foreign import javascript "return document.getElementById($1)" getElem :: JSString -> IO JSVal

Holding JavaScript values in Haskell. A JSVal is a first class Haskell value that refers to a JavaScript value (a DOM node, a function, a string, ...). The JavaScript value stays alive as long as the Haskell value does, and is released when the JSVal is garbage collected, or right away with freeJSVal.

Calling Haskell from JavaScript. Haskell functions can be turned into JavaScript functions (syncCallback, asyncCallback, "wrapper" imports), so they can be used as event handlers, timers, and Promise continuations.

A program that lives in the event loop. A browser application does not end when main returns, and it cannot block the browser's thread. The runtime returns to the JavaScript event loop whenever all Haskell threads are blocked, and is resumed by a callback, a timer, or a settling Promise. threadDelay, MVars and forkIO work in that setting. No C stack has to be preserved for this (Haskell threads keep their state in the heap), so emscripten's ASYNCIFY is not needed.

Awaiting Promises. An interruptible import is an async function. The Haskell thread that calls it waits for the Promise while the other Haskell threads keep running, and a rejected Promise is a Haskell exception.

Exceptions across the boundary, in both directions. A JavaScript exception in a safe or interruptible import is raised in Haskell as a JSException. An uncaught Haskell exception in a callback is thrown to the JavaScript caller as an Error (an asynchronous callback rejects its Promise).

Source compatibility with GHC. The module is called GHC.Wasm.Prim and follows GHC's API, with the GHCJS style callback functions added. The intent is that code written for GHC's WebAssembly or JavaScript backends, such as miso's FFI layer, needs few changes. JSString has no Eq/Show instances, like GHC's, so a library that defines its own does not get duplicate instances.

Output for the browser. New targets produce a single file for the browser, with or without WebAssembly, and for node. The browser target is compiled for size without losing speed (see Targets).

A runtime that runs programs without a C compiler. The browser_rts target builds the runtime once; a program is then compiled to a combinator file in seconds and fetched at run time (see The browser runtime). This is what miso dev in haskell-miso/cli uses on every save.

Code that also has to compile natively. A module that uses the JavaScript FFI still compiles for a native target: the JavaScript code is left out and nothing JavaScript specific reaches the C compiler (tests/JSNative.hs). So one code base can have a native build, e.g. for a server or for tests.

What it does not solve

It is emscripten only. foreign import javascript does something only with the emscripten targets. There is no JavaScript FFI for a compiler that itself runs natively and no way to run the JavaScript code at compile time. (On the 2ltt branch a foreign import javascript is for this reason the one thing that is object level only.)

Only a few types cross the boundary. Arguments and results are Int, Word, Char, Bool, Double, Float, Ptr, JSVal and newtypes of these, with () as a result. There is no automatic conversion of String, Text, lists, records, Maybe, or 64 bit integers. Strings go through toJSString/textToJSString, which copy via UTF-8. Everything else is the job of a library on top (in miso, its ToJSVal/FromJSVal classes).

Callbacks take and return JSVal only. A "wrapper" import wraps a function of type JSVal -> ... -> IO () or IO JSVal. The helper functions cover zero to three arguments.

A callback cannot always block. A callback called from the JavaScript event loop may block (it then waits like any other thread, and its JavaScript caller gets undefined, or an already resolved Promise for "wrapper"). But a callback that returns a value, one that is called from inside the JavaScript code of an import, and a foreign export called from JavaScript, must not block; that is a fatal error. There is no way to check this at compile time.

unsafe is the default, and it is unforgiving. Unlike the Haskell report, an import without a safety annotation is unsafe, and a JavaScript exception in an unsafe import is fatal (as with GHC's JavaScript backend). Write safe to get a JSException instead.

A fatal error stops the Haskell side for good. After a fatal runtime error, or a JavaScript exception from an unsafe import inside a callback, the runtime is stopped. In the browser the page lives on, and every later call into Haskell throws an Error saying that the runtime has stopped. There is no restart.

Memory is tied to the Haskell garbage collector. A JavaScript value referenced by a JSVal is only released when the Haskell GC finds the JSVal dead, so JavaScript memory can stay around until the next Haskell collection. The browser targets use a 4M cell heap (about 60MB, instead of the default 50M cells) and force a collection after many new handles so that this happens regularly; a program that needs a bigger heap has to set -optc -DHEAP_CELLS=N. A callback is released when its JSVal is collected or freed.

browser_rts fixes the foreign imports when the runtime is built. A program whose foreign imports are not in the runtime's FFI table needs a runtime built for it (--embed-ffis, or built from that program). The .comb file lists its imports after a ##### line, so a tool can tell when that is.

Not in this PR. Inline JavaScript with [js| ... |] is PR #2, and the speedup for -sWASM=0 builds is PR #1; both target jsval. There is no DOM library here: this is the FFI that such a library is written with. A quickjs target was dropped: it was never run, and a program using threadDelay hangs on it, since the runtime waits in a setTimeout and qjs has none.

The browser target needs WebAssembly exception handling, which browsers have had since 2022. Older browsers need the browser_js target.

browser_js and emscripten_js were not run. All the testing here and in CI uses WebAssembly (emscripten under node, browser under Chromium through miso's test suite, see below). The -sWASM=0 targets were built on the fork before the rebase, not since.

The language feature

foreign import javascript [unsafe|safe|interruptible] "code" name :: type
  • The string is JavaScript code. The compiler turns it into an emscripten EM_JS function, mhs_js_<module>_<n>, with the parameters $1, $2, ..., so it is ordinary JavaScript in the output, with nothing compiled at run time. It can be an expression, or statements that use return. The compiler decides which: statements if, outside brackets, strings and comments, the code has a ; or the word return (not as a property name), or starts with a statement keyword (if, let, throw, ...); otherwise an expression. Code that starts with function or class is an expression unless more code follows it.
  • A $k that is not an argument is a compile time error. In particular $0: the arguments start at $1, as in GHC (they started at $0 on the fork before).
  • The code can use the emscripten Module object (e.g. Module.UTF8ToString($1)) and mhsjs, the table of JSVals.
  • A JSVal argument arrives as the JavaScript value it refers to; a JSVal result is entered in the table. A Word argument arrives as an unsigned number (a wasm i32 is signed by default).

The safety annotation selects what happens on a JavaScript exception, and whether the code can wait:

annotation the code is a JavaScript exception
unsafe (the default) a function is fatal
safe a function in a try/catch is raised as a JSException
interruptible an async function, so it can use await is raised as a JSException; so is a rejected Promise

With interruptible the calling Haskell thread waits for the Promise and the other Haskell threads keep running. safe and interruptible imports also catch exceptions from the conversion of the arguments (e.g. a JSVal that was freed).

Two import strings make callbacks instead of calling JavaScript:

  • "wrapper sync" turns a Haskell function into a JavaScript function that calls it and returns when it is done.
  • "wrapper" does the same, but the JavaScript function runs the Haskell code later, from the event loop, and returns a Promise.

In the compiler this touches the parser, Expr.hs, the type checker (the allowed types), Desugar.hs, and mostly FFI.hs, which generates one EM_JS function per import into the C output. The code is passed to _EM_JS (what the EM_JS macro expands to) as a C string, so it does not have to consist of valid C tokens. Primitives.hs gets the JSVal type. The C name of a foreign import is now qualified with its module (mhs_<module>_<n>), since the number alone is only unique within a module; this affects all foreign imports whose entity is not a plain C identifier, not only JavaScript ones.

GHC.Wasm.Prim

A new library module (122 lines), in base:

JSVal, JSString(..), JSException(..)
toJSString, fromJSString            -- String
textToJSString, textFromJSString    -- Text
freeJSVal
jsNull, jsUndefined, isNull, isUndefined
syncCallback,  syncCallback1,  syncCallback2,  syncCallback3     -- IO ()
syncCallback', syncCallback1', syncCallback2', syncCallback3'    -- IO JSVal, the callback returns a value
asyncCallback, asyncCallback1, asyncCallback2, asyncCallback3

The string conversions go through UTF-8 with explicit lengths, so a NUL character in the text survives, and decode with a single TextDecoder created with ignoreBOM, so a leading U+FEFF survives as well (a default decoder strips it). JSException is defined in Control.Exception.Internal, since the runtime raises it. The two runtime functions the library needs, js_exn_string (the description of a JavaScript exception, a malloc()ed UTF-8 C string) and js_free_jsval, are ordinary C functions with C types, declared in mhsffi.h and imported with plain foreign import ccall; the JSVal is passed as the payload of its foreign pointer, i.e. the handle. So the library builds with any mhs, upstream's included, with no runtime-specific knowledge in the compiler.

Callbacks and the scheduler

This is the largest part of the change: src/runtime/eval.c grows by about 900 lines.

  • A callback is a Haskell thread. A callback used to run on whatever stack was current, so there was no current thread, and catch, getMaskingState, forkIO and myThreadId read a null pointer (which happens to be readable in wasm, so it appeared to work). A callback now runs as a thread of its own, first and without preemption; when it runs out of its reduction budget it gets a new one. A foreign export called from JavaScript while the threads wait in the event loop runs the same way (it used to run as a second main thread, which ended the program when it finished).
  • Waiting for JavaScript. When all threads are blocked (main included, e.g. in takeMVar waiting for a callback, or in an interruptible import), the runtime flushes stdout and returns to the JavaScript event loop, and waits there until a callback wakes it or the earliest threadDelay expires. It used to poll with emscripten_sleep(1).
  • After main. When a program has live callbacks the JavaScript runtime stays alive after main returns, so the callbacks can still be invoked. Haskell threads keep running after main or a callback finishes. The program ends when the main thread finishes and no callback is left; the runtime counts the live callbacks, so a deadlock is reported again once they have all been freed. When the program exits, the timer armed for a threadDelay is dropped (it used to fire into the stopped runtime).
  • Results. A callback that returns a value runs its action exactly once and hands the value back (it used to run the action twice). Each callback keeps its own error, so a callback that wakes a thread which calls another callback does not see that one's exception.
  • Handles. JSVal handles wrap around instead of overflowing a C int after 2^31 allocations.

Embedded JavaScript files

A .js file on the command line, or in the jsbits directory of a package, is embedded in the output with --pre-js (this part is upstream, augustss#529). A foreign import javascript can call what such a file defines:

foreign import javascript "return jsFlagAdd($1, $2)" jsFlagAdd :: Int -> Int -> IO Int
function jsFlagAdd(x, y) { return x + y; }

At -O3 emscripten removes definitions in a --pre-js file that it sees no use of. Since the code of each import is an EM_JS function in the output, the optimizer sees that the import calls jsFlagAdd and keeps it; the embedded files are still minified and what nothing uses is still removed.

(Before the EM_JS change, the code was a string compiled at run time with a direct eval. That needed a workaround, FFI.jsIdents, which mentioned each import's identifiers in a function that was never called so the optimizer would keep them. Both are gone.)

The alternative, embedding with --extern-pre-js, also works, but then the files are not optimized at all. It is still a matter of configuration: the option is the js key of the target in mhs.conf.

The tests JSFlag and JSBits came from upstream with augustss#529, where arguments are numbered from $0; on this branch they use $1, $2.

Targets

New sections in mhs.conf.in, next to the existing emscripten:

target output notes
emscripten WebAssembly + JavaScript, for node more runtime methods are exported, for the string conversions
emscripten_js JavaScript only (-sWASM=0), for node
browser WebAssembly + JavaScript for the browser no file system, -Oz -sSUPPORT_LONGJMP=wasm, 4M cell heap
browser_rts as browser, but the program is fetched at run time -sINVOKE_RUN=0, see below
browser_js JavaScript only for the browser -O3, 4M cell heap

These are targets for programs. Upstream's existing emscripten_web is a different thing, the compiler itself running in a web page (web-mhs/, ASYNCIFY for typed input); it is left as it is, and mhs.conf.in now says which is which.

Why the browser target is compiled the way it is: the evaluator contains a setjmp (for catch). With emscripten's default JavaScript implementation of longjmp, every call out of a function that uses setjmp goes through a JavaScript trampoline. At -O3 most helpers are inlined and this costs a percent or two; at -Oz, which does not inline, a miso application spent 84% of its time in those trampolines instead of 22%. With WebAssembly exception handling for longjmp the -Oz build is as fast as -O3 and about 12% smaller compressed. browser_js has no WebAssembly, so it stays at -O3. (These measurements were made on the fork before the rebase.)

The standalone runtime compiled to JavaScript (make rts.js, then node rts.js prog.comb) is not in this PR; it is one commit on the rts-js branch.

The browser runtime (browser_rts)

The browser target compiles the runtime and the program together, which means running emcc (an -Oz link takes a minute) for every change of the program. browser_rts separates the two:

mhs -tbrowser_rts [--embed-ffis PKG:...] -o rts.js Main src/runtime/web/rts-web.js   # once
mhs -o app.comb Main                                                                 # per change, seconds

rts.js is the runtime with -sINVOKE_RUN=0; src/runtime/web/rts-web.js (40 lines, installed with the runtime sources) fetches app.comb (or Module.combUrl, the data-comb attribute of the script tag, or in node the MHS_COMB environment variable) and hands it to mhs_run_web, which runs it instead of the compiled in program. The runtime's FFI table has the foreign imports of the program it was built with, plus those of the --embed-ffis packages. Upstream's mhseval.js does the node half of this (a .comb given as a file argument); this adds the fetch, the FFI table, and the keep-alive runtime of this PR, so callbacks and timers work in the fetched program.

miso dev in haskell-miso/cli uses this on every save of a target: browser project: it keys the runtime by the program's foreign imports (read from the ##### section of the .comb) and its C and JavaScript sources, builds it once per key, and compiles only app.comb afterwards.

The test testbrowserrts runs it under node (the readFileSync path); the browser fetch path has no test and is exercised by miso dev.

Fixes from review

622113d2, from the first round:

  • A $k in the code that is not an argument, in particular $0, is a compile time error instead of an undefined variable at run time.
  • Code starting with function or class is a function or class expression unless more code follows; return as a property name no longer makes the code statements.
  • A foreign export called while the threads wait in the event loop runs as a thread of its own.
  • The runtime counts live callbacks, so a deadlock is reported again once they are all freed; stdout is flushed on returning to the event loop; a callback that runs out of its budget gets a new one.
  • Tests JSDeadlock, JSExportBlocked.

22842268, 2733fd0a, 4bb6bdf7, from the second round (each with a test):

  • A threadDelay timer fired after the runtime had exited. If main finished (woken by a callback or a Promise) with no live callback while another thread was in threadDelay, exit() only threw ExitStatus to the caller (the runtime is kept alive by emscripten_exit_with_live_runtime) and the armed timer stayed. When it fired, the "runtime has stopped" Error went into a bare setTimeout callback: an uncaught exception in node (exit status 1 after waiting out the delay), a console error in a browser. Stopping the runtime now clears the timer, and runThreads does nothing once the runtime is dead. Test JSExitTimer.
  • Word arguments at or above 2^31 arrived negative. EM_JS parameters are wasm i32s and emscripten does no unsigned conversion; $1 on 0xFFFFFFFF gave -1. They are converted with >>> 0, as Bool and JSVal arguments are converted.
  • A leading U+FEFF was dropped by toJSString. js_fromUTF8 decoded with a default TextDecoder, which strips a byte order mark. It decodes with ignoreBOM, and the decoder is created once instead of per call. (miso's Data.JSString had a workaround that re-inserted the mark; it is removed in MicroHs: bump to jsval 5fc13363 and drop the U+FEFF workaround dmjio/miso#1691, which also pins this branch.)

589d412e, 3829cfd4, 9b3b623e, 5ea466a3: the quickjs target dropped (see above), main_finish defined after mhs_main so the diff shows its body in place instead of moved, JSExportBlocked made independent of node's console colouring, and the README's JavaScript FFI section restructured (subsections and tables, and the facts of this branch).

eeaba3c1, 218ecd47, e1b02c7b, 7aab5811, from the third round (a review of the whole branch with upstreaming in mind):

  • A wasm trap while main ran left the runtime looking alive. Only entries through Module.mhsjs.enter and an unsafe import's catch recorded that the runtime had stopped; a trap during main itself (an out of bounds read, the evaluator exceeding the stack) went to emscripten's callMain, so in the browser the next DOM event ran its callback on a corrupted heap. main now runs inside a JavaScript frame (mhs_js_enter_main) that marks the runtime stopped for any exception except emscripten's unwind, then rethrows. Test JSTrap.
  • A freed result stopped the runtime. mkCallback fetched a value callback's result inside enter, so a callback returning a JSVal it had freed made enter stop the runtime for good although nothing had unwound. The result is taken right after enter, and an error there is thrown to the caller. Test JSCallback 20.
  • ? is escaped in the generated C string, so JavaScript such as x ??(y) cannot form a trigraph under a strict C mode.
  • js_exn_string and js_free_jsval are ordinary C functions (see GHC.Wasm.Prim) instead of hand-written FFI adapters listed in the compiler's runtimeFFI. Before, a compiler without them in its list, upstream's or any older one, generated stubs for them and failed on IO String; the library could only be built by a compiler already regenerated with this branch. Control.Exception.Internal decodes the UTF-8 message itself with the peek_uint8 and free runtime entries. JSVal tests a non-ASCII message.

What is already upstream

Parts of the fork's work have been merged into augustss/MicroHs and are therefore not in this diff any more:

Tests and what was run

New tests:

test runs with what it covers
JSVal emscripten + node the import forms, the argument and result types (including a Word above 2^31), JSString (including a leading U+FEFF and a NUL), the three safety annotations, a non-ASCII exception message, freeJSVal
JSCallback emscripten + node catch/mask/forkIO/myThreadId in a callback; an uncaught exception in a synchronous and an asynchronous callback; killThread of a delayed thread from a callback; a callback during an await; use after freeJSVal; a value returning callback runs once; the handle table stays bounded; a callback left blocked; nested callbacks and their errors; a value callback returning a freed JSVal
JSDeadlock emscripten + node a deadlock is reported (exit status 1) once the only callback has been freed
JSExportBlocked emscripten + node a foreign export called while main is blocked runs as its own thread; the program ends when main does
JSExitTimer emscripten + node the program ends (status 0, at once) when main does although a thread is still in threadDelay
JSTrap emscripten + node a wasm trap while main runs stops the runtime: a callback called later is refused (exit status 1)
BrowserRtsOther browser_rts + node the runtime built from JSVal runs JSVal.comb and a program it was not built with
ForImpJS (extended) emscripten + node plain JavaScript imports
JSNative native a module that uses the JavaScript FFI compiles and runs for a native target
Text, Unboxed (extended) native Data.Text.toTitle; (##) and operators that start with #

make runtestemscripten runs testforimpjs testjsval testbrowserrts testjscallback testjsdeadlock testjsexportblocked testjsexittimer testjstrap in addition to the existing tests. Before, CI ran no test of the JavaScript FFI itself.

Run on the final commits:

  • CI was green on the pre-rebase head 54f863ec (12 build jobs plus hlint, each for push and pull_request). The branch was then rebased onto upstream d756fa92 (four upstream commits, all test infrastructure, plus a WANT_GMP/WANT_IMATH guard in eval.c that the branch's config.h already satisfies) and regenerated; the native core suite, JSNative, and every JavaScript test target were rerun on the rebased tree.
  • The compiler bootstraps to a fixpoint; generated/mhs.c and generated/base.pkg are from that bootstrap, at version 0.16.12.0. From the branch's previous generated/mhs.c the regeneration took three stages once (that compiler emitted no stub for js_exn_string, the one it builds does, and the next one is the fixpoint). The library no longer needs a compiler that knows about the JavaScript runtime: upstream's mhs builds it.
  • The native core test suite (tester all.tests) and JSNative pass with the new library and runtime, on Linux.
  • On Linux, with emscripten 4.0.10 and node 22: every JavaScript test target above, plus testjsflag and testjsbits. The review fixes were each shown to fail on the previous head and pass on this one. JSVal, JSCallback, JSExitTimer, JSExportBlocked and JSDeadlock also pass compiled for the browser target (-Oz, wasm SjLj) and run under node.
  • The browser target, in a browser: miso's component test suite (tests/app, 343 tests) built with this MicroHs for -tbrowser and run headless in Chromium through miso's ts/playwright.ts, with emscripten 4.0.10 and with 6.0.9, with the miso side of the U+FEFF fix applied: 343 passed with both. That suite exercises unsafe, safe and interruptible imports, callbacks from DOM events, await, and exceptions in both directions. The same was then built and run through miso's Nix expressions (nix-build -A miso-tests-mhs-bundle, playwright-mhs).
  • On macOS x86-64, with emscripten 4.0.8 (before the second round): make runtestmhs, and the JavaScript tests of that time.

Not run: the whole test suite under emscripten locally (CI's emscripten job does that), and the browser_js and emscripten_js targets since the rebase.

Notes for merging

  • runtest no longer needs ghc (20ea518d): its recipe runs ../bin/mhs (tests/Makefile's default) but it depended on bin/gmhs, so make everytestmhs failed on a runner without ghc; upstream's nightly build-macos job fails this way today (make: ghc: No such file or directory). This is an upstream fix, not fork-only.
  • master will differ from upstream. Today master is a copy of augustss/MicroHs master. After this merge, syncing with upstream is a merge or a rebase; on a conflict in generated/mhs.c take either side and bootstrap again.
  • miso pins a pre-rebase commit. MicroHs: bump to jsval 5fc13363 and drop the U+FEFF workaround dmjio/miso#1691 (merged) pins MICROHS_REV to 5fc13363 in Makefile.mhs and nix/source.nix. After this rebase that commit is on no branch (its content is edbd0d40 now); GitHub still serves it for the time being, but miso should be bumped to a commit on the current jsval, or to master once this merges.
  • PRs JavaScript only targets: keep evalprimop and evalprimret out of evali (nfib 4.9s -> 1.0s) #1 and Inline JavaScript: [js| ... |] with ${expr} interpolation #2 target jsval, which was force pushed for the rebase. They need a rebase onto the current jsval, or a retarget to master after this is merged.
  • generated/mcabal.c is the fork's copy, which has the js-sources support. It was not regenerated (that needs the MicroCabal source) and it predates upstream's version bump.
  • lib/base.cabal gets GHC.Wasm.Prim.
  • Upstreaming. The natural split for augustss/MicroHs is three PRs in dependency order: the runtime (callbacks as threads, the event loop, JSVal, jsawait), the compiler and library (foreign import javascript, GHC.Wasm.Prim), and the targets with browser_rts.

@dmjio dmjio mentioned this pull request Oct 7, 2026
10 of 15 tasks
@dmjio
dmjio force-pushed the jsval branch 3 times, most recently from d8bd2fd to f2ec3f8 Compare October 14, 2026 20:08
@dmjio
dmjio force-pushed the jsval branch 9 times, most recently from 088de4d to e358919 Compare October 29, 2026 17:06
@dmjio
dmjio force-pushed the jsval branch 2 times, most recently from e079539 to 556acfc Compare October 31, 2026 19:30
@dmjio dmjio closed this Oct 31, 2026
@dmjio dmjio reopened this Oct 31, 2026
@dmjio dmjio closed this Oct 31, 2026
@dmjio dmjio reopened this Oct 31, 2026
dmjio added a commit to dmjio/miso that referenced this pull request Nov 1, 2026
1a0ce4ba adds one commit to 556acfc4: two hlint suggestions fixed, one in
upstream's Tools/Tester.hs and one in Control.Exception.Internal, with
tester.c and base.pkg regenerated.  It is the head that passed all 26 CI
checks on haskell-miso/MicroHs#5, and that haskell-miso.org was rebuilt
and checked with (miso 3f4956b).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
dmjio added a commit to dmjio/miso that referenced this pull request Nov 1, 2026
* MicroHs: bump to jsval 556acfc4

haskell-miso/MicroHs jsval was rebased onto upstream master (d756fa92)
and gained, since 5fc13363: a trap while main runs marks the runtime as
stopped; a value callback returning a freed JSVal is the caller's error,
not a dead runtime; js_exn_string and js_free_jsval are ordinary C
functions, so the library builds with any mhs; ? is escaped in the
generated C string of a JavaScript import; the quickjs target is gone;
and runtest no longer needs ghc.  Nothing on the miso side changes.

5fc13363 is no longer on a branch after the rebase, hence the bump.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* MicroHs: bump to jsval 1a0ce4ba

1a0ce4ba adds one commit to 556acfc4: two hlint suggestions fixed, one in
upstream's Tools/Tester.hs and one in Control.Exception.Internal, with
tester.c and base.pkg regenerated.  It is the head that passed all 26 CI
checks on haskell-miso/MicroHs#5, and that haskell-miso.org was rebuilt
and checked with (miso 3f4956b).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
@dmjio

dmjio commented Nov 2, 2026

Copy link
Copy Markdown
Member Author

augustss#561

@dmjio
dmjio force-pushed the jsval branch 3 times, most recently from 7635597 to 4de3387 Compare November 8, 2026 21:51
augustss and others added 2 commits November 17, 2026 11:47
Make README.md a short introduction with installation instructions,
an example, and a link to the full documentation.

Add doc/MicroHs.md with the full documentation, assembled from the
old README, the wiki, and the source: Language, Compiler (flags,
interactive mode, targets), Packages, Implementation (compiler and
runtime), Platforms, and Contributing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
augustss and others added 4 commits November 23, 2026 10:48
uname -m gives the kernel's architecture, so a 32 bit x86 program on an
x86_64 kernel (e.g., the nightly's 32 bit Alpine job) got arch "x86_64"
and the CPP symbol x86_64_HOST_ARCH, where GHC would say i386.  With 32
bit words, x86_64, aarch64, and powerpc64 now become i386, arm, and
powerpc.

The compiler's CPP symbols only change after a regen; until then the
CppHost test fails on such a system.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The runtime raises it as exception number 10 (exn_nontermination), which
rtsExn turns into NonTermination.  Control.Exception exports it, and
nonTermination, as GHC does.  Nothing raises it yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
One failing architecture cancelled the rest, so a failure on, e.g.,
riscv64 hid how the other architectures were doing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
augustss and others added 3 commits November 24, 2026 01:17
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With -sWASM=0 (JavaScript only) binaryen inlines evalprimop and
evalprimret into evali, since each has a single caller, in spite of
NOINLINE.  evali is then 233KB of JavaScript, which V8 refuses to optimize
("Function is too big to be optimized"), so the core of the evaluator runs
in V8's lower tiers.

Under emscripten, evali now calls them through volatile pointers, which
cannot be inlined.  evali is then 25KB and V8 optimizes it.  nfib 27 under
node takes 0.9s instead of 4.7s.  The wasm build is as fast as before,
and other targets compile to the same code as before.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@dmjio
dmjio force-pushed the jsval branch 2 times, most recently from 21470ec to 1e2622a Compare November 24, 2026 01:00
augustss and others added 12 commits November 24, 2026 12:50
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Without it the order of the output could depend on where stdout goes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A .combffi file now has two sections after the program: #####FFI, with
the foreign imports (the separator was #####), and then #####Names, with
the name of each definition after its label.

Mhs.Reflect:
* hReflect reads a combinator file, possibly compressed, from a handle.
* The names of the definitions are used for the labels when the file
  has them.
* The A d1 (A d2 (... e)) that ends a file written by mhs is reduced to e.
* Operator names, e.g. Data.Function.., are printed in parentheses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
augustss and others added 6 commits November 25, 2026 01:13
Consistent indentation, the code in commented sections, and no
duplicated code (one resize listener, one function to save the file).

Fixes:
* New cleared the editor through window.editor, which is never set.
* The sync conflict warning used term.writeFile, which does not exist.
* stderr now goes to the terminal like stdout, as UTF-8 and with \r\n.
* Run uses the qualified main of the module, since the earlier imports
  may have a main too, e.g. Demo.main.
* A typo in line_edit.

The trailing space of the prompt is written as \x20, so that it is not
lost when trailing white space is removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The handler of a catch restores the masking state.  It was taken when
CATCHR ran, but a rescheduled thread starts over from its root and runs
CATCHR again, maybe inside a mask.  Then the handler restored the wrong
state, and the thread stayed masked.

This happened in the web REPL when interrupting a canvhs animation:
drawing uses bracket_, and the interrupt comes from another thread.
After the first CTL-C the REPL was masked, so the second CTL-C was
never delivered.

Now CATCH x y z becomes CATCHR m (x z) y z, where m is the masking state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With -r the program runs in the same thread as the compiler, in the
middle of a time slice, so its thread switches depended on how much of
the slice the compiler had used, e.g., if the compilation cache was
used.  Yielding first gives the program a new time slice, as it gets
when it runs on its own.  So the MVar test no longer needs a yield.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…argets

A JavaScript FFI for MicroHs's emscripten target, in the style of GHC's
WebAssembly backend, with the runtime changes that JavaScript callbacks
and the browser need.

- foreign import javascript: the code is inline, with the arguments as
  $1, $2, ...; each import becomes an MHS_EM_JS function (mhsffi.h, the
  expansion of emscripten's _EM_JS), so emscripten's optimizer sees what
  the code uses.  Whether the code is an expression or statements is
  decided at compile time (jsIsStatements); strings, comments and
  regular expression literals are skipped.
- The safety annotations follow GHC's WebAssembly backend: an unsafe
  import is synchronous and a JavaScript exception in it is fatal; safe,
  interruptible and unannotated imports are asynchronous (the calling
  thread waits for the Promise while the others run), and a rejected
  Promise is a JSException.  An asynchronous import must return IO.
- GHC.Wasm.Prim: JSVal (released when garbage collected, or with
  freeJSVal), JSString, and syncCallback / asyncCallback / "wrapper"
  imports, following GHC's API.
- Callbacks run as Haskell threads of their own (run_callback).  An
  uncaught Haskell exception in a callback is thrown to the JavaScript
  caller as an Error.
- The runtime returns to the JavaScript event loop when every Haskell
  thread is blocked, and is resumed by a callback, a timer or a settling
  Promise; no ASYNCIFY.
- The emscripten runtime is in src/runtime/jsffi.c, included by eval.c.
  The core of evali has no JavaScript hooks: IO.jsawait and
  IO.jsawaitres are in evalprimop.
- Targets browser, browser_js, emscripten_js, and browser_rts: a runtime
  built once that fetches and runs a combinator program, so a rebuild
  needs no C compiler.
- A module that uses the JavaScript FFI still compiles for a native
  target (tests/JSNative.hs).
- Foreign import C names are module-qualified, since the import number
  is only unique within a module.
- Tests: JSVal, JSCallback, JSDeadlock, JSExportBlocked, JSExitTimer,
  JSTrap, BrowserRtsOther, ForImpJS, JSNative, Error112.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants