Build language tools in Vex
Vex's std/ide packages provide building blocks for language tools written in Vex: tokenization, grammar descriptions, syntax trees, query metadata, formatted diagnostics, document layout and protocol messages. Use them to build a small configuration language, a source browser, a formatter or an editor integration.
Choose the library layer that owns your problem. These packages are distinct from the compiler's Rust implementation and from the vex-lsp executable used to edit Vex programs.
Choose a component
| Import | Use it for | Main entry points |
|---|---|---|
ide/logos | Tokens and source positions for Vex-like input | newLexer, nextToken, slice |
ide/ungram | Named grammar rules, references and validation | newUngrammar, addNode, parseUngramText, validateGrammar |
ide/rowan | A syntax tree that can reconstruct retained source text | newSyntaxTreeBuilder, createGreenToken, createGreenNode, toRedNode |
ide/salsa | Revision and dependency metadata for incremental queries | newDatabase, queryOrCompute, advanceRevision, invalidateKey |
ide/ariadne | Source labels, diagnostic layout and terminal output | newReport, withLabel, renderReportToString; source caches and terminal-policy helpers |
ide/pretty | Width-sensitive layout for generated text | newPrettyBuilder, docText, docBreak, docGroup, formatDocWithWidth |
ide/doc | Structured documentation with HTML or terminal output | newDocumentationModule, addHeader, addParagraph, addCodeBlock, extractDocComments |
ide/lsp | LSP-shaped positions, diagnostics, requests and responses | newLspServer, parseLspMessage, formatLspResponse, formatDiagnosticNotification |
ide/dap | Debug adapter messages and supplied debugger state | newDapServer, setActiveFrame, addVariable, parseDapMessage, formatDapResponse |
ide/vxir | A Vex-written IR toolkit: graphs, analysis, passes and emitters | Graph and type tables, verifier, pass manager, dialect and target modules |
Import only the components you use. For installed toolchains, select a standard library tree containing those packages. In a compiler source checkout their public entry points are lib/std/ide/<package>/src/lib.vx.
Tokenize a small declaration
Save this complete program as tokens.vx. It consumes tokens until the explicit end-of-file kind, returns a nonzero exit code for an error token and prints each token's source text.
import { newLexer, nextToken, slice } from "ide/logos";
fn main(): i32 {
let! lexer = newLexer("let count = 12;");
while true {
let token = nextToken(&lexer!);
if token.kind == 99 { return 0; }
if token.kind == 0 { return 1; }
$println(slice(&lexer, token));
}
return 0;
}vex run tokens.vxExpected stdout, with exit status 0:
let
count
=
12
;TokenSpan.start and end identify a half-open source range; line and column values accompany it. The lexer owns its source string and advances through a mutable borrow. Token kind 0 is an error and 99 is end of input in this package's token model. Keep these values behind named constants in a larger application.
The lexer skips whitespace. A formatter or exact source reconstruction tool must retain the gaps between token spans as well as comments. A sequence of token texts alone cannot reproduce spaces that were skipped.
Format the same document at two widths
A pretty printer separates the content from its layout. docBreak is a potential line break; docGroup allows the layout engine to flatten that break to a space when the group fits. docNest adds indentation to a nested document.
Save this complete program as layout.vx:
import {
newPrettyBuilder, docText, docBreak, docConcat, docGroup,
formatDocWithWidth
} from "ide/pretty";
fn main(): i32 {
let! builder = newPrettyBuilder();
let first = docText(&builder!, "alpha,");
let split = docBreak(&builder!);
let second = docText(&builder!, "beta");
let tail = docConcat(&builder!, split, second);
let body = docConcat(&builder!, first, tail);
let group = docGroup(&builder!, body);
let wide = formatDocWithWidth(&builder, group, 0, 80);
let narrow = formatDocWithWidth(&builder, group, 0, 5);
$println(wide);
$println(narrow);
if wide != "alpha, beta" { return 1; }
if narrow != "alpha,\nbeta" { return 2; }
return 0;
}vex run layout.vxExpected stdout, with exit status 0:
alpha, beta
alpha,
betaThe width is a layout budget, not permission to split an indivisible text node: alpha, remains six characters even when the requested width is five. Keep document IDs with the builder that created them.
Assemble a lossless syntax tree
Rowan separates stored syntax from its position in a tree. Green nodes retain token text and child structure; red nodes add offsets and parent/depth context. The following function is a library fragment, not a complete program:
import {
GreenNode, newSyntaxTreeBuilder, createGreenToken,
createGreenNode, reconstructSourceText
} from "ide/rowan";
fn reconstructedDeclaration(): string {
let! builder = newSyntaxTreeBuilder();
let keyword = createGreenToken(&builder!, 1, "let ");
let name = createGreenToken(&builder!, 2, "count");
let value = createGreenToken(&builder!, 3, " = 12;\n");
let! children = Vec.new<GreenNode>();
children.push(keyword);
children.push(name);
children.push(value);
let root = createGreenNode(&builder!, 10, children);
return reconstructSourceText(&root);
}The expected string is "let count = 12;\n". The kind numbers here belong to this example's grammar, not a universal token enumeration. Keep trivia in the tree when preserving source spelling; use a separate formatted document when you intentionally want to change layout. A parser built on these components still owns precedence, recovery and the mapping from tokens to grammar rules.
Organize incremental work
Salsa's Database records revisions and memo entries. A useful editor workflow is:
- Give each logical input/query a unique
queryIdand retain its key hash. - Compute the result and pass its hash to
queryOrComputewith dependency IDs. - After an edit, advance the revision and update affected inputs, then recompute affected intermediate queries from dependencies toward consumers.
- Reuse a parent result only after its direct dependencies have current metadata; freshness checks read those entries rather than recursively evaluating their dependencies.
The package receives computedHash; it does not execute a user callback to compute the result. Store the actual result in your application and keep that storage consistent with the recorded hashes. The entry representation has two dependency slots. Design query nodes around that representation or aggregate larger dependency sets through intermediate nodes.
Turn source locations into useful diagnostics
Ariadne combines a report with labelled source ranges, messages and optional notes. Keep the source snapshot alive for the report, choose the byte-span or character-span API deliberately, and use the matching source-cache/indexed adapter. A Unicode character index, UTF-8 byte offset and editor protocol position are different coordinates; convert at a defined boundary.
Use the terminal-policy helpers when selecting ANSI color and output style. Keep the diagnostic message meaningful without color. Documentation output can use ide/doc to compose headers, paragraphs and code blocks, then render to HTML or ANSI terminal text.
Connect an editor or debugger
An integration owns three layers:
| Layer | Responsibility |
|---|---|
| Transport | Read/write messages, handle framing, enforce size limits and close cleanly |
| Protocol | Decode requests, preserve request IDs, encode responses and notifications |
| Language/debugger state | Resolve the requested document revision or stopped process and produce the actual result |
The LSP/DAP packages expose message types and response-building helpers. Connect them to your own source database or debugger adapter; completion contents, hover text, frames and variables must come from that state. Advertise only the methods your integration serves. For editing Vex itself, use the compiler's vex-lsp tool described in the toolchain guide.
Build an IR-based tool
VXIR is a separate Vex-written toolkit for building compiler-like programs. Its public entry module groups type/data-layout tables, graph construction, verification, control-flow and dominance analysis, transformation passes, register allocation, object writers and target encoders. Choose the smallest layer your tool needs and verify its IR before and after a transformation.
For example, a teaching compiler can start with parsing, a typed graph and a scalar interpreter/reference result before selecting a native emitter. Keep target data layout, calling convention, relocations and object format in the target layer. VXIR is distinct from the main Vex compiler's Silicon IR; their APIs and pass identities must not be interchanged.
Continue building
- Modules and public interfaces
- Ownership and strings
- Testing for positive, malformed and boundary inputs
- Documentation generator for the compiler's CLI tool
- Native integration for an external parsing or debugger library