Targets · Zig · Example

Example

The whole language in one short program — a module with a record, a tagged union, a function with per-platform native bodies, and a function that wires up state, a write-back and a return — and the complete Zig it renders to. It is the same program shown on the language page.

Contents

How a Program becomes Zig, in parts. Start with the introduction, then follow each part into the rendered output and the runtime it links against.

Every keyword, in one program

Each keyword has its own page under keywords; here they are all together.

MODULE App

  TYPE Profile
    FIELD Text name
    FIELD Maths.Integer age

  TYPE Status
    OPTION App.Profile active
    OPTION Text pending

  FUNCTION Text Greet
    INPUT Text name
    NATIVE js   "return 'Hi ' + name;"
    NATIVE dart "return 'Hi ' + name;"
    NATIVE zig  "return concat(\"Hi \", name);"

  FUNCTION Text Welcome
    INPUT BINDING App.Profile profile
    HOLE Text row
      INPUT Text line
    STATE Maths.Integer count = 0
    STATE LOCKED Network.Web.Response saved = null
    REVERSE App.Profile submit
      LET Network.Web.Response response = Network.Web.Client.Post profile
      SET saved = response
    LET Text label = Maths.Integer.ToString count
    = label

(The function's swift row is replaced with a zig one here, since Zig needs its own NATIVE body.)

Rendered Zig

The module is a struct container; the record a struct and the union a union(enum), both keeping their dotted path; state uses comptime generics; the function's zig body is spliced in; and because Zig has no closures the write-back is a named struct function.

pub const app = struct {

    pub const Profile = struct {
        name: []const u8,
        age: i64,
    };

    pub const Status = union(enum) {
        active: Profile,
        pending: []const u8,
    };

    pub fn Greet(name: []const u8) []const u8 {
        return concat("Hi ", name);          // the zig NATIVE body
    }

    pub fn Welcome(profile: Profile, row: fn ([]const u8) ReactiveValue([]const u8)) ReactiveValue([]const u8) {
        const count = Program._Runtime.Reactive.state(i64, 0);
        const saved = Program._Runtime.Reactive.stateLocked(network.web.Response, null);
        Program._Runtime.Reactive.reverse(submit, struct { pub fn run() void {
            const response = network.web.client.Post(profile);
            Program._Runtime.Reactive.set(saved, response);   // SET
        } }.run);
        const label = maths.integer.ToString(count);
        return label;
    }
};

Reading it

Indentation becomes nested blocks; because Zig has no closures the REVERSE body is a named struct { pub fn run() void { … } }.run. Dotted names stay real through struct containers, snake_cased (network.web.client.Post) — see naming considerations. The per-keyword mapping is on keywords.