overview

virex is a small runtime written in c++17 and a little c. it has its own language called .vx, a bytecode compiler, a stack virtual machine, a mark-sweep garbage collector, a binary module format, an x86-64 jit, and a hand-written language server. the repository also contains a go-to-c++ translator, a large standard library written in virex itself, editor grammars, and a local playground.

the design is deliberately old-fashioned in the good way: explicit values, explicit bytecode, explicit frames, and no external runtime dependency. the generated c++ is expected to build with g++ -std=c++17 -Wall -Wextra -Werror -Icompiler/runtime. the interpreter and jit share the same program image, so a program can be disassembled, verified, patched, debugged, and then run without changing source.

what the project is

  • a language you can actually run: ./build/virex examples/fib.vx.
  • a bytecode target with assembler, disassembler, verifier, optimizer, diff and stats.
  • a runtime with gc, structured exceptions, closures, records, native calls and cooperative tasks.
  • a stdlib of 103 modules written in the language, not wrappers around a foreign stdlib.
  • tooling: pkg, fmt, lsp, bind, debugger and module emission.

what it is not

it is not a full go runtime, not a complete os sandbox, not a whole-program optimizing compiler, and not a portable jit for every architecture. the jit targets x86-64 posix. the sandbox flags are capability gates. the go-to-c++ suite is a tested subset with documented gaps. those boundaries are part of the design, not accidents to hide.

quick start

the only build requirements are cmake 3.16+, a c++17 compiler, a c compiler for the small posix layer, and mmap / mprotect. sources are globbed under src/ and tests/, so adding a file is enough.

cmake -S . -B build -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release
cmake --build build -j
ctest --test-dir build --output-on-failure

./build/virex examples/fib.vx
./build/virex examples/loops.vx --no-jit --stats
./build/virex examples/lists.vx --disasm
./build/virex pkg check --root .

useful first programs

  • examples/fib.vx — functions, recursion and jit warm-up.
  • examples/loops.vx — loops with interpreter statistics.
  • examples/lists.vx — collection ops and disassembly.
  • examples/hot_loop.vxasm — raw bytecode assembly.
  • examples/modules/main.vx — a small multi-module program.

sanitizer build

cmake -S . -B build-asan -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Debug \
  -DCMAKE_CXX_FLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer" \
  -DCMAKE_C_FLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer" \
  -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=address,undefined"
cmake --build build-asan -j
ASAN_OPTIONS=detect_leaks=1 ./build-asan/virex_tests

the sanitizer build is the right place to work on the vm, gc, and native boundary. release builds are used for differential runs and timing.

compiler playground

the playground works straight from github pages. the page first tries a loopback compiler api; when that is absent, it runs the source with a small in-browser interpreter for a documented subset of virex. the browser engine is not the c++ compiler: it supports functions, records, lists, maps, loops, match, interpolation and the common builtins, and it labels disassembly and module output as previews.

to use the real compiler, run the python standard library server from the repository root. every request is written to a fresh temp directory and the real build/virex binary is invoked:

python3 tools/site_server.py --port 8000

open http://localhost:8000/playground.html. with the server present, the mode selector maps to real compiler entry points:

modecommand shapewhat you see
interpret--no-jit --fuel 2000000program stdout with the interpreter.
run with jit--fuel 2000000same program with hot blocks compiled.
check only--checkverifier and compiler diagnostics.
disassemble--no-jit --disasmdecoded instructions and constants.
analyze--analyzefunctions, reachability, opcode histogram and hints.
emit module--emit module.vxcmodule size and sha-256 of the canonical image.

on github pages, interpret and run execute the subset with a step limit; check reports syntax errors, duplicate functions, unknown calls and arity mismatches; analyze prints source-level counts; disassembly is an instruction preview rather than real bytecode; emit is a textual module preview with a fnv1a hash, not a .vxc file. the status line always names the engine that answered.

local requests are limited by source size, output size, a wall-clock timeout and a fuel budget. non-emit modes pass --no-process --no-net --no-env --no-fs-write. this is capability gating, not process isolation; see sandbox and security.

language tour

.vx is a statically-slotted language: names are resolved into local slots, captured cells, globals, fields or native names at compile time. values remain dynamic at runtime, but the shape of a function frame is known before execution.

fn greet(name = "world") {
    return "hello ${name}";
}

