Skip to content

JavaScript FFI for the emscripten target - #561

Open
dmjio wants to merge 21 commits into
augustss:masterfrom
haskell-miso:jsval
Open

dmjio wants to merge 21 commits into
augustss:masterfrom
haskell-miso:jsval

Conversation

@dmjio

@dmjio dmjio commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Preface

This preface is mine. Everything after it was written by Claude.

I did this by giving Claude (Fable 5.1, and Opus 5.5 for the last round of fixes) the emscripten, MicroHs, GHC (WebAssembly backend and rts/) and miso sources, and asking it to follow your README's instructions for adding primitives. I directed the work, reviewed the changes, and tested them with miso.

The design follows GHC's WebAssembly backend. As there, a JSVal is an integer id shared between the two heaps, indexing a table of JavaScript values on the JavaScript side (GHC's JSValManager); a callback keeps its Haskell function alive with a StablePtr; and a JavaScript FinalizationRegistry calls back into the runtime to free that StablePtr once the JavaScript side has dropped the callback. The one difference: GHC ties the id's lifetime to a Weak# with a C finalizer, while this uses a ForeignPtr with a C finalizer.

It works well for miso. miso's integration tests pass built with MicroHs, for both the WebAssembly (browser) and the JavaScript-only (browser_js) target, in miso's CI on dmjio/miso#1694. And haskell-miso.org, which exercises most of miso, runs normally built entirely with MicroHs, prerendered pages included: https://mhs-latest.netlify.app. miso's FFI layer uses nearly all of the JavaScript FFI that GHC offers (synchronous and asynchronous callbacks, Promises, exceptions in both directions, JSVal lifetimes), so getting its tests and examples to pass is a good sign.

Size: the site's code is about 370 KB compressed with MicroHs, against 1.15 MB with GHC, a third; uncompressed, 1.8 MB against 5.5 MB. Performance is close on a desktop CPU (in-app navigation 158 ms against 125 ms, median), but startup is slower: the app is running after 0.89 s against 0.56 s, and about twice as long on a CPU throttled 4×. Details under Size and performance.

The PR also includes a browser runtime, the browser_rts target with its small loader src/runtime/web/rts-web.js. The miso command line tool (https://github.com/haskell-miso/cli) uses it for hot reload in miso dev: the runtime is built once with emcc, and after that every edit only recompiles the program to a .comb file (a few seconds, no C compiler), which the page fetches and runs. The tool builds a new runtime only when the program's foreign imports or its C and JavaScript files change, which it can tell from the foreign-import list that mhs writes after the ##### line of a .comb. It is close to the existing mhseval.js, with these differences:

mhseval.js (already upstream) browser_rts
gets the program fopen of a .comb in emscripten's in-memory file system, which the caller fills fetches app.comb (or the script tag's data-comb); in node, reads MHS_COMB
FFI table the runtime's built-in entries only also the foreign imports of the program it was built from, and of --embed-ffis packages
JavaScript FFI none all of this PR: JSVal, callbacks, interruptible imports, JSException
after main the program is over stays alive while callbacks exist, and runs Haskell threads from the JavaScript event loop
built for any emscripten environment, -O3 the browser, -Oz -sSUPPORT_LONGJMP=wasm, 4M cell heap

Two related pieces of work are deliberately not part of this PR:


Claude's PR summary

Written by Claude.

foreign import javascript, JSVal, callbacks from JavaScript into Haskell, and a runtime that lives in the browser's event loop. This is what miso uses to compile browser applications with MicroHs; it has been in use there, and in miso dev of haskell-miso/cli, for a while on a fork, rebased onto current master.

Rebased onto current master (9e1cd08). Excluding generated/ (regenerated), the diff is 43 files, +2452 −117: about 1,500 lines of code, 700 of tests, 140 of README. The emscripten runtime is in a new src/runtime/jsffi.c (815 lines), #included by src/runtime/eval.c, with the declarations eval.c uses in src/runtime/jsffi.h (37 lines); eval.c itself is +207 −28, mostly under #if defined(__EMSCRIPTEN__).

Contents

What it adds

Calling JavaScript. The code is inline, with the arguments as $1, $2, ..., as in GHC's WebAssembly backend; an expression, or statements with return:

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

