Skip to content

Unions & Option ​

A union is a nominal, optionally parameterized tagged sum type with packed layout [data (MSB), tag (LSB)]. Neo also provides the built-in Option(T) union.

Syntax ​

neo
pub union Packet(T: LogicType) {
  Empty,
  Word(Int(32)),
  Custom(T),
}

Bit Layout ([data (MSB), tag (LSB)]) ​

For a union with N >= 1 variants:

  • Tag field (LSB):
    • tag_width = 0 when N == 1 (1-variant union).
    • tag_width = clog2(N) when N >= 2.
    • Tag values are assigned 0, 1, ..., N - 1 in declaration order.
    • Occupies bits [tag_width - 1 : 0].
  • Data field (MSB):
    • data_width = max(payload_i.width) across all variants with payloads (or 0 for a tag-only union where no variant has a payload).
    • Occupies bits [tag_width + data_width - 1 : tag_width].
    • Payloads narrower than data_width are placed at the LSB of the data region ([tag_width + pw - 1 : tag_width]) and zero-padded in the upper bits.
  • Total width: tag_width + data_width (queryable via Packet(T).width).
  • Empty unions (0 variants) are rejected (empty_union).

Built-In Option(T) ​

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

VariantTagPayload
Invalid0 (1'b0)None
Valid(T)1 (1'b1)T
  • tag_width = 1, data_width = T.width, total width 1 + T.width.
  • Bit 0 is the validity bit; bits [T.width : 1] carry the payload T.

Validation Rules ​

  • Construction:
    • Payload variant: U.Var(expr) or inferred .Var(expr). Inherits expr's timing.
    • Payload-less variant: U.Var or U.Var() (and .Var / .Var()). Has Constant timing.
  • Pattern matching (match):
    • Scrutinee must be a union or Option(T).
    • Each arm matches either a variant (Var or Var(binding)) or the catch-all wildcard _.
    • When a payload binding x is present, x is bound as a read-only LogicVal with the variant's payload type and the scrutinee's timing.
    • Checked for exhaustiveness (non_exhaustive_match), duplicate arms (duplicate_match_arm), multiple wildcards (multiple_default_cases), and unexpected bindings on payload-less variants (union_variant_no_data).
    • Inside comb, all match arms must assign the exact same set of signals (inconsistent_conditional_assignments).

Elaboration & Code Generation ​

Example ​

Source:

neo
union MyUnion(T: LogicType) {
  A,
  B(Int(32)),
  C(T),
}

@top
module UnionMux(t: Timing) {
  input in(t): MyUnion(Bits(1)),
  output out(t): Int(32),
} {
  comb {
    out = match in {
      A => 1#32,
      B(x) => x,
      C(x) => if x { 42#32 } else { 0#32 },
    };
  }
}

In neo-ir and SystemVerilog:

  • in has width 2 + 32 = 34 bits: in[1:0] is the tag (A = 0, B = 1, C = 2) and in[33:2] is the data region (B's payload is in[33:2], C's 1-bit payload is in[2]).
  • match lowers to a case (in[1:0]) block inside always_comb.
  • Because UnionMux has no sequential logic, no __defaultClock port is emitted.