How can I modify an overwritten array correctly? - automated-tests

How can I overwrite an array, which is marked as modified, in a method?
Or is there a way in Dafny just increase the length of an array by one?
class ownerIndexs{
var oi : map<int, int>;
constructor(){
new;
}
}
class Pendingstate{
var yetNeeded : int;
var ownersDone : bv256;
var index : int;
}
class mo{
var m_pendingIndex : array<int>;
var m_ownerIndex : ownerIndexs;
var m_pending : map<int, Pendingstate>;
var m_required : int;
method confirmAndCheck(operation : int, msgsender : int) returns
(boo : bool, ownerIndex :int,pending : Pendingstate)
requires m_pendingIndex != null
modifies this.m_pendingIndex
ensures m_pendingIndex != null && pending != null
==> 0 < pending.index < m_pendingIndex.Length
&& m_pendingIndex[pending.index] == operation
{
pending := new Pendingstate;
pending.index := m_pendingIndex.Length;
this.m_pendingIndex := extendArrayByOne(this.m_pendingIndex); //Problem with modify clause
m_pendingIndex[pending.index] := operation;
}
method extendArrayByOne(oldarray:array<int>) returns (newarray:array<int>)
requires oldarray!=null
ensures newarray != null
ensures fresh(newarray)
ensures newarray.Length == oldarray.Length+1
ensures forall k::0 <= k <oldarray.Length ==> oldarray[k] == newarray[k]
modifies oldarray
{
newarray := new int[oldarray.Length+1];
var i:=0;
while (i < oldarray.Length)
invariant newarray.Length == oldarray.Length+1
invariant i<=oldarray.Length
invariant forall k::0 <= k < i ==> oldarray[k] == newarray[k]
{
newarray[i] := oldarray[i];
i := i + 1;
}
}
}
As you can see in this code.
I am trying to increase the length of an array by one in the method extendArrayByOne.
After that I am adding the element operation at the end of the new array, which was returned from extendArrayByOne, in the method confirmAndCheck.
Here is a link to a official compiler, which can compile this code:
https://rise4fun.com/Dafny/WtjA
And here is the link to my previous question about extendArrayByOne:
Modifies clause error on a changed object

Related

How to avoid decreases and modify violation?

