From 5fad92b6dc503876c82542ce543c975e816226cd Mon Sep 17 00:00:00 2001 From: Steve Dekorte Date: Tue, 17 Nov 2026 11:33:46 -0800 Subject: [PATCH] Backtraces: record the call chain when an exception is raised Uncaught errors printed "nothing on stack": the backtrace was built from Call objects on the retain stack, which the stackless evaluator no longer leaves there, and the frames are unwound before anything prints. An exception now records its trace from the frame chain at the moment it is raised (IoState_error_ and Coroutine rawSignalException): the raising frame, then each frame waiting on a method or block it called, capped at 64 entries. Exception stackTraceLines formats it; Coroutine backTraceString prints it. pass keeps the original trace. The failing message is added from originalCall or caughtMessage when a tail call replaced its frame. Raising costs about 7-10% more (roughly 3 microseconds). Known limit: a tail call reuses its caller's frame, so the caller of a method's last call has no entry. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011WETVfgtbJ5chDp7AeZUe9 --- Release Notes/_index.json | 5 ++ Release Notes/index.html | 4 +- agents/wasm/Plan.md | 16 ++-- browser/test/vm.test.mjs | 8 ++ docs/Guide/_index.md | 18 ++++ docs/Guide/index.html | 10 ++- docs/index.html | 2 +- index.html | 4 +- libs/iovm/io/Exception.io | 69 ++++++++++++---- libs/iovm/source/IoCoroutine.c | 6 +- libs/iovm/source/IoState_exceptions.c | 54 ++++++++++++ libs/iovm/source/IoState_exceptions.h | 1 + libs/iovm/tests/correctness/BacktraceTest.io | 87 ++++++++++++++++++++ llms-full.txt | 27 +++++- llms.txt | 2 +- 15 files changed, 277 insertions(+), 36 deletions(-) create mode 100644 libs/iovm/tests/correctness/BacktraceTest.io diff --git a/Release Notes/_index.json b/Release Notes/_index.json index 1178faa5f..1e4720ce5 100644 --- a/Release Notes/_index.json +++ b/Release Notes/_index.json @@ -6,6 +6,11 @@ "type": "ContentText", "body": "

Io uses date-based versioning. This page collects the notable changes of the last twelve months — a period in which the VM was rewritten around a stackless evaluator and re-targeted from native binaries to WebAssembly. Entries marked tagged correspond to release tags in the repository; the rest are development milestones on the road between them. For the longer arc, see the Timeline.

" }, + { + "type": "ContentText", + "title": "Unreleased", + "body": "

On master, not yet tagged.

" + }, { "type": "ContentText", "title": "2026.11.18 — Long-running programs stop growing", diff --git a/Release Notes/index.html b/Release Notes/index.html index 69ef43fe0..8b226c241 100644 --- a/Release Notes/index.html +++ b/Release Notes/index.html @@ -11,8 +11,8 @@ -

Release Notes

← Home
Io

Notable changes in Io over the past twelve months.

Io uses date-based versioning. This page collects the notable changes of the last twelve months — a period in which the VM was rewritten around a stackless evaluator and re-targeted from native binaries to WebAssembly. Entries marked tagged correspond to release tags in the repository; the rest are development milestones on the road between them. For the longer arc, see the Timeline.

2026.11.18 — Long-running programs stop growing

