id
stringlengths 3
3
| name
stringlengths 3
3
| docstring
stringlengths 18
18
| code
stringlengths 129
20.6k
| ground_truth
stringlengths 148
21.8k
| test_file
stringlengths 15
119
|
|---|---|---|---|---|---|
379
|
379
|
Dafny program: 379
|
method suma_it(V: array<int>) returns (x: int)
// Algoritmo iterativo que calcula la
// suma de las componentes de un vector
ensures x == suma_vector(V, 0)
{
var n := V.Length ;
x := 0 ;
while (n != 0)
{
x := x + V[n - 1] ;
n := n - 1 ;
}
}
function suma_vector(V: array<int>, n: nat): int
// x = V[n] + V[n + 1] + ... + V[N - 1]
// Funcion auxiliar para la suma de
// las componentes de un vector
requires 0 <= n <= V.Length
reads V
{
if (n == V.Length) then 0
else V[n] + suma_vector(V, n + 1)
}
method Main()
{
var v := new int[] [-1, 2, 5, -5, 8] ;
var w := new int[] [ 1, 0, 5, 5, 8] ;
var s1 := suma_it(v) ;
var s2 := suma_it(w) ;
print "La suma del vector v es: ", s1, "\n" ;
print "La suma del vector w es: ", s2 ;
}
|
method suma_it(V: array<int>) returns (x: int)
// Algoritmo iterativo que calcula la
// suma de las componentes de un vector
ensures x == suma_vector(V, 0)
{
var n := V.Length ;
x := 0 ;
while (n != 0)
invariant 0 <= n <= V.Length && x == suma_vector(V, n)
decreases n
{
x := x + V[n - 1] ;
n := n - 1 ;
}
}
function suma_vector(V: array<int>, n: nat): int
// x = V[n] + V[n + 1] + ... + V[N - 1]
// Funcion auxiliar para la suma de
// las componentes de un vector
requires 0 <= n <= V.Length
decreases V.Length - n
reads V
{
if (n == V.Length) then 0
else V[n] + suma_vector(V, n + 1)
}
method Main()
{
var v := new int[] [-1, 2, 5, -5, 8] ;
var w := new int[] [ 1, 0, 5, 5, 8] ;
var s1 := suma_it(v) ;
var s2 := suma_it(w) ;
print "La suma del vector v es: ", s1, "\n" ;
print "La suma del vector w es: ", s2 ;
}
|
TFG_tmp_tmpbvsao41w_Algoritmos Dafny_suma_it.dfy
|
381
|
381
|
Dafny program: 381
|
method mergeSimple(a1: seq<int>, a2: seq<int>, start: int, end: int, b: array<int>)
modifies b
requires sorted_seq(a1)
requires sorted_seq(a2)
requires 0 <= start <= end <= b.Length
requires |a1| + |a2| == end - start + 1
ensures sorted_slice(b, start, end)
{
var a1Pos := 0;
var a2Pos := 0;
var k := start;
while k < end
{
if a1Pos < |a1| && a2Pos < |a2| && a1[a1Pos] <= a2[a2Pos] {
b[k] := a1[a1Pos];
a1Pos := a1Pos + 1;
} else if a1Pos < |a1| && a2Pos < |a2| && a1[a1Pos] > a2[a2Pos] {
b[k] := a2[a2Pos];
a2Pos := a2Pos + 1;
} else if a1Pos < |a1| {
b[k] := a1[a1Pos];
a1Pos := a1Pos + 1;
} else {
b[k] := a2[a2Pos];
a2Pos := a2Pos + 1;
}
k := k + 1;
}
}
method merge(a1: seq<int>, a2: seq<int>, start: int, end: int, b: array<int>)
modifies b
requires sorted_seq(a1)
requires sorted_seq(a2)
requires end - start == |a1| + |a2|
requires 0 <= start < end < |a1| && end <= |a2| < b.Length
requires end < |a1| && end < |a2|
ensures sorted_slice(b, start, end)
requires b.Length == |a2| + |a1|
ensures merged(a1, a2, b, start, end)
{
var a1Pos := 0;
var a2Pos := 0;
var k := start;
while k < end
{
if a1Pos < |a1| && a2Pos < |a2| && a1[a1Pos] <= a2[a2Pos] {
b[k] := a1[a1Pos];
a1Pos := a1Pos + 1;
} else if a1Pos < |a1| && a2Pos < |a2| && a1[a1Pos] > a2[a2Pos] {
b[k] := a2[a2Pos];
a2Pos := a2Pos + 1;
} else if a1Pos < |a1| {
b[k] := a1[a1Pos];
a1Pos := a1Pos + 1;
} else {
b[k] := a2[a2Pos];
a2Pos := a2Pos + 1;
}
k := k + 1;
}
}
predicate merged(a1: seq<int>, a2: seq<int>, b: array<int>, start: int, end: int)
reads b
requires end - start == |a2| + |a1|
requires 0 <= start <= end <= b.Length
{
multiset(a1) + multiset(a2) == multiset(b[start..end])
}
predicate sorted_slice(a: array<int>, start: int, end: int)
requires 0 <= start <= end <= a.Length
reads a
{
forall i, j :: start <= i <= j < end ==> a[i] <= a[j]
}
predicate sorted_seq(a: seq<int>)
{
forall i, j :: 0 <= i <= j < |a| ==> a[i] <= a[j]
}
predicate sorted(a: array<int>)
reads a
{
forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j]
}
|
method mergeSimple(a1: seq<int>, a2: seq<int>, start: int, end: int, b: array<int>)
modifies b
requires sorted_seq(a1)
requires sorted_seq(a2)
requires 0 <= start <= end <= b.Length
requires |a1| + |a2| == end - start + 1
ensures sorted_slice(b, start, end)
{
var a1Pos := 0;
var a2Pos := 0;
var k := start;
while k < end
invariant (0 <= k && k <= end)
invariant sorted_slice(b, start, k)
invariant (|a1| - a1Pos) + (|a2| - a2Pos) == end - k + 1
invariant 0 <= a1Pos <= |a1|
invariant 0 <= a2Pos <= |a2|
invariant forall i :: start <= i < k && a1Pos < |a1| ==> b[i] <= a1[a1Pos]
invariant forall i :: start <= i < k && a2Pos < |a2| ==> b[i] <= a2[a2Pos]
{
if a1Pos < |a1| && a2Pos < |a2| && a1[a1Pos] <= a2[a2Pos] {
b[k] := a1[a1Pos];
a1Pos := a1Pos + 1;
} else if a1Pos < |a1| && a2Pos < |a2| && a1[a1Pos] > a2[a2Pos] {
b[k] := a2[a2Pos];
a2Pos := a2Pos + 1;
} else if a1Pos < |a1| {
assert(a2Pos >= |a2|);
b[k] := a1[a1Pos];
a1Pos := a1Pos + 1;
} else {
assert(a1Pos >= |a1|);
b[k] := a2[a2Pos];
a2Pos := a2Pos + 1;
}
k := k + 1;
}
}
method merge(a1: seq<int>, a2: seq<int>, start: int, end: int, b: array<int>)
modifies b
requires sorted_seq(a1)
requires sorted_seq(a2)
requires end - start == |a1| + |a2|
requires 0 <= start < end < |a1| && end <= |a2| < b.Length
requires end < |a1| && end < |a2|
ensures sorted_slice(b, start, end)
requires b.Length == |a2| + |a1|
ensures merged(a1, a2, b, start, end)
{
assert forall xs : seq<int> :: xs[0..|xs|] == xs;
assert forall xs : seq<int>, a,b : int :: 0 <= a < b < |xs| ==> xs[a..b+1] == xs[a..b] + [xs[b]];
var a1Pos := 0;
var a2Pos := 0;
var k := start;
while k < end
invariant (0 <= k && k <= end)
invariant sorted_slice(b, start, k)
invariant (|a1| - a1Pos) + (|a2| - a2Pos) == end - k
invariant 0 <= a1Pos <= |a1|
invariant 0 <= a2Pos <= |a2|
invariant forall i :: start <= i < k && a1Pos < |a1| ==> b[i] <= a1[a1Pos]
invariant forall i :: start <= i < k && a2Pos < |a2| ==> b[i] <= a2[a2Pos]
invariant merged(a1[0..a1Pos], a2[0..a2Pos], b, start, k)
{
if a1Pos < |a1| && a2Pos < |a2| && a1[a1Pos] <= a2[a2Pos] {
b[k] := a1[a1Pos];
a1Pos := a1Pos + 1;
} else if a1Pos < |a1| && a2Pos < |a2| && a1[a1Pos] > a2[a2Pos] {
b[k] := a2[a2Pos];
a2Pos := a2Pos + 1;
} else if a1Pos < |a1| {
assert(a2Pos >= |a2|);
b[k] := a1[a1Pos];
a1Pos := a1Pos + 1;
} else {
assert(a1Pos >= |a1|);
b[k] := a2[a2Pos];
a2Pos := a2Pos + 1;
}
k := k + 1;
}
}
predicate merged(a1: seq<int>, a2: seq<int>, b: array<int>, start: int, end: int)
reads b
requires end - start == |a2| + |a1|
requires 0 <= start <= end <= b.Length
{
multiset(a1) + multiset(a2) == multiset(b[start..end])
}
predicate sorted_slice(a: array<int>, start: int, end: int)
requires 0 <= start <= end <= a.Length
reads a
{
forall i, j :: start <= i <= j < end ==> a[i] <= a[j]
}
predicate sorted_seq(a: seq<int>)
{
forall i, j :: 0 <= i <= j < |a| ==> a[i] <= a[j]
}
predicate sorted(a: array<int>)
reads a
{
forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j]
}
|
VerifiedMergeSortDafny_tmp_tmpva7qms1b_MergeSort.dfy
|
382
|
382
|
Dafny program: 382
|
// http://verifythus.cost-ic0701.org/common-example/arraymax-in-dafny
method max(a:array<int>) returns(max:int)
requires a != null;
ensures forall j :: j >= 0 && j < a.Length ==> max >= a[j]; //max is larger then anything in the array
ensures a.Length > 0 ==> exists j :: j >= 0 && j < a.Length && max == a[j]; //max is an element in the array
{
if (a.Length == 0) {
max := 0;
return;
}
max := a[0];
var i := 1;
while i < a.Length
{
if a[i] > max
{
max := a[i];
}
i := i + 1;
}
}
|
// http://verifythus.cost-ic0701.org/common-example/arraymax-in-dafny
method max(a:array<int>) returns(max:int)
requires a != null;
ensures forall j :: j >= 0 && j < a.Length ==> max >= a[j]; //max is larger then anything in the array
ensures a.Length > 0 ==> exists j :: j >= 0 && j < a.Length && max == a[j]; //max is an element in the array
{
if (a.Length == 0) {
max := 0;
return;
}
max := a[0];
var i := 1;
while i < a.Length
invariant i <= a.Length //i is bounded by the array
invariant forall j :: 0 <= j < i ==> max >= a[j] //max is bigger or equal to anything seen so far (up to j)
invariant exists j :: 0 <= j < i && max==a[j] //max exists somewhere in the seen portion of the array
{
if a[i] > max
{
max := a[i];
}
i := i + 1;
}
}
|
Workshop_tmp_tmp0cu11bdq_Lecture_Answers_max_array.dfy
|
383
|
383
|
Dafny program: 383
|
//https://homepage.cs.uiowa.edu/~tinelli/classes/181/Fall21/Tools/Dafny/Examples/selection-sort.shtml
predicate sorted (a: array<int>)
requires a != null
reads a
{
sorted'(a, a.Length)
}
predicate sorted' (a: array<int>, i: int)
requires a != null
requires 0 <= i <= a.Length
reads a
{
forall k :: 0 < k < i ==> a[k-1] <= a[k]
}
// Selection sort on arrays
method SelectionSort(a: array<int>)
modifies a
ensures sorted(a)
//ensures multiset(old(a[..])) == multiset(a[..])
{
var n := 0;
while (n != a.Length)
{
var mindex := n;
var m := n + 1;
while (m != a.Length)
{
if (a[m] < a[mindex]) {
mindex := m;
}
m := m + 1;
}
a[n], a[mindex] := a[mindex], a[n];
n := n + 1;
}
}
|
//https://homepage.cs.uiowa.edu/~tinelli/classes/181/Fall21/Tools/Dafny/Examples/selection-sort.shtml
predicate sorted (a: array<int>)
requires a != null
reads a
{
sorted'(a, a.Length)
}
predicate sorted' (a: array<int>, i: int)
requires a != null
requires 0 <= i <= a.Length
reads a
{
forall k :: 0 < k < i ==> a[k-1] <= a[k]
}
// Selection sort on arrays
method SelectionSort(a: array<int>)
modifies a
ensures sorted(a)
//ensures multiset(old(a[..])) == multiset(a[..])
{
var n := 0;
while (n != a.Length)
invariant 0 <= n <= a.Length
invariant forall i, j :: 0 <= i < n <= j < a.Length ==> a[i] <= a[j] //all the values in the sorted section will be lower then any value in the non sorted section
invariant forall k1, k2 :: 0 <= k1 < k2 < n ==> a[k1] <= a[k2] //all values in the sorted section are sorted with respect to one another
{
var mindex := n;
var m := n + 1;
while (m != a.Length)
invariant n <= m <= a.Length //m (search idx) between valid range
invariant n <= mindex < m <= a.Length // minIndex between valid range
invariant forall i :: n <= i < m ==> a[mindex] <= a[i] //mindex is current smallest in range n < m
{
if (a[m] < a[mindex]) {
mindex := m;
}
m := m + 1;
}
a[n], a[mindex] := a[mindex], a[n];
n := n + 1;
}
}
|
Workshop_tmp_tmp0cu11bdq_Lecture_Answers_selection_sort.dfy
|
384
|
384
|
Dafny program: 384
|
function sumTo( a:array<int>, n:int ) : int
requires a != null;
requires 0 <= n && n <= a.Length;
reads a;
{
if (n == 0) then 0 else sumTo(a, n-1) + a[n-1]
}
method sum_array( a: array<int>) returns (sum: int)
requires a != null;
ensures sum == sumTo(a, a.Length);
{
var i := 0;
sum := 0;
while (i < a.Length)
{
sum := sum + a[i];
i := i + 1;
}
}
|
function sumTo( a:array<int>, n:int ) : int
requires a != null;
requires 0 <= n && n <= a.Length;
reads a;
{
if (n == 0) then 0 else sumTo(a, n-1) + a[n-1]
}
method sum_array( a: array<int>) returns (sum: int)
requires a != null;
ensures sum == sumTo(a, a.Length);
{
var i := 0;
sum := 0;
while (i < a.Length)
invariant 0 <= i <= a.Length;
invariant sum == sumTo(a, i);
{
sum := sum + a[i];
i := i + 1;
}
}
|
Workshop_tmp_tmp0cu11bdq_Lecture_Answers_sum_array.dfy
|
385
|
385
|
Dafny program: 385
|
method TriangleNumber(N: int) returns (t: int)
requires N >= 0
ensures t == N * (N + 1) / 2
{
t := 0;
var n := 0;
while n < N
{
n:= n + 1;
t := t + n;
}
}
|
method TriangleNumber(N: int) returns (t: int)
requires N >= 0
ensures t == N * (N + 1) / 2
{
t := 0;
var n := 0;
while n < N
invariant 0 <= n <= N
invariant t == n * (n + 1) / 2
decreases N - n;// can be left out because it is guessed correctly by Dafny
{
n:= n + 1;
t := t + n;
}
}
|
Workshop_tmp_tmp0cu11bdq_Lecture_Answers_triangle_number.dfy
|
386
|
386
|
Dafny program: 386
|
method rev(a : array<int>)
requires a != null;
modifies a;
ensures forall k :: 0 <= k < a.Length ==> a[k] == old(a[(a.Length - 1) - k]);
{
var i := 0;
while (i < a.Length - 1 - i)
{
a[i], a[a.Length - 1 - i] := a[a.Length - 1 - i], a[i];
i := i + 1;
}
}
|
method rev(a : array<int>)
requires a != null;
modifies a;
ensures forall k :: 0 <= k < a.Length ==> a[k] == old(a[(a.Length - 1) - k]);
{
var i := 0;
while (i < a.Length - 1 - i)
invariant 0 <= i <= a.Length/2;
invariant forall k :: 0 <= k < i || a.Length - 1 - i < k <= a.Length - 1 ==> a[k] == old(a[a.Length - 1 - k]); //The reversed region contains the opposing values
invariant forall k :: i <= k <= a.Length - 1 - i ==> a[k] == old(a[k]); // The non reversed region contains the original values
{
a[i], a[a.Length - 1 - i] := a[a.Length - 1 - i], a[i];
i := i + 1;
}
}
|
Workshop_tmp_tmp0cu11bdq_Workshop_Answers_Question5.dfy
|
387
|
387
|
Dafny program: 387
|
method arrayUpToN(n: int) returns (a: array<int>)
requires n >= 0
ensures a.Length == n
ensures forall j :: 0 < j < n ==> a[j] >= 0
ensures forall j, k : int :: 0 <= j <= k < n ==> a[j] <= a[k]
{
var i := 0;
a := new int[n];
while i < n
{
a[i] := i;
i := i + 1;
}
}
|
method arrayUpToN(n: int) returns (a: array<int>)
requires n >= 0
ensures a.Length == n
ensures forall j :: 0 < j < n ==> a[j] >= 0
ensures forall j, k : int :: 0 <= j <= k < n ==> a[j] <= a[k]
{
var i := 0;
a := new int[n];
while i < n
invariant 0 <= i <= n
invariant forall k :: 0 <= k < i ==> a[k] >= 0
invariant forall k :: 0 <= k < i ==> a[k] == k
invariant forall j, k :: 0 <= j <= k < i ==> a[j] <= a[k]
{
a[i] := i;
i := i + 1;
}
}
|
Workshop_tmp_tmp0cu11bdq_Workshop_Answers_Question6.dfy
|
388
|
388
|
Dafny program: 388
|
/*
* Copyright 2022 ConsenSys Software Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software dis-
* tributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
module Int {
const TWO_7 : int := 0x0_80
const TWO_8 : int := 0x1_00
const TWO_15 : int := 0x0_8000
const TWO_16 : int := 0x1_0000
const TWO_24 : int := 0x1_0000_00
const TWO_31 : int := 0x0_8000_0000
const TWO_32 : int := 0x1_0000_0000
const TWO_40 : int := 0x1_0000_0000_00
const TWO_48 : int := 0x1_0000_0000_0000
const TWO_56 : int := 0x1_0000_0000_0000_00
const TWO_63 : int := 0x0_8000_0000_0000_0000
const TWO_64 : int := 0x1_0000_0000_0000_0000
const TWO_127 : int := 0x0_8000_0000_0000_0000_0000_0000_0000_0000
const TWO_128 : int := 0x1_0000_0000_0000_0000_0000_0000_0000_0000
const TWO_160 : int := 0x1_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000
const TWO_255 : int := 0x0_8000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000
const TWO_256 : int := 0x1_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000
// Signed Integers
const MIN_I8 : int := -TWO_7
const MAX_I8 : int := TWO_7 - 1
const MIN_I16 : int := -TWO_15
const MAX_I16 : int := TWO_15 - 1
const MIN_I32 : int := -TWO_31
const MAX_I32 : int := TWO_31 - 1
const MIN_I64 : int := -TWO_63
const MAX_I64 : int := TWO_63 - 1
const MIN_I128 : int := -TWO_127
const MAX_I128 : int := TWO_127 - 1
const MIN_I256 : int := -TWO_255
const MAX_I256 : int := TWO_255 - 1
newtype{:nativeType "sbyte"} i8 = i:int | MIN_I8 <= i <= MAX_I8
newtype{:nativeType "short"} i16 = i:int | MIN_I16 <= i <= MAX_I16
newtype{:nativeType "int"} i32 = i:int | MIN_I32 <= i <= MAX_I32
newtype{:nativeType "long"} i64 = i:int | MIN_I64 <= i <= MAX_I64
newtype i128 = i:int | MIN_I128 <= i <= MAX_I128
newtype i256 = i:int | MIN_I256 <= i <= MAX_I256
// Unsigned Integers
const MAX_U8 : int := TWO_8 - 1
const MAX_U16 : int := TWO_16 - 1
const MAX_U24 : int := TWO_24 - 1
const MAX_U32 : int := TWO_32 - 1
const MAX_U40 : int := TWO_40 - 1
const MAX_U48 : int := TWO_48 - 1
const MAX_U56 : int := TWO_56 - 1
const MAX_U64 : int := TWO_64 - 1
const MAX_U128 : int := TWO_128 - 1
const MAX_U160: int := TWO_160 - 1
const MAX_U256: int := TWO_256 - 1
newtype{:nativeType "byte"} u8 = i:int | 0 <= i <= MAX_U8
newtype{:nativeType "ushort"} u16 = i:int | 0 <= i <= MAX_U16
newtype{:nativeType "uint"} u24 = i:int | 0 <= i <= MAX_U24
newtype{:nativeType "uint"} u32 = i:int | 0 <= i <= MAX_U32
newtype{:nativeType "ulong"} u40 = i:int | 0 <= i <= MAX_U40
newtype{:nativeType "ulong"} u48 = i:int | 0 <= i <= MAX_U48
newtype{:nativeType "ulong"} u56 = i:int | 0 <= i <= MAX_U56
newtype{:nativeType "ulong"} u64 = i:int | 0 <= i <= MAX_U64
newtype u128 = i:int | 0 <= i <= MAX_U128
newtype u160 = i:int | 0 <= i <= MAX_U160
newtype u256 = i:int | 0 <= i <= MAX_U256
// Determine maximum of two u256 integers.
function Max(i1: int, i2: int) : int {
if i1 >= i2 then i1 else i2
}
// Determine maximum of two u256 integers.
function Min(i1: int, i2: int) : int {
if i1 < i2 then i1 else i2
}
// Round up a given number (i) by a given multiple (r).
function RoundUp(i: int, r: nat) : int
requires r > 0 {
if (i % r) == 0 then i
else
((i/r)*r) + r
}
// Return the maximum value representable using exactly n unsigned bytes.
// This is essentially computing (2^n - 1). However, the point of doing it
// in this fashion is to avoid using Pow() as this is challenging for the
// verifier.
function MaxUnsignedN(n:nat) : (r:nat)
requires 1 <= n <= 32 {
match n
case 1 => MAX_U8
case 2 => MAX_U16
case 3 => MAX_U24
case 4 => MAX_U32
case 5 => MAX_U40
case 6 => MAX_U48
case 7 => MAX_U56
case 8 => MAX_U64
case 16 => MAX_U128
case 20 => MAX_U160
case 32 => MAX_U256
// Fall back case (for now)
case _ =>
Pow(2,n) - 1
}
// =========================================================
// Exponent
// =========================================================
/**
* Compute n^k.
*/
function Pow(n:nat, k:nat) : (r:nat)
// Following needed for some proofs
ensures n > 0 ==> r > 0 {
if k == 0 then 1
else if k == 1 then n
else
var p := k / 2;
var np := Pow(n,p);
if p*2 == k then np * np
else np * np * n
}
// Simple lemma about POW.
lemma lemma_pow2(k:nat)
ensures Pow(2,k) > 0 {
if k == 0 {
} else if k == 1 {
} else {
lemma_pow2(k/2);
}
}
// =========================================================
// Non-Euclidean Division / Remainder
// =========================================================
// This provides a non-Euclidean division operator and is necessary
// because Dafny (unlike just about every other programming
// language) supports Euclidean division. This operator, therefore,
// always divides *towards* zero.
function Div(lhs: int, rhs: int) : int
requires rhs != 0 {
if lhs >= 0 then lhs / rhs
else
-((-lhs) / rhs)
}
// This provides a non-Euclidean Remainder operator and is necessary
// because Dafny (unlike just about every other programming
// language) supports Euclidean division. Observe that this is a
// true Remainder operator, and not a modulus operator. For
// emxaple, this means the result can be negative.
function Rem(lhs: int, rhs: int) : int
requires rhs != 0 {
if lhs >= 0 then (lhs % rhs)
else
var d := -((-lhs) / rhs);
lhs - (d * rhs)
}
}
/**
* Various helper methods related to unsigned 8bit integers.
*/
module U8 {
import opened Int
// Compute the log of a value at base 2 where the result is rounded down.
function Log2(v:u8) : (r:nat)
ensures r < 8 {
// Split 4 bits
if v <= 15 then
// Split 2 bits
if v <= 3 then
// Split 1 bit
if v <= 1 then 0 else 1
else
// Split 1 bit
if v <= 7 then 2 else 3
else
// Split 2 bits
if v <= 63 then
// Split 1 bit
if v <= 31 then 4 else 5
else
// Split 1 bit
if v <= 127 then 6 else 7
}
}
/**
* Various helper methods related to unsigned 16bit integers.
*/
module U16 {
import opened Int
import U8
// Read nth 8bit word (i.e. byte) out of this u16, where 0
// identifies the most significant byte.
function NthUint8(v:u16, k: nat) : u8
// Cannot read more than two words!
requires k < 2 {
if k == 0
then (v / (TWO_8 as u16)) as u8
else
(v % (TWO_8 as u16)) as u8
}
/**
* Compute the log of a value at base 2 where the result is rounded down.
*/
function Log2(v:u16) : (r:nat)
ensures r < 16 {
var low := (v % (TWO_8 as u16)) as u8;
var high := (v / (TWO_8 as u16)) as u8;
if high != 0 then U8.Log2(high)+8 else U8.Log2(low)
}
/**
* Compute the log of a value at base 256 where the result is rounded down.
*/
function Log256(v:u16) : (r:nat)
ensures r <= 1 {
var low := (v % (TWO_8 as u16)) as u8;
var high := (v / (TWO_8 as u16)) as u8;
if high != 0 then 1 else 0
}
/**
* Convert a u16 into a sequence of 2 bytes (in big endian representation).
*/
function ToBytes(v:u16) : (r:seq<u8>)
ensures |r| == 2 {
var low := (v % (TWO_8 as u16)) as u8;
var high := (v / (TWO_8 as u16)) as u8;
[high,low]
}
function Read(bytes: seq<u8>, address:nat) : u16
requires (address+1) < |bytes| {
var b1 := bytes[address] as u16;
var b2 := bytes[address+1] as u16;
(b1 * (TWO_8 as u16)) + b2
}
}
/**
* Various helper methods related to unsigned 32bit integers.
*/
module U32 {
import U16
import opened Int
// Read nth 16bit word out of this u32, where 0 identifies the most
// significant word.
function NthUint16(v:u32, k: nat) : u16
// Cannot read more than two words!
requires k < 2 {
if k == 0
then (v / (TWO_16 as u32)) as u16
else
(v % (TWO_16 as u32)) as u16
}
/**
* Compute the log of a value at base 256 where the result is rounded down.
*/
function Log2(v:u32) : (r:nat)
ensures r < 32 {
var low := (v % (TWO_16 as u32)) as u16;
var high := (v / (TWO_16 as u32)) as u16;
if high != 0 then U16.Log2(high)+16 else U16.Log2(low)
}
/**
* Compute the log of a value at base 256 where the result is rounded down.
*/
function Log256(v:u32) : (r:nat)
ensures r <= 3 {
var low := (v % (TWO_16 as u32)) as u16;
var high := (v / (TWO_16 as u32)) as u16;
if high != 0 then U16.Log256(high)+2 else U16.Log256(low)
}
/**
* Convert a u32 into a sequence of 4 bytes (in big endian representation).
*/
function ToBytes(v:u32) : (r:seq<u8>)
ensures |r| == 4 {
var low := (v % (TWO_16 as u32)) as u16;
var high := (v / (TWO_16 as u32)) as u16;
U16.ToBytes(high) + U16.ToBytes(low)
}
function Read(bytes: seq<u8>, address:nat) : u32
requires (address+3) < |bytes| {
var b1 := U16.Read(bytes, address) as u32;
var b2 := U16.Read(bytes, address+2) as u32;
(b1 * (TWO_16 as u32)) + b2
}
}
/**
* Various helper methods related to unsigned 64bit integers.
*/
module U64 {
import U32
import opened Int
// Read nth 32bit word out of this u64, where 0 identifies the most
// significant word.
function NthUint32(v:u64, k: nat) : u32
// Cannot read more than two words!
requires k < 2 {
if k == 0
then (v / (TWO_32 as u64)) as u32
else
(v % (TWO_32 as u64)) as u32
}
/**
* Compute the log of a value at base 256 where the result is rounded down.
*/
function Log2(v:u64) : (r:nat)
ensures r < 64 {
var low := (v % (TWO_32 as u64)) as u32;
var high := (v / (TWO_32 as u64)) as u32;
if high != 0 then U32.Log2(high)+32 else U32.Log2(low)
}
/**
* Compute the log of a value at base 256 where the result is rounded down.
*/
function Log256(v:u64) : (r:nat)
ensures r <= 7 {
var low := (v % (TWO_32 as u64)) as u32;
var high := (v / (TWO_32 as u64)) as u32;
if high != 0 then U32.Log256(high)+4 else U32.Log256(low)
}
/**
* Convert a u64 into a sequence of 8bytes (in big endian representation).
*/
function ToBytes(v:u64) : (r:seq<u8>)
ensures |r| == 8 {
var low := (v % (TWO_32 as u64)) as u32;
var high := (v / (TWO_32 as u64)) as u32;
U32.ToBytes(high) + U32.ToBytes(low)
}
function Read(bytes: seq<u8>, address:nat) : u64
requires (address+7) < |bytes| {
var b1 := U32.Read(bytes, address) as u64;
var b2 := U32.Read(bytes, address+4) as u64;
(b1 * (TWO_32 as u64)) + b2
}
}
/**
* Various helper methods related to unsigned 128bit integers.
*/
module U128 {
import U64
import opened Int
// Read nth 64bit word out of this u128, where 0 identifies the most
// significant word.
function NthUint64(v:u128, k: nat) : u64
// Cannot read more than two words!
requires k < 2 {
if k == 0
then (v / (TWO_64 as u128)) as u64
else
(v % (TWO_64 as u128)) as u64
}
/**
* Compute the log of a value at base 256 where the result is rounded down.
*/
function Log2(v:u128) : (r:nat)
ensures r < 128 {
var low := (v % (TWO_64 as u128)) as u64;
var high := (v / (TWO_64 as u128)) as u64;
if high != 0 then U64.Log2(high)+64 else U64.Log2(low)
}
/**
* Compute the log of a value at base 256 where the result is rounded down.
*/
function Log256(v:u128) : (r:nat)
ensures r <= 15 {
var low := (v % (TWO_64 as u128)) as u64;
var high := (v / (TWO_64 as u128)) as u64;
if high != 0 then U64.Log256(high)+8 else U64.Log256(low)
}
/**
* Convert a u128 into a sequence of 16bytes (in big endian representation).
*/
function ToBytes(v:u128) : (r:seq<u8>)
ensures |r| == 16 {
var low := (v % (TWO_64 as u128)) as u64;
var high := (v / (TWO_64 as u128)) as u64;
U64.ToBytes(high) + U64.ToBytes(low)
}
function Read(bytes: seq<u8>, address:nat) : u128
requires (address+15) < |bytes| {
var b1 := U64.Read(bytes, address) as u128;
var b2 := U64.Read(bytes, address+8) as u128;
(b1 * (TWO_64 as u128)) + b2
}
}
/**
* Various helper methods related to unsigned 256bit integers.
*/
module U256 {
import opened Int
import U8
import U16
import U32
import U64
import U128
/** An axiom stating that a bv256 converted as a nat is bounded by 2^256. */
lemma {:axiom} as_bv256_as_u256(v: bv256)
ensures v as nat < TWO_256
function Shl(lhs: u256, rhs: u256) : u256
{
var lbv := lhs as bv256;
// NOTE: unclear whether shifting is optimal choice here.
var res := if rhs < 256 then (lbv << rhs) else 0;
//
res as u256
}
function Shr(lhs: u256, rhs: u256) : u256 {
var lbv := lhs as bv256;
// NOTE: unclear whether shifting is optimal choice here.
var res := if rhs < 256 then (lbv >> rhs) else 0;
//
res as u256
}
/**
* Compute the log of a value at base 2, where the result in rounded down.
* This effectively determines the position of the highest on bit.
*/
function Log2(v:u256) : (r:nat)
ensures r < 256 {
var low := (v % (TWO_128 as u256)) as u128;
var high := (v / (TWO_128 as u256)) as u128;
if high != 0 then U128.Log2(high)+128 else U128.Log2(low)
}
/**
* Compute the log of a value at base 256 where the result is rounded down.
*/
function Log256(v:u256) : (r:nat)
ensures r <= 31 {
var low := (v % (TWO_128 as u256)) as u128;
var high := (v / (TWO_128 as u256)) as u128;
if high != 0 then U128.Log256(high)+16 else U128.Log256(low)
}
// Read nth 128bit word out of this u256, where 0 identifies the most
// significant word.
function NthUint128(v:u256, k: nat) : u128
// Cannot read more than two words!
requires k < 2 {
if k == 0
then (v / (TWO_128 as u256)) as u128
else
(v % (TWO_128 as u256)) as u128
}
// Read nth byte out of this u256, where 0 identifies the most
// significant byte.
function NthUint8(v:u256, k: nat) : u8
// Cannot read more than 32bytes!
requires k < 32 {
// This is perhaps a tad ugly. Happy to take suggestions on
// a better approach :)
var w128 := NthUint128(v,k / 16);
var w64 := U128.NthUint64(w128,(k % 16) / 8);
var w32 := U64.NthUint32(w64,(k % 8) / 4);
var w16 := U32.NthUint16(w32,(k % 4) / 2);
U16.NthUint8(w16,k%2)
}
function Read(bytes: seq<u8>, address:nat) : u256
requires (address+31) < |bytes| {
var b1 := U128.Read(bytes, address) as u256;
var b2 := U128.Read(bytes, address+16) as u256;
(b1 * (TWO_128 as u256)) + b2
}
/**
* Convert a u256 into a sequence of 32bytes in big endian representation.
*/
function ToBytes(v:u256) : (r:seq<u8>)
ensures |r| == 32 {
var low := (v % (TWO_128 as u256)) as u128;
var high := (v / (TWO_128 as u256)) as u128;
U128.ToBytes(high) + U128.ToBytes(low)
}
/**
*
*/
function SignExtend(v: u256, k: nat) : u256 {
if k >= 31 then v
else
// Reinterpret k as big endian
var ith := 31 - k;
// Extract byte containing sign bit
var byte := NthUint8(v,ith);
// Extract sign bit
var signbit := ((byte as bv8) & 0x80) == 0x80;
// Replicate sign bit.
var signs := if signbit then seq(31-k, i => 0xff)
else seq(31-k, i => 0);
// Extract unchanged bytes
var bytes := ToBytes(v)[ith..];
// Sanity check
// Done
Read(signs + bytes,0)
}
}
module I256 {
import U256
import Word
import opened Int
// This provides a non-Euclidean division operator and is necessary
// because Dafny (unlike just about every other programming
// language) supports Euclidean division. This operator, therefore,
// always divides *towards* zero.
function Div(lhs: i256, rhs: i256) : i256
// Cannot divide by zero!
requires rhs != 0
// Range restriction to prevent overflow
requires (rhs != -1 || lhs != (-TWO_255 as i256)) {
Int.Div(lhs as int, rhs as int) as i256
}
// This provides a non-Euclidean Remainder operator and is necessary
// because Dafny (unlike just about every other programming
// language) supports Euclidean division. Observe that this is a
// true Remainder operator, and not a modulus operator. For
// emxaple, this means the result can be negative.
function Rem(lhs: i256, rhs: i256) : i256
// Cannot divide by zero!
requires rhs != 0 {
Int.Rem(lhs as int, rhs as int) as i256
}
/**
* Shifting 1 left less than 256 times produces a non-zero value.
*
* More generally, shifting-left 1 less than k times over k bits
* yield a non-zero number.
*
* @example over 2 bits, left-shift 1 once: 01 -> 10
* @example over 4 bits, left-shift 1 3 times: 0001 -> 0010 -> 0100 -> 1000
*/
lemma ShiftYieldsNonZero(x: u256)
requires 0 < x < 256
ensures U256.Shl(1, x) > 0
{
// Thanks Dafny.
}
// Shift Arithmetic Right. This implementation follows the Yellow Paper quite
// accurately.
function Sar(lhs: i256, rhs: u256): i256 {
if rhs == 0 then lhs
else if rhs < 256
then
var r := U256.Shl(1,rhs);
ShiftYieldsNonZero(rhs);
((lhs as int) / (r as int)) as i256
else if lhs < 0 then -1
else 0
}
}
module Word {
import opened Int
// Decode a 256bit word as a signed 256bit integer. Since words
// are represented as u256, the parameter has type u256. However,
// its important to note that this does not mean the value in
// question represents an unsigned 256 bit integer. Rather, it is a
// signed integer encoded into an unsigned integer.
function asI256(w: u256) : i256 {
if w > (MAX_I256 as u256)
then
var v := 1 + MAX_U256 - (w as int);
(-v) as i256
else
w as i256
}
// Encode a 256bit signed integer as a 256bit word. Since words are
// represented as u256, the return is represented as u256. However,
// its important to note that this does not mean the value in
// question represents an unsigned 256 bit integer. Rather, it is a
// signed integer encoded into an unsigned integer.
function fromI256(w: Int.i256) : u256 {
if w < 0
then
var v := 1 + MAX_U256 + (w as int);
v as u256
else
w as u256
}
}
|
/*
* Copyright 2022 ConsenSys Software Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software dis-
* tributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
module Int {
const TWO_7 : int := 0x0_80
const TWO_8 : int := 0x1_00
const TWO_15 : int := 0x0_8000
const TWO_16 : int := 0x1_0000
const TWO_24 : int := 0x1_0000_00
const TWO_31 : int := 0x0_8000_0000
const TWO_32 : int := 0x1_0000_0000
const TWO_40 : int := 0x1_0000_0000_00
const TWO_48 : int := 0x1_0000_0000_0000
const TWO_56 : int := 0x1_0000_0000_0000_00
const TWO_63 : int := 0x0_8000_0000_0000_0000
const TWO_64 : int := 0x1_0000_0000_0000_0000
const TWO_127 : int := 0x0_8000_0000_0000_0000_0000_0000_0000_0000
const TWO_128 : int := 0x1_0000_0000_0000_0000_0000_0000_0000_0000
const TWO_160 : int := 0x1_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000
const TWO_255 : int := 0x0_8000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000
const TWO_256 : int := 0x1_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000
// Signed Integers
const MIN_I8 : int := -TWO_7
const MAX_I8 : int := TWO_7 - 1
const MIN_I16 : int := -TWO_15
const MAX_I16 : int := TWO_15 - 1
const MIN_I32 : int := -TWO_31
const MAX_I32 : int := TWO_31 - 1
const MIN_I64 : int := -TWO_63
const MAX_I64 : int := TWO_63 - 1
const MIN_I128 : int := -TWO_127
const MAX_I128 : int := TWO_127 - 1
const MIN_I256 : int := -TWO_255
const MAX_I256 : int := TWO_255 - 1
newtype{:nativeType "sbyte"} i8 = i:int | MIN_I8 <= i <= MAX_I8
newtype{:nativeType "short"} i16 = i:int | MIN_I16 <= i <= MAX_I16
newtype{:nativeType "int"} i32 = i:int | MIN_I32 <= i <= MAX_I32
newtype{:nativeType "long"} i64 = i:int | MIN_I64 <= i <= MAX_I64
newtype i128 = i:int | MIN_I128 <= i <= MAX_I128
newtype i256 = i:int | MIN_I256 <= i <= MAX_I256
// Unsigned Integers
const MAX_U8 : int := TWO_8 - 1
const MAX_U16 : int := TWO_16 - 1
const MAX_U24 : int := TWO_24 - 1
const MAX_U32 : int := TWO_32 - 1
const MAX_U40 : int := TWO_40 - 1
const MAX_U48 : int := TWO_48 - 1
const MAX_U56 : int := TWO_56 - 1
const MAX_U64 : int := TWO_64 - 1
const MAX_U128 : int := TWO_128 - 1
const MAX_U160: int := TWO_160 - 1
const MAX_U256: int := TWO_256 - 1
newtype{:nativeType "byte"} u8 = i:int | 0 <= i <= MAX_U8
newtype{:nativeType "ushort"} u16 = i:int | 0 <= i <= MAX_U16
newtype{:nativeType "uint"} u24 = i:int | 0 <= i <= MAX_U24
newtype{:nativeType "uint"} u32 = i:int | 0 <= i <= MAX_U32
newtype{:nativeType "ulong"} u40 = i:int | 0 <= i <= MAX_U40
newtype{:nativeType "ulong"} u48 = i:int | 0 <= i <= MAX_U48
newtype{:nativeType "ulong"} u56 = i:int | 0 <= i <= MAX_U56
newtype{:nativeType "ulong"} u64 = i:int | 0 <= i <= MAX_U64
newtype u128 = i:int | 0 <= i <= MAX_U128
newtype u160 = i:int | 0 <= i <= MAX_U160
newtype u256 = i:int | 0 <= i <= MAX_U256
// Determine maximum of two u256 integers.
function Max(i1: int, i2: int) : int {
if i1 >= i2 then i1 else i2
}
// Determine maximum of two u256 integers.
function Min(i1: int, i2: int) : int {
if i1 < i2 then i1 else i2
}
// Round up a given number (i) by a given multiple (r).
function RoundUp(i: int, r: nat) : int
requires r > 0 {
if (i % r) == 0 then i
else
((i/r)*r) + r
}
// Return the maximum value representable using exactly n unsigned bytes.
// This is essentially computing (2^n - 1). However, the point of doing it
// in this fashion is to avoid using Pow() as this is challenging for the
// verifier.
function MaxUnsignedN(n:nat) : (r:nat)
requires 1 <= n <= 32 {
match n
case 1 => MAX_U8
case 2 => MAX_U16
case 3 => MAX_U24
case 4 => MAX_U32
case 5 => MAX_U40
case 6 => MAX_U48
case 7 => MAX_U56
case 8 => MAX_U64
case 16 => MAX_U128
case 20 => MAX_U160
case 32 => MAX_U256
// Fall back case (for now)
case _ =>
Pow(2,n) - 1
}
// =========================================================
// Exponent
// =========================================================
/**
* Compute n^k.
*/
function Pow(n:nat, k:nat) : (r:nat)
// Following needed for some proofs
ensures n > 0 ==> r > 0 {
if k == 0 then 1
else if k == 1 then n
else
var p := k / 2;
var np := Pow(n,p);
if p*2 == k then np * np
else np * np * n
}
// Simple lemma about POW.
lemma lemma_pow2(k:nat)
ensures Pow(2,k) > 0 {
if k == 0 {
assert Pow(2,k) == 1;
} else if k == 1 {
assert Pow(2,k) == 2;
} else {
lemma_pow2(k/2);
}
}
// =========================================================
// Non-Euclidean Division / Remainder
// =========================================================
// This provides a non-Euclidean division operator and is necessary
// because Dafny (unlike just about every other programming
// language) supports Euclidean division. This operator, therefore,
// always divides *towards* zero.
function Div(lhs: int, rhs: int) : int
requires rhs != 0 {
if lhs >= 0 then lhs / rhs
else
-((-lhs) / rhs)
}
// This provides a non-Euclidean Remainder operator and is necessary
// because Dafny (unlike just about every other programming
// language) supports Euclidean division. Observe that this is a
// true Remainder operator, and not a modulus operator. For
// emxaple, this means the result can be negative.
function Rem(lhs: int, rhs: int) : int
requires rhs != 0 {
if lhs >= 0 then (lhs % rhs)
else
var d := -((-lhs) / rhs);
lhs - (d * rhs)
}
}
/**
* Various helper methods related to unsigned 8bit integers.
*/
module U8 {
import opened Int
// Compute the log of a value at base 2 where the result is rounded down.
function Log2(v:u8) : (r:nat)
ensures r < 8 {
// Split 4 bits
if v <= 15 then
// Split 2 bits
if v <= 3 then
// Split 1 bit
if v <= 1 then 0 else 1
else
// Split 1 bit
if v <= 7 then 2 else 3
else
// Split 2 bits
if v <= 63 then
// Split 1 bit
if v <= 31 then 4 else 5
else
// Split 1 bit
if v <= 127 then 6 else 7
}
}
/**
* Various helper methods related to unsigned 16bit integers.
*/
module U16 {
import opened Int
import U8
// Read nth 8bit word (i.e. byte) out of this u16, where 0
// identifies the most significant byte.
function NthUint8(v:u16, k: nat) : u8
// Cannot read more than two words!
requires k < 2 {
if k == 0
then (v / (TWO_8 as u16)) as u8
else
(v % (TWO_8 as u16)) as u8
}
/**
* Compute the log of a value at base 2 where the result is rounded down.
*/
function Log2(v:u16) : (r:nat)
ensures r < 16 {
var low := (v % (TWO_8 as u16)) as u8;
var high := (v / (TWO_8 as u16)) as u8;
if high != 0 then U8.Log2(high)+8 else U8.Log2(low)
}
/**
* Compute the log of a value at base 256 where the result is rounded down.
*/
function Log256(v:u16) : (r:nat)
ensures r <= 1 {
var low := (v % (TWO_8 as u16)) as u8;
var high := (v / (TWO_8 as u16)) as u8;
if high != 0 then 1 else 0
}
/**
* Convert a u16 into a sequence of 2 bytes (in big endian representation).
*/
function ToBytes(v:u16) : (r:seq<u8>)
ensures |r| == 2 {
var low := (v % (TWO_8 as u16)) as u8;
var high := (v / (TWO_8 as u16)) as u8;
[high,low]
}
function Read(bytes: seq<u8>, address:nat) : u16
requires (address+1) < |bytes| {
var b1 := bytes[address] as u16;
var b2 := bytes[address+1] as u16;
(b1 * (TWO_8 as u16)) + b2
}
}
/**
* Various helper methods related to unsigned 32bit integers.
*/
module U32 {
import U16
import opened Int
// Read nth 16bit word out of this u32, where 0 identifies the most
// significant word.
function NthUint16(v:u32, k: nat) : u16
// Cannot read more than two words!
requires k < 2 {
if k == 0
then (v / (TWO_16 as u32)) as u16
else
(v % (TWO_16 as u32)) as u16
}
/**
* Compute the log of a value at base 256 where the result is rounded down.
*/
function Log2(v:u32) : (r:nat)
ensures r < 32 {
var low := (v % (TWO_16 as u32)) as u16;
var high := (v / (TWO_16 as u32)) as u16;
if high != 0 then U16.Log2(high)+16 else U16.Log2(low)
}
/**
* Compute the log of a value at base 256 where the result is rounded down.
*/
function Log256(v:u32) : (r:nat)
ensures r <= 3 {
var low := (v % (TWO_16 as u32)) as u16;
var high := (v / (TWO_16 as u32)) as u16;
if high != 0 then U16.Log256(high)+2 else U16.Log256(low)
}
/**
* Convert a u32 into a sequence of 4 bytes (in big endian representation).
*/
function ToBytes(v:u32) : (r:seq<u8>)
ensures |r| == 4 {
var low := (v % (TWO_16 as u32)) as u16;
var high := (v / (TWO_16 as u32)) as u16;
U16.ToBytes(high) + U16.ToBytes(low)
}
function Read(bytes: seq<u8>, address:nat) : u32
requires (address+3) < |bytes| {
var b1 := U16.Read(bytes, address) as u32;
var b2 := U16.Read(bytes, address+2) as u32;
(b1 * (TWO_16 as u32)) + b2
}
}
/**
* Various helper methods related to unsigned 64bit integers.
*/
module U64 {
import U32
import opened Int
// Read nth 32bit word out of this u64, where 0 identifies the most
// significant word.
function NthUint32(v:u64, k: nat) : u32
// Cannot read more than two words!
requires k < 2 {
if k == 0
then (v / (TWO_32 as u64)) as u32
else
(v % (TWO_32 as u64)) as u32
}
/**
* Compute the log of a value at base 256 where the result is rounded down.
*/
function Log2(v:u64) : (r:nat)
ensures r < 64 {
var low := (v % (TWO_32 as u64)) as u32;
var high := (v / (TWO_32 as u64)) as u32;
if high != 0 then U32.Log2(high)+32 else U32.Log2(low)
}
/**
* Compute the log of a value at base 256 where the result is rounded down.
*/
function Log256(v:u64) : (r:nat)
ensures r <= 7 {
var low := (v % (TWO_32 as u64)) as u32;
var high := (v / (TWO_32 as u64)) as u32;
if high != 0 then U32.Log256(high)+4 else U32.Log256(low)
}
/**
* Convert a u64 into a sequence of 8bytes (in big endian representation).
*/
function ToBytes(v:u64) : (r:seq<u8>)
ensures |r| == 8 {
var low := (v % (TWO_32 as u64)) as u32;
var high := (v / (TWO_32 as u64)) as u32;
U32.ToBytes(high) + U32.ToBytes(low)
}
function Read(bytes: seq<u8>, address:nat) : u64
requires (address+7) < |bytes| {
var b1 := U32.Read(bytes, address) as u64;
var b2 := U32.Read(bytes, address+4) as u64;
(b1 * (TWO_32 as u64)) + b2
}
}
/**
* Various helper methods related to unsigned 128bit integers.
*/
module U128 {
import U64
import opened Int
// Read nth 64bit word out of this u128, where 0 identifies the most
// significant word.
function NthUint64(v:u128, k: nat) : u64
// Cannot read more than two words!
requires k < 2 {
if k == 0
then (v / (TWO_64 as u128)) as u64
else
(v % (TWO_64 as u128)) as u64
}
/**
* Compute the log of a value at base 256 where the result is rounded down.
*/
function Log2(v:u128) : (r:nat)
ensures r < 128 {
var low := (v % (TWO_64 as u128)) as u64;
var high := (v / (TWO_64 as u128)) as u64;
if high != 0 then U64.Log2(high)+64 else U64.Log2(low)
}
/**
* Compute the log of a value at base 256 where the result is rounded down.
*/
function Log256(v:u128) : (r:nat)
ensures r <= 15 {
var low := (v % (TWO_64 as u128)) as u64;
var high := (v / (TWO_64 as u128)) as u64;
if high != 0 then U64.Log256(high)+8 else U64.Log256(low)
}
/**
* Convert a u128 into a sequence of 16bytes (in big endian representation).
*/
function ToBytes(v:u128) : (r:seq<u8>)
ensures |r| == 16 {
var low := (v % (TWO_64 as u128)) as u64;
var high := (v / (TWO_64 as u128)) as u64;
U64.ToBytes(high) + U64.ToBytes(low)
}
function Read(bytes: seq<u8>, address:nat) : u128
requires (address+15) < |bytes| {
var b1 := U64.Read(bytes, address) as u128;
var b2 := U64.Read(bytes, address+8) as u128;
(b1 * (TWO_64 as u128)) + b2
}
}
/**
* Various helper methods related to unsigned 256bit integers.
*/
module U256 {
import opened Int
import U8
import U16
import U32
import U64
import U128
/** An axiom stating that a bv256 converted as a nat is bounded by 2^256. */
lemma {:axiom} as_bv256_as_u256(v: bv256)
ensures v as nat < TWO_256
function Shl(lhs: u256, rhs: u256) : u256
{
var lbv := lhs as bv256;
// NOTE: unclear whether shifting is optimal choice here.
var res := if rhs < 256 then (lbv << rhs) else 0;
//
res as u256
}
function Shr(lhs: u256, rhs: u256) : u256 {
var lbv := lhs as bv256;
// NOTE: unclear whether shifting is optimal choice here.
var res := if rhs < 256 then (lbv >> rhs) else 0;
//
res as u256
}
/**
* Compute the log of a value at base 2, where the result in rounded down.
* This effectively determines the position of the highest on bit.
*/
function Log2(v:u256) : (r:nat)
ensures r < 256 {
var low := (v % (TWO_128 as u256)) as u128;
var high := (v / (TWO_128 as u256)) as u128;
if high != 0 then U128.Log2(high)+128 else U128.Log2(low)
}
/**
* Compute the log of a value at base 256 where the result is rounded down.
*/
function Log256(v:u256) : (r:nat)
ensures r <= 31 {
var low := (v % (TWO_128 as u256)) as u128;
var high := (v / (TWO_128 as u256)) as u128;
if high != 0 then U128.Log256(high)+16 else U128.Log256(low)
}
// Read nth 128bit word out of this u256, where 0 identifies the most
// significant word.
function NthUint128(v:u256, k: nat) : u128
// Cannot read more than two words!
requires k < 2 {
if k == 0
then (v / (TWO_128 as u256)) as u128
else
(v % (TWO_128 as u256)) as u128
}
// Read nth byte out of this u256, where 0 identifies the most
// significant byte.
function NthUint8(v:u256, k: nat) : u8
// Cannot read more than 32bytes!
requires k < 32 {
// This is perhaps a tad ugly. Happy to take suggestions on
// a better approach :)
var w128 := NthUint128(v,k / 16);
var w64 := U128.NthUint64(w128,(k % 16) / 8);
var w32 := U64.NthUint32(w64,(k % 8) / 4);
var w16 := U32.NthUint16(w32,(k % 4) / 2);
U16.NthUint8(w16,k%2)
}
function Read(bytes: seq<u8>, address:nat) : u256
requires (address+31) < |bytes| {
var b1 := U128.Read(bytes, address) as u256;
var b2 := U128.Read(bytes, address+16) as u256;
(b1 * (TWO_128 as u256)) + b2
}
/**
* Convert a u256 into a sequence of 32bytes in big endian representation.
*/
function ToBytes(v:u256) : (r:seq<u8>)
ensures |r| == 32 {
var low := (v % (TWO_128 as u256)) as u128;
var high := (v / (TWO_128 as u256)) as u128;
U128.ToBytes(high) + U128.ToBytes(low)
}
/**
*
*/
function SignExtend(v: u256, k: nat) : u256 {
if k >= 31 then v
else
// Reinterpret k as big endian
var ith := 31 - k;
// Extract byte containing sign bit
var byte := NthUint8(v,ith);
// Extract sign bit
var signbit := ((byte as bv8) & 0x80) == 0x80;
// Replicate sign bit.
var signs := if signbit then seq(31-k, i => 0xff)
else seq(31-k, i => 0);
// Extract unchanged bytes
var bytes := ToBytes(v)[ith..];
// Sanity check
assert |signs + bytes| == 32;
// Done
Read(signs + bytes,0)
}
}
module I256 {
import U256
import Word
import opened Int
// This provides a non-Euclidean division operator and is necessary
// because Dafny (unlike just about every other programming
// language) supports Euclidean division. This operator, therefore,
// always divides *towards* zero.
function Div(lhs: i256, rhs: i256) : i256
// Cannot divide by zero!
requires rhs != 0
// Range restriction to prevent overflow
requires (rhs != -1 || lhs != (-TWO_255 as i256)) {
Int.Div(lhs as int, rhs as int) as i256
}
// This provides a non-Euclidean Remainder operator and is necessary
// because Dafny (unlike just about every other programming
// language) supports Euclidean division. Observe that this is a
// true Remainder operator, and not a modulus operator. For
// emxaple, this means the result can be negative.
function Rem(lhs: i256, rhs: i256) : i256
// Cannot divide by zero!
requires rhs != 0 {
Int.Rem(lhs as int, rhs as int) as i256
}
/**
* Shifting 1 left less than 256 times produces a non-zero value.
*
* More generally, shifting-left 1 less than k times over k bits
* yield a non-zero number.
*
* @example over 2 bits, left-shift 1 once: 01 -> 10
* @example over 4 bits, left-shift 1 3 times: 0001 -> 0010 -> 0100 -> 1000
*/
lemma ShiftYieldsNonZero(x: u256)
requires 0 < x < 256
ensures U256.Shl(1, x) > 0
{
// Thanks Dafny.
}
// Shift Arithmetic Right. This implementation follows the Yellow Paper quite
// accurately.
function Sar(lhs: i256, rhs: u256): i256 {
if rhs == 0 then lhs
else if rhs < 256
then
assert 0 < rhs < 256;
var r := U256.Shl(1,rhs);
ShiftYieldsNonZero(rhs);
((lhs as int) / (r as int)) as i256
else if lhs < 0 then -1
else 0
}
}
module Word {
import opened Int
// Decode a 256bit word as a signed 256bit integer. Since words
// are represented as u256, the parameter has type u256. However,
// its important to note that this does not mean the value in
// question represents an unsigned 256 bit integer. Rather, it is a
// signed integer encoded into an unsigned integer.
function asI256(w: u256) : i256 {
if w > (MAX_I256 as u256)
then
var v := 1 + MAX_U256 - (w as int);
(-v) as i256
else
w as i256
}
// Encode a 256bit signed integer as a 256bit word. Since words are
// represented as u256, the return is represented as u256. However,
// its important to note that this does not mean the value in
// question represents an unsigned 256 bit integer. Rather, it is a
// signed integer encoded into an unsigned integer.
function fromI256(w: Int.i256) : u256 {
if w < 0
then
var v := 1 + MAX_U256 + (w as int);
v as u256
else
w as u256
}
}
|
WrappedEther.dfy
|
389
|
389
|
Dafny program: 389
|
method Main()
{
var q := [1,2,2,5,10,10,10,23];
var i,j := FindRange(q, 10);
print "The number of occurrences of 10 in the sorted sequence [1,2,2,5,10,10,10,23] is ";
print j-i;
print " (starting at index ";
print i;
print " and ending in ";
print j;
print ").\n";
}
// arr = [0, 1, 2] key = 10 -> left = right = |q| = 3
q := [0,1,2];
i,j := FindRange(q, 10);
print "The number of occurrences of 10 in the sorted sequence [0,1,2] is ";
print j-i;
print " (starting at index ";
print i;
print " and ending in ";
print j;
print ").\n";
// arr = [10, 11, 12] key = 1 -> left = right = 0
q := [10,11,12];
i,j := FindRange(q, 1);
print "The number of occurrences of 1 in the sorted sequence [10,11,12] is ";
print j-i;
print " (starting at index ";
print i;
print " and ending in ";
print j;
print ").\n";
// arr = [1, 11, 22] key = 10 -> left = right = i+1 = 1 i is the nearest index to key
q := [1,11,22];
i,j := FindRange(q, 10);
print "The number of occurrences of 10 in the sorted sequence [1,11,22] is ";
print j-i;
print " (starting at index ";
print i;
print " and ending in ";
print j;
print ").\n";
// arr = [1 ,11, 22] key = 11 -> left = 1, right = 2
q := [1,11,22];
i,j := FindRange(q, 11);
print "The number of occurrences of 11 in the sorted sequence [1,11,22] is ";
print j-i;
print " (starting at index ";
print i;
print " and ending in ";
print j;
print ").\n";
// arr = [1 ,11, 11] key = 11 -> left = 1, right = 3
q := [1,11,11];
i,j := FindRange(q, 11);
print "The number of occurrences of 11 in the sorted sequence [1,11,11] is ";
print j-i;
print " (starting at index ";
print i;
print " and ending in ";
print j;
print ").\n";
// arr = [11 ,11, 14] key = 11 -> left = 0, right = 2
q := [11 ,11, 14];
i,j := FindRange(q, 11);
print "The number of occurrences of 11 in the sorted sequence [11 ,11, 14] is ";
print j-i;
print " (starting at index ";
print i;
print " and ending in ";
print j;
print ").\n";
// arr = [1 ,11, 11, 11, 13] key = 11 -> left = 1, right = 4
q := [1,11,11,11,13];
i,j := FindRange(q, 11);
print "The number of occurrences of 11 in the sorted sequence [1,11,11,11,13] is ";
print j-i;
print " (starting at index ";
print i;
print " and ending in ";
print j;
print ").\n";
// arr = [] key = 11 -> left = 0, right = 0
q := [];
i,j := FindRange(q, 11);
print "The number of occurrences of 11 in the sorted sequence [] is ";
print j-i;
print " (starting at index ";
print i;
print " and ending in ";
print j;
print ").\n";
// arr = [11] key = 10 -> left = 0, right = 0
q := [11];
i,j := FindRange(q, 10);
print "The number of occurrences of 10 in the sorted sequence [11] is ";
print j-i;
print " (starting at index ";
print i;
print " and ending in ";
print j;
print ").\n";
// arr = [11] key = 11 -> left = 0, right = 1
q := [11];
i,j := FindRange(q, 11);
print "The number of occurrences of 11 in the sorted sequence [11] is ";
print j-i;
print " (starting at index ";
print i;
print " and ending in ";
print j;
print ").\n";
}
predicate Sorted(q: seq<int>)
{
forall i,j :: 0 <= i <= j < |q| ==> q[i] <= q[j]
}
method {:verify true} FindRange(q: seq<int>, key: int) returns (left: nat, right: nat)
requires Sorted(q)
ensures left <= right <= |q|
ensures forall i :: 0 <= i < left ==> q[i] < key
ensures forall i :: left <= i < right ==> q[i] == key
ensures forall i :: right <= i < |q| ==> q[i] > key
{
left := BinarySearch(q, key, 0, |q|, (n, m) => (n >= m));
right := BinarySearch(q, key, left, |q|, (n, m) => (n > m));
}
// all the values in the range satisfy `comparer` (comparer(q[i], key) == true)
predicate RangeSatisfiesComparer(q: seq<int>, key: int, lowerBound: nat, upperBound: nat, comparer: (int, int) -> bool)
requires 0 <= lowerBound <= upperBound <= |q|
{
forall i :: lowerBound <= i < upperBound ==> comparer(q[i], key)
}
// all the values in the range satisfy `!comparer` (comparer(q[i], key) == false)
predicate RangeSatisfiesComparerNegation(q: seq<int>, key: int, lowerBound: nat, upperBound: nat, comparer: (int, int) -> bool)
requires 0 <= lowerBound <= upperBound <= |q|
{
RangeSatisfiesComparer(q, key, lowerBound, upperBound, (n1, n2) => !comparer(n1, n2))
}
method BinarySearch(q: seq<int>, key: int, lowerBound: nat, upperBound: nat, comparer: (int, int) -> bool) returns (index: nat)
requires Sorted(q)
requires 0 <= lowerBound <= upperBound <= |q|
requires RangeSatisfiesComparerNegation(q, key, 0, lowerBound, comparer)
requires RangeSatisfiesComparer(q, key, upperBound, |q|, comparer)
// comparer is '>' or '>='
requires
(forall n1, n2 :: comparer(n1, n2) == (n1 > n2)) ||
(forall n1, n2 :: comparer(n1, n2) == (n1 >= n2))
ensures lowerBound <= index <= upperBound
ensures RangeSatisfiesComparerNegation(q, key, 0, index, comparer)
ensures RangeSatisfiesComparer(q, key, index, |q|, comparer)
{
var low : nat := lowerBound;
var high : nat := upperBound;
while (low < high)
{
var middle:= low + ((high - low) / 2);
if (comparer(q[middle], key))
{
high := middle;
}
else
{
low := middle + 1;
}
}
index := high;
}
|
method Main()
{
var q := [1,2,2,5,10,10,10,23];
assert Sorted(q);
assert 10 in q;
var i,j := FindRange(q, 10);
print "The number of occurrences of 10 in the sorted sequence [1,2,2,5,10,10,10,23] is ";
print j-i;
print " (starting at index ";
print i;
print " and ending in ";
print j;
print ").\n";
assert i == 4 && j == 7 by {
assert q[0] <= q[1] <= q[2] <= q[3] < 10;
assert q[4] == q[5] == q[6] == 10;
assert 10 < q[7];
}
// arr = [0, 1, 2] key = 10 -> left = right = |q| = 3
q := [0,1,2];
assert Sorted(q);
i,j := FindRange(q, 10);
print "The number of occurrences of 10 in the sorted sequence [0,1,2] is ";
print j-i;
print " (starting at index ";
print i;
print " and ending in ";
print j;
print ").\n";
// arr = [10, 11, 12] key = 1 -> left = right = 0
q := [10,11,12];
assert Sorted(q);
i,j := FindRange(q, 1);
print "The number of occurrences of 1 in the sorted sequence [10,11,12] is ";
print j-i;
print " (starting at index ";
print i;
print " and ending in ";
print j;
print ").\n";
// arr = [1, 11, 22] key = 10 -> left = right = i+1 = 1 i is the nearest index to key
q := [1,11,22];
assert Sorted(q);
i,j := FindRange(q, 10);
print "The number of occurrences of 10 in the sorted sequence [1,11,22] is ";
print j-i;
print " (starting at index ";
print i;
print " and ending in ";
print j;
print ").\n";
// arr = [1 ,11, 22] key = 11 -> left = 1, right = 2
q := [1,11,22];
assert Sorted(q);
i,j := FindRange(q, 11);
print "The number of occurrences of 11 in the sorted sequence [1,11,22] is ";
print j-i;
print " (starting at index ";
print i;
print " and ending in ";
print j;
print ").\n";
// arr = [1 ,11, 11] key = 11 -> left = 1, right = 3
q := [1,11,11];
assert Sorted(q);
i,j := FindRange(q, 11);
print "The number of occurrences of 11 in the sorted sequence [1,11,11] is ";
print j-i;
print " (starting at index ";
print i;
print " and ending in ";
print j;
print ").\n";
// arr = [11 ,11, 14] key = 11 -> left = 0, right = 2
q := [11 ,11, 14];
assert Sorted(q);
i,j := FindRange(q, 11);
print "The number of occurrences of 11 in the sorted sequence [11 ,11, 14] is ";
print j-i;
print " (starting at index ";
print i;
print " and ending in ";
print j;
print ").\n";
// arr = [1 ,11, 11, 11, 13] key = 11 -> left = 1, right = 4
q := [1,11,11,11,13];
assert Sorted(q);
i,j := FindRange(q, 11);
print "The number of occurrences of 11 in the sorted sequence [1,11,11,11,13] is ";
print j-i;
print " (starting at index ";
print i;
print " and ending in ";
print j;
print ").\n";
// arr = [] key = 11 -> left = 0, right = 0
q := [];
assert Sorted(q);
i,j := FindRange(q, 11);
print "The number of occurrences of 11 in the sorted sequence [] is ";
print j-i;
print " (starting at index ";
print i;
print " and ending in ";
print j;
print ").\n";
// arr = [11] key = 10 -> left = 0, right = 0
q := [11];
assert Sorted(q);
i,j := FindRange(q, 10);
print "The number of occurrences of 10 in the sorted sequence [11] is ";
print j-i;
print " (starting at index ";
print i;
print " and ending in ";
print j;
print ").\n";
// arr = [11] key = 11 -> left = 0, right = 1
q := [11];
assert Sorted(q);
i,j := FindRange(q, 11);
print "The number of occurrences of 11 in the sorted sequence [11] is ";
print j-i;
print " (starting at index ";
print i;
print " and ending in ";
print j;
print ").\n";
}
predicate Sorted(q: seq<int>)
{
forall i,j :: 0 <= i <= j < |q| ==> q[i] <= q[j]
}
method {:verify true} FindRange(q: seq<int>, key: int) returns (left: nat, right: nat)
requires Sorted(q)
ensures left <= right <= |q|
ensures forall i :: 0 <= i < left ==> q[i] < key
ensures forall i :: left <= i < right ==> q[i] == key
ensures forall i :: right <= i < |q| ==> q[i] > key
{
left := BinarySearch(q, key, 0, |q|, (n, m) => (n >= m));
right := BinarySearch(q, key, left, |q|, (n, m) => (n > m));
}
// all the values in the range satisfy `comparer` (comparer(q[i], key) == true)
predicate RangeSatisfiesComparer(q: seq<int>, key: int, lowerBound: nat, upperBound: nat, comparer: (int, int) -> bool)
requires 0 <= lowerBound <= upperBound <= |q|
{
forall i :: lowerBound <= i < upperBound ==> comparer(q[i], key)
}
// all the values in the range satisfy `!comparer` (comparer(q[i], key) == false)
predicate RangeSatisfiesComparerNegation(q: seq<int>, key: int, lowerBound: nat, upperBound: nat, comparer: (int, int) -> bool)
requires 0 <= lowerBound <= upperBound <= |q|
{
RangeSatisfiesComparer(q, key, lowerBound, upperBound, (n1, n2) => !comparer(n1, n2))
}
method BinarySearch(q: seq<int>, key: int, lowerBound: nat, upperBound: nat, comparer: (int, int) -> bool) returns (index: nat)
requires Sorted(q)
requires 0 <= lowerBound <= upperBound <= |q|
requires RangeSatisfiesComparerNegation(q, key, 0, lowerBound, comparer)
requires RangeSatisfiesComparer(q, key, upperBound, |q|, comparer)
// comparer is '>' or '>='
requires
(forall n1, n2 :: comparer(n1, n2) == (n1 > n2)) ||
(forall n1, n2 :: comparer(n1, n2) == (n1 >= n2))
ensures lowerBound <= index <= upperBound
ensures RangeSatisfiesComparerNegation(q, key, 0, index, comparer)
ensures RangeSatisfiesComparer(q, key, index, |q|, comparer)
{
var low : nat := lowerBound;
var high : nat := upperBound;
while (low < high)
invariant lowerBound <= low <= high <= upperBound
invariant RangeSatisfiesComparerNegation(q, key, 0, low, comparer)
invariant RangeSatisfiesComparer(q, key, high, |q|, comparer)
decreases high - low
{
var middle:= low + ((high - low) / 2);
if (comparer(q[middle], key))
{
high := middle;
}
else
{
low := middle + 1;
}
}
index := high;
}
|
assertive-programming-assignment-1_tmp_tmp3h_cj44u_FindRange.dfy
|
390
|
390
|
Dafny program: 390
|
method Main() {
var q := [7, -2, 3, -2];
var p, c := ProdAndCount(q, -2);
print "The product of all positive elements in [7,-2,3,-2] is ";
print p;
print "\nThe number of occurrences of -2 in [7,-2,3,-2] is ";
print c;
calc {
RecursiveCount(-2, q);
== { assert q[3] == -2; AppendOne(q, 3); }
1 + RecursiveCount(-2, q[..3]);
== { assert q[2] != -2; AppendOne(q, 2); }
1 + RecursiveCount(-2, q[..2]);
== { assert q[1] == -2; AppendOne(q, 1); }
1 + 1 + RecursiveCount(-2, q[..1]);
== { assert q[0] != -2; AppendOne(q, 0); }
1 + 1 + RecursiveCount(-2, q[..0]);
}
}
}
lemma AppendOne<T>(q: seq<T>, n: nat)
requires n < |q|
ensures q[..n]+[q[n]] == q[..n+1]
{}
function RecursivePositiveProduct(q: seq<int>): int
{
if q == [] then 1
else if q[0] <= 0 then RecursivePositiveProduct(q[1..])
else q[0] * RecursivePositiveProduct(q[1..])
}
function RecursiveCount(key: int, q: seq<int>): int
{
if q == [] then 0
else if q[|q|-1] == key then 1+RecursiveCount(key, q[..|q|-1])
else RecursiveCount(key, q[..|q|-1])
}
method ProdAndCount(q: seq<int>, key: int) returns (prod: int, count: nat)
ensures prod == RecursivePositiveProduct(q)
ensures count == RecursiveCount(key, q)
{
prod := 1;
count := 0;
var size := |q|;
var i := 0;
var curr := 0;
while i < size
count == RecursiveCount(key, q[..i]) && // count invar
prod == RecursivePositiveProduct(q[..i])
{
Lemma_Count_Inv(q, i, count, key);
Lemma_Prod_Inv(q, i, prod);
curr := q[i];
if curr > 0 {
prod := prod*curr;
}
if curr == key {
count := count+1;
}
i := i+1;
}
Lemma_Count_Finish(q, i, count, key);
Lemma_Prod_Finish(q, i, prod);
}
function county(elem: int, key: int): int{
if elem==key then 1 else 0
}
function prody(elem: int): int{
if elem <= 0 then 1 else elem
}
lemma Lemma_Count_Inv(q: seq<int>, i: nat, count: int, key: int)
requires 0 <= i < |q| && count == RecursiveCount(key, q[..i])
ensures 0 <= i+1 <= |q| && county(q[i],key)+count == RecursiveCount(key, q[..i+1])
{
var q1 := q[..i+1];
calc {
RecursiveCount(key, q[..i+1]);
== // def.
if q1 == [] then 0
else if q1[i] == key then 1+RecursiveCount(key,q1[..i])
else RecursiveCount(key, q1[..i]);
== { assert q1 != []; } // simplification for a non-empty sequence
if q1[i] == key then 1+RecursiveCount(key, q1[..i])
else RecursiveCount(key,q1[..i]);
== {KibutzLaw1(q1,key,i);} // the kibutz law
(if q1[i] == key then 1 else 0) + RecursiveCount(key, q1[..i]);
==
county(q1[i],key) + RecursiveCount(key, q1[..i]);
==
county(q[i],key) + RecursiveCount(key, q[..i]);
}
}
lemma Lemma_Prod_Inv(q: seq<int>, i: nat, prod: int)
requires 0 <= i < |q| && prod == RecursivePositiveProduct(q[..i])
ensures 0 <= i+1 <= |q| && prody(q[i])*prod == RecursivePositiveProduct(q[..i+1])
{
var q1 := q[..i+1];
calc {
RecursivePositiveProduct(q[..i+1]);
== // def.
if q1 == [] then 1
else if q1[0] <= 0 then RecursivePositiveProduct(q1[1..])
else q1[0] * RecursivePositiveProduct(q1[1..]);
== { assert q1 != []; } // simplification for a non-empty sequence
if q1[0] <= 0 then RecursivePositiveProduct(q1[1..])
else q1[0] * RecursivePositiveProduct(q1[1..]);
== // def. of q1
if q[0] <= 0 then RecursivePositiveProduct(q[1..i+1])
else q[0] * RecursivePositiveProduct(q[1..i+1]);
== { KibutzLaw2(q);}
(if q[0] <= 0 then 1 else q[0])*RecursivePositiveProduct(q[1..i+1]);
==
prody(q[0])*RecursivePositiveProduct(q[1..i+1]);
== {PrependProd(q);}
RecursivePositiveProduct(q[..i+1]);
== {AppendProd(q[..i+1]);}
prody(q[i])*RecursivePositiveProduct(q[..i]);
==
prody(q[i])*prod;
}
}
lemma Lemma_Count_Finish(q: seq<int>, i: nat, count: int, key: int)
requires inv: 0 <= i <= |q| && count == RecursiveCount(key, q[..i])
requires neg_of_guard: i >= |q|
ensures count == RecursiveCount(key, q)
{
}
lemma Lemma_Prod_Finish(q: seq<int>, i: nat, prod: int)
requires inv: 0 <= i <= |q| && prod == RecursivePositiveProduct(q[..i])
requires neg_of_guard: i >= |q|
ensures prod == RecursivePositiveProduct(q)
{
}
lemma KibutzLaw1(q: seq<int>,key: int,i: nat)
requires q != [] && i < |q|
ensures
(if q[|q|-1] == key then 1 + RecursiveCount(key, q[1..i+1])
else 0 + RecursiveCount(key, q[1..i+1]))
==
(if q[|q|-1] == key then 1 else 0) + RecursiveCount(key, q[1..i+1])
{
if q[|q|-1] == key {
calc {
(if q[|q|-1] == key then 1 + RecursiveCount(key, q[1..i+1])
else 0 + RecursiveCount(key, q[1..i+1]));
==
1 + RecursiveCount(key, q[1..i+1]);
==
(if q[|q|-1] == key then 1 else 0) + RecursiveCount(key, q[1..i+1]);
}
} else {
calc {
(if q[|q|-1] == key then 1 + RecursiveCount(key, q[1..i+1])
else 0 + RecursiveCount(key, q[1..i+1]));
==
0 + RecursiveCount(key, q[1..i+1]);
==
(if q[|q|-1] == key then 1 else 0) + RecursiveCount(key, q[1..i+1]);
}
}
}
lemma {:verify true} KibutzLaw2(q: seq<int>)
requires q != []
ensures
(if q[0] <= 0 then RecursivePositiveProduct(q[1..])
else q[0] * RecursivePositiveProduct(q[1..]))
==
(if q[0] <= 0 then 1 else q[0])*RecursivePositiveProduct(q[1..])
{
if q[0] <= 0 {
calc {
(if q[0] <= 0 then RecursivePositiveProduct(q[1..])
else q[0] * RecursivePositiveProduct(q[1..]));
==
RecursivePositiveProduct(q[1..]);
==
(if q[0] <= 0 then 1 else q[0])*RecursivePositiveProduct(q[1..]);
}
} else {
calc {
(if q[0] <= 0 then RecursivePositiveProduct(q[1..])
else q[0] * RecursivePositiveProduct(q[1..]));
==
q[0] * RecursivePositiveProduct(q[1..]);
==
(if q[0] <= 0 then 1 else q[0])*RecursivePositiveProduct(q[1..]);
}
}
}
lemma AppendCount(key: int, q: seq<int>)
requires q != []
ensures RecursiveCount(key, q) == RecursiveCount(key,q[..|q|-1])+county(q[|q|-1], key)
{
if |q| == 1
{
RecursiveCount(key,q[..|q|-1])+county(q[|q|-1], key) ==
RecursiveCount(key,q[..0])+county(q[0], key) ==
RecursiveCount(key, [])+county(q[0], key) ==
0+county(q[0], key) ==
county(q[0], key);
}
else
{ // inductive step
var q1 := q[1..];
calc {
RecursiveCount(key, q);
== // def. for a non-empty sequence
if q == [] then 0
else if q[|q|-1] == key then 1+RecursiveCount(key, q[..|q|-1])
else RecursiveCount(key, q[..|q|-1]);
==
RecursiveCount(key, q[..|q|-1]) + county(q[|q|-1], key);
}
}
}
lemma PrependProd(q: seq<int>)
requires q != []
ensures RecursivePositiveProduct(q) == prody(q[0])*RecursivePositiveProduct(q[1..])
{
calc {
RecursivePositiveProduct(q);
==
if q == [] then 1
else if q[0] <= 0 then RecursivePositiveProduct(q[1..])
else q[0] * RecursivePositiveProduct(q[1..]);
== { assert q != []; } // simplification for a non-empty sequence
if q[0] <= 0 then RecursivePositiveProduct(q[1..])
else q[0] * RecursivePositiveProduct(q[1..]);
== { KibutzLaw2(q);}
(if q[0] <= 0 then 1 else q[0])*RecursivePositiveProduct(q[1..]);
==
prody(q[0])*RecursivePositiveProduct(q[1..]);
}
}
lemma AppendProd(q: seq<int>)
requires q != []
ensures RecursivePositiveProduct(q) == RecursivePositiveProduct(q[..|q|-1])*prody(q[|q|-1])
{
if |q| == 1
{
RecursivePositiveProduct(q[..|q|-1])*prody(q[|q|-1]) ==
RecursivePositiveProduct(q[..0])*prody(q[0]) ==
RecursivePositiveProduct([])*prody(q[0]) ==
1*prody(q[0]) ==
prody(q[0]);
}
else
{ // inductive step
var q1 := q[1..];
calc {
RecursivePositiveProduct(q);
== // def. for a non-empty sequence
prody(q[0]) * RecursivePositiveProduct(q[1..]);
== { assert q1 != []; assert |q1| < |q|; AppendProd(q1); } // induction hypothesis (one assertion for the precondition, another for termination)
prody(q[0]) * RecursivePositiveProduct(q1[..|q1|-1]) * prody(q1[|q1|-1]);
== { assert q1[..|q1|-1] == q[1..|q|-1]; assert q1[|q1|-1] == q[|q|-1]; }
prody(q[0]) * RecursivePositiveProduct(q[1..|q|-1]) * prody(q[|q|-1]);
== {PrependProd(q[..|q|-1]);}
RecursivePositiveProduct(q[..|q|-1]) * prody(q[|q|-1]);
}
}
}
|
method Main() {
var q := [7, -2, 3, -2];
var p, c := ProdAndCount(q, -2);
print "The product of all positive elements in [7,-2,3,-2] is ";
print p;
assert p == RecursivePositiveProduct(q) == 21;
print "\nThe number of occurrences of -2 in [7,-2,3,-2] is ";
print c;
assert c == RecursiveCount(-2, q) == 2 by {
calc {
RecursiveCount(-2, q);
== { assert q[3] == -2; AppendOne(q, 3); }
1 + RecursiveCount(-2, q[..3]);
== { assert q[2] != -2; AppendOne(q, 2); }
1 + RecursiveCount(-2, q[..2]);
== { assert q[1] == -2; AppendOne(q, 1); }
1 + 1 + RecursiveCount(-2, q[..1]);
== { assert q[0] != -2; AppendOne(q, 0); }
1 + 1 + RecursiveCount(-2, q[..0]);
}
}
}
lemma AppendOne<T>(q: seq<T>, n: nat)
requires n < |q|
ensures q[..n]+[q[n]] == q[..n+1]
{}
function RecursivePositiveProduct(q: seq<int>): int
decreases |q|
{
if q == [] then 1
else if q[0] <= 0 then RecursivePositiveProduct(q[1..])
else q[0] * RecursivePositiveProduct(q[1..])
}
function RecursiveCount(key: int, q: seq<int>): int
decreases |q|
{
if q == [] then 0
else if q[|q|-1] == key then 1+RecursiveCount(key, q[..|q|-1])
else RecursiveCount(key, q[..|q|-1])
}
method ProdAndCount(q: seq<int>, key: int) returns (prod: int, count: nat)
ensures prod == RecursivePositiveProduct(q)
ensures count == RecursiveCount(key, q)
{
prod := 1;
count := 0;
var size := |q|;
var i := 0;
var curr := 0;
while i < size
invariant 0 <= i <= size && // legal index
count == RecursiveCount(key, q[..i]) && // count invar
prod == RecursivePositiveProduct(q[..i])
decreases size-i
{
Lemma_Count_Inv(q, i, count, key);
Lemma_Prod_Inv(q, i, prod);
curr := q[i];
if curr > 0 {
prod := prod*curr;
}
if curr == key {
count := count+1;
}
i := i+1;
}
Lemma_Count_Finish(q, i, count, key);
Lemma_Prod_Finish(q, i, prod);
}
function county(elem: int, key: int): int{
if elem==key then 1 else 0
}
function prody(elem: int): int{
if elem <= 0 then 1 else elem
}
lemma Lemma_Count_Inv(q: seq<int>, i: nat, count: int, key: int)
requires 0 <= i < |q| && count == RecursiveCount(key, q[..i])
ensures 0 <= i+1 <= |q| && county(q[i],key)+count == RecursiveCount(key, q[..i+1])
{
assert q[..i+1] == q[..i] + [q[i]];
var q1 := q[..i+1];
calc {
RecursiveCount(key, q[..i+1]);
== // def.
if q1 == [] then 0
else if q1[i] == key then 1+RecursiveCount(key,q1[..i])
else RecursiveCount(key, q1[..i]);
== { assert q1 != []; } // simplification for a non-empty sequence
if q1[i] == key then 1+RecursiveCount(key, q1[..i])
else RecursiveCount(key,q1[..i]);
== {KibutzLaw1(q1,key,i);} // the kibutz law
(if q1[i] == key then 1 else 0) + RecursiveCount(key, q1[..i]);
==
county(q1[i],key) + RecursiveCount(key, q1[..i]);
==
county(q[i],key) + RecursiveCount(key, q[..i]);
}
}
lemma Lemma_Prod_Inv(q: seq<int>, i: nat, prod: int)
requires 0 <= i < |q| && prod == RecursivePositiveProduct(q[..i])
ensures 0 <= i+1 <= |q| && prody(q[i])*prod == RecursivePositiveProduct(q[..i+1])
{
assert q[..i+1] == q[..i] + [q[i]];
var q1 := q[..i+1];
calc {
RecursivePositiveProduct(q[..i+1]);
== // def.
if q1 == [] then 1
else if q1[0] <= 0 then RecursivePositiveProduct(q1[1..])
else q1[0] * RecursivePositiveProduct(q1[1..]);
== { assert q1 != []; } // simplification for a non-empty sequence
if q1[0] <= 0 then RecursivePositiveProduct(q1[1..])
else q1[0] * RecursivePositiveProduct(q1[1..]);
== // def. of q1
if q[0] <= 0 then RecursivePositiveProduct(q[1..i+1])
else q[0] * RecursivePositiveProduct(q[1..i+1]);
== { KibutzLaw2(q);}
(if q[0] <= 0 then 1 else q[0])*RecursivePositiveProduct(q[1..i+1]);
==
prody(q[0])*RecursivePositiveProduct(q[1..i+1]);
== {PrependProd(q);}
RecursivePositiveProduct(q[..i+1]);
== {AppendProd(q[..i+1]);}
prody(q[i])*RecursivePositiveProduct(q[..i]);
==
prody(q[i])*prod;
}
}
lemma Lemma_Count_Finish(q: seq<int>, i: nat, count: int, key: int)
requires inv: 0 <= i <= |q| && count == RecursiveCount(key, q[..i])
requires neg_of_guard: i >= |q|
ensures count == RecursiveCount(key, q)
{
assert i <= |q| && count == RecursiveCount(key, q[..i]) by { reveal inv; }
assert i == |q| by { reveal inv,neg_of_guard; }
assert q[..i] == q[..|q|] == q;
}
lemma Lemma_Prod_Finish(q: seq<int>, i: nat, prod: int)
requires inv: 0 <= i <= |q| && prod == RecursivePositiveProduct(q[..i])
requires neg_of_guard: i >= |q|
ensures prod == RecursivePositiveProduct(q)
{
assert i <= |q| && prod == RecursivePositiveProduct(q[..i]) by { reveal inv; }
assert i == |q| by { reveal inv,neg_of_guard; }
assert q[..i] == q[..|q|] == q;
}
lemma KibutzLaw1(q: seq<int>,key: int,i: nat)
requires q != [] && i < |q|
ensures
(if q[|q|-1] == key then 1 + RecursiveCount(key, q[1..i+1])
else 0 + RecursiveCount(key, q[1..i+1]))
==
(if q[|q|-1] == key then 1 else 0) + RecursiveCount(key, q[1..i+1])
{
if q[|q|-1] == key {
calc {
(if q[|q|-1] == key then 1 + RecursiveCount(key, q[1..i+1])
else 0 + RecursiveCount(key, q[1..i+1]));
==
1 + RecursiveCount(key, q[1..i+1]);
==
(if q[|q|-1] == key then 1 else 0) + RecursiveCount(key, q[1..i+1]);
}
} else {
calc {
(if q[|q|-1] == key then 1 + RecursiveCount(key, q[1..i+1])
else 0 + RecursiveCount(key, q[1..i+1]));
==
0 + RecursiveCount(key, q[1..i+1]);
==
(if q[|q|-1] == key then 1 else 0) + RecursiveCount(key, q[1..i+1]);
}
}
}
lemma {:verify true} KibutzLaw2(q: seq<int>)
requires q != []
ensures
(if q[0] <= 0 then RecursivePositiveProduct(q[1..])
else q[0] * RecursivePositiveProduct(q[1..]))
==
(if q[0] <= 0 then 1 else q[0])*RecursivePositiveProduct(q[1..])
{
if q[0] <= 0 {
calc {
(if q[0] <= 0 then RecursivePositiveProduct(q[1..])
else q[0] * RecursivePositiveProduct(q[1..]));
==
RecursivePositiveProduct(q[1..]);
==
(if q[0] <= 0 then 1 else q[0])*RecursivePositiveProduct(q[1..]);
}
} else {
calc {
(if q[0] <= 0 then RecursivePositiveProduct(q[1..])
else q[0] * RecursivePositiveProduct(q[1..]));
==
q[0] * RecursivePositiveProduct(q[1..]);
==
(if q[0] <= 0 then 1 else q[0])*RecursivePositiveProduct(q[1..]);
}
}
}
lemma AppendCount(key: int, q: seq<int>)
requires q != []
ensures RecursiveCount(key, q) == RecursiveCount(key,q[..|q|-1])+county(q[|q|-1], key)
{
if |q| == 1
{
assert
RecursiveCount(key,q[..|q|-1])+county(q[|q|-1], key) ==
RecursiveCount(key,q[..0])+county(q[0], key) ==
RecursiveCount(key, [])+county(q[0], key) ==
0+county(q[0], key) ==
county(q[0], key);
assert RecursiveCount(key, q) == county(q[0], key);
}
else
{ // inductive step
var q1 := q[1..];
calc {
RecursiveCount(key, q);
== // def. for a non-empty sequence
if q == [] then 0
else if q[|q|-1] == key then 1+RecursiveCount(key, q[..|q|-1])
else RecursiveCount(key, q[..|q|-1]);
==
RecursiveCount(key, q[..|q|-1]) + county(q[|q|-1], key);
}
}
}
lemma PrependProd(q: seq<int>)
requires q != []
ensures RecursivePositiveProduct(q) == prody(q[0])*RecursivePositiveProduct(q[1..])
{
calc {
RecursivePositiveProduct(q);
==
if q == [] then 1
else if q[0] <= 0 then RecursivePositiveProduct(q[1..])
else q[0] * RecursivePositiveProduct(q[1..]);
== { assert q != []; } // simplification for a non-empty sequence
if q[0] <= 0 then RecursivePositiveProduct(q[1..])
else q[0] * RecursivePositiveProduct(q[1..]);
== { KibutzLaw2(q);}
(if q[0] <= 0 then 1 else q[0])*RecursivePositiveProduct(q[1..]);
==
prody(q[0])*RecursivePositiveProduct(q[1..]);
}
}
lemma AppendProd(q: seq<int>)
requires q != []
ensures RecursivePositiveProduct(q) == RecursivePositiveProduct(q[..|q|-1])*prody(q[|q|-1])
{
if |q| == 1
{
assert
RecursivePositiveProduct(q[..|q|-1])*prody(q[|q|-1]) ==
RecursivePositiveProduct(q[..0])*prody(q[0]) ==
RecursivePositiveProduct([])*prody(q[0]) ==
1*prody(q[0]) ==
prody(q[0]);
assert RecursivePositiveProduct(q) == prody(q[0]);
}
else
{ // inductive step
var q1 := q[1..];
calc {
RecursivePositiveProduct(q);
== // def. for a non-empty sequence
prody(q[0]) * RecursivePositiveProduct(q[1..]);
== { assert q1 != []; assert |q1| < |q|; AppendProd(q1); } // induction hypothesis (one assertion for the precondition, another for termination)
prody(q[0]) * RecursivePositiveProduct(q1[..|q1|-1]) * prody(q1[|q1|-1]);
== { assert q1[..|q1|-1] == q[1..|q|-1]; assert q1[|q1|-1] == q[|q|-1]; }
prody(q[0]) * RecursivePositiveProduct(q[1..|q|-1]) * prody(q[|q|-1]);
== {PrependProd(q[..|q|-1]);}
RecursivePositiveProduct(q[..|q|-1]) * prody(q[|q|-1]);
}
}
}
|
assertive-programming-assignment-1_tmp_tmp3h_cj44u_ProdAndCount.dfy
|
391
|
391
|
Dafny program: 391
|
method Main()
{
var q := [1,2,4,5,6,7,10,23];
var i,j := FindAddends(q, 10);
print "Searching for addends of 10 in q == [1,2,4,5,6,7,10,23]:\n";
print "Found that q[";
print i;
print "] + q[";
print j;
print "] == ";
print q[i];
print " + ";
print q[j];
print " == 10";
}
predicate Sorted(q: seq<int>)
{
forall i,j :: 0 <= i <= j < |q| ==> q[i] <= q[j]
}
predicate HasAddends(q: seq<int>, x: int)
{
exists i,j :: 0 <= i < j < |q| && q[i] + q[j] == x
}
method FindAddends(q: seq<int>, x: int) returns (i: nat, j: nat)
requires Sorted(q) && HasAddends(q, x)
ensures i < j < |q| && q[i]+q[j] == x
{
i := 0;
j := |q| - 1;
var sum := q[i] + q[j];
while sum != x
{
if (sum > x)
{
// Sum it too big, lower it by decreasing the high index
LoopInvWhenSumIsBigger(q, x, i, j, sum);
j := j - 1;
}
// 'sum == x' cannot occur because the loop's guard is 'sum !=x'.
else // (sum < x)
{
// Sum is too small, make it bigger by increasing the low index.
i := i + 1;
}
sum := q[i] + q[j];
}
}
predicate IsValidIndex<T>(q: seq<T>, i: nat)
{
0 <= i < |q|
}
predicate AreOreredIndices<T>(q: seq<T>, i: nat, j: nat)
{
0 <= i < j < |q|
}
predicate AreAddendsIndices(q: seq<int>, x: int, i: nat, j: nat)
requires IsValidIndex(q, i) && IsValidIndex(q, j)
{
q[i] + q[j] == x
}
predicate HasAddendsInIndicesRange(q: seq<int>, x: int, i: nat, j: nat)
requires AreOreredIndices(q, i, j)
{
HasAddends(q[i..(j + 1)], x)
}
predicate LoopInv(q: seq<int>, x: int, i: nat, j: nat, sum: int)
{
AreOreredIndices(q, i, j) &&
HasAddendsInIndicesRange(q, x, i, j) &&
AreAddendsIndices(q, sum, i, j)
}
lemma LoopInvWhenSumIsBigger(q: seq<int>, x: int, i: nat, j: nat, sum: int)
requires HasAddends(q, x)
requires Sorted(q)
requires sum > x;
requires LoopInv(q, x, i, j, sum)
ensures HasAddendsInIndicesRange(q, x, i, j - 1)
{
}
|
method Main()
{
var q := [1,2,4,5,6,7,10,23];
assert Sorted(q);
assert HasAddends(q,10) by { assert q[2]+q[4] == 4+6 == 10; }
var i,j := FindAddends(q, 10);
print "Searching for addends of 10 in q == [1,2,4,5,6,7,10,23]:\n";
print "Found that q[";
print i;
print "] + q[";
print j;
print "] == ";
print q[i];
print " + ";
print q[j];
print " == 10";
assert i == 2 && j == 4;
}
predicate Sorted(q: seq<int>)
{
forall i,j :: 0 <= i <= j < |q| ==> q[i] <= q[j]
}
predicate HasAddends(q: seq<int>, x: int)
{
exists i,j :: 0 <= i < j < |q| && q[i] + q[j] == x
}
method FindAddends(q: seq<int>, x: int) returns (i: nat, j: nat)
requires Sorted(q) && HasAddends(q, x)
ensures i < j < |q| && q[i]+q[j] == x
{
i := 0;
j := |q| - 1;
var sum := q[i] + q[j];
while sum != x
invariant LoopInv(q, x, i, j, sum)
decreases j - i
{
if (sum > x)
{
// Sum it too big, lower it by decreasing the high index
LoopInvWhenSumIsBigger(q, x, i, j, sum);
j := j - 1;
}
// 'sum == x' cannot occur because the loop's guard is 'sum !=x'.
else // (sum < x)
{
// Sum is too small, make it bigger by increasing the low index.
i := i + 1;
}
sum := q[i] + q[j];
}
}
predicate IsValidIndex<T>(q: seq<T>, i: nat)
{
0 <= i < |q|
}
predicate AreOreredIndices<T>(q: seq<T>, i: nat, j: nat)
{
0 <= i < j < |q|
}
predicate AreAddendsIndices(q: seq<int>, x: int, i: nat, j: nat)
requires IsValidIndex(q, i) && IsValidIndex(q, j)
{
q[i] + q[j] == x
}
predicate HasAddendsInIndicesRange(q: seq<int>, x: int, i: nat, j: nat)
requires AreOreredIndices(q, i, j)
{
HasAddends(q[i..(j + 1)], x)
}
predicate LoopInv(q: seq<int>, x: int, i: nat, j: nat, sum: int)
{
AreOreredIndices(q, i, j) &&
HasAddendsInIndicesRange(q, x, i, j) &&
AreAddendsIndices(q, sum, i, j)
}
lemma LoopInvWhenSumIsBigger(q: seq<int>, x: int, i: nat, j: nat, sum: int)
requires HasAddends(q, x)
requires Sorted(q)
requires sum > x;
requires LoopInv(q, x, i, j, sum)
ensures HasAddendsInIndicesRange(q, x, i, j - 1)
{
assert q[i..j] < q[i..(j + 1)];
}
|
assertive-programming-assignment-1_tmp_tmp3h_cj44u_SearchAddends.dfy
|
392
|
392
|
Dafny program: 392
|
// shenanigans going through the dafny tutorial
method MultipleReturns(x: int, y: int) returns (more: int, less: int)
requires 0 < y
ensures less < x < more
{
more := x + y;
less := x - y;
}
method Max(a: int, b: int) returns (c: int)
ensures a <= c && b <= c
ensures a == c || b == c
{
if a > b {
c := a;
} else { c := b; }
}
method Testing() {
var x := Max(3,15);
}
function max(a: int, b: int): int
{
if a > b then a else b
}
method Testing'() {
}
function abs(x: int): int
{
if x < 0 then -x else x
}
method Abs(x: int) returns (y: int)
ensures y == abs(x)
{
return abs(x);
}
method m(n: nat)
{
var i := 0;
while i != n
{
i := i + 1;
}
}
function fib(n: nat): nat
{
if n == 0 then 0
else if n == 1 then 1
else fib(n - 1) + fib(n - 2)
}
method Find(a: array<int>, key: int) returns (index: int)
ensures 0 <= index ==> index < a.Length && a[index] == key
ensures index < 0 ==> forall k :: 0 <= k < a.Length ==> a[k] != key
{
var i := 0;
while i < a.Length
{
if a[i] == key {return i;}
i := i+1;
}
return -1;
}
method FindMax(a: array<int>) returns (i: int)
requires a.Length >= 1
ensures 0 <= i < a.Length
ensures forall k :: 0 <= k < a.Length ==> a[k] <= a[i]
{
i := 0;
var max := a[i];
var j := 1;
while j < a.Length
{
if max < a[j] { max := a[j]; i := j; }
j := j+1;
}
}
predicate sorted(a: array<int>)
reads a
{
forall j, k :: 0 <= j < k < a.Length ==> a[j] < a[k]
}
predicate sorted'(a: array?<int>) // Change the type
reads a
{
forall j, k :: a != null && 0 <= j < k < a.Length ==> a[j] <= a[k]
}
|
// shenanigans going through the dafny tutorial
method MultipleReturns(x: int, y: int) returns (more: int, less: int)
requires 0 < y
ensures less < x < more
{
more := x + y;
less := x - y;
}
method Max(a: int, b: int) returns (c: int)
ensures a <= c && b <= c
ensures a == c || b == c
{
if a > b {
c := a;
} else { c := b; }
}
method Testing() {
var x := Max(3,15);
assert x >= 3 && x >= 15;
assert x == 15;
}
function max(a: int, b: int): int
{
if a > b then a else b
}
method Testing'() {
assert max(1,2) == 2;
assert forall a,b : int :: max (a,b) == a || max (a,b) == b;
}
function abs(x: int): int
{
if x < 0 then -x else x
}
method Abs(x: int) returns (y: int)
ensures y == abs(x)
{
return abs(x);
}
method m(n: nat)
{
var i := 0;
while i != n
invariant 0 <= i <= n
{
i := i + 1;
}
assert i == n;
}
function fib(n: nat): nat
{
if n == 0 then 0
else if n == 1 then 1
else fib(n - 1) + fib(n - 2)
}
method Find(a: array<int>, key: int) returns (index: int)
ensures 0 <= index ==> index < a.Length && a[index] == key
ensures index < 0 ==> forall k :: 0 <= k < a.Length ==> a[k] != key
{
var i := 0;
while i < a.Length
invariant 0 <= i <= a.Length
invariant forall k :: 0 <= k < i ==> a[k] != key
{
if a[i] == key {return i;}
i := i+1;
}
assert i == a.Length;
return -1;
}
method FindMax(a: array<int>) returns (i: int)
requires a.Length >= 1
ensures 0 <= i < a.Length
ensures forall k :: 0 <= k < a.Length ==> a[k] <= a[i]
{
i := 0;
var max := a[i];
var j := 1;
while j < a.Length
invariant 0 < j <= a.Length
invariant i < j
invariant max == a[i]
invariant forall k :: 0 <= k < j ==> a[k] <= max
{
if max < a[j] { max := a[j]; i := j; }
j := j+1;
}
}
predicate sorted(a: array<int>)
reads a
{
forall j, k :: 0 <= j < k < a.Length ==> a[j] < a[k]
}
predicate sorted'(a: array?<int>) // Change the type
reads a
{
forall j, k :: a != null && 0 <= j < k < a.Length ==> a[j] <= a[k]
}
|
bbfny_tmp_tmpw4m0jvl0_enjoying.dfy
|
393
|
393
|
Dafny program: 393
|
class {:autocontracts} Queue {
// Atributos
var circularQueue: array<int>;
var rear: nat; // cauda
var front: nat; // head
var counter: nat;
// Abstração
ghost var Content: seq<int>;
// Predicado
ghost predicate Valid()
{
0 <= counter <= circularQueue.Length &&
0 <= front &&
0 <= rear &&
Content == circularQueue[..]
}
// Construtor
constructor()
ensures circularQueue.Length == 0
ensures front == 0 && rear == 0
ensures Content == [] // REVISAR
ensures counter == 0
{
circularQueue := new int[0];
rear := 0;
front := 0;
Content := [];
counter := 0;
} //[tam] ; [1, 2, 3, 4]
method insert(item: int)
// requires rear <= circularQueue.Length
// ensures (front == 0 && rear == 0 && circularQueue.Length == 1) ==>
// (
// Content == [item] &&
// |Content| == 1
// )
// ensures circularQueue.Length != 0 ==>
// (
// (front == 0 && rear == 0 && circularQueue.Length == 1) ==>
// (
// Content == old(Content) &&
// |Content| == old(|Content|)
// )
// ||
// (front == 0 && rear == circularQueue.Length-1 ) ==>
// (
// Content == old(Content) + [item] &&
// |Content| == old(|Content|) + 1
// )
// ||
// (rear + 1 != front && rear != circularQueue.Length-1 && rear + 1 < circularQueue.Length - 1) ==>
// (
// Content == old(Content[0..rear]) + [item] + old(Content[rear..circularQueue.Length])
// )
// ||
// (rear + 1 == front) ==>
// (
// Content[0..rear + 1] == old(Content[0..rear]) + [item] &&
// forall i :: rear + 2 <= i <= circularQueue.Length ==> Content[i] == old(Content[i-1])
// )
// )
{
//counter := counter + 1;
// if front == 0 && rear == 0 && circularQueue.Length == 0
// {
// var queueInsert: array<int>;
// queueInsert := new int [circularQueue.Length + 1];
// queueInsert[0] := item;
// circularQueue := queueInsert;
// Content := [item];
// rear := rear + 1;
// }
// else if front == 0 && rear == circularQueue.Length-1 && circularQueue.Length > 0
// {
// var queueInsert: array<int>;
// queueInsert := new int [circularQueue.Length + 1];
// var i: nat := 0;
// while i < circularQueue.Length
// invariant circularQueue.Length + 1 == queueInsert.Length
// {
// queueInsert[i] := circularQueue[i];
// i := i + 1;
// }
// queueInsert[queueInsert.Length - 1] := item;
// Content := Content + [item];
// rear := rear + 1;
// circularQueue := queueInsert;
// }
}
method auxInsertEmptyQueue(item:int)
requires front == 0 && rear == 0 && circularQueue.Length == 0
ensures circularQueue.Length == 1
ensures Content == [item]
ensures |Content| == 1
ensures rear == 1
ensures counter == old(counter) + 1
ensures front == 0
{
counter := counter + 1;
var queueInsert: array<int>;
queueInsert := new int [circularQueue.Length + 1];
queueInsert[0] := item;
circularQueue := queueInsert;
Content := [item];
rear := rear + 1;
}
method auxInsertEndQueue(item:int)
requires front == 0 && rear == circularQueue.Length && circularQueue.Length >= 1
ensures Content == old(Content) + [item]
ensures |Content| == old(|Content|) + 1
ensures front == 0
ensures rear == old(rear) + 1
ensures counter == old(counter) + 1
// {
// counter := counter + 1;
// var queueInsert: array<int>;
// queueInsert := new int [circularQueue.Length + 1];
// var i: nat := 0;
// while i < circularQueue.Length
// invariant circularQueue.Length + 1 == queueInsert.Length
// invariant 0 <= i <= circularQueue.Length
// invariant forall j :: 0 <= j < i ==> queueInsert[j] == circularQueue[j]
// {
// queueInsert[i] := circularQueue[i];
// i := i + 1;
// }
// queueInsert[queueInsert.Length - 1] := item;
// Content := Content + [item];
// rear := rear + 1;
// circularQueue := queueInsert;
// }
method auxInsertSpaceQueue(item:int)
requires rear < front && front < circularQueue.Length
ensures rear == old(rear) + 1
ensures counter == old(counter) + 1
ensures Content == old(Content[0..rear]) + [item] + old(Content[rear+1..circularQueue.Length])
ensures |Content| == old(|Content|) + 1
method auxInsertInitQueue(item:int)
method auxInsertBetweenQueue(item:int)
// remove apenas mudando o ponteiro
// sem resetar o valor na posição, pois, provavelmente,
// vai ser sobrescrito pela inserção
method remove() returns (item: int)
requires front < circularQueue.Length
requires circularQueue.Length > 0
ensures rear <= |old(Content)|
ensures circularQueue.Length > 0
ensures item == old(Content)[old(front)]
ensures front == (old(front) + 1) % circularQueue.Length
ensures old(front) < rear ==> Content == old(Content)[old(front)..rear]
ensures old(front) > rear ==> Content == old(Content)[0 .. rear] + old(Content)[old(front)..|old(Content)|]
/*{
if counter == 0 {
item := -1;
} else {
item := circularQueue[front];
front := (front + 1) % circularQueue.Length;
counter := counter - 1;
}
}*/
method size() returns (size:nat)
ensures size == counter
{
size := counter;
}
method isEmpty() returns (isEmpty: bool)
ensures isEmpty == true ==> counter == 0;
ensures isEmpty == false ==> counter != 0;
{
isEmpty := if counter == 0 then true else false;
}
method contains(item: int) returns (contains: bool)
ensures contains == true ==> item in circularQueue[..]
ensures contains == false ==> item !in circularQueue[..]
{
var i: nat := 0;
contains := false;
while (i < circularQueue.Length)
{
if (circularQueue[i] == item) {
contains := true;
break;
}
i := i + 1;
}
}
// TODO
method mergeQueues(otherQueue: Queue) returns (mergedQueue: Queue)
{
// queue1.merge(queue2)
var newQueueSize : int := otherQueue.circularQueue.Length + circularQueue.Length;
var newFront: int := front;
var newRear: int := otherQueue.rear;
var tmp: array<int> := new int[newQueueSize];
forall i | 0 <= i < circularQueue.Length
{
tmp[i] := circularQueue[i];
}
// vamos copiar valores vazios?
// como identificamos os vazios? entre o rear e o front
// como iteramos entre rear e front? front -> rear
// [1, 3, 5, 7, 9] + [0, 2, 4, 6, 8] => [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]
// front => 8
// rear => 0
mergedQueue := new Queue();
}
}
method Main ()
{
var circularQueue := new Queue();
var isQueueEmpty := circularQueue.isEmpty();
var queueSize := circularQueue.size();
circularQueue.auxInsertEmptyQueue(2);
circularQueue.auxInsertEndQueue(4);
circularQueue.auxInsertEndQueue(4);
circularQueue.auxInsertEndQueue(56);
var contains56 := circularQueue.contains(56);
var contains4 := circularQueue.contains(4);
var item := circularQueue.remove();
//assert circularQueue.Content == [2, 4, 4, 56];
}
|
class {:autocontracts} Queue {
// Atributos
var circularQueue: array<int>;
var rear: nat; // cauda
var front: nat; // head
var counter: nat;
// Abstração
ghost var Content: seq<int>;
// Predicado
ghost predicate Valid()
{
0 <= counter <= circularQueue.Length &&
0 <= front &&
0 <= rear &&
Content == circularQueue[..]
}
// Construtor
constructor()
ensures circularQueue.Length == 0
ensures front == 0 && rear == 0
ensures Content == [] // REVISAR
ensures counter == 0
{
circularQueue := new int[0];
rear := 0;
front := 0;
Content := [];
counter := 0;
} //[tam] ; [1, 2, 3, 4]
method insert(item: int)
// requires rear <= circularQueue.Length
// ensures (front == 0 && rear == 0 && circularQueue.Length == 1) ==>
// (
// Content == [item] &&
// |Content| == 1
// )
// ensures circularQueue.Length != 0 ==>
// (
// (front == 0 && rear == 0 && circularQueue.Length == 1) ==>
// (
// Content == old(Content) &&
// |Content| == old(|Content|)
// )
// ||
// (front == 0 && rear == circularQueue.Length-1 ) ==>
// (
// Content == old(Content) + [item] &&
// |Content| == old(|Content|) + 1
// )
// ||
// (rear + 1 != front && rear != circularQueue.Length-1 && rear + 1 < circularQueue.Length - 1) ==>
// (
// Content == old(Content[0..rear]) + [item] + old(Content[rear..circularQueue.Length])
// )
// ||
// (rear + 1 == front) ==>
// (
// Content[0..rear + 1] == old(Content[0..rear]) + [item] &&
// forall i :: rear + 2 <= i <= circularQueue.Length ==> Content[i] == old(Content[i-1])
// )
// )
{
//counter := counter + 1;
// if front == 0 && rear == 0 && circularQueue.Length == 0
// {
// var queueInsert: array<int>;
// queueInsert := new int [circularQueue.Length + 1];
// queueInsert[0] := item;
// circularQueue := queueInsert;
// Content := [item];
// rear := rear + 1;
// }
// else if front == 0 && rear == circularQueue.Length-1 && circularQueue.Length > 0
// {
// var queueInsert: array<int>;
// queueInsert := new int [circularQueue.Length + 1];
// var i: nat := 0;
// while i < circularQueue.Length
// invariant circularQueue.Length + 1 == queueInsert.Length
// {
// queueInsert[i] := circularQueue[i];
// i := i + 1;
// }
// queueInsert[queueInsert.Length - 1] := item;
// Content := Content + [item];
// rear := rear + 1;
// circularQueue := queueInsert;
// }
}
method auxInsertEmptyQueue(item:int)
requires front == 0 && rear == 0 && circularQueue.Length == 0
ensures circularQueue.Length == 1
ensures Content == [item]
ensures |Content| == 1
ensures rear == 1
ensures counter == old(counter) + 1
ensures front == 0
{
counter := counter + 1;
var queueInsert: array<int>;
queueInsert := new int [circularQueue.Length + 1];
queueInsert[0] := item;
circularQueue := queueInsert;
Content := [item];
rear := rear + 1;
}
method auxInsertEndQueue(item:int)
requires front == 0 && rear == circularQueue.Length && circularQueue.Length >= 1
ensures Content == old(Content) + [item]
ensures |Content| == old(|Content|) + 1
ensures front == 0
ensures rear == old(rear) + 1
ensures counter == old(counter) + 1
// {
// counter := counter + 1;
// var queueInsert: array<int>;
// queueInsert := new int [circularQueue.Length + 1];
// var i: nat := 0;
// while i < circularQueue.Length
// invariant circularQueue.Length + 1 == queueInsert.Length
// invariant 0 <= i <= circularQueue.Length
// invariant forall j :: 0 <= j < i ==> queueInsert[j] == circularQueue[j]
// {
// queueInsert[i] := circularQueue[i];
// i := i + 1;
// }
// queueInsert[queueInsert.Length - 1] := item;
// Content := Content + [item];
// rear := rear + 1;
// circularQueue := queueInsert;
// }
method auxInsertSpaceQueue(item:int)
requires rear < front && front < circularQueue.Length
ensures rear == old(rear) + 1
ensures counter == old(counter) + 1
ensures Content == old(Content[0..rear]) + [item] + old(Content[rear+1..circularQueue.Length])
ensures |Content| == old(|Content|) + 1
method auxInsertInitQueue(item:int)
method auxInsertBetweenQueue(item:int)
// remove apenas mudando o ponteiro
// sem resetar o valor na posição, pois, provavelmente,
// vai ser sobrescrito pela inserção
method remove() returns (item: int)
requires front < circularQueue.Length
requires circularQueue.Length > 0
ensures rear <= |old(Content)|
ensures circularQueue.Length > 0
ensures item == old(Content)[old(front)]
ensures front == (old(front) + 1) % circularQueue.Length
ensures old(front) < rear ==> Content == old(Content)[old(front)..rear]
ensures old(front) > rear ==> Content == old(Content)[0 .. rear] + old(Content)[old(front)..|old(Content)|]
/*{
if counter == 0 {
item := -1;
} else {
item := circularQueue[front];
front := (front + 1) % circularQueue.Length;
counter := counter - 1;
}
}*/
method size() returns (size:nat)
ensures size == counter
{
size := counter;
}
method isEmpty() returns (isEmpty: bool)
ensures isEmpty == true ==> counter == 0;
ensures isEmpty == false ==> counter != 0;
{
isEmpty := if counter == 0 then true else false;
}
method contains(item: int) returns (contains: bool)
ensures contains == true ==> item in circularQueue[..]
ensures contains == false ==> item !in circularQueue[..]
{
var i: nat := 0;
contains := false;
while (i < circularQueue.Length)
decreases circularQueue.Length - i
invariant 0 <= i <= circularQueue.Length
invariant !contains ==> forall j :: 0 <= j < i ==> circularQueue[j] != item
{
if (circularQueue[i] == item) {
contains := true;
break;
}
i := i + 1;
}
}
// TODO
method mergeQueues(otherQueue: Queue) returns (mergedQueue: Queue)
{
// queue1.merge(queue2)
var newQueueSize : int := otherQueue.circularQueue.Length + circularQueue.Length;
var newFront: int := front;
var newRear: int := otherQueue.rear;
var tmp: array<int> := new int[newQueueSize];
forall i | 0 <= i < circularQueue.Length
{
tmp[i] := circularQueue[i];
}
// vamos copiar valores vazios?
// como identificamos os vazios? entre o rear e o front
// como iteramos entre rear e front? front -> rear
// [1, 3, 5, 7, 9] + [0, 2, 4, 6, 8] => [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]
// front => 8
// rear => 0
mergedQueue := new Queue();
}
}
method Main ()
{
var circularQueue := new Queue();
assert circularQueue.circularQueue.Length == 0;
assert circularQueue.Content == [];
assert circularQueue.Content != [1];
var isQueueEmpty := circularQueue.isEmpty();
assert isQueueEmpty == true;
var queueSize := circularQueue.size();
assert queueSize == 0;
circularQueue.auxInsertEmptyQueue(2);
assert circularQueue.Content == [2];
assert circularQueue.counter == 1;
assert circularQueue.circularQueue.Length == 1;
assert circularQueue.front == 0;
assert circularQueue.rear == 1;
assert circularQueue.rear != 2;
assert circularQueue.front != 2;
circularQueue.auxInsertEndQueue(4);
assert circularQueue.Content == [2,4];
assert circularQueue.counter == 2;
assert circularQueue.front == 0;
assert circularQueue.rear == 2;
circularQueue.auxInsertEndQueue(4);
assert circularQueue.Content == [2,4,4];
assert circularQueue.counter == 3;
circularQueue.auxInsertEndQueue(56);
assert circularQueue.Content == [2,4,4,56];
assert circularQueue.counter == 4;
var contains56 := circularQueue.contains(56);
assert contains56 == true;
var contains4 := circularQueue.contains(4);
assert contains4 == true;
var item := circularQueue.remove();
assert item == 2;
//assert circularQueue.Content == [2, 4, 4, 56];
assert (0 + 1) % 6 == 1;
assert (1 + 1) % 6 == 2;
assert (2 + 1) % 6 == 3;
assert (3 + 1) % 6 == 4;
assert (4 + 1) % 6 == 5;
assert (5 + 1) % 6 == 0;
assert (0 + 1) % 6 == 1;
}
|
circular-queue-implemetation_tmp_tmpnulfdc9l_Queue.dfy
|
394
|
394
|
Dafny program: 394
|
// ASSIGNMENT P1
// CMSC 433 FALL 2023
// PERFECT SCORE: 100 POINTS
//
// This assignment contains nine questions, each of which involves writing Dafny
// code. You should include your solutions in a single Dafny file and submit it using
// Gradescope.
//
// Revision history
//
// 2023-09-22 2:50 pm Fixed typo in Problem 3.
// Question 1 (5 points)
//
// Fill in a requires clause that enables Dafny to verify
// method PlusOne
method PlusOne (x : int) returns (y : int)
requires x >= 0
ensures y > 0
{
y := x+1;
}
// Question 2 (5 points)
//
// Fill in requires clause(s) that enable(s) Dafny to verify the array bounds
// in method Swap (which swaps elements i and j in array a).
method Swap (a : array?<int>, i : int, j : int)
requires a != null && 0 <= i < a.Length && 0 <= j < a.Length// TODO
modifies a // Dafny requires listing of objects modified in a method
{
var tmp : int := a[i];
a[i] := a[j];
a[j] := a[i];
}
// Question 3 (5 points)
//
// Give ensures clause(s) asserting that d is the result, and r the
// remainder, of dividing m by n. Your clauses cannot use "/" or "%" (which are
// the Dafny division and mod operators, respectively). By definition, the
// remainder must be non-negative.
method IntDiv (m : int, n : int) returns (d : int, r : int)
requires n > 0
ensures m == n * d + r && 0 <= r < n // TODO
{
return m / n, m % n;
}
// Question 4 (5 points)
//
// Give ensures clause(s) asserting that the return value has the same
// length as array a and contains as its elements the sum of the
// corresponding elements in arrays a and b.
method ArraySum (a : array<int>, b : array<int>) returns (c : array<int>)
requires a.Length == b.Length
ensures c.Length == a.Length &&
forall i : int :: 0 <= i < c.Length ==> c[i] == a[i] + b[i] // TODO
{
c := new int [a.Length]; // Creates new array of size a.Length
var i : int := 0;
while (i < a.Length)
{
c[i] := a[i] + b[i];
i := i + 1;
}
}
// Question 5 (10 points)
// Euclid's algorithm is used to compute the greatest common divisor of two
// positive integers. If m and n are two such integers, then gcd(m,n) is the
// largest positve integer that evenly divides both m and n, where j evenly divides i
// if and only if i % j == 0 (% is the Dafny mod operator). Write requires and
// ensures clauses for the method header Euclid below. Your requires clauses
// should also specify that the first argument is at least as large as the second.
// You do *not* need to implement the method!
method Euclid (m : int, n : int) returns (gcd : int)
requires m > 1 && n > 1 && m >= n // TODO
ensures gcd > 0 && gcd <= n && gcd <= m && m % gcd == 0 && n % gcd == 0 // TODO
// YOU DO NOT NEED TO IMPLEMENT Euclid!!
// Question 6 (10 points)
//
// Give invariant(s) that enable(s) Dafny to verify the following program, which
// returns true if and only if array a is sorted.
method IsSorted (a : array<int>) returns (isSorted : bool)
ensures isSorted <==> forall j : int :: 1 <= j < a.Length ==> a[j-1] <= a[j]
{
isSorted := true;
var i : int := 1;
if (a.Length < 2)
{
return;
}
else
{
while (i < a.Length)
{
if a[i-1] > a[i]
{
return false;
}
i := i+1;
}
}
}
// Question 7 (20 points)
//
// Implement, and have Dafny verify, the method IsPrime below, which returns true
// if and only if the given positive integer is prime.
method IsPrime (m : int) returns (isPrime : bool)
requires m > 0 // m must be greater than 0
ensures isPrime <==> (m > 1 && forall j : int :: 2 <= j < m ==> m % j != 0)
// ensures states that "isPrime is true iff m > 1 && not divisible by [2, m-1)"
{
isPrime := true; // asume is prime initially
if m <= 1 {
isPrime := false;
} else {
var i : int := 2;
while (i < m)
// invariant specifies that isPrime is true iff at each j from 2 to i-1, not j | m
{
if (m % i == 0)
{
isPrime := false;
break;
}
i := i + 1;
}
}
}
// Question 8 (20 points)
//
// Implement, and have Dafny verify, the method Reverse below, which returns a new array
// aRev consisting of the elements of a, but in reverse order. To create a new
// array of ints use the Dafny command "new int[...]", where "..." is the number
// of elements in the array.
method Reverse (a : array<int>) returns (aRev : array<int>)
ensures aRev.Length == a.Length
ensures forall i : int :: 0 <= i < a.Length ==> a[i] == aRev[aRev.Length-i-1]
ensures fresh(aRev) // Indicates returned object is newly created in method body
{
aRev := new int[a.Length];
var i : int := 0;
while (i < a.Length)
{
aRev[i] := a[a.Length-i-1];
i := i + 1;
}
}
// Question 9 (20 points)
//
// Implement and verify method NoDups, which returns true if and only if there
// are no duplicate elements in array a. Note that the requires clause allows
// you to assume that a is sorted, and that this precondition is necessary for
// the ensures clause to imply a lack of duplicates.
method NoDups (a : array<int>) returns (noDups : bool)
requires forall j : int :: 0 < j < a.Length ==> a[j-1] <= a[j] // a sorted
ensures noDups <==> forall j : int :: 1 <= j < a.Length ==> a[j-1] != a[j]
{
noDups := true;
var i : int := 1;
if (a.Length < 2)
{
return;
}
while (i < a.Length)
{
if (a[i-1] == a[i])
{
noDups := false;
break;
}
i := i + 1;
}
}
|
// ASSIGNMENT P1
// CMSC 433 FALL 2023
// PERFECT SCORE: 100 POINTS
//
// This assignment contains nine questions, each of which involves writing Dafny
// code. You should include your solutions in a single Dafny file and submit it using
// Gradescope.
//
// Revision history
//
// 2023-09-22 2:50 pm Fixed typo in Problem 3.
// Question 1 (5 points)
//
// Fill in a requires clause that enables Dafny to verify
// method PlusOne
method PlusOne (x : int) returns (y : int)
requires x >= 0
ensures y > 0
{
y := x+1;
}
// Question 2 (5 points)
//
// Fill in requires clause(s) that enable(s) Dafny to verify the array bounds
// in method Swap (which swaps elements i and j in array a).
method Swap (a : array?<int>, i : int, j : int)
requires a != null && 0 <= i < a.Length && 0 <= j < a.Length// TODO
modifies a // Dafny requires listing of objects modified in a method
{
var tmp : int := a[i];
a[i] := a[j];
a[j] := a[i];
}
// Question 3 (5 points)
//
// Give ensures clause(s) asserting that d is the result, and r the
// remainder, of dividing m by n. Your clauses cannot use "/" or "%" (which are
// the Dafny division and mod operators, respectively). By definition, the
// remainder must be non-negative.
method IntDiv (m : int, n : int) returns (d : int, r : int)
requires n > 0
ensures m == n * d + r && 0 <= r < n // TODO
{
return m / n, m % n;
}
// Question 4 (5 points)
//
// Give ensures clause(s) asserting that the return value has the same
// length as array a and contains as its elements the sum of the
// corresponding elements in arrays a and b.
method ArraySum (a : array<int>, b : array<int>) returns (c : array<int>)
requires a.Length == b.Length
ensures c.Length == a.Length &&
forall i : int :: 0 <= i < c.Length ==> c[i] == a[i] + b[i] // TODO
{
c := new int [a.Length]; // Creates new array of size a.Length
var i : int := 0;
while (i < a.Length)
invariant i <= a.Length
invariant forall j : int :: 0 <= j < i ==> c[j] == a[j] + b[j]
{
c[i] := a[i] + b[i];
i := i + 1;
}
}
// Question 5 (10 points)
// Euclid's algorithm is used to compute the greatest common divisor of two
// positive integers. If m and n are two such integers, then gcd(m,n) is the
// largest positve integer that evenly divides both m and n, where j evenly divides i
// if and only if i % j == 0 (% is the Dafny mod operator). Write requires and
// ensures clauses for the method header Euclid below. Your requires clauses
// should also specify that the first argument is at least as large as the second.
// You do *not* need to implement the method!
method Euclid (m : int, n : int) returns (gcd : int)
requires m > 1 && n > 1 && m >= n // TODO
ensures gcd > 0 && gcd <= n && gcd <= m && m % gcd == 0 && n % gcd == 0 // TODO
// YOU DO NOT NEED TO IMPLEMENT Euclid!!
// Question 6 (10 points)
//
// Give invariant(s) that enable(s) Dafny to verify the following program, which
// returns true if and only if array a is sorted.
method IsSorted (a : array<int>) returns (isSorted : bool)
ensures isSorted <==> forall j : int :: 1 <= j < a.Length ==> a[j-1] <= a[j]
{
isSorted := true;
var i : int := 1;
if (a.Length < 2)
{
return;
}
else
{
while (i < a.Length)
invariant 1 <= i <= a.Length
invariant isSorted <==> forall j: int :: 1 <= j < i ==> a[j-1] <= a[j] // TODO
{
if a[i-1] > a[i]
{
return false;
}
i := i+1;
}
}
}
// Question 7 (20 points)
//
// Implement, and have Dafny verify, the method IsPrime below, which returns true
// if and only if the given positive integer is prime.
method IsPrime (m : int) returns (isPrime : bool)
requires m > 0 // m must be greater than 0
ensures isPrime <==> (m > 1 && forall j : int :: 2 <= j < m ==> m % j != 0)
// ensures states that "isPrime is true iff m > 1 && not divisible by [2, m-1)"
{
isPrime := true; // asume is prime initially
if m <= 1 {
isPrime := false;
} else {
var i : int := 2;
while (i < m)
invariant isPrime <==> forall j : int :: 2 <= j < i ==> m % j != 0
// invariant specifies that isPrime is true iff at each j from 2 to i-1, not j | m
{
if (m % i == 0)
{
isPrime := false;
break;
}
i := i + 1;
}
}
}
// Question 8 (20 points)
//
// Implement, and have Dafny verify, the method Reverse below, which returns a new array
// aRev consisting of the elements of a, but in reverse order. To create a new
// array of ints use the Dafny command "new int[...]", where "..." is the number
// of elements in the array.
method Reverse (a : array<int>) returns (aRev : array<int>)
ensures aRev.Length == a.Length
ensures forall i : int :: 0 <= i < a.Length ==> a[i] == aRev[aRev.Length-i-1]
ensures fresh(aRev) // Indicates returned object is newly created in method body
{
aRev := new int[a.Length];
var i : int := 0;
while (i < a.Length)
invariant 0 <= i <= a.Length
invariant forall j : int :: 0 <= j < i ==> aRev[j] == a[a.Length-j-1]
{
aRev[i] := a[a.Length-i-1];
i := i + 1;
}
}
// Question 9 (20 points)
//
// Implement and verify method NoDups, which returns true if and only if there
// are no duplicate elements in array a. Note that the requires clause allows
// you to assume that a is sorted, and that this precondition is necessary for
// the ensures clause to imply a lack of duplicates.
method NoDups (a : array<int>) returns (noDups : bool)
requires forall j : int :: 0 < j < a.Length ==> a[j-1] <= a[j] // a sorted
ensures noDups <==> forall j : int :: 1 <= j < a.Length ==> a[j-1] != a[j]
{
noDups := true;
var i : int := 1;
if (a.Length < 2)
{
return;
}
while (i < a.Length)
invariant 1 <= i <= a.Length
invariant noDups <==> forall j : int :: 1 <= j < i ==> a[j-1] != a[j]
{
if (a[i-1] == a[i])
{
noDups := false;
break;
}
i := i + 1;
}
}
|
cmsc433_tmp_tmpe3ob3a0o_dafny_project1_p1-assignment-2.dfy
|
395
|
395
|
Dafny program: 395
|
// A8Q1 — Steph Renee McIntyre
// Following the solutions from Carmen Bruni
// There is no definition for power, so this function will be used for validating that our imperative program is correct. This is just for Dafny.
function power(a: int, n: int): int //function for a to the power of n
requires 0 <= n;
method A8Q1(y0: int, x: int) returns (z: int)
requires y0 >= 0;
/*Post-Condition*/ ensures z==power(x,y0);
{var y := y0; //This is here for Dafny's sake and immutable inputs...
/* (| y=y0 ^ y>=0 |) - Pre-Condition */
/* (| 1=power(x,y0-y) ^ y>=0 |) - implied (a) */
z := 1;
/* (| z=power(x,y0-y) ^ y>=0 |) - assignment */
while (y>0)
{
/* (| z=power(x,y0-y) ^ y>=0 ^ y>0 |) - partial-while */
/* (| z*x=power(x,y0-(y-1)) ^ (y-1)>=0 |) - implied (b) */
z := z*x;
/* (| z=power(x,y0-(y-1)) ^ (y-1)>=0 |) - assignment */
y := y-1;
/* (| z=power(x,y0-y) ^ y>=0 |) - assignment */
}
/* (| z=power(x,y0-y) ^ y>=0 ^ -(y>0) |) - partial-while */
/* (| z=power(x,y0-y) |) - implied (c) */
}
/* Proof of implieds can be seen on LEARN.
Note: If you are unconvinced, putting asserts for each condition will demonstrate the correctness of the statements.
*/
|
// A8Q1 — Steph Renee McIntyre
// Following the solutions from Carmen Bruni
// There is no definition for power, so this function will be used for validating that our imperative program is correct. This is just for Dafny.
function power(a: int, n: int): int //function for a to the power of n
requires 0 <= n;
decreases n;{if (n == 0) then 1 else a * power(a, n - 1)}
method A8Q1(y0: int, x: int) returns (z: int)
requires y0 >= 0;
/*Post-Condition*/ ensures z==power(x,y0);
{var y := y0; //This is here for Dafny's sake and immutable inputs...
/* (| y=y0 ^ y>=0 |) - Pre-Condition */
/* (| 1=power(x,y0-y) ^ y>=0 |) - implied (a) */
z := 1;
/* (| z=power(x,y0-y) ^ y>=0 |) - assignment */
while (y>0)
invariant z==power(x,y0-y) && y>=0;
decreases y; /* variant */
{
/* (| z=power(x,y0-y) ^ y>=0 ^ y>0 |) - partial-while */
/* (| z*x=power(x,y0-(y-1)) ^ (y-1)>=0 |) - implied (b) */
z := z*x;
/* (| z=power(x,y0-(y-1)) ^ (y-1)>=0 |) - assignment */
y := y-1;
/* (| z=power(x,y0-y) ^ y>=0 |) - assignment */
}
/* (| z=power(x,y0-y) ^ y>=0 ^ -(y>0) |) - partial-while */
/* (| z=power(x,y0-y) |) - implied (c) */
}
/* Proof of implieds can be seen on LEARN.
Note: If you are unconvinced, putting asserts for each condition will demonstrate the correctness of the statements.
*/
|
cs245-verification_tmp_tmp0h_nxhqp_A8_Q1.dfy
|
399
|
399
|
Dafny program: 399
|
// Sorting:
// Pre/Post Condition Issues - An investigation
// -- Stephanie McIntyre
// Based on examples in class
// First Attempt at specifying requirements for sorting array A in incrementing order
// We want our Hoare triple of (|Pre-Condition|) Code (|Post-Condition|) to hold iff A is properly sorted.
method sort(A: array<int>, n: int)
modifies A; requires n==A.Length;
/* Pre-Condition */ requires n>=0;
/* Post-Condition */ ensures forall i,j:: 0<=i<=j<n ==> A[i]<=A[j]; //This states that A is sorted.
//Can we write code that does not sort A that still satisfies the requirements?
//Consider the following program:
{
var k := 0;
while(k<n)
{
A[k] := k;
k := k+1;
}
}
|
// Sorting:
// Pre/Post Condition Issues - An investigation
// -- Stephanie McIntyre
// Based on examples in class
// First Attempt at specifying requirements for sorting array A in incrementing order
// We want our Hoare triple of (|Pre-Condition|) Code (|Post-Condition|) to hold iff A is properly sorted.
method sort(A: array<int>, n: int)
modifies A; requires n==A.Length;
/* Pre-Condition */ requires n>=0;
/* Post-Condition */ ensures forall i,j:: 0<=i<=j<n ==> A[i]<=A[j]; //This states that A is sorted.
//Can we write code that does not sort A that still satisfies the requirements?
//Consider the following program:
{
var k := 0;
while(k<n)
invariant k<=n;
invariant forall i:: 0<=i<k ==> A[i]==i;
{
A[k] := k;
k := k+1;
}
}
|
cs245-verification_tmp_tmp0h_nxhqp_SortingIssues_FirstAttempt.dfy
|
400
|
400
|
Dafny program: 400
|
//power -- Stephanie Renee McIntyre
//Based on the code used in the course overheads for Fall 2018
//There is no definition for power, so this function will be used for validating that our imperative program is correct.
function power(a: int, n: int): int //function for a to the power of n
requires 0 <= a && 0 <= n;
//Our code from class
method compute_power(a: int, n: int) returns (s: int)
/*Pre-Condition*/ requires n >= 0 && a >= 0;
/*Post-Condition*/ ensures s == power(a,n);
{
/* (| a >= 0 ^ n >= 0 |) - Pre-Condition: requires statement above */
/* (| 1 = power(a,0) ^ 0<=n |) - implied (a) */ assert 1 == power(a,0) && 0<=n;
s := 1;
/* (| s = power(a,0) ^ 0<=n |) - assignment */ assert s == power(a,0) && 0<=n;
var i := 0;
/* (| s = power(a,i) ^ i<=n |) - assignment */ assert s == power(a,i) && i<=n;
while (i < n)
{
/* (| s = power(a,i) ^ i<=n ^ i<n |) - partial-while */ assert s == power(a,i) && i<=n && i<n;
/* (| s*a = power(a,i+1) ^ i+1<=n |) - implied (b) */ assert s*a == power(a,i+1) && i+1<=n;
s := s*a;
/* (| s = power(a,i+1) ^ i+1<=n |) - assignment */ assert s == power(a,i+1) && i+1<=n;
i := i+1;
/* (| s = power(a,i) ^ i<=n |) - assignment */ assert s == power(a,i) && i<=n;
}
/* (| s = power(a,i) ^ i<=n ^ -(i<n) |) - partial-while */ assert s == power(a,i) && i<=n && !(i<n);
/* (| s = power(a,n) |) - implied (c) //Post-Condition: ensures statement above */
}
/* Proof of implied (a): Follows from definition of the power function. */
/* Proof of implied (b): Details left as exercise, but this is relatively simple. */
/* Proof of implied (c): Simple substitution and uses the fact that i=n. */
/* Proof of termination: the loop guard gives us the expression i<n. This is equivalent to n-i>=0.
Prior to the loop, n>=0 and i=0.
Each iteration of the loop, i increases by 1 and thus n-i decreases by 1. Thus n-i will eventually reach 0.
When the n-i=0, n=i and thus the loop guard ends the loop as it is no longer the case that i<n.
Thus the program terminates.
*/
|
//power -- Stephanie Renee McIntyre
//Based on the code used in the course overheads for Fall 2018
//There is no definition for power, so this function will be used for validating that our imperative program is correct.
function power(a: int, n: int): int //function for a to the power of n
requires 0 <= a && 0 <= n;
decreases n;{if (n == 0) then 1 else a * power(a, n - 1)}
//Our code from class
method compute_power(a: int, n: int) returns (s: int)
/*Pre-Condition*/ requires n >= 0 && a >= 0;
/*Post-Condition*/ ensures s == power(a,n);
{
/* (| a >= 0 ^ n >= 0 |) - Pre-Condition: requires statement above */
/* (| 1 = power(a,0) ^ 0<=n |) - implied (a) */ assert 1 == power(a,0) && 0<=n;
s := 1;
/* (| s = power(a,0) ^ 0<=n |) - assignment */ assert s == power(a,0) && 0<=n;
var i := 0;
/* (| s = power(a,i) ^ i<=n |) - assignment */ assert s == power(a,i) && i<=n;
while (i < n)
invariant s==power(a,i) && i<=n;
decreases n-i; //this is the variant
{
/* (| s = power(a,i) ^ i<=n ^ i<n |) - partial-while */ assert s == power(a,i) && i<=n && i<n;
/* (| s*a = power(a,i+1) ^ i+1<=n |) - implied (b) */ assert s*a == power(a,i+1) && i+1<=n;
s := s*a;
/* (| s = power(a,i+1) ^ i+1<=n |) - assignment */ assert s == power(a,i+1) && i+1<=n;
i := i+1;
/* (| s = power(a,i) ^ i<=n |) - assignment */ assert s == power(a,i) && i<=n;
}
/* (| s = power(a,i) ^ i<=n ^ -(i<n) |) - partial-while */ assert s == power(a,i) && i<=n && !(i<n);
/* (| s = power(a,n) |) - implied (c) //Post-Condition: ensures statement above */
}
/* Proof of implied (a): Follows from definition of the power function. */
/* Proof of implied (b): Details left as exercise, but this is relatively simple. */
/* Proof of implied (c): Simple substitution and uses the fact that i=n. */
/* Proof of termination: the loop guard gives us the expression i<n. This is equivalent to n-i>=0.
Prior to the loop, n>=0 and i=0.
Each iteration of the loop, i increases by 1 and thus n-i decreases by 1. Thus n-i will eventually reach 0.
When the n-i=0, n=i and thus the loop guard ends the loop as it is no longer the case that i<n.
Thus the program terminates.
*/
|
cs245-verification_tmp_tmp0h_nxhqp_power.dfy
|
401
|
401
|
Dafny program: 401
|
// Quicksort Partition -- Stephanie McIntyre
// Based on examples in class
// Parts have been modified cause you know, arrays are different...
method QuicksortPartition(X: array<int>, n: int, p: int) returns (a: int, b: int)
modifies X;
/*Pre-Condition*/ requires X.Length>=1 && n == X.Length;
/*Post-Condition*/ ensures b>=n;
ensures forall x:: 0<=x<a<n ==> X[x] <= p;
ensures forall x:: a==n || (0<=a<=x<n ==> X[x] > p);
ensures multiset(X[..])==multiset(old(X[..])) //This says the new X is a permutation of our old version of X.
{
a := 0;
while ( a < n && X[a] <= p )
{
a := a+1;
}
b := a+1;
while ( b<n )
{
if ( X[b] <= p ) {
var t := X[b];
X[b] := X[a];
X[a] := t;
a := a+1;
}
b := b+1;
}
}
/* The annotations and implied proofs are left for you.
I might do them later on next week. */
|
// Quicksort Partition -- Stephanie McIntyre
// Based on examples in class
// Parts have been modified cause you know, arrays are different...
method QuicksortPartition(X: array<int>, n: int, p: int) returns (a: int, b: int)
modifies X;
/*Pre-Condition*/ requires X.Length>=1 && n == X.Length;
/*Post-Condition*/ ensures b>=n;
ensures forall x:: 0<=x<a<n ==> X[x] <= p;
ensures forall x:: a==n || (0<=a<=x<n ==> X[x] > p);
ensures multiset(X[..])==multiset(old(X[..])) //This says the new X is a permutation of our old version of X.
{
a := 0;
while ( a < n && X[a] <= p )
invariant 0<=a<=n
invariant forall x:: (0<=x<=a-1 ==> X[x]<=p)
{
a := a+1;
}
b := a+1;
while ( b<n )
invariant 0<=a<b<=n+1;
invariant b==n+1 ==> a==n //This is for Dafny for access issues. Don't worry about it in our stuff.
invariant forall x:: (0<=x<=a-1 ==> X[x]<=p);
invariant forall x:: a==n || (0<=a<=x<b ==> X[x] > p);
invariant multiset(X[..])==multiset(old(X[..])) //This says the new X is a permutation of our old version of X.
{
if ( X[b] <= p ) {
var t := X[b];
X[b] := X[a];
X[a] := t;
a := a+1;
}
b := b+1;
}
}
/* The annotations and implied proofs are left for you.
I might do them later on next week. */
|
cs245-verification_tmp_tmp0h_nxhqp_quicksort-partition.dfy
|
403
|
403
|
Dafny program: 403
|
method M1(x: int, y: int) returns (r: int)
ensures r == x*y
{
if (x == 0){
r:= 0;
} else if( x < 0){
r:= M1(-x, y);
r:= -r;
} else {
r:= M1(x-1, y);
r:= A1(r, y);
}
}
method A1(x: int, y: int) returns (r: int)
ensures r == x + y
{
r:= x;
if( y < 0){
var n:= y;
while(n != 0)
{
r:= r-1;
n:= n + 1;
}
} else {
var n := y;
while(n!= 0)
{
r:= r + 1;
n:= n - 1;
}
}
}
|
method M1(x: int, y: int) returns (r: int)
ensures r == x*y
decreases x < 0, x
{
if (x == 0){
r:= 0;
} else if( x < 0){
r:= M1(-x, y);
r:= -r;
} else {
r:= M1(x-1, y);
r:= A1(r, y);
}
}
method A1(x: int, y: int) returns (r: int)
ensures r == x + y
{
r:= x;
if( y < 0){
var n:= y;
while(n != 0)
invariant r == x + y - n
invariant -n >= 0
{
r:= r-1;
n:= n + 1;
}
} else {
var n := y;
while(n!= 0)
invariant r == x+ y - n
invariant n >= 0
{
r:= r + 1;
n:= n - 1;
}
}
}
|
cs357_tmp_tmpn4fsvwzs_lab7_question5.dfy
|
405
|
405
|
Dafny program: 405
|
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
datatype Abc = End | Wrapper(seq<Abc>)
lemma SeqRank0(a: Abc)
ensures a != Wrapper([a])
{
// The reason we need the assert is to match the trigger in the rank axioms produced
// for datatypes containing sequences.
// See "is SeqType" case of AddDatatype in Translator.cs
}
lemma SeqRank1(s: seq<Abc>)
requires s != []
ensures s[0] != Wrapper(s)
{
}
datatype Def = End | MultiWrapper(multiset<Def>)
lemma MultisetRank(a: Def)
ensures a != MultiWrapper(multiset{a})
{
}
datatype Ghi = End | SetWrapper(set<Ghi>)
lemma SetRank(a: Ghi)
ensures a != SetWrapper({a})
{
}
|
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
datatype Abc = End | Wrapper(seq<Abc>)
lemma SeqRank0(a: Abc)
ensures a != Wrapper([a])
{
assert [a][0] == a; // TODO: one could consider strengthening axioms to eliminate the need for this assert
// The reason we need the assert is to match the trigger in the rank axioms produced
// for datatypes containing sequences.
// See "is SeqType" case of AddDatatype in Translator.cs
}
lemma SeqRank1(s: seq<Abc>)
requires s != []
ensures s[0] != Wrapper(s)
{
}
datatype Def = End | MultiWrapper(multiset<Def>)
lemma MultisetRank(a: Def)
ensures a != MultiWrapper(multiset{a})
{
}
datatype Ghi = End | SetWrapper(set<Ghi>)
lemma SetRank(a: Ghi)
ensures a != SetWrapper({a})
{
}
|
dafl_tmp_tmp_r3_8w3y_dafny_examples_dafny0_ContainerRanks.dfy
|
408
|
408
|
Dafny program: 408
|
// RUN: %dafny /compile:0 /print:"%t.print" /dprint:"%t.dprint" /printTooltips "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
lemma Tests<T>(t: T, uu: seq<T>) returns (z: bool)
requires 10 <= |uu| && uu[4] == t
ensures !z
{
if {
case true =>
z := 72 in set i | 0 <= i < 10;
case true =>
z := -8 in set k: nat | k < 10;
case true =>
z := 6 in set m | 0 <= m < 10 && Even(m) :: m + 1;
case true =>
z := t !in set u | u in uu;
case true =>
z := t !in set u {:autotriggers false} | u in uu :: Id(u);
}
}
lemma TestsWhereTriggersMatter<T>(t: T, uu: seq<T>) returns (z: bool)
requires 10 <= |uu| && uu[4] == t
ensures z
{
if {
case true =>
z := 7 in set i | 0 <= i < 10;
case true =>
z := 8 in set k: nat | k < 10;
case true =>
// In the line below, auto-triggers should pick Even(m)
z := 5 in set m | 0 <= m < 10 && Even(m) :: m + 1;
// a necessary lemma:
case true =>
z := t in set u | u in uu;
case true =>
z := t in set u {:autotriggers false} | u in uu :: Id(u);
}
}
function Id<T>(t: T): T { t }
predicate Even(x: int) { x % 2 == 0 }
class Container<T> {
ghost var Contents: set<T>
var elems: seq<T>
method Add(t: T)
requires Contents == set x | x in elems
modifies this
ensures Contents == set x | x in elems
{
elems := elems + [t];
Contents := Contents + {t};
}
}
class IntContainer {
ghost var Contents: set<int>
var elems: seq<int>
method Add(t: int)
requires Contents == set x | x in elems
modifies this
ensures Contents == set x | x in elems
{
elems := elems + [t];
Contents := Contents + {t};
}
}
method UnboxedBoundVariables(si: seq<int>)
{
var iii := set x | x in si;
var ti := si + [115];
var jjj := set y | y in ti;
var nnn := set n: nat | n in si;
if forall i :: 0 <= i < |si| ==> 0 <= si[i] {
}
}
|
// RUN: %dafny /compile:0 /print:"%t.print" /dprint:"%t.dprint" /printTooltips "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
lemma Tests<T>(t: T, uu: seq<T>) returns (z: bool)
requires 10 <= |uu| && uu[4] == t
ensures !z
{
if {
case true =>
z := 72 in set i | 0 <= i < 10;
case true =>
z := -8 in set k: nat | k < 10;
case true =>
z := 6 in set m | 0 <= m < 10 && Even(m) :: m + 1;
case true =>
z := t !in set u | u in uu;
case true =>
z := t !in set u {:autotriggers false} | u in uu :: Id(u);
}
}
lemma TestsWhereTriggersMatter<T>(t: T, uu: seq<T>) returns (z: bool)
requires 10 <= |uu| && uu[4] == t
ensures z
{
if {
case true =>
z := 7 in set i | 0 <= i < 10;
case true =>
z := 8 in set k: nat | k < 10;
case true =>
// In the line below, auto-triggers should pick Even(m)
z := 5 in set m | 0 <= m < 10 && Even(m) :: m + 1;
// a necessary lemma:
assert Even(4);
case true =>
z := t in set u | u in uu;
case true =>
z := t in set u {:autotriggers false} | u in uu :: Id(u);
}
}
function Id<T>(t: T): T { t }
predicate Even(x: int) { x % 2 == 0 }
class Container<T> {
ghost var Contents: set<T>
var elems: seq<T>
method Add(t: T)
requires Contents == set x | x in elems
modifies this
ensures Contents == set x | x in elems
{
elems := elems + [t];
Contents := Contents + {t};
}
}
class IntContainer {
ghost var Contents: set<int>
var elems: seq<int>
method Add(t: int)
requires Contents == set x | x in elems
modifies this
ensures Contents == set x | x in elems
{
elems := elems + [t];
Contents := Contents + {t};
}
}
method UnboxedBoundVariables(si: seq<int>)
{
var iii := set x | x in si;
var ti := si + [115];
var jjj := set y | y in ti;
assert iii + {115} == jjj;
var nnn := set n: nat | n in si;
if forall i :: 0 <= i < |si| ==> 0 <= si[i] {
assert nnn == iii;
}
}
|
dafl_tmp_tmp_r3_8w3y_dafny_examples_dafny0_InSetComprehension.dfy
|
409
|
409
|
Dafny program: 409
|
// RUN: %dafny /compile:0 /functionSyntax:4 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
predicate P0(A: bool, B: bool, C: bool) {
A &&
B ==> C // warning: suspicious lack of parentheses (lhs of ==>)
}
predicate P1(A: bool, B: bool, C: bool) {
A && B ==>
C
}
predicate P2(A: bool, B: bool, C: bool) {
A &&
B
==>
C
}
predicate P3(A: bool, B: bool, C: bool, D: bool) {
A &&
B ==>
C &&
D
}
predicate P4(A: bool, B: bool, C: bool, D: bool) {
A &&
B
==>
C &&
D
}
predicate P5(A: bool, B: bool, C: bool) {
A ==>
&& B
&& C
}
predicate P6(A: bool, B: bool, C: bool) {
A ==>
|| B
|| C
}
predicate Q0(A: bool, B: bool, C: bool, D: bool) {
A &&
B ==> C && // warning (x2): suspicious lack of parentheses (lhs and rhs of ==>)
D
}
predicate Q1(A: bool, B: bool, C: bool, D: bool) {
A &&
B ==> C && // warning: suspicious lack of parentheses (lhs of ==>)
D
}
predicate Q2(A: bool, B: bool, C: bool, D: bool) {
A &&
B ==> (C && // warning: suspicious lack of parentheses (lhs of ==>)
D)
}
predicate Q3(A: bool, B: bool, C: bool, D: bool) {
(A &&
B) ==> (C &&
D)
}
predicate Q4(A: bool, B: bool, C: bool, D: bool) {
&& A
&& B ==> C // warning (x2): suspicious lack of parentheses (lhs and rhs of ==>)
&& D
}
predicate Q4a(A: bool, B: bool, C: bool, D: bool) {
&& A
&& B ==>
C && D
}
predicate Q4b(A: bool, B: bool, C: bool, D: bool) {
&& A
&& B ==>
C &&
D
}
predicate Q4c(A: bool, B: bool, C: bool, D: bool) {
&& A
&& B ==>
&& C
&& D
}
predicate Q4d(A: bool, B: bool, C: bool, D: bool) {
&& A
&& B ==>
&& C
&& D
}
predicate Q5(A: bool, B: bool, C: bool, D: bool) {
&& A
&& B ==> C // warning: suspicious lack of parentheses (lhs of ==>)
&& D
}
predicate Q6(A: bool, B: bool, C: bool, D: bool) {
&& A
&& B ==> && C // warning (x2): suspicious lack of parentheses (lhs and rhs of ==>)
&& D
}
predicate Q7(A: bool, B: bool, C: bool, D: bool) {
A
==> // warning: suspicious lack of parentheses (rhs of ==>)
B && C &&
D
}
predicate Q8(A: bool, B: bool, C: bool, D: bool) {
A
==>
B && C &&
D
}
predicate Q8a(A: bool, B: bool, C: bool, D: bool) {
(A
==>
B && C &&
D
) &&
(B || C)
}
predicate Q8b(A: bool, B: bool, C: bool, D: bool) {
A &&
B
==>
B &&
D
}
predicate Q8c(t: int, x: int, y: int)
{
&& (t == 2 ==> x < y)
&& (|| t == 3
|| t == 2
==>
&& x == 100
&& y == 1000
)
&& (t == 4 ==> || 0 <= x || 0 <= y)
}
predicate Q8d(t: int, x: int, y: int)
{
|| t == 3
|| t == 2
==>
&& x == 100
&& y == 1000
}
predicate Q9(A: bool, B: bool, C: bool) {
A ==> B ==>
C
}
ghost predicate R0(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x :: P(x) ==>
Q(x) &&
R(x)
}
ghost predicate R1(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x :: P(x) && Q(x) ==>
R(x)
}
ghost predicate R2(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x :: P(x) ==> Q(x) ==>
R(x)
}
ghost predicate R3(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x :: P(x) ==>
Q(x) ==>
R(x)
}
ghost predicate R4(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x :: P(x) ==> Q(x) ==>
R(x)
}
ghost predicate R5(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x :: P(x) ==>
forall y :: Q(y) ==>
R(x)
}
ghost predicate R6(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x :: (P(x) ==> Q(x)) && // warning: suspicious lack of parentheses (forall)
R(x)
}
ghost predicate R7(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x ::
(P(x) ==> Q(x)) &&
R(x)
}
ghost predicate R8(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x ::
(P(x) ==> Q(x)) &&
R(x)
}
ghost predicate R9(P: int -> bool, Q: int -> bool, R: int -> bool) {
exists x :: (P(x) ==> Q(x)) && // warning: suspicious lack of parentheses (exists)
R(x)
}
ghost predicate R10(P: int -> bool, Q: int -> bool, R: int -> bool) {
exists x :: P(x) && // warning: suspicious lack of parentheses (exists)
exists y :: Q(y) && // warning: suspicious lack of parentheses (exists)
R(x)
}
lemma Injective()
ensures forall x, y ::
Negate(x) == Negate(y)
==> x == y
{
}
function Negate(x: int): int {
-x
}
predicate Quant0(s: string) {
&& s != []
&& (|| 'a' <= s[0] <= 'z'
|| 'A' <= s[0] <= 'Z')
&& forall i :: 1 <= i < |s| ==>
|| 'a' <= s[i] <= 'z'
|| 'A' <= s[i] <= 'Z'
|| '0' <= s[i] <= '9'
}
predicate Quant1(m: array2<string>, P: int -> bool)
reads m
{
forall i :: 0 <= i < m.Length0 && P(i) ==> forall j :: 0 <= j < m.Length1 ==>
m[i, j] != ""
}
predicate Quant2(s: string) {
forall i :: 0 <= i < |s| ==> if s[i] == '*' then false else
s[i] == 'a' || s[i] == 'b'
}
ghost predicate Quant3(f: int -> int, g: int -> int) {
forall x ::
f(x) == g(x)
}
ghost predicate Quant4(f: int -> int, g: int -> int) {
forall x :: f(x) ==
g(x)
}
ghost predicate Quant5(f: int -> int, g: int -> int) {
forall x :: f(x)
== g(x)
}
function If0(s: string): int {
if |s| == 3 then 2 else 3 + // warning: suspicious lack of parentheses (if-then-else)
(2 * |s|)
}
function If1(s: string): int {
if |s| == 3 then 2 else
3 + (2 * |s|)
}
function If2(s: string): int {
if |s| == 3 then 2 else (3 +
2 * |s|)
}
function If3(s: string): int {
if |s| == 3 then 2 else
3 +
2 * |s|
}
predicate Waterfall(A: bool, B: bool, C: bool, D: bool, E: bool) {
A ==>
B ==>
C ==>
D ==>
E
}
ghost predicate MoreOps0(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x :: P(x) <== Q(x) <== // warning: suspicious lack of parentheses (rhs of <==)
R(x)
}
ghost predicate MoreOps1(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x :: P(x) <== Q(x) <==>
R(x)
}
ghost predicate MoreOps2(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x :: P(x) ==> Q(x) <==>
R(x)
}
ghost predicate MoreOps3(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x :: P(x) ==> Q(x) <==>
R(x) ==>
P(x)
}
ghost predicate MoreOps4(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x :: P(x) <==> Q(x) && // warning: suspicious lack of parentheses (rhs of <==>)
R(x)
}
lemma IntLemma(x: int)
function StmtExpr0(x: int): int {
if x == 17 then
2
else
IntLemma(x);
3
}
function StmtExpr1(x: int): int {
if x == 17 then // warning: suspicious lack of parentheses (if-then-else)
2
else
IntLemma(x);
3
}
function StmtExpr2(x: int): int {
if x == 17 then
2
else
3
}
function StmtExpr3(x: int): int {
if x == 17 then // warning: suspicious lack of parentheses (if-then-else)
2
else
3
}
function FunctionWithDefaultParameterValue(x: int, y: int := 100): int
function UseDefaultValues(x: int): int {
if x <= 0 then 0 else
FunctionWithDefaultParameterValue(x - 1)
}
function Square(x: int): int {
x * x
}
predicate Let0(lo: int, hi: int)
requires lo <= hi
{
forall x :: lo <= x < hi ==> var square := Square(x);
0 <= square
}
ghost predicate Let1(P: int -> bool) {
forall x :: 0 <= x && P(x) ==> var bigger :| x <= bigger;
0 <= bigger
}
predicate SomeProperty<X>(x: X)
method Parentheses0(arr: array<int>, P: int -> bool)
{
[i]);
var x := forall i :: 0 <= i < arr.Length ==> SomeProperty(
arr[i]);
var y := forall i :: 0 <= i < arr.Length ==> P(
arr[i]);
arr);
var u := if arr.Length == 3 then true else fresh(
arr);
}
method Parentheses1(w: bool, x: int)
{
var a := if w then {} else {x,
x, x};
var b := if w then iset{} else iset{x,
x, x};
var c := if w then [] else [x,
x, x];
var d := if w then multiset{} else multiset{x,
x, x};
var e := if w then map[] else map[x :=
x];
var f := if w then imap[] else imap[
x := x];
}
datatype Record = Record(x: int, y: int)
method Parentheses2(w: bool, x: int, y: int)
{
var a := if w then Record(0,
0
) else Record(x,
y);
var b := if w then
a else a
.
(
x
:=
y
)
;
}
method Parentheses3(w: bool, arr: array<int>, m: array2<int>, i: nat, j: nat)
requires i < j < arr.Length <= m.Length0 <= m.Length1
{
var a := if w then 0 else arr
[
i];
var b := if w then [] else arr
[ i .. ];
var c := if w then [] else arr
[..
i];
var d := if w then [] else arr
[
i..j];
var e := if w then [] else arr
[
..j][i..];
var f := if w then [] else arr // warning: suspicious lack of parentheses (if-then-else)
[..i] + arr[i..];
var g := if w then 0 else m
[i,
j];
var h := if w then arr[..] else arr[..j]
[0 := 25];
}
codatatype Stream = More(head: int, tail: Stream)
method Parentheses4(w: bool, s: Stream, t: Stream)
{
ghost var a := if w then true else s ==#[
12] t;
ghost var b := if w then true else s ==#[ // warning: suspicious lack of parentheses (ternary)
12] t;
ghost var c := if w then true else s // warning: suspicious lack of parentheses (ternary)
!=#[12] t;
ghost var d := if w then true else s
!=#[12] t;
}
/**** revisit the following when the original match'es are being resolved (https://github.com/dafny-lang/dafny/pull/2734)
datatype Color = Red | Blue
method Parentheses5(w: bool, color: Color) {
var a := if w then 5 else match color
case Red => 6
case
Blue => 7;
var b := if w then 5 else match
color
case Red => 6
case
Blue => 7;
var c := if w then 5 else match color { // warning: suspicious lack of parentheses (if-then-else)
case Red => 6
case
Blue => 7} + 10;
var d :=
match color
case Red => 6
case Blue => 7 // warning: suspicious lack of parentheses (case)
+ 10;
var e :=
match color
case Red => 6
+ 10
case Blue => 7;
var f :=
match color {
case Red => 6
case Blue => 7
+ 10 };
var g :=
if w then 5 else match color { // warning: suspicious lack of parentheses (if-then-else)
case Red => 6
case Blue => 7
+ 10 }
+ 20;
}
***/
module MyModule {
function MyFunction(x: int): int
lemma Lemma(x: int)
}
module QualifiedNames {
import MyModule
predicate P(x: int) {
var u := x;
MyModule.MyFunction(x) ==
x
}
predicate Q(x: int) {
var u := x;
MyModule.Lemma(x);
x == MyModule.MyFunction(x)
}
function F(): int
{
var p := 1000;
MyModule.Lemma(p);
p
}
predicate R(x: int) {
var u := x; // warning: suspicious lack of parentheses (let)
MyModule.
Lemma(x);
x ==
MyModule.MyFunction(x)
}
}
module MatchAcrossMultipleLines {
datatype PQ = P(int) | Q(bool)
method M(s: set<PQ>)
requires
(forall pq | pq in s :: match pq {
case P(x) => true
case Q(y) => y == false
})
{
}
datatype YZ = Y | Z
function F(A: bool, B: int, C: YZ): int
requires C != Y
{
if A then B else match C {
case Z => 3
}
}
}
|
// RUN: %dafny /compile:0 /functionSyntax:4 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
predicate P0(A: bool, B: bool, C: bool) {
A &&
B ==> C // warning: suspicious lack of parentheses (lhs of ==>)
}
predicate P1(A: bool, B: bool, C: bool) {
A && B ==>
C
}
predicate P2(A: bool, B: bool, C: bool) {
A &&
B
==>
C
}
predicate P3(A: bool, B: bool, C: bool, D: bool) {
A &&
B ==>
C &&
D
}
predicate P4(A: bool, B: bool, C: bool, D: bool) {
A &&
B
==>
C &&
D
}
predicate P5(A: bool, B: bool, C: bool) {
A ==>
&& B
&& C
}
predicate P6(A: bool, B: bool, C: bool) {
A ==>
|| B
|| C
}
predicate Q0(A: bool, B: bool, C: bool, D: bool) {
A &&
B ==> C && // warning (x2): suspicious lack of parentheses (lhs and rhs of ==>)
D
}
predicate Q1(A: bool, B: bool, C: bool, D: bool) {
A &&
B ==> C && // warning: suspicious lack of parentheses (lhs of ==>)
D
}
predicate Q2(A: bool, B: bool, C: bool, D: bool) {
A &&
B ==> (C && // warning: suspicious lack of parentheses (lhs of ==>)
D)
}
predicate Q3(A: bool, B: bool, C: bool, D: bool) {
(A &&
B) ==> (C &&
D)
}
predicate Q4(A: bool, B: bool, C: bool, D: bool) {
&& A
&& B ==> C // warning (x2): suspicious lack of parentheses (lhs and rhs of ==>)
&& D
}
predicate Q4a(A: bool, B: bool, C: bool, D: bool) {
&& A
&& B ==>
C && D
}
predicate Q4b(A: bool, B: bool, C: bool, D: bool) {
&& A
&& B ==>
C &&
D
}
predicate Q4c(A: bool, B: bool, C: bool, D: bool) {
&& A
&& B ==>
&& C
&& D
}
predicate Q4d(A: bool, B: bool, C: bool, D: bool) {
&& A
&& B ==>
&& C
&& D
}
predicate Q5(A: bool, B: bool, C: bool, D: bool) {
&& A
&& B ==> C // warning: suspicious lack of parentheses (lhs of ==>)
&& D
}
predicate Q6(A: bool, B: bool, C: bool, D: bool) {
&& A
&& B ==> && C // warning (x2): suspicious lack of parentheses (lhs and rhs of ==>)
&& D
}
predicate Q7(A: bool, B: bool, C: bool, D: bool) {
A
==> // warning: suspicious lack of parentheses (rhs of ==>)
B && C &&
D
}
predicate Q8(A: bool, B: bool, C: bool, D: bool) {
A
==>
B && C &&
D
}
predicate Q8a(A: bool, B: bool, C: bool, D: bool) {
(A
==>
B && C &&
D
) &&
(B || C)
}
predicate Q8b(A: bool, B: bool, C: bool, D: bool) {
A &&
B
==>
B &&
D
}
predicate Q8c(t: int, x: int, y: int)
{
&& (t == 2 ==> x < y)
&& (|| t == 3
|| t == 2
==>
&& x == 100
&& y == 1000
)
&& (t == 4 ==> || 0 <= x || 0 <= y)
}
predicate Q8d(t: int, x: int, y: int)
{
|| t == 3
|| t == 2
==>
&& x == 100
&& y == 1000
}
predicate Q9(A: bool, B: bool, C: bool) {
A ==> B ==>
C
}
ghost predicate R0(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x :: P(x) ==>
Q(x) &&
R(x)
}
ghost predicate R1(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x :: P(x) && Q(x) ==>
R(x)
}
ghost predicate R2(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x :: P(x) ==> Q(x) ==>
R(x)
}
ghost predicate R3(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x :: P(x) ==>
Q(x) ==>
R(x)
}
ghost predicate R4(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x :: P(x) ==> Q(x) ==>
R(x)
}
ghost predicate R5(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x :: P(x) ==>
forall y :: Q(y) ==>
R(x)
}
ghost predicate R6(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x :: (P(x) ==> Q(x)) && // warning: suspicious lack of parentheses (forall)
R(x)
}
ghost predicate R7(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x ::
(P(x) ==> Q(x)) &&
R(x)
}
ghost predicate R8(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x ::
(P(x) ==> Q(x)) &&
R(x)
}
ghost predicate R9(P: int -> bool, Q: int -> bool, R: int -> bool) {
exists x :: (P(x) ==> Q(x)) && // warning: suspicious lack of parentheses (exists)
R(x)
}
ghost predicate R10(P: int -> bool, Q: int -> bool, R: int -> bool) {
exists x :: P(x) && // warning: suspicious lack of parentheses (exists)
exists y :: Q(y) && // warning: suspicious lack of parentheses (exists)
R(x)
}
lemma Injective()
ensures forall x, y ::
Negate(x) == Negate(y)
==> x == y
{
}
function Negate(x: int): int {
-x
}
predicate Quant0(s: string) {
&& s != []
&& (|| 'a' <= s[0] <= 'z'
|| 'A' <= s[0] <= 'Z')
&& forall i :: 1 <= i < |s| ==>
|| 'a' <= s[i] <= 'z'
|| 'A' <= s[i] <= 'Z'
|| '0' <= s[i] <= '9'
}
predicate Quant1(m: array2<string>, P: int -> bool)
reads m
{
forall i :: 0 <= i < m.Length0 && P(i) ==> forall j :: 0 <= j < m.Length1 ==>
m[i, j] != ""
}
predicate Quant2(s: string) {
forall i :: 0 <= i < |s| ==> if s[i] == '*' then false else
s[i] == 'a' || s[i] == 'b'
}
ghost predicate Quant3(f: int -> int, g: int -> int) {
forall x ::
f(x) == g(x)
}
ghost predicate Quant4(f: int -> int, g: int -> int) {
forall x :: f(x) ==
g(x)
}
ghost predicate Quant5(f: int -> int, g: int -> int) {
forall x :: f(x)
== g(x)
}
function If0(s: string): int {
if |s| == 3 then 2 else 3 + // warning: suspicious lack of parentheses (if-then-else)
(2 * |s|)
}
function If1(s: string): int {
if |s| == 3 then 2 else
3 + (2 * |s|)
}
function If2(s: string): int {
if |s| == 3 then 2 else (3 +
2 * |s|)
}
function If3(s: string): int {
if |s| == 3 then 2 else
3 +
2 * |s|
}
predicate Waterfall(A: bool, B: bool, C: bool, D: bool, E: bool) {
A ==>
B ==>
C ==>
D ==>
E
}
ghost predicate MoreOps0(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x :: P(x) <== Q(x) <== // warning: suspicious lack of parentheses (rhs of <==)
R(x)
}
ghost predicate MoreOps1(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x :: P(x) <== Q(x) <==>
R(x)
}
ghost predicate MoreOps2(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x :: P(x) ==> Q(x) <==>
R(x)
}
ghost predicate MoreOps3(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x :: P(x) ==> Q(x) <==>
R(x) ==>
P(x)
}
ghost predicate MoreOps4(P: int -> bool, Q: int -> bool, R: int -> bool) {
forall x :: P(x) <==> Q(x) && // warning: suspicious lack of parentheses (rhs of <==>)
R(x)
}
lemma IntLemma(x: int)
function StmtExpr0(x: int): int {
if x == 17 then
2
else
IntLemma(x);
3
}
function StmtExpr1(x: int): int {
if x == 17 then // warning: suspicious lack of parentheses (if-then-else)
2
else
IntLemma(x);
3
}
function StmtExpr2(x: int): int {
if x == 17 then
2
else
assert x != 17;
3
}
function StmtExpr3(x: int): int {
if x == 17 then // warning: suspicious lack of parentheses (if-then-else)
2
else
assert x != 17;
3
}
function FunctionWithDefaultParameterValue(x: int, y: int := 100): int
function UseDefaultValues(x: int): int {
if x <= 0 then 0 else
FunctionWithDefaultParameterValue(x - 1)
}
function Square(x: int): int {
x * x
}
predicate Let0(lo: int, hi: int)
requires lo <= hi
{
forall x :: lo <= x < hi ==> var square := Square(x);
0 <= square
}
ghost predicate Let1(P: int -> bool) {
forall x :: 0 <= x && P(x) ==> var bigger :| x <= bigger;
0 <= bigger
}
predicate SomeProperty<X>(x: X)
method Parentheses0(arr: array<int>, P: int -> bool)
{
assert forall i :: 0 <= i < arr.Length ==> arr[i] == old(arr
[i]);
var x := forall i :: 0 <= i < arr.Length ==> SomeProperty(
arr[i]);
var y := forall i :: 0 <= i < arr.Length ==> P(
arr[i]);
assert forall i :: 0 <= i < arr.Length && SomeProperty(i) ==> unchanged(
arr);
var u := if arr.Length == 3 then true else fresh(
arr);
}
method Parentheses1(w: bool, x: int)
{
var a := if w then {} else {x,
x, x};
var b := if w then iset{} else iset{x,
x, x};
var c := if w then [] else [x,
x, x];
var d := if w then multiset{} else multiset{x,
x, x};
var e := if w then map[] else map[x :=
x];
var f := if w then imap[] else imap[
x := x];
}
datatype Record = Record(x: int, y: int)
method Parentheses2(w: bool, x: int, y: int)
{
var a := if w then Record(0,
0
) else Record(x,
y);
var b := if w then
a else a
.
(
x
:=
y
)
;
}
method Parentheses3(w: bool, arr: array<int>, m: array2<int>, i: nat, j: nat)
requires i < j < arr.Length <= m.Length0 <= m.Length1
{
var a := if w then 0 else arr
[
i];
var b := if w then [] else arr
[ i .. ];
var c := if w then [] else arr
[..
i];
var d := if w then [] else arr
[
i..j];
var e := if w then [] else arr
[
..j][i..];
var f := if w then [] else arr // warning: suspicious lack of parentheses (if-then-else)
[..i] + arr[i..];
var g := if w then 0 else m
[i,
j];
var h := if w then arr[..] else arr[..j]
[0 := 25];
}
codatatype Stream = More(head: int, tail: Stream)
method Parentheses4(w: bool, s: Stream, t: Stream)
{
ghost var a := if w then true else s ==#[
12] t;
ghost var b := if w then true else s ==#[ // warning: suspicious lack of parentheses (ternary)
12] t;
ghost var c := if w then true else s // warning: suspicious lack of parentheses (ternary)
!=#[12] t;
ghost var d := if w then true else s
!=#[12] t;
}
/**** revisit the following when the original match'es are being resolved (https://github.com/dafny-lang/dafny/pull/2734)
datatype Color = Red | Blue
method Parentheses5(w: bool, color: Color) {
var a := if w then 5 else match color
case Red => 6
case
Blue => 7;
var b := if w then 5 else match
color
case Red => 6
case
Blue => 7;
var c := if w then 5 else match color { // warning: suspicious lack of parentheses (if-then-else)
case Red => 6
case
Blue => 7} + 10;
var d :=
match color
case Red => 6
case Blue => 7 // warning: suspicious lack of parentheses (case)
+ 10;
var e :=
match color
case Red => 6
+ 10
case Blue => 7;
var f :=
match color {
case Red => 6
case Blue => 7
+ 10 };
var g :=
if w then 5 else match color { // warning: suspicious lack of parentheses (if-then-else)
case Red => 6
case Blue => 7
+ 10 }
+ 20;
}
***/
module MyModule {
function MyFunction(x: int): int
lemma Lemma(x: int)
}
module QualifiedNames {
import MyModule
predicate P(x: int) {
var u := x;
MyModule.MyFunction(x) ==
x
}
predicate Q(x: int) {
var u := x;
MyModule.Lemma(x);
x == MyModule.MyFunction(x)
}
function F(): int
{
var p := 1000;
MyModule.Lemma(p);
p
}
predicate R(x: int) {
var u := x; // warning: suspicious lack of parentheses (let)
MyModule.
Lemma(x);
x ==
MyModule.MyFunction(x)
}
}
module MatchAcrossMultipleLines {
datatype PQ = P(int) | Q(bool)
method M(s: set<PQ>)
requires
(forall pq | pq in s :: match pq {
case P(x) => true
case Q(y) => y == false
})
{
}
datatype YZ = Y | Z
function F(A: bool, B: int, C: YZ): int
requires C != Y
{
if A then B else match C {
case Z => 3
}
}
}
|
dafl_tmp_tmp_r3_8w3y_dafny_examples_dafny0_PrecedenceLinter.dfy
|
412
|
412
|
Dafny program: 412
|
///////////////////
// Binary search
///////////////////
predicate isSorted(a:array<int>)
reads a
{
forall i:nat, j:nat :: i <= j < a.Length ==> a[i] <= a[j]
}
// a[lo] <= a[lo+1] <= ... <= a[hi-2] <= a[hi-1]
method binSearch(a:array<int>, K:int) returns (b:bool)
requires isSorted(a)
ensures b == exists i:nat :: i < a.Length && a[i] == K
{
var lo: nat := 0 ;
var hi: nat := a.Length ;
while (lo < hi)
//invariant forall j:nat :: j < lo ==> a[j] < K
{
var mid: nat := (lo + hi) / 2 ; assert lo <= mid <= hi ;
if (a[mid] < K) { assert a[lo] <= a[mid];
lo := mid + 1 ; assert mid < lo <= hi;
} else if (a[mid] > K) { assert K < a[mid];
hi := mid ; assert lo <= hi == mid;
} else {
return true ; assert a[mid] == K;
}
}
return false ;
}
/* Note: the following definition of isSorted:
predicate isSorted(a:array<int>)
reads a
{
forall i:nat :: i < a.Length - 1 ==> a[i] <= a[i+1]
}
although equivalent to the one above is not enough for Dafny to be able
to prove the invariants for the loop in binSearch.
The given one works because it *explicitly* states that every element
of the input array is smaller than or equal to all later elements.
This fact is implied by the alternative definition of isSorted given
here (which only talks about array elements and their successors).
However, it needs to be derived as an auxiliary lemma first, something
that Dafny is not currently able to do automatically.
*/
|
///////////////////
// Binary search
///////////////////
predicate isSorted(a:array<int>)
reads a
{
forall i:nat, j:nat :: i <= j < a.Length ==> a[i] <= a[j]
}
// a[lo] <= a[lo+1] <= ... <= a[hi-2] <= a[hi-1]
method binSearch(a:array<int>, K:int) returns (b:bool)
requires isSorted(a)
ensures b == exists i:nat :: i < a.Length && a[i] == K
{
var lo: nat := 0 ;
var hi: nat := a.Length ;
while (lo < hi)
decreases hi - lo
invariant 0 <= lo <= hi <= a.Length
//invariant forall j:nat :: j < lo ==> a[j] < K
invariant forall i:nat :: (i < lo || hi <= i < a.Length) ==> a[i] != K
{
var mid: nat := (lo + hi) / 2 ; assert lo <= mid <= hi ;
if (a[mid] < K) { assert a[lo] <= a[mid];
assert a[mid] < K ;
lo := mid + 1 ; assert mid < lo <= hi;
} else if (a[mid] > K) { assert K < a[mid];
hi := mid ; assert lo <= hi == mid;
} else {
return true ; assert a[mid] == K;
}
}
return false ;
}
/* Note: the following definition of isSorted:
predicate isSorted(a:array<int>)
reads a
{
forall i:nat :: i < a.Length - 1 ==> a[i] <= a[i+1]
}
although equivalent to the one above is not enough for Dafny to be able
to prove the invariants for the loop in binSearch.
The given one works because it *explicitly* states that every element
of the input array is smaller than or equal to all later elements.
This fact is implied by the alternative definition of isSorted given
here (which only talks about array elements and their successors).
However, it needs to be derived as an auxiliary lemma first, something
that Dafny is not currently able to do automatically.
*/
|
dafl_tmp_tmp_r3_8w3y_dafny_examples_uiowa_binary-search.dfy
|
413
|
413
|
Dafny program: 413
|
/*
CS:5810 Formal Methods in Software Engineering
Fall 2017
The University of Iowa
Instructor: Cesare Tinelli
Credits: Example adapted from Dafny tutorial
*/
// n = 0, 1, 2, 3, 4, 5, 6, 7, 8, ...
// fib(n) = 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
function fib(n: nat): nat
{
if n == 0 then 0
else if n == 1 then 1
else fib(n - 1) + fib(n - 2)
}
method ComputeFib(n: nat) returns (f: nat)
ensures f == fib(n);
{
if (n == 0)
{ f := 0; }
else {
var i := 1;
var f_2 := 0;
var f_1 := 0;
f := 1;
while (i < n)
{
f_2 := f_1;
f_1 := f;
f := f_1 + f_2;
i := i + 1;
}
}
}
|
/*
CS:5810 Formal Methods in Software Engineering
Fall 2017
The University of Iowa
Instructor: Cesare Tinelli
Credits: Example adapted from Dafny tutorial
*/
// n = 0, 1, 2, 3, 4, 5, 6, 7, 8, ...
// fib(n) = 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
function fib(n: nat): nat
decreases n;
{
if n == 0 then 0
else if n == 1 then 1
else fib(n - 1) + fib(n - 2)
}
method ComputeFib(n: nat) returns (f: nat)
ensures f == fib(n);
{
if (n == 0)
{ f := 0; }
else {
var i := 1;
var f_2 := 0;
var f_1 := 0;
f := 1;
while (i < n)
decreases n - i;
invariant i <= n;
invariant f_1 == fib(i - 1);
invariant f == fib(i);
{
f_2 := f_1;
f_1 := f;
f := f_1 + f_2;
i := i + 1;
}
}
}
|
dafl_tmp_tmp_r3_8w3y_dafny_examples_uiowa_fibonacci.dfy
|
414
|
414
|
Dafny program: 414
|
/*
CS:5810 Formal Methods in Software Engineering
Fall 2017
The University of Iowa
Instructor: Cesare Tinelli
Credits: Example adapted from Dafny tutorial
*/
method Find(a: array<int>, key: int) returns (i: int)
requires a != null;
// if i is non-negative then
ensures 0 <= i ==> (// (1) i is smaller than the length of a
i < a.Length &&
// (2) key is at position i in a
a[i] == key &&
// (3) i is the smallest position where key appears
forall k :: 0 <= k < i ==> a[k] != key
);
// if index is negative then
ensures i < 0 ==>
// a does not contain key
forall k :: 0 <= k < a.Length ==> a[k] != key;
{
i := 0;
while (i < a.Length)
// key is at none of the positions seen so far
{
if (a[i] == key) { return; }
i := i + 1;
}
i := -1;
}
|
/*
CS:5810 Formal Methods in Software Engineering
Fall 2017
The University of Iowa
Instructor: Cesare Tinelli
Credits: Example adapted from Dafny tutorial
*/
method Find(a: array<int>, key: int) returns (i: int)
requires a != null;
// if i is non-negative then
ensures 0 <= i ==> (// (1) i is smaller than the length of a
i < a.Length &&
// (2) key is at position i in a
a[i] == key &&
// (3) i is the smallest position where key appears
forall k :: 0 <= k < i ==> a[k] != key
);
// if index is negative then
ensures i < 0 ==>
// a does not contain key
forall k :: 0 <= k < a.Length ==> a[k] != key;
{
i := 0;
while (i < a.Length)
decreases a.Length - i;
invariant 0 <= i <= a.Length;
// key is at none of the positions seen so far
invariant forall k :: 0 <= k < i ==> a[k] != key;
{
if (a[i] == key) { return; }
i := i + 1;
}
i := -1;
}
|
dafl_tmp_tmp_r3_8w3y_dafny_examples_uiowa_find.dfy
|
415
|
415
|
Dafny program: 415
|
/*
CS:5810 Formal Methods in Software Engineering
Fall 2021
The University of Iowa
Instructor: Cesare Tinelli
Credits: Example adapted from material by Graeme Smith
*/
/////////////////////
// Modifying arrays
/////////////////////
method SetEndPoints(a: array<int>, left: int, right: int)
requires a.Length != 0
modifies a
{
a[0] := left;
a[a.Length - 1] := right;
}
method Aliases(a: array<int>, b: array<int>)
requires a.Length >= b.Length > 100
modifies a
{
a[0] := 10;
var c := a;
if b == a {
b[10] := b[0] + 1; // ok since b == a
}
c[20] := a[14] + 2; // ok since c == a
// b[0] := 4;
}
// Creating new arrays
method NewArray() returns (a: array<int>)
ensures a.Length == 20
ensures fresh(a)
{
a := new int[20];
var b := new int[30];
a[6] := 216;
b[7] := 343;
}
method Caller()
{
var a := NewArray();
a[8] := 512; // allowed only if `a` is fresh
}
// Initializing arrays
method InitArray<T>(a: array<T>, d: T)
modifies a
ensures forall i :: 0 <= i < a.Length ==> a[i] == d
{
var n := 0;
while n != a.Length
{
a[n] := d;
n := n + 1;
}
}
// Referring to prestate values of variables
method UpdateElements(a: array<int>)
requires a.Length == 10
modifies a
ensures old(a[4]) < a[4]
ensures a[6] <= old(a[6])
ensures a[8] == old(a[8])
{
a[4] := a[4] + 3;
a[8] := a[8] + 1;
a[7] := 516;
a[8] := a[8] - 1;
}
// Incrementing arrays
method IncrementArray(a: array<int>)
modifies a
ensures forall i :: 0 <= i < a.Length ==> a[i] == old(a[i]) + 1
{
var n := 0;
while n != a.Length
{
a[n] := a[n] + 1;
n := n + 1;
}
}
// Copying arrays
method CopyArray<T>(a: array<T>, b: array<T>)
requires a.Length == b.Length
modifies b
ensures forall i :: 0 <= i < a.Length ==> b[i] == old(a[i])
{
var n := 0;
while n != a.Length
0 <= i < a.Length ==> a[i] == old(a[i])
{
b[n] := a[n];
n := n + 1;
}
}
|
/*
CS:5810 Formal Methods in Software Engineering
Fall 2021
The University of Iowa
Instructor: Cesare Tinelli
Credits: Example adapted from material by Graeme Smith
*/
/////////////////////
// Modifying arrays
/////////////////////
method SetEndPoints(a: array<int>, left: int, right: int)
requires a.Length != 0
modifies a
{
a[0] := left;
a[a.Length - 1] := right;
}
method Aliases(a: array<int>, b: array<int>)
requires a.Length >= b.Length > 100
modifies a
{
a[0] := 10;
var c := a;
if b == a {
b[10] := b[0] + 1; // ok since b == a
}
c[20] := a[14] + 2; // ok since c == a
// b[0] := 4;
}
// Creating new arrays
method NewArray() returns (a: array<int>)
ensures a.Length == 20
ensures fresh(a)
{
a := new int[20];
var b := new int[30];
a[6] := 216;
b[7] := 343;
}
method Caller()
{
var a := NewArray();
a[8] := 512; // allowed only if `a` is fresh
}
// Initializing arrays
method InitArray<T>(a: array<T>, d: T)
modifies a
ensures forall i :: 0 <= i < a.Length ==> a[i] == d
{
var n := 0;
while n != a.Length
invariant 0 <= n <= a.Length
invariant forall i :: 0 <= i < n ==> a[i] == d
{
a[n] := d;
n := n + 1;
}
}
// Referring to prestate values of variables
method UpdateElements(a: array<int>)
requires a.Length == 10
modifies a
ensures old(a[4]) < a[4]
ensures a[6] <= old(a[6])
ensures a[8] == old(a[8])
{
a[4] := a[4] + 3;
a[8] := a[8] + 1;
a[7] := 516;
a[8] := a[8] - 1;
}
// Incrementing arrays
method IncrementArray(a: array<int>)
modifies a
ensures forall i :: 0 <= i < a.Length ==> a[i] == old(a[i]) + 1
{
var n := 0;
while n != a.Length
invariant 0 <= n <= a.Length
invariant forall i :: 0 <= i < n ==> a[i] == old(a[i]) + 1
invariant forall i :: n <= i < a.Length ==> a[i] == old(a[i])
{
a[n] := a[n] + 1;
n := n + 1;
}
}
// Copying arrays
method CopyArray<T>(a: array<T>, b: array<T>)
requires a.Length == b.Length
modifies b
ensures forall i :: 0 <= i < a.Length ==> b[i] == old(a[i])
{
var n := 0;
while n != a.Length
invariant 0 <= n <= a.Length
invariant forall i :: 0 <= i < n ==> b[i] == old(a[i])
invariant forall i ::
0 <= i < a.Length ==> a[i] == old(a[i])
{
b[n] := a[n];
n := n + 1;
}
}
|
dafl_tmp_tmp_r3_8w3y_dafny_examples_uiowa_modifying-arrays.dfy
|
416
|
416
|
Dafny program: 416
|
/* https://leetcode.com/problems/two-sum/
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
*/
ghost predicate correct_pair(pair: (int, int), nums: seq<int>, target: int) {
var (i, j) := pair;
&& 0 <= i < |nums|
&& 0 <= j < |nums|
&& i != j // "you may not use the same element twice"
&& nums[i] + nums[j] == target
}
// We actually make a weaker pre-condition: there exists at least one solution.
// For verification simplicity, we pretend as if:
// - `seq` were Python list
// - `map` were Python dict
method twoSum(nums: seq<int>, target: int) returns (pair: (int, int))
requires exists i, j :: correct_pair((i, j), nums, target)
ensures correct_pair(pair, nums, target)
{
// use a map whose keys are elements of `nums`, values are indices,
// so that we can look up, in constant time, the "complementary partner" for any index.
var e_to_i := map[];
// iterate though `nums`, building the map on the fly:
for j := 0 to |nums|
// the following states the properties of map `e_to_i`:
// the following says no correct pairs exist among what we've seen so far:
{
var element := nums[j];
var rest := target - element;
if rest in e_to_i { // partner found!
var i := e_to_i[rest];
return (i, j);
} else {
e_to_i := e_to_i[element := j];
}
}
// unreachable here, since there's at least one solution
}
/* Discussions
1. It may be tempting to append `&& e_to_i[nums[i']] == i'` to the invariant (formula A),
but this is wrong, because `nums` may contain redundant elements.
Redundant elements will share the same key in `e_to_i`, the newer overwriting the older.
2. Tip: Generally, we often need invariants when copying data from a container to another.
To specify a set/map, we often need "back and forth" assertions, namely:
(a) What elements are in the map/set (like in formula A)
(b) What do elements in the set/map satisfy (like in formula B)
*/
|
/* https://leetcode.com/problems/two-sum/
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
*/
ghost predicate correct_pair(pair: (int, int), nums: seq<int>, target: int) {
var (i, j) := pair;
&& 0 <= i < |nums|
&& 0 <= j < |nums|
&& i != j // "you may not use the same element twice"
&& nums[i] + nums[j] == target
}
// We actually make a weaker pre-condition: there exists at least one solution.
// For verification simplicity, we pretend as if:
// - `seq` were Python list
// - `map` were Python dict
method twoSum(nums: seq<int>, target: int) returns (pair: (int, int))
requires exists i, j :: correct_pair((i, j), nums, target)
ensures correct_pair(pair, nums, target)
{
// use a map whose keys are elements of `nums`, values are indices,
// so that we can look up, in constant time, the "complementary partner" for any index.
var e_to_i := map[];
// iterate though `nums`, building the map on the fly:
for j := 0 to |nums|
// the following states the properties of map `e_to_i`:
invariant forall i' | 0 <= i' < j :: nums[i'] in e_to_i /* (A) */
invariant forall e | e in e_to_i :: 0 <= e_to_i[e] < j && nums[e_to_i[e]] == e /* (B) */
// the following says no correct pairs exist among what we've seen so far:
invariant forall i', j' | i' < j && j' < j :: !correct_pair((i', j'), nums, target)
{
var element := nums[j];
var rest := target - element;
if rest in e_to_i { // partner found!
var i := e_to_i[rest];
return (i, j);
} else {
e_to_i := e_to_i[element := j];
}
}
// unreachable here, since there's at least one solution
}
/* Discussions
1. It may be tempting to append `&& e_to_i[nums[i']] == i'` to the invariant (formula A),
but this is wrong, because `nums` may contain redundant elements.
Redundant elements will share the same key in `e_to_i`, the newer overwriting the older.
2. Tip: Generally, we often need invariants when copying data from a container to another.
To specify a set/map, we often need "back and forth" assertions, namely:
(a) What elements are in the map/set (like in formula A)
(b) What do elements in the set/map satisfy (like in formula B)
*/
|
dafleet_tmp_tmpa2e4kb9v_0001-0050_0001-two-sum.dfy
|
417
|
417
|
Dafny program: 417
|
/* https://leetcode.com/problems/longest-substring-without-repeating-characters/
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
*/
// a left-inclusive right-exclusive interval:
type interval = iv: (int, int) | iv.0 <= iv.1 witness (0, 0)
ghost function length(iv: interval): int {
iv.1 - iv.0
}
ghost predicate valid_interval(s: string, iv: interval) {
&& (0 <= iv.0 <= iv.1 <= |s|) // interval is in valid range
&& (forall i, j | iv.0 <= i < j < iv.1 :: s[i] != s[j]) // no repeating characters in interval
}
// Below shows an efficient solution using standard "sliding window" technique.
// For verification simplicity, we pretend as if:
// - `set` were Python set (or even better, a fixed-size array -- if the "alphabet" is small)
//
// `best_iv` is for verification purpose, not returned by the real program, thus `ghost`.
method lengthOfLongestSubstring(s: string) returns (n: int, ghost best_iv: interval)
ensures valid_interval(s, best_iv) && length(best_iv) == n /** `best_iv` is valid */
ensures forall iv | valid_interval(s, iv) :: length(iv) <= n /** `best_iv` is longest */
{
var lo, hi := 0, 0; // initialize the interval [lo, hi)
var char_set: set<char> := {}; // `char_set` stores all chars within the interval
n, best_iv := 0, (0, 0); // keep track of the max length and corresponding interval
while hi < |s|
// Below are "mundane" invariants, maintaining the relationships between variables:
// The invariant below reflects the insights behind the "sliding window":
{
if s[hi] !in char_set { // sliding `hi` to lengthen the interval:
char_set := char_set + {s[hi]};
hi := hi + 1;
if hi - lo > n { // update the max length:
n := hi - lo;
best_iv := (lo, hi);
}
} else { // sliding `lo` to shorten the interval:
char_set := char_set - {s[lo]};
lo := lo + 1;
}
}
}
/* Discussions
1. The "sliding window" technique is the most "fancy" part of the solution,
ensuring an O(n) time despite the O(n^2) search space.
The reason why it works lies in the last two invariants: (A) and (B).
Invariant (A) is simply a "partial" guarantee for the longest valid substring in `s[..hi]`,
so once the loop finishes, as `hi == |s|`, this "partial" guarantee becomes "full".
Invariant (B) is crucial: it encodes why we can monotonically increase `lo` as we increase `hi`.
What's the "intuition" behind that? Let me share an "informal proof" below:
Let `sub(i)` be the longest valid substring whose last character is `s[i]`.
Apparently, the final answer will be "the longest among the longests", i.e.
`max(|sub(0)|, |sub(1)|, ..., |sub(|s|-1)|)`.
Now, notice that the "starting position" of `sub(i)` is monotonically increasing regarding `i`!
Otherwise, imagine `sub(i+1)` started at `j` while `sub(i)` started at `j+1` (or even worse),
then `sub(i)` could be made longer (by starting at `j` instead).
This is an obvious contradiction.
Therefore, when we search for the starting position of `sub(i)` (the `lo`) for each `i` (the `hi`),
there's no need to "look back".
2. The solution above can be made more efficient, using "jumping window" instead of "sliding window".
Namely, we use a dict (instead of set) to look up the "position of repetition",
and move `lo` right after that position at once.
You can even "early terminate" (based on `lo`) when all remaining intervals are doomed "no longer",
resulting in even fewer number of loop iterations.
(Time complexity will still be O(n), though.)
The corresponding verification code is shown below:
*/
// For verification simplicity, we pretend as if:
// - `map` were Python dict (or even better, a fixed-size array -- if the "alphabet" is small)
method lengthOfLongestSubstring'(s: string) returns (n: int, ghost best_iv: interval)
ensures valid_interval(s, best_iv) && length(best_iv) == n
ensures forall iv | valid_interval(s, iv) :: length(iv) <= n
{
var lo, hi := 0, 0;
var char_to_index: map<char, int> := map[]; // records the "most recent" index of a given char
n, best_iv := 0, (0, 0);
// Once |s| - lo <= n, there will be no more chance, so early-terminate:
while |s| - lo > n /* (C) */
// while hi < |s| && |s| - lo > n /* (D) */
var i := char_to_index[c]; // the "Dafny way" to denote `char_to_index[c]` as `i` for brevity
0 <= i < hi && s[i] == c
&& (forall i' | i < i' < hi :: s[i'] != c) // note: this line captures that `i` is the "most recent"
{
if s[hi] in char_to_index && char_to_index[s[hi]] >= lo { // has repetition!
lo := char_to_index[s[hi]] + 1;
}
char_to_index := char_to_index[s[hi] := hi];
hi := hi + 1;
if hi - lo > n {
n := hi - lo;
best_iv := (lo, hi);
}
}
}
// Bonus Question:
// "Why can we safely use (C) instead of (D) as the loop condition? Won't `hi` go out-of-bound?"
// Can you figure it out?
|
/* https://leetcode.com/problems/longest-substring-without-repeating-characters/
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
*/
// a left-inclusive right-exclusive interval:
type interval = iv: (int, int) | iv.0 <= iv.1 witness (0, 0)
ghost function length(iv: interval): int {
iv.1 - iv.0
}
ghost predicate valid_interval(s: string, iv: interval) {
&& (0 <= iv.0 <= iv.1 <= |s|) // interval is in valid range
&& (forall i, j | iv.0 <= i < j < iv.1 :: s[i] != s[j]) // no repeating characters in interval
}
// Below shows an efficient solution using standard "sliding window" technique.
// For verification simplicity, we pretend as if:
// - `set` were Python set (or even better, a fixed-size array -- if the "alphabet" is small)
//
// `best_iv` is for verification purpose, not returned by the real program, thus `ghost`.
method lengthOfLongestSubstring(s: string) returns (n: int, ghost best_iv: interval)
ensures valid_interval(s, best_iv) && length(best_iv) == n /** `best_iv` is valid */
ensures forall iv | valid_interval(s, iv) :: length(iv) <= n /** `best_iv` is longest */
{
var lo, hi := 0, 0; // initialize the interval [lo, hi)
var char_set: set<char> := {}; // `char_set` stores all chars within the interval
n, best_iv := 0, (0, 0); // keep track of the max length and corresponding interval
while hi < |s|
decreases |s| - hi, |s| - lo
// Below are "mundane" invariants, maintaining the relationships between variables:
invariant 0 <= lo <= hi <= |s|
invariant valid_interval(s, (lo, hi))
invariant char_set == set i | lo <= i < hi :: s[i]
invariant valid_interval(s, best_iv) && length(best_iv) == n
// The invariant below reflects the insights behind the "sliding window":
invariant forall iv: interval | iv.1 <= hi && valid_interval(s, iv) :: length(iv) <= n /* (A) */
invariant forall iv: interval | iv.1 > hi && iv.0 < lo :: !valid_interval(s, iv) /* (B) */
{
if s[hi] !in char_set { // sliding `hi` to lengthen the interval:
char_set := char_set + {s[hi]};
hi := hi + 1;
if hi - lo > n { // update the max length:
n := hi - lo;
best_iv := (lo, hi);
}
} else { // sliding `lo` to shorten the interval:
char_set := char_set - {s[lo]};
lo := lo + 1;
}
}
}
/* Discussions
1. The "sliding window" technique is the most "fancy" part of the solution,
ensuring an O(n) time despite the O(n^2) search space.
The reason why it works lies in the last two invariants: (A) and (B).
Invariant (A) is simply a "partial" guarantee for the longest valid substring in `s[..hi]`,
so once the loop finishes, as `hi == |s|`, this "partial" guarantee becomes "full".
Invariant (B) is crucial: it encodes why we can monotonically increase `lo` as we increase `hi`.
What's the "intuition" behind that? Let me share an "informal proof" below:
Let `sub(i)` be the longest valid substring whose last character is `s[i]`.
Apparently, the final answer will be "the longest among the longests", i.e.
`max(|sub(0)|, |sub(1)|, ..., |sub(|s|-1)|)`.
Now, notice that the "starting position" of `sub(i)` is monotonically increasing regarding `i`!
Otherwise, imagine `sub(i+1)` started at `j` while `sub(i)` started at `j+1` (or even worse),
then `sub(i)` could be made longer (by starting at `j` instead).
This is an obvious contradiction.
Therefore, when we search for the starting position of `sub(i)` (the `lo`) for each `i` (the `hi`),
there's no need to "look back".
2. The solution above can be made more efficient, using "jumping window" instead of "sliding window".
Namely, we use a dict (instead of set) to look up the "position of repetition",
and move `lo` right after that position at once.
You can even "early terminate" (based on `lo`) when all remaining intervals are doomed "no longer",
resulting in even fewer number of loop iterations.
(Time complexity will still be O(n), though.)
The corresponding verification code is shown below:
*/
// For verification simplicity, we pretend as if:
// - `map` were Python dict (or even better, a fixed-size array -- if the "alphabet" is small)
method lengthOfLongestSubstring'(s: string) returns (n: int, ghost best_iv: interval)
ensures valid_interval(s, best_iv) && length(best_iv) == n
ensures forall iv | valid_interval(s, iv) :: length(iv) <= n
{
var lo, hi := 0, 0;
var char_to_index: map<char, int> := map[]; // records the "most recent" index of a given char
n, best_iv := 0, (0, 0);
// Once |s| - lo <= n, there will be no more chance, so early-terminate:
while |s| - lo > n /* (C) */
// while hi < |s| && |s| - lo > n /* (D) */
decreases |s| - hi
invariant 0 <= lo <= hi <= |s|
invariant valid_interval(s, (lo, hi))
invariant forall i | 0 <= i < hi :: s[i] in char_to_index
invariant forall c | c in char_to_index ::
var i := char_to_index[c]; // the "Dafny way" to denote `char_to_index[c]` as `i` for brevity
0 <= i < hi && s[i] == c
&& (forall i' | i < i' < hi :: s[i'] != c) // note: this line captures that `i` is the "most recent"
invariant valid_interval(s, best_iv) && length(best_iv) == n
invariant forall iv: interval | iv.1 <= hi && valid_interval(s, iv) :: length(iv) <= n
invariant forall iv: interval | iv.1 > hi && iv.0 < lo :: !valid_interval(s, iv)
{
if s[hi] in char_to_index && char_to_index[s[hi]] >= lo { // has repetition!
lo := char_to_index[s[hi]] + 1;
}
char_to_index := char_to_index[s[hi] := hi];
hi := hi + 1;
if hi - lo > n {
n := hi - lo;
best_iv := (lo, hi);
}
}
}
// Bonus Question:
// "Why can we safely use (C) instead of (D) as the loop condition? Won't `hi` go out-of-bound?"
// Can you figure it out?
|
dafleet_tmp_tmpa2e4kb9v_0001-0050_0003-longest-substring-without-repeating-characters.dfy
|
418
|
418
|
Dafny program: 418
|
/* https://leetcode.com/problems/longest-palindromic-substring/
Given a string s, return the longest palindromic substring in s.
Example 1:
Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.
*/
// Specifying the problem: whether `s[i..j]` is palindromic
ghost predicate palindromic(s: string, i: int, j: int)
requires 0 <= i <= j <= |s|
{
j - i < 2 || (s[i] == s[j-1] && palindromic(s, i+1, j-1))
}
// A "common sense" about palindromes:
lemma lemma_palindromic_contains(s: string, lo: int, hi: int, lo': int, hi': int)
requires 0 <= lo <= lo' <= hi' <= hi <= |s|
requires lo + hi == lo' + hi'
requires palindromic(s, lo, hi)
ensures palindromic(s, lo', hi')
{
if lo < lo' {
lemma_palindromic_contains(s, lo + 1, hi - 1, lo', hi');
}
}
// A useful "helper function" that returns the longest palindrome at a given center (i0, j0).
method expand_from_center(s: string, i0: int, j0: int) returns (lo: int, hi: int)
requires 0 <= i0 <= j0 <= |s|
requires palindromic(s, i0, j0)
ensures 0 <= lo <= hi <= |s| && palindromic(s, lo, hi)
ensures forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) // Among all palindromes
&& i + j == i0 + j0 // sharing the same center,
:: j - i <= hi - lo // `s[lo..hi]` is longest.
{
lo, hi := i0, j0;
// we try expanding whenever possible:
while lo - 1 >= 0 && hi < |s| && s[lo - 1] == s[hi]
{
lo, hi := lo - 1, hi + 1;
}
// proves that we cannot go further:
forall i, j | 0 <= i <= j <= |s| && i + j == i0 + j0 && j - i > hi - lo ensures !palindromic(s, i, j) {
if palindromic(s, i, j) { // prove by contradiction:
lemma_palindromic_contains(s, i, j, lo - 1, hi + 1);
}
}
}
// The main algorithm.
// We traverse all centers from left to right, and "expand" each of them, to find the longest palindrome.
method longestPalindrome(s: string) returns (ans: string, lo: int, hi: int)
ensures 0 <= lo <= hi <= |s| && ans == s[lo..hi] // `ans` is indeed a substring in `s`
ensures palindromic(s, lo, hi) // `ans` is palindromic
ensures forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) :: j - i <= hi - lo // `ans` is longest
{
lo, hi := 0, 0;
for k := 0 to |s|
{
var a, b := expand_from_center(s, k, k);
if b - a > hi - lo {
lo, hi := a, b;
}
var c, d := expand_from_center(s, k, k + 1);
if d - c > hi - lo {
lo, hi := c, d;
}
}
return s[lo..hi], lo, hi;
}
/* Discussions
1. Dafny is super bad at slicing (esp. nested slicing).
Do circumvent it whenever possible. It can save you a lot of assertions & lemmas!
For example, instead of `palindromic(s[i..j])`, use the pattern `palindromic(s, i, j)` instead.
I didn't realize this (ref: https://github.com/Nangos/dafleet/commit/3302ddd7642240ff2b2f6a8c51e8becd5c9b6437),
Resulting in a couple of clumsy lemmas.
2. Bonus -- Manacher's algorithm
Our above solution needs `O(|s|^2)` time in the worst case. Can we improve it? Yes.
Manacher's algorithm guarantees an `O(|s|)` time.
To get the intuition, ask yourself: when will it really take `O(|s|^2)` time?
When there are a lot of "nesting and overlapping" palindromes. like in `abcbcbcba` or even `aaaaaa`.
Imagine each palindrome as a "mirror". "Large mirrors" reflect "small mirrors".
Therefore, when we "expand" from some "center", we can "reuse" some information from its "mirrored center".
For example, we move the "center", from left to right, in the string `aiaOaia...`
Here, the char `O` is the "large mirror".
When the current center is the second `i`, it is "mirrored" to the first `i` (which we've calculated for),
so we know the palindrome centered at the second `i` must have at least a length of 3 (`aia`).
So we can expand directly from `aia`, instead of expanding from scratch.
Manacher's algorithm is verified below.
Also, I will verify that "every loop is entered for only `O(|s|)` times",
which "indirectly" proves that the entire algorithm runs in `O(|s|)` time.
*/
// A reference implementation of Manacher's algorithm:
// (Ref. https://en.wikipedia.org/wiki/Longest_palindromic_substring#Manacher's_algorithm) for details...
method {:vcs_split_on_every_assert} longestPalindrome'(s: string) returns (ans: string, lo: int, hi: int)
ensures 0 <= lo <= hi <= |s| && ans == s[lo..hi]
ensures palindromic(s, lo, hi)
ensures forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) :: j - i <= hi - lo
{
var bogus: char :| true; // an arbitrary character
var s' := insert_bogus_chars(s, bogus);
var radii := new int[|s'|];
var center, radius := 0, 0;
// vars below are just for verifying time complexity:
ghost var loop_counter_outer, loop_counter_inner1, loop_counter_inner2 := 0, 0, 0;
while center < |s'|
{
loop_counter_outer := loop_counter_outer + 1;
// Stage 1: Still the normal "expand from center" routine, except `radius` is NOT necessarily zero:
while center - (radius + 1) >= 0 && center + (radius + 1) < |s'|
&& s'[center - (radius + 1)] == s'[center + (radius + 1)]
{
loop_counter_inner1 := loop_counter_inner1 + 1;
radius := radius + 1;
}
lemma_end_of_expansion(s', center, radius);
radii[center] := radius;
var old_center, old_radius := center, radius;
center := center + 1;
radius := 0;
// Stage 2: Quickly infer the maximal radius, using the symmetry of known palindromes.
while center <= old_center + old_radius
{
loop_counter_inner2 := loop_counter_inner2 + 1;
var mirrored_center := old_center - (center - old_center);
var max_mirrored_radius := old_center + old_radius - center;
lemma_mirrored_palindrome(s', old_center, old_radius, mirrored_center, radii[mirrored_center], center);
if radii[mirrored_center] < max_mirrored_radius {
radii[center] := radii[mirrored_center];
center := center + 1;
} else if radii[mirrored_center] > max_mirrored_radius {
radii[center] := max_mirrored_radius;
center := center + 1;
} else {
radius := max_mirrored_radius;
break;
}
}
}
// verify that the worst time complexity (measured by loop iterations) is O(|s'|) == O(|s|):
// wrap up results:
var (c, r) := argmax(radii, 0);
lo, hi := (c - r) / 2, (c + r) / 2; // notice that both ends are bogus chars at position 0, 2, 4, 6, etc.!
lemma_result_transfer(s, s', bogus, radii, c, r, hi, lo);
return s[lo..hi], lo, hi;
}
// Below are helper functions and lemmas we used:
// Inserts bogus characters to the original string (e.g. from `abc` to `|a|b|c|`).
// Note that this is neither efficient nor necessary in reality, but just for the ease of understanding.
function {:opaque} insert_bogus_chars(s: string, bogus: char): (s': string)
ensures |s'| == 2 * |s| + 1
ensures forall i | 0 <= i <= |s| :: s'[i * 2] == bogus
ensures forall i | 0 <= i < |s| :: s'[i * 2 + 1] == s[i]
{
if s == "" then
[bogus]
else
var s'_old := insert_bogus_chars(s[1..], bogus);
var s'_new := [bogus] + [s[0]] + s'_old;
s'_new
}
// Returns (max_index, max_value) of array `a` starting from index `start`.
function {:opaque} argmax(a: array<int>, start: int): (res: (int, int))
reads a
requires 0 <= start < a.Length
ensures start <= res.0 < a.Length && a[res.0] == res.1
ensures forall i | start <= i < a.Length :: a[i] <= res.1
{
if start == a.Length - 1 then
(start, a[start])
else
var (i, v) := argmax(a, start + 1);
if a[start] >= v then (start, a[start]) else (i, v)
}
// Whether an interval at center `c` with a radius `r` is within the boundary of `s'`.
ghost predicate inbound_radius(s': string, c: int, r: int)
{
r >= 0 && 0 <= c-r && c+r < |s'|
}
// Whether `r` is a valid palindromic radius at center `c`.
ghost predicate palindromic_radius(s': string, c: int, r: int)
requires inbound_radius(s', c, r)
{
palindromic(s', c-r, c+r+1)
}
// Whether `r` is the maximal palindromic radius at center `c`.
ghost predicate max_radius(s': string, c: int, r: int)
{
&& inbound_radius(s', c, r)
&& palindromic_radius(s', c, r)
&& (forall r' | r' > r && inbound_radius(s', c, r') :: !palindromic_radius(s', c, r'))
}
// Basically, just "rephrasing" the `lemma_palindromic_contains`,
// talking about center and radius, instead of interval
lemma lemma_palindromic_radius_contains(s': string, c: int, r: int, r': int)
requires inbound_radius(s', c, r) && palindromic_radius(s', c, r)
requires 0 <= r' <= r
ensures inbound_radius(s', c, r') && palindromic_radius(s', c, r')
{
lemma_palindromic_contains(s', c-r, c+r+1, c-r', c+r'+1);
}
// When "expand from center" ends, we've find the max radius:
lemma lemma_end_of_expansion(s': string, c: int, r: int)
requires inbound_radius(s', c, r) && palindromic_radius(s', c, r)
requires inbound_radius(s', c, r + 1) ==> s'[c - (r + 1)] != s'[c + (r + 1)]
ensures max_radius(s', c, r)
{
forall r' | r' > r && inbound_radius(s', c, r') ensures !palindromic_radius(s', c, r') {
if palindromic_radius(s', c, r') { // proof by contradiction
lemma_palindromic_radius_contains(s', c, r', r+1);
}
}
}
// The critical insight behind Manacher's algorithm.
//
// Given the longest palindrome centered at `c` has length `r`, consider the interval from `c-r` to `c+r`.
// Consider a pair of centers in the interval: `c1` (left half) and `c2` (right half), equally away from `c`.
// Then, the length of longest palindromes at `c1` and `c2` are related as follows:
lemma lemma_mirrored_palindrome(s': string, c: int, r: int, c1: int, r1: int, c2: int)
requires max_radius(s', c, r) && max_radius(s', c1, r1)
requires c - r <= c1 < c < c2 <= c + r
requires c2 - c == c - c1
ensures c2 + r1 < c + r ==> max_radius(s', c2, r1)
ensures c2 + r1 > c + r ==> max_radius(s', c2, c + r - c2)
ensures c2 + r1 == c + r ==> palindromic_radius(s', c2, c + r - c2)
{
// proof looks long, but is quite straightforward at each step:
if c2 + r1 < c + r {
for r2 := 0 to r1
{
var r2' := r2 + 1;
}
var r2' := r1 + 1;
lemma_end_of_expansion(s', c2, r1);
} else {
for r2 := 0 to c + r - c2
{
var r2' := r2 + 1;
}
if c2 + r1 > c + r {
var r2' := (c + r - c2) + 1;
if inbound_radius(s', c, r + 1) {
lemma_end_of_expansion(s', c2, c + r - c2);
}
}
}
}
//, where:
ghost function abs(x: int): int {
if x >= 0 then x else -x
}
// Transfering our final result on `s'` to that on `s`:
lemma lemma_result_transfer(s: string, s': string, bogus: char, radii: array<int>, c: int, r: int, hi: int, lo: int)
requires s' == insert_bogus_chars(s, bogus)
requires radii.Length == |s'|
requires forall i | 0 <= i < radii.Length :: max_radius(s', i, radii[i])
requires (c, r) == argmax(radii, 0)
requires lo == (c - r) / 2 && hi == (c + r) / 2
ensures 0 <= lo <= hi <= |s|
ensures palindromic(s, lo, hi)
ensures forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) :: j - i <= hi - lo
{
// For each center, rephrase [maximal radius in `s'`] into [maximal interval in `s`]:
forall k | 0 <= k < radii.Length
ensures max_interval_for_same_center(s, k, (k - radii[k]) / 2, (k + radii[k]) / 2) {
// We need to show `k` and `radii[k]` are either "both odd" or "both even". We prove by contradiction:
if (k + radii[k]) % 2 == 1 {
lemma_palindrome_bogus(s, s', bogus, k, radii[k]);
}
// We then relate `s` and `s'` using their "isomorphism":
var lo, hi := (k - radii[k]) / 2, (k + radii[k]) / 2;
lemma_palindrome_isomorph(s, s', bogus, lo, hi);
forall i, j | 0 <= i <= j <= |s| && i + j == k && j - i > radii[k] ensures !palindromic(s, i, j) {
lemma_palindrome_isomorph(s, s', bogus, i, j);
}
}
// We then iteratively build the last post-condition:
for k := 0 to radii.Length - 1
{
forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) && i + j == k + 1 ensures j - i <= hi - lo {
var k := k + 1;
}
}
}
// The following returns whether `s[lo..hi]` is the longest palindrome s.t. `lo + hi == k`:
ghost predicate max_interval_for_same_center(s: string, k: int, lo: int, hi: int) {
&& 0 <= lo <= hi <= |s|
&& lo + hi == k
&& palindromic(s, lo, hi)
&& (forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) && i + j == k :: j - i <= hi - lo)
}
// Establishes the "palindromic isomorphism" between `s` and `s'`.
lemma lemma_palindrome_isomorph(s: string, s': string, bogus: char, lo: int, hi: int)
requires s' == insert_bogus_chars(s, bogus)
requires 0 <= lo <= hi <= |s|
ensures palindromic(s, lo, hi) <==> palindromic_radius(s', lo + hi, hi - lo)
{
if palindromic(s, lo, hi) { // ==>
for r := 0 to hi - lo
{
if (lo + hi - r) % 2 == 1 {
lemma_palindrome_bogus(s, s', bogus, lo + hi, r);
} else {
var i', j' := lo + hi - (r + 1), lo + hi + (r + 1);
var i, j := i' / 2, j' / 2;
// Notice that `s'[i'] == s[i] && s'[j'] == s[j]`; apparently Dafny does
}
}
}
if palindromic_radius(s', lo + hi, hi - lo) { // <==
var lo', hi' := lo, hi;
while lo' + 1 <= hi' - 1
{
lo', hi' := lo' + 1, hi' - 1;
}
}
}
// Implies that whenever `c + r` is odd, the corresponding palindrome can be "lengthened for free"
// because its both ends are the bogus char.
lemma lemma_palindrome_bogus(s: string, s': string, bogus: char, c: int, r: int)
requires s' == insert_bogus_chars(s, bogus)
requires inbound_radius(s', c, r) && palindromic_radius(s', c, r)
requires (c + r) % 2 == 1
ensures inbound_radius(s', c, r + 1) && palindromic_radius(s', c, r + 1)
{
var left, right := c - (r + 1), c + (r + 1);
}
|
/* https://leetcode.com/problems/longest-palindromic-substring/
Given a string s, return the longest palindromic substring in s.
Example 1:
Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.
*/
// Specifying the problem: whether `s[i..j]` is palindromic
ghost predicate palindromic(s: string, i: int, j: int)
requires 0 <= i <= j <= |s|
decreases j - i
{
j - i < 2 || (s[i] == s[j-1] && palindromic(s, i+1, j-1))
}
// A "common sense" about palindromes:
lemma lemma_palindromic_contains(s: string, lo: int, hi: int, lo': int, hi': int)
requires 0 <= lo <= lo' <= hi' <= hi <= |s|
requires lo + hi == lo' + hi'
requires palindromic(s, lo, hi)
ensures palindromic(s, lo', hi')
decreases lo' - lo
{
if lo < lo' {
lemma_palindromic_contains(s, lo + 1, hi - 1, lo', hi');
}
}
// A useful "helper function" that returns the longest palindrome at a given center (i0, j0).
method expand_from_center(s: string, i0: int, j0: int) returns (lo: int, hi: int)
requires 0 <= i0 <= j0 <= |s|
requires palindromic(s, i0, j0)
ensures 0 <= lo <= hi <= |s| && palindromic(s, lo, hi)
ensures forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) // Among all palindromes
&& i + j == i0 + j0 // sharing the same center,
:: j - i <= hi - lo // `s[lo..hi]` is longest.
{
lo, hi := i0, j0;
// we try expanding whenever possible:
while lo - 1 >= 0 && hi < |s| && s[lo - 1] == s[hi]
invariant 0 <= lo <= hi <= |s| && lo + hi == i0 + j0
invariant palindromic(s, lo, hi)
{
lo, hi := lo - 1, hi + 1;
}
// proves that we cannot go further:
forall i, j | 0 <= i <= j <= |s| && i + j == i0 + j0 && j - i > hi - lo ensures !palindromic(s, i, j) {
if palindromic(s, i, j) { // prove by contradiction:
lemma_palindromic_contains(s, i, j, lo - 1, hi + 1);
}
}
}
// The main algorithm.
// We traverse all centers from left to right, and "expand" each of them, to find the longest palindrome.
method longestPalindrome(s: string) returns (ans: string, lo: int, hi: int)
ensures 0 <= lo <= hi <= |s| && ans == s[lo..hi] // `ans` is indeed a substring in `s`
ensures palindromic(s, lo, hi) // `ans` is palindromic
ensures forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) :: j - i <= hi - lo // `ans` is longest
{
lo, hi := 0, 0;
for k := 0 to |s|
invariant 0 <= lo <= hi <= |s|
invariant palindromic(s, lo, hi)
invariant forall i, j | 0 <= i <= j <= |s| && i + j < 2 * k && palindromic(s, i, j) :: j - i <= hi - lo
{
var a, b := expand_from_center(s, k, k);
if b - a > hi - lo {
lo, hi := a, b;
}
var c, d := expand_from_center(s, k, k + 1);
if d - c > hi - lo {
lo, hi := c, d;
}
}
return s[lo..hi], lo, hi;
}
/* Discussions
1. Dafny is super bad at slicing (esp. nested slicing).
Do circumvent it whenever possible. It can save you a lot of assertions & lemmas!
For example, instead of `palindromic(s[i..j])`, use the pattern `palindromic(s, i, j)` instead.
I didn't realize this (ref: https://github.com/Nangos/dafleet/commit/3302ddd7642240ff2b2f6a8c51e8becd5c9b6437),
Resulting in a couple of clumsy lemmas.
2. Bonus -- Manacher's algorithm
Our above solution needs `O(|s|^2)` time in the worst case. Can we improve it? Yes.
Manacher's algorithm guarantees an `O(|s|)` time.
To get the intuition, ask yourself: when will it really take `O(|s|^2)` time?
When there are a lot of "nesting and overlapping" palindromes. like in `abcbcbcba` or even `aaaaaa`.
Imagine each palindrome as a "mirror". "Large mirrors" reflect "small mirrors".
Therefore, when we "expand" from some "center", we can "reuse" some information from its "mirrored center".
For example, we move the "center", from left to right, in the string `aiaOaia...`
Here, the char `O` is the "large mirror".
When the current center is the second `i`, it is "mirrored" to the first `i` (which we've calculated for),
so we know the palindrome centered at the second `i` must have at least a length of 3 (`aia`).
So we can expand directly from `aia`, instead of expanding from scratch.
Manacher's algorithm is verified below.
Also, I will verify that "every loop is entered for only `O(|s|)` times",
which "indirectly" proves that the entire algorithm runs in `O(|s|)` time.
*/
// A reference implementation of Manacher's algorithm:
// (Ref. https://en.wikipedia.org/wiki/Longest_palindromic_substring#Manacher's_algorithm) for details...
method {:vcs_split_on_every_assert} longestPalindrome'(s: string) returns (ans: string, lo: int, hi: int)
ensures 0 <= lo <= hi <= |s| && ans == s[lo..hi]
ensures palindromic(s, lo, hi)
ensures forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) :: j - i <= hi - lo
{
var bogus: char :| true; // an arbitrary character
var s' := insert_bogus_chars(s, bogus);
var radii := new int[|s'|];
var center, radius := 0, 0;
// vars below are just for verifying time complexity:
ghost var loop_counter_outer, loop_counter_inner1, loop_counter_inner2 := 0, 0, 0;
while center < |s'|
invariant 0 <= center <= |s'|
invariant forall c | 0 <= c < center :: max_radius(s', c, radii[c])
invariant center < |s'| ==> inbound_radius(s', center, radius) && palindromic_radius(s', center, radius)
invariant center == |s'| ==> radius == 0
invariant loop_counter_outer <= center
invariant loop_counter_inner1 <= center + radius && loop_counter_inner2 <= center
{
loop_counter_outer := loop_counter_outer + 1;
// Stage 1: Still the normal "expand from center" routine, except `radius` is NOT necessarily zero:
while center - (radius + 1) >= 0 && center + (radius + 1) < |s'|
&& s'[center - (radius + 1)] == s'[center + (radius + 1)]
decreases center - radius
invariant inbound_radius(s', center, radius) && palindromic_radius(s', center, radius)
invariant loop_counter_inner1 <= center + radius
{
loop_counter_inner1 := loop_counter_inner1 + 1;
radius := radius + 1;
}
lemma_end_of_expansion(s', center, radius);
radii[center] := radius;
var old_center, old_radius := center, radius;
center := center + 1;
radius := 0;
// Stage 2: Quickly infer the maximal radius, using the symmetry of known palindromes.
while center <= old_center + old_radius
invariant 0 <= center <= |s'|
invariant forall c | 0 <= c < center :: max_radius(s', c, radii[c])
invariant center < |s'| ==> inbound_radius(s', center, radius) && palindromic_radius(s', center, radius)
invariant loop_counter_inner2 <= center - 1
{
loop_counter_inner2 := loop_counter_inner2 + 1;
var mirrored_center := old_center - (center - old_center);
var max_mirrored_radius := old_center + old_radius - center;
lemma_mirrored_palindrome(s', old_center, old_radius, mirrored_center, radii[mirrored_center], center);
if radii[mirrored_center] < max_mirrored_radius {
radii[center] := radii[mirrored_center];
center := center + 1;
} else if radii[mirrored_center] > max_mirrored_radius {
radii[center] := max_mirrored_radius;
center := center + 1;
} else {
radius := max_mirrored_radius;
break;
}
}
}
// verify that the worst time complexity (measured by loop iterations) is O(|s'|) == O(|s|):
assert |s'| == 2 * |s| + 1;
assert loop_counter_outer <= |s'|;
assert loop_counter_inner1 <= |s'|;
assert loop_counter_inner2 <= |s'|;
// wrap up results:
var (c, r) := argmax(radii, 0);
lo, hi := (c - r) / 2, (c + r) / 2; // notice that both ends are bogus chars at position 0, 2, 4, 6, etc.!
lemma_result_transfer(s, s', bogus, radii, c, r, hi, lo);
return s[lo..hi], lo, hi;
}
// Below are helper functions and lemmas we used:
// Inserts bogus characters to the original string (e.g. from `abc` to `|a|b|c|`).
// Note that this is neither efficient nor necessary in reality, but just for the ease of understanding.
function {:opaque} insert_bogus_chars(s: string, bogus: char): (s': string)
ensures |s'| == 2 * |s| + 1
ensures forall i | 0 <= i <= |s| :: s'[i * 2] == bogus
ensures forall i | 0 <= i < |s| :: s'[i * 2 + 1] == s[i]
{
if s == "" then
[bogus]
else
var s'_old := insert_bogus_chars(s[1..], bogus);
var s'_new := [bogus] + [s[0]] + s'_old;
assert forall i | 1 <= i <= |s| :: s'_new[i * 2] == s'_old[(i-1) * 2];
s'_new
}
// Returns (max_index, max_value) of array `a` starting from index `start`.
function {:opaque} argmax(a: array<int>, start: int): (res: (int, int))
reads a
requires 0 <= start < a.Length
ensures start <= res.0 < a.Length && a[res.0] == res.1
ensures forall i | start <= i < a.Length :: a[i] <= res.1
decreases a.Length - start
{
if start == a.Length - 1 then
(start, a[start])
else
var (i, v) := argmax(a, start + 1);
if a[start] >= v then (start, a[start]) else (i, v)
}
// Whether an interval at center `c` with a radius `r` is within the boundary of `s'`.
ghost predicate inbound_radius(s': string, c: int, r: int)
{
r >= 0 && 0 <= c-r && c+r < |s'|
}
// Whether `r` is a valid palindromic radius at center `c`.
ghost predicate palindromic_radius(s': string, c: int, r: int)
requires inbound_radius(s', c, r)
{
palindromic(s', c-r, c+r+1)
}
// Whether `r` is the maximal palindromic radius at center `c`.
ghost predicate max_radius(s': string, c: int, r: int)
{
&& inbound_radius(s', c, r)
&& palindromic_radius(s', c, r)
&& (forall r' | r' > r && inbound_radius(s', c, r') :: !palindromic_radius(s', c, r'))
}
// Basically, just "rephrasing" the `lemma_palindromic_contains`,
// talking about center and radius, instead of interval
lemma lemma_palindromic_radius_contains(s': string, c: int, r: int, r': int)
requires inbound_radius(s', c, r) && palindromic_radius(s', c, r)
requires 0 <= r' <= r
ensures inbound_radius(s', c, r') && palindromic_radius(s', c, r')
{
lemma_palindromic_contains(s', c-r, c+r+1, c-r', c+r'+1);
}
// When "expand from center" ends, we've find the max radius:
lemma lemma_end_of_expansion(s': string, c: int, r: int)
requires inbound_radius(s', c, r) && palindromic_radius(s', c, r)
requires inbound_radius(s', c, r + 1) ==> s'[c - (r + 1)] != s'[c + (r + 1)]
ensures max_radius(s', c, r)
{
forall r' | r' > r && inbound_radius(s', c, r') ensures !palindromic_radius(s', c, r') {
if palindromic_radius(s', c, r') { // proof by contradiction
lemma_palindromic_radius_contains(s', c, r', r+1);
}
}
}
// The critical insight behind Manacher's algorithm.
//
// Given the longest palindrome centered at `c` has length `r`, consider the interval from `c-r` to `c+r`.
// Consider a pair of centers in the interval: `c1` (left half) and `c2` (right half), equally away from `c`.
// Then, the length of longest palindromes at `c1` and `c2` are related as follows:
lemma lemma_mirrored_palindrome(s': string, c: int, r: int, c1: int, r1: int, c2: int)
requires max_radius(s', c, r) && max_radius(s', c1, r1)
requires c - r <= c1 < c < c2 <= c + r
requires c2 - c == c - c1
ensures c2 + r1 < c + r ==> max_radius(s', c2, r1)
ensures c2 + r1 > c + r ==> max_radius(s', c2, c + r - c2)
ensures c2 + r1 == c + r ==> palindromic_radius(s', c2, c + r - c2)
{
// proof looks long, but is quite straightforward at each step:
if c2 + r1 < c + r {
for r2 := 0 to r1
invariant palindromic_radius(s', c2, r2)
{
var r2' := r2 + 1;
assert s'[c1+r2'] == s'[c2-r2'] by { lemma_palindromic_radius_contains(s', c, r, abs(c - c1 - r2')); }
assert s'[c1-r2'] == s'[c2+r2'] by { lemma_palindromic_radius_contains(s', c, r, abs(c - c1 + r2')); }
assert s'[c1-r2'] == s'[c1+r2'] by { lemma_palindromic_radius_contains(s', c1, r1, r2'); }
}
var r2' := r1 + 1;
assert s'[c1+r2'] == s'[c2-r2'] by { lemma_palindromic_radius_contains(s', c, r, abs(c - c1 - r2')); }
assert s'[c1-r2'] == s'[c2+r2'] by { lemma_palindromic_radius_contains(s', c, r, abs(c - c1 + r2')); }
assert s'[c1-r2'] != s'[c1+r2'] by { assert !palindromic_radius(s', c1, r2'); }
lemma_end_of_expansion(s', c2, r1);
} else {
for r2 := 0 to c + r - c2
invariant palindromic_radius(s', c2, r2)
{
var r2' := r2 + 1;
assert s'[c1+r2'] == s'[c2-r2'] by { lemma_palindromic_radius_contains(s', c, r, abs(c - c1 - r2')); }
assert s'[c1-r2'] == s'[c2+r2'] by { lemma_palindromic_radius_contains(s', c, r, abs(c - c1 + r2')); }
assert s'[c1-r2'] == s'[c1+r2'] by { lemma_palindromic_radius_contains(s', c1, r1, r2'); }
}
if c2 + r1 > c + r {
var r2' := (c + r - c2) + 1;
if inbound_radius(s', c, r + 1) {
assert s'[c1+r2'] == s'[c2-r2'] by { lemma_palindromic_radius_contains(s', c, r, abs(c - c1 - r2')); }
assert s'[c1-r2'] != s'[c2+r2'] by { assert !palindromic_radius(s', c, r + 1); }
assert s'[c1-r2'] == s'[c1+r2'] by { lemma_palindromic_radius_contains(s', c1, r1, r2'); }
lemma_end_of_expansion(s', c2, c + r - c2);
}
}
}
}
//, where:
ghost function abs(x: int): int {
if x >= 0 then x else -x
}
// Transfering our final result on `s'` to that on `s`:
lemma lemma_result_transfer(s: string, s': string, bogus: char, radii: array<int>, c: int, r: int, hi: int, lo: int)
requires s' == insert_bogus_chars(s, bogus)
requires radii.Length == |s'|
requires forall i | 0 <= i < radii.Length :: max_radius(s', i, radii[i])
requires (c, r) == argmax(radii, 0)
requires lo == (c - r) / 2 && hi == (c + r) / 2
ensures 0 <= lo <= hi <= |s|
ensures palindromic(s, lo, hi)
ensures forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) :: j - i <= hi - lo
{
// For each center, rephrase [maximal radius in `s'`] into [maximal interval in `s`]:
forall k | 0 <= k < radii.Length
ensures max_interval_for_same_center(s, k, (k - radii[k]) / 2, (k + radii[k]) / 2) {
// We need to show `k` and `radii[k]` are either "both odd" or "both even". We prove by contradiction:
if (k + radii[k]) % 2 == 1 {
lemma_palindrome_bogus(s, s', bogus, k, radii[k]);
}
// We then relate `s` and `s'` using their "isomorphism":
var lo, hi := (k - radii[k]) / 2, (k + radii[k]) / 2;
lemma_palindrome_isomorph(s, s', bogus, lo, hi);
forall i, j | 0 <= i <= j <= |s| && i + j == k && j - i > radii[k] ensures !palindromic(s, i, j) {
lemma_palindrome_isomorph(s, s', bogus, i, j);
}
}
// We then iteratively build the last post-condition:
for k := 0 to radii.Length - 1
invariant forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) && i + j <= k :: j - i <= hi - lo
{
forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) && i + j == k + 1 ensures j - i <= hi - lo {
var k := k + 1;
assert max_interval_for_same_center(s, k, (k - radii[k]) / 2, (k + radii[k]) / 2);
}
}
}
// The following returns whether `s[lo..hi]` is the longest palindrome s.t. `lo + hi == k`:
ghost predicate max_interval_for_same_center(s: string, k: int, lo: int, hi: int) {
&& 0 <= lo <= hi <= |s|
&& lo + hi == k
&& palindromic(s, lo, hi)
&& (forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) && i + j == k :: j - i <= hi - lo)
}
// Establishes the "palindromic isomorphism" between `s` and `s'`.
lemma lemma_palindrome_isomorph(s: string, s': string, bogus: char, lo: int, hi: int)
requires s' == insert_bogus_chars(s, bogus)
requires 0 <= lo <= hi <= |s|
ensures palindromic(s, lo, hi) <==> palindromic_radius(s', lo + hi, hi - lo)
{
if palindromic(s, lo, hi) { // ==>
for r := 0 to hi - lo
invariant palindromic_radius(s', lo + hi, r)
{
if (lo + hi - r) % 2 == 1 {
lemma_palindrome_bogus(s, s', bogus, lo + hi, r);
} else {
var i', j' := lo + hi - (r + 1), lo + hi + (r + 1);
var i, j := i' / 2, j' / 2;
assert s[i] == s[j] by { lemma_palindromic_contains(s, lo, hi, i, j + 1); }
// Notice that `s'[i'] == s[i] && s'[j'] == s[j]`; apparently Dafny does
}
}
}
if palindromic_radius(s', lo + hi, hi - lo) { // <==
var lo', hi' := lo, hi;
while lo' + 1 <= hi' - 1
invariant lo <= lo' <= hi' <= hi
invariant lo' + hi' == lo + hi
invariant palindromic_radius(s', lo + hi, hi' - lo')
invariant palindromic(s, lo', hi') ==> palindromic(s, lo, hi) // "reversed construction"
{
assert palindromic_radius(s', lo + hi, hi' - lo' - 1); // ignore bogus chars and move on
lo', hi' := lo' + 1, hi' - 1;
}
}
}
// Implies that whenever `c + r` is odd, the corresponding palindrome can be "lengthened for free"
// because its both ends are the bogus char.
lemma lemma_palindrome_bogus(s: string, s': string, bogus: char, c: int, r: int)
requires s' == insert_bogus_chars(s, bogus)
requires inbound_radius(s', c, r) && palindromic_radius(s', c, r)
requires (c + r) % 2 == 1
ensures inbound_radius(s', c, r + 1) && palindromic_radius(s', c, r + 1)
{
var left, right := c - (r + 1), c + (r + 1);
assert left == (left / 2) * 2;
assert right == (right / 2) * 2;
assert s'[left] == s'[right] == bogus;
}
|
dafleet_tmp_tmpa2e4kb9v_0001-0050_0005-longest-palindromic-substring.dfy
|
419
|
419
|
Dafny program: 419
|
module Split {
function splitHelper(s: string, separator: string, index: nat, sindex: nat, results: seq<string>): seq<seq<char>>
requires index <= |s|
requires sindex <= |s|
requires sindex <= index
// requires forall ss: string :: ss in results ==> NotContains(ss,separator)
// ensures forall ss :: ss in splitHelper(s, separator, index, sindex, results) ==> NotContains(ss, separator)
{
if index >= |s| then results + [s[sindex..index]]
else if |separator| == 0 && index == |s|-1 then splitHelper(s, separator, index+1, index, results)
else if |separator| == 0 then
splitHelper(s, separator, index+1, index+1, results + [s[sindex..(index+1)]])
else if index+|separator| > |s| then splitHelper(s, separator, |s|, sindex, results)
else if s[index..index+|separator|] == separator then splitHelper(s, separator, index+|separator|, index+|separator|, results + [s[sindex..index]])
else splitHelper(s, separator, index+1, sindex, results)
}
function split(s: string, separator: string): seq<string>
ensures split(s, separator) == splitHelper(s, separator, 0,0, [])
{
splitHelper(s, separator, 0, 0, [])
}
predicate Contains(haystack: string, needle: string)
// ensures !NotContainsThree(haystack, needle)
ensures Contains(haystack, needle) <==> exists k :: 0 <= k <= |haystack| && needle <= haystack[k..]
ensures Contains(haystack, needle) <==> exists i :: 0 <= i <= |haystack| && (needle <= haystack[i..])
ensures !Contains(haystack, needle) <==> forall i :: 0 <= i <= |haystack| ==> !(needle <= haystack[i..])
{
if needle <= haystack then
true
else if |haystack| > 0 then
Contains(haystack[1..], needle)
else
false
}
function splitOnBreak(s: string): seq<string> {
if Contains(s, "\r\n") then split(s,"\r\n") else split(s,"\n")
}
function splitOnDoubleBreak(s: string): seq<string> {
if Contains(s, "\r\n") then split(s,"\r\n\r\n") else split(s,"\n\n")
}
}
|
module Split {
function splitHelper(s: string, separator: string, index: nat, sindex: nat, results: seq<string>): seq<seq<char>>
requires index <= |s|
requires sindex <= |s|
requires sindex <= index
// requires forall ss: string :: ss in results ==> NotContains(ss,separator)
// ensures forall ss :: ss in splitHelper(s, separator, index, sindex, results) ==> NotContains(ss, separator)
decreases |s| - index
{
if index >= |s| then results + [s[sindex..index]]
else if |separator| == 0 && index == |s|-1 then splitHelper(s, separator, index+1, index, results)
else if |separator| == 0 then
assert separator == [];
assert s[sindex..index+1] != [];
splitHelper(s, separator, index+1, index+1, results + [s[sindex..(index+1)]])
else if index+|separator| > |s| then splitHelper(s, separator, |s|, sindex, results)
else if s[index..index+|separator|] == separator then splitHelper(s, separator, index+|separator|, index+|separator|, results + [s[sindex..index]])
else splitHelper(s, separator, index+1, sindex, results)
}
function split(s: string, separator: string): seq<string>
ensures split(s, separator) == splitHelper(s, separator, 0,0, [])
{
splitHelper(s, separator, 0, 0, [])
}
predicate Contains(haystack: string, needle: string)
// ensures !NotContainsThree(haystack, needle)
ensures Contains(haystack, needle) <==> exists k :: 0 <= k <= |haystack| && needle <= haystack[k..]
ensures Contains(haystack, needle) <==> exists i :: 0 <= i <= |haystack| && (needle <= haystack[i..])
ensures !Contains(haystack, needle) <==> forall i :: 0 <= i <= |haystack| ==> !(needle <= haystack[i..])
{
if needle <= haystack then
assert haystack[0..] == haystack;
true
else if |haystack| > 0 then
assert forall i :: 1 <= i <= |haystack| ==> haystack[i..] == haystack[1..][(i-1)..];
Contains(haystack[1..], needle)
else
false
}
function splitOnBreak(s: string): seq<string> {
if Contains(s, "\r\n") then split(s,"\r\n") else split(s,"\n")
}
function splitOnDoubleBreak(s: string): seq<string> {
if Contains(s, "\r\n") then split(s,"\r\n\r\n") else split(s,"\n\n")
}
}
|
dafny-aoc-2019_tmp_tmpj6suy_rv_parser_split.dfy
|
420
|
420
|
Dafny program: 420
|
// program verifies
predicate sortedbad(s: string)
{
// no b's after non-b's
forall i, j :: 0 <= i <= j < |s| && s[i] == 'b' && s[j] != 'b' ==> i < j &&
// only non-d's before d's
forall i, j :: 0 <= i <= j < |s| && s[i] != 'd' && s[j] == 'd' ==> i < j
}
method BadSort(a: string) returns (b: string)
requires forall i :: 0<=i<|a| ==> a[i] in {'b', 'a', 'd'}
ensures sortedbad(b)
ensures multiset(b[..]) == multiset(a[..])
{
b := a;
var next:int := 0;
var aPointer:int := 0;
var dPointer:int := |b|;
while (next != dPointer)
{
if(b[next] == 'a'){
next := next + 1;
}
else if(b[next] == 'b'){
b := b[next := b[aPointer]][aPointer := b[next]];
next := next + 1;
aPointer := aPointer + 1;
}
else{
dPointer := dPointer - 1;
b := b[next := b[dPointer]][dPointer := b[next]];
}
}
}
|
// program verifies
predicate sortedbad(s: string)
{
// no b's after non-b's
forall i, j :: 0 <= i <= j < |s| && s[i] == 'b' && s[j] != 'b' ==> i < j &&
// only non-d's before d's
forall i, j :: 0 <= i <= j < |s| && s[i] != 'd' && s[j] == 'd' ==> i < j
}
method BadSort(a: string) returns (b: string)
requires forall i :: 0<=i<|a| ==> a[i] in {'b', 'a', 'd'}
ensures sortedbad(b)
ensures multiset(b[..]) == multiset(a[..])
{
b := a;
var next:int := 0;
var aPointer:int := 0;
var dPointer:int := |b|;
while (next != dPointer)
decreases if next <= dPointer then dPointer - next else next - dPointer
invariant 0 <= aPointer <= next <= dPointer <= |b|
invariant forall i :: 0 <= i < aPointer ==> b[i] == 'b'
invariant forall i :: aPointer <= i < next ==> b[i] == 'a'
invariant forall i :: dPointer <= i < |b| ==> b[i] == 'd'
invariant forall i :: 0<=i<|b| ==> b[i] in {'b', 'a', 'd'}
invariant sortedbad(b)
invariant multiset(b[..]) == multiset(a[..])
{
if(b[next] == 'a'){
next := next + 1;
}
else if(b[next] == 'b'){
b := b[next := b[aPointer]][aPointer := b[next]];
next := next + 1;
aPointer := aPointer + 1;
}
else{
dPointer := dPointer - 1;
b := b[next := b[dPointer]][dPointer := b[next]];
}
}
}
|
dafny-duck_tmp_tmplawbgxjo_ex3.dfy
|
421
|
421
|
Dafny program: 421
|
// program verifies
function expo(x:int, n:nat): int
{
if n == 0 then 1
else x * expo(x, n-1)
}
lemma {:induction false} Expon23(n: nat)
requires n >= 0
ensures ((expo(2,3*n) - expo(3,n)) % (2+3)) == 0
{
// base case
if (n == 0) {
}
else if (n == 1) {
}
else {
Expon23(n-1); // lemma proved for case n-1
// training dafny up
// training dafny up
// some more training
// not really needed
}
}
|
// program verifies
function expo(x:int, n:nat): int
{
if n == 0 then 1
else x * expo(x, n-1)
}
lemma {:induction false} Expon23(n: nat)
requires n >= 0
ensures ((expo(2,3*n) - expo(3,n)) % (2+3)) == 0
{
// base case
if (n == 0) {
assert (expo(2,3*0)-expo(3,0)) % 5 == 0;
}
else if (n == 1) {
assert (expo(2,3*1)-expo(3,1)) % 5 == 0;
}
else {
Expon23(n-1); // lemma proved for case n-1
assert (expo(2,3*(n-1)) - expo(3,n-1)) % 5 == 0;
// training dafny up
assert expo(2,3*n) == expo(2,3*(n-1)+2)*expo(2,1);
assert expo(2,3*n) == expo(2,3*(n-1)+3);
// training dafny up
assert expo(2,3*(n-1)+3) == expo(2,3*(n-1)+1)*expo(2,2);
assert expo(2,3*(n-1)+3) == expo(2,3*(n-1))*expo(2,3);
assert expo(3,(n-1)+1) == expo(3,(n-1))*expo(3,1);
// some more training
assert expo(3,n) == expo(3,n-1)*expo(3,1);
assert expo(3,n) == expo(3,(n-1)+1);
// not really needed
assert expo(2,3*(n-1))*expo(2,3) == expo(2,3*(n-1))*8;
assert expo(3,(n-1))*expo(3,1) == expo(3,(n-1))*3;
assert expo(2,3*n) - expo(3,n) == expo(2,3*(n-1)+3) - expo(3,(n-1)+1);
assert (expo(2,3*n) - expo(3,n)) % 5 == (expo(2,3*(n-1)+3) - expo(3,(n-1)+1)) % 5; // rewriting it
assert (expo(2,3*n) - expo(3,n)) % 5 == (expo(2,3*(n-1))*expo(2,3) - expo(3,(n-1))*expo(3,1)) % 5;
assert (expo(2,3*n) - expo(3,n)) % 5 == (expo(2,3*(n-1))*8 - expo(3,(n-1))*3) % 5;
assert (expo(2,3*n) - expo(3,n)) % 5 == (expo(2,3*(n-1))*8 - expo(3,n-1)*8 + expo(3,n-1)*8 - expo(3,(n-1))*3) % 5; // imporant step to refactorize RHS
assert (expo(2,3*n) - expo(3,n)) % 5 == (8*(expo(2,3*(n-1)) - expo(3,n-1)) + expo(3,n-1)*(8-3)) % 5;
assert (expo(2,3*n) - expo(3,n)) % 5 == (8*(expo(2,3*(n-1)) - expo(3,n-1)) + expo(3,n-1)*(5)) % 5;
assert (expo(2,3*n) - expo(3,n)) % 5 == ((8*(expo(2,3*(n-1)) - expo(3,n-1))) % 5 + (expo(3,n-1)*(5)) % 5) % 5;
assert (expo(2,3*n) - expo(3,n)) % 5 == 0;
}
}
|
dafny-duck_tmp_tmplawbgxjo_ex5.dfy
|
422
|
422
|
Dafny program: 422
|
// Given an array of integers, it returns the sum. [1,3,3,2]->9
function Sum(xs: seq<int>): int {
if |xs| == 0 then 0 else Sum(xs[..|xs|-1]) + xs[|xs|-1]
}
method SumArray(xs: array<int>) returns (s: int)
ensures s == Sum(xs[..])
{
s := 0;
var i := 0;
while i < xs.Length
{
s := s + xs[i];
i := i + 1;
}
}
|
// Given an array of integers, it returns the sum. [1,3,3,2]->9
function Sum(xs: seq<int>): int {
if |xs| == 0 then 0 else Sum(xs[..|xs|-1]) + xs[|xs|-1]
}
method SumArray(xs: array<int>) returns (s: int)
ensures s == Sum(xs[..])
{
s := 0;
var i := 0;
while i < xs.Length
invariant 0 <= i <= xs.Length
invariant s == Sum(xs[..i])
{
s := s + xs[i];
assert xs[..i+1] == xs[..i] + [xs[i]];
i := i + 1;
}
assert xs[..] == xs[..i];
}
|
dafny-duck_tmp_tmplawbgxjo_p1.dfy
|
423
|
423
|
Dafny program: 423
|
// Given an array of positive and negative integers,
// it returns an array of the absolute value of all the integers. [-4,1,5,-2,-5]->[4,1,5,2,5]
function abs(x:int):nat {
if x < 0 then -x else x
}
method absx(x:array<int>) returns (y:array<int>)
ensures y.Length == x.Length
ensures forall i :: 0 <= i < y.Length ==> y[i] == abs(x[i])
{
// put the old array in to new array (declare a new array)
// loop through the new array
// convert negative to positive by assigning new to be old
// increment
y:= new int [x.Length];
var j:= 0;
while (j < y.Length)
// need to have here equals to make sure we cover the last element
{
if(x[j] < 0) {
y[j] := -x[j];
} else {
y[j] := x[j];
}
j:= j + 1;
}
}
method Main() {
var d := new int [5];
var c := new int [5];
d[0], d[1], d[2], d[3], d[4] := -4, 1, 5, -2 , -5;
//c[0], c[1], c[2], c[3], c[4] := 4, 1, 5, 2 , 5;
c:=absx(d);
//assert forall x :: 0<=x<c.Length ==> c[x] >= 0;
print c[..];
}
|
// Given an array of positive and negative integers,
// it returns an array of the absolute value of all the integers. [-4,1,5,-2,-5]->[4,1,5,2,5]
function abs(x:int):nat {
if x < 0 then -x else x
}
method absx(x:array<int>) returns (y:array<int>)
ensures y.Length == x.Length
ensures forall i :: 0 <= i < y.Length ==> y[i] == abs(x[i])
{
// put the old array in to new array (declare a new array)
// loop through the new array
// convert negative to positive by assigning new to be old
// increment
y:= new int [x.Length];
var j:= 0;
assert y.Length == x.Length;
while (j < y.Length)
invariant 0<=j<=y.Length
// need to have here equals to make sure we cover the last element
invariant forall i :: 0 <= i < j <= y.Length ==> y[i] == abs(x[i])
{
if(x[j] < 0) {
y[j] := -x[j];
} else {
y[j] := x[j];
}
j:= j + 1;
}
}
method Main() {
var d := new int [5];
var c := new int [5];
d[0], d[1], d[2], d[3], d[4] := -4, 1, 5, -2 , -5;
//c[0], c[1], c[2], c[3], c[4] := 4, 1, 5, 2 , 5;
c:=absx(d);
assert c[..] == [4, 1, 5, 2 ,5];
//assert forall x :: 0<=x<c.Length ==> c[x] >= 0;
print c[..];
}
|
dafny-duck_tmp_tmplawbgxjo_p2.dfy
|
424
|
424
|
Dafny program: 424
|
//Given an array of natural numbers, it returns the maximum value. [5,1,3,6,12,3]->12
method max(x:array<nat>) returns (y:nat)
// for index loop problems
requires x.Length > 0
// ensuring that we maintain y as greater than the elements in the array
ensures forall j :: 0 <= j < x.Length ==> y >= x[j]
// ensuring that the return value is in the array
ensures y in x[..]
{
y:= x[0];
var i := 0;
while(i < x.Length)
// create new index
{
if(y <= x[i]){
y := x[i];
}
i := i + 1;
}
}
method Main()
{
// when we did the other way it didnt work
var a:= new nat [6][5, 1, 3, 6, 12, 3];
var c:= max(a);
// print c;
}
|
//Given an array of natural numbers, it returns the maximum value. [5,1,3,6,12,3]->12
method max(x:array<nat>) returns (y:nat)
// for index loop problems
requires x.Length > 0
// ensuring that we maintain y as greater than the elements in the array
ensures forall j :: 0 <= j < x.Length ==> y >= x[j]
// ensuring that the return value is in the array
ensures y in x[..]
{
y:= x[0];
var i := 0;
while(i < x.Length)
invariant 0 <=i <=x.Length
// create new index
invariant forall j :: 0 <= j < i ==> y >= x[j]
invariant y in x[..]
{
if(y <= x[i]){
y := x[i];
}
i := i + 1;
}
assert y in x[..];
}
method Main()
{
// when we did the other way it didnt work
var a:= new nat [6][5, 1, 3, 6, 12, 3];
var c:= max(a);
assert c == 12;
// print c;
}
|
dafny-duck_tmp_tmplawbgxjo_p3.dfy
|
425
|
425
|
Dafny program: 425
|
//Given two arrays of integers, it returns a single array with all integers merged.
// [1,5,2,3],[4,3,5]->[1,5,2,3,4,3,5]
method single(x:array<int>, y:array<int>) returns (b:array<int>)
requires x.Length > 0
requires y.Length > 0
// ensuring that the new array is the two arrays joined
ensures b[..] == x[..] + y[..]
{
// getting the new array to have the length of the two arrays
b:= new int [x.Length + y.Length];
var i := 0;
// to loop over the final array
var index := 0;
var sumi := x.Length + y.Length;
while (i < x.Length && index < sumi)
// making sure all elements up to index and i in both arrays are same
{
b[index]:= x[i];
i := i + 1;
index:= index+1;
}
i := 0;
while (i < y.Length && index < sumi)
// making sure that all elements in x and y are the same as b
{
b[index]:= y[i];
i := i + 1;
index:= index + 1;
}
}
method Main()
{
var a:= new int [4][1,5,2,3];
var b:= new int [3][4,3,5];
var c:= new int [7];
c := single(a,b);
//print c[..];
}
|
//Given two arrays of integers, it returns a single array with all integers merged.
// [1,5,2,3],[4,3,5]->[1,5,2,3,4,3,5]
method single(x:array<int>, y:array<int>) returns (b:array<int>)
requires x.Length > 0
requires y.Length > 0
// ensuring that the new array is the two arrays joined
ensures b[..] == x[..] + y[..]
{
// getting the new array to have the length of the two arrays
b:= new int [x.Length + y.Length];
var i := 0;
// to loop over the final array
var index := 0;
var sumi := x.Length + y.Length;
while (i < x.Length && index < sumi)
invariant 0 <= i <= x.Length
invariant 0 <= index <= sumi
// making sure all elements up to index and i in both arrays are same
invariant b[..index] == x[..i]
{
b[index]:= x[i];
i := i + 1;
index:= index+1;
}
i := 0;
while (i < y.Length && index < sumi)
invariant 0 <= i <= y.Length
invariant 0 <= index <= sumi
// making sure that all elements in x and y are the same as b
invariant b[..index] == x[..] + y[..i]
{
b[index]:= y[i];
i := i + 1;
index:= index + 1;
}
}
method Main()
{
var a:= new int [4][1,5,2,3];
var b:= new int [3][4,3,5];
var c:= new int [7];
c := single(a,b);
assert c[..] == [1,5,2,3,4,3,5];
//print c[..];
}
|
dafny-duck_tmp_tmplawbgxjo_p4.dfy
|
426
|
426
|
Dafny program: 426
|
//Given an array of characters, it filters all the vowels. [‘d’,’e’,’l’,’i’,’g’,’h’,’t’]-> [’e’,’i’]
const vowels: set<char> := {'a', 'e', 'i', 'o', 'u'}
function FilterVowels(xs: seq<char>): seq<char>
{
if |xs| == 0 then []
else if xs[|xs|-1] in vowels then FilterVowels(xs[..|xs|-1]) + [xs[|xs|-1]]
else FilterVowels(xs[..|xs|-1])
}
method FilterVowelsArray(xs: array<char>) returns (ys: array<char>)
ensures fresh(ys)
ensures FilterVowels(xs[..]) == ys[..]
{
var n := 0;
var i := 0;
while i < xs.Length
{
if xs[i] in vowels {
n := n + 1;
}
i := i + 1;
}
ys := new char[n];
i := 0;
var j := 0;
while i < xs.Length
{
if xs[i] in vowels {
ys[j] := xs[i];
j := j + 1;
}
i := i + 1;
}
}
|
//Given an array of characters, it filters all the vowels. [‘d’,’e’,’l’,’i’,’g’,’h’,’t’]-> [’e’,’i’]
const vowels: set<char> := {'a', 'e', 'i', 'o', 'u'}
function FilterVowels(xs: seq<char>): seq<char>
{
if |xs| == 0 then []
else if xs[|xs|-1] in vowels then FilterVowels(xs[..|xs|-1]) + [xs[|xs|-1]]
else FilterVowels(xs[..|xs|-1])
}
method FilterVowelsArray(xs: array<char>) returns (ys: array<char>)
ensures fresh(ys)
ensures FilterVowels(xs[..]) == ys[..]
{
var n := 0;
var i := 0;
while i < xs.Length
invariant 0 <= i <= xs.Length
invariant n == |FilterVowels(xs[..i])|
invariant forall j :: 0 <= j <= i ==> n >= |FilterVowels(xs[..j])|
{
assert xs[..i+1] == xs[..i] + [xs[i]];
if xs[i] in vowels {
n := n + 1;
}
i := i + 1;
}
ys := new char[n];
i := 0;
var j := 0;
while i < xs.Length
invariant 0 <= i <= xs.Length
invariant 0 <= j <= ys.Length
invariant ys[..j] == FilterVowels(xs[..i])
{
assert xs[..i+1] == xs[..i] + [xs[i]];
if xs[i] in vowels {
assert ys.Length >= |FilterVowels(xs[..i+1])|;
ys[j] := xs[i];
j := j + 1;
}
i := i + 1;
}
assert xs[..] == xs[..i];
assert ys[..] == ys[..j];
}
|
dafny-duck_tmp_tmplawbgxjo_p6.dfy
|
427
|
427
|
Dafny program: 427
|
method AbsIt(s: array<int>)
modifies s
ensures forall i :: 0 <= i < s.Length ==> if old(s[i]) < 0 then s[i] == -old(s[i]) else s[i] == old(s[i])
ensures s.Length == old(s).Length
{
var i: int := 0;
while i < s.Length
{
if (s[i] < 0) {
s[i] := -s[i];
}
i := i + 1;
}
}
method Tester()
{
var a := new int[][-1,2,-3,4,-5,6,-7,8,-9];
// testcase 1
AbsIt(a);
var b:array<int> := new int[][-42,-2,-42,-2,-42,-2];
// testcase 2
AbsIt(b);
var c:array<int> := new int[][-1];
// testcase 3
AbsIt(c);
var d:array<int> := new int[][42];
// testcase 4
AbsIt(b);
var e:array<int> := new int[][];
// testcase 5
AbsIt(e);
}
|
method AbsIt(s: array<int>)
modifies s
ensures forall i :: 0 <= i < s.Length ==> if old(s[i]) < 0 then s[i] == -old(s[i]) else s[i] == old(s[i])
ensures s.Length == old(s).Length
{
var i: int := 0;
while i < s.Length
invariant 0 <= i <= s.Length
invariant forall j :: 0 <= j < i ==> if old(s[j]) < 0 then s[j] == -old(s[j]) else s[j] == old(s[j])
invariant forall j :: i <= j < s.Length ==> s[j] == old(s[j])
{
if (s[i] < 0) {
s[i] := -s[i];
}
i := i + 1;
}
}
method Tester()
{
var a := new int[][-1,2,-3,4,-5,6,-7,8,-9];
// testcase 1
assert a[0]==-1 && a[1]==2 && a[2]==-3 && a[3]==4 && a[4]==-5;
assert a[5]==6 && a[6]==-7 && a[7]==8 && a[8]==-9;
AbsIt(a);
assert a[0]==1 && a[1]==2 && a[2]==3 && a[3]==4 && a[4]==5;
assert a[5]==6 && a[6]==7 && a[7]==8 && a[8]==9;
var b:array<int> := new int[][-42,-2,-42,-2,-42,-2];
// testcase 2
assert b[0]==-42 && b[1]==-2 && b[2]==-42;
assert b[3]==-2 && b[4]==-42 && b[5]==-2;
AbsIt(b);
assert b[0]==42 && b[1]==2 && b[2]==42;
assert b[3]==2 && b[4]==42 && b[5]==2;
var c:array<int> := new int[][-1];
// testcase 3
assert c[0]==-1;
AbsIt(c);
assert c[0]==1;
var d:array<int> := new int[][42];
// testcase 4
assert d[0]==42;
AbsIt(b);
assert d[0]==42;
var e:array<int> := new int[][];
// testcase 5
AbsIt(e);
assert e.Length==0; // array is empty
}
|
dafny-exercise_tmp_tmpouftptir_absIt.dfy
|
428
|
428
|
Dafny program: 428
|
method appendArray(a: array<int>, b: array<int>) returns (c: array<int>)
ensures c.Length == a.Length + b.Length
ensures forall i :: 0 <= i < a.Length ==> a[i] == c[i]
ensures forall i :: 0 <= i < b.Length ==> b[i] == c[a.Length + i]
{
c := new int[a.Length + b.Length];
var i := 0;
while i < a.Length
{
c[i] := a[i];
i := i + 1;
}
while i < b.Length + a.Length
{
c[i] := b[i - a.Length];
i := i + 1;
}
}
|
method appendArray(a: array<int>, b: array<int>) returns (c: array<int>)
ensures c.Length == a.Length + b.Length
ensures forall i :: 0 <= i < a.Length ==> a[i] == c[i]
ensures forall i :: 0 <= i < b.Length ==> b[i] == c[a.Length + i]
{
c := new int[a.Length + b.Length];
var i := 0;
while i < a.Length
invariant 0 <= i <= a.Length
invariant forall j :: 0 <= j < i ==> c[j] == a[j]
{
c[i] := a[i];
i := i + 1;
}
while i < b.Length + a.Length
invariant a.Length <= i <= b.Length + a.Length
invariant forall j :: 0 <= j < a.Length ==> a[j] == c[j]
invariant forall j :: a.Length <= j < i ==> c[j] == b[j - a.Length]
{
c[i] := b[i - a.Length];
i := i + 1;
}
}
|
dafny-exercise_tmp_tmpouftptir_appendArray.dfy
|
429
|
429
|
Dafny program: 429
|
function verifyNeg(a: array<int>, idx: int) : nat
reads a
requires 0 <= idx <= a.Length
{
if idx == 0 then 0
else verifyNeg(a, idx - 1) + (if a[idx - 1] < 0 then 1 else 0)
}
method CountNeg(a: array<int>) returns (cnt: nat)
ensures cnt == verifyNeg(a, a.Length)
{
var i := 0;
cnt := 0;
while i < a.Length
{
if a[i] < 0 {
cnt := cnt + 1;
}
i := i + 1;
}
}
method Main()
{
var arr: array<int> := new int[][0,-1,-2,4];
var res := CountNeg(arr);
}
|
function verifyNeg(a: array<int>, idx: int) : nat
reads a
requires 0 <= idx <= a.Length
{
if idx == 0 then 0
else verifyNeg(a, idx - 1) + (if a[idx - 1] < 0 then 1 else 0)
}
method CountNeg(a: array<int>) returns (cnt: nat)
ensures cnt == verifyNeg(a, a.Length)
{
var i := 0;
cnt := 0;
while i < a.Length
invariant 0 <= i <= a.Length
invariant cnt == verifyNeg(a, i)
{
if a[i] < 0 {
cnt := cnt + 1;
}
i := i + 1;
}
}
method Main()
{
var arr: array<int> := new int[][0,-1,-2,4];
var res := CountNeg(arr);
assert res == verifyNeg(arr, arr.Length);
}
|
dafny-exercise_tmp_tmpouftptir_countNeg.dfy
|
431
|
431
|
Dafny program: 431
|
method firstE(a: array<char>) returns (x: int)
ensures if 'e' in a[..] then 0 <= x < a.Length && a[x] == 'e' && forall i | 0 <= i < x :: a[i] != 'e' else x == -1
{
var i: int := 0;
while i < a.Length
{
if (a[i] == 'e') {
return i;
}
i := i + 1;
}
return -1;
}
method Main() {
var a: array<char> := new char[]['c','h','e','e','s','e'];
var res := firstE(a);
a := new char[]['e'];
res := firstE(a);
a := new char[][];
res := firstE(a);
}
|
method firstE(a: array<char>) returns (x: int)
ensures if 'e' in a[..] then 0 <= x < a.Length && a[x] == 'e' && forall i | 0 <= i < x :: a[i] != 'e' else x == -1
{
var i: int := 0;
while i < a.Length
invariant 0 <= i <= a.Length
invariant forall j :: 0 <= j < i ==> a[j] != 'e'
{
if (a[i] == 'e') {
return i;
}
i := i + 1;
}
return -1;
}
method Main() {
var a: array<char> := new char[]['c','h','e','e','s','e'];
assert a[0] == 'c' && a[1] == 'h' && a[2] == 'e';
var res := firstE(a);
assert res == 2;
a := new char[]['e'];
assert a[0] == 'e';
res := firstE(a);
assert res == 0;
a := new char[][];
res := firstE(a);
assert res == -1;
}
|
dafny-exercise_tmp_tmpouftptir_firstE.dfy
|
432
|
432
|
Dafny program: 432
|
method MaxArray(a: array<int>) returns (max:int)
requires a.Length > 0
ensures forall i :: 0 <= i < a.Length ==> a[i] <= max
ensures exists i :: 0 <= i < a.Length && a[i] == max
{
var i: nat := 1;
max := a[0];
while i < a.Length
{
if (a[i] > max) {
max := a[i];
}
i := i + 1;
}
}
method Main() {
var arr : array<int> := new int[][-11,2,42,-4];
var res := MaxArray(arr);
}
|
method MaxArray(a: array<int>) returns (max:int)
requires a.Length > 0
ensures forall i :: 0 <= i < a.Length ==> a[i] <= max
ensures exists i :: 0 <= i < a.Length && a[i] == max
{
var i: nat := 1;
max := a[0];
while i < a.Length
invariant 0 <= i <= a.Length
invariant forall j :: 0 <= j < i ==> a[j] <= max
invariant exists j :: 0 <= j < i && a[j] == max
{
if (a[i] > max) {
max := a[i];
}
i := i + 1;
}
}
method Main() {
var arr : array<int> := new int[][-11,2,42,-4];
var res := MaxArray(arr);
assert arr[0] == -11 && arr[1] == 2 && arr[2] == 42 && arr[3] == -4;
assert res == 42;
}
|
dafny-exercise_tmp_tmpouftptir_maxArray.dfy
|
434
|
434
|
Dafny program: 434
|
method Deli(a: array<char>, i: nat)
modifies a
requires a.Length > 0
requires 0 <= i < a.Length
ensures forall j :: 0 <= j < i ==> a[j] == old(a[j])
ensures forall j :: i <= j < a.Length - 1 ==> a[j] == old(a[j + 1])
ensures a[a.Length - 1] == '.'
{
var c := i;
while c < a.Length - 1
// unchanged first half
{
a[c] := a[c + 1];
c := c + 1;
}
a[c] := '.';
}
method DeliChecker()
{
var z := new char[]['b','r','o','o','m'];
Deli(z, 1);
Deli(z, 3);
Deli(z, 4);
Deli(z, 3);
Deli(z, 0);
Deli(z, 0);
Deli(z, 0);
z := new char[]['x'];
Deli(z, 0);
}
|
method Deli(a: array<char>, i: nat)
modifies a
requires a.Length > 0
requires 0 <= i < a.Length
ensures forall j :: 0 <= j < i ==> a[j] == old(a[j])
ensures forall j :: i <= j < a.Length - 1 ==> a[j] == old(a[j + 1])
ensures a[a.Length - 1] == '.'
{
var c := i;
while c < a.Length - 1
invariant i <= c <= a.Length - 1
invariant forall j :: i <= j < c ==> a[j] == old(a[j + 1])
// unchanged first half
invariant forall j :: 0 <= j < i ==> a[j] == old(a[j])
invariant forall j :: c <= j < a.Length ==> a[j] == old(a[j])
{
a[c] := a[c + 1];
c := c + 1;
}
a[c] := '.';
}
method DeliChecker()
{
var z := new char[]['b','r','o','o','m'];
Deli(z, 1);
assert z[..] == "boom.";
Deli(z, 3);
assert z[..] == "boo..";
Deli(z, 4);
assert z[..] == "boo..";
Deli(z, 3);
assert z[..] == "boo..";
Deli(z, 0);
Deli(z, 0);
Deli(z, 0);
assert z[..] == ".....";
z := new char[]['x'];
Deli(z, 0);
assert z[..] == ".";
}
|
dafny-exercise_tmp_tmpouftptir_prac1_ex2.dfy
|
435
|
435
|
Dafny program: 435
|
method GetEven(s: array<nat>) modifies s
ensures forall i :: 0 <= i < s.Length ==>
if old(s[i]) % 2 == 1 then s[i] == old(s[i]) + 1
else s[i] == old(s[i])
{
var i := 0;
while i < s.Length
if old(s[j]) % 2 == 1 then s[j] == old(s[j]) + 1
else s[j] == old(s[j])
{
if s[i] % 2 == 1 {
s[i] := s[i] + 1;
}
i := i + 1;
}
}
method evenTest()
{
var a:array<nat> := new nat[][0,9,4];
GetEven(a);
}
|
method GetEven(s: array<nat>) modifies s
ensures forall i :: 0 <= i < s.Length ==>
if old(s[i]) % 2 == 1 then s[i] == old(s[i]) + 1
else s[i] == old(s[i])
{
var i := 0;
while i < s.Length
invariant 0 <= i <= s.Length
invariant forall j :: 0 <= j < i ==>
if old(s[j]) % 2 == 1 then s[j] == old(s[j]) + 1
else s[j] == old(s[j])
invariant forall j :: i <= j < s.Length ==> s[j] == old(s[j])
{
if s[i] % 2 == 1 {
s[i] := s[i] + 1;
}
i := i + 1;
}
}
method evenTest()
{
var a:array<nat> := new nat[][0,9,4];
assert a[0]==0 && a[1]==9 && a[2]==4;
GetEven(a);
assert a[0]==0 && a[1]==10 && a[2]==4;
}
|
dafny-exercise_tmp_tmpouftptir_prac3_ex2.dfy
|
436
|
436
|
Dafny program: 436
|
predicate triple(a: array<int>)
reads a
{
exists i :: 0 <= i < a.Length - 2 && a[i] == a[i + 1] == a[i + 2]
}
method GetTriple(a: array<int>) returns (index: int)
ensures 0 <= index < a.Length - 2 || index == a.Length
ensures index == a.Length <==> !triple(a)
ensures 0 <= index < a.Length - 2 <==> triple(a)
ensures 0 <= index < a.Length - 2 ==> a[index] == a[index + 1] == a[index + 2]
{
var i: nat := 0;
index := a.Length;
if a.Length < 3 {
return a.Length;
}
while i < a.Length - 2
{
if a[i] == a[i + 1] == a[i + 2] {
return i;
}
i := i + 1;
}
}
method TesterGetTriple()
{
var a: array<int> := new int[1][42];
var b := GetTriple(a);
a := new int[2][42,42];
b := GetTriple(a);
a := new int[3][42,42,0];
b := GetTriple(a);
a := new int[4][42,42,0,42];
b := GetTriple(a);
a := new int[3][42,42,42];
b := GetTriple(a);
a := new int[4][0,42,42,42];
b := GetTriple(a);
a := new int[6][0,0,42,42,42,0];
b := GetTriple(a);
}
|
predicate triple(a: array<int>)
reads a
{
exists i :: 0 <= i < a.Length - 2 && a[i] == a[i + 1] == a[i + 2]
}
method GetTriple(a: array<int>) returns (index: int)
ensures 0 <= index < a.Length - 2 || index == a.Length
ensures index == a.Length <==> !triple(a)
ensures 0 <= index < a.Length - 2 <==> triple(a)
ensures 0 <= index < a.Length - 2 ==> a[index] == a[index + 1] == a[index + 2]
{
var i: nat := 0;
index := a.Length;
if a.Length < 3 {
return a.Length;
}
while i < a.Length - 2
decreases a.Length - i
invariant 0 <= i <= a.Length - 2
invariant index == a.Length <==> (!exists j :: 0 <= j < i && a[j] == a[j + 1] == a[j + 2])
invariant 0 <= index < a.Length - 2 ==> a[index] == a[index + 1] == a[index + 2]
{
if a[i] == a[i + 1] == a[i + 2] {
return i;
}
i := i + 1;
}
}
method TesterGetTriple()
{
var a: array<int> := new int[1][42];
assert a[0] == 42;
var b := GetTriple(a);
assert b==a.Length; // NO TRIPLE
a := new int[2][42,42];
assert a[0] == a[1] == 42;
b := GetTriple(a);
assert b==a.Length; // NO TRIPLE
a := new int[3][42,42,0];
assert a[0] == a[1] == 42 && a[2] == 0;
b := GetTriple(a);
assert b==a.Length; // NO TRIPLE
a := new int[4][42,42,0,42];
assert a[0] == a[1] == a[3] == 42 && a[2] == 0;
b := GetTriple(a);
assert b==a.Length; // NO TRIPLE
a := new int[3][42,42,42];
assert a[0] == a[1] == a[2] == 42;
b := GetTriple(a);
assert b==0; // A TRIPLE!
a := new int[4][0,42,42,42];
assert a[0] == 0 && a[1] == a[2] == a[3] == 42;
b := GetTriple(a);
assert b==1; // A TRIPLE!
a := new int[6][0,0,42,42,42,0];
assert a[0] == a[1] == a[5] == 0 && a[2] == a[3] == a[4] == 42;
b := GetTriple(a);
assert b==2; // A TRIPLE!
}
|
dafny-exercise_tmp_tmpouftptir_prac4_ex2.dfy
|
437
|
437
|
Dafny program: 437
|
method Reverse(a: array<char>) returns (b: array<char>)
requires a.Length > 0
ensures a == old(a)
ensures b.Length == a.Length
ensures forall i :: 0 <= i < a.Length ==> b[i] == a[a.Length - i - 1]
{
b := new char[a.Length];
var i := 0;
while i < a.Length
{
b[i] := a[a.Length - i - 1];
i := i + 1;
}
}
method Main()
{
var a := new char[]['s', 'k', 'r', 'o', 'w', 't', 'i'];
var b := Reverse(a);
print b[..];
a := new char[]['!'];
b := Reverse(a);
print b[..], '\n';
}
|
method Reverse(a: array<char>) returns (b: array<char>)
requires a.Length > 0
ensures a == old(a)
ensures b.Length == a.Length
ensures forall i :: 0 <= i < a.Length ==> b[i] == a[a.Length - i - 1]
{
b := new char[a.Length];
var i := 0;
while i < a.Length
invariant 0 <= i <= a.Length
invariant forall j :: 0 <= j < i ==> b[j] == a[a.Length - j - 1]
{
b[i] := a[a.Length - i - 1];
i := i + 1;
}
}
method Main()
{
var a := new char[]['s', 'k', 'r', 'o', 'w', 't', 'i'];
var b := Reverse(a);
assert b[..] == [ 'i', 't', 'w', 'o', 'r', 'k', 's' ];
print b[..];
a := new char[]['!'];
b := Reverse(a);
assert b[..] == a[..];
print b[..], '\n';
}
|
dafny-exercise_tmp_tmpouftptir_reverse.dfy
|
438
|
438
|
Dafny program: 438
|
method ZapNegatives(a: array<int>)
modifies a
ensures forall i :: 0 <= i < a.Length ==> if old(a[i]) < 0 then a[i] == 0
else a[i] == old(a[i])
ensures a.Length == old(a).Length
{
var i := 0;
while i < a.Length
else a[j] == old(a[j])
{
if a[i] < 0 {
a[i] := 0;
}
i := i + 1;
}
}
method Main()
{
var arr: array<int> := new int[][-1, 2, 3, -4];
ZapNegatives(arr);
}
|
method ZapNegatives(a: array<int>)
modifies a
ensures forall i :: 0 <= i < a.Length ==> if old(a[i]) < 0 then a[i] == 0
else a[i] == old(a[i])
ensures a.Length == old(a).Length
{
var i := 0;
while i < a.Length
invariant 0 <= i <= a.Length
invariant forall j :: 0 <= j < i ==> if old(a[j]) < 0 then a[j] == 0
else a[j] == old(a[j])
invariant forall j :: i <= j < a.Length ==> a[j] == old(a[j])
{
if a[i] < 0 {
a[i] := 0;
}
i := i + 1;
}
}
method Main()
{
var arr: array<int> := new int[][-1, 2, 3, -4];
assert arr[0] == -1 && arr[1] == 2 && arr[2] == 3 && arr[3] == -4;
ZapNegatives(arr);
assert arr[0] == 0 && arr[1] == 2 && arr[2] == 3 && arr[3] == 0;
}
|
dafny-exercise_tmp_tmpouftptir_zapNegatives.dfy
|
439
|
439
|
Dafny program: 439
|
method RemoveDuplicates(nums: array<int>) returns (num_length: int)
modifies nums
requires forall i, j | 0 <= i < j < nums.Length :: nums[i] <= nums[j]
ensures nums.Length == old(nums).Length
ensures 0 <= num_length <= nums.Length
ensures forall i, j | 0 <= i < j < num_length :: nums[i] != nums[j]
ensures forall i | 0 <= i < num_length :: nums[i] in old(nums[..])
ensures forall i | 0 <= i < nums.Length :: old(nums[i]) in nums[..num_length]
{
if nums.Length <= 1 {
return nums.Length;
}
var last := 0;
var i := 1;
ghost var nums_before := nums[..];
while i < nums.Length
// verify that `last` will strictly smaller than `i`
// verify that `nums[i..]` is untouched.
// verify that `nums[..last1]` are sorted and strictly ascending.
// verify that elements in `nums[..last1]` are contained in the origin `nums[..i]`
// verify that elements in origin `nums[..i]` are contained in the `nums[..last1]`
{
if nums[last] < nums[i] {
last := last + 1;
nums[last] := nums[i];
// Theses two assertion are used for the last invariant, which
// verifies that all elements in origin `nums[..i]` are contained in new `nums[..last+1]`
}
i := i + 1;
}
return last + 1;
}
method Testing() {
var nums1 := new int[3];
nums1[0] := 1;
nums1[1] := 1;
nums1[2] := 2;
var num_length1 := RemoveDuplicates(nums1);
print "nums1: ", nums1[..], ", num_length1: ", num_length1, "\n";
var nums2 := new int[10];
nums2[0] := 0;
nums2[1] := 0;
nums2[2] := 1;
nums2[3] := 1;
nums2[4] := 1;
nums2[5] := 2;
nums2[6] := 2;
nums2[7] := 3;
nums2[8] := 3;
nums2[9] := 4;
var num_length2 := RemoveDuplicates(nums2);
print "nums2: ", nums2[..], ", num_length2: ", num_length2, "\n";
}
method Main() {
Testing();
}
|
method RemoveDuplicates(nums: array<int>) returns (num_length: int)
modifies nums
requires forall i, j | 0 <= i < j < nums.Length :: nums[i] <= nums[j]
ensures nums.Length == old(nums).Length
ensures 0 <= num_length <= nums.Length
ensures forall i, j | 0 <= i < j < num_length :: nums[i] != nums[j]
ensures forall i | 0 <= i < num_length :: nums[i] in old(nums[..])
ensures forall i | 0 <= i < nums.Length :: old(nums[i]) in nums[..num_length]
{
if nums.Length <= 1 {
return nums.Length;
}
var last := 0;
var i := 1;
ghost var nums_before := nums[..];
while i < nums.Length
// verify that `last` will strictly smaller than `i`
invariant 0 <= last < i <= nums.Length
// verify that `nums[i..]` is untouched.
invariant nums[i..] == nums_before[i..]
// verify that `nums[..last1]` are sorted and strictly ascending.
invariant forall j, k | 0 <= j < k <= last :: nums[j] < nums[k]
// verify that elements in `nums[..last1]` are contained in the origin `nums[..i]`
invariant forall j | 0 <= j <= last :: nums[j] in nums_before[..i]
// verify that elements in origin `nums[..i]` are contained in the `nums[..last1]`
invariant forall j | 0 <= j < i :: nums_before[j] in nums[..last+1]
{
if nums[last] < nums[i] {
last := last + 1;
nums[last] := nums[i];
// Theses two assertion are used for the last invariant, which
// verifies that all elements in origin `nums[..i]` are contained in new `nums[..last+1]`
assert forall j | 0 <= j < i :: nums_before[j] in nums[..last];
assert forall j | 0 <= j <= i :: nums_before[j] in nums[..last+1];
}
i := i + 1;
}
return last + 1;
}
method Testing() {
var nums1 := new int[3];
nums1[0] := 1;
nums1[1] := 1;
nums1[2] := 2;
var num_length1 := RemoveDuplicates(nums1);
assert forall i, j | 0 <= i < j < num_length1 :: nums1[i] != nums1[j];
assert num_length1 <= nums1.Length;
print "nums1: ", nums1[..], ", num_length1: ", num_length1, "\n";
var nums2 := new int[10];
nums2[0] := 0;
nums2[1] := 0;
nums2[2] := 1;
nums2[3] := 1;
nums2[4] := 1;
nums2[5] := 2;
nums2[6] := 2;
nums2[7] := 3;
nums2[8] := 3;
nums2[9] := 4;
var num_length2 := RemoveDuplicates(nums2);
assert forall i, j | 0 <= i < j < num_length1 :: nums1[i] != nums1[j];
assert num_length2 <= nums2.Length;
print "nums2: ", nums2[..], ", num_length2: ", num_length2, "\n";
}
method Main() {
Testing();
}
|
dafny-exercises_tmp_tmp5mvrowrx_leetcode_26-remove-duplicates-from-sorted-array.dfy
|
440
|
440
|
Dafny program: 440
|
// Examples used in paper:
// Specification and Verification of Object-Oriented Software
// by K. Rustan M. Leino
// link of the paper:
// http://leino.science/papers/krml190.pdf
// Figure 0. An example linked-list program written in Dafny.
class Data { }
class Node {
var list: seq<Data>;
var footprint: set<Node>;
var data: Data;
var next: Node?;
function Valid(): bool
reads this, footprint
{
this in footprint &&
(next == null ==> list == [data]) &&
(next != null ==> next in footprint &&
next.footprint <= footprint &&
!(this in next.footprint) &&
list == [data] + next.list &&
next.Valid())
}
constructor(d: Data)
ensures Valid() && fresh(footprint - {this})
ensures list == [d]
{
data := d;
next := null;
list := [d];
footprint := {this};
}
method SkipHead() returns (r: Node?)
requires Valid()
ensures r == null ==> |list| == 1
ensures r != null ==> r.Valid() && r.footprint <= footprint
{
return next;
}
method Prepend(d: Data) returns (r: Node)
requires Valid()
ensures r.Valid() && fresh(r.footprint - old(footprint))
ensures r.list == [d] + list
{
r := new Node(d);
r.data := d;
r.next := this;
r.footprint := {r} + footprint;
r.list := [r.data] + list;
}
// Figure 1: The Node.ReverseInPlace method,
// which performs an in situ list reversal.
method ReverseInPlace() returns (reverse: Node)
requires Valid()
modifies footprint
ensures reverse.Valid()
// isn't here a typo?
ensures fresh(reverse.footprint - old(footprint))
ensures |reverse.list| == |old(list)|
ensures forall i | 0 <= i < |old(list)| :: old(list)[i] == reverse.list[|old(list)| - 1 - i]
{
var current: Node?;
current := next;
reverse := this;
reverse.next := null;
reverse.footprint := {reverse};
reverse.list := [data];
while current != null
current.Valid()
current in old(footprint) && current.footprint <= old(footprint)
current.footprint !! reverse.footprint
|old(list)| == |reverse.list| + |current.list|
forall i | 0 <= i < |current.list| ::
current.list[i] == old(list)[|reverse.list| + i]
old(list)[i] == reverse.list[|reverse.list| - 1 - i]
{
var nx: Node?;
nx := current.next;
forall i | 0 <= i < |nx.list| ::
current.list[i + 1] == nx.list[i];
// The state looks like: ..., reverse, current, nx, ...
current.next := reverse;
current.footprint := {current} + reverse.footprint;
current.list := [current.data] + reverse.list;
reverse := current;
current := nx;
}
}
}
|
// Examples used in paper:
// Specification and Verification of Object-Oriented Software
// by K. Rustan M. Leino
// link of the paper:
// http://leino.science/papers/krml190.pdf
// Figure 0. An example linked-list program written in Dafny.
class Data { }
class Node {
var list: seq<Data>;
var footprint: set<Node>;
var data: Data;
var next: Node?;
function Valid(): bool
reads this, footprint
{
this in footprint &&
(next == null ==> list == [data]) &&
(next != null ==> next in footprint &&
next.footprint <= footprint &&
!(this in next.footprint) &&
list == [data] + next.list &&
next.Valid())
}
constructor(d: Data)
ensures Valid() && fresh(footprint - {this})
ensures list == [d]
{
data := d;
next := null;
list := [d];
footprint := {this};
}
method SkipHead() returns (r: Node?)
requires Valid()
ensures r == null ==> |list| == 1
ensures r != null ==> r.Valid() && r.footprint <= footprint
{
return next;
}
method Prepend(d: Data) returns (r: Node)
requires Valid()
ensures r.Valid() && fresh(r.footprint - old(footprint))
ensures r.list == [d] + list
{
r := new Node(d);
r.data := d;
r.next := this;
r.footprint := {r} + footprint;
r.list := [r.data] + list;
}
// Figure 1: The Node.ReverseInPlace method,
// which performs an in situ list reversal.
method ReverseInPlace() returns (reverse: Node)
requires Valid()
modifies footprint
ensures reverse.Valid()
// isn't here a typo?
ensures fresh(reverse.footprint - old(footprint))
ensures |reverse.list| == |old(list)|
ensures forall i | 0 <= i < |old(list)| :: old(list)[i] == reverse.list[|old(list)| - 1 - i]
{
var current: Node?;
current := next;
reverse := this;
reverse.next := null;
reverse.footprint := {reverse};
reverse.list := [data];
while current != null
invariant reverse.Valid()
invariant reverse.footprint <= old(footprint)
invariant current == null ==> |old(list)| == |reverse.list|
invariant current != null ==>
current.Valid()
invariant current != null ==>
current in old(footprint) && current.footprint <= old(footprint)
invariant current != null ==>
current.footprint !! reverse.footprint
invariant current != null ==>
|old(list)| == |reverse.list| + |current.list|
invariant current != null ==>
forall i | 0 <= i < |current.list| ::
current.list[i] == old(list)[|reverse.list| + i]
invariant forall i | 0 <= i < |reverse.list| ::
old(list)[i] == reverse.list[|reverse.list| - 1 - i]
decreases |old(list)| - |reverse.list|
{
var nx: Node?;
nx := current.next;
assert nx != null ==>
forall i | 0 <= i < |nx.list| ::
current.list[i + 1] == nx.list[i];
// The state looks like: ..., reverse, current, nx, ...
assert current.data == current.list[0];
current.next := reverse;
current.footprint := {current} + reverse.footprint;
current.list := [current.data] + reverse.list;
reverse := current;
current := nx;
}
}
}
|
dafny-exercises_tmp_tmp5mvrowrx_paper_krml190.dfy
|
442
|
442
|
Dafny program: 442
|
// RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// VSComp 2010, problem 1, compute the sum and max of the elements of an array and prove
// that 'sum <= N * max'.
// Rustan Leino, 18 August 2010.
//
// The problem statement gave the pseudo-code for the method, but did not ask to prove
// that 'sum' or 'max' return as the sum and max, respectively, of the array. The
// given assumption that the array's elements are non-negative is not needed to establish
// the requested postcondition.
method M(N: int, a: array<int>) returns (sum: int, max: int)
requires 0 <= N && a.Length == N && (forall k :: 0 <= k && k < N ==> 0 <= a[k]);
ensures sum <= N * max;
{
sum := 0;
max := 0;
var i := 0;
while (i < N)
{
if (max < a[i]) {
max := a[i];
}
sum := sum + a[i];
i := i + 1;
}
}
method Main()
{
var a := new int[10];
a[0] := 9;
a[1] := 5;
a[2] := 0;
a[3] := 2;
a[4] := 7;
a[5] := 3;
a[6] := 2;
a[7] := 1;
a[8] := 10;
a[9] := 6;
var s, m := M(10, a);
print "N = ", a.Length, " sum = ", s, " max = ", m, "\n";
}
|
// RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// VSComp 2010, problem 1, compute the sum and max of the elements of an array and prove
// that 'sum <= N * max'.
// Rustan Leino, 18 August 2010.
//
// The problem statement gave the pseudo-code for the method, but did not ask to prove
// that 'sum' or 'max' return as the sum and max, respectively, of the array. The
// given assumption that the array's elements are non-negative is not needed to establish
// the requested postcondition.
method M(N: int, a: array<int>) returns (sum: int, max: int)
requires 0 <= N && a.Length == N && (forall k :: 0 <= k && k < N ==> 0 <= a[k]);
ensures sum <= N * max;
{
sum := 0;
max := 0;
var i := 0;
while (i < N)
invariant i <= N && sum <= i * max;
{
if (max < a[i]) {
max := a[i];
}
sum := sum + a[i];
i := i + 1;
}
}
method Main()
{
var a := new int[10];
a[0] := 9;
a[1] := 5;
a[2] := 0;
a[3] := 2;
a[4] := 7;
a[5] := 3;
a[6] := 2;
a[7] := 1;
a[8] := 10;
a[9] := 6;
var s, m := M(10, a);
print "N = ", a.Length, " sum = ", s, " max = ", m, "\n";
}
|
dafny-language-server_tmp_tmpkir0kenl_Test_VSComp2010_Problem1-SumMax.dfy
|
443
|
443
|
Dafny program: 443
|
// RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// Spec# and Boogie and Chalice: The program will be
// the same, except that these languages do not check
// for any kind of termination. Also, in Spec#, there
// is an issue of potential overflows.
// Benchmark1
method Add(x: int, y: int) returns (r: int)
ensures r == x+y;
{
r := x;
if (y < 0) {
var n := y;
while (n != 0)
{
r := r - 1;
n := n + 1;
}
} else {
var n := y;
while (n != 0)
{
r := r + 1;
n := n - 1;
}
}
}
method Mul(x: int, y: int) returns (r: int)
ensures r == x*y;
{
if (x == 0) {
r := 0;
} else if (x < 0) {
r := Mul(-x, y);
r := -r;
} else {
r := Mul(x-1, y);
r := Add(r, y);
}
}
// ---------------------------
method Main() {
TestAdd(3, 180);
TestAdd(3, -180);
TestAdd(0, 1);
TestMul(3, 180);
TestMul(3, -180);
TestMul(180, 3);
TestMul(-180, 3);
TestMul(0, 1);
TestMul(1, 0);
}
method TestAdd(x: int, y: int) {
print x, " + ", y, " = ";
var z := Add(x, y);
print z, "\n";
}
method TestMul(x: int, y: int) {
print x, " * ", y, " = ";
var z := Mul(x, y);
print z, "\n";
}
|
// RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// Spec# and Boogie and Chalice: The program will be
// the same, except that these languages do not check
// for any kind of termination. Also, in Spec#, there
// is an issue of potential overflows.
// Benchmark1
method Add(x: int, y: int) returns (r: int)
ensures r == x+y;
{
r := x;
if (y < 0) {
var n := y;
while (n != 0)
invariant r == x+y-n && 0 <= -n;
{
r := r - 1;
n := n + 1;
}
} else {
var n := y;
while (n != 0)
invariant r == x+y-n && 0 <= n;
{
r := r + 1;
n := n - 1;
}
}
}
method Mul(x: int, y: int) returns (r: int)
ensures r == x*y;
decreases x < 0, x;
{
if (x == 0) {
r := 0;
} else if (x < 0) {
r := Mul(-x, y);
r := -r;
} else {
r := Mul(x-1, y);
r := Add(r, y);
}
}
// ---------------------------
method Main() {
TestAdd(3, 180);
TestAdd(3, -180);
TestAdd(0, 1);
TestMul(3, 180);
TestMul(3, -180);
TestMul(180, 3);
TestMul(-180, 3);
TestMul(0, 1);
TestMul(1, 0);
}
method TestAdd(x: int, y: int) {
print x, " + ", y, " = ";
var z := Add(x, y);
print z, "\n";
}
method TestMul(x: int, y: int) {
print x, " * ", y, " = ";
var z := Mul(x, y);
print z, "\n";
}
|
dafny-language-server_tmp_tmpkir0kenl_Test_VSI-Benchmarks_b1.dfy
|
444
|
444
|
Dafny program: 444
|
// RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
class Benchmark2 {
method BinarySearch(a: array<int>, key: int) returns (result: int)
requires forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j];
ensures -1 <= result < a.Length;
ensures 0 <= result ==> a[result] == key;
ensures result == -1 ==> forall i :: 0 <= i < a.Length ==> a[i] != key;
{
var low := 0;
var high := a.Length;
while (low < high)
{
var mid := low + (high - low) / 2;
var midVal := a[mid];
if (midVal < key) {
low := mid + 1;
} else if (key < midVal) {
high := mid;
} else {
result := mid; // key found
return;
}
}
result := -1; // key not present
}
}
method Main() {
var a := new int[5];
a[0] := -4;
a[1] := -2;
a[2] := -2;
a[3] := 0;
a[4] := 25;
TestSearch(a, 4);
TestSearch(a, -8);
TestSearch(a, -2);
TestSearch(a, 0);
TestSearch(a, 23);
TestSearch(a, 25);
TestSearch(a, 27);
}
method TestSearch(a: array<int>, key: int)
requires forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j];
{
var b := new Benchmark2;
var r := b.BinarySearch(a, key);
print "Looking for key=", key, ", result=", r, "\n";
}
|
// RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
class Benchmark2 {
method BinarySearch(a: array<int>, key: int) returns (result: int)
requires forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j];
ensures -1 <= result < a.Length;
ensures 0 <= result ==> a[result] == key;
ensures result == -1 ==> forall i :: 0 <= i < a.Length ==> a[i] != key;
{
var low := 0;
var high := a.Length;
while (low < high)
invariant 0 <= low <= high <= a.Length;
invariant forall i :: 0 <= i < low ==> a[i] < key;
invariant forall i :: high <= i < a.Length ==> key < a[i];
{
var mid := low + (high - low) / 2;
var midVal := a[mid];
if (midVal < key) {
low := mid + 1;
} else if (key < midVal) {
high := mid;
} else {
result := mid; // key found
return;
}
}
result := -1; // key not present
}
}
method Main() {
var a := new int[5];
a[0] := -4;
a[1] := -2;
a[2] := -2;
a[3] := 0;
a[4] := 25;
TestSearch(a, 4);
TestSearch(a, -8);
TestSearch(a, -2);
TestSearch(a, 0);
TestSearch(a, 23);
TestSearch(a, 25);
TestSearch(a, 27);
}
method TestSearch(a: array<int>, key: int)
requires forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j];
{
var b := new Benchmark2;
var r := b.BinarySearch(a, key);
print "Looking for key=", key, ", result=", r, "\n";
}
|
dafny-language-server_tmp_tmpkir0kenl_Test_VSI-Benchmarks_b2.dfy
|
445
|
445
|
Dafny program: 445
|
// RUN: %dafny /verifyAllModules /allocated:1 /compile:0 /print:"%t.print" /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// This test was contributed by Bryan. It has shown some instabilities in the past.
method seqIntoArray<A>(s: seq<A>, a: array<A>, index: nat)
requires index + |s| <= a.Length
modifies a
ensures a[..] == old(a[..index]) + s + old(a[index + |s|..])
{
var i := index;
while i < index + |s|
{
label A:
a[i] := s[i - index];
calc {
a[..];
== // assignment statement above
old@A(a[..])[i := s[i - index]];
== // invariant on entry to loop
(old(a[..index]) + s[..i - index] + old(a[i..]))[i := s[i - index]];
== { assert old(a[..index]) + s[..i - index] + old(a[i..]) == (old(a[..index]) + s[..i - index]) + old(a[i..]); }
((old(a[..index]) + s[..i - index]) + old(a[i..]))[i := s[i - index]];
== { assert |old(a[..index]) + s[..i - index]| == i; }
(old(a[..index]) + s[..i - index]) + old(a[i..])[0 := s[i - index]];
== { assert old(a[i..])[0 := s[i - index]] == [s[i - index]] + old(a[i..])[1..]; }
(old(a[..index]) + s[..i - index]) + [s[i - index]] + old(a[i..])[1..];
== { assert old(a[i..])[1..] == old(a[i + 1..]); }
(old(a[..index]) + s[..i - index]) + [s[i - index]] + old(a[i + 1..]);
== // redistribute +
old(a[..index]) + (s[..i - index] + [s[i - index]]) + old(a[i + 1..]);
== { assert s[..i - index] + [s[i - index]] == s[..i + 1 - index]; }
old(a[..index]) + s[..i + 1 - index] + old(a[i + 1..]);
}
i := i + 1;
}
}
|
// RUN: %dafny /verifyAllModules /allocated:1 /compile:0 /print:"%t.print" /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// This test was contributed by Bryan. It has shown some instabilities in the past.
method seqIntoArray<A>(s: seq<A>, a: array<A>, index: nat)
requires index + |s| <= a.Length
modifies a
ensures a[..] == old(a[..index]) + s + old(a[index + |s|..])
{
var i := index;
while i < index + |s|
invariant index <= i <= index + |s| <= a.Length
invariant a[..] == old(a[..index]) + s[..i - index] + old(a[i..])
{
label A:
a[i] := s[i - index];
calc {
a[..];
== // assignment statement above
old@A(a[..])[i := s[i - index]];
== // invariant on entry to loop
(old(a[..index]) + s[..i - index] + old(a[i..]))[i := s[i - index]];
== { assert old(a[..index]) + s[..i - index] + old(a[i..]) == (old(a[..index]) + s[..i - index]) + old(a[i..]); }
((old(a[..index]) + s[..i - index]) + old(a[i..]))[i := s[i - index]];
== { assert |old(a[..index]) + s[..i - index]| == i; }
(old(a[..index]) + s[..i - index]) + old(a[i..])[0 := s[i - index]];
== { assert old(a[i..])[0 := s[i - index]] == [s[i - index]] + old(a[i..])[1..]; }
(old(a[..index]) + s[..i - index]) + [s[i - index]] + old(a[i..])[1..];
== { assert old(a[i..])[1..] == old(a[i + 1..]); }
(old(a[..index]) + s[..i - index]) + [s[i - index]] + old(a[i + 1..]);
== // redistribute +
old(a[..index]) + (s[..i - index] + [s[i - index]]) + old(a[i + 1..]);
== { assert s[..i - index] + [s[i - index]] == s[..i + 1 - index]; }
old(a[..index]) + s[..i + 1 - index] + old(a[i + 1..]);
}
i := i + 1;
}
}
|
dafny-language-server_tmp_tmpkir0kenl_Test_allocated1_dafny0_fun-with-slices.dfy
|
446
|
446
|
Dafny program: 446
|
// RUN: %dafny /compile:3 /spillTargetCode:2 /compileTarget:cs "%s" > "%t"
// RUN: %dafny /compile:3 /spillTargetCode:2 /compileTarget:js "%s" >> "%t"
// RUN: %dafny /compile:3 /spillTargetCode:2 /compileTarget:go "%s" >> "%t"
// RUN: %dafny /compile:3 /spillTargetCode:2 /compileTarget:java "%s" >> "%t"
// RUN: %diff "%s.expect" "%t"
method LinearSearch(a: array<int>, key: int) returns (n: nat)
ensures 0 <= n <= a.Length
ensures n == a.Length || a[n] == key
{
n := 0;
while n < a.Length
{
if a[n] == key {
return;
}
n := n + 1;
}
}
method PrintArray<A>(a: array?<A>) {
if (a == null) {
print "It's null\n";
} else {
var i := 0;
while i < a.Length {
print a[i], " ";
i := i + 1;
}
print "\n";
}
}
method Main() {
var a := new int[23];
var i := 0;
while i < 23 {
a[i] := i;
i := i + 1;
}
PrintArray(a);
var n := LinearSearch(a, 17);
print n, "\n";
var s : seq<int> := a[..];
print s, "\n";
s := a[2..16];
print s, "\n";
s := a[20..];
print s, "\n";
s := a[..8];
print s, "\n";
// Conversion to sequence should copy elements (sequences are immutable!)
a[0] := 42;
print s, "\n";
InitTests();
MultipleDimensions();
PrintArray<int>(null);
}
type lowercase = ch | 'a' <= ch <= 'z' witness 'd'
method InitTests() {
var aa := new lowercase[3];
PrintArray(aa);
var s := "hello";
aa := new lowercase[|s|](i requires 0 <= i < |s| => s[i]);
PrintArray(aa);
}
method MultipleDimensions() {
var matrix := new int[2,8];
PrintMatrix(matrix);
matrix := DiagMatrix(3, 5, 0, 1);
PrintMatrix(matrix);
var cube := new int[3,0,4]((_,_,_) => 16);
print "cube dims: ", cube.Length0, " ", cube.Length1, " ", cube.Length2, "\n";
// FIXME: This breaks Java (and has for some time).
//
// var jagged := new array<int>[5];
// var i := 0;
// while i < 5 {
// jagged[i] := new int[i];
// i := i + 1;
// }
// PrintArray(jagged);
}
method DiagMatrix<A>(rows: int, cols: int, zero: A, one: A)
returns (a: array2<A>)
requires rows >= 0 && cols >= 0
{
return new A[rows, cols]((x,y) => if x==y then one else zero);
}
method PrintMatrix<A>(m: array2<A>) {
var i := 0;
while i < m.Length0 {
var j := 0;
while j < m.Length1 {
print m[i,j], " ";
j := j + 1;
}
print "\n";
i := i + 1;
}
}
|
// RUN: %dafny /compile:3 /spillTargetCode:2 /compileTarget:cs "%s" > "%t"
// RUN: %dafny /compile:3 /spillTargetCode:2 /compileTarget:js "%s" >> "%t"
// RUN: %dafny /compile:3 /spillTargetCode:2 /compileTarget:go "%s" >> "%t"
// RUN: %dafny /compile:3 /spillTargetCode:2 /compileTarget:java "%s" >> "%t"
// RUN: %diff "%s.expect" "%t"
method LinearSearch(a: array<int>, key: int) returns (n: nat)
ensures 0 <= n <= a.Length
ensures n == a.Length || a[n] == key
{
n := 0;
while n < a.Length
invariant n <= a.Length
{
if a[n] == key {
return;
}
n := n + 1;
}
}
method PrintArray<A>(a: array?<A>) {
if (a == null) {
print "It's null\n";
} else {
var i := 0;
while i < a.Length {
print a[i], " ";
i := i + 1;
}
print "\n";
}
}
method Main() {
var a := new int[23];
var i := 0;
while i < 23 {
a[i] := i;
i := i + 1;
}
PrintArray(a);
var n := LinearSearch(a, 17);
print n, "\n";
var s : seq<int> := a[..];
print s, "\n";
s := a[2..16];
print s, "\n";
s := a[20..];
print s, "\n";
s := a[..8];
print s, "\n";
// Conversion to sequence should copy elements (sequences are immutable!)
a[0] := 42;
print s, "\n";
InitTests();
MultipleDimensions();
PrintArray<int>(null);
}
type lowercase = ch | 'a' <= ch <= 'z' witness 'd'
method InitTests() {
var aa := new lowercase[3];
PrintArray(aa);
var s := "hello";
aa := new lowercase[|s|](i requires 0 <= i < |s| => s[i]);
PrintArray(aa);
}
method MultipleDimensions() {
var matrix := new int[2,8];
PrintMatrix(matrix);
matrix := DiagMatrix(3, 5, 0, 1);
PrintMatrix(matrix);
var cube := new int[3,0,4]((_,_,_) => 16);
print "cube dims: ", cube.Length0, " ", cube.Length1, " ", cube.Length2, "\n";
// FIXME: This breaks Java (and has for some time).
//
// var jagged := new array<int>[5];
// var i := 0;
// while i < 5 {
// jagged[i] := new int[i];
// i := i + 1;
// }
// PrintArray(jagged);
}
method DiagMatrix<A>(rows: int, cols: int, zero: A, one: A)
returns (a: array2<A>)
requires rows >= 0 && cols >= 0
{
return new A[rows, cols]((x,y) => if x==y then one else zero);
}
method PrintMatrix<A>(m: array2<A>) {
var i := 0;
while i < m.Length0 {
var j := 0;
while j < m.Length1 {
print m[i,j], " ";
j := j + 1;
}
print "\n";
i := i + 1;
}
}
|
dafny-language-server_tmp_tmpkir0kenl_Test_comp_Arrays.dfy
|
449
|
449
|
Dafny program: 449
|
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
method Cubes(a: array<int>)
modifies a
ensures forall i :: 0 <= i < a.Length ==> a[i] == i*i*i
{
var n := 0;
var c := 0;
var k := 1;
var m := 6;
while n < a.Length
{
a[n] := c;
c := c + k;
k := k + m;
m := m + 6;
n := n + 1;
}
}
|
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
method Cubes(a: array<int>)
modifies a
ensures forall i :: 0 <= i < a.Length ==> a[i] == i*i*i
{
var n := 0;
var c := 0;
var k := 1;
var m := 6;
while n < a.Length
invariant 0 <= n <= a.Length
invariant forall i :: 0 <= i < n ==> a[i] == i*i*i
invariant c == n*n*n
invariant k == 3*n*n + 3*n + 1
invariant m == 6*n + 6
{
a[n] := c;
c := c + k;
k := k + m;
m := m + 6;
n := n + 1;
}
}
|
dafny-language-server_tmp_tmpkir0kenl_Test_dafny1_Cubes.dfy
|
450
|
450
|
Dafny program: 450
|
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
class Node {
var nxt: Node?
method ReverseInPlace(x: Node?, r: set<Node>) returns (reverse: Node?)
requires x == null || x in r;
requires (forall y :: y in r ==> y.nxt == null || y.nxt in r); // region closure
modifies r;
ensures reverse == null || reverse in r;
ensures (forall y :: y in r ==> y.nxt == null || y.nxt in r); // region closure
{
var current: Node? := x;
reverse := null;
while (current != null)
{
var tmp := current.nxt;
current.nxt := reverse;
reverse := current;
current := tmp;
}
}
}
|
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
class Node {
var nxt: Node?
method ReverseInPlace(x: Node?, r: set<Node>) returns (reverse: Node?)
requires x == null || x in r;
requires (forall y :: y in r ==> y.nxt == null || y.nxt in r); // region closure
modifies r;
ensures reverse == null || reverse in r;
ensures (forall y :: y in r ==> y.nxt == null || y.nxt in r); // region closure
decreases *;
{
var current: Node? := x;
reverse := null;
while (current != null)
invariant current == null || current in r;
invariant reverse == null || reverse in r;
invariant (forall y :: y in r ==> y.nxt == null || y.nxt in r); // region closure
decreases *; // omit loop termination check
{
var tmp := current.nxt;
current.nxt := reverse;
reverse := current;
current := tmp;
}
}
}
|
dafny-language-server_tmp_tmpkir0kenl_Test_dafny1_ListReverse.dfy
|
451
|
451
|
Dafny program: 451
|
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
method MirrorImage<T>(m: array2<T>)
modifies m
ensures forall i,j :: 0 <= i < m.Length0 && 0 <= j < m.Length1 ==>
m[i,j] == old(m[i, m.Length1-1-j])
{
var a := 0;
while a < m.Length0
m[i,j] == old(m[i, m.Length1-1-j])
m[i,j] == old(m[i,j])
{
var b := 0;
while b < m.Length1 / 2
m[i,j] == old(m[i, m.Length1-1-j])
m[a,j] == old(m[a, m.Length1-1-j]) &&
old(m[a,j]) == m[a, m.Length1-1-j]
m[i,j] == old(m[i,j])
{
m[a, m.Length1-1-b], m[a, b] := m[a, b], m[a, m.Length1-1-b];
b := b + 1;
}
a := a + 1;
}
}
method Flip<T>(m: array2<T>)
requires m.Length0 == m.Length1
modifies m
ensures forall i,j :: 0 <= i < m.Length0 && 0 <= j < m.Length1 ==> m[i,j] == old(m[j,i])
{
var N := m.Length0;
var a := 0;
var b := 1;
while a != N
if i < a || (i == a && j < b)
then m[i,j] == old(m[j,i]) && m[j,i] == old(m[i,j])
else m[i,j] == old(m[i,j]) && m[j,i] == old(m[j,i])
{
if b < N {
m[a,b], m[b,a] := m[b,a], m[a,b];
b := b + 1;
} else {
a := a + 1; b := a + 1;
}
}
}
method Main()
{
var B := new bool[2,5];
B[0,0] := true; B[0,1] := false; B[0,2] := false; B[0,3] := true; B[0,4] := false;
B[1,0] := true; B[1,1] := true; B[1,2] := true; B[1,3] := true; B[1,4] := false;
print "Before:\n";
PrintMatrix(B);
MirrorImage(B);
print "Mirror image:\n";
PrintMatrix(B);
var A := new int[3,3];
A[0,0] := 5; A[0,1] := 7; A[0,2] := 9;
A[1,0] := 6; A[1,1] := 2; A[1,2] := 3;
A[2,0] := 7; A[2,1] := 1; A[2,2] := 0;
print "Before:\n";
PrintMatrix(A);
Flip(A);
print "Flip:\n";
PrintMatrix(A);
}
method PrintMatrix<T>(m: array2<T>)
{
var i := 0;
while i < m.Length0 {
var j := 0;
while j < m.Length1 {
print m[i,j];
j := j + 1;
if j == m.Length1 {
print "\n";
} else {
print ", ";
}
}
i := i + 1;
}
}
|
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
method MirrorImage<T>(m: array2<T>)
modifies m
ensures forall i,j :: 0 <= i < m.Length0 && 0 <= j < m.Length1 ==>
m[i,j] == old(m[i, m.Length1-1-j])
{
var a := 0;
while a < m.Length0
invariant a <= m.Length0
invariant forall i,j :: 0 <= i && i < a && 0 <= j && j < m.Length1 ==>
m[i,j] == old(m[i, m.Length1-1-j])
invariant forall i,j :: a <= i && i < m.Length0 && 0 <= j && j < m.Length1 ==>
m[i,j] == old(m[i,j])
{
var b := 0;
while b < m.Length1 / 2
invariant b <= m.Length1 / 2
invariant forall i,j :: 0 <= i && i < a && 0 <= j && j < m.Length1 ==>
m[i,j] == old(m[i, m.Length1-1-j])
invariant forall j :: 0 <= j && j < b ==>
m[a,j] == old(m[a, m.Length1-1-j]) &&
old(m[a,j]) == m[a, m.Length1-1-j]
invariant forall j :: b <= j && j < m.Length1-b ==> m[a,j] == old(m[a,j])
invariant forall i,j :: a+1 <= i && i < m.Length0 && 0 <= j && j < m.Length1 ==>
m[i,j] == old(m[i,j])
{
m[a, m.Length1-1-b], m[a, b] := m[a, b], m[a, m.Length1-1-b];
b := b + 1;
}
a := a + 1;
}
}
method Flip<T>(m: array2<T>)
requires m.Length0 == m.Length1
modifies m
ensures forall i,j :: 0 <= i < m.Length0 && 0 <= j < m.Length1 ==> m[i,j] == old(m[j,i])
{
var N := m.Length0;
var a := 0;
var b := 1;
while a != N
invariant a < b <= N || (a == N && b == N+1)
invariant forall i,j :: 0 <= i <= j < N ==>
if i < a || (i == a && j < b)
then m[i,j] == old(m[j,i]) && m[j,i] == old(m[i,j])
else m[i,j] == old(m[i,j]) && m[j,i] == old(m[j,i])
decreases N-a, N-b
{
if b < N {
m[a,b], m[b,a] := m[b,a], m[a,b];
b := b + 1;
} else {
a := a + 1; b := a + 1;
}
}
}
method Main()
{
var B := new bool[2,5];
B[0,0] := true; B[0,1] := false; B[0,2] := false; B[0,3] := true; B[0,4] := false;
B[1,0] := true; B[1,1] := true; B[1,2] := true; B[1,3] := true; B[1,4] := false;
print "Before:\n";
PrintMatrix(B);
MirrorImage(B);
print "Mirror image:\n";
PrintMatrix(B);
var A := new int[3,3];
A[0,0] := 5; A[0,1] := 7; A[0,2] := 9;
A[1,0] := 6; A[1,1] := 2; A[1,2] := 3;
A[2,0] := 7; A[2,1] := 1; A[2,2] := 0;
print "Before:\n";
PrintMatrix(A);
Flip(A);
print "Flip:\n";
PrintMatrix(A);
}
method PrintMatrix<T>(m: array2<T>)
{
var i := 0;
while i < m.Length0 {
var j := 0;
while j < m.Length1 {
print m[i,j];
j := j + 1;
if j == m.Length1 {
print "\n";
} else {
print ", ";
}
}
i := i + 1;
}
}
|
dafny-language-server_tmp_tmpkir0kenl_Test_dafny1_MatrixFun.dfy
|
452
|
452
|
Dafny program: 452
|
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
/*
Rustan Leino, 5 Oct 2011
COST Verification Competition, Challenge 1: Maximum in an array
http://foveoos2011.cost-ic0701.org/verification-competition
Given: A non-empty integer array a.
Verify that the index returned by the method max() given below points to
an element maximal in the array.
public class Max {
public static int max(int[] a) {
int x = 0;
int y = a.length-1;
while (x != y) {
if (a[x] <= a[y]) x++;
else y--;
}
return x;
}
}
*/
// Remarks:
// The verification of the loop makes use of a local ghost variable 'm'. To the
// verifier, this variable is like any other, but the Dafny compiler ignores it.
// In other words, ghost variables and ghost assignments (and specifications,
// for that matter) are included in the program just for the purpose of reasoning
// about the program, and they play no role at run time.
// The only thing that needs to be human-trusted about this program is the
// specification of 'max' (and, since verification challenge asked to prove
// something about a particular piece of code, that the body of 'max', minus
// the ghost constructs, is really that code).
// About Dafny:
// As always (when it is successful), Dafny verifies that the program does not
// cause any run-time errors (like array index bounds errors), that the program
// terminates, that expressions and functions are well defined, and that all
// specifications are satisfied. The language prevents type errors by being type
// safe, prevents dangling pointers by not having an "address-of" or "deallocate"
// operation (which is accommodated at run time by a garbage collector), and
// prevents arithmetic overflow errors by using mathematical integers (which
// is accommodated at run time by using BigNum's). By proving that programs
// terminate, Dafny proves that a program's time usage is finite, which implies
// that the program's space usage is finite too. However, executing the
// program may fall short of your hopes if you don't have enough time or
// space; that is, the program may run out of space or may fail to terminate in
// your lifetime, because Dafny does not prove that the time or space needed by
// the program matches your execution environment. The only input fed to
// the Dafny verifier/compiler is the program text below; Dafny then automatically
// verifies and compiles the program (for this program in less than 2 seconds)
// without further human intervention.
method max(a: array<int>) returns (x: int)
requires a.Length != 0
ensures 0 <= x < a.Length
ensures forall i :: 0 <= i < a.Length ==> a[i] <= a[x]
{
x := 0;
var y := a.Length - 1;
ghost var m := y;
while x != y
{
if a[x] <= a[y] {
x := x + 1; m := y;
} else {
y := y - 1; m := x;
}
}
return x;
}
|
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
/*
Rustan Leino, 5 Oct 2011
COST Verification Competition, Challenge 1: Maximum in an array
http://foveoos2011.cost-ic0701.org/verification-competition
Given: A non-empty integer array a.
Verify that the index returned by the method max() given below points to
an element maximal in the array.
public class Max {
public static int max(int[] a) {
int x = 0;
int y = a.length-1;
while (x != y) {
if (a[x] <= a[y]) x++;
else y--;
}
return x;
}
}
*/
// Remarks:
// The verification of the loop makes use of a local ghost variable 'm'. To the
// verifier, this variable is like any other, but the Dafny compiler ignores it.
// In other words, ghost variables and ghost assignments (and specifications,
// for that matter) are included in the program just for the purpose of reasoning
// about the program, and they play no role at run time.
// The only thing that needs to be human-trusted about this program is the
// specification of 'max' (and, since verification challenge asked to prove
// something about a particular piece of code, that the body of 'max', minus
// the ghost constructs, is really that code).
// About Dafny:
// As always (when it is successful), Dafny verifies that the program does not
// cause any run-time errors (like array index bounds errors), that the program
// terminates, that expressions and functions are well defined, and that all
// specifications are satisfied. The language prevents type errors by being type
// safe, prevents dangling pointers by not having an "address-of" or "deallocate"
// operation (which is accommodated at run time by a garbage collector), and
// prevents arithmetic overflow errors by using mathematical integers (which
// is accommodated at run time by using BigNum's). By proving that programs
// terminate, Dafny proves that a program's time usage is finite, which implies
// that the program's space usage is finite too. However, executing the
// program may fall short of your hopes if you don't have enough time or
// space; that is, the program may run out of space or may fail to terminate in
// your lifetime, because Dafny does not prove that the time or space needed by
// the program matches your execution environment. The only input fed to
// the Dafny verifier/compiler is the program text below; Dafny then automatically
// verifies and compiles the program (for this program in less than 2 seconds)
// without further human intervention.
method max(a: array<int>) returns (x: int)
requires a.Length != 0
ensures 0 <= x < a.Length
ensures forall i :: 0 <= i < a.Length ==> a[i] <= a[x]
{
x := 0;
var y := a.Length - 1;
ghost var m := y;
while x != y
invariant 0 <= x <= y < a.Length
invariant m == x || m == y
invariant forall i :: 0 <= i < x ==> a[i] <= a[m]
invariant forall i :: y < i < a.Length ==> a[i] <= a[m]
{
if a[x] <= a[y] {
x := x + 1; m := y;
} else {
y := y - 1; m := x;
}
}
return x;
}
|
dafny-language-server_tmp_tmpkir0kenl_Test_dafny2_COST-verif-comp-2011-1-MaxArray.dfy
|
453
|
453
|
Dafny program: 453
|
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// The RoundDown and RoundUp methods in this file are the ones in the Boogie
// implementation Source/AbsInt/IntervalDomain.cs.
class Rounding {
var thresholds: array<int>
function Valid(): bool
reads this, thresholds
{
forall m,n :: 0 <= m < n < thresholds.Length ==> thresholds[m] <= thresholds[n]
}
method RoundDown(k: int) returns (r: int)
requires Valid()
ensures -1 <= r < thresholds.Length
ensures forall m :: r < m < thresholds.Length ==> k < thresholds[m]
ensures 0 <= r ==> thresholds[r] <= k
{
if (thresholds.Length == 0 || k < thresholds[0]) {
return -1;
}
var i, j := 0, thresholds.Length - 1;
while (i < j)
{
var mid := i + (j - i + 1) / 2;
if (thresholds[mid] <= k) {
i := mid;
} else {
j := mid - 1;
}
}
return i;
}
method RoundUp(k: int) returns (r: int)
requires Valid()
ensures 0 <= r <= thresholds.Length
ensures forall m :: 0 <= m < r ==> thresholds[m] < k
ensures r < thresholds.Length ==> k <= thresholds[r]
{
if (thresholds.Length == 0 || thresholds[thresholds.Length-1] < k) {
return thresholds.Length;
}
var i, j := 0, thresholds.Length - 1;
while (i < j)
{
var mid := i + (j - i) / 2;
if (thresholds[mid] < k) {
i := mid + 1;
} else {
j := mid;
}
}
return i;
}
}
|
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// The RoundDown and RoundUp methods in this file are the ones in the Boogie
// implementation Source/AbsInt/IntervalDomain.cs.
class Rounding {
var thresholds: array<int>
function Valid(): bool
reads this, thresholds
{
forall m,n :: 0 <= m < n < thresholds.Length ==> thresholds[m] <= thresholds[n]
}
method RoundDown(k: int) returns (r: int)
requires Valid()
ensures -1 <= r < thresholds.Length
ensures forall m :: r < m < thresholds.Length ==> k < thresholds[m]
ensures 0 <= r ==> thresholds[r] <= k
{
if (thresholds.Length == 0 || k < thresholds[0]) {
return -1;
}
var i, j := 0, thresholds.Length - 1;
while (i < j)
invariant 0 <= i <= j < thresholds.Length
invariant thresholds[i] <= k
invariant forall m :: j < m < thresholds.Length ==> k < thresholds[m]
{
var mid := i + (j - i + 1) / 2;
assert i < mid <= j;
if (thresholds[mid] <= k) {
i := mid;
} else {
j := mid - 1;
}
}
return i;
}
method RoundUp(k: int) returns (r: int)
requires Valid()
ensures 0 <= r <= thresholds.Length
ensures forall m :: 0 <= m < r ==> thresholds[m] < k
ensures r < thresholds.Length ==> k <= thresholds[r]
{
if (thresholds.Length == 0 || thresholds[thresholds.Length-1] < k) {
return thresholds.Length;
}
var i, j := 0, thresholds.Length - 1;
while (i < j)
invariant 0 <= i <= j < thresholds.Length
invariant k <= thresholds[j]
invariant forall m :: 0 <= m < i ==> thresholds[m] < k
{
var mid := i + (j - i) / 2;
assert i <= mid < j;
if (thresholds[mid] < k) {
i := mid + 1;
} else {
j := mid;
}
}
return i;
}
}
|
dafny-language-server_tmp_tmpkir0kenl_Test_dafny2_Intervals.dfy
|
454
|
454
|
Dafny program: 454
|
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
function Sum(a: seq<int>, s: int, t: int): int
requires 0 <= s <= t <= |a|
{
if s == t then 0 else Sum(a, s, t-1) + a[t-1]
}
method MaxSegSum(a: seq<int>) returns (k: int, m: int)
ensures 0 <= k <= m <= |a|
ensures forall p,q :: 0 <= p <= q <= |a| ==> Sum(a, p, q) <= Sum(a, k, m)
{
k, m := 0, 0;
var s := 0; // invariant s == Sum(a, k, m)
var n := 0;
var c, t := 0, 0; // invariant t == Sum(a, c, n)
while n < |a|
{
t, n := t + a[n], n + 1;
if t < 0 {
c, t := n, 0;
} else if s < t {
k, m, s := c, n, t;
}
}
}
|
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
function Sum(a: seq<int>, s: int, t: int): int
requires 0 <= s <= t <= |a|
{
if s == t then 0 else Sum(a, s, t-1) + a[t-1]
}
method MaxSegSum(a: seq<int>) returns (k: int, m: int)
ensures 0 <= k <= m <= |a|
ensures forall p,q :: 0 <= p <= q <= |a| ==> Sum(a, p, q) <= Sum(a, k, m)
{
k, m := 0, 0;
var s := 0; // invariant s == Sum(a, k, m)
var n := 0;
var c, t := 0, 0; // invariant t == Sum(a, c, n)
while n < |a|
invariant 0 <= c <= n <= |a| && t == Sum(a, c, n)
invariant forall b :: 0 <= b <= n ==> Sum(a, b, n) <= Sum(a, c, n)
invariant 0 <= k <= m <= n && s == Sum(a, k, m)
invariant forall p,q :: 0 <= p <= q <= n ==> Sum(a, p, q) <= Sum(a, k, m)
{
t, n := t + a[n], n + 1;
if t < 0 {
c, t := n, 0;
} else if s < t {
k, m, s := c, n, t;
}
}
}
|
dafny-language-server_tmp_tmpkir0kenl_Test_dafny2_SegmentSum.dfy
|
455
|
455
|
Dafny program: 455
|
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
class Node {
var left: Node?
var right: Node?
var parent: Node?
var anc: set<Node>
var desc: set<Node>
var sense: bool
var pc: int
predicate validDown()
reads this, desc
{
this !in desc &&
left != right && // not needed, but speeds up verification
(right != null ==> right in desc && left !in right.desc) &&
(left != null ==>
left in desc &&
(right != null ==> desc == {left,right} + left.desc + right.desc) &&
(right == null ==> desc == {left} + left.desc) &&
left.validDown()) &&
(left == null ==>
(right != null ==> desc == {right} + right.desc) &&
(right == null ==> desc == {})) &&
(right != null ==> right.validDown()) &&
(blocked() ==> forall m :: m in desc ==> m.blocked()) &&
(after() ==> forall m :: m in desc ==> m.blocked() || m.after())
// (left != null && right != null ==> left.desc !! right.desc) // not needed
}
predicate validUp()
reads this, anc
{
this !in anc &&
(parent != null ==> parent in anc && anc == { parent } + parent.anc && parent.validUp()) &&
(parent == null ==> anc == {}) &&
(after() ==> forall m :: m in anc ==> m.after())
}
predicate valid()
reads this, desc, anc
{ validUp() && validDown() && desc !! anc }
predicate before()
reads this
{ !sense && pc <= 2 }
predicate blocked()
reads this
{ sense }
predicate after()
reads this
{ !sense && 3 <= pc }
method barrier()
requires valid()
requires before()
modifies this, left, right
{
//A
pc := 1;
if(left != null) {
while(!left.sense)
modifies left
{
// this loop body is supposed to model what the "left" thread
// might do to its node. This body models a transition from
// "before" to "blocked" by setting sense to true. A transition
// all the way to "after" is not permitted; this would require
// a change of pc.
// We assume that "left" preserves the validity of its subtree,
// which means in particular that it goes to "blocked" only if
// all its descendants are already blocked.
left.sense := *;
assume left.blocked() ==> forall m :: m in left.desc ==> m.blocked();
}
}
if(right != null) {
while(!right.sense)
modifies right
{
// analogous to the previous loop
right.sense := *;
assume right.blocked() ==> forall m :: m in right.desc ==> m.blocked();
}
}
//B
pc := 2;
if(parent != null) {
sense := true;
}
//C
pc := 3;
while(sense)
modifies this
{
// this loop body is supposed to model what the "parent" thread
// might do to its node. The body models a transition from
// "blocked" to "after" by setting sense to false.
// We assume that "parent" initiates this transition only
// after it went to state "after" itself.
sense := *;
assume !sense ==> parent.after();
}
//D
pc := 4;
if(left != null) {
left.sense := false;
}
//E
pc := 5;
if(right != null) {
right.sense := false;
}
//F
pc := 6;
}
}
|
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
class Node {
var left: Node?
var right: Node?
var parent: Node?
var anc: set<Node>
var desc: set<Node>
var sense: bool
var pc: int
predicate validDown()
reads this, desc
{
this !in desc &&
left != right && // not needed, but speeds up verification
(right != null ==> right in desc && left !in right.desc) &&
(left != null ==>
left in desc &&
(right != null ==> desc == {left,right} + left.desc + right.desc) &&
(right == null ==> desc == {left} + left.desc) &&
left.validDown()) &&
(left == null ==>
(right != null ==> desc == {right} + right.desc) &&
(right == null ==> desc == {})) &&
(right != null ==> right.validDown()) &&
(blocked() ==> forall m :: m in desc ==> m.blocked()) &&
(after() ==> forall m :: m in desc ==> m.blocked() || m.after())
// (left != null && right != null ==> left.desc !! right.desc) // not needed
}
predicate validUp()
reads this, anc
{
this !in anc &&
(parent != null ==> parent in anc && anc == { parent } + parent.anc && parent.validUp()) &&
(parent == null ==> anc == {}) &&
(after() ==> forall m :: m in anc ==> m.after())
}
predicate valid()
reads this, desc, anc
{ validUp() && validDown() && desc !! anc }
predicate before()
reads this
{ !sense && pc <= 2 }
predicate blocked()
reads this
{ sense }
predicate after()
reads this
{ !sense && 3 <= pc }
method barrier()
requires valid()
requires before()
modifies this, left, right
decreases * // allow the method to not terminate
{
//A
pc := 1;
if(left != null) {
while(!left.sense)
modifies left
invariant validDown() // this seems necessary to get the necessary unfolding of functions
invariant valid()
decreases * // to by-pass termination checking for this loop
{
// this loop body is supposed to model what the "left" thread
// might do to its node. This body models a transition from
// "before" to "blocked" by setting sense to true. A transition
// all the way to "after" is not permitted; this would require
// a change of pc.
// We assume that "left" preserves the validity of its subtree,
// which means in particular that it goes to "blocked" only if
// all its descendants are already blocked.
left.sense := *;
assume left.blocked() ==> forall m :: m in left.desc ==> m.blocked();
}
}
if(right != null) {
while(!right.sense)
modifies right
invariant validDown() // this seems necessary to get the necessary unfolding of functions
invariant valid()
decreases * // to by-pass termination checking for this loop
{
// analogous to the previous loop
right.sense := *;
assume right.blocked() ==> forall m :: m in right.desc ==> m.blocked();
}
}
//B
pc := 2;
if(parent != null) {
sense := true;
}
//C
pc := 3;
while(sense)
modifies this
invariant validUp() // this seems necessary to get the necessary unfolding of functions
invariant valid()
invariant left == old(left)
invariant right == old(right)
invariant sense ==> parent != null
decreases * // to by-pass termination checking for this loop
{
// this loop body is supposed to model what the "parent" thread
// might do to its node. The body models a transition from
// "blocked" to "after" by setting sense to false.
// We assume that "parent" initiates this transition only
// after it went to state "after" itself.
sense := *;
assume !sense ==> parent.after();
}
//D
pc := 4;
if(left != null) {
left.sense := false;
}
//E
pc := 5;
if(right != null) {
right.sense := false;
}
//F
pc := 6;
}
}
|
dafny-language-server_tmp_tmpkir0kenl_Test_dafny2_TreeBarrier.dfy
|
456
|
456
|
Dafny program: 456
|
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
function Factorial(n: nat): nat
{
if n == 0 then 1 else n * Factorial(n-1)
}
method ComputeFactorial(n: int) returns (u: int)
requires 1 <= n;
ensures u == Factorial(n);
{
var r := 1;
u := 1;
while (r < n)
{
var v, s := u, 1;
while (s < r + 1)
{
u := u + v;
s := s + 1;
}
r := r + 1;
}
}
|
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
function Factorial(n: nat): nat
{
if n == 0 then 1 else n * Factorial(n-1)
}
method ComputeFactorial(n: int) returns (u: int)
requires 1 <= n;
ensures u == Factorial(n);
{
var r := 1;
u := 1;
while (r < n)
invariant r <= n;
invariant u == Factorial(r);
{
var v, s := u, 1;
while (s < r + 1)
invariant s <= r + 1;
invariant v == Factorial(r) && u == s * Factorial(r);
{
u := u + v;
s := s + 1;
}
r := r + 1;
}
}
|
dafny-language-server_tmp_tmpkir0kenl_Test_dafny2_TuringFactorial.dfy
|
457
|
457
|
Dafny program: 457
|
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// A definition of a co-inductive datatype Stream, whose values are possibly
// infinite lists.
codatatype Stream<T> = SNil | SCons(head: T, tail: Stream<T>)
/*
A function that returns a stream consisting of all integers upwards of n.
The self-call sits in a productive position and is therefore not subject to
termination checks. The Dafny compiler turns this co-recursive call into a
lazily evaluated call, evaluated at the time during the program execution
when the SCons is destructed (if ever).
*/
function Up(n: int): Stream<int>
{
SCons(n, Up(n+1))
}
/*
A function that returns a stream consisting of all multiples
of 5 upwards of n. Note that the first self-call sits in a
productive position and is thus co-recursive. The second self-call
is not in a productive position and therefore it is subject to
termination checking; in particular, each recursive call must
decrease the specific variant function.
*/
function FivesUp(n: int): Stream<int>
{
if n % 5 == 0 then SCons(n, FivesUp(n+1))
else FivesUp(n+1)
}
// A co-predicate that holds for those integer streams where every value is greater than 0.
copredicate Pos(s: Stream<int>)
{
match s
case SNil => true
case SCons(x, rest) => x > 0 && Pos(rest)
}
// SAppend looks almost exactly like Append, but cannot have 'decreases'
// clause, as it is possible it will never terminate.
function SAppend(xs: Stream, ys: Stream): Stream
{
match xs
case SNil => ys
case SCons(x, rest) => SCons(x, SAppend(rest, ys))
}
/*
Example: associativity of append on streams.
The first method proves that append is associative when we consider first
\S{k} elements of the resulting streams. Equality is treated as any other
recursive co-predicate, and has it k-th unfolding denoted as ==#[k].
The second method invokes the first one for all ks, which lets us prove the
postcondition (by (F_=)). Interestingly, in the SNil case in the first
method, we actually prove ==, but by (F_=) applied in the opposite direction
we also get ==#[k].
*/
lemma {:induction false} SAppendIsAssociativeK(k:nat, a:Stream, b:Stream, c:Stream)
ensures SAppend(SAppend(a, b), c) ==#[k] SAppend(a, SAppend(b, c));
{
match (a) {
case SNil =>
case SCons(h, t) => if (k > 0) { SAppendIsAssociativeK(k - 1, t, b, c); }
}
}
lemma SAppendIsAssociative(a:Stream, b:Stream, c:Stream)
ensures SAppend(SAppend(a, b), c) == SAppend(a, SAppend(b, c));
{
forall k:nat { SAppendIsAssociativeK(k, a, b, c); }
// assert for clarity only, postcondition follows directly from it
}
// Equivalent proof using the colemma syntax.
colemma {:induction false} SAppendIsAssociativeC(a:Stream, b:Stream, c:Stream)
ensures SAppend(SAppend(a, b), c) == SAppend(a, SAppend(b, c));
{
match (a) {
case SNil =>
case SCons(h, t) => SAppendIsAssociativeC(t, b, c);
}
}
// In fact the proof can be fully automatic.
colemma SAppendIsAssociative_Auto(a:Stream, b:Stream, c:Stream)
ensures SAppend(SAppend(a, b), c) == SAppend(a, SAppend(b, c));
{
}
colemma {:induction false} UpPos(n:int)
requires n > 0;
ensures Pos(Up(n));
{
UpPos(n+1);
}
colemma UpPos_Auto(n:int)
requires n > 0;
ensures Pos(Up(n));
{
}
// This does induction and coinduction in the same proof.
colemma {:induction false} FivesUpPos(n:int)
requires n > 0;
ensures Pos(FivesUp(n));
{
if (n % 5 == 0) {
FivesUpPos#[_k - 1](n + 1);
} else {
FivesUpPos#[_k](n + 1);
}
}
// Again, Dafny can just employ induction tactic and do it automatically.
// The only hint required is the decrease clause.
colemma FivesUpPos_Auto(n:int)
requires n > 0;
ensures Pos(FivesUp(n));
{
}
|
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// A definition of a co-inductive datatype Stream, whose values are possibly
// infinite lists.
codatatype Stream<T> = SNil | SCons(head: T, tail: Stream<T>)
/*
A function that returns a stream consisting of all integers upwards of n.
The self-call sits in a productive position and is therefore not subject to
termination checks. The Dafny compiler turns this co-recursive call into a
lazily evaluated call, evaluated at the time during the program execution
when the SCons is destructed (if ever).
*/
function Up(n: int): Stream<int>
{
SCons(n, Up(n+1))
}
/*
A function that returns a stream consisting of all multiples
of 5 upwards of n. Note that the first self-call sits in a
productive position and is thus co-recursive. The second self-call
is not in a productive position and therefore it is subject to
termination checking; in particular, each recursive call must
decrease the specific variant function.
*/
function FivesUp(n: int): Stream<int>
decreases 4 - (n-1) % 5;
{
if n % 5 == 0 then SCons(n, FivesUp(n+1))
else FivesUp(n+1)
}
// A co-predicate that holds for those integer streams where every value is greater than 0.
copredicate Pos(s: Stream<int>)
{
match s
case SNil => true
case SCons(x, rest) => x > 0 && Pos(rest)
}
// SAppend looks almost exactly like Append, but cannot have 'decreases'
// clause, as it is possible it will never terminate.
function SAppend(xs: Stream, ys: Stream): Stream
{
match xs
case SNil => ys
case SCons(x, rest) => SCons(x, SAppend(rest, ys))
}
/*
Example: associativity of append on streams.
The first method proves that append is associative when we consider first
\S{k} elements of the resulting streams. Equality is treated as any other
recursive co-predicate, and has it k-th unfolding denoted as ==#[k].
The second method invokes the first one for all ks, which lets us prove the
assertion (included for clarity only). The assertion implies the
postcondition (by (F_=)). Interestingly, in the SNil case in the first
method, we actually prove ==, but by (F_=) applied in the opposite direction
we also get ==#[k].
*/
lemma {:induction false} SAppendIsAssociativeK(k:nat, a:Stream, b:Stream, c:Stream)
ensures SAppend(SAppend(a, b), c) ==#[k] SAppend(a, SAppend(b, c));
decreases k;
{
match (a) {
case SNil =>
case SCons(h, t) => if (k > 0) { SAppendIsAssociativeK(k - 1, t, b, c); }
}
}
lemma SAppendIsAssociative(a:Stream, b:Stream, c:Stream)
ensures SAppend(SAppend(a, b), c) == SAppend(a, SAppend(b, c));
{
forall k:nat { SAppendIsAssociativeK(k, a, b, c); }
// assert for clarity only, postcondition follows directly from it
assert (forall k:nat {:autotriggers false} :: SAppend(SAppend(a, b), c) ==#[k] SAppend(a, SAppend(b, c))); //FIXME: Should Dafny generate a trigger here? If so then which one?
}
// Equivalent proof using the colemma syntax.
colemma {:induction false} SAppendIsAssociativeC(a:Stream, b:Stream, c:Stream)
ensures SAppend(SAppend(a, b), c) == SAppend(a, SAppend(b, c));
{
match (a) {
case SNil =>
case SCons(h, t) => SAppendIsAssociativeC(t, b, c);
}
}
// In fact the proof can be fully automatic.
colemma SAppendIsAssociative_Auto(a:Stream, b:Stream, c:Stream)
ensures SAppend(SAppend(a, b), c) == SAppend(a, SAppend(b, c));
{
}
colemma {:induction false} UpPos(n:int)
requires n > 0;
ensures Pos(Up(n));
{
UpPos(n+1);
}
colemma UpPos_Auto(n:int)
requires n > 0;
ensures Pos(Up(n));
{
}
// This does induction and coinduction in the same proof.
colemma {:induction false} FivesUpPos(n:int)
requires n > 0;
ensures Pos(FivesUp(n));
decreases 4 - (n-1) % 5;
{
if (n % 5 == 0) {
FivesUpPos#[_k - 1](n + 1);
} else {
FivesUpPos#[_k](n + 1);
}
}
// Again, Dafny can just employ induction tactic and do it automatically.
// The only hint required is the decrease clause.
colemma FivesUpPos_Auto(n:int)
requires n > 0;
ensures Pos(FivesUp(n));
decreases 4 - (n-1) % 5;
{
}
|
dafny-language-server_tmp_tmpkir0kenl_Test_dafny3_InductionVsCoinduction.dfy
|
462
|
462
|
Dafny program: 462
|
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// A Dafny rendition of an F* version of QuickSort (included at the bottom of this file).
// Unlike the F* version, Dafny also proves termination and does not use any axioms. However,
// Dafny needs help with a couple of lemmas in places where F* does not need them.
// Comments below show differences between the F* and Dafny versions.
datatype List<T> = Nil | Cons(T, List)
function length(list: List): nat // for termination proof
{
match list
case Nil => 0
case Cons(_, tl) => 1 + length(tl)
}
// In(x, list) returns the number of occurrences of x in list
function In(x: int, list: List<int>): nat
{
match list
case Nil => 0
case Cons(y, tl) => (if x == y then 1 else 0) + In(x, tl)
}
predicate SortedRange(m: int, n: int, list: List<int>)
{
match list
case Nil => m <= n
case Cons(hd, tl) => m <= hd <= n && SortedRange(hd, n, tl)
}
function append(n0: int, n1: int, n2: int, n3: int, i: List<int>, j: List<int>): List<int>
requires n0 <= n1 <= n2 <= n3
requires SortedRange(n0, n1, i) && SortedRange(n2, n3, j)
ensures SortedRange(n0, n3, append(n0, n1, n2, n3, i, j))
ensures forall x :: In(x, append(n0, n1, n2, n3, i, j)) == In(x, i) + In(x, j)
{
match i
case Nil => j
case Cons(hd, tl) => Cons(hd, append(hd, n1, n2, n3, tl, j))
}
function partition(x: int, l: List<int>): (List<int>, List<int>)
ensures var (lo, hi) := partition(x, l);
(forall y :: In(y, lo) == if y <= x then In(y, l) else 0) &&
(forall y :: In(y, hi) == if x < y then In(y, l) else 0) &&
length(l) == length(lo) + length(hi) // for termination proof
{
match l
case Nil => (Nil, Nil)
case Cons(hd, tl) =>
var (lo, hi) := partition(x, tl);
if hd <= x then
(Cons(hd, lo), hi)
else
(lo, Cons(hd, hi))
}
function sort(min: int, max: int, i: List<int>): List<int>
requires min <= max
requires forall x :: In(x, i) != 0 ==> min <= x <= max
ensures SortedRange(min, max, sort(min, max, i))
ensures forall x :: In(x, i) == In(x, sort(min, max, i))
{
match i
case Nil => Nil
case Cons(hd, tl) =>
var (lo, hi) := partition(hd, tl);
var i' := sort(min, hd, lo);
var j' := sort(hd, max, hi);
append(min, hd, hd, max, i', Cons(hd, j'))
}
/*
module Sort
type SortedRange : int => int => list int => E
assume Nil_Sorted : forall (n:int) (m:int). n <= m <==> SortedRange n m []
assume Cons_Sorted: forall (n:int) (m:int) (hd:int) (tl:list int).
SortedRange hd m tl && (n <= hd) && (hd <= m)
<==> SortedRange n m (hd::tl)
val append: n1:int -> n2:int{n1 <= n2} -> n3:int{n2 <= n3} -> n4:int{n3 <= n4}
-> i:list int{SortedRange n1 n2 i}
-> j:list int{SortedRange n3 n4 j}
-> k:list int{SortedRange n1 n4 k
/\ (forall x. In x k <==> In x i \/ In x j)}
let rec append n1 n2 n3 n4 i j = match i with
| [] ->
(match j with
| [] -> j
| _::_ -> j)
| hd::tl -> hd::(append hd n2 n3 n4 tl j)
val partition: x:int
-> l:list int
-> (lo:list int
* hi:list int{(forall y. In y lo ==> y <= x /\ In y l)
/\ (forall y. In y hi ==> x < y /\ In y l)
/\ (forall y. In y l ==> In y lo \/ In y hi)})
let rec partition x l = match l with
| [] -> ([], [])
| hd::tl ->
let lo, hi = partition x tl in
if hd <= x
then (hd::lo, hi)
else (lo, hd::hi)
val sort: min:int
-> max:int{min <= max}
-> i:list int {forall x. In x i ==> (min <= x /\ x <= max)}
-> j:list int{SortedRange min max j /\ (forall x. In x i <==> In x j)}
let rec sort min max i = match i with
| [] -> []
| hd::tl ->
let lo,hi = partition hd tl in
let i' = sort min hd lo in
let j' = sort hd max hi in
append min hd hd max i' (hd::j')
*/
|
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// A Dafny rendition of an F* version of QuickSort (included at the bottom of this file).
// Unlike the F* version, Dafny also proves termination and does not use any axioms. However,
// Dafny needs help with a couple of lemmas in places where F* does not need them.
// Comments below show differences between the F* and Dafny versions.
datatype List<T> = Nil | Cons(T, List)
function length(list: List): nat // for termination proof
{
match list
case Nil => 0
case Cons(_, tl) => 1 + length(tl)
}
// In(x, list) returns the number of occurrences of x in list
function In(x: int, list: List<int>): nat
{
match list
case Nil => 0
case Cons(y, tl) => (if x == y then 1 else 0) + In(x, tl)
}
predicate SortedRange(m: int, n: int, list: List<int>)
decreases list // for termination proof
{
match list
case Nil => m <= n
case Cons(hd, tl) => m <= hd <= n && SortedRange(hd, n, tl)
}
function append(n0: int, n1: int, n2: int, n3: int, i: List<int>, j: List<int>): List<int>
requires n0 <= n1 <= n2 <= n3
requires SortedRange(n0, n1, i) && SortedRange(n2, n3, j)
ensures SortedRange(n0, n3, append(n0, n1, n2, n3, i, j))
ensures forall x :: In(x, append(n0, n1, n2, n3, i, j)) == In(x, i) + In(x, j)
decreases i // for termination proof
{
match i
case Nil => j
case Cons(hd, tl) => Cons(hd, append(hd, n1, n2, n3, tl, j))
}
function partition(x: int, l: List<int>): (List<int>, List<int>)
ensures var (lo, hi) := partition(x, l);
(forall y :: In(y, lo) == if y <= x then In(y, l) else 0) &&
(forall y :: In(y, hi) == if x < y then In(y, l) else 0) &&
length(l) == length(lo) + length(hi) // for termination proof
{
match l
case Nil => (Nil, Nil)
case Cons(hd, tl) =>
var (lo, hi) := partition(x, tl);
if hd <= x then
(Cons(hd, lo), hi)
else
(lo, Cons(hd, hi))
}
function sort(min: int, max: int, i: List<int>): List<int>
requires min <= max
requires forall x :: In(x, i) != 0 ==> min <= x <= max
ensures SortedRange(min, max, sort(min, max, i))
ensures forall x :: In(x, i) == In(x, sort(min, max, i))
decreases length(i) // for termination proof
{
match i
case Nil => Nil
case Cons(hd, tl) =>
assert In(hd, i) != 0; // this proof line not needed in F*
var (lo, hi) := partition(hd, tl);
assert forall y :: In(y, lo) <= In(y, i); // this proof line not needed in F*
var i' := sort(min, hd, lo);
var j' := sort(hd, max, hi);
append(min, hd, hd, max, i', Cons(hd, j'))
}
/*
module Sort
type SortedRange : int => int => list int => E
assume Nil_Sorted : forall (n:int) (m:int). n <= m <==> SortedRange n m []
assume Cons_Sorted: forall (n:int) (m:int) (hd:int) (tl:list int).
SortedRange hd m tl && (n <= hd) && (hd <= m)
<==> SortedRange n m (hd::tl)
val append: n1:int -> n2:int{n1 <= n2} -> n3:int{n2 <= n3} -> n4:int{n3 <= n4}
-> i:list int{SortedRange n1 n2 i}
-> j:list int{SortedRange n3 n4 j}
-> k:list int{SortedRange n1 n4 k
/\ (forall x. In x k <==> In x i \/ In x j)}
let rec append n1 n2 n3 n4 i j = match i with
| [] ->
(match j with
| [] -> j
| _::_ -> j)
| hd::tl -> hd::(append hd n2 n3 n4 tl j)
val partition: x:int
-> l:list int
-> (lo:list int
* hi:list int{(forall y. In y lo ==> y <= x /\ In y l)
/\ (forall y. In y hi ==> x < y /\ In y l)
/\ (forall y. In y l ==> In y lo \/ In y hi)})
let rec partition x l = match l with
| [] -> ([], [])
| hd::tl ->
let lo, hi = partition x tl in
if hd <= x
then (hd::lo, hi)
else (lo, hd::hi)
val sort: min:int
-> max:int{min <= max}
-> i:list int {forall x. In x i ==> (min <= x /\ x <= max)}
-> j:list int{SortedRange min max j /\ (forall x. In x i <==> In x j)}
let rec sort min max i = match i with
| [] -> []
| hd::tl ->
let lo,hi = partition hd tl in
let i' = sort min hd lo in
let j' = sort hd max hi in
append min hd hd max i' (hd::j')
*/
|
dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_Fstar-QuickSort.dfy
|
463
|
463
|
Dafny program: 463
|
// RUN: %dafny /compile:0 /arith:1 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// Proof of the Lucas theorem
// Rustan Leino
// 9 March 2018
//
// Instead of the lemmas doing "up", like:
// P(k) == P(2*k)
// P(k) == P(2*k + 1)
// (see Lucas-up.dfy), the lemmas in this version go "down", like:
// P(k%2) == P(k)
// This file defines the ingredients of the Lucas theorem, proves some
// properties of these, and then states and proves the Lucas theorem
// itself.
// The following predicate gives the boolean value of bit "k" in
// the natural number "n".
predicate Bit(k: nat, n: nat)
{
if k == 0 then n % 2 == 1
else Bit(k-1, n / 2)
}
// Function "BitSet" returns the set of bits in the binary representation
// of a number.
function BitSet(n: nat): set<nat>
{
set i | 0 <= i < n && Bit(i, n)
}
// The following lemma shows that the "i < n" conjunct in
// the set comprehension in "BitSet" does not restrict
// the set any more than the conjunct "Bit(i, n)" does.
lemma BitSize(i: nat, n: nat)
requires Bit(i, n)
ensures i < n
{
}
// An easy-to-read name for the expression that checks if a number
// is even.
predicate EVEN(n: nat)
{
n % 2 == 0
}
// The binomial function is defined like in the Pascal triangle.
// "binom(a, b)" is also knows as "a choose b".
function binom(a: nat, b: nat): nat
{
if b == 0 then 1
else if a == 0 then 0
else binom(a-1, b) + binom(a-1, b-1)
}
// This lemma shows that the parity of "binom" is preserved if
// div-2 is applied to both arguments--except in the case where
// the first argument to "binom" is even and the second argument
// is odd, in which case "binom" is always even.
lemma Lucas_Binary''(a: nat, b: nat)
ensures binom(a, b) % 2 == if EVEN(a) && !EVEN(b) then 0 else binom(a / 2, b / 2) % 2
{
if a == 0 || b == 0 {
} else {
Lucas_Binary''(a - 1, b);
Lucas_Binary''(a - 1, b - 1);
}
}
// "Suc(S)" returns the set constructed by incrementing
// each number in "S" by 1. Stated differently, it is the
// increment-by-1 (successor) function applied pointwise to the
// set.
function Suc(S: set<nat>): set<nat>
{
set x | x in S :: x + 1
}
// The following lemma clearly shows the correspondence between
// "S" and "Suc(S)".
lemma SucElements(S: set<nat>)
ensures forall x :: x in S <==> (x+1) in Suc(S)
{
}
// Here is a lemma that relates BitSet and Suc.
lemma BitSet_Property(n: nat)
ensures BitSet(n) - {0} == Suc(BitSet(n / 2))
{
if n == 0 {
} else {
forall x: nat {
calc {
x in BitSet(n) - {0};
==
x != 0 && x in BitSet(n);
== // def. BitSet
0 < x < n && Bit(x, n);
== // def. Bit
0 < x < n && Bit(x-1, n / 2);
== { if 0 < x && Bit(x-1, n / 2) { BitSize(x-1, n / 2); } }
0 <= x-1 < n / 2 && Bit(x-1, n / 2);
== // def. BitSet
(x-1) in BitSet(n / 2);
== { SucElements(BitSet(n / 2)); }
x in Suc(BitSet(n / 2));
}
}
}
}
lemma Lucas_Theorem'(m: nat, n: nat)
ensures BitSet(m) <= BitSet(n) <==> !EVEN(binom(n, m))
{
if m == 0 && n == 0 {
} else if EVEN(n) && !EVEN(m) {
calc {
!EVEN(binom(n, m));
== { Lucas_Binary''(n, m); }
false;
== { assert 0 in BitSet(m) && 0 !in BitSet(n); }
BitSet(m) <= BitSet(n);
}
} else {
var m', n' := m/2, n/2;
calc {
!EVEN(binom(n, m));
== { Lucas_Binary''(n, m); }
!EVEN(binom(n', m'));
== { Lucas_Theorem'(m', n'); }
BitSet(m') <= BitSet(n');
== { SucElements(BitSet(m')); SucElements(BitSet(n')); }
Suc(BitSet(m')) <= Suc(BitSet(n'));
== { BitSet_Property(m); BitSet_Property(n); }
BitSet(m) - {0} <= BitSet(n) - {0};
== { assert 0 !in BitSet(m) ==> BitSet(m) == BitSet(m) - {0};
BitSet(m) <= BitSet(n);
}
}
}
|
// RUN: %dafny /compile:0 /arith:1 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// Proof of the Lucas theorem
// Rustan Leino
// 9 March 2018
//
// Instead of the lemmas doing "up", like:
// P(k) == P(2*k)
// P(k) == P(2*k + 1)
// (see Lucas-up.dfy), the lemmas in this version go "down", like:
// P(k%2) == P(k)
// This file defines the ingredients of the Lucas theorem, proves some
// properties of these, and then states and proves the Lucas theorem
// itself.
// The following predicate gives the boolean value of bit "k" in
// the natural number "n".
predicate Bit(k: nat, n: nat)
{
if k == 0 then n % 2 == 1
else Bit(k-1, n / 2)
}
// Function "BitSet" returns the set of bits in the binary representation
// of a number.
function BitSet(n: nat): set<nat>
{
set i | 0 <= i < n && Bit(i, n)
}
// The following lemma shows that the "i < n" conjunct in
// the set comprehension in "BitSet" does not restrict
// the set any more than the conjunct "Bit(i, n)" does.
lemma BitSize(i: nat, n: nat)
requires Bit(i, n)
ensures i < n
{
}
// An easy-to-read name for the expression that checks if a number
// is even.
predicate EVEN(n: nat)
{
n % 2 == 0
}
// The binomial function is defined like in the Pascal triangle.
// "binom(a, b)" is also knows as "a choose b".
function binom(a: nat, b: nat): nat
{
if b == 0 then 1
else if a == 0 then 0
else binom(a-1, b) + binom(a-1, b-1)
}
// This lemma shows that the parity of "binom" is preserved if
// div-2 is applied to both arguments--except in the case where
// the first argument to "binom" is even and the second argument
// is odd, in which case "binom" is always even.
lemma Lucas_Binary''(a: nat, b: nat)
ensures binom(a, b) % 2 == if EVEN(a) && !EVEN(b) then 0 else binom(a / 2, b / 2) % 2
{
if a == 0 || b == 0 {
} else {
Lucas_Binary''(a - 1, b);
Lucas_Binary''(a - 1, b - 1);
}
}
// "Suc(S)" returns the set constructed by incrementing
// each number in "S" by 1. Stated differently, it is the
// increment-by-1 (successor) function applied pointwise to the
// set.
function Suc(S: set<nat>): set<nat>
{
set x | x in S :: x + 1
}
// The following lemma clearly shows the correspondence between
// "S" and "Suc(S)".
lemma SucElements(S: set<nat>)
ensures forall x :: x in S <==> (x+1) in Suc(S)
{
}
// Here is a lemma that relates BitSet and Suc.
lemma BitSet_Property(n: nat)
ensures BitSet(n) - {0} == Suc(BitSet(n / 2))
{
if n == 0 {
} else {
forall x: nat {
calc {
x in BitSet(n) - {0};
==
x != 0 && x in BitSet(n);
== // def. BitSet
0 < x < n && Bit(x, n);
== // def. Bit
0 < x < n && Bit(x-1, n / 2);
== { if 0 < x && Bit(x-1, n / 2) { BitSize(x-1, n / 2); } }
0 <= x-1 < n / 2 && Bit(x-1, n / 2);
== // def. BitSet
(x-1) in BitSet(n / 2);
== { SucElements(BitSet(n / 2)); }
x in Suc(BitSet(n / 2));
}
}
}
}
lemma Lucas_Theorem'(m: nat, n: nat)
ensures BitSet(m) <= BitSet(n) <==> !EVEN(binom(n, m))
{
if m == 0 && n == 0 {
} else if EVEN(n) && !EVEN(m) {
calc {
!EVEN(binom(n, m));
== { Lucas_Binary''(n, m); }
false;
== { assert 0 in BitSet(m) && 0 !in BitSet(n); }
BitSet(m) <= BitSet(n);
}
} else {
var m', n' := m/2, n/2;
calc {
!EVEN(binom(n, m));
== { Lucas_Binary''(n, m); }
!EVEN(binom(n', m'));
== { Lucas_Theorem'(m', n'); }
BitSet(m') <= BitSet(n');
== { SucElements(BitSet(m')); SucElements(BitSet(n')); }
Suc(BitSet(m')) <= Suc(BitSet(n'));
== { BitSet_Property(m); BitSet_Property(n); }
BitSet(m) - {0} <= BitSet(n) - {0};
== { assert 0 !in BitSet(m) ==> BitSet(m) == BitSet(m) - {0};
assert 0 in BitSet(n) ==> BitSet(n) - {0} <= BitSet(n); }
BitSet(m) <= BitSet(n);
}
}
}
|
dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_Lucas-down.dfy
|
472
|
472
|
Dafny program: 472
|
// RUN: %dafny "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
lemma TestMap(a: map<int, (int,int)>) {
// The following assertion used to not prove automatically
// the following map comprehension implicitly uses k as the key
== (map k | k in a :: a[k].0);
}
lemma TestSet0(a: set<int>) {
// the following set comprehension implicitly uses k as the term
== (set k | k in a && k < 7);
}
lemma TestSet1(a: set<int>, m: int) {
== (set k | k in a && k < 7 :: m + (k - m));
}
lemma TestSet2(a: set<int>, m: int)
requires m in a && m < 7
{
== (set k | k in a :: if k < 7 then k else m);
}
|
// RUN: %dafny "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
lemma TestMap(a: map<int, (int,int)>) {
// The following assertion used to not prove automatically
assert (map k | k in a :: k := a[k].0)
// the following map comprehension implicitly uses k as the key
== (map k | k in a :: a[k].0);
}
lemma TestSet0(a: set<int>) {
assert (set k | k in a && k < 7 :: k)
// the following set comprehension implicitly uses k as the term
== (set k | k in a && k < 7);
}
lemma TestSet1(a: set<int>, m: int) {
assert (set k | k in a && k < 7 :: k)
== (set k | k in a && k < 7 :: m + (k - m));
}
lemma TestSet2(a: set<int>, m: int)
requires m in a && m < 7
{
assert (set k | k < 7 && k in a)
== (set k | k in a :: if k < 7 then k else m);
}
|
dafny-language-server_tmp_tmpkir0kenl_Test_git-issues_git-issue-336.dfy
|
473
|
473
|
Dafny program: 473
|
// RUN: %dafny /compile:3 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
class Ref<A> {
var val : A
constructor (a : A)
ensures val == a
{
val := a;
}
}
method Main() {
// simple
print "1 = ", (x => x)(1), "\n";
print "3 = ", (x => y => x + y)(1)(2), "\n";
print "3 = ", ((x,y) => y + x)(1,2), "\n";
print "0 = ", (() => 0)(), "\n";
// local variable
var y := 1;
var f := x => x + y;
print "3 = ", f(2), "\n";
print "4 = ", f(3), "\n";
y := 2;
print "3 = ", f(2), "\n";
print "4 = ", f(3), "\n";
// reference
var z := new Ref(1);
f := x reads z => x + z.val;
print "3 = ", f(2), "\n";
print "4 = ", f(3), "\n";
z.val := 2;
print "4 = ", f(2), "\n";
print "5 = ", f(3), "\n";
// loop
f := x => x;
y := 10;
while y > 0
{
f := x => f(x+y);
y := y - 1;
}
print "55 = ", f(0), "\n";
// substitution test
print "0 = ", (x => var y:=x;y)(0), "\n";
print "1 = ", (y => (x => var y:=x;y))(0)(1), "\n";
}
|
// RUN: %dafny /compile:3 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
class Ref<A> {
var val : A
constructor (a : A)
ensures val == a
{
val := a;
}
}
method Main() {
// simple
print "1 = ", (x => x)(1), "\n";
print "3 = ", (x => y => x + y)(1)(2), "\n";
print "3 = ", ((x,y) => y + x)(1,2), "\n";
print "0 = ", (() => 0)(), "\n";
// local variable
var y := 1;
var f := x => x + y;
print "3 = ", f(2), "\n";
print "4 = ", f(3), "\n";
y := 2;
print "3 = ", f(2), "\n";
print "4 = ", f(3), "\n";
// reference
var z := new Ref(1);
f := x reads z => x + z.val;
print "3 = ", f(2), "\n";
print "4 = ", f(3), "\n";
z.val := 2;
print "4 = ", f(2), "\n";
print "5 = ", f(3), "\n";
// loop
f := x => x;
y := 10;
while y > 0
invariant forall x :: f.requires(x)
invariant forall x :: f.reads(x) == {}
{
f := x => f(x+y);
y := y - 1;
}
print "55 = ", f(0), "\n";
// substitution test
print "0 = ", (x => var y:=x;y)(0), "\n";
print "1 = ", (y => (x => var y:=x;y))(0)(1), "\n";
}
|
dafny-language-server_tmp_tmpkir0kenl_Test_hofs_Compilation.dfy
|
474
|
474
|
Dafny program: 474
|
// RUN: %dafny /compile:3 /print:"%t.print" /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
method Main()
{
test0(10);
test5(11);
test6(12);
test1();
test2();
}
predicate valid(x:int)
{
x > 0
}
function ref1(y:int) : int
requires valid(y);
{
y - 1
}
lemma assumption1()
ensures forall a, b :: valid(a) && valid(b) && ref1(a) == ref1(b) ==> a == b;
{
}
method test0(a: int)
{
if ref1.requires(a) {
// the precondition should suffice to let us call the method
ghost var b := ref1(a);
}
}
method test5(a: int)
{
if valid(a) {
// valid(a) is the precondition of ref1
}
}
method test6(a: int)
{
if ref1.requires(a) {
// the precondition of ref1 is valid(a)
}
}
method test1()
{
if * {
} else {
==> a == b;
}
}
function {:opaque} ref2(y:int) : int // Now with an opaque attribute
requires valid(y);
{
y - 1
}
lemma assumption2()
ensures forall a, b :: valid(a) && valid(b) && ref2(a) == ref2(b) ==> a == b;
{
reveal ref2();
}
method test2()
{
assumption2();
if * {
} else {
==> a == b;
}
}
|
// RUN: %dafny /compile:3 /print:"%t.print" /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
method Main()
{
test0(10);
test5(11);
test6(12);
test1();
test2();
}
predicate valid(x:int)
{
x > 0
}
function ref1(y:int) : int
requires valid(y);
{
y - 1
}
lemma assumption1()
ensures forall a, b :: valid(a) && valid(b) && ref1(a) == ref1(b) ==> a == b;
{
}
method test0(a: int)
{
if ref1.requires(a) {
// the precondition should suffice to let us call the method
ghost var b := ref1(a);
}
}
method test5(a: int)
{
if valid(a) {
// valid(a) is the precondition of ref1
assert ref1.requires(a);
}
}
method test6(a: int)
{
if ref1.requires(a) {
// the precondition of ref1 is valid(a)
assert valid(a);
}
}
method test1()
{
if * {
assert forall a, b :: valid(a) && valid(b) && ref1(a) == ref1(b) ==> a == b;
} else {
assert forall a, b :: ref1.requires(a) && ref1.requires(b) && ref1(a) == ref1(b)
==> a == b;
}
}
function {:opaque} ref2(y:int) : int // Now with an opaque attribute
requires valid(y);
{
y - 1
}
lemma assumption2()
ensures forall a, b :: valid(a) && valid(b) && ref2(a) == ref2(b) ==> a == b;
{
reveal ref2();
}
method test2()
{
assumption2();
if * {
assert forall a, b :: valid(a) && valid(b) && ref2(a) == ref2(b) ==> a == b;
} else {
assert forall a, b :: ref2.requires(a) && ref2.requires(b) && ref2(a) == ref2(b)
==> a == b;
}
}
|
dafny-language-server_tmp_tmpkir0kenl_Test_hofs_Requires.dfy
|
475
|
475
|
Dafny program: 475
|
// RUN: %dafny /compile:0 /rprint:"%t.rprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// Tests that come down to comparing the bodies of (possibly nested) functions.
// Many of these currently require far more effort than one would like.
// KRML, 2 May 2016
function Sum(n: nat, f: int -> int): int
{
if n == 0 then 0 else f(n-1) + Sum(n-1, f)
}
lemma Exchange(n: nat, f: int -> int, g: int -> int)
requires forall i :: 0 <= i < n ==> f(i) == g(i)
ensures Sum(n, f) == Sum(n, g)
{
}
lemma ExchangeEta(n: nat, f: int -> int, g: int -> int)
requires forall i :: 0 <= i < n ==> f(i) == g(i)
ensures Sum(n, x => f(x)) == Sum(n, x => g(x))
{
}
lemma NestedAlphaRenaming(n: nat, g: (int,int) -> int)
ensures Sum(n, x => Sum(n, y => g(x,y))) == Sum(n, a => Sum(n, b => g(a,b)))
{
}
lemma DistributePlus1(n: nat, f: int -> int)
ensures Sum(n, x => 1 + f(x)) == n + Sum(n, f)
{
}
lemma Distribute(n: nat, f: int -> int, g: int -> int)
ensures Sum(n, x => f(x) + g(x)) == Sum(n, f) + Sum(n, g)
{
}
lemma {:induction false} PrettyBasicBetaReduction(n: nat, g: (int,int) -> int, i: int)
ensures (x => Sum(n, y => g(x,y)))(i) == Sum(n, y => g(i,y))
{
// NOTE: This proof is by induction on n (it can be done automatically)
if n == 0 {
calc {
(x => Sum(n, y => g(x,y)))(i);
0;
Sum(n, y => g(i,y));
}
} else {
calc {
(x => Sum(n, y => g(x,y)))(i);
g(i,n-1) + (x => Sum(n-1, y => g(x,y)))(i);
{ PrettyBasicBetaReduction(n-1, g, i); }
g(i,n-1) + Sum(n-1, y => g(i,y));
(y => g(i,y))(n-1) + Sum(n-1, y => g(i,y));
Sum(n, y => g(i,y));
}
}
}
lemma BetaReduction0(n: nat, g: (int,int) -> int, i: int)
ensures (x => Sum(n, y => g(x,y)))(i) == Sum(n, y => g(i,y))
{
// automatic proof by induction on n
}
lemma BetaReduction1(n': nat, g: (int,int) -> int, i: int)
ensures g(i,n') + Sum(n', y => g(i,y)) == (x => g(x,n') + Sum(n', y => g(x,y)))(i);
{
}
lemma BetaReductionInside(n': nat, g: (int,int) -> int)
ensures Sum(n', x => g(x,n') + Sum(n', y => g(x,y)))
== Sum(n', x => (w => g(w,n'))(x) + (w => Sum(n', y => g(w,y)))(x))
{
forall i | 0 <= i < n'
{
calc {
(x => g(x,n') + Sum(n', y => g(x,y)))(i);
(x => (w => g(w,n'))(x) + (w => Sum(n', y => g(w,y)))(x))(i);
}
}
Exchange(n', x => g(x,n') + Sum(n', y => g(x,y)), x => (w => g(w,n'))(x) + (w => Sum(n', y => g(w,y)))(x));
}
lemma L(n: nat, n': nat, g: (int, int) -> int)
requires && n == n' + 1
ensures Sum(n, x => Sum(n, y => g(x,y)))
== Sum(n', x => Sum(n', y => g(x,y))) + Sum(n', x => g(x,n')) + Sum(n', y => g(n',y)) + g(n',n')
{
var A := w => g(w,n');
var B := w => Sum(n', y => g(w,y));
calc {
Sum(n, x => Sum(n, y => g(x,y)));
{ assume false;/*TODO*/ }
(x => Sum(n, y => g(x,y)))(n') + Sum(n', x => Sum(n, y => g(x,y)));
{ BetaReduction0(n, g, n'); }
Sum(n, y => g(n',y)) + Sum(n', x => Sum(n, y => g(x,y)));
{ assume false;/*TODO*/ }
(y => g(n',y))(n') + Sum(n', y => g(n',y)) + Sum(n', x => Sum(n, y => g(x,y)));
{ assert (y => g(n',y))(n') == g(n',n'); }
g(n',n') + Sum(n', y => g(n',y)) + Sum(n', x => Sum(n, y => g(x,y)));
{
forall i | 0 <= i < n' {
calc {
(x => Sum(n, y => g(x,y)))(i);
{ PrettyBasicBetaReduction(n, g, i); }
Sum(n, y => g(i,y));
{ assume false;/*TODO*/ }
(y => g(i,y))(n') + Sum(n', y => g(i,y));
// beta reduction
g(i,n') + Sum(n', y => g(i,y));
{ BetaReduction1(n', g, i); }
(x => g(x,n') + Sum(n', y => g(x,y)))(i);
}
}
Exchange(n', x => Sum(n, y => g(x,y)), x => g(x,n') + Sum(n', y => g(x,y)));
}
g(n',n') + Sum(n', y => g(n',y)) + Sum(n', x => g(x,n') + Sum(n', y => g(x,y)));
{ BetaReductionInside(n', g); }
g(n',n') + Sum(n', y => g(n',y)) + Sum(n', x => (w => g(w,n'))(x) + (w => Sum(n', y => g(w,y)))(x));
{ Exchange(n', x => (w => g(w,n'))(x) + (w => Sum(n', y => g(w,y)))(x), x => A(x) + B(x)); }
g(n',n') + Sum(n', y => g(n',y)) + Sum(n', x => A(x) + B(x));
{ Distribute(n', A, B); }
g(n',n') + Sum(n', y => g(n',y)) + Sum(n', A) + Sum(n', B);
// defs. A and B
g(n',n') + Sum(n', y => g(n',y)) + Sum(n', w => g(w,n')) + Sum(n', w => Sum(n', y => g(w,y)));
// alpha renamings, and commutativity of the 4 plus terms
Sum(n', x => Sum(n', y => g(x,y))) + Sum(n', y => g(n',y)) + Sum(n', x => g(x,n')) + g(n',n');
}
}
lemma Commute(n: nat, g: (int,int) -> int)
ensures Sum(n, x => Sum(n, y => g(x,y))) == Sum(n, x => Sum(n, y => g(y,x)))
// TODO
lemma CommuteSum(n: nat, g: (int,int) -> int)
ensures Sum(n, x => Sum(n, y => g(x,y))) == Sum(n, y => Sum(n, x => g(x,y)))
// TODO
|
// RUN: %dafny /compile:0 /rprint:"%t.rprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// Tests that come down to comparing the bodies of (possibly nested) functions.
// Many of these currently require far more effort than one would like.
// KRML, 2 May 2016
function Sum(n: nat, f: int -> int): int
{
if n == 0 then 0 else f(n-1) + Sum(n-1, f)
}
lemma Exchange(n: nat, f: int -> int, g: int -> int)
requires forall i :: 0 <= i < n ==> f(i) == g(i)
ensures Sum(n, f) == Sum(n, g)
{
}
lemma ExchangeEta(n: nat, f: int -> int, g: int -> int)
requires forall i :: 0 <= i < n ==> f(i) == g(i)
ensures Sum(n, x => f(x)) == Sum(n, x => g(x))
{
}
lemma NestedAlphaRenaming(n: nat, g: (int,int) -> int)
ensures Sum(n, x => Sum(n, y => g(x,y))) == Sum(n, a => Sum(n, b => g(a,b)))
{
}
lemma DistributePlus1(n: nat, f: int -> int)
ensures Sum(n, x => 1 + f(x)) == n + Sum(n, f)
{
}
lemma Distribute(n: nat, f: int -> int, g: int -> int)
ensures Sum(n, x => f(x) + g(x)) == Sum(n, f) + Sum(n, g)
{
}
lemma {:induction false} PrettyBasicBetaReduction(n: nat, g: (int,int) -> int, i: int)
ensures (x => Sum(n, y => g(x,y)))(i) == Sum(n, y => g(i,y))
{
// NOTE: This proof is by induction on n (it can be done automatically)
if n == 0 {
calc {
(x => Sum(n, y => g(x,y)))(i);
0;
Sum(n, y => g(i,y));
}
} else {
calc {
(x => Sum(n, y => g(x,y)))(i);
g(i,n-1) + (x => Sum(n-1, y => g(x,y)))(i);
{ PrettyBasicBetaReduction(n-1, g, i); }
g(i,n-1) + Sum(n-1, y => g(i,y));
(y => g(i,y))(n-1) + Sum(n-1, y => g(i,y));
Sum(n, y => g(i,y));
}
}
}
lemma BetaReduction0(n: nat, g: (int,int) -> int, i: int)
ensures (x => Sum(n, y => g(x,y)))(i) == Sum(n, y => g(i,y))
{
// automatic proof by induction on n
}
lemma BetaReduction1(n': nat, g: (int,int) -> int, i: int)
ensures g(i,n') + Sum(n', y => g(i,y)) == (x => g(x,n') + Sum(n', y => g(x,y)))(i);
{
}
lemma BetaReductionInside(n': nat, g: (int,int) -> int)
ensures Sum(n', x => g(x,n') + Sum(n', y => g(x,y)))
== Sum(n', x => (w => g(w,n'))(x) + (w => Sum(n', y => g(w,y)))(x))
{
forall i | 0 <= i < n'
{
calc {
(x => g(x,n') + Sum(n', y => g(x,y)))(i);
(x => (w => g(w,n'))(x) + (w => Sum(n', y => g(w,y)))(x))(i);
}
}
Exchange(n', x => g(x,n') + Sum(n', y => g(x,y)), x => (w => g(w,n'))(x) + (w => Sum(n', y => g(w,y)))(x));
}
lemma L(n: nat, n': nat, g: (int, int) -> int)
requires && n == n' + 1
ensures Sum(n, x => Sum(n, y => g(x,y)))
== Sum(n', x => Sum(n', y => g(x,y))) + Sum(n', x => g(x,n')) + Sum(n', y => g(n',y)) + g(n',n')
{
var A := w => g(w,n');
var B := w => Sum(n', y => g(w,y));
calc {
Sum(n, x => Sum(n, y => g(x,y)));
{ assume false;/*TODO*/ }
(x => Sum(n, y => g(x,y)))(n') + Sum(n', x => Sum(n, y => g(x,y)));
{ BetaReduction0(n, g, n'); }
Sum(n, y => g(n',y)) + Sum(n', x => Sum(n, y => g(x,y)));
{ assume false;/*TODO*/ }
(y => g(n',y))(n') + Sum(n', y => g(n',y)) + Sum(n', x => Sum(n, y => g(x,y)));
{ assert (y => g(n',y))(n') == g(n',n'); }
g(n',n') + Sum(n', y => g(n',y)) + Sum(n', x => Sum(n, y => g(x,y)));
{
forall i | 0 <= i < n' {
calc {
(x => Sum(n, y => g(x,y)))(i);
{ PrettyBasicBetaReduction(n, g, i); }
Sum(n, y => g(i,y));
{ assume false;/*TODO*/ }
(y => g(i,y))(n') + Sum(n', y => g(i,y));
// beta reduction
g(i,n') + Sum(n', y => g(i,y));
{ BetaReduction1(n', g, i); }
(x => g(x,n') + Sum(n', y => g(x,y)))(i);
}
}
Exchange(n', x => Sum(n, y => g(x,y)), x => g(x,n') + Sum(n', y => g(x,y)));
}
g(n',n') + Sum(n', y => g(n',y)) + Sum(n', x => g(x,n') + Sum(n', y => g(x,y)));
{ BetaReductionInside(n', g); }
g(n',n') + Sum(n', y => g(n',y)) + Sum(n', x => (w => g(w,n'))(x) + (w => Sum(n', y => g(w,y)))(x));
{ Exchange(n', x => (w => g(w,n'))(x) + (w => Sum(n', y => g(w,y)))(x), x => A(x) + B(x)); }
g(n',n') + Sum(n', y => g(n',y)) + Sum(n', x => A(x) + B(x));
{ Distribute(n', A, B); }
g(n',n') + Sum(n', y => g(n',y)) + Sum(n', A) + Sum(n', B);
// defs. A and B
g(n',n') + Sum(n', y => g(n',y)) + Sum(n', w => g(w,n')) + Sum(n', w => Sum(n', y => g(w,y)));
// alpha renamings, and commutativity of the 4 plus terms
Sum(n', x => Sum(n', y => g(x,y))) + Sum(n', y => g(n',y)) + Sum(n', x => g(x,n')) + g(n',n');
}
}
lemma Commute(n: nat, g: (int,int) -> int)
ensures Sum(n, x => Sum(n, y => g(x,y))) == Sum(n, x => Sum(n, y => g(y,x)))
// TODO
lemma CommuteSum(n: nat, g: (int,int) -> int)
ensures Sum(n, x => Sum(n, y => g(x,y))) == Sum(n, y => Sum(n, x => g(x,y)))
// TODO
|
dafny-language-server_tmp_tmpkir0kenl_Test_hofs_SumSum.dfy
|
478
|
478
|
Dafny program: 478
|
// RUN: %dafny /compile:0 /print:"%t.print" /dprint:"%t.dprint" /printTooltips "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// This file checks that function applications yield trigger candidates
method M(P: (int -> int) -> bool, g: int -> int)
requires P.requires(g)
requires P(g) {
assume forall f: int -> int :: P.requires(f);
assume forall f: int -> int :: P(f) ==> f.requires(10) && f(10) == 0;
(forall x :: f.requires(x) && g.requires(x) ==> f(x) == g(x)) ==>
f.requires(10) ==>
f(10) == 0;
}
|
// RUN: %dafny /compile:0 /print:"%t.print" /dprint:"%t.dprint" /printTooltips "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// This file checks that function applications yield trigger candidates
method M(P: (int -> int) -> bool, g: int -> int)
requires P.requires(g)
requires P(g) {
assume forall f: int -> int :: P.requires(f);
assume forall f: int -> int :: P(f) ==> f.requires(10) && f(10) == 0;
assert forall f: int -> int ::
(forall x :: f.requires(x) && g.requires(x) ==> f(x) == g(x)) ==>
f.requires(10) ==>
f(10) == 0;
}
|
dafny-language-server_tmp_tmpkir0kenl_Test_triggers_function-applications-are-triggers.dfy
|
481
|
481
|
Dafny program: 481
|
// RUN: %dafny /compile:0 /print:"%t.print" /dprint:"%t.dprint" /printTooltips "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// This file shows how to specify and implement a function to compute the
// largest element of a list. The function is fully specified by two
// preconditions, as proved by the MaximumIsUnique lemma below.
method Maximum(values: seq<int>) returns (max: int)
requires values != []
ensures max in values
ensures forall i | 0 <= i < |values| :: values[i] <= max
{
max := values[0];
var idx := 0;
while (idx < |values|)
{
if (values[idx] > max) {
max := values[idx];
}
idx := idx + 1;
}
}
lemma MaximumIsUnique(values: seq<int>, m1: int, m2: int)
requires m1 in values && forall i | 0 <= i < |values| :: values[i] <= m1
requires m2 in values && forall i | 0 <= i < |values| :: values[i] <= m2
ensures m1 == m2 {
// This lemma does not need a body: Dafny is able to prove it correct entirely automatically.
}
|
// RUN: %dafny /compile:0 /print:"%t.print" /dprint:"%t.dprint" /printTooltips "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// This file shows how to specify and implement a function to compute the
// largest element of a list. The function is fully specified by two
// preconditions, as proved by the MaximumIsUnique lemma below.
method Maximum(values: seq<int>) returns (max: int)
requires values != []
ensures max in values
ensures forall i | 0 <= i < |values| :: values[i] <= max
{
max := values[0];
var idx := 0;
while (idx < |values|)
invariant max in values
invariant idx <= |values|
invariant forall j | 0 <= j < idx :: values[j] <= max
{
if (values[idx] > max) {
max := values[idx];
}
idx := idx + 1;
}
}
lemma MaximumIsUnique(values: seq<int>, m1: int, m2: int)
requires m1 in values && forall i | 0 <= i < |values| :: values[i] <= m1
requires m2 in values && forall i | 0 <= i < |values| :: values[i] <= m2
ensures m1 == m2 {
// This lemma does not need a body: Dafny is able to prove it correct entirely automatically.
}
|
dafny-language-server_tmp_tmpkir0kenl_Test_tutorial_maximum.dfy
|
482
|
482
|
Dafny program: 482
|
// RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
class Composite {
var left: Composite?
var right: Composite?
var parent: Composite?
var val: int
var sum: int
function Valid(S: set<Composite>): bool
reads this, parent, left, right
{
this in S &&
(parent != null ==> parent in S && (parent.left == this || parent.right == this)) &&
(left != null ==> left in S && left.parent == this && left != right) &&
(right != null ==> right in S && right.parent == this && left != right) &&
sum == val + (if left == null then 0 else left.sum) + (if right == null then 0 else right.sum)
}
function Acyclic(S: set<Composite>): bool
reads S
{
this in S &&
(parent != null ==> parent.Acyclic(S - {this}))
}
method Init(x: int)
modifies this
ensures Valid({this}) && Acyclic({this}) && val == x && parent == null
{
parent := null;
left := null;
right := null;
val := x;
sum := val;
}
method Update(x: int, ghost S: set<Composite>)
requires this in S && Acyclic(S)
requires forall c :: c in S ==> c.Valid(S)
modifies S
ensures forall c :: c in S ==> c.Valid(S)
ensures forall c :: c in S ==> c.left == old(c.left) && c.right == old(c.right) && c.parent == old(c.parent)
ensures forall c :: c in S && c != this ==> c.val == old(c.val)
ensures val == x
{
var delta := x - val;
val := x;
Adjust(delta, S, S);
}
method Add(ghost S: set<Composite>, child: Composite, ghost U: set<Composite>)
requires this in S && Acyclic(S)
requires forall c :: c in S ==> c.Valid(S)
requires child in U
requires forall c :: c in U ==> c.Valid(U)
requires S !! U
requires left == null || right == null
requires child.parent == null
// modifies only one of this.left and this.right, and child.parent, and various sum fields:
modifies S, child
ensures child.left == old(child.left) && child.right == old(child.right) && child.val == old(child.val)
ensures forall c :: c in S && c != this ==> c.left == old(c.left) && c.right == old(c.right)
ensures old(left) != null ==> left == old(left)
ensures old(right) != null ==> right == old(right)
ensures forall c :: c in S ==> c.parent == old(c.parent) && c.val == old(c.val)
// sets child.parent to this:
ensures child.parent == this
// leaves everything in S+U valid
ensures forall c: Composite {:autotriggers false} :: c in S+U ==> c.Valid(S+U) // We can't generate a trigger for this at the moment; if we did, we would still need to prevent TrSplitExpr from translating c in S+U to S[c] || U[c].
{
if (left == null) {
left := child;
} else {
right := child;
}
child.parent := this;
Adjust(child.sum, S, S+U);
}
method Dislodge(ghost S: set<Composite>)
requires this in S && Acyclic(S)
requires forall c :: c in S ==> c.Valid(S)
modifies S
ensures forall c :: c in S ==> c.Valid(S)
ensures forall c :: c in S ==> c.val == old(c.val)
ensures forall c :: c in S && c != this ==> c.parent == old(c.parent)
ensures parent == null
ensures forall c :: c in S ==> c.left == old(c.left) || (old(c.left) == this && c.left == null)
ensures forall c :: c in S ==> c.right == old(c.right) || (old(c.right) == this && c.right == null)
ensures Acyclic({this})
{
var p := parent;
parent := null;
if (p != null) {
if (p.left == this) {
p.left := null;
} else {
p.right := null;
}
var delta := -sum;
p.Adjust(delta, S - {this}, S);
}
}
/*private*/ method Adjust(delta: int, ghost U: set<Composite>, ghost S: set<Composite>)
requires U <= S && Acyclic(U)
// everything else is valid:
requires forall c :: c in S && c != this ==> c.Valid(S)
// this is almost valid:
requires parent != null ==> parent in S && (parent.left == this || parent.right == this)
requires left != null ==> left in S && left.parent == this && left != right
requires right != null ==> right in S && right.parent == this && left != right
// ... except that sum needs to be adjusted by delta:
requires sum + delta == val + (if left == null then 0 else left.sum) + (if right == null then 0 else right.sum)
// modifies sum fields in U:
modifies U`sum
// everything is valid, including this:
ensures forall c :: c in S ==> c.Valid(S)
{
var p: Composite? := this;
ghost var T := U;
while (p != null)
{
p.sum := p.sum + delta;
T := T - {p};
p := p.parent;
}
}
}
method Main()
{
var c0 := new Composite.Init(57);
var c1 := new Composite.Init(12);
c0.Add({c0}, c1, {c1});
var c2 := new Composite.Init(48);
var c3 := new Composite.Init(48);
c2.Add({c2}, c3, {c3});
c0.Add({c0,c1}, c2, {c2,c3});
ghost var S := {c0, c1, c2, c3};
c1.Update(100, S);
c2.Update(102, S);
c2.Dislodge(S);
c2.Update(496, S);
c0.Update(0, S);
}
method Harness() {
var a := new Composite.Init(5);
var b := new Composite.Init(7);
a.Add({a}, b, {b});
b.Update(17, {a,b});
var c := new Composite.Init(10);
b.Add({a,b}, c, {c});
b.Dislodge({a,b,c});
}
|
// RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
class Composite {
var left: Composite?
var right: Composite?
var parent: Composite?
var val: int
var sum: int
function Valid(S: set<Composite>): bool
reads this, parent, left, right
{
this in S &&
(parent != null ==> parent in S && (parent.left == this || parent.right == this)) &&
(left != null ==> left in S && left.parent == this && left != right) &&
(right != null ==> right in S && right.parent == this && left != right) &&
sum == val + (if left == null then 0 else left.sum) + (if right == null then 0 else right.sum)
}
function Acyclic(S: set<Composite>): bool
reads S
{
this in S &&
(parent != null ==> parent.Acyclic(S - {this}))
}
method Init(x: int)
modifies this
ensures Valid({this}) && Acyclic({this}) && val == x && parent == null
{
parent := null;
left := null;
right := null;
val := x;
sum := val;
}
method Update(x: int, ghost S: set<Composite>)
requires this in S && Acyclic(S)
requires forall c :: c in S ==> c.Valid(S)
modifies S
ensures forall c :: c in S ==> c.Valid(S)
ensures forall c :: c in S ==> c.left == old(c.left) && c.right == old(c.right) && c.parent == old(c.parent)
ensures forall c :: c in S && c != this ==> c.val == old(c.val)
ensures val == x
{
var delta := x - val;
val := x;
Adjust(delta, S, S);
}
method Add(ghost S: set<Composite>, child: Composite, ghost U: set<Composite>)
requires this in S && Acyclic(S)
requires forall c :: c in S ==> c.Valid(S)
requires child in U
requires forall c :: c in U ==> c.Valid(U)
requires S !! U
requires left == null || right == null
requires child.parent == null
// modifies only one of this.left and this.right, and child.parent, and various sum fields:
modifies S, child
ensures child.left == old(child.left) && child.right == old(child.right) && child.val == old(child.val)
ensures forall c :: c in S && c != this ==> c.left == old(c.left) && c.right == old(c.right)
ensures old(left) != null ==> left == old(left)
ensures old(right) != null ==> right == old(right)
ensures forall c :: c in S ==> c.parent == old(c.parent) && c.val == old(c.val)
// sets child.parent to this:
ensures child.parent == this
// leaves everything in S+U valid
ensures forall c: Composite {:autotriggers false} :: c in S+U ==> c.Valid(S+U) // We can't generate a trigger for this at the moment; if we did, we would still need to prevent TrSplitExpr from translating c in S+U to S[c] || U[c].
{
if (left == null) {
left := child;
} else {
right := child;
}
child.parent := this;
Adjust(child.sum, S, S+U);
}
method Dislodge(ghost S: set<Composite>)
requires this in S && Acyclic(S)
requires forall c :: c in S ==> c.Valid(S)
modifies S
ensures forall c :: c in S ==> c.Valid(S)
ensures forall c :: c in S ==> c.val == old(c.val)
ensures forall c :: c in S && c != this ==> c.parent == old(c.parent)
ensures parent == null
ensures forall c :: c in S ==> c.left == old(c.left) || (old(c.left) == this && c.left == null)
ensures forall c :: c in S ==> c.right == old(c.right) || (old(c.right) == this && c.right == null)
ensures Acyclic({this})
{
var p := parent;
parent := null;
if (p != null) {
if (p.left == this) {
p.left := null;
} else {
p.right := null;
}
var delta := -sum;
p.Adjust(delta, S - {this}, S);
}
}
/*private*/ method Adjust(delta: int, ghost U: set<Composite>, ghost S: set<Composite>)
requires U <= S && Acyclic(U)
// everything else is valid:
requires forall c :: c in S && c != this ==> c.Valid(S)
// this is almost valid:
requires parent != null ==> parent in S && (parent.left == this || parent.right == this)
requires left != null ==> left in S && left.parent == this && left != right
requires right != null ==> right in S && right.parent == this && left != right
// ... except that sum needs to be adjusted by delta:
requires sum + delta == val + (if left == null then 0 else left.sum) + (if right == null then 0 else right.sum)
// modifies sum fields in U:
modifies U`sum
// everything is valid, including this:
ensures forall c :: c in S ==> c.Valid(S)
{
var p: Composite? := this;
ghost var T := U;
while (p != null)
invariant T <= U
invariant p == null || p.Acyclic(T)
invariant forall c :: c in S && c != p ==> c.Valid(S)
invariant p != null ==> p.sum + delta == p.val + (if p.left == null then 0 else p.left.sum) + (if p.right == null then 0 else p.right.sum)
invariant forall c :: c in S ==> c.left == old(c.left) && c.right == old(c.right) && c.parent == old(c.parent) && c.val == old(c.val)
decreases T
{
p.sum := p.sum + delta;
T := T - {p};
p := p.parent;
}
}
}
method Main()
{
var c0 := new Composite.Init(57);
var c1 := new Composite.Init(12);
c0.Add({c0}, c1, {c1});
var c2 := new Composite.Init(48);
var c3 := new Composite.Init(48);
c2.Add({c2}, c3, {c3});
c0.Add({c0,c1}, c2, {c2,c3});
ghost var S := {c0, c1, c2, c3};
c1.Update(100, S);
c2.Update(102, S);
c2.Dislodge(S);
c2.Update(496, S);
c0.Update(0, S);
}
method Harness() {
var a := new Composite.Init(5);
var b := new Composite.Init(7);
a.Add({a}, b, {b});
assert a.sum == 12;
b.Update(17, {a,b});
assert a.sum == 22;
var c := new Composite.Init(10);
b.Add({a,b}, c, {c});
b.Dislodge({a,b,c});
assert b.sum == 27;
}
|
dafny-language-server_tmp_tmpkir0kenl_Test_vacid0_Composite.dfy
|
483
|
483
|
Dafny program: 483
|
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// This method is a slight generalization of the
// code provided in the problem statement since it
// is generic in the type of the array elements.
method swap<T>(a: array<T>, i: int, j: int)
requires 0 <= i < j < a.Length
modifies a
ensures a[i] == old(a[j])
ensures a[j] == old(a[i])
ensures forall m :: 0 <= m < a.Length && m != i && m != j ==> a[m] == old(a[m])
ensures multiset(a[..]) == old(multiset(a[..]))
{
var t := a[i];
a[i] := a[j];
a[j] := t;
}
// This method is a direct translation of the pseudo
// code given in the problem statement.
// The first postcondition expresses that the resulting
// array is sorted, that is, all occurrences of "false"
// come before all occurrences of "true".
// The second postcondition expresses that the post-state
// array is a permutation of the pre-state array. To express
// this, we use Dafny's built-in multisets. The built-in
// function "multiset" takes an array and yields the
// multiset of the array elements.
// Note that Dafny guesses a suitable ranking function
// for the termination proof of the while loop.
// We use the loop guard from the given pseudo-code. However,
// the program also verifies with the stronger guard "i < j"
// (without changing any of the other specifications or
// annotations).
method two_way_sort(a: array<bool>)
modifies a
ensures forall m,n :: 0 <= m < n < a.Length ==> (!a[m] || a[n])
ensures multiset(a[..]) == old(multiset(a[..]))
{
var i := 0;
var j := a.Length - 1;
while (i <= j)
{
if (!a[i]) {
i := i+1;
} else if (a[j]) {
j := j-1;
} else {
swap(a, i, j);
i := i+1;
j := j-1;
}
}
}
|
// RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// This method is a slight generalization of the
// code provided in the problem statement since it
// is generic in the type of the array elements.
method swap<T>(a: array<T>, i: int, j: int)
requires 0 <= i < j < a.Length
modifies a
ensures a[i] == old(a[j])
ensures a[j] == old(a[i])
ensures forall m :: 0 <= m < a.Length && m != i && m != j ==> a[m] == old(a[m])
ensures multiset(a[..]) == old(multiset(a[..]))
{
var t := a[i];
a[i] := a[j];
a[j] := t;
}
// This method is a direct translation of the pseudo
// code given in the problem statement.
// The first postcondition expresses that the resulting
// array is sorted, that is, all occurrences of "false"
// come before all occurrences of "true".
// The second postcondition expresses that the post-state
// array is a permutation of the pre-state array. To express
// this, we use Dafny's built-in multisets. The built-in
// function "multiset" takes an array and yields the
// multiset of the array elements.
// Note that Dafny guesses a suitable ranking function
// for the termination proof of the while loop.
// We use the loop guard from the given pseudo-code. However,
// the program also verifies with the stronger guard "i < j"
// (without changing any of the other specifications or
// annotations).
method two_way_sort(a: array<bool>)
modifies a
ensures forall m,n :: 0 <= m < n < a.Length ==> (!a[m] || a[n])
ensures multiset(a[..]) == old(multiset(a[..]))
{
var i := 0;
var j := a.Length - 1;
while (i <= j)
invariant 0 <= i <= j + 1 <= a.Length
invariant forall m :: 0 <= m < i ==> !a[m]
invariant forall n :: j < n < a.Length ==> a[n]
invariant multiset(a[..]) == old(multiset(a[..]))
{
if (!a[i]) {
i := i+1;
} else if (a[j]) {
j := j-1;
} else {
swap(a, i, j);
i := i+1;
j := j-1;
}
}
}
|
dafny-language-server_tmp_tmpkir0kenl_Test_vstte2012_Two-Way-Sort.dfy
|
487
|
487
|
Dafny program: 487
|
function Expt(b: int, n: nat): int
requires n >= 0
{
if n == 0 then 1 else b * Expt(b, n - 1)
}
method expt(b: int, n: nat) returns (res: int)
ensures res == Expt(b, n)
{
var i := 1;
res := 1;
while i < n + 1
{
res := res * b;
i := i + 1;
}
}
// source: https://www.dcc.fc.up.pt/~nam/web/resources/vfs20/DafnyQuickReference.pdf
lemma {:induction a} distributive(x: int, a: nat, b: nat)
ensures Expt(x, a) * Expt(x, b) == Expt(x, a + b)
|
function Expt(b: int, n: nat): int
requires n >= 0
{
if n == 0 then 1 else b * Expt(b, n - 1)
}
method expt(b: int, n: nat) returns (res: int)
ensures res == Expt(b, n)
{
var i := 1;
res := 1;
while i < n + 1
invariant 0 < i <= n + 1
invariant res == Expt(b, i - 1)
{
res := res * b;
i := i + 1;
}
}
// source: https://www.dcc.fc.up.pt/~nam/web/resources/vfs20/DafnyQuickReference.pdf
lemma {:induction a} distributive(x: int, a: nat, b: nat)
ensures Expt(x, a) * Expt(x, b) == Expt(x, a + b)
|
dafny-programs_tmp_tmpcwodh6qh_src_expt.dfy
|
488
|
488
|
Dafny program: 488
|
function fact(n: nat): nat
ensures fact(n) >= 1
{
if n == 0 then 1 else n * fact(n - 1)
}
method factorial(n: nat) returns (res: nat)
ensures res == fact(n)
{
var i := 1;
res := 1;
while i < n + 1
{
res := i * res;
i := i + 1;
}
}
|
function fact(n: nat): nat
ensures fact(n) >= 1
{
if n == 0 then 1 else n * fact(n - 1)
}
method factorial(n: nat) returns (res: nat)
ensures res == fact(n)
{
var i := 1;
res := 1;
while i < n + 1
invariant 0 < i <= n + 1
invariant res == fact(i - 1) // result satisfies postcondition for every iteration, verification fails without this
{
res := i * res;
i := i + 1;
}
}
|
dafny-programs_tmp_tmpcwodh6qh_src_factorial.dfy
|
491
|
491
|
Dafny program: 491
|
module Rope {
class Rope {
ghost var Contents: string;
ghost var Repr: set<Rope>;
var data: string;
var weight: nat;
var left: Rope?;
var right: Rope?;
ghost predicate Valid()
reads this, Repr
ensures Valid() ==> this in Repr
{
this in Repr &&
(left != null ==>
left in Repr &&
left.Repr < Repr && this !in left.Repr &&
left.Valid() &&
(forall child :: child in left.Repr ==> child.weight <= weight)) &&
(right != null ==>
right in Repr &&
right.Repr < Repr && this !in right.Repr &&
right.Valid()) &&
(left == null && right == null ==>
Repr == {this} &&
Contents == data &&
weight == |data| &&
data != "") &&
(left != null && right == null ==>
Repr == {this} + left.Repr &&
Contents == left.Contents &&
weight == |left.Contents| &&
data == "") &&
(left == null && right != null ==>
Repr == {this} + right.Repr &&
Contents == right.Contents &&
weight == 0 &&
data == "") &&
(left != null && right != null ==>
Repr == {this} + left.Repr + right.Repr &&
left.Repr !! right.Repr &&
Contents == left.Contents + right.Contents &&
weight == |left.Contents| &&
data == "")
}
lemma contentSizeGtZero()
requires Valid()
ensures |Contents| > 0
{}
function getWeightsOfAllRightChildren(): nat
reads right, Repr
requires Valid()
ensures right != null
==> getWeightsOfAllRightChildren() == |right.Contents|
{
if right == null then 0
else right.weight + right.getWeightsOfAllRightChildren()
}
function length(): nat
reads Repr
requires Valid()
ensures |Contents| == length()
{
this.weight + getWeightsOfAllRightChildren()
}
// constructor for creating a terminal node
constructor Terminal(x: string)
requires x != ""
ensures Valid() && fresh(Repr)
&& left == null && right == null
&& data == x
{
data := x;
weight := |x|;
left := null;
right := null;
Contents := x;
Repr := {this};
}
predicate isTerminal()
reads this, this.left, this.right
{ left == null && right == null }
method report(i: nat, j: nat) returns (s: string)
requires 0 <= i <= j <= |this.Contents|
requires Valid()
ensures s == this.Contents[i..j]
{
if i == j {
s := "";
} else {
if this.left == null && this.right == null {
s := data[i..j];
} else {
if (j <= this.weight) {
var s' := this.left.report(i, j);
s := s';
} else if (this.weight <= i) {
var s' := this.right.report(i - this.weight, j - this.weight);
s := s';
} else {
// removing this assertion causes error
var s1 := this.left.report(i, this.weight);
var s2 := this.right.report(0, j - this.weight);
s := s1 + s2;
}
}
}
}
method toString() returns (s: string)
requires Valid()
ensures s == Contents
{
s := report(0, this.length());
}
method getCharAtIndex(index: nat) returns (c: char)
requires Valid() && 0 <= index < |Contents|
ensures c == Contents[index]
{
var nTemp := this;
var i := index;
while (!nTemp.isTerminal())
{
if (i < nTemp.weight) {
nTemp := nTemp.left;
} else {
i := i - nTemp.weight;
nTemp := nTemp.right;
}
}
// Have reached the terminal node with index i
c := nTemp.data[i];
}
static method concat(n1: Rope?, n2: Rope?) returns (n: Rope?)
requires (n1 != null) ==> n1.Valid()
requires (n2 != null) ==> n2.Valid()
requires (n1 != null && n2 != null) ==> (n1.Repr !! n2.Repr)
ensures (n1 != null || n2 != null) <==> n != null && n.Valid()
ensures (n1 == null && n2 == null) <==> n == null
ensures (n1 == null && n2 != null)
==> n == n2 && n != null && n.Valid() && n.Contents == n2.Contents
ensures (n1 != null && n2 == null)
==> n == n1 && n != null && n.Valid() && n.Contents == n1.Contents
ensures (n1 != null && n2 != null)
==> n != null && n.Valid()
&& n.left == n1 && n.right == n2
&& n.Contents == n1.Contents + n2.Contents
&& fresh(n.Repr - n1.Repr - n2.Repr)
{
if (n1 == null) {
n := n2;
} else if (n2 == null) {
n := n1;
} else {
n := new Rope.Terminal("placeholder");
n.left := n1;
n.right := n2;
n.data := "";
var nTemp := n1;
var w := 0;
ghost var nodesTraversed : set<Rope> := {};
while (nTemp.right != null)
==> w + nTemp.weight + |nTemp.right.Contents| == |n1.Contents|
{
w := w + nTemp.weight;
if (nTemp.left != null) {
nodesTraversed := nodesTraversed + nTemp.left.Repr + {nTemp};
} else {
nodesTraversed := nodesTraversed + {nTemp};
}
nTemp := nTemp.right;
}
w := w + nTemp.weight;
if (nTemp.left != null) {
nodesTraversed := nodesTraversed + nTemp.left.Repr + {nTemp};
} else {
nodesTraversed := nodesTraversed + {nTemp};
}
n.weight := w;
n.Contents := n1.Contents + n2.Contents;
n.Repr := {n} + n1.Repr + n2.Repr;
}
}
/**
Dafny needs help to guess that in our definition, every rope must
have non-empty Contents, otherwise it is represented by [null].
The lemma contentSizeGtZero(n) is thus important to prove the
postcondition of this method, in the two places where the lemma is
invoked.
*/
static method split(n: Rope, index: nat) returns (n1: Rope?, n2: Rope?)
requires n.Valid() && 0 <= index <= |n.Contents|
ensures index == 0
==> n1 == null && n2 != null && n2.Valid()
&& n2.Contents == n.Contents && fresh(n2.Repr - n.Repr)
ensures index == |n.Contents|
==> n2 == null && n1 != null && n1.Valid()
&& n1.Contents == n.Contents && fresh(n1.Repr - n.Repr)
ensures 0 < index < |n.Contents|
==> n1 != null && n1.Valid() && n2 != null && n2.Valid()
&& n1.Contents == n.Contents[..index]
&& n2.Contents == n.Contents[index..]
&& n1.Repr !! n2.Repr
&& fresh(n1.Repr - n.Repr) && fresh(n2.Repr - n.Repr)
{
if (index == 0) {
n1 := null;
n2 := n;
n.contentSizeGtZero();
// assert index != |n.Contents|;
} else if (index < n.weight) {
if (n.left != null) {
var s1, s2 := split(n.left, index);
n1 := s1;
n2 := concat(s2, n.right);
} else {
// terminal node
if (index == 0) {
n1 := null;
n2 := n;
} else {
n1 := new Rope.Terminal(n.data[..index]);
n2 := new Rope.Terminal(n.data[index..]);
}
}
} else if (index > n.weight) {
var s1, s2 := split(n.right, index - n.weight);
n1 := concat(n.left, s1);
n2 := s2;
} else {
// since [n.weight == index != 0], it means that [n] cannot be a
// non-terminal node with [left == null].
if (n.left != null && n.right == null) {
n1 := n.left;
n2 := null;
} else if (n.left != null && n.right != null) {
n.right.contentSizeGtZero();
// assert index != |n.Contents|;
n1 := n.left;
n2 := n.right;
} else {
n1 := n;
n2 := null;
}
}
}
static method insert(n1: Rope, n2: Rope, index: nat) returns (n: Rope)
requires n1.Valid() && n2.Valid() && n1.Repr !! n2.Repr
requires 0 <= index < |n1.Contents|
ensures n.Valid()
&& n.Contents ==
n1.Contents[..index] + n2.Contents + n1.Contents[index..]
&& fresh(n.Repr - n1.Repr - n2.Repr)
{
var n1BeforeIndex, n1AfterIndex := split(n1, index);
var firstPart := concat(n1BeforeIndex, n2);
n := concat(firstPart, n1AfterIndex);
}
static method delete(n: Rope, i: nat, j: nat) returns (m: Rope?)
requires n.Valid()
requires 0 <= i < j <= |n.Contents|
ensures (i == 0 && j == |n.Contents|) <==> m == null
ensures m != null ==>
m.Valid() &&
m.Contents == n.Contents[..i] + n.Contents[j..] &&
fresh(m.Repr - n.Repr)
{
var l1, l2 := split(n, i);
var r1, r2 := split(l2, j - i);
m := concat(l1, r2);
}
static method substring(n: Rope, i: nat, j: nat) returns (m: Rope?)
requires n.Valid()
requires 0 <= i < j <= |n.Contents|
ensures (i == j) <==> m == null
ensures m != null ==>
m.Valid() &&
m.Contents == n.Contents[i..j] &&
fresh(m.Repr - n.Repr)
{
var l1, l2 := split(n, i);
var r1, r2 := split(l2, j - i);
m := r1;
}
}
// End of Rope Class
}
// End of Rope Module
|
module Rope {
class Rope {
ghost var Contents: string;
ghost var Repr: set<Rope>;
var data: string;
var weight: nat;
var left: Rope?;
var right: Rope?;
ghost predicate Valid()
reads this, Repr
ensures Valid() ==> this in Repr
{
this in Repr &&
(left != null ==>
left in Repr &&
left.Repr < Repr && this !in left.Repr &&
left.Valid() &&
(forall child :: child in left.Repr ==> child.weight <= weight)) &&
(right != null ==>
right in Repr &&
right.Repr < Repr && this !in right.Repr &&
right.Valid()) &&
(left == null && right == null ==>
Repr == {this} &&
Contents == data &&
weight == |data| &&
data != "") &&
(left != null && right == null ==>
Repr == {this} + left.Repr &&
Contents == left.Contents &&
weight == |left.Contents| &&
data == "") &&
(left == null && right != null ==>
Repr == {this} + right.Repr &&
Contents == right.Contents &&
weight == 0 &&
data == "") &&
(left != null && right != null ==>
Repr == {this} + left.Repr + right.Repr &&
left.Repr !! right.Repr &&
Contents == left.Contents + right.Contents &&
weight == |left.Contents| &&
data == "")
}
lemma contentSizeGtZero()
requires Valid()
ensures |Contents| > 0
decreases Repr
{}
function getWeightsOfAllRightChildren(): nat
reads right, Repr
requires Valid()
decreases Repr
ensures right != null
==> getWeightsOfAllRightChildren() == |right.Contents|
{
if right == null then 0
else right.weight + right.getWeightsOfAllRightChildren()
}
function length(): nat
reads Repr
requires Valid()
ensures |Contents| == length()
{
this.weight + getWeightsOfAllRightChildren()
}
// constructor for creating a terminal node
constructor Terminal(x: string)
requires x != ""
ensures Valid() && fresh(Repr)
&& left == null && right == null
&& data == x
{
data := x;
weight := |x|;
left := null;
right := null;
Contents := x;
Repr := {this};
}
predicate isTerminal()
reads this, this.left, this.right
{ left == null && right == null }
method report(i: nat, j: nat) returns (s: string)
requires 0 <= i <= j <= |this.Contents|
requires Valid()
ensures s == this.Contents[i..j]
decreases Repr
{
if i == j {
s := "";
} else {
if this.left == null && this.right == null {
s := data[i..j];
} else {
if (j <= this.weight) {
var s' := this.left.report(i, j);
s := s';
} else if (this.weight <= i) {
var s' := this.right.report(i - this.weight, j - this.weight);
s := s';
} else {
// removing this assertion causes error
assert i <= this.weight < j;
var s1 := this.left.report(i, this.weight);
var s2 := this.right.report(0, j - this.weight);
s := s1 + s2;
}
}
}
}
method toString() returns (s: string)
requires Valid()
ensures s == Contents
{
s := report(0, this.length());
}
method getCharAtIndex(index: nat) returns (c: char)
requires Valid() && 0 <= index < |Contents|
ensures c == Contents[index]
{
var nTemp := this;
var i := index;
while (!nTemp.isTerminal())
invariant nTemp != null;
invariant nTemp.Valid()
invariant 0 <= i < |nTemp.Contents|
invariant nTemp.Contents[i] == Contents[index]
decreases nTemp.Repr
{
if (i < nTemp.weight) {
nTemp := nTemp.left;
} else {
i := i - nTemp.weight;
nTemp := nTemp.right;
}
}
// Have reached the terminal node with index i
c := nTemp.data[i];
}
static method concat(n1: Rope?, n2: Rope?) returns (n: Rope?)
requires (n1 != null) ==> n1.Valid()
requires (n2 != null) ==> n2.Valid()
requires (n1 != null && n2 != null) ==> (n1.Repr !! n2.Repr)
ensures (n1 != null || n2 != null) <==> n != null && n.Valid()
ensures (n1 == null && n2 == null) <==> n == null
ensures (n1 == null && n2 != null)
==> n == n2 && n != null && n.Valid() && n.Contents == n2.Contents
ensures (n1 != null && n2 == null)
==> n == n1 && n != null && n.Valid() && n.Contents == n1.Contents
ensures (n1 != null && n2 != null)
==> n != null && n.Valid()
&& n.left == n1 && n.right == n2
&& n.Contents == n1.Contents + n2.Contents
&& fresh(n.Repr - n1.Repr - n2.Repr)
{
if (n1 == null) {
n := n2;
} else if (n2 == null) {
n := n1;
} else {
n := new Rope.Terminal("placeholder");
n.left := n1;
n.right := n2;
n.data := "";
var nTemp := n1;
var w := 0;
ghost var nodesTraversed : set<Rope> := {};
while (nTemp.right != null)
invariant nTemp != null
invariant nTemp.Valid()
invariant forall node :: node in nodesTraversed ==> node.weight <= w
invariant nodesTraversed == n1.Repr - nTemp.Repr
invariant nTemp.right == null ==> w + nTemp.weight == |n1.Contents|
invariant nTemp.right != null
==> w + nTemp.weight + |nTemp.right.Contents| == |n1.Contents|
decreases nTemp.Repr
{
w := w + nTemp.weight;
assert w >= 0;
if (nTemp.left != null) {
nodesTraversed := nodesTraversed + nTemp.left.Repr + {nTemp};
} else {
nodesTraversed := nodesTraversed + {nTemp};
}
nTemp := nTemp.right;
}
w := w + nTemp.weight;
if (nTemp.left != null) {
nodesTraversed := nodesTraversed + nTemp.left.Repr + {nTemp};
} else {
nodesTraversed := nodesTraversed + {nTemp};
}
n.weight := w;
n.Contents := n1.Contents + n2.Contents;
n.Repr := {n} + n1.Repr + n2.Repr;
}
}
/**
Dafny needs help to guess that in our definition, every rope must
have non-empty Contents, otherwise it is represented by [null].
The lemma contentSizeGtZero(n) is thus important to prove the
postcondition of this method, in the two places where the lemma is
invoked.
*/
static method split(n: Rope, index: nat) returns (n1: Rope?, n2: Rope?)
requires n.Valid() && 0 <= index <= |n.Contents|
ensures index == 0
==> n1 == null && n2 != null && n2.Valid()
&& n2.Contents == n.Contents && fresh(n2.Repr - n.Repr)
ensures index == |n.Contents|
==> n2 == null && n1 != null && n1.Valid()
&& n1.Contents == n.Contents && fresh(n1.Repr - n.Repr)
ensures 0 < index < |n.Contents|
==> n1 != null && n1.Valid() && n2 != null && n2.Valid()
&& n1.Contents == n.Contents[..index]
&& n2.Contents == n.Contents[index..]
&& n1.Repr !! n2.Repr
&& fresh(n1.Repr - n.Repr) && fresh(n2.Repr - n.Repr)
decreases n.Repr
{
if (index == 0) {
n1 := null;
n2 := n;
n.contentSizeGtZero();
// assert index != |n.Contents|;
} else if (index < n.weight) {
if (n.left != null) {
var s1, s2 := split(n.left, index);
n1 := s1;
n2 := concat(s2, n.right);
} else {
// terminal node
assert n.isTerminal();
if (index == 0) {
n1 := null;
n2 := n;
} else {
n1 := new Rope.Terminal(n.data[..index]);
n2 := new Rope.Terminal(n.data[index..]);
}
}
} else if (index > n.weight) {
var s1, s2 := split(n.right, index - n.weight);
n1 := concat(n.left, s1);
n2 := s2;
} else {
// since [n.weight == index != 0], it means that [n] cannot be a
// non-terminal node with [left == null].
if (n.left != null && n.right == null) {
n1 := n.left;
n2 := null;
} else if (n.left != null && n.right != null) {
n.right.contentSizeGtZero();
// assert index != |n.Contents|;
n1 := n.left;
n2 := n.right;
} else {
assert n.left == null && n.right == null;
n1 := n;
n2 := null;
}
}
}
static method insert(n1: Rope, n2: Rope, index: nat) returns (n: Rope)
requires n1.Valid() && n2.Valid() && n1.Repr !! n2.Repr
requires 0 <= index < |n1.Contents|
ensures n.Valid()
&& n.Contents ==
n1.Contents[..index] + n2.Contents + n1.Contents[index..]
&& fresh(n.Repr - n1.Repr - n2.Repr)
{
var n1BeforeIndex, n1AfterIndex := split(n1, index);
var firstPart := concat(n1BeforeIndex, n2);
n := concat(firstPart, n1AfterIndex);
}
static method delete(n: Rope, i: nat, j: nat) returns (m: Rope?)
requires n.Valid()
requires 0 <= i < j <= |n.Contents|
ensures (i == 0 && j == |n.Contents|) <==> m == null
ensures m != null ==>
m.Valid() &&
m.Contents == n.Contents[..i] + n.Contents[j..] &&
fresh(m.Repr - n.Repr)
{
var l1, l2 := split(n, i);
var r1, r2 := split(l2, j - i);
m := concat(l1, r2);
}
static method substring(n: Rope, i: nat, j: nat) returns (m: Rope?)
requires n.Valid()
requires 0 <= i < j <= |n.Contents|
ensures (i == j) <==> m == null
ensures m != null ==>
m.Valid() &&
m.Contents == n.Contents[i..j] &&
fresh(m.Repr - n.Repr)
{
var l1, l2 := split(n, i);
var r1, r2 := split(l2, j - i);
m := r1;
}
}
// End of Rope Class
}
// End of Rope Module
|
dafny-rope_tmp_tmpl4v_njmy_Rope.dfy
|
492
|
492
|
Dafny program: 492
|
// Proving type safety of a Simply Typed Lambda-Calculus in Dafny
// adapted from Coq (http://www.cis.upenn.edu/~bcpierce/sf/Stlc.html)
/// Utilities
// ... handy for partial functions
datatype option<A> = None | Some(get: A)
/// -----
/// Model
/// -----
/// Syntax
// Types
datatype ty = TBase // (opaque base type)
| TArrow(T1: ty, T2: ty) // T1 => T2
/*BOOL?
| TBool // (base type for booleans)
?BOOL*/
/*NAT?
| TNat // (base type for naturals)
?NAT*/
/*REC?
| TVar(id: int) | TRec(X: nat, T: ty)// (iso-recursive types)
?REC*/
// Terms
datatype tm = tvar(id: int) // x (variable)
| tapp(f: tm, arg: tm) // t t (application)
| tabs(x: int, T: ty, body: tm) // \x:T.t (abstraction)
/*BOOL?
| ttrue | tfalse // true, false (boolean values)
| tif(c: tm, a: tm, b: tm) // if t then t else t (if expression)
?BOOL*/
/*NAT?
| tzero | tsucc(p: tm) | tprev(n: tm)// (naturals)
/*BOOL?
| teq(n1: tm, n2: tm) // (equality on naturals)
?BOOL*/
?NAT*/
/*REC?
| tfold(Tf: ty, tf: tm) | tunfold(tu: tm)// (iso-recursive terms)
?REC*/
/// Operational Semantics
// Values
predicate value(t: tm)
{
t.tabs?
/*BOOL?
|| t.ttrue? || t.tfalse?
?BOOL*/
/*NAT?
|| peano(t)
?NAT*/
/*REC?
|| (t.tfold? && value(t.tf))
?REC*/
}
/*NAT?
predicate peano(t: tm)
{
t.tzero? || (t.tsucc? && peano(t.p))
}
?NAT*/
// Free Variables and Substitution
function fv(t: tm): set<int> //of free variables of t
{
match t
// interesting cases...
case tvar(id) => {id}
case tabs(x, T, body) => fv(body)-{x}//x is bound
// congruent cases...
case tapp(f, arg) => fv(f)+fv(arg)
/*BOOL?
case tif(c, a, b) => fv(a)+fv(b)+fv(c)
case ttrue => {}
case tfalse => {}
?BOOL*/
/*NAT?
case tzero => {}
case tsucc(p) => fv(p)
case tprev(n) => fv(n)
/*BOOL?
case teq(n1, n2) => fv(n1)+fv(n2)
?BOOL*/
?NAT*/
/*REC?
case tfold(T, t1) => fv(t1)
case tunfold(t1) => fv(t1)
?REC*/
}
function subst(x: int, s: tm, t: tm): tm //[x -> s]t
{
match t
// interesting cases...
case tvar(x') => if x==x' then s else t
// N.B. only capture-avoiding if s is closed...
case tabs(x', T, t1) => tabs(x', T, if x==x' then t1 else subst(x, s, t1))
// congruent cases...
case tapp(t1, t2) => tapp(subst(x, s, t1), subst(x, s, t2))
/*BOOL?
case ttrue => ttrue
case tfalse => tfalse
case tif(t1, t2, t3) => tif(subst(x, s, t1), subst(x, s, t2), subst(x, s, t3))
?BOOL*/
/*NAT?
case tzero => tzero
case tsucc(p) => tsucc(subst(x, s, p))
case tprev(n) => tprev(subst(x, s, n))
/*BOOL?
case teq(n1, n2) => teq(subst(x, s, n1), subst(x, s, n2))
?BOOL*/
?NAT*/
/*REC?
case tfold(T, t1) => tfold(T, subst(x, s, t1))
case tunfold(t1) => tunfold(subst(x, s, t1))
?REC*/
}
/*REC?
function ty_fv(T: ty): set<int> //of free type variables of T
{
match T
case TVar(X) => {X}
case TRec(X, T1) => ty_fv(T1)-{X}
case TArrow(T1, T2) => ty_fv(T1)+ty_fv(T2)
case TBase => {}
/*BOOL?
case TBool => {}
?BOOL*/
/*NAT?
case TNat => {}
?NAT*/
}
function tsubst(X: int, S: ty, T: ty): ty
{
match T
case TVar(X') => if X==X' then S else T
case TRec(X', T1) => TRec(X', if X==X' then T1 else tsubst(X, S, T1))
case TArrow(T1, T2) => TArrow(tsubst(X, S, T1), tsubst(X, S, T2))
case TBase => TBase
/*BOOL?
case TBool => TBool
?BOOL*/
/*NAT?
case TNat => TNat
?NAT*/
}
predicate ty_closed(T: ty)
{
forall x :: x !in ty_fv(T)
}
?REC*/
// Reduction
function step(t: tm): option<tm>
{
/* AppAbs */ if (t.tapp? && t.f.tabs? && value(t.arg)) then
Some(subst(t.f.x, t.arg, t.f.body))
/* App1 */ else if (t.tapp? && step(t.f).Some?) then
Some(tapp(step(t.f).get, t.arg))
/* App2 */ else if (t.tapp? && value(t.f) && step(t.arg).Some?) then
Some(tapp(t.f, step(t.arg).get))
/*BOOL?
/* IfTrue */ else if (t.tif? && t.c == ttrue) then
Some(t.a)
/* IfFalse */ else if (t.tif? && t.c == tfalse) then
Some(t.b)
/* If */ else if (t.tif? && step(t.c).Some?) then
Some(tif(step(t.c).get, t.a, t.b))
?BOOL*/
/*NAT?
/* Prev0 */
else if (t.tprev? && t.n.tzero?) then
Some(tzero)
/* PrevSucc */ else if (t.tprev? && peano(t.n) && t.n.tsucc?) then
Some(t.n.p)
/* Prev */ else if (t.tprev? && step(t.n).Some?) then
Some(tprev(step(t.n).get))
/* Succ */ else if (t.tsucc? && step(t.p).Some?) then
Some(tsucc(step(t.p).get))
/*BOOL?
/* EqTrue0 */ else if (t.teq? && t.n1.tzero? && t.n2.tzero?) then
Some(ttrue)
/* EqFalse1 */ else if (t.teq? && t.n1.tsucc? && peano(t.n1) && t.n2.tzero?) then
Some(tfalse)
/* EqFalse2 */ else if (t.teq? && t.n1.tzero? && t.n2.tsucc? && peano(t.n2)) then
Some(tfalse)
/* EqRec */ else if (t.teq? && t.n1.tsucc? && t.n2.tsucc? && peano(t.n1) && peano(t.n2)) then
Some(teq(t.n1.p, t.n2.p))
/* Eq1 */ else if (t.teq? && step(t.n1).Some?) then
Some(teq(step(t.n1).get, t.n2))
/* Eq2 */ else if (t.teq? && peano(t.n1) && step(t.n2).Some?) then
Some(teq(t.n1, step(t.n2).get))
?BOOL*/
?NAT*/
/*REC?
/* UnfoldFold */ else if (t.tunfold? && t.tu.tfold? && value(t.tu.tf)) then Some(t.tu.tf)
/* Fold */ else if (t.tfold? && step(t.tf).Some?) then Some(tfold(t.Tf, step(t.tf).get))
/* Unfold */ else if (t.tunfold? && step(t.tu).Some?) then Some(tunfold(step(t.tu).get))
?REC*/
else None
}
// Multistep reduction:
// The term t reduces to the term t' in n or less number of steps.
predicate reduces_to(t: tm, t': tm, n: nat)
{
t == t' || (n > 0 && step(t).Some? && reduces_to(step(t).get, t', n-1))
}
// Examples
lemma lemma_step_example1(n: nat)
requires n > 0;
// (\x:B=>B.x) (\x:B.x) reduces to (\x:B.x)
ensures reduces_to(tapp(tabs(0, TArrow(TBase, TBase), tvar(0)), tabs(0, TBase, tvar(0))),
tabs(0, TBase, tvar(0)), n);
{
}
/// Typing
// A context is a partial map from variable names to types.
function find(c: map<int,ty>, x: int): option<ty>
{
if (x in c) then Some(c[x]) else None
}
function extend(x: int, T: ty, c: map<int,ty>): map<int,ty>
{
c[x:=T]
}
// Typing Relation
function has_type(c: map<int,ty>, t: tm): option<ty>
{
match t
/* Var */ case tvar(id) => find(c, id)
/* Abs */ case tabs(x, T, body) =>
var ty_body := has_type(extend(x, T, c), body);
if (ty_body.Some?) then
Some(TArrow(T, ty_body.get)) else None
/* App */ case tapp(f, arg) =>
var ty_f := has_type(c, f);
var ty_arg := has_type(c, arg);
if (ty_f.Some? && ty_arg.Some?) then
if ty_f.get.TArrow? && ty_f.get.T1 == ty_arg.get then
Some(ty_f.get.T2) else None else None
/*BOOL?
/* True */ case ttrue => Some(TBool)
/* False */ case tfalse => Some(TBool)
/* If */ case tif(cond, a, b) =>
var ty_c := has_type(c, cond);
var ty_a := has_type(c, a);
var ty_b := has_type(c, b);
if (ty_c.Some? && ty_a.Some? && ty_b.Some?) then
if ty_c.get == TBool && ty_a.get == ty_b.get then
ty_a
else None else None
?BOOL*/
/*NAT?
/* Zero */ case tzero => Some(TNat)
/* Prev */ case tprev(n) =>
var ty_n := has_type(c, n);
if (ty_n.Some?) then
if ty_n.get == TNat then
Some(TNat) else None else None
/* Succ */ case tsucc(p) =>
var ty_p := has_type(c, p);
if (ty_p.Some?) then
if ty_p.get == TNat then
Some(TNat) else None else None
/*BOOL?
/* Eq */ case teq(n1, n2) =>
var ty_n1 := has_type(c, n1);
var ty_n2 := has_type(c, n2);
if (ty_n1.Some? && ty_n2.Some?) then
if ty_n1.get == TNat && ty_n2.get == TNat then
Some(TBool) else None else None
?BOOL*/
?NAT*/
/*REC?
/* Fold */ case tfold(U, t1) =>
var ty_t1 := if (ty_closed(U)) then has_type(c, t1) else None;
if (ty_t1.Some?) then
if U.TRec? && ty_t1.get==tsubst(U.X, U, U.T) then
Some(U) else None else None
/* Unfold */ case tunfold(t1) =>
var ty_t1 := has_type(c, t1);
if ty_t1.Some? then
var U := ty_t1.get;
if U.TRec? then
Some(tsubst(U.X, U, U.T)) else None else None
?REC*/
}
// Examples
lemma example_typing_1()
ensures has_type(map[], tabs(0, TBase, tvar(0))) == Some(TArrow(TBase, TBase));
{
}
lemma example_typing_2()
ensures has_type(map[], tabs(0, TBase, tabs(1, TArrow(TBase, TBase), tapp(tvar(1), tapp(tvar(1), tvar(0)))))) ==
Some(TArrow(TBase, TArrow(TArrow(TBase, TBase), TBase)));
{
var c := extend(1, TArrow(TBase, TBase), extend(0, TBase, map[]));
}
lemma nonexample_typing_1()
ensures has_type(map[], tabs(0, TBase, tabs(1, TBase, tapp(tvar(0), tvar(1))))) == None;
{
var c := extend(1, TBase, extend(0, TBase, map[]));
}
lemma nonexample_typing_3(S: ty, T: ty)
ensures has_type(map[], tabs(0, S, tapp(tvar(0), tvar(0)))) != Some(T);
{
var c := extend(0, S, map[]);
}
/*BOOL?
lemma example_typing_bool()
ensures has_type(map[], tabs(0, TBase, tabs(1, TBase, tabs(2, TBool, tif(tvar(2), tvar(0), tvar(1)))))) ==
Some(TArrow(TBase, TArrow(TBase, TArrow(TBool, TBase))));
{
var c0 := extend(0, TBase, map[]);
var c1 := extend(1, TBase, c0);
var c2 := extend(2, TBool, c1);
}
?BOOL*/
/*NAT?
lemma example_typing_nat()
ensures has_type(map[], tabs(0, TNat, tprev(tvar(0)))) == Some(TArrow(TNat, TNat));
{
var c := extend(0, TNat, map[]);
}
?NAT*/
/*REC?
// TODO
lemma example_typing_rec()
// ∅ |- foldµT. T→α(λx : µT. T → α. (unfold x) x) : µT. T → α
ensures has_type(map[], tfold(TRec(0, TArrow(TVar(0), TBase)), tabs(0, TRec(0, TArrow(TVar(0), TBase)), tapp(tunfold(tvar(0)), tvar(0))))) ==
Some(TRec(0, TArrow(TVar(0), TBase)));
{
var R := TRec(0, TArrow(TVar(0), TBase));
var c := extend(0, R, map[]);
//{x : µT. T → α} x : µT. T → α
//{x : µT. T → α} (unfold x):(µT. T → α) → α {x : µT. T → α} x : µT. T → α
//{x : µT. T → α} ( (unfold x) x)) : α
//∅ (λx : µT. T → α. (unfold x) x)) :(µT. T → α) → α
}
?REC*/
/// -----------------------
/// Type-Safety Properties
/// -----------------------
// Progress:
// A well-typed term is either a value or it can step.
lemma theorem_progress(t: tm)
requires has_type(map[], t).Some?;
ensures value(t) || step(t).Some?;
{
}
// Towards preservation and the substitution lemma
// If x is free in t and t is well-typed in some context,
// then this context must contain x.
lemma {:induction c, t} lemma_free_in_context(c: map<int,ty>, x: int, t: tm)
requires x in fv(t);
requires has_type(c, t).Some?;
ensures find(c, x).Some?;
{
}
// A closed term does not contain any free variables.
// N.B. We're only interested in proving type soundness of closed terms.
predicate closed(t: tm)
{
forall x :: x !in fv(t)
}
// If a term can be well-typed in an empty context,
// then it is closed.
lemma corollary_typable_empty__closed(t: tm)
requires has_type(map[], t).Some?;
ensures closed(t);
{
forall (x:int) ensures x !in fv(t);
{
if (x in fv(t)) {
lemma_free_in_context(map[], x, t);
}
}
}
// If a term t is well-typed in context c,
// and context c' agrees with c on all free variables of t,
// then the term t is well-typed in context c',
// with the same type as in context c.
lemma {:induction t} lemma_context_invariance(c: map<int,ty>, c': map<int,ty>, t: tm)
requires has_type(c, t).Some?;
requires forall x: int :: x in fv(t) ==> find(c, x) == find(c', x);
ensures has_type(c, t) == has_type(c', t);
{
if (t.tabs?) {
lemma_context_invariance(extend(t.x, t.T, c), extend(t.x, t.T, c'), t.body);
}
}
// Substitution preserves typing:
// If s has type S in an empty context,
// and t has type T in a context extended with x having type S,
// then [x -> s]t has type T as well.
lemma lemma_substitution_preserves_typing(c: map<int,ty>, x: int, s: tm, t: tm)
requires has_type(map[], s).Some?;
requires has_type(extend(x, has_type(map[], s).get, c), t).Some?;
ensures has_type(c, subst(x, s, t)) == has_type(extend(x, has_type(map[], s).get, c), t);
{
var S := has_type(map[], s).get;
var cs := extend(x, S, c);
var T := has_type(cs, t).get;
if (t.tvar?) {
if (t.id==x) {
corollary_typable_empty__closed(s);
lemma_context_invariance(map[], c, s);
}
}
if (t.tabs?) {
if (t.x==x) {
lemma_context_invariance(cs, c, t);
} else {
var cx := extend(t.x, t.T, c);
var csx := extend(x, S, cx);
var cxs := extend(t.x, t.T, cs);
lemma_context_invariance(cxs, csx, t.body);
lemma_substitution_preserves_typing(cx, x, s, t.body);
}
}
}
// Preservation:
// A well-type term which steps preserves its type.
lemma theorem_preservation(t: tm)
requires has_type(map[], t).Some?;
requires step(t).Some?;
ensures has_type(map[], step(t).get) == has_type(map[], t);
{
if (t.tapp? && value(t.f) && value(t.arg)) {
lemma_substitution_preserves_typing(map[], t.f.x, t.arg, t.f.body);
}
}
// A normal form cannot step.
predicate normal_form(t: tm)
{
step(t).None?
}
// A stuck term is a normal form that is not a value.
predicate stuck(t: tm)
{
normal_form(t) && !value(t)
}
// Type soundness:
// A well-typed term cannot be stuck.
lemma corollary_soundness(t: tm, t': tm, T: ty, n: nat)
requires has_type(map[], t) == Some(T);
requires reduces_to(t, t', n);
ensures !stuck(t');
{
theorem_progress(t);
if (t != t') {
theorem_preservation(t);
corollary_soundness(step(t).get, t', T, n-1);
}
}
/// QED
|
// Proving type safety of a Simply Typed Lambda-Calculus in Dafny
// adapted from Coq (http://www.cis.upenn.edu/~bcpierce/sf/Stlc.html)
/// Utilities
// ... handy for partial functions
datatype option<A> = None | Some(get: A)
/// -----
/// Model
/// -----
/// Syntax
// Types
datatype ty = TBase // (opaque base type)
| TArrow(T1: ty, T2: ty) // T1 => T2
/*BOOL?
| TBool // (base type for booleans)
?BOOL*/
/*NAT?
| TNat // (base type for naturals)
?NAT*/
/*REC?
| TVar(id: int) | TRec(X: nat, T: ty)// (iso-recursive types)
?REC*/
// Terms
datatype tm = tvar(id: int) // x (variable)
| tapp(f: tm, arg: tm) // t t (application)
| tabs(x: int, T: ty, body: tm) // \x:T.t (abstraction)
/*BOOL?
| ttrue | tfalse // true, false (boolean values)
| tif(c: tm, a: tm, b: tm) // if t then t else t (if expression)
?BOOL*/
/*NAT?
| tzero | tsucc(p: tm) | tprev(n: tm)// (naturals)
/*BOOL?
| teq(n1: tm, n2: tm) // (equality on naturals)
?BOOL*/
?NAT*/
/*REC?
| tfold(Tf: ty, tf: tm) | tunfold(tu: tm)// (iso-recursive terms)
?REC*/
/// Operational Semantics
// Values
predicate value(t: tm)
{
t.tabs?
/*BOOL?
|| t.ttrue? || t.tfalse?
?BOOL*/
/*NAT?
|| peano(t)
?NAT*/
/*REC?
|| (t.tfold? && value(t.tf))
?REC*/
}
/*NAT?
predicate peano(t: tm)
{
t.tzero? || (t.tsucc? && peano(t.p))
}
?NAT*/
// Free Variables and Substitution
function fv(t: tm): set<int> //of free variables of t
{
match t
// interesting cases...
case tvar(id) => {id}
case tabs(x, T, body) => fv(body)-{x}//x is bound
// congruent cases...
case tapp(f, arg) => fv(f)+fv(arg)
/*BOOL?
case tif(c, a, b) => fv(a)+fv(b)+fv(c)
case ttrue => {}
case tfalse => {}
?BOOL*/
/*NAT?
case tzero => {}
case tsucc(p) => fv(p)
case tprev(n) => fv(n)
/*BOOL?
case teq(n1, n2) => fv(n1)+fv(n2)
?BOOL*/
?NAT*/
/*REC?
case tfold(T, t1) => fv(t1)
case tunfold(t1) => fv(t1)
?REC*/
}
function subst(x: int, s: tm, t: tm): tm //[x -> s]t
{
match t
// interesting cases...
case tvar(x') => if x==x' then s else t
// N.B. only capture-avoiding if s is closed...
case tabs(x', T, t1) => tabs(x', T, if x==x' then t1 else subst(x, s, t1))
// congruent cases...
case tapp(t1, t2) => tapp(subst(x, s, t1), subst(x, s, t2))
/*BOOL?
case ttrue => ttrue
case tfalse => tfalse
case tif(t1, t2, t3) => tif(subst(x, s, t1), subst(x, s, t2), subst(x, s, t3))
?BOOL*/
/*NAT?
case tzero => tzero
case tsucc(p) => tsucc(subst(x, s, p))
case tprev(n) => tprev(subst(x, s, n))
/*BOOL?
case teq(n1, n2) => teq(subst(x, s, n1), subst(x, s, n2))
?BOOL*/
?NAT*/
/*REC?
case tfold(T, t1) => tfold(T, subst(x, s, t1))
case tunfold(t1) => tunfold(subst(x, s, t1))
?REC*/
}
/*REC?
function ty_fv(T: ty): set<int> //of free type variables of T
{
match T
case TVar(X) => {X}
case TRec(X, T1) => ty_fv(T1)-{X}
case TArrow(T1, T2) => ty_fv(T1)+ty_fv(T2)
case TBase => {}
/*BOOL?
case TBool => {}
?BOOL*/
/*NAT?
case TNat => {}
?NAT*/
}
function tsubst(X: int, S: ty, T: ty): ty
{
match T
case TVar(X') => if X==X' then S else T
case TRec(X', T1) => TRec(X', if X==X' then T1 else tsubst(X, S, T1))
case TArrow(T1, T2) => TArrow(tsubst(X, S, T1), tsubst(X, S, T2))
case TBase => TBase
/*BOOL?
case TBool => TBool
?BOOL*/
/*NAT?
case TNat => TNat
?NAT*/
}
predicate ty_closed(T: ty)
{
forall x :: x !in ty_fv(T)
}
?REC*/
// Reduction
function step(t: tm): option<tm>
{
/* AppAbs */ if (t.tapp? && t.f.tabs? && value(t.arg)) then
Some(subst(t.f.x, t.arg, t.f.body))
/* App1 */ else if (t.tapp? && step(t.f).Some?) then
Some(tapp(step(t.f).get, t.arg))
/* App2 */ else if (t.tapp? && value(t.f) && step(t.arg).Some?) then
Some(tapp(t.f, step(t.arg).get))
/*BOOL?
/* IfTrue */ else if (t.tif? && t.c == ttrue) then
Some(t.a)
/* IfFalse */ else if (t.tif? && t.c == tfalse) then
Some(t.b)
/* If */ else if (t.tif? && step(t.c).Some?) then
Some(tif(step(t.c).get, t.a, t.b))
?BOOL*/
/*NAT?
/* Prev0 */
else if (t.tprev? && t.n.tzero?) then
Some(tzero)
/* PrevSucc */ else if (t.tprev? && peano(t.n) && t.n.tsucc?) then
Some(t.n.p)
/* Prev */ else if (t.tprev? && step(t.n).Some?) then
Some(tprev(step(t.n).get))
/* Succ */ else if (t.tsucc? && step(t.p).Some?) then
Some(tsucc(step(t.p).get))
/*BOOL?
/* EqTrue0 */ else if (t.teq? && t.n1.tzero? && t.n2.tzero?) then
Some(ttrue)
/* EqFalse1 */ else if (t.teq? && t.n1.tsucc? && peano(t.n1) && t.n2.tzero?) then
Some(tfalse)
/* EqFalse2 */ else if (t.teq? && t.n1.tzero? && t.n2.tsucc? && peano(t.n2)) then
Some(tfalse)
/* EqRec */ else if (t.teq? && t.n1.tsucc? && t.n2.tsucc? && peano(t.n1) && peano(t.n2)) then
Some(teq(t.n1.p, t.n2.p))
/* Eq1 */ else if (t.teq? && step(t.n1).Some?) then
Some(teq(step(t.n1).get, t.n2))
/* Eq2 */ else if (t.teq? && peano(t.n1) && step(t.n2).Some?) then
Some(teq(t.n1, step(t.n2).get))
?BOOL*/
?NAT*/
/*REC?
/* UnfoldFold */ else if (t.tunfold? && t.tu.tfold? && value(t.tu.tf)) then Some(t.tu.tf)
/* Fold */ else if (t.tfold? && step(t.tf).Some?) then Some(tfold(t.Tf, step(t.tf).get))
/* Unfold */ else if (t.tunfold? && step(t.tu).Some?) then Some(tunfold(step(t.tu).get))
?REC*/
else None
}
// Multistep reduction:
// The term t reduces to the term t' in n or less number of steps.
predicate reduces_to(t: tm, t': tm, n: nat)
decreases n;
{
t == t' || (n > 0 && step(t).Some? && reduces_to(step(t).get, t', n-1))
}
// Examples
lemma lemma_step_example1(n: nat)
requires n > 0;
// (\x:B=>B.x) (\x:B.x) reduces to (\x:B.x)
ensures reduces_to(tapp(tabs(0, TArrow(TBase, TBase), tvar(0)), tabs(0, TBase, tvar(0))),
tabs(0, TBase, tvar(0)), n);
{
}
/// Typing
// A context is a partial map from variable names to types.
function find(c: map<int,ty>, x: int): option<ty>
{
if (x in c) then Some(c[x]) else None
}
function extend(x: int, T: ty, c: map<int,ty>): map<int,ty>
{
c[x:=T]
}
// Typing Relation
function has_type(c: map<int,ty>, t: tm): option<ty>
decreases t;
{
match t
/* Var */ case tvar(id) => find(c, id)
/* Abs */ case tabs(x, T, body) =>
var ty_body := has_type(extend(x, T, c), body);
if (ty_body.Some?) then
Some(TArrow(T, ty_body.get)) else None
/* App */ case tapp(f, arg) =>
var ty_f := has_type(c, f);
var ty_arg := has_type(c, arg);
if (ty_f.Some? && ty_arg.Some?) then
if ty_f.get.TArrow? && ty_f.get.T1 == ty_arg.get then
Some(ty_f.get.T2) else None else None
/*BOOL?
/* True */ case ttrue => Some(TBool)
/* False */ case tfalse => Some(TBool)
/* If */ case tif(cond, a, b) =>
var ty_c := has_type(c, cond);
var ty_a := has_type(c, a);
var ty_b := has_type(c, b);
if (ty_c.Some? && ty_a.Some? && ty_b.Some?) then
if ty_c.get == TBool && ty_a.get == ty_b.get then
ty_a
else None else None
?BOOL*/
/*NAT?
/* Zero */ case tzero => Some(TNat)
/* Prev */ case tprev(n) =>
var ty_n := has_type(c, n);
if (ty_n.Some?) then
if ty_n.get == TNat then
Some(TNat) else None else None
/* Succ */ case tsucc(p) =>
var ty_p := has_type(c, p);
if (ty_p.Some?) then
if ty_p.get == TNat then
Some(TNat) else None else None
/*BOOL?
/* Eq */ case teq(n1, n2) =>
var ty_n1 := has_type(c, n1);
var ty_n2 := has_type(c, n2);
if (ty_n1.Some? && ty_n2.Some?) then
if ty_n1.get == TNat && ty_n2.get == TNat then
Some(TBool) else None else None
?BOOL*/
?NAT*/
/*REC?
/* Fold */ case tfold(U, t1) =>
var ty_t1 := if (ty_closed(U)) then has_type(c, t1) else None;
if (ty_t1.Some?) then
if U.TRec? && ty_t1.get==tsubst(U.X, U, U.T) then
Some(U) else None else None
/* Unfold */ case tunfold(t1) =>
var ty_t1 := has_type(c, t1);
if ty_t1.Some? then
var U := ty_t1.get;
if U.TRec? then
Some(tsubst(U.X, U, U.T)) else None else None
?REC*/
}
// Examples
lemma example_typing_1()
ensures has_type(map[], tabs(0, TBase, tvar(0))) == Some(TArrow(TBase, TBase));
{
}
lemma example_typing_2()
ensures has_type(map[], tabs(0, TBase, tabs(1, TArrow(TBase, TBase), tapp(tvar(1), tapp(tvar(1), tvar(0)))))) ==
Some(TArrow(TBase, TArrow(TArrow(TBase, TBase), TBase)));
{
var c := extend(1, TArrow(TBase, TBase), extend(0, TBase, map[]));
assert find(c, 0) == Some(TBase);
assert has_type(c, tvar(0)) == Some(TBase);
assert has_type(c, tvar(1)) == Some(TArrow(TBase, TBase));
assert has_type(c, tapp(tvar(1), tapp(tvar(1), tvar(0)))) == Some(TBase);
}
lemma nonexample_typing_1()
ensures has_type(map[], tabs(0, TBase, tabs(1, TBase, tapp(tvar(0), tvar(1))))) == None;
{
var c := extend(1, TBase, extend(0, TBase, map[]));
assert find(c, 0) == Some(TBase);
assert has_type(c, tapp(tvar(0), tvar(1))) == None;
}
lemma nonexample_typing_3(S: ty, T: ty)
ensures has_type(map[], tabs(0, S, tapp(tvar(0), tvar(0)))) != Some(T);
{
var c := extend(0, S, map[]);
assert has_type(c, tapp(tvar(0), tvar(0))) == None;
}
/*BOOL?
lemma example_typing_bool()
ensures has_type(map[], tabs(0, TBase, tabs(1, TBase, tabs(2, TBool, tif(tvar(2), tvar(0), tvar(1)))))) ==
Some(TArrow(TBase, TArrow(TBase, TArrow(TBool, TBase))));
{
var c0 := extend(0, TBase, map[]);
var c1 := extend(1, TBase, c0);
var c2 := extend(2, TBool, c1);
assert has_type(c2, tvar(2)) == Some(TBool);
assert has_type(c2, tvar(1)) == Some(TBase);
assert has_type(c2, tvar(0)) == Some(TBase);
assert has_type(c2, tif(tvar(2), tvar(0), tvar(1))) == Some(TBase);
assert has_type(c1, tabs(2, TBool, tif(tvar(2), tvar(0), tvar(1)))) == Some(TArrow(TBool, TBase));
assert has_type(c0, tabs(1, TBase, tabs(2, TBool, tif(tvar(2), tvar(0), tvar(1))))) == Some(TArrow(TBase, TArrow(TBool, TBase)));
}
?BOOL*/
/*NAT?
lemma example_typing_nat()
ensures has_type(map[], tabs(0, TNat, tprev(tvar(0)))) == Some(TArrow(TNat, TNat));
{
var c := extend(0, TNat, map[]);
assert has_type(c, tprev(tvar(0)))==Some(TNat);
}
?NAT*/
/*REC?
// TODO
lemma example_typing_rec()
// ∅ |- foldµT. T→α(λx : µT. T → α. (unfold x) x) : µT. T → α
ensures has_type(map[], tfold(TRec(0, TArrow(TVar(0), TBase)), tabs(0, TRec(0, TArrow(TVar(0), TBase)), tapp(tunfold(tvar(0)), tvar(0))))) ==
Some(TRec(0, TArrow(TVar(0), TBase)));
{
var R := TRec(0, TArrow(TVar(0), TBase));
var c := extend(0, R, map[]);
//{x : µT. T → α} x : µT. T → α
assert has_type(c, tvar(0)) == Some(R);
//{x : µT. T → α} (unfold x):(µT. T → α) → α {x : µT. T → α} x : µT. T → α
assert tsubst(R.X, R, R.T) == TArrow(R, TBase);
assert has_type(c, tunfold(tvar(0))) == Some(TArrow(R, TBase));
//{x : µT. T → α} ( (unfold x) x)) : α
assert has_type(c, tapp(tunfold(tvar(0)), tvar(0))) == Some(TBase);
//∅ (λx : µT. T → α. (unfold x) x)) :(µT. T → α) → α
assert has_type(map[], tabs(0, R, tapp(tunfold(tvar(0)), tvar(0)))) == Some(TArrow(R, TBase));
assert ty_fv(R)==ty_fv(TArrow(TVar(0),TBase))-{0}=={};
assert ty_closed(R);
assert has_type(map[], tfold(TRec(0, TArrow(TVar(0), TBase)), tabs(0, TRec(0, TArrow(TVar(0), TBase)), tapp(tunfold(tvar(0)), tvar(0))))).Some?;
}
?REC*/
/// -----------------------
/// Type-Safety Properties
/// -----------------------
// Progress:
// A well-typed term is either a value or it can step.
lemma theorem_progress(t: tm)
requires has_type(map[], t).Some?;
ensures value(t) || step(t).Some?;
{
}
// Towards preservation and the substitution lemma
// If x is free in t and t is well-typed in some context,
// then this context must contain x.
lemma {:induction c, t} lemma_free_in_context(c: map<int,ty>, x: int, t: tm)
requires x in fv(t);
requires has_type(c, t).Some?;
ensures find(c, x).Some?;
decreases t;
{
}
// A closed term does not contain any free variables.
// N.B. We're only interested in proving type soundness of closed terms.
predicate closed(t: tm)
{
forall x :: x !in fv(t)
}
// If a term can be well-typed in an empty context,
// then it is closed.
lemma corollary_typable_empty__closed(t: tm)
requires has_type(map[], t).Some?;
ensures closed(t);
{
forall (x:int) ensures x !in fv(t);
{
if (x in fv(t)) {
lemma_free_in_context(map[], x, t);
assert false;
}
}
}
// If a term t is well-typed in context c,
// and context c' agrees with c on all free variables of t,
// then the term t is well-typed in context c',
// with the same type as in context c.
lemma {:induction t} lemma_context_invariance(c: map<int,ty>, c': map<int,ty>, t: tm)
requires has_type(c, t).Some?;
requires forall x: int :: x in fv(t) ==> find(c, x) == find(c', x);
ensures has_type(c, t) == has_type(c', t);
decreases t;
{
if (t.tabs?) {
assert fv(t.body) == fv(t) || fv(t.body) == fv(t) + {t.x};
lemma_context_invariance(extend(t.x, t.T, c), extend(t.x, t.T, c'), t.body);
}
}
// Substitution preserves typing:
// If s has type S in an empty context,
// and t has type T in a context extended with x having type S,
// then [x -> s]t has type T as well.
lemma lemma_substitution_preserves_typing(c: map<int,ty>, x: int, s: tm, t: tm)
requires has_type(map[], s).Some?;
requires has_type(extend(x, has_type(map[], s).get, c), t).Some?;
ensures has_type(c, subst(x, s, t)) == has_type(extend(x, has_type(map[], s).get, c), t);
decreases t;
{
var S := has_type(map[], s).get;
var cs := extend(x, S, c);
var T := has_type(cs, t).get;
if (t.tvar?) {
if (t.id==x) {
assert T == S;
corollary_typable_empty__closed(s);
lemma_context_invariance(map[], c, s);
}
}
if (t.tabs?) {
if (t.x==x) {
lemma_context_invariance(cs, c, t);
} else {
var cx := extend(t.x, t.T, c);
var csx := extend(x, S, cx);
var cxs := extend(t.x, t.T, cs);
lemma_context_invariance(cxs, csx, t.body);
lemma_substitution_preserves_typing(cx, x, s, t.body);
}
}
}
// Preservation:
// A well-type term which steps preserves its type.
lemma theorem_preservation(t: tm)
requires has_type(map[], t).Some?;
requires step(t).Some?;
ensures has_type(map[], step(t).get) == has_type(map[], t);
{
if (t.tapp? && value(t.f) && value(t.arg)) {
lemma_substitution_preserves_typing(map[], t.f.x, t.arg, t.f.body);
}
}
// A normal form cannot step.
predicate normal_form(t: tm)
{
step(t).None?
}
// A stuck term is a normal form that is not a value.
predicate stuck(t: tm)
{
normal_form(t) && !value(t)
}
// Type soundness:
// A well-typed term cannot be stuck.
lemma corollary_soundness(t: tm, t': tm, T: ty, n: nat)
requires has_type(map[], t) == Some(T);
requires reduces_to(t, t', n);
ensures !stuck(t');
decreases n;
{
theorem_progress(t);
if (t != t') {
theorem_preservation(t);
corollary_soundness(step(t).get, t', T, n-1);
}
}
/// QED
|
dafny-sandbox_tmp_tmp3tu2bu8a_Stlc.dfy
|
494
|
494
|
Dafny program: 494
|
function countTo( a:array<bool>, n:int ) : int
requires a != null;
requires 0 <= n && n <= a.Length;
reads a;
{
if (n == 0) then 0 else countTo(a, n-1) + (if a[n-1] then 1 else 0)
}
method CountTrue(a: array<bool>) returns (result: int)
requires a != null
ensures result == countTo(a, a.Length)
{
result := 0;
for i := 0 to a.Length
{
if a[i] {
result := result + 1;
}
}
}
|
function countTo( a:array<bool>, n:int ) : int
requires a != null;
requires 0 <= n && n <= a.Length;
decreases n;
reads a;
{
if (n == 0) then 0 else countTo(a, n-1) + (if a[n-1] then 1 else 0)
}
method CountTrue(a: array<bool>) returns (result: int)
requires a != null
ensures result == countTo(a, a.Length)
{
result := 0;
for i := 0 to a.Length
invariant 0 <= i <= a.Length
invariant result == countTo(a, i)
{
if a[i] {
result := result + 1;
}
}
}
|
dafny-synthesis_task_id_105.dfy
|
495
|
495
|
Dafny program: 495
|
method AppendArrayToSeq(s: seq<int>, a: array<int>) returns (r: seq<int>)
requires a != null
ensures |r| == |s| + a.Length
ensures forall i :: 0 <= i < |s| ==> r[i] == s[i]
ensures forall i :: 0 <= i < a.Length ==> r[|s| + i] == a[i]
{
r := s;
for i := 0 to a.Length
{
r := r + [a[i]];
}
}
|
method AppendArrayToSeq(s: seq<int>, a: array<int>) returns (r: seq<int>)
requires a != null
ensures |r| == |s| + a.Length
ensures forall i :: 0 <= i < |s| ==> r[i] == s[i]
ensures forall i :: 0 <= i < a.Length ==> r[|s| + i] == a[i]
{
r := s;
for i := 0 to a.Length
invariant 0 <= i <= a.Length
invariant |r| == |s| + i
invariant forall j :: 0 <= j < |s| ==> r[j] == s[j]
invariant forall j :: 0 <= j < i ==> r[|s| + j] == a[j]
{
r := r + [a[i]];
}
}
|
dafny-synthesis_task_id_106.dfy
|
496
|
496
|
Dafny program: 496
|
predicate IsDigit(c: char)
{
48 <= c as int <= 57
}
method IsInteger(s: string) returns (result: bool)
ensures result <==> (|s| > 0) && (forall i :: 0 <= i < |s| ==> IsDigit(s[i]))
{
result := true;
if |s| == 0 {
result := false;
} else {
for i := 0 to |s|
{
if !IsDigit(s[i]) {
result := false;
break;
}
}
}
}
|
predicate IsDigit(c: char)
{
48 <= c as int <= 57
}
method IsInteger(s: string) returns (result: bool)
ensures result <==> (|s| > 0) && (forall i :: 0 <= i < |s| ==> IsDigit(s[i]))
{
result := true;
if |s| == 0 {
result := false;
} else {
for i := 0 to |s|
invariant 0 <= i <= |s|
invariant result <==> (forall k :: 0 <= k < i ==> IsDigit(s[k]))
{
if !IsDigit(s[i]) {
result := false;
break;
}
}
}
}
|
dafny-synthesis_task_id_113.dfy
|
497
|
497
|
Dafny program: 497
|
method SumOfCommonDivisors(a: int, b: int) returns (sum: int)
requires a > 0 && b > 0
ensures sum >= 0
ensures forall d :: 1 <= d <= a && 1 <= d <= b && a % d == 0 && b % d == 0 ==> sum >= d
{
sum := 0;
var i := 1;
while i <= a && i <= b
{
if a % i == 0 && b % i == 0 {
sum := sum + i;
}
i := i + 1;
}
}
|
method SumOfCommonDivisors(a: int, b: int) returns (sum: int)
requires a > 0 && b > 0
ensures sum >= 0
ensures forall d :: 1 <= d <= a && 1 <= d <= b && a % d == 0 && b % d == 0 ==> sum >= d
{
sum := 0;
var i := 1;
while i <= a && i <= b
invariant 1 <= i <= a + 1 && 1 <= i <= b + 1
invariant sum >= 0
invariant forall d :: 1 <= d < i && a % d == 0 && b % d == 0 ==> sum >= d
{
if a % i == 0 && b % i == 0 {
sum := sum + i;
}
i := i + 1;
}
}
|
dafny-synthesis_task_id_126.dfy
|
499
|
499
|
Dafny program: 499
|
function sumNegativesTo( a:array<int>, n:int ) : int
requires a != null;
requires 0 <= n && n <= a.Length;
reads a;
{
if (n == 0) then 0 else if a[n-1] < 0 then sumNegativesTo(a, n-1) + a[n-1] else sumNegativesTo(a, n-1)
}
method SumOfNegatives(a: array<int>) returns (result: int)
ensures result == sumNegativesTo(a, a.Length)
{
result := 0;
for i := 0 to a.Length
{
if a[i] < 0 {
result := result + a[i];
}
}
}
|
function sumNegativesTo( a:array<int>, n:int ) : int
requires a != null;
requires 0 <= n && n <= a.Length;
decreases n;
reads a;
{
if (n == 0) then 0 else if a[n-1] < 0 then sumNegativesTo(a, n-1) + a[n-1] else sumNegativesTo(a, n-1)
}
method SumOfNegatives(a: array<int>) returns (result: int)
ensures result == sumNegativesTo(a, a.Length)
{
result := 0;
for i := 0 to a.Length
invariant 0 <= i <= a.Length
invariant result == sumNegativesTo(a, i)
{
if a[i] < 0 {
result := result + a[i];
}
}
}
|
dafny-synthesis_task_id_133.dfy
|
505
|
505
|
Dafny program: 505
|
method MaxDifference(a: array<int>) returns (diff: int)
requires a.Length > 1
ensures forall i, j :: 0 <= i < a.Length && 0 <= j < a.Length ==> a[i] - a[j] <= diff
{
var minVal := a[0];
var maxVal := a[0];
for i := 1 to a.Length
{
if a[i] < minVal {
minVal := a[i];
} else if a[i] > maxVal {
maxVal := a[i];
}
}
diff := maxVal - minVal;
}
|
method MaxDifference(a: array<int>) returns (diff: int)
requires a.Length > 1
ensures forall i, j :: 0 <= i < a.Length && 0 <= j < a.Length ==> a[i] - a[j] <= diff
{
var minVal := a[0];
var maxVal := a[0];
for i := 1 to a.Length
invariant 1 <= i <= a.Length
invariant minVal <= maxVal
invariant forall k :: 0 <= k < i ==> minVal <= a[k] && a[k] <= maxVal
{
if a[i] < minVal {
minVal := a[i];
} else if a[i] > maxVal {
maxVal := a[i];
}
}
diff := maxVal - minVal;
}
|
dafny-synthesis_task_id_145.dfy
|
506
|
506
|
Dafny program: 506
|
predicate InArray(a: array<int>, x: int)
reads a
{
exists i :: 0 <= i < a.Length && a[i] == x
}
method RemoveElements(a: array<int>, b: array<int>) returns (result: seq<int>)
// All elements in the output are in a and not in b
ensures forall x :: x in result ==> InArray(a, x) && !InArray(b, x)
// The elements in the output are all different
ensures forall i, j :: 0 <= i < j < |result| ==> result[i] != result[j]
{
var res: seq<int> := [];
for i := 0 to a.Length
{
if !InArray(b, a[i]) && a[i] !in res
{
res := res + [a[i]];
}
}
result := res;
}
|
predicate InArray(a: array<int>, x: int)
reads a
{
exists i :: 0 <= i < a.Length && a[i] == x
}
method RemoveElements(a: array<int>, b: array<int>) returns (result: seq<int>)
// All elements in the output are in a and not in b
ensures forall x :: x in result ==> InArray(a, x) && !InArray(b, x)
// The elements in the output are all different
ensures forall i, j :: 0 <= i < j < |result| ==> result[i] != result[j]
{
var res: seq<int> := [];
for i := 0 to a.Length
invariant 0 <= i <= a.Length
invariant forall x :: x in res ==> InArray(a, x) && !InArray(b, x)
invariant forall i, j :: 0 <= i < j < |res| ==> res[i] != res[j]
{
if !InArray(b, a[i]) && a[i] !in res
{
res := res + [a[i]];
}
}
result := res;
}
|
dafny-synthesis_task_id_161.dfy
|
508
|
508
|
Dafny program: 508
|
function sumTo( a:array<int>, start:int, end:int ) : int
requires a != null;
requires 0 <= start && start <= end && end <= a.Length;
reads a;
{
if (start == end) then 0 else sumTo(a, start, end-1) + a[end-1]
}
method SumInRange(a: array<int>, start: int, end: int) returns (sum: int)
requires a != null
requires 0 <= start && start <= end && end <= a.Length
ensures sum == sumTo(a, start, end)
{
sum := 0;
for i := start to end
{
sum := sum + a[i];
}
}
|
function sumTo( a:array<int>, start:int, end:int ) : int
requires a != null;
requires 0 <= start && start <= end && end <= a.Length;
decreases end;
reads a;
{
if (start == end) then 0 else sumTo(a, start, end-1) + a[end-1]
}
method SumInRange(a: array<int>, start: int, end: int) returns (sum: int)
requires a != null
requires 0 <= start && start <= end && end <= a.Length
ensures sum == sumTo(a, start, end)
{
sum := 0;
for i := start to end
invariant start <= i <= end
invariant sum == sumTo(a, start, i)
{
sum := sum + a[i];
}
}
|
dafny-synthesis_task_id_170.dfy
|
510
|
510
|
Dafny program: 510
|
method RemoveChars(s1: string, s2: string) returns (v: string)
ensures |v| <= |s1|
ensures forall i :: 0 <= i < |v| ==> (v[i] in s1) && !(v[i] in s2)
ensures forall i :: 0 <= i < |s1| ==> (s1[i] in s2) || (s1[i] in v)
{
var v' : string := [];
for i := 0 to |s1|
{
if !(s1[i] in s2)
{
v' := v' + [s1[i]];
}
}
return v';
}
|
method RemoveChars(s1: string, s2: string) returns (v: string)
ensures |v| <= |s1|
ensures forall i :: 0 <= i < |v| ==> (v[i] in s1) && !(v[i] in s2)
ensures forall i :: 0 <= i < |s1| ==> (s1[i] in s2) || (s1[i] in v)
{
var v' : string := [];
for i := 0 to |s1|
invariant 0 <= i <= |s1|
invariant |v'| <= i
invariant forall k :: 0 <= k < |v'| ==> (v'[k] in s1) && !(v'[k] in s2)
invariant forall k :: 0 <= k < i ==> (s1[k] in s2) || (s1[k] in v')
{
if !(s1[i] in s2)
{
v' := v' + [s1[i]];
}
}
return v';
}
|
dafny-synthesis_task_id_18.dfy
|
511
|
511
|
Dafny program: 511
|
predicate InArray(a: array<int>, x: int)
reads a
{
exists i :: 0 <= i < a.Length && a[i] == x
}
method SharedElements(a: array<int>, b: array<int>) returns (result: seq<int>)
// All elements in the output are in both a and b
ensures forall x :: x in result ==> (InArray(a, x) && InArray(b, x))
// The elements in the output are all different
ensures forall i, j :: 0 <= i < j < |result| ==> result[i] != result[j]
{
var res: seq<int> := [];
for i := 0 to a.Length
{
if InArray(b, a[i]) && a[i] !in res
{
res := res + [a[i]];
}
}
result := res;
}
|
predicate InArray(a: array<int>, x: int)
reads a
{
exists i :: 0 <= i < a.Length && a[i] == x
}
method SharedElements(a: array<int>, b: array<int>) returns (result: seq<int>)
// All elements in the output are in both a and b
ensures forall x :: x in result ==> (InArray(a, x) && InArray(b, x))
// The elements in the output are all different
ensures forall i, j :: 0 <= i < j < |result| ==> result[i] != result[j]
{
var res: seq<int> := [];
for i := 0 to a.Length
invariant 0 <= i <= a.Length
invariant forall x :: x in res ==> InArray(a, x) && InArray(b, x)
invariant forall i, j :: 0 <= i < j < |res| ==> res[i] != res[j]
{
if InArray(b, a[i]) && a[i] !in res
{
res := res + [a[i]];
}
}
result := res;
}
|
dafny-synthesis_task_id_2.dfy
|
513
|
513
|
Dafny program: 513
|
method ReplaceBlanksWithChar(s: string, ch: char) returns (v: string)
ensures |v| == |s|
ensures forall i :: 0 <= i < |s| ==> (s[i] == ' ' ==> v[i] == ch) && (s[i] != ' ' ==> v[i] == s[i])
{
var s' : string := [];
for i := 0 to |s|
{
if s[i] == ' '
{
s' := s' + [ch];
}
else
{
s' := s' + [s[i]];
}
}
return s';
}
|
method ReplaceBlanksWithChar(s: string, ch: char) returns (v: string)
ensures |v| == |s|
ensures forall i :: 0 <= i < |s| ==> (s[i] == ' ' ==> v[i] == ch) && (s[i] != ' ' ==> v[i] == s[i])
{
var s' : string := [];
for i := 0 to |s|
invariant 0 <= i <= |s|
invariant |s'| == i
invariant forall k :: 0 <= k < i ==> (s[k] == ' ' ==> s'[k] == ch) && (s[k] != ' ' ==> s'[k] == s[k])
{
if s[i] == ' '
{
s' := s' + [ch];
}
else
{
s' := s' + [s[i]];
}
}
return s';
}
|
dafny-synthesis_task_id_230.dfy
|
519
|
519
|
Dafny program: 519
|
predicate InArray(a: array<int>, x: int)
reads a
{
exists i :: 0 <= i < a.Length && a[i] == x
}
method Intersection(a: array<int>, b: array<int>) returns (result: seq<int>)
// All elements in the output are in both a and b
ensures forall x :: x in result ==> (InArray(a, x) && InArray(b, x))
// The elements in the output are all different
ensures forall i, j :: 0 <= i < j < |result| ==> result[i] != result[j]
{
var res: seq<int> := [];
for i := 0 to a.Length
{
if InArray(b, a[i]) && a[i] !in res
{
res := res + [a[i]];
}
}
result := res;
}
|
predicate InArray(a: array<int>, x: int)
reads a
{
exists i :: 0 <= i < a.Length && a[i] == x
}
method Intersection(a: array<int>, b: array<int>) returns (result: seq<int>)
// All elements in the output are in both a and b
ensures forall x :: x in result ==> (InArray(a, x) && InArray(b, x))
// The elements in the output are all different
ensures forall i, j :: 0 <= i < j < |result| ==> result[i] != result[j]
{
var res: seq<int> := [];
for i := 0 to a.Length
invariant 0 <= i <= a.Length
invariant forall x :: x in res ==> (InArray(a, x) && InArray(b, x))
invariant forall i, j :: 0 <= i < j < |res| ==> res[i] != res[j]
{
if InArray(b, a[i]) && a[i] !in res
{
res := res + [a[i]];
}
}
result := res;
}
|
dafny-synthesis_task_id_249.dfy
|
520
|
520
|
Dafny program: 520
|
method InsertBeforeEach(s: seq<string>, x: string) returns (v: seq<string>)
ensures |v| == 2 * |s|
ensures forall i :: 0 <= i < |s| ==> v[2*i] == x && v[2*i + 1] == s[i]
{
v := [];
for i := 0 to |s|
{
v := v + [x, s[i]];
}
}
|
method InsertBeforeEach(s: seq<string>, x: string) returns (v: seq<string>)
ensures |v| == 2 * |s|
ensures forall i :: 0 <= i < |s| ==> v[2*i] == x && v[2*i + 1] == s[i]
{
v := [];
for i := 0 to |s|
invariant 0 <= i <= |s|
invariant |v| == 2 * i
invariant forall j :: 0 <= j < i ==> v[2*j] == x && v[2*j + 1] == s[j]
{
v := v + [x, s[i]];
}
}
|
dafny-synthesis_task_id_251.dfy
|
522
|
522
|
Dafny program: 522
|
method ElementWiseDivision(a: seq<int>, b: seq<int>) returns (result: seq<int>)
requires |a| == |b|
requires forall i :: 0 <= i < |b| ==> b[i] != 0
ensures |result| == |a|
ensures forall i :: 0 <= i < |result| ==> result[i] == a[i] / b[i]
{
result := [];
var i := 0;
while i < |a|
{
result := result + [a[i] / b[i]];
i := i + 1;
}
}
|
method ElementWiseDivision(a: seq<int>, b: seq<int>) returns (result: seq<int>)
requires |a| == |b|
requires forall i :: 0 <= i < |b| ==> b[i] != 0
ensures |result| == |a|
ensures forall i :: 0 <= i < |result| ==> result[i] == a[i] / b[i]
{
result := [];
var i := 0;
while i < |a|
invariant 0 <= i <= |a|
invariant |result| == i
invariant forall k :: 0 <= k < i ==> result[k] == a[k] / b[k]
{
result := result + [a[i] / b[i]];
i := i + 1;
}
}
|
dafny-synthesis_task_id_261.dfy
|
526
|
526
|
Dafny program: 526
|
method SumOfSquaresOfFirstNOddNumbers(n: int) returns (sum: int)
requires n >= 0
ensures sum == (n * (2 * n - 1) * (2 * n + 1)) / 3
{
sum := 0;
var i := 1;
for k:=0 to n
{
sum := sum + i * i;
i := i + 2;
}
}
|
method SumOfSquaresOfFirstNOddNumbers(n: int) returns (sum: int)
requires n >= 0
ensures sum == (n * (2 * n - 1) * (2 * n + 1)) / 3
{
sum := 0;
var i := 1;
for k:=0 to n
invariant 0 <= k <= n
invariant sum == k * (2 * k - 1) * (2 * k + 1) / 3
invariant i == 2 * k + 1
{
sum := sum + i * i;
i := i + 2;
}
}
|
dafny-synthesis_task_id_267.dfy
|
529
|
529
|
Dafny program: 529
|
method SubtractSequences(a: seq<int>, b: seq<int>) returns (result: seq<int>)
requires |a| == |b|
ensures |result| == |a|
ensures forall i :: 0 <= i < |result| ==> result[i] == a[i] - b[i]
{
result := [];
var i := 0;
while i < |a|
{
result := result + [a[i] - b[i]];
i := i + 1;
}
}
|
method SubtractSequences(a: seq<int>, b: seq<int>) returns (result: seq<int>)
requires |a| == |b|
ensures |result| == |a|
ensures forall i :: 0 <= i < |result| ==> result[i] == a[i] - b[i]
{
result := [];
var i := 0;
while i < |a|
invariant 0 <= i <= |a|
invariant |result| == i
invariant forall k :: 0 <= k < i ==> result[k] == a[k] - b[k]
{
result := result + [a[i] - b[i]];
i := i + 1;
}
}
|
dafny-synthesis_task_id_273.dfy
|
532
|
532
|
Dafny program: 532
|
method ElementWiseSubtraction(a: array<int>, b: array<int>) returns (result: array<int>)
requires a != null && b != null
requires a.Length == b.Length
ensures result != null
ensures result.Length == a.Length
ensures forall i :: 0 <= i < result.Length ==> result[i] == a[i] - b[i]
{
result := new int[a.Length];
var i := 0;
while i < a.Length
{
result[i] := a[i] - b[i];
i := i + 1;
}
}
|
method ElementWiseSubtraction(a: array<int>, b: array<int>) returns (result: array<int>)
requires a != null && b != null
requires a.Length == b.Length
ensures result != null
ensures result.Length == a.Length
ensures forall i :: 0 <= i < result.Length ==> result[i] == a[i] - b[i]
{
result := new int[a.Length];
var i := 0;
while i < a.Length
invariant 0 <= i <= a.Length
invariant result.Length == a.Length
invariant forall k :: 0 <= k < i ==> result[k] == a[k] - b[k]
{
result[i] := a[i] - b[i];
i := i + 1;
}
}
|
dafny-synthesis_task_id_282.dfy
|
533
|
533
|
Dafny program: 533
|
method AllElementsEqual(a: array<int>, n: int) returns (result: bool)
requires a != null
ensures result ==> forall i :: 0 <= i < a.Length ==> a[i] == n
ensures !result ==> exists i :: 0 <= i < a.Length && a[i] != n
{
result := true;
for i := 0 to a.Length
{
if a[i] != n {
result := false;
break;
}
}
}
|
method AllElementsEqual(a: array<int>, n: int) returns (result: bool)
requires a != null
ensures result ==> forall i :: 0 <= i < a.Length ==> a[i] == n
ensures !result ==> exists i :: 0 <= i < a.Length && a[i] != n
{
result := true;
for i := 0 to a.Length
invariant 0 <= i <= a.Length
invariant result ==> forall k :: 0 <= k < i ==> a[k] == n
{
if a[i] != n {
result := false;
break;
}
}
}
|
dafny-synthesis_task_id_284.dfy
|
534
|
534
|
Dafny program: 534
|
method MaxLengthList(lists: seq<seq<int>>) returns (maxList: seq<int>)
requires |lists| > 0
ensures forall l :: l in lists ==> |l| <= |maxList|
ensures maxList in lists
{
maxList := lists[0];
for i := 1 to |lists|
{
if |lists[i]| > |maxList| {
maxList := lists[i];
}
}
}
|
method MaxLengthList(lists: seq<seq<int>>) returns (maxList: seq<int>)
requires |lists| > 0
ensures forall l :: l in lists ==> |l| <= |maxList|
ensures maxList in lists
{
maxList := lists[0];
for i := 1 to |lists|
invariant 1 <= i <= |lists|
invariant forall l :: l in lists[..i] ==> |l| <= |maxList|
invariant maxList in lists[..i]
{
if |lists[i]| > |maxList| {
maxList := lists[i];
}
}
}
|
dafny-synthesis_task_id_290.dfy
|
536
|
536
|
Dafny program: 536
|
method IsNonPrime(n: int) returns (result: bool)
requires n >= 2
ensures result <==> (exists k :: 2 <= k < n && n % k == 0)
{
result := false;
var i := 2;
while i <= n/2
{
if n % i == 0
{
result := true;
break;
}
i := i + 1;
}
}
|
method IsNonPrime(n: int) returns (result: bool)
requires n >= 2
ensures result <==> (exists k :: 2 <= k < n && n % k == 0)
{
result := false;
var i := 2;
while i <= n/2
invariant 2 <= i
invariant result <==> (exists k :: 2 <= k < i && n % k == 0)
{
if n % i == 0
{
result := true;
break;
}
i := i + 1;
}
}
|
dafny-synthesis_task_id_3.dfy
|
538
|
538
|
Dafny program: 538
|
method DeepCopySeq(s: seq<int>) returns (copy: seq<int>)
ensures |copy| == |s|
ensures forall i :: 0 <= i < |s| ==> copy[i] == s[i]
{
var newSeq: seq<int> := [];
for i := 0 to |s|
{
newSeq := newSeq + [s[i]];
}
return newSeq;
}
|
method DeepCopySeq(s: seq<int>) returns (copy: seq<int>)
ensures |copy| == |s|
ensures forall i :: 0 <= i < |s| ==> copy[i] == s[i]
{
var newSeq: seq<int> := [];
for i := 0 to |s|
invariant 0 <= i <= |s|
invariant |newSeq| == i
invariant forall k :: 0 <= k < i ==> newSeq[k] == s[k]
{
newSeq := newSeq + [s[i]];
}
return newSeq;
}
|
dafny-synthesis_task_id_307.dfy
|
540
|
540
|
Dafny program: 540
|
method ToCharArray(s: string) returns (a: array<char>)
ensures a.Length == |s|
ensures forall i :: 0 <= i < |s| ==> a[i] == s[i]
{
a := new char[|s|];
for i := 0 to |s|
{
a[i] := s[i];
}
}
|
method ToCharArray(s: string) returns (a: array<char>)
ensures a.Length == |s|
ensures forall i :: 0 <= i < |s| ==> a[i] == s[i]
{
a := new char[|s|];
for i := 0 to |s|
invariant 0 <= i <= |s|
invariant a.Length == |s|
invariant forall k :: 0 <= k < i ==> a[k] == s[k]
{
a[i] := s[i];
}
}
|
dafny-synthesis_task_id_310.dfy
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.