Skip to content

Unions & Option ​

A union (tagged union / sum type) represents a value that is one of several named variants, each optionally carrying a typed hardware payload. Neo also provides the built-in Option(T) union for representing valid/invalid data safely.

Defining a Union ​

neo
union MemReq(addr_w: Pos, data_w: Pos) {
  Read(Bits(addr_w)),
  Write(Tuple(Bits(addr_w), Bits(data_w))),
  Fence, // Payload-less variant
}

Unions are packed as [data (MSB), tag (LSB)]:

  • tag occupies the least significant bits (clog2(variant_count) bits). Variants are numbered 0, 1, ... in declaration order.
  • data occupies the upper bits, sized to the widest variant payload (zero-padded in the upper bits for narrower payloads).
  • 1-variant unions have a 0-bit tag (width equals the single variant's payload width).
  • Tag-only unions (no variant carries a payload) have a 0-bit data field (width equals tag_width).

Constructing Union Values ​

Each variant is accessed through the union type, or with leading-dot shorthand when the expected union type is known:

neo
logic req(t): MemReq(16, 32);

// Explicit type
assign req = MemReq(16, 32).Read(addr);

// Leading-dot shorthand (type inferred from `req`)
assign req = .Write((addr, wdata));

// Payload-less variants work with or without `()`
assign req = .Fence;
assign req = .Fence();

A variant with a payload inherits its payload's timing; a payload-less variant has Constant timing.

Built-In Option(T) ​

Option(T) is a built-in 2-variant union with exact bit encoding:

  • Invalid (tag = 0, no payload)
  • Valid(T) (tag = 1, payload of type T)

Total width is 1 + T.width, with the 1-bit validity tag at bit 0 (LSB) and the payload T in bits [T.width : 1] (MSB).

neo
logic maybe_val(t): Option(Int(32)) = if en {
  .Valid(x)
} else {
  .Invalid
};

Pattern Matching with match ​

To inspect a union or Option(T) safely, use match. Each arm checks the tag and binds the variant's payload to a read-only local variable of the exact payload type and matching timing:

neo
comb {
  out = match maybe_val {
    Valid(v) => v + 1#32,
    Invalid => 0#32,
  };
}

match supports a catch-all wildcard arm _:

neo
comb {
  is_read = match req {
    Read(_) => 1,
    _ => 0,
  };
}

Neo verifies match expressions at compile time:

  • Missing variants without a _ arm trigger a non_exhaustive_match error.
  • Duplicate variant arms trigger a duplicate_match_arm error.
  • Multiple _ arms trigger a multiple_default_cases error.
  • Binding a variable on a payload-less variant triggers a union_variant_no_data error.