Context's modifies clause violation for class with autocontracts - dafny

I have a simple class with autocontracts in Dafny, that creates a new instance of itself.
But Dafny says that "call might violate context's modifies clause" when I call foo.Add() inside Bar method
I can't tell why I'm getting this error since the class does not have any attributes
Am I missing something?
class {:autocontracts} Foo {
predicate Valid()
constructor() { }
method Add() returns (b:bool)
method Bar() returns (fo:Foo)
ensures fresh(fo)
{
fo := new Foo();
var i := 0;
while(i < 3)
modifies fo
invariant fo.Valid()
{
var ret := fo.Add(); //call might violate context's modifies clause Verifier
i := 1 + i;
}
}
}
Dafny Version at VSCode
the installed Dafny version is the latest known: 3.9.0.41003 = 3.9.0

I think you might have oversimplified your example, because I'm not sure I understand your question.
I think the answer you are looking for is that you should delete the line
modifies fo
from the loop and add the line
invariant fresh(fo.Repr)
This fixes the error about violating the context's modifies clause.
The remaining error in the code you did not mention, but it has to do with the autocontracts postcondition for Bar, which is
this.Valid() && fresh(this.Repr - old(this.Repr))
This is doubly confusing because the Foo class has no fields, and the Bar method never mentions this. So one fix would be to make Bar a static method.
Alternatively, if in your original setting you need Bar to be non-static, then you can add the invariant
invariant this.Valid() && fresh(this.Repr - old(this.Repr))
to the loop to fix this second error.

Related

vector<reference_wrapper> .. things going out of scope? how does it work?

Use case: I am converting data from a very old program of mine to a database friendly format. There are parts where I have to do multiple passes over the old data, because in particular the keys have to first exist before I can reference them in relationships. So I thought why not put the incomplete parts in a vector of references during the first pass and return it from the working function, so I can easily use that vector to make the second pass over whatever is still incomplete. I like to avoid pointers when possible so I looked into std::reference_wrapper<T> which seemes like exactly what I need .. except I don't understand it's behavior at all.
I have both vector<OldData> old_data and vector<NewData> new_data as member of my conversion class. The converting member function essentially does:
//...
vector<reference_wrapper<NewData>> incomplete;
for(const auto& old_elem : old_data) {
auto& new_ref = *new_data.insert(new_data.end(), convert(old_elem));
if(is_incomplete(new_ref)) incomplete.push_back(ref(new_ref));
}
return incomplete;
However, incomplete is already broken immediately after the for loop. The program compiles, but crashes and produces gibberish. Now I don't know if I placed ref correctly, but this is only one of many tries where I tried to put it somewhere else, use push_back or emplace_back instead, etc. ..
Something seems to be going out of scope, but what? both new_data and old_data are class members, incomplete also lives outside the loop, and according to the documentation, reference_wrapper is copyable.
Here's a simplified MWE that compiles, crashes, and produces gibberish:
// includes ..
using namespace std;
int main() {
int N = 2; // works correctly for N = 1 without any other changes ... ???
vector<string> strs;
vector<reference_wrapper<string>> refs;
for(int i = 0; i < N; ++i) {
string& sref = ref(strs.emplace_back("a"));
refs.push_back(sref);
}
for (const auto& r : refs) cout << r.get(); // crash & gibberish
}
This is g++ 10.2.0 with -std=c++17 if it means anything. Now I will probably just use pointers and be done, but I would like to understand what is going on here, documentation / search does not seem to help..
The problem here is that you are using vector data structure which might re-allocate memory for the entire vector any time that you add an element, so all previous references on that vector most probably get invalidated, you can resolve your problem by using list instead of vector.

Way to defensive check value assigned to public const variable in immutable class in C++17?

