test_ID
stringlengths 3
3
| test_file
stringlengths 14
119
| ground_truth
stringlengths 70
28.7k
| hints_removed
stringlengths 58
28.7k
|
---|---|---|---|
400 | cs245-verification_tmp_tmp0h_nxhqp_power.dfy | //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.
*/
| //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.
*/
|
401 | cs245-verification_tmp_tmp0h_nxhqp_quicksort-partition.dfy | // 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. */
| // 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. */
|
402 | cs357_tmp_tmpn4fsvwzs_lab7_question2.dfy | method Two(x: int) returns (y: int)
ensures y == x + 1
{
assert true;
var a:= x+1;
assert (a - 1 == 0 ==> x == 0) && (x - 1!= 0 ==> a == x +1);
if(a - 1 == 0){
y:= 1;
} else {
y:= a;
}
}
| method Two(x: int) returns (y: int)
ensures y == x + 1
{
var a:= x+1;
if(a - 1 == 0){
y:= 1;
} else {
y:= a;
}
}
|
403 | cs357_tmp_tmpn4fsvwzs_lab7_question5.dfy | 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;
}
}
}
| 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;
}
}
}
|
404 | cs686_tmp_tmpdhuh5dza_classNotes_notes-9-8-21.dfy | // Forall
method Q1(){
var a := new int[6];
a[0], a[1], a[2], a[3], a[4], a[5] := 1,0,0,0,1,1;
var b := new int[3];
b[0], b[1], b[2] := 1, 0, 1;
var j,k := 1,3;
var p,r := 4,5;
// a) All elements in the range a[j..k] == 0
assert(forall i : int :: j<= i <= k ==> a[i] == 0);
assert(forall i : int :: if j <= i <= k then a[i] == 0 else true);
// b) All zeros in a occur in the interval a[j..k]
assert(forall i : int :: (0 <= i < a.Length && a[i] == 0) ==> j <= i <= k);
// c) It is *not* the case that all ones of a occur in the interval in a[p..r]
assert(a[0] == 1); // helps the next assertion verify
assert(!(forall i : int :: (0 <= i < a.Length && a[i] == 1) ==> p <= i <= r));
// d) a[0..n-1] contains at least two zeros
assert(a[1] == 0 && a[2] == 0);
assert(exists i, j : int :: 0 <= i < j < a.Length && a[i] == 0 && a[j] == 0);
// e) b[0..n-1] contains at the most two zeros (Note: *not* true for array a)
assert(!(exists i, j, k : int :: 0 <= i < j< k < b.Length && b[i] == 0 && b[j] == 0 && b[k] == k));
}
// Quantifiers
class Secret{
var secret : int;
var known : bool;
var count : int;
method Init(x : int)
modifies `secret, `known, `count
requires 1 <= x <= 10
ensures secret == x
ensures known == false
ensures count == 0
{
known := false;
count := 0;
secret := x;
}
method Guess(g : int) returns (result : bool, guesses : int)
modifies `known, `count
requires known == false
ensures if g == secret then
result == true && known == true
else
result == false && known == false
ensures count == old(count) + 1 && guesses == count
{
if (g == secret)
{
known := true;
result := true;
}
else
{
result := false;
}
count := count + 1;
guesses := count;
}
method Main()
{
var testObject : Secret := new Secret.Init(5);
assert(1 <= testObject.secret <= 10);
assert(testObject.secret == 5);
var x, y := testObject.Guess(0);
assert(x == false && y == 1);
x,y := testObject.Guess(5);
assert(x == true && y == 2);
//x,y := testObject.Guess(5);
}
}
| // Forall
method Q1(){
var a := new int[6];
a[0], a[1], a[2], a[3], a[4], a[5] := 1,0,0,0,1,1;
var b := new int[3];
b[0], b[1], b[2] := 1, 0, 1;
var j,k := 1,3;
var p,r := 4,5;
// a) All elements in the range a[j..k] == 0
// b) All zeros in a occur in the interval a[j..k]
// c) It is *not* the case that all ones of a occur in the interval in a[p..r]
// d) a[0..n-1] contains at least two zeros
// e) b[0..n-1] contains at the most two zeros (Note: *not* true for array a)
}
// Quantifiers
class Secret{
var secret : int;
var known : bool;
var count : int;
method Init(x : int)
modifies `secret, `known, `count
requires 1 <= x <= 10
ensures secret == x
ensures known == false
ensures count == 0
{
known := false;
count := 0;
secret := x;
}
method Guess(g : int) returns (result : bool, guesses : int)
modifies `known, `count
requires known == false
ensures if g == secret then
result == true && known == true
else
result == false && known == false
ensures count == old(count) + 1 && guesses == count
{
if (g == secret)
{
known := true;
result := true;
}
else
{
result := false;
}
count := count + 1;
guesses := count;
}
method Main()
{
var testObject : Secret := new Secret.Init(5);
var x, y := testObject.Guess(0);
x,y := testObject.Guess(5);
//x,y := testObject.Guess(5);
}
}
|
405 | dafl_tmp_tmp_r3_8w3y_dafny_examples_dafny0_ContainerRanks.dfy | // 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})
{
}
| // 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})
{
}
|
406 | dafl_tmp_tmp_r3_8w3y_dafny_examples_dafny0_DividedConstructors.dfy | // RUN: %dafny /compile:3 /env:0 /dprint:- "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
method Main() {
var m := new M0.MyClass.Init(20);
print m.a, ", ", m.b, ", ", m.c, "\n";
var r0 := new Regression.A.Make0();
var r1 := new Regression.A.Make1();
assert r0.b != r1.b;
print r0.b, ", ", r1.b, "\n";
}
module M0 {
class MyClass {
var a: nat
const b := 17
var c: real
constructor Init(x: nat)
{
this.a := x;
c := 3.14;
new;
a := a + b;
assert c == 3.14;
assert this.a == 17 + x;
}
constructor (z: real)
ensures c <= 2.0 * z
{
a, c := 50, 2.0 * z;
new;
}
constructor Make()
ensures 10 <= a
{
new;
a := a + b;
}
constructor Create()
ensures 30 <= a
{
new;
a := a + 2*b;
}
}
}
module M1 refines M0 {
class MyClass ... {
const d := 'D';
var e: char;
constructor Init...
{
e := 'e';
new;
e := 'x';
...;
assert e == 'x';
}
constructor ...
{
e := 'y';
new;
}
constructor Make...
{
new;
e := 'z';
}
constructor Create...
{
e := 'w';
}
}
}
module TypeOfThis {
class LinkedList<T(0)> {
ghost var Repr: set<LinkedList<T>>
ghost var Rapr: set<LinkedList?<T>>
ghost var S: set<object>
ghost var T: set<object?>
constructor Init()
{
Repr := {this}; // regression test: this should pass, but once upon a time didn't
}
constructor Init'()
{
Rapr := {this};
}
constructor Create()
{
S := {this}; // regression test: this should pass, but once upon a time didn't
}
constructor Create'()
{
T := {this};
}
constructor Two()
{
new;
var ll: LinkedList? := this;
var o: object? := this;
if
case true => T := {o};
case true => S := {o};
case true => Repr := {ll};
case true => Rapr := {ll};
case true => S := {ll};
case true => T := {ll};
}
method Mutate()
modifies this
{
Repr := {this};
Rapr := {this};
S := {this};
T := {this};
}
}
}
module Regression {
class A {
var b: bool
var y: int
constructor Make0()
ensures b == false // regression test: this didn't used to be provable :O
{
b := false;
}
constructor Make1()
ensures b == true
{
b := true;
}
constructor Make2()
{
b := false;
new; // this sets "alloc" to "true", and the verifier previously was not
// able to distinguish the internal field "alloc" from other boolean
// fields
assert !b; // regression test: this didn't used to be provable :O
}
constructor Make3()
ensures b == false && y == 65
{
b := false;
y := 65;
new;
assert !b; // regression test: this didn't used to be provable :O
assert y == 65;
}
constructor Make4(bb: bool, yy: int)
ensures b == bb && y == yy
{
b, y := bb, yy;
}
}
}
| // RUN: %dafny /compile:3 /env:0 /dprint:- "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
method Main() {
var m := new M0.MyClass.Init(20);
print m.a, ", ", m.b, ", ", m.c, "\n";
var r0 := new Regression.A.Make0();
var r1 := new Regression.A.Make1();
print r0.b, ", ", r1.b, "\n";
}
module M0 {
class MyClass {
var a: nat
const b := 17
var c: real
constructor Init(x: nat)
{
this.a := x;
c := 3.14;
new;
a := a + b;
}
constructor (z: real)
ensures c <= 2.0 * z
{
a, c := 50, 2.0 * z;
new;
}
constructor Make()
ensures 10 <= a
{
new;
a := a + b;
}
constructor Create()
ensures 30 <= a
{
new;
a := a + 2*b;
}
}
}
module M1 refines M0 {
class MyClass ... {
const d := 'D';
var e: char;
constructor Init...
{
e := 'e';
new;
e := 'x';
...;
}
constructor ...
{
e := 'y';
new;
}
constructor Make...
{
new;
e := 'z';
}
constructor Create...
{
e := 'w';
}
}
}
module TypeOfThis {
class LinkedList<T(0)> {
ghost var Repr: set<LinkedList<T>>
ghost var Rapr: set<LinkedList?<T>>
ghost var S: set<object>
ghost var T: set<object?>
constructor Init()
{
Repr := {this}; // regression test: this should pass, but once upon a time didn't
}
constructor Init'()
{
Rapr := {this};
}
constructor Create()
{
S := {this}; // regression test: this should pass, but once upon a time didn't
}
constructor Create'()
{
T := {this};
}
constructor Two()
{
new;
var ll: LinkedList? := this;
var o: object? := this;
if
case true => T := {o};
case true => S := {o};
case true => Repr := {ll};
case true => Rapr := {ll};
case true => S := {ll};
case true => T := {ll};
}
method Mutate()
modifies this
{
Repr := {this};
Rapr := {this};
S := {this};
T := {this};
}
}
}
module Regression {
class A {
var b: bool
var y: int
constructor Make0()
ensures b == false // regression test: this didn't used to be provable :O
{
b := false;
}
constructor Make1()
ensures b == true
{
b := true;
}
constructor Make2()
{
b := false;
new; // this sets "alloc" to "true", and the verifier previously was not
// able to distinguish the internal field "alloc" from other boolean
// fields
}
constructor Make3()
ensures b == false && y == 65
{
b := false;
y := 65;
new;
}
constructor Make4(bb: bool, yy: int)
ensures b == bb && y == yy
{
b, y := bb, yy;
}
}
}
|
407 | dafl_tmp_tmp_r3_8w3y_dafny_examples_dafny0_ForallCompilationNewSyntax.dfy | // RUN: %baredafny run %args --relax-definite-assignment --quantifier-syntax:4 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
method Main() {
var c := new MyClass;
c.arr := new int[10,20];
c.K0(3, 12);
c.K1(3, 12);
c.K2(3, 12);
c.K3(3, 12);
c.K4(12);
c.M();
c.N();
c.P();
c.Q();
}
class MyClass
{
var arr: array2<int>
method K0(i: int, j: int)
requires 0 <= i < arr.Length0 && 0 <= j < arr.Length1
modifies arr
{
forall k <- {-3, 4} {
arr[i,j] := 50;
}
}
method K1(i: int, j: int)
requires 0 <= i < arr.Length0 && 0 <= j < arr.Length1
// note the absence of a modifies clause
{
forall k <- {} {
arr[i,j] := k; // fine, since control will never reach here
}
}
method K2(i: int, j: int)
requires 0 <= i < arr.Length0 && 0 <= j < arr.Length1
modifies arr
{
forall k <- {-3, 4} {
// The following would have been an error (since this test file tests
// compilation, we don't include the test here):
// arr[i,j] := k; // error: k can take on more than one value
}
}
method K3(i: int, j: int)
requires 0 <= i < arr.Length0 && 0 <= j < arr.Length1
modifies arr
{
forall k: nat <- {-3, 4} | k <= i {
arr[k,j] := 50; // fine, since k:nat is at least 0
}
}
method K4(j: int)
requires 0 <= j < arr.Length1
modifies arr
{
forall i | 0 <= i < arr.Length0, k: nat <- {-3, 4} {
arr[i,j] := k; // fine, since k can only take on one value
}
}
method M()
{
var ar := new int [3,3];
var S: set<int> := {2,0};
forall k | k in S {
ar[k,1]:= 0;
}
forall k <- S, j <- S {
ar[k,j]:= 0;
}
}
method N() {
var ar := new int[3, 3];
ar[2,2] := 0;
}
method P() {
var ar := new int[3];
var prev := ar[..];
var S: set<int> := {};
forall k <- S {
ar[k] := 0;
}
assert ar[..] == prev;
}
method Q() {
var ar := new int[3,3];
var S: set<int> := {1,2};
forall k <- S {
ar[0,0] := 0;
}
assert ar[0,0] == 0;
}
}
| // RUN: %baredafny run %args --relax-definite-assignment --quantifier-syntax:4 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
method Main() {
var c := new MyClass;
c.arr := new int[10,20];
c.K0(3, 12);
c.K1(3, 12);
c.K2(3, 12);
c.K3(3, 12);
c.K4(12);
c.M();
c.N();
c.P();
c.Q();
}
class MyClass
{
var arr: array2<int>
method K0(i: int, j: int)
requires 0 <= i < arr.Length0 && 0 <= j < arr.Length1
modifies arr
{
forall k <- {-3, 4} {
arr[i,j] := 50;
}
}
method K1(i: int, j: int)
requires 0 <= i < arr.Length0 && 0 <= j < arr.Length1
// note the absence of a modifies clause
{
forall k <- {} {
arr[i,j] := k; // fine, since control will never reach here
}
}
method K2(i: int, j: int)
requires 0 <= i < arr.Length0 && 0 <= j < arr.Length1
modifies arr
{
forall k <- {-3, 4} {
// The following would have been an error (since this test file tests
// compilation, we don't include the test here):
// arr[i,j] := k; // error: k can take on more than one value
}
}
method K3(i: int, j: int)
requires 0 <= i < arr.Length0 && 0 <= j < arr.Length1
modifies arr
{
forall k: nat <- {-3, 4} | k <= i {
arr[k,j] := 50; // fine, since k:nat is at least 0
}
}
method K4(j: int)
requires 0 <= j < arr.Length1
modifies arr
{
forall i | 0 <= i < arr.Length0, k: nat <- {-3, 4} {
arr[i,j] := k; // fine, since k can only take on one value
}
}
method M()
{
var ar := new int [3,3];
var S: set<int> := {2,0};
forall k | k in S {
ar[k,1]:= 0;
}
forall k <- S, j <- S {
ar[k,j]:= 0;
}
}
method N() {
var ar := new int[3, 3];
ar[2,2] := 0;
}
method P() {
var ar := new int[3];
var prev := ar[..];
var S: set<int> := {};
forall k <- S {
ar[k] := 0;
}
}
method Q() {
var ar := new int[3,3];
var S: set<int> := {1,2};
forall k <- S {
ar[0,0] := 0;
}
}
}
|
408 | dafl_tmp_tmp_r3_8w3y_dafny_examples_dafny0_InSetComprehension.dfy | // 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;
}
}
| // 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] {
}
}
|
409 | dafl_tmp_tmp_r3_8w3y_dafny_examples_dafny0_PrecedenceLinter.dfy | // 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
}
}
}
| // 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
}
}
}
|
410 | dafl_tmp_tmp_r3_8w3y_dafny_examples_dafny0_SeqFromArray.dfy | // RUN: %dafny /compile:3 /print:"%t.print" /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// /autoTriggers:1 added to suppress instabilities
method Main() { }
method H(a: array<int>, c: array<int>, n: nat, j: nat)
requires j < n == a.Length == c.Length
{
var A := a[..];
var C := c[..];
if {
case A[j] == C[j] =>
assert a[j] == c[j];
case forall i :: 0 <= i < n ==> A[i] == C[i] =>
assert a[j] == c[j];
case forall i :: 0 <= i < n ==> A[i] == C[i] =>
assert forall i :: 0 <= i < n ==> a[i] == c[i];
case A == C =>
assert forall i :: 0 <= i < n ==> A[i] == C[i];
case A == C =>
assert forall i :: 0 <= i < n ==> a[i] == c[i];
case true =>
}
}
method K(a: array<int>, c: array<int>, n: nat)
requires n <= a.Length && n <= c.Length
{
var A := a[..n];
var C := c[..n];
if {
case A == C =>
assert forall i :: 0 <= i < n ==> A[i] == C[i];
case A == C =>
assert forall i :: 0 <= i < n ==> a[i] == c[i];
case true =>
}
}
method L(a: array<int>, c: array<int>, n: nat)
requires n <= a.Length == c.Length
{
var A := a[n..];
var C := c[n..];
var h := a.Length - n;
if {
case A == C =>
assert forall i :: 0 <= i < h ==> A[i] == C[i];
case A == C =>
assert forall i :: n <= i < n + h ==> a[i] == c[i];
case true =>
}
}
method M(a: array<int>, c: array<int>, m: nat, n: nat, k: nat, l: nat)
requires k + m <= a.Length
requires l + n <= c.Length
{
var A := a[k..k+m];
var C := c[l..l+n];
if A == C {
if * {
assert m == n;
} else if * {
assert forall i :: 0 <= i < n ==> A[i] == C[i];
} else if * {
assert forall i {:nowarn} :: k <= i < k+n ==> A[i-k] == C[i-k];
} else if * {
assert forall i :: 0 <= i < n ==> A[i] == a[k+i];
} else if * {
assert forall i :: 0 <= i < n ==> C[i] == c[l+i];
} else if * {
assert forall i {:nowarn} :: 0 <= i < n ==> a[k+i] == c[l+i];
}
}
}
method M'(a: array<int>, c: array<int>, m: nat, n: nat, k: nat, l: nat)
requires k + m <= a.Length
requires l + n <= c.Length
{
if {
case l+m <= c.Length && forall i :: 0 <= i < m ==> a[i] == c[l+i] =>
assert a[..m] == c[l..l+m];
case l+a.Length <= c.Length && forall i :: k <= i < a.Length ==> a[i] == c[l+i] =>
assert a[k..] == c[l+k..l+a.Length];
case l+k+m <= c.Length && forall i :: k <= i < k+m ==> a[i] == c[l+i] =>
assert a[k..k+m] == c[l+k..l+k+m];
case true =>
}
}
| // RUN: %dafny /compile:3 /print:"%t.print" /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// /autoTriggers:1 added to suppress instabilities
method Main() { }
method H(a: array<int>, c: array<int>, n: nat, j: nat)
requires j < n == a.Length == c.Length
{
var A := a[..];
var C := c[..];
if {
case A[j] == C[j] =>
case forall i :: 0 <= i < n ==> A[i] == C[i] =>
case forall i :: 0 <= i < n ==> A[i] == C[i] =>
case A == C =>
case A == C =>
case true =>
}
}
method K(a: array<int>, c: array<int>, n: nat)
requires n <= a.Length && n <= c.Length
{
var A := a[..n];
var C := c[..n];
if {
case A == C =>
case A == C =>
case true =>
}
}
method L(a: array<int>, c: array<int>, n: nat)
requires n <= a.Length == c.Length
{
var A := a[n..];
var C := c[n..];
var h := a.Length - n;
if {
case A == C =>
case A == C =>
case true =>
}
}
method M(a: array<int>, c: array<int>, m: nat, n: nat, k: nat, l: nat)
requires k + m <= a.Length
requires l + n <= c.Length
{
var A := a[k..k+m];
var C := c[l..l+n];
if A == C {
if * {
} else if * {
} else if * {
} else if * {
} else if * {
} else if * {
}
}
}
method M'(a: array<int>, c: array<int>, m: nat, n: nat, k: nat, l: nat)
requires k + m <= a.Length
requires l + n <= c.Length
{
if {
case l+m <= c.Length && forall i :: 0 <= i < m ==> a[i] == c[l+i] =>
case l+a.Length <= c.Length && forall i :: k <= i < a.Length ==> a[i] == c[l+i] =>
case l+k+m <= c.Length && forall i :: k <= i < k+m ==> a[i] == c[l+i] =>
case true =>
}
}
|
411 | dafl_tmp_tmp_r3_8w3y_dafny_examples_dafny0_SharedDestructorsCompile.dfy | // RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %dafny /noVerify /compile:4 /compileTarget:cs "%s" >> "%t"
// RUN: %dafny /noVerify /compile:4 /compileTarget:py "%s" >> "%t"
// RUN: %diff "%s.expect" "%t"
datatype Dt =
| A(x: int, y: real)
| B(h: MyClass, x: int)
| C(y: real)
class MyClass { }
method Main()
{
var o := new MyClass;
var s := [A(10, 12.0), B(o, 6), C(3.14)];
assert s[0].x == 10 && s[0].y == 12.0;
assert s[1].h == o && s[1].x == 6;
assert s[2].y == 3.14;
var d := s[0];
print d, ": x=", d.x, " y=", d.y, "\n";
d := s[1];
print d, ": h=", d.h, " x=", d.x, "\n";
d := s[2];
print d, ": y=", d.y, "\n";
s := [A(71, 0.1), B(o, 71)];
var i := 0;
while i < |s|
{
print d, "\n";
d := s[i];
assert d.x == 71;
i := i + 1;
}
BaseKlef(C3(44, 55, 66, 77));
Matte(AA(10, 2));
}
datatype Klef =
| C0(0: int, 1: int, 2: int, c0: int)
| C1(1: int, 2: int, 3: int, c1: int)
| C2(2: int, 3: int, 0: int, c2: int)
| C3(3: int, 0: int, 1: int, c3: int)
method BaseKlef(k: Klef)
requires !k.C0? && !k.C2? && !k.C1?
{
var k' := k.(0 := 100, c3 := 200); // makes a C3
assert k' == C3(k.3, 100, k.1, 200);
print k', "\n";
}
datatype Datte<T> = AA(a: int, x: int) | BB(b: bool, x: int) | CC(c: real) | DD(x: int, o: set<int>, p: bv27, q: T)
method Matte(d: Datte<real>)
requires !d.CC?
{
var d := d;
var s := d.(x := 5);
print d, " ", s, "\n"; // AA(10, 2) AA(10, 5)
d := BB(false, 12);
s := d.(x := 6);
print d, " ", s, "\n"; // BB(false, 12) BB(false, 6)
d := CC(3.2);
s := d.(c := 3.4);
print d, " ", s, "\n"; // CC(3.2) CC(3.4)
d := DD(100, {7}, 5, 9.0);
s := d.(x := 30);
print d, " ", s, "\n"; // DD(100, {7}, 5, 9.0) DD(30, {7}, 5, 9.0)
s := s.(q := 2.0, p := d.p);
print d, " ", s, "\n"; // DD(100, {7}, 5, 9.0) DD(30, {7}, 5, 2.0)
}
| // RUN: %dafny /compile:0 /dprint:"%t.dprint" "%s" > "%t"
// RUN: %dafny /noVerify /compile:4 /compileTarget:cs "%s" >> "%t"
// RUN: %dafny /noVerify /compile:4 /compileTarget:py "%s" >> "%t"
// RUN: %diff "%s.expect" "%t"
datatype Dt =
| A(x: int, y: real)
| B(h: MyClass, x: int)
| C(y: real)
class MyClass { }
method Main()
{
var o := new MyClass;
var s := [A(10, 12.0), B(o, 6), C(3.14)];
var d := s[0];
print d, ": x=", d.x, " y=", d.y, "\n";
d := s[1];
print d, ": h=", d.h, " x=", d.x, "\n";
d := s[2];
print d, ": y=", d.y, "\n";
s := [A(71, 0.1), B(o, 71)];
var i := 0;
while i < |s|
{
print d, "\n";
d := s[i];
i := i + 1;
}
BaseKlef(C3(44, 55, 66, 77));
Matte(AA(10, 2));
}
datatype Klef =
| C0(0: int, 1: int, 2: int, c0: int)
| C1(1: int, 2: int, 3: int, c1: int)
| C2(2: int, 3: int, 0: int, c2: int)
| C3(3: int, 0: int, 1: int, c3: int)
method BaseKlef(k: Klef)
requires !k.C0? && !k.C2? && !k.C1?
{
var k' := k.(0 := 100, c3 := 200); // makes a C3
print k', "\n";
}
datatype Datte<T> = AA(a: int, x: int) | BB(b: bool, x: int) | CC(c: real) | DD(x: int, o: set<int>, p: bv27, q: T)
method Matte(d: Datte<real>)
requires !d.CC?
{
var d := d;
var s := d.(x := 5);
print d, " ", s, "\n"; // AA(10, 2) AA(10, 5)
d := BB(false, 12);
s := d.(x := 6);
print d, " ", s, "\n"; // BB(false, 12) BB(false, 6)
d := CC(3.2);
s := d.(c := 3.4);
print d, " ", s, "\n"; // CC(3.2) CC(3.4)
d := DD(100, {7}, 5, 9.0);
s := d.(x := 30);
print d, " ", s, "\n"; // DD(100, {7}, 5, 9.0) DD(30, {7}, 5, 9.0)
s := s.(q := 2.0, p := d.p);
print d, " ", s, "\n"; // DD(100, {7}, 5, 9.0) DD(30, {7}, 5, 2.0)
}
|
412 | dafl_tmp_tmp_r3_8w3y_dafny_examples_uiowa_binary-search.dfy |
///////////////////
// 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.
*/
|
///////////////////
// 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.
*/
|
413 | dafl_tmp_tmp_r3_8w3y_dafny_examples_uiowa_fibonacci.dfy | /*
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;
}
}
}
| /*
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;
}
}
}
|
414 | dafl_tmp_tmp_r3_8w3y_dafny_examples_uiowa_find.dfy | /*
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;
}
| /*
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;
}
|
415 | dafl_tmp_tmp_r3_8w3y_dafny_examples_uiowa_modifying-arrays.dfy | /*
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;
}
}
| /*
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;
}
}
|
416 | dafleet_tmp_tmpa2e4kb9v_0001-0050_0001-two-sum.dfy | /* 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)
*/
| /* 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)
*/
|
417 | dafleet_tmp_tmpa2e4kb9v_0001-0050_0003-longest-substring-without-repeating-characters.dfy | /* 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?
| /* 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?
|
418 | dafleet_tmp_tmpa2e4kb9v_0001-0050_0005-longest-palindromic-substring.dfy | /* 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;
}
| /* 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);
}
|
419 | dafny-aoc-2019_tmp_tmpj6suy_rv_parser_split.dfy | 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")
}
}
| 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")
}
}
|
420 | dafny-duck_tmp_tmplawbgxjo_ex3.dfy | // 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]];
}
}
}
| // 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]];
}
}
}
|
421 | dafny-duck_tmp_tmplawbgxjo_ex5.dfy | // 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;
}
}
| // 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
}
}
|
422 | dafny-duck_tmp_tmplawbgxjo_p1.dfy | // 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];
}
| // 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;
}
}
|
423 | dafny-duck_tmp_tmplawbgxjo_p2.dfy | // 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[..];
}
| // 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[..];
}
|
424 | dafny-duck_tmp_tmplawbgxjo_p3.dfy | //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;
}
| //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;
}
|
425 | dafny-duck_tmp_tmplawbgxjo_p4.dfy | //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[..];
}
| //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[..];
}
|
426 | dafny-duck_tmp_tmplawbgxjo_p6.dfy | //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];
}
| //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;
}
}
|
427 | dafny-exercise_tmp_tmpouftptir_absIt.dfy | 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
}
| 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);
}
|
428 | dafny-exercise_tmp_tmpouftptir_appendArray.dfy | 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;
}
}
| 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;
}
}
|
429 | dafny-exercise_tmp_tmpouftptir_countNeg.dfy | 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);
}
| 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);
}
|
430 | dafny-exercise_tmp_tmpouftptir_filter.dfy | method Filter(a:seq<char>, b:set<char>) returns(c:set<char>)
ensures forall x :: x in a && x in b <==> x in c
{
var setA: set<char> := set x | x in a;
c := setA * b;
}
method TesterFilter()
{
var v:set<char> := {'a','e','i','o','u'}; // vowels to be used as a filter
var s:seq<char> := "ant-egg-ink-owl-urn";
var w:set<char> := Filter(s, v);
assert w == {'i','u','a','o','e'};
s := "nice-and-easy";
w := Filter(s, v);
assert w == {'a','e','i'};
s := "mssyysywbrpqsxmnlsghrytx"; // no vowels
w := Filter(s, v);
assert w == {};
s := "iiiiiiiiiiiii"; // 1 vowel
w := Filter(s, v);
assert w == {'i'};
s := "aeiou"; // s == v
w := Filter(s, v);
assert w == {'a','e','i','o','u'};
s := "u"; // edge singleton
w := Filter(s, v);
assert w == {'u'};
s := "f"; // edge singleton
w := Filter(s, v);
assert w == {};
s := ""; // edge empty seq
w := Filter(s, v);
assert w == {};
v := {}; // edge empty filter
s := "Any sequence that I like!!!";
w := Filter(s, v);
assert w == {};
}
| method Filter(a:seq<char>, b:set<char>) returns(c:set<char>)
ensures forall x :: x in a && x in b <==> x in c
{
var setA: set<char> := set x | x in a;
c := setA * b;
}
method TesterFilter()
{
var v:set<char> := {'a','e','i','o','u'}; // vowels to be used as a filter
var s:seq<char> := "ant-egg-ink-owl-urn";
var w:set<char> := Filter(s, v);
s := "nice-and-easy";
w := Filter(s, v);
s := "mssyysywbrpqsxmnlsghrytx"; // no vowels
w := Filter(s, v);
s := "iiiiiiiiiiiii"; // 1 vowel
w := Filter(s, v);
s := "aeiou"; // s == v
w := Filter(s, v);
s := "u"; // edge singleton
w := Filter(s, v);
s := "f"; // edge singleton
w := Filter(s, v);
s := ""; // edge empty seq
w := Filter(s, v);
v := {}; // edge empty filter
s := "Any sequence that I like!!!";
w := Filter(s, v);
}
|
431 | dafny-exercise_tmp_tmpouftptir_firstE.dfy | 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;
}
| 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);
}
|
432 | dafny-exercise_tmp_tmpouftptir_maxArray.dfy | 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;
}
| 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);
}
|
433 | dafny-exercise_tmp_tmpouftptir_prac1_ex1.dfy | predicate acheck(a: array<int>, n: int)
reads a
requires n >= 1
{
a.Length % 2 == 0 &&
forall i :: 0 <= i < a.Length ==>
if i % n == 0 then a[i] == 0 else a[i] != 0
}
method Main()
{
var arr: array<int> := new int[][0,42,0,42];
var res := acheck(arr, 2);
assert res;
arr := new int[][];
res := acheck(arr, 2);
assert res;
arr := new int[][0,4,2,0];
assert arr[2] == 2;
res := acheck(arr, 2);
assert !res;
}
| predicate acheck(a: array<int>, n: int)
reads a
requires n >= 1
{
a.Length % 2 == 0 &&
forall i :: 0 <= i < a.Length ==>
if i % n == 0 then a[i] == 0 else a[i] != 0
}
method Main()
{
var arr: array<int> := new int[][0,42,0,42];
var res := acheck(arr, 2);
arr := new int[][];
res := acheck(arr, 2);
arr := new int[][0,4,2,0];
res := acheck(arr, 2);
}
|
434 | dafny-exercise_tmp_tmpouftptir_prac1_ex2.dfy | 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[..] == ".";
}
| 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);
}
|
435 | dafny-exercise_tmp_tmpouftptir_prac3_ex2.dfy | 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;
}
| 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);
}
|
436 | dafny-exercise_tmp_tmpouftptir_prac4_ex2.dfy | 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!
}
| 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);
}
|
437 | dafny-exercise_tmp_tmpouftptir_reverse.dfy | 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';
}
| 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';
}
|
438 | dafny-exercise_tmp_tmpouftptir_zapNegatives.dfy | 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;
}
| 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);
}
|
439 | dafny-exercises_tmp_tmp5mvrowrx_leetcode_26-remove-duplicates-from-sorted-array.dfy |
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();
}
|
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();
}
|
440 | dafny-exercises_tmp_tmp5mvrowrx_paper_krml190.dfy | // 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;
}
}
}
| // 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;
}
}
}
|
441 | dafny-language-server_tmp_tmpkir0kenl_Test_LanguageServerTest_DafnyFiles_symbolTable_15_array.dfy | method Main() {
var i := 2;
var s := [1, i, 3, 4, 5];
print |s|; //size
assert s[|s|-1] == 5; //access the last element
assert s[|s|-1..|s|] == [5]; //slice just the last element, as a singleton
assert s[1..] == [2, 3, 4, 5]; // everything but the first
assert s[..|s|-1] == [1, 2, 3, 4]; // everything but the last
assert s == s[0..] == s[..|s|] == s[0..|s|] == s[..]; // the whole sequence
}
method foo (s: seq<int>)
requires |s| > 1
{
print s[1];
}
| method Main() {
var i := 2;
var s := [1, i, 3, 4, 5];
print |s|; //size
}
method foo (s: seq<int>)
requires |s| > 1
{
print s[1];
}
|
442 | dafny-language-server_tmp_tmpkir0kenl_Test_VSComp2010_Problem1-SumMax.dfy | // 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";
}
| // 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";
}
|
443 | dafny-language-server_tmp_tmpkir0kenl_Test_VSI-Benchmarks_b1.dfy | // 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";
}
| // 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";
}
|
444 | dafny-language-server_tmp_tmpkir0kenl_Test_VSI-Benchmarks_b2.dfy | // 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";
}
| // 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";
}
|
445 | dafny-language-server_tmp_tmpkir0kenl_Test_allocated1_dafny0_fun-with-slices.dfy | // 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;
}
}
| // 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;
}
}
|
446 | dafny-language-server_tmp_tmpkir0kenl_Test_comp_Arrays.dfy | // 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;
}
}
| // 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;
}
}
|
447 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny0_FuelTriggers.dfy | // RUN: %dafny /ironDafny /compile:0 /print:"%t.print" /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// In one version of opaque + fuel, the following failed to verify
// because the quantifier in the requires used a trigger that included
// StartFuel_P, while the assert used StartFuelAssert_P. Since P is
// opaque, we can't tell that those fuels are the same, and hence the
// trigger never fires
predicate {:opaque} P(x:int)
method test(y:int)
requires forall x :: P(x);
{
assert P(y);
}
| // RUN: %dafny /ironDafny /compile:0 /print:"%t.print" /dprint:"%t.dprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// In one version of opaque + fuel, the following failed to verify
// because the quantifier in the requires used a trigger that included
// StartFuel_P, while the assert used StartFuelAssert_P. Since P is
// opaque, we can't tell that those fuels are the same, and hence the
// trigger never fires
predicate {:opaque} P(x:int)
method test(y:int)
requires forall x :: P(x);
{
}
|
448 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny0_snapshots_Inputs_Snapshots0.dfy | method foo()
{
bar();
assert false;
}
method bar()
ensures false;
| method foo()
{
bar();
}
method bar()
ensures false;
|
449 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny1_Cubes.dfy | // 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;
}
}
| // 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;
}
}
|
450 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny1_ListReverse.dfy | // 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;
}
}
}
| // 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;
}
}
}
|
451 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny1_MatrixFun.dfy | // 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;
}
}
| // 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;
}
}
|
452 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny2_COST-verif-comp-2011-1-MaxArray.dfy | // 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;
}
| // 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;
}
|
453 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny2_Intervals.dfy | // 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;
}
}
| // 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;
}
}
|
454 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny2_SegmentSum.dfy | // 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;
}
}
}
| // 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;
}
}
}
|
455 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny2_TreeBarrier.dfy | // 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;
}
}
| // 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;
}
}
|
456 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny2_TuringFactorial.dfy | // 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;
}
}
| // 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;
}
}
|
457 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny3_InductionVsCoinduction.dfy | // 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;
{
}
| // 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));
{
}
|
458 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_Bug144.dfy | // RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
predicate p(i:int)
method m1()
method m2()
{
assume exists i :: p(i);
assert exists i :: p(i);
m1();
assert exists i :: p(i); // FAILS
}
class Test
{
var arr : array<int>;
predicate p(i: int)
method foo()
requires arr.Length > 0
modifies arr
{
assume exists i :: p(i);
arr[0] := 1;
assert exists i :: p(i); // FAILS
}
}
| // RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
predicate p(i:int)
method m1()
method m2()
{
assume exists i :: p(i);
m1();
}
class Test
{
var arr : array<int>;
predicate p(i: int)
method foo()
requires arr.Length > 0
modifies arr
{
assume exists i :: p(i);
arr[0] := 1;
}
}
|
459 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_Bug165.dfy | // RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
type T
function f(a: T) : bool
method Select(s1: seq<T>) returns (r: seq<T>)
ensures (forall e: T :: f(e) ==> multiset(s1)[e] == multiset(r)[e])
ensures (forall e: T :: (!f(e)) ==> 0 == multiset(r)[e])
method Main(s1: seq<T>)
{
var r1, r2: seq<T>;
r1 := Select(s1);
r2 := Select(s1);
assert multiset(r1) == multiset(r2);
}
| // RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
type T
function f(a: T) : bool
method Select(s1: seq<T>) returns (r: seq<T>)
ensures (forall e: T :: f(e) ==> multiset(s1)[e] == multiset(r)[e])
ensures (forall e: T :: (!f(e)) ==> 0 == multiset(r)[e])
method Main(s1: seq<T>)
{
var r1, r2: seq<T>;
r1 := Select(s1);
r2 := Select(s1);
}
|
460 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_Bug58.dfy | // RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
function M1(f:map<int, bool>, i:int):bool
function M2(f:map<int, bool>, i:int):bool
{
M1(map j | j in f :: f[j], i)
}
lemma L(f:map<int, bool>, i:int)
requires i in f;
requires M2(f, i);
requires forall j:int, f:map<int, bool> :: M1(f, j) == (j in f && f[j]);
{
assert f[i];
}
| // RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
function M1(f:map<int, bool>, i:int):bool
function M2(f:map<int, bool>, i:int):bool
{
M1(map j | j in f :: f[j], i)
}
lemma L(f:map<int, bool>, i:int)
requires i in f;
requires M2(f, i);
requires forall j:int, f:map<int, bool> :: M1(f, j) == (j in f && f[j]);
{
}
|
461 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_Bug92.dfy | // RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
module ModOpaque {
function {:opaque} Hidden(x:int) : (int, int)
{
(5, 7)
}
function Visible(x:int) : (int, int)
{
Hidden(x)
}
lemma foo(x:int, y:int, z:int)
requires (y, z) == Visible(x);
{
assert (y, z) == Hidden(x);
}
lemma bar(x:int, y:int, z:int)
requires y == Visible(x).0;
requires z == Visible(x).1;
{
assert (y, z) == Visible(x);
}
lemma baz(x:int, y:int, z:int)
requires y == Visible(x).0;
requires z == Visible(x).1;
{
assert (y, z) == Hidden(x);
}
}
module ModVisible {
function Hidden(x:int) : (int, int)
{
(5, 7)
}
function Visible(x:int) : (int, int)
{
Hidden(x)
}
lemma foo(x:int, y:int, z:int)
requires (y, z) == Visible(x);
{
assert (y, z) == Hidden(x);
}
lemma bar(x:int, y:int, z:int)
requires y == Visible(x).0;
requires z == Visible(x).1;
{
assert (y, z) == Visible(x);
}
lemma baz(x:int, y:int, z:int)
requires y == Visible(x).0;
requires z == Visible(x).1;
{
assert (y, z) == Hidden(x);
}
}
module ModFuel {
function {:fuel 0,0} Hidden(x:int) : (int, int)
{
(5, 7)
}
function Visible(x:int) : (int, int)
{
Hidden(x)
}
lemma foo(x:int, y:int, z:int)
requires (y, z) == Visible(x);
{
assert (y, z) == Hidden(x);
}
lemma bar(x:int, y:int, z:int)
requires y == Visible(x).0;
requires z == Visible(x).1;
{
assert (y, z) == Visible(x);
}
lemma baz(x:int, y:int, z:int)
requires y == Visible(x).0;
requires z == Visible(x).1;
{
assert (y, z) == Hidden(x);
}
}
| // RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
module ModOpaque {
function {:opaque} Hidden(x:int) : (int, int)
{
(5, 7)
}
function Visible(x:int) : (int, int)
{
Hidden(x)
}
lemma foo(x:int, y:int, z:int)
requires (y, z) == Visible(x);
{
}
lemma bar(x:int, y:int, z:int)
requires y == Visible(x).0;
requires z == Visible(x).1;
{
}
lemma baz(x:int, y:int, z:int)
requires y == Visible(x).0;
requires z == Visible(x).1;
{
}
}
module ModVisible {
function Hidden(x:int) : (int, int)
{
(5, 7)
}
function Visible(x:int) : (int, int)
{
Hidden(x)
}
lemma foo(x:int, y:int, z:int)
requires (y, z) == Visible(x);
{
}
lemma bar(x:int, y:int, z:int)
requires y == Visible(x).0;
requires z == Visible(x).1;
{
}
lemma baz(x:int, y:int, z:int)
requires y == Visible(x).0;
requires z == Visible(x).1;
{
}
}
module ModFuel {
function {:fuel 0,0} Hidden(x:int) : (int, int)
{
(5, 7)
}
function Visible(x:int) : (int, int)
{
Hidden(x)
}
lemma foo(x:int, y:int, z:int)
requires (y, z) == Visible(x);
{
}
lemma bar(x:int, y:int, z:int)
requires y == Visible(x).0;
requires z == Visible(x).1;
{
}
lemma baz(x:int, y:int, z:int)
requires y == Visible(x).0;
requires z == Visible(x).1;
{
}
}
|
462 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_Fstar-QuickSort.dfy | // 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')
*/
| // 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')
*/
|
463 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_Lucas-down.dfy | // 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);
}
}
}
| // 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);
}
}
}
|
464 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_MonadicLaws.dfy | // RUN: %dafny /compile:0 /rprint:"%t.rprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// Monadic Laws
// Niki Vazou and Rustan Leino
// 28 March 2016
datatype List<T> = Nil | Cons(head: T, tail: List)
function append(xs: List, ys: List): List
{
match xs
case Nil => ys
case Cons(x, xs') => Cons(x, append(xs', ys))
}
lemma AppendNil(xs: List)
ensures append(xs, Nil) == xs
{
}
lemma AppendAssoc(xs: List, ys: List, zs: List)
ensures append(append(xs, ys), zs) == append(xs, append(ys, zs));
{
}
function Return<T>(a: T): List
{
Cons(a, Nil)
}
function Bind<T,U>(xs: List<T>, f: T -> List<U>): List<U>
{
match xs
case Nil => Nil
case Cons(x, xs') => append(f(x), Bind(xs', f))
}
lemma LeftIdentity<T>(a: T, f: T -> List)
ensures Bind(Return(a), f) == f(a)
{
AppendNil(f(a));
}
lemma RightIdentity<T>(m: List)
ensures Bind(m, Return) == m
{
match m
case Nil =>
assert Bind<T,T>(Nil, Return) == Nil;
case Cons(x, m') =>
calc {
Bind(Cons(x, m'), Return);
append(Return(x), Bind(m', Return));
Cons(x, Bind(m', Return));
}
}
lemma Associativity<T>(m: List, f: T -> List, g: T -> List)
ensures Bind(Bind(m, f), g) == Bind(m, x => Bind(f(x), g))
{
match m
case Nil =>
assert Bind(m, x => Bind(f(x), g)) == Nil;
case Cons(x, xs) =>
match f(x)
case Nil =>
calc {
Bind(xs, y => Bind(f(y), g));
Bind(Cons(x, xs), y => Bind(f(y), g));
}
case Cons(y, ys) =>
calc {
append(g(y), Bind(append(ys, Bind(xs, f)), g));
{ BindOverAppend(ys, Bind(xs, f), g); }
append(g(y), append(Bind(ys, g), Bind(Bind(xs, f), g)));
{ AppendAssoc(g(y), Bind(ys, g), Bind(Bind(xs, f), g)); }
append(append(g(y), Bind(ys, g)), Bind(Bind(xs, f), g));
Bind(Cons(x, xs), z => Bind(f(z), g));
}
}
lemma BindOverAppend<T>(xs: List, ys: List, g: T -> List)
ensures Bind(append(xs, ys), g) == append(Bind(xs, g), Bind(ys, g))
{
match xs
case Nil =>
case Cons(x, xs') =>
AppendAssoc(g(x), Bind(xs', g), Bind(ys, g));
}
| // RUN: %dafny /compile:0 /rprint:"%t.rprint" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// Monadic Laws
// Niki Vazou and Rustan Leino
// 28 March 2016
datatype List<T> = Nil | Cons(head: T, tail: List)
function append(xs: List, ys: List): List
{
match xs
case Nil => ys
case Cons(x, xs') => Cons(x, append(xs', ys))
}
lemma AppendNil(xs: List)
ensures append(xs, Nil) == xs
{
}
lemma AppendAssoc(xs: List, ys: List, zs: List)
ensures append(append(xs, ys), zs) == append(xs, append(ys, zs));
{
}
function Return<T>(a: T): List
{
Cons(a, Nil)
}
function Bind<T,U>(xs: List<T>, f: T -> List<U>): List<U>
{
match xs
case Nil => Nil
case Cons(x, xs') => append(f(x), Bind(xs', f))
}
lemma LeftIdentity<T>(a: T, f: T -> List)
ensures Bind(Return(a), f) == f(a)
{
AppendNil(f(a));
}
lemma RightIdentity<T>(m: List)
ensures Bind(m, Return) == m
{
match m
case Nil =>
case Cons(x, m') =>
calc {
Bind(Cons(x, m'), Return);
append(Return(x), Bind(m', Return));
Cons(x, Bind(m', Return));
}
}
lemma Associativity<T>(m: List, f: T -> List, g: T -> List)
ensures Bind(Bind(m, f), g) == Bind(m, x => Bind(f(x), g))
{
match m
case Nil =>
case Cons(x, xs) =>
match f(x)
case Nil =>
calc {
Bind(xs, y => Bind(f(y), g));
Bind(Cons(x, xs), y => Bind(f(y), g));
}
case Cons(y, ys) =>
calc {
append(g(y), Bind(append(ys, Bind(xs, f)), g));
{ BindOverAppend(ys, Bind(xs, f), g); }
append(g(y), append(Bind(ys, g), Bind(Bind(xs, f), g)));
{ AppendAssoc(g(y), Bind(ys, g), Bind(Bind(xs, f), g)); }
append(append(g(y), Bind(ys, g)), Bind(Bind(xs, f), g));
Bind(Cons(x, xs), z => Bind(f(z), g));
}
}
lemma BindOverAppend<T>(xs: List, ys: List, g: T -> List)
ensures Bind(append(xs, ys), g) == append(Bind(xs, g), Bind(ys, g))
{
match xs
case Nil =>
case Cons(x, xs') =>
AppendAssoc(g(x), Bind(xs', g), Bind(ys, g));
}
|
465 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_Regression19.dfy | // RUN: %dafny "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
predicate ContainsNothingBut5(s: set<int>)
{
forall q :: q in s ==> q == 5
}
predicate YeahContains5(s: set<int>)
{
exists q :: q in s && q == 5
}
predicate ViaSetComprehension(s: set<int>) {
|set q | q in s && q == 5| != 0
}
predicate LambdaTest(s: set<int>) {
(q => q in s)(5)
}
predicate ViaMapComprehension(s: set<int>) {
|(map q | q in s && q == 5 :: true).Keys| != 0
}
predicate Contains5(s: set<int>)
{
var q := 5; q in s
}
datatype R = MakeR(int) | Other
predicate RIs5(r: R) {
match r case MakeR(q) => q == 5 case Other => false
}
lemma NonemptySet(x: int, s: set<int>)
requires x in s
ensures |s| != 0
{
}
lemma NonemptyMap(x: int, s: map<int,bool>)
requires x in s.Keys
ensures |s| != 0
{
}
method M(s: set<int>, r: R, q: int)
requires s == {5} && r == MakeR(5)
{
assert ContainsNothingBut5(s); // forall
assert YeahContains5(s); // exists
NonemptySet(5, set q | q in s && q == 5);
assert ViaSetComprehension(s); // set comprehension
NonemptyMap(5, map q | q in s && q == 5 :: true);
assert ViaMapComprehension(s); // map comprehension
assert LambdaTest(s); // lambda expression
assert Contains5(s); // let expression (once had generated malformed Boogie)
assert RIs5(r); // match expression
}
| // RUN: %dafny "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
predicate ContainsNothingBut5(s: set<int>)
{
forall q :: q in s ==> q == 5
}
predicate YeahContains5(s: set<int>)
{
exists q :: q in s && q == 5
}
predicate ViaSetComprehension(s: set<int>) {
|set q | q in s && q == 5| != 0
}
predicate LambdaTest(s: set<int>) {
(q => q in s)(5)
}
predicate ViaMapComprehension(s: set<int>) {
|(map q | q in s && q == 5 :: true).Keys| != 0
}
predicate Contains5(s: set<int>)
{
var q := 5; q in s
}
datatype R = MakeR(int) | Other
predicate RIs5(r: R) {
match r case MakeR(q) => q == 5 case Other => false
}
lemma NonemptySet(x: int, s: set<int>)
requires x in s
ensures |s| != 0
{
}
lemma NonemptyMap(x: int, s: map<int,bool>)
requires x in s.Keys
ensures |s| != 0
{
}
method M(s: set<int>, r: R, q: int)
requires s == {5} && r == MakeR(5)
{
NonemptySet(5, set q | q in s && q == 5);
NonemptyMap(5, map q | q in s && q == 5 :: true);
}
|
466 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_git-issue133.dfy | // RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
datatype State = State(m:map<int, bool>)
lemma Test(s:State)
requires 42 in s.m
ensures s.(m := s.m[42 := s.m[42]]) == s
{
var s' := s.(m := s.m[42 := s.m[42]]);
assert s'.m == s.m;
}
datatype MyDt = MakeA(x: int, bool) | MakeB(s: multiset<int>, t: State)
lemma AnotherTest(a: MyDt, b: MyDt, c: bool)
requires a.MakeB? && b.MakeB?
requires a.s == multiset(a.t.m.Keys) && |b.s| == 0
requires a.t.m == map[] && |b.t.m| == 0
{
assert a == b;
}
datatype GenDt<X,Y> = Left(X) | Middle(X,int,Y) | Right(y: Y)
method ChangeGen(g: GenDt)
{
match g
case Left(_) =>
case Middle(_,_,_) =>
case Right(u) =>
var h := g.(y := u);
assert g == h;
}
datatype Recursive<X> = Red | Green(next: Recursive, m: set)
lemma RecLem(r: Recursive) returns (s: Recursive)
ensures r == s
{
match r
case Red =>
s := Red;
case Green(next, m) =>
var n := RecLem(next);
s := Green(n, m + m);
}
| // RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
datatype State = State(m:map<int, bool>)
lemma Test(s:State)
requires 42 in s.m
ensures s.(m := s.m[42 := s.m[42]]) == s
{
var s' := s.(m := s.m[42 := s.m[42]]);
}
datatype MyDt = MakeA(x: int, bool) | MakeB(s: multiset<int>, t: State)
lemma AnotherTest(a: MyDt, b: MyDt, c: bool)
requires a.MakeB? && b.MakeB?
requires a.s == multiset(a.t.m.Keys) && |b.s| == 0
requires a.t.m == map[] && |b.t.m| == 0
{
}
datatype GenDt<X,Y> = Left(X) | Middle(X,int,Y) | Right(y: Y)
method ChangeGen(g: GenDt)
{
match g
case Left(_) =>
case Middle(_,_,_) =>
case Right(u) =>
var h := g.(y := u);
}
datatype Recursive<X> = Red | Green(next: Recursive, m: set)
lemma RecLem(r: Recursive) returns (s: Recursive)
ensures r == s
{
match r
case Red =>
s := Red;
case Green(next, m) =>
var n := RecLem(next);
s := Green(n, m + m);
}
|
467 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_git-issue40.dfy | // RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
function SeqRepeat<T>(count:nat, elt:T) : seq<T>
ensures |SeqRepeat<T>(count, elt)| == count
ensures forall i :: 0 <= i < count ==> SeqRepeat<T>(count, elt)[i] == elt
datatype Maybe<T> = Nothing | Just(v: T)
type Num = x | 0 <= x < 10
datatype D = C(seq<Maybe<Num>>)
lemma test()
{
ghost var s := SeqRepeat(1, Nothing);
ghost var e := C(s);
assert e == C(SeqRepeat(1, Nothing));
}
| // RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
function SeqRepeat<T>(count:nat, elt:T) : seq<T>
ensures |SeqRepeat<T>(count, elt)| == count
ensures forall i :: 0 <= i < count ==> SeqRepeat<T>(count, elt)[i] == elt
datatype Maybe<T> = Nothing | Just(v: T)
type Num = x | 0 <= x < 10
datatype D = C(seq<Maybe<Num>>)
lemma test()
{
ghost var s := SeqRepeat(1, Nothing);
ghost var e := C(s);
}
|
468 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_git-issue41.dfy | // RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
type uint32 = i:int | 0 <= i < 0x1_0000_0000
function last<T>(s:seq<T>):T
requires |s| > 0;
{
s[|s|-1]
}
function all_but_last<T>(s:seq<T>):seq<T>
requires |s| > 0;
ensures |all_but_last(s)| == |s| - 1;
{
s[..|s|-1]
}
function ConcatenateSeqs<T>(ss:seq<seq<T>>) : seq<T>
{
if |ss| == 0 then [] else ss[0] + ConcatenateSeqs(ss[1..])
}
lemma {:axiom} lemma_ReverseConcatenateSeqs<T>(ss:seq<seq<T>>)
requires |ss| > 0;
ensures ConcatenateSeqs(ss) == ConcatenateSeqs(all_but_last(ss)) + last(ss);
lemma Test(word_seqs:seq<seq<uint32>>, words:seq<uint32>)
{
var word_seqs' := word_seqs + [words];
calc {
ConcatenateSeqs(word_seqs');
{ lemma_ReverseConcatenateSeqs(word_seqs'); }
ConcatenateSeqs(all_but_last(word_seqs')) + last(word_seqs');
}
}
lemma AltTest(word_seqs:seq<seq<uint32>>, words:seq<uint32>)
{
var word_seqs' := word_seqs + [words];
assert last(word_seqs') == words;
assert ConcatenateSeqs(word_seqs) + last(word_seqs') == ConcatenateSeqs(word_seqs) + words;
}
function f<T>(s:seq<T>):seq<T>
function g<T>(ss:seq<seq<T>>) : seq<T>
lemma {:axiom} lemma_fg<T>(s:seq<seq<T>>)
ensures g(s) == g(f(s));
lemma Test2(s:seq<seq<uint32>>)
{
calc {
g(s);
{ lemma_fg(s); }
g(f(s));
}
}
lemma AltTest2(s:seq<seq<uint32>>)
{
lemma_fg(s);
assert g(s) == g(f(s));
}
| // RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
type uint32 = i:int | 0 <= i < 0x1_0000_0000
function last<T>(s:seq<T>):T
requires |s| > 0;
{
s[|s|-1]
}
function all_but_last<T>(s:seq<T>):seq<T>
requires |s| > 0;
ensures |all_but_last(s)| == |s| - 1;
{
s[..|s|-1]
}
function ConcatenateSeqs<T>(ss:seq<seq<T>>) : seq<T>
{
if |ss| == 0 then [] else ss[0] + ConcatenateSeqs(ss[1..])
}
lemma {:axiom} lemma_ReverseConcatenateSeqs<T>(ss:seq<seq<T>>)
requires |ss| > 0;
ensures ConcatenateSeqs(ss) == ConcatenateSeqs(all_but_last(ss)) + last(ss);
lemma Test(word_seqs:seq<seq<uint32>>, words:seq<uint32>)
{
var word_seqs' := word_seqs + [words];
calc {
ConcatenateSeqs(word_seqs');
{ lemma_ReverseConcatenateSeqs(word_seqs'); }
ConcatenateSeqs(all_but_last(word_seqs')) + last(word_seqs');
}
}
lemma AltTest(word_seqs:seq<seq<uint32>>, words:seq<uint32>)
{
var word_seqs' := word_seqs + [words];
}
function f<T>(s:seq<T>):seq<T>
function g<T>(ss:seq<seq<T>>) : seq<T>
lemma {:axiom} lemma_fg<T>(s:seq<seq<T>>)
ensures g(s) == g(f(s));
lemma Test2(s:seq<seq<uint32>>)
{
calc {
g(s);
{ lemma_fg(s); }
g(f(s));
}
}
lemma AltTest2(s:seq<seq<uint32>>)
{
lemma_fg(s);
}
|
469 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_git-issue67.dfy | // RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
class Node { }
predicate Q(x: Node)
predicate P(x: Node)
method AuxMethod(y: Node)
modifies y
method MainMethod(y: Node)
modifies y
{
AuxMethod(y); // remove this call and the assertion below goes through (as it should)
forall x | Q(x)
ensures P(x)
{
assume false;
}
// The following assertion should be a direct consequence of the forall statement above
assert forall x :: Q(x) ==> P(x);
}
| // RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
class Node { }
predicate Q(x: Node)
predicate P(x: Node)
method AuxMethod(y: Node)
modifies y
method MainMethod(y: Node)
modifies y
{
AuxMethod(y); // remove this call and the assertion below goes through (as it should)
forall x | Q(x)
ensures P(x)
{
assume false;
}
// The following assertion should be a direct consequence of the forall statement above
}
|
470 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_git-issue74.dfy | // RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
function{:opaque} f(x:int):int { x }
lemma L()
ensures forall x:int :: f(x) == x
{
forall x:int
ensures f(x) == x
{
reveal f();
}
assert forall x:int :: f(x) == x;
}
| // RUN: %dafny /compile:0 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
function{:opaque} f(x:int):int { x }
lemma L()
ensures forall x:int :: f(x) == x
{
forall x:int
ensures f(x) == x
{
reveal f();
}
}
|
471 | dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_git-issue76.dfy | // RUN: %dafny /compile:3 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
method Main() {
M0();
M1();
EqualityOfStrings0();
EqualityOfStrings1();
}
// The verification of the following methods requires knowledge
// about the injectivity of sequence displays.
method M0()
{
assert {"x","y","z"}-{"y"} == {"x","z"};
}
method M1()
{
var n :| ("R",n) in {("R",2),("P",1)};
assert n == 2;
print n, "\n";
}
method EqualityOfStrings0() {
assert "a" != "b";
}
method EqualityOfStrings1() {
assert "a" + "b" == "ab";
}
method M2()
{
assert !( [0,0] in {[0,2],[1,2]} );
}
method M3()
{
assert [0,0] !in {[0,2],[1,2]};
}
| // RUN: %dafny /compile:3 "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
method Main() {
M0();
M1();
EqualityOfStrings0();
EqualityOfStrings1();
}
// The verification of the following methods requires knowledge
// about the injectivity of sequence displays.
method M0()
{
}
method M1()
{
var n :| ("R",n) in {("R",2),("P",1)};
print n, "\n";
}
method EqualityOfStrings0() {
}
method EqualityOfStrings1() {
}
method M2()
{
}
method M3()
{
}
|
472 | dafny-language-server_tmp_tmpkir0kenl_Test_git-issues_git-issue-336.dfy | // 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);
}
| // 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);
}
|
473 | dafny-language-server_tmp_tmpkir0kenl_Test_hofs_Compilation.dfy | // 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";
}
| // 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";
}
|
474 | dafny-language-server_tmp_tmpkir0kenl_Test_hofs_Requires.dfy | // 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;
}
}
| // 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;
}
}
|
475 | dafny-language-server_tmp_tmpkir0kenl_Test_hofs_SumSum.dfy | // 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
|
476 | dafny-language-server_tmp_tmpkir0kenl_Test_hofs_WhileLoop.dfy | // RUN: %dafny /compile:3 /print:"%t.print" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
class Ref<A(0)> {
var val: A
}
method Nice(n: int) returns (k: int) {
var f : int -> int := x => x;
var i := new Ref<int>;
i.val := 0;
while i.val < n
invariant forall u :: f.requires(u)
invariant forall u :: f.reads(u) == {}
invariant forall u :: f(u) == u + i.val
{
i.val := i.val + 1;
f := x => f(x) + 1;
}
return f(0);
}
method OneShot(n: int) returns (k: int) {
var f : int -> int := x => x;
var i := 0;
while i < n
invariant forall u :: f.requires(u)
invariant forall u :: f(u) == u + i
{
i := i + 1;
f := x requires f.requires(x) reads f.reads(x) => f(x) + 1;
}
k := f(0);
}
method HeapQuant(n: int) returns (k: int) {
var f : int -> int := x => x;
var i := new Ref;
ghost var r := 0;
i.val := 0;
while i.val < n
invariant forall u :: f.requires(u)
invariant forall u :: f.reads(u) == {}
invariant r == i.val
invariant forall u :: f(u) == u + r
{
i.val, r := i.val + 1, r + 1;
f := x => f(x) + 1;
}
k := f(0);
}
method Main() {
var k0 := Nice(22);
var k1 := OneShot(22);
var k2 := HeapQuant(22);
print k0, " ", k1, " ", k2, "\n";
}
| // RUN: %dafny /compile:3 /print:"%t.print" "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
class Ref<A(0)> {
var val: A
}
method Nice(n: int) returns (k: int) {
var f : int -> int := x => x;
var i := new Ref<int>;
i.val := 0;
while i.val < n
{
i.val := i.val + 1;
f := x => f(x) + 1;
}
return f(0);
}
method OneShot(n: int) returns (k: int) {
var f : int -> int := x => x;
var i := 0;
while i < n
{
i := i + 1;
f := x requires f.requires(x) reads f.reads(x) => f(x) + 1;
}
k := f(0);
}
method HeapQuant(n: int) returns (k: int) {
var f : int -> int := x => x;
var i := new Ref;
ghost var r := 0;
i.val := 0;
while i.val < n
{
i.val, r := i.val + 1, r + 1;
f := x => f(x) + 1;
}
k := f(0);
}
method Main() {
var k0 := Nice(22);
var k1 := OneShot(22);
var k2 := HeapQuant(22);
print k0, " ", k1, " ", k2, "\n";
}
|
477 | dafny-language-server_tmp_tmpkir0kenl_Test_triggers_auto-triggers-fix-an-issue-listed-in-the-ironclad-notebook.dfy | // RUN: %dafny /compile:0 /print:"%t.print" /dprint:"%t.dprint" /printTooltips "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// This example was listed in IronClad's notebook as one place were z3 picked
// much too liberal triggers. THe Boogie code for this is shown below:
//
// forall k#2: Seq Box :: $Is(k#2, TSeq(TInt)) && $IsAlloc(k#2, TSeq(TInt), $Heap)
// ==> Seq#Equal(_module.__default.HashtableLookup($Heap, h1#0, k#2),
// _module.__default.HashtableLookup($Heap, h2#0, k#2))
//
// and z3 would pick $Is(k#2, TSeq(TInt)) or $IsAlloc(k#2, TSeq(TInt), $Heap) as
// triggers.
type Key = seq<int>
type Value = seq<int>
type Hashtable = map<Key, Value>
function HashtableLookup(h: Hashtable, k: Key): Value
lemma HashtableAgreement(h1:Hashtable, h2:Hashtable, k:Key)
requires forall k :: HashtableLookup(h1,k) == HashtableLookup(h2,k) {
assert true || (k in h1) == (k in h2);
}
| // RUN: %dafny /compile:0 /print:"%t.print" /dprint:"%t.dprint" /printTooltips "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// This example was listed in IronClad's notebook as one place were z3 picked
// much too liberal triggers. THe Boogie code for this is shown below:
//
// forall k#2: Seq Box :: $Is(k#2, TSeq(TInt)) && $IsAlloc(k#2, TSeq(TInt), $Heap)
// ==> Seq#Equal(_module.__default.HashtableLookup($Heap, h1#0, k#2),
// _module.__default.HashtableLookup($Heap, h2#0, k#2))
//
// and z3 would pick $Is(k#2, TSeq(TInt)) or $IsAlloc(k#2, TSeq(TInt), $Heap) as
// triggers.
type Key = seq<int>
type Value = seq<int>
type Hashtable = map<Key, Value>
function HashtableLookup(h: Hashtable, k: Key): Value
lemma HashtableAgreement(h1:Hashtable, h2:Hashtable, k:Key)
requires forall k :: HashtableLookup(h1,k) == HashtableLookup(h2,k) {
}
|
478 | dafny-language-server_tmp_tmpkir0kenl_Test_triggers_function-applications-are-triggers.dfy | // 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;
}
| // 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;
}
|
479 | dafny-language-server_tmp_tmpkir0kenl_Test_triggers_large-quantifiers-dont-break-dafny.dfy | // RUN: %dafny /compile:0 /print:"%t.print" /dprint:"%t.dprint" /printTooltips "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// This test ensures that the trigger collector (the routine that picks trigger
// candidates) does not actually consider all subsets of terms; if it did, the
// following would take horribly long
predicate P0(x: bool)
predicate P1(x: bool)
predicate P2(x: bool)
predicate P3(x: bool)
predicate P4(x: bool)
predicate P5(x: bool)
predicate P6(x: bool)
predicate P7(x: bool)
predicate P8(x: bool)
predicate P9(x: bool)
predicate P10(x: bool)
predicate P11(x: bool)
predicate P12(x: bool)
predicate P13(x: bool)
predicate P14(x: bool)
predicate P15(x: bool)
predicate P16(x: bool)
predicate P17(x: bool)
predicate P18(x: bool)
predicate P19(x: bool)
predicate P20(x: bool)
predicate P21(x: bool)
predicate P22(x: bool)
predicate P23(x: bool)
predicate P24(x: bool)
predicate P25(x: bool)
predicate P26(x: bool)
predicate P27(x: bool)
predicate P28(x: bool)
predicate P29(x: bool)
predicate P30(x: bool)
predicate P31(x: bool)
predicate P32(x: bool)
predicate P33(x: bool)
predicate P34(x: bool)
predicate P35(x: bool)
predicate P36(x: bool)
predicate P37(x: bool)
predicate P38(x: bool)
predicate P39(x: bool)
predicate P40(x: bool)
predicate P41(x: bool)
predicate P42(x: bool)
predicate P43(x: bool)
predicate P44(x: bool)
predicate P45(x: bool)
predicate P46(x: bool)
predicate P47(x: bool)
predicate P48(x: bool)
predicate P49(x: bool)
method M() {
assert forall x :: true || P0(x) || P1(x) || P2(x) || P3(x) || P4(x) || P5(x) || P6(x) || P7(x) || P8(x) || P9(x) || P10(x) || P11(x) || P12(x) || P13(x) || P14(x) || P15(x) || P16(x) || P17(x) || P18(x) || P19(x) || P20(x) || P21(x) || P22(x) || P23(x) || P24(x) || P25(x) || P26(x) || P27(x) || P28(x) || P29(x) || P30(x) || P31(x) || P32(x) || P33(x) || P34(x) || P35(x) || P36(x) || P37(x) || P38(x) || P39(x) || P40(x) || P41(x) || P42(x) || P43(x) || P44(x) || P45(x) || P46(x) || P47(x) || P48(x) || P49(x);
}
| // RUN: %dafny /compile:0 /print:"%t.print" /dprint:"%t.dprint" /printTooltips "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// This test ensures that the trigger collector (the routine that picks trigger
// candidates) does not actually consider all subsets of terms; if it did, the
// following would take horribly long
predicate P0(x: bool)
predicate P1(x: bool)
predicate P2(x: bool)
predicate P3(x: bool)
predicate P4(x: bool)
predicate P5(x: bool)
predicate P6(x: bool)
predicate P7(x: bool)
predicate P8(x: bool)
predicate P9(x: bool)
predicate P10(x: bool)
predicate P11(x: bool)
predicate P12(x: bool)
predicate P13(x: bool)
predicate P14(x: bool)
predicate P15(x: bool)
predicate P16(x: bool)
predicate P17(x: bool)
predicate P18(x: bool)
predicate P19(x: bool)
predicate P20(x: bool)
predicate P21(x: bool)
predicate P22(x: bool)
predicate P23(x: bool)
predicate P24(x: bool)
predicate P25(x: bool)
predicate P26(x: bool)
predicate P27(x: bool)
predicate P28(x: bool)
predicate P29(x: bool)
predicate P30(x: bool)
predicate P31(x: bool)
predicate P32(x: bool)
predicate P33(x: bool)
predicate P34(x: bool)
predicate P35(x: bool)
predicate P36(x: bool)
predicate P37(x: bool)
predicate P38(x: bool)
predicate P39(x: bool)
predicate P40(x: bool)
predicate P41(x: bool)
predicate P42(x: bool)
predicate P43(x: bool)
predicate P44(x: bool)
predicate P45(x: bool)
predicate P46(x: bool)
predicate P47(x: bool)
predicate P48(x: bool)
predicate P49(x: bool)
method M() {
}
|
480 | dafny-language-server_tmp_tmpkir0kenl_Test_triggers_loop-detection-looks-at-ranges-too.dfy | // RUN: %dafny /compile:0 /print:"%t.print" /dprint:"%t.dprint" /printTooltips "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// This file checks that loops between the range and the term of a quantifier
// are properly detected.
predicate P(x: int)
method M(x: int) {
// This will be flagged as a loop even without looking at the range
assert true || forall x: int | P(x) :: P(x+1);
// This requires checking the range for looping terms
assert true || forall x: int | P(x+1) :: P(x);
}
| // RUN: %dafny /compile:0 /print:"%t.print" /dprint:"%t.dprint" /printTooltips "%s" > "%t"
// RUN: %diff "%s.expect" "%t"
// This file checks that loops between the range and the term of a quantifier
// are properly detected.
predicate P(x: int)
method M(x: int) {
// This will be flagged as a loop even without looking at the range
// This requires checking the range for looping terms
}
|
481 | dafny-language-server_tmp_tmpkir0kenl_Test_tutorial_maximum.dfy | // 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.
}
| // 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.
}
|
482 | dafny-language-server_tmp_tmpkir0kenl_Test_vacid0_Composite.dfy | // 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;
}
| // 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});
}
|
483 | dafny-language-server_tmp_tmpkir0kenl_Test_vstte2012_Two-Way-Sort.dfy | // 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;
}
}
}
| // 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;
}
}
}
|
484 | dafny-learn_tmp_tmpn94ir40q_R01_assertions.dfy | method Abs(x: int) returns (y: int)
ensures 0 <= y
ensures x < 0 ==> y == -x
ensures x >= 0 ==> y == x
{
if x < 0 {
return -x;
} else {
return x;
}
}
method TestingAbs()
{
var w := Abs(4);
assert w >= 0;
var v := Abs(3);
assert 0 <= v;
}
method TestingAbs2()
{
var v := Abs(3);
// property of v dependes on the post condition
assert 0 <= v;
assert v == 3;
}
// Exercise 1. Write a test method that calls your Max method from Exercise 0 and then asserts something about the result.
// Use your code from Exercise 0
method Max(a: int, b: int) returns (c: int)
ensures c >= a
ensures c >= b
{
c := a;
if b > c {
c := b;
}
}
method TestingMax() {
// Assert some things about Max. Does it operate as you expect?
// If it does not, can you think of a way to fix it?
var a := 3;
var b := 2;
var c := Max(a, b);
assert c >= a;
assert c >= b;
}
| method Abs(x: int) returns (y: int)
ensures 0 <= y
ensures x < 0 ==> y == -x
ensures x >= 0 ==> y == x
{
if x < 0 {
return -x;
} else {
return x;
}
}
method TestingAbs()
{
var w := Abs(4);
var v := Abs(3);
}
method TestingAbs2()
{
var v := Abs(3);
// property of v dependes on the post condition
}
// Exercise 1. Write a test method that calls your Max method from Exercise 0 and then asserts something about the result.
// Use your code from Exercise 0
method Max(a: int, b: int) returns (c: int)
ensures c >= a
ensures c >= b
{
c := a;
if b > c {
c := b;
}
}
method TestingMax() {
// Assert some things about Max. Does it operate as you expect?
// If it does not, can you think of a way to fix it?
var a := 3;
var b := 2;
var c := Max(a, b);
}
|
485 | dafny-learn_tmp_tmpn94ir40q_R01_functions.dfy | function abs(x: int): int
{
if x < 0 then -x else x
}
method Testing_abs()
{
var v := abs(3);
assert v == 3;
}
// Exercise 4. Write a function max that returns the larger of two given integer parameters. Write a test method using an assert that checks that your function is correct.
function max(a: int, b: int): int
{
// Fill in an expression here.
if a > b then a else b
}
method Testing_max() {
// Add assertions to check max here.
assert max(3, 4) == 4;
assert max(-1, -4) == -1;
}
// Exercise 6:
method Abs(x: int) returns (y: int)
ensures abs(x) == y
{
// Then change this body to also use abs.
if x < 0 {
return -x;
} else {
return x;
}
}
// Ghost
ghost function Double(val:int) : int
{
2 * val
}
method TestDouble(val: int) returns (val2:int)
ensures val2 == Double(val)
{
val2 := 2 * val;
}
| function abs(x: int): int
{
if x < 0 then -x else x
}
method Testing_abs()
{
var v := abs(3);
}
// Exercise 4. Write a function max that returns the larger of two given integer parameters. Write a test method using an assert that checks that your function is correct.
function max(a: int, b: int): int
{
// Fill in an expression here.
if a > b then a else b
}
method Testing_max() {
// Add assertions to check max here.
}
// Exercise 6:
method Abs(x: int) returns (y: int)
ensures abs(x) == y
{
// Then change this body to also use abs.
if x < 0 {
return -x;
} else {
return x;
}
}
// Ghost
ghost function Double(val:int) : int
{
2 * val
}
method TestDouble(val: int) returns (val2:int)
ensures val2 == Double(val)
{
val2 := 2 * val;
}
|
486 | dafny-mini-project_tmp_tmpjxr3wzqh_src_project2a.dfy | /*
===============================================
DCC831 Formal Methods
2023.2
Mini Project 2 - Part A
Your name: Guilherme de Oliveira Silva
===============================================
*/
function rem<T(==)>(x: T, s: seq<T>): seq<T>
decreases s
ensures x !in rem(x, s)
ensures forall i :: 0 <= i < |rem(x, s)| ==> rem(x, s)[i] in s
ensures forall i :: 0 <= i < |s| && s[i] != x ==> s[i] in rem(x, s)
{
if |s| == 0 then []
else if s[0] == x then rem(x, s[1..])
else [s[0]] + rem(x, s[1..])
}
// The next three classes have a minimal class definition,
// for simplicity
class Address
{
constructor () {}
}
class Date
{
constructor () {}
}
class MessageId
{
constructor () {}
}
//==========================================================
// Message
//==========================================================
class Message
{
var id: MessageId
var content: string
var date: Date
var sender: Address
var recipients: seq<Address>
constructor (s: Address)
ensures fresh(id)
ensures fresh(date)
ensures content == ""
ensures sender == s
ensures recipients == []
{
id := new MessageId();
date := new Date();
this.content := "";
this.sender := s;
this.recipients := [];
}
method setContent(c: string)
modifies this
ensures content == c
{
this.content := c;
}
method setDate(d: Date)
modifies this
ensures date == d
{
this.date := d;
}
method addRecipient(p: nat, r: Address)
modifies this
requires p < |recipients|
ensures |recipients| == |old(recipients)| + 1
ensures recipients[p] == r
ensures forall i :: 0 <= i < p ==> recipients[i] == old(recipients[i])
ensures forall i :: p < i < |recipients| ==> recipients[i] == old(recipients[i-1])
{
this.recipients := this.recipients[..p] + [r] + this.recipients[p..];
}
}
//==========================================================
// Mailbox
//==========================================================
// Each Mailbox has a name, which is a string. Its main content is a set of messages.
class Mailbox {
var messages: set<Message>
var name: string
// Creates an empty mailbox with name n
constructor (n: string)
ensures name == n
ensures messages == {}
{
name := n;
messages := {};
}
// Adds message m to the mailbox
method add(m: Message)
modifies this
ensures m in messages
ensures messages == old(messages) + {m}
{
messages := { m } + messages;
}
// Removes message m from mailbox. m must not be in the mailbox.
method remove(m: Message)
modifies this
requires m in messages
ensures m !in messages
ensures messages == old(messages) - {m}
{
messages := messages - { m };
}
// Empties the mailbox messages
method empty()
modifies this
ensures messages == {}
{
messages := {};
}
}
//==========================================================
// MailApp
//==========================================================
class MailApp {
// abstract field for user defined boxes
ghost var userboxes: set<Mailbox>
// the inbox, drafts, trash and sent are both abstract and concrete
var inbox: Mailbox
var drafts: Mailbox
var trash: Mailbox
var sent: Mailbox
// userboxList implements userboxes
var userboxList: seq<Mailbox>
// Class invariant
ghost predicate Valid()
reads this
{
//----------------------------------------------------------
// Abstract state invariants
//----------------------------------------------------------
// all predefined mailboxes (inbox, ..., sent) are distinct
inbox != drafts &&
inbox != trash &&
inbox != sent &&
drafts != trash &&
drafts != sent &&
// none of the predefined mailboxes are in the set of user-defined mailboxes
inbox !in userboxList &&
drafts !in userboxList &&
trash !in userboxList &&
sent !in userboxList &&
//----------------------------------------------------------
// Abstract-to-concrete state invariants
//----------------------------------------------------------
// userboxes is the set of mailboxes in userboxList
forall i :: 0 <= i < |userboxList| ==> userboxList[i] in userboxes
}
constructor ()
{
inbox := new Mailbox("Inbox");
drafts := new Mailbox("Drafts");
trash := new Mailbox("Trash");
sent := new Mailbox("Sent");
userboxList := [];
}
// Deletes user-defined mailbox mb
method deleteMailbox(mb: Mailbox)
requires Valid()
requires mb in userboxList
// ensures mb !in userboxList
{
// userboxList := rem(mb, userboxList);
}
// Adds a new mailbox with name n to set of user-defined mailboxes
// provided that no user-defined mailbox has name n already
method newMailbox(n: string)
modifies this
requires Valid()
requires !exists mb | mb in userboxList :: mb.name == n
ensures exists mb | mb in userboxList :: mb.name == n
{
var mb := new Mailbox(n);
userboxList := [mb] + userboxList;
}
// Adds a new message with sender s to the drafts mailbox
method newMessage(s: Address)
modifies this.drafts
requires Valid()
ensures exists m | m in drafts.messages :: m.sender == s
{
var m := new Message(s);
drafts.add(m);
}
// Moves message m from mailbox mb1 to a different mailbox mb2
method moveMessage (m: Message, mb1: Mailbox, mb2: Mailbox)
modifies mb1, mb2
requires Valid()
requires m in mb1.messages
requires m !in mb2.messages
ensures m !in mb1.messages
ensures m in mb2.messages
{
mb1.remove(m);
mb2.add(m);
}
// Moves message m from mailbox mb to the trash mailbox provided
// that mb is not the trash mailbox
method deleteMessage (m: Message, mb: Mailbox)
modifies m, mb, this.trash
requires Valid()
requires m in mb.messages
requires m !in trash.messages
{
moveMessage(m, mb, trash);
}
// Moves message m from the drafts mailbox to the sent mailbox
method sendMessage(m: Message)
modifies this.drafts, this.sent
requires Valid()
requires m in drafts.messages
requires m !in sent.messages
{
moveMessage(m, drafts, sent);
}
// Empties the trash mailbox
method emptyTrash()
modifies this.trash
requires Valid()
ensures trash.messages == {}
{
trash.empty();
}
}
| /*
===============================================
DCC831 Formal Methods
2023.2
Mini Project 2 - Part A
Your name: Guilherme de Oliveira Silva
===============================================
*/
function rem<T(==)>(x: T, s: seq<T>): seq<T>
ensures x !in rem(x, s)
ensures forall i :: 0 <= i < |rem(x, s)| ==> rem(x, s)[i] in s
ensures forall i :: 0 <= i < |s| && s[i] != x ==> s[i] in rem(x, s)
{
if |s| == 0 then []
else if s[0] == x then rem(x, s[1..])
else [s[0]] + rem(x, s[1..])
}
// The next three classes have a minimal class definition,
// for simplicity
class Address
{
constructor () {}
}
class Date
{
constructor () {}
}
class MessageId
{
constructor () {}
}
//==========================================================
// Message
//==========================================================
class Message
{
var id: MessageId
var content: string
var date: Date
var sender: Address
var recipients: seq<Address>
constructor (s: Address)
ensures fresh(id)
ensures fresh(date)
ensures content == ""
ensures sender == s
ensures recipients == []
{
id := new MessageId();
date := new Date();
this.content := "";
this.sender := s;
this.recipients := [];
}
method setContent(c: string)
modifies this
ensures content == c
{
this.content := c;
}
method setDate(d: Date)
modifies this
ensures date == d
{
this.date := d;
}
method addRecipient(p: nat, r: Address)
modifies this
requires p < |recipients|
ensures |recipients| == |old(recipients)| + 1
ensures recipients[p] == r
ensures forall i :: 0 <= i < p ==> recipients[i] == old(recipients[i])
ensures forall i :: p < i < |recipients| ==> recipients[i] == old(recipients[i-1])
{
this.recipients := this.recipients[..p] + [r] + this.recipients[p..];
}
}
//==========================================================
// Mailbox
//==========================================================
// Each Mailbox has a name, which is a string. Its main content is a set of messages.
class Mailbox {
var messages: set<Message>
var name: string
// Creates an empty mailbox with name n
constructor (n: string)
ensures name == n
ensures messages == {}
{
name := n;
messages := {};
}
// Adds message m to the mailbox
method add(m: Message)
modifies this
ensures m in messages
ensures messages == old(messages) + {m}
{
messages := { m } + messages;
}
// Removes message m from mailbox. m must not be in the mailbox.
method remove(m: Message)
modifies this
requires m in messages
ensures m !in messages
ensures messages == old(messages) - {m}
{
messages := messages - { m };
}
// Empties the mailbox messages
method empty()
modifies this
ensures messages == {}
{
messages := {};
}
}
//==========================================================
// MailApp
//==========================================================
class MailApp {
// abstract field for user defined boxes
ghost var userboxes: set<Mailbox>
// the inbox, drafts, trash and sent are both abstract and concrete
var inbox: Mailbox
var drafts: Mailbox
var trash: Mailbox
var sent: Mailbox
// userboxList implements userboxes
var userboxList: seq<Mailbox>
// Class invariant
ghost predicate Valid()
reads this
{
//----------------------------------------------------------
// Abstract state invariants
//----------------------------------------------------------
// all predefined mailboxes (inbox, ..., sent) are distinct
inbox != drafts &&
inbox != trash &&
inbox != sent &&
drafts != trash &&
drafts != sent &&
// none of the predefined mailboxes are in the set of user-defined mailboxes
inbox !in userboxList &&
drafts !in userboxList &&
trash !in userboxList &&
sent !in userboxList &&
//----------------------------------------------------------
// Abstract-to-concrete state invariants
//----------------------------------------------------------
// userboxes is the set of mailboxes in userboxList
forall i :: 0 <= i < |userboxList| ==> userboxList[i] in userboxes
}
constructor ()
{
inbox := new Mailbox("Inbox");
drafts := new Mailbox("Drafts");
trash := new Mailbox("Trash");
sent := new Mailbox("Sent");
userboxList := [];
}
// Deletes user-defined mailbox mb
method deleteMailbox(mb: Mailbox)
requires Valid()
requires mb in userboxList
// ensures mb !in userboxList
{
// userboxList := rem(mb, userboxList);
}
// Adds a new mailbox with name n to set of user-defined mailboxes
// provided that no user-defined mailbox has name n already
method newMailbox(n: string)
modifies this
requires Valid()
requires !exists mb | mb in userboxList :: mb.name == n
ensures exists mb | mb in userboxList :: mb.name == n
{
var mb := new Mailbox(n);
userboxList := [mb] + userboxList;
}
// Adds a new message with sender s to the drafts mailbox
method newMessage(s: Address)
modifies this.drafts
requires Valid()
ensures exists m | m in drafts.messages :: m.sender == s
{
var m := new Message(s);
drafts.add(m);
}
// Moves message m from mailbox mb1 to a different mailbox mb2
method moveMessage (m: Message, mb1: Mailbox, mb2: Mailbox)
modifies mb1, mb2
requires Valid()
requires m in mb1.messages
requires m !in mb2.messages
ensures m !in mb1.messages
ensures m in mb2.messages
{
mb1.remove(m);
mb2.add(m);
}
// Moves message m from mailbox mb to the trash mailbox provided
// that mb is not the trash mailbox
method deleteMessage (m: Message, mb: Mailbox)
modifies m, mb, this.trash
requires Valid()
requires m in mb.messages
requires m !in trash.messages
{
moveMessage(m, mb, trash);
}
// Moves message m from the drafts mailbox to the sent mailbox
method sendMessage(m: Message)
modifies this.drafts, this.sent
requires Valid()
requires m in drafts.messages
requires m !in sent.messages
{
moveMessage(m, drafts, sent);
}
// Empties the trash mailbox
method emptyTrash()
modifies this.trash
requires Valid()
ensures trash.messages == {}
{
trash.empty();
}
}
|
487 | dafny-programs_tmp_tmpcwodh6qh_src_expt.dfy | 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)
| 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)
|
488 | dafny-programs_tmp_tmpcwodh6qh_src_factorial.dfy | 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;
}
}
| 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;
}
}
|
489 | dafny-programs_tmp_tmpcwodh6qh_src_max.dfy | method Max(a: int, b: int) returns (c: int)
ensures a >= b ==> c == a
ensures b >= a ==> c == b
{
if a > b {
return a;
} else {
return b;
}
}
method MaxTest() {
var low := 1;
var high := 10;
var v := Max(low, high);
assert v == high;
}
function max(a: int, b: int): int
{
if a > b then a else b
}
method maxTest() {
assert max(1, 10) == 10;
}
| method Max(a: int, b: int) returns (c: int)
ensures a >= b ==> c == a
ensures b >= a ==> c == b
{
if a > b {
return a;
} else {
return b;
}
}
method MaxTest() {
var low := 1;
var high := 10;
var v := Max(low, high);
}
function max(a: int, b: int): int
{
if a > b then a else b
}
method maxTest() {
}
|
490 | dafny-programs_tmp_tmpcwodh6qh_src_ticketsystem.dfy | // Code taken from the following paper: http://leino.science/papers/krml260.pdf
// Each philosopher's pseudocode:
// repeat forever {
// Thinking:
// t: Ticket = ticket, ticket + 1 // request ticket to enter hungry state
// Hungry:
// //...
// wait until serving = t; // Enter
// Eating:
// //...
// serving := serving + 1; // Leaving
// }
// control state values; thinking, hungry, eating
// introduce state for each process: use map from processes to values
type Process(==) // {type comes equipped with ability to compare its values with equality}
datatype CState = Thinking | Hungry | Eating
// provides mutual exclusion
class TicketSystem {
var ticket: int
var serving: int
const P: set<Process>
var cs: map<Process, CState> // cannot use state variable P as domain for maps => use Process => every conceivable process
var t: map<Process, int> // ticket number for each philosopher
// how to know some process p is in domain of map: introduce function which tells whether condition holds or not
predicate Valid() // function which describes system invariant
reads this // may depend on values in the class
{
P <= cs.Keys && P <= t.Keys && serving <= ticket && // ticket may be greater than serving but not the other way around
(forall p :: p in P && cs[p] != Thinking ==> serving <= t[p] < ticket) && // any current ticket number is in the range of serving to ticket
(forall p,q ::
p in P && q in P && p != q && cs[p] != Thinking && cs[q] != Thinking ==> t[p] != t[q] // some other process may have a value equal to 'serving'
) &&
(forall p :: p in P && cs[p] == Eating ==> t[p] == serving) // if eating, the current ticket number must be the one being served
}
constructor (processes: set<Process>)
ensures Valid() // postcondition
{
P := processes;
ticket, serving := 0, 0;
cs := map p | p in processes :: Thinking; // set initial state of every process to Thinking
t := map p | p in processes :: 0;
}
// atomic events to formalize for each process: request, enter, leave
// model each atomic event by a method
// atomicity: read or write just once in body
// method AtomicStep(p: Process)
// requires Valid() && p in P && cs[p] == Thinking // Request(p) is only enabled when p is thinking
// modifies this
// ensures Valid()
method Request(p: Process)
requires Valid() && p in P && cs[p] == Thinking
modifies this
ensures Valid()
{
t, ticket := t[p := ticket], ticket + 1; // map update p to ticket, update ticket
cs := cs[p := Hungry]; // map update p to Hungry state
}
method Enter(p: Process)
requires Valid() && p in P && cs[p] == Hungry
modifies this
ensures Valid()
{
if t[p] == serving {
cs := cs[p := Eating]; // map update p to eating state
}
}
method Leave(p: Process)
requires Valid() && p in P && cs[p] == Eating
modifies this
ensures Valid()
{
assert t[p] == serving;
serving := serving + 1;
cs := cs[p := Thinking];
}
// correctness: no two process are in eating state at same time
// prove that invariant implies condition
lemma MutualExclusion(p: Process, q: Process)
requires Valid() && p in P && q in P // if system is in valid state and both p, q are processes
requires cs[p] == Eating && cs[q] == Eating // both p, q are in Eating state
ensures p == q // p and q are the same process
}
| // Code taken from the following paper: http://leino.science/papers/krml260.pdf
// Each philosopher's pseudocode:
// repeat forever {
// Thinking:
// t: Ticket = ticket, ticket + 1 // request ticket to enter hungry state
// Hungry:
// //...
// wait until serving = t; // Enter
// Eating:
// //...
// serving := serving + 1; // Leaving
// }
// control state values; thinking, hungry, eating
// introduce state for each process: use map from processes to values
type Process(==) // {type comes equipped with ability to compare its values with equality}
datatype CState = Thinking | Hungry | Eating
// provides mutual exclusion
class TicketSystem {
var ticket: int
var serving: int
const P: set<Process>
var cs: map<Process, CState> // cannot use state variable P as domain for maps => use Process => every conceivable process
var t: map<Process, int> // ticket number for each philosopher
// how to know some process p is in domain of map: introduce function which tells whether condition holds or not
predicate Valid() // function which describes system invariant
reads this // may depend on values in the class
{
P <= cs.Keys && P <= t.Keys && serving <= ticket && // ticket may be greater than serving but not the other way around
(forall p :: p in P && cs[p] != Thinking ==> serving <= t[p] < ticket) && // any current ticket number is in the range of serving to ticket
(forall p,q ::
p in P && q in P && p != q && cs[p] != Thinking && cs[q] != Thinking ==> t[p] != t[q] // some other process may have a value equal to 'serving'
) &&
(forall p :: p in P && cs[p] == Eating ==> t[p] == serving) // if eating, the current ticket number must be the one being served
}
constructor (processes: set<Process>)
ensures Valid() // postcondition
{
P := processes;
ticket, serving := 0, 0;
cs := map p | p in processes :: Thinking; // set initial state of every process to Thinking
t := map p | p in processes :: 0;
}
// atomic events to formalize for each process: request, enter, leave
// model each atomic event by a method
// atomicity: read or write just once in body
// method AtomicStep(p: Process)
// requires Valid() && p in P && cs[p] == Thinking // Request(p) is only enabled when p is thinking
// modifies this
// ensures Valid()
method Request(p: Process)
requires Valid() && p in P && cs[p] == Thinking
modifies this
ensures Valid()
{
t, ticket := t[p := ticket], ticket + 1; // map update p to ticket, update ticket
cs := cs[p := Hungry]; // map update p to Hungry state
}
method Enter(p: Process)
requires Valid() && p in P && cs[p] == Hungry
modifies this
ensures Valid()
{
if t[p] == serving {
cs := cs[p := Eating]; // map update p to eating state
}
}
method Leave(p: Process)
requires Valid() && p in P && cs[p] == Eating
modifies this
ensures Valid()
{
serving := serving + 1;
cs := cs[p := Thinking];
}
// correctness: no two process are in eating state at same time
// prove that invariant implies condition
lemma MutualExclusion(p: Process, q: Process)
requires Valid() && p in P && q in P // if system is in valid state and both p, q are processes
requires cs[p] == Eating && cs[q] == Eating // both p, q are in Eating state
ensures p == q // p and q are the same process
}
|
491 | dafny-rope_tmp_tmpl4v_njmy_Rope.dfy | 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
| 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
|
492 | dafny-sandbox_tmp_tmp3tu2bu8a_Stlc.dfy | // 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
| // 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
|
493 | dafny-synthesis_task_id_101.dfy | method KthElement(arr: array<int>, k: int) returns (result: int)
requires 1 <= k <= arr.Length
ensures result == arr[k - 1]
{
result := arr[k - 1];
} | method KthElement(arr: array<int>, k: int) returns (result: int)
requires 1 <= k <= arr.Length
ensures result == arr[k - 1]
{
result := arr[k - 1];
} |
494 | dafny-synthesis_task_id_105.dfy | 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;
}
}
} | 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;
}
}
} |
495 | dafny-synthesis_task_id_106.dfy | 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]];
}
} | 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]];
}
} |
496 | dafny-synthesis_task_id_113.dfy | 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;
}
}
}
} | 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;
}
}
}
} |
497 | dafny-synthesis_task_id_126.dfy | 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;
}
} | 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;
}
} |
498 | dafny-synthesis_task_id_127.dfy | method Multiply(a: int, b: int) returns (result: int)
ensures result == a * b
{
result := a * b;
} | method Multiply(a: int, b: int) returns (result: int)
ensures result == a * b
{
result := a * b;
} |
499 | dafny-synthesis_task_id_133.dfy | 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];
}
}
} | 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];
}
}
} |