Nimala Raku DAP
=begin rakudoc :kind<Language> :subkind<Tooling> :category<debugging>
<p align="center"> <img src="https://gitlab.com/nimala/raku/raku-lsp/-/raw/main/Raku-LSP-192.jpeg" alt="Nimala Logo" width="128" /> </p>
Overview
Nimala ships a Debug Adapter Protocol (DAP) server for Raku, written in pure Raku.
It lets any DAP-capable editor (VS Code, Neovim with nvim-dap, Emacs with dap-mode,
JetBrains IDEs, ā¦) launch a Raku program, stop at breakpoints, step through code, inspect
variables, and evaluate expressions.
The adapter is a separate executable, nimala-raku-dap. It sits between the editor and the
debugged program (the debuggee):
Editor / DAP client
ā DAP: JSON over stdin/stdout, Content-Length framing
ā¼
nimala-raku-dap (Nimala::Raku-DAP)
ā MoarVM Remote Debugging Protocol: MessagePack over loopback TCP
ā¼
raku --debug-port=<port> --debug-suspend <program> [args]
The debuggee runs on the native MoarVM remote debugger. It executes the normal, precompiled bytecode of your program and its modules, so there is no special debug build, no separate precompilation store, and no slow first launch.
This document has two parts:
Part I explains how to use the debugger.
Part II gives developers a high-level map of the implementation.
For protocol details and the history behind design decisions see docs/debug.md,
docs/DEBUG-MOARVM.md, and docs/moarvm-upstream-question.md.
Part I: Using the debugger
Requirements
A Rakudo on MoarVM with remote debugging support (
raku --debug-portmust exist). Development and verification use Rakudo/MoarVM 2026.09. Under Rakudo 2024.07 the adapter can abort at random withMoarVM panic: Internal error: zeroed target thread ID in work pass, and the thread list shows extra runtime threads.The Nimala distribution, installed with
zef install .or used from a source checkout.A DAP client. The bundled VS Code extension (
editors/vscode/) is the reference client.
Starting from VS Code
The extension registers a debugger of type raku.
Zero-config launch
Open a Raku file and press F5 without a launch.json. The extension builds a
configuration that launches the active file. Attributes missing from any raku configuration are filled from the
settings below; includePaths defaults to lib plus raku.includePaths.
launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "raku",
"request": "launch",
"name": "Launch Raku Program",
"program": "${file}",
"cwd": "${workspaceFolder}",
"args": [],
"includePaths": ["lib"],
"env": { "MY_VAR": "value" },
"stopOnEntry": false,
"smartStepMode": "into"
}
]
}
Extension settings
| Setting | Default | Meaning |
|---|---|---|
| raku.executablePath | raku | Default debuggee executable; also runs the adapter when it is a .raku script |
| raku.includePaths | [] | Extra -I paths; the default includePaths is lib plus these |
| raku.dap.serverPath | (empty) | Path to nimala-raku-dap; derived from raku.lsp.serverPath or PATH when empty |
| raku.dap.debugPort | 0 | Default debug port; 0 picks a free port |
| raku.dap.smartStepMode | into | Default smart stepping mode (into, over, disable) |
Starting from other clients
The adapter speaks DAP on stdin/stdout. Configure your client to run:
nimala-raku-dap # installed via zef
raku -Ilib bin/nimala-raku-dap # from a source checkout
A minimal session is:
initialize ā launch ā setBreakpoints / setFunctionBreakpoints /
setExceptionBreakpoints ā configurationDone ā (wait for "stopped") ā ā¦
The adapter answers initialize with its capabilities and immediately sends the
initialized event. The debuggee is held suspended until configurationDone arrives, so
breakpoints sent in between are already active when the first line runs.
A complete client used by the test suite lives in t/Nimala/Raku-DAP/TestClient.rakumod.
Launch configuration
Only request: "launch" is supported. attach is answered with an error because MoarVM
cannot be attached to a process that was not started with --debug-port.
| Attribute | Type | Default | Description |
|---|---|---|
| program | string | required | Script to debug; absolute or relative to cwd |
| args | array | [] | Command-line arguments for the program |
| cwd | string | see below | Working directory of the debuggee |
| executable | string | raku | Raku executable (aliases: rakuPath, executablePath) |
| includePaths | array | [] | Extra module search paths, passed as -I |
| env | object | {} | Extra environment variables for the debuggee; null removes one |
| stopOnEntry | boolean | false | Stop at the first executable line of program |
| debugPort | integer | automatic | Fixed MoarVM debug port (alias: port) |
| smartStepMode | string | into | into, over, or disable (see Smart stepping) |
| console | string | internalConsole | internalConsole, integratedTerminal, or externalTerminal |
| noDebug | boolean | false | Run the program without the debugger |
| trace | boolean | false | Write a protocol trace log (see Troubleshooting) |
With integratedTerminal or externalTerminal, the client starts the debuggee through the DAP
runInTerminal request; when the client does not support it, the adapter falls back to internalConsole.
If cwd is omitted, the adapter walks up from the program's directory to the nearest
directory containing META6.json or .git, and falls back to the program's directory.
The program path, the working directory, and an explicit debugPort are validated before
launch; failures are reported as an error response to launch.
The debuggee always receives RAKUDO_LINE_BUFFERED=1, so its output appears in the debug
console promptly.
Features
Line breakpoints
Set breakpoints in the editor gutter. Breakpoints on lines that cannot stop (blank lines, comments, lone braces) are moved to the next executable statement; the response reports the adjusted line. Breakpoints beyond the end of the file are reported as unverified.
Breakpoints can be added and removed while the program runs.
Conditional breakpoints
A condition is a bounded expression. The program only stops when the condition is true. A condition that does not parse marks the breakpoint as unverified and the parse error is shown in the editor.
$count > 10
%config<mode> eq 'debug'
$user.name ne ''
Hit-count conditions
The hit condition counts how often a breakpoint was reached and stops only when the count matches:
| Hit condition | Stops when the hit count ⦠|
|---|---|
| 5 or == 5 | equals 5 |
| > 5 | is greater than 5 |
| >= 5 | is at least 5 |
| < 5 | is less than 5 |
| <= 5 | is at most 5 |
| % 5 | is a multiple of 5 |
Logpoints
A logpoint prints a message instead of stopping. Expressions in curly braces are evaluated
and interpolated; anything that cannot be evaluated is shown as <not evaluatable> .
Processing item {$i} of {@items.elems}: {$item.name}
Each hit can run only one rendering helper (.gist, .Str, .raku, .elems); see the
limitation under Expressions.
Function breakpoints
Enter a routine name (for example process-order) in the editor's function breakpoint
panel. The adapter looks the name up in the workspace symbol index and sets a line breakpoint
at every matching routine inside the workspace. Conditions and hit conditions work as for line
breakpoints. Routines that exist only outside the workspace are reported as unverified.
Exception breakpoints
Two filters are offered:
| Filter | Default | Behaviour |
|---|---|---|
| Uncaught Exceptions | on | Stop when an exception is about to terminate the program |
| All Exceptions | off | Stop whenever an exception is thrown, even if caught |
Both filters accept a condition (a bounded expression).
When stopped on an exception, the editor shows the exception type, message, and backtrace
(DAP exceptionInfo). Exception breakpoints rely on the injected helper module; see
The injected helper.
Stepping
Continue resumes until the next breakpoint, exception, or program end.
Step Over (
next) runs to the next statement of the current routine. Called routines run at full speed unless they contain a user breakpoint.Step Into (
stepIn) enters the routine called on the current line, including routines in other files and modules.Step Out (
stepOut) runs until the current routine returns to its caller.Pause suspends a running program.
User breakpoints always win: if one is hit while a step is in progress, the program stops
there with reason breakpoint.
Smart stepping
Rakudo implements much of the language in Raku and NQP. Stepping naively would land in
compiler, runtime, and dispatcher code. smartStepMode controls what happens:
| Mode | Behaviour |
|---|---|
| into | Step into user code; skip Rakudo, MoarVM, and NQP internals (default) |
| over | Step over internal calls and return to user code |
| disable | No filtering; stop wherever MoarVM stops |
Skipping is bounded. If user code is not reached within 500 internal steps, the adapter stops
and reports where it is. Breakpoints, exceptions, and pause requests are never filtered.
smartStepMode applies only to native stepping, that is when the MoarVM build has no line drift; with drift,
sweep stepping is used instead (see Stepping engine).
Threads and call stacks
Threads that can run your code are listed; MoarVM runtime threads (debug server, spesh, async I/O, supervisor) and idle thread-pool workers are hidden. Each stop shows the full call stack with file, line, and routine name. Frames from Rakudo internals are recognised so the editor can focus on your code.
Variables
Each stack frame has a Locals scope with the lexical variables of that frame.
Compiler-generated lexicals are hidden.
Variables removed by the optimizer are shown as
<optimized out>.Objects, arrays, and hashes are expanded lazily: attributes, positional elements, and associative entries are fetched only when you open them.
Changing variable values (setVariable) is not supported.
Expressions
The debug console, hover evaluation, breakpoint conditions, and logpoints share a deliberately small expression language. It reads program state but never changes it.
| Form | Example |
|---|---|
| Variable (any sigil/twigil) | $x @list %h $!attr $*DYNAMIC |
| Attribute access | $obj.name $obj.inner.value |
| Hash subscript | %h<key> %h{'key'} %h{$k} |
| Array index | @a[0] @a[-1] |
| Type | $x.WHAT |
| Rendering helpers | $x.gist $x.Str $x.raku @a.elems |
| Comparison with a literal | $n >= 3 $s eq 'abc' $o == Nil |
Supported comparison operators: == != < <= > = eq ne lt le gt ge>. A comparison with Nil tests
definedness: $o == Nil is true when $o is undefined. === (value identity) and =:= (container identity)
are refused: the adapter only sees copies of the debuggee's values, so the result would be meaningless.
Literals: integers, decimals, numbers with exponent, single- or double-quoted strings,
True, False, Nil.
Arbitrary method calls, subroutine calls, and assignments are rejected. This is intentional: calling arbitrary code inside a suspended VM can deadlock or crash it.
Limitation: MoarVM allows at most one code invocation per stop. The rendering helpers
(.gist, .Str, .raku, .elems) need such an invocation, so only one distinct
helper expression can be evaluated per stop; repeating the same expression reuses the cached
result. Step or continue to evaluate another one. Plain variable, attribute, and subscript
access are not limited. Hover and watch expressions never run a helper.
Troubleshooting
Tracing
Set "trace": true in the launch configuration or export NIMALA_DAP_TRACE=1 before the
adapter starts. The adapter then writes all DAP and MoarVM traffic to
$TMPDIR/nimala-dap-trace-<pid>.log (mode 0600).
Common problems
Breakpoint shown as unverified: The line is not executable, the file has fewer lines, or the condition does not parse. Hover over the breakpoint to see the reason.
Exception breakpoints do nothing, values show without
.gist: The injected helper could not be found. Check that the distribution is installed completely and that$XDG_CACHE_HOME(default~/.cache) is writable."Port ⦠is already in use": Remove
debugPortto let the adapter pick a free port."MoarVM supports at most one evaluation per stop": See the limitation in Expressions.
Security note
MoarVM's debug server listens on an unauthenticated TCP port on 127.0.0.1. Any local
process that connects first gains full control of the debuggee. The adapter reduces the window
by choosing a random port right before launch, connecting within milliseconds, and killing
the debuggee if the handshake fails. Do not debug on shared multi-user machines where other
local users are untrusted. A complete fix requires changes in MoarVM (see
docs/moarvm-upstream-question.md).
Part II: Architecture
Design goals
Pure Raku. No native extensions; the MessagePack codec and DAP framing are part of Nimala.
Out of process. The adapter never runs inside the debuggee. A crash in one side does not take down the other.
Native VM debugging. Breakpoints and stepping are implemented by MoarVM, so precompiled modules are debuggable and run at normal speed.
Safe inspection. Reading state must never hang or mutate the debuggee.
Asynchronous. DAP requests, MoarVM notifications, and debuggee output are handled concurrently with
Promise,Supply, andProc::Async.
Module map
Nimala::Raku-DAP Entry point (run-dap-server); stdin loop, JSON dispatch, tracing
āāā Framing Content-Length framing for DAP over stdio
āāā Trace Opt-in trace log; attempt() for tolerated failures
āāā Session Session actor: initialize, launch, restart, terminate,
ā ā configurationDone, disconnect, process lifecycle
ā āāā LaunchConfig Launch argument parsing and validation, debuggee command line
ā āāā Launcher Starts the debuggee (owned or runInTerminal) and connects
ā āāā DebuggeeProcess Debuggee process start, exit, and termination
ā āāā BreakpointRequests set*Breakpoints and breakpointLocations requests
ā āāā BreakpointRegistry Line, function, exception, and entry breakpoints; hit counts
ā āāā SourceLines Path resolution, cached source lines, breakpoint line adjustment
ā āāā ClientCoordinates Client line/column base and path/URI conversion
ā āāā SymbolScanner Lightweight routine index for function breakpoints
āāā Translate Facade: DAP request ā MoarVM commands
ā āāā FrameClassifier User vs. internal frames, executable lines, routine ranges
ā āāā Stepping Sweep stepping, step-in, step-out, smart stepping
ā āāā StopHandler Stop events: breakpoint matching, conditions,
ā ā hit counts, logpoints, exception stops
ā āāā Inspector Handles scopes, variables, and evaluate requests
ā āāā ValueRenderer Variable rendering and lazy object expansion
ā āāā Evaluator Evaluates bounded expressions in a frame
ā āāā ExceptionState Exception recording and exceptionInfo
āāā Remote Per-stop cached MoarVM reads; the only helper invocation path
āāā ThreadState Per-thread stop state and active step context
āāā Protocol MoarVM remote protocol client (TCP, greeting, requests/events)
āāā MessagePack Pure-Raku MessagePack encoder/decoder
āāā Handles Frame/variable reference registry, released on resume
āāā Expression Grammar, refusal checks, and literal comparison for bounded expressions
āāā MoarVMProbe Detects the MoarVM line-drift bug; caches the result
resources/injected-helper/Nimala/Raku-DAP/InjectedHelper.rakumod
Loaded into the debuggee: safe rendering, exception hooks
Request flow
stdin āāāŗ Framing āāāŗ Nimala::Raku-DAP dispatch
ā
āā lifecycle & breakpoints āāāŗ Session
āā runtime requests āāāāāāāāāāŗ Translate āāŗ Stepping / Inspector / ā¦
ā
ā¼
Protocol āāāŗ MoarVM (TCP)
ā
MoarVM notifications āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
āāāŗ StopHandler āāāŗ DAP events (stopped, output, terminated, ā¦) āāāŗ stdout
Requests that do not need a running debuggee (initialize, setBreakpoints before launch)
are answered by Session directly; breakpoints received early are buffered and applied as
soon as the MoarVM connection exists. Runtime requests (threads, stackTrace, scopes,
variables, evaluate, continue, next, stepIn, stepInTargets, stepOut, pause,
exceptionInfo) go through a dispatch table in Translate.
Launch sequence
launchvalidates the arguments and picks a port.The debuggee is started with
Proc::Async(or by the client throughrunInTerminalwhenconsolenames a terminal):raku --debug-port=<port> --debug-suspend -I<includePaths> -I<helper> -MNimala::Raku-DAP::InjectedHelper <program> <args>.--debug-suspendkeeps it halted before the first statement.Protocolconnects to127.0.0.1:<port>, reads MoarVM's 24-byte greeting (MOARVM-REMOTE-DEBUG\0plus major/minor version) and answersMOARVM-REMOTE-CLIENT-OK\0.Buffered line, function, and exception breakpoints are applied;
stopOnEntryadds a breakpoint on the first executable line.After
configurationDonethe adapter resumes all threads.Debuggee stdout/stderr are forwarded as DAP
outputevents; process exit producesexitedandterminated.
If the handshake fails, the debuggee is killed with SIGKILL so no listening port is left
behind.
MoarVM remote protocol
All messages after the greeting are MessagePack maps with a numeric type and a request
id. Protocol correlates responses with requests through promises and publishes
unsolicited notifications as a Supply. The message types used most are:
| Type | Message | Used for |
|---|---|---|
| 5/6 | Suspend / Resume all | stop handling, continue |
| 13 | Thread stack trace | stackTrace, depth checks |
| 15 | Set breakpoint (16 confirms) | line, function, entry, sweep breakpoints |
| 17 | Breakpoint notification | stop events |
| 18 | Clear breakpoint | removing breakpoints |
| 20/21 | Step into / Step over | native stepping when available |
| 23 | Step completed | stop events |
| 24 | Release handles | end of a stop |
| 26/27 | Context handle / lexicals | scopes and variables |
| 32-44 | Object attributes, metadata, ⦠| lazy expansion of objects |
| 36 | Invoke (whitelisted only) | rendering helpers in InjectedHelper |
docs/DEBUG-MOARVM.md documents the protocol in full.
Stop handling
On every stop notification the adapter first suspends all threads, so state cannot change
while it is inspected. StopHandler then decides what the stop means:
A user breakpoint: evaluate condition and hit count; for logpoints emit an
outputevent and resume; otherwise emitstoppedwith reasonbreakpoint.A step or sweep breakpoint: let
Steppingdecide whether the step is finished or must continue (see below).An exception: record it in
ExceptionStateand emitstoppedwith reasonexception.
Every frame and object handle allocated while stopped is tracked in Handles and released in
one batch on resume or disconnect, so the debuggee does not accumulate pinned objects.
Stepping engine
Some MoarVM builds report wrong line numbers after stepping: when MoarVM instruments a frame's
bytecode for debugging it does not update the frame's line annotation table, so the line
reported by Step completed and stack traces drifts. Breakpoint IDs, in contrast, are
always exact.
MoarVMProbe detects the bug once per VM/compiler version by debugging a tiny script, and
caches the result in $XDG_CACHE_HOME/nimala/moarvm-features.json (default ~/.cache; first run
about 2 s, later runs under 1 ms).
Bug present:
Steppinguses routine-scoped sweep stepping. For Step Over it sets temporary breakpoints on every executable line of the current routine (not of nested routines), records the stack depth, and stops at the first sweep breakpoint hit at the same or a shallower depth. Called routines therefore run at native speed. Step Into resolves the callee through the symbol index, sets an entry breakpoint, and sweeps the entered routine. Step Out sets a breakpoint on the caller's continuation line. Sweep breakpoints are removed when the step ends.Bug absent: Step Over and Step Into are forwarded to MoarVM's native step commands.
Once MoarVM is fixed upstream, the probe flips automatically and the native path is used without code changes.
FrameClassifier supports both paths: it decides whether a frame belongs to user code or to
Rakudo/MoarVM/NQP internals (for smart stepping), which source lines are executable, and
where routines start and end.
Variable inspection and evaluation
Inspector and ValueRenderer turn MoarVM context and object handles into DAP scopes and variables. Values
are first described from object metadata without running any code. A human-readable
rendering (.gist etc.) needs code execution in the debuggee; this is done only through
the whitelisted functions of the injected helper.
Expression parses the bounded grammar into a variable plus a chain of accessors and an
optional comparison. Evaluator resolves the variable in the frame's lexicals and walks
the accessors with the attribute/positional/associative protocol messages. MoarVM's
Find Method (35) and non-whitelisted Invoke (36) are blocked by protocol guards.
The injected helper
Nimala::Raku-DAP::InjectedHelper is loaded into the debuggee with -M. It provides:
_nimala_gist,_nimala_str,_nimala_raku,_nimala_elems: rendering wrapped intry, so a failing.gistyields a placeholder instead of an exception.Exception hooks for the uncaught and all exceptions filters. The debuggee runs with
RAKU_EXCEPTIONS_HANDLER=Nimalaso uncaught exceptions reach the hook, where the adapter holds a breakpoint.
In a source checkout the helper is taken from resources/injected-helper. Installed
distributions store resources under hashed names, so the adapter copies the helper to
$XDG_CACHE_HOME/nimala/injected-helper/<version>/ and rewrites it only when the
content changes. Without a helper the debugger still works, but exception breakpoints and
helper-based rendering are unavailable.
Concurrency
Session serialises lifecycle state behind a startup barrier: the debuggee is resumed only
after both the MoarVM connection and configurationDone exist, whatever order they arrive in.
Writes to stdout are protected by a lock in Framing; the trace log has its own lock. Long
operations (connecting, applying breakpoints, evaluating) run in start blocks so the stdin
loop keeps reading requests.
Testing
DAP tests live under xt/Nimala/Raku-DAP/. Most are end-to-end: they start the adapter,
drive it with TestClient.rakumod, launch real debuggee scripts, and assert on DAP events.
Run them with:
prove6 -l xt/Nimala/Raku-DAP/
zef install runs only t/, which holds three installation checks; t/02-dap-session.rakutest debugs one small
program end to end.
Capability summary
| DAP capability | Supported |
|---|---|
| launch | yes |
| attach | no |
| configurationDone | yes |
| terminate / restart | yes |
| runInTerminal (console setting) | yes |
| Line breakpoints | yes |
| breakpointLocations | yes |
| Conditional breakpoints | yes |
| Hit-count breakpoints | yes |
| Logpoints | yes |
| Function breakpoints | yes |
| Exception breakpoints (uncaught/all) | yes |
| exceptionInfo | yes |
| continue / next / stepIn / stepOut | yes |
| stepInTargets | yes |
| pause | yes |
| threads / stackTrace | yes |
| scopes / variables (lazy expansion) | yes |
| evaluate (bounded), hover evaluation | yes |
| setVariable | no |
| Step back / reverse debugging | no |
| Completions in debug console | no |
See also
docs/debug.mdā detailed reference, including historical backgrounddocs/DEBUG-MOARVM.mdā MoarVM remote protocol investigation and message referencedocs/moarvm-upstream-question.mdā upstream findings (line drift, port security)docs/lsp-coverage.mdā LSP and DAP coverage table
AUTHOR
kliklamala
LICENSE
Artistic-2.0
=end rakudoc