fn main() {
    let names = ["ada", "grace"];
    for (name in names) {
        println(greet(name));
    }
    match (len(names)) {
        1 => println("one"),
        2 => println("two"),
        default => println("many"),
    }
}

the small surface

  • fn declares functions; return exits them.
  • let and var declare locals; assignment uses =.
  • if, while, do, for and match cover control flow.
  • try, catch, throw and defer cover cleanup.
  • type declares records; interface declares method shapes.
  • import "x.vx"; compiles another source file into the same program.

the compiler is hand-written in src/lang/lang.cpp. there is no generated parser and no external parser dependency.

values and types

runtime values are tagged. integers and reals are distinct, strings are byte strings with length, lists and maps are gc objects, and functions can be first-class values. null is its own value, not zero and not an empty string.

valueliteral or constructornotes
nullnullmissing map reads return it; get() still throws.
bool-like int1, 0conditions use truthiness; there is no separate bool tag in the language surface.
int42, 0xff64-bit signed host integer.
real1.5, 2e3double precision.
string"abc", "hi ${name}"\$ is a literal dollar sign.
list[1, 2]indexed from zero; slices are half-open.
mapmap(), {"a": 1}string keys; m[k] reads insert a null slot.
functionfn ... or a nameclosures capture cells, not raw stack slots.
recordtype Point { x, y }fields plus optional methods.

annotations and checks

optional type annotations are accepted for parameters and locals. they are useful to readers and to a few compiler checks, but this is not a full static type system. runtime operations still validate their operands, and bad stores produce vm errors with file and line information.

expressions and operators

precedence follows a familiar order: logical or, logical and, bitwise or, xor, and, equality, comparison, shifts and ranges, additive, then multiplicative. parentheses always win.

groupoperatorsnotes
logic||, &&, !short circuit.
bitwise|, ^, &, <<, >>emit bor, bxor, band, shl, shr.
comparison==, !=, <, <=, >, >=strings compare lexicographically.
arithmetic+, -, *, /, %+ also concatenates strings.
range..used by for and range helpers.
ternarycond ? a : bonly the chosen branch is evaluated.
compound++, --, ??=, ||=, &&=variables and place chains evaluate the place once with a typed store check.

slices and indexing

let part = text[1:4];      // half open, bounds evaluated once
let item = list[2];         // list index
let value = map["k"];       // missing key inserts and reads null
map["k"] = 7;               // explicit write

string interpolation uses ${name} inside double quotes. a literal dollar sign is written \$. template strings in virex source that want to show a placeholder must escape it as \${name} so the outer template does not consume it.

statements and declarations

statements are compiled into straight-line bytecode with jump targets. the parser prefers statement form in statement position, so a match used as a statement does not accidentally parse as an expression.

match

match (value) {
    1 => println("one"),
    2, 3 => println("small"),
    default => println("other"),
}

the final default is mandatory and the first matching arm wins. arms are evaluated in source order.

destructuring

let [a, b] = pair;
let Point(px, py) = point;

loops

while tests first, do tests last, and for walks lists, maps, strings or ranges. loop bodies are normal lexical scopes, so closures capture per-iteration cells rather than sharing one mutable slot.

functions and closures

fn make_counter(start = 0) {
    var count = start;
    return fn () {
        count++;
        return count;
    };
}

functions compile to bytecode functions with a fixed slot count. captured locals are promoted to cells with new_cell, load_cell and store_cell. a closure stores those cell references in its captures, so two calls to make_counter get independent state.

default parameters

trailing parameters may have defaults. the compiler records a minimum arity in the module image (version 8 and newer), so calls with fewer arguments are legal and missing arguments trigger the default expression at call time. passing null also triggers the default.

function values

names can be used as values, stored in lists and maps, and called with call_value. method calls use call_method; member function fields use call_member. all three share the same frame and exception machinery.

records and interfaces

type Pair {
    left,
    right,

    fn sum() {
        return this.left + this.right;
    }
}

interface Shape {
    fn area();
}

records are gc objects with named member slots. field access emits load_field and store_field; methods are functions stored on the type metadata in the module image. there is no inheritance chain and no virtual dispatch table beyond method lookup on the record type.

interfaces are used by the compiler and the language server to describe expected method shapes. they are intentionally small: they help tools and readability without pretending to be a full typeclass or trait system.

