Modifies clause error on a changed object - automated-tests

How can I state (in Dafny) an "ensures" guarantee that the object returned by a method will be "new", i.e., will not be the same as an object used anywhere else (yet)?
The following code shows a minimal example:
method newArray(a:array<int>) returns (b:array<int>)
requires a != null
ensures b != null
ensures a != b
ensures b.Length == a.Length+1
{
b := new int[a.Length+1];
}
class Testing {
var test : array<int>;
method doesnotwork()
requires this.test!=null
requires this.test.Length > 10;
modifies this
{
this.test := newArray(this.test); //change array a with b
this.test[3] := 9; //error modifies clause
}
method doeswork()
requires this.test!=null
requires this.test.Length > 10;
modifies this
{
this.test := new int[this.test.Length+1];
this.test[3] := 9;
}
}
The "doeswork" function compiles (and verifies) correctly, but the other one does not, as the Dafny compiler cannot know that the object returned by the "newArray" function is new, i.e., is not required to be listed as modifiable in the "require" statement of the "doesnotwork" function in order for that function to fulfill the requirement that it only modifies "this". In the "doeswork" function, I simply inserted the definition of the "newArray" function, and then it works.
You can find the example above under https://rise4fun.com/Dafny/hHWwr, where it can also be ran online.
Thanks!

You can say ensures fresh(b) on newArray.
fresh means exactly what you described: the object is not the same as any object that was allocated before the call to newArray.

Related

in Delphi 5, is a TList parameter always passed by reference?

