In Specman, determinant is not constrained by its when subtype attributes - specman

Next question to post:
Hi,
I have the following test case:
<’
struct item_s {
payload:list of byte;
kind:[SMALL,BIG];
when SMALL item_s {
keep payload.size() < 10;
};
};
extend sys {
!item:item_s;
run() is also {
for i from 1 to 10 {
gen item keeping {
.payload.size() == 100;
};
};
};
};
‘>
I expected the test to generate only BIG items. Instead, I see that occasionally a SMALL item is generated, which leads to a contradiction. What is the explanation for this behavior?

The user guide states that
Any field that is declared or constrained under a when subtype depends on the value of the when determinant. In other words, there is an implicit unidirectional constraint (a subtype dependency) between the when determinant and the dependent field:
when-determinant -> dependent-field
This means that kind and payload are generated separately. You'll need to move your constraint outside of the when subtype:
keep kind == SMALL => payload.size() < 10;
You can find more info in the Working with When Subtype Dependencies in Constraints chapter of the Specman Generation User Guide.

Related

Is there a dart function annotation that makes the type checker do type narrowing or condition assertions

Is there a construct that communicates to the type checker a function's post-condition?
For example, in typescript it is possible to say
function assertIsNumber(value: any): asserts value is number {
if (typeof value !== 'number') {
throw new TypeError();
}
}
I would like to be able to do something like the following in dart:
class SomeClass {
int? value;
_checkPreconditions() {
if(value == null) {
throw MyPreconditionError()
}
// ...
}
somefunc() {
_checkPreconditions();
// here we know `value` is a non-null int.
final sum = value + 5;
}
}
I understand I could coerce the value to non-null sum = value! + 5, but I would prefer to allow the function to inform the type checker if possible.
It looks like the type system of Dart is not so powerful. The only thing that looks (from first glance) possible is to create a custom code analyzer package (or search for one that already exists).
Dart annotations don't actually do anything. They provide hints to tools such as the Dart analyzer (usually so that it can generate additional warnings), but they cannot change program behavior. Even if you could convince the analyzer to treat some variables as different types, you still wouldn't be able to compile and run your code.
Annotations can be used by code generation tools, so one possibility might be to generate a statement such as final value = this.value!; automatically. However, that would be a lot of trouble to go through (and would mean that code then would need to use this.value = 42; for assignments and would prevent your code from being analyzed directly).

Is there any method to know whether a member is declared random or not in a class in SV