errors and defer

fn read_value(map, key) {
    defer println("read finished");
    try {
        return get(map, key);
    } catch (error) {
        println(error);
        return null;
    }
}

bytecode exceptions use try_begin and try_end ranges with a handler table. throw unwinds frames and renders a call trace with file and line data from the module image.

defer f(args) is lowered by the compiler, not by a new opcode. deferred calls run in reverse order on normal return and on exception unwind. arguments are captured when the defer statement executes, so later mutations do not change what is called.

map access semantics

m[k] is an insert-or-write place. reading a missing key creates a null slot, which makes m[k] = v simple and predictable. get(m, k) is the strict form and throws on a missing key. has, getor and map_get_or are available when a caller wants the check to be explicit.

modules and imports

./build/virex -I stdlib/strings/src main.vx
./build/virex -I stdlib/json/src -I stdlib/result/src main.vx

imports are textual: import "name.vx"; resolves through include directories, compiles that file into the current program, and makes its module-level functions visible. the compiler caches compiled modules by canonical path so a diamond import does not duplicate a definition.

pure-virex stdlib modules have no entry point. they are compiled as modules and tested by small programs that import them. package tooling never fetches anything; it only inspects the local stdlib/ tree. include directories remain the explicit way to make an import resolvable.

module output

--emit file.vxc writes a versioned binary image that can be run later with ./build/virex file.vxc. the same container is used by the assembler path and by .vxbc text-assembled programs.

compiler pipeline

the compiler lives almost entirely in src/lang/lang.cpp and src/lang/module.cpp. a source file is lexed into tokens, parsed into expressions and statements, lowered into a bytecode program, and optionally written to a module image. each stage keeps file and line information so runtime errors and tools can point back at source.

stagewhereoutput
lexingsrc/lang/lang.cppidentifiers, numbers, strings, operators and comments skipped.
parsingsrc/lang/lang.cppexpression tree with precedence and statement forms.
name resolutioncompiler passeslocal slots, captures, globals and native references.
loweringcompiler passesbytecode instructions, labels and exception ranges.
verificationsrc/bytecode/verifier.cppstack and code checks before execution.
optional optimizationsrc/bytecode/optimizer.cpppeephole rewrites under --opt.
emissionsrc/module/encoder.cpp.vxc image or in-memory program.

what lowering actually does

  • local variables become integer slot indexes; captured variables become cells.
  • string interpolation becomes string concatenation instructions.
  • defer becomes hidden cleanup calls in every return path.
  • default parameters become arity checks and default expressions.
  • slices become one bounds calculation followed by a string or list slice.
  • match becomes comparison chains with a mandatory final branch.

--analyze prints functions, reachability, dead bytes, peephole hints and an opcode histogram. --diff a b compares two programs instruction by instruction, which is how the gocpp suite proves that a source change did not alter generated code for unrelated cases.

bytecode and vm

the vm is a stack machine. each frame has a function image, an instruction pointer, a base pointer into the value stack, local slots, and an optional exception range. instructions are small and deliberately readable in disassembly.

instruction families

familyexamplespurpose
constants and stackpush, push_real, push_string, dup, swap, popmove values through the evaluation stack.
locals and globalsload_local, store_local, load_global, store_global, load_cellaccess slots and captured cells.
arithmeticadd, sub, mul, div, mod, powtyped numeric operations.
comparison and logiceq, ne, lt, le, gt, ge, lnotconditions and truthiness.
bitwiseband, bor, bxor, shl, shrinteger bit operations.
control flowjmp, jz, jnz, call, ret, haltbranches and frames.
containersnew_list, new_map, load_index, store_index, map_keys, iter_pairslist and map operations.
stringsstr_concat, str_slice, str_find, str_lower, str_upper, str_replacebyte string operations.
recordsnew_struct, load_field, store_field, call_methodrecord layout and methods.
exceptionstry_begin, try_end, throwstructured unwinding.
native and gccall_native, gc, check_typehost calls and runtime checks.

source files for this layer are in src/bytecode/: opcode.cpp, program.h, assembler.cpp, disassembler.cpp, verifier.cpp, cfg.cpp, optimizer.cpp, diff.cpp and stats.cpp. the vm loop is src/interpreter/vm.cpp, with exceptions in src/interpreter/exceptions/ and profiling in src/interpreter/profiler.cpp.