I am migrating some code from Delphi 5 to a modern platform. Currently I have the compiled code (which works in my environment) and the source code (which cannot be compiled in my environment). This means I can't really experiment with the code by changing it or inserting breakpoints or dumping values. In looking at one particular passage of code, I see that one Procedure (ProcedureA) is calling another (ProcedureB) and passing in parameters that must be by reference, since otherwise ProcedureB would have no effect. It's my understanding that a var prefix must be added to parameters in a Procedure's parameter list in order for them to be passed by reference, but this is not being done here. One of the parameters, though, is of type TList, which I know to be essentially an array of pointers. My question is: are parameters of type TList (as well as others having to do with pointers) implicitly passed by reference?
Here's the code:
Procedure ProcedureB(PartyHeaderInformationPtr : PartyHeaderInformationPointer;
PartyHeaderTable : TTable;
_PrisonCode : String;
_FineType : TFineTypes;
PartyHeaderInformationList : TList);
begin
with PartyHeaderInformationPtr^, PartyHeaderTable do
begin
AssessmentYear := FieldByName('TaxRollYr').Text;
PartyType := FieldByName('PartyType').Text;
PartyNumber := FieldByName('PartyNo').AsInteger;
PrisonCode := _PrisonCode;
FineType := _FineType;
end; {with PartyHeaderInformationPtr^ ...}
PartyHeaderInformationList.Add(PartyHeaderInformationPtr);
end; {AddPartyHeaderPointerInformation}
{=================================================================}
Procedure ProcedureA(PartyHeaderTable : TTable;
PartyDetailTable : TTable;
PartyHeaderInformationList : TList);
var
Done, FirstTimeThrough : Boolean;
PrisonPartyFound, JunglePartyFound : Boolean;
PrisonPartyYear, PrisonCode, PartyType : String;
PartyHeaderInformationPtr : PartyHeaderInformationPointer;
begin
PartyHeaderTable.Last;
PrisonPartyYear := '';
PrisonPartyFound := False;
JunglePartyFound := False;
Done := False;
FirstTimeThrough := True;
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else PartyHeaderTable.Prior;
If PartyHeaderTable.BOF
then Done := True;
If not Done
then
begin
PartyType := PartyHeaderTable.FieldByName('PartyType').Text;
If ((not JunglePartyFound) and
((PartyType = 'MU') or
(PartyType = 'TO')))
then
begin
JunglePartyFound := True;
New(PartyHeaderInformationPtr);
AddPartyHeaderPointerInformation(PartyHeaderInformationPtr,
PartyHeaderTable,
'', ltPlace,
PartyHeaderInformationList);
end; {If ((not JunglePartyFound) and ...}
end; {If not Done}
until Done;
end; {FillPartyHeaderInformationList}
Yes.
In Delphi, classes are reference types.
Every variable of type TBitmap, TList, TButton, TStringList, TForm etc. is nothing but a pointer to the object, so an object is always passed "by reference". It is only this address, this native-sized integer, that is given to the called routine.
Consequently, even without var, the called routine can alter the object since it, like the caller, has the address to it. But the pointer itself is passed by value, so if the called routine alters the parameter pointer to point to a different object, the caller will not see that; only the called routine's copy of the address is changed. With var, the pointer itself is passed by reference, so the called routine can change that too: it can change the original object, and it can make the caller's variable point to a different object, if it wants to.
On the other hand, value types like integers, booleans, sets, static arrays, and records are passed by value, so -- without any parameter decoration such as var -- the called routine gets a copy, and any changes made are only made to that copy. The caller will not see its variable being modified. If you use a var parameter, however, the variable will be passed by reference.
So, in your case, it has nothing to do with TList being a "list" or being something that "contains pointers". It's about TList being a class.

What does 'myVariable.(type)' return exactly?

I created a simple code
package main
import (
"fmt"
)
func main() {
a := 5
b := &a
Test(b)
fmt.Println(a)
fmt.Println(*b)
}
func Test(result interface{}){
switch r := result.(type) {
case *int:
*r = 10
}
}
You can run it here
In Test method inside switch statement I create new variable that is a type of my parameter.
Why does my variable 'b' update after update of this pointer. Why does this new variable points to the old one?
The result of program execution is
10
10
But expected
5
5
UPDATE
I'd like to precise the question. I did not assign my pointer to 'b' to variable 'r' in Test.
I expect that
r := result.(type)
gives me the type of the result. But why if I change value of a pointer of a new variable result is changed too
UPDATE 2
As suggested I checked again a specification and didn't found an answer. In the next construction
switch r := result.(type) {
case *int:
*r = 10
}
What does result.(type) return exactly?
A type switch compares types rather than values. It is otherwise similar > to an expression switch. It is marked by a special switch expression that > has the form of a type assertion using the reserved word type rather than > an actual type:
switch x.(type) {
// cases
}
See information on type assertions here and here.
There is a good description of pointers in go here.
In your code &a means the address of a and b returns a pointer to an int (*int).
In the Test function you are saying store the value 10 in the memory location pointed to by r.

D: Strange behaviour from std.container.BinaryHeap with custom function for comparison

I've written the following code for a heap of Node*s, which are found in module node:
import std.exception, std.container;
public import node;
alias NodeArray = Array!(const (Node)*);
alias NodeHeap = BinaryHeap!(NodeArray, cmp_node_ptr);
auto make_heap() {
return new NodeHeap(NodeArray(cast(const(Node)*)[]));
}
void insert(NodeHeap* heap, in Node* u) {
enforce(heap && u);
heap.insert(u);
}
pure bool cmp_node_ptr(in Node* a, in Node* b) {
enforce(a && b);
return (a.val > b.val);
}
I then tried running the following unit tests on it, where make_leaf returns a Node* initialized with the argument given:
unittest {
auto u = make_leaf(10);
auto heap = make_heap();
insert(heap, u); //bad things happen here
assert(heap.front == u);
auto v = make_leaf(20);
insert(heap, v);
assert(heap.front == u); //assures heap property
}
The tests make it to the line I comment-marked, and then throw an enforcement error on the line enforce(a && b) in cmp_node_ptr. I'm totally lost as to why this is happening.
you are doing wrong thing in this operator:
NodeArray(cast(const(Node)*)[])
you obviously want to create empty NodeArray, but what you really got is NodeArray with one null item. NodeArray constructor takes list of values for new array as arguments, and you passing one "empty array" (which is essentially null), thus creating NodeArray with one null element.
the correct way is just:
NodeArray()
i.e.:
auto make_heap() {
return new NodeHeap();
}
make this change and everything will be fine.
p.s. it seems that D notation for multiple arguments of type U (U[] values...) made you think that constructor accepts another array as initialiser.
p.p.s. sorry, fixed make_heap() code: accidentally forgot to write "NodeArray()" in it. and edited it again, as empty NodeArray() call is not necessary there. double fault!

In go reflection package, is the call Value.Kind() a syntactic sugar to Value.Type().Kind()?

Both of the reflect.Type interface and reflect.Value type implement the same Kind() method signature, suppose that we have some value object v := reflect.ValueOf(x)
Is v.Kind() just call v.Type().Kind() ?
They contain the same value, but do not seem to refer to the same thing:
type.go source
value.go source
A Type is usually implemented by unexported struct rtype (via TypeOf), while the Value contains a *rtype and extends flag, which is itself a reduced form of the Kind:
// flag holds metadata about the value.
// The lowest bits are flag bits:
// - flagRO: obtained via unexported field, so read-only
// - flagIndir: val holds a pointer to the data
// - flagAddr: v.CanAddr is true (implies flagIndir)
// - flagMethod: v is a method value.
// The next five bits give the Kind of the value.
// This repeats typ.Kind() except for method values.
// The remaining 23+ bits give a method number for method values.
// If flag.kind() != Func, code can assume that flagMethod is unset.
// If typ.size > ptrSize, code can assume that flagIndir is set.
When getting the ValueOf something:
// ValueOf returns a new Value initialized to the concrete value
// stored in the interface i. ValueOf(nil) returns the zero Value.
func ValueOf(i interface{}) Value {
[...]
// For an interface value with the noAddr bit set,
// the representation is identical to an empty interface.
eface := *(*emptyInterface)(unsafe.Pointer(&i))
typ := eface.typ
/** Flag is built from the type, then kept separate (my comment) */
fl := flag(typ.Kind()) << flagKindShift
if typ.size > ptrSize {
fl |= flagIndir
}
return Value{typ, unsafe.Pointer(eface.word), fl}
}
And so when you get the kind of a Value (remember it extends its flag):
func (v Value) Kind() Kind {
return v.kind()
}
func (f flag) kind() Kind {
return Kind((f >> flagKindShift) & flagKindMask)
}
While getting the kind of a type: (Type is an interface, usually implemented by *rtype)
func (t *rtype) Kind() Kind { return Kind(t.kind & kindMask) }
So although they seem to be equal in most of the cases, v.Kind() is not v.Type().Kind()
The file reflect/value.go states that the relevant field in the implementation of reflect.Value "repeats typ.Kind() except for method values". So, unless the value is a method, value.Kind() and value.Type().Kind() return the same number.

ARC [rewriter] NSInvocation's setArgument is not safe to be used with an object with ownership other than __unsafe_unretained

I been to convert my project to ARC and i m stuck with this error.
&object,&invocation and &callerToRetain is showing me error of "[rewriter] NSInvocation's setArgument is not safe to be used with an object with ownership other than __unsafe_unretained"
+ (void)performSelector:(SEL)selector onTarget:(id *)target withObject:(id)object amount:(void *)amount callerToRetain:(id)callerToRetain{if ([*target respondsToSelector:selector]) {
NSMethodSignature *signature = nil;
signature = [*target methodSignatureForSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setSelector:selector];
int argumentNumber = 2;
// If we got an object parameter, we pass a pointer to the object pointer
if (object) {
[invocation setArgument:&object atIndex:argumentNumber];
argumentNumber++;
}
// For the amount we'll just pass the pointer directly so NSInvocation will call the method using the number itself rather than a pointer to it
if (amount) {
[invocation setArgument:amount atIndex:argumentNumber];
}
SEL callback = #selector(performInvocation:onTarget:releasingObject:);
NSMethodSignature *cbSignature = [ASIHTTPRequest methodSignatureForSelector:callback];
NSInvocation *cbInvocation = [NSInvocation invocationWithMethodSignature:cbSignature];
[cbInvocation setSelector:callback];
[cbInvocation setTarget:self];
[cbInvocation setArgument:&invocation atIndex:2];
[cbInvocation setArgument:&target atIndex:3];
if (callerToRetain) {
[cbInvocation setArgument:&callerToRetain atIndex:4];
}
CFRetain(invocation);
// Used to pass in a request that we must retain until after the call
// We're using CFRetain rather than [callerToRetain retain] so things to avoid earthquakes when using garbage collection
if (callerToRetain) {
CFRetain(callerToRetain);
}
[cbInvocation performSelectorOnMainThread:#selector(invoke) withObject:nil waitUntilDone:[NSThread isMainThread]];
}}
Please help me out.
An NSInvocation by default does not retain or copy given arguments for efficiency, so each object passed as argument must still live when the invocation is invoked. That means the pointers passed to -setArgument:atIndex: are handled as __unsafe_unretained.
If you use NSInvocation in ARC, the simplest way to get it working is
call [invocation retainArguments] after creating the invocation object. That means the invocation will retain the given arguments.
When passing the arguments, cast them to __unsafe_unretained.
There is no step 3.

Resources