x2c

Extend the language.

Operators, macros, and compile-time code that shape the language.

runtime Lisp

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.

examples/magic/runtime.xlink
#include <assert.h>
#include <lisp-bindings.x>

int seats_left(String plan) => plan == "pro" ? 25 : 2;

int main(void) {
  // 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);
  assert(whole == 0 && partial == 2);
  return 0;
}

Actual output

Expected output

together: 0; split: 2

Run locally: x2c run examples/magic/runtime.x

macros

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.

examples/magic/derive.xlink
#include <derive.x>
#include <assert.h>

// 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>);

int main(void) {
  // 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));
  assert(ada.equal(copy) && ada.equal(restored));
  restored.home.y = 9;
  assert(!ada.equal(restored));
  return 0;
}

Actual output

Expected output

equal: 1
Person{ name: "Ada", home: Point { x: 3, y: 4 } }
JSON equal: 1

Run locally: x2c run examples/magic/derive.x

templates

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.

examples/magic/macros.xlink
#include <derive.x>
#include <assert.h>

// 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);

int main(void) {
  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);
  assert(start == copy);
  return 0;
}

Actual output

Expected output

Point { x: 3, y: 4 }
equal: 1

Run locally: x2c run examples/magic/macros.x

decorators

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.

examples/magic/decorators.xlink
#include <assert.h>
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;

int main(void) {
  // Prints "enter answer", then "leave answer".
  int result = answer();
  assert(result == 42);
  return 0;
}

Actual output

Expected output

enter answer
leave answer

Run locally: x2c run examples/magic/decorators.x

keywords

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.

examples/magic/keywords.xlink
#include <assert.h>
macro Decorator $control.with_lock(Stmt $body, Expr $lock) { {
    Mutex held = $lock;
    held.lock();
    defer held.unlock();
    $body
  } }

keyword with_lock $control.with_lock;

int main(void) {
  auto Mutex mutex = Mutex.new();
  try with_lock(mutex) { raise %(oops); }
  catch %(oops):
  {
    assert(mutex.try_lock());
    mutex.unlock();
    puts("caught, and the lock is already free");
  }
  return 0;
}

Actual output

Expected output

caught, and the lock is already free

Run locally: x2c run examples/magic/keywords.x

extensions

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.

packages/x2cui/examples/counter.xlink
/*  counter.x -- a small interface supplied by an imported package */
import "x2cui" with App, Ui;

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

This program needs a package, so it runs only with the native toolchain.

Expected output

No console output.
Run locally:
make -C packages/x2cui build
./x2c build --package-dir packages \
  --c-include-dir packages/x2cui/deps/include \
  -I packages/x2cui/deps/include \
  --output /tmp/x2cui-counter packages/x2cui/examples/counter.x
/tmp/x2cui-counter

meta

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.

examples/magic/fields.xlink
#include "meta.x"

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);

int main(void) {
  Reading noon = { 21, "roof", 12 };
  $show(noon);
  return 0;
}

Actual output

Expected output

celsius = 21
station = roof
gusts = 12

Run locally: x2c run examples/magic/fields.x

compile-time

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.

examples/magic/compile-time.xlink
#include <assert.h>

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 main(void) {
  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]);
  assert(codes[1] == 404 && labels[1] == "Not Found");
  return 0;
}

Actual output

Expected output

200: OK
404: Not Found
503: Unavailable

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

autodiff

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.

packages/autodiff/examples/energy-gradient.xlink
// Differentiate a loop with a continue in reverse mode, then check the
// gradient against a central finite difference.
#include <assert.h>
#include <math.h>
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);
}

int main(void) {
  double dx, dy;
  double value = energy_grad(1.0, 2.0, 5, &dx, &dy);
  double h = 1e-6;
  double check = (energy(1.0 + h, 2.0, 5) - energy(1.0 - h, 2.0, 5)) / (2 * h);
  assert(fabs(value - energy(1.0, 2.0, 5)) < 1e-12);
  assert(fabs(dx - check) < 1e-5);
  printf("energy %.6f  d/dx %.6f  d/dy %.6f\n", value, dx, dy);
  return 0;
}

This program needs a package, so it runs only with the native toolchain.

Expected output

energy -6.399698  d/dx -3.317359  d/dy -7.389056
Run locally:
make -C packages/autodiff builds/example-energy-gradient
./packages/autodiff/builds/example-energy-gradient

operators

Existing collections do the storage work; the new type supplies the meaning. Set.new reuses Map storage. Set.add and Set.mul define union and intersection, and protocol Map(Set) connects them to + and *. The operators return new sets, leaving both inputs unchanged.

examples/magic/operators.xlink
#include <assert.h>
// 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);

int main(void) {
  // 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("union: %s\n", set_union.keys().list().sort().repr());
  printf("intersection: %s\n", intersection.keys().list().sort().repr());
  assert(set_union.len() == 3 && set_union.contains(<apple>) &&
         set_union.contains(<pear>) && set_union.contains(<bread>));
  assert(fruit.len() == 2 && lunch.len() == 2);
  assert(Set.new(nil).len() == 0);
  assert(Set.new(%(apple pear apple)).len() == 2);
  assert(intersection.len() == 1 && intersection.contains(<pear>));
  assert((fruit * fruit).len() == 2);
  assert((fruit * Set.new(nil)).len() == 0);
  assert((Set.new(nil) * fruit).len() == 0);
  assert(fruit.len() == 2 && lunch.len() == 2);
  return 0;
}

Actual output

Expected output

union: (apple bread pear)
intersection: (pear)

Run locally: x2c run examples/magic/operators.x

same list

A meta function computes the squares during translation, a literal writes (1 4 9) out, and direct cons calls build the same cells. Runtime Lisp calculates the squares on the fly to produce the same List. All four results compare equal in constant time because they resolve to the exact same object.

examples/magic/ways-to-agree.xlink
#include <assert.h>

// A meta function computes the List during translation.
meta static List squares(int n) {
  Array items = [];
  for (int i = 1; i <= n; i++) items.push(i * i);
  return items.list_free();
}

int main(void) {
  List comptime = $squares(3);

  // A literal compiles to a form similar to the cons cells below.
  List literal = %(1 4 9);

  // Explicit construction reveals the underlying C functions.
  List constructed = cons(int_var(1),
    cons(int_var(4), cons(int_var(9), NULL)));

  // Runtime Lisp will build it on the fly.
  auto Lisp lisp = Lisp.new();
  List runtime = lisp.eval(%(list (* 1 1) (* 2 2) (* 3 3)));

  List ways = $(comptime, literal, constructed, runtime);
  foreach (List left in ways)
    foreach (List right in ways) assert(left == right);
  assert(comptime == literal && literal == constructed &&
         constructed == runtime);
  puts("All four lists are equal.");
  return 0;
}

Actual output

Expected output

All four lists are equal.

Run locally: x2c run examples/magic/ways-to-agree.x