x2c

Everyday values and operations.

Values, text, and collections. Read down the page or choose an example from the index.

var

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.

examples/love/values.xlink
#include <assert.h>

// One parameter and result type; behavior follows the contained value.
Var twice(Var value) => value + value;

int main(void) {
  // 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);
  return 0;
}

Actual output

Expected output

42 haha
integer object
sold out

Run locally: x2c run examples/love/values.x

names

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.

examples/love/symbols.xlink
int main(void) {
  // 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;
  }
  return 0;
}

Actual output

Expected output

same name: 1
flag: 1; name: ready
waiting for a worker

Run locally: x2c run examples/love/symbols.x

text

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.

examples/love/strings.xlink
#include <assert.h>
#include <string.h>

int main(void) {
  // 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];
  assert(padded == "  hello  " && word == "hello" && loud == "HELLO");

  // 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));
  return 0;
}

Actual output

Expected output

same text
h: HELLO (5 bytes)
C sees 5 bytes

Run locally: x2c run examples/love/strings.x

collections

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.

examples/love/collections.xlink
#include <assert.h>

int main(void) {
  // Immutable Lists share tails and mix value kinds.
  List order = %("tea" 3 2.5), labeled = cons(<order>, order);
  assert(labeled.cdr() == order);

  // Arrays grow and change in place.
  Array basket = ["tea", 3, 2.5];
  basket[1] += 1;
  basket.push(<packed>);
  assert(basket == ["tea", 4, 2.5, <packed>]);

  // Maps find values by key.
  Map details = {name: "tea", quantity: 3, price: 2.5};
  details[<quantity>] += 1;
  assert(basket[1] == details[<quantity>]);
  printf("%s\n%s\n%s: %s\n",
         labeled.repr(), basket.repr(),
         details[<name>], details[<quantity>]);
  return 0;
}

Actual output

Expected output

(order "tea" 3 2.5)
[ "tea", 4, 2.5, <packed> ]
tea: 4

Run locally: x2c run examples/love/collections.x

literals

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.

examples/love/literals.xlink
#include <assert.h>

int main(void) {
  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 } }
    ]
  };
  Map venue = workshop[<venue>];
  Map address = venue[<address>];
  Array hosts = workshop[<hosts>];
  Map host = hosts[0];
  Map pricing = workshop[<pricing>];
  Array sessions = workshop[<sessions>];
  Map first = sessions[0], last = sessions[2];
  Map project = first[<project>], audio = last[<audio>];
  assert(venue[<seats>] == 24 && address[<city>] == "Bristol");
  assert(host[<skills>] == %(graphics games));
  assert(pricing[<student>] == 15.0 && pricing[<currency>] == "GBP");
  assert(project[<width>] == 320 && audio[<volume>] == 0.75);
  assert(workshop[<topics>] == %(graphics sound games));
  printf("%s at %s, %s\n", workshop[<title>], venue[<name>], address[<city>]);
  printf("%s teaches %s\n", host[<name>], first[<title>]);
  printf("student ticket: %.2f %s\n", (double) pricing[<student>], pricing[<currency>]);
  return 0;
}

Actual output

Expected output

Make a tiny game at The Maker House, Bristol
Ada teaches Draw a world
student ticket: 15.00 GBP

Run locally: x2c run examples/love/literals.x

two tests

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.

examples/love/two-kinds.xlink
#include <assert.h>

int main(void) {
  // 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>]);
  return 0;
}

Actual output

Expected output

1 2 3

Run locally: x2c run examples/love/two-kinds.x

files

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.

examples/love/files.xlink
#include <stdlib.h>
#include "path.x"

// The checked-in data sits beside the examples wherever they live.
String example_data(String name) {
  Path source = String.new(__FILE__);
  return source.dirname().join("../data", name);
}

int main(int argc, char **argv) {
  String path = argc > 1 ? argv[1]
                        : example_data("love-files/quantities.txt");

  // 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);
  return 0;
}

Actual output

Expected output

whole file (13 bytes):
1 2 3

4 5 6
total: 21

Run locally: x2c run examples/love/files.x

loops

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.

examples/love/loops.xlink
#include "path.x"

String example_data(String name) {
  Path source = String.new(__FILE__);
  return source.dirname().join("../data", name);
}

int main(int argc, char **argv) {
  Path directory = argc > 1 ? argv[1] : example_data("love-files");
  Path path = directory.join("quantities.txt");

  // 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);
  return 0;
}

Actual output

Expected output

score: 3
score: 4
score: 5
Ada
Grace
stock: 2
tea
and
cake
coffee
and
biscuits
1
2
3
4
5
6

Run locally: x2c run examples/love/loops.x

memory

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.

examples/power/scopes.xlink
auto int item_count(void) { // Reclaim on return.
  return ["red", "green", "blue"].len();
}

int main(void) {
  auto Array owned = [1, 2]; // Clean up the value held on exit.
  Map counts = auto {files: 2}; // Clean up the acquired value.
  printf("items: %zu, files: %d\n",
         owned.length, (int) counts[<files>]);

  auto { // Reclaim this region's allocations together.
    Array temporary = [1, 2, 3];
    printf("region: %zu\n", temporary.length);
  }

  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.
  printf("function: %d\n", item_count());
  return 0;
}

Actual output

Expected output

items: 2, files: 2
region: 3
destination: 3
function: 3