How I can avoid a decreases error, if my index will be not decreases after every iteration?
And why I am getting a modify clause on an object and an array, while I am using modify clause on them?
class ownerIndexs{
var oi : map<int, int>;
constructor(){
new;
}
}
class multiowned{
var m_numOwners : int;
var m_owners : array<int>;
var m_ownerIndex : ownerIndexs;
method reorganizeOwners() returns (boo : bool)
requires m_owners != null && m_ownerIndex != null
requires m_owners.Length >= 2
requires 0 <= m_numOwners < m_owners.Length
modifies this
modifies this.m_owners
modifies this.m_ownerIndex;
{
var frees : int := 1;
while (frees < m_numOwners)
decreases m_numOwners - frees //error 1
invariant m_owners != null && m_numOwners < m_owners.Length
invariant m_ownerIndex != null
{
while (frees < m_numOwners && m_owners[frees] != 0)
decreases m_numOwners - frees
invariant frees <= m_numOwners
invariant m_owners != null && m_numOwners < m_owners.Length
invariant m_ownerIndex != null
{
frees := frees +1;
}
while (m_numOwners > 1 && m_owners[m_numOwners] == 0)
invariant m_owners != null && m_numOwners < m_owners.Length
invariant m_ownerIndex != null
{
m_numOwners := m_numOwners-1;
}
if (frees < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[frees] == 0)
{
m_owners[frees] := m_owners[m_numOwners]; //error 2
m_ownerIndex.oi := m_ownerIndex.oi[m_owners[frees] := frees]; //error 3
m_owners[m_numOwners] := 0;
}
}
boo := true;
}
}
I upload this code also in Dafny, where you can compile it again: https://rise4fun.com/Dafny/bYDH .
As you can see, I modified the array m_owner and also outsourced ownerIndex to an another object, because of other modify violations issues.
But here it seems like dafnys language is limited, isn`t it?
You write modifies this.m_owners but when you go to modify this.m_owners, Dafny doesn't know that this.m_owners still refers to the same object as it did at the beginning of the method.
Try adding these invariants to your while loops,
invariant this.m_owners == old(this.m_owners)
invariant this.m_ownerIndex == old(this.m_ownerIndex)
For the decreases clause, you'll need to prove to Dafny that m_numOwners - frees actually decreases, which doesn't seem true to me - it seems to me like it could be the case that both inner while-loop conditions will be false, in which case neither m_numOwners nor frees will change. That could be a bug in your code, or maybe you need more preconditions and invariants, I'm not sure of your intent.

Convert uintptr from reflection into pointer (*)

I just can't find the way to get a slice of pointer to each attribute of a given struct. I am using reflection to get my pointers (Thanks to https://stackoverflow.com/a/24348352/6093604)
if valueField.CanAddr() {
address = fmt.Sprintf("0x%X", valueField.Addr().Pointer())
}
As you can see, valueField.Addr().Pointer() returns a pointer addr value, however, using reflection, I would like to get a usable pointer for sql.Rows.Scan()
So what did I do is:
func StructAttributesToPointersSlice(object interface{}) []interface{} {
val := reflect.ValueOf(object)
if val.Kind() == reflect.Interface && !val.IsNil() {
elm := val.Elem()
if elm.Kind() == reflect.Ptr && !elm.IsNil() && elm.Elem().Kind() == reflect.Ptr {
val = elm
}
}
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
var ptrs []interface{}
for i := 0; i < val.NumField(); i++ {
valueField := val.Field(i)
if valueField.Kind() == reflect.Ptr {
valueField = valueField.Elem()
}
if valueField.CanAddr() {
ptrs = append(ptrs, valueField.Addr().Pointer())
}
}
return ptrs
}
But when I try to use it for Scan() sql function:
var values []interface{}
// Iterate over each rows got from the query
for rows.Next() {
ptrs := utils.StructAttributesToPointersSlice(&newObject)
for _, item := range ptrs {
fmt.Println(reflect.TypeOf(item))
}
err = rows.Scan(ptrs...)
if err != nil {
return nil, model.Status{Code: http.StatusInternalServerError, Error: err.Error()}
} else {
values = append(values, newObject)
}
}
I am getting this error:
sql: Scan error on column index 0: destination not a pointer
I know it's because it's not the good type since it's a uintptr, but then how to transform it into usable pointer?
Thanks
Use unsafe.Pointer to convert a uintptr to a pointer of some type. As an example, the following expression converts uintptr u to a T pointer:
(*T)(unsafe.Pointer(u))
This conversion does not help in StructAttributesToPointersSlice because the struct fields can be of any type. Also, the conversion from uintptr is not needed and unsafe.
The expression valueField.Addr() is the reflect.Value for the pointer to the field. Call Interface() to get the actual pointer. To fix the program, change
ptrs = append(ptrs, valueField.Addr().Pointer())
to
ptrs = append(ptrs, valueField.Addr().Interface())
Here's a simplified version of the function:
func StructAttributesToPointersSlice(object interface{}) []interface{} {
v := reflect.ValueOf(object)
if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct {
panic("argument must be a pointer to struct")
}
v = v.Elem()
var result []interface{}
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
if !f.CanSet() {
continue
}
result = append(result, f.Addr().Interface())
}
return result
}
Some notes about this code:
The argument must be a pointer to a struct.
There's no need to call CanAddr on the fields. The check for pointer to struct covers this.
The CanSet() skips over unexported fields. You may want it to panic instead.
The function panics for errors in the caller. Consider returning an error instead.
playground example

Get fields of empty struct slice in Go

I have a function
func (r *render) foo(v interface{}) {
val := reflect.ValueOf(v)
fields := structs.Fields(val.Index(0).Interface())
...
Which takes a slice of structs and tries to get the fields of v,
however if v is empty then "val.Index(0)" crashes the program. Is there a better way to do this?
You need to check first if you have a slice to begin with, then check if you have an empty slice, and you probably should check that you have a struct too while you're at it: (example)
val := reflect.ValueOf(v)
if val.Kind() != reflect.Slice {
fmt.Println("not a slice")
return
}
if val.Len() == 0 {
fmt.Println("empty slice")
return
}
if val.Index(0).Kind() != reflect.Struct {
fmt.Println("not a slice of structs")
return
}
fields := structs.Fields(val.Index(0).Interface())
...
If you only want the fields from a struct type, regardless of if the slice is empty, you can use the slice type's Elem method to extract it (example)
// get the internal type of the slice
t := val.Type().Elem()
if t.Kind() != reflect.Struct {
fmt.Println("not a struct")
return
}
fmt.Println("Type:", t)
for i := 0; i < t.NumField(); i++ {
fmt.Println(t.Field(i).Name)
}

In Swift can I use a tuple as the key in a dictionary?

I'm wondering if I can somehow use an x, y pair as the key to my dictionary
let activeSquares = Dictionary <(x: Int, y: Int), SKShapeNode>()
But I get the error:
Cannot convert the expression's type '<<error type>>' to type '$T1'
and the error:
Type '(x: Int, y: Int)?' does not conform to protocol 'Hashable'
So.. how can we make it conform?
The definition for Dictionary is struct Dictionary<KeyType : Hashable, ValueType> : ..., i.e. the type of the key must conform to the protocol Hashable. But the language guide tells us that protocols can be adopted by classes, structs and enums, i.e. not by tuples. Therefore, tuples cannot be used as Dictionary keys.
A workaround would be defining a hashable struct type containing two Ints (or whatever you want to put in your tuple).
As mentioned in the answer above, it is not possible. But you can wrap tuple into generic structure with Hashable protocol as a workaround:
struct Two<T:Hashable,U:Hashable> : Hashable {
let values : (T, U)
var hashValue : Int {
get {
let (a,b) = values
return a.hashValue &* 31 &+ b.hashValue
}
}
}
// comparison function for conforming to Equatable protocol
func ==<T:Hashable,U:Hashable>(lhs: Two<T,U>, rhs: Two<T,U>) -> Bool {
return lhs.values == rhs.values
}
// usage:
let pair = Two(values:("C","D"))
var pairMap = Dictionary<Two<String,String>,String>()
pairMap[pair] = "A"
Unfortunately, as of Swift 4.2 the standard library still doesn't provide conditional conformance to Hashable for tuples and this is not considered valid code by the compiler:
extension (T1, T2): Hashable where T1: Hashable, T2: Hashable {
// potential generic `Hashable` implementation here..
}
In addition, structs, classes and enums having tuples as their fields won't get Hashable automatically synthesized.
While other answers suggested using arrays instead of tuples, this would cause inefficiencies. A tuple is a very simple structure that can be easily optimized due to the fact that the number and types of elements is known at compile-time. An Array instance almost always preallocates more contiguous memory to accommodate for potential elements to be added. Besides, using Array type forces you to either make item types the same or to use type erasure. That is, if you don't care about inefficiency (Int, Int) could be stored in [Int], but (String, Int) would need something like [Any].
The workaround that I found relies on the fact that Hashable does synthesize automatically for fields stored separately, so this code works even without manually adding Hashable and Equatable implementations like in Marek Gregor's answer:
struct Pair<T: Hashable, U: Hashable>: Hashable {
let first: T
let second: U
}
No need special code or magic numbers to implement Hashable
Hashable in Swift 4.2:
struct PairKey: Hashable {
let first: UInt
let second: UInt
func hash(into hasher: inout Hasher) {
hasher.combine(self.first)
hasher.combine(self.second)
}
static func ==(lhs: PairKey, rhs: PairKey) -> Bool {
return lhs.first == rhs.first && lhs.second == rhs.second
}
}
More info: https://nshipster.com/hashable/
I created this code in an app:
struct Point2D: Hashable{
var x : CGFloat = 0.0
var y : CGFloat = 0.0
var hashValue: Int {
return "(\(x),\(y))".hashValue
}
static func == (lhs: Point2D, rhs: Point2D) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
}
struct Point3D: Hashable{
var x : CGFloat = 0.0
var y : CGFloat = 0.0
var z : CGFloat = 0.0
var hashValue: Int {
return "(\(x),\(y),\(z))".hashValue
}
static func == (lhs: Point3D, rhs: Point3D) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z
}
}
var map : [Point2D : Point3D] = [:]
map.updateValue(Point3D(x: 10.0, y: 20.0,z:0), forKey: Point2D(x: 10.0,
y: 20.0))
let p = map[Point2D(x: 10.0, y: 20.0)]!
If you don't mind a bit of inefficiency, you can easily convert your tuple to a string and then use that for the dictionary key...
var dict = Dictionary<String, SKShapeNode>()
let tup = (3,4)
let key:String = "\(tup)"
dict[key] = ...
You can't yet in Swift 5.3.2, But you can use an Array instead of tuple:
var dictionary: Dictionary<[Int], Any> = [:]
And usage is simple:
dictionary[[1,2]] = "hi"
dictionary[[2,2]] = "bye"
Also it supports any dimentions:
dictionary[[1,2,3,4,5,6]] = "Interstellar"
I suggest to implement structure and use solution similar to boost::hash_combine.
Here is what I use:
struct Point2: Hashable {
var x:Double
var y:Double
public var hashValue: Int {
var seed = UInt(0)
hash_combine(seed: &seed, value: UInt(bitPattern: x.hashValue))
hash_combine(seed: &seed, value: UInt(bitPattern: y.hashValue))
return Int(bitPattern: seed)
}
static func ==(lhs: Point2, rhs: Point2) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
}
func hash_combine(seed: inout UInt, value: UInt) {
let tmp = value &+ 0x9e3779b97f4a7c15 &+ (seed << 6) &+ (seed >> 2)
seed ^= tmp
}
It's much faster then using string for hash value.
If you want to know more about magic number.
Add extension file to project (View on gist.github.com):
extension Dictionary where Key == Int64, Value == SKNode {
func int64key(_ key: (Int32, Int32)) -> Int64 {
return (Int64(key.0) << 32) | Int64(key.1)
}
subscript(_ key: (Int32, Int32)) -> SKNode? {
get {
return self[int64key(key)]
}
set(newValue) {
self[int64key(key)] = newValue
}
}
}
Declaration:
var dictionary: [Int64 : SKNode] = [:]
Use:
var dictionary: [Int64 : SKNode] = [:]
dictionary[(0,1)] = SKNode()
dictionary[(1,0)] = SKNode()
Or just use Arrays instead. I was trying to do the following code:
let parsed:Dictionary<(Duration, Duration), [ValveSpan]> = Dictionary(grouping: cut) { span in (span.begin, span.end) }
Which led me to this post. After reading through these and being disappointed (because if they can synthesize Equatable and Hashable by just adopting the protocol without doing anything, they should be able to do it for tuples, no?), I suddenly realized, just use Arrays then. No clue how efficient it is, but this change works just fine:
let parsed:Dictionary<[Duration], [ValveSpan]> = Dictionary(grouping: cut) { span in [span.begin, span.end] }
My more general question becomes "so why aren't tuples first class structs like arrays are then? Python pulled it off (duck and run)."
struct Pair<T:Hashable> : Hashable {
let values : (T, T)
init(_ a: T, _ b: T) {
values = (a, b)
}
static func == (lhs: Pair<T>, rhs: Pair<T>) -> Bool {
return lhs.values == rhs.values
}
func hash(into hasher: inout Hasher) {
let (a, b) = values
hasher.combine(a)
hasher.combine(b)
}
}
let myPair = Pair(3, 4)
let myPairs: Set<Pair<Int>> = set()
myPairs.update(myPair)

Reflecting The Fields of a Empty's Slices Underyling Type?

I have the following query builder function:
func CreateQuery(t interface{}, where string) {
var b bytes.Buffer
b.WriteString("SELECT ")
s := reflect.ValueOf(t).Elem()
typeOfT := s.Type()
for i := 0; i < s.NumField() - 1; i++ {
b.WriteString(fmt.Sprintf("%s, ", typeOfT.Field(i).Name))
}
//Last one has no Comma
b.WriteString(fmt.Sprintf("%s ", typeOfT.Field(s.NumField() - 1).Name))
b.WriteString(fmt.Sprintf("FROM %s ", typeOfT.Name()))
b.WriteString(where)
fmt.Println(b.String())
}
There works fine when called as follows:
var dst FooStruct
CreateQuery(&dst, "")
But the following raises a "call of reflect.Value.NumField on slice Value" Panic:
var dst []FooStruct
CreateQuery(&dst, "")
How I can I make the function print the fields of a slice's underlying struct type? It seems like I want the inverse of reflect's SliceOf function.
You can only call NumField or Field methods on a reflect.Type representing a struct (i.e. t.Kind() == reflect.Struct).
If you have a slice type, you can access the contained type via the Elem method, which returns another reflect.Type. If the slice contains a struct, then you can call NumField/Field on this type.
You can iterate over the slice, calling CreateQuery for every query:
func CreateQueries(t interface{}, where string) {
v := reflect.ValueOf(t)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() == reflect.Array || v.Kind() == reflect.Slice {
for i := 0; i < v.Len(); i++ {
CreateQuery(v.Index(i).Interface(), where)
}
}
}
Using reflect.Value.Index you can access each field separately, calling .Interface() on the
value yields the interface{} type representation of that value, making it suitable to put
it in your CreateQuery function (which expects a interface{} value).

Resources