Each import becomes an emscripten EM_JS function in the generated C, so it is ordinary JavaScript in the output that emscripten's optimizer sees; nothing is compiled at run time. A $k that is not an argument is a compile time error. Allowed types: Int, Word, Char, Bool, Double, Float, Ptr, JSVal, newtypes of these, () as a result.

Holding JavaScript values. JSVal is a T_FORPTR whose payload is an index into a table on the JavaScript side (Module.mhsjs), with a finalizer that drops the entry when the node is collected. freeJSVal drops it eagerly. Handle 0 is undefined; handles wrap around at 2^31.

Callbacks. foreign import javascript "wrapper sync" and "wrapper" turn a Haskell function of type JSVal -> ... -> IO () (or IO JSVal) into a JavaScript function; GHC.Wasm.Prim wraps them as syncCallback/asyncCallback (0 to 3 arguments), the GHCJS names. A callback runs as a Haskell thread of its own. An uncaught Haskell exception in it is thrown to the JavaScript caller as an Error.

A program in the event loop. When every Haskell thread is blocked, the runtime returns to the JavaScript event loop; a callback, a timer (for threadDelay) or a settling Promise resumes it. While callbacks exist the runtime stays alive after main returns. threadDelay, MVar and forkIO work unchanged.

Promises. An interruptible import is an async function. The calling thread waits for its Promise through an MVar that the JavaScript side fills when the Promise settles; the other threads keep running. A rejected Promise is a JSException.

Exceptions. safe and interruptible imports turn a JavaScript exception into a JSException (new, in Control.Exception.Internal, raised by the runtime as the JSVal node itself; primIsInt reports it with a new rts_exn code, the same mechanism as the other RTS exceptions). unsafe, the default, treats one as fatal, as GHC's JavaScript backend does. The exception's description comes from js_exn_string, an ordinary C function (Ptr () -> IO CString) that Control.Exception.Internal imports and decodes; js_free_jsval is the same kind of function. Neither needs the compiler to know anything about the JavaScript runtime.

Targets. browser (WebAssembly, -Oz -sSUPPORT_LONGJMP=wasm, no file system), browser_js (-sWASM=0), emscripten_js, and browser_rts, all for programs, unlike the existing emscripten_web, which runs the compiler itself in a page and is untouched (mhs.conf.in now says which is which). With browser_rts the runtime is built once, and the program is compiled to a .comb and fetched at run time (src/runtime/web/rts-web.js, 40 lines). It is what makes a sub-second edit-reload loop possible without emcc; the .comb's ##### foreign-import listing tells the tool when the runtime must be rebuilt.

GHC.Wasm.Prim, 122 lines in base: JSVal, JSString, JSException, toJSString/fromJSString, textToJSString/textFromJSString (UTF-8 with explicit lengths, so NUL and a leading U+FEFF survive), freeJSVal, jsNull/jsUndefined/isNull/isUndefined, and the callback functions. The name is GHC's so that code written for GHC's WebAssembly backend compiles; see the questions below.

Design

No ASYNCIFY. A blocked Haskell thread keeps its state in the heap (mt_root); cleanup() already clears the C stack on every reschedule. So "all threads blocked" is a state the runtime can simply return from: run_threads() returns to mhs_main, which calls emscripten_exit_with_live_runtime(), and mhs_js_run_threads() (called from a timer, after a callback, or when a Promise settles) continues them. The C stack of main is gone and nothing needs it.

A callback is a thread, run to completion. run_callback() creates a thread for the IO action, puts it at the head of the run queue, and evaluates it with a slice that is never exhausted (CALLBACK_SLICE), so no other thread runs under it. Called from the event loop (no Haskell thread on the C stack) it may block, in which case it is parked like any thread and JavaScript gets undefined. Called from inside the JavaScript of an import, or when it must return a value, it must not block: that is a fatal error, since a Haskell thread's C frames are below it. throwTo from a callback cannot wait for delivery and is asynchronous there. The previous fork code ran callbacks on whatever stack was current with no current thread, which is why catch, getMaskingState, forkIO and myThreadId read a null pointer in a callback; that is what this replaces.