debugging

--debug starts an interactive bytecode debugger; --debug-script file runs commands from a file and forces interpretation. --break pc adds a breakpoint before the debugger starts. the debugger supports breakpoints, watchpoints, stepping, a small repl and hex dumps.

jit tier

the jit is a hand-written x86-64 compiler in src/jit/. it emits real machine bytes into executable pages, seals those pages read-execute, and enters compiled code from the interpreter loop. it is not a whole-program compiler: hot blocks and supported shapes are compiled, while complex or dynamic paths stay interpreted.

filerole
src/jit/jit.cpphot block selection and compilation state.
src/jit/x64_emitter.cppraw x86-64 instruction encoding.
src/jit/regalloc.cpphost register assignment for compiled operands.
src/jit/machine_code_buffer.cppowned executable buffers.
src/jit/disasm_x64.cppruntime disassembly for debugging generated code.
src/memory/exec_mem.cppmmap and mprotect page handling.

knobs

  • --hot n sets the block hit threshold, default 32.
  • --trace prints compilation events.
  • --no-jit forces the interpreter.
  • --stats prints result, op counts, jit stats and gc stats.

the honest limit is that many dynamic operations are not compiled. integer arithmetic, control flow and call-return shapes are the sweet spot. strings, maps, exceptions and native calls generally fall back or deoptimize to shared runtime helpers.

gc and memory

the collector is stop-the-world and non-moving. gc objects include strings, lists, maps, functions, closures, cells, records and task state. allocation comes from an mmap-backed heap with a block allocator in src/memory/block_allocator.cpp.

areasourcebehavior
object modelsrc/gc/objects/tagged objects with type and size metadata.
heapsrc/gc/heap/mark-sweep collection over traced roots.
system memorysrc/memory/sys_mem.cposix mapping layer.
executable memorysrc/memory/exec_mem.cppwritable then read-execute jit pages.

flags

  • --heap n sets initial heap bytes, default 4m.
  • --heap-max n sets the maximum, default 1g.
  • --gc n sets the collection threshold, default 64k.
  • --gc-stress collects on every allocation.

a non-moving collector keeps native pointers simple but means the heap can fragment. there is no compacting phase, no generational nursery, and no concurrent marking. for vm work, run the sanitizer build with --gc-stress on small programs.

module format

.vxc and .vxbc share a versioned, little-endian container implemented in src/module/vxc_format.cpp. the encoder is src/module/encoder.cpp, linking is src/module/linker.cpp, and manifest helpers are in src/module/manifest.cpp.

the image carries code, globals, function records, file and line tables, member names, struct and type metadata, methods, string constants, native names from version 7 onward, minimum arity for default parameters from version 8 onward, and the module name. older versions remain readable.

loader hardening

  • verifier limits on stack depth and code size.
  • loader caps on counts and string sizes.
  • vm frame and handler caps.
  • canonical hashing through --hash.
  • path verification through --verify.

--patch file replaces or adds functions in a target image then runs it, which is useful for debugging a single function without rebuilding a whole program.

native stdlib

native functions live under src/stdlib/native/. each folder registers a small, flat set of host functions with the vm through native.cpp and native.h. there is no dynamic plugin loading; the native table is compiled into the binary.

areaexamples
text and datatext, encoding, json, toml, xml, compress, binary
math and structuremath, matrix, bits, stats, units, geo, color
systemfs, path, process, sys, term, time, random
networknet, http
security and validationcrypto, regex, validate, uuid, semver
runtimetask, error, duration

natives receive a native_context and a packed argument array. they validate arity and value kinds through helpers such as want_text, then return a tagged value. throwing from a native uses the current program counter so the runtime can render a useful trace.

adding a native

  1. create a file under src/stdlib/native/<area>/.
  2. write small n_* functions with explicit argument checks.
  3. register names and arities in the area registration table.
  4. add a test under tests/ and keep output deterministic.

capabilities

capability flags gate whole classes of natives. they are checked at the native boundary, not inside the language, and they do not create a separate operating-system process jail.

flagwhat it disables
--no-processprocess spawning natives.
--no-fs-readfilesystem read natives.
--no-fs-writefilesystem mutation natives.
--no-netnetwork natives.
--no-envenvironment reads and mutation covered by policy.
--sandboxprocess, fs read/write, net and env access covered by policy.

