x2c is a language for people who love to code.
Every programming language is built around a few values that determine what is easy or awkward to express. Python values readability and comes with batteries included. C values a small and fast mapping to the machine. Lisp values code and data being the same. Languages are opinionated because their goals conflict, and each one picks its priorities.
x2c is a quirky little language that would rather not pick. Static or dynamic, mutable or immutable, compile-time or run-time, managed or unmanaged: every option stays available. x2c is picky about one thing only, which is that it all stays one small language. The same code works in every mode, from single bits up to whole systems. You can change your mind or your paradigm without changing languages.
All of which makes x2c sound like a language with no values. It has three: love, power, and magic, and we know how that sounds. Nonetheless, see the panel for the values translated into code.
Under the hood, x2c is a superset of C that compiles to C, so everything stays close to native representations and works with the entire C ecosystem. If you know C, you already write x2c.
Why bother? Because programming is not about making computers do things; it is about helping brains think things, and x2c is a language for thinking in code.
Some users report heightened expressiveness, a sense of universality, and a touch of transcendence. Be sure to drink plenty of water.
Code is Love
Simple things are simple. Work with values, text, and collections directly. Read a file, walk its contents, and keep temporary memory scoped to the work that needs it. Skip the parts you hate; focus on what you love: the actual ideas.
// One parameter and result type; behavior follows the contained value.
Var twice(Var value) => value + value;
// The same function adds numbers and joins text.
Var number = twice(21), text = twice("ha");
printf("%s %s\n", number, text);
// Test a contained type, or inspect its broader kind.
assert(number is int && text is String);
printf("%s %s\n", number.kind().str(), text.kind().str());
// A Var can hold another kind of value later.
number = "sold out";
if (number is String)
printf("%s\n", number);View complete example →So Var, so good.
A Var is one 64-bit slot, the size of a double or pointer on supported targets. It holds numbers, text, names, collections, and participating user types. Functions can accept and return Vars, choosing operations from their contents at runtime. Use is to test the contained type and kind() to inspect its broader group.
// Separate contexts can use the same named value.
Symbol job = <ready>, network = <ready>;
printf("same name: %d\n", job == network);
// The symbol does not declare a C identifier.
int ready = 1;
printf("flag: %d; name: %s\n", ready, job.str());
// Symbol literals are constants, so C switch works.
switch (job) {
case <ready>:
puts("waiting for a worker");
break;
case <running>:
puts("doing the work");
break;
}View complete example →Symbol pleasures.
Symbols are named values that need no enum declaration. The same literal spelling gives the same value in every context. Reuse names without qualifying C identifiers or declaring constants that conflict with other declarations.
// Compare text with ==, whether literal or built at runtime.
String padded = " hello ", prefix = "hel";
String word = padded.strip(), same = prefix + "lo";
if (word == "hello" && word == same)
puts("same text");
// Transformations produce new values; the original stays untouched.
String loud = word.upper();
String first = word[:1];
// Interpolate text and expressions directly.
puts(%"$first: $loud ($(word.len()) bytes)");
// Read-only C functions accept nonempty Strings directly.
printf("C sees %zu bytes\n", strlen(word));View complete example →Text me, maybe.
Strings compare by contents with ==, so literals and independently constructed values agree without strcmp. Strip whitespace, change case, and take slices without changing the original. Interpolation puts values and expressions directly into the result.
Strings interoperate with C functions that read their bytes. Empty Strings are NULL, so respect the C function’s null-pointer contract. Strings are immutable; never pass one as a writable destination.
// Immutable Lists share tails and mix value kinds.
List order = %("tea" 3 2.5), labeled = cons(<order>, order);
// Arrays grow and change in place.
Array basket = ["tea", 3, 2.5];
basket[1] += 1;
basket.push(<packed>);
// Maps find values by key.
Map details = {name: "tea", quantity: 3, price: 2.5};
details[<quantity>] += 1;
printf("%s\n%s\n%s: %s\n",
labeled.repr(), basket.repr(),
details[<name>], details[<quantity>]);View complete example →Array of sunshine.
C’s native arrays do not grow, and keyed lookup needs a separate data structure. x2c supplies Lists, growable Arrays, and Maps with literals and common operations. Their Var elements can mix value kinds. Lists share immutable tails; Arrays grow and change in place; Maps find values by key.
Map workshop = {
title: "Make a tiny game",
topics: %(graphics sound games),
venue: {
name: "The Maker House", room: "Studio 2", seats: 24,
address: { street: "12 Garden Lane", city: "Bristol" }
},
hosts: [
{ name: "Ada", role: <instructor>, skills: %(graphics games) },
{ name: "Sam", role: <mentor>, skills: %(music sound) }
],
pricing: { currency: "GBP", standard: 35.0, student: 15.0 },
bring: ["A laptop", "Headphones", "An unfinished idea"],
sessions: [
{ title: "Draw a world", minutes: 45,
project: { width: 320, height: 240, colors: 16 } },
{ title: "Make it move", minutes: 60,
controls: { left: <a>, right: <d>, jump: <space> } },
{ title: "Add some sound", minutes: 30,
audio: { channels: 2, volume: 0.75, rate: 44100 } }
]
};View complete example →Just my types.
Describe nested data directly with collection literals. The punctuation shows how the pieces fit together, and expressions supply the values that vary.
// Values: equal content is the same object, so == is a pointer compare.
String greeting = "hel" + "lo", word = "hello";
List pair = %(1 2), twin = cons(1, cons(2, NULL));
assert(greeting == word && pair == twin && pair === twin);
// Objects: Arrays and Maps have identity; copies of the handle share it.
Array scores = [7, 3, 9], same = scores, other = [7, 3, 9];
assert(scores == other && scores !== other);
same.push(5);
assert(scores == same && scores === same);
assert(scores != other && scores !== other);
// Equal Strings and Lists find the same Map entry.
Map seen = {(greeting): 1, (pair): 2, done: other.len()};
printf("%s %s %s\n", seen["hello"], seen[%(1 2)], seen[<done>]);View complete example →The object of my detection.
Strings, Lists, and Symbols share equal values. Arrays and Maps are mutable objects: two separate Arrays can have equal contents without being the same Array.
Use == to test contents and === to test identity. String and List keys let you retrieve a Map entry using an independently constructed equal value.
// Read the whole text file and close it in one expression.
String text = path.open("r").string_close();
printf("whole file (%d bytes):\n%s", text.len(), text);
// Or stream lines, keeping the close beside the open.
auto File input = path.open("r");
long total = 0;
foreach (String line in input)
foreach (String word in line.words())
total += atol(word);
printf("total: %ld\n", total);View complete example →Smooth pickup lines.
Read the whole file and close it with string_close(), or iterate through its lines. In the example, the loop splits each line into words and sums the numbers. The File iterator handles line scanning and buffering.
Once the text is a String, filtering, transforming, slicing, and joining are method calls. You can also iterate through its bytes when character-oriented work calls for it. These operations avoid manual C buffers and scanning loops.
// Walk collection elements and Map values.
foreach (int score in [3, 4, 5])
printf("score: %d\n", score);
foreach (String name in %("Ada" "Grace"))
puts(name);
foreach (int count in {"tea": 2})
printf("stock: %d\n", count);
// Split text into lines, then words.
String text = "tea and cake\ncoffee and biscuits";
foreach (String line in text.lines())
foreach (String word in line.words())
puts(word);
// Read file lines and walk their words.
auto File input = path.open("r");
foreach (String line in input)
foreach (String word in line.words())
puts(word);View complete example →Loop, there it is!
The same foreach walks Array and List elements, Map values, and file lines. Walk the lines and words of a String directly, without first collecting them into another container.
auto int item_count(void) { // Reclaim on return.
return ["red", "green", "blue"].len();
}
auto Array owned = [1, 2]; // Clean up the value held on exit.
Map counts = auto {files: 2}; // Clean up the acquired value.
auto { // Reclaim this region's allocations together.
Array temporary = [1, 2, 3];
}
auto for (int i = 0; i < 2; i++) // One region.
Array.new().push(i);
for (int i = 0; i < 2; i++) auto { // Per iteration.
Array.new().push(i);
}
auto Scope work = NULL; // Destroy this Scope at block exit.
Array items;
auto (&work) items = [1, 2, 3]; // Select a destination.
printf("destination: %zu\n", items.length); // Still alive.View complete example →Let byte-gones be bygones.
Declaration auto cleans up the current value; initializer auto cleans up the acquired value. Inferred auto name = value and $auto(value) provide the same respective cleanups. Raw pointers need a cleanup operation.
Region auto reclaims allocations on every exit. It wraps blocks, statements, or functions. auto (&work) only selects and restores a destination; the managed Scope supplies reclamation.
More in the docs: values, symbols, collections and literals, files, and methods.
Code is Power
Complex things are possible. Your types, collection operations, patterns, packages, and threads work together. The pieces are small, but they compose and compound. Each piece you add gives your code more power.
class Color { int red, green, blue; };
// Construction follows field order; equality compares every field.
Color coral = Color.new(255, 127, 80);
Color same = Color.new(255, 127, 80);
assert(coral == same);
// Generated hashing and equality let equal colors share a Map entry.
Map names = {(coral): "coral"};
assert(names[same] == "coral");
// Colors also work as Array elements.
Array palette = [Color.new(255, 127, 80), Color.new(70, 130, 180)];
assert(palette[0] == coral);
// Printing includes the class name and each named field.
printf("%s: %s\n", names[same], coral.repr());View complete example →A class act.
Declare three fields. Construction, fieldwise equality, hashing, and printing come free. Use a Color as a Map key: an independently constructed equal color finds the same entry. Store Color values in Arrays, too. No custom methods are needed.
// Reuse Map storage: its keys are the set members.
typedef Map Set;
Set Set.add(Set left, Set right) => left.copy().merge(right);
Set Set.mul(Set left, Set right) => Set.new(left.keys()
.filter(%!(Var key) => key in right));
Set Set.new(List keys) => keys.foldl(%{},
%!(Map set, Var key) => set.update_n(1, key, (Var) 1));
// Connect add and mul to the + and * operators.
protocol Map(T) { T T.add(T, T); T T.mul(T, T); }
protocol Map(Set);
// Create two sets, then take their union and intersection.
Set fruit = Set.new(%(apple pear));
Set lunch = Set.new(%(pear bread));
Set set_union = fruit + lunch;
Set intersection = fruit * lunch;
printf("%d in the union, %d in both\n", set_union.len(), intersection.len());View complete example →Sets appeal.
A Set built on a Map gains union and intersection through operators. The type is a typedef Map Set: it reuses Map storage and operations while giving the result a vocabulary of its own.
// Store documents once; words refer to them by ID.
class Index { Array documents; Map words; } *;
void Index.init(Index index) {
index.documents = []; index.words = {};
}
// Add each word once per document, regardless of case or repetition.
void Index.insert(Index index, String name, String text) {
int id = index.documents.len();
index.documents.push(name);
foreach (String word in text.lower().words().iter().unique())
index.words.setdefault(word, []).array().push(id);
}
// An unknown word has no matches; lookup does not change the index.
Array Index.find(Index index, String word)
=> index.words.getdefault(word.lower(), []);View complete example →Index marks the spot.
Collect document words into an index, then combine the indexed results. Maps, Arrays, and iterator operations make the useful structure visible in the program.
Array orders = [
%(tea 2 "Ada"),
%(coffee 1 "Grace"),
%(tea 1 "Linus")
];
// Give each field a typed name.
foreach (List order in orders) {
(Symbol item, int count, String who) = order;
printf("%s wants %d %s\n", who, count, item.str());
}
// Select a shape and bind its fields in the condition.
foreach (List order in orders)
if (order ~= %(tea ?(int n) ?(String who)) && n > 1)
puts(%"$who is thirsty");View complete example →Breaking up is easy to do.
Destructuring gives each position a typed name. A pattern condition selects tea orders and binds their fields for the rest of the condition and its body.
// Recognize a nested condition and exchange its branches.
List simplify(List node) {
match (node) {
case %(if (not ?condition) ?yes ?no):
return simplify(%(if $condition $no $yes));
case %(if true ?yes ?): return simplify(yes);
case %(if false ? ?no): return simplify(no);
case %(if ?condition ?yes ?no):
return %(if $condition $(simplify(yes)) $(simplify(no)));
// Capture a whole block, transform it, splice it back in.
case %(block *body):
return %(block @(body.map(%!(List item) => simplify(item))));
default: return node;
}
}
List code = %(block
(if (not ready) (call wait) (call start))
(if true (call save) (call discard)));
puts(simplify(code).repr());
// (block (if ready (call start) (call wait)) (call save))View complete example →Match ado about nothing.
match selects nested List structures and binds their parts. Templates rebuild the result: $ inserts a value and @ splices a sequence.
This small simplifier combines pattern matching and reconstruction without manually indexing every node.
List seen = %(3 1 3 2 1 4);
printf("unique: %s\n", seen.iter().unique().list().repr());
List urgent = %(101 102), routine = %(201 202 203);
printf("queue: %s\n", urgent.iter()
.chain(routine.iter()).head(4).list().repr());
printf("first square over threshold: %d\n", range(1, 20)
.map(%!(value) => value * value)
.find(%!(value) => value > 70).int());
List temperatures = %(71 106 98 112 87);
printf("temperature alerts: %d\n", temperatures.iter()
.filter(%!(value) => value > 100).count());
printf("temperature warning: %s\n", temperatures.iter()
.any(%!(value) => value > 110) ? "yes" : "no");
List scores = %(91 88 100 73);
printf("scores valid: %s\n", scores.iter()
.all(%!(score) => score >= 0 && score <= 100) ? "yes" : "no");
printf("numbered: %s\n", %(<parse> <compile> <link>).iter()
.enumerate(1).list().repr());View complete example →Lazy does it.
Iterators select, merge, and enumerate values as they are consumed. Compose the operations around the task, then collect or reduce the result where you need it.
// The caller decides how to present content that cannot be text.
String preview(String path) {
try return read_text(path);
catch %(bad-arg *):
return "No text preview: file contains a NUL byte.";
catch %(not-found *):
return "No preview: file not found.";
catch:
return "No preview: unable to read file.";
}
// Close the file on success or while unwinding from a failed read.
String read_text(String path) {
auto File input = path.open("r");
return input.string();
}
// document.bin contains a NUL byte, which String cannot hold.
puts(preview(%"$directory/document.bin"));View complete example →Catch of the day.
A failed read can leave a block without leaving its file open. Cleanup stays beside the resource; the caller handles the failure where it can decide what to do next.
// A bounded channel carries values between worker threads.
Channel lines = auto Channel.new(<string>, 4);
Map counts = {};
// Thread.run starts every worker and joins them all before returning.
Thread.run([
%!(void) => {
foreach (String line in %("tea and cake" "cake and more cake"))
lines.send(line);
lines.close();
},
%!(void) => {
foreach (String line in lines)
foreach (String word in line.words()) counts[word] += 1;
}
]);
printf("cake: %s, tea: %s\n", counts["cake"], counts["tea"]);View complete example →Concurrently yours.
Channels connect a producer and consumer. One worker updates the counts, and the caller reads the result after joining. Ownership and communication remain visible in the code.
// Import the package under a name you choose.
import "pcre2" as rx;
// Compile a pattern with named captures; release it on exit.
auto rx.Regexp request = rx.Regexp.compile(
"^(?<method>[A-Z]+) (?<path>/[^ ]+)$", 0);
// Sample requests include lines the pattern will ignore.
String text = $dedent(%"
GET /docs
POST /build
-- idle --
DELETE /cache
GET missing-slash
");
foreach (String line in text.lines()) {
rx.RegexpMatch found = request.match(line);
if (found)
puts(%"$(found[<method>]) requests $(found[<path>])");
}View complete example →The whole package.
Import PCRE2 under the name rx, compile a pattern, and read named captures. Package types and methods work alongside ordinary x2c Strings, iteration, and scoped cleanup.
More in the docs: collections, iteration, scopes, match, threads, exceptions, and packages.
Code is Magic
Keep the values. Change how you program. Evaluate Lisp alongside compiled code, use macros to generate repeated definitions, and add constructs that fit your problem. One language. One data model. New ways to program.
int seats_left(String plan) => plan == "pro" ? 25 : 2;
// Expose an ordinary typed function to the runtime interpreter.
auto Lisp lisp = Lisp.new();
lisp.bind("seats-left", seats_left);
// Keep the party together, or admit as many people as fit.
List together = %(lambda (plan n)
(if (<= n (seats-left plan)) n 0));
List split = %(lambda (plan n)
(if (<= n (seats-left plan)) n (seats-left plan)));
// Supply either policy as data to the same evaluator.
Var plan = "free", guests = 12;
int whole = lisp.eval(%($together $plan $guests));
int partial = lisp.eval(%($split $plan $guests));
printf("together: %d; split: %d\n", whole, partial);View complete example →Lisp and learn.
Lisp uses the same Vars, Strings, Lists, and other values as compiled x2c. No separate data model or conversion layer stands between them. Bind a typed native function, then pass ordinary values through an editable Lisp policy. Here, each policy is a List, and the evaluator calls seats_left in the compiled host program. Change the policy without changing the evaluator.
See expanded example: Embed scripting
// Request operations from the declared fields.
class Point { int x, y; };
typedef struct Person { String name; Point home; } Person;
$derive(Point, <map>);
$derive(Person, <json>, <equal>, <repr>);
// Map conversion preserves the nested record.
Person ada = { "Ada", { 3, 4 } };
Map fields = ada.to_map();
Person copy = Person.from_map(fields);
printf("equal: %d\n%s\n", ada.equal(copy), copy.repr());
// The same fields also make a JSON round trip.
String text = ada.json();
Person restored = Person.from_json(text);
printf("JSON equal: %d\n", ada.equal(restored));View complete example →The rewrite stuff.
Use shipped macros without writing a generator. $derive works with value classes and ordinary struct typedefs. Point gets equality and representation from its class declaration; Person requests them explicitly. The generated operations preserve nested fields through Map and JSON conversions.
// One template generates both directions of JSON conversion.
macro Unit $json.record(Type $type, Expr $read) {
using $value, $text;
String $type.json($type $value) => ((Var) $value.to_map()).json();
$type $type.from_json(String $text) =>
$read(Json.parse($text).map());
}
// Apply the template to a type that already converts to and from Maps.
class Point { int x, y; };
$derive(Point, <map>);
$json.record(Point, Point.from_map);
Point start = Point.new(3, 4);
String text = start.json();
Point copy = Point.from_json(text);
printf("%s\nequal: %d\n", copy.repr(), start == copy);View complete example →Just my prototype.
A macro template receives syntax and produces declarations. Supply a type and its Map reader to generate a pair of ordinary functions. This example adapts the JSON conversion template used by $derive. using gives the generated parameter names fresh private identities.
macro Decorator $trace(Function $function) {
printf("enter %s\n", $Code.name($function));
defer printf("leave %s\n", $Code.name($function));
@Code.body($function)
}
$trace()
int answer(void) => 42;
// Prints "enter answer", then "leave answer".
int result = answer();View complete example →Highly decorated.
A decorator is a macro that receives the declaration, statement, or expression that follows it. Here it adds tracing around a function body. The function keeps its ordinary calling interface while the transformation supplies the repeated entry and exit work.
macro Decorator $control.with_lock(Stmt $body, Expr $lock) { {
Mutex held = $lock;
held.lock();
defer held.unlock();
$body
} }
keyword with_lock $control.with_lock;
auto Mutex mutex = Mutex.new();
try with_lock(mutex) { raise %(oops); }
catch %(oops):
puts("caught, and the lock is already free");View complete example →One good term deserves another.
Turn locking and cleanup into a statement. The decorator introduces the held lock and its deferred release, so the body can concentrate on the operation being protected.
keyword gives a macro an ordinary word spelling. This is, in fact, how some of the built-ins of the language are implemented. The compiler prelude defines class and foreach through keyword aliases backed by compiler helpers. Your program can use the same mechanism.
import "x2cui" with App, Ui;
App app = auto App.open(title: "Counter", width: 360, height: 240);
int clicks = 0;
while (app.frame()) {
Ui ui = app.ui();
ui.column (pad: 24, gap: 12) {
ui.heading("A tiny counter", 2);
if (ui.button("Add one", variant: primary))
clicks++;
ui.text(%"Clicked $clicks times.");
}
}View complete example →A C change.
One import brings in a UI notation: block containers, named options, and short option values. The package generates these forms at compile time from CUI’s declarations. Your program uses the extension alongside ordinary C control flow; the compiler needs no UI-specific feature.
typedef struct Reading { int celsius; String station; int gusts; } Reading;
// The compiler hands a meta function the fields of a struct type.
meta static List show_fields(List receiver, TypeInfo type) {
Array lines = [];
foreach (List field in type.assoc(<fields>)) {
String name = field.car();
List label = $!String{ $name };
lines.push($!Stmt{ printf("%s = %s\n", $label, (Var) $receiver.$name); });
}
return $!Stmt{ { @(lines.list_free()) } };
}
// The macro captures the expression; the meta function writes the code.
macro Stmt $show(Expr $value) => $show_fields($value, $value);
Reading noon = { 21, "roof", 12 };
$show(noon);View complete example →It takes one to code one.
A meta function runs ordinary x2c during translation. It can inspect types and captured syntax, use ordinary runtime operations, and construct the code the compiler inserts. Here, the macro captures an expression and the meta function generates statements from its fields.
meta static List responses(void) =>
%((200 "OK") (404 "Not Found") (503 "Unavailable"));
meta static int response_count(void) => responses().len();
meta static List setup(void) {
Array steps = [];
int i = 0;
foreach (List row in responses()) {
steps.push($!{
codes[$i] = $(row[0]);
labels[$i] = $(row[1]);
});
i++;
}
List statements = steps.list_free();
return $!{ @statements };
}
int codes[$response_count()];
String labels[$response_count()];
$setup();
for (int i = 0; i < $response_count(); i++)
printf("%d: %s\n", codes[i], labels[i]);View complete example →Block and roll.
The compiler runs setup, which builds one code block for each table row. The $!{ ... } literal quotes code; $i and $(row[0]) insert values, and @statements splices the accumulated blocks into the result. $setup() inserts those assignments into main. $response_count() sizes both arrays and sets the loop bound from the same table. The finished program uses ordinary C arrays; the generation loop runs only during compilation.
import "autodiff";
$ad.reverse()
static double energy(double x, double y, int n) {
double s = 0.0;
for (int i = 0; i < n; i++) {
if (i == 2)
continue;
s += x * x * (double) i;
}
return sin(s) / x - exp(y);
}
double dx, dy;
double value = energy_grad(1.0, 2.0, 5, &dx, &dy);View complete example →Derive me crazy.
At compile time, $ad.reverse() transforms this function into energy_grad: native code that computes the value and both partial derivatives. The transformation handles the loop, branch, and mathematical operations together. Write the calculation once; the package generates its derivative code. The complete example checks the result against a finite difference.
See expanded example: Differentiate a function
More in the docs: protocols, macros and meta functions, runtime Lisp, self-hosting, compiler inspection, and architecture.
Install x2c
x2c is experimental. Expect changes between releases.
Platforms. macOS 15 or later (arm64, x86_64); Linux with glibc 2.38 or later on x86_64 or arm64 (aarch64); Windows through WSL2.
curl -fsSL https://x2c-lang.dev/install.sh | sh
export PATH="$HOME/.local/x2c/bin:$PATH"
x2c run ~/.local/x2c/examples/foreach.xInstall native binaries. One command downloads the compiler, runtime, headers, and examples for your platform into ~/.local/x2c. The installer needs a C compiler named cc. See the package installation instructions to add packages. The release notes list what changed and how to upgrade.
Or build from source. Follow the source installation instructions to build a checkout and install x2c into your home directory.
Put packages to work
Draw a chart, build a desktop or terminal app, query data, or train a model. Below is one working example from each of ten packages, with code, its result, and the complete source and setup instructions.
Packages give libraries their own namespaces, so you can use them together without name collisions. Build once, then import by name. Shims and adapters add idiomatic x2c types and methods while keeping the native API available; Lisp bindings and decorators can extend the language itself.
Browse packages or learn how to import one.
# From your x2c checkout
make build-safe
./configure --packages raylib
make -C packages/raylib short-example
cd packages/raylib
./builds/climate-trends
# Result: builds/climate-trends.png
Packages need their native libraries prepared first. Release bundles cover macOS and Linux on arm64 and x86_64; torch bundles cover macOS arm64 and Linux x86_64 only. raylib, SQLite, and x2cui have no release bundle and build from a source checkout.
import "torch" with Torch, Tensor, Module, Optimizer;
static Module _mlp(void) {
Module model = Module.composed();
model.register("l1", Module.linear(4, 8));
model.register("l2", Module.linear(8, 1));
return model;
}
// _affine(layer, x) is x.matmul(weight.t()) + bias.
static Tensor _forward(Module model, Tensor x) =>
_affine(model.child("l2"), _affine(model.child("l1"), x).tanh());
Module model = _mlp();
Optimizer adam = Optimizer.adam(model, 0.05);
for (int step = 0; step < 200; step++) {
auto {
Tensor pick = Torch.randperm(64).narrow(0, 0, 16);
adam.zero_grad();
Tensor guess = _forward(model, x.index_select(0, pick));
Tensor error = Tensor.mse_loss(guess, y.index_select(0, pick));
error.backward();
adam.step();
}
}
model.save("builds/mlp.pt");
// torch.load reads it in Python.Weight for it.
Register two linear layers, write the forward pass in x2c, and train
with Adam. Each step releases its temporary tensors. Save the named
weights and biases for Python to read with torch.load.
The complete example supplies training data and checks that reloading preserves the result:
trained loss 0.024875
reloaded loss 0.024875
Uses PyTorch’s libtorch: CPU or MPS on macOS arm64, CPU on Linux x86_64. The prepared libraries are required at runtime.
See expanded example: Recognize digits
import "raylib";
Image chart = Image.new(2160, 960, paper);
defer chart.free();
// ... draw the title and the temperature grid ...
Vector2 origin = { 84, 252 }, previous = { 0 };
int index = 0;
foreach (int high, highs) {
Vector2 offset = { index * 94, -(high - 60) * 6 };
Vector2 point = origin + offset;
if (index) {
// ... fill the area below the segment ...
chart.draw_line(previous.scale(3), point.scale(3), 9, teal);
}
previous = point;
index++;
}
// ... draw labels with the bundled TrueType font ...
chart.resize(1440, 640);
chart.export(output);Plot twist.

Turn seven daily temperatures into a PNG with ordinary vectors, Lists, and drawing methods. Each temperature becomes a point; lines join the points over a pale filled area, and labels mark the days and highs. The complete program draws this chart into an image and exports it as a PNG. It initializes a small window before loading the font.
raylib has no release bundle. Build it from a checkout with
make -C packages/raylib run.
import "termbox2" with Termbox;
static void _draw(Termbox terminal, ArrayChar cells,
int width, int height) {
terminal.clear();
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++) {
if (!cells[y * width + x])
continue;
int run = 1;
while (x + run < width && cells[y * width + x + run])
run++;
terminal.fill(x, y, run, 1, "#",
TB_GREEN | TB_BOLD, TB_DEFAULT);
x += run - 1;
}
terminal.present();
}Terminal velocity.