// Current Class
class x;
rand int a;
int b; // b is nonrandom as of now
function new();
endfunction
function abc;
// if a != ref.a, where ref is reference object of class x, declared somewhere else
a.rand_mode(0);
endfunciton
// Future Possible Class
class x;
rand int a;
rand int b; // b is also a random variable now
function new();
endfunction
function abc;
// if a != ref.a, where ref is reference object of class x, declared somewhere else
a.rand_mode(0);
// if b != ref.b, where ref is reference object of class x, declared somewhere else
b.rand_mode(0);
endfunciton
So in function abc, depending upon whether a rand member value matches or doesn't match with the value of that member in reference class, that rand declared members of class x, should be active or inactive accordinly.
Purpose - I need to check if a rand variable matches with reference class value then only it should be randomized, otherwise not.
I want to generalize method abc, for all possible future variations (So I don't need to modify it, as done in the above example), and as I don't know, when a class member may become rand or nonrand member, Is there any inbuilt method to know, whether a member of a class is declared as rand or not in that class?
You could change your perspective on the problem slightly. Instead of trying to disable randomization for fields that are declared rand, why not say that when they get randomized, they should keep their value?
According to this nice post, there's a new construct in SV 2012, const'(...) that would work in this case. Unfortunately I don't think many vendors support it. Your randomize() call would look like this:
if (!rand_obj.randomize() with {
const'(a) != ref_obj.a -> a == const'(a);
})
$fatal(0, "rand error");
Let's dissect this code. const(a) will sample the value of a prior to doing any sort of randomization. If the value of a before randomization is not equal to the reference value, then we have the second part of the constraint that says a should keep its value. I've tried this code on two simulators but it wasn't supported by either (though it should be legal SV 2012 syntax). Maybe you're lucky enough to have a vendor that supports it.
You can write such constraints even for state variables, as they will still hold.
If you can't get the const syntax to work in your simulator, then the same post shows how you could work around the issue. You could store the values prior to randomization inside the object and use those in the constraint:
class some_class;
rand bit [2:0] a;
bit [2:0] b;
bit [2:0] pre_rand_a;
bit [2:0] pre_rand_b;
function void pre_randomize();
pre_rand_a = a;
pre_rand_b = b;
endfunction
endclass
When you want to randomize, you'd add the following constraints:
if (!rand_obj.randomize() with {
pre_rand_a != ref_obj.a -> a == pre_rand_a;
pre_rand_b != ref_obj.b -> b == pre_rand_b;
})
$fatal(0, "rand error");
You can find a full example on EDAPlayground.
You mention that your function that does randomization is defined outside of the object. Because of that, the pre_rand_* fields can't be local/protected, which isn't very nice. You should consider making the function a class member and pass the reference object to it, so that you can enforce proper encapsulation.
This isn't possible as SystemVerilog doesn't provide any reflection capabilities. You could probably figure this out using the VPI, but I'm not sure how complete the implementation of the VPI is for classes.
Based on what you want to do, I'd say it anyway doesn't make sense to implement such a query just to future proof your code in case some fields will one day become rand. Just as how you add the rand modifier to the field, you can also add it to the list of fields for which randomization should be disabled. Both code locations reside in the same file, so it's difficult to miss.
One certain simulator will return -1 when interrogating a state variable's rand_mode(), but this is non-standard. The LRM explicitly states that it's a compile error to call rand_mode() on non-random fields.

Is it possible to use template arguments in virtual function in modern C++?

I used to do C++ development several years ago and back then I found it difficult to combine template programming with OOP. Currently I program in Swift and I tried doing some of the things I struggled with then.
This Swift code will illustrate the problem:
// protocol is like Java interface or C++ pure virtual base class
protocol Log {
// want to able to add elements from a collection of Ints, but
// it should be any sort of collection that
// can be treated as a sequence
func add<T: SequenceType where T.Generator.Element == Int>(values: T)
}
class DiscreteLog: Log {
var vals: [Int] = []
func add<T: SequenceType where T.Generator.Element == Int>(values: T) {
for v in values {
vals.append(v)
}
}
}
class ContinousLog: Log {
var vals: [Double] = []
func add<T: SequenceType where T.Generator.Element == Int>(values: T) {
for v in values {
vals.append(Double(v))
}
}
}
// I don't have to know whether the log is Continuous or Discrete
// I can still add elements to it
var log: Log = ContinousLog()
log.add([1, 2, 3])
// and elements can come from any kind of sequence, it does not need
// to be an array
log.add(["four": 4, "five: 5].values)
So the problem is that if the C++ code defined as as:
virtual void add(vector<Int> elements>)
Then sure I could have multiple subclasses implement this method, but I could never provide anything but vectors as arguments.
I could try changing it to something more generic using iterator:
virtual void add(vector<Int>::iterator elements>)
But I am still limited to using vector iterators. So I guess I would have to write something like:
template<typename Iterator>
virtual void add(Iterator elements>)
But that will give compile errors as template based arguments are not allowed for virtual methods.
Anyway I wondered if this sort of thing is possible in modern C++.
C++ templates and C#/Swift/Java generics are different things.
They are both "pattern code" in a sense (they are patterns that generate code), but C#/Swift/Java generics use type erasure and "forget" almost everything about the types they work with, while C++ templates are elephants. And elephants never forget.
It turns out that can make an elephant forget, but you have to tell it to. The technique of "forgetting" about details of a type is known as "type erasure" or "run time concepts".
So you want to type erase down to the concept of "a sequence of integers". You want to take any type, so long as it is a sequence of integers, and be able to iterate over it. Seems fair.
boost has such type erasures. But who wants to always rely on boost?
First, type erase an input iterator:
template<class T>
struct input_iterator:
std::iterator<
std::input_iterator_tag, // category
T, // value
std::ptrdiff_t, // distance
T*, // pointer
T // reference
>
{
struct erase {
virtual void advance() = 0;
virtual erase* clone() const = 0;
virtual T get() const = 0;
virtual bool equal(erase const& o) = 0;
virtual ~erase() {}
};
std::unique_ptr<erase> pimpl;
input_iterator(input_iterator&&)=default;
input_iterator& operator=(input_iterator&&)=default;
input_iterator()=default;
input_iterator& operator++() {
pimpl->advance();
return *this;
}
input_iterator operator++(int) {
auto copy = *this;
++*this;
return copy;
}
input_iterator(input_iterator const& o):
pimpl(o.pimpl?o.pimpl->clone():nullptr)
{}
input_iterator& operator=(input_iterator const&o) {
if (!o.pimpl) {
if (pimpl) pimpl->reset();
return *this;
}
pimpl = std::unique_ptr<erase>(o.pimpl->clone());
return *this;
}
T operator*() const {
return pimpl->get();
}
friend bool operator==( input_iterator const& lhs, input_iterator const& rhs ) {
return lhs.pimpl->equal(*rhs.pimpl);
}
friend bool operator!=( input_iterator const& lhs, input_iterator const& rhs ) {
return !(lhs==rhs);
}
template<class It>
struct impl:erase{
It it;
impl(impl const&)=default;
impl(It in):it(std::move(in)){}
virtual void advance() override { ++it; }
virtual erase* clone() const override { return new impl(*this); }
virtual T get() const override { return *it; }
virtual bool equal(erase const& o) override {
return static_cast<impl const&>(o).it == it;
}
};
template<
class It,
class=std::enable_if<
std::is_convertible<
typename std::iterator_traits<It>::reference,
T
>{}
>
>
input_iterator(It it):pimpl( new impl<It>{it} ) {}
}; // input_iterator
Next, have a range template. This is a container that stores non-type erased iterators, and exposes enough to iterate over those iterators.
template<class It>
struct range {
It b; It e;
It begin() const { return b; }
It end() const { return e; }
range() = default;
range(It start, It finish):b(std::move(start)),e(std::move(finish)) {};
range(range&&)=default;
range(range const&)=default;
range& operator=(range&&)=default;
range& operator=(range const&)=default;
template<class R,
class R_It=std::decay_t<decltype(std::begin(std::declval<R>()))>,
class=std::enable_if< std::is_convertible<R_It, It>{} >
>
range( R&& r ):
range(std::begin(r), std::end(r))
{} // TODO: enable ADL begin lookup
};
The above type is really basic: C++1z has better ones, as does boost, as do I have in my own code base. But it is enough to handle for(:) loops, and implicit conversion from containers with compatible iterators.
Finally our sequence type:
template<class T>
using sequence_of = range<input_iterator<T>>;
Wait, that's it? Nice, those types compose well!
And barring errors, we are done.
Your code now would take a sequence_of<int>, and they could pass a std::vector<int> or std::list<int> or whatever.
The input_iterator type-erasure type-erases any iterator down to getting a T via *, ==, copy, and ++ advance, which is enough for a for(:) loop.
The range<input_iterator<int>> will accept any iterable range (including containers) whose iterators can be converted to an input_iterator<int>.
The downside? We just introduced a bunch of overhead. Each method goes through virtual dispatch, from ++ to * to ==.
This is (roughly) what generics do -- they type-erase down to the requirements you give it in the generic clause. This means they are working with abstract objects, not concrete objects, so they unavoidably suffer performance penalties of this indirection.
C++ templates can be used to generate type erasure, and there are even tools (boost has some) to make it easier. What I did above is a half-assed manual one. Similar techniques are used in std::function<R(Args...)>, which type-erases down to (conceptually) {copy, call with (Args...) returning R, destroy} (plus some incidentals).
live example.
(The code above freely uses C++14.)
So the C++ equivalent Log is:
struct Log {
virtual void add(sequence_of<int>) = 0;
virtual ~Log() {}
};
Now, the type erasure code above is a bit ugly. To be fair, I just implemented a language feature in C++ without direct language support for it.
I've seen some proposals to make type erasure easier in C++. I do not know the status of those proposals.
If you want to do your own, here is an "easy" way to do type erasure in 3 steps:
First, determine what operations you want to erase. Write the equivalent of input_iterator<T> -- give it a bunch of methods and operators that do what you want. Be sparse. Call this the "external type". Ideally nothing in this type is virtual, and it should be a Regular or Semi-regular type (ie, it should behave value-like, or move-only-value-like). Don't implement anything but the interface yet.
Second, write an inner class erase. It provides a pure-virtual interface to a set of functions that could provide what you need in your external type.
Store a unique_ptr<erase> pimpl; within the external type. Forward the methods you expose in the external type to the pimpl;.
Third, write an inner template<class X> class impl<X>:erase. It stores a variable X x;, and it implements everything in erase by interacting with X. It should be constructable from an X (with optional perfect forwarding).
You then create a perfect forwarding constructor for the external type that creates its pimpl via a new impl<X>(whatever). Ideally it should check that its argument is a valid one via SFINAE techniques, but that is just a qualify of implementation issue.
Now the external type "erases" the type of any object it is constructed from "down to" the operations you exposed.
Now, for your actual problem, I'd write array_view or steal std::experimental::array_view, and restrict my input to be any kind of contiguous buffer of data of that type. This is more performant, and accepting any sequence is over engineering unless you really need it.

Refining CQLinq rule for nested visibility

We have NDepend 5.4.1 and we want to alter the queries for field/type/method that could have lower visibility. We want the query to take the scope of the enclosing class into account when deciding whether to consider it a violation.
For example,
internal class X
{
public int A;
public void B() { }
public class C
{
// …
}
}
We don’t want A, B or C to generate a violation saying that any of them should be made internal. If class X was public, on the other hand, and none of A, B and C is used outside the assembly, then they should all generate violations.
To accomplish this, I added the following line to the queries:
// consider visibility of enclosing class
f.ParentType.Visibility < f.OptimalVisibility
So for fields, the new query looks like:
// <Name>Fields that could have a lower visibility</Name>
warnif count > 0 from f in JustMyCode.Fields where
f.Visibility != f.OptimalVisibility &&
!f.HasAttribute("NDepend.Attributes.CannotDecreaseVisibilityAttribute".AllowNoMatch()) &&
!f.HasAttribute("NDepend.Attributes.IsNotDeadCodeAttribute".AllowNoMatch()) &&
// consider visibility of enclosing class
f.ParentType.Visibility < f.OptimalVisibility
select new { f,
f.Visibility ,
CouldBeDeclared = f.OptimalVisibility,
f.MethodsUsingMe }
I altered the query for method visibility and type visibility in a similar manner, except for types I make sure there is an enclosing parent type:
(t.ParentType == null || t.ParentType.Visibility < t.OptimalVisibility)
At first glance and after running some tests, this seems to be doing the right thing. My question is whether this will generate any false positives or miss any violations, since I am not sure whether the enum visibility orderings (comparisons) will do the right thing in all cases.
Here is the NDepend.CodeModel.Visibility enumeration declaration:
public enum Visibility {
None = 0,
Public = 1,
ProtectedAndInternal = 2,
ProtectedOrInternal = 3,
Internal = 4,
Protected = 5,
Private = 6
}
Hence x.ParentType.Visibility < x.OptimalVisibility means x parent type visibility is strictly less restrictive than x optimal visibility.
Notice that Protected is ordered as more restrictive than Internal which is not true neither Internal is more restrictive than Protected. So we had to provide an arbitrary ordering between these two visibility level.
Notice also that a method/field/nested type can be declared in a nested type (recursive) so to be correct we'd need to gather all outter types visibility.
These two facts make me thing that we could construct edge cases where your rule would return false positive, but after tinkering a bit I didn't succeed so.
What we advice is to look at your code base(s) how your custom rules behave to see if they should be modified. If it is fine, then consider it is fine until you eventually find a false positive.
There is a long related debate on the Eric Lippert blog about if a member of an internal type should be declared public or internal. There are solid arguments on both side, and the way our code rule is written favor the side it should be declared as internal, and your change favor the side it should be declared as public.

using macros to constrain lists

I am trying to constrain my list items to be equal to certain values under certain conditions.
For that I have devised a define as computed macro that
define <num_prob_constraints'struct_member> "CHECK_and_SET_CONSTRAINTS <lst'exp>" as computed {
//var cur : list of uint = <lst'exp>.as_a(list of uint);
var t : uint = <lst'exp>.as_a(list of uint).size();
print t;
for i from 1 to 4 {
result = append(result,"keep ",<lst'exp>,"[",i,"]==",i,"=> ",<lst'exp>,"[",i,"]==389; \n");
};
};
and in my code I use this macro like this:
struct schedule{
n : uint;
sched_w : list of list of int;
CHECK_and_SET_CONSTRAINTS sched_w;
};
But this does not work. First, it prints some random size (From the macro) instead of the list’s real size.
Secondly, I get errors of this sort:
*** Error: '1' is of type 'int', while expecting type 'list of int'.
in code generated by macro defined at line 3 in
sports_sched_macro.e
keep sched_w[1]==1=> sched_w[1]==389;
expanded at line 8 in sports_sched.e
CHECK_and_SET_CONSTRAINTS sched_w;
Any ideas on what is wrong here?
Macros are simply code substituts. Their function is simply to replace some string with another (calculated or not) during the parsing phase.
This means that the macro will be deployed where you used it in the parsing phase which precedes the generation phase. So, in fact, the list does not exist yet, and you cannot access it’s size and items.
More specifically, your macro is deployed this way:
struct schedule {
n : uint;
sched_w : list of list of int;
keep sched_w[1]==2=> sched_w[1]==389;
keep sched_w[2]==2=> sched_w[2]==389;
...
...
};
The error message you received tell you that you cannot access specific list items explicitly (since the list size and item’s values are yet undetermined).
If you want to keep your list with size 4, and if the value is 2 you want to replace it with 389, you may need to use the post_generate() method, as you are trying to access values that are already assigned to the list items:
keep sched_w.size()==4;
post_generate() is also{
for each in sched_w {
if (it==2) {it=389};
};
};
Are you sure you want to constrain a 2-dimensional list? This looks a bit different. E.g. for an array schedule[4][1]:
schedule: list of list of int;
keep schedule.size() == 4;
keep for each (sublist) in schedule {
sublist.size() == 1;
for each (elem) in sublist {
...
};
};