How to properly cast arrays in SystemVerilog?

Victor Lyuboslavsky picture Victor Lyuboslavsky · Apr 24, 2014 · Viewed 7.2k times · Source

The bit-stream casting in SystemVerilog for arrays and structs does not seem very safe.

For example, the following casting issue will only be caught at runtime (which could be hours into the simulation):

bit [31:0] bit_queue[$];
logic [31:0] logic_array[5];
for (int i = 0; i < 10; i++) begin
  bit_queue[i] = $urandom;
end

if (catch_issue) begin
  typedef logic [31:0] logic_array_t [5];
  logic_array = logic_array_t'(bit_queue); // <-- ISSUE
end

Is there a proper "safe" procedure for doing bit-stream casting? Where any issues could be caught at compile time or safely handled at runtime? Or is the language broken in this case?

Example code above on EDA Playground: http://www.edaplayground.com/x/2tp

Answer

dave_59 picture dave_59 · Apr 25, 2014

Similar to $cast, it is up to the user to check for compatibility at runtime with

if ( $bits(bit_queue) == $bits(logic_array) )
  logic_array = logic_array_t'(bit_queue);
else
  $error("sizes do not match");

For casts involving dynamically sized variables, you can get a compile time error if no possible array size would produce a valid assignment, but if there is a possible size, you cannot perform that check until the cast occurs, because the size can change up until the time the cast occurs.