Tagged 2026.11.18. A memory fix for programs that never return to the top level: servers, actors, and long-lived coroutines.

  • Loops release their temporaries — while, loop, for and foreach kept every value a loop body created until the enclosing method returned, so a top-level script or an actor that loops forever grew without bound. A 300,000-iteration loop used to leave 300,000 objects behind; it now leaves two (#513).
  • Coroutine switches no longer leak — each yield, pause or resume left a stray marker on the retain stack that kept a few objects alive per switch.
  • A possible crash in for and foreach — loops counting through small integers released the wrong retain-stack entries on each iteration, which could corrupt the stack.

2026.11.17 — Io on npm, and inside the JS event loop

Tagged 2026.11.17. The first release since the WASM merge, and the first on npm.

  • npm package — npm install @iolanguage/io runs the VM from JavaScript in Node and browsers (@iolanguage/io). Releases publish to npm from the release workflow with provenance.
  • Io inside the JS event loop — in the browser and Node build, Io coroutines, actors, wait and await on JS Promises run without blocking JavaScript; an eval that waits resolves when it finishes, and callbacks JS calls later can wait too (#509).
  • ES module — the browser bridge is an ES module with a small API: Io.load(), eval, lobby, onOutput, dispose (#507).
  • Syntax errors no longer crash the VM — unfinished source such as x := ( raises a catchable compile error; it used to trap the VM and end a REPL session (#511).
  • Closures over method locals — a block created inside a method keeps its scope after the method returns; the locals used to be recycled while the block still used them.
  • Fixes found along the way — a message chain sent to an actor future ran more than once; then/catch/finally ran the rest of the statement twice; JS Promises stopped resolving after about a thousand; List_removeLast_ never removed anything, so retained objects were never released.
  • WASI 0.2 component build — make component builds the VM as a WebAssembly component (wasm32-wasip2) alongside the core WASI module.
  • Cooperative scheduler timer queue — wait parks the calling coroutine on a timer queue instead of busy-spinning; timed coroutines run concurrently and the VM idles in a single host wait until the next deadline.
  • Live Interpreter — an in-browser REPL running the full VM, linked from the home page.
  • Performance tracking — a benchmark page recording interpreter, shootout, and SIMD results over time.
  • WASI 0.3 notes — design notes on adopting native-async components (future/stream) once host and toolchain support land.

2026.04.20 — WASM becomes the default target

Tagged 2026.04.20-native-final. The WASM branch merged to master (#495); WebAssembly/WASI is now the default and only build target. The final native build — CMake, Eerie, and DynLib — is frozen at this tag, with ongoing native work on the native branch.

  • SIMD128 Vector backend — the Vector primitive gains a WebAssembly SIMD128 backend, restoring AltiVec-era vector acceleration on modern hardware and in the browser.
  • 64-bit integer literals — integer literals no longer truncate to 32 bits (#420).
  • Map equality — Map implements comparison for equality (#28).
  • JSON singletons — asJson added to nil, true, and false (#27).
  • isKindOf fix — ancestor checks use identity comparison (#201).
  • Site and Book restructured for the WASM era; continuous integration rewritten for the WASM toolchain.

2026.03.06 — Stackless alpha, WASM port, and the JS bridge

Tagged 2026.03.06-stackless-alpha. The first alpha of the stackless VM, together with the initial WebAssembly port and a new JavaScript integration model.

  • WASM/WASI cross-compilation — the VM compiles to a single portable WebAssembly module that runs under wasmtime, Node.js, or the browser.
  • Bidirectional Io↔JavaScript bridge — Io can call JavaScript functions and JavaScript can call Io methods, replacing the native addon model. DynLib, AddonLoader, and the Eerie addon infrastructure were removed.
  • Async/await across the bridge — futures integrate with JavaScript Promises: the eval loop yields and resumes across the JS boundary, and an unrecognized message sent to a pending future implicitly awaits its result.
  • BigInt — arbitrary-precision integers with transparent round-tripping across the Io↔JS bridge.
  • Browser REPL — an interactive interpreter hosted in a web page, with demos for the bridge, DOM access, async, and callbacks.
  • Strings default to UTF-8.

2026.02 — Stackless evaluator

The recursive, C-stack-based evaluator was replaced with a heap-allocated frame state machine — the foundation the WASM port builds on. With no native C stack to switch, the platform-specific coroutine assembly is no longer needed.

  • Iterative eval loop — evaluation runs on a frame state machine instead of C recursion.
  • First-class continuations — the current computation can be captured, resumed, stored, or serialized (callcc, behind the IO_CALLCC build flag).
  • Tail-call optimization — including through if branches.
  • Robust exception unwinding — Io-level exceptions are unwound by the eval loop rather than C setjmp/longjmp.
  • Resumable exceptions — Common Lisp–style signal / withHandler: a handler can resume at the signal site, fall through, or unwind.
  • GC-managed eval frames — frames are pooled, garbage-collected objects; coroutines became frame-based and the old platform-specific coroutine library was removed.

2025.07 — ARM64 coroutines

Native ARM64 coroutine support for Apple Silicon and modern Linux (#476) — the last major addition to the native-era coroutine implementation before the stackless rewrite made platform-specific coroutine code unnecessary.

+

Release Notes

← Home
Io

Notable changes in Io over the past twelve months.

Io uses date-based versioning. This page collects the notable changes of the last twelve months — a period in which the VM was rewritten around a stackless evaluator and re-targeted from native binaries to WebAssembly. Entries marked tagged correspond to release tags in the repository; the rest are development milestones on the road between them. For the longer arc, see the Timeline.

Unreleased

On master, not yet tagged.

  • Backtraces are back — an uncaught error prints the calls that led to it, with file and line, instead of “nothing on stack”. An exception records its trace when it is raised: Exception stackTraceLines returns it as a list, and pass keeps the original.
  • Build — make rebuilds the objects that include a changed header; a clean build is no longer needed after editing one (#515).

2026.11.18 — Long-running programs stop growing

Tagged 2026.11.18. A memory fix for programs that never return to the top level: servers, actors, and long-lived coroutines.

  • Loops release their temporaries — while, loop, for and foreach kept every value a loop body created until the enclosing method returned, so a top-level script or an actor that loops forever grew without bound. A 300,000-iteration loop used to leave 300,000 objects behind; it now leaves two (#513).
  • Coroutine switches no longer leak — each yield, pause or resume left a stray marker on the retain stack that kept a few objects alive per switch.
  • A possible crash in for and foreach — loops counting through small integers released the wrong retain-stack entries on each iteration, which could corrupt the stack.

2026.11.17 — Io on npm, and inside the JS event loop

Tagged 2026.11.17. The first release since the WASM merge, and the first on npm.

  • npm package — npm install @iolanguage/io runs the VM from JavaScript in Node and browsers (@iolanguage/io). Releases publish to npm from the release workflow with provenance.
  • Io inside the JS event loop — in the browser and Node build, Io coroutines, actors, wait and await on JS Promises run without blocking JavaScript; an eval that waits resolves when it finishes, and callbacks JS calls later can wait too (#509).
  • ES module — the browser bridge is an ES module with a small API: Io.load(), eval, lobby, onOutput, dispose (#507).
  • Syntax errors no longer crash the VM — unfinished source such as x := ( raises a catchable compile error; it used to trap the VM and end a REPL session (#511).
  • Closures over method locals — a block created inside a method keeps its scope after the method returns; the locals used to be recycled while the block still used them.
  • Fixes found along the way — a message chain sent to an actor future ran more than once; then/catch/finally ran the rest of the statement twice; JS Promises stopped resolving after about a thousand; List_removeLast_ never removed anything, so retained objects were never released.
  • WASI 0.2 component build — make component builds the VM as a WebAssembly component (wasm32-wasip2) alongside the core WASI module.
  • Cooperative scheduler timer queue — wait parks the calling coroutine on a timer queue instead of busy-spinning; timed coroutines run concurrently and the VM idles in a single host wait until the next deadline.
  • Live Interpreter — an in-browser REPL running the full VM, linked from the home page.
  • Performance tracking — a benchmark page recording interpreter, shootout, and SIMD results over time.
  • WASI 0.3 notes — design notes on adopting native-async components (future/stream) once host and toolchain support land.

2026.04.20 — WASM becomes the default target

Tagged 2026.04.20-native-final. The WASM branch merged to master (#495); WebAssembly/WASI is now the default and only build target. The final native build — CMake, Eerie, and DynLib — is frozen at this tag, with ongoing native work on the native branch.

  • SIMD128 Vector backend — the Vector primitive gains a WebAssembly SIMD128 backend, restoring AltiVec-era vector acceleration on modern hardware and in the browser.
  • 64-bit integer literals — integer literals no longer truncate to 32 bits (#420).
  • Map equality — Map implements comparison for equality (#28).
  • JSON singletons — asJson added to nil, true, and false (#27).
  • isKindOf fix — ancestor checks use identity comparison (#201).
  • Site and Book restructured for the WASM era; continuous integration rewritten for the WASM toolchain.

2026.03.06 — Stackless alpha, WASM port, and the JS bridge

Tagged 2026.03.06-stackless-alpha. The first alpha of the stackless VM, together with the initial WebAssembly port and a new JavaScript integration model.

  • WASM/WASI cross-compilation — the VM compiles to a single portable WebAssembly module that runs under wasmtime, Node.js, or the browser.
  • Bidirectional Io↔JavaScript bridge — Io can call JavaScript functions and JavaScript can call Io methods, replacing the native addon model. DynLib, AddonLoader, and the Eerie addon infrastructure were removed.
  • Async/await across the bridge — futures integrate with JavaScript Promises: the eval loop yields and resumes across the JS boundary, and an unrecognized message sent to a pending future implicitly awaits its result.
  • BigInt — arbitrary-precision integers with transparent round-tripping across the Io↔JS bridge.
  • Browser REPL — an interactive interpreter hosted in a web page, with demos for the bridge, DOM access, async, and callbacks.
  • Strings default to UTF-8.

2026.02 — Stackless evaluator

The recursive, C-stack-based evaluator was replaced with a heap-allocated frame state machine — the foundation the WASM port builds on. With no native C stack to switch, the platform-specific coroutine assembly is no longer needed.

  • Iterative eval loop — evaluation runs on a frame state machine instead of C recursion.
  • First-class continuations — the current computation can be captured, resumed, stored, or serialized (callcc, behind the IO_CALLCC build flag).
  • Tail-call optimization — including through if branches.
  • Robust exception unwinding — Io-level exceptions are unwound by the eval loop rather than C setjmp/longjmp.
  • Resumable exceptions — Common Lisp–style signal / withHandler: a handler can resume at the signal site, fall through, or unwind.
  • GC-managed eval frames — frames are pooled, garbage-collected objects; coroutines became frame-based and the old platform-specific coroutine library was removed.

2025.07 — ARM64 coroutines

Native ARM64 coroutine support for Apple Silicon and modern Linux (#476) — the last major addition to the native-era coroutine implementation before the stackless rewrite made platform-specific coroutine code unnecessary.

- + diff --git a/agents/wasm/Plan.md b/agents/wasm/Plan.md index 369b77409..6fb0d2b0d 100644 --- a/agents/wasm/Plan.md +++ b/agents/wasm/Plan.md @@ -24,14 +24,14 @@ The goal is to **target WASM as Io's only platform**, eliminating all OS-specifi ### Recommended next -1. **VM bugs found while building the scheduler, not yet fixed.** All of them - are in the native build too. (Fixed since: syntax errors crashing the VM, - #511; the retain-stack growth in loops and coroutines, see - [../stackless/Debug_Loop_Leak.md](../stackless/Debug_Loop_Leak.md).) - - **Backtraces** say "nothing on stack" for most errors. - - **`make` doesn't track header dependencies**, and `make` alone doesn't - regenerate `IoVMInit.c`. After changing a `.h` or a core `.io` file: - `rm -rf build/obj build/obj-p2 && make regenerate && make`. +1. **VM bugs found while building the scheduler: all fixed.** Syntax errors + crashing the VM (#511); the retain-stack growth in loops and coroutines + ([../stackless/Debug_Loop_Leak.md](../stackless/Debug_Loop_Leak.md), #513); + `make` not tracking header dependencies (#515); and backtraces saying + "nothing on stack". An exception now records its trace from the frame + chain when it is raised (`Exception stackTrace`, `stackTraceLines`; + `IoState_recordStackTraceOn_`). Known limit: a tail call reuses its + caller's frame, so the caller of a method's last call has no entry. 2. **The Io-side handle table is fixed at 1024 entries** (`IO_HANDLES_MAX`, `browser/io_js_bridge.c`): Io objects JS holds, plus Promises not yet settled. When it is full a new Promise is rejected with diff --git a/browser/test/vm.test.mjs b/browser/test/vm.test.mjs index 585a6e9e0..533f80cd2 100644 --- a/browser/test/vm.test.mjs +++ b/browser/test/vm.test.mjs @@ -32,6 +32,14 @@ test("a syntax error gives status 1 and the VM carries on", async () => { assert.equal((await io.eval("list(1, 2, 3) map(x, x * x) sum")).output, "==> 14\n"); }); +test("an uncaught error prints the calls that led to it", async () => { + const src = "btInner := method(r := 1 + nil; r)\nbtOuter := method(r := btInner; r)\nbtOuter"; + const { status, output } = await io.eval(src); + assert.equal(status, 1); + assert.match(output, /Number \+ .* 1\n\s+Object btInner .* 2\n\s+Object btOuter .* 3\n/); + assert.doesNotMatch(output, /nothing on stack|hostEval/); +}); + test("state persists between evals", async () => { await io.eval("counter := 41"); assert.equal((await io.eval("counter + 1")).output, "==> 42\n"); diff --git a/docs/Guide/_index.md b/docs/Guide/_index.md index b29a2fd26..443801fec 100644 --- a/docs/Guide/_index.md +++ b/docs/Guide/_index.md @@ -1051,6 +1051,24 @@ e catch(Exception, The first argument to catch indicates which types of exceptions will be caught. catch() returns the exception if it doesn't match and nil if it does. +An exception records where it was raised. `showStack` prints the error and the calls that led to it, innermost first, and `stackTraceLines` returns the same lines as a list: + +``` +Account := Object clone +Account withdraw := method(n, r := balance - n; r) +e := try(Account withdraw(10)) +e showStack +``` + +``` + Exception: Account does not respond to 'balance' + --------- + Account balance bank.io 2 + Account withdraw bank.io 3 +``` + +Each line names the target's type and the message, then the file and line the message was sent from. When a method's last expression is a call, that call takes over the method's frame (a tail call), so the method itself does not appear in the trace. + diff --git a/docs/Guide/index.html b/docs/Guide/index.html index cdd23d842..8cf5a9aa2 100644 --- a/docs/Guide/index.html +++ b/docs/Guide/index.html @@ -168,7 +168,13 @@ e catch(Exception, writeln(e coroutine backTraceString) -)

The first argument to catch indicates which types of exceptions will be caught. catch() returns the exception if it doesn't match and nil if it does.

Pass

To re-raise an exception caught by try(), use the pass method. This is useful to pass the exception up to the next outer exception handler, usually after all catches failed to match the type of the current exception:

e := try(
+)

The first argument to catch indicates which types of exceptions will be caught. catch() returns the exception if it doesn't match and nil if it does.

An exception records where it was raised. showStack prints the error and the calls that led to it, innermost first, and stackTraceLines returns the same lines as a list:

Account := Object clone
+Account withdraw := method(n, r := balance - n; r)
+e := try(Account withdraw(10))
+e showStack
  Exception: Account does not respond to 'balance'
+  ---------
+  Account balance                      bank.io 2
+  Account withdraw                     bank.io 3

Each line names the target's type and the message, then the file and line the message was sent from. When a method's last expression is a call, that call takes over the method's frame (a tail call), so the method itself does not appear in the trace.

Pass

To re-raise an exception caught by try(), use the pass method. This is useful to pass the exception up to the next outer exception handler, usually after all catches failed to match the type of the current exception:

e := try(
     // ...
 )
 
@@ -371,6 +377,6 @@
 digit ::= "0" ... "9"
 digits ::= { digit }

The uppercase words above designate elements the lexer treats as tokens.

Credits

Io is the product of all the talented folks who taken the time and interest to make a contribution. The complete list of contributors is difficult to keep track of, but some of the recent major contributors include; Jonathan Wright, Jeremy Tregunna, Mike Austin, Chris Double, Rich Collins, Oliver Ansaldi, James Burgess, Baptist Heyman, Ken Kerahone, Christian Thater, Brian Mitchell, Zachary Bir and many more. The mailing list archives, repo inventory and release history are probably the best sources for a more complete record of individual contributions.

References

1

Goldberg, A et al.

Smalltalk-80: The Language and Its Implementation

Addison-Wesley, 1983

2

Ungar, D and Smith,

RB. Self: The Power of Simplicity

OOPSLA, 1987

3

Smith, W.

Class-based NewtonScript Programming

PIE Developers magazine, Jan 1994

4

Lieberman

H. Concurrent Object-Oriented Programming in Act 1

MIT AI Lab, 1987

5

McCarthy, J et al.

LISP I programmer's manual

MIT Press, 1960

6

Ierusalimschy, R, et al.

Lua: an extensible extension language

John Wiley & Sons, 1996

License

Copyright 2006-2010 Steve Dekorte. All rights reserved.

Redistribution and use of this document with or without modification, are permitted provided that the copies reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

This documentation is provided "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the authors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this documentation, even if advised of the possibility of such damage.

- + diff --git a/docs/index.html b/docs/index.html index f9edd82f9..e1ba45aea 100644 --- a/docs/index.html +++ b/docs/index.html @@ -13,6 +13,6 @@ - + diff --git a/index.html b/index.html index d9af493c0..a8a1e0010 100644 --- a/index.html +++ b/index.html @@ -23,8 +23,8 @@ -
Io

A small, prototype-based programming language — now targeting WASM/WASI.

About

Io is a dynamic, prototype-based language built on a few simple ideas taken from Smalltalk (all values are objects), Self (prototypes, not classes), NewtonScript (differential inheritance), Act1 (actors and futures for concurrency), Lisp (code is a runtime-inspectable message tree), and Lua (small and embeddable).

Its guiding design principle is simplicity and power through conceptual unification — a handful of primitives stand in for features most languages keep separate:

conceptunifies
scopable blocksfunctions, methods, closures
prototypesobjects, classes, namespaces, locals
messagesoperators, calls, assigns, var access

The VM is written in portable C and now targets WebAssembly (WASI) by default. The same binary runs under wasmtime, Node.js, or directly in the browser via a bidirectional Io↔JavaScript bridge.

Key Features

  • Minimal Syntax — Expressions only. No keywords, no statements, no special forms. Every expression is a message send, including assignment, operators, and control flow.
  • Prototype-Based Objects — No classes. New objects are clones of existing ones, slots are created on write, and any object can be used as a prototype for any other.
  • Differential Inheritance — Clones inherit by reference until a slot is assigned, so most objects carry only the deltas that distinguish them from their parents.
  • Multiple Inheritance — Every object has a list of protos; lookup is depth-first with runtime loop detection.
  • Messages as Code — Messages form trees that can be inspected and rewritten at runtime. Argument evaluation can be deferred, so if, while, and for are implementable in Io itself.
  • Runtime Introspection — Slots, protos, message trees, and block source code are all inspectable and modifiable at runtime.
  • Actors and Futures — Any object can receive asyncSend or futureSend messages and run its own coroutine. Futures are transparent (they become their result) and detect deadlocks automatically.
  • Coroutines Everywhere — Concurrency uses cooperative user-level coroutines rather than OS threads, scaling to thousands of active tasks without thread-level overhead.
  • First-Class Continuations — the VM is callcc-capable: the current computation can be captured as a first-class value and later resumed, stored, or serialized.
  • Unified Sequences — Strings, buffers, and numeric vectors share one Sequence primitive, with multiple item types, text encodings, and SIMD acceleration on float vectors.
  • WASM/WASI Target — The default build produces a single WebAssembly module that runs under wasmtime, Node.js, or in browsers, with full access to the DOM when hosted in a page.
  • Io↔JS Bridge — Host integration on the browser target is bidirectional: Io can call JavaScript functions and JavaScript can call Io methods, replacing the native-addon model of earlier Io releases.
  • Embeddable Core — The VM ships as a single WebAssembly module under a BSD license, embeddable in any WASM host — browsers, Node.js, or native apps via wasmtime or wasmer.
+
Io

A small, prototype-based programming language — now targeting WASM/WASI.

About

Io is a dynamic, prototype-based language built on a few simple ideas taken from Smalltalk (all values are objects), Self (prototypes, not classes), NewtonScript (differential inheritance), Act1 (actors and futures for concurrency), Lisp (code is a runtime-inspectable message tree), and Lua (small and embeddable).

Its guiding design principle is simplicity and power through conceptual unification — a handful of primitives stand in for features most languages keep separate:

conceptunifies
scopable blocksfunctions, methods, closures
prototypesobjects, classes, namespaces, locals
messagesoperators, calls, assigns, var access

The VM is written in portable C and now targets WebAssembly (WASI) by default. The same binary runs under wasmtime, Node.js, or directly in the browser via a bidirectional Io↔JavaScript bridge.

Key Features

  • Minimal Syntax — Expressions only. No keywords, no statements, no special forms. Every expression is a message send, including assignment, operators, and control flow.
  • Prototype-Based Objects — No classes. New objects are clones of existing ones, slots are created on write, and any object can be used as a prototype for any other.
  • Differential Inheritance — Clones inherit by reference until a slot is assigned, so most objects carry only the deltas that distinguish them from their parents.
  • Multiple Inheritance — Every object has a list of protos; lookup is depth-first with runtime loop detection.
  • Messages as Code — Messages form trees that can be inspected and rewritten at runtime. Argument evaluation can be deferred, so if, while, and for are implementable in Io itself.
  • Runtime Introspection — Slots, protos, message trees, and block source code are all inspectable and modifiable at runtime.
  • Actors and Futures — Any object can receive asyncSend or futureSend messages and run its own coroutine. Futures are transparent (they become their result) and detect deadlocks automatically.
  • Coroutines Everywhere — Concurrency uses cooperative user-level coroutines rather than OS threads, scaling to thousands of active tasks without thread-level overhead.
  • First-Class Continuations — the VM is callcc-capable: the current computation can be captured as a first-class value and later resumed, stored, or serialized.
  • Unified Sequences — Strings, buffers, and numeric vectors share one Sequence primitive, with multiple item types, text encodings, and SIMD acceleration on float vectors.
  • WASM/WASI Target — The default build produces a single WebAssembly module that runs under wasmtime, Node.js, or in browsers, with full access to the DOM when hosted in a page.
  • Io↔JS Bridge — Host integration on the browser target is bidirectional: Io can call JavaScript functions and JavaScript can call Io methods, replacing the native-addon model of earlier Io releases.
  • Embeddable Core — The VM ships as a single WebAssembly module under a BSD license, embeddable in any WASM host — browsers, Node.js, or native apps via wasmtime or wasmer.
- + diff --git a/libs/iovm/io/Exception.io b/libs/iovm/io/Exception.io index 22247becc..8791f820d 100644 --- a/libs/iovm/io/Exception.io +++ b/libs/iovm/io/Exception.io @@ -323,25 +323,10 @@ Coroutine do( if(exception, buf appendSeq("\n ", exception type, ": ", exception error, "\n")) //writeln("backTraceString 2\n") - if(callStack size > 0) then( + traceLines := if(exception, exception stackTraceLines, list()) + if(traceLines size > 0) then( buf appendSeq(" ---------\n") - - if(exception and exception ?caughtMessage, - buf appendSeq(" ", exception caughtMessage description, "\n") - ) - - frames := callStack - - if(exception and exception originalCall, - index := frames indexOf(exception originalCall) - if(index, - frames sliceInPlace(index) - ) - ) - - frames foreach(v, - buf appendSeq(" ", v description, "\n") - ) + traceLines foreach(line, buf appendSeq(" ", line, "\n")) buf appendSeq("\n") ) else( buf appendSeq(" ---------\n") @@ -595,6 +580,54 @@ MyErrorType := Error clone newSlot("originalCall") //doc Exception originalCall Returns the call object associated with the exception. + newSlot("stackTrace") + /*doc Exception stackTrace + Where the exception was raised, recorded by the VM when it is raised: a + flat List with two items per entry, innermost first, the Message being + evaluated and the type name of its target. nil if never raised. See + stackTraceLines for a readable form. + */ + + stackTraceIgnoredNames := list("raiseException", "rawSignalException") + //doc Exception stackTraceIgnoredNames Names of the VM's own raising steps, left out of the top of stackTraceLines. + + stackTraceLines := method( + /*doc Exception stackTraceLines + Returns the stack trace as a List of strings, innermost call first, + each "TargetType messageName file line". The VM's own raising + steps and the command line's frames are left out. A + method that was the last call in its caller replaces it (a tail + call), so such callers do not appear. + */ + lines := list() + trace := self stackTrace + if(trace isNil, return lines) + atTop := true + first := nil + i := 0 + while(i < trace size, + m := trace at(i) + typeName := trace at(i + 1) + i = i + 2 + if(atTop and stackTraceIgnoredNames contains(m name), continue) + atTop = false + file := m label lastPathComponent + // The host's own frames: the command line, or the browser's eval + if(file == "CLI.io" or m label == "IoState_runCLI()", break) + if(m name == "hostEval" and typeName == "Scheduler", break) + lines append((typeName .. " " .. m name) alignLeft(36) .. " " .. file .. " " .. m lineNumber) + if(first isNil, first = m) + ) + // The message that failed is missing from the frames when a tail + // call replaced its frame (a forward method raising) or when the + // error came from C. originalCall and caughtMessage still have it. + failed := if(originalCall, originalCall message, caughtMessage) + if(failed and failed != first, + lines prepend(if(originalCall, originalCall description, failed description)) + ) + lines + ) + raise := method(error, nestedException, //doc Exception raise(error, optionalNestedException) Raise an exception with the specified error message. coro := Scheduler currentCoroutine diff --git a/libs/iovm/source/IoCoroutine.c b/libs/iovm/source/IoCoroutine.c index b82050098..28283d3be 100644 --- a/libs/iovm/source/IoCoroutine.c +++ b/libs/iovm/source/IoCoroutine.c @@ -638,7 +638,11 @@ IO_METHOD(IoCoroutine, rawSignalException) { IoState *state = IOSTATE; // The exception is already set on this coroutine (by raiseException). - // Signal the eval loop to unwind frames. + // Record where it was raised, then signal the eval loop to unwind frames. + { + IoObject *e = IoCoroutine_rawException(self); + if (e && !ISNIL(e)) IoState_recordStackTraceOn_(state, e); + } state->errorRaised = 1; return self; } diff --git a/libs/iovm/source/IoState_exceptions.c b/libs/iovm/source/IoState_exceptions.c index 5f41c6539..cf4862bde 100644 --- a/libs/iovm/source/IoState_exceptions.c +++ b/libs/iovm/source/IoState_exceptions.c @@ -18,6 +18,7 @@ bootstrap failures where no Io-visible error path exists yet. #include "IoCoroutine.h" #include "IoSeq.h" #include "IoEvalFrame.h" +#include "IoList.h" #include //#define IOSTATE_SHOW_ERRORS 1 @@ -36,6 +37,58 @@ void IoState_fatalError_(IoState *self, char *error) { exit(-1); } +// Longest stack trace recorded on an exception, in entries. +#define IO_STACK_TRACE_MAX 64 + +/*cdoc State IoState_recordStackTraceOn_(self, exception) +Records where an exception was raised, as a List in its stackTrace slot. +The eval loop unwinds the frames before anything can print them, so the +trace has to be taken here, while the frame chain is intact. + +The list is flat, two items per entry, innermost first: the message being +evaluated and the type name of its target. The entries are the frame that +raised, then each frame waiting on a method or block it called. A frame +reused by a tail call has only its latest call, so tail calls leave no +entry for their caller. An exception that already has a trace keeps it, +so re-raising with pass still shows where it first came from. +*/ +void IoState_recordStackTraceOn_(IoState *self, IoObject *exception) { + IoSymbol *slotName = IoState_symbolWithCString_(self, "stackTrace"); + IoSymbol *typeSlot = self->typeSymbol; + IoObject *existing; + IoList *trace; + IoEvalFrame *frame = self->currentFrame; + int isTop = 1; + int count = 0; + + if (!exception) return; + existing = IoObject_rawGetSlot_(exception, slotName); + if (existing && ISLIST(existing)) return; + + trace = IoList_new(self); + IoObject_setSlot_to_(exception, slotName, trace); + + while (frame && count < IO_STACK_TRACE_MAX) { + IoEvalFrameData *fd = FRAME_DATA(frame); + if (fd->message && (isTop || fd->state == FRAME_STATE_ACTIVATE)) { + // The target's type slot when it is a string (no new + // symbol needed), else its tag name, as IoObject_name does. + IoObject *typeName = + fd->target ? IoObject_rawGetSlot_(fd->target, typeSlot) : NULL; + if (!typeName || !ISSEQ(typeName)) { + typeName = IoState_symbolWithCString_( + self, fd->target ? IoTag_name(IoObject_tag(fd->target)) + : "?"); + } + IoList_rawAppend_(trace, fd->message); + IoList_rawAppend_(trace, typeName); + count++; + } + isTop = 0; + frame = fd->parent; + } +} + /*cdoc State IoState_error_(self, m, format, ...) Raises an Io-level exception without longjmp. Formats the description with printf-style vargs, clones the current coroutine's Exception proto, @@ -113,6 +166,7 @@ void IoState_error_(IoState *self, IoMessage *m, const char *format, ...) { IoObject_setSlot_to_(e, IoState_symbolWithCString_(self, "coroutine"), coroutine); IoCoroutine_rawSetException_(coroutine, e); + IoState_recordStackTraceOn_(self, e); } } diff --git a/libs/iovm/source/IoState_exceptions.h b/libs/iovm/source/IoState_exceptions.h index 0800e6388..9b484ef67 100644 --- a/libs/iovm/source/IoState_exceptions.h +++ b/libs/iovm/source/IoState_exceptions.h @@ -6,5 +6,6 @@ IOVM_API void IoState_fatalError_(IoState *self, char *error); +IOVM_API void IoState_recordStackTraceOn_(IoState *self, IoObject *exception); IOVM_API void IoState_error_(IoState *self, IoMessage *m, const char *format, ...); diff --git a/libs/iovm/tests/correctness/BacktraceTest.io b/libs/iovm/tests/correctness/BacktraceTest.io new file mode 100644 index 000000000..c0b2b33d9 --- /dev/null +++ b/libs/iovm/tests/correctness/BacktraceTest.io @@ -0,0 +1,87 @@ +BacktraceTest := UnitTest clone do( + // An exception records where it was raised (Exception stackTrace), taken + // from the frame chain when it is raised. Backtraces used to be built from + // Call objects on the retain stack, which the stackless evaluator no + // longer leaves there, so nearly every error printed "nothing on stack". + // + // Each helper ends with a plain value so its call is not a tail call: a + // tail call reuses its caller's frame, and the caller then has no entry. + + Thing := Object clone do( + type := "Thing" + outer := method(x, r := self inner(x); r) + inner := method(x, r := x + nil; r) + raiser := method(Exception raise("boom"); nil) + missing := method(r := 1 noSuchMethod; r) + looper := method(list(1, 2) foreach(v, if(v == 2, self inner(v))); nil) + ) + + // "Type name" of each trace line, without the file and line columns + calls := method(e, + e stackTraceLines map(line, line exSlice(0, 36) asMutable strip) + ) + + testErrorFromCShowsCallChain := method( + e := try(Thing outer(1)) + assertEquals(list("Number +", "Thing inner", "Thing outer"), calls(e) slice(0, 3)) + ) + + testRaiseShowsCallChain := method( + e := try(Thing raiser) + assertEquals(list("Exception raise", "Thing raiser"), calls(e) slice(0, 2)) + ) + + testMissingMethodShowsFailedMessage := method( + e := try(Thing missing) + assertEquals(list("Number noSuchMethod", "Thing missing"), calls(e) slice(0, 2)) + ) + + testCallsInsideLoopsAndBranches := method( + e := try(Thing looper) + assertEquals(list("Number +", "Thing inner", "Thing looper"), calls(e) slice(0, 3)) + ) + + testLinesNameFileAndLine := method( + e := try(Thing outer(1)) + // each line gives where that message was sent from + assertTrue(e stackTraceLines at(0) containsSeq("BacktraceTest.io 13")) + assertTrue(e stackTraceLines at(1) containsSeq("BacktraceTest.io 12")) + ) + + testPassKeepsTheOriginalTrace := method( + e := try(Thing outer(1)) + e2 := try(e pass) + assertTrue(e == e2) + assertEquals(list("Number +", "Thing inner", "Thing outer"), calls(e2) slice(0, 3)) + ) + + testBackTraceStringIncludesTheTrace := method( + e := try(Thing outer(1)) + s := e coroutine backTraceString + assertTrue(s containsSeq("Thing inner")) + assertFalse(s containsSeq("nothing on stack")) + ) + + testCoroutineErrorHasItsOwnTrace := method( + o := Object clone + o caught := nil + o handleActorException := method(e, self caught = e) + o thing := Thing + o work := method(r := thing outer(1); r) + o @@work + 5 repeat(yield) + assertTrue(o caught != nil) + assertEquals(list("Number +", "Thing inner", "Thing outer"), calls(o caught) slice(0, 3)) + ) + + testNeverRaisedHasNoTrace := method( + assertEquals(list(), Exception clone stackTraceLines) + ) + + testDeepRecursionIsCapped := method( + down := method(n, r := if(n == 0, 1 + nil, down(n - 1)); r) + e := try(down(500)) + assertTrue(e stackTrace size <= 128) + assertEquals("Number +", calls(e) first) + ) +) diff --git a/llms-full.txt b/llms-full.txt index 42ddcc117..5399ec096 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -1,6 +1,6 @@ # Io — Full Documentation -Site build: Io · 2026-11-16 · 6db971fd +Site build: Io · 2026-11-17 · 257b352a Io is a dynamic, prototype-based language built on a few simple ideas taken from Smalltalk (all values are objects), Self (prototypes, not classes), NewtonScript (differential inheritance), Act1 (actors and futures for concurrency), Lisp (code is a runtime-inspectable message tree), and Lua (small and embeddable). @@ -3020,6 +3020,24 @@ e catch(Exception, The first argument to catch indicates which types of exceptions will be caught. catch() returns the exception if it doesn't match and nil if it does. +An exception records where it was raised. `showStack` prints the error and the calls that led to it, innermost first, and `stackTraceLines` returns the same lines as a list: + +``` +Account := Object clone +Account withdraw := method(n, r := balance - n; r) +e := try(Account withdraw(10)) +e showStack +``` + +``` + Exception: Account does not respond to 'balance' + --------- + Account balance bank.io 2 + Account withdraw bank.io 3 +``` + +Each line names the target's type and the message, then the file and line the message was sent from. When a method's last expression is a call, that call takes over the method's frame (a tail call), so the method itself does not appear in the trace. + @@ -7044,6 +7062,13 @@ Notable changes in Io over the past twelve months. Io uses date-based versioning. This page collects the notable changes of the last twelve months — a period in which the VM was rewritten around a stackless evaluator and re-targeted from native binaries to WebAssembly. Entries marked *tagged* correspond to release tags in the [repository](https://github.com/IoLanguage/io); the rest are development milestones on the road between them. For the longer arc, see the [Timeline](../Timeline/index.html). +## Unreleased + +On `master`, not yet tagged. + +- **Backtraces are back** — an uncaught error prints the calls that led to it, with file and line, instead of “nothing on stack”. An exception records its trace when it is raised: `Exception stackTraceLines` returns it as a list, and `pass` keeps the original. +- **Build** — `make` rebuilds the objects that include a changed header; a clean build is no longer needed after editing one ([#515](https://github.com/IoLanguage/io/pull/515)). + ## 2026.11.18 — Long-running programs stop growing *Tagged `2026.11.18`.* A memory fix for programs that never return to the top level: servers, actors, and long-lived coroutines. diff --git a/llms.txt b/llms.txt index 04fdc7e7b..fb4bfacc5 100644 --- a/llms.txt +++ b/llms.txt @@ -2,7 +2,7 @@ > A small, prototype-based programming language — now targeting WASM/WASI. -Site build: Io · 2026-11-16 · 6db971fd +Site build: Io · 2026-11-17 · 257b352a ## Documentation