Skip to content
Systems programming for what’s next.
— Vex

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 ​

ImportUse it forMain entry points
ide/logosTokens and source positions for Vex-like inputnewLexer, nextToken, slice
ide/ungramNamed grammar rules, references and validationnewUngrammar, addNode, parseUngramText, validateGrammar
ide/rowanA syntax tree that can reconstruct retained source textnewSyntaxTreeBuilder, createGreenToken, createGreenNode, toRedNode
ide/salsaRevision and dependency metadata for incremental queriesnewDatabase, queryOrCompute, advanceRevision, invalidateKey
ide/ariadneSource labels, diagnostic layout and terminal outputnewReport, withLabel, renderReportToString; source caches and terminal-policy helpers
ide/prettyWidth-sensitive layout for generated textnewPrettyBuilder, docText, docBreak, docGroup, formatDocWithWidth
ide/docStructured documentation with HTML or terminal outputnewDocumentationModule, addHeader, addParagraph, addCodeBlock, extractDocComments
ide/lspLSP-shaped positions, diagnostics, requests and responsesnewLspServer, parseLspMessage, formatLspResponse, formatDiagnosticNotification
ide/dapDebug adapter messages and supplied debugger statenewDapServer, setActiveFrame, addVariable, parseDapMessage, formatDapResponse
ide/vxirA Vex-written IR toolkit: graphs, analysis, passes and emittersGraph 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.

vex
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;
}
sh
vex run tokens.vx

Expected stdout, with exit status 0:

text
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:

vex
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;
}
sh
vex run layout.vx

Expected stdout, with exit status 0:

text
alpha, beta
alpha,
beta

The 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:

vex
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:

  1. Give each logical input/query a unique queryId and retain its key hash.
  2. Compute the result and pass its hash to queryOrCompute with dependency IDs.
  3. After an edit, advance the revision and update affected inputs, then recompute affected intermediate queries from dependencies toward consumers.
  4. 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:

LayerResponsibility
TransportRead/write messages, handle framing, enforce size limits and close cleanly
ProtocolDecode requests, preserve request IDs, encode responses and notifications
Language/debugger stateResolve 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 ​

Released under the MIT License.