How to create a string from a pre-processor macro - macros

I have a preprocessor macro that represents a hierarchical path into my design.
Example:
`define HPATH top.chip.block
I need to construct a string which holds the value of `HPATH, so in my example the string should equal top.chip.block.
Is there a way to construct such a string?
None of the following attempts worked:
string hpath;
hpath = "`HPATH"; // Results in hpath = "`HPATH"
hpath = \"``HPATH\"; // Doesn't compile
hpath = `HPATH; // Doesn't compile
I want hpath to be equivalent to doing this assignment hpath = "top.chip.block", but by using `HPATH instead of specifying the path again.
I cannot use %m because I need the string within my top-level UVM environment, not within a module.
A little more background: the reason I want to do this is because I am using backdoor register access in the UVM class library. The backdoor API requires setting the hdl_path to the blocks within the design, as a string. I already have `defines for the hierarchical paths and am trying to reuse those when specifying the hdl_paths so I don't have the same path defined twice. My testbench will use both the hierarchical path and the string path.

It's not possible to use a `define macro within a string literal. According to the SystemVerilog LRM:
Macro substitution and argument substitution shall not occur within string literals.
However a string literal can be constructed by using a macro that takes an argument and including the quotes in the macro by using ``"`.
Again, from the LRM:
An `" overrides the usual lexical meaning of " and indicates that the expansion shall include the quotation
mark, substitution of actual arguments, and expansions of embedded macros. This allows string literals to be
constructed from macro arguments.
So this works:
`define STRINGIFY(x) `"x`"
`define HPATH top.chip.block
string hpath = `STRINGIFY(`HPATH);
$display(hpath); // Output: "top.chip.block"
The example code can be run here: http://www.edaplayground.com/s/4/879

I know this is an old thread, but I thought I'd share our solution. The use of the $sformatf allows additional information to be added if needed.
`define STRINGIFY(DEFINE) $sformatf("%0s", `"DEFINE`")

I think this is what you're looking for.
`define HPATH `"top.chip.block`"
string hpath = `HPATH;
As toolic pointed out, the escape sequence %m will give you the current hierarchy when used in a $display statement so that may be a better option.

Related

implicit __source__ argument to julia macro can't be used within quote block

I'll start with my code:
macro example(args...)
local s = __source__
println(s) # This part works, showing macro is called on line 9
quote
println(s) # Julia tells me this variable "s" is not defined
println(__source__) # Likewise, "__source__" is not defined here either
end
end
#example 42 # Line 9 of my file
In my macro above I want to record the line number that is calling the macro and use it within my quote block. Both capturing it in a variable outside the quote block and using it within, or using it directly in the quote block don't work. My understanding is the code outside the quote block runs at parse-time, and the expression returned from the quote block is evaluated at run-time.
I feel like there must be a way to capture that variable and inject it right into the expression that will be evaluated later, but I haven't figured out how to do that. Any help here is appreciated. If there is a better way to do this let me know.
I ended up finding out an answer on my own. In the second line if I changed __source__ to __source__.line or __source__.file it worked fine as long as I then used $ to interpolate the result into the expression the macro returned. I'm still not sure why __source__ on its own didn't work, but using either .line or .file methods is working for me now.
I'm experiencing a similar problem trying to use __source__.
I think I can offer insight into why source.line, etc worked though.
The value of source.line is an integer. The value of source.fike is a string. Numbers and strings evaluate to themselves.
A symbol, on the other hand, evaluates to whatever value it has in the environment.

Warning Control Character '\S' is not valid when concatinating two strings

I have two variables such as:
path='data\voc11\SegmentationClassExt\%s.png'
name='123'
I want to concatenate two strings into one like so:
data\voc11\SegmentationClassExt\123.png
I used the code below:
sprintf(path, name)
However I receive the following error:
Warning: Control Character '\S' is not valid. See 'doc sprintf' for control characters valid in the format string.
ans =
dataoc11
I am using MATLAB on Windows. Could you give me any solution for that. I tried to change path='data\\voc11\\SegmentationClassExt\\%s.png' and when I did that, the above code will work. However, the current data is
path='data\voc11\SegmentationClassExt\%s.png';
use the matlab function fullfile
filename = fullfile ( path, [name '.png'] );
or
filename = fullfile ( path, sprintf ( '%s.png', name ) );
Note: you should avoid using path as a variable as it is already a Matlab function
Before we start, it's highly advised that you do not use path as a local variable. path is a global variable that MATLAB uses to resolve function scope, especially if you are going to use any functions from toolboxes. Overwriting path with your own string will actually make MATLAB not function properly. Use a different variable name.
Now to resolve your problem, you can use either fullfile as what #matlabgui has suggested, or if you don't care about OS compatibility and are only working in Windows, you can either manually change the path as you have placed so that you can introduce two back slashes and it will indeed work on Windows OS, or you can perhaps use a string replace function so that all back slashes will be accompanied with an additional back slash.
Either one of these two methods will work:
Method 1 - Using regular expressions
pat = 'data\voc11\SegmentationClassExt\%s.png';
pat_new = regexprep(pat, '\\', '\\\\');
The function regexprep performs a string replacement by regular expressions. We search for all single backslashes and replace them with double backslashes. Note that the single back slash \ is a special character in regular expressions so if you explicitly what to look for back slashes, you must place an additional back slash beside it.
Method 2 - Using strrep
pat = 'data\voc11\SegmentationClassExt\%s.png';
pat_new = strrep(pat, '\', '\\');
strrep stands for String Replace. It works very similar to regular expressions as we have discussed above. However, what's nice is that you don't have to append an additional back slash when looking for the actual character.
Once you do this, you can use sprintf as normal:
pat_new = sprintf(pat_new, name);

What is the meaning of ${} in powershell?

I have a script where function parameters are expressed like this:
param(
${param1},
${param2},
${param3}
)
What does it mean? I have been unable to find documentation on this.
What's the point of writing parameters that way instead of the more usual
param(
$param1,
$param2,
$param3
)
?
#MikeZ's answer is quite correct in explaining the example in the question, but as far as addressing the question title, there is actually more to say! The ${} notation actually has two uses; the second one is a hidden gem of PowerShell:
That is, you can use this bracket notation to do file I/O operations if you provide a drive-qualified path, as defined in the MSDN page Provider Paths.
(The above image comes from the Complete Guide to PowerShell Punctuation, a one-page wallchart freely available for download, attached to my recent article at Simple-Talk.com.)
They are both just parameter declarations. The two snippets are equivalent. Either syntax can be used here, however the braced form allows characters that would not otherwise be legal in variable names. From the PowerShell 3.0 language specification:
There are two ways of writing a variable name: A braced variable name, which begins with $, followed by a curly bracket-delimited set of one or more almost-arbitrary characters; and an ordinary variable name, which also begins with $, followed by a set of one or more characters from a more restrictive set than a braced variable name allows. Every ordinary variable name can be expressed using a corresponding braced variable name.
From about_Variables
To create or display a variable name that includes spaces or special characters, enclose the variable name in braces. This directs Windows PowerShell to interpret the characters in the variable name literally.
For example, the following command creates and then displays a variable named "save-items".
C:\PS> ${save-items} = "a", "b", "c"
C:\PS> ${save-items}
a
b
c
They are equivalent. It's just an alternative way of declaring a variable.
If you have characters that are illegal in a normal variable, you'd use the braces (think of it as "escaping" the variablename).
There is one additional usage.
One may have variable names like var1, var2, var11, var12, var101, etc.
Regardless if this is desirable variable naming, it just may be.
Using brackets one can precisely determine what is to be used:
assignment of $var11 may be ambiguous, using ${var1}1 or ${var11} leaves no room for mistakes.

Coffeescript Regex interpolation

Coffeescript supports strings interpolation:
user = "world"
greeting = "Hello #{user}!"
Is it possible to use interpolation in regex just like in strings? E.g.
regex = /Hello #{user}/g
P.S. I know that I can use RegExp(greeting, 'g'), I just want a bit cleaner code.
Block Regular Expressions (Heregexes) support interpolation.
Block Regular Expressions
Similar to block strings and comments,
CoffeeScript supports block regexes — extended regular expressions
that ignore internal whitespace and can contain comments and
interpolation. Modeled after Perl's /x modifier, CoffeeScript's block
regexes are delimited by /// and go a long way towards making complex
regular expressions readable.
This coffeescript code:
name="hello"
test=///#{name}///
compiles to
var name, test;
name = "hello";
test = RegExp("" + name);

How do I match strings in shell-style using Perl?

How to match strings in shell-style in Perl? For instance:
foo*
{bar,baz}.smth
joe?
foobar[0-9]
Using regular expressions
Your examples would be:
/foo.*(bar|baz)\.smth joe/
/foobar\d/
However, if what you actually wanted was shell-like filename expansion (e.g. the above was in context of ls foobar[0-9] ), use glob() function:
my #files = glob("foo* {bar,baz}.smth joe");
my #foobar_files = glob("foobar[0-9]");
Please note that the syntax of regular expressions in Perl is NOT that of filename expansion language
File::FnMatch exposes your system's fnmatch(3) implementation, which is probably what implements the shell's wildcard patterns for you.
(Note that {bar,baz}.smth is not matching per se, it is simply "brace expansion" of strings.)