Learning BSV‎ > ‎Data Types‎ > ‎

Tagged Union

Overview

A tagged union is a composite type.  In Bluespec, a union always refers to a tagged union.  A union value contains only one of its members at a time.  This is different from a struct in which each value contains all of the members.  Union member names must begin with an uppercase letter.  Each member name in a particular union must be unique within the union, but may be used in other structs or unions.

In a tagged union, the member names are called tags.  In addition to the bits corresponding to the member types, a tagged union also has some bits to remember the tag.  You can only access a single member at a time, based on the tag. 

Defining Tagged Unions

Syntax

typedef union tagged {type Member1, ... type MemberN}
         UnionName ;

Examples

 typedef union tagged {
      bit  [4:0] Register;
      bit [21:0] Literal;
       struct {
          bit  [4:0] regAddr;
          bit  [4:0] regIndex;
      } Indexed;
 } InstrOperand;

An instruction operand is either a 5-bit register specifier, a 22-bit literal value, or an indexed memory specifier, consisting of two 5-bit register specifiers, as shown in the picture below.


 typedef union tagged {
        void     InvalidFile ;
        Bit#(31) MCD;
        Bit#(31) FD;
    } File;

A file is either an MCD or FD file type, or it is invalid.

Assigning Values to a Tagged Union

Update of tagged union variables is done using normal assignment notation, i.e., one replaces the current value in a tagged union variable by an entirely new tagged union value.  In a struct it makes sense to update a single member and leave the others unchanged, but in a union, one member replaces another.

Assignment Syntax

To set a tagged union member to a value:
 tagged Member_name value
If the member is a structure (as Indexed in InstrOperand)
 tagged Member_name { structmemb0:value, structmemb1:value};

Assignment Example

Using above tagged union InstrOperand
  ...
  InstrOperand  orand;
  ...
  orand = tagged Indexed { regAddr:3, regIndex:4 };
  ...
  orand = tagged Register 23;

Usage

The maybe type is an instance of a tagged union:
 
 typedef union tagged {
      void  Invalid;
      a     Valid;
  } Maybe#(type a)
    deriving (Bits);



Comments