there are also bounded native reads, compressed and decompressed output caps, http body and header caps, verifier and loader limits, and env-gated host info in some system and terminal natives. these are hardening measures, not proof of isolation. the locally served playground uses the same gates plus a timeout and a fuel limit.

stdlib architecture

every pure-virex module has the same tree:

stdlib/<module>/
  src/<module>.vx
  tests/test_<module>.vx
  tests/expected.txt
  tests/run.sh
  docs/api.md
  examples/basic.vx
  readme.md

source files are imported with import "<module>.vx"; and a matching -I stdlib/<module>/src. tests run the module with --no-jit and compare stdout byte-for-byte against expected.txt. ctest registers one virex_stdlib_<module> entry per module.

naming rules

  • functions use a short module prefix, for example cal_*, crc_* or pct_*.
  • module names stay lowercase and avoid collisions with native names.
  • the ini module uses cfg_* because native ini_* names already exist.
  • docs list every public function and its limits; examples are runnable without extra setup.

virex pkg check --root . verifies required files, compiles each module, and compiles each test and example. it is read-only and never downloads anything.

stdlib catalog

there are 103 modules. the table groups them by the job they do; every entry has the same folder layout and a ctest entry. stdout is the contract that each test compares.

groupmodules
text and documents strings, text, textwrap, template, shellquote, markdown, texttable, textstats, humanize, phonetic, roman, lcs, fuzzy, morse, ngram, suffixarray, string_builder
structured data and protocols json, canonicaljson, jsonpointer, jsonpatch, yaml, toml, ini, properties, csv, querystring, url, xmlp, html, encoding, bencode, crc32, adler32
containers and algorithms lists, maps, sets, queues, heap, deque, stack, priorityqueue, tree, trie, ring, graph, dag, grid, interval, ranges, search, sorting, numbers, result, option, pairs, sequence, bloom, bitfield, bitstream, unionfind, segmenttree, cache, statemachine, diff, invertedindex, astar, pagerank, testing, expression, matrix, orderedmap
numeric, time and utility bigint, decimal, rational, complex, polynomial, combinatorics, primes, bits, percent, units, money, geo, color, stats, rate, pagination, duration, time, calendar, cron, semver, uuid, validation, regex, glob, paths, ipaddr, logging, cli, graphviz, crypto

a few modules deliberately wrap host helpers instead of reimplementing them. regex uses posix regex, crypto uses native digests, and json uses the host encoder for scalars. the rest of the logic is written in virex.

tooling

the cli is intentionally one binary with subcommands and flags. virex pkg is read-only; virex fmt shares its formatting pass with the lsp; virex lsp speaks stdio json-rpc; virex bind generates c++ glue from a manifest.

package commands

  • virex pkg list --root . lists module names.
  • virex pkg check --root . checks trees and compiles sources, tests and examples.
  • virex pkg path <name> --root . prints a module path.

there is no pkg add, no registry client, and no implicit include resolution. imports still use -I. that keeps builds reproducible and the tool honest.

compiler inspection

  • --check verifies without running.
  • --disasm prints decoded bytecode.
  • --analyze prints function, reachability and opcode reports.
  • --emit-asm writes reassemblable text.
  • --hash prints a sha-256 of the canonical module image.
  • --verify checks paths against a sha-256 list.
  • --diff compares two programs instruction by instruction.
  • --patch replaces or adds functions in a target image.

formatter