Coming back to C++ after a hiatus in Java. Attempting to create an immutable object and after working in Java, a public const variable seems the most sensible (like Java final).
public:
const int A;
All well and good, but if I want to defensive check this value, how might I go about it. The code below seems strange to me, but unlike Java final members, I can't seem to set A in the constructor after defensive checks (compiler error).
MyObj::MyObj(int a) : A(a) {
if (a < 0)
throw invalid_argument("must be positive");
}
A public const variable for A seems like a clearer, cleaner solution than a getter only with a non const int behind it, but open to that or other ideas if this is bad practice.
Your example as it stands should work fine:
class MyObj {
public:
const int var;
MyObj(int var) : var(var) {
if (var < 0)
throw std::invalid_argument("must be positive");
}
};
(Live example, or with out-of-line constructor)
If you intend that MyObj will always be immutable, then a const member is
probably fine. If you want the variable to be immutable in general, but still have the possibility to overwrite the entire object with an assignment, then better to have a private variable with a getter:
class MyObj {
int var;
public:
MyObj(int var) : var(var) {
if (var < 0)
throw std::invalid_argument("must be positive");
}
int getVar() const { return var; }
};
// now allows
MyObj a(5);
MyObj b(10);
a = b;
Edit
Apparently, what you want to do is something like
MyObj(int var) {
if (var < 0)
throw std::invalid_argument("must be positive");
this->var = var;
}
This is not possible; once a const variable has a value it cannot be changed. Once the body ({} bit) of the constructor starts, const variables already have a value, though in this case the value is "undefined" since you're not setting it (and the compiler is throwing an error because of it).
Moreover, there's actually no point to this. There is no efficiency difference in setting the variable after the checks or before them, and it's not like any external observers will be able to see the difference regardless since the throw statement will unroll the stack, deconstructing the object straight away.
Generally the answer by N. Shead is the regular practice - but you can also consider:
Create domain-specific types and use them instead of general primitives. E.g., if your field is a telephone number, have a type TelephoneNumber which, in its constructor (or factory), taking a string, does all the telephone number validation you'd like (and throws on invalid). Then you write something like:
class Contact {
const TelephoneNumber phone_;
public:
Contact(string phone) : phone_(phone) { ... }
...
When you do this the constructor for TelephoneNumber taking a string argument will be called when initializing the field phone_ and the validation will happen.
Using domain-specific types this way is discussed on the web under the name "primitive obsession" as a "code smell".
(The problem with this approach IMO is that you pretty much have to use it everywhere, and from the start of your project, otherwise you start having to have explicit (or implicit) casting all over the place and your code looks like crap and you can never be sure if the value you have has been validated or not. If you're working with an existing codebase it is nearly impossible to retrofit it completely though you might just start using it for particularly important/ubiquitous types.)
Create validation methods that take and return some value, and which perform the validation necessary - throwing when invalid otherwise returning its argument. Here's an example validator:
string ValidatePhoneNumber(string v) {
<some kind of validation throwing on invalid...>
return v;
}
And use it as follows:
class Contact {
const string phone_;
public:
Contact(string phone) : phone_(ValidatePhoneNumber(phone)) { ... }
I've seen this used when an application or library is doing so much validation of domain-specific types that a small library of these domain-specific validator methods has been built up and code readers are used to them. I wouldn't really consider it idiomatic, but it does have the advantage that the validation is right out there in the open where you can see it.

Overwriting array in dafny

I'm trying to overwrite an array inside a method. The compiler is giving me the error "Error: LHS of assignment must denote a mutable variable".
method invalidSort(a : array<int>)
modifies a;
requires a != null;
ensures sorted(a[..]);
{
a := new int[0];
}
Am I staring myself blind and missing something or why does Dafny not allow this?
In Dafny, method parameters cannot be assigned to. You can use a local variable if you need to update the value internally.
For example,
var a' := new int[0];
If you want this new array to be available to the caller, you'll also need to return it.
return a';
All that said, if you're trying to write an in-place sorting method, then you don't need to do any of this. Just modify a in place.
a[0] := 0;
// ...

Very untyped and recursive class definition that compiles but seems a corner case to me

These 4 lines compile but do not make sense to me :
open System
type mclas (y) =
member x.m = x.m
let z = mclas (1:>obj)
Question : In what case would we need to code in such way ? Am I activating subtle class features I am not aware of ?
Edit : If there is no use case, what is the status of this piece of code regarding compiler warning/error and is it eligible for some Issue raising on github ?
Note : At runtime, the debugger cannot evaluate variable z saying "Function evaluation timed out".
The member m actually compiles to something like this in IL:
.property instance object m {
.get instance object Program/mclas::get_m()
}
So m is a property of type object which has a getter that recurses endless. The C# equivalent of this would be:
public class mclas
{
public mclas(object y) { }
public object x {
get {
return x;
}
}
}
Because the recursion never ends, taking too long and/or there is a StackOverflowException happening when the Debugger tries to evaluate m, it cancels and spits out that the evaluation timed out.
And for your actual question: I don't think that you ever need this kind of self-reference in F#, at least I can't think of any possible use.
I think that this behaviour of the compiler makes sense, because a member without paramters will always compile to a get-only property, and then this would be the most obvious way of defining an infinite recursing property (just because this has no use doesn't mean that you can't do it).

Member variable becomes null, spuriously?

I observe an assertion failure which I've attempted to sketch below. Briefly, an initialized class member becomes null spuriously when I call an overridden method.
abstract class A<T> {
T target
def something() {
assert target != null // sanity check -- fails when invoked below
return this
}
}
class B extends A<Something> {
static B makeB() {
def b = new B()
b.target = new Something();
assert b.target != null
return b
}
}
// package test
// Test code
//
def b = B.makeB() // <-- success.
assert b != null
assert b.target != null
b.something() // <-- fails assertion
print "Success!"
I'm having trouble producing a minimal test case -- the above (with Long in place of Something) runs successfully at compileonline.com but not with our code on our machines.
The problem goes away if I re-implement the something method in the subclass B.
Has anybody observed a similar effect? I'm already quite frustrated at this.
Problem Found: A Mixin uses the same member name
Stepping through the code and examining local stack variables carefully, we found that the Grails Integration Test Mixin has an instance variable target that was receiving the assignment messages. Presumably, any instance variable sharing a name with a mixin's instance variable should be subject to the behavior I describe above, but we don't know the complete set of conditions
The most reasonably solution time-wise (with a nod #cfrick) was to rename our variable target to something else.
Follow-up Questions
Is this expected behavior? Best solution in a sea of bad ones?
Has this behavior changed with a new Groovy compiler or Grails stack?
(still relevant) What is the minimal test case?

Resources