Randomization Scope Resolution



class trans;
  rand bit [3:0] addr;
endclass

class seq;
 rand bit [3:0] addr;
 rand trans t;
   
   function new();
       t = new() ;
   endfunction

  function void display();

     $display(" addr is %0d , t.addr is %0d ",addr,t.addr);

  endfunction

endclass


seq  s ;

initial begin

  s = new();

  if ( s.randomize() with { addr == 10 ; } ) 
   begin
    s.display() ;
   end

end

I notice that property ‘addr’ of class seq gets Constrained whereas property ‘addr’ of trans is Unconstrained !!

But I were to change only the seq class to ::


// Remove 'addr' property from class seq :: 
class seq;
 rand trans t;
   
   function new();
       t = new() ;
   endfunction

  function void display();

     $display(" addr is %0d , t.addr is %0d ",addr,t.addr);

  endfunction

endclass

I notice an error with ::


  if ( s.randomize() with { addr == 10 ; } )  // Compile-error , why ??

[Q1] Wouldn’t the solver look for addr inside seq Class first followed by trans class ( since seq class has handle t ) ?

[Q2] How is addr searched for ? First seq class ( since we call randomize() on object of seq ) followed by ?

(a) Sub-class handles in seq class OR Directly the scope Containing method call ( initial block in our case ) ?

In reply to Have_A_Doubt:

The constraint solver only knows about the variables associated with the class being randomized. In this case, only ‘addr’ in seq is constrained by the randomization call.

You can add a constraint to seq to ensure that t.addr = addr:


  constraint t_address_c { t.addr == addr; }; 

Randomization first searches the object that is being randomized. If it does
not find the variable inside the class (whose instance is being randomized)
then it tries to resolve from the scope containing the inline constraint.

In your example, it searches for addr in seq class.
Since it is not found it searches the enclosing scope ie, the initial block.
It errors out indicating trans is not found.

It never looks inside subobjects. So whether tran contains a “addr” variable is
irrelevant.