Nimala Raku LSP
=begin rakudoc :kind<Language> :subkind<Tooling> :category<editing>
<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 Language Server Protocol (LSP 3.18) server for Raku, written in pure Raku. It gives any LSP-capable editor (VS Code, Neovim, Helix, Emacs, Kate, Zed, JetBrains IDEs, ā¦) Raku-aware features: diagnostics from the real compiler, completion, hover documentation, navigation, refactoring, semantic highlighting, and more.
The server is a separate executable, nimala-raku-lsp. The editor starts it and talks to
it over stdin/stdout (or TCP) using JSON-RPC:
Editor / LSP client
ā JSON-RPC 2.0, Content-Length framing (stdio or TCP)
ā¼
nimala-raku-lsp (Nimala::Raku-LSP)
ā
āāā raku -c syntax diagnostics (subprocess)
āāā NativeWorker RakuAST symbols/tokens (subprocess)
āāā .nimala/symbols.db persistent symbol index (SQLite)
This document has two parts:
Part I explains how to install, configure, and use the server.
Part II gives developers a high-level map of the implementation.
The debugger is described separately in doc/DAP.rakudoc. A method-by-method coverage table
is kept in docs/lsp-coverage.md; the analysis subsystem is detailed in docs/analysis.md.
Part I: Using the language server
Requirements and installation
Rakudo 2026.09 (tested and recommended). Rakudo 2024.07 runs with limitations: the RakuAST-based analysis (native symbols, semantic tokens) ignores signature parameters and fails on files with
BEGINblocks, so the built-in parser fills in.The
sqlite3shared library, used for the symbol index.Raku dependencies:
DBIish,JSON::Fast(installed byzef).
zef install Nimala::Raku-LSP
zef puts the nimala-raku-lsp and nimala-raku-dap scripts into the bin/ directory of the repository it
installs to. Without root rights that is usually ~/.raku/bin, which must be in PATH (for example
export PATH="$HOME/.raku/bin:$PATH" in ~/.bashrc). Otherwise point the editor at the script directly, in VS Code
with raku.lsp.serverPath.
From a source checkout the server can also be run as raku -Ilib bin/nimala-raku-lsp.
Starting the server
nimala-raku-lsp # stdio (default; what editors use)
nimala-raku-lsp --port=5007 # TCP on 127.0.0.1:5007
nimala-raku-lsp --host=0.0.0.0 -p 5007 # TCP on another interface
nimala-raku-lsp --tcp=127.0.0.1:5007 # TCP, host:port form
nimala-raku-lsp -p 5007 --single-session # exit after the client disconnects
TCP mode is useful when one long-running server should serve several editor sessions, or
when debugging the server itself. Without --single-session it keeps accepting connections.
VS Code
The extension in editors/vscode/ starts the server for files with language raku. The
server registers a file watcher dynamically for **/*.{raku,rakumod,rakutest,rakudoc,nqp,p6,pm6,pod6,t,t6},
so changes made outside the editor reach the index. The raku settings section is sent as
initializationOptions and synchronized on every change.
| Setting | Default | Meaning |
|---|---|---|
| raku.executablePath | raku | Raku used for the server, syntax checks, and tools |
| raku.lsp.serverPath | (empty) | Path to nimala-raku-lsp; looked up in PATH when empty |
| raku.includePaths | [] | Extra -I directories for syntax checks and tools |
| raku.syntaxCheck.enable | true | Live compiler diagnostics on/off |
| raku.syntaxCheck.timeout | 5 | Seconds before a syntax check is killed |
In untrusted workspaces (Workspace Trust) the extension starts neither the language server nor the Test Explorer until trust is granted, and ignores workspace values of the executable, server path, and include path settings.
Editor commands: Restart Language Server, Run Raku File, Debug Raku File, Debug Test,
Open RakuDoc Preview (also to the Side).
The extension also shows a language status item (server state, Raku version), lists test files
and subtests in the Test Explorer, provides prove6/zef tasks with a $raku problem
matcher, and ships snippets for common Raku constructs.
Other editors
Configure the client to start nimala-raku-lsp (no arguments) for Raku files. Example for
Neovim:
vim.lsp.config('nimala', {
cmd = { 'nimala-raku-lsp' },
filetypes = { 'raku' },
root_markers = { 'META6.json', '.git' },
settings = { raku = { syntaxCheck = { enable = true, timeout = 5 } } },
})
vim.lsp.enable('nimala')
Configuration
Settings arrive as initializationOptions in initialize and are updated with
workspace/didChangeConfiguration. Keys are looked up first under a raku section and then
at the top level, so both of these forms work:
{ "raku": { "syntaxCheck": { "enable": true, "timeout": 5 }, "includePaths": ["lib"] } }
{ "syntaxCheck": { "enable": true, "timeout": 5 }, "includePaths": ["lib"] }
| Key | Default | Meaning |
|---|---|---|
| syntaxCheck.enable | true | Run raku -c for diagnostics |
| syntaxCheck.timeout | 5 | Seconds before the check process is killed |
| executablePath | raku | Raku binary for checks (alias: rakuPath) |
| includePaths | [] | Extra -I directories |
Environment variables read by the server:
| Variable | Effect |
|---|---|
| NIMALA_LOG=1 | Log server events to $XDG_STATE_HOME/nimala/lsp.log |
| (default ~/.local/state/nimala/lsp.log) | |
| NIMALA_WORKER_TIMEOUT | Seconds before a NativeWorker subprocess is abandoned (default 10) |
The workspace and the symbol index
On initialized the server indexes every Raku source file in all workspace folders in the
background and reports progress to the editor (cancellable). Directories .git, .nimala,
.precomp, .vscode, .vscode-test, node_modules, scratch, .cache, and blib are
skipped.
The index is stored in .nimala/symbols.db in the workspace root. On the next start only
files whose size or modification time changed are re-parsed, so startup is fast. Add
.nimala/ to your .gitignore. Deleting the directory is safe; it is rebuilt on the next
start. Without a workspace folder the index lives in memory.
Multi-root workspaces are supported: adding a folder indexes it, removing one prunes its entries.
Installed modules (from zef) are indexed on demand when you use them, so completion,
hover, and go-to-definition also work for third-party code.
Features
Diagnostics
Every open document is checked with the real compiler (raku -c) in a separate process.
Errors and warnings appear with exact positions and the full compiler message. Project
library paths (lib next to the nearest META6.json or .git) and includePaths are
added automatically.
Checks run when a document is opened, changed, or saved; an outdated check is cancelled when a newer edit arrives.
Checks that exceed
syntaxCheck.timeout(for example aBEGINblock that loops) are killed.Both push (
publishDiagnostics) and pull diagnostics (textDocument/diagnostic,workspace/diagnostic) are supported; the server uses pull when the client offers it.
Note: raku -c runs BEGIN and use phasers, so checking a file executes its
compile-time code, exactly as compiling it would.
Completion
Triggered while typing and on . and :.
Methods after
., based on the inferred type of the invocant: own methods first, then inherited ones and role methods, ordered by distance in the method resolution order.Metamethods after
.^(.^methods,.^attributes,.^parents, ā¦, plus your ownmethod ^foo).Variables in scope, types, keywords, module names after
use/need, and namespaces after::.Documentation for core items is loaded lazily when an item is selected.
Type inference understands declared types, .new assignments, declared return types of
method chains, typed containers (Array[User], Hash[Str, Order], Promise[T] with
.result), element extraction (.first, .head, .pop), and self inside classes and roles.
Inline completion
Ghost-text templates for control flow (for, if, unless, with, while, loop,
given, try, ā¦), declarations (sub, method, class, role, enum,
unit class|module|role), Pod blocks (=begin ā¦), #| doc comments, and test helpers
(subtest, plan), aligned to the current indentation.
Hover and signature help
Hover shows the declaration, signature, inferred type,
#|doc comments, and offline core documentation with a link to docs.raku.org. Core docs ship with the distribution inresources/core-docs.db, so no network access is needed.Signature help (on
(and,) shows the routine signature and highlights the active parameter.
Navigation
| Feature | What it does |
|---|---|
| Go to definition | Variables, routines, methods, types, module files of use/need |
| Go to declaration | Same as definition |
| Go to type definition | User types ā their declaration; core types ā docs.raku.org |
| Go to implementation | Role ā composing classes, class ā subclasses, role method ā implementations |
| Find references | Workspace-wide, including or excluding the declaration |
| Document highlight | Highlights all uses of the symbol under the cursor in the file |
| Document symbols | Outline of packages, classes, routines, attributes, variables |
| Workspace symbols | Substring search over the SQLite index |
| Document links | URLs and use/need module names become clickable |
Hierarchies
Type hierarchy: supertypes (
is,also is,does,also does) and subtypes.Call hierarchy: incoming calls (who calls this routine) and outgoing calls (what it calls).
Refactoring and code actions
Rename (with prepare) is scope-aware: renaming a lexical variable does not touch an unrelated
variable with the same name in another scope. Renaming a file updates its unit class
declaration and use statements across the project.
| Kind | Actions |
|---|---|
| Quick fix | Declare local variable (my) or attribute (has); create stub for an |
| undefined sub; add a missing use; insert missing semicolon; add use | |
| v6.d; trim trailing whitespace | |
| Refactor | Extract to method / variable / constant; inline variable; convert to |
| postfix if; convert to single quotes; generate accessor method; | |
| implement missing role methods; move class/role to a new file |
Expensive edits are computed only when an action is chosen (codeAction/resolve).
Code lenses
Reference counts above classes, methods, attributes, and variables (click to list them).
Implementation counts for roles.
ā¶ Run All Tests and ā¶ Run Subtest in test files (
.rakutest,.t,.t6), with companion ā¶ Debug All Tests and ā¶ Debug Subtest lenses (commandnimala.debugTest).
Formatting
Document and range formatting re-indent code by nesting depth, trim trailing whitespace, and
leave multi-line strings and heredocs untouched. The editor's tabSize and insertSpaces
options are honoured. It works on code with syntax errors.
On-type formatting re-indents a single line as you type: the line of a } or ;, and the completed
line when you press Enter. Only that line's leading whitespace changes; heredoc, Pod and string lines are left
alone.
Editor features
Semantic tokens (full, range, and delta) for precise highlighting of Raku constructs.
Inlay hints: inferred variable types, parameter names at call sites, method return types; details on hover.
Folding ranges for blocks, declarations, Pod sections, and comment runs.
Selection ranges: expand selection from word to expression, statement, block, declaration, and file.
Linked editing of paired Pod
=begin/=endnames, heredoc terminators, and loop labels.Inline values while debugging with the Nimala DAP.
Server commands
workspace/executeCommand supports nimala.trimWhitespace and nimala.moveSymbol. They are normally
invoked through code actions; Extract to Method is a code action resolved through codeAction/resolve. An
unknown command is answered with error -32602.
Troubleshooting
No diagnostics: Check that
raku.syntaxCheck.enableis true and thatraku.executablePathpoints to a workingraku. Missing modules usually mean a missingincludePathsentry.Diagnostics appear late or not at all for large files: Raise
raku.syntaxCheck.timeout.Stale symbols after large external changes: Restart the server, or delete
.nimala/to force a full re-index.Anything else: Start the server with
NIMALA_LOG=1and inspect~/.local/state/nimala/lsp.log.
Security considerations
Like standard Raku tooling, the language server executes compile-time code when inspecting documents:
Compile-Time Execution: Background syntax checking (
raku -c) and native AST parsing executeBEGIN,CHECK, andINITblocks as well as compile-time side effects of imported modules (use).Doc Preview Evaluation: Rendering RakuDoc to HTML (
raku --doc=HTML) also evaluates compile-time blocks in opened files.Untrusted Code: Never open untrusted Raku files or untrusted workspaces without inspecting them first. Always use isolated environments (containers or sandboxes) when reviewing unknown code.
Part II: Architecture
Design goals
Pure Raku, no native extensions besides the SQLite driver.
Error tolerance. Code being edited is usually broken; every feature must degrade gracefully instead of failing.
Isolation. Anything that can hang, crash, or leak (the compiler, RakuAST) runs in a subprocess with a timeout.
Responsiveness. Requests are handled concurrently; long work is debounced, cancellable, and runs in the background.
Spec-driven types. All LSP 3.18 data structures are generated from the official
metaModel.json.
Module map
Nimala::Raku-LSP Entry point: run-server (stdio), run-tcp-server
āāā Transport::Stdio / Socket Byte streams for stdio and TCP
āāā Transport::Framing Content-Length framing
āāā Dispatcher JSON-RPC dispatch, method whitelist, cancellation, logging
āāā Handler Handler class composed of roles:
ā āāā Lifecycle initialize, initialized, shutdown, exit, indexing, progress
ā āāā Sync didOpen/didChange/didClose/didSave, watched files, debounce
ā āāā Diagnostics Push and pull diagnostics
ā āāā Intelligence hover, completion, signatureHelp, inlineCompletion
ā āāā Navigation definition, references, highlights, symbols, links
ā āāā Hierarchy type and call hierarchy
ā āāā Refactoring rename, codeAction, willRenameFiles, executeCommand
ā āāā CodeActionProviders Individual quick fixes and refactorings
ā āāā CodeLens codeLens, codeLens/resolve
ā āāā Formatting formatting, rangeFormatting, onTypeFormatting
ā āāā SemanticTokens semanticTokens full/range/delta with result cache
ā āāā EditorFeatures folding, selection range, inlay hints, linked editing,
ā inline values
āāā Analysis Facade over:
ā āāā Diagnostics raku -c subprocess and error parsing
ā āāā Symbols Symbol extraction from all parser tiers
ā āāā Cursor Word at point, call context, active parameter
ā āāā TypeInference Variable and expression types
ā āāā Completion Type-aware completion pipeline
ā āāā InlineCompletion Ghost-text templates
ā āāā Intelligence Hover, definitions, scoped references
āāā Parser Error-tolerant custom grammar (tier 1), native worker spawning
āāā NativeWorker RakuAST symbols and tokens in a subprocess (tiers 2/3)
āāā Document Text store, incremental edits, UTF-16 positions, parse caches
āāā Workspace ProjectIndex: files ā symbols across workspace folders
āāā SymbolDB SQLite persistence (.nimala/symbols.db)
āāā VendorIndex Symbols of installed modules
āāā CoreDocs Core documentation (resources/core-docs.db)
āāā Cache File discovery, exclusions, content hashing
āāā Client Server ā client notifications and requests
āāā URI file:// URI ā path conversion
āāā Protocol::Types Generated LSP 3.18 types
Request flow
stdin/TCP āāŗ Framing āāŗ Dispatcher āāŗ Handler role method āāŗ Analysis / Parser / Workspace
ā ā
āāāāāāāāāāāāāāāā result āāāāāāāāāāāāāāāāāā
ā¼
Framing āāŗ stdout/TCP
The Dispatcher maps LSP method names to handler methods by replacing / with -
(textDocument/hover ā textDocument-hover) and only dispatches methods on a whitelist.
Each request runs asynchronously; a $/cancelRequest sets the request's cancellation token,
which long loops (references, symbol search, semantic tokens) check periodically, and the
request then fails with RequestCancelled (-32800). On shutdown the dispatcher waits for
in-flight requests.
Server-initiated traffic (publishDiagnostics, $/progress, workspace/applyEdit,
refresh requests, window/showDocument) goes through Client, which tracks pending
requests with timeouts.
Document synchronisation
Document stores the text with precomputed line offsets and converts between LSP positions
(UTF-16 code units, as advertised by positionEncoding) and Raku string offsets. Incremental
changes are applied in order. Each document carries version-stamped caches for the custom AST,
native symbols, native tokens, and semantic tokens, so a feature never reuses results from
an older version.
On didChange the index update and the syntax check are debounced (about 300 ms); native
analysis runs only when a feature asks for it. External file changes arrive through
workspace/didChangeWatchedFiles; they update the index and trigger debounced ā¦/refresh
requests (code lens, inlay hints, semantic tokens, folding ranges, diagnostics, inline values)
when the client supports them.
Multi-tier parsing
Raku is hard to parse, and code being edited is often invalid. Nimala therefore uses several parsers and takes the best result available:
| Tier | Parser | Runs | Strength |
|---|---|---|---|
| 1 | Custom grammar (Parser) | in-process | Fast; tolerates broken code |
| 2/3 | RakuAST via NativeWorker | subprocess | Compiler-accurate symbols and tokens |
| ā | Regex heuristics | in-process | Last resort for partial lines |
The NativeWorker is a precompiled module started as
raku -I<repo> -I<project-lib> -MNimala::Raku-LSP::NativeWorker -e ⦠. It receives the
source on stdin and returns symbols and semantic tokens as JSON. Running RakuAST out of
process keeps its memory use, global stash side effects, and occasional crashes away from
the server; a timeout (NIMALA_WORKER_TIMEOUT) bounds every run. If native analysis fails for
a document version, the document is marked and the server falls back to tier 1 until the
next edit.
The worker runs without holding the document's parse lock, so tier 1 parsing of the same document continues
meanwhile, and concurrent requests for the same document version share one worker run.
No compiler or RakuAST code runs inside the server process itself.
Analysis
The Analysis facade re-exports the functions of its sub-modules so handlers depend on one
module. Key pieces:
Symbols converts any parser output into LSP
DocumentSymbol/SymbolInformation.Cursor finds the identifier at a position with full Raku identifier rules (sigils, twigils, kebab-case) and determines call contexts and active parameters.
TypeInference resolves types in stages: declared type, constructor assignment, method return types, container unwrapping, sigil defaults, and
self.Completion classifies the context, resolves the invocant type, collects members along the MRO (core types, roles, workspace classes, installed modules), and ranks the result.
Intelligence builds hover cards, finds definitions (document ā open documents ā workspace index ā installed modules), and finds references with lexical scope awareness.
Diagnostics runs
raku -cthroughProc::Async, kills it on timeout, and parses compiler output into LSP diagnostics.
Indexing and persistence
Workspace (the ProjectIndex) maps files to symbols and symbols to locations for all
workspace folders; it keeps no symbol caches in memory. SymbolDB is the single symbol store:
files on disk are kept in SQLite with file size and modification time, so unchanged files are
skipped instead of being parsed again, and open documents go into temporary overlay tables that
shadow the stored version of the file until it is closed. Background indexing runs in a
cancellable task with $/progress reporting.
VendorIndex extracts symbols of installed modules on first use, primarily by introspecting
the loaded module in an isolated subprocess, falling back to source scanning, and caches the
result in the same database. CoreDocs reads the prebuilt core documentation database and
renders Pod to Markdown for hover and completion.
Concurrency
Requests, notifications, debounced tasks, and background indexing run concurrently. To avoid
deadlocks, locks are always taken in this order, and never held across an await, sleep,
or subprocess:
Transport / framing lock
DocumentStore lock
Handler state locks (debounce, semantic token cache, cancellation tokens, progress, diagnostics jobs, indexing)
Parser lock (per-document parse lock)
SymbolDB lock
ProjectIndex leaf locks (per-URI job chains, module scan snapshot), never held across database calls
Generated protocol types
Protocol::Types is generated from the LSP 3.18 metaModel.json by
tools/generate-lsp-types.raku. Do not edit it by hand; regenerate it instead.
Development
raku -Ilib -c lib/Nimala/Raku-LSP/Handler/Navigation.rakumod # compile check
prove6 -l t/ xt/ # full test suite
raku tools/format-all.raku --check # formatting
Tests live under xt/ and mirror the module namespaces (for example
xt/Nimala/Raku-LSP/Handler/hover.rakutest). Each handler has its own test file. t/ holds only the installation
checks that zef install runs: all modules load, and one LSP and one DAP session against bin/.
The handler can also be used programmatically:
use Nimala::Raku-LSP::Handler;
use JSON::RPC::Server;
my $server = JSON::RPC::Server.new(application => Nimala::Raku-LSP::Handler.new);
say $server.handler(q:to/END/);
{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"processId":null,"rootUri":null,"capabilities":{}}}
END
Capability summary
| Area | Supported |
|---|---|
| Lifecycle | initialize, initialized, shutdown, exit, cancelRequest, progress |
| Synchronisation | didOpen, didChange (incremental), willSave, didSave, didClose |
| Diagnostics | push, document pull, workspace pull |
| Intelligence | completion (+resolve), inline completion, hover, signature help |
| Navigation | definition, declaration, type definition, implementation, |
| references, document highlight, document/workspace symbols, | |
| document links | |
| Hierarchies | type hierarchy, call hierarchy |
| Refactoring | rename (+prepare), code actions (+resolve), willRenameFiles, |
| executeCommand | |
| Editor | code lens (+resolve), formatting, range formatting, on-type |
| formatting, folding, | |
| selection range, semantic tokens (full/range/delta), inlay hints | |
| (+resolve), linked editing, inline values | |
| Workspace | multi-root folders, watched files, configuration changes, |
| server-initiated refreshes | |
| Not supported | notebooks, color provider, monikers, willSaveWaitUntil, |
| rangesFormatting, setTrace/logTrace, did/willCreateFiles, | |
| did/willDeleteFiles, didRenameFiles, textDocumentContent, | |
| documentLink/resolve, workspaceSymbol/resolve, telemetry | |
| (full list in docs/lsp-coverage.md) |
See also
doc/DAP.rakudocā the Nimala debug adapterdocs/lsp-coverage.mdā method-by-method LSP and DAP coveragedocs/analysis.mdā analysis subsystem in detaildocs/code-completion.mdā completion pipeline
AUTHOR
kliklamala
LICENSE
Artistic-2.0
=end rakudoc