Run locally: x2c run examples/power/scopes.x

lists

cons prepends a value while sharing the original List tail. Equal Lists share canonical structure, making equality a pointer comparison. List.map, List.filter, and List.foldl compose without changing their inputs. Nested literals and destructuring keep the resulting data as readable as the operations that produce it.

examples/love/lists.xlink
#include <assert.h>

int main(void) {
  // Prepend in constant time, sharing the original tail.
  List prices = %(3 5 8), extended = cons(2, prices);
  assert(extended.cdr() == prices && extended == %(2 3 5 8));

  // Compose transformations without changing either input.
  List totals = extended.map(%!(price) => price * 2);
  List selected = totals.filter(%!(total) => total >= 10);

  // Unpack values, then fold them into a single result.
  Var (first, second) = selected;
  Var sum = selected.foldl(0, %!(a, b) => a + b);
  printf("selected: %s + %s = %s\n", first, second, sum);

  // A literal can combine names, computed values, and nested Lists.
  puts(%(total $sum items $selected).repr());
  puts(%"original: $(prices.repr()); extended: $(extended.repr())");

  // car gets the first value; cdr gets the rest, spliced with @.
  List parts = %((first $(selected.car())) (rest @(selected.cdr())));
  puts(parts.repr());
  return 0;
}

Actual output

Expected output

selected: 10 + 16 = 26
(total 26 items (10 16))
original: (3 5 8); extended: (2 3 5 8)
((first 10) (rest 16))

Run locally: x2c run examples/love/lists.x

arrays

Array combines indexed access, growth, slicing, and functional operations. Array.copy creates a separate sequence; Array.sort and Array.reverse mutate it. Assignment shares the object, == compares contents, and === compares identity. Copies and slices are shallow: nested objects remain shared.

examples/love/arrays.xlink
#include <assert.h>

int main(void) {
  // Grow and update a sequence in place.
  Array scores = [7, 3, 9];
  scores.push(5); scores[1] += 1;

  // Sorting mutates; copy first to keep the original order.
  Array ranked = scores.copy().sort().reverse();
  assert(scores == [7, 4, 9, 5] && scores !== ranked);

  // Slices and map create new Arrays.
  Array top = ranked[:2];
  Array boosted = top.map(%!(score) => score + 1);
  Var total = boosted.foldl(0, %!(a, b) => a + b);
  printf("scores: %s; ranked: %s\n", scores.repr(), ranked.repr());

  // Use indexed access or iterate over the resulting values.
  foreach (int score in boosted)
    printf("%d ", score);
  printf("=> total %s, best %s\n", total, boosted[0]);
  return 0;
}

Actual output

Expected output

scores: [ 7, 4, 9, 5 ]; ranked: [ 9, 7, 5, 4 ]
10 8 => total 18, best 10

Run locally: x2c run examples/love/arrays.x

maps

Map grows as entries are added, with brackets for reads and updates. Map.getdefault supplies a fallback without inserting; Map.try_get distinguishes a missing key from a stored zero. Map traversal order is unspecified, so this example sorts the keys before printing their values.

examples/love/maps.xlink

int main(void) {
  // Start with named items and their stock quantities.
  Map stock = {"tea": 12, "coffee": 8, "milk": 6, "sugar": 0};

  // Update existing entries or add new ones with the same syntax.
  stock["tea"] -= 2;
  stock["coffee"] += 5;
  stock["cocoa"] = 4;

  // Fetch a value directly, or supply a fallback without inserting.
  printf("tea: %s; biscuits: %s\n",
    stock["tea"],
    stock.getdefault("biscuits", 0));

  // A stored zero is different from an absent key.
  Var sugar;
  if (stock.try_get("sugar", sugar))
    puts(%"sugar is stocked: $sugar remaining");

  // Sort the keys to visit each value in a predictable order.
  Array items = auto stock.keys().array().sort();
  foreach (String item in items)
    puts(%"$item: $(stock[item])");
  return 0;
}

Actual output

Expected output

tea: 10; biscuits: 0
sugar is stocked: 0 remaining
cocoa: 4
coffee: 13
milk: 6
sugar: 0
tea: 10

Run locally: x2c run examples/love/maps.x

methods

Point.new and Point.move give a user-defined type the same calling style as the built-ins. Type-qualified names let other types define their own methods without collisions. Dot notation works for both fields and method calls; the compiler supplies the receiver argument.

examples/love/methods.xlink
#include <assert.h>
// Define a type with its own named methods.
typedef struct Point { int x, y; } *Point;

// Allocate a Point in the current Scope.
Point Point.new(int x, int y) {
  Point point = xmalloc(sizeof(struct Point));
  point.x = x; point.y = y;
  return point;
}

// Fields and methods both use dot notation.
void Point.move(Point point, int dx, int dy) {
  point.x += dx; point.y += dy;
}

int main(void) {
  // Create and move a Point with compact dot calls.
  Point point = Point.new(1, 2);
  assert(point.x == 1 && point.y == 2);
  printf("start: (%d, %d)\n", point.x, point.y);
  point.move(3, 4);
  assert(point.x == 4 && point.y == 6);
  printf("moved: (%d, %d)\n", point.x, point.y);
  return 0;
}

Actual output

Expected output

start: (1, 2)
moved: (4, 6)

Run locally: x2c run examples/love/methods.x