machdocs
Home Ecosystem Changelog

Records, unions, and tags

A rec is a named collection of typed fields, each with its own storage. A uni overlaps its fields in the same memory. A tag defines a discriminated value with compiler-enforced lexical guards.

Records

A rec lays out its fields side by side. Each field has independent storage, and the record's size is the sum of the field sizes plus any padding the compiler inserts for alignment. A record may be generic over type parameters.

rec NAME {
    field1: type;
    field2: type;
    ...
}

rec NAME[T, U] { ... }      # generic over type parameters
pub rec Point {
    x: i64;
    y: i64;
}

pub rec Pair[T, U] {
    left:  T;
    right: U;
}

Construction and access

A record literal names the type and supplies each field by name. Read a field with ..

val p: Point          = Point{ x: 1, y: 2 };
val q: Pair[i64, u8]  = Pair[i64, u8]{ left: 5, right: 6u8 };
val n: i64            = p.x;            # field access via .

A field given twice in one literal, or a name the record does not declare, is refused. A positional literal such as Point{1, 2} is refused too, because positional braces build a vector.

A literal may leave fields out. Every omitted field is zero-initialized: integers and floats read 0, pointers read nil, and a nested record or array is zero in every byte. This holds for a literal built at run time and for a constant one alike, and T{} is all zero. Padding between fields is not a field, and it is unspecified unless the record holds a secret.

val z: Point = Point{ x: 3 };                 # z.y is 0

== and != on a whole record, union or tag are refused. Compare the fields, or use std.derive.eq.

Memory layout

By default the compiler may insert padding between fields to satisfy each field's alignment, following the natural C-style rule. The #[align(N)] decorator on a record raises its minimum type alignment to N bytes, where N is a power of two.

#[align(16)]
pub rec Aligned {
    a: u8;
    b: i64;
}

#[packed] is the inverse: every field sits immediately after the previous one, there is no tail padding, and the type takes no alignment from its fields. That is what describes a shape whose layout is not mach's to choose - a C struct, a file header, a wire frame. The two compose, each owning one question: packed decides padding, align decides the record's own alignment.

#[packed]
rec Header {
    magic:    u8;    # offset 0
    version:  u16;   # offset 1
    length:   u32;   # offset 3
    checksum: u64;   # offset 7
}                    # $size_of == 15, $align_of == 1

Packing is not transitive: a record a packed record contains keeps its own internal padding and is merely placed without any. Taking the address of a packed field is refused, since the resulting pointer type would state an alignment its storage does not have (cannot take the address of a field of a `#[packed]` record, because it may be misaligned for its type); ?r on the whole record stays legal. #[volatile] on a record or union makes every access to its storage a volatile access, the way a memory-mapped register block is declared. See Decorators for the full rule set.

Unions

A uni is a collection of named fields that share the same memory. Writing one field overwrites whatever bytes the others held. A union's size is the size of its largest field plus any alignment padding. Unions may be generic.

pub uni Number {
    i: i64;
    f: f64;
}

pub uni Maybe[T] {
    some: T;
    none: u8;
}
Restriction

The compiler does not track which field of a union is live. Reading a field other than the one last written reinterprets raw bytes; keeping the active field straight is the programmer's responsibility. A literal writes the field it names and nothing else, so the bytes past that field are unspecified.

Tags

A tag defines a discriminated value with compiler-enforced payload safety. Unlike an untracked union, a tag stores a discriminator alongside its payload area, and the compiler refuses to read any payload outside a lexical guard for its case.

The discriminator type is written after the tag name and must be one of u8, u16, u32 or u64, wide enough to number every case. Case codes follow declaration order from zero. Cases may carry a single typed payload or remain payload-free, and several values ride one case as a record payload.

pub tag Shape: u8 {
    circle: f64;
    rect: Rect;
    point;
}

pub tag Option[T]: u8 {
    none;
    some: T;
}

Values are constructed using the type name, case name, and curly braces. A payload case supplies its value inside the braces, while a unit case uses empty braces.

val c: Shape = Shape.circle{3.14};
val p: Shape = Shape.point{};

There is no other construction form: omitting a required payload, supplying one to a payloadless case, supplying two, naming the payload, or writing Shape{...} with no case is a compile error. Shape.circle alone is a case selector, not a value. A zero-initialized tag holds its first declared case, with that case's payload zeroed. Whole tags can be assigned, passed and returned.

The std failure tags

The failure types every std API answers with are ordinary std tags, imported like any other declaration. The compiler has no knowledge of their names.

pub tag res[T, E]: u8 { err: E; ok: T; }   # std.types.result
pub tag opt[T]:    u8 { none; some: T; } # std.types.option
pub tag err[E]:    u8 { err: E; ok; }    # std.types.error

The error case comes first, so a zero-initialized res or err is a failure and a zero-initialized opt is none.

Payload guards and sel

The sel keyword tests whether a tag instance currently holds a specific case. The expression sel place.case reads only the discriminator and yields a u1, so it can be stored in a bool, negated, and combined with && and ||. The operand is a place, and sel p.case on a pointer to a tag reads through it once.

Reading, writing or addressing a case payload is permitted only inside a lexical guard for that place and case. A payload read outside one is refused with a tag payload requires a `sel` guard for its case.

fun area(s: Shape) f64 {
    if (sel s.circle) {
        ret 3.141592653589793 * s.circle * s.circle;
    }
    if (sel s.rect) {
        ret s.rect.w * s.rect.h;
    }
    ret 0.0;
}

Guards obey strict lexical scope rules:

That last rule is the failure-handling pattern: test the error case, leave, and read the success payload after.

fun increment(input: u8) res[i64, ParseError] {
    val res_parsed: res[i64, ParseError] = parse(input);
    if (sel res_parsed.err) { ret res[i64, ParseError].err{res_parsed.err}; }
    ret res[i64, ParseError].ok{res_parsed.ok + 1};   # guarded: the chain above exits
}
Guard restrictions

A guard is matched by spelling, so a guarded place is a path of names, fields, dereferences and indexes by a name or a literal. ||, ! and every other operator open no guard. Whole-value assignment to the guarded place is refused inside the guard. Assigning a name the place is spelled with, such as the i of sel items[i].c, ends the guard from that point on.

See also

  • Decorators - #[deprecated] on declarations and cases
  • Intrinsics - $cases, $is_tag, and $discriminant_of for tag reflection
  • Statements - control flow and conditional guards
  • Types - aggregate and primitive type definitions