x2c

x2c essentials

Start with dynamic values and native types, then explore sharing, quoted data, classes, protocols, patterns, lifetime, and compile-time code.

Continue with the language walkthrough or read the guide to x2c from C.

Values and conversions

Compare the exact type tags of a Var with the value you get when assigning it to a double.

View source.

examples/tours/essentials/values.xlink
#include "system-macros.x"

/* Dynamic values cross typed boundaries; native types still matter. is
   tests an exact tag. Conversion can succeed without that tag matching. */
int main(void) {
  Var value = 42;
  double converted = value;
  printf("Int tag: %d\nDouble tag: %d\nConverted to double: %.1f\n",
         value is int, value is double, converted);
  Var wide = 42L;
  puts($dedent(%"
    Numeric equality: $(value == wide)
    Identity: $(value === wide)"));
  return 0;
}

Actual output

Expected output

Int tag: 1
Double tag: 0
Converted to double: 42.0
Numeric equality: 1
Identity: 0

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

Immutable values and shared objects

Change an array through a second handle and watch the change appear through the first.

View source.

examples/tours/essentials/sharing.xlink
#include "system-macros.x"

/* Immutable values and mutable objects have different copying rules.
   Canonical Strings and Lists share equal structure. An Array copy here is
   another handle to the same object; mutation is visible through both. */
int main(void) {
  List tail = %(2 3), whole = %(1 @tail);
  Array numbers = [2, 3], same = numbers;
  same[0] = 9;
  puts($dedent(%"
    Shared list tail: $(whole.cdr() === tail)
    Array after mutation: $(numbers.repr())"));
  String greeting = "hello" + " world", expected = "hello world";
  puts(%"Canonical string identity: $(greeting === expected)");
  Map counts = {zero: 0};
  Var found;
  int present = counts.try_get(<zero>, found);
  puts($dedent(%"
    Zero key present: $present
    Stored value: $found
    Missing key present: $(<missing> in counts)"));
  return 0;
}

Actual output

Expected output

Shared list tail: 1
Array after mutation: [ 9, 3 ]
Canonical string identity: 1
Zero key present: 1
Stored value: 0
Missing key present: 0

Run locally: x2c run examples/tours/essentials/sharing.x

Quoting and interpolation

Put a name in a quoted list, insert its value, then splice a whole list into the result.

View source.

examples/tours/essentials/quoting.xlink
#include "system-macros.x"

/* Quoted names are data, not variable reads. $ inserts one value; @ splices
   elements. Bare Map keys name Atoms. */
int main(void) {
  int n = 2;
  List pair = $(n, n + 1);
  printf("Quoted name: %s\nInserted value: %s\n", %(n).repr(), $(n).repr());
  printf("Nested list: %s\nSpliced list: %s\n", %($pair).repr(), %(@pair).repr());
  String key = "answer";
  Map named = {key: n}, evaluated = ${key: n};
  puts($dedent(%"
    Bare keys: $(named.keys().list().repr())
    Evaluated keys: $(evaluated.keys().list().repr())"));
  return 0;
}

Actual output

Expected output

Quoted name: (n)
Inserted value: (2)
Nested list: ((2 3))
Spliced list: (2 3)
Bare keys: (key)
Evaluated keys: ("answer")

Run locally: x2c run examples/tours/essentials/quoting.x

Classes and copying

Move a point through a reference method, then compare what happens when you change a node through a copied handle.

View source.

examples/tours/essentials/classes.xlink
/* Classes choose representations, not an object hierarchy. A record copies
   its fields. A pointer class copies its handle. Reference methods borrow
   the original record; no & is needed at the call. */
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);
  Node node = auto Node.new(7);
  Node same = node;
  same.value++;
  printf("Moved point: (%d, %d)\nCopied point: (%d, %d)\nShared node: %d\n",
         point.x, point.y, copy.x, copy.y, node.value);
  // A record containing an Array would copy that handle, not its contents.
  return 0;
}

Actual output

Expected output

Moved point: (3, 4)
Copied point: (2, 3)
Shared node: 8

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

Protocols and operators

Use + to combine two sets and check that the original set keeps its members.

View source.

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

/* Protocol adoption gives ordinary types shared operations. Set reuses Map
   storage. These methods make + a union, not arithmetic. */
typedef Map Set;
static Set Set.add(Set a, Set b) => a.copy().merge(b);
protocol Map(T) { T T.add(T, T); }
protocol Map(Set);

int main(void) {
  Set a = {apple: 1, pear: 1}, b = {pear: 1, bread: 1};
  Set combined = a + b;
  puts($dedent(%"
    Union: $(combined.keys().list().sort().repr())
    Original set size: $(a.len())"));
  return 0;
}

Actual output

Expected output

Union: (apple bread pear)
Original set size: 2

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

Patterns and templates

Extract two coordinates and the remaining flags, then try the same coordinate pattern with doubles.

View source.

examples/tours/essentials/patterns.xlink
/* A pattern states the structure you need and names its parts. Typed
   captures test tags rather than converting; a double does not match ?(int
   n). Templates then build a result without manual List plumbing. */
int main(void) {
  List command = %(move (3 4) fast quiet);
  match (command) {
    case %(move (?(int x) ?(int y)) *flags):
      puts(%"Matched command: $(%(at $x $y @flags).repr())");
  }
  List real = %(move (3.0 4.0));
  printf("Doubles match the int pattern: %d\n",
         real ~= %(move (?(int x) ?(int y))));
  return 0;
}

Actual output

Expected output

Matched command: (at 3 4 fast quiet)
Doubles match the int pattern: 0

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

Lifetime and cleanup

Keep an array past the end of its allocation region, then watch cleanup run before the error handler.

View source.

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

/* Copying a reference does not keep its owner alive. auto regions free
   allocations; initializer auto cleans an acquired value. Neither is
   garbage collection. A closure also copies handles, not objects. */
int main(void) {
  Scope saved = auto Scope.new();
  Array kept;
  auto {
    Array temporary = [1, 2];
    temporary.move_to(&saved);
    kept = temporary;
  }
  int count = 3;
  Func snapshot = %!() => count;
  Func shared = %!(int n) using &count => count += n;
  count = 10;
  Var before = snapshot(), after = shared(2);
  puts($dedent(%"
    Retained array: $(kept.repr())
    Captured value: $before
    Shared value: $after"));
  // alias substitutes an expression each time; with saves and restores storage.
  alias kept[0] as first;
  first += 4;
  with (count = 99) {
    puts($dedent(%"
      Temporary count: $count
      Aliased element: $(first)"));
  }
  try {
    defer puts("Cleanup before catch");
    raise %(bad-arg (operation "tour"));
  }
  catch %(bad-arg *): puts(%"Caught error. Restored count: $count");
  return 0;
}

Actual output

Expected output

Retained array: [ 1, 2 ]
Captured value: 3
Shared value: 12
Temporary count: 99
Aliased element: 5
Cleanup before catch
Caught error. Restored count: 12

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

Compile-time code

Calculate a cube during translation, repeat a statement with a decorator, and evaluate a Lisp expression at runtime.

View source.

examples/tours/essentials/compile-time.xlink
#include "system-macros.x"

/* The same language computes values and constructs source at compile time.
   meta enables compilation-time calls; $ requests one. Macros capture
   syntax. Declared macro locals are private; free names normally come from
   the caller. */
meta static int cube(int n) => n * n * n;
macro Decorator $twice(Stmt $body) {
  { for (int repeat = 0; repeat < 2; repeat++) $body }
}
keyword twice $twice;

int main(void) {
  int n = 3, total = 0;
  twice { total += cube(n); }
  printf("Compile-time cube: %d\nRuntime total: %d\n", $cube(3), total);
  // Lists can also be executable data. Lisp evaluates them at runtime.
  List expression = %(+ 2 3);
  Lisp lisp = auto Lisp.new();
  puts($dedent(%"
    Lisp result: $(lisp.eval(expression))
    Native result: $(2 + 3)"));
  return 0;
}

Actual output

Expected output

Compile-time cube: 27
Runtime total: 54
Lisp result: 5
Native result: 5

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

Threads

Send two lines through a channel and count their words after both workers finish.

View source.

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

/* Threads share references; joining does not transfer their ownership. The
   parent owns counts. Only the consumer writes it, and main reads after
   both workers finish. Immutable text crosses the channel without copying. */
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/essentials/threads.x