x2c

Language walkthrough

Start with Var and progress through collections, functions, types, operators, patterns, macros, and cooperating threads.

See x2c essentials for the main distinctions or consult the syntax map.

Values and types

Use a Var in arithmetic, convert it to an int, and assign a string to the same variable.

View source.

examples/tours/language/values.xlink
/* Var carries a runtime tag. Typed destinations request conversions;
   ordinary int arithmetic remains native C arithmetic. */
int main(void) {
  Var value = 42;
  value += 1;
  int count = value;
  double half = count / 2.0;
  printf("Var value: %s\nNative int: %d\nHalf: %.1f\n", value, count, half);
  value = "ready";
  printf("New Var value: %s\nString tag: %d\n", value, value is String);
  return 0;
}

Actual output

Expected output

Var value: 43
Native int: 43
Half: 21.5
New Var value: ready
String tag: 1

Run locally: x2c run examples/tours/language/values.x

Names and text

Build a string, slice its first five characters, and look up a symbol in a set.

View source.

examples/tours/language/text.xlink
#include "system-macros.x"

/* Symbols encode short names. Atoms also represent longer exact names.
   Strings are immutable, canonical text; + and slices produce values. */
int main(void) {
  Symbol phase = <ready>;
  Atom name = %(a-name-too-long-for-a-symbol).car();
  SymbolSet phases = %<ready running done>;
  String greeting = "hello" + " world", expected = "hello world";
  puts($dedent(%"
    Greeting: $greeting
    Slice: $(greeting[0:5])
    Phase: $phase
    Long atom: $name
    Phase index: $(phases.index(phase))
    Equal strings: $(greeting == expected)
    Identical strings: $(greeting === expected)"));
  return 0;
}

Actual output

Expected output

Greeting: hello world
Slice: hello
Phase: ready
Long atom: a-name-too-long-for-a-symbol
Phase index: 0
Equal strings: 1
Identical strings: 1

Run locally: x2c run examples/tours/language/text.x

Collections and literals

Build lists, arrays, and maps, then check how quoting affects their contents and how copies share them.

View source.

examples/tours/language/collections.xlink
#include "system-macros.x"

/* Lists are immutable and share tails. Arrays and Maps are mutable; copying
   a handle shares its object. Percent literals quote names as data. */
int main(void) {
  int n = 2;
  List quoted = %(n $n $(n + 1));
  List evaluated = $(n, n + 1), extended = %(1 @evaluated);
  Array numbers = [1, n, n + 1], shared = numbers;
  shared[0] = 9;
  String key = "answer";
  Map named = {key: n}, computed = ${key: n};
  puts($dedent(%"
    Quoted list: $(quoted.repr())
    Evaluated list: $(evaluated.repr())
    Extended list: $(extended.repr())
    Array: $(numbers.repr())
    Last item: $(numbers[-1])
    Slice: $(numbers[1:].repr())
    Bare keys: $(named.keys().list().repr())
    Computed keys: $(computed.keys().list().repr())
    Computed key present: $(key in computed)
    Shared list tail: $(extended.cdr() === evaluated)
    Shared array: $(numbers === shared)"));
  // Quoted Array/Map contents follow the same data-reading rule.
  Array tags = %[ready, done];
  Map settings = %{mode: fast};
  puts($dedent(%"
    Quoted array: $(tags.repr())
    Quoted map mode: $(settings[<mode>])"));
  return 0;
}

Actual output

Expected output

Quoted list: (n 2 3)
Evaluated list: (2 3)
Extended list: (1 2 3)
Array: [ 9, 2, 3 ]
Last item: 3
Slice: [ 2, 3 ]
Bare keys: (key)
Computed keys: ("answer")
Computed key present: 1
Shared list tail: 1
Shared array: 1
Quoted array: [ <ready>, <done> ]
Quoted map mode: fast

Run locally: x2c run examples/tours/language/collections.x

Iteration and absence

Skip an item during iteration, unpack a list, and check whether a map contains a stored zero.

View source.

examples/tours/language/iteration.xlink
#include "system-macros.x"

/* foreach converts each item to the declared type. try_get reports presence
   separately from its output: a stored zero is still a present value. */
int main(void) {
  List numbers = %(1 2 3 4);
  int total = 0;
  foreach (int n in numbers) {
    if (n == 2) continue;
    total += n;
  }
  (int first, String label) = %(7 "seven");
  Map counts = {zero: 0};
  Var found;
  int present = counts.try_get(<zero>, found);
  puts($dedent(%"
    Sum after skipping 2: $total
    Unpacked number: $first
    Unpacked label: $label
    Zero key present: $present
    Stored value: $found
    Missing key present: $(<missing> in counts)"));
  // False does not mean absent: empty containers and numeric zero are false.
  Array empty = [];
  printf("Empty array is true: %d\nNull differs from void: %d\n",
         empty ? 1 : 0, (Var) NULL !== void);
  return 0;
}

Actual output

Expected output

Sum after skipping 2: 8
Unpacked number: 7
Unpacked label: seven
Zero key present: 1
Stored value: 0
Missing key present: 0
Empty array is true: 0
Null differs from void: 1

Run locally: x2c run examples/tours/language/iteration.x

Functions and closures

Pass a reference, splice positional arguments, and see what changes when a closure captures by reference.

View source.

examples/tours/language/functions.xlink
#include "system-macros.x"

/* References borrow caller storage; call without &. Rest parameters collect
   arguments into a List or Map. @ explicitly splices arguments. */
static int square(int n) => n * n;
static void increment(int &n) => n++;
static List collect(List @items) => items;
static String describe(String name, Map @options) =>
  %"$name: $(options.getdefault(<count>, 1))";

int main(void) {
  int count = 3;
  increment(count);
  List pair = %(2 3);
  puts($dedent(%"
    Square: $(square(count))
    Collected arguments: $(collect(1, @pair).repr())
    Item description: $(describe("items", count: count))"));
  Func snapshot = %!() => count;
  Func update = %!(int n) using &count => count += n;
  count = 10;
  Var old = snapshot(), next = update(2);
  puts($dedent(%"
    Captured value: $old
    Shared value: $next
    Local value: $count"));
  List doubled = pair.map(%!(int n) => n * 2);
  Var total = pair.iter().map(square).foldl(0, %!(int a, int b) => a + b);
  puts($dedent(%"
    Doubled items: $(doubled.repr())
    Sum of squares: $total"));
  return 0;
}

Actual output

Expected output

Square: 16
Collected arguments: (1 2 3)
Item description: items: 4
Captured value: 4
Shared value: 12
Local value: 12
Doubled items: (4 6)
Sum of squares: 13

Run locally: x2c run examples/tours/language/functions.x

Types and methods

Update a counter through a method and read it through a type that delegates to it.

View source.

examples/tours/language/methods.xlink
#include "system-macros.x"

/* A method is a type-qualified function. A reference receiver updates the
   original record. delegate forwards unresolved methods through a field. */
typedef struct Counter { int value; } Counter;
static void Counter.add(Counter &c, int amount) => c.value += amount;
static int Counter.read(Counter c) => c.value;
typedef struct Meter { delegate Counter counter; } Meter;
typedef List Trail;
static Self Trail.record(Self trail, Var item) => cons(item, trail);

int main(void) {
  Counter counter = {2};
  counter.add(3);
  Counter copy = counter;
  copy.add(1);
  Meter meter = {counter};
  Trail trail = %(2);
  trail = trail.record(3).record(4);
  puts($dedent(%"
    Original counter: $(counter.read())
    Copied counter: $(copy.read())
    Delegated counter: $(meter.read())
    Trail after recording: $(trail.repr())"));
  return 0;
}

Actual output

Expected output

Original counter: 5
Copied counter: 6
Delegated counter: 5
Trail after recording: (4 3 2)

Run locally: x2c run examples/tours/language/methods.x

Classes

Move a record, use its value as a map key, and update a node through a copied pointer.

View source.

examples/tours/language/classes.xlink
/* class generates operations for a chosen C representation. Point is a
   record value; Node is a pointer. Record copying is shallow, not
   recursive. */
class Point { int x; int y; };
class Node { int value; } *;
static void Point.move(Point &p, int dx, int dy) { p.x += dx; p.y += dy; }

int main(void) {
  Point point = Point.new(2, 3), copy = point;
  point.move(1, 1);
  Var boxed = point; // Boxing a record copies it into owned storage.
  Map labels = {};
  labels[boxed] = "here";
  printf("Moved point: (%d, %d)\nCopied point: (%d, %d)\nLabel for equal point: %s\n",
         point.x, point.y, copy.x, copy.y, labels[Point.new(3, 4)]);
  Node node = auto Node.new(7);
  Node same = node;
  same.value++;
  puts(%"Shared node: $(node.value)");
  return 0;
}

Actual output

Expected output

Moved point: (3, 4)
Copied point: (2, 3)
Label for equal point: here
Shared node: 8

Run locally: x2c run examples/tours/language/classes.x

Protocols and operators

Give a map-backed set union and intersection operations through protocol adoption.

View source.

examples/tours/language/operators.xlink
#include "system-macros.x"

/* A typedef can reuse storage while defining new operations. Explicit
   adoption connects those methods to a protocol; names alone do not. */
typedef Map Set;
static Set Set.new(List keys) {
  Set set = {};
  foreach (Var key in keys) set[key] = 1;
  return set;
}
static Set Set.add(Set a, Set b) => a.copy().merge(b);
static Set Set.mul(Set a, Set b) =>
  Set.new(a.keys().filter(%!(Var key) => key in b));
protocol Map(T) { T T.add(T, T); T T.mul(T, T); }
protocol Map(Set);

int main(void) {
  Set a = Set.new(%(apple pear)), b = Set.new(%(pear bread));
  Set combined = a + b, common = a * b;
  // Map traversal has no promised order; sort before presenting keys.
  puts($dedent(%"
    Union: $(combined.keys().list().sort().repr())
    Intersection: $(common.keys().list().sort().repr())"));
  return 0;
}

Actual output

Expected output

Union: (apple bread pear)
Intersection: (pear)

Run locally: x2c run examples/tours/language/operators.x

Patterns and templates

Match coordinates and flags, then simplify an addition by building a new list from the captures.

View source.

examples/tours/language/patterns.xlink
/* Match arms try in order without fallthrough. Typed captures test tags,
   not convertibility. A rest capture is a List; $ inserts and @ splices. */
static List simplify(List expression) {
  match (expression) {
    case %(add ?value 0): return %(value $value);
    case %(add ?(int a) ?(int b)): return %(value $(a + b));
    default: return expression;
  }
}

int main(void) {
  List command = %(move (3 4) fast quiet);
  match (command) {
    case %(move (?(int x) ?(int y)) *flags) if (x > 0):
      puts(%"Matched command: $(%(at $x $y @flags).repr())");
    default: puts("No move matched");
  }
  List result = simplify(%(add 2 3));
  if (result ~= %(value ?(int n)))
    puts(%"Simplified value: $n");
  return 0;
}

Actual output

Expected output

Matched command: (at 3 4 fast quiet)
Simplified value: 5

Run locally: x2c run examples/tours/language/patterns.x

Lifetime and errors

Move an array to a longer-lived scope and observe the order of cleanup, catch, and finally.

View source.

examples/tours/language/lifetime.xlink
#include "system-macros.x"

/* A region frees mutable allocations together. Canonical text belongs to a
   pool, normally lasting until shutdown. Containers do not adopt
   references. */
static String make_label(void) {
  auto {
    Buffer out = Buffer.new();
    out.write("ready").write("!");
    return out; // The String conversion interns text before the region ends.
  }
  return NULL;
}

int main(void) {
  puts(%"Label: $(make_label())");
  Scope saved = auto Scope.new();
  Array kept;
  auto {
    Array temporary = [1, 2];
    temporary.move_to(&saved); // Preserve the container beyond this region.
    kept = temporary;
  }
  puts(%"Retained array: $(kept.repr())");
  int level = 1;
  with (level = 9) {
    puts(%"Temporary level: $level");
  }
  alias kept[0] as first;
  first += 4; // An alias substitutes its expression on each use.
  puts($dedent(%"
    Restored level: $level
    Aliased element: $(kept[0])"));
  try {
    defer puts("Cleanup before catch");
    raise %(bad-arg (operation "tour"));
  }
  catch %(bad-arg *details): puts("Caught bad-arg");
  finally puts("Finally");
  return 0;
}

Actual output

Expected output

Label: ready!
Retained array: [ 1, 2 ]
Temporary level: 9
Restored level: 1
Aliased element: 5
Cleanup before catch
Caught bad-arg
Finally

Run locally: x2c run examples/tours/language/lifetime.x

Compile-time code

Compare a runtime call with a compile-time call, then see how two macros resolve the same name.

View source.

examples/tours/language/compile-time.xlink
#include "meta.x"

/* An ordinary call runs now; $ calls a meta function during translation. A
   macro receives syntax. Its declared locals are private per expansion;
   free names resolve at the call site unless kept with using. */
meta static int cube(int n) => n * n * n;
static int factor = 2;
macro Expression $scaled(Expr $n) => $n * factor;
macro Expression $fixed(Expr $n) using factor => $n * factor;

macro Decorator $twice(Stmt $body) {
  { for (int repeat = 0; repeat < 2; repeat++) $body }
}
keyword twice $twice;

// A quotation writes generated code in source form; the hole inserts syntax.
meta static List report_code(List value) =>
  $!{ printf("Generated report: %s\n", (Var) $value); };
macro Stmt $report(Expr $value) => $report_code($value);

int main(void) {
  int n = 3;
  printf("Runtime cube: %d\nCompile-time cube: %d\n", cube(n), $cube(3));
  int factor = 10;
  printf("Caller name result: %d\nKept name result: %d\n", $scaled(3), $fixed(3));
  int total = 0;
  twice { total++; }
  $report(total);
  // Lisp is a runtime library, not the implementation of meta functions.
  Lisp lisp = auto Lisp.new();
  puts(%"Runtime Lisp result: $(lisp.eval(%(+ 2 3)))");
  return 0;
}

Actual output

Expected output

Runtime cube: 27
Compile-time cube: 27
Caller name result: 30
Kept name result: 6
Generated report: 2
Runtime Lisp result: 5

Run locally: x2c run examples/tours/language/compile-time.x

Threads and channels

Feed lines from one worker to another through a bounded channel and read the result after both workers join.

View source.

examples/tours/language/threads.xlink
#include "system-macros.x"

/* One worker writes counts; main reads only after Thread.run joins both.
   The parent owns the Map and Channel throughout. Strings are canonical.
   Channel capacity bounds queued messages, not the canonical-value pool. */
int main(void) {
  Channel lines = auto Channel.new(<string>, 2);
  Map counts = {};
  Thread.run([
    %!() => {
      defer lines.close();
      foreach (String line in %("tea and cake" "more cake")) lines.send(line);
    },
    %!() => {
      foreach (String line in lines)
        foreach (String word in line.words()) counts[word] += 1;
    }
  ]);
  puts($dedent(%"
    Cake: $(counts["cake"])
    Tea: $(counts["tea"])"));
  return 0;
}

Actual output

Expected output

Cake: 2
Tea: 1

Run locally: x2c run examples/tours/language/threads.x