Why setjmp-based catch forces -sSUPPORT_LONGJMP=wasm for -Oz. With emscripten's JavaScript longjmp, every call out of a function containing setjmp goes through a JavaScript trampoline. -O3 inlines most helpers into evali and pays a percent or two; -Oz does not inline and a miso application spent 84% of its time in trampolines. With WebAssembly exception handling (all browsers since 2022) -Oz matches -O3 and is about 12% smaller compressed. browser_js has no wasm and stays -O3.

Why EM_JS and not EM_ASM or a --pre-js. The code of each import has to be visible to emscripten's optimizer so that definitions in embedded .js files it calls are kept (#529 made those files --pre-js; a direct eval of a string would hide the uses). EM_JS gets the code into the output as a named function. The compiler passes the code to _EM_JS as a C string literal because EM_JS stringifies its body with #__VA_ARGS__, which requires valid C tokens; JavaScript with unbalanced quotes or # is not.

Why the JSVal table and not the value in the heap. Only numbers cross the wasm boundary. This is also GHC's design (JSValManager: a Map keyed by integer, a FinalizationRegistry for callbacks).

A stopped runtime stays stopped. Every entry from JavaScript (callbacks, timers, settling Promises) goes through one wrapper that records an exception unwinding the C stack, and main itself runs inside such a frame (mhs_js_enter_main), so a wasm trap at any point marks the runtime as stopped; later calls into Haskell throw an Error instead of running on a corrupted heap. An unsafe import's JavaScript exception is fatal by the same route.

What changes where

