replace `define with let construct - system-verilog

I'm trying to avoid using `define pre-processor and start using "let" since it's a language construct.
Here is my example:
`define MY_REGISTER_RANGE 15:0
logic [`MY_REGISTER_RANGE] my_array;
How can I do the same with let construct? My code is very simple but it assumes that I'm `include the file where my macro MY_REGISTER_RANGE is defined (in another file).
Thanks.

You can only substitute certain kinds of expressions using let. You can't just define a range.
You should use a typedef instead of let
typedef logic [15:0] MY_REGISTER_t;
MY_REGISTER_t my_array;

In this particular case you do not need the let construct. Moreover, the construct has nothing to do with declarations of variables.
You can start using parameters instead of text macros. For example
parameter MY_REGISTER_WIDTH = 16;
...
logic [MY_REGISTER_WIDTH-1:0] my_array;
The let construct defines a simple function containing a single expression. In this respect it could be used to replace certain types of macros, e.g.
`define MULT(A,B) A * B
...
R = `MULT(O1,O2);
could be replaced with
let MULT(A,B) = A * B;
...
R = MULT(O1,O2);

Related

Defining Julia types using macros

Let's say I want to define a series of structs that will be used as parametric types for some other struct later on. For instance, I would like to have something like
abstract type Letter end
struct A <: Letter end
struct B <: Letter end
...etc...
The idea I've had is to define a macro which takes a string of the name of the struct I want to create and defines it as well as some basic methods. I would then execute the macro in a loop for all names and get all my structs defined at compile time. Something like this:
const LETTERS = ["A","B","C","D"]
abstract type Letter end
macro _define_type(ex)
lines = Vector{Expr}()
push!(lines, Meta.parse("export $ex"))
push!(lines, Meta.parse("struct $ex <: Letter end"))
push!(lines, Meta.parse("string(::Type{$ex}) = \"$ex\""))
return Expr(:block,lines...)
end
#_define_type "A"
for ex in LETTERS
#_define_type ex
end
The first way of executing the macro (with a single string) works and does what I want. However, when I execute the macro in a loop it does not. It tells me some variables are declared both as local and global variables.
Can someone explain what is happening? I believe it may be solved by a proper use of esc, but I can't figure out how.
Thanks!
Edit: Thank you all for the amazing responses! Got my code running!
I think this is what you are trying to do:
module MyModule
abstract type Letter end
const LETTERS = ["A", "B", "C", "D"]
for letter in LETTERS
sym = Symbol(letter)
#eval begin
export $sym
struct $sym <: Letter end
Base.string(::Type{$sym}) = $letter
end
end
end
using .MyModule
string(A) # "A"
See the Code Generation section for more details:
https://docs.julialang.org/en/v1/manual/metaprogramming/#Code-Generation
Okay, the problem here is that in Julia for loops introduce a separate, local scope, while struct definitions need to be in the global scope. So your macro fails because it creates struct definitions in the local scope of the for loop.
A way to get around this is to use #eval, to ensure your struct definitions are evaluated in the global scope. In that case, you don't need to create a macro for that, just have a simple loop like this:
abstract type Letter end
const LETTERS = [:A, :B, :C, :D, :E]
for ex in LETTERS
#eval struct $ex <: Letters end
end
You can even put that loop in a function and it will still work. The defined structs can have fields, as #eval covers the entire code block that follows it.
Note that LETTERS must contain symbols rather than strings for this to work correctly. It's easy enough to convert a vector of strings into a vector of symbols using Symbol.(vector_of_strings).
While there are other ways of achieving what you want to do I believe the core issue is understanding the nature of macros. From the docs (emphasis mine):
Macros are necessary because they execute when code is parsed, therefore, macros allow the programmer to generate and include fragments of customized code before the full program is run.
So the macro in your loop does not "see" the values "A", "B", "C" and "D", it sees the expression: ex. To demonstrate this try using #macroexpand:
julia> #macroexpand #_define_type ex
quote
export ex
struct ex <: Main.Letter
#= none:1 =#
end
var"#11#string"(::Main.Type{Main.ex}) = begin
#= none:1 =#
"ex"
end
end
As you can see the actual value of the variable ex does not matter. With this in mind let's look at the actual error you get. You can reproduce it like this:
julia> for ex in ["A"]
struct ex <: Letter
end
end
ERROR: syntax: variable "ex" declared both local and global
Stacktrace:
[1] top-level scope
# REPL[52]:1
You can probably see that this is not what you want, but why this specific error? The reason is that structs are implicitly global while the loop variable is local.
Here is a possible solution that uses a macro that takes a variable number of arguments instead (I also switched to providing the expression directly instead of as a string):
abstract type Letter end
macro _define_types(exprs...)
blocks = map(exprs) do ex
name = string(ex)
quote
export $ex
struct $ex <: Letter end
Base.string(::Type{$ex}) = $name
end
end
Expr(:block, blocks...)
end
#_define_types A
#_define_types B C D

