systemverilog learning --- call back

call back

A callback is a return call. Simply put, a callback is an empty method and an external function calls it, or a method of a class is implemented by calling a virtual method. Users can extend the class and implement this virtual method. A virtual method is called a callback method, and calling a virtual method is called a callback hook. The operating mechanism is as follows:
Insert image description here
method calls method. Among them, the temp method calls callback_1 and callback_2, which are all virtual methods, that is, the empty method has no specific implementation. It is precisely because callback_1 and callback_2 are both empty implementations, so it will not affect the normal logic. But it increases the scalability of the method, that is, we can add the required control logic in callback_1 without modifying the temp method to implement it. At this point we recall the randomize function, its two empty implementations are pre_randomize() and post_randomize() respectively.
If we want to implement a callback function, we have to write a virtual method, and another method calls the virtual method. When using the callback function, it is necessary to extend the class, and provide the implementation of the callback function, and cover the original class by extending the class.

typedef enum {
    
    OKAY, EXOKAY, SLVERR, DECERR} resp_type;

class slave_driver;
    resp_type resp;
    
    //callback method
    virtual task update_resp;   endtask
    
    //send response task
    task    send_response;
        std::randomize(resp) with ( resp == OKAY;);
        update_resp;
    endtask
endclass

class slave_env;

    slave_drive slv_driver;
    function new();
        slv_driver = new();
    endfunction
    
    //run task to call driver logic
    
    task run;
        repeat(2)begin
            slv_driver.send_response();
            $display("Slave generated response is %s", slv_driver.resp.name());
        end
    endtask

endclass

module basic_test;

    slave_env env;
    
    initial begin
        //create env
        env = new();
        
        //calling run of env
        env.run();
    end

endmodule

The execution results are as follows:
Insert image description here
What if I also want to test the error response. We can comment out basic_test, then use the class err_inject to inherit the original slave_driver class, override the method update_resp, and assign resp to SLVERR. In program error_test, assign the err_driver handle to slv_driver in env, that is, assign the subclass handle to the parent class handle. Since the parent class method is modified with virtual, the updata_resp method of the subclass error_driver will be called.
Insert image description here
The running results are as follows:
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_45614076/article/details/126518899