SystemVerilog for Verification: A Guide to Learning the Testbench Language Features

As you write more tests, you can end up with many constraints. They can interact with each other in unexpected ways, and the extra code to enable and disable them adds to the test complexity. Additionally, constantly adding and editing constraints to a class could cause problems in a team environment.
Many tests only randomize objects at one place in the code. SystemVerilog allows you to add an extra constraint using randomize() with. This is equivalent to adding an extra constraint to any existing ones in effect. Example 6-23 shows a base class with constraints, then two randomize() with statements.
class Transaction; rand bit [31:0] addr, data; constraint c1 {addr inside{[0:100],[1000:2000]};}endclassTransaction t = new();initial begin int s; t = new(); // addr is 50-100, 1000-1500, data < 10 assert(t.randomize() with {addr >= 50; addr <= 1500; data < 10;}); driveBus(t); // force addr to a specific value, data > 10 assert(t.randomize() with {addr == 2000; data > 10;}); driveBus(t); end The extra constraints are added to the existing ones in effect. Use constraint_mode if you need to disable a conflicting constraint. Note that inside the with{} statement, SystemVerilog uses the scope of the class. That is why Example 6-23 used...