area lines what
src/runtime/jsffi.c, jsffi.h +815, +37 new, #included by eval.c (it needs the evaluator's statics): the JavaScript side (mhs_js_init, 190 lines of JS in one EM_JS), JSVal handles, run_callback, mhs_js_callback, mhs_js_settle, js_await (for T_IO_JSAWAIT), js_suspend (the event-loop return in run_threads), mhs_js_run_threads, arm_timer, mhs_js_enter_main, js_exn_string/js_free_jsval (with native stand-ins), mhs_run_web and run_comb, js_throwto/js_yield (throwTo and yield in a callback), js_main_done, mhs_to_HsStablePtr; jsffi.h declares what eval.c calls
src/runtime/eval.c +207 −28 the hooks into jsffi.c (each call site a line or two under #if; throwto, yield, pause_exec, MHS_INIT_ARGS and the end of mhs_main_body are unchanged for other targets), T_IO_JSAWAIT/T_IO_JSAWAITRES, start_exec split into run_threads, main_finish split out of mhs_main so it can also run from the event loop, FP_JSVAL, exn_jsexception, rts_exn_msg/die_msg split out of die_exn
src/runtime/mhsffi.h +12 mhs_from_JSVal/mhs_to_JSVal/mhs_js_check_error, mhs_to_HsStablePtr, js_exn_string/js_free_jsval
src/MicroHs/FFI.hs +200 −48 one EM_JS per import, the expression/statement decision, $k checking, the wrapper imports, #if __EMSCRIPTEN__ guards so native builds compile
src/MicroHs/Desugar.hs +58 −10 jsKind, the interruptible wrapping (^f >>= IO.jsawait kind), module-qualified FFI numbers
Expr.hs, Parse.hs, TypeCheck.hs +19 −13 Safety is kept on ForImp
lib/GHC/Wasm/Prim.hs +122 new
lib/Control/Exception/Internal.hs +52 −2 JSException and its message (a small UTF-8 decoder over peek_uint8); catch re-raises the translated exception
lib/Primitives.hs, lib/base.cabal +2 JSVal
mhs.conf.in +44 −1 four targets, and a comment on the two families
src/runtime/web/rts-web.js +40 the browser_rts loader
tests/ +700 see below
README.md +139 a "JavaScript FFI" section

Two changes are not emscripten-specific and are worth a look on their own:

  • Foreign import C names are now module-qualified (mhs_<module>_<n> instead of mhs_<n>), for every import whose entity is not a plain C identifier. The number is only unique within a module; two modules with inline-code imports collided. This changes generated C for existing programs with such imports.
  • catch re-raises the translated exception (primRaise se instead of primRaise e in Control.Exception.Internal), so a handler of the wrong type passes on the SomeException it was given, not the raw RTS value.

What it deliberately does not do

  • No JavaScript FFI for a native mhs, and no way to run the JavaScript at compile time.
  • No marshalling beyond the scalar types and JSVal; String/Text go through toJSString, lists and records are a library's job.
  • No DOM library. This is the FFI such a library is written with.
  • The .comb of a program is not self-describing for browser_rts: the runtime's FFI table is fixed when it is built. A program with other foreign imports needs another runtime (--embed-ffis).
  • No restart after a fatal error. In the browser the page lives on, and every later call into Haskell throws an Error saying the runtime has stopped, instead of running on a corrupted heap.

Compatibility and cost for non-emscripten targets

  • jsffi.c is all under #if defined(__EMSCRIPTEN__) except the two native stand-ins. In eval.c everything is under #if except: two new rts_exn codes and FP_JSVAL (enum values), main_finish being a function, the mt_callback flag on struct mthread, and T_IO_JSAWAIT erroring. gc_check is unchanged for native code.
  • A module using foreign import javascript compiles and runs natively; the imports become T_BADDYN nodes and error only if called (tests/JSNative.hs).
  • base gains GHC.Wasm.Prim and JSException. Native programs that use catch now link js_exn_string and js_free_jsval, which exist as stand-ins in the native runtime, so nothing changes at run time.
  • generated/mhs.c and generated/base.pkg are regenerated; the compiler bootstraps to a fixpoint. The native test suite and the emscripten tests passed locally after the rebase; the later moves into jsffi.c/jsffi.h are checked by CI.

Tests

test target covers
JSVal emscripten every import form and type (incl. Word above 2^31), JSString round trips (NUL, U+FEFF), the three safety annotations, freeJSVal, GC of handles
JSCallback (19 cases) emscripten catch/mask/forkIO/myThreadId in a callback; uncaught exceptions in sync and async callbacks; killThread from a callback; a callback during an await; use after free; value callbacks run once; the handle table stays bounded; parked callbacks; nested callbacks and their errors; an unsafe exception stopping the runtime
JSDeadlock, JSExportBlocked, JSExitTimer, JSTrap emscripten deadlock reported once callbacks are freed; a foreign export while main is blocked; exit with a thread still in threadDelay; a wasm trap during main stops the runtime
BrowserRtsOther browser_rts a runtime running a program it was not built with
ForImpJS (extended), JSNative, JSFlag/JSBits (from #529, renumbered)

A real application: haskell-miso.org built with this branch, the miso website built entirely by MicroHs: the client (-tbrowser, one app.js with the wasm embedded) and the 48 prerendered pages, written by the site's prerender program compiled with MicroHs for -temscripten and run under node. The client hydrates the prerendered HTML; routing, the theme toggle, the CSS animations and the interactive demos work. Size and timings are under Size and performance.

make runtestemscripten runs them. The same tests also pass compiled for the browser target (-Oz, wasm SjLj) under node; the native core suite passes with the new library; and miso's integration tests pass built with MicroHs for both browser and browser_js, in miso's CI (dmjio/miso#1694) and locally with emscripten 4.0.10 and 6.0.9.

Size and performance

The same site, haskell-miso.org, built two ways: the production site (GHC 9.14 WebAssembly backend, wasm-opt -O2, prerendered by GHC) and https://mhs-latest.netlify.app (this branch: client and prerendered pages both built by MicroHs). Both are prerendered HTML that the client hydrates.

Size of the code the browser downloads:

GHC wasm MicroHs
files app.wasm + ghc_wasm_jsffi.js + index.js app.js (wasm embedded)
over the wire, as served 1,149,945 B (gzip) 365,869 B (brotli)
gzip -9, like for like 1,103,202 B (app.wasm alone) 381,930 B
uncompressed 5,529,506 B 1,797,442 B

Performance, headless Chromium, cold cache, 10 loads per build and condition; navigation is 6 in-app clicks per load (/docs/, /examples/, /blog/, twice), timed until the new page's heading is in the DOM and two frames have been drawn. The two sites are on different hosts (Netlify and production's), which affects first paint more than anything else here. In the plots, [==#==] is the middle half of the samples with # at the median, and the whiskers reach the minimum and maximum.

Desktop CPU

First contentful paint (ms, n = 10 per build)
GHC        |-[==#=]----------------------------------------|   median 332
MicroHs              |[#===]--------------|                    median 414
         250                       550                    850

App running (miso started) (ms, n = 10 per build)
GHC       |[=#==]--------------------------------------|       median 556
MicroHs                            |---[#=]----------------|   median 890
         500                       825                   1150

In-app navigation (ms, n = 60 per build)
GHC        |--[=====#====]-----------------------------|       median 125
MicroHs         [========#=======]-------------------|         median 158
         50                        225                    400
build min median p75 max
first contentful paint GHC 276 332 360 836
first contentful paint MicroHs 396 414 463 636
app running GHC 508 556 586 1086
app running MicroHs 832 890 916 1135
navigation GHC 67 125 159 364
navigation MicroHs 98 158 212 353

Page errors: GHC 0, MicroHs 0.

CPU throttled 4× (about a mid-range phone)

First contentful paint (ms, n = 10 per build)
GHC           |--[#==]-----------------------------------|     median 472
MicroHs                   |--[==#==]--------|                  median 580
         400                       600                    800

App running (miso started) (ms, n = 10 per build)
GHC       |[#=]-------------|                                  median 972
MicroHs                                     |---[===#===]-|    median 2028
         900                       1575                  2250

In-app navigation (ms, n = 60 per build)
GHC        |-[==========#==========]---------------------|     median 366
MicroHs       |---[==============#========]--------|           median 516
         100                       550                   1000
build min median p75 max
first contentful paint GHC 440 472 495 780
first contentful paint MicroHs 536 580 605 672
app running GHC 929 972 1024 1412
app running MicroHs 1832 2028 2133 2200
navigation GHC 133 366 560 952
navigation MicroHs 197 516 684 833

Page errors: GHC 0, MicroHs 0.

In short: in-app navigation is within about 30 ms of GHC on a desktop CPU and about 1.4× on a slow one; startup, until the app is running, is about 1.6× on a desktop CPU and 2× on a slow one. The time goes into MicroHs evaluating a combinator graph where GHC runs compiled code; the FFI hot spots (string conversion, per-callback allocation, the JSVal table) have not been optimised yet.

Questions for review

These are the decisions I would rather have your view on than guess at:

  1. Where the emscripten code lives. It is 900 lines in eval.c under #if. Done, as suggested: it is now in src/runtime/jsffi.c, #included from eval.c like md5.c (it needs the evaluator's statics, hence inclusion rather than a separate translation unit). eval.c calls it only through a few plain C functions declared in src/runtime/jsffi.h (js_init, js_enter_main, js_main_done, js_suspend, js_await, js_ffe_eval, js_throwto, js_yield, report_callback_exn), since an EM_JS function must be defined before its first use. Non-emscripten code paths in eval.c read as before.
  2. The module name. GHC.Wasm.Prim is GHC's name and is what makes miso's FFI layer compile unchanged. If you would rather not have GHC.* in lib/, an Mhs.JS (or similar) with GHC.Wasm.Prim re-exporting it works too.
  3. The safety mapping. Here unsafe (the default) is synchronous and fatal on exception, safe synchronous with JSException, interruptible asynchronous. GHC's WebAssembly backend makes safe the asynchronous one. The split here keeps "may this block" and "may this throw" independent, but it is a divergence from GHC that I want to be deliberate.
  4. _EM_JS. The compiler uses emscripten's internal macro to pass the code as a string. It has been stable since EM_JS exists, but it is underscored. The alternative is a small header in src/runtime defining our own MHS_EM_JS with the same expansion, which pins the dependency in one place.

Reviewing in parts

The runtime, the compiler and the targets can be read independently, in that order:

  1. Runtime (jsffi.c, then eval.c and mhsffi.h): in eval.c the hooks under __EMSCRIPTEN__, plus main_finish, run_threads, mt_callback, the enums. Testable through the existing foreign export javascript without the new syntax.
  2. Compiler and library (FFI.hs, Desugar.hs, Expr.hs, Parse.hs, TypeCheck.hs, GHC.Wasm.Prim, Control.Exception.Internal).
  3. Targets (mhs.conf.in, rts-web.js, README).

If splitting into three PRs is easier for you, the commits are already arranged so that each part builds on its own.

🤖 Generated with Claude Code

@augustss

augustss commented Nov 5, 2026

Copy link
Copy Markdown
Owner

It'll take a little while before this gets merged.
I'm not going to merge a PR I don't understand, and this is a rather large PR. :)

@dmjio

dmjio commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

Understandable, it is very big yes. Sorry about that :) The good news is that it is pretty well isolated to eval.c and gated behind __EMSCRIPTEN__, so it shouldn't disturb others.

No rush to merge at all. And if you come to the conclusion this would better live in a fork, that's completely fine by me. I just figured this would put us at parity with GHC in terms of its JS / WASM backend features, and others could benefit as well.

@augustss

augustss commented Nov 8, 2026

Copy link
Copy Markdown
Owner

I definitely want mhs to have the functionality that this provides, so it will get merged eventually.
I think it's great that the JS stuff gets some love.

@augustss

augustss commented Nov 8, 2026

Copy link
Copy Markdown
Owner

To answer question 1: I would prefer if the 900 lines added to eval.c were in a separate file that is #included

dmjio and others added 17 commits November 8, 2026 14:40
…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. Squash of the jsval branch onto upstream master.

- foreign import javascript: the JavaScript code is inline, with the
  arguments as $1, $2, ...; each import becomes an EM_JS function,
  mhs_js_<name>, so emscripten's optimizer sees what the code uses and
  keeps it. Whether the code is an expression or statements is decided
  at compile time (jsIsStatements). safe and interruptible imports turn
  a JavaScript exception into a JSException; an interruptible import is
  async, and the calling thread waits for its Promise while the others
  run.
- 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, and each callback keeps its own 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.
- Targets browser, browser_js, emscripten_js and quickjs, and
  browser_rts: a runtime built once that fetches and runs a combinator
  program (app.comb), so a rebuild needs no C compiler.
- JavaScript files embedded in the output: .js arguments and the jsbits
  of a package (README; the suffix detection itself is upstream, augustss#529).
- A module that uses the JavaScript FFI still compiles for a native
  target (tests/JSNative.hs).
- Tests: JSVal, JSCallback, ForImpJS, JSNative, BrowserRtsOther, run
  with the emscripten tests.

Data.Text.Encoding is left as upstream has it: augustss#557 already stores NUL
as C0 80 in decodeUtf8 and turns it back into 00 in encodeUtf8.

The compiler is regenerated in two steps, since the runtime's
js_exn_string (used by Control.Exception.Internal) is only in the new
compiler's runtimeFFI list: upstream's compiler built the new one with
upstream's Control.Exception.Internal, which then bootstrapped (stage2
equal to stage1).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
- foreign import javascript: a $k in the code that is not an argument
  (in particular $0: the arguments are $1, $2, ... as with GHC's
  WebAssembly backend, but were $0, $1, ... before) is a compile-time
  error, instead of an undefined variable when the code runs.
- Code that starts with 'function' or 'class' is a function or class
  expression unless more code follows it; it was taken for statements,
  which made the generated JavaScript a syntax error.  'return' as a
  property name ($1.return) no longer makes the code statements.
- A foreign export called from JavaScript while the threads wait in the
  JavaScript event loop runs as a thread of its own, like a callback.  It
  ran as a second main thread, which ended the program when it finished.
- The runtime counts the live callbacks instead of setting a flag when
  the first one is made, so a deadlock is reported again once they have
  all been freed.  Standard output is flushed when the runtime returns
  to the JavaScript event loop.
- A callback that runs out of its reduction budget gets a new one, so
  yield() does not run on every reduction from then on.
- Tests: JSDeadlock, JSExportBlocked.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
When every thread is blocked and one is in threadDelay, the runtime arms a
JavaScript timer and returns to the event loop.  If main then finished (woken
by a callback or a Promise) with no live callback, main_finish called exit(),
which under emscripten_exit_with_live_runtime only throws ExitStatus to the
caller, and the timer stayed armed.  When it fired, runThreads called check()
outside any try, so the "runtime has stopped" Error was thrown into a bare
setTimeout callback: in node an uncaught exception (exit status 1 instead of
0, after waiting out the delay), in a browser a console error.

Stopping the runtime (stop, and the atexit hook mhs_js_exited) now also clears
the timer, and runThreads does nothing once the runtime has stopped: a timer
has no caller to throw to.

Test: JSExitTimer, run with the emscripten tests.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The parameters of the EM_JS function of an import are wasm i32s, which arrive
in JavaScript as signed numbers, and emscripten does no unsigned conversion.
So a Word argument >= 2^31 was negative in the JavaScript code ("$1" applied
to 0xFFFFFFFF gave -1).  Convert it in place with >>> 0, as Bool and JSVal
arguments are converted.  Results were already right: ToInt32 wraps them.

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

js_fromUTF8 decoded with a default TextDecoder, which strips a leading byte
order mark, so toJSString "\xFEFF..." lost its first character (miso worked
around this in its own Data.JSString).  Decode with ignoreBOM, and create the
decoder once instead of on every conversion.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
It was never run, and a program using threadDelay hangs on it: the
runtime returns to the event loop with a setTimeout, and qjs has none.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The end of mhs_main became main_finish so that it can also run from
mhs_js_run_threads.  Defining it before mhs_main made the diff show the
whole tail as moved; after it, the tail stays in place and only the
emscripten branch in mhs_main is new.  No change in behaviour.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
node colours a number given to console.log as a separate argument when
FORCE_COLOR is set (the output then has escape codes), so the test failed
on such a terminal.  Concatenate instead.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Subsections (calling JavaScript, JavaScript values, callbacks, the event
loop, targets, the browser runtime, embedded files), tables for the safety
annotations and the targets, and the facts of the current branch: $0 is an
error, a leading U+FEFF survives, browser_rts and rts-web.js, and that
a foreign export called from JavaScript must not block.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Only entries through Module.mhsjs.enter (callbacks, timers, Promises) and an
unsafe import's catch recorded that the runtime had stopped.  A wasm trap
while main itself was running, e.g. the evaluator exceeding the stack, went
to emscripten's callMain instead: in the browser that is a console error,
ABORT stays false, and the next DOM event ran its callback on a corrupted
heap.  main now runs inside a JavaScript frame (mhs_js_enter_main) that
calls Module.mhsjs.stop for any exception except emscripten's 'unwind',
then rethrows, so callMain still decides what an exit means.

Test: JSTrap, an out of bounds read while main runs; a callback called
50 ms later is refused.  It needs its own pre-js to keep node alive after
the uncaught exception.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…me's

mkCallback fetched a value callback's result (getJSVal) inside enter, so a
callback that returned a JSVal it had already freed made enter stop the
runtime for good, although nothing had unwound: the C stack had returned
normally.  The result is now taken right after enter (still before any other
Haskell thread runs), and an error there is thrown to the caller like an
uncaught Haskell exception.  Test: JSCallback 20.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
JavaScript such as 'x ??(y)' inside the generated C string literal forms a
trigraph.  Clang's default mode only warns, but a strict C99 build would
rewrite the code.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
They were hand-written FFI adapters, known to the compiler through its
runtimeFFI list, and js_exn_string was the only runtime entry typed IO String
(building the Haskell string in C).  A compiler without them in its list,
i.e. upstream's or any older one, generated stubs for them and failed on the
types: the library could only be built by a compiler already regenerated
with this branch, in two steps.

Now they are plain C functions with C types, declared in mhsffi.h:
  js_exn_string :: Ptr () -> IO CString    the description, malloc()ed, UTF-8
  js_free_jsval :: Ptr () -> IO ()
The JSVal is passed as the payload of its foreign pointer, which is the
handle (primForeignPtrToPtr), so no new C type is needed, and the stubs are
generated as for any other import.  Control.Exception.Internal decodes the
UTF-8 itself (it cannot import Foreign.C.String) with the peek_uint8 and
free runtime entries, which every compiler has.  Natively the two functions
exist too, so a program using the JavaScript FFI still links.

The regeneration takes one more stage than usual once: the current compiler
emits no stub for js_exn_string, the one it builds does, and the one after
that is the fixpoint (stage 2 equals stage 3).

Test: JSVal checks that a non-ASCII message survives.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The nested if in the let of peekUTF8 was an hlint suggestion, which the
lint job treats as a failure.  Regenerates base.pkg.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
emscripten, emscripten_js, browser, browser_js and browser_rts are for
programs (with the JavaScript FFI and the event loop); emscripten_web is
for running the compiler itself in a web page (web-mhs/).  Say so where
the targets are defined and described; nothing else changes.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Both are hlint suggestions, which the lint job treats as failures; the
Tester one is in upstream's own recent change (upstream's lint job fails
on it too).  Regenerates tester.c and base.pkg.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@dmjio
dmjio force-pushed the jsval branch 2 times, most recently from 934c206 to 7635597 Compare November 8, 2026 21:27
dmjio and others added 2 commits November 8, 2026 15:51
The emscripten code (the JavaScript side, JSVal handles, callbacks,
interruptible imports, running the threads from the JavaScript event
loop) moves from eval.c to src/runtime/jsffi.c, #included by eval.c like
md5.c, since it needs the evaluator's statics.  eval.c calls it through a
few plain C functions declared in src/runtime/jsffi.h, included at the
top of eval.c under __EMSCRIPTEN__ (an EM_JS function must be defined
before its first use).

What only the JavaScript FFI uses lives there too: the callback cases of
throwto() and yield() (js_throwto, js_yield), the end of main under
emscripten (js_main_done), the run time program of browser_rts
(run_comb), and mhs_to_HsStablePtr.  So for other targets throwto(),
yield(), pause_exec(), MHS_INIT_ARGS and the end of mhs_main_body read
as before.

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

dmjio commented Nov 8, 2026

Copy link
Copy Markdown
Contributor Author

Okay cool, have gone ahead and moved most of the JS FFI logic out of eval.c into jsffi.c, as suggested:

  • src/runtime/jsffi.c (new) holds all the emscripten runtime code: the JavaScript side, JSVal handles, callbacks, interruptible imports, and running the threads from the JavaScript event loop. It's #included from eval.c like md5.c, since it needs the evaluator's internals.
  • src/runtime/jsffi.h (new, small) declares what eval.c calls. Each call site in eval.c is now a line or two under #if defined(__EMSCRIPTEN__).
  • The eval.c diff went from +975 to +207 lines, most of it now in jsffi.c. For non-emscripten targets, throwto, yield, pause_exec, MHS_INIT_ARGS and the end of mhs_main are unchanged.

Claude identified additional things present in this PR that we could upstream separately, to make it easier to review. These aren't JS FFI specific; they fix bugs the JS FFI runs into (1 especially), but apply more generally.

FFI bug fixes, with tests where possible.

    1. Module-qualified C names for foreign imports. Inline-code imports (capi expressions, javascript) are named mhs_<n>, where n is the binding's position in its module. Two modules can get the same name, and makeFFI then silently keeps only one of them, so the other module's import calls the wrong function.
    1. dropForallContext in ccall/arity. A foreign import with a forall or a constraint in its type gets the wrong arity.
    1. catch re-raises the translated exception (se instead of e), so a handler of the wrong type passes on a proper SomeException.
    1. A one-word fix: mhs_js_set_haskellCallback now uses globalThis._haskellCallback, since assigning an undeclared global throws in strict mode.

I can split these off into 4 separate PRs, and then rebase against master here, to make this PR more focused.

@augustss

augustss commented Nov 8, 2026

Copy link
Copy Markdown
Owner

Yes, please split. I prefer unrelated items to go in their own PRs.

@augustss

Copy link
Copy Markdown
Owner

Adding safe/unsafe to the AST would be a good thing to split out.

dmjio and others added 2 commits November 12, 2026 17:44
Conflicts:
- Parse.hs: take master's default safety (Safe, as in the Haskell report).
  README updated; the JSCallback test that relies on a fatal exception is
  now explicitly `unsafe`.
- Desugar.hs: keep jsval's safety-aware ForImp/parseImpEnt, take master's
  foreign import C name (number first, then module).
- tests/Makefile: keep both testjsnative and testffiname.
- generated/mhs.c, generated/base.pkg: regenerated (mhs.c at a fixpoint).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Conflicts:
- Desugar.hs: drop an explicit forall from a foreign import's type
  (master, augustss#574), then apply jsval's safety handling to that type.
- tests/Makefile: keep both testforimpforall and testjsnative.
- generated/mhs.c, generated/base.pkg: regenerated (mhs.c at a fixpoint).

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

This branch has not been deployed

No deployments
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.

2 participants