Conway’s Game of Life fills the terminal with a changing world. The drawing function paints adjacent living cells in one call, then presents the frame. The complete program starts with random cells, advances each generation, handles resizing, and exits on a keypress.
See expanded example: Game of Life in a TTY
import "sqlite" with Database, Prepared;
// The database and table are already open.
Prepared insert =
auto db.prepare("INSERT INTO observation VALUES (?, ?, ?)");
foreach (List reading, %(
("/guide" 200 12000)
("/reference" 503 40000)
("/source" 200 3100000)
)) insert.bind(@reading).execute();
Prepared report = auto db.prepare(
$dedent(%"
SELECT url, status, us
FROM observation
WHERE status >= 400 OR us > ?
ORDER BY us DESC
")
);
report.bind(3000000);
foreach (List row, report)
printf("%s", %"$(row[0]): HTTP $(row[1]), $(row[2]) us\n");A SELECT few.
Query endpoint observations with a bound parameter, then iterate over copied row Lists. The report selects requests that either failed or took more than three seconds, with the slowest first. Bind the threshold as a value to change it without rebuilding the SQL string.
The complete example creates an in-memory database and inserts three
observations. Two need attention: /source succeeds but takes 3.1 seconds;
/reference returns HTTP 503. The fast, successful /guide request stays
out of the report. Automatic cleanup releases each statement and closes
the database.
Output:
/source: HTTP 200, 3100000 us
/reference: HTTP 503, 40000 us
SQLite has no release bundle. Build it from a checkout with
make -C packages/sqlite run.
import "yyjson" as json;
auto {
Map config = json.Json.read_file("examples/services.json");
Array services = config["services"];
Array unhealthy = [];
foreach (Map service, services) {
String mark = service["healthy"].truth() ? "ok" : "DOWN";
printf("%s", %" $(service["name"]):$(service["port"]) $mark\n");
if (!service["healthy"].truth())
unhealthy.push(service["name"]);
}
Var report = unhealthy;
json.Json.write_file(report, "/tmp/unhealthy.json");
}JSON and the Autobots.
Read a JSON file into ordinary Maps and Arrays, then use the same
indexing and iteration as any other x2c collection. Each service supplies
a name, port, and health flag; the report marks it ok or DOWN.
Collect the unhealthy names in a new Array and write it back as JSON.
Here, only release-worker needs attention. The saved file contains that
single name, ready for another program to read.
Full example output:
region us-west, 3 services
artifact-api:8080 ok
release-worker:9100 DOWN
docs-site:443 ok
wrote ["release-worker"] to /tmp/unhealthy.json
import "pcre2" with Regexp, RegexpMatch;
Regexp entry = auto Regexp.compile(
"^(?<time>\\d\\d:\\d\\d:\\d\\d) "
"(?<program>\\w+)\\[\\d+\\]: (?<text>.*)$",
0
);
Regexp fields = auto Regexp.compile("\\s*\\|\\s*", 0);
Map counts = {};
foreach (String line, %(
"09:14:02 sshd[441]: accepted key | user=ada | port=22"
"09:14:07 cron[88]: ran backup | status=ok"
"09:15:31 sshd[512]: refused password | user=root | port=22"
"-- rotated --"
)) {
RegexpMatch found = entry.match(line);
if (!found) continue;
Var seen = 0;
counts.try_get(found[<program>], seen);
counts[found[<program>]] = seen + 1;
printf("%s %s\n", found[<time>], found[<program>]);
foreach (String field, fields.split(found[<text>]))
printf(" %s\n", field);
}Matchmaker, matchmaker.
Named captures pick out the time, program, and message from each log entry. Access captures by name, then split the message on vertical bars, consuming the surrounding whitespace. Lines that do not match, such as the log’s rotation marker, are skipped.
The first parsed entry appears below. The complete example also counts
entries in a Map and prints a summary: two from sshd and one from
cron.
First entry’s output:
09:14:02 sshd
accepted key
user=ada
port=22
import "libcurl" with CurlBatch, CurlEasy;
static String page_title(String html) {
return html.split("<title>").last().string()
.split("</title>").car();
}
List pages = %("/guide" "/reference" "/source");
CurlEasy curl = auto CurlEasy.new().timeouts(1000, 3000);
List urls = pages.map(%!(String page) => site + page);
CurlBatch batch = auto curl.get_all(urls, 3);
for (int i = 0; i < batch.len(); i++)
printf("%s: %s\n", pages[i].string()[1:],
page_title(batch.response(i).text()));Page turners.
Fetch three URLs concurrently and print their page titles. A lambda
joins each page path to the site’s base URL; get_all runs the batch
with up to three transfers at once. Read each response body as a String
and extract its title.
The complete example accepts the site URL on the command line. This captured run uses the package’s local fixture pages.
Output:
guide: x2c Language Guide
reference: x2c Reference
source: x2c Source
import "libuv" with UvLoop, UvProcess;
UvLoop loop = auto UvLoop.new();
UvProcess normalized =
auto loop.spawn(%("/usr/bin/tr" "[:lower:]" "[:upper:]"));
normalized.write($dedent(%"
alpha
beta
gamma
")).close_stdin();
UvProcess counted = auto loop.spawn(%("/usr/bin/wc" "-l"));
// ... write the same three lines and close its input ...
loop.run(UV_RUN_DEFAULT);
printf("normalized:\n");
foreach (String line, normalized.stdout().lines())
printf(" %s\n", line);
printf("line count: %s", counted.stdout());Spawn to be wild.
Start two child processes and send each the same three lines. tr
converts them to uppercase while wc counts them. Close each input
stream so the commands can finish, then run the event loop to collect
their output and exit statuses.
Both children start before the loop runs. Their captured output remains available afterward, and both exit successfully. The complete example also prints their process IDs before collecting the results.
Output after the process IDs:
normalized:
ALPHA
BETA
GAMMA
line count: 3
exits: normalized=0 counted=0
import "blis" with Blis, BlisObject;
// links is the matrix; ones is a vector of ones.
BlisObject rank = auto BlisObject.copy_vector(
%(0.2 0.2 0.2 0.2 0.2), BLIS_DOUBLE
);
double shift = 1.0;
int round = 0;
for (; shift > 1e-15 && round < 100; round++) {
auto {
BlisObject next = links.matmul(rank);
next = next.scale(1.0 / next.dotv(ones));
shift = (next - rank).normfv();
rank.copy_from(next);
}
}
printf("converged after %d rounds, shift %.1e\n", round, shift);Rank you very much.
Multiply a link matrix by a rank vector, normalize the scores, and
repeat until they converge. matmul multiplies the matrix and vector;
ordinary operators handle the remaining arithmetic. Each round copies
the new scores into the retained rank vector and releases its temporary
values.
The complete example builds a five-page graph and starts every page
with equal rank. After 53 rounds, index leads. The blog has no incoming
links, so its score falls to zero.
Full example output:
converged after 53 rounds, shift 7.9e-16
index 0.3333
guide 0.3056
reference 0.2778
download 0.0833
blog 0.0000
import "x2cui" with App, Offscreen, TextField, Ui;
ui.table ("orders", sort: &s.sort, selectable: true,
columns: {"Order": 90, "Customer": fill,
"Date": unsorted(90), "Status": 120,
"Amount": right(110)})
ui.each (Order o in shown, key: o.id)
ui.table_row (row, selected: s.selected == o) {
if (row.clicked)
s.selected = o;
ui.cell_text(o.id);
ui.cell () {
ui.avatar(o.customer, size: 28);
ui.column (gap: 0, width: fill) {
ui.text(o.customer, font: medium, nowrap: true);
ui.text(o.email, size: 12,
color: text_secondary, nowrap: true);
}
}
ui.cell_text(o.date);
ui.cell ()
ui.badge(o.status, tone: o.tone, dot: true);
ui.cell_text(o.price);
}UI complete me.

x2cui provides an x2c interface to CUI’s drawn components. Define table columns with a Map, then compose each row from text, avatars, and badges. The complete orders example sorts columns, selects rows, and draws pagination. This image comes from its off-screen renderer.
The package is experimental and source-only.
Go further.
About x2c tells its story. Read the docs to learn the language and look up its library. Browse the source to see how it works or make it your own.
Repository counts from make stats.
code / comment lines in the core compiler.
code / comment lines in the library source.
10 command programs, including build/run, lint, graph analysis, and language server.
14 components implementing language features with macros and rewrite rules. Code / comment lines.
unit tests.
compiler fixtures.
showcase examples.
integrations with working examples.