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:
| mode | command shape | what you see |
|---|---|---|
| interpret | --no-jit --fuel 2000000 | program stdout with the interpreter. |
| run with jit | --fuel 2000000 | same program with hot blocks compiled. |
| check only | --check | verifier and compiler diagnostics. |
| disassemble | --no-jit --disasm | decoded instructions and constants. |
| analyze | --analyze | functions, reachability, opcode histogram and hints. |
| emit module | --emit module.vxc | module 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
fndeclares functions;returnexits them.letandvardeclare locals; assignment uses=.if,while,do,forandmatchcover control flow.try,catch,throwanddefercover cleanup.typedeclares records;interfacedeclares 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.
| value | literal or constructor | notes |
|---|---|---|
| null | null | missing map reads return it; get() still throws. |
| bool-like int | 1, 0 | conditions use truthiness; there is no separate bool tag in the language surface. |
| int | 42, 0xff | 64-bit signed host integer. |
| real | 1.5, 2e3 | double precision. |
| string | "abc", "hi ${name}" | \$ is a literal dollar sign. |
| list | [1, 2] | indexed from zero; slices are half-open. |
| map | map(), {"a": 1} | string keys; m[k] reads insert a null slot. |
| function | fn ... or a name | closures capture cells, not raw stack slots. |
| record | type 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.
| group | operators | notes |
|---|---|---|
| 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. |
| ternary | cond ? a : b | only 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.
| stage | where | output |
|---|---|---|
| lexing | src/lang/lang.cpp | identifiers, numbers, strings, operators and comments skipped. |
| parsing | src/lang/lang.cpp | expression tree with precedence and statement forms. |
| name resolution | compiler passes | local slots, captures, globals and native references. |
| lowering | compiler passes | bytecode instructions, labels and exception ranges. |
| verification | src/bytecode/verifier.cpp | stack and code checks before execution. |
| optional optimization | src/bytecode/optimizer.cpp | peephole rewrites under --opt. |
| emission | src/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.
deferbecomes 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.
matchbecomes 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
| family | examples | purpose |
|---|---|---|
| constants and stack | push, push_real, push_string, dup, swap, pop | move values through the evaluation stack. |
| locals and globals | load_local, store_local, load_global, store_global, load_cell | access slots and captured cells. |
| arithmetic | add, sub, mul, div, mod, pow | typed numeric operations. |
| comparison and logic | eq, ne, lt, le, gt, ge, lnot | conditions and truthiness. |
| bitwise | band, bor, bxor, shl, shr | integer bit operations. |
| control flow | jmp, jz, jnz, call, ret, halt | branches and frames. |
| containers | new_list, new_map, load_index, store_index, map_keys, iter_pairs | list and map operations. |
| strings | str_concat, str_slice, str_find, str_lower, str_upper, str_replace | byte string operations. |
| records | new_struct, load_field, store_field, call_method | record layout and methods. |
| exceptions | try_begin, try_end, throw | structured unwinding. |
| native and gc | call_native, gc, check_type | host 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.
| file | role |
|---|---|
src/jit/jit.cpp | hot block selection and compilation state. |
src/jit/x64_emitter.cpp | raw x86-64 instruction encoding. |
src/jit/regalloc.cpp | host register assignment for compiled operands. |
src/jit/machine_code_buffer.cpp | owned executable buffers. |
src/jit/disasm_x64.cpp | runtime disassembly for debugging generated code. |
src/memory/exec_mem.cpp | mmap and mprotect page handling. |
knobs
--hot nsets the block hit threshold, default 32.--traceprints compilation events.--no-jitforces the interpreter.--statsprints 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.
| area | source | behavior |
|---|---|---|
| object model | src/gc/objects/ | tagged objects with type and size metadata. |
| heap | src/gc/heap/ | mark-sweep collection over traced roots. |
| system memory | src/memory/sys_mem.c | posix mapping layer. |
| executable memory | src/memory/exec_mem.cpp | writable then read-execute jit pages. |
flags
--heap nsets initial heap bytes, default 4m.--heap-max nsets the maximum, default 1g.--gc nsets the collection threshold, default 64k.--gc-stresscollects 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.
| area | examples |
|---|---|
| text and data | text, encoding, json, toml, xml, compress, binary |
| math and structure | math, matrix, bits, stats, units, geo, color |
| system | fs, path, process, sys, term, time, random |
| network | net, http |
| security and validation | crypto, regex, validate, uuid, semver |
| runtime | task, 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
- create a file under
src/stdlib/native/<area>/. - write small
n_*functions with explicit argument checks. - register names and arities in the area registration table.
- 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.
| flag | what it disables |
|---|---|
--no-process | process spawning natives. |
--no-fs-read | filesystem read natives. |
--no-fs-write | filesystem mutation natives. |
--no-net | network natives. |
--no-env | environment reads and mutation covered by policy. |
--sandbox | process, 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_*orpct_*. - module names stay lowercase and avoid collisions with native names.
- the
inimodule usescfg_*because nativeini_*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.
| group | modules |
|---|---|
| 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
--checkverifies without running.--disasmprints decoded bytecode.--analyzeprints function, reachability and opcode reports.--emit-asmwrites reassemblable text.--hashprints a sha-256 of the canonical module image.--verifychecks paths against a sha-256 list.--diffcompares two programs instruction by instruction.--patchreplaces 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.
| layer | source | job |
|---|---|---|
| transport | transport.cpp | content-length framing and json messages. |
| protocol | protocol.cpp | positions, ranges, locations, utf-16 conversion. |
| document | document.cpp | open buffer text, line starts and word_at. |
| analysis | analysis.cpp | lexical symbols and diagnostics per buffer. |
| features | one file per feature | hover, refs, symbols, formatting, and so on. |
| capabilities | capabilities.cpp | the 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
| feature | behavior | honest boundary |
|---|---|---|
| hover and completion | declaration detail, keywords, functions and module names. | no inferred types for arbitrary expressions. |
| definition and declaration | locals first, then module names across open buffers. | same answer for both methods; no declaration files exist. |
| implementation and type definition | method and record declaration lookup. | small record and interface model, not full polymorphism. |
| references | lexical identifier matches across open buffers. | not data-flow resolved; comments and strings are skipped. |
| document highlight | all 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 symbols | flat symbol list and workspace query across open buffers. | lexical scan, not a persisted workspace index. |
| call hierarchy | prepared callables, incoming and outgoing calls. | name-based call matching inside a function body. |
| rename and prepare rename | lexical identifier rename in open buffers. | no cross-project disk edits. |
| signature help | active parameter from comma and parenthesis position. | parameter names come from declaration text. |
| formatting and range formatting | indentation and trailing-space edits. | range edits touch only selected lines and add no final newline. |
| folding, links, selection, inlay hints | brace ranges, import links, nested selections and small hints. | line and text based. |
| semantic tokens | full, ranged and delta results with a real previous-result cache. | lexical token classes from the same scanner. |
| code actions | var to let for never-reassigned locals. | deliberately conservative. |
| code lens | real 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.
| editor | files | notes |
|---|---|---|
| vs code | editors/vscode/ | language config, textmate grammar, extension manifest and a transparent green VX icon. |
| jetbrains | editors/jetbrains/virex.tmbundle/ | textmate bundle syntax for a lightweight plugin. |
| visual studio | editors/visual-studio/ | textmate grammar and package metadata. |
| textmate | grammars/textmate/ | shared grammar source. |
| tree-sitter | grammars/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.vxcompares runtime stdout and exit status against go for 251 cases.tests/gocpp/check.vxchecks 457 compiler diagnostic cases.tests/gocpp/pkg.vxchecks 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.txtwith 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.
| area | limitation |
|---|---|
| platform | jit and executable pages target x86-64 posix. |
| gc | stop-the-world, non-moving, no generational nursery. |
| concurrency | cooperative tasks with yield, sleep and channel switches; not os threads per task. |
| jit | partial coverage; many dynamic paths stay interpreted. |
| natives | no dynamic native loading. |
| sandbox | capability gates, not complete isolation. |
| regex | size caps but no hard execution budget. |
| lsp | lexical and open-buffer based; no full compiler semantics. |
| tree-sitter | grammar assets and smoke script exist, but generate and test tools are unavailable here. |
| gocpp | tested subset, not full go parity. |
| stdlib | some 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
- create the full folder tree under
stdlib/<name>/. - write pure-virex source with prefixed function names.
- add a deterministic test and regenerate
expected.txt. - write
docs/api.mdwith functions and limits. - add a runnable
examples/basic.vx. - register the module in
CMakeLists.txtand the catalogs. - run
ctestandvirex pkg check --root ..
adding an lsp feature
- add a line/text-based helper rather than inventing compiler semantics.
- advertise the capability only with a real handler.
- keep answers scoped to open buffers unless a disk index truly exists.
- 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 flag | meaning |
|---|---|
lsp | run the language server over stdin and stdout. |
bind <manifest> | generate c++ and virex bindings from a manifest. |
pkg list|check|path | inspect local pure-virex modules. |
fmt [--check|--write] file|- | format source or stdin with the lsp formatting pass. |
--disasm | print decoded bytecode and exit. |
--check | verify the program and exit. |
--analyze | print functions, reachability, dead bytes, hints and opcode histogram. |
--opt | run the peephole optimizer before execution. |
--debug | start the interactive bytecode debugger. |
--debug-script file | run debugger commands from a file and force interpretation. |
--break pc | add a breakpoint before the debugger starts. |
--emit file | write a .vxc module and exit. |
--emit-asm file | write reassemblable bytecode text. |
--hash | print the sha-256 of the canonical module image. |
--verify file | check paths against a sha-256 list; - reads stdin. |
--diff a b | compare two programs instruction by instruction. |
--patch file | replace or add functions in a target image then run it. |
--no-jit | interpreter only. |
--hot n | block hit threshold before jit compilation, default 32. |
--heap n | initial heap bytes, default 4m. |
--heap-max n | maximum heap bytes, default 1g. |
--gc n | collection threshold in bytes, default 64k. |
--gc-stress | collect on every allocation. |
--fuel n | run at most n instructions; 0 is unlimited. |
--trace | print jit compilation events. |
--stats | print result, op counts, jit stats and gc stats. |
--sandbox | apply the broad capability gate. |
--no-process, --no-fs-read, --no-fs-write, --no-net, --no-env | individual capability gates. |
--version, --help | version 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.