the formatter is line-based and conservative. it fixes indentation, trims trailing spaces, and leaves blank lines alone. it tracks strings, line comments and brace depth so a { inside a literal never changes indentation.

./build/virex fmt file.vx
./build/virex fmt --write file.vx
./build/virex fmt --check file.vx

the lsp exposes the same pass as whole-document formatting and as range formatting. range edits only touch selected lines, use lsp exclusive end positions, and never add a final newline. running the formatter twice on the same text is idempotent.

there is no line-width wrapping, no import sorting, and no semantic rewrite. code actions are also conservative: only var to let for locals never assigned after declaration.

lsp architecture

the language server is a synchronous stdio json-rpc loop in src/lsp/server.cpp. one request at a time keeps document versions and diagnostics ordered without locks. clients send full text replacement on every edit, so incremental sync is intentionally not advertised.

layersourcejob
transporttransport.cppcontent-length framing and json messages.
protocolprotocol.cpppositions, ranges, locations, utf-16 conversion.
documentdocument.cppopen buffer text, line starts and word_at.
analysisanalysis.cpplexical symbols and diagnostics per buffer.
featuresone file per featurehover, refs, symbols, formatting, and so on.
capabilitiescapabilities.cppthe exact feature set advertised at initialize.

the server keeps text exactly as the client sent it and converts byte offsets to protocol utf-16 offsets itself. this matters as soon as a file contains characters outside ascii. diagnostics are published on open and change, and cleared on close.

what the analysis can and cannot know

symbols.cpp scans identifiers outside comments and strings. it records declaration offset, kind, brace depth and a one-line detail string. it does not perform type inference or a full compile. definition, declaration, references, highlights and code lens answers are therefore based on lexical name matching plus a few scope rules, never on a pretend type database.

cross-file answers are limited to buffers the editor has opened. locals stay buffer-local. module-level declarations are shared across open buffers because imports can use them from anywhere. virex has no separate declaration files, so definition and declaration answers are intentionally the same.

lsp features

featurebehaviorhonest boundary
hover and completiondeclaration detail, keywords, functions and module names.no inferred types for arbitrary expressions.
definition and declarationlocals first, then module names across open buffers.same answer for both methods; no declaration files exist.
implementation and type definitionmethod and record declaration lookup.small record and interface model, not full polymorphism.
referenceslexical identifier matches across open buffers.not data-flow resolved; comments and strings are skipped.
document highlightall occurrences of the word under the cursor in one buffer.all occurrences are kind text because reads and writes need data flow.
document and workspace symbolsflat symbol list and workspace query across open buffers.lexical scan, not a persisted workspace index.
call hierarchyprepared callables, incoming and outgoing calls.name-based call matching inside a function body.
rename and prepare renamelexical identifier rename in open buffers.no cross-project disk edits.
signature helpactive parameter from comma and parenthesis position.parameter names come from declaration text.
formatting and range formattingindentation and trailing-space edits.range edits touch only selected lines and add no final newline.
folding, links, selection, inlay hintsbrace ranges, import links, nested selections and small hints.line and text based.
semantic tokensfull, ranged and delta results with a real previous-result cache.lexical token classes from the same scanner.
code actionsvar to let for never-reassigned locals.deliberately conservative.
code lensreal use counts for module-level declarations across open buffers.informational only; no command and no fake action.

every advertised capability has a handler. there are no command-only lenses, no fake diagnostics, and no workspace index that silently reads files outside open buffers.

editor integration

editor assets are real files in the repository, not screenshots or placeholders.

editorfilesnotes
vs codeeditors/vscode/language config, textmate grammar, extension manifest and a transparent green VX icon.
jetbrainseditors/jetbrains/virex.tmbundle/textmate bundle syntax for a lightweight plugin.
visual studioeditors/visual-studio/textmate grammar and package metadata.
textmategrammars/textmate/shared grammar source.
tree-sittergrammars/tree-sitter-virex/grammar source and smoke script.

bash grammars/tree-sitter-virex/smoke.sh checks the grammar assets locally. tree-sitter generate and tree-sitter test are not available in this environment, so the project does not claim those commands passed. the json grammars are validated by a small ctest-side json check.

go-to-c++ translator

compiler/main.vx is a translator written in virex that maps a practical subset of go to c++17 with a header-only runtime under compiler/runtime/. it is a compatibility and validation tool, not the main path for writing virex programs.

./build/virex compiler/main.vx -- input.go -o out.cpp
./build/virex compiler/main.vx -- input.go --build bin --run
./build/virex tests/gocpp/check.vx
./build/virex tests/gocpp/pkg.vx
./build/virex tests/gocpp/run.vx

differential suites

  • tests/gocpp/run.vx compares runtime stdout and exit status against go for 251 cases.
  • tests/gocpp/check.vx checks 457 compiler diagnostic cases.
  • tests/gocpp/pkg.vx checks 9 small package projects.

stderr is intentionally not compared; the suites compare stdout and exit status for supported cases. generated c++ is compiled with strict warnings and -Werror.

unsupported areas

full go parity is not a goal that has been met. reflect, unsafe, cgo, plugin, go/debug/runtime, gc and scheduler parity, full net/http with tls and x509, database drivers, encoding/xml, gob, asn1, and full math/big or cmplx are documented gaps. see docs/go-to-cpp.md for the detailed matrix.

testing

tests are split into c++ unit groups, ctest smoke scripts, stdlib output comparisons, language and bytecode suites, and virex-driven gocpp suites. the main binary is virex_tests; individual groups can be selected by name on the command line.

./build/virex_tests
./build/virex_tests lsp_formatter lsp_code_lens
ctest --test-dir build --output-on-failure
./build/virex tests/gocpp/check.vx
./build/virex tests/gocpp/pkg.vx
./build/virex tests/gocpp/run.vx

what each layer guards

  • core c++ tests cover values, maps, bytecode, gc, vm, jit, module format and lsp helpers.
  • stdlib tests compare stdout against expected.txt with no jit.
  • examples are run with and without jit and must agree.
  • the bind smoke test generates glue and compiles it with strict warnings.
  • the site smoke tests check links, documentation sections and the playground API.
  • gocpp suites protect compatibility claims and diagnostic output.

a clean tree currently has 103 modules checked by pkg check, 42 root examples matching across jit modes, 0 markdown prose audit issues, 7 valid json grammar files, and a clean git diff --check.

performance notes

performance work is measured, not assumed. --stats prints op counts, jit stats and gc stats. --analyze shows opcode histograms and dead bytes. --hot controls how quickly a block is considered hot.

fast paths

  • integer arithmetic and local slot access in compiled hot blocks.
  • simple loops with predictable branches.
  • direct native calls with small argument counts.
  • map index writes after the key already exists.

expected costs

  • stop-the-world mark-sweep pauses grow with live object count.
  • string concatenation allocates; loops that build text should be measured.
  • map reads through m[k] can insert a null slot.
  • lexical lsp scans are cheap per buffer but not a whole-workspace index.
  • quadratic stdlib routines such as lcs and long division are documented as such.

the jit does not make every operation fast. dynamic calls, strings, maps and exceptions usually remain interpreted or call shared helpers. that is why --no-jit is a first-class mode and why examples are validated in both modes.

sandbox and security

the word sandbox in this project means capability gating. flags turn off classes of natives at the host boundary. they do not create a jail, a separate uid, a container, or a syscall filter. a program that needs files, network or processes should be run without the relevant gates; a program that should not have them should be run with the gates and with the understanding that resource exhaustion is still possible.

--sandbox disables process spawning, filesystem reads and writes, network access, and env access covered by policy. it does not stop cpu or memory exhaustion, and some host-info reads may remain depending on the native surface in use.

hardening already present

  • bounded native reads and output caps for compression.
  • http body and header caps.
  • verifier stack and code limits.
  • vxc loader caps on counts and strings.
  • vm frame and handler caps.
  • fuel as an instruction budget.
  • env-gated host info in some system and terminal natives.

regex caveat

regex support uses posix regex with size caps. there is no hard execution-time or step budget for a pathological pattern, so untrusted regex input should still be treated as risky.

limitations

these are the current, honest limits of the tree. they are not hidden behind a claim of completeness.

arealimitation
platformjit and executable pages target x86-64 posix.
gcstop-the-world, non-moving, no generational nursery.
concurrencycooperative tasks with yield, sleep and channel switches; not os threads per task.
jitpartial coverage; many dynamic paths stay interpreted.
nativesno dynamic native loading.
sandboxcapability gates, not complete isolation.
regexsize caps but no hard execution budget.
lsplexical and open-buffer based; no full compiler semantics.
tree-sittergrammar assets and smoke script exist, but generate and test tools are unavailable here.
gocpptested subset, not full go parity.
stdlibsome modules are intentionally small and document their bounds in docs/api.md.

when in doubt, run the module test, the example, and the relevant ctest group. the repository prefers a documented limit over a quiet approximation.

contributing

keep changes small, local and testable. source prose in markdown is informal and lowercase; code, commands and identifiers keep their exact spelling. generated c++ must compile with -Wall -Wextra -Werror.

adding a stdlib module

  1. create the full folder tree under stdlib/<name>/.
  2. write pure-virex source with prefixed function names.
  3. add a deterministic test and regenerate expected.txt.
  4. write docs/api.md with functions and limits.
  5. add a runnable examples/basic.vx.
  6. register the module in CMakeLists.txt and the catalogs.
  7. run ctest and virex pkg check --root ..

adding an lsp feature

  1. add a line/text-based helper rather than inventing compiler semantics.
  2. advertise the capability only with a real handler.
  3. keep answers scoped to open buffers unless a disk index truly exists.
  4. add a c++ test that drives server::handle_message.

changing the language

update the compiler, bytecode tests, language examples, editor grammars, this documentation and the gocpp differential expectations together. a syntax change that only touches the parser is not done.

roadmap

the direction is depth before breadth: keep the runtime honest, expand tested library coverage, and improve editor answers without pretending the lsp has a full compiler frontend.

  • more pure-virex modules with the same folder and ctest contract.
  • better disassembly and analysis reports for compiler work.
  • more jit shapes, always with interpreter parity tests.
  • richer lsp answers that remain explicit about open-buffer scope.
  • tree-sitter generate and test when the toolchain is available.
  • documented gocpp subset growth driven by differential cases.
  • hardening around regex budgets and untrusted input surfaces.

items are added only when they can be backed by a test and a document. the repository does not ship roadmap claims as if they were shipped features.

appendix: cli reference

command or flagmeaning
lsprun the language server over stdin and stdout.
bind <manifest>generate c++ and virex bindings from a manifest.
pkg list|check|pathinspect local pure-virex modules.
fmt [--check|--write] file|-format source or stdin with the lsp formatting pass.
--disasmprint decoded bytecode and exit.
--checkverify the program and exit.
--analyzeprint functions, reachability, dead bytes, hints and opcode histogram.
--optrun the peephole optimizer before execution.
--debugstart the interactive bytecode debugger.
--debug-script filerun debugger commands from a file and force interpretation.
--break pcadd a breakpoint before the debugger starts.
--emit filewrite a .vxc module and exit.
--emit-asm filewrite reassemblable bytecode text.
--hashprint the sha-256 of the canonical module image.
--verify filecheck paths against a sha-256 list; - reads stdin.
--diff a bcompare two programs instruction by instruction.
--patch filereplace or add functions in a target image then run it.
--no-jitinterpreter only.
--hot nblock hit threshold before jit compilation, default 32.
--heap ninitial heap bytes, default 4m.
--heap-max nmaximum heap bytes, default 1g.
--gc ncollection threshold in bytes, default 64k.
--gc-stresscollect on every allocation.
--fuel nrun at most n instructions; 0 is unlimited.
--traceprint jit compilation events.
--statsprint result, op counts, jit stats and gc stats.
--sandboxapply the broad capability gate.
--no-process, --no-fs-read, --no-fs-write, --no-net, --no-envindividual capability gates.
--version, --helpversion and usage output.

arguments after the source file are passed to the program and are available through args(). anything after -- is passed through.

appendix: file map

src/
  common/       values, errors, arena, hashmap, bitset, checksum, json
  bytecode/     opcodes, assembler, disassembler, verifier, cfg, optimizer
  interpreter/  vm loop, profiler, jit state, exceptions and frames
  jit/          x64 emitter, regalloc, machine code, runtime disasm
  gc/           object kinds and mark-sweep heap
  memory/       mmap, block allocator, executable pages
  stdlib/       builtins, native modules, containers, numeric helpers
  lang/         lexer, parser, compiler and source module loader
  module/       vxc container, encoder, linker and manifest
  diagnostics/  call trace and stack rendering
  debugger/     breakpoints, watchpoints, repl and hexdump
  lsp/          protocol, transport, analysis and every feature handler
  concurrency/  spinlock, channel, thread pool and task scheduler
compiler/       go-to-c++ translator and runtime headers
stdlib/         103 pure-virex modules
tests/          c++ tests, smoke scripts, gocpp suites and golden output
examples/       .vx and .vxasm programs
docs/           extra project documents
editors/        vs code, jetbrains and visual studio assets
grammars/       textmate and tree-sitter grammars
site/           this website and its playground frontend
tools/          local site server

build outputs and local editor noise are ignored by git. the site is plain static html, so the repository remains readable without a frontend toolchain.