Structs in VHDL

Our first example will show the concept of structs and how to work with them. Structs are typed collections of fields and are useful for grouping data to form records.

-- Define a 'person' record with 'name' and 'age' fields
type person is record
    name : string(1 to 20);
    age  : integer;
end record;

-- Function to create a new 'person' record with a given name
function newPerson(name : in string) return person is
    p : person;
begin
    p.name := name;
    p.age  := 42; -- default age
    return p;
end function;

-- Main procedure demonstrating various ways to create and use records
procedure main is
    -- Create a new person record
    p1 : person := (name => "Bob", age => 20);
    -- Print fields of the record
    procedure print_person(p : in person) is
    begin
        report p.name & " " & integer'image(p.age);
    end procedure;
begin
    -- Print the person record
    print_person(p1);

    -- Create a person record with named fields
    p1 := (name => "Alice", age => 30);
    print_person(p1);

    -- Create a person record with only name, age will be defaulted
    p1 := (name => "Fred", age => 0);
    print_person(p1);

    -- Pointer to a person record (simulation only as VHDL does not support direct pointers)
    -- In VHDL, we use access types for pointers, however, here is a conceptual pointer usage
    type person_ptr is access person;
    p_ptr : person_ptr := new person'(name => "Ann", age => 40);
    print_person(p_ptr.all);

    -- Use the newPerson function to create a new person
    p_ptr := new person'(newPerson("Jon"));
    print_person(p_ptr.all);

    -- Accessing and modifying record fields
    p1 := (name => "Sean", age => 50);
    report p1.name;        -- Accessing name
    p1.age := 51;          -- Modifying age
    report integer'image(p1.age);
    
    -- Example showing anonymous record types
    type dog_record is record
        name   : string(1 to 20);
        isGood : boolean;
    end record;

    -- Create an instance of anonymous record type
    dog : dog_record := (name => "Rex", isGood => true);
    report dog.name & " " & boolean'image(dog.isGood);
end procedure main;

To run this VHDL code, you will need a VHDL simulator like ModelSim or GHDL. Set up the testbench and run the simulation to see the assignments and field access in action.

This example showcases record definition, creation, field assignment, and usage of functions to instantiate records. This is a fundamental aspect of VHDL’s capability to handle complex data types for modeling and simulation.