Passing a varying number of macro arguments as a string in System Verilog

I have an existing code that uses some macro definitions in order to display messages from my test cases. I want to change the implementation of these macros, however, as these macros are extensively used in already existing testcases, I am looking to reimplement their functionality witout having to modify how the macros are used.
Currently the macros are difined as such:
`define My_Info $write("INFO:"); $display
`define My_Error $write("ERROR:"); $display
In the testcases, example calls of these macros include:
`My_Info("This is an info message with arguments %0d, %0d, and %0d", var1, var2, var3);
`My_Info("My_ID", $psprintf("ID : %s", var4));
`My_Error("Failed to open file: %s ", fname);
Currently $display, displays the messages in the brakets.
What I want to do is to define the macros in a way that these messages in the brakets of the macro calls could be passed as a string argument to a function (for example the function my_msg(msg) where msg is a string and my_msg is a function that formats and returns this string to the log file.
My issue is, because in the testcases the macro calls have varying number of arguments as seen in the example above, I am not sure how to define the macros in a universal way.
Currenlty my solution is to define the macros like:
`define My_Info(string=" ", var1= , var2= , var3= , var4= ) my_msg($sformat(s,var1, var2, var3, var4)
But this relies on a finite number of arguments (in this case 5).
Is there a more elegant way of doing it?
You can workaround the lack of varying numbers of macro arguments by requiring an extra set of ()'s.
module top;
`define my_error(msg) begin $error({"My ID:",$sformatf msg}); end
int a,b;
initial begin
`my_error( ("hello") )
`my_error( ("A = %0d B = %0d", a,b) )
end
endmodule

What is meant by this SystemVerilog typedef enum statement?

typedef enum logic [1:0] {S0, S1, S2} statetype;
Does this statement mean that any variable declared as 'statetype' can only take three values, 2'b00, 2'b01, and 2'b10? If so, what happens if I assign the said variable with the value 2'b11?
The IEEE Std 1800-2017, section 6.19.3 Type checking, states:
Enumerated types are strongly typed; thus, a variable of type enum
cannot be directly assigned a value that lies outside the enumeration
set unless an explicit cast is used or unless the enum variable is a
member of a union. This is a powerful type-checking aid, which
prevents users from accidentally assigning nonexistent values to
variables of an enumerated type. The enumeration values can still be
used as constants in expressions, and the results can be assigned to
any variable of a compatible integral type.
Enumerated variables are type-checked in assignments, arguments, and
relational operators.
What I observe in practice is that some simulators issue a compile warning while others issue a compile error. You can see what happens on multiple simulators on edaplayground (if you sign up for a free account there).
For example, with VCS, the following code:
module tb;
typedef enum logic [1:0] {S0, S1, S2} statetype;
statetype s;
initial begin
s = S0;
$display("n=%s,s=%0d,", s.name(), s);
s = 3;
$display("n=%s,s=%0d,", s.name(), s);
end
endmodule
issues this warning:
Warning-[ENUMASSIGN] Illegal assignment to enum variable
tb.v, 16
tb, "s = 3;"
Only expressions of the enum type can be assigned to an enum variable.
The type int is incompatible with the enum 'statetype'
Expression: 3
Use the static cast operator to convert the expression to enum type.
but, it still runs the simulation and prints:
n=S0,s=0
n=,s=3
I believe the question should be rephrased to say that what is this is happening in our test-bench and how to avoid it. This will gives us more cleaner and bug free code.
efficient code to avoid the confusion:
typedef enum logic [1:0] {S0, S1, S2} statetype;
module top();
statetype st_e;
initial begin
for(int val=0;val<4; val++) begin
// casting for avoid confusion and gotchas
if (!$cast(st_e,val)) begin
$error("Casting not possible -> statetype:%0s and val:%0d",st_e,val);
end else begin
$display("statetype:%0s and val:%0d",st_e,val);
end
end
end
endmodule: top
This code is already there in edaplayground feel free to try it and update it. This could be replace with the sv macro for more efficiency. Please let me know I will provide the example for macros.
Output will be:
# run -all
# statetype:S0 and val:0
# statetype:S1 and val:1
# statetype:S2 and val:2
# ** Error: Casting not possible -> statetype:S2 and val:3
# Time: 0 ns Scope: top File: testbench.sv Line: 14
# exit

Why are macros based on abstract syntax trees better than macros based on string preprocessing?

I am beginning my journey of learning Rust. I came across this line in Rust by Example:
However, unlike macros in C and other languages, Rust macros are expanded into abstract syntax trees, rather than string preprocessing, so you don't get unexpected precedence bugs.
Why is an abstract syntax tree better than string preprocessing?
If you have this in C:
#define X(A,B) A+B
int r = X(1,2) * 3;
The value of r will be 7, because the preprocessor expands it to 1+2 * 3, which is 1+(2*3).
In Rust, you would have:
macro_rules! X { ($a:expr,$b:expr) => { $a+$b } }
let r = X!(1,2) * 3;
This will evaluate to 9, because the compiler will interpret the expansion as (1+2)*3. This is because the compiler knows that the result of the macro is supposed to be a complete, self-contained expression.
That said, the C macro could also be defined like so:
#define X(A,B) ((A)+(B))
This would avoid any non-obvious evaluation problems, including the arguments themselves being reinterpreted due to context. However, when you're using a macro, you can never be sure whether or not the macro has correctly accounted for every possible way it could be used, so it's hard to tell what any given macro expansion will do.
By using AST nodes instead of text, Rust ensures this ambiguity can't happen.
A classic example using the C preprocessor is
#define MUL(a, b) a * b
// ...
int res = MUL(x + y, 5);
The use of the macro will expand to
int res = x + y * 5;
which is very far from the expected
int res = (x + y) * 5;
This happens because the C preprocessor really just does simple text-based substitutions, it's not really an integral part of the language itself. Preprocessing and parsing are two separate steps.
If the preprocessor instead parsed the macro like the rest of the compiler, which happens for languages where macros are part of the actual language syntax, this is no longer a problem as things like precedence (as mentioned) and associativity are taken into account.

Pack individual signal into an array

I have a bunch of signals like this:
logic [7:0] in0;
logic [7:0] in1;
logic [7:0] in2;
logic [7:0] in3;
That I want to assign to an array:
logic [7:0] in_array [4];
assign in_array[0] = in0;
assign in_array[1] = in1;
assign in_array[2] = in2;
assign in_array[3] = in3;
Easy enough, but if instead of 4 items I have 128 this gets annoying. I am sure there is a combination of defines and generates that can do this in a loop. Something like:
`define IN(x) inx
genvar i;
generate
for(i = 0; i<4; i++) begin
assign in_array[i] = `IN(i);
end
endgenerate
The above code doesn't work, but I think that I have done something like this before.
Simplifying that code is something that cannot be done in SystemVerilog. You can reduce you typing by creating a macro like below (note the double backticks ``), but you will still need to manually write each index. Macros are are resolved before generate loops and the input variable to the macro is treated as a literal.
// short named macro for reduced typing
// Note: using short named macro is typically a bad practice,
// but will be removed latter with an undef
`define A(idx) assign array_in[idx] = out``idx
//This works
`A(0);
`A(1);
`A(2);
`A(3);
// doesn't work. For example # gidx==0 will eval to 'assign array_in[0] = outgidx;'.
// There is not outgidx
genvar gidx;
generate
for(gidx=0; gidx<4; gidx++) begin
`A(gidx);
end
endgenerate
`undef A // prevent macro from from being used latter on
If it is just a small number of entries, it is best to do it manually. If it is large number of entries, then you need to consider a way to generate the for you, such as embedded coded.
There are also various embedded code (such as Perl's EP3, Ruby's eRuby/ruby_it, Python's prepro, etc.) that can generate the desired code. Pick your preference. You will need to per-process these files before giving to the compiler. Example with EP3 generating 400 assignments:
#perl_begin
foreach my $idx (0..400) {
printf "assign array_in[%0d] = out%0d;", $idx, $idx;
}
#perl_end
Use `` to separate text from argument.
`define IN(x) in``x
But there is another issue with the variable i not being declared at the time when the macro is evaluated. Thus the whole generate loop just connects to ini, because i is just another letter. Because of this macros cannot be assigned by dynamically allocated values.
The environment of your module already has to connect explicitly to each input assign in0 = out0; ... assign in127 = out127. So the simplest solution would be to have in_array as your modules input and let the environment connect to it assign array_in[0] = out0.
Something like this:
module parent_module();
/*some other stuff that has outputs out0, out1 etc.*/
logic [7:0] array_in[4];
assign array_in[0] = out0;
assign array_in[1] = out1;
assign array_in[2] = out2;
assign array_in[3] = out3;
my_module(.array_in(array_in));
endmodule