Skip to content
JeremiasRyPublic

About

A javascript runtime

Resources

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

GO_JS: A javaScript runtime and a JIT-compiler

A javascript runtime built from scratch using GO

Features

  • Event loop (setTimeout, async/await, micro/macro task queues)
  • mark-and-sweep Garbage collection
  • Bytecode VM (A custom stack based virtual machine)
  • JIT compilation
  • Closures / Classes
  • Core language support: Prototypal inheritance, for..of, for..in, while, for, try/catch, Promises, let/const, object destructuring, generators
  • String, Date, Array, Object, Map, Promise and Set prototypes

Flow of execution / Design

  1. Parse javascript file into an AST, (uses a port of acorn to golang.)
  2. Pre-pass the syntax tree to define all variables to symboltables and figure out if anything is captured by a closure etc.
  3. Compile the syntax tree into a custom bytecode
  4. Start 2 goroutines, one for the virtual machine and one for the event loop
    • The vm listens to our eventloop
  5. Dispatch our generated function (the bytecode) to the event loop
  6. VM picks up our function and begins executing
    • during execution, hot functions are compiled by the JIT and run as machine code; hot loops inside functions that are called only once are entered with on-stack replacement (OSR)
    • unsupported instructions (heap operations, calls, string conversion, iterators) return to Go through a bridge that performs the operation with full VM semantics and then re-enters the compiled code; a failed guard deoptimizes to the interpreter at the exact bytecode IP
    • all possible encounters with setTimeouts/await instructions are dispatched to our eventloop accordingly
    • when out of work VM will first drain the microtask queue, after that it will consumethe task queue
  7. If our VM is not executing and eventloop doesn't have any work, we have finished our program
flowchart TD
    A[Parser] -->|AST| B[Compiler]
    B --> | bytecode| C{Start Runtime}
    C --> |bytecode| D[Event Loop]
    D --> | task | G[Task Queue]
    C -->E[Virtual Machine]


    G --> |task| E
    R --> |setTimeout/promise/await| D

    E --> |function| T(Call)

    T -->  J{hot path JIT?}
    J --> | Yes | I(Compile)
    J --> | No | R(Execute)
    I --> | machine code | R
Loading

Implementation Scope & A real world example

The runtime is not a full ECMAScript implementation, for example var is completely omitted, it can handle an Advent Of Code puzzle which encompasses a lot of useful language features, also scripts in the test-scripts folder give a good representation of the language features implemented.

See the ECMAScript implementation roadmap for prioritized features, implementation dependencies, and JavaScript regression tests.

How to run

Requires go version 1.22.5

  1. git clone the repo
  2. cd /runtime
  3. go run main.go <your_javascript_file.js> use --debug flag to see all the fun stuff

Test suite can be run with docker by running ./test.sh in the root of the repo. Set GO_JS_DIFFERENTIAL=1 to run every positive case with the JIT both disabled and forced, and fail on any divergence.

Web demo and MCP agent bridge

The web demo exposes one MCP endpoint per browser/device:

https://<host>/session/<client-id>/mcp

Open the demo, copy the MCP endpoint shown above the editor, and give it to a Streamable HTTP MCP client.

The MCP activity indicator is separate from the browser connection. It shows Agent active after valid MCP traffic and Last active after 60 seconds without traffic, so manual runs work without an MCP client connected.

Every browser tab keeps its own WebSocket connection to /ws/<client-id>, and all tabs for the same client share one session. The WebSocket carries only small status notifications; job submission and results use HTTP:

  1. Manual runs submit POST /session/<client-id>/jobs with a client_request_id.
  2. GET /session/<client-id>/jobs/<job-id> returns the authoritative status, and GET /session/<client-id>/jobs/<job-id>/result returns raw JSON with gzip when the browser accepts it.
  3. An MCP client calls the execute tool.
  4. The backend pushes the code to every connected tab over WebSocket.
  5. The tabs replace the editor contents, and the first HTTP submission is accepted using the execute request ID as its idempotency key.
  6. The backend queues the job for the Firecracker worker pool and broadcasts run.status events for Pending, Processing, and the terminal state.
  7. The browser fetches the result over HTTP, while the MCP tool call receives the output extracted by the worker.

The session survives brief WebSocket disconnects and expires 30 minutes after the last browser tab disconnects. Status polling recovers terminal jobs after a backend restart. Session and in-flight job state are kept in memory; restarting the backend invalidates active sessions, but the stable client id recreates the same MCP URL on the next page load.

For frontend development, the SvelteKit dev server proxies /ws, /session, and /scripts to port 8000, so the same browser-origin URLs work in development and production.

Test runner

The test runner is neatly packaged in to a docker container.

test.sh

  1. Discover all top-level .js files in test-scripts and the configured negative tests.
  2. Run each case against NodeJS and GO_JS with the same Script or Module source goal.
  3. Compare stdout and verify expected error classes/phases. Timeouts, crashes, and mismatches fail the suite.
./test.sh

The expanded ECMAScript tests run through this same Docker suite. test/cases.json configures source-goal overrides, expected-error cases, and the per-process timeout. Imported fixtures are loaded by their entrypoints. The suite reports every case and exits nonzero if any regression, puzzle, or benchmark execution fails.

After the test run few benchmark scripts are also ran against nodeJS to compare the performance (essentially comparing against V8). Below is one example run summarized (The test suite was ran on my local machine)

Benchmark NodeJs GO_JS
'naive-recursive-fib.js' 545ms 590ms
'try-catch-shenanigans.js' 1037ms 509ms
'string-operations.js' 14ms 49ms
'array-iteration.js' 34ms 108ms
'object-access.js' 55ms 481ms

About

A javascript runtime

Resources

Stars

1 star

Watchers

1 watching

Forks

Used by

Contributors

Languages