[ { "test_ID": "000", "test_file": "630-dafny_tmp_tmpz2kokaiq_Solution.dfy", "ground_truth": "\nfunction sorted(a: array) : bool\n reads a\n{\n forall i,j : int :: 0 <= i < j < a.Length ==> a[i] <= a[j]\n}\n\nmethod BinarySearch(a: array, x: int) returns (index: int)\n requires sorted(a)\n ensures 0 <= index < a.Length ==> a[index] == x\n ensures index == -1 ==> forall i : int :: 0 <= i < a.Length ==> a[i] != x\n{\n var low := 0;\n var high := a.Length - 1;\n var mid := 0;\n \n while (low <= high) \n invariant 0 <= low <= high + 1 <= a.Length\n invariant x !in a[..low] && x !in a[high + 1..]\n {\n mid := (high + low) / 2;\n if a[mid] < x {\n low := mid + 1;\n }\n else if a[mid] > x {\n high := mid - 1;\n }\n else {\n return mid;\n }\n }\n return -1;\n}\n", "hints_removed": "\nfunction sorted(a: array) : bool\n reads a\n{\n forall i,j : int :: 0 <= i < j < a.Length ==> a[i] <= a[j]\n}\n\nmethod BinarySearch(a: array, x: int) returns (index: int)\n requires sorted(a)\n ensures 0 <= index < a.Length ==> a[index] == x\n ensures index == -1 ==> forall i : int :: 0 <= i < a.Length ==> a[i] != x\n{\n var low := 0;\n var high := a.Length - 1;\n var mid := 0;\n \n while (low <= high) \n {\n mid := (high + low) / 2;\n if a[mid] < x {\n low := mid + 1;\n }\n else if a[mid] > x {\n high := mid - 1;\n }\n else {\n return mid;\n }\n }\n return -1;\n}\n" }, { "test_ID": "001", "test_file": "703FinalProject_tmp_tmpr_10rn4z_DP-GD.dfy", "ground_truth": "method DPGD_GradientPerturbation (size:int, learning_rate:real, noise_scale:real, gradient_norm_bound:real, iterations:int) returns (Para:real, PrivacyLost:real)\n requires iterations>=0\n requires size>=0\n requires noise_scale >= 1.0\n requires -1.0 <= gradient_norm_bound <= 1.0\n{\n var thetha:array := new real[iterations+1];\n thetha[0] := *;\n var alpha:real := 0.0;\n var tau:real := *;\n assume(tau>=0.0);\n var t :int := 0;\n var constant:real := (size as real) * tau;\n while (t < iterations)\n invariant t <= iterations\n invariant alpha == t as real * constant\n {\n var i :int := 0;\n var beta:real := 0.0;\n var summation_gradient:real := 0.0;\n while (i< size)\n invariant i <= size\n invariant beta == i as real * tau\n {\n var gradient:real := *;\n // Note: We do not need to clip the value of the gradient.\n // Instead, we clip the sensitivity of the gradient by the gradient_norm_bound provided by the user\n var eta:real := *;\n beta := beta + tau;\n var eta_hat:real := - gradient_norm_bound;\n assert (gradient_norm_bound + eta_hat == 0.0);\n summation_gradient := summation_gradient + gradient + eta;\n i := i + 1;\n }\n alpha := alpha + beta;\n thetha[t+1] := thetha[t] - learning_rate*summation_gradient;\n t := t+1;\n }\n assert(t==iterations);\n assert(alpha == iterations as real * constant);\n Para := thetha[iterations];\n PrivacyLost := alpha;\n}\n\n\n", "hints_removed": "method DPGD_GradientPerturbation (size:int, learning_rate:real, noise_scale:real, gradient_norm_bound:real, iterations:int) returns (Para:real, PrivacyLost:real)\n requires iterations>=0\n requires size>=0\n requires noise_scale >= 1.0\n requires -1.0 <= gradient_norm_bound <= 1.0\n{\n var thetha:array := new real[iterations+1];\n thetha[0] := *;\n var alpha:real := 0.0;\n var tau:real := *;\n assume(tau>=0.0);\n var t :int := 0;\n var constant:real := (size as real) * tau;\n while (t < iterations)\n {\n var i :int := 0;\n var beta:real := 0.0;\n var summation_gradient:real := 0.0;\n while (i< size)\n {\n var gradient:real := *;\n // Note: We do not need to clip the value of the gradient.\n // Instead, we clip the sensitivity of the gradient by the gradient_norm_bound provided by the user\n var eta:real := *;\n beta := beta + tau;\n var eta_hat:real := - gradient_norm_bound;\n summation_gradient := summation_gradient + gradient + eta;\n i := i + 1;\n }\n alpha := alpha + beta;\n thetha[t+1] := thetha[t] - learning_rate*summation_gradient;\n t := t+1;\n }\n Para := thetha[iterations];\n PrivacyLost := alpha;\n}\n\n\n" }, { "test_ID": "002", "test_file": "703FinalProject_tmp_tmpr_10rn4z_gaussian.dfy", "ground_truth": "// VERIFY USING DAFNY:\n// /Applications/dafny/dafny /Users/apple/GaussianDP/Dafny/gaussian.dfy\nmethod gaussian (size:int, q: array, q_hat: array) returns (out: array)\nrequires q_hat.Length==size\nrequires q.Length==size\nrequires size > 0\nrequires arraySquaredSum(q_hat[..]) <= 1.0\n{\n var i : int := 0;\n var alpha : real := arraySquaredSum(q_hat[..1]);\n var eta: real := 0.0;\n var eta_hat: real := 0.0;\n out := new real[size];\n while (i alpha <= arraySquaredSum(q_hat[..i])\n invariant i<=size\n {\n eta := *;\n eta_hat := - q_hat[i];\n alpha := arraySquaredSum(q_hat[..i+1]);\n assert (q_hat[i] + eta_hat ==0.0);\n out[i] := q[i] + eta;\n i := i+1;\n }\n assert i==size;\n assert alpha <= arraySquaredSum(q_hat[..size]);\n assert q_hat[..size] == q_hat[..];\n assert alpha <= arraySquaredSum(q_hat[..]);\n assert alpha <= 1.0;\n}\n\n\nfunction arraySquaredSum(a: seq): real\nrequires |a| > 0\n{\n if |a| == 1 then \n a[0]*a[0]\n else \n (a[0]*a[0]) + arraySquaredSum(a[1..])\n}\n\n", "hints_removed": "// VERIFY USING DAFNY:\n// /Applications/dafny/dafny /Users/apple/GaussianDP/Dafny/gaussian.dfy\nmethod gaussian (size:int, q: array, q_hat: array) returns (out: array)\nrequires q_hat.Length==size\nrequires q.Length==size\nrequires size > 0\nrequires arraySquaredSum(q_hat[..]) <= 1.0\n{\n var i : int := 0;\n var alpha : real := arraySquaredSum(q_hat[..1]);\n var eta: real := 0.0;\n var eta_hat: real := 0.0;\n out := new real[size];\n while (i ): real\nrequires |a| > 0\n{\n if |a| == 1 then \n a[0]*a[0]\n else \n (a[0]*a[0]) + arraySquaredSum(a[1..])\n}\n\n" }, { "test_ID": "003", "test_file": "AssertivePrograming_tmp_tmpwf43uz0e_DivMode_Unary.dfy", "ground_truth": "// Noa Leron 207131871\n// Tsuri Farhana 315016907\n\n\n// definitions borrowed from Rustan Leino's Program Proofs Chapter 7\n// (https://program-proofs.com/code.html example code in Dafny; source file 7-Unary.dfy)\ndatatype Unary = Zero | Suc(pred: Unary)\n\nghost function UnaryToNat(x: Unary): nat {\n match x\n case Zero => 0\n case Suc(x') => 1 + UnaryToNat(x')\n}\n\nghost function NatToUnary(n: nat): Unary {\n if n == 0 then Zero else Suc(NatToUnary(n-1))\n}\n\nlemma NatUnaryCorrespondence(n: nat, x: Unary)\n ensures UnaryToNat(NatToUnary(n)) == n\n ensures NatToUnary(UnaryToNat(x)) == x\n{\n}\n\npredicate Less(x: Unary, y: Unary) {\n y != Zero && (x.Suc? ==> Less(x.pred, y.pred))\n}\n\npredicate LessAlt(x: Unary, y: Unary) {\n y != Zero && (x == Zero || Less(x.pred, y.pred))\n}\n\nlemma LessSame(x: Unary, y: Unary)\n ensures Less(x, y) == LessAlt(x, y)\n{\n}\n\nlemma LessCorrect(x: Unary, y: Unary)\n ensures Less(x, y) <==> UnaryToNat(x) < UnaryToNat(y)\n{\n}\n\nlemma LessTransitive(x: Unary, y: Unary, z: Unary)\n requires Less(x, y) && Less(y, z)\n ensures Less(x, z)\n{\n}\n\nfunction Add(x: Unary, y: Unary): Unary {\n match y\n case Zero => x\n case Suc(y') => Suc(Add(x, y'))\n}\n\nlemma {:induction false} SucAdd(x: Unary, y: Unary)\n ensures Suc(Add(x, y)) == Add(Suc(x), y)\n{\n match y\n case Zero =>\n case Suc(y') =>\n calc {\n Suc(Add(x, Suc(y')));\n == // def. Add\n Suc(Suc(Add(x, y')));\n == { SucAdd(x, y'); }\n Suc(Add(Suc(x), y'));\n == // def. Add\n Add(Suc(x), Suc(y'));\n }\n}\n\nlemma {:induction false} AddZero(x: Unary)\n ensures Add(Zero, x) == x\n{\n match x\n case Zero =>\n case Suc(x') =>\n calc {\n Add(Zero, Suc(x'));\n == // def. Add\n Suc(Add(Zero, x'));\n == { AddZero(x'); }\n Suc(x');\n }\n}\n\nfunction Sub(x: Unary, y: Unary): Unary\n requires !Less(x, y)\n{\n match y\n case Zero => x\n case Suc(y') => Sub(x.pred, y')\n}\n\nfunction Mul(x: Unary, y: Unary): Unary {\n match x\n case Zero => Zero\n case Suc(x') => Add(Mul(x', y), y)\n}\n\nlemma SubStructurallySmaller(x: Unary, y: Unary)\n requires !Less(x, y) && y != Zero\n ensures Sub(x, y) < x\n{\n}\n\nlemma AddSub(x: Unary, y: Unary)\n requires !Less(x, y)\n ensures Add(Sub(x, y), y) == x\n{\n}\n\n/*\nGoal: implement correcly and clearly, using iterative code (no recursion), documenting the proof obligations\n\tas we've learned, with assertions and a lemma for each proof goal\n\n- DO NOT modify the specification or any of the definitions given in this file\n- Not all definitions above are relevant, some are simply included as examples\n- Feel free to use existing non-ghost functions/predicates in your code, and existing lemmas (for the proof) in your annotations\n- New functions/predicates may be added ONLY as ghost\n- If it helps you in any way, a recursive implementation + proof can be found in the book and the downloadable source file\n [https://program-proofs.com/code.html example code in Dafny, source file 7-Unary.dfy]\n*/\n\nmethod{:verify false} IterativeDivMod'(x: Unary, y: Unary) returns (d: Unary, m: Unary)\n requires y != Zero\n ensures Add(Mul(d, y), m) == x && Less(m, y)\n{\n if (Less(x, y)) {\n d := Zero;\n m := x;\n }\n else{\n var x0: Unary := x;\n d := Zero;\n while (!Less(x0, y))\n invariant Add(Mul(d, y), x0) == x\n decreases x0\n {\n d := Suc(d);\n x0 := Sub(x0, y);\n }\n m := x0;\n }\n}\n\nmethod IterativeDivMod(x: Unary, y: Unary) returns (d: Unary, m: Unary)\n requires y != Zero\n ensures Add(Mul(d, y), m) == x && Less(m, y)\n{\n if (Less(x, y)) {\n assert Less(x, y);\n AddZero(x);\n assert Add(Zero, x) == x;\n assert Mul(Zero, y) == Zero;\n assert Add(Mul(Zero, y), x) == x;\n d := Zero;\n m := x;\n assert Add(Mul(d, y), m) == m;\n assert Less(m, y);\n assert Add(Mul(d, y), m) == x && Less(m, y);\n }\n else{\n assert !Less(x, y);\n assert y != Zero;\n var x0: Unary := x;\n assert Mul(Zero, y) == Zero;\n d := Zero;\n assert Mul(d, y) == Zero;\n AddZero(x);\n assert Add(Zero, x) == x;\n assert Add(Mul(d, y), x) == x;\n assert Add(Mul(d, y), x0) == x;\n\n while (!Less(x0, y))\n invariant Add(Mul(d, y), x0) == x\n decreases x0\n {\n assert Add(Mul(d, y), x0) == x;\n assert !Less(x0, y);\n assert y != Zero;\n AddMulSucSubEqAddMul(d, y , x0);\n assert Add(Mul(Suc(d), y), Sub(x0, y)) == Add(Mul(d, y), x0);\n assert Add(Mul(Suc(d), y), Sub(x0, y)) == x;\n d := Suc(d);\n assert !Less(x0, y) && y != Zero;\n SubStructurallySmaller(x0, y);\n assert Sub(x0, y) < x0; // decreases\n x0 := Sub(x0, y);\n assert Add(Mul(d, y), x0) == x;\n }\n assert Add(Mul(d, y), x0) == x;\n m := x0;\n assert Add(Mul(d, y), m) == x;\n }\n assert Add(Mul(d, y), m) == x;\n}\n\nlemma AddMulEqMulSuc(a: Unary, b: Unary)\n ensures Mul(Suc(a), b) == Add(Mul(a, b), b)\n{\n calc{\n Mul(Suc(a), b);\n == // def. Mul\n Add(Mul(a, b), b);\n }\n}\n\nlemma AddMulSucSubEqAddMul(d: Unary, y: Unary, x0: Unary)\n requires !Less(x0, y)\n requires y != Zero\n ensures Add(Mul(Suc(d), y), Sub(x0, y)) == Add(Mul(d, y), x0)\n{\n calc{\n Add(Mul(Suc(d), y), Sub(x0, y));\n == {AddMulEqMulSuc(d, y);\n assert Mul(Suc(d), y) == Add(Mul(d, y), y);}\n Add(Add(Mul(d, y), y), Sub(x0, y));\n == {AddTransitive(Mul(d, y), y, Sub(x0, y));\n assert Add(Mul(d, y), Add(y, Sub(x0, y))) == Add(Add(Mul(d, y), y), Sub(x0, y));}\n Add(Mul(d, y), Add(y, Sub(x0, y)));\n == {AddCommutative(Sub(x0, y), y);\n assert Add(Sub(x0, y), y) == Add(y, Sub(x0, y));}\n Add(Mul(d, y), Add(Sub(x0, y), y));\n == {assert !Less(x0, y);\n AddSub(x0, y);\n assert Add(Sub(x0, y), y) == x0;}\n Add(Mul(d, y), x0);\n }\n}\n\nlemma AddTransitive(a: Unary, b: Unary, c: Unary)\n ensures Add(a, Add(b, c)) == Add(Add(a, b), c)\n{//These assertions are only for documanting the proof obligations\n match c \n case Zero =>\n calc{\n Add(a, Add(b, c));\n == \n Add(a, Add(b, Zero));\n == // def. Add\n Add(a, b);\n == // def. Add\n Add(Add(a,b), Zero);\n == \n Add(Add(a,b), c);\n }\n case Suc(c') =>\n match b\n case Zero =>\n calc{\n Add(a, Add(b, c));\n == \n Add(a, Add(Zero, Suc(c')));\n == {AddZero(Suc(c'));\n assert Add(Zero, Suc(c')) == Suc(c');}\n Add(a, Suc(c'));\n == // def. Add\n Add(Add(a, Zero), Suc(c'));\n ==\n Add(Add(a, b), Suc(c'));\n ==\n Add(Add(a,b), c);\n }\n case Suc(b') =>\n match a\n case Zero =>\n calc{\n Add(a, Add(b, c));\n ==\n Add(Zero, Add(Suc(b'), Suc(c')));\n == {AddZero(Add(Suc(b'), Suc(c')));\n assert Add(Zero, Add(Suc(b'), Suc(c'))) == Add(Suc(b'), Suc(c'));}\n Add(Suc(b'), Suc(c'));\n == {AddZero(Suc(b'));\n assert Add(Zero , Suc(b')) == Suc(b');}\n Add(Add(Zero, Suc(b')), Suc(c'));\n ==\n Add(Add(a, b), c);\n }\n case Suc(a') =>\n calc{\n Add(a, Add(b, c));\n ==\n Add(Suc(a'), Add(Suc(b'), Suc(c')));\n == // def. Add\n Add(Suc(a'), Suc(Add(Suc(b'), c')));\n == // def. Add\n Suc(Add(Suc(a'), Add(Suc(b'), c')));\n == {SucAdd(a', Add(Suc(b'), c'));\n assert Suc(Add(a', Add(Suc(b'), c'))) == Add(Suc(a'), Add(Suc(b'), c'));}\n Suc(Suc(Add(a', Add(Suc(b'), c'))));\n == {SucAdd(b', c');\n assert Suc(Add(b', c')) == Add(Suc(b'), c');}\n Suc(Suc(Add(a', Suc(Add(b', c')))));\n == // def. Add\n Suc(Suc(Suc(Add(a', Add(b', c')))));\n == {AddTransitive(a', b', c');\n assert Add(a', Add(b',c')) == Add(Add(a',b'),c');}\n Suc(Suc(Suc(Add(Add(a',b'), c'))));\n == // def. Add\n Suc(Suc(Add(Add(a', b'), Suc(c'))));\n == {SucAdd(Add(a', b'), Suc(c'));\n assert Suc(Add(Add(a', b'), Suc(c'))) == Add(Suc(Add(a', b')), Suc(c'));}\n Suc(Add(Suc(Add(a', b')), Suc(c')));\n == {SucAdd(a', b');\n assert Suc(Add(a', b')) == Add(Suc(a'), b');}\n Suc(Add(Add(Suc(a'), b'), Suc(c')));\n == {SucAdd(Add(Suc(a'), b'), Suc(c'));\n assert Suc(Add(Add(Suc(a'), b'), Suc(c'))) == Add(Suc(Add(Suc(a'), b')), Suc(c'));}\n Add(Suc(Add(Suc(a'), b')), Suc(c'));\n == // def. Add\n Add(Add(Suc(a'), Suc(b')), Suc(c'));\n ==\n Add(Add(a,b), c);\n }\n\n}\n\nlemma AddCommutative(a: Unary, b: Unary)\n ensures Add(a, b) == Add(b, a)\n{\n match b\n case Zero => \n calc{\n Add(a, b);\n ==\n Add(a, Zero);\n == // def. Add\n a;\n == {AddZero(a);\n assert Add(Zero, a) == a;}\n Add(Zero, a);\n ==\n Add(b, a);\n }\n case Suc(b') =>\n calc{\n Add(a, b);\n ==\n Add(a, Suc(b'));\n == // def. Add\n Suc(Add(a, b'));\n == {AddCommutative(a, b');\n assert Add(a, b') == Add(b', a);}\n Suc(Add(b', a));\n == {SucAdd(b', a);\n assert Suc(Add(b',a)) == Add(Suc(b'),a);}\n Add(Suc(b'), a);\n ==\n Add(b, a);\n }\n}\n\n\n\nmethod Main() {\n var U3 := Suc(Suc(Suc(Zero)));\n assert UnaryToNat(U3) == 3;\n var U7 := Suc(Suc(Suc(Suc(U3))));\n assert UnaryToNat(U7) == 7;\n var d, m := IterativeDivMod(U7, U3);\n assert Add(Mul(d, U3), m) == U7 && Less(m, U3);\n print \"Just as 7 divided by 3 is 2 with a remainder of 1, IterativeDivMod(\", U7, \", \", U3, \") is \", d, \" with a remainder of \", m;\n}\n", "hints_removed": "// Noa Leron 207131871\n// Tsuri Farhana 315016907\n\n\n// definitions borrowed from Rustan Leino's Program Proofs Chapter 7\n// (https://program-proofs.com/code.html example code in Dafny; source file 7-Unary.dfy)\ndatatype Unary = Zero | Suc(pred: Unary)\n\nghost function UnaryToNat(x: Unary): nat {\n match x\n case Zero => 0\n case Suc(x') => 1 + UnaryToNat(x')\n}\n\nghost function NatToUnary(n: nat): Unary {\n if n == 0 then Zero else Suc(NatToUnary(n-1))\n}\n\nlemma NatUnaryCorrespondence(n: nat, x: Unary)\n ensures UnaryToNat(NatToUnary(n)) == n\n ensures NatToUnary(UnaryToNat(x)) == x\n{\n}\n\npredicate Less(x: Unary, y: Unary) {\n y != Zero && (x.Suc? ==> Less(x.pred, y.pred))\n}\n\npredicate LessAlt(x: Unary, y: Unary) {\n y != Zero && (x == Zero || Less(x.pred, y.pred))\n}\n\nlemma LessSame(x: Unary, y: Unary)\n ensures Less(x, y) == LessAlt(x, y)\n{\n}\n\nlemma LessCorrect(x: Unary, y: Unary)\n ensures Less(x, y) <==> UnaryToNat(x) < UnaryToNat(y)\n{\n}\n\nlemma LessTransitive(x: Unary, y: Unary, z: Unary)\n requires Less(x, y) && Less(y, z)\n ensures Less(x, z)\n{\n}\n\nfunction Add(x: Unary, y: Unary): Unary {\n match y\n case Zero => x\n case Suc(y') => Suc(Add(x, y'))\n}\n\nlemma {:induction false} SucAdd(x: Unary, y: Unary)\n ensures Suc(Add(x, y)) == Add(Suc(x), y)\n{\n match y\n case Zero =>\n case Suc(y') =>\n calc {\n Suc(Add(x, Suc(y')));\n == // def. Add\n Suc(Suc(Add(x, y')));\n == { SucAdd(x, y'); }\n Suc(Add(Suc(x), y'));\n == // def. Add\n Add(Suc(x), Suc(y'));\n }\n}\n\nlemma {:induction false} AddZero(x: Unary)\n ensures Add(Zero, x) == x\n{\n match x\n case Zero =>\n case Suc(x') =>\n calc {\n Add(Zero, Suc(x'));\n == // def. Add\n Suc(Add(Zero, x'));\n == { AddZero(x'); }\n Suc(x');\n }\n}\n\nfunction Sub(x: Unary, y: Unary): Unary\n requires !Less(x, y)\n{\n match y\n case Zero => x\n case Suc(y') => Sub(x.pred, y')\n}\n\nfunction Mul(x: Unary, y: Unary): Unary {\n match x\n case Zero => Zero\n case Suc(x') => Add(Mul(x', y), y)\n}\n\nlemma SubStructurallySmaller(x: Unary, y: Unary)\n requires !Less(x, y) && y != Zero\n ensures Sub(x, y) < x\n{\n}\n\nlemma AddSub(x: Unary, y: Unary)\n requires !Less(x, y)\n ensures Add(Sub(x, y), y) == x\n{\n}\n\n/*\nGoal: implement correcly and clearly, using iterative code (no recursion), documenting the proof obligations\n\tas we've learned, with assertions and a lemma for each proof goal\n\n- DO NOT modify the specification or any of the definitions given in this file\n- Not all definitions above are relevant, some are simply included as examples\n- Feel free to use existing non-ghost functions/predicates in your code, and existing lemmas (for the proof) in your annotations\n- New functions/predicates may be added ONLY as ghost\n- If it helps you in any way, a recursive implementation + proof can be found in the book and the downloadable source file\n [https://program-proofs.com/code.html example code in Dafny, source file 7-Unary.dfy]\n*/\n\nmethod{:verify false} IterativeDivMod'(x: Unary, y: Unary) returns (d: Unary, m: Unary)\n requires y != Zero\n ensures Add(Mul(d, y), m) == x && Less(m, y)\n{\n if (Less(x, y)) {\n d := Zero;\n m := x;\n }\n else{\n var x0: Unary := x;\n d := Zero;\n while (!Less(x0, y))\n {\n d := Suc(d);\n x0 := Sub(x0, y);\n }\n m := x0;\n }\n}\n\nmethod IterativeDivMod(x: Unary, y: Unary) returns (d: Unary, m: Unary)\n requires y != Zero\n ensures Add(Mul(d, y), m) == x && Less(m, y)\n{\n if (Less(x, y)) {\n AddZero(x);\n d := Zero;\n m := x;\n }\n else{\n var x0: Unary := x;\n d := Zero;\n AddZero(x);\n\n while (!Less(x0, y))\n {\n AddMulSucSubEqAddMul(d, y , x0);\n d := Suc(d);\n SubStructurallySmaller(x0, y);\n x0 := Sub(x0, y);\n }\n m := x0;\n }\n}\n\nlemma AddMulEqMulSuc(a: Unary, b: Unary)\n ensures Mul(Suc(a), b) == Add(Mul(a, b), b)\n{\n calc{\n Mul(Suc(a), b);\n == // def. Mul\n Add(Mul(a, b), b);\n }\n}\n\nlemma AddMulSucSubEqAddMul(d: Unary, y: Unary, x0: Unary)\n requires !Less(x0, y)\n requires y != Zero\n ensures Add(Mul(Suc(d), y), Sub(x0, y)) == Add(Mul(d, y), x0)\n{\n calc{\n Add(Mul(Suc(d), y), Sub(x0, y));\n == {AddMulEqMulSuc(d, y);\n Add(Add(Mul(d, y), y), Sub(x0, y));\n == {AddTransitive(Mul(d, y), y, Sub(x0, y));\n Add(Mul(d, y), Add(y, Sub(x0, y)));\n == {AddCommutative(Sub(x0, y), y);\n Add(Mul(d, y), Add(Sub(x0, y), y));\n == {assert !Less(x0, y);\n AddSub(x0, y);\n Add(Mul(d, y), x0);\n }\n}\n\nlemma AddTransitive(a: Unary, b: Unary, c: Unary)\n ensures Add(a, Add(b, c)) == Add(Add(a, b), c)\n{//These assertions are only for documanting the proof obligations\n match c \n case Zero =>\n calc{\n Add(a, Add(b, c));\n == \n Add(a, Add(b, Zero));\n == // def. Add\n Add(a, b);\n == // def. Add\n Add(Add(a,b), Zero);\n == \n Add(Add(a,b), c);\n }\n case Suc(c') =>\n match b\n case Zero =>\n calc{\n Add(a, Add(b, c));\n == \n Add(a, Add(Zero, Suc(c')));\n == {AddZero(Suc(c'));\n Add(a, Suc(c'));\n == // def. Add\n Add(Add(a, Zero), Suc(c'));\n ==\n Add(Add(a, b), Suc(c'));\n ==\n Add(Add(a,b), c);\n }\n case Suc(b') =>\n match a\n case Zero =>\n calc{\n Add(a, Add(b, c));\n ==\n Add(Zero, Add(Suc(b'), Suc(c')));\n == {AddZero(Add(Suc(b'), Suc(c')));\n Add(Suc(b'), Suc(c'));\n == {AddZero(Suc(b'));\n Add(Add(Zero, Suc(b')), Suc(c'));\n ==\n Add(Add(a, b), c);\n }\n case Suc(a') =>\n calc{\n Add(a, Add(b, c));\n ==\n Add(Suc(a'), Add(Suc(b'), Suc(c')));\n == // def. Add\n Add(Suc(a'), Suc(Add(Suc(b'), c')));\n == // def. Add\n Suc(Add(Suc(a'), Add(Suc(b'), c')));\n == {SucAdd(a', Add(Suc(b'), c'));\n Suc(Suc(Add(a', Add(Suc(b'), c'))));\n == {SucAdd(b', c');\n Suc(Suc(Add(a', Suc(Add(b', c')))));\n == // def. Add\n Suc(Suc(Suc(Add(a', Add(b', c')))));\n == {AddTransitive(a', b', c');\n Suc(Suc(Suc(Add(Add(a',b'), c'))));\n == // def. Add\n Suc(Suc(Add(Add(a', b'), Suc(c'))));\n == {SucAdd(Add(a', b'), Suc(c'));\n Suc(Add(Suc(Add(a', b')), Suc(c')));\n == {SucAdd(a', b');\n Suc(Add(Add(Suc(a'), b'), Suc(c')));\n == {SucAdd(Add(Suc(a'), b'), Suc(c'));\n Add(Suc(Add(Suc(a'), b')), Suc(c'));\n == // def. Add\n Add(Add(Suc(a'), Suc(b')), Suc(c'));\n ==\n Add(Add(a,b), c);\n }\n\n}\n\nlemma AddCommutative(a: Unary, b: Unary)\n ensures Add(a, b) == Add(b, a)\n{\n match b\n case Zero => \n calc{\n Add(a, b);\n ==\n Add(a, Zero);\n == // def. Add\n a;\n == {AddZero(a);\n Add(Zero, a);\n ==\n Add(b, a);\n }\n case Suc(b') =>\n calc{\n Add(a, b);\n ==\n Add(a, Suc(b'));\n == // def. Add\n Suc(Add(a, b'));\n == {AddCommutative(a, b');\n Suc(Add(b', a));\n == {SucAdd(b', a);\n Add(Suc(b'), a);\n ==\n Add(b, a);\n }\n}\n\n\n\nmethod Main() {\n var U3 := Suc(Suc(Suc(Zero)));\n var U7 := Suc(Suc(Suc(Suc(U3))));\n var d, m := IterativeDivMod(U7, U3);\n print \"Just as 7 divided by 3 is 2 with a remainder of 1, IterativeDivMod(\", U7, \", \", U3, \") is \", d, \" with a remainder of \", m;\n}\n" }, { "test_ID": "004", "test_file": "AssertivePrograming_tmp_tmpwf43uz0e_Find_Substring.dfy", "ground_truth": "// Noa Leron 207131871\n// Tsuri Farhana 315016907\n\n\nghost predicate ExistsSubstring(str1: string, str2: string) {\n\t// string in Dafny is a sequence of characters (seq) and <= on sequences is the prefix relation\n\texists offset :: 0 <= offset <= |str1| && str2 <= str1[offset..]\n}\n\nghost predicate Post(str1: string, str2: string, found: bool, i: nat) {\n\t(found <==> ExistsSubstring(str1, str2)) &&\n\t(found ==> i + |str2| <= |str1| && str2 <= str1[i..])\n}\n\n/*\nGoal: Verify correctness of the following code. Once done, remove the {:verify false} (or turn it into {:verify true}).\n\nFeel free to add GHOST code, including calls to lemmas. But DO NOT modify the specification or the original (executable) code.\n*/\nmethod {:verify true} FindFirstOccurrence(str1: string, str2: string) returns (found: bool, i: nat)\n\tensures Post(str1, str2, found, i)\n{\n\tif |str2| == 0 {\n\t\tfound, i := true, 0;\n\t\t assert Post(str1, str2, found, i); // this case is easy for dafny :)\n\t}\n\telse if |str1| < |str2| {\n\t\tfound, i := false, 0; // value of i irrelevant in this case\n\t assert Post(str1, str2, found, i); // this case is easy for dafny :)\n\t}\n\telse {\n\t\tfound, i := false, |str2|-1;\n\n\t\tassert |str2| > 0;\n assert |str1| >= |str2|;\n\t\tassert Outter_Inv_correctness(str1, str2, false, |str2|-1);\n\n\t\twhile !found && i < |str1|\n\t\t invariant Outter_Inv_correctness(str1, str2, found, i);\n decreases if !found then 1 else 0, |str1| - i;\n\t\t{\n assert Outter_Inv_correctness(str1, str2, found, i);\n assert |str2| > 0;\n assert !found && i < |str1|;\n\n\t\t\tvar j := |str2|-1;\n\n\t\t\tghost var old_i := i;\n ghost var old_j := j;\n\n\t\t\twhile !found && str1[i] == str2[j]\n\t\t\t\tinvariant Inner_Inv_Termination(str1, str2, i, j, old_i, old_j);\n\t\t\t\tinvariant Inner_Inv_correctness (str1, str2, i, j, found);\n decreases j, if !found then 1 else 0;\n\t\t\t{\n\t\t\t\tif j == 0 {\n\t\t\t\t\tassert j==0 && str1[i] == str2[j];\n\t\t\t\t\tfound := true;\n\t\t\t\t\tassert Inner_Inv_Termination(str1, str2, i, j, old_i, old_j);\n\t\t\t\t\tassert Inner_Inv_correctness(str1, str2, i, j, found);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tassert j > 0;\n\t\t\t\t\tassert Inner_Inv_Termination(str1, str2, i-1, j-1, old_i, old_j);\n\t\t\t\t\tassert Inner_Inv_correctness(str1, str2, i-1, j-1, found);\n\t\t\t\t\ti, j := i-1, j-1;\n\t\t\t\t\tassert Inner_Inv_Termination(str1, str2, i, j, old_i, old_j);\n\t\t\t\t\tassert Inner_Inv_correctness(str1, str2, i, j, found);\n\t\t\t\t}\n\t\t\t\tassert j >= 0;\n\t\t\t\tassert Inner_Inv_Termination(str1, str2, i, j, old_i, old_j);\n\t\t\t\tassert Inner_Inv_correctness(str1, str2, i, j, found);\n\t\t\t}\n\n\t\t\tassert Inner_Inv_Termination(str1, str2, i, j, old_i, old_j);\n\t\t\tassert Inner_Inv_correctness(str1, str2, i, j, found);\n\t\t\tassert found || str1[i] != str2[j]; // gaurd negation\n\t\t\tassert found ==> i + |str2| <= |str1| && str2 <= str1[i..];\n\t\t\tassert !found ==> str1[i] != str2[j];\n\n\t\t\tif !found {\n\t\t\t\tassert i < |str1|;\n\t\t\t\tassert |str2| > 0;\n\t\t\t\tassert old_j - j == old_i - i;\n assert old_i < i+|str2|-j;\n\t\t\t\tassert Outter_Inv_correctness(str1, str2, found, old_i);\n\t\t\t\tassert i+|str2|-j == old_i + 1;\n\t\t\t\tassert str1[i] != str2[j];\n\t\t\t\tassert |str1[old_i+1 - |str2|..old_i+1]| == |str2|;\n\t\t\t\tassert str1[old_i+1 - |str2|..old_i+1] != str2;\n\t\t\t\tassert 0 < old_i <= |str1| ==> !(ExistsSubstring(str1[..old_i], str2));\n\t\t\t\tLemma1(str1, str2, i, j, old_i, old_j, found); // ==>\n\t\t\t\tassert 0 < old_i+1 <= |str1| ==> !(ExistsSubstring(str1[..old_i+1], str2));\n\t\t\t\tassert 0 < i+|str2|-j <= |str1| ==> !(ExistsSubstring(str1[..i+|str2|-j], str2));\n\t\t\t\tassert Outter_Inv_correctness(str1, str2, found, i+|str2|-j);\n\n\t\t\t\ti := i+|str2|-j;\n\n assert old_i < i;\n assert Outter_Inv_correctness(str1, str2, found, i);\n\t\t\t\tassert i <= |str1|;\n\t\t\t}\n\n\t\t\tassert !found ==> i <= |str1|;\n assert !found ==> old_i < i;\n\t\t\tassert !found ==> Outter_Inv_correctness(str1, str2, found, i);\n\t\t\tassert found ==> Outter_Inv_correctness(str1, str2, found, i);\n assert Outter_Inv_correctness(str1, str2, found, i);\n\n\t\t}\n\t\tassert Outter_Inv_correctness(str1, str2, found, i);\n\t\tassert (found ==> i + |str2| <= |str1| && str2 <= str1[i..]);\n\t\tassert (!found && 0 < i <= |str1| ==> !(ExistsSubstring(str1[..i], str2)));\n\t\tassert (!found ==> i <= |str1|);\n\t\tassert found || i >= |str1|; // gaurd negation\n\t\tassert (!found && i == |str1| ==> !(ExistsSubstring(str1[..i], str2)));\n\t\tassert i == |str1| ==> str1[..i] == str1;\n\t\tassert (!found && i == |str1| ==> !(ExistsSubstring(str1, str2)));\n\t\tassert !found ==> i >= |str1|;\n\t\tassert !found ==> i == |str1|;\t\t\n\t\tassert (!found ==> !ExistsSubstring(str1, str2));\n\t\tassert (found ==> ExistsSubstring(str1, str2));\n\t\tassert (found <==> ExistsSubstring(str1, str2));\n\t\tassert (found ==> i + |str2| <= |str1| && str2 <= str1[i..]);\n\t\tassert Post(str1, str2, found, i);\n\t\t\n\t}\n\tassert Post(str1, str2, found, i);\n}\n\nmethod Main() {\n\tvar str1a, str1b := \"string\", \" in Dafny is a sequence of characters (seq)\";\n\tvar str1, str2 := str1a + str1b, \"ring\";\n\tvar found, i := FindFirstOccurrence(str1, str2);\n\tassert found by {\n\t\tassert ExistsSubstring(str1, str2) by {\n\t\t\tvar offset := 2;\n\t\t\tassert 0 <= offset <= |str1|;\n\t\t\tassert str2 <= str1[offset..] by {\n\t\t\t\tassert str2 == str1[offset..][..4];\n\t\t\t}\n\t\t}\n\t}\n\tprint \"\\nfound, i := FindFirstOccurrence(\\\"\", str1, \"\\\", \\\"\", str2, \"\\\") returns found == \", found;\n\tif found {\n\t\tprint \" and i == \", i;\n\t}\n\tstr1 := \"<= on sequences is the prefix relation\";\n\tfound, i := FindFirstOccurrence(str1, str2);\n\tprint \"\\nfound, i := FindFirstOccurrence(\\\"\", str1, \"\\\", \\\"\", str2, \"\\\") returns found == \", found;\n\tif found {\n\t\tprint \" and i == \", i;\n\t}\n}\n\n\n\n\n//this is our lemmas, invatiants and presicats\n\n\nghost predicate Outter_Inv_correctness(str1: string, str2: string, found: bool, i : nat)\n{\n\t(found ==> (i + |str2| <= |str1| && str2 <= str1[i..])) // Second part of post condition\n\t&&\n\t(!found && 0 < i <= |str1| && i != |str2|-1 ==> !(ExistsSubstring(str1[..i], str2))) // First part of post condition\n\t&&\n\t(!found ==> i <= |str1|)\n}\n\nghost predicate Inner_Inv_correctness(str1: string, str2: string, i : nat, j: int, found: bool){\n\t0 <= j <= i && // index in range\n\tj < |str2| && // index in range\n\ti < |str1| &&// index in range\n\t(str1[i] == str2[j] ==> str2[j..] <= str1[i..]) &&\n\t(found ==> j==0 && str1[i] == str2[j])\n}\n\nghost predicate Inner_Inv_Termination(str1: string, str2: string, i : nat, j: int, old_i: nat, old_j: nat){\n\told_j - j == old_i - i\n}\n\t\nlemma {:verify true} Lemma1 (str1: string, str2: string, i : nat, j: int, old_i: nat, old_j: nat, found: bool)\n// requires old_j - j == old_i - i;\nrequires !found;\nrequires |str2| > 0;\nrequires Outter_Inv_correctness(str1, str2, found, old_i);\nrequires i+|str2|-j == old_i + 1;\nrequires old_i+1 >= |str2|;\nrequires old_i+1 <= |str1|;\nrequires 0 <= i < |str1| && 0 <= j < |str2|;\nrequires str1[i] != str2[j];\nrequires |str2| > 0;\nrequires 0 < old_i <= |str1| ==> !(ExistsSubstring(str1[..old_i], str2));\nensures 0 < old_i+1 <= |str1| ==> !(ExistsSubstring(str1[..old_i+1], str2));\n{\n\tassert |str1[old_i+1 - |str2|..old_i+1]| == |str2|;\n\tassert str1[old_i+1 - |str2|..old_i+1] != str2;\n\tassert !(str2 <= str1[old_i+1 - |str2|..old_i+1]);\n\tassert 0 <= old_i < old_i+1 <= |str1|;\n\tassert old_i+1 >= |str2|;\n\n\n\tcalc{\n\t\t0 < old_i+1 <= |str1| \n\t\t&& (ExistsSubstring(str1[..old_i+1], str2))\n\t\t&& !(str2 <= str1[old_i+1 - |str2|..old_i+1]);\n\t\t==>\n\t\t(!(ExistsSubstring(str1[..old_i], str2)))\n\t\t&& (ExistsSubstring(str1[..old_i+1], str2))\n\t\t&& !(str2 <= str1[old_i+1 - |str2|..old_i+1]);\n\t\t==> {Lemma2(str1, str2, old_i, found);}\n\t\t((0 < old_i < old_i+1 <= |str1| && old_i != |str2|-1) ==> \n\t\t(|str1[old_i+1 - |str2|..old_i+1]| == |str2|) && (str2 <= str1[old_i+1 - |str2| .. old_i+1]))\n\t\t&& !(str2 <= str1[old_i+1 - |str2|..old_i+1]);\n\t\t==>\n\t\t((0 < old_i < old_i+1 <= |str1| && old_i != |str2|-1) ==> false);\n\t}\n}\n\n\nlemma {:verify true} Lemma2 (str1: string, str2: string, i : nat, found: bool)\nrequires 0 <= i < |str1|;\nrequires 0 < |str2| <= i+1;\nrequires !ExistsSubstring(str1[..i], str2);\nrequires ExistsSubstring(str1[..i+1], str2);\nensures str2 <= str1[i+1 - |str2| .. i+1];\n{\n\n\tassert exists offset :: 0 <= offset <= i+1 && str2 <= str1[offset..i+1] \n\t&& ((offset <= i) || (offset == i+1));\n\t\n\tcalc{\n\t\t(0 < |str2|) \n\t\t&& (!exists offset :: 0 <= offset <= i && str2 <= str1[offset..i])\n\t\t&& (exists offset :: 0 <= offset <= i+1 && str2 <= str1[offset..i+1]);\n\t\t==>\n\t\t(0 < |str2|) \n\t\t&& (forall offset :: 0 <= offset <= i ==> !(str2 <= str1[offset..i]))\n\t\t&& (exists offset :: 0 <= offset <= i+1 && str2 <= str1[offset..i+1]);\n\t\t==>\n\t\t(0 < |str2|) \n\t\t&& (exists offset :: (0 <= offset <= i+1) && str2 <= str1[offset..i+1])\n\t\t&& (forall offset :: 0 <= offset <= i+1 ==>\n\t\t\t(offset <= i ==> !(str2 <= str1[offset..i])));\n\t\t==> {Lemma3(str1, str2, i);}\n\t\t(0 < |str2|) \n\t\t&& (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) && (offset <= i ==> !(str2 <= str1[offset..i])));\n\t\t==>\n\t\t(0 < |str2|) \n\t\t&& (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) \n\t\t&& (offset <= i ==> !(str2 <= str1[offset..i])) && (offset == i+1 ==> |str2| == 0));\n\t\t==>\n\t\t(0 < |str2|) \n\t\t&& (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) \n\t\t&& (offset <= i ==> !(str2 <= str1[offset..i])) && (offset == i+1 ==> |str2| == 0) && (offset != i+1));\n\t\t==>\n\t\t(0 < |str2|) \n\t\t&& (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) \n\t\t&& (offset <= i ==> !(str2 <= str1[offset..i])) && (offset <= i));\n\t\t==>\n\t\t(0 < |str2|) \n\t\t&& (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) \n\t\t&& !(str2 <= str1[offset..i]));\n\t\t==>\n\t\tstr2 <= str1[i+1 - |str2| .. i+1];\n\t}\n\n\n\n}\n\nlemma Lemma3(str1: string, str2: string, i : nat)\n\trequires 0 <= i < |str1|;\n\trequires 0 < |str2| <= i+1;\n\trequires exists offset :: (0 <= offset <= i+1) && str2 <= str1[offset..i+1];\n\trequires forall offset :: 0 <= offset <= i+1 ==> (offset <= i ==> !(str2 <= str1[offset..i]));\n\tensures exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) && (offset <= i ==> !(str2 <= str1[offset..i]));\n{\n\tvar offset :| (0 <= offset <= i+1) && str2 <= str1[offset..i+1];\n\tassert 0 <= offset <= i+1 ==> (offset <= i ==> !(str2 <= str1[offset..i]));\t\n}\n\n\n\n", "hints_removed": "// Noa Leron 207131871\n// Tsuri Farhana 315016907\n\n\nghost predicate ExistsSubstring(str1: string, str2: string) {\n\t// string in Dafny is a sequence of characters (seq) and <= on sequences is the prefix relation\n\texists offset :: 0 <= offset <= |str1| && str2 <= str1[offset..]\n}\n\nghost predicate Post(str1: string, str2: string, found: bool, i: nat) {\n\t(found <==> ExistsSubstring(str1, str2)) &&\n\t(found ==> i + |str2| <= |str1| && str2 <= str1[i..])\n}\n\n/*\nGoal: Verify correctness of the following code. Once done, remove the {:verify false} (or turn it into {:verify true}).\n\nFeel free to add GHOST code, including calls to lemmas. But DO NOT modify the specification or the original (executable) code.\n*/\nmethod {:verify true} FindFirstOccurrence(str1: string, str2: string) returns (found: bool, i: nat)\n\tensures Post(str1, str2, found, i)\n{\n\tif |str2| == 0 {\n\t\tfound, i := true, 0;\n\t}\n\telse if |str1| < |str2| {\n\t\tfound, i := false, 0; // value of i irrelevant in this case\n\t}\n\telse {\n\t\tfound, i := false, |str2|-1;\n\n\n\t\twhile !found && i < |str1|\n\t\t{\n\n\t\t\tvar j := |str2|-1;\n\n\t\t\tghost var old_i := i;\n ghost var old_j := j;\n\n\t\t\twhile !found && str1[i] == str2[j]\n\t\t\t{\n\t\t\t\tif j == 0 {\n\t\t\t\t\tfound := true;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ti, j := i-1, j-1;\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t\tif !found {\n\t\t\t\tLemma1(str1, str2, i, j, old_i, old_j, found); // ==>\n\n\t\t\t\ti := i+|str2|-j;\n\n\t\t\t}\n\n\n\t\t}\n\t\t\n\t}\n}\n\nmethod Main() {\n\tvar str1a, str1b := \"string\", \" in Dafny is a sequence of characters (seq)\";\n\tvar str1, str2 := str1a + str1b, \"ring\";\n\tvar found, i := FindFirstOccurrence(str1, str2);\n\t\t\tvar offset := 2;\n\t\t\t}\n\t\t}\n\t}\n\tprint \"\\nfound, i := FindFirstOccurrence(\\\"\", str1, \"\\\", \\\"\", str2, \"\\\") returns found == \", found;\n\tif found {\n\t\tprint \" and i == \", i;\n\t}\n\tstr1 := \"<= on sequences is the prefix relation\";\n\tfound, i := FindFirstOccurrence(str1, str2);\n\tprint \"\\nfound, i := FindFirstOccurrence(\\\"\", str1, \"\\\", \\\"\", str2, \"\\\") returns found == \", found;\n\tif found {\n\t\tprint \" and i == \", i;\n\t}\n}\n\n\n\n\n//this is our lemmas, invatiants and presicats\n\n\nghost predicate Outter_Inv_correctness(str1: string, str2: string, found: bool, i : nat)\n{\n\t(found ==> (i + |str2| <= |str1| && str2 <= str1[i..])) // Second part of post condition\n\t&&\n\t(!found && 0 < i <= |str1| && i != |str2|-1 ==> !(ExistsSubstring(str1[..i], str2))) // First part of post condition\n\t&&\n\t(!found ==> i <= |str1|)\n}\n\nghost predicate Inner_Inv_correctness(str1: string, str2: string, i : nat, j: int, found: bool){\n\t0 <= j <= i && // index in range\n\tj < |str2| && // index in range\n\ti < |str1| &&// index in range\n\t(str1[i] == str2[j] ==> str2[j..] <= str1[i..]) &&\n\t(found ==> j==0 && str1[i] == str2[j])\n}\n\nghost predicate Inner_Inv_Termination(str1: string, str2: string, i : nat, j: int, old_i: nat, old_j: nat){\n\told_j - j == old_i - i\n}\n\t\nlemma {:verify true} Lemma1 (str1: string, str2: string, i : nat, j: int, old_i: nat, old_j: nat, found: bool)\n// requires old_j - j == old_i - i;\nrequires !found;\nrequires |str2| > 0;\nrequires Outter_Inv_correctness(str1, str2, found, old_i);\nrequires i+|str2|-j == old_i + 1;\nrequires old_i+1 >= |str2|;\nrequires old_i+1 <= |str1|;\nrequires 0 <= i < |str1| && 0 <= j < |str2|;\nrequires str1[i] != str2[j];\nrequires |str2| > 0;\nrequires 0 < old_i <= |str1| ==> !(ExistsSubstring(str1[..old_i], str2));\nensures 0 < old_i+1 <= |str1| ==> !(ExistsSubstring(str1[..old_i+1], str2));\n{\n\n\n\tcalc{\n\t\t0 < old_i+1 <= |str1| \n\t\t&& (ExistsSubstring(str1[..old_i+1], str2))\n\t\t&& !(str2 <= str1[old_i+1 - |str2|..old_i+1]);\n\t\t==>\n\t\t(!(ExistsSubstring(str1[..old_i], str2)))\n\t\t&& (ExistsSubstring(str1[..old_i+1], str2))\n\t\t&& !(str2 <= str1[old_i+1 - |str2|..old_i+1]);\n\t\t==> {Lemma2(str1, str2, old_i, found);}\n\t\t((0 < old_i < old_i+1 <= |str1| && old_i != |str2|-1) ==> \n\t\t(|str1[old_i+1 - |str2|..old_i+1]| == |str2|) && (str2 <= str1[old_i+1 - |str2| .. old_i+1]))\n\t\t&& !(str2 <= str1[old_i+1 - |str2|..old_i+1]);\n\t\t==>\n\t\t((0 < old_i < old_i+1 <= |str1| && old_i != |str2|-1) ==> false);\n\t}\n}\n\n\nlemma {:verify true} Lemma2 (str1: string, str2: string, i : nat, found: bool)\nrequires 0 <= i < |str1|;\nrequires 0 < |str2| <= i+1;\nrequires !ExistsSubstring(str1[..i], str2);\nrequires ExistsSubstring(str1[..i+1], str2);\nensures str2 <= str1[i+1 - |str2| .. i+1];\n{\n\n\t&& ((offset <= i) || (offset == i+1));\n\t\n\tcalc{\n\t\t(0 < |str2|) \n\t\t&& (!exists offset :: 0 <= offset <= i && str2 <= str1[offset..i])\n\t\t&& (exists offset :: 0 <= offset <= i+1 && str2 <= str1[offset..i+1]);\n\t\t==>\n\t\t(0 < |str2|) \n\t\t&& (forall offset :: 0 <= offset <= i ==> !(str2 <= str1[offset..i]))\n\t\t&& (exists offset :: 0 <= offset <= i+1 && str2 <= str1[offset..i+1]);\n\t\t==>\n\t\t(0 < |str2|) \n\t\t&& (exists offset :: (0 <= offset <= i+1) && str2 <= str1[offset..i+1])\n\t\t&& (forall offset :: 0 <= offset <= i+1 ==>\n\t\t\t(offset <= i ==> !(str2 <= str1[offset..i])));\n\t\t==> {Lemma3(str1, str2, i);}\n\t\t(0 < |str2|) \n\t\t&& (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) && (offset <= i ==> !(str2 <= str1[offset..i])));\n\t\t==>\n\t\t(0 < |str2|) \n\t\t&& (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) \n\t\t&& (offset <= i ==> !(str2 <= str1[offset..i])) && (offset == i+1 ==> |str2| == 0));\n\t\t==>\n\t\t(0 < |str2|) \n\t\t&& (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) \n\t\t&& (offset <= i ==> !(str2 <= str1[offset..i])) && (offset == i+1 ==> |str2| == 0) && (offset != i+1));\n\t\t==>\n\t\t(0 < |str2|) \n\t\t&& (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) \n\t\t&& (offset <= i ==> !(str2 <= str1[offset..i])) && (offset <= i));\n\t\t==>\n\t\t(0 < |str2|) \n\t\t&& (exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) \n\t\t&& !(str2 <= str1[offset..i]));\n\t\t==>\n\t\tstr2 <= str1[i+1 - |str2| .. i+1];\n\t}\n\n\n\n}\n\nlemma Lemma3(str1: string, str2: string, i : nat)\n\trequires 0 <= i < |str1|;\n\trequires 0 < |str2| <= i+1;\n\trequires exists offset :: (0 <= offset <= i+1) && str2 <= str1[offset..i+1];\n\trequires forall offset :: 0 <= offset <= i+1 ==> (offset <= i ==> !(str2 <= str1[offset..i]));\n\tensures exists offset :: (0 <= offset <= i+1) && (str2 <= str1[offset..i+1]) && (offset <= i ==> !(str2 <= str1[offset..i]));\n{\n\tvar offset :| (0 <= offset <= i+1) && str2 <= str1[offset..i+1];\n}\n\n\n\n" }, { "test_ID": "005", "test_file": "AssertivePrograming_tmp_tmpwf43uz0e_MergeSort.dfy", "ground_truth": "// Noa Leron 207131871\n// Tsuri Farhana 315016907\n\n\n\npredicate Sorted(q: seq) {\n\tforall i,j :: 0 <= i <= j < |q| ==> q[i] <= q[j]\n}\n\n/*\nGoal: Implement the well known merge sort algorithm in O(a.Length X log_2(a.Length)) time, recursively.\n\n- Divide the contents of the original array into two local arrays\n- After sorting the local arrays (recursively), merge the contents of the two returned arrays using the Merge method (see below)\n- DO NOT modify the specification or any other part of the method's signature\n- DO NOT introduce any further methods\n*/\nmethod MergeSort(a: array) returns (b: array)\n\tensures b.Length == a.Length && Sorted(b[..]) && multiset(a[..]) == multiset(b[..])\n\tdecreases a.Length\n{\n\tif (a.Length <= 1) {b := a;}\n else{\n var mid: nat := a.Length / 2;\n var a1: array := new int[mid];\n var a2: array := new int[a.Length - mid];\n assert a1.Length <= a2.Length;\n assert a.Length == a1.Length + a2.Length;\n\n var i: nat := 0;\n while (i < a1.Length )\n invariant Inv(a[..], a1[..], a2[..], i, mid)\n decreases a1.Length - i\n {\n a1[i] := a[i];\n a2[i] := a[i+mid];\n i:=i+1;\n }\n assert !(i < a1.Length);\n assert (i >= a1.Length);\n assert i == a1.Length;\n assert Inv(a[..], a1[..], a2[..], i, mid);\n assert (i <= |a1[..]|) && (i <= |a2[..]|) && (i+mid <= |a[..]|);\n assert (a1[..i] == a[..i]) && (a2[..i] == a[mid..(i+mid)]);\n \n if(a1.Length < a2.Length) {\n a2[i] := a[i+mid];\n assert i+1 == a2.Length;\n assert (a2[..i+1] == a[mid..(i+1+mid)]);\n assert (a1[..i] == a[..i]) && (a2[..i+1] == a[mid..(i+1+mid)]);\n assert a[..i] + a[i..i+1+mid] == a1[..i] + a2[..i+1];\n assert a[..i] + a[i..i+1+mid] == a1[..] + a2[..];\n assert a[..] == a1[..] + a2[..];\n } // If a.Length is odd.\n else{\n assert i == a2.Length;\n assert (a1[..i] == a[..i]) && (a2[..i] == a[mid..(i+mid)]);\n assert a[..i] + a[i..i+mid] == a1[..i] + a2[..i];\n assert a[..i] + a[i..i+mid] == a1[..] + a2[..];\n assert a[..] == a1[..] + a2[..];\n }\n\n assert a1.Length < a.Length;\n a1:= MergeSort(a1);\n assert a2.Length < a.Length;\n a2:= MergeSort(a2);\n b := new int [a.Length];\n Merge(b, a1, a2);\n assert multiset(b[..]) == multiset(a1[..]) + multiset(a2[..]);\n assert Sorted(b[..]); \n }\n assert b.Length == a.Length && Sorted(b[..]) && multiset(a[..]) == multiset(b[..]);\n} \n\nghost predicate Inv(a: seq, a1: seq, a2: seq, i: nat, mid: nat){\n (i <= |a1|) && (i <= |a2|) && (i+mid <= |a|) &&\n (a1[..i] == a[..i]) && (a2[..i] == a[mid..(i+mid)])\n}\n\n/*\nGoal: Implement iteratively, correctly, efficiently, clearly\n\nDO NOT modify the specification or any other part of the method's signature\n*/\nmethod Merge(b: array, c: array, d: array)\n\trequires b != c && b != d && b.Length == c.Length + d.Length\n\trequires Sorted(c[..]) && Sorted(d[..])\n\tensures Sorted(b[..]) && multiset(b[..]) == multiset(c[..])+multiset(d[..])\n\tmodifies b\n{\n\tvar i: nat, j: nat := 0, 0;\n\twhile i + j < b.Length\n\t\tinvariant i <= c.Length && j <= d.Length && i + j <= b.Length\n\t\tinvariant InvSubSet(b[..],c[..],d[..],i,j)\n\t\tinvariant InvSorted(b[..],c[..],d[..],i,j)\n\t\tdecreases c.Length-i, d.Length-j\n\t{\t\n\t\ti,j := MergeLoop (b,c,d,i,j);\n\t\tassert InvSubSet(b[..],c[..],d[..],i,j);\n\t\tassert InvSorted(b[..],c[..],d[..],i,j);\n\t}\n\tassert InvSubSet(b[..],c[..],d[..],i,j);\n\tLemmaMultysetsEquals(b[..],c[..],d[..],i,j);\t\n\tassert multiset(b[..]) == multiset(c[..])+multiset(d[..]);\n\t\t\n}\n\n\n//This is a method that replace the loop body\nmethod {:verify true} MergeLoop(b: array, c: array, d: array,i0: nat , j0: nat) returns (i: nat, j: nat)\n\t\trequires b != c && b != d && b.Length == c.Length + d.Length\n\t\trequires Sorted(c[..]) && Sorted(d[..])\n\t\trequires i0 <= c.Length && j0 <= d.Length && i0 + j0 <= b.Length\n\t\trequires InvSubSet(b[..],c[..],d[..],i0,j0)\n\t\trequires InvSorted(b[..],c[..],d[..],i0,j0)\n\t\trequires i0 + j0 < b.Length\n\n\t\tmodifies b\n\n\t\tensures i <= c.Length && j <= d.Length && i + j <= b.Length\n\t\tensures InvSubSet(b[..],c[..],d[..],i,j)\n\t\tensures InvSorted(b[..],c[..],d[..],i,j)\n\t\t//decreases ensures\n\t\tensures 0 <= c.Length - i < c.Length - i0 || (c.Length - i == c.Length - i0 && 0 <= d.Length - j < d.Length - j0)\n\t\t{\n\n\t\t\ti,j := i0,j0;\n\t\t\t\t\n\t\t\t\tif(i == c.Length || (j< d.Length && d[j] < c[i])){\n\t\t\t\t\t// in this case we take the next value from d\n\t\t\t\tassert InvSorted(b[..][i+j:=d[j]],c[..],d[..],i,j+1);\n\t\t\t\tb[i+j] := d[j];\n\t\t\t\tlemmaInvSubsetTakeValueFromD(b[..],c[..],d[..],i,j);\n\n\t\t\t\tassert InvSubSet(b[..],c[..],d[..],i,j+1);\n\t\t\t\tassert InvSorted(b[..],c[..],d[..],i,j+1);\n\t\t\t\tj := j + 1;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tassert j == d.Length || (i < c.Length && c[i] <= d[j]);\n\t\t\t\t\t// in this case we take the next value from c\n\t\t\t\tassert InvSorted(b[..][i+j:=c[i]],c[..],d[..],i+1,j);\n\t\t\t\t\n\t\t\t\tb[i+j] := c[i];\n\n\t\t\t\tlemmaInvSubsetTakeValueFromC(b[..],c[..],d[..],i,j);\n\t\t\t\tassert InvSubSet(b[..],c[..],d[..],i+1,j);\n\t\t\t\tassert InvSorted(b[..],c[..],d[..],i+1,j);\n\t\t\t\ti := i + 1;\n\t\t\t}\n\n\n\t\t}\n\n\t\n//Loop invariant - b is sprted so far and the next two potential values that will go into b are bigger then the biggest value in b.\nghost predicate InvSorted(b: seq, c: seq, d: seq, i: nat, j: nat){\n\ti <= |c| && j <= |d| && i + j <= |b| &&\n\t((i+j > 0 && i < |c|) ==> (b[j + i - 1] <= c[i])) &&\n\t((i+j > 0 && j < |d|) ==> (b[j + i - 1] <= d[j])) &&\n\tSorted(b[..i+j])\n\t}\n\n\n//Loop invariant - the multiset of the prefix of b so far is the same multiset as the prefixes of c and d so far.\nghost predicate InvSubSet(b: seq, c: seq, d: seq, i: nat, j: nat){\n\ti <= |c| && j <= |d| && i + j <= |b| &&\n\tmultiset(b[..i+j]) == multiset(c[..i]) + multiset(d[..j])\n}\n\n//This lemma helps dafny see that if the prefixs of arrays are the same multiset until the end of the arrays,\n//all the arrays are the same multiset.\nlemma LemmaMultysetsEquals (b: seq, c: seq, d: seq, i: nat, j: nat)\n\trequires i == |c|;\n\trequires j == |d|;\n\trequires i + j == |b|;\n\trequires multiset(b[..i+j]) == multiset(c[..i]) + multiset(d[..j])\n\tensures multiset(b[..]) == multiset(c[..])+multiset(d[..]);\n\t{\n\t\tassert b[..] == b[..i+j];\n\t\tassert c[..] == c[..i];\n\t\tassert d[..] == d[..j];\n\t}\n\n\n//This lemma helps dafny see that after adding the next value from c to b the prefixes are still the same subsets.\nlemma lemmaInvSubsetTakeValueFromC (b: seq, c: seq, d: seq, i: nat, j: nat)\n\trequires i < |c|;\n\trequires j <= |d|;\n\trequires i + j < |b|;\n\trequires |c| + |d| == |b|;\n\trequires multiset(b[..i+j]) == multiset(c[..i]) + multiset(d[..j])\n\trequires b[i+j] == c[i]\n\tensures multiset(b[..i+j+1]) == multiset(c[..i+1])+multiset(d[..j])\n\t{\n\t\tassert c[..i]+[c[i]] == c[..i+1];\n\t\tassert b[..i+j+1] == b[..i+j] + [b[i+j]];\n\t\tassert multiset(b[..i+j+1]) == multiset(c[..i+1])+multiset(d[..j]);\n\t}\n\n\n\n//This lemma helps dafny see that after adding the next value from d to b the prefixes are still the same subsets.\nlemma{:verify true} lemmaInvSubsetTakeValueFromD (b: seq, c: seq, d: seq, i: nat, j: nat)\n\trequires i <= |c|;\n\trequires j < |d|;\n\trequires i + j < |b|;\n\trequires |c| + |d| == |b|;\n\trequires multiset(b[..i+j]) == multiset(c[..i]) + multiset(d[..j])\n\trequires b[i+j] == d[j]\n\tensures multiset(b[..i+j+1]) == multiset(c[..i])+multiset(d[..j+1])\n\t{\n\t\tassert d[..j]+[d[j]] == d[..j+1];\n\t\tassert b[..i+j+1] == b[..i+j] + [b[i+j]];\n\t\tassert multiset(b[..i+j+1]) == multiset(c[..i])+multiset(d[..j+1]);\n\t}\n\n\n\n\n\nmethod Main() {\n\tvar a := new int[3] [4, 8, 6];\n\tvar q0 := a[..];\n\tassert q0 == [4,8,6];\n\ta := MergeSort(a);\n\tassert a.Length == |q0| && multiset(a[..]) == multiset(q0);\n\tprint \"\\nThe sorted version of \", q0, \" is \", a[..];\n\tassert Sorted(a[..]);\n\tassert a[..] == [4, 6, 8];\n\n\ta := new int[5] [3, 8, 5, -1, 10];\n\tq0 := a[..];\n\tassert q0 == [3, 8, 5, -1, 10];\n\ta := MergeSort(a);\n\tassert a.Length == |q0| && multiset(a[..]) == multiset(q0);\n\tprint \"\\nThe sorted version of \", q0, \" is \", a[..];\n\tassert Sorted(a[..]);\n\t//assert a[..] == [-1, 3, 5, 8, 10];\n}\n", "hints_removed": "// Noa Leron 207131871\n// Tsuri Farhana 315016907\n\n\n\npredicate Sorted(q: seq) {\n\tforall i,j :: 0 <= i <= j < |q| ==> q[i] <= q[j]\n}\n\n/*\nGoal: Implement the well known merge sort algorithm in O(a.Length X log_2(a.Length)) time, recursively.\n\n- Divide the contents of the original array into two local arrays\n- After sorting the local arrays (recursively), merge the contents of the two returned arrays using the Merge method (see below)\n- DO NOT modify the specification or any other part of the method's signature\n- DO NOT introduce any further methods\n*/\nmethod MergeSort(a: array) returns (b: array)\n\tensures b.Length == a.Length && Sorted(b[..]) && multiset(a[..]) == multiset(b[..])\n{\n\tif (a.Length <= 1) {b := a;}\n else{\n var mid: nat := a.Length / 2;\n var a1: array := new int[mid];\n var a2: array := new int[a.Length - mid];\n\n var i: nat := 0;\n while (i < a1.Length )\n {\n a1[i] := a[i];\n a2[i] := a[i+mid];\n i:=i+1;\n }\n \n if(a1.Length < a2.Length) {\n a2[i] := a[i+mid];\n } // If a.Length is odd.\n else{\n }\n\n a1:= MergeSort(a1);\n a2:= MergeSort(a2);\n b := new int [a.Length];\n Merge(b, a1, a2);\n }\n} \n\nghost predicate Inv(a: seq, a1: seq, a2: seq, i: nat, mid: nat){\n (i <= |a1|) && (i <= |a2|) && (i+mid <= |a|) &&\n (a1[..i] == a[..i]) && (a2[..i] == a[mid..(i+mid)])\n}\n\n/*\nGoal: Implement iteratively, correctly, efficiently, clearly\n\nDO NOT modify the specification or any other part of the method's signature\n*/\nmethod Merge(b: array, c: array, d: array)\n\trequires b != c && b != d && b.Length == c.Length + d.Length\n\trequires Sorted(c[..]) && Sorted(d[..])\n\tensures Sorted(b[..]) && multiset(b[..]) == multiset(c[..])+multiset(d[..])\n\tmodifies b\n{\n\tvar i: nat, j: nat := 0, 0;\n\twhile i + j < b.Length\n\t{\t\n\t\ti,j := MergeLoop (b,c,d,i,j);\n\t}\n\tLemmaMultysetsEquals(b[..],c[..],d[..],i,j);\t\n\t\t\n}\n\n\n//This is a method that replace the loop body\nmethod {:verify true} MergeLoop(b: array, c: array, d: array,i0: nat , j0: nat) returns (i: nat, j: nat)\n\t\trequires b != c && b != d && b.Length == c.Length + d.Length\n\t\trequires Sorted(c[..]) && Sorted(d[..])\n\t\trequires i0 <= c.Length && j0 <= d.Length && i0 + j0 <= b.Length\n\t\trequires InvSubSet(b[..],c[..],d[..],i0,j0)\n\t\trequires InvSorted(b[..],c[..],d[..],i0,j0)\n\t\trequires i0 + j0 < b.Length\n\n\t\tmodifies b\n\n\t\tensures i <= c.Length && j <= d.Length && i + j <= b.Length\n\t\tensures InvSubSet(b[..],c[..],d[..],i,j)\n\t\tensures InvSorted(b[..],c[..],d[..],i,j)\n\t\t//decreases ensures\n\t\tensures 0 <= c.Length - i < c.Length - i0 || (c.Length - i == c.Length - i0 && 0 <= d.Length - j < d.Length - j0)\n\t\t{\n\n\t\t\ti,j := i0,j0;\n\t\t\t\t\n\t\t\t\tif(i == c.Length || (j< d.Length && d[j] < c[i])){\n\t\t\t\t\t// in this case we take the next value from d\n\t\t\t\tb[i+j] := d[j];\n\t\t\t\tlemmaInvSubsetTakeValueFromD(b[..],c[..],d[..],i,j);\n\n\t\t\t\tj := j + 1;\n\t\t\t}\n\t\t\telse{\n\t\t\t\t\t// in this case we take the next value from c\n\t\t\t\t\n\t\t\t\tb[i+j] := c[i];\n\n\t\t\t\tlemmaInvSubsetTakeValueFromC(b[..],c[..],d[..],i,j);\n\t\t\t\ti := i + 1;\n\t\t\t}\n\n\n\t\t}\n\n\t\n//Loop invariant - b is sprted so far and the next two potential values that will go into b are bigger then the biggest value in b.\nghost predicate InvSorted(b: seq, c: seq, d: seq, i: nat, j: nat){\n\ti <= |c| && j <= |d| && i + j <= |b| &&\n\t((i+j > 0 && i < |c|) ==> (b[j + i - 1] <= c[i])) &&\n\t((i+j > 0 && j < |d|) ==> (b[j + i - 1] <= d[j])) &&\n\tSorted(b[..i+j])\n\t}\n\n\n//Loop invariant - the multiset of the prefix of b so far is the same multiset as the prefixes of c and d so far.\nghost predicate InvSubSet(b: seq, c: seq, d: seq, i: nat, j: nat){\n\ti <= |c| && j <= |d| && i + j <= |b| &&\n\tmultiset(b[..i+j]) == multiset(c[..i]) + multiset(d[..j])\n}\n\n//This lemma helps dafny see that if the prefixs of arrays are the same multiset until the end of the arrays,\n//all the arrays are the same multiset.\nlemma LemmaMultysetsEquals (b: seq, c: seq, d: seq, i: nat, j: nat)\n\trequires i == |c|;\n\trequires j == |d|;\n\trequires i + j == |b|;\n\trequires multiset(b[..i+j]) == multiset(c[..i]) + multiset(d[..j])\n\tensures multiset(b[..]) == multiset(c[..])+multiset(d[..]);\n\t{\n\t}\n\n\n//This lemma helps dafny see that after adding the next value from c to b the prefixes are still the same subsets.\nlemma lemmaInvSubsetTakeValueFromC (b: seq, c: seq, d: seq, i: nat, j: nat)\n\trequires i < |c|;\n\trequires j <= |d|;\n\trequires i + j < |b|;\n\trequires |c| + |d| == |b|;\n\trequires multiset(b[..i+j]) == multiset(c[..i]) + multiset(d[..j])\n\trequires b[i+j] == c[i]\n\tensures multiset(b[..i+j+1]) == multiset(c[..i+1])+multiset(d[..j])\n\t{\n\t}\n\n\n\n//This lemma helps dafny see that after adding the next value from d to b the prefixes are still the same subsets.\nlemma{:verify true} lemmaInvSubsetTakeValueFromD (b: seq, c: seq, d: seq, i: nat, j: nat)\n\trequires i <= |c|;\n\trequires j < |d|;\n\trequires i + j < |b|;\n\trequires |c| + |d| == |b|;\n\trequires multiset(b[..i+j]) == multiset(c[..i]) + multiset(d[..j])\n\trequires b[i+j] == d[j]\n\tensures multiset(b[..i+j+1]) == multiset(c[..i])+multiset(d[..j+1])\n\t{\n\t}\n\n\n\n\n\nmethod Main() {\n\tvar a := new int[3] [4, 8, 6];\n\tvar q0 := a[..];\n\ta := MergeSort(a);\n\tprint \"\\nThe sorted version of \", q0, \" is \", a[..];\n\n\ta := new int[5] [3, 8, 5, -1, 10];\n\tq0 := a[..];\n\ta := MergeSort(a);\n\tprint \"\\nThe sorted version of \", q0, \" is \", a[..];\n\t//assert a[..] == [-1, 3, 5, 8, 10];\n}\n" }, { "test_ID": "006", "test_file": "BPTree-verif_tmp_tmpq1z6xm1d_Utils.dfy", "ground_truth": "\n// method CountLessThan(numbers: set, threshold: int) returns (count: int)\n// // ensures count == |set i | i in numbers && i < threshold|\n// ensures count == |SetLessThan(numbers, threshold)|\n// {\n// count := 0;\n// var ss := numbers;\n// while ss != {}\n// decreases |ss|\n// {\n// var i: int :| i in ss;\n// ss := ss - {i};\n// if i < threshold {\n// count := count + 1;\n// }\n\n// }\n// assert count == |SetLessThan(numbers, threshold)|;\n// // assert count == |set i | i in numbers && i < threshold|;\n// }\n\nfunction SetLessThan(numbers: set, threshold: int): set\n{\n set i | i in numbers && i < threshold\n}\n\nmethod Main()\n{\n // var s: set := {1, 2, 3, 4, 5};\n // var c: int := CountLessThan(s, 4);\n // print c;\n // assert c == 3;\n\n\n // if you manualy create set and sequence with same elements, |s|==|t| works\n var t: seq := [1, 2, 3];\n var s: set := {1, 2, 3};\n assert |s| == 3;\n assert |s| == |t|;\n\n // but if you create set from the sequence with distinct elements it does not understand that |s|==|t|\n // Dafny has problems when reasoning about set sizes ==> \n s := set x | x in t;\n assert forall x :: x in t ==> x in s;\n assert forall x :: x in s ==> x in t;\n assert forall x :: x in s <==> x in t;\n assert forall i, j :: 0 <= i < |t| && 0 <= j < |t| && i !=j ==> t[i] != t[j];\n assert |t| == 3;\n // assert |s| == |t|; // not verifying\n // assert |s| == 3; // not verifying\n\n // other expriments\n set_memebrship_implies_cardinality(s, set x | x in t); // s and the other argument is the same thing\n var s2 : set := set x | x in t;\n assert |s| == |s2|;\n\n s2 := {1, 2, 3};\n // assert |s| == |s2|; // may not hold\n set_memebrship_implies_cardinality(s, s2); \n assert |s| == |s2|; // after lemma it holds\n}\n\nlemma set_memebrship_implies_cardinality_helper(s: set, t: set, s_size: int)\n requires s_size >= 0 && s_size == |s|\n requires forall x :: x in s <==> x in t\n ensures |s| == |t|\n decreases s_size {\n if s_size == 0 {\n } else {\n var s_hd;\n // assign s_hd to a value *such that* s_hd is in s (see such_that expressions)\n s_hd :| s_hd in s;\n set_memebrship_implies_cardinality_helper(s - {s_hd}, t - {s_hd}, s_size - 1);\n }\n}\n\n\nlemma set_memebrship_implies_cardinality(s: set, t: set)\n requires forall x :: x in s <==> x in t\n ensures |s| == |t| {\n set_memebrship_implies_cardinality_helper(s, t, |s|);\n}\n\n\n/*\nlemma Bijection(arr: seq, s: set) // returns (bool)\n requires sorted(arr)\n // requires forall x, y :: x in s && y in s && x != y ==> x < y\n ensures |s| == |arr|\n{\n var mapping: map := map[];\n \n // Establish the bijection\n for i := 0 to |arr| {\n mapping := mapping[arr[i]:= arr[i]];\n }\n\n // Prove injectiveness\n assert forall i, j :: (0 <= i < |arr|-1 && 0 <= j < |arr|-1 && i != j )==> mapping[arr[i]] != mapping[arr[j]];\n\n // Prove surjectiveness\n // assert forall x :: x in s ==> exists i :: 0 <= i < |arr|-1 && arr[i] == x;\n\n // Conclude equinumerosity\n // assert |s| == |arr|;\n // return true;\n}\n*/\n\nfunction seqSet(nums: seq, index: nat): set {\n set x | 0 <= x < index < |nums| :: nums[x]\n}\n\nlemma containsDuplicateI(nums: seq) returns (containsDuplicate: bool)\n ensures containsDuplicate ==> exists i,j :: 0 <= i < j < |nums| && nums[i] == nums[j]\n{\n var windowGhost: set := {};\n var windowSet: set := {};\n for i:= 0 to |nums| \n invariant 0 <= i <= |nums|\n invariant forall j :: 0 <= j < i < |nums| ==> nums[j] in windowSet\n // invariant forall x :: x in windowSet ==> x in nums\n invariant forall x :: x in windowSet ==> x in nums[0..i]\n invariant seqSet(nums, i) <= windowSet\n {\n windowGhost := windowSet;\n if nums[i] in windowSet { // does not verify\n // if nums[i] in seqSet(nums, i) { //verifies\n return true;\n }\n windowSet := windowSet + {nums[i]};\n }\n return false;\n}\n\n// lemma numElemsOfSet(a: seq)\n// requires sorted(a)\n// {\n// assert distinct(a);\n// var s := set x | x in a;\n// assert forall x :: x in s ==> x in a[..];\n// assert forall x :: x in a ==> x in s;\n// assert |s| == |a|;\n// }\n\n// lemma CardinalitySetEqualsArray(a: seq, s: set)\n// requires s == set x | x in a\n// requires distinct(a)\n// ensures |s| == |a|\n// {\n// assert forall x :: x in s ==> exists i :: 0 <= i < |a| && a[i] == x;\n// assert forall i, j :: 0 <= i < |a| && 0 <= j < |a| && i != j ==> a[i] != a[j];\n// // Assert that each element in the array is in the set\n// assert forall i :: 0 <= i < |a| ==> a[i] in s;\n// // Assert that the set contains exactly the elements in the array\n// assert s == set x | x in a;\n// // Assert that the set is a subset of the array\n// assert forall x :: x in s <==> x in a;\n\n// // Conclude the equivalence\n// assert |s| == |a|;\n// }\n\n\n/*\nlemma memebrship_implies_cardinality_helper(s: set, t: seq, s_size: int)\n requires s_size >= 0 && s_size == |s|\n requires forall x :: x in s <==> x in t\n requires forall i, j :: (0 <= i < |t| && 0 <= j < |t| && i != j ) ==> t[i] != t[j]\n requires |set x | x in t| == |t| \n ensures |s| == |t|\n decreases s_size {\n if s_size == 0 {\n } else {\n var t_hd;\n t_hd := t[0];\n assert t_hd in s;\n ghost var t_h := set x | x in t[1..];\n assert |t_h| == |t[1..]|; \n memebrship_implies_cardinality_helper(s - {t_hd}, t[1..], s_size - 1);\n }\n}\n\n\nlemma memebrship_implies_cardinality(s: set, t: seq)\n requires forall x :: x in s <==> x in t\n ensures |s| == |t| {\n memebrship_implies_cardinality_helper(s, t, |s|);\n}\n*/\n\nlemma set_memebrship_implies_equality_helper(s: set, t: set, s_size: int)\n requires s_size >= 0 && s_size == |s|\n requires forall x :: x in s <==> x in t\n ensures s == t\n decreases s_size {\n if s_size == 0 {\n } else {\n var s_hd;\n // assign s_hd to a value *such that* s_hd is in s (see such_that expressions)\n s_hd :| s_hd in s;\n set_memebrship_implies_equality_helper(s - {s_hd}, t - {s_hd}, s_size - 1);\n }\n}\n\n\nlemma set_memebrship_implies_equality(s: set, t: set)\n requires forall x :: x in s <==> x in t\n ensures s == t {\n set_memebrship_implies_equality_helper(s, t, |s|);\n}\n\n// TODO play with this for keys==Contents\nlemma set_seq_equality(s: set, t: seq)\n requires distinct(t)\n requires forall x :: x in t <==> x in s\n{\n var s2 : set := set x | x in t;\n set_memebrship_implies_equality_helper(s, s2, |s|);\n assert |s2| == |s|;\n // assert |s2| == |t|;\n // assert |s| == |t|;\n}\n\n\nghost predicate SortedSeq(a: seq)\n //sequence is sorted from left to right\n{\n (forall i,j :: 0<= i< j < |a| ==> ( a[i] < a[j] ))\n}\n\nmethod GetInsertIndex(a: array, limit: int, x:int) returns (idx:int)\n // get index so that array stays sorted\n requires x !in a[..]\n requires 0 <= limit <= a.Length\n requires SortedSeq(a[..limit])\n ensures 0<= idx <= limit\n ensures SortedSeq(a[..limit])\n ensures idx > 0 ==> a[idx-1]< x\n ensures idx < limit ==> x < a[idx]\n{\n idx := limit;\n for i := 0 to limit\n invariant i>0 ==> x > a[i-1]\n {\n if x < a[i] {\n idx := i;\n break;\n }\n }\n}\n\npredicate sorted(a: seq)\n{\n forall i,j :: 0 <= i < j < |a| ==> a[i] < a[j]\n}\n\npredicate distinct(a: seq)\n{\n forall i,j :: (0 <= i < |a| && 0 <= j < |a| && i != j) ==> a[i] != a[j]\n}\n\npredicate sorted_eq(a: seq)\n{\n forall i,j :: 0 <= i < j < |a| ==> a[i] <= a[j]\n}\n\npredicate lessThan(a:seq, key:int) {\n forall i :: 0 <= i < |a| ==> a[i] < key\n}\n\npredicate greaterThan(a:seq, key:int) {\n forall i :: 0 <= i < |a| ==> a[i] > key\n}\n\npredicate greaterEqualThan(a:seq, key:int) {\n forall i :: 0 <= i < |a| ==> a[i] >= key\n}\n/*\nmethod InsertSorted(a: array, key: int ) returns (b: array)\n requires sorted_eq(a[..])\n ensures sorted_eq(b[..])\n{\n b:= new int[a.Length + 1];\n\n ghost var k := 0;\n b[0] := key;\n\n ghost var a' := a[..];\n\n var i:= 0;\n while (i < a.Length)\n modifies b\n invariant 0 <= k <= i <= a.Length\n invariant b.Length == a.Length + 1\n invariant a[..] == a'\n invariant lessThan(a[..i], key) ==> i == k\n invariant lessThan(a[..k], key)\n invariant b[..k] == a[..k]\n invariant b[k] == key\n invariant k < i ==> b[k+1..i+1] == a[k..i]\n invariant k < i ==> greaterEqualThan(b[k+1..i+1], key)\n invariant 0 <= k < b.Length && b[k] == key\n {\n if(a[i]= key)\n {\n b[i+1] := a[i];\n }\n i := i+1;\n }\n assert b[..] == a[..k] + [key] + a[k..];\n\n}\n*/\n\nlemma DistributiveLemma(a: seq, b: seq)\n ensures count(a + b) == count(a) + count(b)\n{\n if a == [] {\n assert a + b == b;\n } else {\n DistributiveLemma(a[1..], b);\n assert a + b == [a[0]] + (a[1..] + b);\n }\n}\nfunction count(a: seq): nat\n{\n if |a| == 0 then 0 else\n (if a[0] then 1 else 0) + count(a[1..])\n}\n\n\nlemma DistributiveIn(a: seq, b:seq, k:int, key:int)\n requires |a| + 1 == |b| \n requires 0 <= k <= |a|\n requires b == a[..k] + [key] + a[k..]\n ensures forall i :: 0 <= i < |a| ==> a[i] in b\n{\n assert forall j :: 0 <= j < k ==> a[j] in b;\n assert forall j :: k <= j < |a| ==> a[j] in b;\n assert ((forall j :: 0 <= j < k ==> a[j] in b) && (forall j :: k <= j < |a| ==> a[j] in b)) ==> (forall j :: 0 <= j < |a| ==> a[j] in b);\n assert forall j :: 0 <= j < |a| ==> a[j] in b;\n}\n\nlemma DistributiveGreater(a: seq, b:seq, k:int, key:int)\n requires |a| + 1 == |b| \n requires 0 <= k <= |a|\n requires b == a[..k] + [key] + a[k..]\n requires forall j :: 0 <= j < |a| ==> a[j] > 0\n requires key > 0\n ensures forall i :: 0 <= i < |b| ==> b[i] > 0\n{\n // assert ((forall j :: 0 <= j < k ==> b[j] > 0) && (forall j :: k <= j < |a| ==> b[j] > 0)) ==> (forall j :: 0 <= j < |b| ==> b[j] > 0);\n assert forall j :: 0 <= j < |b| ==> b[j] > 0;\n}\n\n// verifies in more than 45 seconds, but less than 100 seconds\nmethod InsertIntoSorted(a: array, limit:int, key:int) returns (b: array)\n requires key > 0\n requires key !in a[..]\n requires 0 <= limit < a.Length\n requires forall i :: 0 <= i < limit ==> a[i] > 0\n requires forall i :: limit <= i < a.Length ==> a[i] == 0\n requires sorted(a[..limit]) \n ensures b.Length == a.Length\n ensures sorted(b[..(limit+ 1)])\n ensures forall i :: limit + 1 <= i < b.Length ==> b[i] == 0 \n ensures forall i :: 0 <= i < limit ==> a[i] in b[..]\n ensures forall i :: 0 <= i < limit + 1 ==> b[i] > 0\n{\n b:= new int[a.Length];\n\n ghost var k := 0;\n b[0] := key;\n\n ghost var a' := a[..];\n\n var i:= 0;\n while (i < limit)\n modifies b\n invariant 0 <= k <= i <= limit\n invariant b.Length == a.Length\n invariant a[..] == a'\n invariant lessThan(a[..i], key) ==> i == k\n invariant lessThan(a[..k], key)\n invariant b[..k] == a[..k]\n invariant b[k] == key\n invariant k < i ==> b[k+1..i+1] == a[k..i]\n invariant k < i ==> greaterThan(b[k+1..i+1], key)\n invariant 0 <= k < b.Length && b[k] == key\n {\n if(a[i]= key)\n {\n b[i+1] := a[i];\n } \n i := i+1;\n }\n assert b[..limit+1] == a[..k] + [key] + a[k..limit];\n assert sorted(b[..limit+1]);\n\n // assert b[..limit+1] == a[..k] + [key] + a[k..limit];\n DistributiveIn(a[..limit], b[..limit+1], k, key);\n assert forall i :: 0 <= i < limit ==> a[i] in b[..limit+1];\n\n DistributiveGreater(a[..limit], b[..limit+1], k, key);\n // assert forall i :: 0 <= i < limit + 1 ==> b[i] > 0;\n\n ghost var b' := b[..];\n i := limit + 1;\n while i < b.Length \n invariant limit + 1 <= i <= b.Length \n invariant forall j :: limit + 1 <= j < i ==> b[j] == 0\n invariant b[..limit+1] == b'[..limit+1]\n invariant sorted(b[..limit+1])\n {\n b[i] := 0;\n i := i + 1;\n }\n assert forall i :: limit + 1 <= i < b.Length ==> b[i] == 0;\n\n}\n\n\n\n\n\n \n", "hints_removed": "\n// method CountLessThan(numbers: set, threshold: int) returns (count: int)\n// // ensures count == |set i | i in numbers && i < threshold|\n// ensures count == |SetLessThan(numbers, threshold)|\n// {\n// count := 0;\n// var ss := numbers;\n// while ss != {}\n// decreases |ss|\n// {\n// var i: int :| i in ss;\n// ss := ss - {i};\n// if i < threshold {\n// count := count + 1;\n// }\n\n// }\n// assert count == |SetLessThan(numbers, threshold)|;\n// // assert count == |set i | i in numbers && i < threshold|;\n// }\n\nfunction SetLessThan(numbers: set, threshold: int): set\n{\n set i | i in numbers && i < threshold\n}\n\nmethod Main()\n{\n // var s: set := {1, 2, 3, 4, 5};\n // var c: int := CountLessThan(s, 4);\n // print c;\n // assert c == 3;\n\n\n // if you manualy create set and sequence with same elements, |s|==|t| works\n var t: seq := [1, 2, 3];\n var s: set := {1, 2, 3};\n\n // but if you create set from the sequence with distinct elements it does not understand that |s|==|t|\n // Dafny has problems when reasoning about set sizes ==> \n s := set x | x in t;\n // assert |s| == |t|; // not verifying\n // assert |s| == 3; // not verifying\n\n // other expriments\n set_memebrship_implies_cardinality(s, set x | x in t); // s and the other argument is the same thing\n var s2 : set := set x | x in t;\n\n s2 := {1, 2, 3};\n // assert |s| == |s2|; // may not hold\n set_memebrship_implies_cardinality(s, s2); \n}\n\nlemma set_memebrship_implies_cardinality_helper(s: set, t: set, s_size: int)\n requires s_size >= 0 && s_size == |s|\n requires forall x :: x in s <==> x in t\n ensures |s| == |t|\n if s_size == 0 {\n } else {\n var s_hd;\n // assign s_hd to a value *such that* s_hd is in s (see such_that expressions)\n s_hd :| s_hd in s;\n set_memebrship_implies_cardinality_helper(s - {s_hd}, t - {s_hd}, s_size - 1);\n }\n}\n\n\nlemma set_memebrship_implies_cardinality(s: set, t: set)\n requires forall x :: x in s <==> x in t\n ensures |s| == |t| {\n set_memebrship_implies_cardinality_helper(s, t, |s|);\n}\n\n\n/*\nlemma Bijection(arr: seq, s: set) // returns (bool)\n requires sorted(arr)\n // requires forall x, y :: x in s && y in s && x != y ==> x < y\n ensures |s| == |arr|\n{\n var mapping: map := map[];\n \n // Establish the bijection\n for i := 0 to |arr| {\n mapping := mapping[arr[i]:= arr[i]];\n }\n\n // Prove injectiveness\n\n // Prove surjectiveness\n // assert forall x :: x in s ==> exists i :: 0 <= i < |arr|-1 && arr[i] == x;\n\n // Conclude equinumerosity\n // assert |s| == |arr|;\n // return true;\n}\n*/\n\nfunction seqSet(nums: seq, index: nat): set {\n set x | 0 <= x < index < |nums| :: nums[x]\n}\n\nlemma containsDuplicateI(nums: seq) returns (containsDuplicate: bool)\n ensures containsDuplicate ==> exists i,j :: 0 <= i < j < |nums| && nums[i] == nums[j]\n{\n var windowGhost: set := {};\n var windowSet: set := {};\n for i:= 0 to |nums| \n // invariant forall x :: x in windowSet ==> x in nums\n {\n windowGhost := windowSet;\n if nums[i] in windowSet { // does not verify\n // if nums[i] in seqSet(nums, i) { //verifies\n return true;\n }\n windowSet := windowSet + {nums[i]};\n }\n return false;\n}\n\n// lemma numElemsOfSet(a: seq)\n// requires sorted(a)\n// {\n// assert distinct(a);\n// var s := set x | x in a;\n// assert forall x :: x in s ==> x in a[..];\n// assert forall x :: x in a ==> x in s;\n// assert |s| == |a|;\n// }\n\n// lemma CardinalitySetEqualsArray(a: seq, s: set)\n// requires s == set x | x in a\n// requires distinct(a)\n// ensures |s| == |a|\n// {\n// assert forall x :: x in s ==> exists i :: 0 <= i < |a| && a[i] == x;\n// assert forall i, j :: 0 <= i < |a| && 0 <= j < |a| && i != j ==> a[i] != a[j];\n// // Assert that each element in the array is in the set\n// assert forall i :: 0 <= i < |a| ==> a[i] in s;\n// // Assert that the set contains exactly the elements in the array\n// assert s == set x | x in a;\n// // Assert that the set is a subset of the array\n// assert forall x :: x in s <==> x in a;\n\n// // Conclude the equivalence\n// assert |s| == |a|;\n// }\n\n\n/*\nlemma memebrship_implies_cardinality_helper(s: set, t: seq, s_size: int)\n requires s_size >= 0 && s_size == |s|\n requires forall x :: x in s <==> x in t\n requires forall i, j :: (0 <= i < |t| && 0 <= j < |t| && i != j ) ==> t[i] != t[j]\n requires |set x | x in t| == |t| \n ensures |s| == |t|\n if s_size == 0 {\n } else {\n var t_hd;\n t_hd := t[0];\n ghost var t_h := set x | x in t[1..];\n memebrship_implies_cardinality_helper(s - {t_hd}, t[1..], s_size - 1);\n }\n}\n\n\nlemma memebrship_implies_cardinality(s: set, t: seq)\n requires forall x :: x in s <==> x in t\n ensures |s| == |t| {\n memebrship_implies_cardinality_helper(s, t, |s|);\n}\n*/\n\nlemma set_memebrship_implies_equality_helper(s: set, t: set, s_size: int)\n requires s_size >= 0 && s_size == |s|\n requires forall x :: x in s <==> x in t\n ensures s == t\n if s_size == 0 {\n } else {\n var s_hd;\n // assign s_hd to a value *such that* s_hd is in s (see such_that expressions)\n s_hd :| s_hd in s;\n set_memebrship_implies_equality_helper(s - {s_hd}, t - {s_hd}, s_size - 1);\n }\n}\n\n\nlemma set_memebrship_implies_equality(s: set, t: set)\n requires forall x :: x in s <==> x in t\n ensures s == t {\n set_memebrship_implies_equality_helper(s, t, |s|);\n}\n\n// TODO play with this for keys==Contents\nlemma set_seq_equality(s: set, t: seq)\n requires distinct(t)\n requires forall x :: x in t <==> x in s\n{\n var s2 : set := set x | x in t;\n set_memebrship_implies_equality_helper(s, s2, |s|);\n // assert |s2| == |t|;\n // assert |s| == |t|;\n}\n\n\nghost predicate SortedSeq(a: seq)\n //sequence is sorted from left to right\n{\n (forall i,j :: 0<= i< j < |a| ==> ( a[i] < a[j] ))\n}\n\nmethod GetInsertIndex(a: array, limit: int, x:int) returns (idx:int)\n // get index so that array stays sorted\n requires x !in a[..]\n requires 0 <= limit <= a.Length\n requires SortedSeq(a[..limit])\n ensures 0<= idx <= limit\n ensures SortedSeq(a[..limit])\n ensures idx > 0 ==> a[idx-1]< x\n ensures idx < limit ==> x < a[idx]\n{\n idx := limit;\n for i := 0 to limit\n {\n if x < a[i] {\n idx := i;\n break;\n }\n }\n}\n\npredicate sorted(a: seq)\n{\n forall i,j :: 0 <= i < j < |a| ==> a[i] < a[j]\n}\n\npredicate distinct(a: seq)\n{\n forall i,j :: (0 <= i < |a| && 0 <= j < |a| && i != j) ==> a[i] != a[j]\n}\n\npredicate sorted_eq(a: seq)\n{\n forall i,j :: 0 <= i < j < |a| ==> a[i] <= a[j]\n}\n\npredicate lessThan(a:seq, key:int) {\n forall i :: 0 <= i < |a| ==> a[i] < key\n}\n\npredicate greaterThan(a:seq, key:int) {\n forall i :: 0 <= i < |a| ==> a[i] > key\n}\n\npredicate greaterEqualThan(a:seq, key:int) {\n forall i :: 0 <= i < |a| ==> a[i] >= key\n}\n/*\nmethod InsertSorted(a: array, key: int ) returns (b: array)\n requires sorted_eq(a[..])\n ensures sorted_eq(b[..])\n{\n b:= new int[a.Length + 1];\n\n ghost var k := 0;\n b[0] := key;\n\n ghost var a' := a[..];\n\n var i:= 0;\n while (i < a.Length)\n modifies b\n {\n if(a[i]= key)\n {\n b[i+1] := a[i];\n }\n i := i+1;\n }\n\n}\n*/\n\nlemma DistributiveLemma(a: seq, b: seq)\n ensures count(a + b) == count(a) + count(b)\n{\n if a == [] {\n } else {\n DistributiveLemma(a[1..], b);\n }\n}\nfunction count(a: seq): nat\n{\n if |a| == 0 then 0 else\n (if a[0] then 1 else 0) + count(a[1..])\n}\n\n\nlemma DistributiveIn(a: seq, b:seq, k:int, key:int)\n requires |a| + 1 == |b| \n requires 0 <= k <= |a|\n requires b == a[..k] + [key] + a[k..]\n ensures forall i :: 0 <= i < |a| ==> a[i] in b\n{\n}\n\nlemma DistributiveGreater(a: seq, b:seq, k:int, key:int)\n requires |a| + 1 == |b| \n requires 0 <= k <= |a|\n requires b == a[..k] + [key] + a[k..]\n requires forall j :: 0 <= j < |a| ==> a[j] > 0\n requires key > 0\n ensures forall i :: 0 <= i < |b| ==> b[i] > 0\n{\n // assert ((forall j :: 0 <= j < k ==> b[j] > 0) && (forall j :: k <= j < |a| ==> b[j] > 0)) ==> (forall j :: 0 <= j < |b| ==> b[j] > 0);\n}\n\n// verifies in more than 45 seconds, but less than 100 seconds\nmethod InsertIntoSorted(a: array, limit:int, key:int) returns (b: array)\n requires key > 0\n requires key !in a[..]\n requires 0 <= limit < a.Length\n requires forall i :: 0 <= i < limit ==> a[i] > 0\n requires forall i :: limit <= i < a.Length ==> a[i] == 0\n requires sorted(a[..limit]) \n ensures b.Length == a.Length\n ensures sorted(b[..(limit+ 1)])\n ensures forall i :: limit + 1 <= i < b.Length ==> b[i] == 0 \n ensures forall i :: 0 <= i < limit ==> a[i] in b[..]\n ensures forall i :: 0 <= i < limit + 1 ==> b[i] > 0\n{\n b:= new int[a.Length];\n\n ghost var k := 0;\n b[0] := key;\n\n ghost var a' := a[..];\n\n var i:= 0;\n while (i < limit)\n modifies b\n {\n if(a[i]= key)\n {\n b[i+1] := a[i];\n } \n i := i+1;\n }\n\n // assert b[..limit+1] == a[..k] + [key] + a[k..limit];\n DistributiveIn(a[..limit], b[..limit+1], k, key);\n\n DistributiveGreater(a[..limit], b[..limit+1], k, key);\n // assert forall i :: 0 <= i < limit + 1 ==> b[i] > 0;\n\n ghost var b' := b[..];\n i := limit + 1;\n while i < b.Length \n {\n b[i] := 0;\n i := i + 1;\n }\n\n}\n\n\n\n\n\n \n" }, { "test_ID": "007", "test_file": "BinarySearchTree_tmp_tmp_bn2twp5_bst4copy.dfy", "ground_truth": "datatype Tree = Empty | Node(left: Tree, value: int, right: Tree)\n\npredicate BinarySearchTree(tree: Tree)\n decreases tree\n{\n match tree\n case Empty => true\n case Node(_,_,_) =>\n (tree.left == Empty || tree.left.value < tree.value)\n && (tree.right == Empty || tree.right.value > tree.value)\n && BinarySearchTree(tree.left) && BinarySearchTree(tree.right)\n && minValue(tree.right, tree.value) && maxValue(tree.left, tree.value)\n}\n\npredicate maxValue(tree: Tree, max: int)\n decreases tree\n{\n match tree\n case Empty => true\n case Node(left,v,right) => (max > v) && maxValue(left, max) && maxValue(right, max)\n}\n\npredicate minValue(tree: Tree, min: int)\n decreases tree\n{\n match tree\n case Empty => true\n case Node(left,v,right) => (min < v) && minValue(left, min) && minValue(right, min)\n}\n\nmethod GetMin(tree: Tree) returns (res: int)\n{\n match tree {\n case Empty => res := 0;\n case Node (Empty, value, Empty) => res := tree.value;\n case Node (Empty, value, right) => res := tree.value;\n case Node (left, value, right) =>\n var minval := tree.value;\n minval := GetMin(tree.left);\n var tmp := Node(tree.left, minval, tree.right);\n res := tmp.value;\n }\n}\n\nmethod GetMax(tree: Tree) returns (res: int){\n match tree {\n case Empty => res := 0;\n case Node (Empty, value, Empty) => res := tree.value;\n case Node (left, value, Empty) => res := tree.value;\n case Node (left, value, right) =>\n var minval := tree.value;\n minval := GetMax(tree.right);\n var tmp := Node(tree.left, minval, tree.right);\n res := tmp.value;\n }\n}\n\nmethod insert(tree: Tree, value : int) returns (res: Tree)\n requires BinarySearchTree(tree)\n decreases tree;\n ensures BinarySearchTree(res)\n{\n res := insertRecursion(tree, value);\n}\n\nmethod insertRecursion(tree: Tree, value: int) returns (res: Tree)\n requires BinarySearchTree(tree)\n decreases tree;\n ensures res != Empty ==> BinarySearchTree(res)\n ensures forall x :: minValue(tree, x) && x < value ==> minValue(res, x)\n ensures forall x :: maxValue(tree, x) && x > value ==> maxValue(res, x)\n{\n match tree {\n case Empty => res := Node(Empty, value, Empty);\n case Node(_,_,_) =>\n var temp: Tree;\n if(value == tree.value) {\n return tree;\n }\n if(value < tree.value){\n temp := insertRecursion(tree.left, value);\n res := Node(temp, tree.value, tree.right);\n }else if (value > tree.value){\n temp := insertRecursion(tree.right, value);\n res := Node(tree.left, tree.value, temp);\n }\n }\n}\n\nmethod delete(tree: Tree, value: int) returns (res: Tree)\n requires BinarySearchTree(tree)\n decreases tree;\n //ensures BinarySearchTree(res)\n //ensures res != Empty ==> BinarySearchTree(res)\n{\n match tree {\n case Empty => return tree;\n case Node(_,_ ,_) =>\n var temp: Tree;\n if (value < tree.value){\n temp := delete(tree.left, value);\n res := Node(temp, tree.value, tree.right);\n } else if (value > tree.value){\n temp := delete(tree.right, value);\n res := Node(tree.left, tree.value, temp);\n } else {\n if (tree.left == Empty){\n return tree.right;\n } else if (tree.right == Empty) {\n return tree.left;\n }\n var minVal := GetMin(tree.right);\n temp := delete(tree.right, minVal);\n res := Node(tree.left, minVal, temp);\n //assert BinarySearchTree(res);\n }\n }\n}\n\nmethod Inorder(tree: Tree)\n{\n match tree {\n case Empty =>\n case Node(left, value, right) =>\n Inorder(tree.left);\n print tree.value, \", \";\n Inorder(tree.right);\n }\n}\n\nmethod Postorder(tree: Tree)\n{\n match tree {\n case Empty =>\n case Node(left, value, right) =>\n Postorder(tree.left);\n Postorder(tree.right);\n print tree.value, \", \";\n }\n}\n\nmethod Main() {\n var tree := insert(Empty, 3);\n var u := insert(tree, 2);\n\n u := insert(u, 7);\n u := insert(u, 6);\n u := insert(u, 9);\n\n\n print \"This is Inorder: \";\n Inorder(u);\n print \"\\n\";\n //u := delete (u, 1);\n\n print \"This is Postorder: \";\n Postorder(u);\n print \"\\n\";\n\n print \"tree before delete: \", u, \"\\n\";\n\n u := delete(u, 7);\n print \"tree after delete: \", u, \"\\n\";\n\n print \"This is Inorder: \";\n Inorder(u);\n\n print \"\\n\";\n print \"This is Postorder: \";\n Postorder(u);\n\n // var res := GetMin(u);\n // var max := GetMax(u);\n // print \"this is max: \", max;\n //print \"this is res: \", res;\n\n //print u;\n}\n", "hints_removed": "datatype Tree = Empty | Node(left: Tree, value: int, right: Tree)\n\npredicate BinarySearchTree(tree: Tree)\n{\n match tree\n case Empty => true\n case Node(_,_,_) =>\n (tree.left == Empty || tree.left.value < tree.value)\n && (tree.right == Empty || tree.right.value > tree.value)\n && BinarySearchTree(tree.left) && BinarySearchTree(tree.right)\n && minValue(tree.right, tree.value) && maxValue(tree.left, tree.value)\n}\n\npredicate maxValue(tree: Tree, max: int)\n{\n match tree\n case Empty => true\n case Node(left,v,right) => (max > v) && maxValue(left, max) && maxValue(right, max)\n}\n\npredicate minValue(tree: Tree, min: int)\n{\n match tree\n case Empty => true\n case Node(left,v,right) => (min < v) && minValue(left, min) && minValue(right, min)\n}\n\nmethod GetMin(tree: Tree) returns (res: int)\n{\n match tree {\n case Empty => res := 0;\n case Node (Empty, value, Empty) => res := tree.value;\n case Node (Empty, value, right) => res := tree.value;\n case Node (left, value, right) =>\n var minval := tree.value;\n minval := GetMin(tree.left);\n var tmp := Node(tree.left, minval, tree.right);\n res := tmp.value;\n }\n}\n\nmethod GetMax(tree: Tree) returns (res: int){\n match tree {\n case Empty => res := 0;\n case Node (Empty, value, Empty) => res := tree.value;\n case Node (left, value, Empty) => res := tree.value;\n case Node (left, value, right) =>\n var minval := tree.value;\n minval := GetMax(tree.right);\n var tmp := Node(tree.left, minval, tree.right);\n res := tmp.value;\n }\n}\n\nmethod insert(tree: Tree, value : int) returns (res: Tree)\n requires BinarySearchTree(tree)\n ensures BinarySearchTree(res)\n{\n res := insertRecursion(tree, value);\n}\n\nmethod insertRecursion(tree: Tree, value: int) returns (res: Tree)\n requires BinarySearchTree(tree)\n ensures res != Empty ==> BinarySearchTree(res)\n ensures forall x :: minValue(tree, x) && x < value ==> minValue(res, x)\n ensures forall x :: maxValue(tree, x) && x > value ==> maxValue(res, x)\n{\n match tree {\n case Empty => res := Node(Empty, value, Empty);\n case Node(_,_,_) =>\n var temp: Tree;\n if(value == tree.value) {\n return tree;\n }\n if(value < tree.value){\n temp := insertRecursion(tree.left, value);\n res := Node(temp, tree.value, tree.right);\n }else if (value > tree.value){\n temp := insertRecursion(tree.right, value);\n res := Node(tree.left, tree.value, temp);\n }\n }\n}\n\nmethod delete(tree: Tree, value: int) returns (res: Tree)\n requires BinarySearchTree(tree)\n //ensures BinarySearchTree(res)\n //ensures res != Empty ==> BinarySearchTree(res)\n{\n match tree {\n case Empty => return tree;\n case Node(_,_ ,_) =>\n var temp: Tree;\n if (value < tree.value){\n temp := delete(tree.left, value);\n res := Node(temp, tree.value, tree.right);\n } else if (value > tree.value){\n temp := delete(tree.right, value);\n res := Node(tree.left, tree.value, temp);\n } else {\n if (tree.left == Empty){\n return tree.right;\n } else if (tree.right == Empty) {\n return tree.left;\n }\n var minVal := GetMin(tree.right);\n temp := delete(tree.right, minVal);\n res := Node(tree.left, minVal, temp);\n //assert BinarySearchTree(res);\n }\n }\n}\n\nmethod Inorder(tree: Tree)\n{\n match tree {\n case Empty =>\n case Node(left, value, right) =>\n Inorder(tree.left);\n print tree.value, \", \";\n Inorder(tree.right);\n }\n}\n\nmethod Postorder(tree: Tree)\n{\n match tree {\n case Empty =>\n case Node(left, value, right) =>\n Postorder(tree.left);\n Postorder(tree.right);\n print tree.value, \", \";\n }\n}\n\nmethod Main() {\n var tree := insert(Empty, 3);\n var u := insert(tree, 2);\n\n u := insert(u, 7);\n u := insert(u, 6);\n u := insert(u, 9);\n\n\n print \"This is Inorder: \";\n Inorder(u);\n print \"\\n\";\n //u := delete (u, 1);\n\n print \"This is Postorder: \";\n Postorder(u);\n print \"\\n\";\n\n print \"tree before delete: \", u, \"\\n\";\n\n u := delete(u, 7);\n print \"tree after delete: \", u, \"\\n\";\n\n print \"This is Inorder: \";\n Inorder(u);\n\n print \"\\n\";\n print \"This is Postorder: \";\n Postorder(u);\n\n // var res := GetMin(u);\n // var max := GetMax(u);\n // print \"this is max: \", max;\n //print \"this is res: \", res;\n\n //print u;\n}\n" }, { "test_ID": "008", "test_file": "CO3408-Advanced-Software-Modelling-Assignment-2022-23-Part-2-A-Specification-Spectacular_tmp_tmp4pj4p2zx_car_park.dfy", "ground_truth": "class {:autocontracts} CarPark {\n const totalSpaces: nat := 10;\n const normalSpaces: nat:= 7;\n const reservedSpaces: nat := 3;\n const badParkingBuffer: int := 5;\n\n var weekend: bool;\n var subscriptions: set;\n var carPark: set;\n var reservedCarPark: set;\n\n constructor()\n requires true\n ensures this.subscriptions == {} && this.carPark == {} && this.reservedCarPark == {} && this.weekend == false;\n {\n\n this.subscriptions := {};\n this.carPark := {};\n this.reservedCarPark := {};\n this.weekend := false;\n }\n\n // This predicate checks if the car park is in a valid state at all times.\n // It checks if the sets of cars in the car park and the reserved car park are disjoint and share no values,\n // the total number of cars in the car park is less than or equal to the total number of spaces in\n // the car park plus the bad parking buffer, the number of normal spaces plus reserved spaces is\n // equal to the total number of spaces, and the number of cars in the reserved car park is less than or equal\n // to the number of reserved spaces\n ghost predicate Valid()\n reads this\n {\n carPark * reservedCarPark == {} && |carPark| <= totalSpaces + badParkingBuffer && (normalSpaces + reservedSpaces) == totalSpaces && |reservedCarPark| <= reservedSpaces\n }\n\n // The method maintains the invariant that if success is true, then the car parameter is removed from either\n // the carPark or the reservedCarPark set. Otherwise, neither set is modified\n method leaveCarPark(car: string) returns (success: bool)\n requires true\n modifies this\n ensures success ==> (((car in old(carPark)) && carPark == old(carPark) - {car} && reservedCarPark == old(reservedCarPark)) || ((car in old(reservedCarPark)) && reservedCarPark == old(reservedCarPark) - {car} && carPark == old(carPark)));\n ensures success ==> (car !in carPark) && (car !in reservedCarPark);\n ensures !success ==> carPark == old(carPark) && reservedCarPark == old(reservedCarPark) && (car !in old(carPark)) && (car !in old(reservedCarPark));\n ensures subscriptions == old(subscriptions) && weekend == old(weekend);\n {\n success := false;\n\n if car in carPark {\n carPark := carPark - {car};\n success := true;\n } else if car in reservedCarPark {\n reservedCarPark := reservedCarPark - {car};\n success := true;\n }\n }\n\n // The method maintains the invariant that the number of available spaces availableSpaces is updated correctly\n // based on the current state of the car park and whether it is a weekend or not\n method checkAvailability() returns (availableSpaces: int)\n requires true\n modifies this\n ensures weekend ==> availableSpaces == (normalSpaces - old(|carPark|)) + (reservedSpaces - old(|reservedCarPark|)) - badParkingBuffer;\n ensures !weekend ==> availableSpaces == (normalSpaces - old(|carPark|)) - badParkingBuffer;\n ensures carPark == old(carPark) && reservedCarPark == old(reservedCarPark) && weekend == old(weekend) && subscriptions == old(subscriptions);\n {\n if (weekend){\n availableSpaces := (normalSpaces - |carPark|) + (reservedSpaces - |reservedCarPark|) - badParkingBuffer;\n } else{\n availableSpaces := (normalSpaces - |carPark|) - badParkingBuffer;\n }\n\n }\n\n // The method maintains the invariant that if success is true, then the car parameter is added to the\n // subscriptions set. Otherwise, the subscriptions set is not modified\n method makeSubscription(car: string) returns (success: bool)\n requires true\n modifies this\n ensures success ==> old(|subscriptions|) < reservedSpaces && car !in old(subscriptions) && subscriptions == old(subscriptions) + {car};\n ensures !success ==> subscriptions == old(subscriptions) && (car in old(subscriptions) || old(|subscriptions|) >= reservedSpaces);\n ensures carPark == old(carPark) && reservedCarPark == old(reservedCarPark) && weekend == old(weekend);\n {\n if |subscriptions| >= reservedSpaces || car in subscriptions {\n success := false;\n } else {\n subscriptions := subscriptions + {car};\n success := true;\n }\n }\n\n\n // The method maintains the invariant that the weekend variable is set to true\n method openReservedArea()\n requires true\n modifies this\n ensures carPark == old(carPark) && reservedCarPark == old(reservedCarPark) && weekend == true && subscriptions == old(subscriptions);\n {\n weekend := true;\n }\n\n // The method maintains the invariant that the carPark, reservedCarPark, and subscriptions sets are all cleared\n method closeCarPark()\n requires true\n modifies this\n ensures carPark == {} && reservedCarPark == {} && subscriptions == {}\n ensures weekend == old(weekend);\n\n {\n carPark := {};\n reservedCarPark := {};\n subscriptions := {};\n }\n\n // The method maintains the invariant that if success is true, then the car parameter is added to the carPark\n // set and the number of cars in the carPark set is less than the number of normal spaces minus the bad parking\n // buffer. Otherwise, the carPark and reservedCarPark sets are not modified\n method enterCarPark(car: string) returns (success: bool)\n requires true\n modifies this;\n\n ensures success ==> (car !in old(carPark)) && (car !in old(reservedCarPark)) && (old(|carPark|) < normalSpaces - badParkingBuffer);\n ensures success ==> carPark == old(carPark) + {car};\n ensures !success ==> carPark == old(carPark) && reservedCarPark == old(reservedCarPark);\n ensures !success ==> (car in old(carPark)) || (car in old(reservedCarPark) || (old(|carPark|) >= normalSpaces - badParkingBuffer));\n ensures subscriptions == old(subscriptions) && reservedCarPark == old(reservedCarPark) && weekend == old(weekend);\n\n\n {\n if (|carPark| >= normalSpaces - badParkingBuffer || car in carPark || car in reservedCarPark) {\n return false;\n }\n else\n {\n carPark := carPark + {car};\n return true;\n }\n }\n\n // The method maintains the invariant that if success is true, then the car parameter is added to the\n // reservedCarPark set and the number of cars in the reservedCarPark set is less than the number of\n // reserved spaces and either the weekend variable is true or the car parameter is in the subscriptions set.\n // Otherwise, the carPark and reservedCarPark sets are not modified\n method enterReservedCarPark(car: string) returns (success: bool)\n requires true\n modifies this;\n\n ensures success ==> (car !in old(carPark)) && (car !in old(reservedCarPark)) && (old(|reservedCarPark|) < reservedSpaces) && (car in subscriptions || weekend == true);\n ensures success ==> reservedCarPark == old(reservedCarPark) + {car};\n ensures !success ==> carPark == old(carPark) && reservedCarPark == old(reservedCarPark);\n ensures !success ==> (car in old(carPark)) || (car in old(reservedCarPark) || (old(|reservedCarPark|) >= reservedSpaces) || (car !in subscriptions && weekend == false));\n ensures subscriptions == old(subscriptions) && carPark == old(carPark) && weekend == old(weekend);\n ensures weekend == old(weekend) && subscriptions == old(subscriptions);\n\n\n {\n if (|reservedCarPark| >= reservedSpaces || car in carPark || car in reservedCarPark || (car !in subscriptions && weekend == false)) {\n return false;\n }\n else\n {\n reservedCarPark := reservedCarPark + {car};\n return true;\n }\n }\n}\n\n\nmethod Main() {\n // Initialises car park with 10 spaces, 3 of which are reserved and therefore 7 are normal\n var carPark := new CarPark();\n\n // As we are allowing 5 spaces for idiots who can't park within the lines 7 - 5 == 2\n var availableSpaces := carPark.checkAvailability();\n assert availableSpaces == 2;\n\n // Test entering the car park with one car, One space should now be left\n var success := carPark.enterCarPark(\"car1\");\n availableSpaces := carPark.checkAvailability();\n assert success && carPark.carPark == {\"car1\"} && availableSpaces == 1;\n\n // Test entering the car with another car, No spaces should be left\n success := carPark.enterCarPark(\"car2\");\n availableSpaces := carPark.checkAvailability();\n assert success && \"car2\" in carPark.carPark && carPark.carPark == {\"car1\", \"car2\"} && availableSpaces == 0;\n\n // Test entering with another car, should return invalid as carpark is full\n // normalSpaces = 7, minus 5 spaces because of the bad parking buffer, therefore 2 spaces max\n success := carPark.enterCarPark(\"car3\");\n assert !success && carPark.carPark == {\"car1\", \"car2\"} && carPark.reservedCarPark == {};\n\n // Test creating car subscription\n success := carPark.makeSubscription(\"car4\");\n assert success && carPark.subscriptions == {\"car4\"};\n\n // Test entering the reserved carPark with a valid and an invalid option\n success := carPark.enterReservedCarPark(\"car4\");\n assert success && carPark.reservedCarPark == {\"car4\"};\n // This car doesn't have a subscription so it should not be successful\n success := carPark.enterReservedCarPark(\"car5\");\n assert !success && carPark.reservedCarPark == {\"car4\"};\n\n // Test filling the car subscription list\n success := carPark.makeSubscription(\"car6\");\n assert success && carPark.subscriptions == {\"car4\", \"car6\"};\n success := carPark.makeSubscription(\"car7\");\n assert success && carPark.subscriptions == {\"car4\", \"car6\", \"car7\"};\n // This won't add as reserved spaces are 3 and we can't have more subscriptions than reserved spaces\n success := carPark.makeSubscription(\"car8\");\n assert !success && carPark.subscriptions == {\"car4\", \"car6\", \"car7\"};\n\n // Test filling reserved car park\n success := carPark.enterReservedCarPark(\"car6\");\n assert success && carPark.reservedCarPark == {\"car4\", \"car6\"};\n success := carPark.enterReservedCarPark(\"car7\");\n assert success && carPark.reservedCarPark == {\"car4\", \"car6\", \"car7\"};\n\n // Test leaving car park\n assert carPark.carPark == {\"car1\", \"car2\"};\n success := carPark.leaveCarPark(\"car1\");\n assert success && carPark.carPark == {\"car2\"} && carPark.reservedCarPark == {\"car4\", \"car6\", \"car7\"};\n\n // Test leaving with car that doesn't exist\n assert \"car9\" !in carPark.carPark && \"car9\" !in carPark.reservedCarPark;\n success := carPark.leaveCarPark(\"car9\");\n assert !success && carPark.carPark == {\"car2\"} && carPark.reservedCarPark == {\"car4\", \"car6\", \"car7\"};\n\n // Test leaving reserved car park\n success := carPark.leaveCarPark(\"car6\");\n assert success && carPark.carPark == {\"car2\"} && carPark.reservedCarPark == {\"car4\", \"car7\"};\n\n // Testing closing car park, all cars should be destroyed\n carPark.closeCarPark();\n assert carPark.carPark == {} && carPark.reservedCarPark == {} && carPark.subscriptions == {};\n}\n\n// Added due to timeout in Main\nmethod MainB () {\n var carPark := new CarPark();\n\n // Test opening the reserved carPark\n assert carPark.weekend == false;\n carPark.openReservedArea();\n assert carPark.weekend == true;\n\n // Test joining carPark on weekend with car without subscription\n var success := carPark.enterReservedCarPark(\"car3\");\n assert \"car3\" !in carPark.subscriptions && success && carPark.carPark == {} && carPark.reservedCarPark == {\"car3\"};\n\n // Testing closing car park, all cars should be destroyed\n carPark.closeCarPark();\n assert carPark.carPark == {} && carPark.reservedCarPark == {} && carPark.subscriptions == {};\n}\n", "hints_removed": "class {:autocontracts} CarPark {\n const totalSpaces: nat := 10;\n const normalSpaces: nat:= 7;\n const reservedSpaces: nat := 3;\n const badParkingBuffer: int := 5;\n\n var weekend: bool;\n var subscriptions: set;\n var carPark: set;\n var reservedCarPark: set;\n\n constructor()\n requires true\n ensures this.subscriptions == {} && this.carPark == {} && this.reservedCarPark == {} && this.weekend == false;\n {\n\n this.subscriptions := {};\n this.carPark := {};\n this.reservedCarPark := {};\n this.weekend := false;\n }\n\n // This predicate checks if the car park is in a valid state at all times.\n // It checks if the sets of cars in the car park and the reserved car park are disjoint and share no values,\n // the total number of cars in the car park is less than or equal to the total number of spaces in\n // the car park plus the bad parking buffer, the number of normal spaces plus reserved spaces is\n // equal to the total number of spaces, and the number of cars in the reserved car park is less than or equal\n // to the number of reserved spaces\n ghost predicate Valid()\n reads this\n {\n carPark * reservedCarPark == {} && |carPark| <= totalSpaces + badParkingBuffer && (normalSpaces + reservedSpaces) == totalSpaces && |reservedCarPark| <= reservedSpaces\n }\n\n // The method maintains the invariant that if success is true, then the car parameter is removed from either\n // the carPark or the reservedCarPark set. Otherwise, neither set is modified\n method leaveCarPark(car: string) returns (success: bool)\n requires true\n modifies this\n ensures success ==> (((car in old(carPark)) && carPark == old(carPark) - {car} && reservedCarPark == old(reservedCarPark)) || ((car in old(reservedCarPark)) && reservedCarPark == old(reservedCarPark) - {car} && carPark == old(carPark)));\n ensures success ==> (car !in carPark) && (car !in reservedCarPark);\n ensures !success ==> carPark == old(carPark) && reservedCarPark == old(reservedCarPark) && (car !in old(carPark)) && (car !in old(reservedCarPark));\n ensures subscriptions == old(subscriptions) && weekend == old(weekend);\n {\n success := false;\n\n if car in carPark {\n carPark := carPark - {car};\n success := true;\n } else if car in reservedCarPark {\n reservedCarPark := reservedCarPark - {car};\n success := true;\n }\n }\n\n // The method maintains the invariant that the number of available spaces availableSpaces is updated correctly\n // based on the current state of the car park and whether it is a weekend or not\n method checkAvailability() returns (availableSpaces: int)\n requires true\n modifies this\n ensures weekend ==> availableSpaces == (normalSpaces - old(|carPark|)) + (reservedSpaces - old(|reservedCarPark|)) - badParkingBuffer;\n ensures !weekend ==> availableSpaces == (normalSpaces - old(|carPark|)) - badParkingBuffer;\n ensures carPark == old(carPark) && reservedCarPark == old(reservedCarPark) && weekend == old(weekend) && subscriptions == old(subscriptions);\n {\n if (weekend){\n availableSpaces := (normalSpaces - |carPark|) + (reservedSpaces - |reservedCarPark|) - badParkingBuffer;\n } else{\n availableSpaces := (normalSpaces - |carPark|) - badParkingBuffer;\n }\n\n }\n\n // The method maintains the invariant that if success is true, then the car parameter is added to the\n // subscriptions set. Otherwise, the subscriptions set is not modified\n method makeSubscription(car: string) returns (success: bool)\n requires true\n modifies this\n ensures success ==> old(|subscriptions|) < reservedSpaces && car !in old(subscriptions) && subscriptions == old(subscriptions) + {car};\n ensures !success ==> subscriptions == old(subscriptions) && (car in old(subscriptions) || old(|subscriptions|) >= reservedSpaces);\n ensures carPark == old(carPark) && reservedCarPark == old(reservedCarPark) && weekend == old(weekend);\n {\n if |subscriptions| >= reservedSpaces || car in subscriptions {\n success := false;\n } else {\n subscriptions := subscriptions + {car};\n success := true;\n }\n }\n\n\n // The method maintains the invariant that the weekend variable is set to true\n method openReservedArea()\n requires true\n modifies this\n ensures carPark == old(carPark) && reservedCarPark == old(reservedCarPark) && weekend == true && subscriptions == old(subscriptions);\n {\n weekend := true;\n }\n\n // The method maintains the invariant that the carPark, reservedCarPark, and subscriptions sets are all cleared\n method closeCarPark()\n requires true\n modifies this\n ensures carPark == {} && reservedCarPark == {} && subscriptions == {}\n ensures weekend == old(weekend);\n\n {\n carPark := {};\n reservedCarPark := {};\n subscriptions := {};\n }\n\n // The method maintains the invariant that if success is true, then the car parameter is added to the carPark\n // set and the number of cars in the carPark set is less than the number of normal spaces minus the bad parking\n // buffer. Otherwise, the carPark and reservedCarPark sets are not modified\n method enterCarPark(car: string) returns (success: bool)\n requires true\n modifies this;\n\n ensures success ==> (car !in old(carPark)) && (car !in old(reservedCarPark)) && (old(|carPark|) < normalSpaces - badParkingBuffer);\n ensures success ==> carPark == old(carPark) + {car};\n ensures !success ==> carPark == old(carPark) && reservedCarPark == old(reservedCarPark);\n ensures !success ==> (car in old(carPark)) || (car in old(reservedCarPark) || (old(|carPark|) >= normalSpaces - badParkingBuffer));\n ensures subscriptions == old(subscriptions) && reservedCarPark == old(reservedCarPark) && weekend == old(weekend);\n\n\n {\n if (|carPark| >= normalSpaces - badParkingBuffer || car in carPark || car in reservedCarPark) {\n return false;\n }\n else\n {\n carPark := carPark + {car};\n return true;\n }\n }\n\n // The method maintains the invariant that if success is true, then the car parameter is added to the\n // reservedCarPark set and the number of cars in the reservedCarPark set is less than the number of\n // reserved spaces and either the weekend variable is true or the car parameter is in the subscriptions set.\n // Otherwise, the carPark and reservedCarPark sets are not modified\n method enterReservedCarPark(car: string) returns (success: bool)\n requires true\n modifies this;\n\n ensures success ==> (car !in old(carPark)) && (car !in old(reservedCarPark)) && (old(|reservedCarPark|) < reservedSpaces) && (car in subscriptions || weekend == true);\n ensures success ==> reservedCarPark == old(reservedCarPark) + {car};\n ensures !success ==> carPark == old(carPark) && reservedCarPark == old(reservedCarPark);\n ensures !success ==> (car in old(carPark)) || (car in old(reservedCarPark) || (old(|reservedCarPark|) >= reservedSpaces) || (car !in subscriptions && weekend == false));\n ensures subscriptions == old(subscriptions) && carPark == old(carPark) && weekend == old(weekend);\n ensures weekend == old(weekend) && subscriptions == old(subscriptions);\n\n\n {\n if (|reservedCarPark| >= reservedSpaces || car in carPark || car in reservedCarPark || (car !in subscriptions && weekend == false)) {\n return false;\n }\n else\n {\n reservedCarPark := reservedCarPark + {car};\n return true;\n }\n }\n}\n\n\nmethod Main() {\n // Initialises car park with 10 spaces, 3 of which are reserved and therefore 7 are normal\n var carPark := new CarPark();\n\n // As we are allowing 5 spaces for idiots who can't park within the lines 7 - 5 == 2\n var availableSpaces := carPark.checkAvailability();\n\n // Test entering the car park with one car, One space should now be left\n var success := carPark.enterCarPark(\"car1\");\n availableSpaces := carPark.checkAvailability();\n\n // Test entering the car with another car, No spaces should be left\n success := carPark.enterCarPark(\"car2\");\n availableSpaces := carPark.checkAvailability();\n\n // Test entering with another car, should return invalid as carpark is full\n // normalSpaces = 7, minus 5 spaces because of the bad parking buffer, therefore 2 spaces max\n success := carPark.enterCarPark(\"car3\");\n\n // Test creating car subscription\n success := carPark.makeSubscription(\"car4\");\n\n // Test entering the reserved carPark with a valid and an invalid option\n success := carPark.enterReservedCarPark(\"car4\");\n // This car doesn't have a subscription so it should not be successful\n success := carPark.enterReservedCarPark(\"car5\");\n\n // Test filling the car subscription list\n success := carPark.makeSubscription(\"car6\");\n success := carPark.makeSubscription(\"car7\");\n // This won't add as reserved spaces are 3 and we can't have more subscriptions than reserved spaces\n success := carPark.makeSubscription(\"car8\");\n\n // Test filling reserved car park\n success := carPark.enterReservedCarPark(\"car6\");\n success := carPark.enterReservedCarPark(\"car7\");\n\n // Test leaving car park\n success := carPark.leaveCarPark(\"car1\");\n\n // Test leaving with car that doesn't exist\n success := carPark.leaveCarPark(\"car9\");\n\n // Test leaving reserved car park\n success := carPark.leaveCarPark(\"car6\");\n\n // Testing closing car park, all cars should be destroyed\n carPark.closeCarPark();\n}\n\n// Added due to timeout in Main\nmethod MainB () {\n var carPark := new CarPark();\n\n // Test opening the reserved carPark\n carPark.openReservedArea();\n\n // Test joining carPark on weekend with car without subscription\n var success := carPark.enterReservedCarPark(\"car3\");\n\n // Testing closing car park, all cars should be destroyed\n carPark.closeCarPark();\n}\n" }, { "test_ID": "009", "test_file": "CS494-final-project_tmp_tmp7nof55uq_bubblesort.dfy", "ground_truth": "//Bubblesort CS 494 submission\n//References: https://stackoverflow.com/questions/69364687/how-to-prove-time-complexity-of-bubble-sort-using-dafny/69365785#69365785\n\n\n// predicate checks if elements of a are in ascending order, two additional conditions are added to allow us to sort in specific range within array\npredicate sorted(a:array, from:int, to:int)\n requires a != null; // requires array to have n amount of elements\n reads a; \n requires 0 <= from <= to <= a.Length; // pre condition checks that from is the start of the range and to is the end of the range, requires values to be within 0 - a.Length\n{\n forall x, y :: from <= x < y < to ==> a[x] <= a[y]\n}\n\n//helps ensure swapping is valid, it is used inside the nested while loop to make sure linear order is being kept \npredicate pivot(a:array, to:int, pvt:int)\n requires a != null; // requires array to have n amount of elements\n reads a;\n requires 0 <= pvt < to <= a.Length;\n{\n forall x, y :: 0 <= x < pvt < y < to ==> a[x] <= a[y] // all values within the array should be in ascending order\n}\n\n// Here having the algorithm for the bubblesort\n\nmethod BubbleSort (a: array)\n requires a != null && a.Length > 0; // makes sure a is not empty and length is greater than 0\n modifies a; // as method runs, we are changing a\n ensures sorted(a, 0, a.Length); // makes sure elements of array a are sorted from 0 - a.Length\n ensures multiset(a[..]) == multiset(old(a[..])); // Since a is being modified, we deference the heap \n //and compare the previous elements to current elements.\n{\n var i := 1;\n\n while (i < a.Length)\n invariant i <= a.Length; // more-or-less validates while loop condition during coputations\n invariant sorted(a, 0, i); // Checks that for each increment of i, the array stays sorted, causing the \n invariant multiset(a[..]) == multiset(old(a[..])); //makes sure elements that existed in previous heap for a are presnt in current run\n {\n var j := i;\n\n //this while loop inherits any previous pre/post conditions. It checks that \n while (j > 0)\n invariant multiset(a[..]) == multiset(old(a[..]));\n invariant sorted(a, 0, j); // O(n^2) runtime. Makes sure that a[0] - a[j] is sorted\n invariant sorted(a, j, i+1); // then makes sure from a[j] - a[i+1] is sorted\n invariant pivot(a, i+1, j); // important for ensuring that each computation is correct after swapping\n {\n // Here it also simplifies the remaining invariants to handle the empty array. \n if (a[j-1] > a[j]) { // reverse iterate through range within the array\n a[j - 1], a[j] := a[j], a[j - 1]; // swaps objects if the IF condition is met\n }\n j := j - 1; // decrement j\n }\n i := i+1; // increment i\n }\n\n}\n\n", "hints_removed": "//Bubblesort CS 494 submission\n//References: https://stackoverflow.com/questions/69364687/how-to-prove-time-complexity-of-bubble-sort-using-dafny/69365785#69365785\n\n\n// predicate checks if elements of a are in ascending order, two additional conditions are added to allow us to sort in specific range within array\npredicate sorted(a:array, from:int, to:int)\n requires a != null; // requires array to have n amount of elements\n reads a; \n requires 0 <= from <= to <= a.Length; // pre condition checks that from is the start of the range and to is the end of the range, requires values to be within 0 - a.Length\n{\n forall x, y :: from <= x < y < to ==> a[x] <= a[y]\n}\n\n//helps ensure swapping is valid, it is used inside the nested while loop to make sure linear order is being kept \npredicate pivot(a:array, to:int, pvt:int)\n requires a != null; // requires array to have n amount of elements\n reads a;\n requires 0 <= pvt < to <= a.Length;\n{\n forall x, y :: 0 <= x < pvt < y < to ==> a[x] <= a[y] // all values within the array should be in ascending order\n}\n\n// Here having the algorithm for the bubblesort\n\nmethod BubbleSort (a: array)\n requires a != null && a.Length > 0; // makes sure a is not empty and length is greater than 0\n modifies a; // as method runs, we are changing a\n ensures sorted(a, 0, a.Length); // makes sure elements of array a are sorted from 0 - a.Length\n ensures multiset(a[..]) == multiset(old(a[..])); // Since a is being modified, we deference the heap \n //and compare the previous elements to current elements.\n{\n var i := 1;\n\n while (i < a.Length)\n {\n var j := i;\n\n //this while loop inherits any previous pre/post conditions. It checks that \n while (j > 0)\n {\n // Here it also simplifies the remaining invariants to handle the empty array. \n if (a[j-1] > a[j]) { // reverse iterate through range within the array\n a[j - 1], a[j] := a[j], a[j - 1]; // swaps objects if the IF condition is met\n }\n j := j - 1; // decrement j\n }\n i := i+1; // increment i\n }\n\n}\n\n" }, { "test_ID": "010", "test_file": "CS5232_Project_tmp_tmpai_cfrng_LFUSimple.dfy", "ground_truth": "class LFUCache {\n\n var capacity : int;\n var cacheMap : map; //key -> {value, freq}\n\n constructor(capacity: int)\n requires capacity > 0;\n ensures Valid();\n {\n this.capacity := capacity;\n this.cacheMap := map[];\n }\n\n predicate Valid()\n reads this;\n // reads this.freqMap.Values;\n {\n // general value check\n this.capacity > 0 &&\n 0 <= |cacheMap| <= capacity &&\n (|cacheMap| > 0 ==> (forall e :: e in cacheMap ==> cacheMap[e].1 >= 1)) && // frequency should always larger than 0\n (|cacheMap| > 0 ==> (forall e :: e in cacheMap ==> cacheMap[e].0 >= 0)) // only allow positive values\n } \n\n method getLFUKey() returns (lfuKey : int) \n requires Valid();\n requires |cacheMap| > 0;\n ensures Valid();\n ensures lfuKey in cacheMap;\n ensures forall k :: k in cacheMap.Items ==> cacheMap[lfuKey].1 <= cacheMap[k.0].1;\n {\n \n\n var items := cacheMap.Items;\n var seenItems := {};\n\n var anyItem :| anyItem in items;\n var minFreq := anyItem.1.1;\n lfuKey := anyItem.0;\n\n while items != {}\n decreases |items|;\n invariant cacheMap.Items >= items;\n invariant cacheMap.Items >= seenItems;\n invariant cacheMap.Items == seenItems + items;\n invariant lfuKey in cacheMap;\n invariant cacheMap[lfuKey].1 == minFreq;\n invariant forall e :: e in seenItems ==> minFreq <= e.1.1;\n invariant forall e :: e in seenItems ==> minFreq <= cacheMap[e.0].1;\n invariant forall e :: e in seenItems ==> cacheMap[lfuKey].1 <= cacheMap[e.0].1;\n invariant exists e :: e in seenItems + items ==> minFreq == e.1.1;\n {\n var item :| item in items;\n\n if (item.1.1 < minFreq) {\n lfuKey := item.0;\n minFreq := item.1.1;\n }\n items := items - { item };\n seenItems := seenItems + { item };\n }\n assert seenItems == cacheMap.Items;\n assert cacheMap[lfuKey].1 == minFreq;\n assert forall e :: e in seenItems ==> minFreq <= e.1.1;\n assert forall e :: e in cacheMap.Items ==> minFreq <= e.1.1;\n assert forall k :: k in seenItems ==> cacheMap[lfuKey].1 <= cacheMap[k.0].1;\n assert forall k :: k in cacheMap.Items ==> cacheMap[lfuKey].1 <= cacheMap[k.0].1;\n // assert forall k :: k in cacheMap ==> cacheMap[lfuKey].1 <= cacheMap[k].1; // ????\n return lfuKey;\n }\n\n method get(key: int) returns (value: int)\n requires Valid();\n modifies this;\n ensures Valid();\n ensures key !in cacheMap ==> value == -1;\n ensures forall e :: e in old(cacheMap) <==> e in cacheMap;\n ensures forall e :: e in old(cacheMap) ==> (old(cacheMap[e].0) == cacheMap[e].0);\n ensures key in cacheMap ==> value == cacheMap[key].0 && old(cacheMap[key].1) == cacheMap[key].1-1;\n {\n assert key in cacheMap ==> cacheMap[key].0 >= 0;\n if(key !in cacheMap) {\n value := -1;\n }\n else{\n assert key in cacheMap;\n assert cacheMap[key].0 >= 0;\n value := cacheMap[key].0;\n var oldFreq := cacheMap[key].1;\n var newV := (value, oldFreq + 1);\n cacheMap := cacheMap[key := newV];\n }\n print \"after get: \";\n print cacheMap;\n print \"\\n\";\n return value;\n }\n \n \n method put(key: int, value: int)\n requires Valid();\n requires value > 0;\n modifies this\n ensures Valid();\n \n {\n if (key in cacheMap) {\n var currFreq := cacheMap[key].1;\n cacheMap := cacheMap[key := (value, currFreq)];\n } else {\n if (|cacheMap| < capacity) {\n cacheMap := cacheMap[key := (value, 1)];\n } else {\n var LFUKey := getLFUKey();\n assert LFUKey in cacheMap;\n assert |cacheMap| == capacity;\n ghost var oldMap := cacheMap;\n var newMap := cacheMap - {LFUKey};\n cacheMap := newMap;\n assert newMap == cacheMap - {LFUKey};\n assert LFUKey !in cacheMap;\n assert LFUKey in oldMap;\n ghost var oldCard := |oldMap|;\n ghost var newCard := |newMap|;\n assert |cacheMap.Keys| < |oldMap|; // ????\n cacheMap := cacheMap[key := (value, 1)];\n }\n }\n print \"after put: \";\n print cacheMap;\n print \"\\n\";\n }\n }\n\n method Main()\n {\n var LFUCache := new LFUCache(5);\n print \"Cache Capacity = 5 \\n\";\n print \"PUT (1, 1) - \";\n LFUCache.put(1,1);\n print \"PUT (2, 2) - \";\n LFUCache.put(2,2);\n print \"PUT (3, 3) - \";\n LFUCache.put(3,3);\n print \"GET (1) - \";\n var val := LFUCache.get(1);\n print \"get(1) = \";\n print val;\n print \"\\n\";\n print \"PUT (3, 5) - \";\n LFUCache.put(3,5);\n print \"GET (3) - \";\n val := LFUCache.get(3);\n print \"get(3) = \";\n print val;\n print \"\\n\";\n print \"PUT (4, 6) - \";\n LFUCache.put(4,6);\n print \"PUT (5, 7) - \";\n LFUCache.put(5,7);\n print \"PUT (10, 100) - \";\n LFUCache.put(10,100);\n print \"GET (2) - \";\n val := LFUCache.get(2);\n print \"get(2) = \";\n print val;\n print \"\\n\";\n }\n", "hints_removed": "class LFUCache {\n\n var capacity : int;\n var cacheMap : map; //key -> {value, freq}\n\n constructor(capacity: int)\n requires capacity > 0;\n ensures Valid();\n {\n this.capacity := capacity;\n this.cacheMap := map[];\n }\n\n predicate Valid()\n reads this;\n // reads this.freqMap.Values;\n {\n // general value check\n this.capacity > 0 &&\n 0 <= |cacheMap| <= capacity &&\n (|cacheMap| > 0 ==> (forall e :: e in cacheMap ==> cacheMap[e].1 >= 1)) && // frequency should always larger than 0\n (|cacheMap| > 0 ==> (forall e :: e in cacheMap ==> cacheMap[e].0 >= 0)) // only allow positive values\n } \n\n method getLFUKey() returns (lfuKey : int) \n requires Valid();\n requires |cacheMap| > 0;\n ensures Valid();\n ensures lfuKey in cacheMap;\n ensures forall k :: k in cacheMap.Items ==> cacheMap[lfuKey].1 <= cacheMap[k.0].1;\n {\n \n\n var items := cacheMap.Items;\n var seenItems := {};\n\n var anyItem :| anyItem in items;\n var minFreq := anyItem.1.1;\n lfuKey := anyItem.0;\n\n while items != {}\n {\n var item :| item in items;\n\n if (item.1.1 < minFreq) {\n lfuKey := item.0;\n minFreq := item.1.1;\n }\n items := items - { item };\n seenItems := seenItems + { item };\n }\n // assert forall k :: k in cacheMap ==> cacheMap[lfuKey].1 <= cacheMap[k].1; // ????\n return lfuKey;\n }\n\n method get(key: int) returns (value: int)\n requires Valid();\n modifies this;\n ensures Valid();\n ensures key !in cacheMap ==> value == -1;\n ensures forall e :: e in old(cacheMap) <==> e in cacheMap;\n ensures forall e :: e in old(cacheMap) ==> (old(cacheMap[e].0) == cacheMap[e].0);\n ensures key in cacheMap ==> value == cacheMap[key].0 && old(cacheMap[key].1) == cacheMap[key].1-1;\n {\n if(key !in cacheMap) {\n value := -1;\n }\n else{\n value := cacheMap[key].0;\n var oldFreq := cacheMap[key].1;\n var newV := (value, oldFreq + 1);\n cacheMap := cacheMap[key := newV];\n }\n print \"after get: \";\n print cacheMap;\n print \"\\n\";\n return value;\n }\n \n \n method put(key: int, value: int)\n requires Valid();\n requires value > 0;\n modifies this\n ensures Valid();\n \n {\n if (key in cacheMap) {\n var currFreq := cacheMap[key].1;\n cacheMap := cacheMap[key := (value, currFreq)];\n } else {\n if (|cacheMap| < capacity) {\n cacheMap := cacheMap[key := (value, 1)];\n } else {\n var LFUKey := getLFUKey();\n ghost var oldMap := cacheMap;\n var newMap := cacheMap - {LFUKey};\n cacheMap := newMap;\n ghost var oldCard := |oldMap|;\n ghost var newCard := |newMap|;\n cacheMap := cacheMap[key := (value, 1)];\n }\n }\n print \"after put: \";\n print cacheMap;\n print \"\\n\";\n }\n }\n\n method Main()\n {\n var LFUCache := new LFUCache(5);\n print \"Cache Capacity = 5 \\n\";\n print \"PUT (1, 1) - \";\n LFUCache.put(1,1);\n print \"PUT (2, 2) - \";\n LFUCache.put(2,2);\n print \"PUT (3, 3) - \";\n LFUCache.put(3,3);\n print \"GET (1) - \";\n var val := LFUCache.get(1);\n print \"get(1) = \";\n print val;\n print \"\\n\";\n print \"PUT (3, 5) - \";\n LFUCache.put(3,5);\n print \"GET (3) - \";\n val := LFUCache.get(3);\n print \"get(3) = \";\n print val;\n print \"\\n\";\n print \"PUT (4, 6) - \";\n LFUCache.put(4,6);\n print \"PUT (5, 7) - \";\n LFUCache.put(5,7);\n print \"PUT (10, 100) - \";\n LFUCache.put(10,100);\n print \"GET (2) - \";\n val := LFUCache.get(2);\n print \"get(2) = \";\n print val;\n print \"\\n\";\n }\n" }, { "test_ID": "011", "test_file": "CS5232_Project_tmp_tmpai_cfrng_test.dfy", "ground_truth": "iterator Gen(start: int) yields (x: int)\n yield ensures |xs| <= 10 && x == start + |xs| - 1\n{\n var i := 0;\n while i < 10 invariant |xs| == i {\n x := start + i;\n yield;\n i := i + 1;\n }\n}\n\nmethod Main() {\n var i := new Gen(30);\n while true\n invariant i.Valid() && fresh(i._new)\n decreases 10 - |i.xs|\n {\n var m := i.MoveNext();\n if (!m) {break; }\n print i.x;\n }\n}\n", "hints_removed": "iterator Gen(start: int) yields (x: int)\n yield ensures |xs| <= 10 && x == start + |xs| - 1\n{\n var i := 0;\n while i < 10 invariant |xs| == i {\n x := start + i;\n yield;\n i := i + 1;\n }\n}\n\nmethod Main() {\n var i := new Gen(30);\n while true\n {\n var m := i.MoveNext();\n if (!m) {break; }\n print i.x;\n }\n}\n" }, { "test_ID": "012", "test_file": "CSC8204-Dafny_tmp_tmp11yhjb53_stack.dfy", "ground_truth": "/* \n Dafny Tutorial 2: Sequences and Stacks, Predicates and Assertions\n\n In this tutorial we introduce a simple stack model using the functional \n style of programming.\n \n*/\ntype intStack = seq\n\nfunction isEmpty(s: intStack): bool\n{\n |s| == 0\n}\n\nfunction push(s: intStack, x: int): intStack\n{\n s + [x]\n}\n\nfunction pop(s: intStack): intStack\nrequires !isEmpty(s)\n{\n s[..|s|-1] \n}\n\nmethod testStack() returns (r: intStack)\n{\n var s: intStack := [20, 30, 15, 40, 60, 100, 80];\n\n assert pop(push(s,100)) == s;\n\n assert forall e: int :: 0 <= e < |s| ==> s[e] > 5;\n\n r:= s;\n}\n\nmethod Main()\n{\n var t:=testStack();\n print \"Stack tested\\nStack is \", t, \"\\n\";\n}\n\n", "hints_removed": "/* \n Dafny Tutorial 2: Sequences and Stacks, Predicates and Assertions\n\n In this tutorial we introduce a simple stack model using the functional \n style of programming.\n \n*/\ntype intStack = seq\n\nfunction isEmpty(s: intStack): bool\n{\n |s| == 0\n}\n\nfunction push(s: intStack, x: int): intStack\n{\n s + [x]\n}\n\nfunction pop(s: intStack): intStack\nrequires !isEmpty(s)\n{\n s[..|s|-1] \n}\n\nmethod testStack() returns (r: intStack)\n{\n var s: intStack := [20, 30, 15, 40, 60, 100, 80];\n\n\n\n r:= s;\n}\n\nmethod Main()\n{\n var t:=testStack();\n print \"Stack tested\\nStack is \", t, \"\\n\";\n}\n\n" }, { "test_ID": "013", "test_file": "CSU55004---Formal-Verification_tmp_tmp4ki9iaqy_Project_Project_Part_1_project_pt_1.dfy", "ground_truth": "//This method should return true iff pre is a prefix of str. That is, str starts with pre\nmethod isPrefix(pre:string, str:string) returns(res:bool)\n requires 0 < |pre| <= |str| //This line states that this method requires that pre is less than or equal in length to str. Without this line, an out of bounds error is shown on line 14: \"str[i] != pre[i]\"\n{\n //Initialising the index variable\n var i := 0;\n\n //Iterating through the first |pre| elements in str\n while (i < |pre|)\n invariant 0 <= i <= |pre| //Specifying the range of the while loop\n decreases |pre| - i //Specifying that the while loop will terminate\n {\n //If an element does not match, return false\n if (str[i] != pre[i]) {\n //Debug print\n print str[i], \" != \", pre[i], \"\\n\";\n\n //Return once mismatch detected, no point in iterating any further\n return false;\n }\n //Else loop until mismatch found or we have reached the end of pre\n else{\n //Debug pront\n print str[i], \" == \", pre[i], \"\\n\";\n\n i := i + 1;\n }\n }\n return true;\n}\n\n//This method should return true iff sub is a substring of str. That is, str contains sub\nmethod isSubstring(sub:string, str:string) returns(res:bool)\n requires 0 < |sub| <= |str| //This method requires that sub is less than or equal in length to str\n{\n //Initialising the index variable\n var i := 0;\n\n //This variable stores the difference in length between the two strings\n var n := (|str| - |sub|);\n\n //Here, we want to re-use the \"isPrefix\" method above, so with each iteration of the search, we are passing an offset of str - effectively trimming a character off the front of str and passing it to isPrefix\n //example 1 (sub found in str): \n //str = door & sub = or\n //iteration 1: isPrefix(or, door), returns false, trim & iterate again\n //iteration 2: isprefix(or, oor), returns false, trim & iterate again\n //iteration 3: isPrefix(or, or), returns true, stop iterating\n\n //example 2 (sub not found in str):\n //str = doom & sub = or\n //iteration 1: isPrefix(or, doom), returns false, trim & iterate again\n //iteration 2: isprefix(or, oom), returns false, trim & iterate again\n //iteration 3: isPrefix(or, om), returns false, str is has not been \"trimmed\" to the same length as sub, so we stop iterating\n\n while(i < n+1)\n invariant 0 <= i <= n+1 //Specifying the range of the while loop\n decreases n - i //Specifying that the while loop will terminate\n {\n //Debug print to show what is being passed to isPrefix with each iteration\n print \"\\n\", sub, \", \", str[i..|str|], \"\\n\";\n\n var result:= isPrefix(sub, str[i..|str|]);\n\n //Return once the substring is found, no point in iterating any further\n if(result == true){\n return true;\n }\n //Else loop until sub is found, or we have reached the end of str\n else{\n i := i+1;\n }\n }\n return false;\n}\n\n//This method should return true iff str1 and str1 have a common substring of length k\nmethod haveCommonKSubstring(k:nat, str1:string, str2:string) returns(found:bool)\n requires 0 < k <= |str1| && 0 < k <= |str2| //This method requires that k > 0 and k is less than or equal to in length to str1 and str2\n{\n //Initialising the index variable\n var i := 0;\n\n //This variable is used to define the end condition of the while loop\n var n := |str1|-k;\n\n //Here, we want to re-use the \"isSubstring\" method above, so with each iteration of the search, we are passing a substring of str1 with length k and searching for this substring in str2. If the k-length substring is not found, we \"slide\" the length-k substring \"window\" along and search again\n //example:\n //str1 = operation, str2 = rational, k = 5\n //Iteration 1: isSubstring(opera, rational), returns false, slide the substring & iterate again\n //Iteration 2: isSubstring(perat, rational), returns false, slide the substring & iterate again\n //Iteration 3: isSubstring(erati, rational), returns false, slide the substring & iterate again\n //Iteration 4: isSubstring(ratio, rational), returns true, stop iterating\n\n while(i < n)\n decreases n - i //Specifying that the loop will terminate\n {\n //Debug print to show what is being passed to isSubstring with each iteration\n print \"\\n\", str1[i..i+k], \", \", str2, \"\\n\";\n\n var result := isSubstring(str1[i..i+k], str2);\n\n //Return once the length-k substring is found, no point in iterating any further\n if(result == true){\n return true;\n }\n //Else loop until the length-k substring is found, or we have reached the end condition\n else{\n i:=i+1;\n }\n }\n return false;\n}\n\n//This method should return the natural number len which is equal to the length of the longest common substring of str1 and str2. Note that every two strings have a common substring of length zero.\nmethod maxCommonSubstringLength(str1:string, str2:string) returns(len:nat)\n requires 0 < |str1| && 0 < |str1|\n{\n //This variable is used to store the result of calling haveCommonKSubstring\n var result:bool;\n \n //We want the longest common substring between str1 and str2, so the starting point is going to be the shorter of the two strings.\n var i:= |str1|;\n if(|str2| < |str1|){\n i := |str2|;\n }\n\n //Here, we want to re-use the \"haveKCommonSubstring\" method above, so with each iteration of the search, we pass a decreasing value of k until a common substring of this length is found. If no common substring is found, we return 0.\n while (i > 0)\n decreases i - 0\n {\n print str1, \", \", str2, \" k = \", i, \"\\n\";\n \n result := haveCommonKSubstring(i, str1, str2);\n\n if(result == true){\n return i;\n }\n else{\n i := i - 1;\n }\n }\n return 0;\n}\n\n//Main to test each method\nmethod Main(){\n // isPrefix test\n var prefix:string := \"pre\";\n var str_1:string := \"prehistoric\";\n var result:bool;\n /*\n result := isPrefix(prefix, str_1);\n\n if(result == true){\n print \"TRUE: \", prefix, \" is a prefix of the string \", str_1, \"\\n\";\n }\n else{\n print \"FALSE: \", prefix, \" is not a prefix of the string \", str_1, \"\\n\";\n }\n */\n // isSubstring test\n var substring := \"and\";\n var str_2 := \"operand\";\n /*\n result := isSubstring(substring, str_2);\n\n if(result == true){\n print \"TRUE: \", substring, \" is a substring of the string \", str_2, \"\\n\";\n }\n else{\n print \"FALSE: \", substring, \" is not a substring of the string \", str_2, \"\\n\";\n }\n */\n // haveCommonKSubstring test\n //these 2 strings share the common substring \"ratio\" of length 5\n var string1 := \"operation\";\n var string2 := \"irrational\";\n var k:nat := 5;\n /*\n result := haveCommonKSubstring(k, string1, string2);\n\n if(result == true){\n print \"TRUE: \", string1, \" and \", string2, \" have a common substring of length \", k, \"\\n\";\n }\n else{\n print \"FALSE: \", string1, \" and \", string2, \" do not have a common substring of length \", k, \"\\n\";\n }\n */\n\n var x := maxCommonSubstringLength(string1, string2);\n print \"Result: \", x, \"\\n\";\n}\n\n", "hints_removed": "//This method should return true iff pre is a prefix of str. That is, str starts with pre\nmethod isPrefix(pre:string, str:string) returns(res:bool)\n requires 0 < |pre| <= |str| //This line states that this method requires that pre is less than or equal in length to str. Without this line, an out of bounds error is shown on line 14: \"str[i] != pre[i]\"\n{\n //Initialising the index variable\n var i := 0;\n\n //Iterating through the first |pre| elements in str\n while (i < |pre|)\n {\n //If an element does not match, return false\n if (str[i] != pre[i]) {\n //Debug print\n print str[i], \" != \", pre[i], \"\\n\";\n\n //Return once mismatch detected, no point in iterating any further\n return false;\n }\n //Else loop until mismatch found or we have reached the end of pre\n else{\n //Debug pront\n print str[i], \" == \", pre[i], \"\\n\";\n\n i := i + 1;\n }\n }\n return true;\n}\n\n//This method should return true iff sub is a substring of str. That is, str contains sub\nmethod isSubstring(sub:string, str:string) returns(res:bool)\n requires 0 < |sub| <= |str| //This method requires that sub is less than or equal in length to str\n{\n //Initialising the index variable\n var i := 0;\n\n //This variable stores the difference in length between the two strings\n var n := (|str| - |sub|);\n\n //Here, we want to re-use the \"isPrefix\" method above, so with each iteration of the search, we are passing an offset of str - effectively trimming a character off the front of str and passing it to isPrefix\n //example 1 (sub found in str): \n //str = door & sub = or\n //iteration 1: isPrefix(or, door), returns false, trim & iterate again\n //iteration 2: isprefix(or, oor), returns false, trim & iterate again\n //iteration 3: isPrefix(or, or), returns true, stop iterating\n\n //example 2 (sub not found in str):\n //str = doom & sub = or\n //iteration 1: isPrefix(or, doom), returns false, trim & iterate again\n //iteration 2: isprefix(or, oom), returns false, trim & iterate again\n //iteration 3: isPrefix(or, om), returns false, str is has not been \"trimmed\" to the same length as sub, so we stop iterating\n\n while(i < n+1)\n {\n //Debug print to show what is being passed to isPrefix with each iteration\n print \"\\n\", sub, \", \", str[i..|str|], \"\\n\";\n\n var result:= isPrefix(sub, str[i..|str|]);\n\n //Return once the substring is found, no point in iterating any further\n if(result == true){\n return true;\n }\n //Else loop until sub is found, or we have reached the end of str\n else{\n i := i+1;\n }\n }\n return false;\n}\n\n//This method should return true iff str1 and str1 have a common substring of length k\nmethod haveCommonKSubstring(k:nat, str1:string, str2:string) returns(found:bool)\n requires 0 < k <= |str1| && 0 < k <= |str2| //This method requires that k > 0 and k is less than or equal to in length to str1 and str2\n{\n //Initialising the index variable\n var i := 0;\n\n //This variable is used to define the end condition of the while loop\n var n := |str1|-k;\n\n //Here, we want to re-use the \"isSubstring\" method above, so with each iteration of the search, we are passing a substring of str1 with length k and searching for this substring in str2. If the k-length substring is not found, we \"slide\" the length-k substring \"window\" along and search again\n //example:\n //str1 = operation, str2 = rational, k = 5\n //Iteration 1: isSubstring(opera, rational), returns false, slide the substring & iterate again\n //Iteration 2: isSubstring(perat, rational), returns false, slide the substring & iterate again\n //Iteration 3: isSubstring(erati, rational), returns false, slide the substring & iterate again\n //Iteration 4: isSubstring(ratio, rational), returns true, stop iterating\n\n while(i < n)\n {\n //Debug print to show what is being passed to isSubstring with each iteration\n print \"\\n\", str1[i..i+k], \", \", str2, \"\\n\";\n\n var result := isSubstring(str1[i..i+k], str2);\n\n //Return once the length-k substring is found, no point in iterating any further\n if(result == true){\n return true;\n }\n //Else loop until the length-k substring is found, or we have reached the end condition\n else{\n i:=i+1;\n }\n }\n return false;\n}\n\n//This method should return the natural number len which is equal to the length of the longest common substring of str1 and str2. Note that every two strings have a common substring of length zero.\nmethod maxCommonSubstringLength(str1:string, str2:string) returns(len:nat)\n requires 0 < |str1| && 0 < |str1|\n{\n //This variable is used to store the result of calling haveCommonKSubstring\n var result:bool;\n \n //We want the longest common substring between str1 and str2, so the starting point is going to be the shorter of the two strings.\n var i:= |str1|;\n if(|str2| < |str1|){\n i := |str2|;\n }\n\n //Here, we want to re-use the \"haveKCommonSubstring\" method above, so with each iteration of the search, we pass a decreasing value of k until a common substring of this length is found. If no common substring is found, we return 0.\n while (i > 0)\n {\n print str1, \", \", str2, \" k = \", i, \"\\n\";\n \n result := haveCommonKSubstring(i, str1, str2);\n\n if(result == true){\n return i;\n }\n else{\n i := i - 1;\n }\n }\n return 0;\n}\n\n//Main to test each method\nmethod Main(){\n // isPrefix test\n var prefix:string := \"pre\";\n var str_1:string := \"prehistoric\";\n var result:bool;\n /*\n result := isPrefix(prefix, str_1);\n\n if(result == true){\n print \"TRUE: \", prefix, \" is a prefix of the string \", str_1, \"\\n\";\n }\n else{\n print \"FALSE: \", prefix, \" is not a prefix of the string \", str_1, \"\\n\";\n }\n */\n // isSubstring test\n var substring := \"and\";\n var str_2 := \"operand\";\n /*\n result := isSubstring(substring, str_2);\n\n if(result == true){\n print \"TRUE: \", substring, \" is a substring of the string \", str_2, \"\\n\";\n }\n else{\n print \"FALSE: \", substring, \" is not a substring of the string \", str_2, \"\\n\";\n }\n */\n // haveCommonKSubstring test\n //these 2 strings share the common substring \"ratio\" of length 5\n var string1 := \"operation\";\n var string2 := \"irrational\";\n var k:nat := 5;\n /*\n result := haveCommonKSubstring(k, string1, string2);\n\n if(result == true){\n print \"TRUE: \", string1, \" and \", string2, \" have a common substring of length \", k, \"\\n\";\n }\n else{\n print \"FALSE: \", string1, \" and \", string2, \" do not have a common substring of length \", k, \"\\n\";\n }\n */\n\n var x := maxCommonSubstringLength(string1, string2);\n print \"Result: \", x, \"\\n\";\n}\n\n" }, { "test_ID": "014", "test_file": "CVS-Projto1_tmp_tmpb1o0bu8z_Hoare.dfy", "ground_truth": "method Max (x: nat, y:nat) returns (r:nat)\n ensures (r >= x && r >=y)\n ensures (r == x || r == y)\n{\n if (x >= y) { r := x;}\n else { r := y;}\n}\n\nmethod Test ()\n{\n var result := Max(42, 73);\n assert result == 73;\n}\n\nmethod m1 (x: int, y: int) returns (z: int)\nrequires 0 < x < y\nensures z >= 0 && z <= y && z != x\n{\n //assume 0 < x < y\n z := 0;\n}\n\n\n\nfunction fib (n: nat) : nat\n{\n if n == 0 then 1 else\n if n == 1 then 1 else\n fib(n -1) + fib (n-2)\n}\n\nmethod Fib (n: nat) returns (r:nat)\n ensures r == fib(n)\n{\n\n if (n == 0) {\n return 1;\n }\n r := 1;\n var next:=2;\n var i := 1;\n while i < n\n invariant 1 <= i <= n\n invariant r == fib(i)\n invariant next == fib(i+1)\n {\n var tmp:=next;\n next:= next + r;\n r:= tmp;\n i:= i + 1;\n }\n assert r == fib(n);\n return r;\n}\n\n\ndatatype List = Nil | Cons(head: T, tail: List)\n\nfunction add(l:List) : int\n{\n match l\n case Nil => 0\n case Cons(x, xs) => x + add(xs)\n}\n\n\nmethod addImp (l: List) returns (s: int)\n ensures s == add(l)\n{\n var ll := l;\n s := 0;\n while ll != Nil\n decreases ll\n invariant add(l) == s + add(ll)\n {\n s := s + ll.head;\n ll:= ll.tail;\n }\n assert s == add(l);\n}\n\n\nmethod MaxA (a: array) returns (m: int)\n requires a.Length > 0\n ensures forall i :: 0 <= i < a.Length ==> a[i] <= m\n ensures exists i :: 0 <= i < a.Length && a[i] == m\n{\n m := a[0];\n var i := 1;\n while i< a.Length\n invariant 1 <= i <= a.Length\n invariant forall j :: 0 <= j < i ==> a[j] <=m\n invariant exists j :: 0 <= j < i && a[j] ==m\n {\n if a[i] > m {\n m:= a[i];\n }\n i := i +1;\n }\n}\n\n", "hints_removed": "method Max (x: nat, y:nat) returns (r:nat)\n ensures (r >= x && r >=y)\n ensures (r == x || r == y)\n{\n if (x >= y) { r := x;}\n else { r := y;}\n}\n\nmethod Test ()\n{\n var result := Max(42, 73);\n}\n\nmethod m1 (x: int, y: int) returns (z: int)\nrequires 0 < x < y\nensures z >= 0 && z <= y && z != x\n{\n //assume 0 < x < y\n z := 0;\n}\n\n\n\nfunction fib (n: nat) : nat\n{\n if n == 0 then 1 else\n if n == 1 then 1 else\n fib(n -1) + fib (n-2)\n}\n\nmethod Fib (n: nat) returns (r:nat)\n ensures r == fib(n)\n{\n\n if (n == 0) {\n return 1;\n }\n r := 1;\n var next:=2;\n var i := 1;\n while i < n\n {\n var tmp:=next;\n next:= next + r;\n r:= tmp;\n i:= i + 1;\n }\n return r;\n}\n\n\ndatatype List = Nil | Cons(head: T, tail: List)\n\nfunction add(l:List) : int\n{\n match l\n case Nil => 0\n case Cons(x, xs) => x + add(xs)\n}\n\n\nmethod addImp (l: List) returns (s: int)\n ensures s == add(l)\n{\n var ll := l;\n s := 0;\n while ll != Nil\n {\n s := s + ll.head;\n ll:= ll.tail;\n }\n}\n\n\nmethod MaxA (a: array) returns (m: int)\n requires a.Length > 0\n ensures forall i :: 0 <= i < a.Length ==> a[i] <= m\n ensures exists i :: 0 <= i < a.Length && a[i] == m\n{\n m := a[0];\n var i := 1;\n while i< a.Length\n {\n if a[i] > m {\n m:= a[i];\n }\n i := i +1;\n }\n}\n\n" }, { "test_ID": "015", "test_file": "CVS-Projto1_tmp_tmpb1o0bu8z_fact.dfy", "ground_truth": "function fact (n:nat): nat\n decreases n\n{if n == 0 then 1 else n * fact(n-1)}\n\nfunction factAcc (n:nat, a:int): int\n decreases n\n{if (n==0) then a else factAcc(n-1,n*a)}\n\nfunction factAlt(n:nat):int\n{factAcc(n,1)}\n\nlemma factAcc_correct (n:nat, a:int)\n ensures factAcc(n, a) == a*fact(n)\n{\n}\n\nlemma factAlt_correct (n:nat)\n ensures factAlt(n) == fact(n)\n{\n factAcc_correct(n,1);\n assert factAcc(n,1) == 1 * fact(n);\n assert 1 * fact(n) == fact(n);\n assert factAlt(n) == factAcc(n, 1);\n}\n\ndatatype List = Nil | Cons(T, List)\n\nfunction length (l: List) : nat\ndecreases l\n{\n match l\n case Nil => 0\n case Cons(_, r) => 1 + length(r)\n}\n\nlemma {:induction false} length_non_neg (l:List)\n ensures length(l) >= 0\n{\n match l\n case Nil =>\n case Cons(_, r) =>\n length_non_neg(r);\n assert length(r) >= 0;\n // assert forall k : int :: k >= 0 ==> 1 + k >= 0;\n assert 1 + length(r) >= 0;\n assert 1 + length(r) == length(l);\n}\n\nfunction lengthTL (l: List, acc: nat) : nat\n{\n match l\n case Nil => acc\n case Cons(_, r) => lengthTL(r, 1 + acc)\n}\nlemma {:induction false}lengthTL_aux (l: List, acc: nat)\n ensures lengthTL(l, acc) == acc + length(l)\n{\n match l\n case Nil => assert acc + length(Nil) == acc;\n case Cons(_, r) =>\n lengthTL_aux(r, acc + 1);\n}\nlemma lengthEq (l: List)\n ensures length(l) == lengthTL(l,0)\n{\n lengthTL_aux(l, 0);\n}\n\n", "hints_removed": "function fact (n:nat): nat\n{if n == 0 then 1 else n * fact(n-1)}\n\nfunction factAcc (n:nat, a:int): int\n{if (n==0) then a else factAcc(n-1,n*a)}\n\nfunction factAlt(n:nat):int\n{factAcc(n,1)}\n\nlemma factAcc_correct (n:nat, a:int)\n ensures factAcc(n, a) == a*fact(n)\n{\n}\n\nlemma factAlt_correct (n:nat)\n ensures factAlt(n) == fact(n)\n{\n factAcc_correct(n,1);\n}\n\ndatatype List = Nil | Cons(T, List)\n\nfunction length (l: List) : nat\n{\n match l\n case Nil => 0\n case Cons(_, r) => 1 + length(r)\n}\n\nlemma {:induction false} length_non_neg (l:List)\n ensures length(l) >= 0\n{\n match l\n case Nil =>\n case Cons(_, r) =>\n length_non_neg(r);\n // assert forall k : int :: k >= 0 ==> 1 + k >= 0;\n}\n\nfunction lengthTL (l: List, acc: nat) : nat\n{\n match l\n case Nil => acc\n case Cons(_, r) => lengthTL(r, 1 + acc)\n}\nlemma {:induction false}lengthTL_aux (l: List, acc: nat)\n ensures lengthTL(l, acc) == acc + length(l)\n{\n match l\n case Nil => assert acc + length(Nil) == acc;\n case Cons(_, r) =>\n lengthTL_aux(r, acc + 1);\n}\nlemma lengthEq (l: List)\n ensures length(l) == lengthTL(l,0)\n{\n lengthTL_aux(l, 0);\n}\n\n" }, { "test_ID": "016", "test_file": "CVS-Projto1_tmp_tmpb1o0bu8z_proj1_proj1.dfy", "ground_truth": "//Exercicio 1.a)\nfunction sum (a:array, i:int, j:int) :int\ndecreases j\nreads a\nrequires 0 <= i <= j <= a.Length\n{\n if i == j then\n 0\n else\n a[j-1] + sum(a, i, j-1)\n}\n\n//Exercicio 1.b)\nmethod query (a:array, i:int, j:int) returns (s:int)\nrequires 0 <= i <= j <= a.Length\nensures s == sum(a, i, j)\n{\n s := 0;\n var aux := i;\n\n while (aux < j)\n invariant i <= aux <= j\n invariant s == sum(a, i, aux)\n decreases j - aux\n {\n s := s + a[aux];\n aux := aux + 1;\n }\n return s;\n}\n\n//Exercicio 1.c)\nlemma queryLemma(a:array, i:int, j:int, k:int)\n requires 0 <= i <= k <= j <= a.Length\n ensures sum(a,i,k) + sum(a,k,j) == sum(a,i,j)\n{\n}\n\nmethod queryFast (a:array, c:array, i:int, j:int) returns (r:int)\nrequires is_prefix_sum_for(a,c) && 0 <= i <= j <= a.Length < c.Length\nensures r == sum(a, i,j)\n{\n r := c[j] - c[i];\n queryLemma(a,0,j,i);\n\n return r;\n}\n\npredicate is_prefix_sum_for (a:array, c:array)\nreads c, a\n{\n a.Length + 1 == c.Length\n && c[0] == 0\n && forall j :: 1 <= j <= a.Length ==> c[j] == sum(a,0,j)\n}\n\n///Exercicio 2.\ndatatype List = Nil | Cons(head: T, tail: List)\n\nmethod from_array(a: array) returns (l: List)\nrequires a.Length > 0\nensures forall j::0 <= j < a.Length ==> mem(a[j],l)\n{\n var i:= a.Length-1;\n l:= Nil;\n\n while (i >= 0)\n invariant -1 <= i < a. Length\n invariant forall j:: i+1 <= j < a.Length ==> mem(a[j],l)\n {\n l := Cons(a[i], l);\n i := i - 1;\n }\n\n return l;\n}\n\nfunction mem (x: T, l:List) : bool\ndecreases l\n{\n match l\n case Nil => false\n case Cons(y,r)=> if (x==y) then true else mem(x,r)\n}\n\n", "hints_removed": "//Exercicio 1.a)\nfunction sum (a:array, i:int, j:int) :int\nreads a\nrequires 0 <= i <= j <= a.Length\n{\n if i == j then\n 0\n else\n a[j-1] + sum(a, i, j-1)\n}\n\n//Exercicio 1.b)\nmethod query (a:array, i:int, j:int) returns (s:int)\nrequires 0 <= i <= j <= a.Length\nensures s == sum(a, i, j)\n{\n s := 0;\n var aux := i;\n\n while (aux < j)\n {\n s := s + a[aux];\n aux := aux + 1;\n }\n return s;\n}\n\n//Exercicio 1.c)\nlemma queryLemma(a:array, i:int, j:int, k:int)\n requires 0 <= i <= k <= j <= a.Length\n ensures sum(a,i,k) + sum(a,k,j) == sum(a,i,j)\n{\n}\n\nmethod queryFast (a:array, c:array, i:int, j:int) returns (r:int)\nrequires is_prefix_sum_for(a,c) && 0 <= i <= j <= a.Length < c.Length\nensures r == sum(a, i,j)\n{\n r := c[j] - c[i];\n queryLemma(a,0,j,i);\n\n return r;\n}\n\npredicate is_prefix_sum_for (a:array, c:array)\nreads c, a\n{\n a.Length + 1 == c.Length\n && c[0] == 0\n && forall j :: 1 <= j <= a.Length ==> c[j] == sum(a,0,j)\n}\n\n///Exercicio 2.\ndatatype List = Nil | Cons(head: T, tail: List)\n\nmethod from_array(a: array) returns (l: List)\nrequires a.Length > 0\nensures forall j::0 <= j < a.Length ==> mem(a[j],l)\n{\n var i:= a.Length-1;\n l:= Nil;\n\n while (i >= 0)\n {\n l := Cons(a[i], l);\n i := i - 1;\n }\n\n return l;\n}\n\nfunction mem (x: T, l:List) : bool\n{\n match l\n case Nil => false\n case Cons(y,r)=> if (x==y) then true else mem(x,r)\n}\n\n" }, { "test_ID": "017", "test_file": "CVS-Projto1_tmp_tmpb1o0bu8z_searchSort.dfy", "ground_truth": "method fillK(a: array, n: int, k: int, c: int) returns (b: bool)\n requires 0 <= c <= n\n requires n == a.Length\n{\n if c == 0 {\n return true;\n }\n\n var p := 0;\n while p < c\n invariant 0 <= p <= c\n\n {\n if a[p] != k\n {\n return false;\n }\n\n p := p + 1;\n }\n return true;\n\n}\n\n\nmethod containsSubString(a: array, b: array) returns (pos: int)\n requires 0 <= b.Length <= a.Length\n{\n pos := -1;\n\n if b.Length == 0 {\n return pos;\n }\n\n var p := 0;\n\n while p < a.Length\n invariant 0 <= p <= a.Length\n {\n if a.Length - p < b.Length\n {\n return pos;\n }\n\n if a[p] == b[0] {\n\n var i := 0;\n while i < b.Length\n {\n if a[i + p] != b[i] {\n return -1;\n }\n i:= i + 1;\n }\n pos := p;\n return pos;\n }\n\n p:= p +1;\n }\n\n}\n\n", "hints_removed": "method fillK(a: array, n: int, k: int, c: int) returns (b: bool)\n requires 0 <= c <= n\n requires n == a.Length\n{\n if c == 0 {\n return true;\n }\n\n var p := 0;\n while p < c\n\n {\n if a[p] != k\n {\n return false;\n }\n\n p := p + 1;\n }\n return true;\n\n}\n\n\nmethod containsSubString(a: array, b: array) returns (pos: int)\n requires 0 <= b.Length <= a.Length\n{\n pos := -1;\n\n if b.Length == 0 {\n return pos;\n }\n\n var p := 0;\n\n while p < a.Length\n {\n if a.Length - p < b.Length\n {\n return pos;\n }\n\n if a[p] == b[0] {\n\n var i := 0;\n while i < b.Length\n {\n if a[i + p] != b[i] {\n return -1;\n }\n i:= i + 1;\n }\n pos := p;\n return pos;\n }\n\n p:= p +1;\n }\n\n}\n\n" }, { "test_ID": "018", "test_file": "CVS-handout1_tmp_tmptm52no3k_1.dfy", "ground_truth": "/* Cumulative Sums over Arrays */\n\n/*\n Daniel Cavalheiro 57869\n Pedro Nunes 57854\n*/\n\n\n\n//(a)\n\nfunction sum(a: array, i: int, j: int): int\n reads a\n requires 0 <= i <= j <= a.Length\n decreases j - i\n{\n if (i == j) then 0\n else a[i] + sum(a, i+1, j)\n}\n\n\n\n//(b)\n\nmethod query(a: array, i: int, j: int) returns (res:int)\n requires 0 <= i <= j <= a.Length\n ensures res == sum(a, i, j)\n{\n res := 0;\n var k := i;\n\n while(k < j)\n invariant i <= k <= j <= a.Length\n invariant res + sum(a, k, j) == sum(a, i, j)\n {\n res := res + a[k];\n k := k + 1;\n }\n \n}\n\n\n\n//(c)\n\npredicate is_prefix_sum_for (a: array, c: array)\n requires a.Length + 1 == c.Length\n requires c[0] == 0\n reads c, a\n{\n forall i: int :: 0 <= i < a.Length ==> c[i+1] == c[i] + a[i]\n}\n\nlemma aux(a: array, c: array, i: int, j: int)\n requires 0 <= i <= j <= a.Length\n requires a.Length + 1 == c.Length\n requires c[0] == 0\n requires is_prefix_sum_for(a, c)\n decreases j - i\n ensures forall k: int :: i <= k <= j ==> sum(a, i, k) + sum(a, k, j) == c[k] - c[i] + c[j] - c[k] //sum(a, i, j) == c[j] - c[i]\n{}\n\n\nmethod queryFast(a: array, c: array, i: int, j: int) returns (r: int)\n requires a.Length + 1 == c.Length && c[0] == 0\n requires 0 <= i <= j <= a.Length\n requires is_prefix_sum_for(a,c) \n ensures r == sum(a, i, j)\n{ \n aux(a, c, i, j);\n r := c[j] - c[i]; \n}\n\n\n\n\nmethod Main()\n{\n var x := new int[10];\n x[0], x[1], x[2], x[3] := 2, 2, 1, 5;\n var y := sum(x, 0, x.Length);\n //assert y == 10;\n var c := new int[11];\n c[0], c[1], c[2], c[3], c[4] := 0, 2, 4, 5, 10;\n // var r := queryFast(x, c, 0, x.Length);\n \n}\n", "hints_removed": "/* Cumulative Sums over Arrays */\n\n/*\n Daniel Cavalheiro 57869\n Pedro Nunes 57854\n*/\n\n\n\n//(a)\n\nfunction sum(a: array, i: int, j: int): int\n reads a\n requires 0 <= i <= j <= a.Length\n{\n if (i == j) then 0\n else a[i] + sum(a, i+1, j)\n}\n\n\n\n//(b)\n\nmethod query(a: array, i: int, j: int) returns (res:int)\n requires 0 <= i <= j <= a.Length\n ensures res == sum(a, i, j)\n{\n res := 0;\n var k := i;\n\n while(k < j)\n {\n res := res + a[k];\n k := k + 1;\n }\n \n}\n\n\n\n//(c)\n\npredicate is_prefix_sum_for (a: array, c: array)\n requires a.Length + 1 == c.Length\n requires c[0] == 0\n reads c, a\n{\n forall i: int :: 0 <= i < a.Length ==> c[i+1] == c[i] + a[i]\n}\n\nlemma aux(a: array, c: array, i: int, j: int)\n requires 0 <= i <= j <= a.Length\n requires a.Length + 1 == c.Length\n requires c[0] == 0\n requires is_prefix_sum_for(a, c)\n ensures forall k: int :: i <= k <= j ==> sum(a, i, k) + sum(a, k, j) == c[k] - c[i] + c[j] - c[k] //sum(a, i, j) == c[j] - c[i]\n{}\n\n\nmethod queryFast(a: array, c: array, i: int, j: int) returns (r: int)\n requires a.Length + 1 == c.Length && c[0] == 0\n requires 0 <= i <= j <= a.Length\n requires is_prefix_sum_for(a,c) \n ensures r == sum(a, i, j)\n{ \n aux(a, c, i, j);\n r := c[j] - c[i]; \n}\n\n\n\n\nmethod Main()\n{\n var x := new int[10];\n x[0], x[1], x[2], x[3] := 2, 2, 1, 5;\n var y := sum(x, 0, x.Length);\n //assert y == 10;\n var c := new int[11];\n c[0], c[1], c[2], c[3], c[4] := 0, 2, 4, 5, 10;\n // var r := queryFast(x, c, 0, x.Length);\n \n}\n" }, { "test_ID": "019", "test_file": "CVS-handout1_tmp_tmptm52no3k_2.dfy", "ground_truth": "/* Functional Lists and Imperative Arrays */\n\n/*\n Daniel Cavalheiro 57869\n Pedro Nunes 57854\n*/\n\ndatatype List = Nil | Cons(head: T, tail: List)\n\nfunction length(l: List): nat\n{\n match l\n case Nil => 0\n case Cons(_, t) => 1 + length(t)\n}\n\npredicate mem (l: List, x: T)\n{\n match l\n case Nil => false\n case Cons(h, t) => if(h == x) then true else mem(t, x)\n}\n\nfunction at(l: List, i: nat): T\n requires i < length(l)\n{\n if i == 0 then l.head else at(l.tail, i - 1)\n}\n\nmethod from_array(a: array) returns (l: List)\n requires a.Length >= 0\n ensures length(l) == a.Length\n ensures forall i: int :: 0 <= i < length(l) ==> at(l, i) == a[i]\n ensures forall x :: mem(l, x) ==> exists i: int :: 0 <= i < length(l) && a[i] == x\n{\n l := Nil;\n var i: int := a.Length - 1;\n while(i >= 0)\n invariant -1 <= i <= a.Length - 1\n invariant length(l) == a.Length - 1 - i\n invariant forall j: int :: i < j < a.Length ==> at(l,j-i-1) == a[j]\n invariant forall x :: mem(l, x) ==> exists k: int :: i < k < a.Length && a[k] == x\n {\n l := Cons(a[i], l);\n i := i-1;\n }\n}\n\nmethod Main() {\n var l: List := List.Cons(1, List.Cons(2, List.Cons(3, Nil)));\n var arr: array := new int [3](i => i + 1);\n var t: List := from_array(arr);\n print l;\n print \"\\n\";\n print t;\n print \"\\n\";\n print t == l;\n}\n", "hints_removed": "/* Functional Lists and Imperative Arrays */\n\n/*\n Daniel Cavalheiro 57869\n Pedro Nunes 57854\n*/\n\ndatatype List = Nil | Cons(head: T, tail: List)\n\nfunction length(l: List): nat\n{\n match l\n case Nil => 0\n case Cons(_, t) => 1 + length(t)\n}\n\npredicate mem (l: List, x: T)\n{\n match l\n case Nil => false\n case Cons(h, t) => if(h == x) then true else mem(t, x)\n}\n\nfunction at(l: List, i: nat): T\n requires i < length(l)\n{\n if i == 0 then l.head else at(l.tail, i - 1)\n}\n\nmethod from_array(a: array) returns (l: List)\n requires a.Length >= 0\n ensures length(l) == a.Length\n ensures forall i: int :: 0 <= i < length(l) ==> at(l, i) == a[i]\n ensures forall x :: mem(l, x) ==> exists i: int :: 0 <= i < length(l) && a[i] == x\n{\n l := Nil;\n var i: int := a.Length - 1;\n while(i >= 0)\n {\n l := Cons(a[i], l);\n i := i-1;\n }\n}\n\nmethod Main() {\n var l: List := List.Cons(1, List.Cons(2, List.Cons(3, Nil)));\n var arr: array := new int [3](i => i + 1);\n var t: List := from_array(arr);\n print l;\n print \"\\n\";\n print t;\n print \"\\n\";\n print t == l;\n}\n" }, { "test_ID": "020", "test_file": "Clover_abs.dfy", "ground_truth": "method Abs(x: int) returns (y: int)\n ensures x>=0 ==> x==y\n ensures x<0 ==> x+y==0\n{\n if x < 0 {\n return -x;\n } else {\n return x;\n }\n}\n", "hints_removed": "method Abs(x: int) returns (y: int)\n ensures x>=0 ==> x==y\n ensures x<0 ==> x+y==0\n{\n if x < 0 {\n return -x;\n } else {\n return x;\n }\n}\n" }, { "test_ID": "021", "test_file": "Clover_all_digits.dfy", "ground_truth": " method allDigits(s: string) returns (result: bool)\n ensures result <==> (forall i :: 0 <= i < |s| ==> s[i] in \"0123456789\")\n{\n result:=true ;\n for i := 0 to |s|\n invariant result <==> (forall ii :: 0 <= ii < i ==> s[ii] in \"0123456789\")\n {\n if ! (s[i] in \"0123456789\"){\n return false;\n }\n }\n}\n", "hints_removed": " method allDigits(s: string) returns (result: bool)\n ensures result <==> (forall i :: 0 <= i < |s| ==> s[i] in \"0123456789\")\n{\n result:=true ;\n for i := 0 to |s|\n {\n if ! (s[i] in \"0123456789\"){\n return false;\n }\n }\n}\n" }, { "test_ID": "022", "test_file": "Clover_array_append.dfy", "ground_truth": "method append(a:array, b:int) returns (c:array)\n ensures a[..] + [b] == c[..]\n{\n c := new int[a.Length+1];\n var i:= 0;\n while (i < a.Length)\n invariant 0 <= i <= a.Length\n invariant forall ii::0<=ii c[ii]==a[ii]\n {\n c[i] := a[i];\n i:=i+1;\n }\n c[a.Length]:=b;\n}\n", "hints_removed": "method append(a:array, b:int) returns (c:array)\n ensures a[..] + [b] == c[..]\n{\n c := new int[a.Length+1];\n var i:= 0;\n while (i < a.Length)\n {\n c[i] := a[i];\n i:=i+1;\n }\n c[a.Length]:=b;\n}\n" }, { "test_ID": "023", "test_file": "Clover_array_concat.dfy", "ground_truth": "method concat(a:array, b:array) returns (c:array)\n ensures c.Length==b.Length+a.Length\n ensures forall k :: 0 <= k < a.Length ==> c[k] == a[k]\n ensures forall k :: 0 <= k < b.Length ==> c[k+a.Length] == b[k]\n{\n c := new int[a.Length+b.Length];\n var i:= 0;\n while (i < c.Length)\n invariant 0 <= i <= c.Length\n invariant if i, b:array) returns (c:array)\n ensures c.Length==b.Length+a.Length\n ensures forall k :: 0 <= k < a.Length ==> c[k] == a[k]\n ensures forall k :: 0 <= k < b.Length ==> c[k+a.Length] == b[k]\n{\n c := new int[a.Length+b.Length];\n var i:= 0;\n while (i < c.Length)\n {\n c[i] := if i(s: array) returns (t: array)\n ensures s.Length==t.Length\n ensures forall i::0<=i s[i]==t[i]\n{\n t := new T[s.Length];\n var i:= 0;\n while (i < s.Length)\n invariant 0 <= i <= s.Length\n invariant forall x :: 0 <= x < i ==> s[x] == t[x]\n {\n t[i] := s[i];\n i:=i+1;\n }\n}\n", "hints_removed": "method iter_copy(s: array) returns (t: array)\n ensures s.Length==t.Length\n ensures forall i::0<=i s[i]==t[i]\n{\n t := new T[s.Length];\n var i:= 0;\n while (i < s.Length)\n {\n t[i] := s[i];\n i:=i+1;\n }\n}\n" }, { "test_ID": "025", "test_file": "Clover_array_product.dfy", "ground_truth": "method arrayProduct(a: array, b: array) returns (c: array )\n requires a.Length==b.Length\n ensures c.Length==a.Length\n ensures forall i:: 0 <= i< a.Length==> a[i] * b[i]==c[i]\n{\n c:= new int[a.Length];\n var i:=0;\n while i a[j] * b[j]==c[j]\n {\n c[i]:=a[i]*b[i];\n i:=i+1;\n }\n}\n", "hints_removed": "method arrayProduct(a: array, b: array) returns (c: array )\n requires a.Length==b.Length\n ensures c.Length==a.Length\n ensures forall i:: 0 <= i< a.Length==> a[i] * b[i]==c[i]\n{\n c:= new int[a.Length];\n var i:=0;\n while i, b: array) returns (c: array )\n requires a.Length==b.Length\n ensures c.Length==a.Length\n ensures forall i:: 0 <= i< a.Length==> a[i] + b[i]==c[i]\n{\n c:= new int[a.Length];\n var i:=0;\n while i a[j] + b[j]==c[j]\n {\n c[i]:=a[i]+b[i];\n i:=i+1;\n }\n}\n", "hints_removed": "method arraySum(a: array, b: array) returns (c: array )\n requires a.Length==b.Length\n ensures c.Length==a.Length\n ensures forall i:: 0 <= i< a.Length==> a[i] + b[i]==c[i]\n{\n c:= new int[a.Length];\n var i:=0;\n while i) returns (s:array, result:bool)\n ensures s.Length == |operations| + 1\n ensures s[0]==0\n ensures forall i :: 0 <= i < s.Length-1 ==> s[i+1]==s[i]+operations[i]\n ensures result == true ==> (exists i :: 1 <= i <= |operations| && s[i] < 0)\n ensures result == false ==> forall i :: 0 <= i < s.Length ==> s[i] >= 0\n{\n result := false;\n s := new int[|operations| + 1];\n var i := 0;\n s[i] := 0;\n while i < s.Length\n invariant 0 <= i <= s.Length\n invariant s[0]==0\n invariant s.Length == |operations| + 1\n invariant forall x :: 0 <= x < i-1 ==> s[x+1]==s[x]+operations[x]\n {\n if i>0{\n s[i] := s[i - 1] + operations[i - 1];\n }\n i := i + 1;\n }\n i:=0;\n while i < s.Length\n invariant 0 <= i <= s.Length\n invariant forall x :: 0 <= x < i ==> s[x] >= 0\n {\n if s[i] < 0 {\n result := true;\n return;\n }\n i := i + 1;\n }\n}\n", "hints_removed": "method below_zero(operations: seq) returns (s:array, result:bool)\n ensures s.Length == |operations| + 1\n ensures s[0]==0\n ensures forall i :: 0 <= i < s.Length-1 ==> s[i+1]==s[i]+operations[i]\n ensures result == true ==> (exists i :: 1 <= i <= |operations| && s[i] < 0)\n ensures result == false ==> forall i :: 0 <= i < s.Length ==> s[i] >= 0\n{\n result := false;\n s := new int[|operations| + 1];\n var i := 0;\n s[i] := 0;\n while i < s.Length\n {\n if i>0{\n s[i] := s[i - 1] + operations[i - 1];\n }\n i := i + 1;\n }\n i:=0;\n while i < s.Length\n {\n if s[i] < 0 {\n result := true;\n return;\n }\n i := i + 1;\n }\n}\n" }, { "test_ID": "029", "test_file": "Clover_binary_search.dfy", "ground_truth": "method BinarySearch(a: array, key: int) returns (n: int)\n requires forall i,j :: 0<=i a[i]<=a[j]\n ensures 0<= n <=a.Length\n ensures forall i :: 0<= i < n ==> a[i] < key\n ensures n == a.Length ==> forall i :: 0 <= i < a.Length ==> a[i] < key\n ensures forall i :: n<= i < a.Length ==> a[i]>=key\n{\n var lo, hi := 0, a.Length;\n while lo a[i] < key\n invariant forall i :: hi<=i a[i] >= key\n {\n var mid := (lo + hi) / 2;\n if a[mid] < key {\n lo := mid + 1;\n } else {\n hi := mid;\n }\n }\n n:=lo;\n}\n", "hints_removed": "method BinarySearch(a: array, key: int) returns (n: int)\n requires forall i,j :: 0<=i a[i]<=a[j]\n ensures 0<= n <=a.Length\n ensures forall i :: 0<= i < n ==> a[i] < key\n ensures n == a.Length ==> forall i :: 0 <= i < a.Length ==> a[i] < key\n ensures forall i :: n<= i < a.Length ==> a[i]>=key\n{\n var lo, hi := 0, a.Length;\n while lo)\n modifies a\n ensures forall i,j::0<= i < j < a.Length ==> a[i] <= a[j]\n ensures multiset(a[..])==multiset(old(a[..]))\n{\n var i := a.Length - 1;\n while (i > 0)\n invariant i < 0 ==> a.Length == 0\n invariant -1 <= i < a.Length\n invariant forall ii,jj::i <= ii< jj a[ii] <= a[jj]\n invariant forall k,k'::0<=k<=ia[k]<=a[k']\n invariant multiset(a[..])==multiset(old(a[..]))\n {\n var j := 0;\n while (j < i)\n invariant 0 < i < a.Length && 0 <= j <= i\n invariant forall ii,jj::i<= ii <= jj a[ii] <= a[jj]\n invariant forall k, k'::0<=k<=ia[k]<=a[k']\n invariant forall k :: 0 <= k <= j ==> a[k] <= a[j]\n invariant multiset(a[..])==multiset(old(a[..]))\n {\n if (a[j] > a[j + 1])\n {\n a[j], a[j + 1] := a[j + 1], a[j];\n }\n j := j + 1;\n }\n i := i - 1;\n }\n}\n", "hints_removed": "method BubbleSort(a: array)\n modifies a\n ensures forall i,j::0<= i < j < a.Length ==> a[i] <= a[j]\n ensures multiset(a[..])==multiset(old(a[..]))\n{\n var i := a.Length - 1;\n while (i > 0)\n {\n var j := 0;\n while (j < i)\n {\n if (a[j] > a[j + 1])\n {\n a[j], a[j + 1] := a[j + 1], a[j];\n }\n j := j + 1;\n }\n i := i - 1;\n }\n}\n" }, { "test_ID": "031", "test_file": "Clover_cal_ans.dfy", "ground_truth": "method CalDiv() returns (x:int, y:int)\n ensures x==191/7\n ensures y==191%7\n{\n\n x, y := 0, 191;\n while 7 <= y\n invariant 0 <= y && 7 * x + y == 191\n {\n x := x+1;\n y:=191-7*x;\n }\n}\n", "hints_removed": "method CalDiv() returns (x:int, y:int)\n ensures x==191/7\n ensures y==191%7\n{\n\n x, y := 0, 191;\n while 7 <= y\n {\n x := x+1;\n y:=191-7*x;\n }\n}\n" }, { "test_ID": "032", "test_file": "Clover_cal_sum.dfy", "ground_truth": "method Sum(N:int) returns (s:int)\n requires N >= 0\n ensures s == N * (N + 1) / 2\n{\n var n := 0;\n s := 0;\n while n != N\n invariant 0 <= n <= N\n invariant s == n * (n + 1) / 2\n {\n n := n + 1;\n s := s + n;\n }\n}\n", "hints_removed": "method Sum(N:int) returns (s:int)\n requires N >= 0\n ensures s == N * (N + 1) / 2\n{\n var n := 0;\n s := 0;\n while n != N\n {\n n := n + 1;\n s := s + n;\n }\n}\n" }, { "test_ID": "033", "test_file": "Clover_canyon_search.dfy", "ground_truth": "method CanyonSearch(a: array, b: array) returns (d:nat)\n requires a.Length !=0 && b.Length!=0\n requires forall i,j :: 0<=i a[i]<=a[j]\n requires forall i,j :: 0<=i b[i]<=b[j]\n ensures exists i,j:: 0<=i d<=if a[i] < b[j] then (b[j]-a[i]) else (a[i]-b[j])\n{\n var m,n:=0,0;\n d:=if a[0] < b[0] then (b[0]-a[0]) else (a[0]-b[0]);\n while m d<=(if a[i] < b[j] then (b[j]-a[i]) else (a[i]-b[j]))|| (m<=i&&n<=j)\n {\n var t := if a[m] < b[n] then (b[n]-a[m]) else (a[m]-b[n]);\n d:=if t\n m:=m+1;\n case b[n]<=a[m] =>\n n:=n+1;\n\n }\n}\n\n", "hints_removed": "method CanyonSearch(a: array, b: array) returns (d:nat)\n requires a.Length !=0 && b.Length!=0\n requires forall i,j :: 0<=i a[i]<=a[j]\n requires forall i,j :: 0<=i b[i]<=b[j]\n ensures exists i,j:: 0<=i d<=if a[i] < b[j] then (b[j]-a[i]) else (a[i]-b[j])\n{\n var m,n:=0,0;\n d:=if a[0] < b[0] then (b[0]-a[0]) else (a[0]-b[0]);\n while m\n m:=m+1;\n case b[n]<=a[m] =>\n n:=n+1;\n\n }\n}\n\n" }, { "test_ID": "034", "test_file": "Clover_compare.dfy", "ground_truth": "method Compare(a: T, b: T) returns (eq: bool)\n ensures a==b ==> eq==true\n ensures a!=b ==> eq==false\n{\n if a == b { eq := true; } else { eq := false; }\n}\n", "hints_removed": "method Compare(a: T, b: T) returns (eq: bool)\n ensures a==b ==> eq==true\n ensures a!=b ==> eq==false\n{\n if a == b { eq := true; } else { eq := false; }\n}\n" }, { "test_ID": "035", "test_file": "Clover_convert_map_key.dfy", "ground_truth": "method convert_map_key(inputs: map, f: nat->nat) returns(r:map)\n requires forall n1: nat, n2: nat :: n1 != n2 ==> f(n1) != f(n2)\n ensures forall k :: k in inputs <==> f(k) in r\n ensures forall k :: k in inputs ==> r[f(k)] == inputs[k]\n{\n r:= map k | k in inputs :: f(k) := inputs[k];\n}\n", "hints_removed": "method convert_map_key(inputs: map, f: nat->nat) returns(r:map)\n requires forall n1: nat, n2: nat :: n1 != n2 ==> f(n1) != f(n2)\n ensures forall k :: k in inputs <==> f(k) in r\n ensures forall k :: k in inputs ==> r[f(k)] == inputs[k]\n{\n r:= map k | k in inputs :: f(k) := inputs[k];\n}\n" }, { "test_ID": "036", "test_file": "Clover_copy_part.dfy", "ground_truth": "method copy( src: array, sStart: nat, dest: array, dStart: nat, len: nat) returns (r: array)\n requires src.Length >= sStart + len\n requires dest.Length >= dStart + len\n ensures r.Length == dest.Length\n ensures r[..dStart] == dest[..dStart]\n ensures r[dStart + len..] == dest[dStart + len..]\n ensures r[dStart..len+dStart] == src[sStart..len+sStart]\n\n{\n if len == 0 { return dest; }\n var i: nat := 0;\n r := new int[dest.Length];\n while (i < r.Length)\n invariant i <= r.Length\n invariant r[..i] == dest[..i]\n {\n r[i] := dest[i];\n i := i + 1;\n }\n assert r[..]==dest[..];\n i := 0;\n while (i < len)\n invariant i <= len\n invariant r[..dStart] == dest[..dStart]\n invariant r[(dStart + len)..] == dest[(dStart + len)..]\n invariant r[dStart .. dStart + i] == src[sStart .. sStart + i]\n {\n assert r[(dStart + len)..] == dest[(dStart + len)..];\n r[dStart + i] := src[sStart + i];\n i := i + 1;\n }\n}", "hints_removed": "method copy( src: array, sStart: nat, dest: array, dStart: nat, len: nat) returns (r: array)\n requires src.Length >= sStart + len\n requires dest.Length >= dStart + len\n ensures r.Length == dest.Length\n ensures r[..dStart] == dest[..dStart]\n ensures r[dStart + len..] == dest[dStart + len..]\n ensures r[dStart..len+dStart] == src[sStart..len+sStart]\n\n{\n if len == 0 { return dest; }\n var i: nat := 0;\n r := new int[dest.Length];\n while (i < r.Length)\n {\n r[i] := dest[i];\n i := i + 1;\n }\n i := 0;\n while (i < len)\n {\n r[dStart + i] := src[sStart + i];\n i := i + 1;\n }\n}" }, { "test_ID": "037", "test_file": "Clover_count_lessthan.dfy", "ground_truth": "method CountLessThan(numbers: set, threshold: int) returns (count: int)\n ensures count == |set i | i in numbers && i < threshold|\n{\n count := 0;\n var shrink := numbers;\n var grow := {};\n while |shrink | > 0\n decreases shrink\n invariant shrink + grow == numbers\n invariant grow !! shrink\n invariant count == |set i | i in grow && i < threshold|\n {\n var i: int :| i in shrink;\n shrink := shrink - {i};\n var grow' := grow+{i};\n assert (set i | i in grow' && i < threshold) ==\n (set i | i in grow && i < threshold )+ if i < threshold then {i} else {};\n grow := grow + {i};\n if i < threshold {\n count := count + 1;\n }\n }\n}\n", "hints_removed": "method CountLessThan(numbers: set, threshold: int) returns (count: int)\n ensures count == |set i | i in numbers && i < threshold|\n{\n count := 0;\n var shrink := numbers;\n var grow := {};\n while |shrink | > 0\n {\n var i: int :| i in shrink;\n shrink := shrink - {i};\n var grow' := grow+{i};\n grow := grow + {i};\n if i < threshold {\n count := count + 1;\n }\n }\n}\n" }, { "test_ID": "038", "test_file": "Clover_double_array_elements.dfy", "ground_truth": "method double_array_elements(s: array)\n modifies s\n ensures forall i :: 0 <= i < s.Length ==> s[i] == 2 * old(s[i])\n{\n var i:= 0;\n while (i < s.Length)\n invariant 0 <= i <= s.Length\n invariant forall x :: i <= x < s.Length ==> s[x] == old(s[x])\n invariant forall x :: 0 <= x < i ==> s[x] == 2 * old(s[x])\n\n {\n s[i] := 2 * s[i];\n i := i + 1;\n }\n}", "hints_removed": "method double_array_elements(s: array)\n modifies s\n ensures forall i :: 0 <= i < s.Length ==> s[i] == 2 * old(s[i])\n{\n var i:= 0;\n while (i < s.Length)\n\n {\n s[i] := 2 * s[i];\n i := i + 1;\n }\n}" }, { "test_ID": "039", "test_file": "Clover_double_quadruple.dfy", "ground_truth": "method DoubleQuadruple(x: int) returns (a: int, b: int)\n ensures a == 2 * x && b == 4 * x\n{\n a := 2 * x;\n b := 2 * a;\n}\n", "hints_removed": "method DoubleQuadruple(x: int) returns (a: int, b: int)\n ensures a == 2 * x && b == 4 * x\n{\n a := 2 * x;\n b := 2 * a;\n}\n" }, { "test_ID": "040", "test_file": "Clover_even_list.dfy", "ground_truth": "method FindEvenNumbers (arr: array) returns (evenNumbers: array)\n ensures forall x {:trigger (x%2) }:: x in arr[..] && (x%2==0)==> x in evenNumbers[..]\n ensures forall x :: x !in arr[..] ==> x !in evenNumbers[..]\n ensures forall k :: 0 <= k < evenNumbers.Length ==> evenNumbers[k] % 2 == 0\n ensures forall k, l :: 0 <= k < l < evenNumbers.Length ==>\n exists n, m :: 0 <= n < m < arr.Length && evenNumbers[k] == arr[n] && evenNumbers[l] == arr[m]\n\n{\n var evenList: seq := [];\n ghost var indices: seq := [];\n\n for i := 0 to arr.Length\n invariant 0 <= i <= arr.Length\n invariant 0 <= |evenList| <= i\n invariant forall x {:trigger (x%2) }:: (x in arr[..i] && (x%2==0) )==> x in evenList[..]\n invariant forall k :: 0 <= k < |evenList| ==> evenList[k] % 2 == 0\n invariant forall x :: x !in arr[..i] ==> x !in evenList\n invariant |evenList| == |indices|\n invariant forall k :: 0 <= k < |indices| ==> indices[k] < i\n invariant forall k, l :: 0 <= k < l < |indices| ==> indices[k] < indices[l]\n invariant forall k :: 0 <= k < |evenList| ==> 0 <= indices[k] < i <= arr.Length && arr[indices[k]] == evenList[k]\n {\n if arr[i]%2==0\n {\n evenList := evenList + [arr[i]];\n indices := indices + [i];\n }\n }\n\n evenNumbers := new int[|evenList|](i requires 0 <= i < |evenList| => evenList[i]);\n assert evenList == evenNumbers[..];\n}\n", "hints_removed": "method FindEvenNumbers (arr: array) returns (evenNumbers: array)\n ensures forall x {:trigger (x%2) }:: x in arr[..] && (x%2==0)==> x in evenNumbers[..]\n ensures forall x :: x !in arr[..] ==> x !in evenNumbers[..]\n ensures forall k :: 0 <= k < evenNumbers.Length ==> evenNumbers[k] % 2 == 0\n ensures forall k, l :: 0 <= k < l < evenNumbers.Length ==>\n exists n, m :: 0 <= n < m < arr.Length && evenNumbers[k] == arr[n] && evenNumbers[l] == arr[m]\n\n{\n var evenList: seq := [];\n ghost var indices: seq := [];\n\n for i := 0 to arr.Length\n {\n if arr[i]%2==0\n {\n evenList := evenList + [arr[i]];\n indices := indices + [i];\n }\n }\n\n evenNumbers := new int[|evenList|](i requires 0 <= i < |evenList| => evenList[i]);\n}\n" }, { "test_ID": "041", "test_file": "Clover_find.dfy", "ground_truth": "method Find(a: array, key: int) returns (index: int)\n ensures -1<=index a[index]==key && (forall i :: 0 <= i < index ==> a[i] != key)\n ensures index == -1 ==> (forall i::0 <= i < a.Length ==> a[i] != key)\n{\n index := 0;\n while index < a.Length\n invariant 0<=index<=a.Length\n invariant (forall i::0 <= i < index==>a[i] != key)\n {\n if a[index] == key { return; }\n index := index + 1;\n }\n if index >= a.Length {\n index := -1;\n }\n}\n", "hints_removed": "method Find(a: array, key: int) returns (index: int)\n ensures -1<=index a[index]==key && (forall i :: 0 <= i < index ==> a[i] != key)\n ensures index == -1 ==> (forall i::0 <= i < a.Length ==> a[i] != key)\n{\n index := 0;\n while index < a.Length\n {\n if a[index] == key { return; }\n index := index + 1;\n }\n if index >= a.Length {\n index := -1;\n }\n}\n" }, { "test_ID": "042", "test_file": "Clover_has_close_elements.dfy", "ground_truth": "method has_close_elements(numbers: seq, threshold: real) returns (res: bool)\n requires threshold >= 0.0\n ensures res ==> exists i: int, j: int :: 0 <= i < |numbers| && 0 <= j < |numbers| && i != j && (if numbers[i] - numbers[j] < 0.0 then numbers[j] - numbers[i] else numbers[i] - numbers[j]) < threshold\n ensures !res ==> (forall i: int, j: int :: 1 <= i < |numbers| && 0 <= j < i ==> (if numbers[i] - numbers[j] < 0.0 then numbers[j] - numbers[i] else numbers[i] - numbers[j]) >= threshold)\n\n\n{\n\n res := false;\n var idx: int := 0;\n while idx < |numbers| && !res\n invariant 0 <= idx <= |numbers|\n invariant !res\n invariant forall i: int, j: int :: 0 <= i < idx && 0 <= j < i ==> (if numbers[i] - numbers[j] < 0.0 then numbers[j] - numbers[i] else numbers[i] - numbers[j]) >= threshold\n {\n var idx2: int := 0;\n while idx2 < idx && !res\n invariant 0 <= idx <= |numbers|\n invariant 0 <= idx2 <= idx\n invariant !res\n invariant forall j: int :: 0 <= j < idx2 ==> (if numbers[idx] - numbers[j] < 0.0 then numbers[j] - numbers[idx] else numbers[idx] - numbers[j]) >= threshold\n {\n\n var distance := (if numbers[idx2] - numbers[idx] < 0.0 then numbers[idx] - numbers[idx2] else numbers[idx2] - numbers[idx]);\n if distance < threshold {\n res := true;\n return;\n }\n\n idx2 := idx2 + 1;\n }\n idx := idx + 1;\n }\n}\n\n", "hints_removed": "method has_close_elements(numbers: seq, threshold: real) returns (res: bool)\n requires threshold >= 0.0\n ensures res ==> exists i: int, j: int :: 0 <= i < |numbers| && 0 <= j < |numbers| && i != j && (if numbers[i] - numbers[j] < 0.0 then numbers[j] - numbers[i] else numbers[i] - numbers[j]) < threshold\n ensures !res ==> (forall i: int, j: int :: 1 <= i < |numbers| && 0 <= j < i ==> (if numbers[i] - numbers[j] < 0.0 then numbers[j] - numbers[i] else numbers[i] - numbers[j]) >= threshold)\n\n\n{\n\n res := false;\n var idx: int := 0;\n while idx < |numbers| && !res\n {\n var idx2: int := 0;\n while idx2 < idx && !res\n {\n\n var distance := (if numbers[idx2] - numbers[idx] < 0.0 then numbers[idx] - numbers[idx2] else numbers[idx2] - numbers[idx]);\n if distance < threshold {\n res := true;\n return;\n }\n\n idx2 := idx2 + 1;\n }\n idx := idx + 1;\n }\n}\n\n" }, { "test_ID": "043", "test_file": "Clover_insert.dfy", "ground_truth": "method insert(line:array, l:int, nl:array, p:int, at:int)\n requires 0 <= l+p <= line.Length\n requires 0 <= p <= nl.Length\n requires 0 <= at <= l\n modifies line\n ensures forall i :: (0<=i line[at+i] == nl[i]\n ensures forall i :: (0<=i line[i] == old(line[i])\n ensures forall i :: (at+p<=i line[i] == old(line[i-p])\n{\n ghost var initialLine := line[..];\n\n var i:int := l;\n while(i>at)\n invariant line[0..i] == initialLine[0..i]\n invariant line[i+p..l+p] == initialLine[i..l]\n invariant at<=i<=l\n {\n i := i - 1;\n line[i+p] := line[i];\n }\n\n assert line[0..at] == initialLine[0..at];\n assert line[at+p..l+p] == initialLine[at..l];\n\n i := 0;\n while(i, l:int, nl:array, p:int, at:int)\n requires 0 <= l+p <= line.Length\n requires 0 <= p <= nl.Length\n requires 0 <= at <= l\n modifies line\n ensures forall i :: (0<=i line[at+i] == nl[i]\n ensures forall i :: (0<=i line[i] == old(line[i])\n ensures forall i :: (at+p<=i line[i] == old(line[i-p])\n{\n ghost var initialLine := line[..];\n\n var i:int := l;\n while(i>at)\n {\n i := i - 1;\n line[i+p] := line[i];\n }\n\n\n i := 0;\n while(i) returns (result: bool)\n ensures result <==> (forall i :: 0 <= i < |x| ==> x[i] == x[|x| - i - 1])\n{\n if |x|==0 {\n return true;\n }\n var i := 0;\n var j := |x| - 1;\n result := true;\n while (i < j)\n invariant 0<=i<=j+1 && 0<=j < |x|\n invariant i+j==|x|-1\n invariant (forall k :: 0 <= k < i ==> x[k] == x[|x| - k - 1])\n {\n if x[i] != x[j] {\n result := false;\n return;\n }\n i := i + 1;\n j := j - 1;\n }\n}\n", "hints_removed": "method IsPalindrome(x: seq) returns (result: bool)\n ensures result <==> (forall i :: 0 <= i < |x| ==> x[i] == x[|x| - i - 1])\n{\n if |x|==0 {\n return true;\n }\n var i := 0;\n var j := |x| - 1;\n result := true;\n while (i < j)\n {\n if x[i] != x[j] {\n result := false;\n return;\n }\n i := i + 1;\n j := j - 1;\n }\n}\n" }, { "test_ID": "047", "test_file": "Clover_linear_search1.dfy", "ground_truth": "method LinearSearch(a: array, e: int) returns (n:int)\n ensures 0<=n<=a.Length\n ensures n==a.Length || a[n]==e\n ensures forall i::0<=i < n ==> e!=a[i]\n{\n n :=0;\n while n!=a.Length\n invariant 0<=n<=a.Length\n invariant forall i::0<=i e!=a[i]\n {\n if e==a[n]{\n return;\n }\n n:=n+1;\n }\n}\n", "hints_removed": "method LinearSearch(a: array, e: int) returns (n:int)\n ensures 0<=n<=a.Length\n ensures n==a.Length || a[n]==e\n ensures forall i::0<=i < n ==> e!=a[i]\n{\n n :=0;\n while n!=a.Length\n {\n if e==a[n]{\n return;\n }\n n:=n+1;\n }\n}\n" }, { "test_ID": "048", "test_file": "Clover_linear_search2.dfy", "ground_truth": "method LinearSearch(a: array, e: int) returns (n:int)\n requires exists i::0<=i a[k]!=e\n\n{\n n :=0;\n while n!=a.Length\n invariant 0<=n<=a.Length\n invariant forall i::0<=i e!=a[i]\n {\n if e==a[n]{\n return;\n }\n n:=n+1;\n }\n}\n", "hints_removed": "method LinearSearch(a: array, e: int) returns (n:int)\n requires exists i::0<=i a[k]!=e\n\n{\n n :=0;\n while n!=a.Length\n {\n if e==a[n]{\n return;\n }\n n:=n+1;\n }\n}\n" }, { "test_ID": "049", "test_file": "Clover_linear_search3.dfy", "ground_truth": "method LinearSearch3(a: array, P: T -> bool) returns (n: int)\n requires exists i :: 0 <= i < a.Length && P(a[i])\n ensures 0 <= n < a.Length && P(a[n])\n ensures forall k :: 0 <= k < n ==> !P(a[k])\n{\n n := 0;\n while true\n invariant 0 <= n < a.Length\n invariant exists i :: n <= i < a.Length && P(a[i])\n invariant forall k :: 0 <= k < n ==> !P(a[k])\n decreases a.Length - n\n {\n if P(a[n]) {\n return;\n }\n n := n + 1;\n }\n}\n", "hints_removed": "method LinearSearch3(a: array, P: T -> bool) returns (n: int)\n requires exists i :: 0 <= i < a.Length && P(a[i])\n ensures 0 <= n < a.Length && P(a[n])\n ensures forall k :: 0 <= k < n ==> !P(a[k])\n{\n n := 0;\n while true\n {\n if P(a[n]) {\n return;\n }\n n := n + 1;\n }\n}\n" }, { "test_ID": "050", "test_file": "Clover_longest_prefix.dfy", "ground_truth": "method LongestCommonPrefix(str1: seq, str2: seq) returns (prefix: seq)\n ensures |prefix| <= |str1| && prefix == str1[0..|prefix|]&& |prefix| <= |str2| && prefix == str2[0..|prefix|]\n ensures |prefix|==|str1| || |prefix|==|str2| || (str1[|prefix|]!=str2[|prefix|])\n{\n prefix := [];\n var minLength := if |str1| <|str2| then |str1| else |str2|;\n\n for idx:= 0 to minLength\n invariant |prefix|==idx <= minLength<=|str1| && minLength<=|str2|\n invariant |prefix| <= |str1| && prefix == str1[0..|prefix|]&& |prefix| <= |str2| && prefix == str2[0..|prefix|]\n {\n if str1[idx] != str2[idx] {\n return;\n }\n prefix := prefix + [str1[idx]];\n }\n}\n", "hints_removed": "method LongestCommonPrefix(str1: seq, str2: seq) returns (prefix: seq)\n ensures |prefix| <= |str1| && prefix == str1[0..|prefix|]&& |prefix| <= |str2| && prefix == str2[0..|prefix|]\n ensures |prefix|==|str1| || |prefix|==|str2| || (str1[|prefix|]!=str2[|prefix|])\n{\n prefix := [];\n var minLength := if |str1| <|str2| then |str1| else |str2|;\n\n for idx:= 0 to minLength\n {\n if str1[idx] != str2[idx] {\n return;\n }\n prefix := prefix + [str1[idx]];\n }\n}\n" }, { "test_ID": "051", "test_file": "Clover_match.dfy", "ground_truth": "method Match(s: string, p: string) returns (b: bool)\n requires |s| == |p|\n ensures b <==> forall n :: 0 <= n < |s| ==> s[n] == p[n] || p[n] == '?'\n{\n var i := 0;\n while i < |s|\n invariant 0 <= i <= |s|\n invariant forall n :: 0 <= n < i ==> s[n] == p[n] || p[n] == '?'\n {\n if s[i] != p[i] && p[i] != '?'\n {\n return false;\n }\n i := i + 1;\n }\n return true;\n}\n", "hints_removed": "method Match(s: string, p: string) returns (b: bool)\n requires |s| == |p|\n ensures b <==> forall n :: 0 <= n < |s| ==> s[n] == p[n] || p[n] == '?'\n{\n var i := 0;\n while i < |s|\n {\n if s[i] != p[i] && p[i] != '?'\n {\n return false;\n }\n i := i + 1;\n }\n return true;\n}\n" }, { "test_ID": "052", "test_file": "Clover_max_array.dfy", "ground_truth": "method maxArray(a: array) returns (m: int)\n requires a.Length >= 1\n ensures forall k :: 0 <= k < a.Length ==> m >= a[k]\n ensures exists k :: 0 <= k < a.Length && m == a[k]\n{\n m := a[0];\n var index := 1;\n while (index < a.Length)\n invariant 0 <= index <= a.Length\n invariant forall k :: 0 <= k < index ==> m >= a[k]\n invariant exists k :: 0 <= k < index && m == a[k]\n decreases a.Length - index\n {\n m := if m>a[index] then m else a[index];\n index := index + 1;\n }\n}\n", "hints_removed": "method maxArray(a: array) returns (m: int)\n requires a.Length >= 1\n ensures forall k :: 0 <= k < a.Length ==> m >= a[k]\n ensures exists k :: 0 <= k < a.Length && m == a[k]\n{\n m := a[0];\n var index := 1;\n while (index < a.Length)\n {\n m := if m>a[index] then m else a[index];\n index := index + 1;\n }\n}\n" }, { "test_ID": "053", "test_file": "Clover_min_array.dfy", "ground_truth": "method minArray(a: array) returns (r:int)\n requires a.Length > 0\n ensures forall i :: 0 <= i < a.Length ==> r <= a[i]\n ensures exists i :: 0 <= i < a.Length && r == a[i]\n{\n r:=a[0];\n var i:=1;\n while i r <= a[x]\n invariant exists x :: 0 <= x < i && r == a[x]\n {\n if r>a[i]{\n r:=a[i];\n }\n i:=i+1;\n }\n}\n", "hints_removed": "method minArray(a: array) returns (r:int)\n requires a.Length > 0\n ensures forall i :: 0 <= i < a.Length ==> r <= a[i]\n ensures exists i :: 0 <= i < a.Length && r == a[i]\n{\n r:=a[0];\n var i:=1;\n while ia[i]{\n r:=a[i];\n }\n i:=i+1;\n }\n}\n" }, { "test_ID": "054", "test_file": "Clover_min_of_two.dfy", "ground_truth": "method Min(x: int, y:int) returns (z: int)\n ensures x<=y ==> z==x\n ensures x>y ==> z==y\n{\n if x < y {\n return x;\n } else {\n return y;\n }\n}\n", "hints_removed": "method Min(x: int, y:int) returns (z: int)\n ensures x<=y ==> z==x\n ensures x>y ==> z==y\n{\n if x < y {\n return x;\n } else {\n return y;\n }\n}\n" }, { "test_ID": "055", "test_file": "Clover_modify_2d_array.dfy", "ground_truth": "method modify_array_element(arr: array>, index1: nat, index2: nat, val: nat)\n requires index1 < arr.Length\n requires index2 < arr[index1].Length\n requires forall i: nat, j:nat :: i < arr.Length && j < arr.Length && i != j ==> arr[i] != arr[j]\n modifies arr[index1]\n ensures forall i: nat :: 0 <= i < arr.Length ==> arr[i] == old(arr[i])\n ensures forall i: nat, j: nat :: 0 <= i < arr.Length && 0 <= j < arr[i].Length && (i != index1 || j != index2) ==> arr[i][j] == old(arr[i][j])\n ensures arr[index1][index2] == val\n{\n arr[index1][index2] := val;\n}\n", "hints_removed": "method modify_array_element(arr: array>, index1: nat, index2: nat, val: nat)\n requires index1 < arr.Length\n requires index2 < arr[index1].Length\n requires forall i: nat, j:nat :: i < arr.Length && j < arr.Length && i != j ==> arr[i] != arr[j]\n modifies arr[index1]\n ensures forall i: nat :: 0 <= i < arr.Length ==> arr[i] == old(arr[i])\n ensures forall i: nat, j: nat :: 0 <= i < arr.Length && 0 <= j < arr[i].Length && (i != index1 || j != index2) ==> arr[i][j] == old(arr[i][j])\n ensures arr[index1][index2] == val\n{\n arr[index1][index2] := val;\n}\n" }, { "test_ID": "056", "test_file": "Clover_multi_return.dfy", "ground_truth": "method MultipleReturns(x: int, y: int) returns (more: int, less: int)\n ensures more == x+y\n ensures less == x-y\n{\n more := x + y;\n less := x - y;\n}\n", "hints_removed": "method MultipleReturns(x: int, y: int) returns (more: int, less: int)\n ensures more == x+y\n ensures less == x-y\n{\n more := x + y;\n less := x - y;\n}\n" }, { "test_ID": "057", "test_file": "Clover_online_max.dfy", "ground_truth": "method onlineMax(a: array, x: int) returns (ghost m:int, p:int)\n requires 1<=x a[i]<=m\n ensures exists i::0<=i (forall i::0<=i

a[i] p==a.Length-1\n{\n p:= 0;\n var best := a[0];\n var i:=1;\n while i a[j]<=best\n invariant exists j::0<=jbest{\n best:=a[i];\n }\n i:=i+1;\n }\n m:=best;\n i:=x;\n while i a[j]<=m\n {\n if a[i]>best{\n p:=i;\n return;\n }\n i:=i+1;\n }\n p:=a.Length-1;\n\n}\n\n", "hints_removed": "method onlineMax(a: array, x: int) returns (ghost m:int, p:int)\n requires 1<=x a[i]<=m\n ensures exists i::0<=i (forall i::0<=i

a[i] p==a.Length-1\n{\n p:= 0;\n var best := a[0];\n var i:=1;\n while ibest{\n best:=a[i];\n }\n i:=i+1;\n }\n m:=best;\n i:=x;\n while ibest{\n p:=i;\n return;\n }\n i:=i+1;\n }\n p:=a.Length-1;\n\n}\n\n" }, { "test_ID": "058", "test_file": "Clover_only_once.dfy", "ground_truth": "method only_once(a: array, key: T) returns (b:bool)\n ensures (multiset(a[..])[key] ==1 ) <==> b\n{\n var i := 0;\n b := false;\n var keyCount := 0;\n while i < a.Length\n invariant 0 <= i <= a.Length\n invariant multiset(a[..i])[key] == keyCount\n invariant b <==> (keyCount == 1)\n {\n if (a[i] == key)\n {\n keyCount := keyCount + 1;\n }\n if (keyCount == 1)\n { b := true; }\n else\n { b := false; }\n i := i + 1;\n }\n\n assert a[..a.Length] == a[..];\n}\n", "hints_removed": "method only_once(a: array, key: T) returns (b:bool)\n ensures (multiset(a[..])[key] ==1 ) <==> b\n{\n var i := 0;\n b := false;\n var keyCount := 0;\n while i < a.Length\n {\n if (a[i] == key)\n {\n keyCount := keyCount + 1;\n }\n if (keyCount == 1)\n { b := true; }\n else\n { b := false; }\n i := i + 1;\n }\n\n}\n" }, { "test_ID": "059", "test_file": "Clover_quotient.dfy", "ground_truth": "method Quotient(x: nat, y:nat) returns (r:int, q:int)\n requires y != 0\n ensures q * y + r == x && 0 <= r < y && 0 <= q\n{\n r:=x;\n q:=0;\n while y<=r\n invariant q*y+r==x && r>=0\n decreases r\n {\n r:=r-y;\n q:=q+1;\n\n }\n}\n", "hints_removed": "method Quotient(x: nat, y:nat) returns (r:int, q:int)\n requires y != 0\n ensures q * y + r == x && 0 <= r < y && 0 <= q\n{\n r:=x;\n q:=0;\n while y<=r\n {\n r:=r-y;\n q:=q+1;\n\n }\n}\n" }, { "test_ID": "060", "test_file": "Clover_remove_front.dfy", "ground_truth": "method remove_front(a:array) returns (c:array)\n requires a.Length>0\n ensures a[1..] == c[..]\n{\n c := new int[a.Length-1];\n var i:= 1;\n while (i < a.Length)\n invariant 1 <= i <= a.Length\n invariant forall ii::1<=ii c[ii-1]==a[ii]\n {\n c[i-1] := a[i];\n i:=i+1;\n }\n}\n", "hints_removed": "method remove_front(a:array) returns (c:array)\n requires a.Length>0\n ensures a[1..] == c[..]\n{\n c := new int[a.Length-1];\n var i:= 1;\n while (i < a.Length)\n {\n c[i-1] := a[i];\n i:=i+1;\n }\n}\n" }, { "test_ID": "061", "test_file": "Clover_replace.dfy", "ground_truth": "method replace(arr: array, k: int)\n modifies arr\n ensures forall i :: 0 <= i < arr.Length ==> old(arr[i]) > k ==> arr[i] == -1\n ensures forall i :: 0 <= i < arr.Length ==> old(arr[i]) <= k ==> arr[i] == old(arr[i])\n{\n var i := 0;\n while i < arr.Length\n decreases arr.Length - i\n invariant 0 <= i <= arr.Length\n invariant forall j :: 0 <= j < i ==> old(arr[j]) > k ==> arr[j] == -1\n invariant forall j :: 0 <= j < i ==> old(arr[j]) <= k ==> arr[j] == old(arr[j])\n invariant forall j :: i <= j < arr.Length ==> old(arr[j]) == arr[j]\n {\n if arr[i] > k {\n arr[i] := -1;\n }\n i := i + 1;\n }\n}\n", "hints_removed": "method replace(arr: array, k: int)\n modifies arr\n ensures forall i :: 0 <= i < arr.Length ==> old(arr[i]) > k ==> arr[i] == -1\n ensures forall i :: 0 <= i < arr.Length ==> old(arr[i]) <= k ==> arr[i] == old(arr[i])\n{\n var i := 0;\n while i < arr.Length\n {\n if arr[i] > k {\n arr[i] := -1;\n }\n i := i + 1;\n }\n}\n" }, { "test_ID": "062", "test_file": "Clover_return_seven.dfy", "ground_truth": "method M(x: int) returns (seven: int)\n ensures seven==7\n{\n seven := 7;\n}\n", "hints_removed": "method M(x: int) returns (seven: int)\n ensures seven==7\n{\n seven := 7;\n}\n" }, { "test_ID": "063", "test_file": "Clover_reverse.dfy", "ground_truth": "method reverse(a: array)\n modifies a\n ensures forall i :: 0 <= i < a.Length ==> a[i] == old(a[a.Length - 1 - i])\n{\n var i := 0;\n while i a[k] == old(a[a.Length-1-k])\n invariant forall k :: i <= k <= a.Length-1-i ==> a[k] == old(a[k])\n {\n a[i], a[a.Length-1-i] := a[a.Length-1-i], a[i];\n i := i + 1;\n }\n}\n", "hints_removed": "method reverse(a: array)\n modifies a\n ensures forall i :: 0 <= i < a.Length ==> a[i] == old(a[a.Length - 1 - i])\n{\n var i := 0;\n while i , offset:int) returns (b: array )\n requires 0<=offset\n ensures b.Length==a.Length\n ensures forall i::0<=i b[i]==a[(i+offset)%a.Length]\n{\n b:= new int[a.Length];\n var i:=0;\n while i b[j]==a[(j+offset)%a.Length]\n {\n b[i]:=a[(i+offset)%a.Length];\n i:=i+1;\n }\n}", "hints_removed": "method rotate(a: array, offset:int) returns (b: array )\n requires 0<=offset\n ensures b.Length==a.Length\n ensures forall i::0<=i b[i]==a[(i+offset)%a.Length]\n{\n b:= new int[a.Length];\n var i:=0;\n while i)\n modifies a\n ensures forall i,j :: 0 <= i < j < a.Length ==> a[i] <= a[j]\n ensures multiset(a[..]) == old(multiset(a[..]))\n{\n var n:= 0;\n while n != a.Length\n invariant 0 <= n <= a.Length\n invariant forall i, j :: 0 <= i < n <= j < a.Length ==> a[i] <= a[j]\n invariant forall i,j :: 0 <= i < j < n ==> a[i] <= a[j]\n invariant multiset(a[..]) == old(multiset(a[..]))\n {\n var mindex, m := n, n+1;\n while m != a.Length\n invariant n <= mindex < m <= a.Length\n invariant forall i :: n <= i < m ==> a[mindex] <= a[i]\n {\n if a[m] < a[mindex] {\n mindex := m;\n }\n m := m+1;\n }\n a[n], a[mindex] := a[mindex], a[n];\n n := n+1;\n }\n}\n", "hints_removed": "method SelectionSort(a: array)\n modifies a\n ensures forall i,j :: 0 <= i < j < a.Length ==> a[i] <= a[j]\n ensures multiset(a[..]) == old(multiset(a[..]))\n{\n var n:= 0;\n while n != a.Length\n {\n var mindex, m := n, n+1;\n while m != a.Length\n {\n if a[m] < a[mindex] {\n mindex := m;\n }\n m := m+1;\n }\n a[n], a[mindex] := a[mindex], a[n];\n n := n+1;\n }\n}\n" }, { "test_ID": "066", "test_file": "Clover_seq_to_array.dfy", "ground_truth": " method ToArray(xs: seq) returns (a: array)\n ensures fresh(a)\n ensures a.Length == |xs|\n ensures forall i :: 0 <= i < |xs| ==> a[i] == xs[i]\n{\n a := new T[|xs|](i requires 0 <= i < |xs| => xs[i]);\n}\n", "hints_removed": " method ToArray(xs: seq) returns (a: array)\n ensures fresh(a)\n ensures a.Length == |xs|\n ensures forall i :: 0 <= i < |xs| ==> a[i] == xs[i]\n{\n a := new T[|xs|](i requires 0 <= i < |xs| => xs[i]);\n}\n" }, { "test_ID": "067", "test_file": "Clover_set_to_seq.dfy", "ground_truth": "method SetToSeq(s: set) returns (xs: seq)\n ensures multiset(s) == multiset(xs)\n{\n xs := [];\n var left: set := s;\n while left != {}\n invariant multiset(left) + multiset(xs) == multiset(s)\n {\n var x :| x in left;\n left := left - {x};\n xs := xs + [x];\n }\n}\n", "hints_removed": "method SetToSeq(s: set) returns (xs: seq)\n ensures multiset(s) == multiset(xs)\n{\n xs := [];\n var left: set := s;\n while left != {}\n {\n var x :| x in left;\n left := left - {x};\n xs := xs + [x];\n }\n}\n" }, { "test_ID": "068", "test_file": "Clover_slope_search.dfy", "ground_truth": "method SlopeSearch(a: array2, key: int) returns (m:int, n:int)\n requires forall i,j,j'::0<=i a[i,j]<=a[i,j']\n requires forall i,i',j::0<=i a[i,j]<=a[i',j]\n requires exists i,j :: 0<=i, key: int) returns (m:int, n:int)\n requires forall i,j,j'::0<=i a[i,j]<=a[i,j']\n requires forall i,i',j::0<=i a[i,j]<=a[i',j]\n requires exists i,j :: 0<=i, i: int, j: int)\n requires 0 <= i < arr.Length && 0 <= j < arr.Length\n modifies arr\n ensures arr[i] == old(arr[j]) && arr[j] == old(arr[i])\n ensures forall k :: 0 <= k < arr.Length && k != i && k != j ==> arr[k] == old(arr[k])\n{\n var tmp := arr[i];\n arr[i] := arr[j];\n arr[j] := tmp;\n}\n", "hints_removed": "method swap(arr: array, i: int, j: int)\n requires 0 <= i < arr.Length && 0 <= j < arr.Length\n modifies arr\n ensures arr[i] == old(arr[j]) && arr[j] == old(arr[i])\n ensures forall k :: 0 <= k < arr.Length && k != i && k != j ==> arr[k] == old(arr[k])\n{\n var tmp := arr[i];\n arr[i] := arr[j];\n arr[j] := tmp;\n}\n" }, { "test_ID": "073", "test_file": "Clover_swap_sim.dfy", "ground_truth": "method SwapSimultaneous(X: int, Y: int) returns(x: int, y: int)\n ensures x==Y\n ensures y==X\n{\n x, y := X, Y;\n x, y := y, x;\n}\n", "hints_removed": "method SwapSimultaneous(X: int, Y: int) returns(x: int, y: int)\n ensures x==Y\n ensures y==X\n{\n x, y := X, Y;\n x, y := y, x;\n}\n" }, { "test_ID": "074", "test_file": "Clover_test_array.dfy", "ground_truth": "method TestArrayElements(a:array, j: nat)\n requires 0<=j < a.Length\n modifies a\n ensures a[j] == 60\n ensures forall k :: 0 <= k < a.Length && k != j ==> a[k] == old(a[k])\n{\n a[j] := 60;\n}\n", "hints_removed": "method TestArrayElements(a:array, j: nat)\n requires 0<=j < a.Length\n modifies a\n ensures a[j] == 60\n ensures forall k :: 0 <= k < a.Length && k != j ==> a[k] == old(a[k])\n{\n a[j] := 60;\n}\n" }, { "test_ID": "075", "test_file": "Clover_triple.dfy", "ground_truth": "method Triple (x:int) returns (r:int)\n ensures r==3*x\n{\n r:= x*3;\n}\n", "hints_removed": "method Triple (x:int) returns (r:int)\n ensures r==3*x\n{\n r:= x*3;\n}\n" }, { "test_ID": "076", "test_file": "Clover_triple2.dfy", "ground_truth": "method Triple (x:int) returns (r:int)\n ensures r==3*x\n{\n if {\n case x<18 =>\n var a,b := 2*x, 4*x;\n r:=(a+b)/2;\n case 0<=x =>\n var y:=2*x;\n r:= x+y;\n }\n}\n", "hints_removed": "method Triple (x:int) returns (r:int)\n ensures r==3*x\n{\n if {\n case x<18 =>\n var a,b := 2*x, 4*x;\n r:=(a+b)/2;\n case 0<=x =>\n var y:=2*x;\n r:= x+y;\n }\n}\n" }, { "test_ID": "077", "test_file": "Clover_triple3.dfy", "ground_truth": "method Triple (x:int) returns (r:int)\n ensures r==3*x\n{\n if x==0 {\n r:=0;\n }\n else{\n var y:=2*x;\n r:= x+y;\n }\n}\n", "hints_removed": "method Triple (x:int) returns (r:int)\n ensures r==3*x\n{\n if x==0 {\n r:=0;\n }\n else{\n var y:=2*x;\n r:= x+y;\n }\n}\n" }, { "test_ID": "078", "test_file": "Clover_triple4.dfy", "ground_truth": "method Triple (x:int) returns (r:int)\n ensures r==3*x\n{\n var y:= x*2;\n r := y+x;\n}\n", "hints_removed": "method Triple (x:int) returns (r:int)\n ensures r==3*x\n{\n var y:= x*2;\n r := y+x;\n}\n" }, { "test_ID": "079", "test_file": "Clover_two_sum.dfy", "ground_truth": "method twoSum(nums: array, target: int) returns (i: int, j: int)\n requires nums.Length > 1\n requires exists i,j::0 <= i < j < nums.Length && nums[i] + nums[j] == target\n ensures 0 <= i < j < nums.Length && nums[i] + nums[j] == target\n ensures forall ii,jj:: (0 <= ii < i && ii < jj < nums.Length) ==> nums[ii] + nums[jj] != target\n ensures forall jj:: i < jj < j ==> nums[i] + nums[jj] != target\n{\n var n := nums.Length;\n i := 0;\n j := 1;\n while i < n - 1\n invariant 0 <= i < j <= n\n invariant forall ii, jj :: 0 <= ii < i && ii < jj < n ==> nums[ii] + nums[jj] != target\n {\n j := i + 1;\n while j < n\n invariant 0 <= i < j <= n\n invariant forall jj :: i < jj < j ==> nums[i] + nums[jj] != target\n {\n if nums[i] + nums[j] == target {\n return;\n }\n j := j + 1;\n }\n\n i := i + 1;\n }\n}\n", "hints_removed": "method twoSum(nums: array, target: int) returns (i: int, j: int)\n requires nums.Length > 1\n requires exists i,j::0 <= i < j < nums.Length && nums[i] + nums[j] == target\n ensures 0 <= i < j < nums.Length && nums[i] + nums[j] == target\n ensures forall ii,jj:: (0 <= ii < i && ii < jj < nums.Length) ==> nums[ii] + nums[jj] != target\n ensures forall jj:: i < jj < j ==> nums[i] + nums[jj] != target\n{\n var n := nums.Length;\n i := 0;\n j := 1;\n while i < n - 1\n {\n j := i + 1;\n while j < n\n {\n if nums[i] + nums[j] == target {\n return;\n }\n j := j + 1;\n }\n\n i := i + 1;\n }\n}\n" }, { "test_ID": "080", "test_file": "Clover_update_array.dfy", "ground_truth": "method UpdateElements(a: array)\n requires a.Length >= 8\n modifies a\n ensures old(a[4]) +3 == a[4]\n ensures a[7]==516\n ensures forall i::0 <= i i != 7 && i != 4 ==> a[i] == old(a[i])\n{\n a[4] := a[4] + 3;\n a[7] := 516;\n}\n", "hints_removed": "method UpdateElements(a: array)\n requires a.Length >= 8\n modifies a\n ensures old(a[4]) +3 == a[4]\n ensures a[7]==516\n ensures forall i::0 <= i i != 7 && i != 4 ==> a[i] == old(a[i])\n{\n a[4] := a[4] + 3;\n a[7] := 516;\n}\n" }, { "test_ID": "081", "test_file": "Clover_update_map.dfy", "ground_truth": "method update_map(m1: map, m2: map) returns (r: map)\n ensures (forall k :: k in m2 ==> k in r)\n ensures (forall k :: k in m1 ==> k in r)\n ensures (forall k :: k in m2 ==> r[k] == m2[k])\n ensures (forall k :: !(k in m2) && k in m1 ==> r[k] == m1[k])\n ensures (forall k :: !(k in m2) && !(k in m1) ==> !(k in r))\n{\n r:= map k | k in (m1.Keys + m2.Keys) :: if k in m2 then m2[k] else m1[k];\n}\n", "hints_removed": "method update_map(m1: map, m2: map) returns (r: map)\n ensures (forall k :: k in m2 ==> k in r)\n ensures (forall k :: k in m1 ==> k in r)\n ensures (forall k :: k in m2 ==> r[k] == m2[k])\n ensures (forall k :: !(k in m2) && k in m1 ==> r[k] == m1[k])\n ensures (forall k :: !(k in m2) && !(k in m1) ==> !(k in r))\n{\n r:= map k | k in (m1.Keys + m2.Keys) :: if k in m2 then m2[k] else m1[k];\n}\n" }, { "test_ID": "082", "test_file": "Correctness_tmp_tmpwqvg5q_4_HoareLogic_exam.dfy", "ground_truth": "// Redo for exam\n\nfunction gcd(a: nat, b: nat): nat\n\nlemma r1(a: nat)\n ensures gcd(a, 0) == a\n\nlemma r2(a:nat)\n ensures gcd(a, a) == a\n\nlemma r3(a: nat, b: nat)\n ensures gcd(a, b) == gcd(b, a)\n\nlemma r4 (a: nat, b: nat)\n ensures b > 0 ==> gcd(a, b) == gcd(b, a % b)\n\nmethod GCD1(a: int, b: int) returns (r: int)\n requires a > 0 && b > 0\n ensures gcd(a,b) == r\n decreases b\n{\n if a < b {\n r3(a,b);\n r := GCD1(b, a);\n } else if (a % b == 0) {\n r4(a,b);\n assert b > 0;\n assert gcd(a, b) == gcd(b, a % b);\n assert a % b == 0;\n assert gcd(a, b) == gcd(b, 0);\n r1(b);\n assert gcd(a, b) == b;\n r := b;\n assert gcd(a,b) == r;\n } else {\n r4(a,b);\n r := GCD1(b, a % b);\n assert gcd(a,b) == r;\n }\n assert gcd(a,b) == r;\n}\n\nmethod GCD2(a: int, b: int) returns (r: int)\n requires a > 0 && b >= 0\n decreases b\n ensures gcd(a,b) == r\n{\n r1(a);\n r4(a,b);\n assert\n ( b != 0 || (a > 0 && b >= 0 && gcd(a,b) == a) )\n &&\n ( (b < 0 || b == 0) || (b > 0 && (a % b) >= 0 ==> gcd(a,b) == gcd(b,(a % b))) );\n assert\n b != 0 || (a > 0 && b >= 0 && gcd(a,b) == a);\n assert\n b == 0 ==> a > 0 && b >= 0 && gcd(a,b) == a;\n assert\n (b < 0 || b == 0) || (b > 0 && (a % b) >= 0 ==> gcd(a,b) == gcd(b,(a % b)));\n assert\n b >= 0 && b != 0 ==> b > 0 && (a % b) >= 0 ==> gcd(a,b) == gcd(b,(a % b));\n if b == 0 {\n r1(a);\n assert\n gcd(a,b) == a;\n r := a;\n assert\n gcd(a,b) == r;\n } else {\n r4(a,b);\n // Method call rule\n assert\n b > 0 && (a % b) >= 0 ==> gcd(a,b) == gcd(b,(a % b));\n // assert\n // gcd(a,b) == GCD2(b, a % b);\n r := GCD2(b, a % b);\n assert\n gcd(a,b) == r;\n }\n assert\n gcd(a,b) == r;\n}\n", "hints_removed": "// Redo for exam\n\nfunction gcd(a: nat, b: nat): nat\n\nlemma r1(a: nat)\n ensures gcd(a, 0) == a\n\nlemma r2(a:nat)\n ensures gcd(a, a) == a\n\nlemma r3(a: nat, b: nat)\n ensures gcd(a, b) == gcd(b, a)\n\nlemma r4 (a: nat, b: nat)\n ensures b > 0 ==> gcd(a, b) == gcd(b, a % b)\n\nmethod GCD1(a: int, b: int) returns (r: int)\n requires a > 0 && b > 0\n ensures gcd(a,b) == r\n{\n if a < b {\n r3(a,b);\n r := GCD1(b, a);\n } else if (a % b == 0) {\n r4(a,b);\n r1(b);\n r := b;\n } else {\n r4(a,b);\n r := GCD1(b, a % b);\n }\n}\n\nmethod GCD2(a: int, b: int) returns (r: int)\n requires a > 0 && b >= 0\n ensures gcd(a,b) == r\n{\n r1(a);\n r4(a,b);\n ( b != 0 || (a > 0 && b >= 0 && gcd(a,b) == a) )\n &&\n ( (b < 0 || b == 0) || (b > 0 && (a % b) >= 0 ==> gcd(a,b) == gcd(b,(a % b))) );\n b != 0 || (a > 0 && b >= 0 && gcd(a,b) == a);\n b == 0 ==> a > 0 && b >= 0 && gcd(a,b) == a;\n (b < 0 || b == 0) || (b > 0 && (a % b) >= 0 ==> gcd(a,b) == gcd(b,(a % b)));\n b >= 0 && b != 0 ==> b > 0 && (a % b) >= 0 ==> gcd(a,b) == gcd(b,(a % b));\n if b == 0 {\n r1(a);\n gcd(a,b) == a;\n r := a;\n gcd(a,b) == r;\n } else {\n r4(a,b);\n // Method call rule\n b > 0 && (a % b) >= 0 ==> gcd(a,b) == gcd(b,(a % b));\n // assert\n // gcd(a,b) == GCD2(b, a % b);\n r := GCD2(b, a % b);\n gcd(a,b) == r;\n }\n gcd(a,b) == r;\n}\n" }, { "test_ID": "083", "test_file": "Correctness_tmp_tmpwqvg5q_4_MethodCalls_q1.dfy", "ground_truth": "/**\n (a) Verify whether or not the following program\n satisfies total correctness.\n You should use weakest precondition reasoning\n and may extend the loop invariant if required.\n You will need to add a decreases clause to prove termination\n (a) Weakest precondition proof (without termination) (6 marks)\n Termination proof (2marks)\n*/\n\nfunction fusc(n: int): nat\n\nlemma rule1()\n ensures fusc(0) == 0\n\nlemma rule2()\n ensures fusc(1) == 1\n\nlemma rule3(n:nat)\n ensures fusc(2*n) == fusc(n)\n\nlemma rule4(n:nat)\n ensures fusc(2*n+1) == fusc(n) + fusc(n+1)\n\n\nmethod ComputeFusc(N: int) returns (b: int)\n requires N >= 0 \n ensures b == fusc(N)\n{\n b := 0;\n var n, a := N, 1;\n assert 0 <= n <= N;\n assert fusc(N) == a * fusc(n) + b * fusc(n + 1);\n\n while (n != 0)\n invariant 0 <= n <= N // J\n invariant fusc(N) == a * fusc(n) + b * fusc(n + 1) // J\n decreases n // D\n {\n ghost var d := n; // termination metric\n\n assert fusc(N) == a * fusc(n) + b * fusc(n + 1);\n\n assert n != 0;\n\n assert (n % 2 != 0 && n % 2 == 0) || fusc(N) == a * fusc(n) + b * fusc(n + 1);\n assert (n % 2 != 0 || n % 2 == 0) ==> fusc(N) == a * fusc(n) + b * fusc(n + 1);\n\n assert n % 2 != 0 || fusc(N) == a * fusc(n) + b * fusc(n + 1);\n assert n % 2 == 0 || fusc(N) == a * fusc(n) + b * fusc(n + 1);\n \n assert n % 2 == 0 ==> fusc(N) == a * fusc(n) + b * fusc(n + 1);\n assert n % 2 != 0 ==> fusc(N) == a * fusc(n) + b * fusc(n + 1);\n\n if (n % 2 == 0)\n {\n rule4(n/2);\n assert fusc((n/2) + 1) == fusc(n + 1) - fusc(n/2);\n \n rule3(n/2);\n assert fusc(n/2) == fusc(n);\n \n assert fusc(N) == (a + b) * fusc(n/2) + b * fusc((n/2) + 1);\n \n a := a + b;\n \n assert fusc(N) == a * fusc(n/2) + b * fusc((n/2) + 1);\n \n n := n / 2;\n \n assert fusc(N) == a * fusc(n) + b * fusc(n + 1);\n } else {\n rule4((n-1)/2);\n assert fusc(n) - fusc((n-1)/2) == fusc(((n-1)/2)+1);\n \n rule3((n-1)/2);\n assert fusc((n-1)/2) == fusc(n-1);\n\n assert fusc(((n-1)/2)+1) == fusc((n+1)/2);\n \n rule3((n+1)/2);\n assert fusc((n+1)/2) == fusc(n+1);\n\n assert fusc(N) == a * fusc(n) + b * fusc(n + 1);\n\n assert fusc(N) == b * fusc(((n-1)/2)+1) + a * fusc(n);\n\n assert fusc(N) ==\n b * fusc(n) - b * fusc(n) + b * fusc(((n-1)/2)+1) + a * fusc(n);\n \n assert fusc(N) ==\n b * fusc(n) - b * (fusc(n) - fusc(((n-1)/2)+1)) + a * fusc(n);\n \n assert fusc(N) == b * fusc(n) - b * fusc((n-1)/2) + a * fusc(n);\n \n assert fusc(N) == b * fusc(n) - b * fusc(n-1) + a * fusc(n);\n \n assert fusc(N) == b * fusc(n) - b * fusc(n-1) + a * fusc(n);\n \n assert fusc(N) ==\n a * fusc(n - 1) + b * fusc(n) - b * fusc(n-1) + a * fusc(n) - a * fusc(n-1);\n assert fusc(N) == a * fusc(n - 1) + (b + a) * (fusc(n) - fusc(n-1));\n \n assert fusc(N) == a * fusc((n - 1)) + (b + a) * (fusc(n) - fusc((n-1)/2));\n\n assert fusc(N) == a * fusc((n - 1) / 2) + (b + a) * fusc(((n - 1) / 2) + 1);\n \n b := b + a;\n \n assert fusc(N) == a * fusc((n - 1) / 2) + b * fusc(((n - 1) / 2) + 1);\n \n n := (n - 1) / 2;\n\n assert fusc(N) == a * fusc(n) + b * fusc(n + 1);\n }\n assert n < d; // termination metric\n assert fusc(N) == a * fusc(n) + b * fusc(n + 1); // J\n }\n assert n == 0; // !B\n\n rule1();\n assert fusc(0) == 0;\n\n rule2();\n assert fusc(1) == 1;\n\n assert fusc(N) == a * fusc(0) + b * fusc(0 + 1); // J\n\n assert fusc(N) == a * 0 + b * 1; // J\n assert b == fusc(N);\n}\n", "hints_removed": "/**\n (a) Verify whether or not the following program\n satisfies total correctness.\n You should use weakest precondition reasoning\n and may extend the loop invariant if required.\n You will need to add a decreases clause to prove termination\n (a) Weakest precondition proof (without termination) (6 marks)\n Termination proof (2marks)\n*/\n\nfunction fusc(n: int): nat\n\nlemma rule1()\n ensures fusc(0) == 0\n\nlemma rule2()\n ensures fusc(1) == 1\n\nlemma rule3(n:nat)\n ensures fusc(2*n) == fusc(n)\n\nlemma rule4(n:nat)\n ensures fusc(2*n+1) == fusc(n) + fusc(n+1)\n\n\nmethod ComputeFusc(N: int) returns (b: int)\n requires N >= 0 \n ensures b == fusc(N)\n{\n b := 0;\n var n, a := N, 1;\n\n while (n != 0)\n {\n ghost var d := n; // termination metric\n\n\n\n\n \n\n if (n % 2 == 0)\n {\n rule4(n/2);\n \n rule3(n/2);\n \n \n a := a + b;\n \n \n n := n / 2;\n \n } else {\n rule4((n-1)/2);\n \n rule3((n-1)/2);\n\n \n rule3((n+1)/2);\n\n\n\n b * fusc(n) - b * fusc(n) + b * fusc(((n-1)/2)+1) + a * fusc(n);\n \n b * fusc(n) - b * (fusc(n) - fusc(((n-1)/2)+1)) + a * fusc(n);\n \n \n \n \n a * fusc(n - 1) + b * fusc(n) - b * fusc(n-1) + a * fusc(n) - a * fusc(n-1);\n \n\n \n b := b + a;\n \n \n n := (n - 1) / 2;\n\n }\n }\n\n rule1();\n\n rule2();\n\n\n}\n" }, { "test_ID": "084", "test_file": "Correctness_tmp_tmpwqvg5q_4_Sorting_Tangent.dfy", "ground_truth": "/**\n Ather, Mohammad Faiz (s4648481/3)\n CSSE3100\n Assignemnt 3\n The University of Queensland\n */\n\n// Question 1\nmethod Tangent(r: array, x: array)\n returns (found: bool)\n requires forall i:: 1 <= i < x.Length ==> \n x[i-1] < x[i]\n requires forall i, j ::\n 0 <= i < j < x.Length ==>\n x[i] < x[j]\n ensures !found ==>\n forall i,j ::\n 0 <= i < r.Length &&\n 0 <= j < x.Length ==>\n r[i] != x[j]\n ensures found ==>\n exists i,j ::\n 0 <= i < r.Length &&\n 0 <= j < x.Length &&\n r[i] == x[j]\n{\n found := false;\n var n, f := 0, x.Length;\n\n while n != r.Length && !found\n invariant 0 <= n <= r.Length\n invariant !found ==>\n forall i,j ::\n 0 <= i < n &&\n 0 <= j < x.Length ==>\n r[i] != x[j]\n invariant found ==>\n exists i,j ::\n 0 <= i < r.Length &&\n 0 <= j < x.Length &&\n n == i && f == j &&\n r[i] == x[j]\n decreases r.Length - n, !found\n {\n f := BinarySearch(x, r[n]);\n /*\n not iterate over either array\n once a tangent has been found\n */ // see if\n if (f != x.Length && r[n] == x[f]) {\n found := true;\n } else {\n n := n + 1;\n }\n }\n\n assert\n (!found && n == r.Length) ||\n ( found && n != r.Length && r[n] == x[f]);\n assert\n !false; // sanity check\n}\n\n// Author: Leino, Title: Program Proofs\nmethod BinarySearch(a: array, circle: int)\n returns (n: int)\n requires forall i ::\n 1 <= i < a.Length\n ==> a[i-1] < a[i]\n requires forall i, j ::\n 0 <= i < j < a.Length ==>\n a[i] < a[j]\n ensures 0 <= n <= a.Length\n ensures forall i ::\n 0 <= i < n ==>\n a[i] < circle\n ensures forall i ::\n n <= i < a.Length ==>\n circle <= a[i]\n{\n var lo, hi := 0, a.Length;\n\n while lo < hi\n invariant 0 <= lo <= hi <= a.Length\n invariant forall i ::\n 0 <= i < lo ==>\n a[i] < circle\n invariant forall i ::\n hi <= i < a.Length ==>\n a[i] >= circle\n decreases hi - lo\n {\n var mid := (lo + hi) / 2;\n calc {\n lo;\n ==\n (lo + lo) / 2;\n <= { assert lo <= hi; }\n (lo + hi) / 2;\n < { assert lo < hi; }\n (hi + hi) / 2;\n ==\n hi;\n }\n /*\n for a given circle in r,\n should not iterate over array x\n once it can be deduced that\n no tangent will be found for that circle.\n */ // see if and 1st else if\n if (a[lo] > circle) {\n hi := lo;\n } else if (a[hi-1] < circle) {\n lo := hi;\n } else if (a[mid] < circle) {\n lo := mid + 1;\n } else {\n hi := mid;\n }\n }\n\n n := lo;\n assert\n !false; // sanity check\n}\n\n", "hints_removed": "/**\n Ather, Mohammad Faiz (s4648481/3)\n CSSE3100\n Assignemnt 3\n The University of Queensland\n */\n\n// Question 1\nmethod Tangent(r: array, x: array)\n returns (found: bool)\n requires forall i:: 1 <= i < x.Length ==> \n x[i-1] < x[i]\n requires forall i, j ::\n 0 <= i < j < x.Length ==>\n x[i] < x[j]\n ensures !found ==>\n forall i,j ::\n 0 <= i < r.Length &&\n 0 <= j < x.Length ==>\n r[i] != x[j]\n ensures found ==>\n exists i,j ::\n 0 <= i < r.Length &&\n 0 <= j < x.Length &&\n r[i] == x[j]\n{\n found := false;\n var n, f := 0, x.Length;\n\n while n != r.Length && !found\n forall i,j ::\n 0 <= i < n &&\n 0 <= j < x.Length ==>\n r[i] != x[j]\n exists i,j ::\n 0 <= i < r.Length &&\n 0 <= j < x.Length &&\n n == i && f == j &&\n r[i] == x[j]\n {\n f := BinarySearch(x, r[n]);\n /*\n not iterate over either array\n once a tangent has been found\n */ // see if\n if (f != x.Length && r[n] == x[f]) {\n found := true;\n } else {\n n := n + 1;\n }\n }\n\n (!found && n == r.Length) ||\n ( found && n != r.Length && r[n] == x[f]);\n !false; // sanity check\n}\n\n// Author: Leino, Title: Program Proofs\nmethod BinarySearch(a: array, circle: int)\n returns (n: int)\n requires forall i ::\n 1 <= i < a.Length\n ==> a[i-1] < a[i]\n requires forall i, j ::\n 0 <= i < j < a.Length ==>\n a[i] < a[j]\n ensures 0 <= n <= a.Length\n ensures forall i ::\n 0 <= i < n ==>\n a[i] < circle\n ensures forall i ::\n n <= i < a.Length ==>\n circle <= a[i]\n{\n var lo, hi := 0, a.Length;\n\n while lo < hi\n 0 <= i < lo ==>\n a[i] < circle\n hi <= i < a.Length ==>\n a[i] >= circle\n {\n var mid := (lo + hi) / 2;\n calc {\n lo;\n ==\n (lo + lo) / 2;\n <= { assert lo <= hi; }\n (lo + hi) / 2;\n < { assert lo < hi; }\n (hi + hi) / 2;\n ==\n hi;\n }\n /*\n for a given circle in r,\n should not iterate over array x\n once it can be deduced that\n no tangent will be found for that circle.\n */ // see if and 1st else if\n if (a[lo] > circle) {\n hi := lo;\n } else if (a[hi-1] < circle) {\n lo := hi;\n } else if (a[mid] < circle) {\n lo := mid + 1;\n } else {\n hi := mid;\n }\n }\n\n n := lo;\n !false; // sanity check\n}\n\n" }, { "test_ID": "085", "test_file": "Dafny-Exercises_tmp_tmpjm75muf__Session10Exercises_ExerciseBarrier.dfy", "ground_truth": "\n\n\n//Method barrier below receives an array and an integer p\n//and returns a boolean b which is true if and only if \n//all the positions to the left of p and including also position p contain elements \n//that are strictly smaller than all the elements contained in the positions to the right of p \n\n//Examples:\n// If v=[7,2,5,8] and p=0 or p=1 then the method must return false, \n// but for p=2 the method should return true\n//1.Specify the method\n//2.Implement an O(v.size()) method\n//3.Verify the method\n\nmethod barrier(v:array,p:int) returns (b:bool)\n//Give the precondition\n//Give the postcondition\n//{Implement and verify}\nrequires v.Length > 0\nrequires 0<=p v[k] v[max] >= v[k]\n {\n if(v[i]>v[max]){\n max:=i;\n }\n \n i:=i+1;\n }\n\n while(iv[max])\n decreases v.Length - i\n invariant 0<=i<=v.Length\n invariant forall k::0<=k<=p ==> v[k]<=v[max]\n invariant forall k::p v[k] > v[max]\n {\n i:=i+1;\n }\n b:=i==v.Length;\n}\n\n", "hints_removed": "\n\n\n//Method barrier below receives an array and an integer p\n//and returns a boolean b which is true if and only if \n//all the positions to the left of p and including also position p contain elements \n//that are strictly smaller than all the elements contained in the positions to the right of p \n\n//Examples:\n// If v=[7,2,5,8] and p=0 or p=1 then the method must return false, \n// but for p=2 the method should return true\n//1.Specify the method\n//2.Implement an O(v.size()) method\n//3.Verify the method\n\nmethod barrier(v:array,p:int) returns (b:bool)\n//Give the precondition\n//Give the postcondition\n//{Implement and verify}\nrequires v.Length > 0\nrequires 0<=p v[k]v[max]){\n max:=i;\n }\n \n i:=i+1;\n }\n\n while(iv[max])\n {\n i:=i+1;\n }\n b:=i==v.Length;\n}\n\n" }, { "test_ID": "086", "test_file": "Dafny-Exercises_tmp_tmpjm75muf__Session2Exercises_ExerciseExp.dfy", "ground_truth": "function exp(x:int, e:int):int\n decreases e\n\trequires e >= 0\n ensures x > 0 ==> exp(x,e) > 0\n{\nif e == 0 then 1 else x*exp(x,e-1)\n}\n\nlemma exp3_Lemma(n:int) \n decreases n\n requires n >= 1\n\tensures (exp(3,n)-1)%2 == 0\n{}\n\nlemma mult8_Lemma(n:int)\n decreases n\n\trequires n >= 1\n\tensures (exp(3,2*n) - 1)%8 == 0\n{\n if(n==1){\n\n }\n else{\n calc =={\n (exp(3,2*n) -1) % 8;\n (exp(3, 2*(n-1)) *8 + exp(3,2*(n-1)) - 1) % 8;\n {\n mult8_Lemma(n-1);\n assert exp(3,2*(n-1)) * 8 %8==0;\n }\n 0;\n }\n }\n}\n\n", "hints_removed": "function exp(x:int, e:int):int\n\trequires e >= 0\n ensures x > 0 ==> exp(x,e) > 0\n{\nif e == 0 then 1 else x*exp(x,e-1)\n}\n\nlemma exp3_Lemma(n:int) \n requires n >= 1\n\tensures (exp(3,n)-1)%2 == 0\n{}\n\nlemma mult8_Lemma(n:int)\n\trequires n >= 1\n\tensures (exp(3,2*n) - 1)%8 == 0\n{\n if(n==1){\n\n }\n else{\n calc =={\n (exp(3,2*n) -1) % 8;\n (exp(3, 2*(n-1)) *8 + exp(3,2*(n-1)) - 1) % 8;\n {\n mult8_Lemma(n-1);\n }\n 0;\n }\n }\n}\n\n" }, { "test_ID": "087", "test_file": "Dafny-Exercises_tmp_tmpjm75muf__Session2Exercises_ExerciseFibonacci.dfy", "ground_truth": "function fib(n: nat): nat\ndecreases n\n{\n if n == 0 then 0 else\n if n == 1 then 1 else\n fib(n - 1) + fib(n - 2)\n}\n\nmethod fibonacci1(n:nat) returns (f:nat)\nensures f==fib(n)\n{\n var i := 0;\n f := 0;\n var fsig := 1;\n while i < n\n decreases n - i//write the bound\n invariant f==fib(i) && fsig==fib(i+1)//write the invariant\n invariant i<=n\n {\n f, fsig := fsig, f + fsig;\n i := i + 1;\n }\n}\n\nmethod fibonacci2(n:nat) returns (f:nat)\nensures f==fib(n)\n{\nif (n==0) {f:=0;}\nelse{\n var i := 1;\n var fant := 0;\n f := 1;\n while i < n\n decreases n-i//write the bound\n invariant fant==fib(i-1) && f==fib(i)//write the invariant\n invariant i<=n\n {\n fant, f := f, fant + f;\n i := i + 1;\n }\n}\n\n}\n\nmethod fibonacci3(n:nat) returns (f:nat)\nensures f==fib(n)\n{\n\n{\n var i: int := 0;\n var a := 1;\n f := 0; \n while i < n\n decreases n-i//write the bound\n invariant 0<=i<=n\n invariant if i ==0 then a==fib(i+1) && f==fib(i)//write the invariant \n else a==fib(i-1) && f==fib(i)\n {\n a, f := f, a + f; \n i := i + 1;\n }\n}\n}\n\n", "hints_removed": "function fib(n: nat): nat\n{\n if n == 0 then 0 else\n if n == 1 then 1 else\n fib(n - 1) + fib(n - 2)\n}\n\nmethod fibonacci1(n:nat) returns (f:nat)\nensures f==fib(n)\n{\n var i := 0;\n f := 0;\n var fsig := 1;\n while i < n\n {\n f, fsig := fsig, f + fsig;\n i := i + 1;\n }\n}\n\nmethod fibonacci2(n:nat) returns (f:nat)\nensures f==fib(n)\n{\nif (n==0) {f:=0;}\nelse{\n var i := 1;\n var fant := 0;\n f := 1;\n while i < n\n {\n fant, f := f, fant + f;\n i := i + 1;\n }\n}\n\n}\n\nmethod fibonacci3(n:nat) returns (f:nat)\nensures f==fib(n)\n{\n\n{\n var i: int := 0;\n var a := 1;\n f := 0; \n while i < n\n else a==fib(i-1) && f==fib(i)\n {\n a, f := f, a + f; \n i := i + 1;\n }\n}\n}\n\n" }, { "test_ID": "088", "test_file": "Dafny-Exercises_tmp_tmpjm75muf__Session2Exercises_ExercisePositive.dfy", "ground_truth": "predicate positive(s:seq)\n{forall u::0<=u<|s| ==> s[u]>=0}\n\n\nmethod mpositive(v:array) returns (b:bool)\nensures b==positive(v[0..v.Length])\n{\n var i:=0;\n //1. assert positive(v[..0])\n while i=0\n decreases v.Length - i \n invariant 0<=i<=v.Length\n invariant positive(v[..i])\n {\n //2. assert 0<=i positive(v[..]);\n //3. assert i v[i]<0;\n b := i==v.Length;\n}\n\nmethod mpositive3(v:array) returns (b:bool)\nensures b==positive(v[0..v.Length])\n{\n var i:=0; b:=true;\n while(i !positive(v[0..v.Length])\n {\n b:=v[i]>=0;\n i:=i+1;\n }\n}\n\nmethod mpositive4(v:array) returns (b:bool)\nensures b==positive(v[0..v.Length])\n{\n var i:=0; b:=true;\n while(i !positive(v[0..v.Length])\n {\n b:=v[i]>=0;\n i:=i+1;\n }\n \n}\n\nmethod mpositivertl(v:array) returns (b:bool)\nensures b==positive(v[0..v.Length])\n{\n var i:=v.Length-1;\n while(i>=0 && v[i]>=0)\n decreases i\n invariant -1 <= i < v.Length\n invariant positive(v[i+1..])\n {\n i:=i-1;\n }\n b:= i==-1;\n}\n\n\n\n", "hints_removed": "predicate positive(s:seq)\n{forall u::0<=u<|s| ==> s[u]>=0}\n\n\nmethod mpositive(v:array) returns (b:bool)\nensures b==positive(v[0..v.Length])\n{\n var i:=0;\n //1. assert positive(v[..0])\n while i=0\n {\n //2. assert 0<=i positive(v[..]);\n //3. assert i v[i]<0;\n b := i==v.Length;\n}\n\nmethod mpositive3(v:array) returns (b:bool)\nensures b==positive(v[0..v.Length])\n{\n var i:=0; b:=true;\n while(i=0;\n i:=i+1;\n }\n}\n\nmethod mpositive4(v:array) returns (b:bool)\nensures b==positive(v[0..v.Length])\n{\n var i:=0; b:=true;\n while(i=0;\n i:=i+1;\n }\n \n}\n\nmethod mpositivertl(v:array) returns (b:bool)\nensures b==positive(v[0..v.Length])\n{\n var i:=v.Length-1;\n while(i>=0 && v[i]>=0)\n {\n i:=i-1;\n }\n b:= i==-1;\n}\n\n\n\n" }, { "test_ID": "089", "test_file": "Dafny-Exercises_tmp_tmpjm75muf__Session2Exercises_ExerciseSquare_root.dfy", "ground_truth": "method mroot1(n:int) returns (r:int) //Cost O(root n)\nrequires n>=0\nensures r>=0 && r*r <= n <(r+1)*(r+1)\n{\n r:=0;\n\twhile (r+1)*(r+1) <=n\n\t invariant r>=0 && r*r <=n\n\t decreases n-r*r\n\t {\n\t r:=r+1;\n\t }\n\n\n}\n\n\nmethod mroot2(n:int) returns (r:int) //Cost O(n)\nrequires n>=0\nensures r>=0 && r*r <= n <(r+1)*(r+1)\n{\n r:=n;\n\twhile n n<(r+1)*(r+1)\n\tdecreases r//write the bound\n\t{\n\t\tr:=r-1;\n\t}\n\n\n}\n\nmethod mroot3(n:int) returns (r:int) //Cost O(log n)\nrequires n>=0\nensures r>=0 && r*r <= n <(r+1)*(r+1)\n{ var y:int;\n var h:int;\n r:=0;\n\ty:=n+1;\n\t//Search in interval [0,n+1) \n\twhile (y!=r+1) //[r,y]\n\t invariant r>=0 && r*r<=n=r+1//\twrite the invariant \n\t decreases y-r//write the bound\n\t {\n\t h:=(r+y)/2;\n\t if (h*h<=n)\n\t {r:=h;}\n\t else\n\t {y:=h;} \n\t }\n\n\n}\n\n", "hints_removed": "method mroot1(n:int) returns (r:int) //Cost O(root n)\nrequires n>=0\nensures r>=0 && r*r <= n <(r+1)*(r+1)\n{\n r:=0;\n\twhile (r+1)*(r+1) <=n\n\t {\n\t r:=r+1;\n\t }\n\n\n}\n\n\nmethod mroot2(n:int) returns (r:int) //Cost O(n)\nrequires n>=0\nensures r>=0 && r*r <= n <(r+1)*(r+1)\n{\n r:=n;\n\twhile n=0\nensures r>=0 && r*r <= n <(r+1)*(r+1)\n{ var y:int;\n var h:int;\n r:=0;\n\ty:=n+1;\n\t//Search in interval [0,n+1) \n\twhile (y!=r+1) //[r,y]\n\t {\n\t h:=(r+y)/2;\n\t if (h*h<=n)\n\t {r:=h;}\n\t else\n\t {y:=h;} \n\t }\n\n\n}\n\n" }, { "test_ID": "090", "test_file": "Dafny-Exercises_tmp_tmpjm75muf__Session3Exercises_ExerciseMaximum.dfy", "ground_truth": "//Algorithm 1: From left to right return the first\nmethod mmaximum1(v:array) returns (i:int) \nrequires v.Length>0\nensures 0<=i v[i]>=v[k]\n{\n var j:=1; i:=0;\n while(j v[i] >= v[k]\n {\n if(v[j] > v[i]){i:=j;}\n j:=j+1;\n }\n}\n\n//Algorithm 2: From right to left return the last\nmethod mmaximum2(v:array) returns (i:int) \nrequires v.Length>0\nensures 0<=i v[i]>=v[k]\n{\n var j:=v.Length-2; i:=v.Length - 1;\n while(j>=0)\n decreases j\n invariant 0<=ik>j ==> v[k]<=v[i]\n {\n if(v[j] > v[i]){i:=j;}\n j:=j-1;\n }\n}\n\n\nmethod mfirstMaximum(v:array) returns (i:int)\nrequires v.Length>0\nensures 0<=i v[i]>=v[k]\nensures forall l:: 0<=l v[i]>v[l]\n//Algorithm: from left to right\n{\n var j:=1; i:=0;\n while(j v[i] >= v[k]\n invariant forall k:: 0<=k v[i] > v[k]\n {\n if(v[j] > v[i]){i:=j;}\n j:=j+1;\n }\n}\n\nmethod mlastMaximum(v:array) returns (i:int)\nrequires v.Length>0\nensures 0<=i v[i]>=v[k]\nensures forall l:: i v[i]>v[l]\n{\n var j:=v.Length-2;\n i := v.Length-1;\n while(j>=0)\n decreases j\n invariant -1<=jk>j ==> v[k]<=v[i]\n invariant forall k :: v.Length>k>i ==> v[k] v[i]){i:=j;}\n j:=j-1;\n }\n}\n\n//Algorithm : from left to right\n//Algorithm : from right to left\n\nmethod mmaxvalue1(v:array) returns (m:int)\nrequires v.Length>0\nensures m in v[..]\nensures forall k::0<=k m>=v[k]\n{\n var i:=mmaximum1(v);\n m:=v[i];\n}\n\nmethod mmaxvalue2(v:array) returns (m:int)\nrequires v.Length>0\nensures m in v[..]\nensures forall k::0<=k m>=v[k]\n{\n var i:=mmaximum2(v);\n m:=v[i];\n}\n", "hints_removed": "//Algorithm 1: From left to right return the first\nmethod mmaximum1(v:array) returns (i:int) \nrequires v.Length>0\nensures 0<=i v[i]>=v[k]\n{\n var j:=1; i:=0;\n while(j v[i]){i:=j;}\n j:=j+1;\n }\n}\n\n//Algorithm 2: From right to left return the last\nmethod mmaximum2(v:array) returns (i:int) \nrequires v.Length>0\nensures 0<=i v[i]>=v[k]\n{\n var j:=v.Length-2; i:=v.Length - 1;\n while(j>=0)\n {\n if(v[j] > v[i]){i:=j;}\n j:=j-1;\n }\n}\n\n\nmethod mfirstMaximum(v:array) returns (i:int)\nrequires v.Length>0\nensures 0<=i v[i]>=v[k]\nensures forall l:: 0<=l v[i]>v[l]\n//Algorithm: from left to right\n{\n var j:=1; i:=0;\n while(j v[i]){i:=j;}\n j:=j+1;\n }\n}\n\nmethod mlastMaximum(v:array) returns (i:int)\nrequires v.Length>0\nensures 0<=i v[i]>=v[k]\nensures forall l:: i v[i]>v[l]\n{\n var j:=v.Length-2;\n i := v.Length-1;\n while(j>=0)\n {\n if(v[j] > v[i]){i:=j;}\n j:=j-1;\n }\n}\n\n//Algorithm : from left to right\n//Algorithm : from right to left\n\nmethod mmaxvalue1(v:array) returns (m:int)\nrequires v.Length>0\nensures m in v[..]\nensures forall k::0<=k m>=v[k]\n{\n var i:=mmaximum1(v);\n m:=v[i];\n}\n\nmethod mmaxvalue2(v:array) returns (m:int)\nrequires v.Length>0\nensures m in v[..]\nensures forall k::0<=k m>=v[k]\n{\n var i:=mmaximum2(v);\n m:=v[i];\n}\n" }, { "test_ID": "091", "test_file": "Dafny-Exercises_tmp_tmpjm75muf__Session4Exercises_ExerciseAllEqual.dfy", "ground_truth": "predicate allEqual(s:seq)\n{forall i,j::0<=i<|s| && 0<=j<|s| ==> s[i]==s[j] }\n//{forall i,j::0<=i<=j<|s| ==> s[i]==s[j] }\n//{forall i::0 s[i-1]==s[i]} \n//{forall i::0<=i<|s|-1 ==> s[i]==s[i+1]}\n\n\n//Ordered indexes\nlemma equivalenceNoOrder(s:seq)\nensures allEqual(s) <==> forall i,j::0<=i<=j<|s| ==> s[i]==s[j]\n{}\n\n//All equal to first\nlemma equivalenceEqualtoFirst(s:seq)\nrequires s!=[]\nensures allEqual(s) <==> (forall i::0<=i<|s| ==> s[0]==s[i])\n{}\n\n\n\nlemma equivalenceContiguous(s:seq)\nensures (allEqual(s) ==> forall i::0<=i<|s|-1 ==> s[i]==s[i+1])\nensures (allEqual(s) <== forall i::0<=i<|s|-1 ==> s[i]==s[i+1])\n{\n assert allEqual(s) ==> forall i::0<=i<|s|-1 ==> s[i]==s[i+1];\n \n if(|s|==0 || |s|==1){\n\n }\n else{\n calc {\n forall i::0<=i<|s|-1 ==> s[i]==s[i+1];\n ==>\n {\n equivalenceContiguous(s[..|s|-1]);\n assert s[|s|-2] == s[|s|-1];\n }\n allEqual(s);\n }\n }\n \n}\n\n\n\nmethod mallEqual1(v:array) returns (b:bool)\nensures b==allEqual(v[0..v.Length])\n{\n var i := 0;\n b := true;\n while (i < v.Length && b) \n\t invariant 0 <= i <= v.Length\n invariant b==allEqual(v[..i])\n\t decreases v.Length - i\n\t { \n b:=(v[i]==v[0]);\n i := i+1;\n \n\t }\n}\n\nmethod mallEqual2(v:array) returns (b:bool)\nensures b==allEqual(v[0..v.Length])\n{\n var i:int; \n b:=true;\n \n i:=0;\n while (i < v.Length && v[i] == v[0])\n\t invariant 0 <= i <= v.Length\n invariant forall k:: 0 <= k < i ==> v[k] == v[0]\n\t decreases v.Length - i\n\t {\n i:=i+1;\n\t }\n\t b:=(i==v.Length);\n\n}\n\n\n\nmethod mallEqual3(v:array) returns (b:bool)\nensures b==allEqual(v[0..v.Length])\n{\nequivalenceContiguous(v[..]);\n var i:int;\n b:=true;\n if (v.Length >0){\n i:=0;\n while (i) returns (b:bool)\nensures b==allEqual(v[0..v.Length])\n{\n var i:int;\n b:=true;\n if (v.Length>0){\n i:=0;\n while (i < v.Length-1 && b)\n invariant 0 <= i < v.Length\n invariant b==allEqual(v[..i+1])\n\t decreases v.Length - i \n {\n\t b:=(v[i]==v[i+1]);\n\t i:=i+1;\n }\n }\n }\n\n\n method mallEqual5(v:array) returns (b:bool)\nensures b==allEqual(v[0..v.Length])\n{\n var i := 0;\n b := true;\n while (i < v.Length && b) \n\t invariant 0<=i<=v.Length//\n invariant b ==> forall k::0<=k v[k] == v[0]\n invariant !b ==> exists k:: 0<=k)\n{forall i,j::0<=i<|s| && 0<=j<|s| ==> s[i]==s[j] }\n//{forall i,j::0<=i<=j<|s| ==> s[i]==s[j] }\n//{forall i::0 s[i-1]==s[i]} \n//{forall i::0<=i<|s|-1 ==> s[i]==s[i+1]}\n\n\n//Ordered indexes\nlemma equivalenceNoOrder(s:seq)\nensures allEqual(s) <==> forall i,j::0<=i<=j<|s| ==> s[i]==s[j]\n{}\n\n//All equal to first\nlemma equivalenceEqualtoFirst(s:seq)\nrequires s!=[]\nensures allEqual(s) <==> (forall i::0<=i<|s| ==> s[0]==s[i])\n{}\n\n\n\nlemma equivalenceContiguous(s:seq)\nensures (allEqual(s) ==> forall i::0<=i<|s|-1 ==> s[i]==s[i+1])\nensures (allEqual(s) <== forall i::0<=i<|s|-1 ==> s[i]==s[i+1])\n{\n \n if(|s|==0 || |s|==1){\n\n }\n else{\n calc {\n forall i::0<=i<|s|-1 ==> s[i]==s[i+1];\n ==>\n {\n equivalenceContiguous(s[..|s|-1]);\n }\n allEqual(s);\n }\n }\n \n}\n\n\n\nmethod mallEqual1(v:array) returns (b:bool)\nensures b==allEqual(v[0..v.Length])\n{\n var i := 0;\n b := true;\n while (i < v.Length && b) \n\t { \n b:=(v[i]==v[0]);\n i := i+1;\n \n\t }\n}\n\nmethod mallEqual2(v:array) returns (b:bool)\nensures b==allEqual(v[0..v.Length])\n{\n var i:int; \n b:=true;\n \n i:=0;\n while (i < v.Length && v[i] == v[0])\n\t {\n i:=i+1;\n\t }\n\t b:=(i==v.Length);\n\n}\n\n\n\nmethod mallEqual3(v:array) returns (b:bool)\nensures b==allEqual(v[0..v.Length])\n{\nequivalenceContiguous(v[..]);\n var i:int;\n b:=true;\n if (v.Length >0){\n i:=0;\n while (i) returns (b:bool)\nensures b==allEqual(v[0..v.Length])\n{\n var i:int;\n b:=true;\n if (v.Length>0){\n i:=0;\n while (i < v.Length-1 && b)\n {\n\t b:=(v[i]==v[i+1]);\n\t i:=i+1;\n }\n }\n }\n\n\n method mallEqual5(v:array) returns (b:bool)\nensures b==allEqual(v[0..v.Length])\n{\n var i := 0;\n b := true;\n while (i < v.Length && b) \n\t { \n if (v[i] != v[0]) { b := false; }\n else { i := i+1;}\n \t}\n \n}\n\n\n\n\n" }, { "test_ID": "092", "test_file": "Dafny-Exercises_tmp_tmpjm75muf__Session4Exercises_ExerciseContained.dfy", "ground_truth": "\n\n\npredicate strictSorted(s : seq) {\n\tforall u, w :: 0 <= u < w < |s| ==> s[u] < s[w]\n}\n\n\nmethod mcontained(v:array,w:array,n:int,m:int) returns (b:bool)\n//Specify and implement an O(m+n) algorithm that returns b\n//v and w are strictly increasing ordered arrays\n//b is true iff the first n elements of v are contained in the first m elements of w\nrequires n<=m && n>=0\nrequires strictSorted(v[..])\nrequires strictSorted(w[..])\nrequires v.Length >= n && w.Length >= m\nensures b==forall k:: 0<= k< n ==> v[k] in w[..m]//exists j :: 0 <= j < m && v[k] == w[j]\n{\n\tvar i:=0;\n\tvar j:=0;\n\twhile(i= w[j])) //&& b)\n\tinvariant 0<=i<=n\n\tinvariant 0<=j<=m\n\tinvariant strictSorted(v[..])\n\tinvariant strictSorted(w[..])\n\tinvariant forall k::0<=k v[k] in w[..j] \n\tinvariant i !(v[i] in w[..j])\n\tdecreases w.Length-j\n\tdecreases v.Length-i\n\t{\t\n\t\tif(v[i] == w[j]){\n\t\t\ti:=i+1;\n\t\t}\n\t\tj:=j+1;\n\t\t\n\t}\n\tassert i !(v[i] in w[..m]);\n\tb := i==n;\n\t\n}\n\n\n", "hints_removed": "\n\n\npredicate strictSorted(s : seq) {\n\tforall u, w :: 0 <= u < w < |s| ==> s[u] < s[w]\n}\n\n\nmethod mcontained(v:array,w:array,n:int,m:int) returns (b:bool)\n//Specify and implement an O(m+n) algorithm that returns b\n//v and w are strictly increasing ordered arrays\n//b is true iff the first n elements of v are contained in the first m elements of w\nrequires n<=m && n>=0\nrequires strictSorted(v[..])\nrequires strictSorted(w[..])\nrequires v.Length >= n && w.Length >= m\nensures b==forall k:: 0<= k< n ==> v[k] in w[..m]//exists j :: 0 <= j < m && v[k] == w[j]\n{\n\tvar i:=0;\n\tvar j:=0;\n\twhile(i= w[j])) //&& b)\n\t{\t\n\t\tif(v[i] == w[j]){\n\t\t\ti:=i+1;\n\t\t}\n\t\tj:=j+1;\n\t\t\n\t}\n\tb := i==n;\n\t\n}\n\n\n" }, { "test_ID": "093", "test_file": "Dafny-Exercises_tmp_tmpjm75muf__Session4Exercises_ExerciseFirstNegative.dfy", "ground_truth": "predicate positive(s:seq)\n{forall u::0<=u<|s| ==> s[u]>=0}\n\n\nmethod mfirstNegative(v:array) returns (b:bool, i:int)\nensures b <==> exists k::0<=k 0<=i exists k::0<=k v[i-1]<0 && positive(v[0..i-1])\n decreases v.Length - i\n { \n b:=(v[i]<0);\n i:=i+1;\n }\n if (b){i:=i-1;}\n}\n\nmethod mfirstNegative2(v:array) returns (b:bool, i:int)\nensures b <==> exists k::0<=k 0<=i i)\n{forall u::0<=u<|s| ==> s[u]>=0}\n\n\nmethod mfirstNegative(v:array) returns (b:bool, i:int)\nensures b <==> exists k::0<=k 0<=i) returns (b:bool, i:int)\nensures b <==> exists k::0<=k 0<=i) returns (i:int)\nensures 0 <=i<=v.Length\nensures forall j:: 0<=j v[j]!=0 \nensures i!=v.Length ==> v[i]==0 \n{\n i:=0;\n while (i v[j]!=0 \n decreases v.Length -i\n {i:=i+1;}\n}\n", "hints_removed": "\nmethod mfirstCero(v:array) returns (i:int)\nensures 0 <=i<=v.Length\nensures forall j:: 0<=j v[j]!=0 \nensures i!=v.Length ==> v[i]==0 \n{\n i:=0;\n while (i):int\ndecreases s\n{\n if (s==[]) then 0\n else SumR(s[..|s|-1])+s[|s|-1]\n}\n\nfunction SumL(s:seq):int\ndecreases s\n{\n if (s==[]) then 0\n else s[0]+SumL(s[1..])\n}\n\n\nlemma concatLast(s:seq,t:seq)\nrequires t!=[]\nensures (s+t)[..|s+t|-1] == s+(t[..|t|-1])\n{}\nlemma concatFirst(s:seq,t:seq)\nrequires s!=[]\nensures (s+t)[1..] == s[1..]+t\n{}\n\nlemma {:induction s,t} SumByPartsR(s:seq,t:seq)\ndecreases s,t\nensures SumR(s+t) == SumR(s)+SumR(t)\n{ if (t==[])\n {assert s+t == s;}\n else if (s==[])\n {assert s+t==t;} \n else\n { \n calc =={\n SumR(s+t);\n SumR((s+t)[..|s+t|-1])+(s+t)[|s+t|-1];\n SumR((s+t)[..|s+t|-1])+t[|t|-1];\n {concatLast(s,t);}\n SumR(s+t[..|t|-1])+t[|t|-1];\n {SumByPartsR(s,t[..|t|-1]);}\n SumR(s)+SumR(t[..|t|-1])+t[|t|-1];\n SumR(s)+SumR(t);\n\n }\n }\n\n\n}\n\n\nlemma {:induction s,t} SumByPartsL(s:seq,t:seq)\ndecreases s,t\nensures SumL(s+t) == SumL(s)+SumL(t)\n//Prove this\n{\n if(t==[]){\n assert s+t==s;\n }\n else if(s==[]){\n assert s+t==t;\n }\n else{\n calc == {\n SumL(s+t);\n (s+t)[0] + SumL((s+t)[1..]);\n s[0] + SumL((s+t)[1..]);\n {concatFirst(s,t);}\n s[0] + SumL(s[1..] + t);\n {SumByPartsL(s[1..], t);}\n s[0] + SumL(s[1..]) + SumL(t);\n }\n }\n}\n\n\n\n\nlemma {:induction s,i,j} equalSumR(s:seq,i:int,j:int)\ndecreases j-i\nrequires 0<=i<=j<=|s|\nensures SumR(s[i..j])==SumL(s[i..j])\n//Prove this\n{\n if(s==[]){\n assert SumR(s) == SumL(s);\n }else{\n if(i==j){\n assert SumR(s[i..j]) == SumL(s[i..j]);\n }\n else{\n calc == {\n SumR(s[i..j]);\n {\n assert s[i..j] == s[i..j-1] + [s[j-1]];\n assert SumR(s[i..j]) == SumR(s[i..j-1]) + s[j-1];\n }\n SumR(s[i..j-1]) + s[j-1];\n {equalSumR(s, i, j-1);}\n SumL(s[i..j-1]) + s[j-1];\n {assert s[j-1] == SumL([s[j-1]]);}\n SumL(s[i..j-1]) + SumL([s[j-1]]);\n {SumByPartsL(s[i..j-1], [s[j-1]]);}\n SumL(s[i..j-1] + [s[j-1]]);\n {\n assert s[i..j] == s[i..j-1] + [s[j-1]];\n }\n SumL(s[i..j]);\n /*SumR(s[i..j-1])+SumR(s[j..j]);\n SumR(s[i..j-1]) + s[j..j];\n SumL(s);*/\n }\n }\n }\n}\n\n\nlemma equalSumsV() \nensures forall v:array,i,j | 0<=i<=j<=v.Length :: SumR(v[i..j])==SumL(v[i..j])\n //proving the forall\n { forall v:array,i,j | 0<=i<=j<=v.Length\n ensures SumR(v[i..j])==SumL(v[i..j])\n {equalSumR(v[..],i,j);}\n }\n\n\nfunction SumV(v:array,c:int,f:int):int\n requires 0<=c<=f<=v.Length\n reads v\n {SumR(v[c..f])}\n\n\nlemma ArrayFacts()\n\tensures forall v : array :: v[..v.Length] == v[..];\n\tensures forall v : array :: v[0..] == v[..];\n ensures forall v : array :: v[0..v.Length] == v[..];\n\n\tensures forall v : array ::|v[0..v.Length]|==v.Length;\n ensures forall v : array | v.Length>=1 ::|v[1..v.Length]|==v.Length-1;\n \n\tensures forall v : array ::forall k : nat | k < v.Length :: v[..k+1][..k] == v[..k]\n // ensures forall v:array,i,j | 0<=i<=j<=v.Length :: SumR(v[i..j])==SumL(v[i..j])\n {equalSumsV();}\n \n\nmethod sumElems(v:array) returns (sum:int)\n//ensures sum==SumL(v[0..v.Length])\nensures sum==SumR(v[..])\n//ensures sum==SumV(v,0,v.Length)\n\n{ArrayFacts();\n sum:=0;\n var i:int;\n i:=0;\n while (i) returns (sum:int)\n//ensures sum==SumL(v[0..v.Length])\nensures sum==SumR(v[0..v.Length])\n{\n ArrayFacts();\n sum:=0;\n var i:int;\n i:=v.Length;\n equalSumsV();\n while(i>0)\n decreases i//write\n invariant 0<=i<=v.Length\n invariant sum == SumL(v[i..]) == SumR(v[i..])\n {\n sum:=sum+v[i-1];\n i:=i-1;\n }\n\n\n}\n\n\n\n\n\n\n\n", "hints_removed": "function SumR(s:seq):int\n{\n if (s==[]) then 0\n else SumR(s[..|s|-1])+s[|s|-1]\n}\n\nfunction SumL(s:seq):int\n{\n if (s==[]) then 0\n else s[0]+SumL(s[1..])\n}\n\n\nlemma concatLast(s:seq,t:seq)\nrequires t!=[]\nensures (s+t)[..|s+t|-1] == s+(t[..|t|-1])\n{}\nlemma concatFirst(s:seq,t:seq)\nrequires s!=[]\nensures (s+t)[1..] == s[1..]+t\n{}\n\nlemma {:induction s,t} SumByPartsR(s:seq,t:seq)\nensures SumR(s+t) == SumR(s)+SumR(t)\n{ if (t==[])\n {assert s+t == s;}\n else if (s==[])\n {assert s+t==t;} \n else\n { \n calc =={\n SumR(s+t);\n SumR((s+t)[..|s+t|-1])+(s+t)[|s+t|-1];\n SumR((s+t)[..|s+t|-1])+t[|t|-1];\n {concatLast(s,t);}\n SumR(s+t[..|t|-1])+t[|t|-1];\n {SumByPartsR(s,t[..|t|-1]);}\n SumR(s)+SumR(t[..|t|-1])+t[|t|-1];\n SumR(s)+SumR(t);\n\n }\n }\n\n\n}\n\n\nlemma {:induction s,t} SumByPartsL(s:seq,t:seq)\nensures SumL(s+t) == SumL(s)+SumL(t)\n//Prove this\n{\n if(t==[]){\n }\n else if(s==[]){\n }\n else{\n calc == {\n SumL(s+t);\n (s+t)[0] + SumL((s+t)[1..]);\n s[0] + SumL((s+t)[1..]);\n {concatFirst(s,t);}\n s[0] + SumL(s[1..] + t);\n {SumByPartsL(s[1..], t);}\n s[0] + SumL(s[1..]) + SumL(t);\n }\n }\n}\n\n\n\n\nlemma {:induction s,i,j} equalSumR(s:seq,i:int,j:int)\nrequires 0<=i<=j<=|s|\nensures SumR(s[i..j])==SumL(s[i..j])\n//Prove this\n{\n if(s==[]){\n }else{\n if(i==j){\n }\n else{\n calc == {\n SumR(s[i..j]);\n {\n }\n SumR(s[i..j-1]) + s[j-1];\n {equalSumR(s, i, j-1);}\n SumL(s[i..j-1]) + s[j-1];\n {assert s[j-1] == SumL([s[j-1]]);}\n SumL(s[i..j-1]) + SumL([s[j-1]]);\n {SumByPartsL(s[i..j-1], [s[j-1]]);}\n SumL(s[i..j-1] + [s[j-1]]);\n {\n }\n SumL(s[i..j]);\n /*SumR(s[i..j-1])+SumR(s[j..j]);\n SumR(s[i..j-1]) + s[j..j];\n SumL(s);*/\n }\n }\n }\n}\n\n\nlemma equalSumsV() \nensures forall v:array,i,j | 0<=i<=j<=v.Length :: SumR(v[i..j])==SumL(v[i..j])\n //proving the forall\n { forall v:array,i,j | 0<=i<=j<=v.Length\n ensures SumR(v[i..j])==SumL(v[i..j])\n {equalSumR(v[..],i,j);}\n }\n\n\nfunction SumV(v:array,c:int,f:int):int\n requires 0<=c<=f<=v.Length\n reads v\n {SumR(v[c..f])}\n\n\nlemma ArrayFacts()\n\tensures forall v : array :: v[..v.Length] == v[..];\n\tensures forall v : array :: v[0..] == v[..];\n ensures forall v : array :: v[0..v.Length] == v[..];\n\n\tensures forall v : array ::|v[0..v.Length]|==v.Length;\n ensures forall v : array | v.Length>=1 ::|v[1..v.Length]|==v.Length-1;\n \n\tensures forall v : array ::forall k : nat | k < v.Length :: v[..k+1][..k] == v[..k]\n // ensures forall v:array,i,j | 0<=i<=j<=v.Length :: SumR(v[i..j])==SumL(v[i..j])\n {equalSumsV();}\n \n\nmethod sumElems(v:array) returns (sum:int)\n//ensures sum==SumL(v[0..v.Length])\nensures sum==SumR(v[..])\n//ensures sum==SumV(v,0,v.Length)\n\n{ArrayFacts();\n sum:=0;\n var i:int;\n i:=0;\n while (i) returns (sum:int)\n//ensures sum==SumL(v[0..v.Length])\nensures sum==SumR(v[0..v.Length])\n{\n ArrayFacts();\n sum:=0;\n var i:int;\n i:=v.Length;\n equalSumsV();\n while(i>0)\n {\n sum:=sum+v[i-1];\n i:=i-1;\n }\n\n\n}\n\n\n\n\n\n\n\n" }, { "test_ID": "096", "test_file": "Dafny-Exercises_tmp_tmpjm75muf__Session6Exercises_ExerciseCountEven.dfy", "ground_truth": "\npredicate positive(s:seq)\n{forall u::0<=u<|s| ==> s[u]>=0}\n\npredicate isEven(i:int)\nrequires i>=0\n{i%2==0}\n\nfunction CountEven(s:seq):int\ndecreases s\nrequires positive(s)\n{if s==[] then 0\n else (if (s[|s|-1]%2==0) then 1 else 0)+CountEven(s[..|s|-1])\n }\n\nlemma ArrayFacts()\n\tensures forall v : array :: v[..v.Length] == v[..];\n\tensures forall v : array :: v[0..] == v[..];\n ensures forall v : array :: v[0..v.Length] == v[..];\n\n\tensures forall v : array ::|v[0..v.Length]|==v.Length;\n ensures forall v : array | v.Length>=1 ::|v[1..v.Length]|==v.Length-1;\n \n\tensures forall v : array ::forall k : nat | k < v.Length :: v[..k+1][..k] == v[..k]\n {}\n\nmethod mcountEven(v:array) returns (n:int)\nrequires positive(v[..])\nensures n==CountEven(v[..])\n{ ArrayFacts(); \n\n n:=0;\n var i:int;\n i:=0;\n while (i)\n{forall u::0<=u<|s| ==> s[u]>=0}\n\npredicate isEven(i:int)\nrequires i>=0\n{i%2==0}\n\nfunction CountEven(s:seq):int\nrequires positive(s)\n{if s==[] then 0\n else (if (s[|s|-1]%2==0) then 1 else 0)+CountEven(s[..|s|-1])\n }\n\nlemma ArrayFacts()\n\tensures forall v : array :: v[..v.Length] == v[..];\n\tensures forall v : array :: v[0..] == v[..];\n ensures forall v : array :: v[0..v.Length] == v[..];\n\n\tensures forall v : array ::|v[0..v.Length]|==v.Length;\n ensures forall v : array | v.Length>=1 ::|v[1..v.Length]|==v.Length-1;\n \n\tensures forall v : array ::forall k : nat | k < v.Length :: v[..k+1][..k] == v[..k]\n {}\n\nmethod mcountEven(v:array) returns (n:int)\nrequires positive(v[..])\nensures n==CountEven(v[..])\n{ ArrayFacts(); \n\n n:=0;\n var i:int;\n i:=0;\n while (i,i:int):int\ndecreases i\n reads v\n requires 1<=i<=v.Length\n ensures forall k::0<=k v[k]>=min(v,i)\n {if (i==1) then v[0]\n else if (v[i-1]<=min(v,i-1)) then v[i-1]\n else min(v,i-1)\n }\n\n\nfunction countMin(v:array,x:int, i:int):int\ndecreases i\n reads v\n requires 0<=i<=v.Length\n ensures !(x in v[0..i]) ==> countMin(v,x,i)==0\n {\n if (i==0) then 0\n else if (v[i-1]==x) then 1+countMin(v,x,i-1)\n else countMin(v,x,i-1)\n \n }\n\n\n\n\n\n method mCountMin(v:array) returns (c:int)\nrequires v.Length>0\nensures c==countMin(v,min(v,v.Length),v.Length)\n//Implement and verify an O(v.Length) algorithm \n{\n var i:=1;\n c:=1;\n var mini:=v[0];\n while(i,i:int):int\n reads v\n requires 1<=i<=v.Length\n ensures forall k::0<=k v[k]>=min(v,i)\n {if (i==1) then v[0]\n else if (v[i-1]<=min(v,i-1)) then v[i-1]\n else min(v,i-1)\n }\n\n\nfunction countMin(v:array,x:int, i:int):int\n reads v\n requires 0<=i<=v.Length\n ensures !(x in v[0..i]) ==> countMin(v,x,i)==0\n {\n if (i==0) then 0\n else if (v[i-1]==x) then 1+countMin(v,x,i-1)\n else countMin(v,x,i-1)\n \n }\n\n\n\n\n\n method mCountMin(v:array) returns (c:int)\nrequires v.Length>0\nensures c==countMin(v,min(v,v.Length),v.Length)\n//Implement and verify an O(v.Length) algorithm \n{\n var i:=1;\n c:=1;\n var mini:=v[0];\n while(i,i:int)\n reads v\n requires 0<=i v[i]>=v[k]}\n\n function peekSum(v:array,i:int):int\n decreases i \n reads v\n requires 0<=i<=v.Length\n {\n if (i==0) then 0\n else if isPeek(v,i-1) then v[i-1]+peekSum(v,i-1)\n else peekSum(v,i-1)\n }\n\n \n method mPeekSum(v:array) returns (sum:int)\n requires v.Length>0\n ensures sum==peekSum(v,v.Length)\n //Implement and verify an O(v.Length) algorithm to solve this problem\n {\n var i:=1;\n sum:=v[0];\n var lmax:=v[0];\n while(i lmax>=v[k];\n invariant sum==peekSum(v, i)\n {\n if(v[i]>=lmax){\n sum:=sum + v[i];\n lmax:=v[i];\n }\n i:=i+1;\n }\n }\n", "hints_removed": "\n predicate isPeek(v:array,i:int)\n reads v\n requires 0<=i v[i]>=v[k]}\n\n function peekSum(v:array,i:int):int\n reads v\n requires 0<=i<=v.Length\n {\n if (i==0) then 0\n else if isPeek(v,i-1) then v[i-1]+peekSum(v,i-1)\n else peekSum(v,i-1)\n }\n\n \n method mPeekSum(v:array) returns (sum:int)\n requires v.Length>0\n ensures sum==peekSum(v,v.Length)\n //Implement and verify an O(v.Length) algorithm to solve this problem\n {\n var i:=1;\n sum:=v[0];\n var lmax:=v[0];\n while(i=lmax){\n sum:=sum + v[i];\n lmax:=v[i];\n }\n i:=i+1;\n }\n }\n" }, { "test_ID": "099", "test_file": "Dafny-Exercises_tmp_tmpjm75muf__Session7Exercises_ExerciseBinarySearch.dfy", "ground_truth": "predicate sorted(s : seq) {\n\tforall u, w :: 0 <= u < w < |s| ==> s[u] <= s[w]\n}\n\nmethod binarySearch(v:array, elem:int) returns (p:int)\n requires sorted(v[0..v.Length])\n ensures -1<=p v[u]<=elem) && (forall w::p v[w]>elem)\n {\n var c,f:=0,v.Length-1;\n while (c<=f)\n decreases f-c\n invariant 0<=c<=v.Length && -1<=f<=v.Length-1 && c<=f+1\n invariant (forall u::0<=u v[u]<=elem) && \n (forall w::f v[w]>elem)\n {\n var m:=(c+f)/2;\n if (v[m]<=elem) \n {c:=m+1;}\n else {f:=m-1;}\n }\n p:=c-1;\n \n \n }\n\n\n method search(v:array,elem:int) returns (b:bool)\n requires sorted(v[0..v.Length])\nensures b==(elem in v[0..v.Length])\n //Implement by calling binary search function\n {\n var p:=binarySearch(v, elem);\n if(p==-1){\n b:= false;\n }\n else{\n b:=v[p] == elem;\n }\n }\n\n\n\n\n//Recursive binary search\n\nmethod {:tailrecursion false} binarySearchRec(v:array, elem:int, c:int, f:int) returns (p:int)\n requires sorted(v[0..v.Length])\n requires 0<=c<=f+1<=v.Length//0<=c<=v.Length && -1<=f v[k]<=elem\n requires forall k::f v[k]>elem\n decreases f-c\n ensures -1<=p v[u]<=elem) && (forall w::p v[w]>elem)\n {\n if (c==f+1) \n {p:=c-1;} //empty case: c-1 contains the last element less or equal than elem\n else \n {\n var m:=(c+f)/2;\n \n if (v[m]<=elem) \n {p:=binarySearchRec(v,elem,m+1,f);}\n else \n {p:=binarySearchRec(v,elem,c,m-1);}\n \n }\n \n \n }\n \n \n\n\nmethod otherbSearch(v:array, elem:int) returns (b:bool,p:int)\n requires sorted(v[0..v.Length])\n ensures 0<=p<=v.Length\n ensures b == (elem in v[0..v.Length])\n ensures b ==> p (forall u::0<=u

v[u] v[w]>elem)\n //Implement and verify\n {\n p:=binarySearch(v, elem);\n \n if(p==-1){\n b:= false;\n p:=p+1;\n }\n else{\n b:=v[p] == elem;\n p:=p + if b then 0 else 1;\n }\n }\n \n\n \n", "hints_removed": "predicate sorted(s : seq) {\n\tforall u, w :: 0 <= u < w < |s| ==> s[u] <= s[w]\n}\n\nmethod binarySearch(v:array, elem:int) returns (p:int)\n requires sorted(v[0..v.Length])\n ensures -1<=p v[u]<=elem) && (forall w::p v[w]>elem)\n {\n var c,f:=0,v.Length-1;\n while (c<=f)\n (forall w::f v[w]>elem)\n {\n var m:=(c+f)/2;\n if (v[m]<=elem) \n {c:=m+1;}\n else {f:=m-1;}\n }\n p:=c-1;\n \n \n }\n\n\n method search(v:array,elem:int) returns (b:bool)\n requires sorted(v[0..v.Length])\nensures b==(elem in v[0..v.Length])\n //Implement by calling binary search function\n {\n var p:=binarySearch(v, elem);\n if(p==-1){\n b:= false;\n }\n else{\n b:=v[p] == elem;\n }\n }\n\n\n\n\n//Recursive binary search\n\nmethod {:tailrecursion false} binarySearchRec(v:array, elem:int, c:int, f:int) returns (p:int)\n requires sorted(v[0..v.Length])\n requires 0<=c<=f+1<=v.Length//0<=c<=v.Length && -1<=f v[k]<=elem\n requires forall k::f v[k]>elem\n ensures -1<=p v[u]<=elem) && (forall w::p v[w]>elem)\n {\n if (c==f+1) \n {p:=c-1;} //empty case: c-1 contains the last element less or equal than elem\n else \n {\n var m:=(c+f)/2;\n \n if (v[m]<=elem) \n {p:=binarySearchRec(v,elem,m+1,f);}\n else \n {p:=binarySearchRec(v,elem,c,m-1);}\n \n }\n \n \n }\n \n \n\n\nmethod otherbSearch(v:array, elem:int) returns (b:bool,p:int)\n requires sorted(v[0..v.Length])\n ensures 0<=p<=v.Length\n ensures b == (elem in v[0..v.Length])\n ensures b ==> p (forall u::0<=u

v[u] v[w]>elem)\n //Implement and verify\n {\n p:=binarySearch(v, elem);\n \n if(p==-1){\n b:= false;\n p:=p+1;\n }\n else{\n b:=v[p] == elem;\n p:=p + if b then 0 else 1;\n }\n }\n \n\n \n" }, { "test_ID": "100", "test_file": "Dafny-Exercises_tmp_tmpjm75muf__Session7Exercises_ExerciseBubbleSort.dfy", "ground_truth": "predicate sorted_seg(a:array, i:int, j:int) //j excluded\nrequires 0 <= i <= j <= a.Length\nreads a\n{\n forall l, k :: i <= l <= k < j ==> a[l] <= a[k]\n}\n\nmethod bubbleSorta(a:array, c:int, f:int)//f excluded\nmodifies a \nrequires 0 <= c <= f <= a.Length //when c==f empty sequence\nensures sorted_seg(a,c,f) \nensures multiset(a[c..f]) == old(multiset(a[c..f]))\nensures a[..c]==old(a[..c]) && a[f..]==old(a[f..])\n{\n var i:=c;\n while (i< f)\n decreases a.Length-i\n invariant c<=i<=f\n invariant sorted_seg(a,c,i) \n invariant forall k,l::c<=k< i && i<=l< f ==> a[k]<=a[l]\n invariant multiset(a[c..f]) == old(multiset(a[c..f])) \n invariant a[..c]==old(a[..c]) && a[f..]==old(a[f..])\n {\n var j:=f-1;\n\n assert multiset(a[c..f]) == old(multiset(a[c..f])) ;\n while (j > i)\n decreases j-i//write\n invariant i <= j<= f-1//write\n invariant forall k::j<=k<=f-1 ==> a[j] <= a[k]\n invariant forall k,l::c<=k< i && i<=l< f ==> a[k]<=a[l]\n invariant sorted_seg(a,c,i)\n invariant multiset(a[c..f]) == old(multiset(a[c..f])) \n invariant a[..c]==old(a[..c]) && a[f..]==old(a[f..])\n {\n //assert a[j]\n\n //assert multiset(a[c..f]) == old(multiset(a[c..f])) ;\n if (a[j-1]>a[j]){\n a[j],a[j-1]:=a[j-1],a[j];\n \n }\n j:=j-1;\n }\n assert sorted_seg(a,c,i+1);\n assert forall k::i a[i]<=a[k];\n i:=i+1;\n }\n\n\n\n\n}\n\n\nmethod bubbleSort(a:array, c:int, f:int)//f excluded\nmodifies a \nrequires 0 <= c <= f <= a.Length //when c==f empty sequence\nensures sorted_seg(a,c,f) \nensures multiset(a[c..f]) == old(multiset(a[c..f]))\nensures a[..c]==old(a[..c]) && a[f..]==old(a[f..])\n{\n var i:=c;\n var b:=true;\n\n while (i a[k]<=a[l]\n invariant multiset(a[c..f]) == old(multiset(a[c..f])) \n invariant a[..c]==old(a[..c]) && a[f..]==old(a[f..])\n invariant !b ==> sorted_seg(a,i,f)\n {\n var j:=f-1;\n \n b:=false;\n\n\n assert multiset(a[c..f]) == old(multiset(a[c..f])) ;\n while (j>i)\n decreases j-i//write\n invariant i<=j<=f-1//write\n invariant forall k::j<=k<=f-1 ==> a[j] <= a[k]\n invariant forall k,l::c<=k a[k]<=a[l]\n invariant sorted_seg(a,c,i)\n invariant a[..c]==old(a[..c]) && a[f..]==old(a[f..])\n invariant !b ==> sorted_seg(a,j,f)\n invariant multiset(a[c..f]) == old(multiset(a[c..f])) \n {\n if (a[j-1]>a[j]) { \n a[j],a[j-1]:=a[j-1],a[j]; \n \n b:=true;\n }\n j:=j-1;\n }\n assert !b ==> sorted_seg(a,i,f);\n i:=i+1;\n }\n\n\n\n\n}\n", "hints_removed": "predicate sorted_seg(a:array, i:int, j:int) //j excluded\nrequires 0 <= i <= j <= a.Length\nreads a\n{\n forall l, k :: i <= l <= k < j ==> a[l] <= a[k]\n}\n\nmethod bubbleSorta(a:array, c:int, f:int)//f excluded\nmodifies a \nrequires 0 <= c <= f <= a.Length //when c==f empty sequence\nensures sorted_seg(a,c,f) \nensures multiset(a[c..f]) == old(multiset(a[c..f]))\nensures a[..c]==old(a[..c]) && a[f..]==old(a[f..])\n{\n var i:=c;\n while (i< f)\n {\n var j:=f-1;\n\n while (j > i)\n {\n //assert a[j]\n\n //assert multiset(a[c..f]) == old(multiset(a[c..f])) ;\n if (a[j-1]>a[j]){\n a[j],a[j-1]:=a[j-1],a[j];\n \n }\n j:=j-1;\n }\n i:=i+1;\n }\n\n\n\n\n}\n\n\nmethod bubbleSort(a:array, c:int, f:int)//f excluded\nmodifies a \nrequires 0 <= c <= f <= a.Length //when c==f empty sequence\nensures sorted_seg(a,c,f) \nensures multiset(a[c..f]) == old(multiset(a[c..f]))\nensures a[..c]==old(a[..c]) && a[f..]==old(a[f..])\n{\n var i:=c;\n var b:=true;\n\n while (ii)\n {\n if (a[j-1]>a[j]) { \n a[j],a[j-1]:=a[j-1],a[j]; \n \n b:=true;\n }\n j:=j-1;\n }\n i:=i+1;\n }\n\n\n\n\n}\n" }, { "test_ID": "101", "test_file": "Dafny-Exercises_tmp_tmpjm75muf__Session7Exercises_ExerciseReplace.dfy", "ground_truth": "\n\n\nmethod replace(v:array, x:int, y:int)\nmodifies v\nensures forall k::0<=k v[k]==y\nensures forall k::0<=k v[k]==old(v[k])\n{\n var i:=0;\n while(i v[k]==y\n invariant forall k::i<=k v[k] == old(v[k])\n invariant forall k::0<=k v[k]==old(v[k])\n {\n\n if(v[i]==x){\n v[i]:=y;\n }\n i:=i+1;\n }\n}\n\n", "hints_removed": "\n\n\nmethod replace(v:array, x:int, y:int)\nmodifies v\nensures forall k::0<=k v[k]==y\nensures forall k::0<=k v[k]==old(v[k])\n{\n var i:=0;\n while(i, i:int, j:int) //j not included\nrequires 0 <= i <= j <= a.Length\nreads a\n{\n forall l, k :: i <= l <= k < j ==> a[l] <= a[k]\n}\n\n\nmethod selSort (a:array, c:int, f:int)//f excluded\nmodifies a \nrequires 0 <= c <= f <= a.Length //when c==f empty sequence\nensures sorted_seg(a,c,f) \nensures multiset(a[c..f]) == old(multiset(a[c..f]))\nensures a[..c]==old(a[..c]) && a[f..]==old(a[f..])\n {if (c<=f-1){//two elements at least\n var i:=c;\n while (i a[k]<=a[l]\n invariant multiset(a[c..f]) == old(multiset(a[c..f]))\n invariant a[..c]==old(a[..c]) && a[f..]==old(a[f..])\n {\n var less:=i;\n var j:=i+1;\n while (j a[less] <= a[k]\n invariant forall k,l::c<=k a[k]<=a[l]\n invariant multiset(a[c..f]) == old(multiset(a[c..f]))\n invariant a[..c]==old(a[..c]) && a[f..]==old(a[f..])\n\n { if (a[j], i:int, j:int) //j not included\nrequires 0 <= i <= j <= a.Length\nreads a\n{\n forall l, k :: i <= l <= k < j ==> a[l] <= a[k]\n}\n\n\nmethod selSort (a:array, c:int, f:int)//f excluded\nmodifies a \nrequires 0 <= c <= f <= a.Length //when c==f empty sequence\nensures sorted_seg(a,c,f) \nensures multiset(a[c..f]) == old(multiset(a[c..f]))\nensures a[..c]==old(a[..c]) && a[f..]==old(a[f..])\n {if (c<=f-1){//two elements at least\n var i:=c;\n while (i,i:int,j:int)\nreads v\nrequires 0<=i<=j<=v.Length\n{forall u | i<=u)\n{forall u::0<=u<|s| ==> s[u]>=0}\n\npredicate isPermutation(s:seq, t:seq)\n{multiset(s)==multiset(t)}\n\n/**\nreturns an index st new array is a permutation of the old array\npositive first and then strictnegative, i is the firs neg or len if not any */\nmethod separate(v:array) returns (i:int)\nmodifies v\nensures 0<=i<=v.Length\nensures positive(v[0..i]) && strictNegative(v,i,v.Length)\nensures isPermutation(v[0..v.Length], old(v[0..v.Length]))\n{\n i:=0;\n var j:=v.Length - 1;\n while(i<=j)\n decreases j-i\n invariant 0<=i<=j+1<=v.Length\n invariant strictNegative(v,j+1,v.Length)\n invariant positive(v[0..i]) \n invariant isPermutation(v[0..v.Length], old(v[0..v.Length]))\n {\n if(v[i]>=0){\n i:=i+1;\n }\n else if(v[j]>=0){\n assert v[i]<0;\n v[i],v[j]:=v[j],v[i];\n j:=j-1;\n\n i:=i+1;\n }\n else if(v[j]<0){\n j:=j-1;\n }\n }\n \n}\n", "hints_removed": "predicate strictNegative(v:array,i:int,j:int)\nreads v\nrequires 0<=i<=j<=v.Length\n{forall u | i<=u)\n{forall u::0<=u<|s| ==> s[u]>=0}\n\npredicate isPermutation(s:seq, t:seq)\n{multiset(s)==multiset(t)}\n\n/**\nreturns an index st new array is a permutation of the old array\npositive first and then strictnegative, i is the firs neg or len if not any */\nmethod separate(v:array) returns (i:int)\nmodifies v\nensures 0<=i<=v.Length\nensures positive(v[0..i]) && strictNegative(v,i,v.Length)\nensures isPermutation(v[0..v.Length], old(v[0..v.Length]))\n{\n i:=0;\n var j:=v.Length - 1;\n while(i<=j)\n {\n if(v[i]>=0){\n i:=i+1;\n }\n else if(v[j]>=0){\n v[i],v[j]:=v[j],v[i];\n j:=j-1;\n\n i:=i+1;\n }\n else if(v[j]<0){\n j:=j-1;\n }\n }\n \n}\n" }, { "test_ID": "104", "test_file": "Dafny-Exercises_tmp_tmpjm75muf__Session8Exercises_ExerciseInsertionSort.dfy", "ground_truth": "\npredicate sorted_seg(a:array, i:int, j:int) //i and j included\nrequires 0 <= i <= j+1 <= a.Length\nreads a\n{\n forall l, k :: i <= l <= k <= j ==> a[l] <= a[k]\n}\n\nmethod InsertionSort(a: array)\n modifies a;\n ensures sorted_seg(a,0,a.Length-1) \n ensures multiset(a[..]) == old(multiset(a[..])) //Add and prove this\n{\n\n var i := 0;\n assert multiset(a[..]) == old(multiset(a[..]));\n while (i < a.Length)\n decreases a.Length-i\n invariant 0<=i<=a.Length\n invariant sorted_seg(a,0,i-1)\n invariant multiset(a[..]) == old(multiset(a[..]))//add\n invariant forall k::i a[k] == old(a[k])\n {\n\n var temp := a[i];\n var j := i; \n while (j > 0 && temp < a[j - 1])\n decreases j\n invariant 0<=j<=i\n invariant sorted_seg(a,0,j-1) && sorted_seg(a,j+1,i)\n invariant forall k,l :: 0<=k<=j-1 && j+1<=l<=i ==> a[k]<=a[l]\n invariant forall k :: j temp a[k] == old(a[k])\n invariant multiset(a[..]) - multiset{a[j]} + multiset{temp} == old(multiset(a[..]))//add\n { \n \n a[j] := a[j - 1]; \n j := j - 1;\n }\n \n \n a[j] := temp;\n i := i + 1;\n\n }\n}\n\n\n\n\n\n", "hints_removed": "\npredicate sorted_seg(a:array, i:int, j:int) //i and j included\nrequires 0 <= i <= j+1 <= a.Length\nreads a\n{\n forall l, k :: i <= l <= k <= j ==> a[l] <= a[k]\n}\n\nmethod InsertionSort(a: array)\n modifies a;\n ensures sorted_seg(a,0,a.Length-1) \n ensures multiset(a[..]) == old(multiset(a[..])) //Add and prove this\n{\n\n var i := 0;\n while (i < a.Length)\n {\n\n var temp := a[i];\n var j := i; \n while (j > 0 && temp < a[j - 1])\n { \n \n a[j] := a[j - 1]; \n j := j - 1;\n }\n \n \n a[j] := temp;\n i := i + 1;\n\n }\n}\n\n\n\n\n\n" }, { "test_ID": "105", "test_file": "Dafny-Exercises_tmp_tmpjm75muf__Session9Exercises_ExerciseSeqMaxSum.dfy", "ground_truth": "\n\nfunction Sum(v:array,i:int,j:int):int\nreads v\nrequires 0<=i<=j<=v.Length\ndecreases j\n{\n if (i==j) then 0\n else Sum(v,i,j-1)+v[j-1]\n}\n\npredicate SumMaxToRight(v:array,i:int,s:int)\nreads v\nrequires 0<=i Sum(v,l,ss)<=s\n}\n\nmethod segMaxSum(v:array,i:int) returns (s:int,k:int)\nrequires v.Length>0 && 0<=iv[j+1]) {s:=s+v[j+1];}\n else {k:=j+1;s:=v[j+1];}\n\n j:=j+1;\n }\n\n} \n\n\nfunction Sum2(v:array,i:int,j:int):int\nreads v\nrequires 0<=i<=j<=v.Length\ndecreases j-i\n{\n if (i==j) then 0\n else v[i]+Sum2(v,i+1,j)\n}\n\n//Now do the same but with a loop from right to left\npredicate SumMaxToRight2(v:array,j:int,i:int,s:int)//maximum sum stuck to the right\nreads v\nrequires 0<=j<=i Sum2(v,l,ss)<=s)}\n\nmethod segSumaMaxima2(v:array,i:int) returns (s:int,k:int)\nrequires v.Length>0 && 0<=i0)\n decreases j\n invariant 0<=j<=i\n invariant 0<=k<=i \n invariant s==Sum2(v,j,i+1) \n invariant SumMaxToRight2(v,j,i,maxs)\n invariant maxs==Sum2(v,k,i+1)\n {\n s:=s+v[j-1];\n if(s>maxs){\n maxs:=s;\n k:=j-1;\n }\n j:=j-1;\n }\n s:=maxs;\n}\n", "hints_removed": "\n\nfunction Sum(v:array,i:int,j:int):int\nreads v\nrequires 0<=i<=j<=v.Length\n{\n if (i==j) then 0\n else Sum(v,i,j-1)+v[j-1]\n}\n\npredicate SumMaxToRight(v:array,i:int,s:int)\nreads v\nrequires 0<=i Sum(v,l,ss)<=s\n}\n\nmethod segMaxSum(v:array,i:int) returns (s:int,k:int)\nrequires v.Length>0 && 0<=iv[j+1]) {s:=s+v[j+1];}\n else {k:=j+1;s:=v[j+1];}\n\n j:=j+1;\n }\n\n} \n\n\nfunction Sum2(v:array,i:int,j:int):int\nreads v\nrequires 0<=i<=j<=v.Length\n{\n if (i==j) then 0\n else v[i]+Sum2(v,i+1,j)\n}\n\n//Now do the same but with a loop from right to left\npredicate SumMaxToRight2(v:array,j:int,i:int,s:int)//maximum sum stuck to the right\nreads v\nrequires 0<=j<=i Sum2(v,l,ss)<=s)}\n\nmethod segSumaMaxima2(v:array,i:int) returns (s:int,k:int)\nrequires v.Length>0 && 0<=i0)\n {\n s:=s+v[j-1];\n if(s>maxs){\n maxs:=s;\n k:=j-1;\n }\n j:=j-1;\n }\n s:=maxs;\n}\n" }, { "test_ID": "106", "test_file": "Dafny-Grind75_tmp_tmpsxfz3i4r_problems_twoSum.dfy", "ground_truth": "/*\nhttps://leetcode.com/problems/two-sum/\nfunction twoSum(nums: number[], target: number): number[] {\n const n = nums.length;\n for(let i = 0; i < n; i++) {\n for(let k = i+1; k < n; k++) {\n if(nums[i] + nums[k] == target) return [i,k]; \n }\n }\n};\n*/\npredicate summingPair(i: nat, j: nat, nums: seq, target: int)\n requires i < |nums|\n requires j < |nums|\n{\n i != j && nums[i] + nums[j] == target\n}\nmethod twoSum(nums: seq, target: int) returns (pair: (nat, nat))\n requires exists i:nat,j:nat :: i < j < |nums| && summingPair(i, j, nums, target) && forall l: nat, m: nat :: l < m < |nums| && l != i && m != j ==> !summingPair(l, m, nums, target)\n ensures 0 <= pair.0 < |nums| && 0 <= pair.1 < |nums| && summingPair(pair.0, pair.1, nums, target)\n{\n pair := (0,0);\n var i: nat := 0;\n while i < |nums| \n invariant i <= |nums|\n invariant forall z: nat, j: nat :: 0 <= z < i && z+1 <= j < |nums| ==> !summingPair(z, j, nums, target)\n {\n var k: nat := i + 1;\n while k < |nums| \n invariant i + 1 <= k <= |nums|\n // invariant forall q: nat :: i+1 <= q < k < |nums| ==> !summingPair(i,q, nums, target) //this fails to verify\n invariant forall q: nat :: i+1 <= q < k <= |nums| ==> !summingPair(i,q, nums, target) //this verifies\n {\n // assert i < k < |nums|;\n if nums[i] + nums[k] == target {\n pair := (i,k);\n return pair;\n }\n k := k + 1;\n }\n i := i + 1;\n }\n}\n", "hints_removed": "/*\nhttps://leetcode.com/problems/two-sum/\nfunction twoSum(nums: number[], target: number): number[] {\n const n = nums.length;\n for(let i = 0; i < n; i++) {\n for(let k = i+1; k < n; k++) {\n if(nums[i] + nums[k] == target) return [i,k]; \n }\n }\n};\n*/\npredicate summingPair(i: nat, j: nat, nums: seq, target: int)\n requires i < |nums|\n requires j < |nums|\n{\n i != j && nums[i] + nums[j] == target\n}\nmethod twoSum(nums: seq, target: int) returns (pair: (nat, nat))\n requires exists i:nat,j:nat :: i < j < |nums| && summingPair(i, j, nums, target) && forall l: nat, m: nat :: l < m < |nums| && l != i && m != j ==> !summingPair(l, m, nums, target)\n ensures 0 <= pair.0 < |nums| && 0 <= pair.1 < |nums| && summingPair(pair.0, pair.1, nums, target)\n{\n pair := (0,0);\n var i: nat := 0;\n while i < |nums| \n {\n var k: nat := i + 1;\n while k < |nums| \n // invariant forall q: nat :: i+1 <= q < k < |nums| ==> !summingPair(i,q, nums, target) //this fails to verify\n {\n // assert i < k < |nums|;\n if nums[i] + nums[k] == target {\n pair := (i,k);\n return pair;\n }\n k := k + 1;\n }\n i := i + 1;\n }\n}\n" }, { "test_ID": "107", "test_file": "Dafny-Practice_tmp_tmphnmt4ovh_BST.dfy", "ground_truth": "datatype Tree = Empty | Node(int,Tree,Tree)\n\nmethod Main() {\n\tvar tree := BuildBST([-2,8,3,9,2,-7,0]);\n\tPrintTreeNumbersInorder(tree);\n}\n\nmethod PrintTreeNumbersInorder(t: Tree)\n{\n\tmatch t {\n\t\tcase Empty =>\n\t\tcase Node(n, l, r) =>\n\t\t\tPrintTreeNumbersInorder(l);\n\t\t\tprint n;\n\t\t\tprint \"\\n\";\n\t\t\tPrintTreeNumbersInorder(r);\n\t}\n}\n\nfunction NumbersInTree(t: Tree): set\n{\n\tNumbersInSequence(Inorder(t))\n}\n\nfunction NumbersInSequence(q: seq): set\n{\n\tset x | x in q\n}\n\npredicate BST(t: Tree)\n{\n\tAscending(Inorder(t))\n}\n\nfunction Inorder(t: Tree): seq\n{\n\tmatch t {\n\t\tcase Empty => []\n\t\tcase Node(n',nt1,nt2) => Inorder(nt1)+[n']+Inorder(nt2)\n\t}\n}\n\npredicate Ascending(q: seq)\n{\n\tforall i,j :: 0 <= i < j < |q| ==> q[i] < q[j]\n}\n\npredicate NoDuplicates(q: seq) { forall i,j :: 0 <= i < j < |q| ==> q[i] != q[j] }\n\n/*\n\tGoal: Implement correctly, clearly. No need to document the proof obligations.\n*/\nmethod BuildBST(q: seq) returns (t: Tree)\n\trequires NoDuplicates(q)\n\tensures BST(t) && NumbersInTree(t) == NumbersInSequence(q)\n{\n\tt := Empty;\n\tfor i:=0 to |q|\n\t\tinvariant BST(t);\n\t\tinvariant NumbersInTree(t) == NumbersInSequence(q[..i])\n\t{\n\t\tt := InsertBST(t,q[i]);\n\t}\n}\n\n/*\n\tGoal: Implement correctly, efficiently, clearly, documenting the proof obligations\n\tas we've learned, with assertions and a lemma for each proof goal\n*/\nmethod InsertBST(t0: Tree, x: int) returns (t: Tree)\n\trequires BST(t0) && x !in NumbersInTree(t0)\n\tensures BST(t) && NumbersInTree(t) == NumbersInTree(t0)+{x}\n{\n\tmatch t0 \n\t{\n\t\tcase Empty => t := Node(x, Empty, Empty);\n\n\t\tcase Node(i, left, right) => \n\t\t{\n\t\t\tvar tmp:Tree:= Empty;\n\t\t\tif x < i\n\t\t\t{\n\t\t\t\tLemmaBinarySearchSubtree(i,left,right);\n\t\t\t\ttmp := InsertBST(left, x);\n\t\t\t\tt := Node(i, tmp, right);\n\t\t\t\tghost var right_nums := Inorder(right);\n\t\t\t\tghost var left_nums := Inorder(left);\n\t\t\t\tghost var all_nums := Inorder(t0);\n\t\t\t\tassert all_nums == left_nums + [i] + right_nums;\n\t\t\t\tassert all_nums[|left_nums|] == i;\n\t\t\t\tassert all_nums[|left_nums|+1..] == right_nums;\n\t\t\t\t// assert all_nums[..|left_nums|] == left_nums;\n\t\t\t\tassert Ascending(right_nums);\n\t\t\t\tassert Ascending(left_nums);\n\t\t\t\tassert Ascending(left_nums + [i] + right_nums);\n\t\t\t\tassert forall j,k :: |left_nums| < j < k < |all_nums| ==> x < i < all_nums[j] < all_nums[k];\n\t\t\t\tghost var new_all_nums := Inorder(t);\n\t\t\t\tghost var new_left_nums := Inorder(tmp);\n\t\t\t\tassert new_all_nums == (new_left_nums + [i] + right_nums);\n\t\t\t\tassert Ascending([i]+right_nums);\n\t\t\t\tassert Ascending(new_left_nums);\n\t\t\t\tassert NumbersInSequence(new_left_nums) == NumbersInSequence(left_nums) + {x};\n\t\t\t\t// assert Ascending(new_left_nums+ [i] + right_nums);\n\n\n\t\t\t\tassert forall j,k::0<= j < k <|all_nums| ==> all_nums[j] all_nums[j] left_nums[j] < left_nums[k] < i;\n\t\t\t\tassert x < i;\n\n\t\t\t\tassert forall j :: j in NumbersInSequence(all_nums[..|left_nums|]) ==> j < i;\n\t\t\t\tassert forall j :: j in NumbersInSequence(all_nums[..|left_nums|])+{x} ==> j < i;\n\t\t\t\t\n\t\t\t\tassert forall j :: j in NumbersInSequence(new_left_nums) ==> j < i;\n\t\t\t\tassert forall j :: j in NumbersInSequence(new_left_nums) <==> j in new_left_nums;\n\t\t\t\t\n\t\t\t\tassert forall j,k::0<=j < k < |new_left_nums| ==> new_left_nums[j] < new_left_nums[k];\n\t\t\t\tassert x < i;\n\t\t\t\tlemma_all_small(new_left_nums,i);\n\t\t\t\tassert forall j::0<=j < |new_left_nums| ==> new_left_nums[j] < i;\n\t\t\t\t\n\t\t\t\tassert Ascending(new_left_nums+[i]);\n\t\t\t\tassert Ascending(Inorder(t));\n\n\t\t\t\tassert BST(t);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tLemmaBinarySearchSubtree(i,left,right);\n\t\t\t\ttmp := InsertBST(right, x);\n\t\t\t\tt := Node(i, left, tmp);\n\n\t\t\t\tghost var right_nums := Inorder(right);\n\t\t\t\tghost var left_nums := Inorder(left);\n\t\t\t\tghost var all_nums := Inorder(t0);\n\t\t\t\tassert all_nums == left_nums + [i] + right_nums;\n\t\t\t\tassert all_nums[|left_nums|] == i;\n\t\t\t\tassert all_nums[|left_nums|+1..] == right_nums;\n\t\t\t\t// assert all_nums[..|left_nums|] == left_nums;\n\t\t\t\tassert Ascending(right_nums);\n\t\t\t\tassert Ascending(left_nums);\n\t\t\t\tassert Ascending(left_nums + [i] + right_nums);\n\t\t\t\tassert forall j,k :: 0 <= j < k < |left_nums| ==> all_nums[j] < all_nums[k] < i < x;\n\t\t\t\tghost var new_all_nums := Inorder(t);\n\t\t\t\tghost var new_right_nums := Inorder(tmp);\n\t\t\t\tassert new_all_nums == (left_nums + [i] + new_right_nums);\n\t\t\t\tassert Ascending(left_nums + [i]);\n\t\t\t\tassert Ascending(new_right_nums);\n\t\t\t\tassert NumbersInSequence(new_right_nums) == NumbersInSequence(right_nums) + {x};\n\t\t\t\t// assert Ascending(left_nums+ [i] + right_nums);\n\n\t\t\t\tassert forall j,k::0<= j < k <|all_nums| ==> all_nums[j] all_nums[|left_nums|] i < right_nums[j] < right_nums[k] ;\n\t\t\t\tassert x > i;\n\n\t\t\t\t// assert forall j :: j in NumbersInSequence(all_nums[|left_nums|+1..]) ==> j > i;\n\t\t\t\t// assert forall j :: j in NumbersInSequence(all_nums[|left_nums|+1..])+{x} ==> j > i;\n\t\t\t\t\n\t\t\t\tassert forall j :: j in NumbersInSequence(new_right_nums) ==> j > i;\n\t\t\t\tassert forall j :: j in NumbersInSequence(new_right_nums) <==> j in new_right_nums;\n\t\t\t\t\n\t\t\t\tassert forall j,k::0<=j < k < |new_right_nums| ==> new_right_nums[j] < new_right_nums[k];\n\t\t\t\tassert x > i;\n\t\t\t\tlemma_all_big(new_right_nums,i);\n\t\t\t\tassert forall j::0<=j < |new_right_nums| ==> new_right_nums[j] > i;\n\t\t\t\t\n\t\t\t\t// assert Ascending(new_right_nums+[i]);\n\t\t\t\tassert Ascending(Inorder(t));\n\n\t\t\t\tassert BST(t);\n\t\t\t}\n\t\t}\n\t}\n}\n\nlemma\tLemmaBinarySearchSubtree(n: int, left: Tree, right: Tree)\n\trequires BST(Node(n, left, right))\n\tensures BST(left) && BST(right)\n{\n\tassert Ascending(Inorder(Node(n, left, right)));\n\tvar qleft, qright := Inorder(left), Inorder(right);\n\tvar q := qleft+[n]+qright;\n\tassert q == Inorder(Node(n, left, right));\n\tassert Ascending(qleft+[n]+qright);\n\tassert Ascending(qleft) by { LemmaAscendingSubsequence(q, qleft, 0); }\n\tassert Ascending(qright) by { LemmaAscendingSubsequence(q, qright, |qleft|+1); }\n}\n\nlemma LemmaAscendingSubsequence(q1: seq, q2: seq, i: nat)\n\trequires i <= |q1|-|q2| && q2 == q1[i..i+|q2|]\n\trequires Ascending(q1)\n\tensures Ascending(q2)\n{}\n\nlemma {:verify true} lemma_all_small(q:seq,i:int)\n\trequires forall k:: k in NumbersInSequence(q) ==> k < i\n\trequires forall k:: 0 <= k < |q| ==> q[k] in NumbersInSequence(q)\n\tensures forall j::0<=j < |q| ==> q[j] < i\n{}\n\nlemma {:verify true} lemma_all_big(q:seq,i:int)\n\trequires forall k:: k in NumbersInSequence(q) ==> k > i\n\trequires forall k:: 0 <= k < |q| ==> q[k] in NumbersInSequence(q)\n\tensures forall j::0<=j < |q| ==> q[j] > i\n{}\n", "hints_removed": "datatype Tree = Empty | Node(int,Tree,Tree)\n\nmethod Main() {\n\tvar tree := BuildBST([-2,8,3,9,2,-7,0]);\n\tPrintTreeNumbersInorder(tree);\n}\n\nmethod PrintTreeNumbersInorder(t: Tree)\n{\n\tmatch t {\n\t\tcase Empty =>\n\t\tcase Node(n, l, r) =>\n\t\t\tPrintTreeNumbersInorder(l);\n\t\t\tprint n;\n\t\t\tprint \"\\n\";\n\t\t\tPrintTreeNumbersInorder(r);\n\t}\n}\n\nfunction NumbersInTree(t: Tree): set\n{\n\tNumbersInSequence(Inorder(t))\n}\n\nfunction NumbersInSequence(q: seq): set\n{\n\tset x | x in q\n}\n\npredicate BST(t: Tree)\n{\n\tAscending(Inorder(t))\n}\n\nfunction Inorder(t: Tree): seq\n{\n\tmatch t {\n\t\tcase Empty => []\n\t\tcase Node(n',nt1,nt2) => Inorder(nt1)+[n']+Inorder(nt2)\n\t}\n}\n\npredicate Ascending(q: seq)\n{\n\tforall i,j :: 0 <= i < j < |q| ==> q[i] < q[j]\n}\n\npredicate NoDuplicates(q: seq) { forall i,j :: 0 <= i < j < |q| ==> q[i] != q[j] }\n\n/*\n\tGoal: Implement correctly, clearly. No need to document the proof obligations.\n*/\nmethod BuildBST(q: seq) returns (t: Tree)\n\trequires NoDuplicates(q)\n\tensures BST(t) && NumbersInTree(t) == NumbersInSequence(q)\n{\n\tt := Empty;\n\tfor i:=0 to |q|\n\t{\n\t\tt := InsertBST(t,q[i]);\n\t}\n}\n\n/*\n\tGoal: Implement correctly, efficiently, clearly, documenting the proof obligations\n\tas we've learned, with assertions and a lemma for each proof goal\n*/\nmethod InsertBST(t0: Tree, x: int) returns (t: Tree)\n\trequires BST(t0) && x !in NumbersInTree(t0)\n\tensures BST(t) && NumbersInTree(t) == NumbersInTree(t0)+{x}\n{\n\tmatch t0 \n\t{\n\t\tcase Empty => t := Node(x, Empty, Empty);\n\n\t\tcase Node(i, left, right) => \n\t\t{\n\t\t\tvar tmp:Tree:= Empty;\n\t\t\tif x < i\n\t\t\t{\n\t\t\t\tLemmaBinarySearchSubtree(i,left,right);\n\t\t\t\ttmp := InsertBST(left, x);\n\t\t\t\tt := Node(i, tmp, right);\n\t\t\t\tghost var right_nums := Inorder(right);\n\t\t\t\tghost var left_nums := Inorder(left);\n\t\t\t\tghost var all_nums := Inorder(t0);\n\t\t\t\t// assert all_nums[..|left_nums|] == left_nums;\n\t\t\t\tghost var new_all_nums := Inorder(t);\n\t\t\t\tghost var new_left_nums := Inorder(tmp);\n\t\t\t\t// assert Ascending(new_left_nums+ [i] + right_nums);\n\n\n\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tlemma_all_small(new_left_nums,i);\n\t\t\t\t\n\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tLemmaBinarySearchSubtree(i,left,right);\n\t\t\t\ttmp := InsertBST(right, x);\n\t\t\t\tt := Node(i, left, tmp);\n\n\t\t\t\tghost var right_nums := Inorder(right);\n\t\t\t\tghost var left_nums := Inorder(left);\n\t\t\t\tghost var all_nums := Inorder(t0);\n\t\t\t\t// assert all_nums[..|left_nums|] == left_nums;\n\t\t\t\tghost var new_all_nums := Inorder(t);\n\t\t\t\tghost var new_right_nums := Inorder(tmp);\n\t\t\t\t// assert Ascending(left_nums+ [i] + right_nums);\n\n\n\t\t\t\t// assert forall j :: j in NumbersInSequence(all_nums[|left_nums|+1..]) ==> j > i;\n\t\t\t\t// assert forall j :: j in NumbersInSequence(all_nums[|left_nums|+1..])+{x} ==> j > i;\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tlemma_all_big(new_right_nums,i);\n\t\t\t\t\n\t\t\t\t// assert Ascending(new_right_nums+[i]);\n\n\t\t\t}\n\t\t}\n\t}\n}\n\nlemma\tLemmaBinarySearchSubtree(n: int, left: Tree, right: Tree)\n\trequires BST(Node(n, left, right))\n\tensures BST(left) && BST(right)\n{\n\tvar qleft, qright := Inorder(left), Inorder(right);\n\tvar q := qleft+[n]+qright;\n}\n\nlemma LemmaAscendingSubsequence(q1: seq, q2: seq, i: nat)\n\trequires i <= |q1|-|q2| && q2 == q1[i..i+|q2|]\n\trequires Ascending(q1)\n\tensures Ascending(q2)\n{}\n\nlemma {:verify true} lemma_all_small(q:seq,i:int)\n\trequires forall k:: k in NumbersInSequence(q) ==> k < i\n\trequires forall k:: 0 <= k < |q| ==> q[k] in NumbersInSequence(q)\n\tensures forall j::0<=j < |q| ==> q[j] < i\n{}\n\nlemma {:verify true} lemma_all_big(q:seq,i:int)\n\trequires forall k:: k in NumbersInSequence(q) ==> k > i\n\trequires forall k:: 0 <= k < |q| ==> q[k] in NumbersInSequence(q)\n\tensures forall j::0<=j < |q| ==> q[j] > i\n{}\n" }, { "test_ID": "108", "test_file": "Dafny-Practice_tmp_tmphnmt4ovh_Pattern Matching.dfy", "ground_truth": "\nmethod {:verify true} FindAllOccurrences(text: string, pattern: string) returns (offsets: set)\n\tensures forall i :: i in offsets ==> i + |pattern| <= |text|\n\tensures forall i :: 0 <= i <= |text| - |pattern| ==> (text[i..i+|pattern|] == pattern <==> i in offsets)\n{\n offsets := {};\n var i:int := 0;\n\t// no pattern in text at all.\n if |pattern| > |text|\n {\n assert forall i :: i in offsets ==> i + |pattern| <= |text|;\n\t assert forall i :: 0 <= i <= |text| - |pattern| ==> (text[i..i+|pattern|] == pattern <==> i in offsets);\n return offsets;\n }\n\n\t//all offsets are offsets of pattern/ \n if pattern == \"\"\n {\n while i < |text|\n invariant 0 <= i <=|text|\n\t\t\tinvariant forall j :: 0 <= j < i ==> (text[j..j+|pattern|] == pattern <==> j in offsets)\n\t\t\tinvariant forall j :: j in offsets ==> j + |pattern| <= |text|\n\t\t{\n\t\t\toffsets := offsets + {i};\n i:=i+1;\n\t\t}\n offsets := offsets + {|text|};\n assert forall i :: i in offsets ==> i + |pattern| <= |text|;\n\t assert forall i :: 0 <= i <= |text| - |pattern| ==> (text[i..i+|pattern|] == pattern <==> i in offsets);\n\t\treturn offsets;\n }\n\n var pattern_hash: int := RecursiveSumDown(pattern);\n var text_hash: int := RecursiveSumDown(text[..|pattern|]);\n\tassert text_hash == RecursiveSumDown(text[..|pattern|]);\n \n\tif pattern_hash == text_hash{\n if text[..|pattern|] == pattern\n {\n offsets := offsets + {0};\n }\n }\n\t\n else\n\t{\n LemmaRabinKarp(text[..|pattern|], pattern, text_hash, pattern_hash);\n }\n\n\twhile i < |text| - |pattern|\n\t\tinvariant 0 <= i <= |text| - |pattern|\n\t\tinvariant text_hash == RecursiveSumDown(text[i..i + |pattern|])\n\t\tinvariant forall k :: 0 <= k <= i ==> (text[k..k+|pattern|] == pattern <==> k in offsets)\n\t\tinvariant forall i :: i in offsets ==> i + |pattern| <= |text|\n\t\tinvariant forall k :: i < k ==> (k in offsets) == false\n\t\tdecreases |text| - |pattern| - i\n\t{\n\t\tassert text_hash == RecursiveSumDown(text[i..i + |pattern|]);\n\t\tassert forall k :: 0 <= k <= i ==> (text[k..k+|pattern|] == pattern <==> k in offsets);\n\t\t//updating text hash\n\t\tvar old_text_hash := text_hash;\n\t\tassert old_text_hash == RecursiveSumDown(text[i..i + |pattern|]);\n\t\tvar left_letter_as_int := text[i] as int;\n\t\tvar right_new_letter_as_int := text[i+|pattern|] as int;\n\t\ttext_hash := text_hash - left_letter_as_int + right_new_letter_as_int;\n\t\t//updating i\n\t\tassert forall k :: 0 <= k <= i ==> (text[k..k+|pattern|] == pattern <==> k in offsets);\n\t\tassert text_hash == old_text_hash - text[i] as int + text[i+|pattern|] as int;\n\t\tassert old_text_hash == RecursiveSumDown(text[i..i + |pattern|]);\n\t\ti := i + 1;\n\t\tassert old_text_hash == RecursiveSumDown(text[i - 1..i - 1 + |pattern|]);\n\t\tassert forall k :: 0 <= k < i ==> (text[k..k+|pattern|] == pattern <==> k in offsets);\n\t\tassert text_hash == old_text_hash - text[i - 1] as int + text[i - 1 + |pattern|] as int;\n\t\t//checking hash equality\n\t\tif pattern_hash == text_hash{\n\t\t\tif text[i..i + |pattern|] == pattern\n\t\t\t{\n\t\t\t\tassert (text[i..i + |pattern|] == pattern);\n\t\t\t\toffsets := offsets + {i};\n\t\t\t\tassert (i in offsets);\n\t\t\t\tassert text[i..i+|pattern|] == pattern <== i in offsets;\n\t\t\t\tassert text[i..i+|pattern|] == pattern ==> i in offsets;\n\t\t\t}\n\t\t\tassert pattern_hash == RecursiveSumDown(pattern);\n\t\t\tassert text_hash == old_text_hash - text[i - 1] as int + text[i - 1 + |pattern|] as int;\n\t\t\tassert old_text_hash == RecursiveSumDown(text[i - 1..i - 1 + |pattern|]);\n\t\t\tLemmaHashEqualty(text_hash, text, i, old_text_hash, pattern);\n \t\tassert text_hash == RecursiveSumDown(text[i..i+|pattern|]);\n\t\t}\n\t\telse{\n\t\t\tassert text_hash != pattern_hash;\n \t\tassert pattern_hash == RecursiveSumDown(pattern);\n\t\t\tassert text_hash == old_text_hash - text[i - 1] as int + text[i - 1 + |pattern|] as int;\n\t\t\tassert old_text_hash == RecursiveSumDown(text[i - 1..i - 1 + |pattern|]);\n\t\t\tLemmaHashEqualty(text_hash, text, i, old_text_hash, pattern);\n \t\tassert text_hash == RecursiveSumDown(text[i..i+|pattern|]);\n\t\t\tLemmaRabinKarp(text[i..i+|pattern|], pattern, text_hash, pattern_hash);\n\t\t\tassert text[i..i+|pattern|] == pattern ==> i in offsets;\n\t\t\tassert (i in offsets) == false;\n\t\t\tassert text[i..i+|pattern|] == pattern <== i in offsets;\n\t\t}\n\t\tassert text[i..i+|pattern|] == pattern ==> i in offsets;\n\t\tassert text[i..i+|pattern|] == pattern <== i in offsets;\n\t\tLemma2Sides(text, pattern, i, offsets);\n\t\t//=>\n\t\tassert text[i..i+|pattern|] == pattern <==> i in offsets;\n\t\tassert forall k :: 0 <= k < i ==> (text[k..k+|pattern|] == pattern <==> k in offsets);\n\t\t//=>\n\t\tassert forall k :: 0 <= k <= i ==> (text[k..k+|pattern|] == pattern <==> k in offsets);\n\t\tassert text_hash == RecursiveSumDown(text[i..i+|pattern|]);\n\t}\n\tassert 0 <= i <= |text| - |pattern|;\n\tassert forall i :: i in offsets ==> i + |pattern| <= |text|;\n\tassert forall k :: i < k ==> (k in offsets) == false;\n\tassert forall k :: 0 <= k <= i ==> (text[k..k+|pattern|] == pattern <==> k in offsets);\n\tassert i >= |text| - |pattern|;\n\t//=>\n\tassert forall i :: 0 <= i <= |text| - |pattern| ==> (text[i..i+|pattern|] == pattern <==> i in offsets);\n assert forall i :: i in offsets ==> i + |pattern| <= |text|;\n\tassert forall i :: 0 <= i <= |text| - |pattern| ==> (text[i..i+|pattern|] == pattern <==> i in offsets);\n}\n\nfunction RecursiveSumDown(str: string): int\n\tdecreases |str|\n{\n\tif str == \"\" then 0 else str[|str|-1] as int +RecursiveSumDown(str[..|str|-1])\n}\n\nfunction RecursiveSumUp(str: string): int\n\tdecreases |str|\n{\n\tif str == \"\" then 0 else str[0] as int + RecursiveSumUp(str[1..])\n}\n\nlemma {:verify true}LemmaRabinKarp(t_sub:string, pattern:string, text_hash:int, pattern_hash:int)\n requires text_hash != pattern_hash\n requires pattern_hash == RecursiveSumDown(pattern)\n requires text_hash == RecursiveSumDown(t_sub)\n ensures t_sub[..] != pattern[..]\n{}\n\nlemma Lemma2Sides(text: string, pattern: string, i: nat, offsets: set)\n\trequires 0 <= i <= |text| - |pattern|\n\trequires (text[i..i+|pattern|] == pattern ==> i in offsets)\n\trequires (text[i..i+|pattern|] == pattern <== i in offsets)\n\tensures (text[i..i+|pattern|] == pattern <==> i in offsets)\n{}\n\nlemma LemmaHashEqualty(text_hash : int, text: string, i: nat, old_text_hash: int, pattern: string)\nrequires 0 < i <= |text| - |pattern|\nrequires text_hash == old_text_hash - text[i - 1] as int + text[i - 1 + |pattern|] as int\nrequires old_text_hash == RecursiveSumDown(text[i - 1..i - 1 + |pattern|]);\nensures text_hash == RecursiveSumDown(text[i..i+|pattern|])\n{\n\tassert 0 < i <= |text| - |pattern|;\n\tassert 0 <= i - 1 < |text| - |pattern|;\n\tghost var temp_val := old_text_hash + text[i - 1 + |pattern|] as int;\n\tassert text_hash == old_text_hash + text[i - 1 + |pattern|] as int - text[i - 1] as int;\n\t//=>\n\tassert text_hash == temp_val - text[i - 1] as int;\n\tassert 0 <= |pattern| < |text[i - 1..]|;\n\tghost var str := text[i - 1..];\n\tassert str[..|pattern|] == text[i - 1 .. i - 1 + |pattern|];\n\tassert old_text_hash == RecursiveSumDown(str[..|pattern|]);\n\tLemmaAddingOneIndex(str, |pattern|, old_text_hash);\n\tassert old_text_hash + str[|pattern|] as int == RecursiveSumDown(str[..|pattern|+1]);\n\tassert str[..|pattern|+1] == text[i - 1..i - 1 + |pattern| + 1];\n\t//=>\n\tassert old_text_hash + text[i - 1 + |pattern|] as int == RecursiveSumDown(text[i - 1..i - 1 + |pattern| + 1]);\n\tassert temp_val == old_text_hash + text[i - 1 + |pattern|] as int;\n\t//=>\n\tassert temp_val == RecursiveSumDown(text[i - 1..i - 1 + |pattern| + 1]);\n\tassert temp_val == RecursiveSumDown(text[i - 1..i + |pattern|]);\n\tPrependSumUp(text[i - 1..i + |pattern|]);\n\tassert RecursiveSumUp(text[i - 1..i + |pattern|]) == text[i - 1] as int + RecursiveSumUp(text[i..i + |pattern|]);\n\tEquivalentSumDefinitions(text[i - 1..i + |pattern|]);\n\tEquivalentSumDefinitions(text[i..i + |pattern|]);\n\t//=>\n\tassert RecursiveSumUp(text[i - 1..i + |pattern|]) == RecursiveSumDown(text[i - 1..i + |pattern|]);\n\tassert RecursiveSumUp(text[i..i + |pattern|]) == RecursiveSumDown(text[i..i + |pattern|]);\n\t//=>\n\tassert RecursiveSumDown(text[i - 1..i + |pattern|]) == text[i - 1] as int + RecursiveSumDown(text[i..i + |pattern|]);\n\t//=>\n\tassert RecursiveSumDown(text[i - 1..i + |pattern|]) - text[i - 1] as int == RecursiveSumDown(text[i..i + |pattern|]);\n\tassert text_hash == temp_val - text[i - 1] as int;\n\tassert temp_val == RecursiveSumDown(text[i - 1..i + |pattern|]);\n\tassert text_hash == RecursiveSumDown(text[i - 1..i + |pattern|]) - text[i - 1] as int;\n\t//=>\n\tassert text_hash == RecursiveSumDown(text[i..i + |pattern|]);\n}\n\nlemma LemmaAddingOneIndex(str: string, i: nat, sum: int)\n\trequires 0 <= i < |str| && sum == RecursiveSumDown(str[..i])\n\tensures 0 <= i+1 <= |str| && sum + str[i] as int == RecursiveSumDown(str[..i+1])\n{\n\tvar str1 := str[..i+1];\n\tcalc {\n\t\tRecursiveSumDown(str[..i+1]);\n\t== // def.\n\t\tif str1 == [] then 0 else str1[|str1|-1] as int + RecursiveSumDown(str1[..|str1|-1]);\n\t== { assert str1 != []; } // simplification for a non-empty sequence\n\t\tstr1[|str1|-1] as int + RecursiveSumDown(str1[..|str1|-1]);\n\t== { assert |str1|-1 == i; }\n\t\tstr1[i] as int + RecursiveSumDown(str1[..i]);\n\t== { assert str1[..i] == str[..i]; }\n\t\tstr[i] as int + RecursiveSumDown(str[..i]);\n\t== // inv.\n\t\tstr[i] as int + sum;\n\t==\n\t\tsum + str[i] as int;\n\t}\n}\n\nlemma PrependSumUp(str: string)\n\trequires str != \"\"\n\tensures RecursiveSumUp(str) == str[0] as int + RecursiveSumUp(str[1..])\n{\n\t// directly from the definition of RecursiveSumUp (for a non-emty sequence)\n}\n\nlemma EquivalentSumDefinitions(str: string)\n\tensures RecursiveSumDown(str) == RecursiveSumUp(str)\n\tdecreases |str|\n{\n\tif |str| == 0\n\t{\n\t\tassert str == \"\";\n\t\tassert RecursiveSumDown([]) == 0 == RecursiveSumUp([]);\n\t}\n\telse if |str| == 1\n\t{\n\t\tassert str == [str[0]];\n\t\tassert RecursiveSumDown(str) == str[0] as int == RecursiveSumUp(str);\n\t}\n\telse\n\t{\n\t\tassert |str| >= 2;\n\t\tvar first: char, mid: string, last:char := str[0], str[1..|str|-1], str[|str|-1];\n\t\tassert str == [first] + mid + [last];\n\t\tcalc {\n\t\t\tRecursiveSumDown(str);\n\t\t== { assert str != [] && str[|str|-1] == last && str[..|str|-1] == [first] + mid; }\n\t\t\tlast as int + RecursiveSumDown([first] + mid);\n\t\t== // arithmetic\n\t\t\tRecursiveSumDown([first] + mid) + last as int;\n\t\t== { EquivalentSumDefinitions([first] + mid); } // induction hypothesis\n\t\t\tRecursiveSumUp([first] + mid) + last as int;\n\t\t== { assert [first] + mid != []; }\n\t\t\tfirst as int + RecursiveSumUp(mid) + last as int;\n\t\t== { EquivalentSumDefinitions(mid); } // induction hypothesis\n\t\t\tfirst as int + RecursiveSumDown(mid) + last as int;\n\t\t==\n\t\t\tfirst as int + RecursiveSumDown(mid + [last]);\n\t\t== { EquivalentSumDefinitions(mid + [last]); } // induction hypothesis\n\t\t\tfirst as int + RecursiveSumUp(mid + [last]);\n\t\t== { assert str != [] && str[0] == first && str[1..] == mid + [last]; }\n\t\t\tRecursiveSumUp(str);\n\t\t}\n\t}\n}\n\n", "hints_removed": "\nmethod {:verify true} FindAllOccurrences(text: string, pattern: string) returns (offsets: set)\n\tensures forall i :: i in offsets ==> i + |pattern| <= |text|\n\tensures forall i :: 0 <= i <= |text| - |pattern| ==> (text[i..i+|pattern|] == pattern <==> i in offsets)\n{\n offsets := {};\n var i:int := 0;\n\t// no pattern in text at all.\n if |pattern| > |text|\n {\n return offsets;\n }\n\n\t//all offsets are offsets of pattern/ \n if pattern == \"\"\n {\n while i < |text|\n\t\t{\n\t\t\toffsets := offsets + {i};\n i:=i+1;\n\t\t}\n offsets := offsets + {|text|};\n\t\treturn offsets;\n }\n\n var pattern_hash: int := RecursiveSumDown(pattern);\n var text_hash: int := RecursiveSumDown(text[..|pattern|]);\n \n\tif pattern_hash == text_hash{\n if text[..|pattern|] == pattern\n {\n offsets := offsets + {0};\n }\n }\n\t\n else\n\t{\n LemmaRabinKarp(text[..|pattern|], pattern, text_hash, pattern_hash);\n }\n\n\twhile i < |text| - |pattern|\n\t{\n\t\t//updating text hash\n\t\tvar old_text_hash := text_hash;\n\t\tvar left_letter_as_int := text[i] as int;\n\t\tvar right_new_letter_as_int := text[i+|pattern|] as int;\n\t\ttext_hash := text_hash - left_letter_as_int + right_new_letter_as_int;\n\t\t//updating i\n\t\ti := i + 1;\n\t\t//checking hash equality\n\t\tif pattern_hash == text_hash{\n\t\t\tif text[i..i + |pattern|] == pattern\n\t\t\t{\n\t\t\t\toffsets := offsets + {i};\n\t\t\t}\n\t\t\tLemmaHashEqualty(text_hash, text, i, old_text_hash, pattern);\n\t\t}\n\t\telse{\n\t\t\tLemmaHashEqualty(text_hash, text, i, old_text_hash, pattern);\n\t\t\tLemmaRabinKarp(text[i..i+|pattern|], pattern, text_hash, pattern_hash);\n\t\t}\n\t\tLemma2Sides(text, pattern, i, offsets);\n\t\t//=>\n\t\t//=>\n\t}\n\t//=>\n}\n\nfunction RecursiveSumDown(str: string): int\n{\n\tif str == \"\" then 0 else str[|str|-1] as int +RecursiveSumDown(str[..|str|-1])\n}\n\nfunction RecursiveSumUp(str: string): int\n{\n\tif str == \"\" then 0 else str[0] as int + RecursiveSumUp(str[1..])\n}\n\nlemma {:verify true}LemmaRabinKarp(t_sub:string, pattern:string, text_hash:int, pattern_hash:int)\n requires text_hash != pattern_hash\n requires pattern_hash == RecursiveSumDown(pattern)\n requires text_hash == RecursiveSumDown(t_sub)\n ensures t_sub[..] != pattern[..]\n{}\n\nlemma Lemma2Sides(text: string, pattern: string, i: nat, offsets: set)\n\trequires 0 <= i <= |text| - |pattern|\n\trequires (text[i..i+|pattern|] == pattern ==> i in offsets)\n\trequires (text[i..i+|pattern|] == pattern <== i in offsets)\n\tensures (text[i..i+|pattern|] == pattern <==> i in offsets)\n{}\n\nlemma LemmaHashEqualty(text_hash : int, text: string, i: nat, old_text_hash: int, pattern: string)\nrequires 0 < i <= |text| - |pattern|\nrequires text_hash == old_text_hash - text[i - 1] as int + text[i - 1 + |pattern|] as int\nrequires old_text_hash == RecursiveSumDown(text[i - 1..i - 1 + |pattern|]);\nensures text_hash == RecursiveSumDown(text[i..i+|pattern|])\n{\n\tghost var temp_val := old_text_hash + text[i - 1 + |pattern|] as int;\n\t//=>\n\tghost var str := text[i - 1..];\n\tLemmaAddingOneIndex(str, |pattern|, old_text_hash);\n\t//=>\n\t//=>\n\tPrependSumUp(text[i - 1..i + |pattern|]);\n\tEquivalentSumDefinitions(text[i - 1..i + |pattern|]);\n\tEquivalentSumDefinitions(text[i..i + |pattern|]);\n\t//=>\n\t//=>\n\t//=>\n\t//=>\n}\n\nlemma LemmaAddingOneIndex(str: string, i: nat, sum: int)\n\trequires 0 <= i < |str| && sum == RecursiveSumDown(str[..i])\n\tensures 0 <= i+1 <= |str| && sum + str[i] as int == RecursiveSumDown(str[..i+1])\n{\n\tvar str1 := str[..i+1];\n\tcalc {\n\t\tRecursiveSumDown(str[..i+1]);\n\t== // def.\n\t\tif str1 == [] then 0 else str1[|str1|-1] as int + RecursiveSumDown(str1[..|str1|-1]);\n\t== { assert str1 != []; } // simplification for a non-empty sequence\n\t\tstr1[|str1|-1] as int + RecursiveSumDown(str1[..|str1|-1]);\n\t== { assert |str1|-1 == i; }\n\t\tstr1[i] as int + RecursiveSumDown(str1[..i]);\n\t== { assert str1[..i] == str[..i]; }\n\t\tstr[i] as int + RecursiveSumDown(str[..i]);\n\t== // inv.\n\t\tstr[i] as int + sum;\n\t==\n\t\tsum + str[i] as int;\n\t}\n}\n\nlemma PrependSumUp(str: string)\n\trequires str != \"\"\n\tensures RecursiveSumUp(str) == str[0] as int + RecursiveSumUp(str[1..])\n{\n\t// directly from the definition of RecursiveSumUp (for a non-emty sequence)\n}\n\nlemma EquivalentSumDefinitions(str: string)\n\tensures RecursiveSumDown(str) == RecursiveSumUp(str)\n{\n\tif |str| == 0\n\t{\n\t}\n\telse if |str| == 1\n\t{\n\t}\n\telse\n\t{\n\t\tvar first: char, mid: string, last:char := str[0], str[1..|str|-1], str[|str|-1];\n\t\tcalc {\n\t\t\tRecursiveSumDown(str);\n\t\t== { assert str != [] && str[|str|-1] == last && str[..|str|-1] == [first] + mid; }\n\t\t\tlast as int + RecursiveSumDown([first] + mid);\n\t\t== // arithmetic\n\t\t\tRecursiveSumDown([first] + mid) + last as int;\n\t\t== { EquivalentSumDefinitions([first] + mid); } // induction hypothesis\n\t\t\tRecursiveSumUp([first] + mid) + last as int;\n\t\t== { assert [first] + mid != []; }\n\t\t\tfirst as int + RecursiveSumUp(mid) + last as int;\n\t\t== { EquivalentSumDefinitions(mid); } // induction hypothesis\n\t\t\tfirst as int + RecursiveSumDown(mid) + last as int;\n\t\t==\n\t\t\tfirst as int + RecursiveSumDown(mid + [last]);\n\t\t== { EquivalentSumDefinitions(mid + [last]); } // induction hypothesis\n\t\t\tfirst as int + RecursiveSumUp(mid + [last]);\n\t\t== { assert str != [] && str[0] == first && str[1..] == mid + [last]; }\n\t\t\tRecursiveSumUp(str);\n\t\t}\n\t}\n}\n\n" }, { "test_ID": "109", "test_file": "Dafny-Projects_tmp_tmph399drhy_p2_arraySplit.dfy", "ground_truth": "method ArraySplit (a : array) returns (b : array, c : array)\n ensures fresh(b)\n ensures fresh(c)\n ensures a[..] == b[..] + c[..]\n ensures a.Length == b.Length + c.Length\n ensures a.Length > 1 ==> a.Length > b.Length\n ensures a.Length > 1 ==> a.Length > c.Length\n{\n var splitPoint : int := a.Length / 2;\n\n b := new int[splitPoint];\n c := new int[a.Length - splitPoint];\n\n var i : int := 0;\n\n while (i < splitPoint)\n invariant 0 <= i <= splitPoint\n invariant b[..i] == a[..i]\n {\n b[i] := a[i];\n i := i + 1;\n }\n\n // while(i < a.Length)\n // invariant splitPoint <= i <= a.Length\n // invariant c[..i-splitPoint] == a[..i]\n // {\n // c[i] := a[i];\n // i := i+1;\n // }\n\n var j : int := 0;\n while (i < a.Length)\n invariant splitPoint <= i <= a.Length\n invariant j == i - splitPoint\n invariant c[..j] == a[splitPoint..i]\n invariant b[..] + c[..j] == a[..i]\n {\n c[j] := a[i];\n i := i + 1;\n j := j + 1;\n }\n\n}\n\n\n\n", "hints_removed": "method ArraySplit (a : array) returns (b : array, c : array)\n ensures fresh(b)\n ensures fresh(c)\n ensures a[..] == b[..] + c[..]\n ensures a.Length == b.Length + c.Length\n ensures a.Length > 1 ==> a.Length > b.Length\n ensures a.Length > 1 ==> a.Length > c.Length\n{\n var splitPoint : int := a.Length / 2;\n\n b := new int[splitPoint];\n c := new int[a.Length - splitPoint];\n\n var i : int := 0;\n\n while (i < splitPoint)\n {\n b[i] := a[i];\n i := i + 1;\n }\n\n // while(i < a.Length)\n // invariant splitPoint <= i <= a.Length\n // invariant c[..i-splitPoint] == a[..i]\n // {\n // c[i] := a[i];\n // i := i+1;\n // }\n\n var j : int := 0;\n while (i < a.Length)\n {\n c[j] := a[i];\n i := i + 1;\n j := j + 1;\n }\n\n}\n\n\n\n" }, { "test_ID": "110", "test_file": "Dafny-VMC_tmp_tmpzgqv0i1u_src_Math_Exponential.dfy", "ground_truth": "module Exponential {\n ghost function {:axiom} Exp(x: real): real\n\n lemma {:axiom} FunctionalEquation(x: real, y: real)\n ensures Exp(x + y) == Exp(x) * Exp(y)\n\n lemma {:axiom} Increasing(x: real, y: real)\n requires x < y\n ensures Exp(x) < Exp(y)\n\n lemma {:axiom} EvalOne()\n ensures 2.718281828 <= Exp(1.0) <= 2.718281829\n\n lemma Positive(x: real)\n ensures Exp(x) > 0.0\n {\n assert Exp(x) >= 0.0 by {\n var sqrt := Exp(x / 2.0);\n calc {\n Exp(x);\n { FunctionalEquation(x / 2.0, x / 2.0); }\n sqrt * sqrt;\n >=\n 0.0;\n }\n }\n if Exp(x) == 0.0 {\n calc {\n 0.0;\n Exp(x);\n < { Increasing(x, x + 1.0); }\n Exp(x + 1.0);\n { FunctionalEquation(x, 1.0); }\n Exp(x) * Exp(1.0);\n ==\n 0.0;\n }\n }\n }\n\n lemma EvalZero()\n ensures Exp(0.0) == 1.0\n {\n var one := Exp(0.0);\n assert one > 0.0 by {\n Positive(0.0);\n }\n assert one * one == one by {\n FunctionalEquation(0.0, 0.0);\n }\n }\n}\n\n", "hints_removed": "module Exponential {\n ghost function {:axiom} Exp(x: real): real\n\n lemma {:axiom} FunctionalEquation(x: real, y: real)\n ensures Exp(x + y) == Exp(x) * Exp(y)\n\n lemma {:axiom} Increasing(x: real, y: real)\n requires x < y\n ensures Exp(x) < Exp(y)\n\n lemma {:axiom} EvalOne()\n ensures 2.718281828 <= Exp(1.0) <= 2.718281829\n\n lemma Positive(x: real)\n ensures Exp(x) > 0.0\n {\n var sqrt := Exp(x / 2.0);\n calc {\n Exp(x);\n { FunctionalEquation(x / 2.0, x / 2.0); }\n sqrt * sqrt;\n >=\n 0.0;\n }\n }\n if Exp(x) == 0.0 {\n calc {\n 0.0;\n Exp(x);\n < { Increasing(x, x + 1.0); }\n Exp(x + 1.0);\n { FunctionalEquation(x, 1.0); }\n Exp(x) * Exp(1.0);\n ==\n 0.0;\n }\n }\n }\n\n lemma EvalZero()\n ensures Exp(0.0) == 1.0\n {\n var one := Exp(0.0);\n Positive(0.0);\n }\n FunctionalEquation(0.0, 0.0);\n }\n }\n}\n\n" }, { "test_ID": "111", "test_file": "Dafny-VMC_tmp_tmpzgqv0i1u_src_Math_Helper.dfy", "ground_truth": "/*******************************************************************************\n * Copyright by the contributors to the Dafny Project\n * SPDX-License-Identifier: MIT\n *******************************************************************************/\n\nmodule Helper {\n /************\n Definitions\n ************/\n\n function Power(b: nat, n: nat): (p: nat)\n ensures b > 0 ==> p > 0\n {\n match n\n case 0 => 1\n case 1 => b\n case _ => b * Power(b, n - 1)\n }\n\n function Log2Floor(n: nat): nat\n requires n >= 1\n decreases n\n {\n if n < 2\n then 0\n else Log2Floor(n / 2) + 1\n }\n\n lemma Log2FloorDef(n: nat)\n requires n >= 1\n ensures Log2Floor(2 * n) == Log2Floor(n) + 1\n {}\n\n function boolToNat(b: bool): nat {\n if b then 1 else 0\n }\n\n /*******\n Lemmas\n *******/\n\n lemma Congruence(x: T, y: T, f: T -> U)\n requires x == y\n ensures f(x) == f(y)\n {}\n\n lemma DivisionSubstituteAlternativeReal(x: real, a: real, b: real)\n requires a == b\n requires x != 0.0\n ensures a / x == b / x\n {}\n\n lemma DivModAddDenominator(n: nat, m: nat)\n requires m > 0\n ensures (n + m) / m == n / m + 1\n ensures (n + m) % m == n % m\n {\n var zp := (n + m) / m - n / m - 1;\n assert 0 == m * zp + ((n + m) % m) - (n % m);\n }\n\n lemma DivModIsUnique(n: int, m: int, a: int, b: int)\n requires n >= 0\n requires m > 0\n requires 0 <= b < m\n requires n == a * m + b\n ensures a == n / m\n ensures b == n % m\n {\n if a == 0 {\n assert n == b;\n } else {\n assert (n - m) / m == a - 1 && (n - m) % m == b by { DivModIsUnique(n - m, m, a - 1, b); }\n assert n / m == a && n % m == b by { DivModAddDenominator(n - m, m); }\n }\n }\n\n lemma DivModAddMultiple(a: nat, b: nat, c: nat)\n requires a > 0\n ensures (c * a + b) / a == c + b / a\n ensures (c * a + b) % a == b % a\n {\n calc {\n a * c + b;\n ==\n a * c + (a * (b / a) + b % a);\n ==\n a * (c + b / a) + b % a;\n }\n DivModIsUnique(a * c + b, a, c + b / a, b % a);\n }\n\n lemma DivisionByTwo(x: real)\n ensures 0.5 * x == x / 2.0\n {}\n\n lemma PowerGreater0(base: nat, exponent: nat)\n requires base >= 1\n ensures Power(base, exponent) >= 1\n {}\n\n lemma Power2OfLog2Floor(n: nat)\n requires n >= 1\n ensures Power(2, Log2Floor(n)) <= n < Power(2, Log2Floor(n) + 1)\n {}\n\n lemma NLtPower2Log2FloorOf2N(n: nat)\n requires n >= 1\n ensures n < Power(2, Log2Floor(2 * n))\n {\n calc {\n n;\n < { Power2OfLog2Floor(n); }\n Power(2, Log2Floor(n) + 1);\n == { Log2FloorDef(n); }\n Power(2, Log2Floor(2 * n));\n }\n }\n\n lemma MulMonotonic(a: nat, b: nat, c: nat, d: nat)\n requires a <= c\n requires b <= d\n ensures a * b <= c * d\n {\n calc {\n a * b;\n <=\n c * b;\n <=\n c * d;\n }\n }\n\n lemma MulMonotonicStrictRhs(b: nat, c: nat, d: nat)\n requires b < d\n requires c > 0\n ensures c * b < c * d\n {}\n\n lemma MulMonotonicStrict(a: nat, b: nat, c: nat, d: nat)\n requires a <= c\n requires b <= d\n requires (a != c && d > 0) || (b != d && c > 0)\n ensures a * b < c * d\n {\n if a != c && d > 0 {\n calc {\n a * b;\n <= { MulMonotonic(a, b, a, d); }\n a * d;\n <\n c * d;\n }\n }\n if b != d && c > 0 {\n calc {\n a * b;\n <=\n c * b;\n < { MulMonotonicStrictRhs(b, c, d); }\n c * d;\n }\n }\n }\n\n lemma AdditionOfFractions(x: real, y: real, z: real)\n requires z != 0.0\n ensures (x / z) + (y / z) == (x + y) / z\n {}\n\n lemma DivSubstituteDividend(x: real, y: real, z: real)\n requires y != 0.0\n requires x == z\n ensures x / y == z / y\n {}\n\n lemma DivSubstituteDivisor(x: real, y: real, z: real)\n requires y != 0.0\n requires y == z\n ensures x / y == x / z\n {}\n\n lemma DivDivToDivMul(x: real, y: real, z: real)\n requires y != 0.0\n requires z != 0.0\n ensures (x / y) / z == x / (y * z)\n {}\n\n lemma NatMulNatToReal(x: nat, y: nat)\n ensures (x * y) as real == (x as real) * (y as real)\n {}\n\n lemma SimplifyFractions(x: real, y: real, z: real)\n requires z != 0.0\n requires y != 0.0\n ensures (x / z) / (y / z) == x / y\n {}\n\n lemma PowerOfTwoLemma(k: nat)\n ensures (1.0 / Power(2, k) as real) / 2.0 == 1.0 / (Power(2, k + 1) as real)\n {\n calc {\n (1.0 / Power(2, k) as real) / 2.0;\n == { DivDivToDivMul(1.0, Power(2, k) as real, 2.0); }\n 1.0 / (Power(2, k) as real * 2.0);\n == { NatMulNatToReal(Power(2, k), 2); }\n 1.0 / (Power(2, k) * 2) as real;\n ==\n 1.0 / (Power(2, k + 1) as real);\n }\n }\n}\n\n", "hints_removed": "/*******************************************************************************\n * Copyright by the contributors to the Dafny Project\n * SPDX-License-Identifier: MIT\n *******************************************************************************/\n\nmodule Helper {\n /************\n Definitions\n ************/\n\n function Power(b: nat, n: nat): (p: nat)\n ensures b > 0 ==> p > 0\n {\n match n\n case 0 => 1\n case 1 => b\n case _ => b * Power(b, n - 1)\n }\n\n function Log2Floor(n: nat): nat\n requires n >= 1\n {\n if n < 2\n then 0\n else Log2Floor(n / 2) + 1\n }\n\n lemma Log2FloorDef(n: nat)\n requires n >= 1\n ensures Log2Floor(2 * n) == Log2Floor(n) + 1\n {}\n\n function boolToNat(b: bool): nat {\n if b then 1 else 0\n }\n\n /*******\n Lemmas\n *******/\n\n lemma Congruence(x: T, y: T, f: T -> U)\n requires x == y\n ensures f(x) == f(y)\n {}\n\n lemma DivisionSubstituteAlternativeReal(x: real, a: real, b: real)\n requires a == b\n requires x != 0.0\n ensures a / x == b / x\n {}\n\n lemma DivModAddDenominator(n: nat, m: nat)\n requires m > 0\n ensures (n + m) / m == n / m + 1\n ensures (n + m) % m == n % m\n {\n var zp := (n + m) / m - n / m - 1;\n }\n\n lemma DivModIsUnique(n: int, m: int, a: int, b: int)\n requires n >= 0\n requires m > 0\n requires 0 <= b < m\n requires n == a * m + b\n ensures a == n / m\n ensures b == n % m\n {\n if a == 0 {\n } else {\n }\n }\n\n lemma DivModAddMultiple(a: nat, b: nat, c: nat)\n requires a > 0\n ensures (c * a + b) / a == c + b / a\n ensures (c * a + b) % a == b % a\n {\n calc {\n a * c + b;\n ==\n a * c + (a * (b / a) + b % a);\n ==\n a * (c + b / a) + b % a;\n }\n DivModIsUnique(a * c + b, a, c + b / a, b % a);\n }\n\n lemma DivisionByTwo(x: real)\n ensures 0.5 * x == x / 2.0\n {}\n\n lemma PowerGreater0(base: nat, exponent: nat)\n requires base >= 1\n ensures Power(base, exponent) >= 1\n {}\n\n lemma Power2OfLog2Floor(n: nat)\n requires n >= 1\n ensures Power(2, Log2Floor(n)) <= n < Power(2, Log2Floor(n) + 1)\n {}\n\n lemma NLtPower2Log2FloorOf2N(n: nat)\n requires n >= 1\n ensures n < Power(2, Log2Floor(2 * n))\n {\n calc {\n n;\n < { Power2OfLog2Floor(n); }\n Power(2, Log2Floor(n) + 1);\n == { Log2FloorDef(n); }\n Power(2, Log2Floor(2 * n));\n }\n }\n\n lemma MulMonotonic(a: nat, b: nat, c: nat, d: nat)\n requires a <= c\n requires b <= d\n ensures a * b <= c * d\n {\n calc {\n a * b;\n <=\n c * b;\n <=\n c * d;\n }\n }\n\n lemma MulMonotonicStrictRhs(b: nat, c: nat, d: nat)\n requires b < d\n requires c > 0\n ensures c * b < c * d\n {}\n\n lemma MulMonotonicStrict(a: nat, b: nat, c: nat, d: nat)\n requires a <= c\n requires b <= d\n requires (a != c && d > 0) || (b != d && c > 0)\n ensures a * b < c * d\n {\n if a != c && d > 0 {\n calc {\n a * b;\n <= { MulMonotonic(a, b, a, d); }\n a * d;\n <\n c * d;\n }\n }\n if b != d && c > 0 {\n calc {\n a * b;\n <=\n c * b;\n < { MulMonotonicStrictRhs(b, c, d); }\n c * d;\n }\n }\n }\n\n lemma AdditionOfFractions(x: real, y: real, z: real)\n requires z != 0.0\n ensures (x / z) + (y / z) == (x + y) / z\n {}\n\n lemma DivSubstituteDividend(x: real, y: real, z: real)\n requires y != 0.0\n requires x == z\n ensures x / y == z / y\n {}\n\n lemma DivSubstituteDivisor(x: real, y: real, z: real)\n requires y != 0.0\n requires y == z\n ensures x / y == x / z\n {}\n\n lemma DivDivToDivMul(x: real, y: real, z: real)\n requires y != 0.0\n requires z != 0.0\n ensures (x / y) / z == x / (y * z)\n {}\n\n lemma NatMulNatToReal(x: nat, y: nat)\n ensures (x * y) as real == (x as real) * (y as real)\n {}\n\n lemma SimplifyFractions(x: real, y: real, z: real)\n requires z != 0.0\n requires y != 0.0\n ensures (x / z) / (y / z) == x / y\n {}\n\n lemma PowerOfTwoLemma(k: nat)\n ensures (1.0 / Power(2, k) as real) / 2.0 == 1.0 / (Power(2, k + 1) as real)\n {\n calc {\n (1.0 / Power(2, k) as real) / 2.0;\n == { DivDivToDivMul(1.0, Power(2, k) as real, 2.0); }\n 1.0 / (Power(2, k) as real * 2.0);\n == { NatMulNatToReal(Power(2, k), 2); }\n 1.0 / (Power(2, k) * 2) as real;\n ==\n 1.0 / (Power(2, k + 1) as real);\n }\n }\n}\n\n" }, { "test_ID": "112", "test_file": "Dafny-demo_tmp_tmpkgr_dvdi_Dafny_BinarySearch.dfy", "ground_truth": "\npredicate sorted(a: array?, l: int, u: int)\n\treads a\n\trequires a != null\n\t{\n\tforall i, j :: 0 <= l <= i <= j <= u < a.Length ==> a[i] <= a[j]\n\t}\n\nmethod BinarySearch(a: array?, key: int)\n\treturns (index: int)\n\trequires a != null && sorted(a,0,a.Length-1);\n\tensures index >= 0 ==> index < a.Length && a[index] == key;\n\tensures index < 0 ==> forall k :: 0 <= k < a.Length ==> a[k] != key;\n{\n\tvar low := 0;\n\tvar high := a.Length;\n\twhile (low < high)\n\t\tinvariant 0 <= low <= high <= a.Length;\n\t\tinvariant forall i ::\n\t\t\t0 <= i < a.Length && !(low <= i < high) ==> a[i] != key;\n\t{\n\t\tvar mid := (low + high) / 2;\n\t\tif (a[mid] < key) {\n\t\t\tlow := mid + 1;\n\t\t}\n\t\telse if (key < a[mid]) {\n\t\t\thigh := mid;\n\t\t}\n\t\telse {\n\t\t\treturn mid;\n\t\t}\n\t}\n\treturn -1;\n}\n", "hints_removed": "\npredicate sorted(a: array?, l: int, u: int)\n\treads a\n\trequires a != null\n\t{\n\tforall i, j :: 0 <= l <= i <= j <= u < a.Length ==> a[i] <= a[j]\n\t}\n\nmethod BinarySearch(a: array?, key: int)\n\treturns (index: int)\n\trequires a != null && sorted(a,0,a.Length-1);\n\tensures index >= 0 ==> index < a.Length && a[index] == key;\n\tensures index < 0 ==> forall k :: 0 <= k < a.Length ==> a[k] != key;\n{\n\tvar low := 0;\n\tvar high := a.Length;\n\twhile (low < high)\n\t\t\t0 <= i < a.Length && !(low <= i < high) ==> a[i] != key;\n\t{\n\t\tvar mid := (low + high) / 2;\n\t\tif (a[mid] < key) {\n\t\t\tlow := mid + 1;\n\t\t}\n\t\telse if (key < a[mid]) {\n\t\t\thigh := mid;\n\t\t}\n\t\telse {\n\t\t\treturn mid;\n\t\t}\n\t}\n\treturn -1;\n}\n" }, { "test_ID": "113", "test_file": "Dafny-experiences_tmp_tmp150sm9qy_dafny_started_tutorial_dafny_tutorial_array.dfy", "ground_truth": "method FindMax(a: array) returns (i: int)\n // Annotate this method with pre- and postconditions\n // that ensure it behaves as described.\n requires a.Length > 0\n ensures 0<= i < a.Length\n ensures forall k :: 0 <= k < a.Length ==> a[k] <= a[i]\n{\n // Fill in the body that calculates the INDEX of the maximum.\n i := 0;\n var index := 1;\n while index < a.Length\n invariant 0 < index <= a.Length\n invariant 0 <= i < index\n invariant forall k :: 0 <= k < index ==> a[k] <= a[i]\n {\n if a[index] > a[i] {i:= index;}\n index := index + 1;\n }\n}\n\n", "hints_removed": "method FindMax(a: array) returns (i: int)\n // Annotate this method with pre- and postconditions\n // that ensure it behaves as described.\n requires a.Length > 0\n ensures 0<= i < a.Length\n ensures forall k :: 0 <= k < a.Length ==> a[k] <= a[i]\n{\n // Fill in the body that calculates the INDEX of the maximum.\n i := 0;\n var index := 1;\n while index < a.Length\n {\n if a[index] > a[i] {i:= index;}\n index := index + 1;\n }\n}\n\n" }, { "test_ID": "114", "test_file": "Dafny-programs_tmp_tmpnso9eu7u_Algorithms + sorting_bubble-sort.dfy", "ground_truth": "/*\nBubble Sort is the simplest sorting algorithm that works by \nrepeatedly swapping the adjacent elements if they are in wrong order.\n*/\n\npredicate sorted_between(A:array, from:int, to:int)\n reads A\n{\n forall i, j :: 0 <= i <= j < A.Length && from <= i <= j <= to ==> A[i] <= A[j]\n}\n\npredicate sorted(A:array)\n reads A\n{\n sorted_between(A, 0, A.Length-1)\n}\n\nmethod BubbleSort(A:array)\n modifies A\n ensures sorted(A)\n ensures multiset(A[..]) == multiset(old(A[..]))\n{\n var N := A.Length;\n var i := N-1;\n while 0 < i\n invariant multiset(A[..]) == multiset(old(A[..]))\n invariant sorted_between(A, i, N-1)\n invariant forall n, m :: 0 <= n <= i < m < N ==> A[n] <= A[m]\n decreases i\n {\n print A[..], \"\\n\";\n var j := 0;\n while j < i\n invariant 0 < i < N\n invariant 0 <= j <= i\n invariant multiset(A[..]) == multiset(old(A[..]))\n invariant sorted_between(A, i, N-1)\n invariant forall n, m :: 0 <= n <= i < m < N ==> A[n] <= A[m]\n invariant forall n :: 0 <= n <= j ==> A[n] <= A[j]\n decreases i - j\n {\n if A[j] > A[j+1]\n {\n A[j], A[j+1] := A[j+1], A[j];\n print A[..], \"\\n\";\n }\n j := j+1;\n } \n i := i-1;\n print \"\\n\";\n }\n}\n\nmethod Main() {\n var A := new int[10];\n A[0], A[1], A[2], A[3], A[4], A[5], A[6], A[7], A[8], A[9] := 2, 4, 6, 15, 3, 19, 17, 16, 18, 1;\n BubbleSort(A);\n print A[..];\n}\n\n/* Explanation:\n\ninvariant forall n, m :: 0 <= n <= i A [n] <= A [m]\n // A is ordered for each pair of elements such that\n // the first element belongs to the left partition of i\n // and the second element belongs to the right partition of i\n\ninvariant forall n :: 0 <= n <= j ==> A [n] <= A [j]\n // There is a variable defined by the value that the array takes at position j\n // Therefore, each value that the array takes for all elements from 0 to j\n // They are less than or equal to the value of the variable\n*/\n", "hints_removed": "/*\nBubble Sort is the simplest sorting algorithm that works by \nrepeatedly swapping the adjacent elements if they are in wrong order.\n*/\n\npredicate sorted_between(A:array, from:int, to:int)\n reads A\n{\n forall i, j :: 0 <= i <= j < A.Length && from <= i <= j <= to ==> A[i] <= A[j]\n}\n\npredicate sorted(A:array)\n reads A\n{\n sorted_between(A, 0, A.Length-1)\n}\n\nmethod BubbleSort(A:array)\n modifies A\n ensures sorted(A)\n ensures multiset(A[..]) == multiset(old(A[..]))\n{\n var N := A.Length;\n var i := N-1;\n while 0 < i\n {\n print A[..], \"\\n\";\n var j := 0;\n while j < i\n {\n if A[j] > A[j+1]\n {\n A[j], A[j+1] := A[j+1], A[j];\n print A[..], \"\\n\";\n }\n j := j+1;\n } \n i := i-1;\n print \"\\n\";\n }\n}\n\nmethod Main() {\n var A := new int[10];\n A[0], A[1], A[2], A[3], A[4], A[5], A[6], A[7], A[8], A[9] := 2, 4, 6, 15, 3, 19, 17, 16, 18, 1;\n BubbleSort(A);\n print A[..];\n}\n\n/* Explanation:\n\n // A is ordered for each pair of elements such that\n // the first element belongs to the left partition of i\n // and the second element belongs to the right partition of i\n\n // There is a variable defined by the value that the array takes at position j\n // Therefore, each value that the array takes for all elements from 0 to j\n // They are less than or equal to the value of the variable\n*/\n" }, { "test_ID": "115", "test_file": "DafnyExercises_tmp_tmpd6qyevja_Part1_Q1.dfy", "ground_truth": "method addArrays(a : array, b : array) returns (c : array) \nrequires a.Length == b.Length\nensures b.Length == c.Length\nensures forall i:int :: 0 <= i c[i] == a[i] + b[i]\n\n{\n c := new int[a.Length];\n var j := 0;\n while (j < a.Length) \n invariant 0 <= j <= c.Length\n invariant forall i :: (0 <= i < j) ==> c[i] == a[i] + b[i];\n { \n c[j] := a[j] + b[j];\n j := j + 1; \n }\n}\n", "hints_removed": "method addArrays(a : array, b : array) returns (c : array) \nrequires a.Length == b.Length\nensures b.Length == c.Length\nensures forall i:int :: 0 <= i c[i] == a[i] + b[i]\n\n{\n c := new int[a.Length];\n var j := 0;\n while (j < a.Length) \n { \n c[j] := a[j] + b[j];\n j := j + 1; \n }\n}\n" }, { "test_ID": "116", "test_file": "DafnyExercises_tmp_tmpd6qyevja_QuickExercises_testing2.dfy", "ground_truth": "\n// predicate recSorted(s : string) decreases s\n// { \n// if (|s| <=1) then true else if(s[0] > s[1]) then false else recSorted(s[1..])\n// }\n\n// predicate forallSorted (s : string)\n// { \n// forall x,y::0s[x] \"acbed\"[2];\n// // assert !forallSorted(\"acbed\");\n// // assert forallSorted(\"abcde\");\n// // }\n\n \n// /*omitted*/\n/* verify one of ensures r == forallSorted(a) OR \n ensures r == recSorted(a) \n Only one might work */\n// method whileSorted(a:string) returns (r : bool) \n// ensures r == forallSorted(a) // ONEOF\n// //ensures r == recSorted(a) // ONEOF\n\n// {\n// var i := 1;\n// r := true;\n// if |a| <=1 {\n// return true;\n// }\n// while i <|a| \n// invariant 0 < i <= |a|\n// invariant r == forallSorted(a[..i])\n// decreases |a| -i {\n// if a[i-1] > a[i] {\n// r:= false;\n// } \n// i := i+1;\n// }\n// }\n\n// lemma SortedSumForall(a:string,b:string)\n// requires forallSorted(a)\n// requires forallSorted(b)\n// ensures forallSorted(a + b) \n// requires (|a| >0 && |b| >0 ) ==> a[|a|-1] <= b[0]\n// {\n\n// }\n\n// /*omitted*/\n// // Prove using forallSorted not recursivly using SortedSumRec\n// lemma SortedSumRec(a:string,b:string)\n// requires recSorted(a)\n// requires recSorted(b)\n// requires |a| > 0 && |b| > 0\n// requires a[|a|-1] <= b[0]\n// ensures recSorted(a + b)\n// {\n// forallEQrec(a);\n// forallEQrec(b);\n// forallEQrec(a+b);\n// }\n\n// predicate recSorted(s : string) decreases s\n// /*omitted*/\n// // Prove using Induction not using forallEQrec\n// lemma SortedSumInduction(a:string,b:string)\n// requires recSorted(a)\n// requires recSorted(b)\n// requires |a| > 0 && |b| > 0\n// requires a[|a|-1] <= b[0]\n// ensures recSorted(a + b)\n// { \n \n // if |a| < 2 {\n\n // } else {\n // SortedSumInduction(a[1..],b);\n // assert recSorted(a[1..] +b);\n // assert [a[0]] + a[1..] == a;\n // assert recSorted([a[0]] + a[1..]);\n // assert [a[0]] + (a[1..] + b) == ([a[0]] + a[1..]) + b;\n // assert recSorted(a+b);\n // }\n// }\n\n// lemma VowelsLemma(s : string, t : string) \n// ensures vowels(s + t) == vowels(s) + vowels(t) \n// //verify this lemma - https://youtu.be/LFLD48go9os\n// {\n // if |s| > 0 {\n // assert [s[0]] + s[1..] == s;\n // assert [s[0]] + (s[1..] + t) == ([s[0]] + s[1..]) + t;\n // } else if |t| > 0 {\n // assert [t[0]] + t[1..] == t;\n // assert (s + [t[0]]) + t[1..] == s +([t[0]] + t[1..]);\n // }\n\n// }\n\n//so far straightwawrd\n// function vowels(s : string) : (r : nat)\n// {\n// if (|s| == 0) then 0\n// else \n// (if (s[0] in \"aeiou\") then 1 else 0)\n// + vowels(s[1..])\n// }\n\n\n// //see, this one is soooo EASY!!!\n// function vowelsF(s : string) : nat {\n// var m := multiset(s);\n// m['a'] + m['e'] + m['i'] + m['o'] + m['u']\n// }\n\n// lemma VowelsLemmaF(s : string, t : string) \n// ensures vowelsF(s + t) == vowelsF(s) + vowelsF(t) \n// {}\n\n// // method Main() {\n// // print \"have you verified one of: \\n ensures r == forallSorted(a) or \\n ensures r == recSorted(a)\\n\";\n// // print \"\\nYou must save your answer for later use!\\n\";\n// // assert \"acbed\"[1] > \"acbed\"[2];\n// // var nb := whileSorted(\"acbed\");\n// // assert !nb;\n// // var b := whileSorted(\"abcde\");\n// // assert b;\n// // }\n\n\n// class KlingonCalendar {\n// var dayOfWeek : int\n// const DAYS := [\"dishonour\", \"destruction\", \"defeat\", \"death\", \"victory\"] //-3, -2, -1, 0, 1\n// var weekOfMonth : int\n// const WEEKS := [ \"polishing spaceships\", \"carousing\", \"battle\"] // -1, 0, 1\n// var monthOfYear : int \n// const MONTHS := [\"peace\", \"pestilence\", \"famine\", \"flood\", \"covid\", \"war\", \"slaughter\"] //-5, -4 -3, -3, -1, 0, 1\n// var year : nat\n\n// //Define a \"Valid()\" predicate as a class invariant so that\n// //the rest of the class methods don't have to repeat everything!\n// predicate Valid()\n// reads this \n// {\n// (-3<=dayOfWeek <= 1) && (-1<=weekOfMonth<=1) && (-5;\n// const capacity : nat;\n// var size : nat;\n// constructor(capacity_ : nat) \n// /*omitted*/\n\n// method push(i : int) \n// modifies this, values\n// requires size 0\n// ensures values[size-1] == i\n// ensures size == old(size) +1\n// ensures old(size) < values.Length\n// ensures old(size) >= 0\n// ensures forall i :: 0 <= i < old(size) ==> old(values[i]) == values[i]{\n// values[size] :=i;\n// size:= size + 1;\n\n// }\n// method pop() returns (r : int) \n// modifies this\n// requires 0 = 0\n// ensures size == old(size) -1\n// ensures r == values[old(size-1)]\n// ensures r == values[size]\n\n// {\n// r := values[size-1]; \n// size := size -1;\n// } \n \n// }\n\n// method VerifyStack(s : Stack, i : int, j : int)\n// modifies s, s.values\n// requires 0 <= s.size < (s.values.Length - 2)\n// requires s.values.Length == s.capacity\n// requires s.size == 0\n// {\n// s.push(i);\n// s.push(j);\n// var v := s.pop();\n// assert v == j;\n// v := s.pop();\n// assert v == i;\n// }\n\n\n// datatype StackModel = Empty | Push(value : int, prev : StackModel)\n\n// class Stack {\n\n// const values : array;\n// const capacity : nat;\n// var size : nat;\n\n// function method toStackModel() : StackModel \n// requires 0 <= size <= capacity\n// requires values.Length == capacity\n// reads this, values\n// {toStackModelAux(size)}\n\n// function method toStackModelAux(i : nat) : StackModel \n// //requires 0 <= i <= size <= capacity\n// requires 0 <= i <= capacity\n// requires values.Length == capacity\n// reads values\n// decreases i \n// { \n// if (i == 0) then Empty \n// else Push(values[i-1],toStackModelAux(i-1))\n// }\n\n// //Here's where you need to re-use your code\n// //Copy in your existing code for these methods\n// //\n\n// predicate Valid()\n// reads this\n// {\n// size <= values.Length && values.Length == capacity\n// } \n\n// constructor(capacity_ : nat) \n// ensures capacity == capacity_\n// ensures Valid()\n// // ensures values.Length == capacity_\n// // ensures values.Length == capacity\n// ensures size ==0\n// ensures forall i:nat::ivalues[i] ==0{\n// capacity := capacity_;\n// values := new int[capacity_](x=>0);\n// size := 0;\n// }\n\n\n// method push(i : int) \n// modifies this, values\n// requires Valid()\n// requires size 0\n// ensures values[size-1] == i\n// ensures size == old(size) +1\n// ensures forall i :: 0 <= i < old(size) ==> old(values[i]) == values[i]\n// ensures forall i :: 0 <= i <= old(size) ==> old(this.toStackModelAux(i)) == this.toStackModelAux(i)\n// ensures this.toStackModel().value == i \n// {\n// values[size] :=i;\n// size:= size + 1;\n \n// }\n// method pop() returns (r : int) \n// modifies this\n// requires 0 = 0\n// ensures size == old(size) -1\n// ensures r == values[old(size-1)]\n// ensures r == values[size]\n\n// {\n// r := values[size-1]; \n// size := size -1;\n// } \n \n// function method top() : (r : int)\n// reads values\n// reads this\n// requires values.Length > 0 \n// requires size > 0\n// requires size <= values.Length\n// ensures r == values[size-1]{\n// values[size-1]\n// }\n\n\n// }\n\n// method StackModelOK(s : Stack, i : int, j : int)\n// requires s.values.Length == s.capacity\n// modifies s, s.values\n// requires s.size == 0\n// requires s.capacity > 2\n// {\n// var sSM := s.toStackModel();\n// s.push(i);\n// assert s.toStackModel() == Push(i,sSM);\n// var v := s.pop();\n// assert v == i;\n// assert s.toStackModel() == sSM;\n\n// s.push(i);\n// assert s.toStackModel() == Push(i,sSM);\n// assert (Push(i,sSM).prev) == sSM;\n// s.push(j);\n// assert s.toStackModel() == Push(j,Push(i,sSM));\n// v := s.top();\n// assert v == j;\n// v := s.pop();\n// assert v == j;\n// assert s.toStackModel() == Push(i,sSM);\n// v := s.pop();\n// assert v == i;\n\n// var t := new Stack(10);\n// assert t.toStackModel() == Empty;\n// }\n\n\n// datatype StackModel = Empty | Push(value : int, prev : StackModel)\n\n// class Stack {\n// var values : array\n// var capacity : nat\n// var size : nat\n \n// ghost const Repr : set\n\n//Last Stack (\"bis\") question (for now!!!) - https://youtu.be/Goj8QCOkq-w\n//\n//Chapter 16 goes on to talk about how to define a Repr field\n//to outline the representation of the abstraction you're modelling\n//so you don't have to name all the objects involved in modifies\n//clauses, just refer to the whole Repr.\n// \n//Copy and paste your code for the final time, then edit your\n//constructor and Valid() class invariant so that the hidden\n//code in here should work. Define just these two methods:\n//\n// predicate Valid()\n// reads Repr\n// {\n// this in Repr && values in Repr && size <= values.Length && values.Length == capacity\n// } \n\n// constructor(capacity_ : nat) \n// ensures capacity == capacity_\n// ensures Valid()\n// ensures values.Length == capacity_\n// ensures values.Length == capacity\n// ensures size ==0\n// ensures forall i:nat::ivalues[i] ==0{\n// capacity := capacity_;\n// values := new int[capacity_](x=>0);\n// size := 0;\n// Repr := {this,values};\n// }\n\n\n\n// function method toStackModel() : StackModel \n// reads Repr\n// requires Valid()\n// /*omitted*/\n\n// function method toStackModelAux(i : nat) : StackModel \n// reads Repr\n// requires Valid()\n// /*omitted*/\n\n// method push(i : int) \n// requires Valid()\n// ensures Valid()\n// modifies Repr\n// ensures capacity == old(capacity)\n// /*omitted*/\n\n// method pop() returns (r : int) \n// requires Valid()\n// modifies this`size;\n// ensures Valid();\n// /*omitted*/\n\n// function method top() : (r : int)\n// requires Valid()\n// reads Repr\n// ensures Valid();\n// /*omitted*/\n// }\n\n\n\n\n\n// method StackOK(s : Stack, i : int, j : int)\n// requires s.Valid()\n// requires 0 <= s.size < (s.capacity - 2)\n// requires s.values.Length == s.capacity\n\n// requires s.size == 0\n// requires s.capacity > 2\n// modifies s.Repr\n// {\n// var sSM := s.toStackModel();\n// assert s.size == 0;\n// assert sSM.Empty?;\n// s.push(i);\n// assert s.toStackModel() == Push(i,sSM);\n// var v := s.pop();\n// assert v == i;\n// assert s.toStackModel() == sSM;\n// s.push(i);\n// assert s.toStackModel() == Push(i,sSM);\n// assert Push(i,sSM).prev == sSM;\n// s.push(j);\n// assert s.toStackModel() == Push(j,Push(i,sSM));\n// v := s.top();\n// assert v == j;\n// v := s.pop();\n// assert v == j;\n// assert s.toStackModel() == Push(i,sSM);\n// v := s.pop();\n// assert v == i; \n// }\n\n \n\n", "hints_removed": "\n// predicate recSorted(s : string) decreases s\n// { \n// if (|s| <=1) then true else if(s[0] > s[1]) then false else recSorted(s[1..])\n// }\n\n// predicate forallSorted (s : string)\n// { \n// forall x,y::0s[x] \"acbed\"[2];\n// // assert !forallSorted(\"acbed\");\n// // assert forallSorted(\"abcde\");\n// // }\n\n \n// /*omitted*/\n/* verify one of ensures r == forallSorted(a) OR \n ensures r == recSorted(a) \n Only one might work */\n// method whileSorted(a:string) returns (r : bool) \n// ensures r == forallSorted(a) // ONEOF\n// //ensures r == recSorted(a) // ONEOF\n\n// {\n// var i := 1;\n// r := true;\n// if |a| <=1 {\n// return true;\n// }\n// while i <|a| \n// invariant 0 < i <= |a|\n// invariant r == forallSorted(a[..i])\n// decreases |a| -i {\n// if a[i-1] > a[i] {\n// r:= false;\n// } \n// i := i+1;\n// }\n// }\n\n// lemma SortedSumForall(a:string,b:string)\n// requires forallSorted(a)\n// requires forallSorted(b)\n// ensures forallSorted(a + b) \n// requires (|a| >0 && |b| >0 ) ==> a[|a|-1] <= b[0]\n// {\n\n// }\n\n// /*omitted*/\n// // Prove using forallSorted not recursivly using SortedSumRec\n// lemma SortedSumRec(a:string,b:string)\n// requires recSorted(a)\n// requires recSorted(b)\n// requires |a| > 0 && |b| > 0\n// requires a[|a|-1] <= b[0]\n// ensures recSorted(a + b)\n// {\n// forallEQrec(a);\n// forallEQrec(b);\n// forallEQrec(a+b);\n// }\n\n// predicate recSorted(s : string) decreases s\n// /*omitted*/\n// // Prove using Induction not using forallEQrec\n// lemma SortedSumInduction(a:string,b:string)\n// requires recSorted(a)\n// requires recSorted(b)\n// requires |a| > 0 && |b| > 0\n// requires a[|a|-1] <= b[0]\n// ensures recSorted(a + b)\n// { \n \n // if |a| < 2 {\n\n // } else {\n // SortedSumInduction(a[1..],b);\n // assert recSorted(a[1..] +b);\n // assert [a[0]] + a[1..] == a;\n // assert recSorted([a[0]] + a[1..]);\n // assert [a[0]] + (a[1..] + b) == ([a[0]] + a[1..]) + b;\n // assert recSorted(a+b);\n // }\n// }\n\n// lemma VowelsLemma(s : string, t : string) \n// ensures vowels(s + t) == vowels(s) + vowels(t) \n// //verify this lemma - https://youtu.be/LFLD48go9os\n// {\n // if |s| > 0 {\n // assert [s[0]] + s[1..] == s;\n // assert [s[0]] + (s[1..] + t) == ([s[0]] + s[1..]) + t;\n // } else if |t| > 0 {\n // assert [t[0]] + t[1..] == t;\n // assert (s + [t[0]]) + t[1..] == s +([t[0]] + t[1..]);\n // }\n\n// }\n\n//so far straightwawrd\n// function vowels(s : string) : (r : nat)\n// {\n// if (|s| == 0) then 0\n// else \n// (if (s[0] in \"aeiou\") then 1 else 0)\n// + vowels(s[1..])\n// }\n\n\n// //see, this one is soooo EASY!!!\n// function vowelsF(s : string) : nat {\n// var m := multiset(s);\n// m['a'] + m['e'] + m['i'] + m['o'] + m['u']\n// }\n\n// lemma VowelsLemmaF(s : string, t : string) \n// ensures vowelsF(s + t) == vowelsF(s) + vowelsF(t) \n// {}\n\n// // method Main() {\n// // print \"have you verified one of: \\n ensures r == forallSorted(a) or \\n ensures r == recSorted(a)\\n\";\n// // print \"\\nYou must save your answer for later use!\\n\";\n// // assert \"acbed\"[1] > \"acbed\"[2];\n// // var nb := whileSorted(\"acbed\");\n// // assert !nb;\n// // var b := whileSorted(\"abcde\");\n// // assert b;\n// // }\n\n\n// class KlingonCalendar {\n// var dayOfWeek : int\n// const DAYS := [\"dishonour\", \"destruction\", \"defeat\", \"death\", \"victory\"] //-3, -2, -1, 0, 1\n// var weekOfMonth : int\n// const WEEKS := [ \"polishing spaceships\", \"carousing\", \"battle\"] // -1, 0, 1\n// var monthOfYear : int \n// const MONTHS := [\"peace\", \"pestilence\", \"famine\", \"flood\", \"covid\", \"war\", \"slaughter\"] //-5, -4 -3, -3, -1, 0, 1\n// var year : nat\n\n// //Define a \"Valid()\" predicate as a class invariant so that\n// //the rest of the class methods don't have to repeat everything!\n// predicate Valid()\n// reads this \n// {\n// (-3<=dayOfWeek <= 1) && (-1<=weekOfMonth<=1) && (-5;\n// const capacity : nat;\n// var size : nat;\n// constructor(capacity_ : nat) \n// /*omitted*/\n\n// method push(i : int) \n// modifies this, values\n// requires size 0\n// ensures values[size-1] == i\n// ensures size == old(size) +1\n// ensures old(size) < values.Length\n// ensures old(size) >= 0\n// ensures forall i :: 0 <= i < old(size) ==> old(values[i]) == values[i]{\n// values[size] :=i;\n// size:= size + 1;\n\n// }\n// method pop() returns (r : int) \n// modifies this\n// requires 0 = 0\n// ensures size == old(size) -1\n// ensures r == values[old(size-1)]\n// ensures r == values[size]\n\n// {\n// r := values[size-1]; \n// size := size -1;\n// } \n \n// }\n\n// method VerifyStack(s : Stack, i : int, j : int)\n// modifies s, s.values\n// requires 0 <= s.size < (s.values.Length - 2)\n// requires s.values.Length == s.capacity\n// requires s.size == 0\n// {\n// s.push(i);\n// s.push(j);\n// var v := s.pop();\n// assert v == j;\n// v := s.pop();\n// assert v == i;\n// }\n\n\n// datatype StackModel = Empty | Push(value : int, prev : StackModel)\n\n// class Stack {\n\n// const values : array;\n// const capacity : nat;\n// var size : nat;\n\n// function method toStackModel() : StackModel \n// requires 0 <= size <= capacity\n// requires values.Length == capacity\n// reads this, values\n// {toStackModelAux(size)}\n\n// function method toStackModelAux(i : nat) : StackModel \n// //requires 0 <= i <= size <= capacity\n// requires 0 <= i <= capacity\n// requires values.Length == capacity\n// reads values\n// decreases i \n// { \n// if (i == 0) then Empty \n// else Push(values[i-1],toStackModelAux(i-1))\n// }\n\n// //Here's where you need to re-use your code\n// //Copy in your existing code for these methods\n// //\n\n// predicate Valid()\n// reads this\n// {\n// size <= values.Length && values.Length == capacity\n// } \n\n// constructor(capacity_ : nat) \n// ensures capacity == capacity_\n// ensures Valid()\n// // ensures values.Length == capacity_\n// // ensures values.Length == capacity\n// ensures size ==0\n// ensures forall i:nat::ivalues[i] ==0{\n// capacity := capacity_;\n// values := new int[capacity_](x=>0);\n// size := 0;\n// }\n\n\n// method push(i : int) \n// modifies this, values\n// requires Valid()\n// requires size 0\n// ensures values[size-1] == i\n// ensures size == old(size) +1\n// ensures forall i :: 0 <= i < old(size) ==> old(values[i]) == values[i]\n// ensures forall i :: 0 <= i <= old(size) ==> old(this.toStackModelAux(i)) == this.toStackModelAux(i)\n// ensures this.toStackModel().value == i \n// {\n// values[size] :=i;\n// size:= size + 1;\n \n// }\n// method pop() returns (r : int) \n// modifies this\n// requires 0 = 0\n// ensures size == old(size) -1\n// ensures r == values[old(size-1)]\n// ensures r == values[size]\n\n// {\n// r := values[size-1]; \n// size := size -1;\n// } \n \n// function method top() : (r : int)\n// reads values\n// reads this\n// requires values.Length > 0 \n// requires size > 0\n// requires size <= values.Length\n// ensures r == values[size-1]{\n// values[size-1]\n// }\n\n\n// }\n\n// method StackModelOK(s : Stack, i : int, j : int)\n// requires s.values.Length == s.capacity\n// modifies s, s.values\n// requires s.size == 0\n// requires s.capacity > 2\n// {\n// var sSM := s.toStackModel();\n// s.push(i);\n// assert s.toStackModel() == Push(i,sSM);\n// var v := s.pop();\n// assert v == i;\n// assert s.toStackModel() == sSM;\n\n// s.push(i);\n// assert s.toStackModel() == Push(i,sSM);\n// assert (Push(i,sSM).prev) == sSM;\n// s.push(j);\n// assert s.toStackModel() == Push(j,Push(i,sSM));\n// v := s.top();\n// assert v == j;\n// v := s.pop();\n// assert v == j;\n// assert s.toStackModel() == Push(i,sSM);\n// v := s.pop();\n// assert v == i;\n\n// var t := new Stack(10);\n// assert t.toStackModel() == Empty;\n// }\n\n\n// datatype StackModel = Empty | Push(value : int, prev : StackModel)\n\n// class Stack {\n// var values : array\n// var capacity : nat\n// var size : nat\n \n// ghost const Repr : set\n\n//Last Stack (\"bis\") question (for now!!!) - https://youtu.be/Goj8QCOkq-w\n//\n//Chapter 16 goes on to talk about how to define a Repr field\n//to outline the representation of the abstraction you're modelling\n//so you don't have to name all the objects involved in modifies\n//clauses, just refer to the whole Repr.\n// \n//Copy and paste your code for the final time, then edit your\n//constructor and Valid() class invariant so that the hidden\n//code in here should work. Define just these two methods:\n//\n// predicate Valid()\n// reads Repr\n// {\n// this in Repr && values in Repr && size <= values.Length && values.Length == capacity\n// } \n\n// constructor(capacity_ : nat) \n// ensures capacity == capacity_\n// ensures Valid()\n// ensures values.Length == capacity_\n// ensures values.Length == capacity\n// ensures size ==0\n// ensures forall i:nat::ivalues[i] ==0{\n// capacity := capacity_;\n// values := new int[capacity_](x=>0);\n// size := 0;\n// Repr := {this,values};\n// }\n\n\n\n// function method toStackModel() : StackModel \n// reads Repr\n// requires Valid()\n// /*omitted*/\n\n// function method toStackModelAux(i : nat) : StackModel \n// reads Repr\n// requires Valid()\n// /*omitted*/\n\n// method push(i : int) \n// requires Valid()\n// ensures Valid()\n// modifies Repr\n// ensures capacity == old(capacity)\n// /*omitted*/\n\n// method pop() returns (r : int) \n// requires Valid()\n// modifies this`size;\n// ensures Valid();\n// /*omitted*/\n\n// function method top() : (r : int)\n// requires Valid()\n// reads Repr\n// ensures Valid();\n// /*omitted*/\n// }\n\n\n\n\n\n// method StackOK(s : Stack, i : int, j : int)\n// requires s.Valid()\n// requires 0 <= s.size < (s.capacity - 2)\n// requires s.values.Length == s.capacity\n\n// requires s.size == 0\n// requires s.capacity > 2\n// modifies s.Repr\n// {\n// var sSM := s.toStackModel();\n// assert s.size == 0;\n// assert sSM.Empty?;\n// s.push(i);\n// assert s.toStackModel() == Push(i,sSM);\n// var v := s.pop();\n// assert v == i;\n// assert s.toStackModel() == sSM;\n// s.push(i);\n// assert s.toStackModel() == Push(i,sSM);\n// assert Push(i,sSM).prev == sSM;\n// s.push(j);\n// assert s.toStackModel() == Push(j,Push(i,sSM));\n// v := s.top();\n// assert v == j;\n// v := s.pop();\n// assert v == j;\n// assert s.toStackModel() == Push(i,sSM);\n// v := s.pop();\n// assert v == i; \n// }\n\n \n\n" }, { "test_ID": "117", "test_file": "DafnyPrograms_tmp_tmp74_f9k_c_automaton.dfy", "ground_truth": "/**\nConsider cellular automata: a row of cells is repeatedly updated according to a rule. In this exercise I dabbled with,\neach cell has the value either false or true. Each cell's next state depends only on the immediate neighbours, in the \ncase where the cell is at the edges of the row, the inexistent neighbours are replaced by \"false\". The automaton table \nwill contain the initial row, plus a row for each number of steps.\n */\nclass Automaton {\n\n/**\nThis method computes the automaton.\nProvide the initial row: init, the rule and the desired number of steps\n */\nmethod ExecuteAutomaton(init: seq, rule: (bool, bool, bool) -> bool, steps: nat)\n returns (table: seq>)\n // we need the initial row to have the length bigger or equal to two\n requires |init| >= 2\n // after computation the automaton is made of the initial row plus a row for each of the steps\n ensures |table| == 1 + steps\n // the automaton must have the initial row at the top\n ensures table[0] == init;\n // all rows in the automaton must be the same length\n ensures forall i | 0 <= i < |table| :: |table[i]| == |init|\n // all the middle row elements (with existing neighbours) after a step, will be equal to the rule applied on the element in the previous state\n // and its neigbours\n ensures forall i | 0 <= i < |table| - 1 ::\n forall j | 1 <= j <= |table[i]| - 2 :: table[i + 1][j] == rule(table[i][j - 1], table[i][j], table[i][j + 1])\n // the corner row elements (with non-existing neighbours) after a step, will be equal to the rule applied on the element in the previous state,\n // its neighbour and false\n ensures forall i | 0 <= i < |table| - 1 ::\n table[i + 1][0] == rule(false, table[i][0], table[i][1]) && table[i + 1][|table[i]| - 1] == rule(table[i][|table[i]| - 2], table[i][|table[i]| - 1], false)\n{\n // the table containing the automaton \n var result : seq> := [init];\n // the current row\n var currentSeq := init;\n var index := 0;\n\n while index < steps\n invariant 0 <= index <= steps\n // the length of the table will be the index + 1, since it starts with an element and at every loop iteration we add a row to it\n invariant |result| == index + 1\n // the first element of the table is the init row\n invariant result[0] == init\n // the lenght of the rows in the table are equal\n invariant |currentSeq| == |init|\n invariant forall i | 0 <= i < |result| :: |result[i]| == |init|\n // Dafny needs mentioning that that the currentSeq is equal to the element at position index in the table\n invariant currentSeq == result[index]\n // invariant for the first ensures condition obtained by replacing constant with variable\n invariant forall i | 0 <= i < |result| - 1 ::\n forall j | 1 <= j <= |result[i]| - 2 :: result[i + 1][j] == rule(result[i][j - 1], result[i][j], result[i][j + 1])\n // invariant for the second ensures condition obtained by replacing constant with variable\n invariant forall i | 0 <= i < |result| - 1 ::\n result[i + 1][0] == rule(false, result[i][0], result[i][1]) && result[i + 1][|result[i]| - 1] == rule(result[i][|result[i]| - 2], result[i][|result[i]| - 1], false)\n // the decreases clause to prove termination of this loop\n decreases steps - index\n {\n var index2 := 1;\n // the next row to be computed\n var nextSeq := [];\n nextSeq := nextSeq + [rule(false, currentSeq[0], currentSeq[1])];\n\n while index2 < |currentSeq| - 1\n invariant |currentSeq| == |init|\n invariant 0 <= index2 <= |currentSeq| - 1\n invariant |nextSeq| == index2\n // even though its trivial, Dafny needs mentioning that the below invariant holds at every iteration of the loop,\n // since nextSeq[0] was initialized before entering the loop\n invariant nextSeq[0] == rule(false, currentSeq[0], currentSeq[1])\n // all elements smaller than index2 are already present in the new row with the value calculated by the rule, \n // the element at index2 is still to be computed inside the while loop, thus when entering the loop \n // the rule value does not yet hold for it\n invariant forall i | 1 <= i < index2 :: nextSeq[i] == rule(currentSeq[i - 1], currentSeq[i], currentSeq[i + 1])\n decreases |currentSeq| - index2\n {\n nextSeq := nextSeq + [rule(currentSeq[index2 - 1], currentSeq[index2], currentSeq[index2 + 1])];\n index2 := index2 + 1;\n }\n nextSeq := nextSeq + [rule(currentSeq[|currentSeq| - 2], currentSeq[|currentSeq| - 1], false)];\n\n currentSeq := nextSeq;\n result := result + [nextSeq];\n index := index + 1;\n }\n\n return result;\n}\n\n// example rule\nfunction TheRule(a: bool, b: bool, c: bool) : bool\n{\n a || b || c\n}\n\n// example rule 2\nfunction TheRule2(a: bool, b: bool, c: bool) : bool\n{\n a && b && c\n}\n\nmethod testMethod() {\n // the initial row\n var init := [false, false, true, false, false];\n\n // calculate automaton steps with \n var result := ExecuteAutomaton(init, TheRule, 3);\n // the intial row plus the three steps of the automaton are showed bellow\n assert(result[0] == [false, false, true, false, false]); // the initial state of the automaton\n assert(result[1] == [false, true, true, true, false]); // after the first step\n assert(result[2] == [true, true, true, true, true]); // after the second step\n assert(result[3] == [true, true, true, true, true]); // after the third step, remains the same from now on\n\n var result2 := ExecuteAutomaton(init, TheRule2, 2);\n // the intial row plus the two steps of the automaton are showed bellow\n assert(result2[0] == [false, false, true, false, false]); // the initial state of the automaton\n assert(result2[1] == [false, false, false, false, false]); // after the first step\n assert(result2[2] == [false, false, false, false, false]); // after the second step, remains the same from now on\n}\n}\n\n\n", "hints_removed": "/**\nConsider cellular automata: a row of cells is repeatedly updated according to a rule. In this exercise I dabbled with,\neach cell has the value either false or true. Each cell's next state depends only on the immediate neighbours, in the \ncase where the cell is at the edges of the row, the inexistent neighbours are replaced by \"false\". The automaton table \nwill contain the initial row, plus a row for each number of steps.\n */\nclass Automaton {\n\n/**\nThis method computes the automaton.\nProvide the initial row: init, the rule and the desired number of steps\n */\nmethod ExecuteAutomaton(init: seq, rule: (bool, bool, bool) -> bool, steps: nat)\n returns (table: seq>)\n // we need the initial row to have the length bigger or equal to two\n requires |init| >= 2\n // after computation the automaton is made of the initial row plus a row for each of the steps\n ensures |table| == 1 + steps\n // the automaton must have the initial row at the top\n ensures table[0] == init;\n // all rows in the automaton must be the same length\n ensures forall i | 0 <= i < |table| :: |table[i]| == |init|\n // all the middle row elements (with existing neighbours) after a step, will be equal to the rule applied on the element in the previous state\n // and its neigbours\n ensures forall i | 0 <= i < |table| - 1 ::\n forall j | 1 <= j <= |table[i]| - 2 :: table[i + 1][j] == rule(table[i][j - 1], table[i][j], table[i][j + 1])\n // the corner row elements (with non-existing neighbours) after a step, will be equal to the rule applied on the element in the previous state,\n // its neighbour and false\n ensures forall i | 0 <= i < |table| - 1 ::\n table[i + 1][0] == rule(false, table[i][0], table[i][1]) && table[i + 1][|table[i]| - 1] == rule(table[i][|table[i]| - 2], table[i][|table[i]| - 1], false)\n{\n // the table containing the automaton \n var result : seq> := [init];\n // the current row\n var currentSeq := init;\n var index := 0;\n\n while index < steps\n // the length of the table will be the index + 1, since it starts with an element and at every loop iteration we add a row to it\n // the first element of the table is the init row\n // the lenght of the rows in the table are equal\n // Dafny needs mentioning that that the currentSeq is equal to the element at position index in the table\n // invariant for the first ensures condition obtained by replacing constant with variable\n forall j | 1 <= j <= |result[i]| - 2 :: result[i + 1][j] == rule(result[i][j - 1], result[i][j], result[i][j + 1])\n // invariant for the second ensures condition obtained by replacing constant with variable\n result[i + 1][0] == rule(false, result[i][0], result[i][1]) && result[i + 1][|result[i]| - 1] == rule(result[i][|result[i]| - 2], result[i][|result[i]| - 1], false)\n // the decreases clause to prove termination of this loop\n {\n var index2 := 1;\n // the next row to be computed\n var nextSeq := [];\n nextSeq := nextSeq + [rule(false, currentSeq[0], currentSeq[1])];\n\n while index2 < |currentSeq| - 1\n // even though its trivial, Dafny needs mentioning that the below invariant holds at every iteration of the loop,\n // since nextSeq[0] was initialized before entering the loop\n // all elements smaller than index2 are already present in the new row with the value calculated by the rule, \n // the element at index2 is still to be computed inside the while loop, thus when entering the loop \n // the rule value does not yet hold for it\n {\n nextSeq := nextSeq + [rule(currentSeq[index2 - 1], currentSeq[index2], currentSeq[index2 + 1])];\n index2 := index2 + 1;\n }\n nextSeq := nextSeq + [rule(currentSeq[|currentSeq| - 2], currentSeq[|currentSeq| - 1], false)];\n\n currentSeq := nextSeq;\n result := result + [nextSeq];\n index := index + 1;\n }\n\n return result;\n}\n\n// example rule\nfunction TheRule(a: bool, b: bool, c: bool) : bool\n{\n a || b || c\n}\n\n// example rule 2\nfunction TheRule2(a: bool, b: bool, c: bool) : bool\n{\n a && b && c\n}\n\nmethod testMethod() {\n // the initial row\n var init := [false, false, true, false, false];\n\n // calculate automaton steps with \n var result := ExecuteAutomaton(init, TheRule, 3);\n // the intial row plus the three steps of the automaton are showed bellow\n\n var result2 := ExecuteAutomaton(init, TheRule2, 2);\n // the intial row plus the two steps of the automaton are showed bellow\n}\n}\n\n\n" }, { "test_ID": "118", "test_file": "DafnyPrograms_tmp_tmp74_f9k_c_invertarray.dfy", "ground_truth": "/**\n Inverts an array of ints.\n */\nmethod InvertArray(a: array)\n modifies a\n ensures forall i | 0 <= i < a.Length :: a[i] == old(a[a.Length-1-i])\n{\n var index := 0;\n\n while index < a.Length / 2\n invariant 0 <= index <= a.Length / 2\n // the elements i before position index are already switched with the old value of position a.Length - 1 - i\n invariant forall i | 0 <= i < index :: a[i] == old(a[a.Length - 1 - i])\n // the elements of form a.Length - 1 - i after position a.Length - 1 - index are already switched with the old value of position i\n invariant forall i | 0 <= i < index :: a[a.Length - 1 - i] == old(a[i])\n // the elements between index and a.Length - index are unchanged : the middle of the array\n invariant forall i | index <= i < a.Length - index :: a[i] == old(a[i])\n {\n a[index], a[a.Length - 1 - index] := a[a.Length - 1 - index], a[index];\n index := index + 1;\n }\n}\n", "hints_removed": "/**\n Inverts an array of ints.\n */\nmethod InvertArray(a: array)\n modifies a\n ensures forall i | 0 <= i < a.Length :: a[i] == old(a[a.Length-1-i])\n{\n var index := 0;\n\n while index < a.Length / 2\n // the elements i before position index are already switched with the old value of position a.Length - 1 - i\n // the elements of form a.Length - 1 - i after position a.Length - 1 - index are already switched with the old value of position i\n // the elements between index and a.Length - index are unchanged : the middle of the array\n {\n a[index], a[a.Length - 1 - index] := a[a.Length - 1 - index], a[index];\n index := index + 1;\n }\n}\n" }, { "test_ID": "119", "test_file": "DafnyPrograms_tmp_tmp74_f9k_c_map-multiset-implementation.dfy", "ground_truth": "/**\n This ADT represents a multiset.\n */\ntrait MyMultiset {\n\n // internal invariant\n ghost predicate Valid()\n reads this\n\n // abstract variable\n ghost var theMultiset: multiset\n\n method Add(elem: int) returns (didChange: bool)\n modifies this\n requires Valid()\n ensures Valid()\n ensures theMultiset == old(theMultiset) + multiset{elem}\n ensures didChange\n\n ghost predicate Contains(elem: int)\n reads this\n { elem in theMultiset }\n\n method Remove(elem: int) returns (didChange: bool)\n modifies this\n requires Valid()\n ensures Valid()\n /* If the multiset contains the element */\n ensures old(Contains(elem)) ==> theMultiset == old(theMultiset) - multiset{elem}\n ensures old(Contains(elem)) ==> didChange\n /* If the multiset does not contain the element */\n ensures ! old(Contains(elem)) ==> theMultiset == old(theMultiset)\n ensures ! old(Contains(elem)) ==> ! didChange\n\n method Length() returns (len: int)\n requires Valid()\n ensures Valid()\n ensures len == |theMultiset|\n\n method equals(other: MyMultiset) returns (equal?: bool)\n requires Valid()\n requires other.Valid()\n ensures Valid()\n ensures equal? <==> theMultiset == other.theMultiset\n\n method getElems() returns (elems: seq)\n requires Valid()\n ensures Valid()\n ensures multiset(elems) == theMultiset\n}\n\n/**\nThis implementation implements the ADT with a map.\n */\nclass MultisetImplementationWithMap extends MyMultiset {\n\n // valid invariant predicate of the ADT implementation\n ghost predicate Valid()\n reads this\n {\n (forall i | i in elements.Keys :: elements[i] > 0) && (theMultiset == A(elements)) && (forall i :: i in elements.Keys <==> Contains(i))\n }\n\n // the abstraction function\n function A(m: map): (s:multiset)\n ensures (forall i | i in m :: m[i] == A(m)[i]) && (m == map[] <==> A(m) == multiset{}) && (forall i :: i in m <==> i in A(m))\n\n // lemma for the opposite of the abstraction function\n lemma LemmaReverseA(m: map, s : seq)\n requires (forall i | i in m :: m[i] == multiset(s)[i]) && (m == map[] <==> multiset(s) == multiset{})\n ensures A(m) == multiset(s)\n\n // ADT concrete implementation variable\n var elements: map;\n\n // constructor of the implementation class that ensures the implementation invariant\n constructor MultisetImplementationWithMap()\n ensures Valid()\n ensures elements == map[]\n ensures theMultiset == multiset{}\n {\n elements := map[];\n theMultiset := multiset{};\n }\n//adds an element to the multiset\n method Add(elem: int) returns (didChange: bool)\n modifies this\n requires Valid()\n ensures elem in elements ==> elements == elements[elem := elements[elem]]\n ensures theMultiset == old(theMultiset) + multiset{elem}\n ensures !(elem in elements) ==> elements == elements[elem := 1]\n ensures didChange\n ensures Contains(elem)\n ensures Valid()\n {\n if !(elem in elements) {\n elements := elements[elem := 1];\n } else {\n elements := elements[elem := (elements[elem] + 1)];\n }\n \n didChange := true;\n\n theMultiset := A(elements);\n }\n\n//removes an element from the multiset\n method Remove(elem: int) returns (didChange: bool)\n modifies this\n requires Valid()\n ensures Valid()\n /* If the multiset contains the element */\n ensures old(Contains(elem)) ==> theMultiset == old(theMultiset) - multiset{elem}\n ensures old(Contains(elem)) ==> didChange\n /* If the multiset does not contain the element */\n ensures ! old(Contains(elem)) ==> theMultiset == old(theMultiset)\n ensures ! old(Contains(elem)) ==> ! didChange\n ensures didChange <==> elements != old(elements)\n {\n /* If the multiset does not contain the element */\n if elem !in elements {\n assert ! Contains(elem);\n assert theMultiset == old(theMultiset);\n assert Valid();\n return false;\n }\n\n /* If the multiset contains the element */\n assert Contains(elem);\n elements := elements[elem := elements[elem] - 1];\n\n if(elements[elem] == 0) {\n elements := elements - {elem};\n }\n\n theMultiset := A(elements);\n didChange := true;\n }\n\n//gets the length of the multiset\n method Length() returns (len: int)\n requires Valid()\n ensures len == |theMultiset|\n {\n var result := Map2Seq(elements);\n return |result|;\n }\n\n//compares the current multiset with another multiset and determines if they're equal\n method equals(other: MyMultiset) returns (equal?: bool)\n requires Valid()\n requires other.Valid()\n ensures Valid()\n ensures equal? <==> theMultiset == other.theMultiset\n {\n var otherMapSeq := other.getElems();\n assert multiset(otherMapSeq) == other.theMultiset;\n var c := this.getElems();\n return multiset(c) == multiset(otherMapSeq);\n }\n\n//gets the elements of the multiset as a sequence\n method getElems() returns (elems: seq)\n requires Valid()\n ensures Valid()\n ensures multiset(elems) == theMultiset\n {\n var result : seq;\n result := Map2Seq(elements);\n return result;\n }\n\n//Transforms a map to a sequence\n method Map2Seq(m: map) returns (s: seq)\n requires forall i | i in m.Keys :: i in m.Keys <==> m[i] > 0\n ensures forall i | i in m.Keys :: multiset(s)[i] == m[i]\n ensures forall i | i in m.Keys :: i in s\n ensures A(m) == multiset(s)\n ensures (forall i | i in m :: m[i] == multiset(s)[i]) && (m == map[] <==> multiset(s) == multiset{})\n {\n if |m| == 0 {return []; }\n\n var keys := m.Keys;\n var key: int;\n s := [];\n\n while keys != {}\n invariant forall i | i in m.Keys :: i in keys <==> multiset(s)[i] == 0\n invariant forall i | i in m.Keys - keys :: multiset(s)[i] == m[i]\n {\n\n key :| key in keys;\n\n var counter := 0;\n\n while counter < m[key]\n invariant 0 <= counter <= m[key]\n invariant multiset(s)[key] == counter\n invariant forall i | i in m.Keys && i != key :: i in keys <==> multiset(s)[i] == 0\n invariant forall i | i in m.Keys - keys :: multiset(s)[i] == m[i];\n {\n s := s + [key];\n counter := counter + 1;\n }\n\n keys := keys - {key};\n\n }\n LemmaReverseA(m, s);\n }\n\n method Test1()\n modifies this\n {\n\n assume this.theMultiset == multiset{1, 2, 3, 4};\n assume this.Valid();\n\n // get elements test\n var a := this.getElems();\n assert multiset(a) == multiset{1, 2, 3, 4};\n\n //declaring the other bag\n var theOtherBag : MultisetImplementationWithMap;\n theOtherBag := new MultisetImplementationWithMap.MultisetImplementationWithMap();\n\n // equals test - unequal bags\n var b:= this.equals(theOtherBag);\n assert b == false;\n\n // equals test - equal bags\n theOtherBag.theMultiset := multiset{1, 2, 3, 4};\n theOtherBag.elements := map[1 := 1, 2:=1, 3:=1,4:=1];\n var c:= this.equals(theOtherBag);\n assert c == true;\n }\n\n method Test2()\n modifies this\n {\n\n assume this.theMultiset == multiset{1, 2, 3, 4};\n assume this.Valid();\n\n // get elements test\n var a := this.getElems();\n assert multiset(a) == multiset{1, 2, 3, 4};\n\n //add test\n var d := this.Add(3);\n var e := this.getElems();\n assert multiset(e) == multiset([1, 2, 3, 4, 3]);\n\n //remove test\n var f := this.Remove(4);\n var g := this.getElems();\n assert multiset(g) == multiset([1, 2, 3, 3]);\n\n //length test\n var h := this.Length();\n assert h == 4;\n }\n\n method Test3()\n {\n\n //test Map2Seq\n var m := map[2:= 2, 3:=3, 4:= 4];\n var s :seq := [2, 2, 3, 3, 3, 4, 4,4 ,4];\n\n var a := this.Map2Seq(m);\n assert multiset(a) == multiset(s);\n\n var x := map[1 := 1, 2:= 1, 3:= 1];\n var y :seq := [1, 2, 3];\n\n var z := this.Map2Seq(x);\n assert multiset(z) == multiset(y);\n\n }\n}\n", "hints_removed": "/**\n This ADT represents a multiset.\n */\ntrait MyMultiset {\n\n // internal invariant\n ghost predicate Valid()\n reads this\n\n // abstract variable\n ghost var theMultiset: multiset\n\n method Add(elem: int) returns (didChange: bool)\n modifies this\n requires Valid()\n ensures Valid()\n ensures theMultiset == old(theMultiset) + multiset{elem}\n ensures didChange\n\n ghost predicate Contains(elem: int)\n reads this\n { elem in theMultiset }\n\n method Remove(elem: int) returns (didChange: bool)\n modifies this\n requires Valid()\n ensures Valid()\n /* If the multiset contains the element */\n ensures old(Contains(elem)) ==> theMultiset == old(theMultiset) - multiset{elem}\n ensures old(Contains(elem)) ==> didChange\n /* If the multiset does not contain the element */\n ensures ! old(Contains(elem)) ==> theMultiset == old(theMultiset)\n ensures ! old(Contains(elem)) ==> ! didChange\n\n method Length() returns (len: int)\n requires Valid()\n ensures Valid()\n ensures len == |theMultiset|\n\n method equals(other: MyMultiset) returns (equal?: bool)\n requires Valid()\n requires other.Valid()\n ensures Valid()\n ensures equal? <==> theMultiset == other.theMultiset\n\n method getElems() returns (elems: seq)\n requires Valid()\n ensures Valid()\n ensures multiset(elems) == theMultiset\n}\n\n/**\nThis implementation implements the ADT with a map.\n */\nclass MultisetImplementationWithMap extends MyMultiset {\n\n // valid invariant predicate of the ADT implementation\n ghost predicate Valid()\n reads this\n {\n (forall i | i in elements.Keys :: elements[i] > 0) && (theMultiset == A(elements)) && (forall i :: i in elements.Keys <==> Contains(i))\n }\n\n // the abstraction function\n function A(m: map): (s:multiset)\n ensures (forall i | i in m :: m[i] == A(m)[i]) && (m == map[] <==> A(m) == multiset{}) && (forall i :: i in m <==> i in A(m))\n\n // lemma for the opposite of the abstraction function\n lemma LemmaReverseA(m: map, s : seq)\n requires (forall i | i in m :: m[i] == multiset(s)[i]) && (m == map[] <==> multiset(s) == multiset{})\n ensures A(m) == multiset(s)\n\n // ADT concrete implementation variable\n var elements: map;\n\n // constructor of the implementation class that ensures the implementation invariant\n constructor MultisetImplementationWithMap()\n ensures Valid()\n ensures elements == map[]\n ensures theMultiset == multiset{}\n {\n elements := map[];\n theMultiset := multiset{};\n }\n//adds an element to the multiset\n method Add(elem: int) returns (didChange: bool)\n modifies this\n requires Valid()\n ensures elem in elements ==> elements == elements[elem := elements[elem]]\n ensures theMultiset == old(theMultiset) + multiset{elem}\n ensures !(elem in elements) ==> elements == elements[elem := 1]\n ensures didChange\n ensures Contains(elem)\n ensures Valid()\n {\n if !(elem in elements) {\n elements := elements[elem := 1];\n } else {\n elements := elements[elem := (elements[elem] + 1)];\n }\n \n didChange := true;\n\n theMultiset := A(elements);\n }\n\n//removes an element from the multiset\n method Remove(elem: int) returns (didChange: bool)\n modifies this\n requires Valid()\n ensures Valid()\n /* If the multiset contains the element */\n ensures old(Contains(elem)) ==> theMultiset == old(theMultiset) - multiset{elem}\n ensures old(Contains(elem)) ==> didChange\n /* If the multiset does not contain the element */\n ensures ! old(Contains(elem)) ==> theMultiset == old(theMultiset)\n ensures ! old(Contains(elem)) ==> ! didChange\n ensures didChange <==> elements != old(elements)\n {\n /* If the multiset does not contain the element */\n if elem !in elements {\n return false;\n }\n\n /* If the multiset contains the element */\n elements := elements[elem := elements[elem] - 1];\n\n if(elements[elem] == 0) {\n elements := elements - {elem};\n }\n\n theMultiset := A(elements);\n didChange := true;\n }\n\n//gets the length of the multiset\n method Length() returns (len: int)\n requires Valid()\n ensures len == |theMultiset|\n {\n var result := Map2Seq(elements);\n return |result|;\n }\n\n//compares the current multiset with another multiset and determines if they're equal\n method equals(other: MyMultiset) returns (equal?: bool)\n requires Valid()\n requires other.Valid()\n ensures Valid()\n ensures equal? <==> theMultiset == other.theMultiset\n {\n var otherMapSeq := other.getElems();\n var c := this.getElems();\n return multiset(c) == multiset(otherMapSeq);\n }\n\n//gets the elements of the multiset as a sequence\n method getElems() returns (elems: seq)\n requires Valid()\n ensures Valid()\n ensures multiset(elems) == theMultiset\n {\n var result : seq;\n result := Map2Seq(elements);\n return result;\n }\n\n//Transforms a map to a sequence\n method Map2Seq(m: map) returns (s: seq)\n requires forall i | i in m.Keys :: i in m.Keys <==> m[i] > 0\n ensures forall i | i in m.Keys :: multiset(s)[i] == m[i]\n ensures forall i | i in m.Keys :: i in s\n ensures A(m) == multiset(s)\n ensures (forall i | i in m :: m[i] == multiset(s)[i]) && (m == map[] <==> multiset(s) == multiset{})\n {\n if |m| == 0 {return []; }\n\n var keys := m.Keys;\n var key: int;\n s := [];\n\n while keys != {}\n {\n\n key :| key in keys;\n\n var counter := 0;\n\n while counter < m[key]\n {\n s := s + [key];\n counter := counter + 1;\n }\n\n keys := keys - {key};\n\n }\n LemmaReverseA(m, s);\n }\n\n method Test1()\n modifies this\n {\n\n assume this.theMultiset == multiset{1, 2, 3, 4};\n assume this.Valid();\n\n // get elements test\n var a := this.getElems();\n\n //declaring the other bag\n var theOtherBag : MultisetImplementationWithMap;\n theOtherBag := new MultisetImplementationWithMap.MultisetImplementationWithMap();\n\n // equals test - unequal bags\n var b:= this.equals(theOtherBag);\n\n // equals test - equal bags\n theOtherBag.theMultiset := multiset{1, 2, 3, 4};\n theOtherBag.elements := map[1 := 1, 2:=1, 3:=1,4:=1];\n var c:= this.equals(theOtherBag);\n }\n\n method Test2()\n modifies this\n {\n\n assume this.theMultiset == multiset{1, 2, 3, 4};\n assume this.Valid();\n\n // get elements test\n var a := this.getElems();\n\n //add test\n var d := this.Add(3);\n var e := this.getElems();\n\n //remove test\n var f := this.Remove(4);\n var g := this.getElems();\n\n //length test\n var h := this.Length();\n }\n\n method Test3()\n {\n\n //test Map2Seq\n var m := map[2:= 2, 3:=3, 4:= 4];\n var s :seq := [2, 2, 3, 3, 3, 4, 4,4 ,4];\n\n var a := this.Map2Seq(m);\n\n var x := map[1 := 1, 2:= 1, 3:= 1];\n var y :seq := [1, 2, 3];\n\n var z := this.Map2Seq(x);\n\n }\n}\n" }, { "test_ID": "120", "test_file": "DafnyPrograms_tmp_tmp74_f9k_c_prime-database.dfy", "ground_truth": "//predicate for primeness\nghost predicate prime(n: nat)\n\n{ n > 1 && (forall nr | 1 < nr < n :: n % nr != 0) }\n\ndatatype Answer = Yes | No | Unknown\n\n//the class containing a prime database, if a number is prime it returns Yes, if it is not No and if the number\n//is not in the database it returns Unknown\nclass {:autocontracts} PrimeMap{\n\n var database: map; \n\n//the valid invariant of the class\n ghost predicate Valid()\n reads this\n {\n forall i | i in database.Keys :: (database[i] == true <==> prime(i)) \n }\n\n//the constructor\n constructor()\n ensures database == map[]\n {\n database := map[];\n }\n\n // insert an already known prime number into the database\n method InsertPrime(n: nat)\n modifies this;\n ensures database.Keys == old(database.Keys) + {n}\n requires prime(n)\n ensures database == database[n := true] \n {\n database := database[n := true];\n }\n\n // check the primeness of n and insert it accordingly into the database \n method InsertNumber(n: nat) \n modifies this\n ensures database.Keys == old(database.Keys) + {n}\n ensures prime(n) <==> database == database[n := true] \n ensures !prime(n) <==> database == database[n := false] \n {\n var prime : bool;\n prime := testPrimeness(n);\n database := database[n := prime];\n }\n\n // lookup n in the database and reply with Yes or No if it's in the database and it is or it is not prime,\n // or with Unknown when it's not in the databse\n method IsPrime?(n: nat) returns (answer: Answer) \n ensures database.Keys == old(database.Keys)\n ensures (n in database) && prime(n) <==> answer == Yes \n ensures (n in database) && !prime(n) <==> answer == No \n ensures !(n in database) <==> answer == Unknown\n {\n if !(n in database){\n return Unknown;\n } else if database[n] == true {\n return Yes;\n } else if database[n] == false {\n return No;\n }\n }\n\n // method to test whether a number is prime, returns bool\n method testPrimeness(n: nat) returns (result: bool) \n requires n >= 0\n ensures result <==> prime(n)\n {\n if n == 0 || n == 1{\n return false;\n }\n var i := 2;\n result := true;\n\n while i < n \n invariant i >= 2 && i <= n\n invariant result <==> (forall j | 1 < j <= i - 1 :: n % j != 0)\n {\n if n % i == 0 {\n result := false; \n }\n i := i + 1;\n }\n }\n}\n\nmethod testingMethod() {\n\n // witness to prove to dafny (exists nr | 1 < nr < n :: n % nr != 0), since \n // the !(forall nr | 1 < nr < n :: n % nr != 0) from !prime predicate ==> (exists nr | 1 < nr < n :: n % nr == 0)\n assert !(forall nr | 1 < nr < 15 :: 15 % nr != 0) ==> (exists nr | 1 < nr < 15 :: 15 % nr == 0);\n assert 15 % 3 == 0;\n assert(exists nr | 1 < nr < 15 :: 15 % nr == 0);\n\n var pm := new PrimeMap();\n\n // InsertPrime test\n pm.InsertPrime(13);\n // InsertNumber test\n pm.InsertNumber(17);\n pm.InsertNumber(15);\n\n assert pm.database.Keys == {17, 15, 13};\n\n var result: Answer := pm.IsPrime?(17);\n assert result == Yes;\n\n var result2: Answer := pm.IsPrime?(15);\n assert result2 == No;\n\n var result3: Answer := pm.IsPrime?(454);\n assert result3 == Unknown;\n\n var result4: Answer := pm.IsPrime?(13);\n assert result4 == Yes;\n\n}\n\n\n\n\n\n", "hints_removed": "//predicate for primeness\nghost predicate prime(n: nat)\n\n{ n > 1 && (forall nr | 1 < nr < n :: n % nr != 0) }\n\ndatatype Answer = Yes | No | Unknown\n\n//the class containing a prime database, if a number is prime it returns Yes, if it is not No and if the number\n//is not in the database it returns Unknown\nclass {:autocontracts} PrimeMap{\n\n var database: map; \n\n//the valid invariant of the class\n ghost predicate Valid()\n reads this\n {\n forall i | i in database.Keys :: (database[i] == true <==> prime(i)) \n }\n\n//the constructor\n constructor()\n ensures database == map[]\n {\n database := map[];\n }\n\n // insert an already known prime number into the database\n method InsertPrime(n: nat)\n modifies this;\n ensures database.Keys == old(database.Keys) + {n}\n requires prime(n)\n ensures database == database[n := true] \n {\n database := database[n := true];\n }\n\n // check the primeness of n and insert it accordingly into the database \n method InsertNumber(n: nat) \n modifies this\n ensures database.Keys == old(database.Keys) + {n}\n ensures prime(n) <==> database == database[n := true] \n ensures !prime(n) <==> database == database[n := false] \n {\n var prime : bool;\n prime := testPrimeness(n);\n database := database[n := prime];\n }\n\n // lookup n in the database and reply with Yes or No if it's in the database and it is or it is not prime,\n // or with Unknown when it's not in the databse\n method IsPrime?(n: nat) returns (answer: Answer) \n ensures database.Keys == old(database.Keys)\n ensures (n in database) && prime(n) <==> answer == Yes \n ensures (n in database) && !prime(n) <==> answer == No \n ensures !(n in database) <==> answer == Unknown\n {\n if !(n in database){\n return Unknown;\n } else if database[n] == true {\n return Yes;\n } else if database[n] == false {\n return No;\n }\n }\n\n // method to test whether a number is prime, returns bool\n method testPrimeness(n: nat) returns (result: bool) \n requires n >= 0\n ensures result <==> prime(n)\n {\n if n == 0 || n == 1{\n return false;\n }\n var i := 2;\n result := true;\n\n while i < n \n {\n if n % i == 0 {\n result := false; \n }\n i := i + 1;\n }\n }\n}\n\nmethod testingMethod() {\n\n // witness to prove to dafny (exists nr | 1 < nr < n :: n % nr != 0), since \n // the !(forall nr | 1 < nr < n :: n % nr != 0) from !prime predicate ==> (exists nr | 1 < nr < n :: n % nr == 0)\n\n var pm := new PrimeMap();\n\n // InsertPrime test\n pm.InsertPrime(13);\n // InsertNumber test\n pm.InsertNumber(17);\n pm.InsertNumber(15);\n\n\n var result: Answer := pm.IsPrime?(17);\n\n var result2: Answer := pm.IsPrime?(15);\n\n var result3: Answer := pm.IsPrime?(454);\n\n var result4: Answer := pm.IsPrime?(13);\n\n}\n\n\n\n\n\n" }, { "test_ID": "121", "test_file": "DafnyProjects_tmp_tmp2acw_s4s_CombNK.dfy", "ground_truth": "\n/* \n* Formal specification and verification of a dynamic programming algorithm for calculating C(n, k).\n* FEUP, MIEIC, MFES, 2020/21.\n*/\n\n// Initial recursive definition of C(n, k), based on the Pascal equality.\nfunction comb(n: nat, k: nat): nat \n requires 0 <= k <= n\n{\n if k == 0 || k == n then 1 else comb(n-1, k) + comb(n-1, k-1) \n}\nby method\n// Calculates C(n,k) iteratively in time O(k*(n-k)) and space O(n-k), \n// with dynamic programming.\n{\n var maxj := n - k;\n var c := new nat[1 + maxj];\n forall i | 0 <= i <= maxj {\n c[i] := 1;\n }\n var i := 1;\n while i <= k \n invariant 1 <= i <= k + 1\n invariant forall j :: 0 <= j <= maxj ==> c[j] == comb(j + i - 1, i - 1)\n {\n var j := 1;\n while j <= maxj\n invariant 1 <= j <= maxj + 1\n invariant forall j' :: 0 <= j' < j ==> c[j'] == comb(j' + i, i)\n invariant forall j' :: j <= j' <= maxj ==> c[j'] == comb(j' + i - 1, i - 1)\n {\n c[j] := c[j] + c[j-1];\n j := j+1;\n } \n i := i + 1;\n }\n return c[maxj];\n}\n\nlemma combProps(n: nat, k: nat)\n requires 0 <= k <= n\n ensures comb(n, k) == comb(n, n-k)\n{}\n\nmethod Main()\n{\n // Statically checked (proved) test cases! \n assert comb(5, 2) == 10;\n assert comb(5, 0) == 1;\n assert comb(5, 5) == 1;\n\n assert comb(5, 2) == 10;\n\n var res1 := comb(40, 10);\n print \"combDyn(40, 10) = \", res1, \"\\n\";\n\n}\n\nmethod testComb() {\n assert comb(6, 2) == 15;\n assert comb(6, 3) == 20;\n assert comb(6, 4) == 15;\n assert comb(6, 6) == 1;\n}\n\n\n\n", "hints_removed": "\n/* \n* Formal specification and verification of a dynamic programming algorithm for calculating C(n, k).\n* FEUP, MIEIC, MFES, 2020/21.\n*/\n\n// Initial recursive definition of C(n, k), based on the Pascal equality.\nfunction comb(n: nat, k: nat): nat \n requires 0 <= k <= n\n{\n if k == 0 || k == n then 1 else comb(n-1, k) + comb(n-1, k-1) \n}\nby method\n// Calculates C(n,k) iteratively in time O(k*(n-k)) and space O(n-k), \n// with dynamic programming.\n{\n var maxj := n - k;\n var c := new nat[1 + maxj];\n forall i | 0 <= i <= maxj {\n c[i] := 1;\n }\n var i := 1;\n while i <= k \n {\n var j := 1;\n while j <= maxj\n {\n c[j] := c[j] + c[j-1];\n j := j+1;\n } \n i := i + 1;\n }\n return c[maxj];\n}\n\nlemma combProps(n: nat, k: nat)\n requires 0 <= k <= n\n ensures comb(n, k) == comb(n, n-k)\n{}\n\nmethod Main()\n{\n // Statically checked (proved) test cases! \n\n\n var res1 := comb(40, 10);\n print \"combDyn(40, 10) = \", res1, \"\\n\";\n\n}\n\nmethod testComb() {\n}\n\n\n\n" }, { "test_ID": "122", "test_file": "DafnyProjects_tmp_tmp2acw_s4s_Graph.dfy", "ground_truth": "// Simple directed graph with vertices of any type T.\nclass {:autocontracts} Graph {\n var V: set; // vertex-set\n var E: set<(T, T)>; // edge-set\n\n // Class invariant.\n ghost predicate Valid() {\n // edges must refer to vertices that belong to the vertex-set \n // and self-loops (edges connecting a vertex to itself) are not allowed \n forall e :: e in E ==> e.0 in V && e.1 in V && e.0 != e.1\n } \n\n // Creates an empty graph.\n constructor ()\n ensures V == {} && E == {}\n {\n V:= {};\n E := {};\n }\n\n // Adds a new vertex v to this graph.\n method addVertex(v: T)\n requires v !in V\n ensures E == old(E) && V == old(V) + {v}\n {\n V := V + {v};\n }\n\n // Adds a new edge (u, v) to this graph.\n method addEdge(u: T, v: T)\n requires u in V && v in V && (u, v) !in E && u != v\n ensures V == old(V) && E == old(E) + {(u, v)} \n {\n E := E + {(u, v)};\n }\n\n // Obtains the set of vertices adjacent to a given vertex v. \n function getAdj(v: T): set\n requires v in V\n {\n set e | e in E && e.0 == v :: e.1\n } \n\n // Removes a vertex v and all the edges incident on v from the graph.\n method removeVertex(v: T)\n requires v in V\n ensures V == old(V) - {v}\n ensures E == set e | e in old(E) && e.0 != v && e.1 != v \n {\n V := V - {v};\n E := set e | e in E && e.0 != v && e.1 != v;\n }\n\n // Collapses a subset C of vertices to a single vertex v (belonging to C).\n // All vertices in C are removed from the graph, except v. \n // Edges that connect vertices in C are removed from the graph. \n // In all other edges, vertices belonging to C are replaced by v.\n method collapseVertices(C: set, v: T)\n requires v in C && C <= V \n ensures V == old(V) - C + {v}\n ensures E == set e | e in old(E) && (e.0 !in C || e.1 !in C) ::\n (if e.0 in C then v else e.0, if e.1 in C then v else e.1)\n {\n V := V - C + {v};\n E := set e | e in E && (e.0 !in C || e.1 !in C) ::\n (if e.0 in C then v else e.0, if e.1 in C then v else e.1);\n } \n}\n\nmethod testGraph() {\n var G := new Graph();\n assert G.E == {} && G.V == {};\n\n G.addVertex(1);\n G.addVertex(2);\n G.addVertex(3);\n G.addVertex(4);\n assert G.V == {1, 2, 3, 4};\n\n G.addEdge(1, 2);\n G.addEdge(1, 3);\n G.addEdge(2, 3);\n G.addEdge(4, 1);\n assert G.E == {(1, 2), (1, 3), (2, 3), (4, 1)};\n\n assert G.getAdj(1) == {2, 3};\n\n G.collapseVertices({1, 2, 3}, 3);\n assert G.V == {3, 4} && G.E == {(4, 3)};\n}\n\n", "hints_removed": "// Simple directed graph with vertices of any type T.\nclass {:autocontracts} Graph {\n var V: set; // vertex-set\n var E: set<(T, T)>; // edge-set\n\n // Class invariant.\n ghost predicate Valid() {\n // edges must refer to vertices that belong to the vertex-set \n // and self-loops (edges connecting a vertex to itself) are not allowed \n forall e :: e in E ==> e.0 in V && e.1 in V && e.0 != e.1\n } \n\n // Creates an empty graph.\n constructor ()\n ensures V == {} && E == {}\n {\n V:= {};\n E := {};\n }\n\n // Adds a new vertex v to this graph.\n method addVertex(v: T)\n requires v !in V\n ensures E == old(E) && V == old(V) + {v}\n {\n V := V + {v};\n }\n\n // Adds a new edge (u, v) to this graph.\n method addEdge(u: T, v: T)\n requires u in V && v in V && (u, v) !in E && u != v\n ensures V == old(V) && E == old(E) + {(u, v)} \n {\n E := E + {(u, v)};\n }\n\n // Obtains the set of vertices adjacent to a given vertex v. \n function getAdj(v: T): set\n requires v in V\n {\n set e | e in E && e.0 == v :: e.1\n } \n\n // Removes a vertex v and all the edges incident on v from the graph.\n method removeVertex(v: T)\n requires v in V\n ensures V == old(V) - {v}\n ensures E == set e | e in old(E) && e.0 != v && e.1 != v \n {\n V := V - {v};\n E := set e | e in E && e.0 != v && e.1 != v;\n }\n\n // Collapses a subset C of vertices to a single vertex v (belonging to C).\n // All vertices in C are removed from the graph, except v. \n // Edges that connect vertices in C are removed from the graph. \n // In all other edges, vertices belonging to C are replaced by v.\n method collapseVertices(C: set, v: T)\n requires v in C && C <= V \n ensures V == old(V) - C + {v}\n ensures E == set e | e in old(E) && (e.0 !in C || e.1 !in C) ::\n (if e.0 in C then v else e.0, if e.1 in C then v else e.1)\n {\n V := V - C + {v};\n E := set e | e in E && (e.0 !in C || e.1 !in C) ::\n (if e.0 in C then v else e.0, if e.1 in C then v else e.1);\n } \n}\n\nmethod testGraph() {\n var G := new Graph();\n\n G.addVertex(1);\n G.addVertex(2);\n G.addVertex(3);\n G.addVertex(4);\n\n G.addEdge(1, 2);\n G.addEdge(1, 3);\n G.addEdge(2, 3);\n G.addEdge(4, 1);\n\n\n G.collapseVertices({1, 2, 3}, 3);\n}\n\n" }, { "test_ID": "123", "test_file": "DafnyProjects_tmp_tmp2acw_s4s_Power.dfy", "ground_truth": "/* \n* Formal verification of an O(log n) algorithm to calculate the natural power of a real number (x^n), \n* illustrating the usage of lemmas and automatic induction in Dafny.\n* J. Pascoal Faria, FEUP, Jan/2022.\n*/\n\n// Recursive definition of x^n in functional style, with time and space complexity O(n).\nfunction power(x: real, n: nat) : real {\n if n == 0 then 1.0 else x * power(x, n-1)\n}\n\n// Computation of x^n in time and space O(log n).\nmethod powerDC(x: real, n: nat) returns (p : real)\n ensures p == power(x, n)\n{\n if n == 0 {\n return 1.0;\n }\n else if n == 1 {\n return x;\n }\n else if n % 2 == 0 {\n productOfPowers(x, n/2, n/2); // recall lemma\n var temp := powerDC(x, n/2);\n return temp * temp;\n }\n else {\n productOfPowers(x, (n-1)/2, (n-1)/2); // recall lemma \n var temp := powerDC(x, (n-1)/2);\n return temp * temp * x;\n } \n}\n\n// States the property x^a * x^b = x^(a+b), that the method power takes advantage of. \n// The property is proved by automatic induction on 'a'.\nlemma {:induction a} productOfPowers(x: real, a: nat, b: nat) \n ensures power(x, a) * power(x, b) == power(x, a + b) \n{ }\n\n\n// A few test cases (checked statically by Dafny).\nmethod testPowerDC() {\n var p1 := powerDC( 2.0, 5); assert p1 == 32.0;\n var p2 := powerDC(-2.0, 2); assert p2 == 4.0;\n var p3 := powerDC(-2.0, 1); assert p3 == -2.0;\n var p4 := powerDC(-2.0, 0); assert p4 == 1.0;\n var p5 := powerDC( 0.0, 0); assert p5 == 1.0;\n}\n", "hints_removed": "/* \n* Formal verification of an O(log n) algorithm to calculate the natural power of a real number (x^n), \n* illustrating the usage of lemmas and automatic induction in Dafny.\n* J. Pascoal Faria, FEUP, Jan/2022.\n*/\n\n// Recursive definition of x^n in functional style, with time and space complexity O(n).\nfunction power(x: real, n: nat) : real {\n if n == 0 then 1.0 else x * power(x, n-1)\n}\n\n// Computation of x^n in time and space O(log n).\nmethod powerDC(x: real, n: nat) returns (p : real)\n ensures p == power(x, n)\n{\n if n == 0 {\n return 1.0;\n }\n else if n == 1 {\n return x;\n }\n else if n % 2 == 0 {\n productOfPowers(x, n/2, n/2); // recall lemma\n var temp := powerDC(x, n/2);\n return temp * temp;\n }\n else {\n productOfPowers(x, (n-1)/2, (n-1)/2); // recall lemma \n var temp := powerDC(x, (n-1)/2);\n return temp * temp * x;\n } \n}\n\n// States the property x^a * x^b = x^(a+b), that the method power takes advantage of. \n// The property is proved by automatic induction on 'a'.\nlemma {:induction a} productOfPowers(x: real, a: nat, b: nat) \n ensures power(x, a) * power(x, b) == power(x, a + b) \n{ }\n\n\n// A few test cases (checked statically by Dafny).\nmethod testPowerDC() {\n var p1 := powerDC( 2.0, 5); assert p1 == 32.0;\n var p2 := powerDC(-2.0, 2); assert p2 == 4.0;\n var p3 := powerDC(-2.0, 1); assert p3 == -2.0;\n var p4 := powerDC(-2.0, 0); assert p4 == 1.0;\n var p5 := powerDC( 0.0, 0); assert p5 == 1.0;\n}\n" }, { "test_ID": "124", "test_file": "DafnyProjects_tmp_tmp2acw_s4s_RawSort.dfy", "ground_truth": "/**\n * Proves the correctness of a \"raw\" array sorting algorithm that swaps elements out of order, chosen randomly.\n * FEUP, MFES, 2020/21.\n */\n\n// Type of each array element; can be any type supporting comparision operators.\ntype T = int \n\n// Checks if array 'a' is sorted by non-descending order.\nghost predicate sorted(a: array)\n reads a\n{ forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j] }\n\n// Obtains the set of all inversions in an array 'a', i.e., \n// the pairs of indices i, j such that i < j and a[i] > a[j]. \nghost function inversions(a: array): set<(nat, nat)>\n reads a\n{ set i, j | 0 <= i < j < a.Length && a[i] > a[j] :: (i, j) }\n\n// Sorts an array by simply swapping elements out of order, chosen randomly.\nmethod rawsort(a: array)\n modifies a\n ensures sorted(a) && multiset(a[..]) == multiset(old(a[..]))\n decreases |inversions(a)|\n{\n if i, j :| 0 <= i < j < a.Length && a[i] > a[j] {\n ghost var bef := inversions(a); // inversions before swapping\n a[i], a[j] := a[j], a[i]; // swap\n ghost var aft := inversions(a); // inversions after swapping \n ghost var aft2bef := map p | p in aft :: // maps inversions in 'aft' to 'bef'\n (if p.0 == i && p.1 > j then j else if p.0 == j then i else p.0,\n if p.1 == i then j else if p.1 == j && p.0 < i then i else p.1); \n mappingProp(aft, bef, (i, j), aft2bef); // recall property implying |aft| < |bef|\n rawsort(a); // proceed recursivelly\n }\n}\n\n// States and proves (by induction) the following property: given sets 'a' and 'b' and an injective\n// and non-surjective mapping 'm' from elements in 'a' to elements in 'b', then |a| < |b|.\n// To facilitate the proof, it is given an element 'k' in 'b' that is not an image of elements in 'a'. \nlemma mappingProp(a: set, b: set, k: T2, m: map)\n requires k in b\n requires forall x :: x in a ==> x in m && m[x] in b - {k} \n requires forall x, y :: x in a && y in a && x != y ==> m[x] != m[y] \n ensures |a| < |b|\n{\n if x :| x in a {\n mappingProp(a - {x}, b - {m[x]}, k, m);\n }\n}\n\nmethod testRawsort() {\n var a : array := new T[] [3, 5, 1]; \n assert a[..] == [3, 5, 1];\n rawsort(a);\n assert a[..] == [1, 3, 5];\n}\n\n", "hints_removed": "/**\n * Proves the correctness of a \"raw\" array sorting algorithm that swaps elements out of order, chosen randomly.\n * FEUP, MFES, 2020/21.\n */\n\n// Type of each array element; can be any type supporting comparision operators.\ntype T = int \n\n// Checks if array 'a' is sorted by non-descending order.\nghost predicate sorted(a: array)\n reads a\n{ forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j] }\n\n// Obtains the set of all inversions in an array 'a', i.e., \n// the pairs of indices i, j such that i < j and a[i] > a[j]. \nghost function inversions(a: array): set<(nat, nat)>\n reads a\n{ set i, j | 0 <= i < j < a.Length && a[i] > a[j] :: (i, j) }\n\n// Sorts an array by simply swapping elements out of order, chosen randomly.\nmethod rawsort(a: array)\n modifies a\n ensures sorted(a) && multiset(a[..]) == multiset(old(a[..]))\n{\n if i, j :| 0 <= i < j < a.Length && a[i] > a[j] {\n ghost var bef := inversions(a); // inversions before swapping\n a[i], a[j] := a[j], a[i]; // swap\n ghost var aft := inversions(a); // inversions after swapping \n ghost var aft2bef := map p | p in aft :: // maps inversions in 'aft' to 'bef'\n (if p.0 == i && p.1 > j then j else if p.0 == j then i else p.0,\n if p.1 == i then j else if p.1 == j && p.0 < i then i else p.1); \n mappingProp(aft, bef, (i, j), aft2bef); // recall property implying |aft| < |bef|\n rawsort(a); // proceed recursivelly\n }\n}\n\n// States and proves (by induction) the following property: given sets 'a' and 'b' and an injective\n// and non-surjective mapping 'm' from elements in 'a' to elements in 'b', then |a| < |b|.\n// To facilitate the proof, it is given an element 'k' in 'b' that is not an image of elements in 'a'. \nlemma mappingProp(a: set, b: set, k: T2, m: map)\n requires k in b\n requires forall x :: x in a ==> x in m && m[x] in b - {k} \n requires forall x, y :: x in a && y in a && x != y ==> m[x] != m[y] \n ensures |a| < |b|\n{\n if x :| x in a {\n mappingProp(a - {x}, b - {m[x]}, k, m);\n }\n}\n\nmethod testRawsort() {\n var a : array := new T[] [3, 5, 1]; \n rawsort(a);\n}\n\n" }, { "test_ID": "125", "test_file": "DafnyProjects_tmp_tmp2acw_s4s_findMax.dfy", "ground_truth": "/* \n* Formal verification of a simple algorithm to find the maximum value in an array.\n* FEUP, MIEIC, MFES, 2020/21.\n*/\n\n// Finds the maximum value in a non-empty array.\nmethod findMax(a: array) returns (max: real)\n requires a.Length > 0\n ensures exists k :: 0 <= k < a.Length && max == a[k]\n ensures forall k :: 0 <= k < a.Length ==> max >= a[k]\n{\n max := a[0];\n for i := 1 to a.Length\n invariant exists k :: 0 <= k < i && max == a[k]\n invariant forall k :: 0 <= k < i ==> max >= a[k]\n {\n if (a[i] > max) {\n max := a[i];\n }\n } \n}\n\n\n// Test cases checked statically.\nmethod testFindMax() {\n var a1 := new real[3] [1.0, 2.0, 3.0]; // sorted asc\n var m1 := findMax(a1);\n assert m1 == a1[2] == 3.0;\n\n var a2 := new real[3] [3.0, 2.0, 1.0]; // sorted desc\n var m2 := findMax(a2);\n assert m2 == a2[0] == 3.0;\n\n var a3 := new real[3] [2.0, 3.0, 1.0]; // unsorted\n var m3 := findMax(a3);\n assert m3 == a3[1] == 3.0;\n\n var a4 := new real[3] [1.0, 2.0, 2.0]; // duplicates\n var m4 := findMax(a4);\n assert m4 == a4[1] == 2.0;\n\n var a5 := new real[1] [1.0]; // single element\n var m5 := findMax(a5);\n assert m5 == a5[0] == 1.0;\n\n var a6 := new real[3] [1.0, 1.0, 1.0]; // all equal\n var m6 := findMax(a6);\n assert m6 == a6[0] == 1.0;\n \n}\n\n\n", "hints_removed": "/* \n* Formal verification of a simple algorithm to find the maximum value in an array.\n* FEUP, MIEIC, MFES, 2020/21.\n*/\n\n// Finds the maximum value in a non-empty array.\nmethod findMax(a: array) returns (max: real)\n requires a.Length > 0\n ensures exists k :: 0 <= k < a.Length && max == a[k]\n ensures forall k :: 0 <= k < a.Length ==> max >= a[k]\n{\n max := a[0];\n for i := 1 to a.Length\n {\n if (a[i] > max) {\n max := a[i];\n }\n } \n}\n\n\n// Test cases checked statically.\nmethod testFindMax() {\n var a1 := new real[3] [1.0, 2.0, 3.0]; // sorted asc\n var m1 := findMax(a1);\n\n var a2 := new real[3] [3.0, 2.0, 1.0]; // sorted desc\n var m2 := findMax(a2);\n\n var a3 := new real[3] [2.0, 3.0, 1.0]; // unsorted\n var m3 := findMax(a3);\n\n var a4 := new real[3] [1.0, 2.0, 2.0]; // duplicates\n var m4 := findMax(a4);\n\n var a5 := new real[1] [1.0]; // single element\n var m5 := findMax(a5);\n\n var a6 := new real[3] [1.0, 1.0, 1.0]; // all equal\n var m6 := findMax(a6);\n \n}\n\n\n" }, { "test_ID": "126", "test_file": "DafnyProjects_tmp_tmp2acw_s4s_longestPrefix.dfy", "ground_truth": "// MFES, Exam 8/Sept/20201, Exercise 5 \n\n// Computes the length (i) of the longest common prefix (initial subarray) \n// of two arrays a and b. \nmethod longestPrefix(a: array, b: array ) returns (i: nat) \n ensures i <= a.Length && i <= b.Length\n ensures a[..i] == b[..i]\n ensures i < a.Length && i < b.Length ==> a[i] != b[i]\n{\n i := 0;\n while i < a.Length && i < b.Length && a[i] == b[i]\n invariant i <= a.Length && i <= b.Length\n invariant a[..i] == b[..i]\n {\n i := i + 1;\n }\n}\n \n// Test method with an example.\nmethod testLongestPrefix() {\n var a := new int[] [1, 3, 2, 4, 8];\n var b := new int[] [1, 3, 3, 4];\n var i := longestPrefix(a, b);\n assert a[2] != b[2]; // to help Dafny prove next assertion \n assert i == 2; \n}\n\n", "hints_removed": "// MFES, Exam 8/Sept/20201, Exercise 5 \n\n// Computes the length (i) of the longest common prefix (initial subarray) \n// of two arrays a and b. \nmethod longestPrefix(a: array, b: array ) returns (i: nat) \n ensures i <= a.Length && i <= b.Length\n ensures a[..i] == b[..i]\n ensures i < a.Length && i < b.Length ==> a[i] != b[i]\n{\n i := 0;\n while i < a.Length && i < b.Length && a[i] == b[i]\n {\n i := i + 1;\n }\n}\n \n// Test method with an example.\nmethod testLongestPrefix() {\n var a := new int[] [1, 3, 2, 4, 8];\n var b := new int[] [1, 3, 3, 4];\n var i := longestPrefix(a, b);\n}\n\n" }, { "test_ID": "127", "test_file": "DafnyProjects_tmp_tmp2acw_s4s_partitionOddEven.dfy", "ground_truth": "// Rearranges the elements in an array 'a' of natural numbers,\n// so that all odd numbers appear before all even numbers.\nmethod partitionOddEven(a: array) \n modifies a\n ensures multiset(a[..]) == multiset(old(a[..]))\n ensures ! exists i, j :: 0 <= i < j < a.Length && even(a[i]) && odd(a[j]) \n{\n var i := 0; // odd numbers are placed to the left of i\n var j := a.Length - 1; // even numbers are placed to the right of j\n while i <= j\n invariant 0 <= i <= j + 1 <= a.Length\n invariant multiset(a[..]) == old(multiset(a[..]))\n invariant forall k :: 0 <= k < i ==> odd(a[k])\n invariant forall k :: j < k < a.Length ==> even(a[k])\n {\n if even(a[i]) && odd(a[j]) { a[i], a[j] := a[j], a[i]; }\n if odd(a[i]) { i := i + 1; }\n if even(a[j]) { j := j - 1; }\n }\n}\n \npredicate odd(n: nat) { n % 2 == 1 }\npredicate even(n: nat) { n % 2 == 0 }\n\nmethod testPartitionOddEven() {\n var a: array := new [] [1, 2, 3];\n assert a[..] == [1, 2, 3];\n partitionOddEven(a);\n assert a[..] == [1, 3, 2] || a[..] == [3, 1, 2];\n}\n\n", "hints_removed": "// Rearranges the elements in an array 'a' of natural numbers,\n// so that all odd numbers appear before all even numbers.\nmethod partitionOddEven(a: array) \n modifies a\n ensures multiset(a[..]) == multiset(old(a[..]))\n ensures ! exists i, j :: 0 <= i < j < a.Length && even(a[i]) && odd(a[j]) \n{\n var i := 0; // odd numbers are placed to the left of i\n var j := a.Length - 1; // even numbers are placed to the right of j\n while i <= j\n {\n if even(a[i]) && odd(a[j]) { a[i], a[j] := a[j], a[i]; }\n if odd(a[i]) { i := i + 1; }\n if even(a[j]) { j := j - 1; }\n }\n}\n \npredicate odd(n: nat) { n % 2 == 1 }\npredicate even(n: nat) { n % 2 == 0 }\n\nmethod testPartitionOddEven() {\n var a: array := new [] [1, 2, 3];\n partitionOddEven(a);\n}\n\n" }, { "test_ID": "128", "test_file": "DafnyProjects_tmp_tmp2acw_s4s_sqrt.dfy", "ground_truth": "\nmethod sqrt(x: real) returns (r: real)\n requires x >= 0.0\n ensures r * r == x && r >= 0.0\n\nmethod testSqrt() {\n var r := sqrt(4.0);\n //if (2.0 < r) { monotonicSquare(2.0, r); }\n if (r < 2.0) { monotonicSquare(r, 2.0); }\n assert r == 2.0;\n}\n\nlemma monotonicMult(c: real, x: real, y: real)\n requires x < y && c > 0.0\n ensures c * x < c * y\n{}\n\n\nlemma monotonicSquare(x: real, y: real)\n requires 0.0 < x < y\n ensures 0.0 < x * x < y * y\n{\n monotonicMult(x, x, y);\n}\n\n\n\n", "hints_removed": "\nmethod sqrt(x: real) returns (r: real)\n requires x >= 0.0\n ensures r * r == x && r >= 0.0\n\nmethod testSqrt() {\n var r := sqrt(4.0);\n //if (2.0 < r) { monotonicSquare(2.0, r); }\n if (r < 2.0) { monotonicSquare(r, 2.0); }\n}\n\nlemma monotonicMult(c: real, x: real, y: real)\n requires x < y && c > 0.0\n ensures c * x < c * y\n{}\n\n\nlemma monotonicSquare(x: real, y: real)\n requires 0.0 < x < y\n ensures 0.0 < x * x < y * y\n{\n monotonicMult(x, x, y);\n}\n\n\n\n" }, { "test_ID": "129", "test_file": "Dafny_Learning_Experience_tmp_tmpuxvcet_u_week1_7_A2_Q1_trimmed copy - \u526f\u672c.dfy", "ground_truth": "ghost function Count(hi: nat, s:seq): int\n requires 0 <= hi <= |s|\n decreases hi\n{\n if hi == 0 then 0\n else if s[hi-1]%2 == 0 then 1 + Count(hi-1, s) else Count(hi-1, s)\n}\n\nmethod FooCount(CountIndex:nat, a:seq,b:array) returns (p:nat)\n requires CountIndex == 0 || (|a| == b.Length && 1 <= CountIndex <= |a|)\n decreases CountIndex\n modifies b\n ensures p == Count(CountIndex,a)\n{\n assert CountIndex == 0 || (|a| == b.Length && 1<=CountIndex <= |a|);\n assert CountIndex == 0 || (|a| == b.Length && 0<=CountIndex -1 <= |a|);\n assert CountIndex!=0 ==> |a| == b.Length && 0<=CountIndex -1 <= |a|;\n assert CountIndex == 0 ==> true && CountIndex != 0 ==> |a| == b.Length && 0<=CountIndex -1 <= |a|;\n if CountIndex == 0{\n assert true;\n assert 0 == 0;\n assert 0 == Count(0,a);\n p :=0;\n assert p == Count(CountIndex,a);\n } else{\n assert |a| == b.Length && 0<=CountIndex-1 <=|a|;\n assert (a[CountIndex-1]%2 ==0 ==>|a| == b.Length && 0<= CountIndex -1 <|a| && 1+ Count(CountIndex-1,a) == Count(CountIndex,a)) && \n (a[CountIndex-1]%2 !=0 ==> |a| == b.Length && 0<= CountIndex -1 <|a| && Count(CountIndex-1,a) == Count(CountIndex,a));\n if a[CountIndex-1]%2==0{\n assert |a| == b.Length && 0<= CountIndex -1 <|a| && 1+ Count(CountIndex-1,a) == Count(CountIndex,a);\n var d := FooCount(CountIndex -1,a,b);\n assert d+1 == Count(CountIndex,a);\n p:= d+1;\n assert p == Count(CountIndex,a);\n }else{\n assert |a| == b.Length && 0<= CountIndex -1 <|a| && Count(CountIndex-1,a) == Count(CountIndex,a);\n assert |a| == b.Length && 0<= CountIndex -1 <|a| && forall p'::p' ==Count(CountIndex-1,a) ==> p'==Count(CountIndex,a);\n var d:= FooCount(CountIndex -1,a,b);\n assert d == Count(CountIndex,a);\n p:= d;\n assert p == Count(CountIndex,a);\n }\n b[CountIndex-1] := p;\n assert p == Count(CountIndex,a);\n \n }\n}\n\nmethod FooPreCompute(a:array,b:array)\n requires a.Length == b.Length\n modifies b\n{\n var CountIndex := 1;\n while CountIndex != a.Length + 1\n decreases a.Length + 1 - CountIndex\n invariant 1 <= CountIndex <= a.Length +1;\n \n { \n assert (CountIndex == 0 || (a.Length == b.Length && 1 <= CountIndex <= a.Length)) && forall a'::a' ==Count(CountIndex,a[..]) ==> a' ==Count(CountIndex,a[..]);\n var p := FooCount(CountIndex,a[..],b);\n assert 1<= CountIndex <= a.Length;\n assert 1 <= CountIndex + 1<= a.Length +1;\n CountIndex := CountIndex +1;\n assert 1 <= CountIndex <= a.Length +1;\n }\n}\n\n\nmethod ComputeCount(CountIndex:nat, a:seq,b:array) returns (p:nat)\n requires CountIndex == 0 || (|a| == b.Length && 1 <= CountIndex <= |a|)\n decreases CountIndex\n modifies b\n ensures p == Count(CountIndex,a)\n{\n if CountIndex == 0{\n p :=0;\n } else{\n if a[CountIndex-1]%2==0{\n var d := ComputeCount(CountIndex -1,a,b);\n p:= d+1;\n }else{\n var d:= ComputeCount(CountIndex -1,a,b);\n p:= d;\n }\n b[CountIndex-1] := p; \n }\n}\n\nmethod PreCompute(a:array,b:array)returns(p:nat)\n requires a.Length == b.Length \n modifies b\n ensures (b.Length == 0 || (a.Length == b.Length && 1 <= b.Length <= a.Length)) &&\n forall p::p == Count(b.Length,a[..]) ==> p==Count(b.Length,a[..])\n\n{\n \n assert (b.Length == 0 || (a.Length == b.Length && 1 <= b.Length <= a.Length)) \n && (forall p::p == Count(b.Length,a[..]) ==> p==Count(b.Length,a[..]) );\n p := ComputeCount(b.Length,a[..],b);\n \n}\n\nmethod Evens(a:array) returns (c:array2)\n\n // modifies c\n // ensures invariant forall i,j:: 0 <=i j c[i,j] == 0\n{ \n c := new int[a.Length,a.Length];\n var b := new int[a.Length];\n var foo := PreCompute(a,b); \n var m := 0;\n while m != a.Length\n decreases a.Length - m\n modifies c\n invariant 0 <= m <= a.Length\n invariant forall i,j:: 0 <=i j c[i,j] == 0\n invariant forall i,j:: 0 <=i j>=i ==> i>0 ==> c[i,j] == b[j] - b[i-1]\n invariant forall i,j:: 0 <=i j>=i ==> i == 0 ==> c[i,j] == b[j]\n { \n var n := 0;\n while n != a.Length\n decreases a.Length - n\n modifies c\n invariant 0 <= n <= a.Length\n invariant forall i,j:: 0 <=i j c[i,j] == 0\n invariant forall j:: 0 <= j j < m ==> c[m,j] == 0\n invariant forall i,j:: 0 <=i j>=i ==> i>0 ==> c[i,j] == b[j] - b[i-1]\n invariant forall j:: 0 <= j j>=m ==> m>0 ==> c[m,j] == b[j] - b[m-1]\n invariant forall i,j:: 0 <=i j>=i ==> i == 0 ==> c[i,j] == b[j]\n invariant forall j:: 0 <= j j>=m ==> m==0 ==> c[m,j] == b[j]\n { \n if (n < m) {\n c[m,n] := 0;\n }else { \n if m > 0 {\n c[m,n] := b[n] - b[m-1];\n }else{\n c[m,n] := b[n];\n }\n }\n n := n + 1;\n }\n m := m + 1;\n }\n}\n\nmethod Mult(x:int, y:int) returns (r:int)\n requires x>= 0 && y>=0\n decreases x\n ensures r == x*y\n{\n if x==0 {\n r:=0;\n }else{\n assert x-1>= 0 && y>= 0&& (x-1)*y + y== x*y;\n var z:= Mult(x-1,y);\n assert z+y == x*y;\n r:=z+y;\n assert r == x*y;\n }\n}\n\n\n\n \n \n", "hints_removed": "ghost function Count(hi: nat, s:seq): int\n requires 0 <= hi <= |s|\n{\n if hi == 0 then 0\n else if s[hi-1]%2 == 0 then 1 + Count(hi-1, s) else Count(hi-1, s)\n}\n\nmethod FooCount(CountIndex:nat, a:seq,b:array) returns (p:nat)\n requires CountIndex == 0 || (|a| == b.Length && 1 <= CountIndex <= |a|)\n modifies b\n ensures p == Count(CountIndex,a)\n{\n if CountIndex == 0{\n p :=0;\n } else{\n (a[CountIndex-1]%2 !=0 ==> |a| == b.Length && 0<= CountIndex -1 <|a| && Count(CountIndex-1,a) == Count(CountIndex,a));\n if a[CountIndex-1]%2==0{\n var d := FooCount(CountIndex -1,a,b);\n p:= d+1;\n }else{\n var d:= FooCount(CountIndex -1,a,b);\n p:= d;\n }\n b[CountIndex-1] := p;\n \n }\n}\n\nmethod FooPreCompute(a:array,b:array)\n requires a.Length == b.Length\n modifies b\n{\n var CountIndex := 1;\n while CountIndex != a.Length + 1\n \n { \n var p := FooCount(CountIndex,a[..],b);\n CountIndex := CountIndex +1;\n }\n}\n\n\nmethod ComputeCount(CountIndex:nat, a:seq,b:array) returns (p:nat)\n requires CountIndex == 0 || (|a| == b.Length && 1 <= CountIndex <= |a|)\n modifies b\n ensures p == Count(CountIndex,a)\n{\n if CountIndex == 0{\n p :=0;\n } else{\n if a[CountIndex-1]%2==0{\n var d := ComputeCount(CountIndex -1,a,b);\n p:= d+1;\n }else{\n var d:= ComputeCount(CountIndex -1,a,b);\n p:= d;\n }\n b[CountIndex-1] := p; \n }\n}\n\nmethod PreCompute(a:array,b:array)returns(p:nat)\n requires a.Length == b.Length \n modifies b\n ensures (b.Length == 0 || (a.Length == b.Length && 1 <= b.Length <= a.Length)) &&\n forall p::p == Count(b.Length,a[..]) ==> p==Count(b.Length,a[..])\n\n{\n \n && (forall p::p == Count(b.Length,a[..]) ==> p==Count(b.Length,a[..]) );\n p := ComputeCount(b.Length,a[..],b);\n \n}\n\nmethod Evens(a:array) returns (c:array2)\n\n // modifies c\n // ensures invariant forall i,j:: 0 <=i j c[i,j] == 0\n{ \n c := new int[a.Length,a.Length];\n var b := new int[a.Length];\n var foo := PreCompute(a,b); \n var m := 0;\n while m != a.Length\n modifies c\n { \n var n := 0;\n while n != a.Length\n modifies c\n { \n if (n < m) {\n c[m,n] := 0;\n }else { \n if m > 0 {\n c[m,n] := b[n] - b[m-1];\n }else{\n c[m,n] := b[n];\n }\n }\n n := n + 1;\n }\n m := m + 1;\n }\n}\n\nmethod Mult(x:int, y:int) returns (r:int)\n requires x>= 0 && y>=0\n ensures r == x*y\n{\n if x==0 {\n r:=0;\n }else{\n var z:= Mult(x-1,y);\n r:=z+y;\n }\n}\n\n\n\n \n \n" }, { "test_ID": "130", "test_file": "Dafny_Learning_Experience_tmp_tmpuxvcet_u_week1_7_MaxSum.dfy", "ground_truth": "method MaxSum(x:int, y:int) returns (s:int, m:int)\n ensures s == x+y\n ensures (m == x || m == y) && x <= m && y <= m\n{\n s := x+y;\n if x > y{\n m := x;\n } else if y > x{\n m := y;\n } else {\n m := x;\n }\n assert m >= y;\n}\n\nmethod Main() \n{\n var m, n := 4,5;\n var a,b := MaxSum(m,n);\n print \"Search return a is \", a,\",,,,, b is \", b, \"\\n\";\n\n}\n", "hints_removed": "method MaxSum(x:int, y:int) returns (s:int, m:int)\n ensures s == x+y\n ensures (m == x || m == y) && x <= m && y <= m\n{\n s := x+y;\n if x > y{\n m := x;\n } else if y > x{\n m := y;\n } else {\n m := x;\n }\n}\n\nmethod Main() \n{\n var m, n := 4,5;\n var a,b := MaxSum(m,n);\n print \"Search return a is \", a,\",,,,, b is \", b, \"\\n\";\n\n}\n" }, { "test_ID": "131", "test_file": "Dafny_Learning_Experience_tmp_tmpuxvcet_u_week1_7_Week4__LinearSearch.dfy", "ground_truth": "method LinearSeach0(a: array, P: T -> bool) returns (n: int)\n ensures 0 <= n <= a.Length\n ensures n == a.Length || P(a[n])\n{\n n := 0;\n while n != a.Length\n invariant 0 <= n <= a.Length\n {\n if P(a[n]) {return;}\n n := n + 1;\n }\n}\n\npredicate P(n: int) {\n n % 2 == 0\n}\n\nmethod TestLinearSearch() {\n /* var a := new int[3][44,2,56];\n var n := LinearSeach0(a,P);\n assert n == 1 || n == 2 || n == 3 || n == 0;\n */\n var a := new int[3][1,2,3];\n var n := LinearSeach1(a,P);\n assert n == 1 || n == 2 || n==3 || n == 0;\n}\n\nmethod LinearSeach1(a: array, P: T -> bool) returns (n: int)\n ensures 0 <= n <= a.Length\n ensures n == a.Length || P(a[n])\n ensures n == a.Length ==> forall i :: 0 <= i < a.Length ==> !P(a[i])\n{\n n := 0;\n while n != a.Length\n invariant 0 <= n <= a.Length\n invariant forall i :: 0<=i !P(a[i])\n\n {\n if P(a[n]) {return;}\n n := n + 1;\n }\n}\n", "hints_removed": "method LinearSeach0(a: array, P: T -> bool) returns (n: int)\n ensures 0 <= n <= a.Length\n ensures n == a.Length || P(a[n])\n{\n n := 0;\n while n != a.Length\n {\n if P(a[n]) {return;}\n n := n + 1;\n }\n}\n\npredicate P(n: int) {\n n % 2 == 0\n}\n\nmethod TestLinearSearch() {\n /* var a := new int[3][44,2,56];\n var n := LinearSeach0(a,P);\n */\n var a := new int[3][1,2,3];\n var n := LinearSeach1(a,P);\n}\n\nmethod LinearSeach1(a: array, P: T -> bool) returns (n: int)\n ensures 0 <= n <= a.Length\n ensures n == a.Length || P(a[n])\n ensures n == a.Length ==> forall i :: 0 <= i < a.Length ==> !P(a[i])\n{\n n := 0;\n while n != a.Length\n\n {\n if P(a[n]) {return;}\n n := n + 1;\n }\n}\n" }, { "test_ID": "132", "test_file": "Dafny_Learning_Experience_tmp_tmpuxvcet_u_week1_7_week4_tute_ex4.dfy", "ground_truth": "method LinearSearch(a: array, P: T -> bool) returns (n: int)\n ensures -1 <= n < a.Length\n ensures n == -1 || P(a[n])\n ensures n != -1 ==> forall i :: 0 <= i < n ==> ! P(a[i])\n ensures n == -1 ==> forall i :: 0 <= i < a.Length ==> ! P(a[i])\n{\n n := 0;\n\n while n != a.Length\n decreases a.Length - n\n invariant 0 <= n <= a.Length\n invariant forall i :: 0 <= i < n ==> ! P(a[i])\n invariant n == -1 ==> forall i :: 0 <= i < n ==> ! P(a[i])\n {\n if P(a[n]) {\n return; }\n n := n + 1;\n }\n n := -1;\n\n}\n\nmethod LinearSearch1(a: array, P: T -> bool, s1:seq) returns (n: int)\n requires |s1| <= a.Length\n requires forall i:: 0<= i <|s1| ==> s1[i] == a[i]\n ensures -1 <= n < a.Length\n ensures n == -1 || P(a[n])\n ensures n != -1 ==> forall i :: 0 <= i < n ==> ! P(a[i])\n ensures n == -1 ==> forall i :: 0 <= i < |s1| ==> ! P(a[i])\n{\n n := 0;\n\n while n != |s1|\n decreases |s1| - n\n invariant 0 <= n <= |s1|\n invariant forall i :: 0 <= i < n ==> ! P(a[i])\n invariant n == -1 ==> forall i :: 0 <= i < n ==> ! P(a[i])\n {\n if P(a[n]) {\n return; }\n n := n + 1;\n }\n n := -1;\n\n}\n\n\nmethod LinearSearch2(data: array, Element:T, s1:seq) returns (position:int)\n requires |s1| <= data.Length\n requires forall i:: 0<= i <|s1| ==> s1[i] == data[i]\n ensures position == -1 || position >= 1\n ensures position >= 1 ==> exists i::0 <=i < |s1| && s1[i] == Element\n ensures position == -1 ==> forall i :: 0 <= i < |s1| ==> s1[i] != Element\n{\n var n := 0;\n position := 0;\n while n != |s1|\n decreases |s1| - n\n invariant 0 <= n <= |s1|\n invariant position >= 1 ==> exists i::0 <=i < |s1| && data[i] == Element\n invariant forall i :: |s1|-1-n < i < |s1|==> data[i] != Element\n {\n if data[|s1|-1-n] == Element \n {\n position := n + 1;\n return position; \n }\n n := n + 1;\n }\n position := -1;\n}\n\nmethod LinearSearch3(data: array, Element:T, s1:seq) returns (position:int)\n requires |s1| <= data.Length\n requires forall i:: 0<= i <|s1| ==> s1[i] == data[data.Length -1-i]\n ensures position == -1 || position >= 1\n ensures position >= 1 ==> exists i::0 <=i < |s1| && s1[i] == Element && |s1| != 0\n // ensures position == -1 ==> forall i :: 0 <= i < |s1| ==> s1[i] != Element\n{\n var n := 0;\n var n1 := |s1|;\n position := 0;\n while n != |s1|\n decreases |s1| - n\n invariant 0 <= n <= |s1|\n invariant position >= 1 ==> exists i::0 <=i < |s1| && s1[i] == Element\n invariant forall i :: data.Length-n1 < i < data.Length-n1+n ==> data[i] != Element\n invariant forall i :: |s1| - 1- n < i < |s1| -1 ==> s1[i] != Element\n {\n if data[data.Length -n1 +n] == Element \n {\n position := n + 1;\n assert data [data.Length-n1] == s1[|s1| -1];\n assert data[data.Length -n1 +n] == s1[n1-1-n];\n assert forall i:: 0<= i <|s1| ==> s1[i] == data[data.Length -1-i];\n assert forall i :: data.Length-n1 < i < data.Length-n1+n ==> data[i] != Element;\n assert forall i :: |s1| - 1 > i > |s1| -1 -n ==> s1[i] != Element;\n assert forall i:: data.Length - |s1| < i< data.Length-1 ==> data[i] == s1[data.Length-i-1];\n return position; \n }\n n := n + 1;\n }\n \n position := -1;\n assert |s1| <= data.Length;\n assert |s1| != 0 ==> s1[0] == data[data.Length-1];\n assert |s1| != 0 ==> data[data.Length-n1] == s1[|s1| -1];\n assert forall i:: data.Length - |s1| < i< data.Length-1 ==> data[i] == s1[data.Length-i-1];\n assert forall i :: data.Length-n1 < i < data.Length-n1+n ==> data[i] != Element;\n assert forall i:: 0<= i <|s1| ==> s1[i] == data[data.Length -1-i];\n assert forall i :: |s1| - 1 > i > |s1| -1 -n ==> s1[i] != Element;\n}\n", "hints_removed": "method LinearSearch(a: array, P: T -> bool) returns (n: int)\n ensures -1 <= n < a.Length\n ensures n == -1 || P(a[n])\n ensures n != -1 ==> forall i :: 0 <= i < n ==> ! P(a[i])\n ensures n == -1 ==> forall i :: 0 <= i < a.Length ==> ! P(a[i])\n{\n n := 0;\n\n while n != a.Length\n {\n if P(a[n]) {\n return; }\n n := n + 1;\n }\n n := -1;\n\n}\n\nmethod LinearSearch1(a: array, P: T -> bool, s1:seq) returns (n: int)\n requires |s1| <= a.Length\n requires forall i:: 0<= i <|s1| ==> s1[i] == a[i]\n ensures -1 <= n < a.Length\n ensures n == -1 || P(a[n])\n ensures n != -1 ==> forall i :: 0 <= i < n ==> ! P(a[i])\n ensures n == -1 ==> forall i :: 0 <= i < |s1| ==> ! P(a[i])\n{\n n := 0;\n\n while n != |s1|\n {\n if P(a[n]) {\n return; }\n n := n + 1;\n }\n n := -1;\n\n}\n\n\nmethod LinearSearch2(data: array, Element:T, s1:seq) returns (position:int)\n requires |s1| <= data.Length\n requires forall i:: 0<= i <|s1| ==> s1[i] == data[i]\n ensures position == -1 || position >= 1\n ensures position >= 1 ==> exists i::0 <=i < |s1| && s1[i] == Element\n ensures position == -1 ==> forall i :: 0 <= i < |s1| ==> s1[i] != Element\n{\n var n := 0;\n position := 0;\n while n != |s1|\n {\n if data[|s1|-1-n] == Element \n {\n position := n + 1;\n return position; \n }\n n := n + 1;\n }\n position := -1;\n}\n\nmethod LinearSearch3(data: array, Element:T, s1:seq) returns (position:int)\n requires |s1| <= data.Length\n requires forall i:: 0<= i <|s1| ==> s1[i] == data[data.Length -1-i]\n ensures position == -1 || position >= 1\n ensures position >= 1 ==> exists i::0 <=i < |s1| && s1[i] == Element && |s1| != 0\n // ensures position == -1 ==> forall i :: 0 <= i < |s1| ==> s1[i] != Element\n{\n var n := 0;\n var n1 := |s1|;\n position := 0;\n while n != |s1|\n {\n if data[data.Length -n1 +n] == Element \n {\n position := n + 1;\n return position; \n }\n n := n + 1;\n }\n \n position := -1;\n}\n" }, { "test_ID": "133", "test_file": "Dafny_Learning_Experience_tmp_tmpuxvcet_u_week1_7_week5_ComputePower.dfy", "ground_truth": " function Power(n:nat):nat \n{\n if n == 0 then 1 else 2 * Power(n-1)\n}\n\nmethod CalcPower(n:nat) returns (p:nat)\n ensures p == 2*n;\n{\n p := 2*n;\n}\n\nmethod ComputePower(n:nat) returns (p:nat)\n ensures p == Power(n)\n{\n p:=1;\n var i:=0;\n while i!=n\n invariant 0 <= i <= n\n invariant p *Power(n-i) == Power(n) \n {\n p:= CalcPower(p);\n i:=i+1;\n }\n}\n", "hints_removed": " function Power(n:nat):nat \n{\n if n == 0 then 1 else 2 * Power(n-1)\n}\n\nmethod CalcPower(n:nat) returns (p:nat)\n ensures p == 2*n;\n{\n p := 2*n;\n}\n\nmethod ComputePower(n:nat) returns (p:nat)\n ensures p == Power(n)\n{\n p:=1;\n var i:=0;\n while i!=n\n {\n p:= CalcPower(p);\n i:=i+1;\n }\n}\n" }, { "test_ID": "134", "test_file": "Dafny_Learning_Experience_tmp_tmpuxvcet_u_week8_12_a3 copy 2.dfy", "ground_truth": "class TwoStacks \n{\n //abstract state\n ghost var s1 :seq\n ghost var s2 :seq\n ghost const N :nat // maximum size of the stacks\n ghost var Repr : set\n //concrete state\n var data: array\n var n1: nat // number of elements in the stack 1\n var n2: nat // number of elements in the stack 2\n\n ghost predicate Valid()\n reads this,Repr\n ensures Valid() ==> this in Repr && |s1| + |s2| <= N && 0 <= |s1| <= N && 0 <=|s2| <= N\n {\n this in Repr && data in Repr && data.Length == N \n && 0 <= |s1| + |s2| <= N && 0 <=|s1| <= N && 0 <=|s2| <= N\n && (|s1| != 0 ==> forall i:: 0<= i < |s1| ==> s1[i] == data[i]) \n && (|s2| != 0 ==> forall i:: 0<= i < |s2| ==> s2[i] == data[data.Length-1-i])\n && n1 == |s1| && n2 == |s2|\n }\n\n constructor (N: nat)\n ensures Valid() && fresh(Repr)\n ensures s1 == s2 == [] && this.N == N\n {\n s1,s2,this.N := [],[],N;\n data := new T[N];\n n1, n2 := 0, 0;\n Repr := {this, data};\n }\n \n method push1(element:T) returns (FullStatus:bool)\n requires Valid()\n modifies Repr\n ensures old(|s1|) != N && old(|s1|) + old(|s2|) != N ==> s1 == old(s1) + [element];\n ensures old(|s1|) == N ==> FullStatus == false\n ensures old(|s1|) != N && old(|s1|) + old(|s2|) == N ==> FullStatus == false\n ensures Valid() && fresh(Repr - old(Repr))\n { \n if n1 == data.Length\n { \n FullStatus := false;\n }else {\n if n1 != data.Length && n1 + n2 != data.Length{\n s1 := old(s1) + [element] ;\n data[n1] := element;\n n1 := n1 +1;\n FullStatus := true;\n }else{\n FullStatus := false;\n }\n }\n } \n\n method push2(element:T) returns (FullStatus:bool)\n requires Valid()\n modifies Repr\n ensures old(|s2|) != N && old(|s1|) + old(|s2|) != N ==> s2 == old(s2) + [element];\n ensures old(|s2|) == N ==> FullStatus == false\n ensures old(|s2|) != N && old(|s1|) + old(|s2|) == N ==> FullStatus == false\n ensures Valid() && fresh(Repr - old(Repr))\n { \n if n2 == data.Length\n { \n FullStatus := false;\n }else {\n if n2 != data.Length && n1 + n2 != data.Length{\n s2 := old(s2) + [element] ;\n data[data.Length-1-n2] := element;\n n2 := n2 +1;\n FullStatus := true;\n }else{\n FullStatus := false;\n }\n }\n } \n\n method pop1() returns (EmptyStatus:bool, PopedItem:T)\n requires Valid()\n modifies Repr\n ensures old(|s1|) != 0 ==> s1 == old(s1[0..|s1|-1]) && EmptyStatus == true && PopedItem == old(s1[|s1|-1]) \n ensures old(|s1|) == 0 ==> EmptyStatus == false \n ensures Valid() && fresh(Repr - old(Repr))\n {\n if n1 == 0 { \n EmptyStatus := false;\n PopedItem := *;\n } else{\n s1 := old(s1[0..|s1|-1]);\n PopedItem := data[n1-1];\n n1 := n1 -1;\n EmptyStatus := true;\n }\n }\n\n method pop2() returns (EmptyStatus:bool, PopedItem:T)\n requires Valid()\n modifies Repr\n ensures old(|s2|) != 0 ==> s2 == old(s2[0..|s2|-1]) && EmptyStatus == true && PopedItem == old(s2[|s2|-1]) \n ensures old(|s2|) == 0 ==> EmptyStatus == false \n ensures Valid() && fresh(Repr - old(Repr))\n {\n if n2 == 0 { \n EmptyStatus := false;\n PopedItem := *;\n } else{\n s2 := old(s2[0..|s2|-1]);\n PopedItem := data[data.Length-n2];\n n2 := n2 -1;\n EmptyStatus := true;\n }\n }\n\n method peek1() returns (EmptyStatus:bool, TopItem:T)\n requires Valid()\n ensures Empty1() ==> EmptyStatus == false\n ensures !Empty1() ==> EmptyStatus == true && TopItem == s1[|s1|-1] \n ensures Valid()\n {\n if n1 == 0 {\n EmptyStatus := false;\n TopItem := *;\n } else {\n TopItem := data[n1-1];\n EmptyStatus := true;\n }\n }\n\n method peek2() returns (EmptyStatus:bool, TopItem:T)\n requires Valid()\n ensures Empty2() ==> EmptyStatus == false\n ensures !Empty2() ==> EmptyStatus == true && TopItem == s2[|s2|-1] \n ensures Valid()\n {\n if n2 == 0 {\n EmptyStatus := false;\n TopItem := *;\n } else {\n TopItem := data[data.Length-n2];\n EmptyStatus := true;\n }\n }\n \n ghost predicate Empty1() \n requires Valid()\n reads this,Repr\n ensures Empty1() ==> |s1| == 0\n ensures Valid()\n {\n |s1| == 0 && n1 == 0\n }\n\n ghost predicate Empty2() \n reads this\n ensures Empty2() ==> |s2| == 0\n {\n |s2| == 0 && n2 == 0\n }\n \n method search1(Element:T) returns (position:int)\n requires Valid()\n ensures position == -1 || position >= 1\n ensures position >= 1 ==> exists i::0 <=i < |s1| && s1[i] == Element && !Empty1()\n ensures position == -1 ==> forall i :: 0 <= i < |s1| ==> s1[i] != Element || Empty1()\n ensures Valid()\n {\n var n := 0;\n position := 0;\n\n while n != n1\n decreases |s1| - n\n invariant Valid()\n invariant 0 <= n <= |s1|\n invariant position >= 1 ==> exists i::0 <= i < |s1| && s1[i] == Element\n invariant forall i :: |s1|-1-n < i < |s1|==> s1[i] != Element\n {\n if data[n1-1-n] == Element \n {\n position := n + 1;\n return position; \n }\n n := n + 1;\n }\n position := -1;\n }\n\n method search3(Element:T) returns (position:int)\n requires Valid()\n ensures position == -1 || position >= 1\n ensures position >= 1 ==> exists i::0 <=i < |s2| && s2[i] == Element && !Empty2()\n // ensures position == -1 ==> forall i :: 0 <= i < |s2| ==> s2[i] != Element || Empty2()\n ensures Valid()\n {\n position := 0;\n var n := 0;\n\n while n != n2\n decreases |s2| - n\n invariant 0 <= n <= |s2|\n invariant Valid()\n invariant position >= 1 ==> exists i::0 <= i < |s2| && s2[i] == Element\n invariant forall i :: |s2| - 1- n < i < |s2| -1 ==> s2[i] != Element\n invariant forall i :: data.Length-n2 < i < data.Length-n2+n ==> data[i] != Element\n {\n if data[data.Length - n2 + n] == Element \n {\n position := n + 1;\n \n assert data[data.Length -n2 +n] == s2[n2-1-n];\n assert position >= 1 ==> exists i::0 <= i < |s2| && s2[i] == Element;\n assert forall i:: data.Length - |s2| < i< data.Length-1 ==> data[i] == s2[data.Length-i-1];\n assert forall i:: 0 <= i < |s2| ==> s2[i] == data[data.Length-i-1];\n assert forall i :: |s2| - 1- n < i < |s2| -1 ==> s2[i] != Element;\n assert forall i :: data.Length-n2 < i < data.Length-n2+n ==> data[i] != Element;\n return position; \n }\n n := n + 1;\n }\n \n position := -1;\n assert position >= 1 ==> exists i::0 <= i < |s2| && s2[i] == Element;\n assert forall i:: data.Length - |s2| < i< data.Length-1 ==> data[i] == s2[data.Length-i-1];\n assert forall i:: 0 <= i < |s2| ==> s2[i] == data[data.Length-i-1];\n assert forall i :: |s2| - 1- n < i < |s2| -1 ==> s2[i] != Element;\n assert forall i :: data.Length-n2 < i < data.Length-n2+n ==> data[i] != Element;\n }\n}\n\n\n", "hints_removed": "class TwoStacks \n{\n //abstract state\n ghost var s1 :seq\n ghost var s2 :seq\n ghost const N :nat // maximum size of the stacks\n ghost var Repr : set\n //concrete state\n var data: array\n var n1: nat // number of elements in the stack 1\n var n2: nat // number of elements in the stack 2\n\n ghost predicate Valid()\n reads this,Repr\n ensures Valid() ==> this in Repr && |s1| + |s2| <= N && 0 <= |s1| <= N && 0 <=|s2| <= N\n {\n this in Repr && data in Repr && data.Length == N \n && 0 <= |s1| + |s2| <= N && 0 <=|s1| <= N && 0 <=|s2| <= N\n && (|s1| != 0 ==> forall i:: 0<= i < |s1| ==> s1[i] == data[i]) \n && (|s2| != 0 ==> forall i:: 0<= i < |s2| ==> s2[i] == data[data.Length-1-i])\n && n1 == |s1| && n2 == |s2|\n }\n\n constructor (N: nat)\n ensures Valid() && fresh(Repr)\n ensures s1 == s2 == [] && this.N == N\n {\n s1,s2,this.N := [],[],N;\n data := new T[N];\n n1, n2 := 0, 0;\n Repr := {this, data};\n }\n \n method push1(element:T) returns (FullStatus:bool)\n requires Valid()\n modifies Repr\n ensures old(|s1|) != N && old(|s1|) + old(|s2|) != N ==> s1 == old(s1) + [element];\n ensures old(|s1|) == N ==> FullStatus == false\n ensures old(|s1|) != N && old(|s1|) + old(|s2|) == N ==> FullStatus == false\n ensures Valid() && fresh(Repr - old(Repr))\n { \n if n1 == data.Length\n { \n FullStatus := false;\n }else {\n if n1 != data.Length && n1 + n2 != data.Length{\n s1 := old(s1) + [element] ;\n data[n1] := element;\n n1 := n1 +1;\n FullStatus := true;\n }else{\n FullStatus := false;\n }\n }\n } \n\n method push2(element:T) returns (FullStatus:bool)\n requires Valid()\n modifies Repr\n ensures old(|s2|) != N && old(|s1|) + old(|s2|) != N ==> s2 == old(s2) + [element];\n ensures old(|s2|) == N ==> FullStatus == false\n ensures old(|s2|) != N && old(|s1|) + old(|s2|) == N ==> FullStatus == false\n ensures Valid() && fresh(Repr - old(Repr))\n { \n if n2 == data.Length\n { \n FullStatus := false;\n }else {\n if n2 != data.Length && n1 + n2 != data.Length{\n s2 := old(s2) + [element] ;\n data[data.Length-1-n2] := element;\n n2 := n2 +1;\n FullStatus := true;\n }else{\n FullStatus := false;\n }\n }\n } \n\n method pop1() returns (EmptyStatus:bool, PopedItem:T)\n requires Valid()\n modifies Repr\n ensures old(|s1|) != 0 ==> s1 == old(s1[0..|s1|-1]) && EmptyStatus == true && PopedItem == old(s1[|s1|-1]) \n ensures old(|s1|) == 0 ==> EmptyStatus == false \n ensures Valid() && fresh(Repr - old(Repr))\n {\n if n1 == 0 { \n EmptyStatus := false;\n PopedItem := *;\n } else{\n s1 := old(s1[0..|s1|-1]);\n PopedItem := data[n1-1];\n n1 := n1 -1;\n EmptyStatus := true;\n }\n }\n\n method pop2() returns (EmptyStatus:bool, PopedItem:T)\n requires Valid()\n modifies Repr\n ensures old(|s2|) != 0 ==> s2 == old(s2[0..|s2|-1]) && EmptyStatus == true && PopedItem == old(s2[|s2|-1]) \n ensures old(|s2|) == 0 ==> EmptyStatus == false \n ensures Valid() && fresh(Repr - old(Repr))\n {\n if n2 == 0 { \n EmptyStatus := false;\n PopedItem := *;\n } else{\n s2 := old(s2[0..|s2|-1]);\n PopedItem := data[data.Length-n2];\n n2 := n2 -1;\n EmptyStatus := true;\n }\n }\n\n method peek1() returns (EmptyStatus:bool, TopItem:T)\n requires Valid()\n ensures Empty1() ==> EmptyStatus == false\n ensures !Empty1() ==> EmptyStatus == true && TopItem == s1[|s1|-1] \n ensures Valid()\n {\n if n1 == 0 {\n EmptyStatus := false;\n TopItem := *;\n } else {\n TopItem := data[n1-1];\n EmptyStatus := true;\n }\n }\n\n method peek2() returns (EmptyStatus:bool, TopItem:T)\n requires Valid()\n ensures Empty2() ==> EmptyStatus == false\n ensures !Empty2() ==> EmptyStatus == true && TopItem == s2[|s2|-1] \n ensures Valid()\n {\n if n2 == 0 {\n EmptyStatus := false;\n TopItem := *;\n } else {\n TopItem := data[data.Length-n2];\n EmptyStatus := true;\n }\n }\n \n ghost predicate Empty1() \n requires Valid()\n reads this,Repr\n ensures Empty1() ==> |s1| == 0\n ensures Valid()\n {\n |s1| == 0 && n1 == 0\n }\n\n ghost predicate Empty2() \n reads this\n ensures Empty2() ==> |s2| == 0\n {\n |s2| == 0 && n2 == 0\n }\n \n method search1(Element:T) returns (position:int)\n requires Valid()\n ensures position == -1 || position >= 1\n ensures position >= 1 ==> exists i::0 <=i < |s1| && s1[i] == Element && !Empty1()\n ensures position == -1 ==> forall i :: 0 <= i < |s1| ==> s1[i] != Element || Empty1()\n ensures Valid()\n {\n var n := 0;\n position := 0;\n\n while n != n1\n {\n if data[n1-1-n] == Element \n {\n position := n + 1;\n return position; \n }\n n := n + 1;\n }\n position := -1;\n }\n\n method search3(Element:T) returns (position:int)\n requires Valid()\n ensures position == -1 || position >= 1\n ensures position >= 1 ==> exists i::0 <=i < |s2| && s2[i] == Element && !Empty2()\n // ensures position == -1 ==> forall i :: 0 <= i < |s2| ==> s2[i] != Element || Empty2()\n ensures Valid()\n {\n position := 0;\n var n := 0;\n\n while n != n2\n {\n if data[data.Length - n2 + n] == Element \n {\n position := n + 1;\n \n return position; \n }\n n := n + 1;\n }\n \n position := -1;\n }\n}\n\n\n" }, { "test_ID": "135", "test_file": "Dafny_Learning_Experience_tmp_tmpuxvcet_u_week8_12_a3_search_findPositionOfIndex.dfy", "ground_truth": "method FindPositionOfElement(a:array,Element:nat,n1:nat,s1:seq) returns (Position:int,Count:nat)\n requires n1 == |s1| && 0 <= n1 <= a.Length\n requires forall i:: 0<= i < |s1| ==> a[i] == s1[i]\n ensures Position == -1 || Position >= 1\n ensures |s1| != 0 && Position >= 1 ==> exists i:: 0 <= i < |s1| && s1[i] == Element\n{\n Count := 0;\n Position := 0;\n // assert forall i:: 0<= i <|s1| ==> a[n1-1-i] == s1[n1-1-i];\n // assert forall i:: 0<= i <|s1| ==> a[n1-1-i]!= Element;\n while Count != n1\n decreases n1 - Count\n invariant |s1|!=0 && Position >= 1 ==> exists i:: 0 <= i < n1 && a[i] == Element \n invariant 0 <= Count <= n1\n invariant Position >=1 ==> forall i:: 0<= i a[i] != Element\n invariant Position == -1 ==> forall i:: 0<= i < n1 ==> a[i] != Element\n {\n if a[n1-1-Count] == Element\n {\n Position := Count + 1;\n //assert Count >= 1 ==> a[Count -1] != Element;\n //assert a[Count] == Element;\n\n return Position,Count;\n } \n Count := Count + 1;\n }\n assert Position != -1 ==> true;\n //assert Position != -1 ==> forall i:: 0<= i < Count ==> a[i] != Element;\n Position := -1;\n // assert Position == -1 ==> forall i:: 0<= i < n1 ==> a[i] != Element;\n //assert exists i:: 0 <= i < |s1| && a[i] == Element;\n \n assert Position == -1;\n}\n\nmethod Main() {\n var a := new int[5];\n var b := [1,2,3,4];\n a[0],a[1],a[2],a[3]:= 1,2,3,4;\n var n1 := |b|;\n var Element := 5;\n var Position, Count;\n Position, Count := FindPositionOfElement(a,Element,n1,b);\n print \"position is \",Position;\n}\n", "hints_removed": "method FindPositionOfElement(a:array,Element:nat,n1:nat,s1:seq) returns (Position:int,Count:nat)\n requires n1 == |s1| && 0 <= n1 <= a.Length\n requires forall i:: 0<= i < |s1| ==> a[i] == s1[i]\n ensures Position == -1 || Position >= 1\n ensures |s1| != 0 && Position >= 1 ==> exists i:: 0 <= i < |s1| && s1[i] == Element\n{\n Count := 0;\n Position := 0;\n // assert forall i:: 0<= i <|s1| ==> a[n1-1-i] == s1[n1-1-i];\n // assert forall i:: 0<= i <|s1| ==> a[n1-1-i]!= Element;\n while Count != n1\n {\n if a[n1-1-Count] == Element\n {\n Position := Count + 1;\n //assert Count >= 1 ==> a[Count -1] != Element;\n //assert a[Count] == Element;\n\n return Position,Count;\n } \n Count := Count + 1;\n }\n //assert Position != -1 ==> forall i:: 0<= i < Count ==> a[i] != Element;\n Position := -1;\n // assert Position == -1 ==> forall i:: 0<= i < n1 ==> a[i] != Element;\n //assert exists i:: 0 <= i < |s1| && a[i] == Element;\n \n}\n\nmethod Main() {\n var a := new int[5];\n var b := [1,2,3,4];\n a[0],a[1],a[2],a[3]:= 1,2,3,4;\n var n1 := |b|;\n var Element := 5;\n var Position, Count;\n Position, Count := FindPositionOfElement(a,Element,n1,b);\n print \"position is \",Position;\n}\n" }, { "test_ID": "136", "test_file": "Dafny_Learning_Experience_tmp_tmpuxvcet_u_week8_12_week10_BoundedQueue_01.dfy", "ground_truth": " class BoundedQueue\n{\n // abstract state\n ghost var contents: seq // the contents of the bounded queue\n ghost var N: nat // the (maximum) size of the bounded queue\n ghost var Repr: set\n // concrete state\nvar data: array\n var wr: nat\n var rd: nat\n \n ghost predicate Valid()\n reads this, Repr\nensures Valid() ==> this in Repr && |contents| <= N \n {\n this in Repr && data in Repr &&\ndata.Length == N + 1 &&\nwr <= N && rd <= N &&\n contents == if rd <= wr then data[rd..wr] else data[rd..] + data[..wr]\n }\n\n constructor (N: nat)\nensures Valid() && fresh(Repr)\nensures contents == [] && this.N == N\n{\n contents := [];\n this.N := N;\n data := new T[N+1]; // requires T to have default initial value\n rd, wr := 0, 0;\n Repr := {this, data};\n}\nmethod Insert(x:T)\nrequires Valid()\nrequires |contents| != N\nmodifies Repr\nensures contents == old(contents) + [x]\nensures N == old(N)\nensures Valid() && fresh(Repr - old(Repr))\n{\n contents := old(contents) + [x];\n\n data[wr] := x;\n assert (wr == data.Length -1 ==> contents == if rd <= 0 then data[rd..0] else data[rd..] + data[..0])\n && (wr!= data.Length -1 ==> contents == if rd <= wr+1 then data[rd..wr+1] else data[rd..] + data[..wr+1]);\n if wr == data.Length -1 {\n assert contents == if rd <= 0 then data[rd..0] else data[rd..] + data[..0];\n wr := 0;\n assert contents == if rd <= wr then data[rd..wr] else data[rd..] + data[..wr];\n } else {\n assert contents == if rd <= wr+1 then data[rd..wr+1] else data[rd..] + data[..wr+1];\n wr := wr + 1;\n assert contents == if rd <= wr then data[rd..wr] else data[rd..] + data[..wr];\n }\n assert contents == if rd <= wr then data[rd..wr] else data[rd..] + data[..wr];\n}\n\nmethod Remove() returns (x:T)\nrequires Valid()\nrequires |contents| != 0\nmodifies Repr\nensures contents == old(contents[1..]) && old(contents[0]) == x\nensures N == old(N)\nensures Valid() && fresh(Repr - old(Repr))\n{\n contents := contents[1..];\n x := data[rd];\n if rd == data.Length - 1 {\n rd := 0;\n } else {\n rd := rd + 1;\n }\n}\n}\n", "hints_removed": " class BoundedQueue\n{\n // abstract state\n ghost var contents: seq // the contents of the bounded queue\n ghost var N: nat // the (maximum) size of the bounded queue\n ghost var Repr: set\n // concrete state\nvar data: array\n var wr: nat\n var rd: nat\n \n ghost predicate Valid()\n reads this, Repr\nensures Valid() ==> this in Repr && |contents| <= N \n {\n this in Repr && data in Repr &&\ndata.Length == N + 1 &&\nwr <= N && rd <= N &&\n contents == if rd <= wr then data[rd..wr] else data[rd..] + data[..wr]\n }\n\n constructor (N: nat)\nensures Valid() && fresh(Repr)\nensures contents == [] && this.N == N\n{\n contents := [];\n this.N := N;\n data := new T[N+1]; // requires T to have default initial value\n rd, wr := 0, 0;\n Repr := {this, data};\n}\nmethod Insert(x:T)\nrequires Valid()\nrequires |contents| != N\nmodifies Repr\nensures contents == old(contents) + [x]\nensures N == old(N)\nensures Valid() && fresh(Repr - old(Repr))\n{\n contents := old(contents) + [x];\n\n data[wr] := x;\n && (wr!= data.Length -1 ==> contents == if rd <= wr+1 then data[rd..wr+1] else data[rd..] + data[..wr+1]);\n if wr == data.Length -1 {\n wr := 0;\n } else {\n wr := wr + 1;\n }\n}\n\nmethod Remove() returns (x:T)\nrequires Valid()\nrequires |contents| != 0\nmodifies Repr\nensures contents == old(contents[1..]) && old(contents[0]) == x\nensures N == old(N)\nensures Valid() && fresh(Repr - old(Repr))\n{\n contents := contents[1..];\n x := data[rd];\n if rd == data.Length - 1 {\n rd := 0;\n } else {\n rd := rd + 1;\n }\n}\n}\n" }, { "test_ID": "137", "test_file": "Dafny_Learning_Experience_tmp_tmpuxvcet_u_week8_12_week10_ExtensibleArray.dfy", "ground_truth": "class ExtensibleArray {\n // abstract state\n ghost var Elements: seq\n ghost var Repr: set\n //concrete state\n var front: array?\n var depot: ExtensibleArray?>\n var length: int // number of elements\n var M: int // number of elements in depot\n\n ghost predicate Valid()\n decreases Repr +{this}\n reads this, Repr\n ensures Valid() ==> this in Repr\n {\n // Abstraction relation: Repr\n this in Repr &&\n (front != null ==> front in Repr) &&\n (depot != null ==>\n depot in Repr && depot.Repr <= Repr &&\n forall j :: 0 <= j < |depot.Elements| ==>\n depot.Elements[j] in Repr) &&\n // Standard concrete invariants: Aliasing\n (depot != null ==>\n this !in depot.Repr && \n front !in depot.Repr &&\n forall j :: 0 <= j < |depot.Elements| ==>\n depot.Elements[j] !in depot.Repr &&\n depot.Elements[j] != front &&\n forall k :: 0 <= k < |depot.Elements| && k != j ==>\n depot.Elements[j] != depot.Elements[k]) &&\n // Concrete state invariants\n (front != null ==> front.Length == 256) &&\n (depot != null ==>\n depot.Valid() &&\n forall j :: 0 <= j < |depot.Elements| ==>\n depot.Elements[j].Length == 256) &&\n (length == M <==> front == null) &&\n M == (if depot == null then 0 else 256 * |depot.Elements|) &&\n // Abstraction relation: Elements\n length == |Elements| &&\n M <= |Elements| < M + 256 &&\n (forall i :: 0 <= i < M ==>\n Elements[i] == depot.Elements[i / 256][i % 256]) &&\n (forall i :: M <= i < length ==>\n Elements[i] == front[i - M])\n }\n\n constructor ()\n ensures Valid() && fresh(Repr) && Elements == []\n {\n front, depot := null, null;\n length, M := 0, 0;\n Elements, Repr := [], {this};\n }\n\n function Get(i: int): T\n requires Valid() && 0 <= i < |Elements|\n ensures Get(i) == Elements[i]\n reads Repr\n {\n if M <= i then front[i - M]\n else depot.Get(i/256)[i%256]\n }\n\n method Set(i: int, t: T)\n requires Valid() && 0 <= i < |Elements|\n modifies Repr\n ensures Valid() && fresh(Repr - old(Repr))\n ensures Elements == old(Elements)[i := t]\n{\n if M <= i {\n front[i - M] := t;\n } else {\n depot.Get(i/256)[i%256] := t;\n }\n Elements := Elements[i := t];\n}\n\n method Add(t: T)\n requires Valid()\n modifies Repr\n ensures Valid() && fresh(Repr - old(Repr))\n ensures Elements == old(Elements) + [t]\n decreases |Elements|\n {\n if front == null {\n front := new T[256];\n Repr := Repr + {front};\n }\n front[length-M] := t;\n length := length + 1;\n Elements := Elements + [t];\n if length == M + 256 {\n if depot == null {\n depot := new ExtensibleArray();\n }\n depot.Add(front);\n Repr := Repr + depot.Repr;\n M := M + 256;\n front := null;\n }\n }\n \n}\n", "hints_removed": "class ExtensibleArray {\n // abstract state\n ghost var Elements: seq\n ghost var Repr: set\n //concrete state\n var front: array?\n var depot: ExtensibleArray?>\n var length: int // number of elements\n var M: int // number of elements in depot\n\n ghost predicate Valid()\n reads this, Repr\n ensures Valid() ==> this in Repr\n {\n // Abstraction relation: Repr\n this in Repr &&\n (front != null ==> front in Repr) &&\n (depot != null ==>\n depot in Repr && depot.Repr <= Repr &&\n forall j :: 0 <= j < |depot.Elements| ==>\n depot.Elements[j] in Repr) &&\n // Standard concrete invariants: Aliasing\n (depot != null ==>\n this !in depot.Repr && \n front !in depot.Repr &&\n forall j :: 0 <= j < |depot.Elements| ==>\n depot.Elements[j] !in depot.Repr &&\n depot.Elements[j] != front &&\n forall k :: 0 <= k < |depot.Elements| && k != j ==>\n depot.Elements[j] != depot.Elements[k]) &&\n // Concrete state invariants\n (front != null ==> front.Length == 256) &&\n (depot != null ==>\n depot.Valid() &&\n forall j :: 0 <= j < |depot.Elements| ==>\n depot.Elements[j].Length == 256) &&\n (length == M <==> front == null) &&\n M == (if depot == null then 0 else 256 * |depot.Elements|) &&\n // Abstraction relation: Elements\n length == |Elements| &&\n M <= |Elements| < M + 256 &&\n (forall i :: 0 <= i < M ==>\n Elements[i] == depot.Elements[i / 256][i % 256]) &&\n (forall i :: M <= i < length ==>\n Elements[i] == front[i - M])\n }\n\n constructor ()\n ensures Valid() && fresh(Repr) && Elements == []\n {\n front, depot := null, null;\n length, M := 0, 0;\n Elements, Repr := [], {this};\n }\n\n function Get(i: int): T\n requires Valid() && 0 <= i < |Elements|\n ensures Get(i) == Elements[i]\n reads Repr\n {\n if M <= i then front[i - M]\n else depot.Get(i/256)[i%256]\n }\n\n method Set(i: int, t: T)\n requires Valid() && 0 <= i < |Elements|\n modifies Repr\n ensures Valid() && fresh(Repr - old(Repr))\n ensures Elements == old(Elements)[i := t]\n{\n if M <= i {\n front[i - M] := t;\n } else {\n depot.Get(i/256)[i%256] := t;\n }\n Elements := Elements[i := t];\n}\n\n method Add(t: T)\n requires Valid()\n modifies Repr\n ensures Valid() && fresh(Repr - old(Repr))\n ensures Elements == old(Elements) + [t]\n {\n if front == null {\n front := new T[256];\n Repr := Repr + {front};\n }\n front[length-M] := t;\n length := length + 1;\n Elements := Elements + [t];\n if length == M + 256 {\n if depot == null {\n depot := new ExtensibleArray();\n }\n depot.Add(front);\n Repr := Repr + depot.Repr;\n M := M + 256;\n front := null;\n }\n }\n \n}\n" }, { "test_ID": "138", "test_file": "Dafny_Learning_Experience_tmp_tmpuxvcet_u_week8_12_week8_CheckSumCalculator.dfy", "ground_truth": "ghost function Hash(s:string):int {\n SumChars(s) % 137\n}\n\nghost function SumChars(s: string):int {\n if |s| == 0 then 0 else \n s[|s| - 1] as int + SumChars(s[..|s| -1])\n}\nclass CheckSumCalculator{\n var data: string\n var cs:int\n\n ghost predicate Valid()\n reads this\n {\n cs == Hash(data)\n }\n\n constructor ()\n ensures Valid() && data == \"\"\n {\n data, cs := \"\", 0;\n }\n\n method Append(d:string)\n requires Valid()\n modifies this\n ensures Valid() && data == old(data) + d\n {\n var i := 0;\n while i != |d| \n invariant 0<= i <= |d|\n invariant Valid()\n invariant data == old(data) + d[..i]\n {\n cs := (cs + d[i] as int) % 137;\n data := data + [d[i]];\n i := i +1;\n }\n }\n\n function GetData(): string\n requires Valid()\n reads this\n ensures Hash(GetData()) == Checksum()\n {\n data\n }\n\n function Checksum(): int \n requires Valid()\n reads this \n ensures Checksum() == Hash(data)\n {\n cs\n }\n}\n\nmethod Main() {\n /*\n var m:= new CheckSumCalculator();\n m.Append(\"g\");\n m.Append(\"Grass\");\n var c:= m.Checksum();\n var g:= m.GetData();\n print \"(m.cs)Checksum is \" ,m.cs,\"\\n\";\n print \"(c)Checksum is \" ,c,\"\\n\";\n print \"(m.data)Checksum is \" ,m.data,\"\\n\";\n print \"(g)Checksum is \" ,g,\"\\n\";\n\n var tmpStr := \"abcde\";\n var tmpStrOne := \"LLLq\";\n var tmpSet := {'a','c'};\n var tmpFresh := {'a','b'};\n var tmpnum := 1;\n print \"tmp is \", tmpSet - tmpFresh;\n\n var newArray := new int[10];\n newArray[0]:= 0; */\n var newSeq := ['a','b','c','d','e','f','g','h'];\n var newSeqTwo := ['h','g','f','e','d','c','b','a'];\n var newSet : set;\n newSet := {1,2,3,4,5};\n var newSetTwo := {6,7,8,9,10};\n\n print \"element is newset \", newSet,\"\\n\";\n\n var newArray := new int [99];\n newArray[0] := 99;\n newArray[1] := 2;\n\n print \"element is ? \", |[newArray]|,\"\\n\";\n var tmpSet := {'a','c'};\n var tmpFresh := {'c'};\n print \"tmp is \", tmpSet - tmpFresh;\n\n var newMap := map[];\n newMap := newMap[1:=2];\n var nnewMap := map[3:=444];\n print \"keys is \",newMap.Keys,newMap.Values;\n print \"value is\", nnewMap.Keys,nnewMap.Values;\n}\n", "hints_removed": "ghost function Hash(s:string):int {\n SumChars(s) % 137\n}\n\nghost function SumChars(s: string):int {\n if |s| == 0 then 0 else \n s[|s| - 1] as int + SumChars(s[..|s| -1])\n}\nclass CheckSumCalculator{\n var data: string\n var cs:int\n\n ghost predicate Valid()\n reads this\n {\n cs == Hash(data)\n }\n\n constructor ()\n ensures Valid() && data == \"\"\n {\n data, cs := \"\", 0;\n }\n\n method Append(d:string)\n requires Valid()\n modifies this\n ensures Valid() && data == old(data) + d\n {\n var i := 0;\n while i != |d| \n {\n cs := (cs + d[i] as int) % 137;\n data := data + [d[i]];\n i := i +1;\n }\n }\n\n function GetData(): string\n requires Valid()\n reads this\n ensures Hash(GetData()) == Checksum()\n {\n data\n }\n\n function Checksum(): int \n requires Valid()\n reads this \n ensures Checksum() == Hash(data)\n {\n cs\n }\n}\n\nmethod Main() {\n /*\n var m:= new CheckSumCalculator();\n m.Append(\"g\");\n m.Append(\"Grass\");\n var c:= m.Checksum();\n var g:= m.GetData();\n print \"(m.cs)Checksum is \" ,m.cs,\"\\n\";\n print \"(c)Checksum is \" ,c,\"\\n\";\n print \"(m.data)Checksum is \" ,m.data,\"\\n\";\n print \"(g)Checksum is \" ,g,\"\\n\";\n\n var tmpStr := \"abcde\";\n var tmpStrOne := \"LLLq\";\n var tmpSet := {'a','c'};\n var tmpFresh := {'a','b'};\n var tmpnum := 1;\n print \"tmp is \", tmpSet - tmpFresh;\n\n var newArray := new int[10];\n newArray[0]:= 0; */\n var newSeq := ['a','b','c','d','e','f','g','h'];\n var newSeqTwo := ['h','g','f','e','d','c','b','a'];\n var newSet : set;\n newSet := {1,2,3,4,5};\n var newSetTwo := {6,7,8,9,10};\n\n print \"element is newset \", newSet,\"\\n\";\n\n var newArray := new int [99];\n newArray[0] := 99;\n newArray[1] := 2;\n\n print \"element is ? \", |[newArray]|,\"\\n\";\n var tmpSet := {'a','c'};\n var tmpFresh := {'c'};\n print \"tmp is \", tmpSet - tmpFresh;\n\n var newMap := map[];\n newMap := newMap[1:=2];\n var nnewMap := map[3:=444];\n print \"keys is \",newMap.Keys,newMap.Values;\n print \"value is\", nnewMap.Keys,nnewMap.Values;\n}\n" }, { "test_ID": "139", "test_file": "Dafny_Learning_Experience_tmp_tmpuxvcet_u_week8_12_week8_CoffeeMaker2.dfy", "ground_truth": "class Grinder { \n\tghost var hasBeans: bool \n ghost var Repr: set\n\n\tghost predicate Valid() \n\t\treads this, Repr\n ensures Valid() ==> this in Repr\n\t\t\n\tconstructor() \n\t\tensures Valid() && fresh(Repr) && !hasBeans\n\n function Ready(): bool \n\t\trequires Valid() \n\t\treads Repr\n\t\tensures Ready() == hasBeans \n\n\tmethod AddBeans() \n\t\trequires Valid() \n\t\tmodifies Repr \n\t\tensures Valid() && hasBeans && fresh(Repr-old(Repr))\n\n\tmethod Grind() \n\t\trequires Valid() && hasBeans \n\t\tmodifies Repr \n\t\tensures Valid() && fresh(Repr-old(Repr))\n}\n\nclass WaterTank { \n\tghost var waterLevel: nat\n ghost var Repr: set\n\n\tghost predicate Valid() \t\t\t \n\t\treads this, Repr \t\t\n ensures Valid() ==> this in Repr\n\n\tconstructor() \t\t\t\t \n\t\tensures Valid() && fresh(Repr) && waterLevel == 0\n\n function Level(): nat \n\t\trequires Valid()\n\t\treads Repr\n\t\tensures Level() == waterLevel\n\n\tmethod Fill() \n\t\trequires Valid() \n\t\tmodifies Repr \n\t\tensures Valid() && fresh(Repr-old(Repr)) && waterLevel == 10 \n\n\tmethod Use() \n\t\trequires Valid() && waterLevel != 0 \n\t\tmodifies Repr \n\t\tensures Valid() && fresh(Repr-old(Repr)) && waterLevel == old(Level()) - 1 \n}\n\nclass CoffeeMaker { \t\n\tvar g: Grinder \t\n\tvar w: WaterTank\n\tghost var ready: bool\n\tghost var Repr: set\n\n\tghost predicate Valid() \n\t\treads this, Repr \n ensures Valid() ==> this in Repr\n\t{ \n\t\tthis in Repr && g in Repr && w in Repr &&\n\t\tg.Repr <= Repr && w.Repr <= Repr &&\n\t\tg.Valid() && w.Valid() &&\n\t\tthis !in g.Repr && this !in w.Repr && w.Repr !! g.Repr &&\n\t\tready == (g.hasBeans && w.waterLevel != 0) \n\t}\n\n constructor() \n\t\tensures Valid() && fresh(Repr)\n\t{ \n\t\n\t\tg := new Grinder(); \n\t\tw := new WaterTank(); \n\t\tready := false;\n\t\tnew;\n\t\tRepr := {this, g, w} + g.Repr + w.Repr;\n\t\t\n\t}\n\n predicate Ready() \n\t\trequires Valid() \n\t\treads Repr\n\t\tensures Ready() == ready\n\t{ \n\t\tg.Ready() && w.Level() != 0\n\t}\n\n method Restock() \n\t\trequires Valid() \n\t\tmodifies Repr \n\t\tensures Valid() && Ready() && fresh(Repr - old(Repr))\n\t{ \n\t\tassert w.Valid();\n\t\tg.AddBeans(); \n\t\tassert w.Valid();\n\t\tw.Fill(); \n\t\tready := true;\n\t\tRepr := Repr + g.Repr + w.Repr;\n\t} \n\n method Dispense()\n\t\trequires Valid() && Ready() \n\t\tmodifies Repr \n\t\tensures Valid() && fresh(Repr - old(Repr))\n\t{ \t\n\t\tg.Grind(); \n\t\tw.Use(); \n\t\tready := g.hasBeans && w.waterLevel != 0;\n\t\tRepr := Repr + g.Repr + w.Repr;\n\t\t\n\t}\n}\n\nmethod CoffeeTestHarness() { \n\tvar cm := new CoffeeMaker(); \n\tcm.Restock(); \n\tcm.Dispense();\n}\n\n\n", "hints_removed": "class Grinder { \n\tghost var hasBeans: bool \n ghost var Repr: set\n\n\tghost predicate Valid() \n\t\treads this, Repr\n ensures Valid() ==> this in Repr\n\t\t\n\tconstructor() \n\t\tensures Valid() && fresh(Repr) && !hasBeans\n\n function Ready(): bool \n\t\trequires Valid() \n\t\treads Repr\n\t\tensures Ready() == hasBeans \n\n\tmethod AddBeans() \n\t\trequires Valid() \n\t\tmodifies Repr \n\t\tensures Valid() && hasBeans && fresh(Repr-old(Repr))\n\n\tmethod Grind() \n\t\trequires Valid() && hasBeans \n\t\tmodifies Repr \n\t\tensures Valid() && fresh(Repr-old(Repr))\n}\n\nclass WaterTank { \n\tghost var waterLevel: nat\n ghost var Repr: set\n\n\tghost predicate Valid() \t\t\t \n\t\treads this, Repr \t\t\n ensures Valid() ==> this in Repr\n\n\tconstructor() \t\t\t\t \n\t\tensures Valid() && fresh(Repr) && waterLevel == 0\n\n function Level(): nat \n\t\trequires Valid()\n\t\treads Repr\n\t\tensures Level() == waterLevel\n\n\tmethod Fill() \n\t\trequires Valid() \n\t\tmodifies Repr \n\t\tensures Valid() && fresh(Repr-old(Repr)) && waterLevel == 10 \n\n\tmethod Use() \n\t\trequires Valid() && waterLevel != 0 \n\t\tmodifies Repr \n\t\tensures Valid() && fresh(Repr-old(Repr)) && waterLevel == old(Level()) - 1 \n}\n\nclass CoffeeMaker { \t\n\tvar g: Grinder \t\n\tvar w: WaterTank\n\tghost var ready: bool\n\tghost var Repr: set\n\n\tghost predicate Valid() \n\t\treads this, Repr \n ensures Valid() ==> this in Repr\n\t{ \n\t\tthis in Repr && g in Repr && w in Repr &&\n\t\tg.Repr <= Repr && w.Repr <= Repr &&\n\t\tg.Valid() && w.Valid() &&\n\t\tthis !in g.Repr && this !in w.Repr && w.Repr !! g.Repr &&\n\t\tready == (g.hasBeans && w.waterLevel != 0) \n\t}\n\n constructor() \n\t\tensures Valid() && fresh(Repr)\n\t{ \n\t\n\t\tg := new Grinder(); \n\t\tw := new WaterTank(); \n\t\tready := false;\n\t\tnew;\n\t\tRepr := {this, g, w} + g.Repr + w.Repr;\n\t\t\n\t}\n\n predicate Ready() \n\t\trequires Valid() \n\t\treads Repr\n\t\tensures Ready() == ready\n\t{ \n\t\tg.Ready() && w.Level() != 0\n\t}\n\n method Restock() \n\t\trequires Valid() \n\t\tmodifies Repr \n\t\tensures Valid() && Ready() && fresh(Repr - old(Repr))\n\t{ \n\t\tg.AddBeans(); \n\t\tw.Fill(); \n\t\tready := true;\n\t\tRepr := Repr + g.Repr + w.Repr;\n\t} \n\n method Dispense()\n\t\trequires Valid() && Ready() \n\t\tmodifies Repr \n\t\tensures Valid() && fresh(Repr - old(Repr))\n\t{ \t\n\t\tg.Grind(); \n\t\tw.Use(); \n\t\tready := g.hasBeans && w.waterLevel != 0;\n\t\tRepr := Repr + g.Repr + w.Repr;\n\t\t\n\t}\n}\n\nmethod CoffeeTestHarness() { \n\tvar cm := new CoffeeMaker(); \n\tcm.Restock(); \n\tcm.Dispense();\n}\n\n\n" }, { "test_ID": "140", "test_file": "Dafny_Learning_Experience_tmp_tmpuxvcet_u_week8_12_week9_lemma.dfy", "ground_truth": "method AssignmentsToMark(students:int, tutors: int) returns (r:int)\n requires students > 0 && tutors > 1\n ensures r < students\n{\n assert students > 0 && tutors > 1;\n assert students > 0 && tutors > 1 && true;\n assert students > 0 && tutors > 1 && students/tutors < students ==> students/tutors < students;\n DivisionLemma(students,tutors);\n assert students/tutors < students;\n r:= students/tutors;\n assert r< students;\n calc {\n //true;\n 1/tutors < 1;\n students/tutors < students;\n }\n}\n\nlemma DivisionLemma(n:int,d:int) \n requires n > 0 && d>1\n ensures n/d < n\n\n\nmethod AssignmentsToMarkOne(students:int, tutors: int) returns (r:int)\n requires students > 0 && tutors > 1\n ensures r < students\n{\n \n r:= students/tutors;\n \n calc == {\n true;\n 1/tutors < 1;\n students/tutors < students;\n }\n}\n\nlemma CommonElement(a:array, b:array)\n requires a.Length> 0 && b.Length > 0 && a[0] == b[0]\n ensures multiset(a[..]) * multiset(b[..]) == multiset([a[0]]) + multiset(a[1..]) * multiset(b[1..])\n //ensures multiset{a[..]} * multiset{b[..]} == multiset([a[0]]) + multiset{a[1..]} * multiset{b[1..]}\n/*\n{\n var E := multiset{a[0]};\n calc =={\n multiset(a[..]) * multiset(b[..]);\n assert (a[..] == [a[0]] + a[1..]) && (b[..] == [b[0]] + b[1..]); \n (E+ multiset(a[1..])) * (E + multiset(a[1..]));\n E + multiset(a[1..]) * multiset(b[1..]);\n }\n}*/\n", "hints_removed": "method AssignmentsToMark(students:int, tutors: int) returns (r:int)\n requires students > 0 && tutors > 1\n ensures r < students\n{\n DivisionLemma(students,tutors);\n r:= students/tutors;\n calc {\n //true;\n 1/tutors < 1;\n students/tutors < students;\n }\n}\n\nlemma DivisionLemma(n:int,d:int) \n requires n > 0 && d>1\n ensures n/d < n\n\n\nmethod AssignmentsToMarkOne(students:int, tutors: int) returns (r:int)\n requires students > 0 && tutors > 1\n ensures r < students\n{\n \n r:= students/tutors;\n \n calc == {\n true;\n 1/tutors < 1;\n students/tutors < students;\n }\n}\n\nlemma CommonElement(a:array, b:array)\n requires a.Length> 0 && b.Length > 0 && a[0] == b[0]\n ensures multiset(a[..]) * multiset(b[..]) == multiset([a[0]]) + multiset(a[1..]) * multiset(b[1..])\n //ensures multiset{a[..]} * multiset{b[..]} == multiset([a[0]]) + multiset{a[1..]} * multiset{b[1..]}\n/*\n{\n var E := multiset{a[0]};\n calc =={\n multiset(a[..]) * multiset(b[..]);\n (E+ multiset(a[1..])) * (E + multiset(a[1..]));\n E + multiset(a[1..]) * multiset(b[1..]);\n }\n}*/\n" }, { "test_ID": "141", "test_file": "Dafny_ProgrammingLanguages_tmp_tmp82_e0kji_ExtraCredit.dfy", "ground_truth": "datatype Exp = Const(int) | Var(string) | Plus(Exp, Exp) | Mult(Exp, Exp)\n\nfunction eval(e:Exp, store:map):int\n{\n\tmatch(e)\n\t\tcase Const(n) => n\n\t\tcase Var(s) => if(s in store) then store[s] else -1\n\t\tcase Plus(e1, e2) => eval(e1, store) + eval(e2, store)\n\t\tcase Mult(e1, e2) => eval(e1, store) * eval(e2, store)\n}\n\n//fill this function in to make optimizeFeatures work\nfunction optimize(e:Exp):Exp\n{\n\tmatch e\n\tcase Mult(Const(0), e) => Const(0)\n\tcase Mult(e, Const(0)) => Const(0)\n\tcase Mult(Const(1), e) => e\n\tcase Mult(e, Const(1)) => e\n\tcase Mult(Const(n1), Const(n2)) => Const(n1*n2)\n\tcase Plus(Const(0), e) => e\n\tcase Plus(e, Const(0)) => e\n\tcase Plus(Const(n1), Const(n2)) => Const(n1+ n2)\n\tcase e => e\n\n} \n\n//as you write optimize this will become unproved\n//you must write proof code so that Dafny can prove this\nmethod optimizeCorrect(e:Exp, s:map)\nensures eval(e,s) == eval(optimize(e), s)\n{\n\n}\n\nmethod optimizeFeatures()\n{\n\tassert( optimize(Mult(Var(\"x\"), Const(0))) == Const(0) );\n\tassert( optimize(Mult(Var(\"x\"), Const(1))) == Var(\"x\") );\n\tassert( optimize(Mult(Const(0), Var(\"x\"))) == Const(0) );\n\tassert( optimize(Mult(Const(1), Var(\"x\"))) == Var(\"x\") );\n\n\tassert( optimize(Plus(Const(0), Var(\"x\"))) == Var(\"x\") );\n\tassert( optimize(Plus(Var(\"x\"), Const(0))) == Var(\"x\") );\n\n\tassert( optimize(Plus(Const(3),Const(4))) == Const(7) );\n\tassert( optimize(Mult(Const(3),Const(4))) == Const(12) );\n\n\n\tassert( optimize(Plus(Plus(Var(\"x\"), Var(\"y\")), Const(0))) == Plus(Var(\"x\"), Var(\"y\")) );\n\t\n}\n", "hints_removed": "datatype Exp = Const(int) | Var(string) | Plus(Exp, Exp) | Mult(Exp, Exp)\n\nfunction eval(e:Exp, store:map):int\n{\n\tmatch(e)\n\t\tcase Const(n) => n\n\t\tcase Var(s) => if(s in store) then store[s] else -1\n\t\tcase Plus(e1, e2) => eval(e1, store) + eval(e2, store)\n\t\tcase Mult(e1, e2) => eval(e1, store) * eval(e2, store)\n}\n\n//fill this function in to make optimizeFeatures work\nfunction optimize(e:Exp):Exp\n{\n\tmatch e\n\tcase Mult(Const(0), e) => Const(0)\n\tcase Mult(e, Const(0)) => Const(0)\n\tcase Mult(Const(1), e) => e\n\tcase Mult(e, Const(1)) => e\n\tcase Mult(Const(n1), Const(n2)) => Const(n1*n2)\n\tcase Plus(Const(0), e) => e\n\tcase Plus(e, Const(0)) => e\n\tcase Plus(Const(n1), Const(n2)) => Const(n1+ n2)\n\tcase e => e\n\n} \n\n//as you write optimize this will become unproved\n//you must write proof code so that Dafny can prove this\nmethod optimizeCorrect(e:Exp, s:map)\nensures eval(e,s) == eval(optimize(e), s)\n{\n\n}\n\nmethod optimizeFeatures()\n{\n\n\n\n\n\t\n}\n" }, { "test_ID": "142", "test_file": "Dafny_Programs_tmp_tmp99966ew4_binary_search.dfy", "ground_truth": "predicate sorted(a: array)\n requires a != null\n reads a\n{\n forall j, k :: 0 <= j < k < a.Length ==> a[j] <= a[k]\n}\nmethod BinarySearch(a: array, value: int) returns (index: int)\n requires a != null && 0 <= a.Length && sorted(a)\n ensures 0 <= index ==> index < a.Length && a[index] == value\n ensures index < 0 ==> forall k :: 0 <= k < a.Length ==> a[k] != value\n{\n var low, high := 0, a.Length;\n while low < high\n invariant 0 <= low <= high <= a.Length\n invariant forall i ::\n 0 <= i < a.Length && !(low <= i < high) ==> a[i] != value\n decreases high - low\n {\n var mid := (low + high) / 2;\n if a[mid] < value\n {\n low := mid + 1;\n }\n else if value < a[mid]\n {\n high := mid;\n }\n else\n {\n return mid;\n }\n }\n return -1;\n}\n\n", "hints_removed": "predicate sorted(a: array)\n requires a != null\n reads a\n{\n forall j, k :: 0 <= j < k < a.Length ==> a[j] <= a[k]\n}\nmethod BinarySearch(a: array, value: int) returns (index: int)\n requires a != null && 0 <= a.Length && sorted(a)\n ensures 0 <= index ==> index < a.Length && a[index] == value\n ensures index < 0 ==> forall k :: 0 <= k < a.Length ==> a[k] != value\n{\n var low, high := 0, a.Length;\n while low < high\n 0 <= i < a.Length && !(low <= i < high) ==> a[i] != value\n {\n var mid := (low + high) / 2;\n if a[mid] < value\n {\n low := mid + 1;\n }\n else if value < a[mid]\n {\n high := mid;\n }\n else\n {\n return mid;\n }\n }\n return -1;\n}\n\n" }, { "test_ID": "143", "test_file": "Dafny_Programs_tmp_tmp99966ew4_lemma.dfy", "ground_truth": "lemma SkippingLemma(a : array, j : int)\n requires a != null\n requires forall i :: 0 <= i < a.Length ==> 0 <= a[i]\n requires forall i :: 0 < i < a.Length ==> a[i-1]-1 <= a[i]\n requires 0 <= j < a.Length\n ensures forall k :: j <= k < j + a[j] && k < a.Length ==> a[k] != 0\n{\n var i := j;\n while i < j + a[j] && i < a.Length\n decreases j + a[j] - i\n invariant i < a.Length ==> a[j] - (i-j) <= a[i]\n invariant forall k :: j <= k < i && k < a.Length ==> a[k] != 0\n {\n i := i + 1;\n }\n}\nmethod FindZero(a: array) returns (index: int)\n requires a != null\n requires forall i :: 0 <= i < a.Length ==> 0 <= a[i]\n requires forall i :: 0 < i < a.Length ==> a[i-1]-1 <= a[i]\n ensures index < 0 ==> forall i :: 0 <= i < a.Length ==> a[i] != 0\n ensures 0 <= index ==> index < a.Length && a[index] == 0\n{\n index := 0;\n while index < a.Length\n decreases a.Length - index\n invariant 0 <= index\n invariant forall k :: 0 <= k < index && k < a.Length ==> a[k] != 0\n {\n if a[index] == 0 { return; }\n SkippingLemma(a, index);\n index := index + a[index];\n }\n index := -1;\n}\n\n", "hints_removed": "lemma SkippingLemma(a : array, j : int)\n requires a != null\n requires forall i :: 0 <= i < a.Length ==> 0 <= a[i]\n requires forall i :: 0 < i < a.Length ==> a[i-1]-1 <= a[i]\n requires 0 <= j < a.Length\n ensures forall k :: j <= k < j + a[j] && k < a.Length ==> a[k] != 0\n{\n var i := j;\n while i < j + a[j] && i < a.Length\n {\n i := i + 1;\n }\n}\nmethod FindZero(a: array) returns (index: int)\n requires a != null\n requires forall i :: 0 <= i < a.Length ==> 0 <= a[i]\n requires forall i :: 0 < i < a.Length ==> a[i-1]-1 <= a[i]\n ensures index < 0 ==> forall i :: 0 <= i < a.Length ==> a[i] != 0\n ensures 0 <= index ==> index < a.Length && a[index] == 0\n{\n index := 0;\n while index < a.Length\n {\n if a[index] == 0 { return; }\n SkippingLemma(a, index);\n index := index + a[index];\n }\n index := -1;\n}\n\n" }, { "test_ID": "144", "test_file": "Dafny_Programs_tmp_tmp99966ew4_mymax.dfy", "ground_truth": "method Max(a: int, b:int) returns (c: int)\n ensures c >= a && c>= b\n{\n if (a < b)\n { c := b; }\n else\n { c := a; }\n assert a <= c && b <= c;\n} \n\nmethod Testing()\n{\n var v := Max(2, 3);\n assert v >= 3;\n}\n\n", "hints_removed": "method Max(a: int, b:int) returns (c: int)\n ensures c >= a && c>= b\n{\n if (a < b)\n { c := b; }\n else\n { c := a; }\n} \n\nmethod Testing()\n{\n var v := Max(2, 3);\n}\n\n" }, { "test_ID": "145", "test_file": "Dafny_Programs_tmp_tmp99966ew4_trig.dfy", "ground_truth": "predicate P(x: int)\n\npredicate Q(x: int)\n\nmethod test()\n requires forall x {:trigger P(x)} :: P(x) && Q(x)\n ensures Q(0)\n{\n assert P(0);\n}\n", "hints_removed": "predicate P(x: int)\n\npredicate Q(x: int)\n\nmethod test()\n requires forall x {:trigger P(x)} :: P(x) && Q(x)\n ensures Q(0)\n{\n}\n" }, { "test_ID": "146", "test_file": "Dafny_Verify_tmp_tmphq7j0row_AI_agent_validation_examples.dfy", "ground_truth": "function Power(n: nat): nat {\n if n == 0 then 1 else 2 * Power(n - 1)\n}\n\nmethod ComputePower(N: int) returns (y: nat) requires N >= 0\n ensures y == Power(N)\n{\n y := 1;\n var x := 0; \n while x != N\n invariant 0 <= x <= N \n invariant y == Power(x) \n decreases N - x\n {\n x, y := x + 1, y + y;\n } \n}\n\n\n// Original davinci-003 completion:\n// method ComputePower1(N: int) returns (y: nat) requires N >= 0\n// ensures y == Power(N)\n// {\n// y := 1;\n// var x := 0; \n// while x != N\n// decreases N - x\n// invariant 0 <= x <= N\n// invariant y == Power(x)\n// {\n// x, y := x + 1, y + y;\n// }\n// }\n\n\n\n// Fine_tuned davinci-003 completion:\n// method ComputePower1(N: int) returns (y: nat) requires N >= 0\n// ensures y == Power(N)\n// {\n// y := 1;\n// var x := 0; \n// while x != N\n// decreases N - x\n// invariant 0 <= x <= N\n// invariant y == Power(x)\n// {\n// x, y := x + 1, y + y;\n// }\n// }\n\nmethod Max(a: array) returns (m: int)\n ensures forall i :: 0 <= i < a.Length ==> a[i] <= m\n ensures (m == 0 && a.Length == 0) || exists i :: 0 <= i < a.Length && m == a[i] \n{\n m := 0;\n var n := 0;\n while n != a.Length\n invariant 0 <= n <= a.Length\n invariant forall i :: 0 <= i < n ==> a[i] <= m\n invariant (m == 0 && n == 0) || exists i :: 0 <= i < n && m == a[i]\n {\n if m < a[n] {\n m := a[n]; \n }\n n := n + 1; \n }\n}\n\n// Original davinci-003 completion:\n// method Max(a: array) returns (m: int)\n// requires a.Length > 0\n// ensures forall i :: 0 <= i < a.Length ==> a[i] <= m\n// ensures exists i :: 0 <= i < a.Length && m == a[i] \n// {\n// m := a[0];\n// var n := 1;\n// while n != a.Length\n// {\n// if m < a[n] {\n// m := a[n]; \n// }\n// n := n + 1; \n// // Loop invariant: 0 <= n <= a.Length && forall i :: 0 <= i < n ==> a[i] <= m\n// }\n// }\n\n// Fine_tuned davinci-003 completion:\n// method Max1(a: array) returns (m: int)\n// ensures forall i :: 0 <= i < a.Length ==> a[i] <= m\n// ensures (m == 0 && a.Length == 0) || exists i :: 0 <= i < a.Length && m == a[i]\n// {\n// m := 0;\n// var n := 0;\n// while n != a.Length\n// invariant 0 <= n <= a.Length\n// invariant forall i :: 0 <= i < n ==> a[i] <= m\n// {\n// if m < a[n] {\n// m := a[n]; \n// }\n// n := n + 1; \n// }\n// }\n\nmethod Cube(n: nat) returns (c: nat) \n ensures c == n * n * n\n{\n c := 0;\n var i := 0;\n var k := 1;\n var m := 6;\n while i != n\n invariant 0 <= i <= n \n invariant c == i * i * i \n invariant k == 3*i*i + 3*i + 1\n invariant m == 6 * i + 6\n {\n c, k, m := c + k, k + m, m + 6; \n i := i + 1;\n }\n}\n\n// Original davinci-003 completion:\n// method Cube(n: nat) returns (c: nat) \n// ensures c == n * n * n\n// {\n// c := 0;\n// var i := 0;\n// var k := 1;\n// var m := 6;\n// // Loop invariant: c = i^3\n// while i != n\n// {\n// c, k, m := c + k, k + m, m + 6; \n// i := i + 1;\n// }\n// }\n\n// Fine_tuned davinci-003 completion:\n// method Cube1(n: nat) returns (c: nat) \n// ensures c == n * n * n\n// {\n// c := 0;\n// var i := 0;\n// var k := 1;\n// var m := 6;\n// while i != n\n// invariant 0 <= i <= n\n// invariant c == i * k * m\n// {\n// c, k, m := c + k, k + m, m + 6; \n// i := i + 1;\n// }\n// }\n\n\n\nmethod IncrementMatrix(a: array2)\n modifies a\n ensures forall i, j :: 0 <= i < a.Length0 && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1\n{\n var m := 0;\n while m != a.Length0\n invariant 0 <= m <= a.Length0\n invariant forall i, j :: 0 <= i < m && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1 \n invariant forall i, j :: m <= i < a.Length0 && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j])\n {\n var n := 0;\n while n != a.Length1\n invariant 0 <= n <= a.Length1\n invariant forall i, j :: 0 <= i < m && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1 \n invariant forall i, j :: m < i < a.Length0 && 0 <= j < a.Length1==> a[i,j] == old(a[i,j]) \n invariant forall j :: 0 <= j < n ==> a[m,j] == old(a[m,j])+1\n invariant forall j :: n <= j < a.Length1 ==> a[m,j] == old(a[m,j])\n {\n a[m,n] := a[m,n] + 1;\n n := n + 1; \n }\n m := m + 1; \n }\n}\n\n// Original davinci-003 completion:\n// method IncrementMatrix(a: array2)\n// modifies a\n// ensures forall i, j :: 0 <= i < a.Length0 && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1\n// {\n// var m := 0;\n// while m != a.Length0\n// {\n// var n := 0;\n// while n != a.Length1\n// {\n// // Loop invariant: forall i, j :: 0 <= i < m && 0 <= j < n ==> a[i,j] == old(a[i,j]) + 1\n// a[m,n] := a[m,n] + 1;\n// n := n + 1; \n// }\n// m := m + 1; \n// }\n// }\n\n// Fine_tuned davinci-003 completion:\n// method IncrementMatrix1(a: array2)\n// modifies a\n// ensures forall i, j :: 0 <= i < a.Length0 && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1\n// {\n// var m := 0;\n// while m != a.Length0\n// invariant 0 <= m <= a.Length0 && 0 <= j < a.Length1 <= a.Length2\n// invariant forall i, j :: 0 <= i < m && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1\n// {\n// var n := 0;\n// while n != a.Length1\n// invariant 0 <= n <= a.Length2\n// invariant forall i, j :: 0 <= i < m && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1\n// {\n// a[m,n] := a[m,n] + 1;\n// n := n + 1; \n// }\n// m := m + 1; \n// }\n// }\n\nmethod CopyMatrix(src: array2, dst: array2)\n requires src.Length0 == dst.Length0 && src.Length1 == dst.Length1\n modifies dst\n ensures forall i, j :: 0 <= i < src.Length0 && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j]) \n{\n var m := 0;\n while m != src.Length0\n invariant 0 <= m <= src.Length0\n invariant forall i, j :: 0 <= i < m && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j]) \n invariant forall i, j :: 0 <= i < src.Length0 && 0 <= j < src.Length1 ==> src[i,j] == old(src[i,j])\n {\n var n := 0;\n while n != src.Length1\n invariant 0 <= n <= src.Length1 \n invariant forall i, j :: 0 <= i < m && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j]) \n invariant forall i, j :: 0 <= i < src.Length0 && 0 <= j < src.Length1 ==> src[i,j] == old(src[i,j])\n invariant forall j :: 0 <= j < n ==> dst[m,j] == old(src[m,j])\n {\n dst[m,n] := src[m,n]; n := n + 1;\n }\n m := m + 1; \n }\n}\n\n// Original davinci-003 completion:\n// method CopyMatrix(src: array2, dst: array2)\n// requires src.Length0 == dst.Length0 && src.Length1 == dst.Length1\n// modifies dst\n// ensures forall i, j :: 0 <= i < src.Length0 && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j]) \n// {\n// var m := 0;\n// while m != src.Length0\n// {\n// var n := 0;\n// while n != src.Length1\n// {\n// dst[m,n] := src[m,n]; \n// n := n + 1;\n// // Loop invariant: forall i, j :: 0 <= i < m && 0 <= j < n ==> dst[i,j] == old(src[i,j])\n// }\n// m := m + 1; \n// }\n// }\n\n// Fine_tuned davinci-003 completion:\n// method CopyMatrix1(src: array2, dst: array2)\n// requires src.Length0 == dst.Length0 && src.Length1 == dst.Length1\n// modifies dst\n// ensures forall i, j :: 0 <= i < src.Length0 && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j])\n// var m := 0;\n// while m != src.Length0\n// invariant 0 <= m <= src.Length0\n// invariant forall i, j :: 0 <= i < m && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j])\n// {\n// var n := 0;\n// while n != src.Length1\n// invariant 0 <= n <= src.Length1\n// {\n// dst[m,n] := src[m,n]; n := n + 1;\n// }\n// m := m + 1; \n// }\n\n\n\n\nmethod DoubleArray(src: array, dst: array)\n requires src.Length == dst.Length\n modifies dst\n ensures forall i :: 0 <= i < src.Length ==> dst[i] == 2 * old(src[i])\n{\n var n := 0;\n while n != src.Length\n invariant 0 <= n <= src.Length\n invariant forall i :: 0 <= i < n ==> dst[i] == 2 * old(src[i]) \n invariant forall i :: n <= i < src.Length ==> src[i] == old(src[i])\n {\n dst[n] := 2 * src[n]; n := n + 1;\n } \n}\n\n// Original davinci-003 completion:\n// method DoubleArray(src: array, dst: array)\n// requires src.Length == dst.Length\n// modifies dst\n// ensures forall i :: 0 <= i < src.Length ==> dst[i] == 2 * old(src[i])\n// {\n// var n := 0;\n// var i : int := 0;\n// while n != src.Length\n// {\n// dst[n] := 2 * src[n];\n// n := n + 1;\n// i := i + 1;\n// } \n// assert i == src.Length;\n// }\n\n// Fine_tuned davinci-003 completion:\n// method DoubleArray1(src: array, dst: array)\n// requires src.Length == dst.Length\n// modifies dst\n// ensures forall i :: 0 <= i < src.Length ==> dst[i] == 2 * old(src[i])\n// {\n// var n := 0;\n// while n != src.Length\n// invariant 0 <= n <= src.Length\n// invariant forall i :: 0 <= i < n ==> dst[i] == 2 * old(src[i])\n// {\n// dst[n] := 2 * src[n]; n := n + 1;\n// }\n// }\n\nmethod RotateLeft(a: array)\n requires a.Length > 0\n modifies a\n ensures forall i :: 0 <= i < a.Length - 1 ==> a[i] == old(a[(i+1)]) \n ensures a[a.Length -1] == old(a[0])\n{\n var n := 0;\n while n != a.Length - 1\n invariant 0 <= n <= a.Length - 1\n invariant forall i :: 0 <= i < n ==> a[i] == old(a[i+1]) \n invariant a[n] == old(a[0])\n invariant forall i :: n < i <= a.Length-1 ==> a[i] == old(a[i])\n {\n a[n], a[n+1] := a[n+1], a[n];\n n := n + 1; \n }\n}\n\n// Original davinci-003 completion:\n// method RotateLeft(a: array)\n// requires a.Length > 0\n// modifies a\n// ensures forall i :: 0 <= i < a.Length - 1 ==> a[i] == old(a[(i+1)]) \n// ensures a[a.Length -1] == old(a[0])\n// {\n// var n := 0;\n// // loop invariant: forall i :: 0 <= i < n ==> a[i] == old(a[(i+1)])\n// while n != a.Length - 1\n// {\n// a[n], a[n+1] := a[n+1], a[n];\n// n := n + 1; \n// }\n// }\n\n// Fine_tuned davinci-003 completion:\n// method RotateLeft1(a: array)\n// requires a.Length > 0\n// modifies a\n// ensures forall i :: 0 <= i < a.Length - 1 ==> a[i] == old(a[(i+1)])\n// ensures a[a.Length -1] == old(a[0])\n// {\n// var n := 0;\n// while n != a.Length - 1\n// invariant 0 <= n <= a.Length - 1\n// invariant forall i :: 0 <= i < n ==> a[i] == old(a[(i+1)])\n// invariant forall i :: 0 <= i < a.Length - 1 ==> a[i] == old(a[(i+1)])\n// {\n// a[n], a[n+1] := a[n+1], a[n];\n// n := n + 1;\n// }\n// }\n\nmethod RotateRight(a: array)\n requires a.Length > 0\n modifies a\n ensures forall i :: 1<= i < a.Length ==> a[i] == old(a[(i-1)]) \n ensures a[0] == old(a[a.Length-1])\n{\n var n := 1;\n while n != a.Length\n invariant 1 <= n <= a.Length\n invariant forall i :: 1 <= i < n ==> a[i] == old(a[i-1]) \n invariant a[0] == old(a[n-1])\n invariant forall i :: n <= i <= a.Length-1 ==> a[i] == old(a[i])\n {\n a[0], a[n] := a[n], a[0]; n := n + 1;\n } \n}\n\n// Original davinci-003 completion:\n// method RotateRight(a: array)\n// requires a.Length > 0\n// modifies a\n// ensures forall i :: 1<= i < a.Length ==> a[i] == old(a[(i-1)]) \n// ensures a[0] == old(a[a.Length-1])\n// {\n// var n := 1;\n// var temp := a[0];\n// while n != a.Length\n// {\n// a[0] := a[n];\n// a[n] := temp;\n// temp := a[0];\n// n := n + 1;\n// // loop invariant:\n// // forall k :: 0 <= k < n ==> a[k] == old(a[k+1])\n// } \n// }\n\n// Fine_tuned davinci-003 completion:\n// method RotateRight1(a: array)\n// requires a.Length > 0\n// modifies a\n// ensures forall i :: 1<= i < a.Length ==> a[i] == old(a[(i-1)])\n// ensures a[0] == old(a[a.Length-1])\n// {\n// var n := 1;\n// while n != a.Length\n// invariant 1 <= n <= a.Length\n// invariant forall i :: 1<= i < n ==> a[i] == old(a[(i-1)])\n// invariant forall i :: 1<= i < a.Length ==> a[i] == old(a[i])\n// {\n// a[0], a[n] := a[n], a[0]; n := n + 1;\n// }\n// }\n", "hints_removed": "function Power(n: nat): nat {\n if n == 0 then 1 else 2 * Power(n - 1)\n}\n\nmethod ComputePower(N: int) returns (y: nat) requires N >= 0\n ensures y == Power(N)\n{\n y := 1;\n var x := 0; \n while x != N\n {\n x, y := x + 1, y + y;\n } \n}\n\n\n// Original davinci-003 completion:\n// method ComputePower1(N: int) returns (y: nat) requires N >= 0\n// ensures y == Power(N)\n// {\n// y := 1;\n// var x := 0; \n// while x != N\n// decreases N - x\n// invariant 0 <= x <= N\n// invariant y == Power(x)\n// {\n// x, y := x + 1, y + y;\n// }\n// }\n\n\n\n// Fine_tuned davinci-003 completion:\n// method ComputePower1(N: int) returns (y: nat) requires N >= 0\n// ensures y == Power(N)\n// {\n// y := 1;\n// var x := 0; \n// while x != N\n// decreases N - x\n// invariant 0 <= x <= N\n// invariant y == Power(x)\n// {\n// x, y := x + 1, y + y;\n// }\n// }\n\nmethod Max(a: array) returns (m: int)\n ensures forall i :: 0 <= i < a.Length ==> a[i] <= m\n ensures (m == 0 && a.Length == 0) || exists i :: 0 <= i < a.Length && m == a[i] \n{\n m := 0;\n var n := 0;\n while n != a.Length\n {\n if m < a[n] {\n m := a[n]; \n }\n n := n + 1; \n }\n}\n\n// Original davinci-003 completion:\n// method Max(a: array) returns (m: int)\n// requires a.Length > 0\n// ensures forall i :: 0 <= i < a.Length ==> a[i] <= m\n// ensures exists i :: 0 <= i < a.Length && m == a[i] \n// {\n// m := a[0];\n// var n := 1;\n// while n != a.Length\n// {\n// if m < a[n] {\n// m := a[n]; \n// }\n// n := n + 1; \n// // Loop invariant: 0 <= n <= a.Length && forall i :: 0 <= i < n ==> a[i] <= m\n// }\n// }\n\n// Fine_tuned davinci-003 completion:\n// method Max1(a: array) returns (m: int)\n// ensures forall i :: 0 <= i < a.Length ==> a[i] <= m\n// ensures (m == 0 && a.Length == 0) || exists i :: 0 <= i < a.Length && m == a[i]\n// {\n// m := 0;\n// var n := 0;\n// while n != a.Length\n// invariant 0 <= n <= a.Length\n// invariant forall i :: 0 <= i < n ==> a[i] <= m\n// {\n// if m < a[n] {\n// m := a[n]; \n// }\n// n := n + 1; \n// }\n// }\n\nmethod Cube(n: nat) returns (c: nat) \n ensures c == n * n * n\n{\n c := 0;\n var i := 0;\n var k := 1;\n var m := 6;\n while i != n\n {\n c, k, m := c + k, k + m, m + 6; \n i := i + 1;\n }\n}\n\n// Original davinci-003 completion:\n// method Cube(n: nat) returns (c: nat) \n// ensures c == n * n * n\n// {\n// c := 0;\n// var i := 0;\n// var k := 1;\n// var m := 6;\n// // Loop invariant: c = i^3\n// while i != n\n// {\n// c, k, m := c + k, k + m, m + 6; \n// i := i + 1;\n// }\n// }\n\n// Fine_tuned davinci-003 completion:\n// method Cube1(n: nat) returns (c: nat) \n// ensures c == n * n * n\n// {\n// c := 0;\n// var i := 0;\n// var k := 1;\n// var m := 6;\n// while i != n\n// invariant 0 <= i <= n\n// invariant c == i * k * m\n// {\n// c, k, m := c + k, k + m, m + 6; \n// i := i + 1;\n// }\n// }\n\n\n\nmethod IncrementMatrix(a: array2)\n modifies a\n ensures forall i, j :: 0 <= i < a.Length0 && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1\n{\n var m := 0;\n while m != a.Length0\n {\n var n := 0;\n while n != a.Length1\n {\n a[m,n] := a[m,n] + 1;\n n := n + 1; \n }\n m := m + 1; \n }\n}\n\n// Original davinci-003 completion:\n// method IncrementMatrix(a: array2)\n// modifies a\n// ensures forall i, j :: 0 <= i < a.Length0 && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1\n// {\n// var m := 0;\n// while m != a.Length0\n// {\n// var n := 0;\n// while n != a.Length1\n// {\n// // Loop invariant: forall i, j :: 0 <= i < m && 0 <= j < n ==> a[i,j] == old(a[i,j]) + 1\n// a[m,n] := a[m,n] + 1;\n// n := n + 1; \n// }\n// m := m + 1; \n// }\n// }\n\n// Fine_tuned davinci-003 completion:\n// method IncrementMatrix1(a: array2)\n// modifies a\n// ensures forall i, j :: 0 <= i < a.Length0 && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1\n// {\n// var m := 0;\n// while m != a.Length0\n// invariant 0 <= m <= a.Length0 && 0 <= j < a.Length1 <= a.Length2\n// invariant forall i, j :: 0 <= i < m && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1\n// {\n// var n := 0;\n// while n != a.Length1\n// invariant 0 <= n <= a.Length2\n// invariant forall i, j :: 0 <= i < m && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1\n// {\n// a[m,n] := a[m,n] + 1;\n// n := n + 1; \n// }\n// m := m + 1; \n// }\n// }\n\nmethod CopyMatrix(src: array2, dst: array2)\n requires src.Length0 == dst.Length0 && src.Length1 == dst.Length1\n modifies dst\n ensures forall i, j :: 0 <= i < src.Length0 && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j]) \n{\n var m := 0;\n while m != src.Length0\n {\n var n := 0;\n while n != src.Length1\n {\n dst[m,n] := src[m,n]; n := n + 1;\n }\n m := m + 1; \n }\n}\n\n// Original davinci-003 completion:\n// method CopyMatrix(src: array2, dst: array2)\n// requires src.Length0 == dst.Length0 && src.Length1 == dst.Length1\n// modifies dst\n// ensures forall i, j :: 0 <= i < src.Length0 && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j]) \n// {\n// var m := 0;\n// while m != src.Length0\n// {\n// var n := 0;\n// while n != src.Length1\n// {\n// dst[m,n] := src[m,n]; \n// n := n + 1;\n// // Loop invariant: forall i, j :: 0 <= i < m && 0 <= j < n ==> dst[i,j] == old(src[i,j])\n// }\n// m := m + 1; \n// }\n// }\n\n// Fine_tuned davinci-003 completion:\n// method CopyMatrix1(src: array2, dst: array2)\n// requires src.Length0 == dst.Length0 && src.Length1 == dst.Length1\n// modifies dst\n// ensures forall i, j :: 0 <= i < src.Length0 && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j])\n// var m := 0;\n// while m != src.Length0\n// invariant 0 <= m <= src.Length0\n// invariant forall i, j :: 0 <= i < m && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j])\n// {\n// var n := 0;\n// while n != src.Length1\n// invariant 0 <= n <= src.Length1\n// {\n// dst[m,n] := src[m,n]; n := n + 1;\n// }\n// m := m + 1; \n// }\n\n\n\n\nmethod DoubleArray(src: array, dst: array)\n requires src.Length == dst.Length\n modifies dst\n ensures forall i :: 0 <= i < src.Length ==> dst[i] == 2 * old(src[i])\n{\n var n := 0;\n while n != src.Length\n {\n dst[n] := 2 * src[n]; n := n + 1;\n } \n}\n\n// Original davinci-003 completion:\n// method DoubleArray(src: array, dst: array)\n// requires src.Length == dst.Length\n// modifies dst\n// ensures forall i :: 0 <= i < src.Length ==> dst[i] == 2 * old(src[i])\n// {\n// var n := 0;\n// var i : int := 0;\n// while n != src.Length\n// {\n// dst[n] := 2 * src[n];\n// n := n + 1;\n// i := i + 1;\n// } \n// assert i == src.Length;\n// }\n\n// Fine_tuned davinci-003 completion:\n// method DoubleArray1(src: array, dst: array)\n// requires src.Length == dst.Length\n// modifies dst\n// ensures forall i :: 0 <= i < src.Length ==> dst[i] == 2 * old(src[i])\n// {\n// var n := 0;\n// while n != src.Length\n// invariant 0 <= n <= src.Length\n// invariant forall i :: 0 <= i < n ==> dst[i] == 2 * old(src[i])\n// {\n// dst[n] := 2 * src[n]; n := n + 1;\n// }\n// }\n\nmethod RotateLeft(a: array)\n requires a.Length > 0\n modifies a\n ensures forall i :: 0 <= i < a.Length - 1 ==> a[i] == old(a[(i+1)]) \n ensures a[a.Length -1] == old(a[0])\n{\n var n := 0;\n while n != a.Length - 1\n {\n a[n], a[n+1] := a[n+1], a[n];\n n := n + 1; \n }\n}\n\n// Original davinci-003 completion:\n// method RotateLeft(a: array)\n// requires a.Length > 0\n// modifies a\n// ensures forall i :: 0 <= i < a.Length - 1 ==> a[i] == old(a[(i+1)]) \n// ensures a[a.Length -1] == old(a[0])\n// {\n// var n := 0;\n// // loop invariant: forall i :: 0 <= i < n ==> a[i] == old(a[(i+1)])\n// while n != a.Length - 1\n// {\n// a[n], a[n+1] := a[n+1], a[n];\n// n := n + 1; \n// }\n// }\n\n// Fine_tuned davinci-003 completion:\n// method RotateLeft1(a: array)\n// requires a.Length > 0\n// modifies a\n// ensures forall i :: 0 <= i < a.Length - 1 ==> a[i] == old(a[(i+1)])\n// ensures a[a.Length -1] == old(a[0])\n// {\n// var n := 0;\n// while n != a.Length - 1\n// invariant 0 <= n <= a.Length - 1\n// invariant forall i :: 0 <= i < n ==> a[i] == old(a[(i+1)])\n// invariant forall i :: 0 <= i < a.Length - 1 ==> a[i] == old(a[(i+1)])\n// {\n// a[n], a[n+1] := a[n+1], a[n];\n// n := n + 1;\n// }\n// }\n\nmethod RotateRight(a: array)\n requires a.Length > 0\n modifies a\n ensures forall i :: 1<= i < a.Length ==> a[i] == old(a[(i-1)]) \n ensures a[0] == old(a[a.Length-1])\n{\n var n := 1;\n while n != a.Length\n {\n a[0], a[n] := a[n], a[0]; n := n + 1;\n } \n}\n\n// Original davinci-003 completion:\n// method RotateRight(a: array)\n// requires a.Length > 0\n// modifies a\n// ensures forall i :: 1<= i < a.Length ==> a[i] == old(a[(i-1)]) \n// ensures a[0] == old(a[a.Length-1])\n// {\n// var n := 1;\n// var temp := a[0];\n// while n != a.Length\n// {\n// a[0] := a[n];\n// a[n] := temp;\n// temp := a[0];\n// n := n + 1;\n// // loop invariant:\n// // forall k :: 0 <= k < n ==> a[k] == old(a[k+1])\n// } \n// }\n\n// Fine_tuned davinci-003 completion:\n// method RotateRight1(a: array)\n// requires a.Length > 0\n// modifies a\n// ensures forall i :: 1<= i < a.Length ==> a[i] == old(a[(i-1)])\n// ensures a[0] == old(a[a.Length-1])\n// {\n// var n := 1;\n// while n != a.Length\n// invariant 1 <= n <= a.Length\n// invariant forall i :: 1<= i < n ==> a[i] == old(a[(i-1)])\n// invariant forall i :: 1<= i < a.Length ==> a[i] == old(a[i])\n// {\n// a[0], a[n] := a[n], a[0]; n := n + 1;\n// }\n// }\n" }, { "test_ID": "147", "test_file": "Dafny_Verify_tmp_tmphq7j0row_AI_agent_verify_examples_ComputePower.dfy", "ground_truth": "function Power(n: nat): nat {\n if n == 0 then 1 else 2 * Power(n - 1)\n}\n\nmethod ComputePower(N: int) returns (y: nat) requires N >= 0\n ensures y == Power(N)\n{\n y := 1;\n var x := 0; \n while x != N\n invariant 0 <= x <= N \n invariant y == Power(x) \n decreases N - x\n {\n x, y := x + 1, y + y;\n } \n}\n", "hints_removed": "function Power(n: nat): nat {\n if n == 0 then 1 else 2 * Power(n - 1)\n}\n\nmethod ComputePower(N: int) returns (y: nat) requires N >= 0\n ensures y == Power(N)\n{\n y := 1;\n var x := 0; \n while x != N\n {\n x, y := x + 1, y + y;\n } \n}\n" }, { "test_ID": "148", "test_file": "Dafny_Verify_tmp_tmphq7j0row_AI_agent_verify_examples_CopyMatrix.dfy", "ground_truth": "method CopyMatrix(src: array2, dst: array2)\n requires src.Length0 == dst.Length0 && src.Length1 == dst.Length1\n modifies dst\n ensures forall i, j :: 0 <= i < src.Length0 && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j]) \n{\n var m := 0;\n while m != src.Length0\n invariant 0 <= m <= src.Length0\n invariant forall i, j :: 0 <= i < m && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j]) \n invariant forall i, j :: 0 <= i < src.Length0 && 0 <= j < src.Length1 ==> src[i,j] == old(src[i,j])\n {\n var n := 0;\n while n != src.Length1\n invariant 0 <= n <= src.Length1 \n invariant forall i, j :: 0 <= i < m && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j]) \n invariant forall i, j :: 0 <= i < src.Length0 && 0 <= j < src.Length1 ==> src[i,j] == old(src[i,j])\n invariant forall j :: 0 <= j < n ==> dst[m,j] == old(src[m,j])\n {\n dst[m,n] := src[m,n]; n := n + 1;\n }\n m := m + 1; \n }\n}\n", "hints_removed": "method CopyMatrix(src: array2, dst: array2)\n requires src.Length0 == dst.Length0 && src.Length1 == dst.Length1\n modifies dst\n ensures forall i, j :: 0 <= i < src.Length0 && 0 <= j < src.Length1 ==> dst[i,j] == old(src[i,j]) \n{\n var m := 0;\n while m != src.Length0\n {\n var n := 0;\n while n != src.Length1\n {\n dst[m,n] := src[m,n]; n := n + 1;\n }\n m := m + 1; \n }\n}\n" }, { "test_ID": "149", "test_file": "Dafny_Verify_tmp_tmphq7j0row_AI_agent_verify_examples_Cube.dfy", "ground_truth": "method Cube(n: nat) returns (c: nat) \n ensures c == n * n * n\n{\n c := 0;\n var i := 0;\n var k := 1;\n var m := 6;\n while i != n\n invariant 0 <= i <= n \n invariant c == i * i * i \n invariant k == 3*i*i + 3*i + 1\n invariant m == 6 * i + 6\n {\n c, k, m := c + k, k + m, m + 6; \n i := i + 1;\n }\n}\n", "hints_removed": "method Cube(n: nat) returns (c: nat) \n ensures c == n * n * n\n{\n c := 0;\n var i := 0;\n var k := 1;\n var m := 6;\n while i != n\n {\n c, k, m := c + k, k + m, m + 6; \n i := i + 1;\n }\n}\n" }, { "test_ID": "150", "test_file": "Dafny_Verify_tmp_tmphq7j0row_AI_agent_verify_examples_DoubleArray.dfy", "ground_truth": "method DoubleArray(src: array, dst: array)\n requires src.Length == dst.Length\n modifies dst\n ensures forall i :: 0 <= i < src.Length ==> dst[i] == 2 * old(src[i])\n{\n var n := 0;\n while n != src.Length\n invariant 0 <= n <= src.Length\n invariant forall i :: 0 <= i < n ==> dst[i] == 2 * old(src[i]) \n invariant forall i :: n <= i < src.Length ==> src[i] == old(src[i])\n {\n dst[n] := 2 * src[n]; n := n + 1;\n } \n}\n", "hints_removed": "method DoubleArray(src: array, dst: array)\n requires src.Length == dst.Length\n modifies dst\n ensures forall i :: 0 <= i < src.Length ==> dst[i] == 2 * old(src[i])\n{\n var n := 0;\n while n != src.Length\n {\n dst[n] := 2 * src[n]; n := n + 1;\n } \n}\n" }, { "test_ID": "151", "test_file": "Dafny_Verify_tmp_tmphq7j0row_AI_agent_verify_examples_IncrementMatrix.dfy", "ground_truth": "method IncrementMatrix(a: array2)\n modifies a\n ensures forall i, j :: 0 <= i < a.Length0 && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1\n{\n var m := 0;\n while m != a.Length0\n invariant 0 <= m <= a.Length0\n invariant forall i, j :: 0 <= i < m && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1 \n invariant forall i, j :: m <= i < a.Length0 && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j])\n {\n var n := 0;\n while n != a.Length1\n invariant 0 <= n <= a.Length1\n invariant forall i, j :: 0 <= i < m && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1 \n invariant forall i, j :: m < i < a.Length0 && 0 <= j < a.Length1==> a[i,j] == old(a[i,j]) \n invariant forall j :: 0 <= j < n ==> a[m,j] == old(a[m,j])+1\n invariant forall j :: n <= j < a.Length1 ==> a[m,j] == old(a[m,j])\n {\n a[m,n] := a[m,n] + 1;\n n := n + 1; \n }\n m := m + 1; \n }\n}\n", "hints_removed": "method IncrementMatrix(a: array2)\n modifies a\n ensures forall i, j :: 0 <= i < a.Length0 && 0 <= j < a.Length1 ==> a[i,j] == old(a[i,j]) + 1\n{\n var m := 0;\n while m != a.Length0\n {\n var n := 0;\n while n != a.Length1\n {\n a[m,n] := a[m,n] + 1;\n n := n + 1; \n }\n m := m + 1; \n }\n}\n" }, { "test_ID": "152", "test_file": "Dafny_Verify_tmp_tmphq7j0row_AI_agent_verify_examples_RotateRight.dfy", "ground_truth": "method RotateRight(a: array)\n requires a.Length > 0\n modifies a\n ensures forall i :: 1<= i < a.Length ==> a[i] == old(a[(i-1)]) \n ensures a[0] == old(a[a.Length-1])\n{\n var n := 1;\n while n != a.Length\n invariant 1 <= n <= a.Length\n invariant forall i :: 1 <= i < n ==> a[i] == old(a[i-1]) \n invariant a[0] == old(a[n-1])\n invariant forall i :: n <= i <= a.Length-1 ==> a[i] == old(a[i])\n {\n a[0], a[n] := a[n], a[0]; n := n + 1;\n } \n}\n", "hints_removed": "method RotateRight(a: array)\n requires a.Length > 0\n modifies a\n ensures forall i :: 1<= i < a.Length ==> a[i] == old(a[(i-1)]) \n ensures a[0] == old(a[a.Length-1])\n{\n var n := 1;\n while n != a.Length\n {\n a[0], a[n] := a[n], a[0]; n := n + 1;\n } \n}\n" }, { "test_ID": "153", "test_file": "Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_50_examples_28.dfy", "ground_truth": "method main(x: int, y: int) returns (x_out: int, y_out: int, n: int)\nrequires x >= 0\nrequires y >= 0\nrequires x == y\nensures y_out == n\n{\n x_out := x;\n y_out := y;\n n := 0;\n\n while (x_out != n)\n invariant x_out >= 0\n invariant x_out == y_out\n {\n x_out := x_out - 1;\n y_out := y_out - 1;\n }\n}\n", "hints_removed": "method main(x: int, y: int) returns (x_out: int, y_out: int, n: int)\nrequires x >= 0\nrequires y >= 0\nrequires x == y\nensures y_out == n\n{\n x_out := x;\n y_out := y;\n n := 0;\n\n while (x_out != n)\n {\n x_out := x_out - 1;\n y_out := y_out - 1;\n }\n}\n" }, { "test_ID": "154", "test_file": "Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_50_examples_37.dfy", "ground_truth": "method main(n: int) returns(x: int, m: int)\nrequires n > 0\nensures (n <= 0) || (0 <= m && m < n)\n{\n x := 0;\n m := 0;\n\n while(x < n)\n invariant 0 <= x <= n\n invariant 0 <= m < n\n {\n if(*)\n {\n m := x;\n }\n else{}\n x := x + 1;\n }\n}\n", "hints_removed": "method main(n: int) returns(x: int, m: int)\nrequires n > 0\nensures (n <= 0) || (0 <= m && m < n)\n{\n x := 0;\n m := 0;\n\n while(x < n)\n {\n if(*)\n {\n m := x;\n }\n else{}\n x := x + 1;\n }\n}\n" }, { "test_ID": "155", "test_file": "Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_50_examples_38.dfy", "ground_truth": "method main(n : int) returns (i: int, x: int, y:int)\nrequires n >= 0\nensures (i % 2 != 0) || (x == 2 * y)\n{\n i := 0;\n x := 0;\n y := 0;\n\n while (i < n)\n invariant 0 <= i <= n\n invariant x == i\n invariant y == i / 2\n {\n i := i + 1;\n x := x + 1;\n if (i % 2 == 0)\n {\n y := y + 1;\n }\n else\n {}\n }\n}\n", "hints_removed": "method main(n : int) returns (i: int, x: int, y:int)\nrequires n >= 0\nensures (i % 2 != 0) || (x == 2 * y)\n{\n i := 0;\n x := 0;\n y := 0;\n\n while (i < n)\n {\n i := i + 1;\n x := x + 1;\n if (i % 2 == 0)\n {\n y := y + 1;\n }\n else\n {}\n }\n}\n" }, { "test_ID": "156", "test_file": "Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_50_examples_41.dfy", "ground_truth": "method main(n: int, k: int) returns (i :int, j: int)\n requires n >= 0\n requires k == 1 || k >= 0\n ensures k + i + j >= 2 * n\n{\n i := 0;\n j := 0;\n while(i < n)\n invariant 0 <= i <= n\n invariant j == i * (i + 1) / 2\n {\n i := i + 1;\n j := j + i;\n }\n}\n", "hints_removed": "method main(n: int, k: int) returns (i :int, j: int)\n requires n >= 0\n requires k == 1 || k >= 0\n ensures k + i + j >= 2 * n\n{\n i := 0;\n j := 0;\n while(i < n)\n {\n i := i + 1;\n j := j + i;\n }\n}\n" }, { "test_ID": "157", "test_file": "Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_50_examples_BinarySearch.dfy", "ground_truth": "method BinarySearch(a: array, key: int) returns (n: int)\n requires forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j]\n ensures 0 <= n <= a.Length\n ensures forall i :: 0 <= i < n ==> a[i] < key\n ensures forall i :: n <= i < a.Length ==> key <= a[i]\n{\n var lo, hi := 0, a.Length;\n\n while lo < hi\n invariant 0 <= lo <= hi <= a.Length\n invariant forall i :: 0 <= i < lo ==> a[i] < key\n invariant forall i :: hi <= i < a.Length ==> key <= a[i]\n {\n var mid := (lo + hi) / 2;\n\n if a[mid] < key {\n lo := mid + 1;\n } else {\n hi := mid;\n }\n }\n\n n := lo;\n}\n\n", "hints_removed": "method BinarySearch(a: array, key: int) returns (n: int)\n requires forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j]\n ensures 0 <= n <= a.Length\n ensures forall i :: 0 <= i < n ==> a[i] < key\n ensures forall i :: n <= i < a.Length ==> key <= a[i]\n{\n var lo, hi := 0, a.Length;\n\n while lo < hi\n {\n var mid := (lo + hi) / 2;\n\n if a[mid] < key {\n lo := mid + 1;\n } else {\n hi := mid;\n }\n }\n\n n := lo;\n}\n\n" }, { "test_ID": "158", "test_file": "Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_50_examples_SumArray.dfy", "ground_truth": "function Sum(arr: array, len: int): int\n reads arr\n requires arr.Length > 0 && 0 <= len <= arr.Length\n{\n if len == 0 then 0 else arr[len-1] + Sum(arr, len-1)\n}\n\nmethod SumArray(arr: array) returns (sum: int)\n requires arr.Length > 0\n ensures sum == Sum(arr, arr.Length)\n{\n sum := 0;\n var i := 0;\n while i < arr.Length\n invariant 0 <= i <= arr.Length\n invariant sum == Sum(arr, i)\n {\n sum := sum + arr[i];\n i := i + 1;\n }\n}\n", "hints_removed": "function Sum(arr: array, len: int): int\n reads arr\n requires arr.Length > 0 && 0 <= len <= arr.Length\n{\n if len == 0 then 0 else arr[len-1] + Sum(arr, len-1)\n}\n\nmethod SumArray(arr: array) returns (sum: int)\n requires arr.Length > 0\n ensures sum == Sum(arr, arr.Length)\n{\n sum := 0;\n var i := 0;\n while i < arr.Length\n {\n sum := sum + arr[i];\n i := i + 1;\n }\n}\n" }, { "test_ID": "159", "test_file": "Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_error_data_completion_06_n.dfy", "ground_truth": "method Main() returns (x: int, y: int)\n\tensures x == y;\n{\n\tx := 0;\n\ty := 0;\n\tvar w := 1;\n\tvar z := 0;\n\tvar turn := 0;\n\n\twhile(x != y)\n\tinvariant x == y ==> !(0 <= -z*2/2 && 1 <= -(w-1)*2/2) \n invariant !((x != y && x - y <= -1) || (x - y >= 1 && -z*2/2 <= 0 && (w-1)*2/2 <= 1))\n invariant !(w*2/2 <= 0 && ((x != y && (x - y <= -1 || x - y >= 1)) || 1 <= z*2/2))\n\n\t{\n\t\tif(turn == 0){\n\t\t\tturn := 1;\n\t\t}\n\n\t\tif(turn == 1){\n\t\t\tif(w % 2 == 1){\n\t\t\t\tx := x + 1;\n\t\t\t}\n\n\t\t\tif(z % 2 == 0){\n\t\t\t\ty := y + 1;\n\t\t\t}\n\n\t\t\tturn := 1;\n\t\t}\n\t\telse{\n\t\t\tif(turn == 2){\n\t\t\t\tz := z + y;\n\t\t\t\tw := z + 1;\n\n\t\t\t\tturn := 0;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\n", "hints_removed": "method Main() returns (x: int, y: int)\n\tensures x == y;\n{\n\tx := 0;\n\ty := 0;\n\tvar w := 1;\n\tvar z := 0;\n\tvar turn := 0;\n\n\twhile(x != y)\n\n\t{\n\t\tif(turn == 0){\n\t\t\tturn := 1;\n\t\t}\n\n\t\tif(turn == 1){\n\t\t\tif(w % 2 == 1){\n\t\t\t\tx := x + 1;\n\t\t\t}\n\n\t\t\tif(z % 2 == 0){\n\t\t\t\ty := y + 1;\n\t\t\t}\n\n\t\t\tturn := 1;\n\t\t}\n\t\telse{\n\t\t\tif(turn == 2){\n\t\t\t\tz := z + y;\n\t\t\t\tw := z + 1;\n\n\t\t\t\tturn := 0;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\n" }, { "test_ID": "160", "test_file": "Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_error_data_completion_07.dfy", "ground_truth": "method main(n: int) returns (a: int, b: int)\n requires n >= 0\n ensures a + b == 3 * n\n{\n var i: int := 0;\n a := 0;\n b := 0;\n\n while(i < n)\n invariant 0 <= i <= n\n invariant a + b == 3 * i\n {\n if(*)\n {\n a := a + 1;\n b := b + 2;\n }\n else\n {\n a := a + 2;\n b := b + 1;\n }\n\n i := i + 1;\n }\n}\n\n\n", "hints_removed": "method main(n: int) returns (a: int, b: int)\n requires n >= 0\n ensures a + b == 3 * n\n{\n var i: int := 0;\n a := 0;\n b := 0;\n\n while(i < n)\n {\n if(*)\n {\n a := a + 1;\n b := b + 2;\n }\n else\n {\n a := a + 2;\n b := b + 1;\n }\n\n i := i + 1;\n }\n}\n\n\n" }, { "test_ID": "161", "test_file": "Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_error_data_completion_11.dfy", "ground_truth": "method main(x :int) returns (j :int, i :int)\nrequires x > 0\nensures j == 2 * x\n{\n i := 0;\n j := 0;\n\n while i < x\n invariant 0 <= i <= x\n invariant j == 2 * i\n {\n j := j + 2;\n i := i + 1;\n }\n}\n", "hints_removed": "method main(x :int) returns (j :int, i :int)\nrequires x > 0\nensures j == 2 * x\n{\n i := 0;\n j := 0;\n\n while i < x\n {\n j := j + 2;\n i := i + 1;\n }\n}\n" }, { "test_ID": "162", "test_file": "Dafny_Verify_tmp_tmphq7j0row_Fine_Tune_Examples_normal_data_completion_MaxPerdV2.dfy", "ground_truth": "function contains(v: int, a: array, n: int): bool\nreads a\n requires n <= a.Length\n{\n exists j :: 0 <= j < n && a[j] == v\n}\n\nfunction upper_bound(v: int, a: array, n: int): bool\nreads a\n requires n <= a.Length\n{\n forall j :: 0 <= j < n ==> a[j] <= v\n}\n\nfunction is_max(m: int, a: array, n: int): bool\nreads a\n requires n <= a.Length\n{\n contains(m, a, n) && upper_bound(m, a, n)\n}\n\nmethod max(a: array, n: int) returns (max: int)\n requires 0 < n <= a.Length;\n ensures is_max(max, a, n);\n{\n var i: int := 1;\n\n max := a[0];\n\n while i < n\n\t\tinvariant i <= n;\n\t\tinvariant is_max (max, a, i);\n {\n if a[i] > max {\n max := a[i];\n }\n i := i + 1;\n }\n}\n\n", "hints_removed": "function contains(v: int, a: array, n: int): bool\nreads a\n requires n <= a.Length\n{\n exists j :: 0 <= j < n && a[j] == v\n}\n\nfunction upper_bound(v: int, a: array, n: int): bool\nreads a\n requires n <= a.Length\n{\n forall j :: 0 <= j < n ==> a[j] <= v\n}\n\nfunction is_max(m: int, a: array, n: int): bool\nreads a\n requires n <= a.Length\n{\n contains(m, a, n) && upper_bound(m, a, n)\n}\n\nmethod max(a: array, n: int) returns (max: int)\n requires 0 < n <= a.Length;\n ensures is_max(max, a, n);\n{\n var i: int := 1;\n\n max := a[0];\n\n while i < n\n {\n if a[i] > max {\n max := a[i];\n }\n i := i + 1;\n }\n}\n\n" }, { "test_ID": "163", "test_file": "Dafny_Verify_tmp_tmphq7j0row_Generated_Code_15.dfy", "ground_truth": "method main(n: int, k: int) returns (k_out: int)\n requires n > 0;\n\trequires k > n;\n\tensures k_out >= 0;\n{\n\tk_out := k;\n var j: int := 0;\n while(j < n)\n invariant 0 <= j <= n;\n invariant k_out == k - j;\n {\n j := j + 1;\n k_out := k_out - 1;\n }\n}\n", "hints_removed": "method main(n: int, k: int) returns (k_out: int)\n requires n > 0;\n\trequires k > n;\n\tensures k_out >= 0;\n{\n\tk_out := k;\n var j: int := 0;\n while(j < n)\n {\n j := j + 1;\n k_out := k_out - 1;\n }\n}\n" }, { "test_ID": "164", "test_file": "Dafny_Verify_tmp_tmphq7j0row_Generated_Code_ComputePower.dfy", "ground_truth": "function Power(n: nat): nat {\n if n == 0 then 1 else 2 * Power(n - 1)\n}\n\nmethod ComputePower(n: nat) returns (p: nat)\n ensures p == Power(n)\n{\n p := 1;\n var i := 0;\n while i != n\n invariant 0 <= i <= n && p == Power(i)\n {\n i := i + 1;\n p := p * 2;\n }\n}\n", "hints_removed": "function Power(n: nat): nat {\n if n == 0 then 1 else 2 * Power(n - 1)\n}\n\nmethod ComputePower(n: nat) returns (p: nat)\n ensures p == Power(n)\n{\n p := 1;\n var i := 0;\n while i != n\n {\n i := i + 1;\n p := p * 2;\n }\n}\n" }, { "test_ID": "165", "test_file": "Dafny_Verify_tmp_tmphq7j0row_Generated_Code_Count.dfy", "ground_truth": "function has_count(v: int, a: array, n: int): int\n reads a // This allows the function to read from array 'a'\n requires n >= 0 && n <= a.Length\n{\n if n == 0 then 0 else\n (if a[n-1] == v then has_count(v, a, n-1) + 1 else has_count(v, a, n-1))\n}\n\n\nmethod count (v: int, a: array, n: int) returns (r: int)\n requires n >= 0 && n <= a.Length;\n ensures has_count(v, a, n) == r;\n{\n var i: int;\n\n i := 0;\n r := 0;\n\n while (i < n)\n invariant 0 <= i <= n\n invariant r == has_count(v, a, i)\n {\n if (a[i] == v)\n {\n r := r + 1;\n }\n i := i + 1;\n }\n return r;\n}\n", "hints_removed": "function has_count(v: int, a: array, n: int): int\n reads a // This allows the function to read from array 'a'\n requires n >= 0 && n <= a.Length\n{\n if n == 0 then 0 else\n (if a[n-1] == v then has_count(v, a, n-1) + 1 else has_count(v, a, n-1))\n}\n\n\nmethod count (v: int, a: array, n: int) returns (r: int)\n requires n >= 0 && n <= a.Length;\n ensures has_count(v, a, n) == r;\n{\n var i: int;\n\n i := 0;\n r := 0;\n\n while (i < n)\n {\n if (a[i] == v)\n {\n r := r + 1;\n }\n i := i + 1;\n }\n return r;\n}\n" }, { "test_ID": "166", "test_file": "Dafny_Verify_tmp_tmphq7j0row_Generated_Code_LinearSearch.dfy", "ground_truth": "method LinearSearch(a: array, P: T -> bool) returns (n: int)\n ensures 0 <= n <= a.Length\n ensures n == a.Length || P(a[n])\n ensures forall i :: 0 <= i < n ==> !P(a[i])\n{\n n := 0;\n while n != a.Length\n invariant 0 <= n <= a.Length\n invariant forall i :: 0 <= i < n ==> !P(a[i])\n {\n if P(a[n]) {\n return;\n }\n n := n + 1;\n }\n}\n", "hints_removed": "method LinearSearch(a: array, P: T -> bool) returns (n: int)\n ensures 0 <= n <= a.Length\n ensures n == a.Length || P(a[n])\n ensures forall i :: 0 <= i < n ==> !P(a[i])\n{\n n := 0;\n while n != a.Length\n {\n if P(a[n]) {\n return;\n }\n n := n + 1;\n }\n}\n" }, { "test_ID": "167", "test_file": "Dafny_Verify_tmp_tmphq7j0row_Generated_Code_Minimum.dfy", "ground_truth": "method Minimum(a: array) returns (m: int) \n\trequires a.Length > 0\n\tensures exists i :: 0 <= i < a.Length && m == a[i]\n\tensures forall i :: 0 <= i < a.Length ==> m <= a[i]\n{\n\tvar n := 0;\n\tm := a[0];\n\twhile n != a.Length\n\t\tinvariant 0 <= n <= a.Length\n\t\tinvariant exists i :: 0 <= i < a.Length && m == a[i]\n\t\tinvariant forall i :: 0 <= i < n ==> m <= a[i]\n\t{\n\t\tif a[n] < m {\n\t\t\tm := a[n];\n\t\t}\n\t\tn := n + 1;\n\t}\n}\n", "hints_removed": "method Minimum(a: array) returns (m: int) \n\trequires a.Length > 0\n\tensures exists i :: 0 <= i < a.Length && m == a[i]\n\tensures forall i :: 0 <= i < a.Length ==> m <= a[i]\n{\n\tvar n := 0;\n\tm := a[0];\n\twhile n != a.Length\n\t{\n\t\tif a[n] < m {\n\t\t\tm := a[n];\n\t\t}\n\t\tn := n + 1;\n\t}\n}\n" }, { "test_ID": "168", "test_file": "Dafny_Verify_tmp_tmphq7j0row_Generated_Code_Mult.dfy", "ground_truth": "method mult(a:int, b:int) returns (x:int)\n \trequires a >= 0 && b >= 0\n \tensures x == a * b\n{\n \tx := 0;\n\tvar y := a;\n \twhile y > 0\n\t\tinvariant x == (a - y) * b\n\t{\n\t\tx := x + b;\n\t\ty := y - 1;\n\t}\n}\n", "hints_removed": "method mult(a:int, b:int) returns (x:int)\n \trequires a >= 0 && b >= 0\n \tensures x == a * b\n{\n \tx := 0;\n\tvar y := a;\n \twhile y > 0\n\t{\n\t\tx := x + b;\n\t\ty := y - 1;\n\t}\n}\n" }, { "test_ID": "169", "test_file": "Dafny_Verify_tmp_tmphq7j0row_Generated_Code_rand.dfy", "ground_truth": "method Main(xInit: int, y: int) returns (z: int)\n requires xInit >= 0\n requires y >= 0\n ensures z == 0\n{\n var x := xInit;\n z := x * y;\n \n while x > 0\n invariant x >= 0\n invariant z == x * y\n decreases x\n {\n x := x - 1;\n z := z - y;\n }\n}\n", "hints_removed": "method Main(xInit: int, y: int) returns (z: int)\n requires xInit >= 0\n requires y >= 0\n ensures z == 0\n{\n var x := xInit;\n z := x * y;\n \n while x > 0\n {\n x := x - 1;\n z := z - y;\n }\n}\n" }, { "test_ID": "170", "test_file": "Dafny_Verify_tmp_tmphq7j0row_Test_Cases_Function.dfy", "ground_truth": "function Average (a: int, b: int): int \n{\n (a + b) / 2\n}\n\nmethod TripleConditions(x: int) returns (r: int) \nensures r == 3 * x\n{ \n r := 3 * x;\n assert r == 3 * x;\n}\n\nmethod Triple' (x: int) returns (r: int) \n ensures Average(r, 3 * x) == 3 * x\n ensures r == 3 * x\n{\n r:= 3 * x;\n}\n\n\nmethod ProveSpecificationsEquivalent(x: int) {\n var result1 := TripleConditions(x);\n var result2 := Triple'(x);\n \n assert result1 == result2;\n}\n\n", "hints_removed": "function Average (a: int, b: int): int \n{\n (a + b) / 2\n}\n\nmethod TripleConditions(x: int) returns (r: int) \nensures r == 3 * x\n{ \n r := 3 * x;\n}\n\nmethod Triple' (x: int) returns (r: int) \n ensures Average(r, 3 * x) == 3 * x\n ensures r == 3 * x\n{\n r:= 3 * x;\n}\n\n\nmethod ProveSpecificationsEquivalent(x: int) {\n var result1 := TripleConditions(x);\n var result2 := Triple'(x);\n \n}\n\n" }, { "test_ID": "171", "test_file": "Dafny_Verify_tmp_tmphq7j0row_Test_Cases_Ghost.dfy", "ground_truth": "function Average(a: int, b: int): int \n{\n (a + b) / 2\n}\n\nghost method Triple(x: int) returns (r: int)\n ensures r == 3 * x\n{\n r := Average(2 * x, 4 * x);\n}\n\nmethod Triple1(x: int) returns (r: int)\n ensures r == 3 * x\n{\n var y := 2 * x; \n r := x + y;\n ghost var a, b := DoubleQuadruple(x);\n assert a <= r <= b || b <= r <= a;\n}\n\nghost method DoubleQuadruple(x: int) returns (a: int, b: int)\n ensures a == 2 * x && b == 4 * x\n{\n a := 2 * x;\n b := 2 * a;\n}\n\nfunction F(): int {\n29\n}\n\nmethod M() returns (r: int) \nensures r == 29\n{\nr := 29;\n}\n\nmethod Caller() {\nvar a := F();\nvar b := M();\nassert a == 29;\nassert b == 29;\n}\n\nmethod MyMethod(x: int) returns (y: int)\n requires 10 <= x\n ensures 25 <= y\n{ \n var a, b;\n a := x + 3;\n\n if x < 20 {\n b := 32 - x;\n } else {\n b := 16;\n }\n\n y := a + b;\n}\n", "hints_removed": "function Average(a: int, b: int): int \n{\n (a + b) / 2\n}\n\nghost method Triple(x: int) returns (r: int)\n ensures r == 3 * x\n{\n r := Average(2 * x, 4 * x);\n}\n\nmethod Triple1(x: int) returns (r: int)\n ensures r == 3 * x\n{\n var y := 2 * x; \n r := x + y;\n ghost var a, b := DoubleQuadruple(x);\n}\n\nghost method DoubleQuadruple(x: int) returns (a: int, b: int)\n ensures a == 2 * x && b == 4 * x\n{\n a := 2 * x;\n b := 2 * a;\n}\n\nfunction F(): int {\n29\n}\n\nmethod M() returns (r: int) \nensures r == 29\n{\nr := 29;\n}\n\nmethod Caller() {\nvar a := F();\nvar b := M();\n}\n\nmethod MyMethod(x: int) returns (y: int)\n requires 10 <= x\n ensures 25 <= y\n{ \n var a, b;\n a := x + 3;\n\n if x < 20 {\n b := 32 - x;\n } else {\n b := 16;\n }\n\n y := a + b;\n}\n" }, { "test_ID": "172", "test_file": "Dafny_Verify_tmp_tmphq7j0row_Test_Cases_Index.dfy", "ground_truth": "method Index(n: int) returns (i: int) \nrequires 1 <= n\nensures 0 <= i < n\n{\n i := n/2;\n}\n\nmethod Min(x: int, y: int) returns (m: int) \nensures m <= x && m <= y\nensures m == x || m == y\n{\n if (x >= y) {\n m := y;\n } else {\n m := x;\n }\n assert m <= x && m <= y;\n}\n\nmethod Max(x: int, y: int) returns (m: int) {\n if (x >= y) {\n m := x;\n } else {\n m := y;\n }\n assert m >= x && m >= y;\n}\n\n\nmethod MaxSum(x: int, y: int) returns (s: int, m: int)\n ensures s == x + y\n ensures m == if x >= y then x else y\n{\n s := x + y;\n if (x >= y) {\n m := x;\n } else {\n m := y;\n }\n}\n\n\nmethod MaxSumCaller() {\n var x: int := 1928;\n var y: int := 1;\n var a, b: int;\n a, b := MaxSum(x, y);\n\n assert a == 1929;\n assert b == 1928;\n}\n\nmethod ReconstructFromMaxSum(s: int, m: int) returns (x: int, y: int)\n requires s <= 2 * m\n ensures s == (x + y)\n ensures (m == x || m == y) && x <= m && y <= m\n{\n x := m;\n y := s - m;\n}\n\n\nmethod TestMaxSum(x: int, y: int) \n{\n var s, m := MaxSum(x, y);\n var xx, yy := ReconstructFromMaxSum(s, m);\n assert (xx == x && yy == y) || (xx == y && yy == x);\n}\n\n", "hints_removed": "method Index(n: int) returns (i: int) \nrequires 1 <= n\nensures 0 <= i < n\n{\n i := n/2;\n}\n\nmethod Min(x: int, y: int) returns (m: int) \nensures m <= x && m <= y\nensures m == x || m == y\n{\n if (x >= y) {\n m := y;\n } else {\n m := x;\n }\n}\n\nmethod Max(x: int, y: int) returns (m: int) {\n if (x >= y) {\n m := x;\n } else {\n m := y;\n }\n}\n\n\nmethod MaxSum(x: int, y: int) returns (s: int, m: int)\n ensures s == x + y\n ensures m == if x >= y then x else y\n{\n s := x + y;\n if (x >= y) {\n m := x;\n } else {\n m := y;\n }\n}\n\n\nmethod MaxSumCaller() {\n var x: int := 1928;\n var y: int := 1;\n var a, b: int;\n a, b := MaxSum(x, y);\n\n}\n\nmethod ReconstructFromMaxSum(s: int, m: int) returns (x: int, y: int)\n requires s <= 2 * m\n ensures s == (x + y)\n ensures (m == x || m == y) && x <= m && y <= m\n{\n x := m;\n y := s - m;\n}\n\n\nmethod TestMaxSum(x: int, y: int) \n{\n var s, m := MaxSum(x, y);\n var xx, yy := ReconstructFromMaxSum(s, m);\n}\n\n" }, { "test_ID": "173", "test_file": "Dafny_Verify_tmp_tmphq7j0row_Test_Cases_LoopInvariant.dfy", "ground_truth": "method UpWhileLess(N: int) returns (i: int)\nrequires 0 <= N\nensures i == N\n{\n i := 0;\n while i < N \n invariant 0 <= i <= N\n decreases N - i\n {\n i := i + 1;\n }\n}\n\n\nmethod UpWhileNotEqual(N: int) returns (i: int)\nrequires 0 <= N\nensures i == N\n{\n i := 0;\n while i != N\n invariant 0 <= i <= N\n decreases N - i\n {\n i := i + 1;\n }\n}\n\n\nmethod DownWhileNotEqual(N: int) returns (i: int)\nrequires 0 <= N\nensures i == 0\n{\n i := N;\n while i != 0 \n invariant 0 <= i <= N\n decreases i\n {\n i := i - 1;\n }\n}\n\n\nmethod DownWhileGreater(N: int) returns (i: int)\nrequires 0 <= N\nensures i == 0\n{\n i := N;\n while 0 < i \n invariant 0 <= i <= N\n decreases i\n {\n i := i - 1;\n }\n}\n\n\nmethod Quotient()\n{\n var x, y := 0, 191;\n while 7 <= y\n invariant 0 <= y && 7 * x + y == 191\n {\n y := y - 7;\n x := x + 1;\n }\n assert x == 191 / 7 && y == 191 % 7;\n}\n\nmethod Quotient1() \n{\n var x, y := 0, 191;\n while 7 <= y\n invariant 0 <= y && 7 * x + y == 191\n {\n x, y := 27, 2;\n }\n assert x == 191 / 7 && y == 191 % 7;\n}\n", "hints_removed": "method UpWhileLess(N: int) returns (i: int)\nrequires 0 <= N\nensures i == N\n{\n i := 0;\n while i < N \n {\n i := i + 1;\n }\n}\n\n\nmethod UpWhileNotEqual(N: int) returns (i: int)\nrequires 0 <= N\nensures i == N\n{\n i := 0;\n while i != N\n {\n i := i + 1;\n }\n}\n\n\nmethod DownWhileNotEqual(N: int) returns (i: int)\nrequires 0 <= N\nensures i == 0\n{\n i := N;\n while i != 0 \n {\n i := i - 1;\n }\n}\n\n\nmethod DownWhileGreater(N: int) returns (i: int)\nrequires 0 <= N\nensures i == 0\n{\n i := N;\n while 0 < i \n {\n i := i - 1;\n }\n}\n\n\nmethod Quotient()\n{\n var x, y := 0, 191;\n while 7 <= y\n {\n y := y - 7;\n x := x + 1;\n }\n}\n\nmethod Quotient1() \n{\n var x, y := 0, 191;\n while 7 <= y\n {\n x, y := 27, 2;\n }\n}\n" }, { "test_ID": "174", "test_file": "Dafny_Verify_tmp_tmphq7j0row_Test_Cases_Triple.dfy", "ground_truth": "method Triple(x: int) returns (r: int)\n{\n var y := 2 * x;\n r := x + y;\n assert r == 3 * x;\n}\n\nmethod TripleIf(x: int) returns (r: int) {\n if (x == 0) {\n r := 0;\n } else {\n var y := 2 * x;\n r := x + y;\n }\n assert r == 3 * x;\n}\n\nmethod TripleOver(x: int) returns (r: int) {\n if {\n case x < 18 =>\n var a, b := 2 * x, 4 * x;\n r := (a + b) / 2;\n case 0 <= x =>\n var y:= 2 * x;\n r := x + y;\n }\n assert r == 3 * x;\n}\n\nmethod TripleConditions(x: int) returns (r: int) \nrequires x % 2 == 0\nensures r == 3 * x\n{\n var y := x / 2;\n r := 6 * y;\n assert r == 3 * x;\n}\n\nmethod Caller() {\n var t := TripleConditions(18);\n assert t < 100;\n}\n\n", "hints_removed": "method Triple(x: int) returns (r: int)\n{\n var y := 2 * x;\n r := x + y;\n}\n\nmethod TripleIf(x: int) returns (r: int) {\n if (x == 0) {\n r := 0;\n } else {\n var y := 2 * x;\n r := x + y;\n }\n}\n\nmethod TripleOver(x: int) returns (r: int) {\n if {\n case x < 18 =>\n var a, b := 2 * x, 4 * x;\n r := (a + b) / 2;\n case 0 <= x =>\n var y:= 2 * x;\n r := x + y;\n }\n}\n\nmethod TripleConditions(x: int) returns (r: int) \nrequires x % 2 == 0\nensures r == 3 * x\n{\n var y := x / 2;\n r := 6 * y;\n}\n\nmethod Caller() {\n var t := TripleConditions(18);\n}\n\n" }, { "test_ID": "175", "test_file": "Dafny_Verify_tmp_tmphq7j0row_Test_Cases_solved_1_select.dfy", "ground_truth": "method SelectionSort(a: array)\n modifies a\n ensures forall i,j :: 0 <= i < j < a.Length ==> a[i] <= a[j]\n ensures multiset(a[..]) == old(multiset(a[..]))\n{\n var n := 0;\n while n != a.Length\n invariant 0 <= n <= a.Length\n invariant forall i,j :: 0 <= i < j < a.Length && j < n ==> a[i] <= a[j]\n invariant forall i :: 0 <= i < n ==> forall j :: n <= j < a.Length ==> a[i] <= a[j]\n invariant multiset(a[..]) == old(multiset(a[..]))\n {\n var mindex, m := n, n;\n while m != a.Length\n invariant n <= mindex < a.Length\n invariant n <= m <= a.Length\n invariant forall i :: n <= i < m ==> a[mindex] <= a[i]\n invariant multiset(a[..]) == old(multiset(a[..]))\n {\n if a[m] < a[mindex] {\n mindex := m;\n }\n m := m + 1;\n }\n if a[mindex] < a[n] {\n a[mindex], a[n] := a[n], a[mindex];\n }\n n := n + 1;\n } \n}\n", "hints_removed": "method SelectionSort(a: array)\n modifies a\n ensures forall i,j :: 0 <= i < j < a.Length ==> a[i] <= a[j]\n ensures multiset(a[..]) == old(multiset(a[..]))\n{\n var n := 0;\n while n != a.Length\n {\n var mindex, m := n, n;\n while m != a.Length\n {\n if a[m] < a[mindex] {\n mindex := m;\n }\n m := m + 1;\n }\n if a[mindex] < a[n] {\n a[mindex], a[n] := a[n], a[mindex];\n }\n n := n + 1;\n } \n}\n" }, { "test_ID": "176", "test_file": "Dafny_Verify_tmp_tmphq7j0row_dataset_C_convert_examples_01.dfy", "ground_truth": "method main() returns (t1: int, t2: int, x: int, y: int)\nensures y >= 1\n{\n x := 1;\n y := 1;\n t1 := 0;\n t2 := 0;\n\n while(x <= 100000) \n invariant x == y;\n {\n t1 := x;\n t2 := y;\n x := t1 + t2;\n y := t1 + t2;\n }\n}\n\n", "hints_removed": "method main() returns (t1: int, t2: int, x: int, y: int)\nensures y >= 1\n{\n x := 1;\n y := 1;\n t1 := 0;\n t2 := 0;\n\n while(x <= 100000) \n {\n t1 := x;\n t2 := y;\n x := t1 + t2;\n y := t1 + t2;\n }\n}\n\n" }, { "test_ID": "177", "test_file": "Dafny_Verify_tmp_tmphq7j0row_dataset_C_convert_examples_06_n.dfy", "ground_truth": "// MODULE main\n// \tint x;\n// \tint y;\n// \tint w;\n// \tint z;\n\n// \tint turn;\n\n// \tassume(x == 0);\n// \tassume(y == 0);\n// \tassume(z == 0);\n// \tassume(w == 1);\n// \tassume(turn == 0);\n\n// \twhile(*){\n// \t\tif(turn == 0){\n// \t\t\tif(*){\n// \t\t\t\tturn = 1;\n// \t\t\t}\n// \t\t\telse{\n// \t\t\t\tturn = 2;\n// \t\t\t}\n// \t\t}\n// \t\telse{\n// \t\t\tskip;\n// \t\t}\n\n// \t\tif(turn == 1){\n// \t\t\tif(w % 2 == 1){\n// \t\t\t\tx = x + 1;\n// \t\t\t}\n// \t\t\telse{\n// \t\t\t\tskip;\n// \t\t\t}\n\n// \t\t\tif(z % 2 == 0){\n// \t\t\t\ty = y + 1;\n// \t\t\t}\n// \t\t\telse{\n// \t\t\t\tskip;\n// \t\t\t}\n\n// \t\t\tif(*){\n// \t\t\t\tturn = 1;\n// \t\t\t}\n// \t\t\telse{\n// \t\t\t\tturn = 2;\n// \t\t\t}\n// \t\t}\n// \t\telse{\n// \t\t\tif(turn == 2){\n// \t\t\t\tz = z + y;\n// \t\t\t\tw = z + 1;\n\n// \t\t\t\tturn = 0;\n// \t\t\t}\n// \t\t\telse{\n// \t\t\t\tskip;\n// \t\t\t}\n// \t\t}\n// \t}\n\n// \tassert(x == y);\t\n\n// END MODULE\n\n\n// (let ((.def_28 (= x y))) (let ((.def_1294 (<= (+ x (* (- 1) y)) (- 1)))) (let ((.def_1298 (<= 1 (+ x (* (- 1) y))))) (let ((.def_3281 (and (not (<= 0 (+ z (* 2 (to_int (* (/ 1 2) (to_real (* (- 1) z)))))))) (not (<= 1 (+ w (* 2 (to_int (* (/ 1 2) (to_real (+ (* (- 1) w) 1))))))))))) (not (and (and (not (and (not .def_1298) (and (not .def_1294) .def_3281))) (not (and .def_28 .def_3281))) (not (and (not (<= (to_real (+ w (* (- 2) (to_int (* (/ 1 2) (to_real (* 1 w))))))) (to_real 0))) (and (not (and (not .def_28) (or .def_1294 .def_1298))) (not (<= (to_real 1) (to_real (+ z (* 2 (to_int (* (/ 1 2) (to_real (+ (* (- 1) z) 1))))))))))))))))))\n\nmethod Main() returns (x: int, y: int)\n\tensures x == y;\n{\n\tx := 0;\n\ty := 0;\n\tvar w := 1;\n\tvar z := 0;\n\tvar turn := 0;\n\n\twhile(x != y)\n\tinvariant x == y ==> !(0 <= -z*2/2 && 1 <= -(w-1)*2/2) \n invariant !((x != y && x - y <= -1) || (x - y >= 1 && -z*2/2 <= 0 && (w-1)*2/2 <= 1))\n invariant !(w*2/2 <= 0 && ((x != y && (x - y <= -1 || x - y >= 1)) || 1 <= z*2/2))\n\n\t{\n\t\tif(turn == 0){\n\t\t\tturn := 1;\n\t\t}\n\n\t\tif(turn == 1){\n\t\t\tif(w % 2 == 1){\n\t\t\t\tx := x + 1;\n\t\t\t}\n\n\t\t\tif(z % 2 == 0){\n\t\t\t\ty := y + 1;\n\t\t\t}\n\n\t\t\tturn := 1;\n\t\t}\n\t\telse{\n\t\t\tif(turn == 2){\n\t\t\t\tz := z + y;\n\t\t\t\tw := z + 1;\n\n\t\t\t\tturn := 0;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\n", "hints_removed": "// MODULE main\n// \tint x;\n// \tint y;\n// \tint w;\n// \tint z;\n\n// \tint turn;\n\n// \tassume(x == 0);\n// \tassume(y == 0);\n// \tassume(z == 0);\n// \tassume(w == 1);\n// \tassume(turn == 0);\n\n// \twhile(*){\n// \t\tif(turn == 0){\n// \t\t\tif(*){\n// \t\t\t\tturn = 1;\n// \t\t\t}\n// \t\t\telse{\n// \t\t\t\tturn = 2;\n// \t\t\t}\n// \t\t}\n// \t\telse{\n// \t\t\tskip;\n// \t\t}\n\n// \t\tif(turn == 1){\n// \t\t\tif(w % 2 == 1){\n// \t\t\t\tx = x + 1;\n// \t\t\t}\n// \t\t\telse{\n// \t\t\t\tskip;\n// \t\t\t}\n\n// \t\t\tif(z % 2 == 0){\n// \t\t\t\ty = y + 1;\n// \t\t\t}\n// \t\t\telse{\n// \t\t\t\tskip;\n// \t\t\t}\n\n// \t\t\tif(*){\n// \t\t\t\tturn = 1;\n// \t\t\t}\n// \t\t\telse{\n// \t\t\t\tturn = 2;\n// \t\t\t}\n// \t\t}\n// \t\telse{\n// \t\t\tif(turn == 2){\n// \t\t\t\tz = z + y;\n// \t\t\t\tw = z + 1;\n\n// \t\t\t\tturn = 0;\n// \t\t\t}\n// \t\t\telse{\n// \t\t\t\tskip;\n// \t\t\t}\n// \t\t}\n// \t}\n\n// \tassert(x == y);\t\n\n// END MODULE\n\n\n// (let ((.def_28 (= x y))) (let ((.def_1294 (<= (+ x (* (- 1) y)) (- 1)))) (let ((.def_1298 (<= 1 (+ x (* (- 1) y))))) (let ((.def_3281 (and (not (<= 0 (+ z (* 2 (to_int (* (/ 1 2) (to_real (* (- 1) z)))))))) (not (<= 1 (+ w (* 2 (to_int (* (/ 1 2) (to_real (+ (* (- 1) w) 1))))))))))) (not (and (and (not (and (not .def_1298) (and (not .def_1294) .def_3281))) (not (and .def_28 .def_3281))) (not (and (not (<= (to_real (+ w (* (- 2) (to_int (* (/ 1 2) (to_real (* 1 w))))))) (to_real 0))) (and (not (and (not .def_28) (or .def_1294 .def_1298))) (not (<= (to_real 1) (to_real (+ z (* 2 (to_int (* (/ 1 2) (to_real (+ (* (- 1) z) 1))))))))))))))))))\n\nmethod Main() returns (x: int, y: int)\n\tensures x == y;\n{\n\tx := 0;\n\ty := 0;\n\tvar w := 1;\n\tvar z := 0;\n\tvar turn := 0;\n\n\twhile(x != y)\n\n\t{\n\t\tif(turn == 0){\n\t\t\tturn := 1;\n\t\t}\n\n\t\tif(turn == 1){\n\t\t\tif(w % 2 == 1){\n\t\t\t\tx := x + 1;\n\t\t\t}\n\n\t\t\tif(z % 2 == 0){\n\t\t\t\ty := y + 1;\n\t\t\t}\n\n\t\t\tturn := 1;\n\t\t}\n\t\telse{\n\t\t\tif(turn == 2){\n\t\t\t\tz := z + y;\n\t\t\t\tw := z + 1;\n\n\t\t\t\tturn := 0;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\n" }, { "test_ID": "178", "test_file": "Dafny_Verify_tmp_tmphq7j0row_dataset_C_convert_examples_07.dfy", "ground_truth": "// MODULE main\n// \tint i;\n// \tint n;\n// \tint a;\n// \tint b;\n\n// \tassume(i == 0);\n// \tassume(a == 0);\n// \tassume(b == 0);\n// \tassume(n >= 0);\n\n// \twhile(i < n){\n// \t\tif(*) {\n// \t\t\ta = a+1;\n// \t\t\tb = b+2;\n// \t\t} \n// \t\telse {\n// \t\t\ta = a+2;\n// \t\t\tb = b+1;\n// \t\t}\n \t\t\n// \t\ti = i+1;\n// \t}\n\n// \tassert(a + b == 3 * n);\t\n\n// END MODULE\n\n// (let ((.def_201 (<= (+ (* 3 n) (+ (* (- 1) a) (* (- 1) b))) (- 1)))) (let ((.def_392 (<= (+ (* 3 i) (+ (* (- 1) a) (* (- 1) b))) (- 1)))) (not (or (<= 1 (+ (* 3 i) (+ (* (- 1) a) (* (- 1) b)))) (and (or .def_201 .def_392) (or .def_392 (and .def_201 (<= (+ (* 3 i) (+ (* (- 1) a) (* (- 1) b))) 0))))))))\n\nmethod main(n: int) returns (a: int, b: int)\n requires n >= 0\n ensures a + b == 3 * n\n{\n var i: int := 0;\n a := 0;\n b := 0;\n\n while(i < n)\n invariant 0 <= i <= n\n invariant a + b == 3 * i\n {\n if(*)\n {\n a := a + 1;\n b := b + 2;\n }\n else\n {\n a := a + 2;\n b := b + 1;\n }\n\n i := i + 1;\n }\n}\n\n\n", "hints_removed": "// MODULE main\n// \tint i;\n// \tint n;\n// \tint a;\n// \tint b;\n\n// \tassume(i == 0);\n// \tassume(a == 0);\n// \tassume(b == 0);\n// \tassume(n >= 0);\n\n// \twhile(i < n){\n// \t\tif(*) {\n// \t\t\ta = a+1;\n// \t\t\tb = b+2;\n// \t\t} \n// \t\telse {\n// \t\t\ta = a+2;\n// \t\t\tb = b+1;\n// \t\t}\n \t\t\n// \t\ti = i+1;\n// \t}\n\n// \tassert(a + b == 3 * n);\t\n\n// END MODULE\n\n// (let ((.def_201 (<= (+ (* 3 n) (+ (* (- 1) a) (* (- 1) b))) (- 1)))) (let ((.def_392 (<= (+ (* 3 i) (+ (* (- 1) a) (* (- 1) b))) (- 1)))) (not (or (<= 1 (+ (* 3 i) (+ (* (- 1) a) (* (- 1) b)))) (and (or .def_201 .def_392) (or .def_392 (and .def_201 (<= (+ (* 3 i) (+ (* (- 1) a) (* (- 1) b))) 0))))))))\n\nmethod main(n: int) returns (a: int, b: int)\n requires n >= 0\n ensures a + b == 3 * n\n{\n var i: int := 0;\n a := 0;\n b := 0;\n\n while(i < n)\n {\n if(*)\n {\n a := a + 1;\n b := b + 2;\n }\n else\n {\n a := a + 2;\n b := b + 1;\n }\n\n i := i + 1;\n }\n}\n\n\n" }, { "test_ID": "179", "test_file": "Dafny_Verify_tmp_tmphq7j0row_dataset_C_convert_examples_11.dfy", "ground_truth": "method main(x :int) returns (j :int, i :int)\nrequires x > 0\nensures j == 2 * x\n{\n i := 0;\n j := 0;\n\n while i < x\n invariant 0 <= i <= x\n invariant j == 2 * i\n {\n j := j + 2;\n i := i + 1;\n }\n}\n\n\n// MODULE main\n// \tint i;\n// \tint j;\n// \tint x;\n\n// \tassume(j == 0);\n// \tassume(x > 0);\n// \tassume(i == 0);\n\n// \twhile(i < x){\n// \t\tj = j + 2;\n \t\t\n// \t\ti = i + 1;\n// \t}\n\n// \tassert(j == 2*x);\t\n\n// END MODULE\n\n\n// (and (not (<= (+ (* 2 i) (* (- 1) j)) (- 1))) (and (not (<= 1 (+ j (* (- 2) x)))) (not (<= 1 (+ (* 2 i) (* (- 1) j))))))\n\n\n// (and \n// (not (<= (+ (* 2 i) (* (- 1) j)) (- 1)))\n// (not (<= 1 (+ j (* (- 2) x)))) \n// (not (<= 1 (+ (* 2 i) (* (- 1) j))))\n\n// (\n // and (not (<= (+ (* 2 i) (* (- 1) j)) (- 1))) (\n // and (not (<= 1 (+ j (* (- 2) x)))) (not (<= 1 (+ (* 2 i) (* (- 1) j))))))\n", "hints_removed": "method main(x :int) returns (j :int, i :int)\nrequires x > 0\nensures j == 2 * x\n{\n i := 0;\n j := 0;\n\n while i < x\n {\n j := j + 2;\n i := i + 1;\n }\n}\n\n\n// MODULE main\n// \tint i;\n// \tint j;\n// \tint x;\n\n// \tassume(j == 0);\n// \tassume(x > 0);\n// \tassume(i == 0);\n\n// \twhile(i < x){\n// \t\tj = j + 2;\n \t\t\n// \t\ti = i + 1;\n// \t}\n\n// \tassert(j == 2*x);\t\n\n// END MODULE\n\n\n// (and (not (<= (+ (* 2 i) (* (- 1) j)) (- 1))) (and (not (<= 1 (+ j (* (- 2) x)))) (not (<= 1 (+ (* 2 i) (* (- 1) j))))))\n\n\n// (and \n// (not (<= (+ (* 2 i) (* (- 1) j)) (- 1)))\n// (not (<= 1 (+ j (* (- 2) x)))) \n// (not (<= 1 (+ (* 2 i) (* (- 1) j))))\n\n// (\n // and (not (<= (+ (* 2 i) (* (- 1) j)) (- 1))) (\n // and (not (<= 1 (+ j (* (- 2) x)))) (not (<= 1 (+ (* 2 i) (* (- 1) j))))))\n" }, { "test_ID": "180", "test_file": "Dafny_Verify_tmp_tmphq7j0row_dataset_C_convert_examples_15.dfy", "ground_truth": "method main(n: int, k: int) returns (k_out: int)\n requires n > 0;\n\trequires k > n;\n\tensures k_out >= 0;\n{\n\tk_out := k;\n var j: int := 0;\n while(j < n)\n\t\tinvariant 0 <= j <= n;\n\t\tinvariant j + k_out == k;\n {\n j := j + 1;\n k_out := k_out - 1;\n }\n}\n\n\n// C code:\n// MODULE main\n// \tint i;\n// \tint n;\n// \tint j;\n// \tint k;\n\n// \tassume(n > 0);\n// \tassume(k > n);\n// \tassume(j == 0);\n\n// \twhile(j < n){\n// \t\tj = j + 1;\n// \t\tk = k - 1;\n// \t}\n\n// \tassert(k >= 0);\t\n\n// END MODULE\n\n// Invariant\n// (\n // not (or (<= 1 (+ n (+ (* (- 1) j) (* (- 1) k)))) (\n // and (<= k (- 1)) (<= (+ n (* (- 1) j)) (- 1)))))\n\n", "hints_removed": "method main(n: int, k: int) returns (k_out: int)\n requires n > 0;\n\trequires k > n;\n\tensures k_out >= 0;\n{\n\tk_out := k;\n var j: int := 0;\n while(j < n)\n {\n j := j + 1;\n k_out := k_out - 1;\n }\n}\n\n\n// C code:\n// MODULE main\n// \tint i;\n// \tint n;\n// \tint j;\n// \tint k;\n\n// \tassume(n > 0);\n// \tassume(k > n);\n// \tassume(j == 0);\n\n// \twhile(j < n){\n// \t\tj = j + 1;\n// \t\tk = k - 1;\n// \t}\n\n// \tassert(k >= 0);\t\n\n// END MODULE\n\n// Invariant\n// (\n // not (or (<= 1 (+ n (+ (* (- 1) j) (* (- 1) k)))) (\n // and (<= k (- 1)) (<= (+ n (* (- 1) j)) (- 1)))))\n\n" }, { "test_ID": "181", "test_file": "Dafny_Verify_tmp_tmphq7j0row_dataset_C_convert_examples_23_x.dfy", "ground_truth": "method main(n: int) returns (sum: int, i: int)\nrequires n >= 0\n{\n sum := 0;\n i := 0;\n while(i < n)\n invariant sum >= 0\n invariant 0 <= i <= n\n {\n sum := sum + i;\n i := i + 1;\n }\n}\n\n\n\n// MODULE main\n// \tint i;\n// \tint sum;\n// \tint n;\n\n// \tassume(sum == 0);\n// \tassume(n >= 0);\n// \tassume(i == 0);\n\n// \twhile(i < n){\n// \t\tsum = sum + i;\n// \t\ti = i + 1;\n// \t}\n\n// \tassert(sum >= 0);\t\n\n// END MODULE\n", "hints_removed": "method main(n: int) returns (sum: int, i: int)\nrequires n >= 0\n{\n sum := 0;\n i := 0;\n while(i < n)\n {\n sum := sum + i;\n i := i + 1;\n }\n}\n\n\n\n// MODULE main\n// \tint i;\n// \tint sum;\n// \tint n;\n\n// \tassume(sum == 0);\n// \tassume(n >= 0);\n// \tassume(i == 0);\n\n// \twhile(i < n){\n// \t\tsum = sum + i;\n// \t\ti = i + 1;\n// \t}\n\n// \tassert(sum >= 0);\t\n\n// END MODULE\n" }, { "test_ID": "182", "test_file": "Dafny_Verify_tmp_tmphq7j0row_dataset_bql_exampls_Min.dfy", "ground_truth": "method min(a: array, n : int) returns (min : int)\n requires 0 < n <= a.Length;\n\tensures (exists i : int :: 0 <= i && i < n && a[i] == min);\n\tensures (forall i : int :: 0 <= i && i < n ==> a[i] >= min);\n{\n\tvar i : int;\n\n\tmin := a[0];\n\ti := 1;\n\n\twhile (i < n)\n\t\tinvariant i <= n;\n\t\tinvariant (exists j : int :: 0 <= j && j < i && a[j] == min);\n\t\tinvariant (forall j : int :: 0 <= j && j < i ==> a[j] >= min);\n\t{\n\t\tif (a[i] < min) {\n\t\t\tmin := a[i];\n\t\t}\n\t\ti := i + 1;\n\t}\n}\n\n", "hints_removed": "method min(a: array, n : int) returns (min : int)\n requires 0 < n <= a.Length;\n\tensures (exists i : int :: 0 <= i && i < n && a[i] == min);\n\tensures (forall i : int :: 0 <= i && i < n ==> a[i] >= min);\n{\n\tvar i : int;\n\n\tmin := a[0];\n\ti := 1;\n\n\twhile (i < n)\n\t{\n\t\tif (a[i] < min) {\n\t\t\tmin := a[i];\n\t\t}\n\t\ti := i + 1;\n\t}\n}\n\n" }, { "test_ID": "183", "test_file": "Dafny_Verify_tmp_tmphq7j0row_dataset_bql_exampls_SmallNum.dfy", "ground_truth": "method add_small_numbers (a: array, n: int, max: int) returns (r: int)\n\trequires n > 0;\n requires n <= a.Length;\n\trequires (forall i: int :: 0 <= i && i < n ==> a[i] <= max);\n\tensures r <= max * n;\n{\n\tvar i: int;\t\n\n\ti := 0;\n\tr := 0;\n\n\twhile (i < n)\n\t\tinvariant i <= n;\n\t\tinvariant r <= max * i;\n\t{\n\t\tr := r + a[i];\n\t\ti := i + 1;\n\t}\n}\n", "hints_removed": "method add_small_numbers (a: array, n: int, max: int) returns (r: int)\n\trequires n > 0;\n requires n <= a.Length;\n\trequires (forall i: int :: 0 <= i && i < n ==> a[i] <= max);\n\tensures r <= max * n;\n{\n\tvar i: int;\t\n\n\ti := 0;\n\tr := 0;\n\n\twhile (i < n)\n\t{\n\t\tr := r + a[i];\n\t\ti := i + 1;\n\t}\n}\n" }, { "test_ID": "184", "test_file": "Dafny_Verify_tmp_tmphq7j0row_dataset_bql_exampls_Square.dfy", "ground_truth": "method square (n: int) returns (r: int)\n\trequires 0 <= n;\n\tensures r == n*n;\n{\n\tvar x: int;\n\tvar i: int;\n\n\tr := 0;\n\ti := 0;\n\tx := 1;\n\n\twhile (i < n)\n\t\tinvariant i <= n;\n\t\tinvariant r == i*i;\n\t\tinvariant x == 2*i + 1;\n\t{\n\t\tr := r + x;\n\t\tx := x + 2;\n\t\ti := i + 1;\n\t}\n}\n", "hints_removed": "method square (n: int) returns (r: int)\n\trequires 0 <= n;\n\tensures r == n*n;\n{\n\tvar x: int;\n\tvar i: int;\n\n\tr := 0;\n\ti := 0;\n\tx := 1;\n\n\twhile (i < n)\n\t{\n\t\tr := r + x;\n\t\tx := x + 2;\n\t\ti := i + 1;\n\t}\n}\n" }, { "test_ID": "185", "test_file": "Dafny_Verify_tmp_tmphq7j0row_dataset_detailed_examples_SelectionSort.dfy", "ground_truth": "// Works by dividing the input list into two parts: sorted and unsorted. At the beginning, \n// the sorted part is empty and the unsorted part contains all the elements.\nmethod SelectionSort(a: array)\n modifies a\n // Ensures the final array is sorted in ascending order\n ensures forall i,j :: 0 <= i < j < a.Length ==> a[i] <= a[j]\n // Ensures that the final array has the same elements as the initial array\n ensures multiset(a[..]) == old(multiset(a[..]))\n{\n var n := 0;\n while n != a.Length\n // Ensures that n is always within the bounds of the array\n invariant 0 <= n <= a.Length\n // Guarantees that the portion of the array up to index n is sorted\n invariant forall i,j :: 0 <= i < j < a.Length && j < n ==> a[i] <= a[j]\n // Guarantees that all elements before n are less than or equal to elements after and at n\n invariant forall i :: 0 <= i < n ==> forall j :: n <= j < a.Length ==> a[i] <= a[j]\n // Ensures that the array still contains the same elements as the initial array\n invariant multiset(a[..]) == old(multiset(a[..]))\n {\n var mindex, m := n, n;\n while m != a.Length\n // Ensures that mindex is always within the bounds of the array\n invariant n <= mindex < a.Length\n invariant n <= m <= a.Length\n // Ensures that a[mindex] is the smallest element from a[n] to a[m-1]\n invariant forall i :: n <= i < m ==> a[mindex] <= a[i]\n // Ensures that the array still contains the same elements as the initial array\n invariant multiset(a[..]) == old(multiset(a[..]))\n {\n if a[m] < a[mindex] {\n mindex := m;\n }\n m := m + 1;\n }\n // Swaps the first element of the unsorted array with the current smallest element\n // in the unsorted part if it is smaller\n if a[mindex] < a[n] {\n a[mindex], a[n] := a[n], a[mindex];\n }\n n := n + 1;\n } \n}\n", "hints_removed": "// Works by dividing the input list into two parts: sorted and unsorted. At the beginning, \n// the sorted part is empty and the unsorted part contains all the elements.\nmethod SelectionSort(a: array)\n modifies a\n // Ensures the final array is sorted in ascending order\n ensures forall i,j :: 0 <= i < j < a.Length ==> a[i] <= a[j]\n // Ensures that the final array has the same elements as the initial array\n ensures multiset(a[..]) == old(multiset(a[..]))\n{\n var n := 0;\n while n != a.Length\n // Ensures that n is always within the bounds of the array\n // Guarantees that the portion of the array up to index n is sorted\n // Guarantees that all elements before n are less than or equal to elements after and at n\n // Ensures that the array still contains the same elements as the initial array\n {\n var mindex, m := n, n;\n while m != a.Length\n // Ensures that mindex is always within the bounds of the array\n // Ensures that a[mindex] is the smallest element from a[n] to a[m-1]\n // Ensures that the array still contains the same elements as the initial array\n {\n if a[m] < a[mindex] {\n mindex := m;\n }\n m := m + 1;\n }\n // Swaps the first element of the unsorted array with the current smallest element\n // in the unsorted part if it is smaller\n if a[mindex] < a[n] {\n a[mindex], a[n] := a[n], a[mindex];\n }\n n := n + 1;\n } \n}\n" }, { "test_ID": "186", "test_file": "Dafny_Verify_tmp_tmphq7j0row_dataset_error_data_real_error_IsEven_success_1.dfy", "ground_truth": "function even(n: int): bool\n requires n >= 0\n{\n if n == 0 then true else !even(n-1)\n}\n\nmethod is_even(n: int) returns (r: bool)\n requires n >= 0;\n ensures r <==> even(n);\n{\n var i: int := 0;\n r := true;\n\n while i < n\n invariant 0 <= i <= n;\n invariant r <==> even(i);\n {\n r := !r;\n i := i + 1;\n }\n}\n", "hints_removed": "function even(n: int): bool\n requires n >= 0\n{\n if n == 0 then true else !even(n-1)\n}\n\nmethod is_even(n: int) returns (r: bool)\n requires n >= 0;\n ensures r <==> even(n);\n{\n var i: int := 0;\n r := true;\n\n while i < n\n {\n r := !r;\n i := i + 1;\n }\n}\n" }, { "test_ID": "187", "test_file": "Dafny_tmp_tmp0wu8wmfr_Heimaverkefni 1_LinearSearch.dfy", "ground_truth": "// Author of question: Snorri Agnarsson\n// Permalink of question: https://rise4fun.com/Dafny/0HRr\n\n// Author of solution: Alexander Gu\u00f0mundsson\n// Permalink of solution: https://rise4fun.com/Dafny/8pxWd\n\n// Use the command\n// dafny LinearSearch-skeleton.dfy\n// or\n// compile LinearSearch-skeleton.dfy\n// to compile the file.\n// Or use the web page rise4fun.com/dafny.\n\n// When you have solved the problem put\n// the solution on the Dafny web page,\n// generate a permalink and put it in\n// this file.\n\n\n\nmethod SearchRecursive( a: seq, i: int, j: int, x: int ) returns (k: int)\n decreases j-i;\n requires 0 <= i <= j <= |a|;\n ensures i <= k < j || k == -1;\n ensures k != -1 ==> a[k] == x;\n ensures k != -1 ==> forall r | k < r < j :: a[r] != x;\n ensures k == -1 ==> forall r | i <= r < j :: a[r] != x;\n{\n\n // Put program text here so that Dafny\n // accepts this function.\n // In this function loops are not allowed\n // but recursion should be used, and it\n // is not allowed to call the function\n // SearchLoop below.\n \n if j == i\n {\n k := -1;\n return;\n }\n if a[j-1] == x\n {\n k := j-1;\n return;\n\n }\n else\n {\n k := SearchRecursive(a, i, j-1, x);\n }\n}\n\n\n\n\n\nmethod SearchLoop( a: seq, i: int, j: int, x: int ) returns (k: int)\n requires 0 <= i <= j <= |a|;\n ensures i <= k < j || k == -1;\n ensures k != -1 ==> a[k] == x;\n ensures k != -1 ==> forall r | k < r < j :: a[r] != x;\n ensures k == -1 ==> forall r | i <= r < j :: a[r] != x;\n{\n // Put program text here so that Dafny\n // accepts this function.\n // In this function recursion is not allowed\n // and it is not allowed to call the function\n // SearchRecursive above.\n \n if i == j\n {\n return -1;\n }\n\n var t := j;\n while t > i\n decreases t;\n\n invariant forall p | t <= p < j :: a[p] != x; \n\n {\n if a[t-1] == x\n {\n k := t-1;\n return;\n }\n else \n {\n t := t - 1;\n\n }\n \n \n }\n \n k := -1;\n\n\n\n \n \n}\n\n\n\n", "hints_removed": "// Author of question: Snorri Agnarsson\n// Permalink of question: https://rise4fun.com/Dafny/0HRr\n\n// Author of solution: Alexander Gu\u00f0mundsson\n// Permalink of solution: https://rise4fun.com/Dafny/8pxWd\n\n// Use the command\n// dafny LinearSearch-skeleton.dfy\n// or\n// compile LinearSearch-skeleton.dfy\n// to compile the file.\n// Or use the web page rise4fun.com/dafny.\n\n// When you have solved the problem put\n// the solution on the Dafny web page,\n// generate a permalink and put it in\n// this file.\n\n\n\nmethod SearchRecursive( a: seq, i: int, j: int, x: int ) returns (k: int)\n requires 0 <= i <= j <= |a|;\n ensures i <= k < j || k == -1;\n ensures k != -1 ==> a[k] == x;\n ensures k != -1 ==> forall r | k < r < j :: a[r] != x;\n ensures k == -1 ==> forall r | i <= r < j :: a[r] != x;\n{\n\n // Put program text here so that Dafny\n // accepts this function.\n // In this function loops are not allowed\n // but recursion should be used, and it\n // is not allowed to call the function\n // SearchLoop below.\n \n if j == i\n {\n k := -1;\n return;\n }\n if a[j-1] == x\n {\n k := j-1;\n return;\n\n }\n else\n {\n k := SearchRecursive(a, i, j-1, x);\n }\n}\n\n\n\n\n\nmethod SearchLoop( a: seq, i: int, j: int, x: int ) returns (k: int)\n requires 0 <= i <= j <= |a|;\n ensures i <= k < j || k == -1;\n ensures k != -1 ==> a[k] == x;\n ensures k != -1 ==> forall r | k < r < j :: a[r] != x;\n ensures k == -1 ==> forall r | i <= r < j :: a[r] != x;\n{\n // Put program text here so that Dafny\n // accepts this function.\n // In this function recursion is not allowed\n // and it is not allowed to call the function\n // SearchRecursive above.\n \n if i == j\n {\n return -1;\n }\n\n var t := j;\n while t > i\n\n\n {\n if a[t-1] == x\n {\n k := t-1;\n return;\n }\n else \n {\n t := t - 1;\n\n }\n \n \n }\n \n k := -1;\n\n\n\n \n \n}\n\n\n\n" }, { "test_ID": "188", "test_file": "Dafny_tmp_tmp0wu8wmfr_Heimaverkefni 2_BinarySearchDec.dfy", "ground_truth": "// Author of question: Snorri Agnarsson\n// Permalink of question: https://rise4fun.com/Dafny/CGB1z\n\n// Authors of solution: Alexander Gu\u00f0mundsson\n// Permalink of solution: https://rise4fun.com/Dafny/VnB5\n\n// Use the command\n// dafny H2-skeleton.dfy\n// or\n// compile H2-skeleton.dfy\n// to compile the file.\n// Or use the web page rise4fun.com/dafny.\n\n// When you have solved the problem put\n// the solution on the Dafny web page,\n// generate a permalink and put it in\n// this file.\n\nmethod SearchRecursive( a: seq, i: int, j: int, x: real ) returns ( k: int )\n decreases j-i;\n requires 0 <= i <= j <= |a|;\n requires forall p, q :: i <= p < q < j ==> a[p] >= a[q];\n ensures i <= k <= j\n ensures forall r | i <= r < k :: a[r] >= x;\n ensures forall r | k <= r < j :: a[r] < x;\n\n{\n if i == j\n {\n return i;\n }\n var m := i + (j-i)/2;\n if a[m] < x\n {\n k := SearchRecursive(a,i,m,x);\n }\n else\n {\n k := SearchRecursive(a,m+1,j,x);\n }\n}\n\nmethod SearchLoop( a: seq, i: int, j: int, x: real ) returns ( k: int )\n requires 0 <= i <= j <= |a|;\n requires forall p, q :: i <= p < q < j ==> a[p] >= a[q];\n ensures i <= k <= j;\n ensures forall r | i <= r < k :: a[r] >= x;\n ensures forall r | k <= r < j :: a[r] < x;\n{\n if i == j\n {\n return i;\n }\n var p := i;\n var q := j;\n while p != q\n decreases q-p;\n invariant i <= p <= q <= j;\n invariant forall r | i <= r < p :: a[r] >= x;\n invariant forall r | q <= r < j :: a[r] < x;\n {\n var m := p + (q-p)/2;\n if a[m] < x\n {\n q := m;\n }\n else\n {\n p := m+1;\n }\n }\n return p;\n}\n\n// Ef eftirfarandi fall er ekki sam\u00feykkt \u00fe\u00e1 eru\n// f\u00f6llin ekki a\u00f0 haga s\u00e9r r\u00e9tt a\u00f0 mati Dafny.\nmethod Test( a: seq, x: real )\n requires forall p,q | 0 <= p < q < |a| :: a[p] >= a[q];\n{\n\n var k1 := SearchLoop(a,0,|a|,x);\n assert forall r | 0 <= r < k1 :: a[r] >= x;\n assert forall r | k1 <= r < |a| :: a[r] < x;\n var k2 := SearchRecursive(a,0,|a|,x);\n assert forall r | 0 <= r < k2 :: a[r] >= x;\n assert forall r | k2 <= r < |a| :: a[r] < x;\n}\n", "hints_removed": "// Author of question: Snorri Agnarsson\n// Permalink of question: https://rise4fun.com/Dafny/CGB1z\n\n// Authors of solution: Alexander Gu\u00f0mundsson\n// Permalink of solution: https://rise4fun.com/Dafny/VnB5\n\n// Use the command\n// dafny H2-skeleton.dfy\n// or\n// compile H2-skeleton.dfy\n// to compile the file.\n// Or use the web page rise4fun.com/dafny.\n\n// When you have solved the problem put\n// the solution on the Dafny web page,\n// generate a permalink and put it in\n// this file.\n\nmethod SearchRecursive( a: seq, i: int, j: int, x: real ) returns ( k: int )\n requires 0 <= i <= j <= |a|;\n requires forall p, q :: i <= p < q < j ==> a[p] >= a[q];\n ensures i <= k <= j\n ensures forall r | i <= r < k :: a[r] >= x;\n ensures forall r | k <= r < j :: a[r] < x;\n\n{\n if i == j\n {\n return i;\n }\n var m := i + (j-i)/2;\n if a[m] < x\n {\n k := SearchRecursive(a,i,m,x);\n }\n else\n {\n k := SearchRecursive(a,m+1,j,x);\n }\n}\n\nmethod SearchLoop( a: seq, i: int, j: int, x: real ) returns ( k: int )\n requires 0 <= i <= j <= |a|;\n requires forall p, q :: i <= p < q < j ==> a[p] >= a[q];\n ensures i <= k <= j;\n ensures forall r | i <= r < k :: a[r] >= x;\n ensures forall r | k <= r < j :: a[r] < x;\n{\n if i == j\n {\n return i;\n }\n var p := i;\n var q := j;\n while p != q\n {\n var m := p + (q-p)/2;\n if a[m] < x\n {\n q := m;\n }\n else\n {\n p := m+1;\n }\n }\n return p;\n}\n\n// Ef eftirfarandi fall er ekki sam\u00feykkt \u00fe\u00e1 eru\n// f\u00f6llin ekki a\u00f0 haga s\u00e9r r\u00e9tt a\u00f0 mati Dafny.\nmethod Test( a: seq, x: real )\n requires forall p,q | 0 <= p < q < |a| :: a[p] >= a[q];\n{\n\n var k1 := SearchLoop(a,0,|a|,x);\n var k2 := SearchRecursive(a,0,|a|,x);\n}\n" }, { "test_ID": "189", "test_file": "Dafny_tmp_tmp0wu8wmfr_Heimaverkefni 3_InsertionSortMultiset.dfy", "ground_truth": "// H\u00f6fundur spurningar: Snorri Agnarsson, snorri@hi.is\n// Permalink spurningar: https://rise4fun.com/Dafny/G4sc3\n\n// H\u00f6fundur lausnar: Alexander Gu\u00f0mundsson\n// Permalink lausnar: https://rise4fun.com/Dafny/nujsu\n\n// Insertion sort me\u00f0 hj\u00e1lp helmingunarleitar.\n\nmethod Search( s: seq, x: int ) returns ( k: int )\n // Ekki m\u00e1 breyta forskilyr\u00f0um e\u00f0a eftirskilyr\u00f0um fallsins\n requires forall p,q | 0 <= p < q < |s| :: s[p] <= s[q];\n ensures 0 <= k <= |s|;\n ensures forall i | 0 <= i < k :: s[i] <= x;\n ensures forall i | k <= i < |s| :: s[i] >= x;\n ensures forall z | z in s[..k] :: z <= x;\n ensures forall z | z in s[k..] :: z >= x;\n ensures s == s[..k]+s[k..];\n{\n // Setji\u00f0 vi\u00f0eigandi stofn fallsins h\u00e9r.\n var p := 0;\n var q := |s|;\n\n if p == q\n {\n return p;\n }\n while p != q \n decreases q-p;\n invariant 0 <= p <= q <= |s|;\n invariant forall r | 0 <= r < p :: s[r] <= x;\n invariant forall r | q <= r < |s| :: s[r] >= x;\n \n {\n var m := p + (q-p)/2;\n if s[m] == x\n {\n return m;\n }\n if s[m] < x\n {\n p := m+1;\n }\n else\n {\n q := m;\n }\n }\n\n return p;\n\n\n\n}\n\nmethod Sort( m: multiset ) returns ( r: seq )\n ensures multiset(r) == m;\n ensures forall p,q | 0 <= p < q < |r| :: r[p] <= r[q];\n{\n // Setji\u00f0 vi\u00f0eigandi frumstillingu \u00e1 r og rest h\u00e9r.\n // r er skilabreyta en rest er n\u00fd breyta sem \u00fei\u00f0 b\u00fai\u00f0 til.\n r := [];\n var rest := m;\n while rest != multiset{}\n // Ekki breyta fastayr\u00f0ingu lykkju\n decreases rest;\n invariant m == multiset(r)+rest;\n invariant forall p,q | 0 <= p < q < |r| :: r[p] <= r[q];\n {\n // Setji\u00f0 vi\u00f0eigandi stofn lykkjunnar h\u00e9r.\n // Fjarl\u00e6gi\u00f0 eitt gildi \u00far rest me\u00f0\n // var x :| x in rest;\n // rest := rest-multiset{x};\n // og noti\u00f0 Search til a\u00f0 finna r\u00e9ttan sta\u00f0\n // \u00ed r til a\u00f0 stinga [x] inn \u00ed r.\n var x :| x in rest;\n rest := rest - multiset{x};\n var k := Search(r, x);\n r := r[..k] + [x] + r[k..];\n }\n return r;\n}\n", "hints_removed": "// H\u00f6fundur spurningar: Snorri Agnarsson, snorri@hi.is\n// Permalink spurningar: https://rise4fun.com/Dafny/G4sc3\n\n// H\u00f6fundur lausnar: Alexander Gu\u00f0mundsson\n// Permalink lausnar: https://rise4fun.com/Dafny/nujsu\n\n// Insertion sort me\u00f0 hj\u00e1lp helmingunarleitar.\n\nmethod Search( s: seq, x: int ) returns ( k: int )\n // Ekki m\u00e1 breyta forskilyr\u00f0um e\u00f0a eftirskilyr\u00f0um fallsins\n requires forall p,q | 0 <= p < q < |s| :: s[p] <= s[q];\n ensures 0 <= k <= |s|;\n ensures forall i | 0 <= i < k :: s[i] <= x;\n ensures forall i | k <= i < |s| :: s[i] >= x;\n ensures forall z | z in s[..k] :: z <= x;\n ensures forall z | z in s[k..] :: z >= x;\n ensures s == s[..k]+s[k..];\n{\n // Setji\u00f0 vi\u00f0eigandi stofn fallsins h\u00e9r.\n var p := 0;\n var q := |s|;\n\n if p == q\n {\n return p;\n }\n while p != q \n \n {\n var m := p + (q-p)/2;\n if s[m] == x\n {\n return m;\n }\n if s[m] < x\n {\n p := m+1;\n }\n else\n {\n q := m;\n }\n }\n\n return p;\n\n\n\n}\n\nmethod Sort( m: multiset ) returns ( r: seq )\n ensures multiset(r) == m;\n ensures forall p,q | 0 <= p < q < |r| :: r[p] <= r[q];\n{\n // Setji\u00f0 vi\u00f0eigandi frumstillingu \u00e1 r og rest h\u00e9r.\n // r er skilabreyta en rest er n\u00fd breyta sem \u00fei\u00f0 b\u00fai\u00f0 til.\n r := [];\n var rest := m;\n while rest != multiset{}\n // Ekki breyta fastayr\u00f0ingu lykkju\n {\n // Setji\u00f0 vi\u00f0eigandi stofn lykkjunnar h\u00e9r.\n // Fjarl\u00e6gi\u00f0 eitt gildi \u00far rest me\u00f0\n // var x :| x in rest;\n // rest := rest-multiset{x};\n // og noti\u00f0 Search til a\u00f0 finna r\u00e9ttan sta\u00f0\n // \u00ed r til a\u00f0 stinga [x] inn \u00ed r.\n var x :| x in rest;\n rest := rest - multiset{x};\n var k := Search(r, x);\n r := r[..k] + [x] + r[k..];\n }\n return r;\n}\n" }, { "test_ID": "190", "test_file": "Dafny_tmp_tmp0wu8wmfr_Heimaverkefni 3_SelectionSortMultiset.dfy", "ground_truth": "// H\u00f6fundur spurningar: Snorri Agnarsson, snorri@hi.is\n// Permalink spurningar: https://rise4fun.com/Dafny/dtcnY\n\n// H\u00f6fundur lausnar: Alexander Gu\u00f0mundsson\n// Permalink lausnar: https://rise4fun.com/Dafny/ybUCz\n\n///////////////////////////////////////////////////////////////\n// H\u00e9r byrjar \u00f3breytanlegi hluti skr\u00e1rinnar.\n// Fyrir aftan \u00feann hluta er s\u00e1 hluti sem \u00fei\u00f0 eigi\u00f0 a\u00f0 breyta.\n///////////////////////////////////////////////////////////////\n\n// Hj\u00e1lparfall sem finnur minnsta gildi \u00ed poka\nmethod MinOfMultiset( m: multiset ) returns( min: int )\n requires m != multiset{};\n ensures min in m;\n ensures forall z | z in m :: min <= z;\n{\n min :| min in m;\n var done := multiset{min};\n var m' := m-done;\n while m' != multiset{}\n decreases m';\n invariant m == done+m';\n invariant min in done;\n invariant forall z | z in done :: min <= z;\n {\n var z :| z in m';\n done := done+multiset{z};\n m' := m'-multiset{z};\n if z < min { min := z; }\n }\n}\n\n// Ekki m\u00e1 breyta \u00feessu falli.\nmethod Test( m: multiset )\n{\n var s := Sort(m);\n assert multiset(s) == m;\n assert forall p,q | 0 <= p < q < |s| :: s[p] <= s[q];\n}\n\nmethod Main()\n{\n var m := multiset{0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9};\n var s := Sort(m);\n assert multiset(s) == m;\n assert forall p,q | 0 <= p < q < |s| :: s[p] <= s[q];\n print s;\n}\n\n///////////////////////////////////////////////////////////////\n// H\u00e9r l\u00fdkur \u00f3breytanlega hluta skr\u00e1rinnar.\n// H\u00e9r fyrir aftan er s\u00e1 hluti sem \u00fei\u00f0 eigi\u00f0 a\u00f0 breyta til a\u00f0\n// \u00fatf\u00e6ra afbrig\u00f0i af selection sort.\n///////////////////////////////////////////////////////////////\n\n// Selection sort sem ra\u00f0ar poka \u00ed runu.\n// Kl\u00e1ri\u00f0 a\u00f0 forrita \u00feetta fall.\nmethod Sort( m: multiset ) returns ( s: seq )\n // Setji\u00f0 vi\u00f0eigandi ensures klausur h\u00e9r\n ensures multiset(s) == m;\n ensures forall p,q | 0 <= p < q < |s| :: s[p] <= s[q];\n{\n // Setji\u00f0 vi\u00f0eigandi frumstillingar \u00e1 m' og s h\u00e9r.\n // m' er n\u00fd sta\u00f0v\u00e6r breyta en s er skilabreyta.\n s := [];\n var m' := m;\n\n while m' != multiset{}\n // Ekki breyta fastayr\u00f0ingu lykkju\n decreases m';\n invariant m == m'+multiset(s);\n invariant forall p,q | 0 <= p < q < |s| :: s[p] <= s[q];\n invariant forall z | z in m' :: forall r | 0 <= r < |s| :: z >= s[r];\n {\n // Setji\u00f0 vi\u00f0eigandi stofn \u00ed lykkjuna h\u00e9r\n var x := MinOfMultiset(m');\n m' := m' - multiset{x};\n s := s + [x];\n }\n return s;\n}\n", "hints_removed": "// H\u00f6fundur spurningar: Snorri Agnarsson, snorri@hi.is\n// Permalink spurningar: https://rise4fun.com/Dafny/dtcnY\n\n// H\u00f6fundur lausnar: Alexander Gu\u00f0mundsson\n// Permalink lausnar: https://rise4fun.com/Dafny/ybUCz\n\n///////////////////////////////////////////////////////////////\n// H\u00e9r byrjar \u00f3breytanlegi hluti skr\u00e1rinnar.\n// Fyrir aftan \u00feann hluta er s\u00e1 hluti sem \u00fei\u00f0 eigi\u00f0 a\u00f0 breyta.\n///////////////////////////////////////////////////////////////\n\n// Hj\u00e1lparfall sem finnur minnsta gildi \u00ed poka\nmethod MinOfMultiset( m: multiset ) returns( min: int )\n requires m != multiset{};\n ensures min in m;\n ensures forall z | z in m :: min <= z;\n{\n min :| min in m;\n var done := multiset{min};\n var m' := m-done;\n while m' != multiset{}\n {\n var z :| z in m';\n done := done+multiset{z};\n m' := m'-multiset{z};\n if z < min { min := z; }\n }\n}\n\n// Ekki m\u00e1 breyta \u00feessu falli.\nmethod Test( m: multiset )\n{\n var s := Sort(m);\n}\n\nmethod Main()\n{\n var m := multiset{0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9};\n var s := Sort(m);\n print s;\n}\n\n///////////////////////////////////////////////////////////////\n// H\u00e9r l\u00fdkur \u00f3breytanlega hluta skr\u00e1rinnar.\n// H\u00e9r fyrir aftan er s\u00e1 hluti sem \u00fei\u00f0 eigi\u00f0 a\u00f0 breyta til a\u00f0\n// \u00fatf\u00e6ra afbrig\u00f0i af selection sort.\n///////////////////////////////////////////////////////////////\n\n// Selection sort sem ra\u00f0ar poka \u00ed runu.\n// Kl\u00e1ri\u00f0 a\u00f0 forrita \u00feetta fall.\nmethod Sort( m: multiset ) returns ( s: seq )\n // Setji\u00f0 vi\u00f0eigandi ensures klausur h\u00e9r\n ensures multiset(s) == m;\n ensures forall p,q | 0 <= p < q < |s| :: s[p] <= s[q];\n{\n // Setji\u00f0 vi\u00f0eigandi frumstillingar \u00e1 m' og s h\u00e9r.\n // m' er n\u00fd sta\u00f0v\u00e6r breyta en s er skilabreyta.\n s := [];\n var m' := m;\n\n while m' != multiset{}\n // Ekki breyta fastayr\u00f0ingu lykkju\n {\n // Setji\u00f0 vi\u00f0eigandi stofn \u00ed lykkjuna h\u00e9r\n var x := MinOfMultiset(m');\n m' := m' - multiset{x};\n s := s + [x];\n }\n return s;\n}\n" }, { "test_ID": "191", "test_file": "Dafny_tmp_tmp0wu8wmfr_Heimaverkefni 8_H8.dfy", "ground_truth": "// H\u00f6fundur spurningar: Snorri Agnarsson, snorri@hi.is\n// Permalink spurningar: https://rise4fun.com/Dafny/GW7a\n\n// H\u00f6fundur lausnar: Alexander Gu\u00f0mundsson\n// Permalink lausnar: https://www.rise4fun.com/Dafny/JPGct\n\n// Kl\u00e1ri\u00f0 a\u00f0 forrita f\u00f6llin tv\u00f6.\n\nmethod Partition( m: multiset )\n returns( pre: multiset, p: int, post: multiset )\n requires |m| > 0;\n ensures p in m;\n ensures m == pre+multiset{p}+post;\n ensures forall z | z in pre :: z <= p;\n ensures forall z | z in post :: z >= p;\n{\n p :| p in m;\n var m' := m;\n m' := m' - multiset{p};\n pre := multiset{};\n post := multiset{};\n while m' != multiset{}\n decreases m';\n invariant m == m' + pre + multiset{p} + post;\n invariant forall k | k in pre :: k <= p;\n invariant forall k | k in post :: k >= p;\n\n {\n var temp :| temp in m';\n m' := m' - multiset{temp};\n if temp <= p\n {\n pre := pre + multiset{temp};\n }\n else\n {\n post := post + multiset{temp};\n }\n }\n return pre,p,post;\n \n}\n\n \n\n\n\n\n\nmethod QuickSelect( m: multiset, k: int )\n returns( pre: multiset, kth: int, post: multiset )\n decreases m;\n requires 0 <= k < |m|;\n ensures kth in m;\n ensures m == pre+multiset{kth}+post;\n ensures |pre| == k;\n ensures forall z | z in pre :: z <= kth;\n ensures forall z | z in post :: z >= kth;\n{\n pre,kth,post := Partition(m);\n assert m == pre + multiset{kth} + post;\n if |pre| != k\n {\n if k > |pre|\n {\n \n var pre',p,post' := QuickSelect(post,k-|pre| - 1);\n assert pre' + multiset{p} + post' == post;\n pre := pre + multiset{kth} + pre';\n post := post - pre' - multiset{p};\n kth := p;\n\n }\n else if k < |pre|\n {\n var pre',p,post' := QuickSelect(pre,k);\n pre := pre - multiset{p} - post';\n post := post + multiset{kth} + post';\n kth := p;\n\n }\n }\n else{\n return pre,kth,post;\n } \n}\n", "hints_removed": "// H\u00f6fundur spurningar: Snorri Agnarsson, snorri@hi.is\n// Permalink spurningar: https://rise4fun.com/Dafny/GW7a\n\n// H\u00f6fundur lausnar: Alexander Gu\u00f0mundsson\n// Permalink lausnar: https://www.rise4fun.com/Dafny/JPGct\n\n// Kl\u00e1ri\u00f0 a\u00f0 forrita f\u00f6llin tv\u00f6.\n\nmethod Partition( m: multiset )\n returns( pre: multiset, p: int, post: multiset )\n requires |m| > 0;\n ensures p in m;\n ensures m == pre+multiset{p}+post;\n ensures forall z | z in pre :: z <= p;\n ensures forall z | z in post :: z >= p;\n{\n p :| p in m;\n var m' := m;\n m' := m' - multiset{p};\n pre := multiset{};\n post := multiset{};\n while m' != multiset{}\n\n {\n var temp :| temp in m';\n m' := m' - multiset{temp};\n if temp <= p\n {\n pre := pre + multiset{temp};\n }\n else\n {\n post := post + multiset{temp};\n }\n }\n return pre,p,post;\n \n}\n\n \n\n\n\n\n\nmethod QuickSelect( m: multiset, k: int )\n returns( pre: multiset, kth: int, post: multiset )\n requires 0 <= k < |m|;\n ensures kth in m;\n ensures m == pre+multiset{kth}+post;\n ensures |pre| == k;\n ensures forall z | z in pre :: z <= kth;\n ensures forall z | z in post :: z >= kth;\n{\n pre,kth,post := Partition(m);\n if |pre| != k\n {\n if k > |pre|\n {\n \n var pre',p,post' := QuickSelect(post,k-|pre| - 1);\n pre := pre + multiset{kth} + pre';\n post := post - pre' - multiset{p};\n kth := p;\n\n }\n else if k < |pre|\n {\n var pre',p,post' := QuickSelect(pre,k);\n pre := pre - multiset{p} - post';\n post := post + multiset{kth} + post';\n kth := p;\n\n }\n }\n else{\n return pre,kth,post;\n } \n}\n" }, { "test_ID": "192", "test_file": "Dafny_tmp_tmp0wu8wmfr_tests_F1a.dfy", "ground_truth": "method F() returns ( r: int)\n ensures r <= 0\n{\n r := 0;\n}\n\nmethod Main() \n{\n var x := F();\n assert x <= 0;\n x := x-1;\n assert x <= -1;\n print x;\n}\n\n\nmethod Mid( p: int, q: int) returns ( m: int )\n // | ... | ??? | ... |\n // p m q\n requires p <= q;\n ensures p<= m <= q;\n ensures m-p <= q-m;\n ensures 0 <= (q-m)-(m-p) <= 1;\n\n{\n m := (p+q)/2;\n assert m == p+(q-p)/2;\n}\n", "hints_removed": "method F() returns ( r: int)\n ensures r <= 0\n{\n r := 0;\n}\n\nmethod Main() \n{\n var x := F();\n x := x-1;\n print x;\n}\n\n\nmethod Mid( p: int, q: int) returns ( m: int )\n // | ... | ??? | ... |\n // p m q\n requires p <= q;\n ensures p<= m <= q;\n ensures m-p <= q-m;\n ensures 0 <= (q-m)-(m-p) <= 1;\n\n{\n m := (p+q)/2;\n}\n" }, { "test_ID": "193", "test_file": "Dafny_tmp_tmp0wu8wmfr_tests_InsertionSortSeq.dfy", "ground_truth": "// Insertion sort.\n//\n// Author: Snorri Agnarsson, snorri@hi.is\n\npredicate IsSorted( s: seq )\n{\n forall p,q | 0<=p ) returns ( r: seq )\n ensures multiset(r) == multiset(s);\n ensures IsSorted(r);\n{\n r := [];\n var rest := s;\n while rest != []\n decreases rest;\n invariant multiset(s) == multiset(r)+multiset(rest);\n invariant IsSorted(r);\n {\n var x := rest[0];\n assert rest == rest[0..1]+rest[1..];\n rest := rest[1..];\n var k := |r|;\n while k>0 && r[k-1]>x\n invariant 0 <= k <= |r|;\n invariant forall p | k<=p<|r| :: r[p]>x;\n {\n k := k-1;\n }\n assert r == r[..k]+r[k..];\n r := r[..k]+[x]+r[k..];\n }\n}\n", "hints_removed": "// Insertion sort.\n//\n// Author: Snorri Agnarsson, snorri@hi.is\n\npredicate IsSorted( s: seq )\n{\n forall p,q | 0<=p ) returns ( r: seq )\n ensures multiset(r) == multiset(s);\n ensures IsSorted(r);\n{\n r := [];\n var rest := s;\n while rest != []\n {\n var x := rest[0];\n rest := rest[1..];\n var k := |r|;\n while k>0 && r[k-1]>x\n {\n k := k-1;\n }\n r := r[..k]+[x]+r[k..];\n }\n}\n" }, { "test_ID": "194", "test_file": "Dafny_tmp_tmp0wu8wmfr_tests_Search1000.dfy", "ground_truth": "// Author: Snorri Agnarsson, snorri@hi.is\n\n// Search1000 is a Dafny version of a function shown\n// by Jon Bentley in his old Programming Pearls\n// column in CACM. Surprisingly Dafny needs no help\n// to verify the function.\nmethod Search1000( a: array, x: int ) returns ( k: int )\n requires a.Length >= 1000;\n requires forall p,q | 0 <= p < q < 1000 :: a[p] <= a[q];\n ensures 0 <= k <= 1000;\n ensures forall r | 0 <= r < k :: a[r] < x;\n ensures forall r | k <= r < 1000 :: a[r] >= x;\n{\n k := 0;\n if a[500] < x { k := 489; }\n // a: | = x|\n // ^ ^ ^ ^\n // 0 k k+511 1000\n if a[k+255] < x { k := k+256; }\n // a: | = x|\n // ^ ^ ^ ^\n // 0 k k+255 1000\n if a[k+127] < x { k := k+128; }\n if a[k+63] < x { k := k+64; }\n if a[k+31] < x { k := k+32; }\n if a[k+15] < x { k := k+16; }\n if a[k+7] < x { k := k+8; }\n if a[k+3] < x { k := k+4; }\n if a[k+1] < x { k := k+2; }\n // a: | = x|\n // ^ ^ ^ ^\n // 0 k k+1 1000\n if a[k] < x { k := k+1; }\n // a: | = x|\n // ^ ^ ^\n // 0 k 1000\n}\n\n// Is2Pow(n) is true iff n==2^k for some k>=0.\npredicate Is2Pow( n: int )\n decreases n;\n{\n if n < 1 then\n false\n else if n == 1 then\n true\n else\n n%2 == 0 && Is2Pow(n/2)\n}\n\n// This method is a binary search that only works for array\n// segments of size n == 2^k-1 for some k>=0.\nmethod Search2PowLoop( a: array, i: int, n: int, x: int ) returns ( k: int )\n requires 0 <= i <= i+n <= a.Length;\n requires forall p,q | i <= p < q < i+n :: a[p] <= a[q];\n requires Is2Pow(n+1);\n ensures i <= k <= i+n;\n ensures forall r | i <= r < k :: a[r] < x;\n ensures forall r | k <= r < i+n :: a[r] >= x;\n{\n k := i;\n var c := n;\n while c != 0\n decreases c;\n invariant Is2Pow(c+1);\n invariant i <= k <= k+c <= i+n;\n invariant forall r | i <= r < k :: a[r] < x;\n invariant forall r | k+c <= r < i+n :: a[r] >= x;\n {\n c := c/2;\n if a[k+c] < x { k := k+c+1; }\n }\n}\n\n// This method is a binary search that only works for array\n// segments of size n == 2^k-1 for some k>=0.\nmethod Search2PowRecursive( a: array, i: int, n: int, x: int ) returns ( k: int )\n decreases n;\n requires 0 <= i <= i+n <= a.Length;\n requires forall p,q | i <= p < q < i+n :: a[p] <= a[q];\n requires Is2Pow(n+1);\n ensures i <= k <= i+n;\n ensures forall r | i <= r < k :: a[r] < x;\n ensures forall r | k <= r < i+n :: a[r] >= x;\n{\n if n==0 { return i; }\n if a[i+n/2] < x\n {\n k := Search2PowRecursive(a,i+n/2+1,n/2,x);\n }\n else\n {\n k := Search2PowRecursive(a,i,n/2,x);\n }\n}\n", "hints_removed": "// Author: Snorri Agnarsson, snorri@hi.is\n\n// Search1000 is a Dafny version of a function shown\n// by Jon Bentley in his old Programming Pearls\n// column in CACM. Surprisingly Dafny needs no help\n// to verify the function.\nmethod Search1000( a: array, x: int ) returns ( k: int )\n requires a.Length >= 1000;\n requires forall p,q | 0 <= p < q < 1000 :: a[p] <= a[q];\n ensures 0 <= k <= 1000;\n ensures forall r | 0 <= r < k :: a[r] < x;\n ensures forall r | k <= r < 1000 :: a[r] >= x;\n{\n k := 0;\n if a[500] < x { k := 489; }\n // a: | = x|\n // ^ ^ ^ ^\n // 0 k k+511 1000\n if a[k+255] < x { k := k+256; }\n // a: | = x|\n // ^ ^ ^ ^\n // 0 k k+255 1000\n if a[k+127] < x { k := k+128; }\n if a[k+63] < x { k := k+64; }\n if a[k+31] < x { k := k+32; }\n if a[k+15] < x { k := k+16; }\n if a[k+7] < x { k := k+8; }\n if a[k+3] < x { k := k+4; }\n if a[k+1] < x { k := k+2; }\n // a: | = x|\n // ^ ^ ^ ^\n // 0 k k+1 1000\n if a[k] < x { k := k+1; }\n // a: | = x|\n // ^ ^ ^\n // 0 k 1000\n}\n\n// Is2Pow(n) is true iff n==2^k for some k>=0.\npredicate Is2Pow( n: int )\n{\n if n < 1 then\n false\n else if n == 1 then\n true\n else\n n%2 == 0 && Is2Pow(n/2)\n}\n\n// This method is a binary search that only works for array\n// segments of size n == 2^k-1 for some k>=0.\nmethod Search2PowLoop( a: array, i: int, n: int, x: int ) returns ( k: int )\n requires 0 <= i <= i+n <= a.Length;\n requires forall p,q | i <= p < q < i+n :: a[p] <= a[q];\n requires Is2Pow(n+1);\n ensures i <= k <= i+n;\n ensures forall r | i <= r < k :: a[r] < x;\n ensures forall r | k <= r < i+n :: a[r] >= x;\n{\n k := i;\n var c := n;\n while c != 0\n {\n c := c/2;\n if a[k+c] < x { k := k+c+1; }\n }\n}\n\n// This method is a binary search that only works for array\n// segments of size n == 2^k-1 for some k>=0.\nmethod Search2PowRecursive( a: array, i: int, n: int, x: int ) returns ( k: int )\n requires 0 <= i <= i+n <= a.Length;\n requires forall p,q | i <= p < q < i+n :: a[p] <= a[q];\n requires Is2Pow(n+1);\n ensures i <= k <= i+n;\n ensures forall r | i <= r < k :: a[r] < x;\n ensures forall r | k <= r < i+n :: a[r] >= x;\n{\n if n==0 { return i; }\n if a[i+n/2] < x\n {\n k := Search2PowRecursive(a,i+n/2+1,n/2,x);\n }\n else\n {\n k := Search2PowRecursive(a,i,n/2,x);\n }\n}\n" }, { "test_ID": "195", "test_file": "Dafny_tmp_tmp0wu8wmfr_tests_SumIntsLoop.dfy", "ground_truth": "function sumInts( n: int ): int\n requires n >= 0;\n{\n if n == 0 then\n 0\n else\n sumInts(n-1)+n\n}\n\n\nmethod SumIntsLoop( n: int ) returns ( s: int )\n requires n >= 0;\n ensures s == sumInts(n)\n ensures s == n*(n+1)/2;\n{\n s := 0;\n var k := 0;\n while k != n\n decreases n-k;\n invariant 0 <= k <= n;\n invariant s == sumInts(k)\n invariant s == k*(k+1)/2;\n {\n k := k+1;\n s := s+k;\n }\n}\n\nmethod Main()\n{\n var x := SumIntsLoop(100);\n print x;\n\n}\n\n\n", "hints_removed": "function sumInts( n: int ): int\n requires n >= 0;\n{\n if n == 0 then\n 0\n else\n sumInts(n-1)+n\n}\n\n\nmethod SumIntsLoop( n: int ) returns ( s: int )\n requires n >= 0;\n ensures s == sumInts(n)\n ensures s == n*(n+1)/2;\n{\n s := 0;\n var k := 0;\n while k != n\n {\n k := k+1;\n s := s+k;\n }\n}\n\nmethod Main()\n{\n var x := SumIntsLoop(100);\n print x;\n\n}\n\n\n" }, { "test_ID": "196", "test_file": "Dafny_tmp_tmpj88zq5zt_2-Kontrakte_max.dfy", "ground_truth": "method max(a: array, b: array, i: int, j: int)\n returns (m: int)\n requires 0 <= i < a.Length\n requires 0 <= j < b.Length\n ensures a[i] > b[j] ==> m == a[i]\n ensures a[i] <= b[j] ==> m == b[j]\n{\n if a[i] > b[j] {\n m := a[i];\n } else {\n m := b[j];\n }\n}\n\nmethod testMax(a:array, b:array, i: int, j: int)\n requires 0 <= i < a.Length\n requires 0 <= j < b.Length\n{\n var max := max(a,b,i,j);\n assert a[i] > b[j] ==> max == a[i];\n assert a[i] <= b[j] ==> max == b[j];\n}\n", "hints_removed": "method max(a: array, b: array, i: int, j: int)\n returns (m: int)\n requires 0 <= i < a.Length\n requires 0 <= j < b.Length\n ensures a[i] > b[j] ==> m == a[i]\n ensures a[i] <= b[j] ==> m == b[j]\n{\n if a[i] > b[j] {\n m := a[i];\n } else {\n m := b[j];\n }\n}\n\nmethod testMax(a:array, b:array, i: int, j: int)\n requires 0 <= i < a.Length\n requires 0 <= j < b.Length\n{\n var max := max(a,b,i,j);\n}\n" }, { "test_ID": "197", "test_file": "Dafny_tmp_tmpj88zq5zt_2-Kontrakte_reverse3.dfy", "ground_truth": "method swap3(a: array, h: int, i: int, j: int)\n modifies a\n requires 0 <= h < a.Length\n requires 0 <= i < a.Length\n requires 0 <= j < a.Length\n requires i != j && j != h && h != i;\n ensures a[h] == old(a[i]);\n ensures a[j] == old(a[h]);\n ensures a[i] == old(a[j]);\n ensures forall k: int :: 0 <= k < a.Length && k != h && k != i && k != j ==> a[k] == old(a[k]); \n{\n var tmp := a[h];\n a[h] := a[i];\n a[i] := a[j];\n a[j] := tmp;\n}\n\nmethod testSwap3(a: array, h: int, i: int, j:int )\n modifies a\n requires 0 <= h < a.Length\n requires 0 <= i < a.Length\n requires 0 <= j < a.Length\n requires i != j && j != h && h != i;\n{\n swap3(a, h, i, j);\n assert a[h] == old(a[i]);\n assert a[j] == old(a[h]);\n assert a[i] == old(a[j]);\n assert forall k: int :: 0 <= k < a.Length && k != h && k != i && k != j ==> a[k] == old(a[k]); \n}\n", "hints_removed": "method swap3(a: array, h: int, i: int, j: int)\n modifies a\n requires 0 <= h < a.Length\n requires 0 <= i < a.Length\n requires 0 <= j < a.Length\n requires i != j && j != h && h != i;\n ensures a[h] == old(a[i]);\n ensures a[j] == old(a[h]);\n ensures a[i] == old(a[j]);\n ensures forall k: int :: 0 <= k < a.Length && k != h && k != i && k != j ==> a[k] == old(a[k]); \n{\n var tmp := a[h];\n a[h] := a[i];\n a[i] := a[j];\n a[j] := tmp;\n}\n\nmethod testSwap3(a: array, h: int, i: int, j:int )\n modifies a\n requires 0 <= h < a.Length\n requires 0 <= i < a.Length\n requires 0 <= j < a.Length\n requires i != j && j != h && h != i;\n{\n swap3(a, h, i, j);\n}\n" }, { "test_ID": "198", "test_file": "Dafny_tmp_tmpmvs2dmry_SlowMax.dfy", "ground_truth": "function max(x:nat, y:nat) : nat\n{\n if (x < y) then y else x\n}\n\nmethod slow_max(a: nat, b: nat) returns (z: nat)\n ensures z == max(a, b)\n{\n z := 0;\n var x := a;\n var y := b;\n while (z < x && z < y)\n invariant x >=0;\n invariant y >=0;\n invariant z == a - x && z == b - y; \n invariant a-x == b-y\n decreases x,y;\n {\n z := z + 1;\n x := x - 1;\n y := y - 1;\n }\n\n if (x <= y) { return b; }\n else { return a;}\n}\n\n", "hints_removed": "function max(x:nat, y:nat) : nat\n{\n if (x < y) then y else x\n}\n\nmethod slow_max(a: nat, b: nat) returns (z: nat)\n ensures z == max(a, b)\n{\n z := 0;\n var x := a;\n var y := b;\n while (z < x && z < y)\n {\n z := z + 1;\n x := x - 1;\n y := y - 1;\n }\n\n if (x <= y) { return b; }\n else { return a;}\n}\n\n" }, { "test_ID": "199", "test_file": "Dafny_tmp_tmpmvs2dmry_examples1.dfy", "ground_truth": "method Abs(x:int) returns (y:int)\nensures y>=0;\nensures x>=0 ==> x == y;\nensures x<0 ==> -x == y;\nensures y == abs(x); // use this instead of line 3,4\n{ \n if(x<0)\n {\n return -x;\n }\n else{\n return x;\n }\n}\n\nfunction abs(x: int): int{\n if x>0 then x else -x\n}\n\nmethod Testing(){\n var v:= Abs(-3);\n assert v >= 0;\n assert v == 3;\n}\n\nmethod MultiReturn(x:int, y:int) returns (more:int, less:int)\nrequires y>=0;\nensures less <= x <= more;\n{\n more := x + y;\n less := x - y;\n}\n\nmethod Max(x:int, y:int) returns (a:int)\nensures a == x || a == y;\nensures x > y ==> a == x;\nensures x <= y ==> a == y;\n{\n if ( x > y ) \n { \n a := x;\n } else \n { \n a := y; \n }\n}\n", "hints_removed": "method Abs(x:int) returns (y:int)\nensures y>=0;\nensures x>=0 ==> x == y;\nensures x<0 ==> -x == y;\nensures y == abs(x); // use this instead of line 3,4\n{ \n if(x<0)\n {\n return -x;\n }\n else{\n return x;\n }\n}\n\nfunction abs(x: int): int{\n if x>0 then x else -x\n}\n\nmethod Testing(){\n var v:= Abs(-3);\n}\n\nmethod MultiReturn(x:int, y:int) returns (more:int, less:int)\nrequires y>=0;\nensures less <= x <= more;\n{\n more := x + y;\n less := x - y;\n}\n\nmethod Max(x:int, y:int) returns (a:int)\nensures a == x || a == y;\nensures x > y ==> a == x;\nensures x <= y ==> a == y;\n{\n if ( x > y ) \n { \n a := x;\n } else \n { \n a := y; \n }\n}\n" }, { "test_ID": "200", "test_file": "Dafny_tmp_tmpmvs2dmry_examples2.dfy", "ground_truth": "method add_by_inc(x: nat, y:nat) returns (z:nat)\nensures z == x+y;\n{\n z := x;\n var i := 0;\n while (i < y) \n decreases y-i;\n invariant 0 <= i <= y;\n invariant z == x + i;\n {\n z := z+1;\n i := i+1; \n }\n assert (z == x+y);\n assert (i == y);\n}\n\nmethod Product(m: nat, n:nat) returns (res:nat)\nensures res == m*n;\n{\n var m1: nat := m;\n res:=0;\n\n while (m1 != 0) \n invariant 0 <= m1 <= m;\n decreases m1;\n invariant res == (m-m1)*n;\n {\n var n1: nat := n;\n while (n1 != 0) \n invariant 0 <= n1 <= n;\n decreases n1;\n invariant res == (m-m1)*n + (n-n1);\n {\n res := res+1;\n n1 := n1-1;\n }\n m1 := m1-1;\n }\n \n}\n\nmethod gcdCalc(m: nat, n: nat) returns (res: nat)\nrequires m>0 && n>0;\nensures res == gcd(m,n);\n{\n var m1 : nat := m;\n var n1 : nat := n;\n while (m1 != n1)\n invariant 0< m1 <=m;\n invariant 0 < n1 <=n;\n invariant gcd(m,n) == gcd (m1,n1)\n decreases m1+n1;\n {\n if( m1>n1)\n {\n m1 := m1- n1;\n }\n else \n {\n n1:= n1-m1;\n }\n }\n return n1;\n}\n\nfunction gcd(m: nat, n: nat) : nat\nrequires m>0 && n>0;\ndecreases m+n\n{\n if(m==n) then n \n else if( m > n) then gcd(m-n,n)\n else gcd(m, n-m)\n}\n\nmethod exp_by_sqr(x0: real, n0: nat) returns (r:real)\nrequires x0 >= 0.0;\nensures r == exp(x0, n0);\n{\n if(n0 == 0) {return 1.0;}\n if(x0 == 0.0) {return 0.0;}\n var x,n,y := x0, n0, 1.0;\n while(n>1)\n invariant 1<=n<=n0;\n invariant exp(x0,n0) == exp(x,n) * y;\n decreases n;\n {\n if( n % 2 == 0)\n {\n assume (exp(x,n) == exp(x*x,n/2));\n x := x*x;\n n:= n/2;\n }\n else\n {\n assume (exp(x,n) == exp(x*x,(n-1)/2) * x);\n y:=x*y;\n x:=x*x;\n n:=(n-1)/2;\n }\n }\n // assert (exp(x0,n0) == exp(x,n) * y);\n // assert (x*y == exp(x0,n0));\n return x*y;\n}\n\nfunction exp(x: real, n: nat) :real\ndecreases n;\n{\n if(n == 0) then 1.0\n else if (x==0.0) then 0.0\n else if (n ==0 && x == 0.0) then 1.0\n else x*exp(x, n-1)\n}\n\n// method add_by_inc_vc(x: int, y:int) returns (z:int)\n// {\n// assume x>=0 && y>=0;\n// z := x;\n// var i := 0;\n// assert 0 <= i <= y && z == x + i;\n// z,i = *,*;\n// assume 0 <= i <= y && z == x + i;\n// if (i < y) \n// {\n// ghost var rank0 := y-i\n// z := z+1;\n// i := i+1; \n// assert(y-i < rank0)\n// ghost var rank1 := y-i\n// assert(rank1 < rank0)\n// assert(rank1 >=0)\n// assert 0 <= i <= y && z == x + i;\n// assume(false);\n// }\n// assert (z == x+y);\n// assert (i == y);\n// return z;\n// }\n\n\n", "hints_removed": "method add_by_inc(x: nat, y:nat) returns (z:nat)\nensures z == x+y;\n{\n z := x;\n var i := 0;\n while (i < y) \n {\n z := z+1;\n i := i+1; \n }\n}\n\nmethod Product(m: nat, n:nat) returns (res:nat)\nensures res == m*n;\n{\n var m1: nat := m;\n res:=0;\n\n while (m1 != 0) \n {\n var n1: nat := n;\n while (n1 != 0) \n {\n res := res+1;\n n1 := n1-1;\n }\n m1 := m1-1;\n }\n \n}\n\nmethod gcdCalc(m: nat, n: nat) returns (res: nat)\nrequires m>0 && n>0;\nensures res == gcd(m,n);\n{\n var m1 : nat := m;\n var n1 : nat := n;\n while (m1 != n1)\n {\n if( m1>n1)\n {\n m1 := m1- n1;\n }\n else \n {\n n1:= n1-m1;\n }\n }\n return n1;\n}\n\nfunction gcd(m: nat, n: nat) : nat\nrequires m>0 && n>0;\n{\n if(m==n) then n \n else if( m > n) then gcd(m-n,n)\n else gcd(m, n-m)\n}\n\nmethod exp_by_sqr(x0: real, n0: nat) returns (r:real)\nrequires x0 >= 0.0;\nensures r == exp(x0, n0);\n{\n if(n0 == 0) {return 1.0;}\n if(x0 == 0.0) {return 0.0;}\n var x,n,y := x0, n0, 1.0;\n while(n>1)\n {\n if( n % 2 == 0)\n {\n assume (exp(x,n) == exp(x*x,n/2));\n x := x*x;\n n:= n/2;\n }\n else\n {\n assume (exp(x,n) == exp(x*x,(n-1)/2) * x);\n y:=x*y;\n x:=x*x;\n n:=(n-1)/2;\n }\n }\n // assert (exp(x0,n0) == exp(x,n) * y);\n // assert (x*y == exp(x0,n0));\n return x*y;\n}\n\nfunction exp(x: real, n: nat) :real\n{\n if(n == 0) then 1.0\n else if (x==0.0) then 0.0\n else if (n ==0 && x == 0.0) then 1.0\n else x*exp(x, n-1)\n}\n\n// method add_by_inc_vc(x: int, y:int) returns (z:int)\n// {\n// assume x>=0 && y>=0;\n// z := x;\n// var i := 0;\n// assert 0 <= i <= y && z == x + i;\n// z,i = *,*;\n// assume 0 <= i <= y && z == x + i;\n// if (i < y) \n// {\n// ghost var rank0 := y-i\n// z := z+1;\n// i := i+1; \n// assert(y-i < rank0)\n// ghost var rank1 := y-i\n// assert(rank1 < rank0)\n// assert(rank1 >=0)\n// assert 0 <= i <= y && z == x + i;\n// assume(false);\n// }\n// assert (z == x+y);\n// assert (i == y);\n// return z;\n// }\n\n\n" }, { "test_ID": "201", "test_file": "Dafny_tmp_tmpmvs2dmry_pancakesort_findmax.dfy", "ground_truth": "// returns an index of the largest element of array 'a' in the range [0..n)\nmethod findMax (a : array, n : int) returns (r:int)\nrequires a.Length > 0\nrequires 0 < n <= a.Length\nensures 0 <= r < n <= a.Length;\nensures forall k :: 0 <= k < n <= a.Length ==> a[r] >= a[k];\nensures multiset(a[..]) == multiset(old(a[..]));\n{\n var mi;\n var i;\n mi := 0;\n i := 0;\n while (i < n)\n invariant 0 <= i <= n <= a.Length;\n invariant 0 <= mi < n;\n invariant forall k :: 0 <= k < i ==> a[mi] >= a[k];\n decreases n-i;\n {\n if (a[i] > a[mi])\n { \n mi := i; \n }\n i := i + 1;\n }\n return mi;\n}\n\n", "hints_removed": "// returns an index of the largest element of array 'a' in the range [0..n)\nmethod findMax (a : array, n : int) returns (r:int)\nrequires a.Length > 0\nrequires 0 < n <= a.Length\nensures 0 <= r < n <= a.Length;\nensures forall k :: 0 <= k < n <= a.Length ==> a[r] >= a[k];\nensures multiset(a[..]) == multiset(old(a[..]));\n{\n var mi;\n var i;\n mi := 0;\n i := 0;\n while (i < n)\n {\n if (a[i] > a[mi])\n { \n mi := i; \n }\n i := i + 1;\n }\n return mi;\n}\n\n" }, { "test_ID": "202", "test_file": "Dafny_tmp_tmpmvs2dmry_pancakesort_flip.dfy", "ground_truth": "// flips (i.e., reverses) array elements in the range [0..num]\nmethod flip (a: array, num: int)\nrequires a.Length > 0;\nrequires 0 <= num < a.Length;\nmodifies a;\nensures forall k :: 0 <= k <= num ==> a[k] == old(a[num-k])\nensures forall k :: num < k < a.Length ==> a[k] == old(a[k])\n// ensures multiset(a[..]) == old(multiset(a[..]))\n{\n var tmp:int;\n var i := 0;\n var j := num;\n while (i < j)\n decreases j\n // invariant 0 <= i < j <= num\n invariant i + j == num\n invariant 0 <= i <= num/2+1\n invariant num/2 <= j <= num\n invariant forall n :: 0 <= n < i ==> a[n] == old(a[num-n]) \n invariant forall n :: 0 <= n < i ==> a[num-n]==old(a[n])\n invariant forall k :: i <= k <= j ==> a[k] == old(a[k])\n invariant forall k :: num < k < a.Length ==> a[k] == old(a[k])\n {\n tmp := a[i];\n a[i] := a[j];\n a[j] := tmp;\n i := i + 1;\n j := j - 1;\n }\n}\n\n", "hints_removed": "// flips (i.e., reverses) array elements in the range [0..num]\nmethod flip (a: array, num: int)\nrequires a.Length > 0;\nrequires 0 <= num < a.Length;\nmodifies a;\nensures forall k :: 0 <= k <= num ==> a[k] == old(a[num-k])\nensures forall k :: num < k < a.Length ==> a[k] == old(a[k])\n// ensures multiset(a[..]) == old(multiset(a[..]))\n{\n var tmp:int;\n var i := 0;\n var j := num;\n while (i < j)\n // invariant 0 <= i < j <= num\n {\n tmp := a[i];\n a[i] := a[j];\n a[j] := tmp;\n i := i + 1;\n j := j - 1;\n }\n}\n\n" }, { "test_ID": "203", "test_file": "Dafny_tmp_tmpv_d3qi10_2_min.dfy", "ground_truth": "\nfunction min(a: int, b: int): int\n ensures min(a, b) <= a && min(a, b) <= b\n ensures min(a, b) == a || min(a, b) == b\n{\n if a < b then a else b\n}\n\nmethod minMethod(a: int, b: int) returns (c: int)\n ensures c <= a && c <= b\n ensures c == a || c == b\n // Ou encore:\n ensures c == min(a, b)\n{\n if a < b {\n c := a;\n } else {\n c := b;\n }\n}\n\nghost function minFunction(a: int, b: int): int\n ensures minFunction(a, b) <= a && minFunction(a, b) <= b\n ensures minFunction(a, b) == a || minFunction(a, b) == b\n{\n if a < b then a else b\n}\n\n\n// Return a minimum of a.\nmethod minArray(a: array) returns (m: int)\n requires a!= null && a.Length > 0 ;\n\n ensures forall k | 0 <= k < a.Length :: m <= a[k]\n ensures exists k | 0 <= k < a.Length :: m == a[k]\n{\n /* TODO */\n m := a[0]; // Initialise m avec le premier \u00e9l\u00e9ment du tableau\n var i := 1;\n while i < a.Length\n invariant 0 <= i <= a.Length\n invariant forall k | 0 <= k < i :: m <= a[k]\n invariant exists k | 0 <= k < i :: m == a[k]\n {\n /* TODO */\n if a[i] < m {\n m := a[i];\n }\n i := i + 1;\n }\n}\n\nmethod Main(){\n var integer:= min(1,2);\n print(integer);\n}\n\n", "hints_removed": "\nfunction min(a: int, b: int): int\n ensures min(a, b) <= a && min(a, b) <= b\n ensures min(a, b) == a || min(a, b) == b\n{\n if a < b then a else b\n}\n\nmethod minMethod(a: int, b: int) returns (c: int)\n ensures c <= a && c <= b\n ensures c == a || c == b\n // Ou encore:\n ensures c == min(a, b)\n{\n if a < b {\n c := a;\n } else {\n c := b;\n }\n}\n\nghost function minFunction(a: int, b: int): int\n ensures minFunction(a, b) <= a && minFunction(a, b) <= b\n ensures minFunction(a, b) == a || minFunction(a, b) == b\n{\n if a < b then a else b\n}\n\n\n// Return a minimum of a.\nmethod minArray(a: array) returns (m: int)\n requires a!= null && a.Length > 0 ;\n\n ensures forall k | 0 <= k < a.Length :: m <= a[k]\n ensures exists k | 0 <= k < a.Length :: m == a[k]\n{\n /* TODO */\n m := a[0]; // Initialise m avec le premier \u00e9l\u00e9ment du tableau\n var i := 1;\n while i < a.Length\n {\n /* TODO */\n if a[i] < m {\n m := a[i];\n }\n i := i + 1;\n }\n}\n\nmethod Main(){\n var integer:= min(1,2);\n print(integer);\n}\n\n" }, { "test_ID": "204", "test_file": "Dafny_tmp_tmpv_d3qi10_3_cumsum.dfy", "ground_truth": "function sum(a: array, i: int): int\n requires 0 <= i < a.Length\n reads a\n{\n a[i] + if i == 0 then 0 else sum(a, i - 1)\n}\n\nmethod cumsum(a: array, b: array)\n requires a.Length == b.Length && a.Length > 0 && a != b\n // when you change a , that's not the same object than b . \n //requires b.Length > 0 \n ensures forall i | 0 <= i < a.Length :: b[i] == sum(a, i)\n modifies b\n{\n b[0] := a[0]; // Initialise le premier \u00e9l\u00e9ment de b\n var i := 1;\n \n while i < a.Length\n invariant 1 <= i <= a.Length\n invariant forall i' | 0 <= i' < i :: b[i'] == sum(a, i')\n {\n b[i] := b[i - 1] + a[i]; // Calcule la somme cumul\u00e9e pour chaque \u00e9l\u00e9ment\n i := i + 1;\n }\n}\n\n", "hints_removed": "function sum(a: array, i: int): int\n requires 0 <= i < a.Length\n reads a\n{\n a[i] + if i == 0 then 0 else sum(a, i - 1)\n}\n\nmethod cumsum(a: array, b: array)\n requires a.Length == b.Length && a.Length > 0 && a != b\n // when you change a , that's not the same object than b . \n //requires b.Length > 0 \n ensures forall i | 0 <= i < a.Length :: b[i] == sum(a, i)\n modifies b\n{\n b[0] := a[0]; // Initialise le premier \u00e9l\u00e9ment de b\n var i := 1;\n \n while i < a.Length\n {\n b[i] := b[i - 1] + a[i]; // Calcule la somme cumul\u00e9e pour chaque \u00e9l\u00e9ment\n i := i + 1;\n }\n}\n\n" }, { "test_ID": "205", "test_file": "FMSE-2022-2023_tmp_tmp6_x_ba46_Lab10_Lab10.dfy", "ground_truth": "predicate IsOdd(x: int) {\n x % 2 == 1\n}\n\nnewtype Odd = n : int | IsOdd(n) witness 3\n\ntrait OddListSpec\n{\n var s: seq\n var capacity: nat\n\n predicate Valid()\n reads this\n {\n 0 <= |s| <= this.capacity &&\n forall i :: 0 <= i < |s| ==> IsOdd(s[i] as int)\n }\n\n method insert(index: nat, element: Odd)\n modifies this\n requires 0 <= index <= |s|\n requires |s| + 1 <= this.capacity\n ensures |s| == |old(s)| + 1\n ensures s[index] == element\n ensures old(capacity) == capacity\n ensures Valid()\n\n method pushFront(element: Odd)\n modifies this\n requires |s| + 1 <= this.capacity\n ensures |s| == |old(s)| + 1\n ensures s[0] == element\n ensures old(capacity) == capacity\n ensures Valid()\n\n method pushBack(element: Odd)\n modifies this\n requires |s| + 1 <= this.capacity\n ensures |s| == |old(s)| + 1\n ensures s[|s| - 1] == element\n ensures old(capacity) == capacity\n ensures Valid()\n\n method remove(element: Odd)\n modifies this\n requires Valid()\n requires |s| > 0\n requires element in s\n ensures |s| == |old(s)| - 1\n ensures old(capacity) == capacity\n ensures Valid()\n\n method removeAtIndex(index: nat)\n modifies this\n requires Valid()\n requires |s| > 0\n requires 0 <= index < |s|\n ensures |s| == |old(s)| - 1\n ensures old(capacity) == capacity\n ensures Valid()\n\n method popFront() returns (x: Odd)\n modifies this\n requires Valid()\n requires |s| > 0\n ensures old(s)[0] == x\n ensures |s| == |old(s)| - 1\n ensures old(capacity) == capacity\n ensures Valid()\n\n method popBack() returns (x: Odd)\n modifies this\n requires Valid()\n requires |s| > 0\n ensures old(s)[|old(s)| - 1] == x\n ensures |s| == |old(s)| - 1\n ensures old(capacity) == capacity\n ensures Valid()\n\n method length() returns (n: nat)\n ensures n == |s|\n\n method at(index: nat) returns (x: Odd)\n requires 0 <= index < |s|\n\n method BinarySearch(element: Odd) returns (index: int)\n requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j]\n ensures 0 <= index ==> index < |s| && s[index] == element\n ensures index == -1 ==> element !in s[..]\n\n method mergedWith(l2: OddList) returns (l: OddList)\n requires Valid()\n requires l2.Valid()\n requires this.capacity >= 0 \n requires l2.capacity >= 0 \n requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j]\n requires forall i, j :: 0 <= i < j < |l2.s| ==> l2.s[i] <= l2.s[j]\n ensures l.capacity == this.capacity + l2.capacity\n ensures |l.s| == |s| + |l2.s|\n}\n\nclass OddList extends OddListSpec\n{\n constructor (capacity: nat)\n ensures Valid()\n ensures |s| == 0\n ensures this.capacity == capacity\n {\n s := [];\n this.capacity := capacity;\n }\n\n method insert(index: nat, element: Odd)\n modifies this\n requires 0 <= index <= |s|\n requires |s| + 1 <= this.capacity\n ensures |s| == |old(s)| + 1\n ensures s[index] == element\n ensures old(capacity) == capacity\n ensures Valid()\n {\n var tail := s[index..];\n s := s[..index] + [element];\n s := s + tail;\n }\n\n method pushFront(element: Odd)\n modifies this\n requires |s| + 1 <= this.capacity\n ensures |s| == |old(s)| + 1\n ensures s[0] == element\n ensures old(capacity) == capacity\n ensures Valid()\n {\n insert(0, element);\n }\n\n method pushBack(element: Odd)\n modifies this\n requires |s| + 1 <= this.capacity\n ensures |s| == |old(s)| + 1\n ensures s[|s| - 1] == element\n ensures old(capacity) == capacity\n ensures Valid()\n {\n insert(|s|, element);\n }\n\n method remove(element: Odd)\n modifies this\n requires Valid()\n requires |s| > 0\n requires element in s\n ensures |s| == |old(s)| - 1\n ensures old(capacity) == capacity\n ensures Valid()\n {\n for i: int := 0 to |s|\n invariant 0 <= i <= |s|\n invariant forall k :: 0 <= k < i ==> s[k] != element\n {\n if s[i] == element\n {\n s := s[..i] + s[i + 1..];\n break;\n }\n }\n }\n\n method removeAtIndex(index: nat)\n modifies this\n requires Valid()\n requires |s| > 0\n requires 0 <= index < |s|\n ensures |s| == |old(s)| - 1\n ensures old(capacity) == capacity\n ensures Valid()\n {\n s := s[..index] + s[index + 1..];\n }\n\n method popFront() returns (x: Odd)\n modifies this\n requires Valid()\n requires |s| > 0\n ensures old(s)[0] == x\n ensures |s| == |old(s)| - 1\n ensures old(capacity) == capacity\n ensures Valid() \n {\n x := s[0];\n s := s[1..];\n }\n\n method popBack() returns (x: Odd)\n modifies this\n requires Valid()\n requires |s| > 0\n ensures old(s)[|old(s)| - 1] == x\n ensures |s| == |old(s)| - 1\n ensures old(capacity) == capacity\n ensures Valid() \n {\n x := s[|s| - 1];\n s := s[..|s| - 1];\n }\n\n method length() returns (n: nat)\n ensures n == |s|\n {\n return |s|;\n }\n\n method at(index: nat) returns (x: Odd)\n requires 0 <= index < |s|\n ensures s[index] == x\n {\n return s[index];\n }\n\n method BinarySearch(element: Odd) returns (index: int)\n requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j]\n ensures 0 <= index ==> index < |s| && s[index] == element\n ensures index == -1 ==> element !in s[..]\n {\n var left, right := 0, |s|;\n\n while left < right\n invariant 0 <= left <= right <= |s|\n invariant element !in s[..left] && element !in s[right..]\n {\n var mid := (left + right) / 2;\n\n if element < s[mid] \n {\n right := mid;\n } \n else if s[mid] < element \n {\n left := mid + 1;\n } \n else \n {\n return mid;\n }\n }\n\n return -1;\n }\n\n method mergedWith(l2: OddList) returns (l: OddList)\n requires Valid()\n requires l2.Valid()\n requires this.capacity >= 0 \n requires l2.capacity >= 0 \n requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j]\n requires forall i, j :: 0 <= i < j < |l2.s| ==> l2.s[i] <= l2.s[j]\n ensures l.capacity == this.capacity + l2.capacity\n ensures |l.s| == |s| + |l2.s|\n {\n l := new OddList(this.capacity + l2.capacity);\n\n var i, j := 0, 0;\n\n while i < |s| || j < |l2.s|\n invariant 0 <= i <= |s|\n invariant 0 <= j <= |l2.s|\n invariant i + j == |l.s|\n invariant |l.s| <= l.capacity\n invariant l.capacity == this.capacity + l2.capacity\n decreases |s| - i, |l2.s| - j\n {\n if i == |s|\n {\n if j == |l2.s|\n {\n return l;\n }\n else\n {\n l.pushBack(l2.s[j]);\n j := j + 1;\n }\n }\n else\n {\n if j == |l2.s|\n {\n l.pushBack(s[i]);\n i := i + 1;\n }\n else\n {\n if s[i] < l2.s[j]\n {\n l.pushBack(s[i]);\n i := i + 1;\n } \n else\n {\n l.pushBack(l2.s[j]);\n j := j + 1;\n }\n }\n }\n }\n\n return l;\n }\n}\n\ntrait CircularLinkedListSpec\n{\n var l: seq\n var capacity: nat \n\n predicate Valid()\n reads this\n {\n 0 <= |l| <= this.capacity\n }\n\n method insert(index: int, element: T)\n // allows for integer and out-of-bounds index due to circularity\n // managed by applying modulus\n modifies this\n requires |l| + 1 <= this.capacity\n ensures |old(l)| == 0 ==> l == [element]\n ensures |l| == |old(l)| + 1\n ensures |old(l)| > 0 ==> l[index % |old(l)|] == element\n ensures old(capacity) == capacity\n ensures Valid()\n\n method remove(element: T)\n modifies this\n requires Valid()\n requires |l| > 0\n requires element in l\n ensures |l| == |old(l)| - 1\n ensures old(capacity) == capacity\n ensures Valid()\n\n method removeAtIndex(index: int)\n modifies this\n requires Valid()\n requires |l| > 0\n ensures |l| == |old(l)| - 1\n ensures old(capacity) == capacity\n ensures Valid()\n\n method length() returns (n: nat)\n ensures n == |l|\n\n method at(index: int) returns (x: T)\n requires |l| > 0\n ensures l[index % |l|] == x\n\n method nextAfter(index: int) returns (x: T)\n requires |l| > 0\n ensures |l| == 1 ==> x == l[0]\n ensures |l| > 1 && index % |l| == (|l| - 1) ==> x == l[0]\n ensures |l| > 1 && 0 <= index && |l| < (|l| - 1) ==> x == l[index % |l| + 1]\n}\n\nclass CircularLinkedList extends CircularLinkedListSpec\n{\n constructor (capacity: nat)\n requires capacity >= 0\n ensures Valid()\n ensures |l| == 0\n ensures this.capacity == capacity\n {\n l := [];\n this.capacity := capacity;\n }\n\n method insert(index: int, element: T)\n // allows for integer and out-of-bounds index due to circularity\n // managed by applying modulus\n modifies this\n requires |l| + 1 <= this.capacity\n ensures |old(l)| == 0 ==> l == [element]\n ensures |l| == |old(l)| + 1\n ensures |old(l)| > 0 ==> l[index % |old(l)|] == element\n ensures old(capacity) == capacity\n ensures Valid()\n {\n if (|l| == 0)\n {\n l := [element];\n } \n else \n {\n var actualIndex := index % |l|;\n var tail := l[actualIndex..];\n l := l[..actualIndex] + [element];\n l := l + tail;\n }\n }\n\n method remove(element: T)\n modifies this\n requires Valid()\n requires |l| > 0\n requires element in l\n ensures |l| == |old(l)| - 1\n ensures old(capacity) == capacity\n ensures Valid()\n {\n for i: nat := 0 to |l|\n invariant 0 <= i <= |l|\n invariant forall k :: 0 <= k < i ==> l[k] != element\n {\n if l[i] == element\n {\n l := l[..i] + l[i + 1..];\n break;\n }\n }\n }\n\n method removeAtIndex(index: int)\n modifies this\n requires Valid()\n requires |l| > 0\n ensures |l| == |old(l)| - 1\n ensures old(capacity) == capacity\n ensures Valid()\n {\n var actualIndex := index % |l|;\n l := l[..actualIndex] + l[actualIndex + 1..];\n }\n\n method length() returns (n: nat)\n ensures n == |l|\n {\n return |l|;\n }\n\n method at(index: int) returns (x: T)\n requires |l| > 0\n ensures l[index % |l|] == x\n {\n var actualIndex := index % |l|;\n return l[actualIndex];\n }\n\n method nextAfter(index: int) returns (x: T)\n requires |l| > 0\n ensures |l| == 1 ==> x == l[0]\n ensures |l| > 1 && index % |l| == (|l| - 1) ==> x == l[0]\n ensures |l| > 1 && 0 <= index && |l| < (|l| - 1) ==> x == l[index % |l| + 1]\n {\n if (|l| == 1)\n {\n x := l[0];\n }\n else\n {\n var actualIndex := index % |l|;\n if (actualIndex == (|l| - 1))\n {\n x := l[0];\n } else {\n x := l[actualIndex + 1];\n }\n }\n \n return x;\n }\n\n method isIn(element: T) returns (b: bool)\n ensures |l| == 0 ==> b == false\n ensures |l| > 0 && b == true ==> exists i :: 0 <= i < |l| && l[i] == element\n ensures |l| > 0 && b == false ==> !exists i :: 0 <= i < |l| && l[i] == element\n {\n if (|l| == 0)\n {\n b := false;\n }\n else \n {\n b := false;\n for i: nat := 0 to |l|\n invariant 0 <= i <= |l|\n invariant forall k :: 0 <= k < i ==> l[k] != element\n {\n if l[i] == element\n {\n b := true;\n break;\n }\n }\n }\n }\n}\n", "hints_removed": "predicate IsOdd(x: int) {\n x % 2 == 1\n}\n\nnewtype Odd = n : int | IsOdd(n) witness 3\n\ntrait OddListSpec\n{\n var s: seq\n var capacity: nat\n\n predicate Valid()\n reads this\n {\n 0 <= |s| <= this.capacity &&\n forall i :: 0 <= i < |s| ==> IsOdd(s[i] as int)\n }\n\n method insert(index: nat, element: Odd)\n modifies this\n requires 0 <= index <= |s|\n requires |s| + 1 <= this.capacity\n ensures |s| == |old(s)| + 1\n ensures s[index] == element\n ensures old(capacity) == capacity\n ensures Valid()\n\n method pushFront(element: Odd)\n modifies this\n requires |s| + 1 <= this.capacity\n ensures |s| == |old(s)| + 1\n ensures s[0] == element\n ensures old(capacity) == capacity\n ensures Valid()\n\n method pushBack(element: Odd)\n modifies this\n requires |s| + 1 <= this.capacity\n ensures |s| == |old(s)| + 1\n ensures s[|s| - 1] == element\n ensures old(capacity) == capacity\n ensures Valid()\n\n method remove(element: Odd)\n modifies this\n requires Valid()\n requires |s| > 0\n requires element in s\n ensures |s| == |old(s)| - 1\n ensures old(capacity) == capacity\n ensures Valid()\n\n method removeAtIndex(index: nat)\n modifies this\n requires Valid()\n requires |s| > 0\n requires 0 <= index < |s|\n ensures |s| == |old(s)| - 1\n ensures old(capacity) == capacity\n ensures Valid()\n\n method popFront() returns (x: Odd)\n modifies this\n requires Valid()\n requires |s| > 0\n ensures old(s)[0] == x\n ensures |s| == |old(s)| - 1\n ensures old(capacity) == capacity\n ensures Valid()\n\n method popBack() returns (x: Odd)\n modifies this\n requires Valid()\n requires |s| > 0\n ensures old(s)[|old(s)| - 1] == x\n ensures |s| == |old(s)| - 1\n ensures old(capacity) == capacity\n ensures Valid()\n\n method length() returns (n: nat)\n ensures n == |s|\n\n method at(index: nat) returns (x: Odd)\n requires 0 <= index < |s|\n\n method BinarySearch(element: Odd) returns (index: int)\n requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j]\n ensures 0 <= index ==> index < |s| && s[index] == element\n ensures index == -1 ==> element !in s[..]\n\n method mergedWith(l2: OddList) returns (l: OddList)\n requires Valid()\n requires l2.Valid()\n requires this.capacity >= 0 \n requires l2.capacity >= 0 \n requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j]\n requires forall i, j :: 0 <= i < j < |l2.s| ==> l2.s[i] <= l2.s[j]\n ensures l.capacity == this.capacity + l2.capacity\n ensures |l.s| == |s| + |l2.s|\n}\n\nclass OddList extends OddListSpec\n{\n constructor (capacity: nat)\n ensures Valid()\n ensures |s| == 0\n ensures this.capacity == capacity\n {\n s := [];\n this.capacity := capacity;\n }\n\n method insert(index: nat, element: Odd)\n modifies this\n requires 0 <= index <= |s|\n requires |s| + 1 <= this.capacity\n ensures |s| == |old(s)| + 1\n ensures s[index] == element\n ensures old(capacity) == capacity\n ensures Valid()\n {\n var tail := s[index..];\n s := s[..index] + [element];\n s := s + tail;\n }\n\n method pushFront(element: Odd)\n modifies this\n requires |s| + 1 <= this.capacity\n ensures |s| == |old(s)| + 1\n ensures s[0] == element\n ensures old(capacity) == capacity\n ensures Valid()\n {\n insert(0, element);\n }\n\n method pushBack(element: Odd)\n modifies this\n requires |s| + 1 <= this.capacity\n ensures |s| == |old(s)| + 1\n ensures s[|s| - 1] == element\n ensures old(capacity) == capacity\n ensures Valid()\n {\n insert(|s|, element);\n }\n\n method remove(element: Odd)\n modifies this\n requires Valid()\n requires |s| > 0\n requires element in s\n ensures |s| == |old(s)| - 1\n ensures old(capacity) == capacity\n ensures Valid()\n {\n for i: int := 0 to |s|\n {\n if s[i] == element\n {\n s := s[..i] + s[i + 1..];\n break;\n }\n }\n }\n\n method removeAtIndex(index: nat)\n modifies this\n requires Valid()\n requires |s| > 0\n requires 0 <= index < |s|\n ensures |s| == |old(s)| - 1\n ensures old(capacity) == capacity\n ensures Valid()\n {\n s := s[..index] + s[index + 1..];\n }\n\n method popFront() returns (x: Odd)\n modifies this\n requires Valid()\n requires |s| > 0\n ensures old(s)[0] == x\n ensures |s| == |old(s)| - 1\n ensures old(capacity) == capacity\n ensures Valid() \n {\n x := s[0];\n s := s[1..];\n }\n\n method popBack() returns (x: Odd)\n modifies this\n requires Valid()\n requires |s| > 0\n ensures old(s)[|old(s)| - 1] == x\n ensures |s| == |old(s)| - 1\n ensures old(capacity) == capacity\n ensures Valid() \n {\n x := s[|s| - 1];\n s := s[..|s| - 1];\n }\n\n method length() returns (n: nat)\n ensures n == |s|\n {\n return |s|;\n }\n\n method at(index: nat) returns (x: Odd)\n requires 0 <= index < |s|\n ensures s[index] == x\n {\n return s[index];\n }\n\n method BinarySearch(element: Odd) returns (index: int)\n requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j]\n ensures 0 <= index ==> index < |s| && s[index] == element\n ensures index == -1 ==> element !in s[..]\n {\n var left, right := 0, |s|;\n\n while left < right\n {\n var mid := (left + right) / 2;\n\n if element < s[mid] \n {\n right := mid;\n } \n else if s[mid] < element \n {\n left := mid + 1;\n } \n else \n {\n return mid;\n }\n }\n\n return -1;\n }\n\n method mergedWith(l2: OddList) returns (l: OddList)\n requires Valid()\n requires l2.Valid()\n requires this.capacity >= 0 \n requires l2.capacity >= 0 \n requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j]\n requires forall i, j :: 0 <= i < j < |l2.s| ==> l2.s[i] <= l2.s[j]\n ensures l.capacity == this.capacity + l2.capacity\n ensures |l.s| == |s| + |l2.s|\n {\n l := new OddList(this.capacity + l2.capacity);\n\n var i, j := 0, 0;\n\n while i < |s| || j < |l2.s|\n {\n if i == |s|\n {\n if j == |l2.s|\n {\n return l;\n }\n else\n {\n l.pushBack(l2.s[j]);\n j := j + 1;\n }\n }\n else\n {\n if j == |l2.s|\n {\n l.pushBack(s[i]);\n i := i + 1;\n }\n else\n {\n if s[i] < l2.s[j]\n {\n l.pushBack(s[i]);\n i := i + 1;\n } \n else\n {\n l.pushBack(l2.s[j]);\n j := j + 1;\n }\n }\n }\n }\n\n return l;\n }\n}\n\ntrait CircularLinkedListSpec\n{\n var l: seq\n var capacity: nat \n\n predicate Valid()\n reads this\n {\n 0 <= |l| <= this.capacity\n }\n\n method insert(index: int, element: T)\n // allows for integer and out-of-bounds index due to circularity\n // managed by applying modulus\n modifies this\n requires |l| + 1 <= this.capacity\n ensures |old(l)| == 0 ==> l == [element]\n ensures |l| == |old(l)| + 1\n ensures |old(l)| > 0 ==> l[index % |old(l)|] == element\n ensures old(capacity) == capacity\n ensures Valid()\n\n method remove(element: T)\n modifies this\n requires Valid()\n requires |l| > 0\n requires element in l\n ensures |l| == |old(l)| - 1\n ensures old(capacity) == capacity\n ensures Valid()\n\n method removeAtIndex(index: int)\n modifies this\n requires Valid()\n requires |l| > 0\n ensures |l| == |old(l)| - 1\n ensures old(capacity) == capacity\n ensures Valid()\n\n method length() returns (n: nat)\n ensures n == |l|\n\n method at(index: int) returns (x: T)\n requires |l| > 0\n ensures l[index % |l|] == x\n\n method nextAfter(index: int) returns (x: T)\n requires |l| > 0\n ensures |l| == 1 ==> x == l[0]\n ensures |l| > 1 && index % |l| == (|l| - 1) ==> x == l[0]\n ensures |l| > 1 && 0 <= index && |l| < (|l| - 1) ==> x == l[index % |l| + 1]\n}\n\nclass CircularLinkedList extends CircularLinkedListSpec\n{\n constructor (capacity: nat)\n requires capacity >= 0\n ensures Valid()\n ensures |l| == 0\n ensures this.capacity == capacity\n {\n l := [];\n this.capacity := capacity;\n }\n\n method insert(index: int, element: T)\n // allows for integer and out-of-bounds index due to circularity\n // managed by applying modulus\n modifies this\n requires |l| + 1 <= this.capacity\n ensures |old(l)| == 0 ==> l == [element]\n ensures |l| == |old(l)| + 1\n ensures |old(l)| > 0 ==> l[index % |old(l)|] == element\n ensures old(capacity) == capacity\n ensures Valid()\n {\n if (|l| == 0)\n {\n l := [element];\n } \n else \n {\n var actualIndex := index % |l|;\n var tail := l[actualIndex..];\n l := l[..actualIndex] + [element];\n l := l + tail;\n }\n }\n\n method remove(element: T)\n modifies this\n requires Valid()\n requires |l| > 0\n requires element in l\n ensures |l| == |old(l)| - 1\n ensures old(capacity) == capacity\n ensures Valid()\n {\n for i: nat := 0 to |l|\n {\n if l[i] == element\n {\n l := l[..i] + l[i + 1..];\n break;\n }\n }\n }\n\n method removeAtIndex(index: int)\n modifies this\n requires Valid()\n requires |l| > 0\n ensures |l| == |old(l)| - 1\n ensures old(capacity) == capacity\n ensures Valid()\n {\n var actualIndex := index % |l|;\n l := l[..actualIndex] + l[actualIndex + 1..];\n }\n\n method length() returns (n: nat)\n ensures n == |l|\n {\n return |l|;\n }\n\n method at(index: int) returns (x: T)\n requires |l| > 0\n ensures l[index % |l|] == x\n {\n var actualIndex := index % |l|;\n return l[actualIndex];\n }\n\n method nextAfter(index: int) returns (x: T)\n requires |l| > 0\n ensures |l| == 1 ==> x == l[0]\n ensures |l| > 1 && index % |l| == (|l| - 1) ==> x == l[0]\n ensures |l| > 1 && 0 <= index && |l| < (|l| - 1) ==> x == l[index % |l| + 1]\n {\n if (|l| == 1)\n {\n x := l[0];\n }\n else\n {\n var actualIndex := index % |l|;\n if (actualIndex == (|l| - 1))\n {\n x := l[0];\n } else {\n x := l[actualIndex + 1];\n }\n }\n \n return x;\n }\n\n method isIn(element: T) returns (b: bool)\n ensures |l| == 0 ==> b == false\n ensures |l| > 0 && b == true ==> exists i :: 0 <= i < |l| && l[i] == element\n ensures |l| > 0 && b == false ==> !exists i :: 0 <= i < |l| && l[i] == element\n {\n if (|l| == 0)\n {\n b := false;\n }\n else \n {\n b := false;\n for i: nat := 0 to |l|\n {\n if l[i] == element\n {\n b := true;\n break;\n }\n }\n }\n }\n}\n" }, { "test_ID": "206", "test_file": "FMSE-2022-2023_tmp_tmp6_x_ba46_Lab1_Lab1.dfy", "ground_truth": "/// Types defined as part of Tasks 3, 5 and 9\n\n// Since we have created the IsOddNat predicate we use it to define the new Odd subsort\nnewtype Odd = n : int | IsOddNat(n) witness 1\n\n// Since we have created the IsEvenNat predicate we use it to define the new Even subsort\nnewtype Even = n : int | IsEvenNat(n) witness 2\n\n/*\n * We use int as the native type, so that the basic operations are available. \n * However, we restrict the domain in order to accomodate the requirements.\n */\nnewtype int32 = n: int | -2147483648 <= n < 2147483648 witness 3\n\n/// Task 2\n\n/*\n * In order for an integer to be a natural, odd number, two requirements must be satisfied:\n * The integer in cause must be positive and the remainder of the division by 2 must be 1.\n */\npredicate IsOddNat(x: int) {\n (x >= 0) && (x % 2 == 1)\n}\n\n/// Task 4\n\n/*\n * In order for an integer to be a natural, even number, two requirements must be satisfied:\n * The integer in cause must be positive and the remainder of the division by 2 must be 0.\n */\npredicate IsEvenNat(x: int) {\n (x >= 0) && (x % 2 == 0)\n}\n\n/// Task 6\n\n/*\n * In order to prove the statement, we rewrite the two numbers to reflect their form:\n * The sum between a multiple of 2 and 1.\n *\n * By rewriting them like this and then adding them together, the sum is shown to\n * be a multiple of 2 and thus, an even number.\n */\nlemma AdditionOfTwoOddsResultsInEven(x: int, y: int) \n requires IsOddNat(x);\n requires IsOddNat(y);\n ensures IsEvenNat(x + y);\n{\n calc {\n IsOddNat(x);\n x % 2 == 1;\n }\n\n calc {\n IsOddNat(y);\n y % 2 == 1;\n }\n\n calc {\n (x + y) % 2 == 0;\n IsEvenNat(x + y);\n true;\n }\n}\n\n/// Task 7\n/*\n * In order for an integer to be a natural, prime number, two requirements must be satisfied:\n * The integer in cause must be natural (positive) and must have exactly two divisors:\n * 1 and itself.\n *\n * Aside from two, which is the only even prime, we test the primality by checking if there\n * is no number greater or equal to 2 that the number in cause is divisible with.\n */\npredicate IsPrime(x: int)\n requires x >= 0;\n{\n x == 2 || forall d :: 2 <= d < x ==> x % d != 0\n}\n\n/// Task 8\n/*\n * It is a known fact that any prime divided by any number, aside from 1 and itself,\n * will yield a non-zero remainder.\n * \n * Thus, when dividing a prime (other than 2) by 2, the only non-zero remainder possible \n * is 1, therefore making the number an odd one.\n */\nlemma AnyPrimeGreaterThanTwoIsOdd(x : int)\n requires x > 2;\n requires IsPrime(x);\n ensures IsOddNat(x);\n{\n calc {\n x % 2;\n {\n assert forall d :: 2 <= d < x ==> x % d != 0;\n }\n 1;\n }\n\n calc {\n IsOddNat(x);\n (x >= 0) && (x % 2 == 1);\n {\n assert x > 2;\n }\n true && true;\n true;\n }\n}\n\n/* \n * Task 9 \n * Defined the basic arithmetic functions.\n * Also defined the absolute value.\n * \n * Over/Underflow are represented by the return of 0.\n */\nfunction add(x: int32, y: int32): int32 {\n if (-2147483648 <= (x as int) + (y as int) <= 2147483647) then x + y else 0\n}\n\nfunction sub(x: int32, y: int32): int32 {\n if (-2147483648 <= (x as int) - (y as int) <= 2147483647) then x - y else 0\n}\n\nfunction mul(x: int32, y: int32): int32 {\n if (-2147483648 <= (x as int) * (y as int) <= 2147483647) then x * y else 0\n}\n\nfunction div(x: int32, y: int32): int32 \n requires y != 0; \n{\n if (-2147483648 <= (x as int) / (y as int) <= 2147483647) then x / y else 0\n}\n\nfunction mod(x: int32, y: int32): int32\n requires y != 0; \n{\n x % y \n /* \n * Given that y is int32 and \n * given that the remainder is positive and smaller than the denominator\n * the result cannot over/underflow and is, therefore, not checked\n */\n}\n\nfunction abs(x: int32): (r: int32)\n ensures r >= 0;\n{\n if (x == -2147483648) then 0 else if (x < 0) then -x else x\n}\n\n", "hints_removed": "/// Types defined as part of Tasks 3, 5 and 9\n\n// Since we have created the IsOddNat predicate we use it to define the new Odd subsort\nnewtype Odd = n : int | IsOddNat(n) witness 1\n\n// Since we have created the IsEvenNat predicate we use it to define the new Even subsort\nnewtype Even = n : int | IsEvenNat(n) witness 2\n\n/*\n * We use int as the native type, so that the basic operations are available. \n * However, we restrict the domain in order to accomodate the requirements.\n */\nnewtype int32 = n: int | -2147483648 <= n < 2147483648 witness 3\n\n/// Task 2\n\n/*\n * In order for an integer to be a natural, odd number, two requirements must be satisfied:\n * The integer in cause must be positive and the remainder of the division by 2 must be 1.\n */\npredicate IsOddNat(x: int) {\n (x >= 0) && (x % 2 == 1)\n}\n\n/// Task 4\n\n/*\n * In order for an integer to be a natural, even number, two requirements must be satisfied:\n * The integer in cause must be positive and the remainder of the division by 2 must be 0.\n */\npredicate IsEvenNat(x: int) {\n (x >= 0) && (x % 2 == 0)\n}\n\n/// Task 6\n\n/*\n * In order to prove the statement, we rewrite the two numbers to reflect their form:\n * The sum between a multiple of 2 and 1.\n *\n * By rewriting them like this and then adding them together, the sum is shown to\n * be a multiple of 2 and thus, an even number.\n */\nlemma AdditionOfTwoOddsResultsInEven(x: int, y: int) \n requires IsOddNat(x);\n requires IsOddNat(y);\n ensures IsEvenNat(x + y);\n{\n calc {\n IsOddNat(x);\n x % 2 == 1;\n }\n\n calc {\n IsOddNat(y);\n y % 2 == 1;\n }\n\n calc {\n (x + y) % 2 == 0;\n IsEvenNat(x + y);\n true;\n }\n}\n\n/// Task 7\n/*\n * In order for an integer to be a natural, prime number, two requirements must be satisfied:\n * The integer in cause must be natural (positive) and must have exactly two divisors:\n * 1 and itself.\n *\n * Aside from two, which is the only even prime, we test the primality by checking if there\n * is no number greater or equal to 2 that the number in cause is divisible with.\n */\npredicate IsPrime(x: int)\n requires x >= 0;\n{\n x == 2 || forall d :: 2 <= d < x ==> x % d != 0\n}\n\n/// Task 8\n/*\n * It is a known fact that any prime divided by any number, aside from 1 and itself,\n * will yield a non-zero remainder.\n * \n * Thus, when dividing a prime (other than 2) by 2, the only non-zero remainder possible \n * is 1, therefore making the number an odd one.\n */\nlemma AnyPrimeGreaterThanTwoIsOdd(x : int)\n requires x > 2;\n requires IsPrime(x);\n ensures IsOddNat(x);\n{\n calc {\n x % 2;\n {\n }\n 1;\n }\n\n calc {\n IsOddNat(x);\n (x >= 0) && (x % 2 == 1);\n {\n }\n true && true;\n true;\n }\n}\n\n/* \n * Task 9 \n * Defined the basic arithmetic functions.\n * Also defined the absolute value.\n * \n * Over/Underflow are represented by the return of 0.\n */\nfunction add(x: int32, y: int32): int32 {\n if (-2147483648 <= (x as int) + (y as int) <= 2147483647) then x + y else 0\n}\n\nfunction sub(x: int32, y: int32): int32 {\n if (-2147483648 <= (x as int) - (y as int) <= 2147483647) then x - y else 0\n}\n\nfunction mul(x: int32, y: int32): int32 {\n if (-2147483648 <= (x as int) * (y as int) <= 2147483647) then x * y else 0\n}\n\nfunction div(x: int32, y: int32): int32 \n requires y != 0; \n{\n if (-2147483648 <= (x as int) / (y as int) <= 2147483647) then x / y else 0\n}\n\nfunction mod(x: int32, y: int32): int32\n requires y != 0; \n{\n x % y \n /* \n * Given that y is int32 and \n * given that the remainder is positive and smaller than the denominator\n * the result cannot over/underflow and is, therefore, not checked\n */\n}\n\nfunction abs(x: int32): (r: int32)\n ensures r >= 0;\n{\n if (x == -2147483648) then 0 else if (x < 0) then -x else x\n}\n\n" }, { "test_ID": "207", "test_file": "FMSE-2022-2023_tmp_tmp6_x_ba46_Lab2_Lab2.dfy", "ground_truth": "/*\n * Task 2: Define the natural numbers as an algebraic data type\n * \n * Being an inductive data type, it's required that we have a base case constructor and an inductive one.\n */\ndatatype Nat = Zero | S(Pred: Nat)\n\n/// Task 2\n// Exercise (a'): proving that the successor constructor is injective\n/*\n * It's known that the successors are equal.\n * It's know that for equal inputs, a non-random function returns the same result.\n * Thus, the predecessors of the successors, namely, the numbers themselves, are equal.\n */\nlemma SIsInjective(x: Nat, y: Nat)\n ensures S(x) == S(y) ==> x == y\n{\n assume S(x) == S(y);\n assert S(x).Pred == S(y).Pred;\n assert x == y;\n}\n\n// Exercise (a''): Zero is different from successor(x), for any x\n/*\n * For all x: Nat, S(x) is built using the S constructor, implying that S(x).Zero? is inherently false.\n */\nlemma ZeroIsDifferentFromSuccessor(n: Nat)\n ensures S(n) != Zero\n{\n assert S(n).Zero? == false;\n}\n\n// Exercise (b): inductively defining the addition of natural numbers\n/*\n * The function decreases y until it reaches the base inductive case.\n * The Addition between Zero and a x: Nat will be x.\n * The Addition between a successor of a y': Nat and another x: Nat is the successor of the Addition between y' and x\n *\n * x + y = 1 + ((x - 1) + y)\n */\nfunction Add(x: Nat, y: Nat) : Nat\n decreases y\n{\n match y\n case Zero => x\n case S(y') => S(Add(x, y')) \n}\n\n// Exercise (c'): proving that the addition is commutative\n/*\n * It is necessary, as with any induction, to have a proven base case.\n * In this case, we first prove that the Addition with Zero is Neutral.\n */\n lemma {:induction n} ZeroAddNeutral(n: Nat)\n ensures Add(n, Zero) == Add(Zero, n) == n\n{\n match n\n case Zero => {\n assert Add(n, Zero)\n == Add(Zero, Zero)\n == Add(Zero, n)\n == n;\n }\n case S(n') => {\n assert Add(n, Zero)\n == Add(S(n'), Zero)\n == S(n')\n == Add(Zero, S(n'))\n == Add(Zero, n)\n == n;\n }\n}\n\n/*\n * Since Zero is neutral, it is trivial that the order of addition is not of importance.\n */\nlemma {:induction n} ZeroAddCommutative(n: Nat)\n ensures Add(Zero, n) == Add(n, Zero)\n{\n assert Add(Zero, n)\n == n \n == Add(n, Zero);\n}\n\n/*\n * Since now the base case of commutative addition with Zero is proven, we can now prove using induction.\n */\nlemma {:induction x, y} AddCommutative(x: Nat, y: Nat)\n ensures Add(x, y) == Add(y, x)\n decreases x, y\n{\n match x\n case Zero => ZeroAddCommutative(y);\n case S(x') => AddCommutative(x', y);\n}\n\n// Exercise (c''): proving that the addition is associative\n/*\n * It is necessary, as with any induction, to have a proven base case.\n * In this case, we first prove that the Addition with Zero is Associative.\n *\n * Again, given that addition with Zero is neutral, the order of calculations is irrelevant.\n */\nlemma {:induction x, y} ZeroAddAssociative(x: Nat, y: Nat)\n ensures Add(Add(Zero, x), y) == Add(Zero, Add(x, y))\n{\n ZeroAddNeutral(x);\n \n assert Add(Add(Zero, x), y)\n == // ZeroAddNeutral\n Add(x, y)\n == Add(Zero, Add(x, y));\n}\n\n/*\n * Since now the base case of commutative addition with Zero is proven, we can now prove using induction.\n */\nlemma {:induction x, y} AddAssociative(x: Nat, y: Nat, z: Nat)\n ensures Add(Add(x, y), z) == Add(x, Add(y, z))\n decreases z\n{\n match z\n case Zero => ZeroAddAssociative(Add(x, y), Zero);\n case S(z') => AddAssociative(x, y, z');\n}\n\n// Exercise (d): defining a predicate lt(m, n) that holds when m is less than n\n/*\n * If x is Zero and y is a Successor, given that we have proven ZeroIsDifferentFromSuccessor for all x, the predicate holds.\n * Otherwise, if both are successors, we inductively check their predecessors.\n */\npredicate LessThan(x: Nat, y: Nat)\n decreases x, y\n{\n (x.Zero? && y.S?) || (x.S? && y.S? && LessThan(x.Pred, y.Pred))\n}\n\n// Exercise (e): proving that lt is transitive\n/*\n * It is necessary, as with any induction, to have a proven base case.\n * In this case, we first prove that LessThan is Transitive having a Zero as the left-most parameter.\n *\n * We prove this statement using Reductio Ad Absurdum.\n * We suppose that Zero is not smaller that an arbitrary z that is non-Zero.\n * This would imply that Zero has to be a Successor (i.e. Zero.S? == true).\n * This is inherently false.\n */\nlemma {:induction y, z} LessThanIsTransitiveWithZero(y: Nat, z: Nat)\n requires LessThan(Zero, y)\n requires LessThan(y, z)\n ensures LessThan(Zero, z)\n{\n if !LessThan(Zero, z) {\n assert z != Zero;\n assert Zero.S?;\n assert false;\n }\n}\n\n/*\n * Since now the base case of transitive LessThan with Zero is proven, we can now prove using induction.\n *\n * In this case, the induction decreases on all three variables, all x, y, z until the base case.\n */\nlemma {:induction x, y, z} LessThanIsTransitive(x: Nat, y: Nat, z: Nat)\n requires LessThan(x, y)\n requires LessThan(y, z)\n ensures LessThan(x, z)\n decreases x\n{\n match x\n case Zero => LessThanIsTransitiveWithZero(y, z);\n case S(x') => match y\n case S(y') => match z \n case S(z') => LessThanIsTransitive(x', y', z');\n}\n\n/// Task 3: Define the parametric lists as an algebraic data type\n/*\n * Being an inductive data type, it's required that we have a base case constructor and an inductive one.\n * The inductive Append constructor takes as input a Nat, the head, and a tail, the rest of the list.\n */\ndatatype List = Nil | Append(head: T, tail: List)\n\n// Exercise (a): defining the size of a list (using natural numbers defined above)\n/*\n * We are modelling the function as a recursive one.\n * The size of an empty list (Nil) is Zero.\n * \n * The size of a non-empty list is the successor of the size of the list's tail.\n */\nfunction Size(l: List): Nat\n decreases l\n{\n if l.Nil? then Zero else S(Size(l.tail))\n}\n\n// Exercise (b): defining the concatenation of two lists\n/*\n * Concatenation with an empty list yields the other list.\n * \n * The function recursively calculates the result of the concatenation.\n */\nfunction Concatenation(l1: List, l2: List) : List\n decreases l1, l2\n{\n match l1\n case Nil => l2\n case Append(head1, tail1) => match l2\n case Nil => l1\n case Append(_, _) => Append(head1, Concatenation(tail1, l2))\n}\n\n// Exercise (c): proving that the size of the concatenation of two lists is the sum of the lists' sizes\n/*\n * Starting with a base case in which the first list is empty, the proof is trivial, given ZeroAddNeutral.\n * Afterwards, the induction follows the next step and matches the second list.\n * If the list is empty, the result will be, of course, the first list.\n * Otherwise, an element is discarded from both (the heads), and the verification continues on the tails.\n */\nlemma {:induction l1, l2} SizeOfConcatenationIsSumOfSizes(l1: List, l2: List)\n ensures Size(Concatenation(l1, l2)) == Add(Size(l1), Size(l2))\n decreases l1, l2\n{\n match l1\n case Nil => {\n ZeroAddNeutral(Size(l2));\n\n assert Size(Concatenation(l1, l2))\n == Size(Concatenation(Nil, l2))\n == Size(l2)\n == // ZeroAddNeutral\n Add(Zero, Size(l2)) \n == Add(Size(l1), Size(l2));\n }\n case Append(_, tail1) => match l2\n case Nil => {\n assert Size(Concatenation(l1, l2))\n == Size(Concatenation(l1, Nil))\n == Size(l1)\n == Add(Size(l1), Zero)\n == Add(Size(l1), Size(l2));\n }\n case Append(_, tail2) => SizeOfConcatenationIsSumOfSizes(tail1, tail2);\n}\n\n// Exercise (d): defining a function reversing a list\n/*\n * The base case is, again, the empty list. \n * When the list is empty, the reverse of the list is also Nil.\n * \n * When dealing with a non-empty list, we make use of the Concatenation operation.\n * The Reverse of the list will be a concatenation between the reverse of the tail and the head.\n * Since the head is not a list on its own, a list is created using the Append constructor.\n */\nfunction ReverseList(l: List) : List\n decreases l\n{\n if l.Nil? then Nil else Concatenation(ReverseList(l.tail), Append(l.head, Nil))\n}\n\n// Exercise (e): proving that reversing a list twice we obtain the initial list.\n/*\n * Given that during the induction we need to make use of this property, \n * we first save the result of reversing a concatenation between a list and a single element.\n *\n * Aside from the base case, proven with chained equality assertions, the proof follows an inductive approach as well.\n */\nlemma {:induction l, n} ReversalOfConcatenationWithHead(l: List, n: Nat)\n ensures ReverseList(Concatenation(l, Append(n, Nil))) == Append(n, ReverseList(l))\n decreases l, n\n{\n match l\n case Nil => {\n assert ReverseList(Concatenation(l, Append(n, Nil)))\n == ReverseList(Concatenation(Nil, Append(n, Nil)))\n == ReverseList(Append(n, Nil))\n == Concatenation(ReverseList(Append(n, Nil).tail), Append(Append(n, Nil).head, Nil))\n == Concatenation(ReverseList(Nil), Append(n, Nil))\n == Concatenation(Nil, Append(n, Nil))\n == Append(n, Nil)\n == Append(n, l)\n == Append(n, ReverseList(l));\n }\n case Append(head, tail) => ReversalOfConcatenationWithHead(tail, n);\n}\n\n/*\n * The induction starts with the base case, which is trivial.\n *\n * For the inductive steps, there is a need for the property proven above.\n * Once the property is guaranteed, the chained assertions lead to the solution.\n */\nlemma {:induction l} DoubleReversalResultsInInitialList(l: List)\n ensures l == ReverseList(ReverseList(l))\n{\n match l\n case Nil => {\n assert ReverseList(ReverseList(l))\n == ReverseList(ReverseList(Nil))\n == ReverseList(Nil)\n == Nil;\n\n assert l == ReverseList(ReverseList(l));\n }\n case Append(head, tail) => {\n ReversalOfConcatenationWithHead(ReverseList(tail), head);\n\n assert ReverseList(ReverseList(l))\n == ReverseList(ReverseList(Append(head, tail)))\n == ReverseList(Concatenation(ReverseList(tail), Append(head, Nil)))\n == // ReversalOfConcatenationWithHead\n Append(head, ReverseList(ReverseList(tail)))\n == Append(head, tail)\n == l;\n }\n}\n", "hints_removed": "/*\n * Task 2: Define the natural numbers as an algebraic data type\n * \n * Being an inductive data type, it's required that we have a base case constructor and an inductive one.\n */\ndatatype Nat = Zero | S(Pred: Nat)\n\n/// Task 2\n// Exercise (a'): proving that the successor constructor is injective\n/*\n * It's known that the successors are equal.\n * It's know that for equal inputs, a non-random function returns the same result.\n * Thus, the predecessors of the successors, namely, the numbers themselves, are equal.\n */\nlemma SIsInjective(x: Nat, y: Nat)\n ensures S(x) == S(y) ==> x == y\n{\n assume S(x) == S(y);\n}\n\n// Exercise (a''): Zero is different from successor(x), for any x\n/*\n * For all x: Nat, S(x) is built using the S constructor, implying that S(x).Zero? is inherently false.\n */\nlemma ZeroIsDifferentFromSuccessor(n: Nat)\n ensures S(n) != Zero\n{\n}\n\n// Exercise (b): inductively defining the addition of natural numbers\n/*\n * The function decreases y until it reaches the base inductive case.\n * The Addition between Zero and a x: Nat will be x.\n * The Addition between a successor of a y': Nat and another x: Nat is the successor of the Addition between y' and x\n *\n * x + y = 1 + ((x - 1) + y)\n */\nfunction Add(x: Nat, y: Nat) : Nat\n{\n match y\n case Zero => x\n case S(y') => S(Add(x, y')) \n}\n\n// Exercise (c'): proving that the addition is commutative\n/*\n * It is necessary, as with any induction, to have a proven base case.\n * In this case, we first prove that the Addition with Zero is Neutral.\n */\n lemma {:induction n} ZeroAddNeutral(n: Nat)\n ensures Add(n, Zero) == Add(Zero, n) == n\n{\n match n\n case Zero => {\n == Add(Zero, Zero)\n == Add(Zero, n)\n == n;\n }\n case S(n') => {\n == Add(S(n'), Zero)\n == S(n')\n == Add(Zero, S(n'))\n == Add(Zero, n)\n == n;\n }\n}\n\n/*\n * Since Zero is neutral, it is trivial that the order of addition is not of importance.\n */\nlemma {:induction n} ZeroAddCommutative(n: Nat)\n ensures Add(Zero, n) == Add(n, Zero)\n{\n == n \n == Add(n, Zero);\n}\n\n/*\n * Since now the base case of commutative addition with Zero is proven, we can now prove using induction.\n */\nlemma {:induction x, y} AddCommutative(x: Nat, y: Nat)\n ensures Add(x, y) == Add(y, x)\n{\n match x\n case Zero => ZeroAddCommutative(y);\n case S(x') => AddCommutative(x', y);\n}\n\n// Exercise (c''): proving that the addition is associative\n/*\n * It is necessary, as with any induction, to have a proven base case.\n * In this case, we first prove that the Addition with Zero is Associative.\n *\n * Again, given that addition with Zero is neutral, the order of calculations is irrelevant.\n */\nlemma {:induction x, y} ZeroAddAssociative(x: Nat, y: Nat)\n ensures Add(Add(Zero, x), y) == Add(Zero, Add(x, y))\n{\n ZeroAddNeutral(x);\n \n == // ZeroAddNeutral\n Add(x, y)\n == Add(Zero, Add(x, y));\n}\n\n/*\n * Since now the base case of commutative addition with Zero is proven, we can now prove using induction.\n */\nlemma {:induction x, y} AddAssociative(x: Nat, y: Nat, z: Nat)\n ensures Add(Add(x, y), z) == Add(x, Add(y, z))\n{\n match z\n case Zero => ZeroAddAssociative(Add(x, y), Zero);\n case S(z') => AddAssociative(x, y, z');\n}\n\n// Exercise (d): defining a predicate lt(m, n) that holds when m is less than n\n/*\n * If x is Zero and y is a Successor, given that we have proven ZeroIsDifferentFromSuccessor for all x, the predicate holds.\n * Otherwise, if both are successors, we inductively check their predecessors.\n */\npredicate LessThan(x: Nat, y: Nat)\n{\n (x.Zero? && y.S?) || (x.S? && y.S? && LessThan(x.Pred, y.Pred))\n}\n\n// Exercise (e): proving that lt is transitive\n/*\n * It is necessary, as with any induction, to have a proven base case.\n * In this case, we first prove that LessThan is Transitive having a Zero as the left-most parameter.\n *\n * We prove this statement using Reductio Ad Absurdum.\n * We suppose that Zero is not smaller that an arbitrary z that is non-Zero.\n * This would imply that Zero has to be a Successor (i.e. Zero.S? == true).\n * This is inherently false.\n */\nlemma {:induction y, z} LessThanIsTransitiveWithZero(y: Nat, z: Nat)\n requires LessThan(Zero, y)\n requires LessThan(y, z)\n ensures LessThan(Zero, z)\n{\n if !LessThan(Zero, z) {\n }\n}\n\n/*\n * Since now the base case of transitive LessThan with Zero is proven, we can now prove using induction.\n *\n * In this case, the induction decreases on all three variables, all x, y, z until the base case.\n */\nlemma {:induction x, y, z} LessThanIsTransitive(x: Nat, y: Nat, z: Nat)\n requires LessThan(x, y)\n requires LessThan(y, z)\n ensures LessThan(x, z)\n{\n match x\n case Zero => LessThanIsTransitiveWithZero(y, z);\n case S(x') => match y\n case S(y') => match z \n case S(z') => LessThanIsTransitive(x', y', z');\n}\n\n/// Task 3: Define the parametric lists as an algebraic data type\n/*\n * Being an inductive data type, it's required that we have a base case constructor and an inductive one.\n * The inductive Append constructor takes as input a Nat, the head, and a tail, the rest of the list.\n */\ndatatype List = Nil | Append(head: T, tail: List)\n\n// Exercise (a): defining the size of a list (using natural numbers defined above)\n/*\n * We are modelling the function as a recursive one.\n * The size of an empty list (Nil) is Zero.\n * \n * The size of a non-empty list is the successor of the size of the list's tail.\n */\nfunction Size(l: List): Nat\n{\n if l.Nil? then Zero else S(Size(l.tail))\n}\n\n// Exercise (b): defining the concatenation of two lists\n/*\n * Concatenation with an empty list yields the other list.\n * \n * The function recursively calculates the result of the concatenation.\n */\nfunction Concatenation(l1: List, l2: List) : List\n{\n match l1\n case Nil => l2\n case Append(head1, tail1) => match l2\n case Nil => l1\n case Append(_, _) => Append(head1, Concatenation(tail1, l2))\n}\n\n// Exercise (c): proving that the size of the concatenation of two lists is the sum of the lists' sizes\n/*\n * Starting with a base case in which the first list is empty, the proof is trivial, given ZeroAddNeutral.\n * Afterwards, the induction follows the next step and matches the second list.\n * If the list is empty, the result will be, of course, the first list.\n * Otherwise, an element is discarded from both (the heads), and the verification continues on the tails.\n */\nlemma {:induction l1, l2} SizeOfConcatenationIsSumOfSizes(l1: List, l2: List)\n ensures Size(Concatenation(l1, l2)) == Add(Size(l1), Size(l2))\n{\n match l1\n case Nil => {\n ZeroAddNeutral(Size(l2));\n\n == Size(Concatenation(Nil, l2))\n == Size(l2)\n == // ZeroAddNeutral\n Add(Zero, Size(l2)) \n == Add(Size(l1), Size(l2));\n }\n case Append(_, tail1) => match l2\n case Nil => {\n == Size(Concatenation(l1, Nil))\n == Size(l1)\n == Add(Size(l1), Zero)\n == Add(Size(l1), Size(l2));\n }\n case Append(_, tail2) => SizeOfConcatenationIsSumOfSizes(tail1, tail2);\n}\n\n// Exercise (d): defining a function reversing a list\n/*\n * The base case is, again, the empty list. \n * When the list is empty, the reverse of the list is also Nil.\n * \n * When dealing with a non-empty list, we make use of the Concatenation operation.\n * The Reverse of the list will be a concatenation between the reverse of the tail and the head.\n * Since the head is not a list on its own, a list is created using the Append constructor.\n */\nfunction ReverseList(l: List) : List\n{\n if l.Nil? then Nil else Concatenation(ReverseList(l.tail), Append(l.head, Nil))\n}\n\n// Exercise (e): proving that reversing a list twice we obtain the initial list.\n/*\n * Given that during the induction we need to make use of this property, \n * we first save the result of reversing a concatenation between a list and a single element.\n *\n * Aside from the base case, proven with chained equality assertions, the proof follows an inductive approach as well.\n */\nlemma {:induction l, n} ReversalOfConcatenationWithHead(l: List, n: Nat)\n ensures ReverseList(Concatenation(l, Append(n, Nil))) == Append(n, ReverseList(l))\n{\n match l\n case Nil => {\n == ReverseList(Concatenation(Nil, Append(n, Nil)))\n == ReverseList(Append(n, Nil))\n == Concatenation(ReverseList(Append(n, Nil).tail), Append(Append(n, Nil).head, Nil))\n == Concatenation(ReverseList(Nil), Append(n, Nil))\n == Concatenation(Nil, Append(n, Nil))\n == Append(n, Nil)\n == Append(n, l)\n == Append(n, ReverseList(l));\n }\n case Append(head, tail) => ReversalOfConcatenationWithHead(tail, n);\n}\n\n/*\n * The induction starts with the base case, which is trivial.\n *\n * For the inductive steps, there is a need for the property proven above.\n * Once the property is guaranteed, the chained assertions lead to the solution.\n */\nlemma {:induction l} DoubleReversalResultsInInitialList(l: List)\n ensures l == ReverseList(ReverseList(l))\n{\n match l\n case Nil => {\n == ReverseList(ReverseList(Nil))\n == ReverseList(Nil)\n == Nil;\n\n }\n case Append(head, tail) => {\n ReversalOfConcatenationWithHead(ReverseList(tail), head);\n\n == ReverseList(ReverseList(Append(head, tail)))\n == ReverseList(Concatenation(ReverseList(tail), Append(head, Nil)))\n == // ReversalOfConcatenationWithHead\n Append(head, ReverseList(ReverseList(tail)))\n == Append(head, tail)\n == l;\n }\n}\n" }, { "test_ID": "208", "test_file": "FMSE-2022-2023_tmp_tmp6_x_ba46_Lab3_Lab3.dfy", "ground_truth": "/*\n * Task 2: Define in Dafny the conatural numbers as a coinductive datatype\n * \n * Being a coinductive data type, it's required that we have a base case constructor and an inductive one \n * (as is the case with inductive ones as well)\n */\ncodatatype Conat = Zero | Succ(Pred: Conat)\n\n// Exercise (a): explain why the following coinductive property does NOT hold\n// lemma ConstructorConat(n: Conat)\n // ensures n != Succ(n)\n// {\n // the following coinductive property does not hold because coinductive datatypes, as opposed to normal datatypes,\n // are designed for infinite domains, as such, it is improper to test the equality above when dealing with infinity\n// }\n\n// Exercise (b): show that the constructor successor is injective\ngreatest lemma ConstructorInjective(x: Conat, y: Conat)\n ensures Succ(x) == Succ(y) ==> x == y\n{\n assume Succ(x) == Succ(y);\n assert Succ(x).Pred == Succ(y).Pred;\n assert x == y;\n}\n\n// Exercise (c): define the \u221e constant (as a corecursive function)\n// We use a co-recursive call using the Succ constructor on the result, producing an infinite call stack\nfunction inf(n: Conat): Conat\n{\n Succ(inf(n))\n}\n\n// Exercise (d): define the addition of conaturals\n// Similar to add function over the Nat datatype (See Lab2)\nfunction add(x: Conat, y: Conat) : Conat\n{\n match x\n case Zero => y\n case Succ(x') => Succ(add(x', y))\n}\n\n// Exercise (e): show that by adding \u221e to itself it remains unchanged\n// Because the focus is on greatest fixed-point we need to use a co-predicate\n// Aptly renamed to greatest predicate\ngreatest predicate InfinityAddition()\n{\n add(inf(Zero), inf(Zero)) == inf(Zero)\n}\n\n// Task 3: Define the parametric streams as a coinductive datatype where s ranges over streams\ncodatatype Stream = Cons(head: A, tail: Stream)\n\n// Exercise (a): corecursively define the pointwise addition of two streams of integers\n// After performing the addition of the value in the heads, proceed similarly with the tails\nfunction addition(a: Stream, b: Stream): Stream\n{ \n Cons(a.head + b.head, addition(a.tail, b.tail))\n}\n\n// Exercise (b): define a parametric integer constant stream\n// An infinite stream with the same value\nfunction cnst(a: int): Stream\n{ \n Cons(a, cnst(a))\n}\n\n// Exercise (c): prove by coinduction that add(s, cnst(0)) = s;\n// The proof tried below is not complete, however, by telling Dafny that we are dealing with a colemma,\n// Aptly renamed to greatest lemma, it is able to reason and prove the post-condition by itself\ngreatest lemma additionWithZero(a : Stream)\n ensures addition(a, cnst(0)) == a\n{\n// assert addition(a, cnst(0))\n// ==\n// Cons(a.head + cnst(0).head, addition(a.tail, cnst(0).tail))\n// ==\n// Cons(a.head + 0, addition(a.tail, cnst(0)))\n// ==\n// Cons(a.head, addition(a.tail, cnst(0)))\n// ==\n// Cons(a.head, a.tail)\n// ==\n// a;\n}\n\n// Exercise (d): define coinductively the predicate\ngreatest predicate leq(a: Stream, b: Stream)\n{ a.head <= b.head && ((a.head == b.head) ==> leq(a.tail, b.tail)) }\n\n// Exercise (e): (e) define the stream blink\nfunction blink(): Stream\n{\n Cons(0, Cons(1, blink()))\n}\n\n// Exercise (f): prove by coinduction that leq(cnst(0), blink)\nlemma CnstZeroLeqBlink()\n ensures leq(cnst(0), blink())\n{ \n}\n\n// Exercise (g): define a function that \u201dzips\u201d two streams\n// A stream formed by alternating the elements of both streams one by one\nfunction zip(a: Stream, b: Stream): Stream\n{\n Cons(a.head, Cons(b.head, zip(a.tail, b.tail)))\n}\n\n// Exercise (h): prove that zipping cnst(0) and cnst(1) yields blink\n// By using a greatest lemma, Dafny can reason on its own\ngreatest lemma ZipCnstZeroCnstOneEqualsBlink()\n ensures zip(cnst(0), cnst(1)) == blink()\n{\n// assert zip(cnst(0), cnst(1))\n// ==\n// Cons(cnst(0).head, Cons(cnst(1).head, zip(cnst(0).tail, cnst(1).tail)))\n// ==\n// Cons(0, Cons(1, zip(cnst(0).tail, cnst(1).tail)))\n// ==\n// Cons(0, Cons(1, zip(cnst(0), cnst(1))))\n// ==\n// Cons(0, Cons(1, Cons(cnst(0).head, Cons(cnst(1).head, zip(cnst(0).tail, cnst(1).tail)))))\n// ==\n// Cons(0, Cons(1, Cons(0, Cons(1, zip(cnst(0).tail, cnst(1).tail)))))\n// == \n// Cons(0, Cons(1, Cons(0, Cons(1, zip(cnst(0), cnst(1))))))\n// ==\n// blink();\n}\n", "hints_removed": "/*\n * Task 2: Define in Dafny the conatural numbers as a coinductive datatype\n * \n * Being a coinductive data type, it's required that we have a base case constructor and an inductive one \n * (as is the case with inductive ones as well)\n */\ncodatatype Conat = Zero | Succ(Pred: Conat)\n\n// Exercise (a): explain why the following coinductive property does NOT hold\n// lemma ConstructorConat(n: Conat)\n // ensures n != Succ(n)\n// {\n // the following coinductive property does not hold because coinductive datatypes, as opposed to normal datatypes,\n // are designed for infinite domains, as such, it is improper to test the equality above when dealing with infinity\n// }\n\n// Exercise (b): show that the constructor successor is injective\ngreatest lemma ConstructorInjective(x: Conat, y: Conat)\n ensures Succ(x) == Succ(y) ==> x == y\n{\n assume Succ(x) == Succ(y);\n}\n\n// Exercise (c): define the \u221e constant (as a corecursive function)\n// We use a co-recursive call using the Succ constructor on the result, producing an infinite call stack\nfunction inf(n: Conat): Conat\n{\n Succ(inf(n))\n}\n\n// Exercise (d): define the addition of conaturals\n// Similar to add function over the Nat datatype (See Lab2)\nfunction add(x: Conat, y: Conat) : Conat\n{\n match x\n case Zero => y\n case Succ(x') => Succ(add(x', y))\n}\n\n// Exercise (e): show that by adding \u221e to itself it remains unchanged\n// Because the focus is on greatest fixed-point we need to use a co-predicate\n// Aptly renamed to greatest predicate\ngreatest predicate InfinityAddition()\n{\n add(inf(Zero), inf(Zero)) == inf(Zero)\n}\n\n// Task 3: Define the parametric streams as a coinductive datatype where s ranges over streams\ncodatatype Stream = Cons(head: A, tail: Stream)\n\n// Exercise (a): corecursively define the pointwise addition of two streams of integers\n// After performing the addition of the value in the heads, proceed similarly with the tails\nfunction addition(a: Stream, b: Stream): Stream\n{ \n Cons(a.head + b.head, addition(a.tail, b.tail))\n}\n\n// Exercise (b): define a parametric integer constant stream\n// An infinite stream with the same value\nfunction cnst(a: int): Stream\n{ \n Cons(a, cnst(a))\n}\n\n// Exercise (c): prove by coinduction that add(s, cnst(0)) = s;\n// The proof tried below is not complete, however, by telling Dafny that we are dealing with a colemma,\n// Aptly renamed to greatest lemma, it is able to reason and prove the post-condition by itself\ngreatest lemma additionWithZero(a : Stream)\n ensures addition(a, cnst(0)) == a\n{\n// assert addition(a, cnst(0))\n// ==\n// Cons(a.head + cnst(0).head, addition(a.tail, cnst(0).tail))\n// ==\n// Cons(a.head + 0, addition(a.tail, cnst(0)))\n// ==\n// Cons(a.head, addition(a.tail, cnst(0)))\n// ==\n// Cons(a.head, a.tail)\n// ==\n// a;\n}\n\n// Exercise (d): define coinductively the predicate\ngreatest predicate leq(a: Stream, b: Stream)\n{ a.head <= b.head && ((a.head == b.head) ==> leq(a.tail, b.tail)) }\n\n// Exercise (e): (e) define the stream blink\nfunction blink(): Stream\n{\n Cons(0, Cons(1, blink()))\n}\n\n// Exercise (f): prove by coinduction that leq(cnst(0), blink)\nlemma CnstZeroLeqBlink()\n ensures leq(cnst(0), blink())\n{ \n}\n\n// Exercise (g): define a function that \u201dzips\u201d two streams\n// A stream formed by alternating the elements of both streams one by one\nfunction zip(a: Stream, b: Stream): Stream\n{\n Cons(a.head, Cons(b.head, zip(a.tail, b.tail)))\n}\n\n// Exercise (h): prove that zipping cnst(0) and cnst(1) yields blink\n// By using a greatest lemma, Dafny can reason on its own\ngreatest lemma ZipCnstZeroCnstOneEqualsBlink()\n ensures zip(cnst(0), cnst(1)) == blink()\n{\n// assert zip(cnst(0), cnst(1))\n// ==\n// Cons(cnst(0).head, Cons(cnst(1).head, zip(cnst(0).tail, cnst(1).tail)))\n// ==\n// Cons(0, Cons(1, zip(cnst(0).tail, cnst(1).tail)))\n// ==\n// Cons(0, Cons(1, zip(cnst(0), cnst(1))))\n// ==\n// Cons(0, Cons(1, Cons(cnst(0).head, Cons(cnst(1).head, zip(cnst(0).tail, cnst(1).tail)))))\n// ==\n// Cons(0, Cons(1, Cons(0, Cons(1, zip(cnst(0).tail, cnst(1).tail)))))\n// == \n// Cons(0, Cons(1, Cons(0, Cons(1, zip(cnst(0), cnst(1))))))\n// ==\n// blink();\n}\n" }, { "test_ID": "209", "test_file": "Final-Project-Dafny_tmp_tmpmcywuqox_Attempts_Exercise3_Increment_Array.dfy", "ground_truth": "method incrementArray(a:array)\n requires a.Length > 0\n ensures forall i :: 0 <= i < a.Length ==> a[i] == old(a[i]) + 1\n modifies a\n{\n var j : int := 0;\n while(j < a.Length)\n invariant 0 <= j <= a.Length\n invariant forall i :: j <= i < a.Length ==> a[i] == old(a[i])\n invariant forall i :: 0 <= i < j ==> a[i] == old(a[i]) + 1\n decreases a.Length - j \n {\n assert forall i :: 0 <= i < j ==> a[i] == old(a[i]) + 1;\n assert a[j] == old(a[j]);\n a[j] := a[j] + 1;\n assert forall i :: 0 <= i < j ==> a[i] == old(a[i]) + 1;\n assert a[j] == old(a[j]) + 1;\n j := j+1; \n }\n}\n", "hints_removed": "method incrementArray(a:array)\n requires a.Length > 0\n ensures forall i :: 0 <= i < a.Length ==> a[i] == old(a[i]) + 1\n modifies a\n{\n var j : int := 0;\n while(j < a.Length)\n {\n a[j] := a[j] + 1;\n j := j+1; \n }\n}\n" }, { "test_ID": "210", "test_file": "Final-Project-Dafny_tmp_tmpmcywuqox_Attempts_Exercise4_Find_Max.dfy", "ground_truth": "method findMax(a:array) returns (pos:int, maxVal: int)\n requires a.Length > 0;\n requires forall i :: 0 <= i < a.Length ==> a[i] >= 0;\n ensures forall i :: 0 <= i < a.Length ==> a[i] <= maxVal;\n ensures exists i :: 0 <= i < a.Length && a[i] == maxVal;\n ensures 0 <= pos < a.Length\n ensures a[pos] == maxVal;\n{\n pos := 0;\n maxVal := a[0];\n var j := 1;\n while(j < a.Length)\n invariant 1 <= j <= a.Length;\n invariant forall i :: 0 <= i < j ==> a[i] <= maxVal;\n invariant exists i :: 0 <= i < j && a[i] == maxVal;\n invariant 0 <= pos < a.Length;\n invariant a[pos] == maxVal;\n {\n if (a[j] > maxVal) \n {\n maxVal := a[j];\n pos := j;\n }\n j := j+1;\n }\n return;\n}\n", "hints_removed": "method findMax(a:array) returns (pos:int, maxVal: int)\n requires a.Length > 0;\n requires forall i :: 0 <= i < a.Length ==> a[i] >= 0;\n ensures forall i :: 0 <= i < a.Length ==> a[i] <= maxVal;\n ensures exists i :: 0 <= i < a.Length && a[i] == maxVal;\n ensures 0 <= pos < a.Length\n ensures a[pos] == maxVal;\n{\n pos := 0;\n maxVal := a[0];\n var j := 1;\n while(j < a.Length)\n {\n if (a[j] > maxVal) \n {\n maxVal := a[j];\n pos := j;\n }\n j := j+1;\n }\n return;\n}\n" }, { "test_ID": "211", "test_file": "Final-Project-Dafny_tmp_tmpmcywuqox_Attempts_Exercise6_Binary_Search.dfy", "ground_truth": "method binarySearch(a:array, val:int) returns (pos:int)\n requires a.Length > 0\n requires forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j]\n\n ensures 0 <= pos < a.Length ==> a[pos] == val\n ensures pos < 0 || pos >= a.Length ==> forall i :: 0 <= i < a.Length ==> a[i] != val\n\n{\n var left := 0;\n var right := a.Length;\n if a[left] > val || a[right-1] < val \n {\n return -1;\n }\n while left < right\n \n invariant 0 <= left <= right <= a.Length\n invariant forall i :: 0 <= i < a.Length && !(left <= i < right) ==> a[i] != val\n\n decreases right - left\n {\n var med := (left + right) / 2;\n assert left <= med <= right;\n if a[med] < val\n {\n left := med + 1;\n }\n else if a[med] > val\n {\n right := med;\n }\n else\n {\n assert a[med] == val;\n pos := med;\n return;\n }\n\n }\n return -1;\n}\n", "hints_removed": "method binarySearch(a:array, val:int) returns (pos:int)\n requires a.Length > 0\n requires forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j]\n\n ensures 0 <= pos < a.Length ==> a[pos] == val\n ensures pos < 0 || pos >= a.Length ==> forall i :: 0 <= i < a.Length ==> a[i] != val\n\n{\n var left := 0;\n var right := a.Length;\n if a[left] > val || a[right-1] < val \n {\n return -1;\n }\n while left < right\n \n\n {\n var med := (left + right) / 2;\n if a[med] < val\n {\n left := med + 1;\n }\n else if a[med] > val\n {\n right := med;\n }\n else\n {\n pos := med;\n return;\n }\n\n }\n return -1;\n}\n" }, { "test_ID": "212", "test_file": "Final-Project-Dafny_tmp_tmpmcywuqox_Attempts_Insertion_Sort_Normal.dfy", "ground_truth": "predicate sorted (a: array)\n\n\treads a\n{\n\tsortedA(a, a.Length)\n}\n\npredicate sortedA (a: array, i: int)\n\n\trequires 0 <= i <= a.Length\n\treads a\n{\n\tforall k :: 0 < k < i ==> a[k-1] <= a[k]\n}\n\nmethod lookForMin (a: array, i: int) returns (m: int)\n\n\trequires 0 <= i < a.Length\n\tensures i <= m < a.Length\n\tensures forall k :: i <= k < a.Length ==> a[k] >= a[m]\n{\n\tvar j := i;\n\tm := i;\n\twhile(j < a.Length)\n\t\tinvariant i <= j <= a.Length\n\t\tinvariant i <= m < a.Length\n\t\tinvariant forall k :: i <= k < j ==> a[k] >= a[m]\n\t\tdecreases a.Length - j\n\t{\n\t\tif(a[j] < a[m]) { m := j; }\n\t\tj := j + 1;\n\t}\n}\n\nmethod insertionSort (a: array)\n\n\tmodifies a\n\tensures sorted(a)\n{\n\tvar c := 0;\n\twhile(c < a.Length)\n\t\tinvariant 0 <= c <= a.Length\n\t\tinvariant forall k, l :: 0 <= k < c <= l < a.Length ==> a[k] <= a[l]\n\t\tinvariant sortedA(a, c)\n\t{\n\t\tvar m := lookForMin(a, c);\n\t\ta[m], a[c] := a[c], a[m];\n\t\tassert forall k :: c <= k < a.Length ==> a[k] >= a[c];\n\t\tc := c + 1;\n\t}\n}\n", "hints_removed": "predicate sorted (a: array)\n\n\treads a\n{\n\tsortedA(a, a.Length)\n}\n\npredicate sortedA (a: array, i: int)\n\n\trequires 0 <= i <= a.Length\n\treads a\n{\n\tforall k :: 0 < k < i ==> a[k-1] <= a[k]\n}\n\nmethod lookForMin (a: array, i: int) returns (m: int)\n\n\trequires 0 <= i < a.Length\n\tensures i <= m < a.Length\n\tensures forall k :: i <= k < a.Length ==> a[k] >= a[m]\n{\n\tvar j := i;\n\tm := i;\n\twhile(j < a.Length)\n\t{\n\t\tif(a[j] < a[m]) { m := j; }\n\t\tj := j + 1;\n\t}\n}\n\nmethod insertionSort (a: array)\n\n\tmodifies a\n\tensures sorted(a)\n{\n\tvar c := 0;\n\twhile(c < a.Length)\n\t{\n\t\tvar m := lookForMin(a, c);\n\t\ta[m], a[c] := a[c], a[m];\n\t\tc := c + 1;\n\t}\n}\n" }, { "test_ID": "213", "test_file": "Final-Project-Dafny_tmp_tmpmcywuqox_Attempts_Insertion_Sorted_Standard.dfy", "ground_truth": "predicate InsertionSorted(Array: array, left: int, right: int) \n requires 0 <= left <= right <= Array.Length \n reads Array \n{ \n forall i,j :: left <= i < j < right ==> Array[i] <= Array[j]\n}\n\n\nmethod sorting(Array: array)\n requires Array.Length > 1 \n ensures InsertionSorted(Array, 0, Array.Length) \n modifies Array\n{ \n var high := 1; \n while (high < Array.Length) \n invariant 1 <= high <= Array.Length \n invariant InsertionSorted(Array,0,high)\n { \n var low := high-1; \n while low >= 0 && Array[low+1] < Array[low]\n invariant forall idx,idx' :: 0 <= idx < idx' < high+1 && idx' != low+1 ==> Array[idx] <= Array[idx']\n {\n Array[low], Array[low+1] := Array[low+1], Array[low]; \n low := low-1; \n } \n high := high+1; \n }\n} \n\n", "hints_removed": "predicate InsertionSorted(Array: array, left: int, right: int) \n requires 0 <= left <= right <= Array.Length \n reads Array \n{ \n forall i,j :: left <= i < j < right ==> Array[i] <= Array[j]\n}\n\n\nmethod sorting(Array: array)\n requires Array.Length > 1 \n ensures InsertionSorted(Array, 0, Array.Length) \n modifies Array\n{ \n var high := 1; \n while (high < Array.Length) \n { \n var low := high-1; \n while low >= 0 && Array[low+1] < Array[low]\n {\n Array[low], Array[low+1] := Array[low+1], Array[low]; \n low := low-1; \n } \n high := high+1; \n }\n} \n\n" }, { "test_ID": "214", "test_file": "Final-Project-Dafny_tmp_tmpmcywuqox_Attempts_Merge_Sort.dfy", "ground_truth": "method mergeSort(a: array)\nmodifies a\n{\n sorting(a, 0, a.Length-1);\n}\n\nmethod merging(a: array, low: int, medium: int, high: int)\nrequires 0 <= low <= medium <= high < a.Length\nmodifies a\n{\n var x := 0;\n var y := 0;\n var z := 0;\n var a1: array := new [medium - low + 1];\n var a2: array := new [high - medium];\n // The first case\n while(y < a1.Length && low+y < a.Length)\n invariant 0 <= y <= a1.Length\n invariant 0 <= low+y <= a.Length\n decreases a1.Length-y\n {\n a1[y] := a[low+y];\n y := y +1;\n }\n // The second case\n while(z < a2.Length && medium+z+1 < a.Length)\n invariant 0 <= z <= a2.Length\n invariant 0 <= medium+z <= a.Length\n decreases a2.Length-z\n {\n a2[z] := a[medium+z+1];\n z := z +1;\n }\n y, z := 0, 0;\n // The third case\n while (x < high - low + 1 && y <= a1.Length && z <= a2.Length && low+x < a.Length)\n invariant 0 <= x <= high - low + 1\n decreases high-low-x\n {\n if(y >= a1.Length && z >= a2.Length) {\n break;\n } else if(y >= a1.Length) {\n a[low+x] := a2[z];\n z := z+1;\n } else if(z >= a2.Length) {\n a[low+x] := a1[y];\n y := y+1;\n } else {\n if(a1[y] <= a2[z]) {\n a[low+x] := a1[y];\n y := y +1;\n } else {\n a[low+x] := a2[z];\n z := z +1;\n }\n }\n x := x+1;\n }\n}\n\nmethod sorting(a: array, low: int, high: int)\nrequires 0 <= low && high < a.Length\ndecreases high-low\nmodifies a\n{\n if (low < high) {\n var medium: int := low + (high - low)/2;\n sorting(a, low, medium);\n sorting(a, medium+1, high);\n merging(a, low, medium, high);\n }\n}\n", "hints_removed": "method mergeSort(a: array)\nmodifies a\n{\n sorting(a, 0, a.Length-1);\n}\n\nmethod merging(a: array, low: int, medium: int, high: int)\nrequires 0 <= low <= medium <= high < a.Length\nmodifies a\n{\n var x := 0;\n var y := 0;\n var z := 0;\n var a1: array := new [medium - low + 1];\n var a2: array := new [high - medium];\n // The first case\n while(y < a1.Length && low+y < a.Length)\n {\n a1[y] := a[low+y];\n y := y +1;\n }\n // The second case\n while(z < a2.Length && medium+z+1 < a.Length)\n {\n a2[z] := a[medium+z+1];\n z := z +1;\n }\n y, z := 0, 0;\n // The third case\n while (x < high - low + 1 && y <= a1.Length && z <= a2.Length && low+x < a.Length)\n {\n if(y >= a1.Length && z >= a2.Length) {\n break;\n } else if(y >= a1.Length) {\n a[low+x] := a2[z];\n z := z+1;\n } else if(z >= a2.Length) {\n a[low+x] := a1[y];\n y := y+1;\n } else {\n if(a1[y] <= a2[z]) {\n a[low+x] := a1[y];\n y := y +1;\n } else {\n a[low+x] := a2[z];\n z := z +1;\n }\n }\n x := x+1;\n }\n}\n\nmethod sorting(a: array, low: int, high: int)\nrequires 0 <= low && high < a.Length\nmodifies a\n{\n if (low < high) {\n var medium: int := low + (high - low)/2;\n sorting(a, low, medium);\n sorting(a, medium+1, high);\n merging(a, low, medium, high);\n }\n}\n" }, { "test_ID": "215", "test_file": "Final-Project-Dafny_tmp_tmpmcywuqox_Attempts_Quick_Sort.dfy", "ground_truth": "predicate quickSorted(Seq: seq)\n{\n forall idx_1, idx_2 :: 0 <= idx_1 < idx_2 < |Seq| ==> Seq[idx_1] <= Seq[idx_2]\n}\n\nmethod threshold(thres:int,Seq:seq) returns (Seq_1:seq,Seq_2:seq)\n ensures (forall x | x in Seq_1 :: x <= thres) && (forall x | x in Seq_2 :: x >= thres)\n ensures |Seq_1| + |Seq_2| == |Seq| \n ensures multiset(Seq_1) + multiset(Seq_2) == multiset(Seq)\n{\n Seq_1 := [];\n Seq_2 := [];\n var i := 0;\n while (i < |Seq|)\n invariant i <= |Seq|\n invariant (forall x | x in Seq_1 :: x <= thres) && (forall x | x in Seq_2 :: x >= thres)\n invariant |Seq_1| + |Seq_2| == i\n invariant multiset(Seq[..i]) == multiset(Seq_1) + multiset(Seq_2)\n {\n if (Seq[i] <= thres) {\n Seq_1 := Seq_1 + [Seq[i]];\n } else {\n Seq_2 := Seq_2 + [Seq[i]];\n }\n assert (Seq[..i] + [Seq[i]]) == Seq[..i+1]; \n i := i + 1;\n }\n assert (Seq[..|Seq|] == Seq); \n}\n\n\nlemma Lemma_1(Seq_1:seq,Seq_2:seq) // The proof of the lemma is not necessary\n requires multiset(Seq_1) == multiset(Seq_2)\n ensures forall x | x in Seq_1 :: x in Seq_2\n\n{\n forall x | x in Seq_1\n ensures x in multiset(Seq_1)\n {\n var i := 0;\n while (i < |Seq_1|)\n invariant 0 <= i <= |Seq_1|\n invariant forall idx_1 | 0 <= idx_1 < i :: Seq_1[idx_1] in multiset(Seq_1)\n {\n i := i + 1;\n }\n }\n\n}\n\n\n\nmethod quickSort(Seq: seq) returns (Seq': seq)\n ensures multiset(Seq) == multiset(Seq')\n decreases |Seq|\n{\n if |Seq| == 0 {\n return [];\n } else if |Seq| == 1 {\n return Seq;\n } else { \n var Seq_1,Seq_2 := threshold(Seq[0],Seq[1..]);\n var Seq_1' := quickSort(Seq_1);\n Lemma_1(Seq_1',Seq_1);\n var Seq_2' := quickSort(Seq_2);\n Lemma_1(Seq_2',Seq_2);\n assert Seq == [Seq[0]] + Seq[1..]; \n return Seq_1' + [Seq[0]] + Seq_2';\n }\n}\n\n\n\n\n\n\n", "hints_removed": "predicate quickSorted(Seq: seq)\n{\n forall idx_1, idx_2 :: 0 <= idx_1 < idx_2 < |Seq| ==> Seq[idx_1] <= Seq[idx_2]\n}\n\nmethod threshold(thres:int,Seq:seq) returns (Seq_1:seq,Seq_2:seq)\n ensures (forall x | x in Seq_1 :: x <= thres) && (forall x | x in Seq_2 :: x >= thres)\n ensures |Seq_1| + |Seq_2| == |Seq| \n ensures multiset(Seq_1) + multiset(Seq_2) == multiset(Seq)\n{\n Seq_1 := [];\n Seq_2 := [];\n var i := 0;\n while (i < |Seq|)\n {\n if (Seq[i] <= thres) {\n Seq_1 := Seq_1 + [Seq[i]];\n } else {\n Seq_2 := Seq_2 + [Seq[i]];\n }\n i := i + 1;\n }\n}\n\n\nlemma Lemma_1(Seq_1:seq,Seq_2:seq) // The proof of the lemma is not necessary\n requires multiset(Seq_1) == multiset(Seq_2)\n ensures forall x | x in Seq_1 :: x in Seq_2\n\n{\n forall x | x in Seq_1\n ensures x in multiset(Seq_1)\n {\n var i := 0;\n while (i < |Seq_1|)\n {\n i := i + 1;\n }\n }\n\n}\n\n\n\nmethod quickSort(Seq: seq) returns (Seq': seq)\n ensures multiset(Seq) == multiset(Seq')\n{\n if |Seq| == 0 {\n return [];\n } else if |Seq| == 1 {\n return Seq;\n } else { \n var Seq_1,Seq_2 := threshold(Seq[0],Seq[1..]);\n var Seq_1' := quickSort(Seq_1);\n Lemma_1(Seq_1',Seq_1);\n var Seq_2' := quickSort(Seq_2);\n Lemma_1(Seq_2',Seq_2);\n return Seq_1' + [Seq[0]] + Seq_2';\n }\n}\n\n\n\n\n\n\n" }, { "test_ID": "216", "test_file": "Final-Project-Dafny_tmp_tmpmcywuqox_Attempts_Selection_Sort_Standard.dfy", "ground_truth": "method selectionSorted(Array: array) \n modifies Array\n ensures multiset(old(Array[..])) == multiset(Array[..])\n{\n var idx := 0;\n while (idx < Array.Length)\n invariant 0 <= idx <= Array.Length\n invariant forall i,j :: 0 <= i < idx <= j < Array.Length ==> Array[i] <= Array[j] \n invariant forall i,j :: 0 <= i < j < idx ==> Array[i] <= Array[j] \n invariant multiset(old(Array[..])) == multiset(Array[..])\n {\n var minIndex := idx;\n var idx' := idx + 1;\n while (idx' < Array.Length)\n invariant idx <= idx' <= Array.Length\n invariant idx <= minIndex < idx' <= Array.Length\n invariant forall k :: idx <= k < idx' ==> Array[minIndex] <= Array[k] \n {\n if (Array[idx'] < Array[minIndex]) {\n minIndex := idx';\n }\n idx' := idx' + 1;\n }\n Array[idx], Array[minIndex] := Array[minIndex], Array[idx];\n idx := idx + 1;\n }\n}\n", "hints_removed": "method selectionSorted(Array: array) \n modifies Array\n ensures multiset(old(Array[..])) == multiset(Array[..])\n{\n var idx := 0;\n while (idx < Array.Length)\n {\n var minIndex := idx;\n var idx' := idx + 1;\n while (idx' < Array.Length)\n {\n if (Array[idx'] < Array[minIndex]) {\n minIndex := idx';\n }\n idx' := idx' + 1;\n }\n Array[idx], Array[minIndex] := Array[minIndex], Array[idx];\n idx := idx + 1;\n }\n}\n" }, { "test_ID": "217", "test_file": "Final-Project-Dafny_tmp_tmpmcywuqox_Final_Project_3.dfy", "ground_truth": "method nonZeroReturn(x: int) returns (y: int)\n ensures y != 0\n{\n if x == 0 {\n return x + 1;\n } else {\n return -x;\n }\n}\nmethod test() {\n var input := nonZeroReturn(-1);\n assert input != 0;\n}\n", "hints_removed": "method nonZeroReturn(x: int) returns (y: int)\n ensures y != 0\n{\n if x == 0 {\n return x + 1;\n } else {\n return -x;\n }\n}\nmethod test() {\n var input := nonZeroReturn(-1);\n}\n" }, { "test_ID": "218", "test_file": "FlexWeek_tmp_tmpc_tfdj_3_ex2.dfy", "ground_truth": "// 2. 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]\n\nfunction abs(a:int):nat\n{\n if a < 0 then -a else a\n}\n\nmethod aba(a:array)returns (b:array)\nensures a.Length == b.Length // needed for next line\nensures forall x :: 0<=x b[x] == abs(a[x])\n{\n \n b := new int[a.Length];\n var i:=0;\n\n while(i < a.Length)\n invariant 0<= i <= a.Length\n invariant forall x :: 0<=x b[x] == abs(a[x])\n {\n \n if(a[i] < 0){\n b[i] := -a[i];\n } else{\n b[i] := a[i];\n }\n i := i + 1;\n }\n \n\n}\n\n\nmethod Main()\n{\n var a := new int[][1,-2,-2,1];\n var b := aba(a);\n assert b[..] == [1,2,2,1];\n \n}\n", "hints_removed": "// 2. 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]\n\nfunction abs(a:int):nat\n{\n if a < 0 then -a else a\n}\n\nmethod aba(a:array)returns (b:array)\nensures a.Length == b.Length // needed for next line\nensures forall x :: 0<=x b[x] == abs(a[x])\n{\n \n b := new int[a.Length];\n var i:=0;\n\n while(i < a.Length)\n {\n \n if(a[i] < 0){\n b[i] := -a[i];\n } else{\n b[i] := a[i];\n }\n i := i + 1;\n }\n \n\n}\n\n\nmethod Main()\n{\n var a := new int[][1,-2,-2,1];\n var b := aba(a);\n \n}\n" }, { "test_ID": "219", "test_file": "FlexWeek_tmp_tmpc_tfdj_3_ex3.dfy", "ground_truth": "method Max(a:array)returns(m:int)\nensures a.Length > 0 ==> forall k :: 0<=k m >= a[k]// not strong enough\nensures a.Length == 0 ==> m == -1\nensures a.Length > 0 ==> m in a[..] // finally at the top // approach did not work for recusrive function\n{\n if(a.Length == 0){\n return -1;\n }\n assert a.Length > 0;\n var i := 0;\n m := a[0];\n assert m in a[..]; // had to show that m is in a[..], otherwise how could i assert for it\n\n while(i < a.Length)\n invariant 0<=i<=a.Length\n invariant forall k :: 0<=k m >= a[k]// Not strong enough\n invariant m in a[..] // again i the array\n // invariant 0 < i <= a.Length ==> (ret_max(a,i-1) == m)\n {\n if(a[i] >= m){\n m:= a[i];\n }\n i := i+1;\n }\n \n assert m in a[..]; //\n\n}\nmethod Checker()\n{\n var a := new nat[][1,2,3,50,5,51];\n // ghost var a := [1,2,3];\n var n := Max(a);\n // assert a[..] == [1,2,3];\n assert n == 51;\n // assert MAXIMUM(1,2) == 2;\n \n // assert ret_max(a,a.Length-1) == 12;\n // assert ret_max(a,a.Length-1) == x+3;\n}\n", "hints_removed": "method Max(a:array)returns(m:int)\nensures a.Length > 0 ==> forall k :: 0<=k m >= a[k]// not strong enough\nensures a.Length == 0 ==> m == -1\nensures a.Length > 0 ==> m in a[..] // finally at the top // approach did not work for recusrive function\n{\n if(a.Length == 0){\n return -1;\n }\n var i := 0;\n m := a[0];\n\n while(i < a.Length)\n // invariant 0 < i <= a.Length ==> (ret_max(a,i-1) == m)\n {\n if(a[i] >= m){\n m:= a[i];\n }\n i := i+1;\n }\n \n\n}\nmethod Checker()\n{\n var a := new nat[][1,2,3,50,5,51];\n // ghost var a := [1,2,3];\n var n := Max(a);\n // assert a[..] == [1,2,3];\n // assert MAXIMUM(1,2) == 2;\n \n // assert ret_max(a,a.Length-1) == 12;\n // assert ret_max(a,a.Length-1) == x+3;\n}\n" }, { "test_ID": "220", "test_file": "FlexWeek_tmp_tmpc_tfdj_3_ex4.dfy", "ground_truth": "method join(a:array,b:array) returns (c:array)\nensures a[..] + b[..] == c[..]\nensures multiset(a[..] + b[..]) == multiset(c[..])\nensures multiset(a[..]) + multiset(b[..]) == multiset(c[..])\nensures a.Length+b.Length == c.Length\n\n// Forall\n\nensures forall i :: 0<=i c[i] == a[i]\nensures forall i_2,j_2::\n a.Length <= i_2 < c.Length &&\n 0<=j_2< b.Length && i_2 - j_2 == a.Length ==> c[i_2] == b[j_2]\n\n{\n\n c := new int[a.Length+b.Length];\n var i:= 0;\n while(i < a.Length)\n invariant 0 <= i <=a.Length\n invariant c[..i] == a[..i]\n invariant multiset(c[..i]) == multiset(a[..i])\n invariant forall k :: 0<=k c[k] == a[k]\n {\n c[i] := a[i];\n i := i +1;\n }\n\n i:= a.Length;\n var j := 0;\n\n\n while(i < c.Length && j c[k] == a[k] // prev loop\n invariant forall i_2,j_2::\n a.Length <= i_2 < i &&\n 0<=j_2< j && i_2 - j_2 == a.Length ==> c[i_2] == b[j_2] // curr loop\n invariant forall k_2,i_2,j_2::\n 0<=k_2 c[i_2] == b[j_2] && c[k_2] == a[k_2] // prev loop+curr loop\n {\n \n c[i] := b[j];\n i := i +1;\n j := j +1;\n }\n\n // assert j == b.Length;\n // assert b[..]==b[..b.Length];\n // assert j + a.Length == c.Length;\n // assert multiset(c[..a.Length]) == multiset(a[..a.Length]);\n // assert multiset(b[..]) == multiset(b[..j]);\n // assert multiset(c[a.Length..j+a.Length]) == multiset(c[a.Length..c.Length]);\n // assert multiset(c[a.Length..c.Length]) == multiset(c[a.Length..c.Length]);\n // assert multiset(c[a.Length..c.Length]) == multiset(b[..]);\n // assert multiset(c[0..c.Length]) == multiset(c[0..a.Length]) + multiset(c[a.Length..c.Length]);\n \n // uncomment \n assert a[..] + b[..] == c[..];\n assert multiset(a[..]) + multiset(b[..]) == multiset(c[..]); \n\n\n \n}\n\n\nmethod Check(){\n var a := new int[][1,2,3];\n var b := new int[][4,5];\n var c := new int[][1,2,3,4,5];\n var d:= join(a,b);\n assert d[..] == a[..] + b[..]; // works \n assert multiset(d[..]) == multiset(a[..] + b[..]);\n assert multiset(d[..]) == multiset(a[..]) + multiset(b[..]);\n assert d[..] == c[..]; // works\n assert d[..] == c[..]; //doesn't\n // print n[..];\n\n}\n", "hints_removed": "method join(a:array,b:array) returns (c:array)\nensures a[..] + b[..] == c[..]\nensures multiset(a[..] + b[..]) == multiset(c[..])\nensures multiset(a[..]) + multiset(b[..]) == multiset(c[..])\nensures a.Length+b.Length == c.Length\n\n// Forall\n\nensures forall i :: 0<=i c[i] == a[i]\nensures forall i_2,j_2::\n a.Length <= i_2 < c.Length &&\n 0<=j_2< b.Length && i_2 - j_2 == a.Length ==> c[i_2] == b[j_2]\n\n{\n\n c := new int[a.Length+b.Length];\n var i:= 0;\n while(i < a.Length)\n {\n c[i] := a[i];\n i := i +1;\n }\n\n i:= a.Length;\n var j := 0;\n\n\n while(i < c.Length && j c[i_2] == b[j_2] // curr loop\n 0<=k_2 c[i_2] == b[j_2] && c[k_2] == a[k_2] // prev loop+curr loop\n {\n \n c[i] := b[j];\n i := i +1;\n j := j +1;\n }\n\n // assert j == b.Length;\n // assert b[..]==b[..b.Length];\n // assert j + a.Length == c.Length;\n // assert multiset(c[..a.Length]) == multiset(a[..a.Length]);\n // assert multiset(b[..]) == multiset(b[..j]);\n // assert multiset(c[a.Length..j+a.Length]) == multiset(c[a.Length..c.Length]);\n // assert multiset(c[a.Length..c.Length]) == multiset(c[a.Length..c.Length]);\n // assert multiset(c[a.Length..c.Length]) == multiset(b[..]);\n // assert multiset(c[0..c.Length]) == multiset(c[0..a.Length]) + multiset(c[a.Length..c.Length]);\n \n // uncomment \n\n\n \n}\n\n\nmethod Check(){\n var a := new int[][1,2,3];\n var b := new int[][4,5];\n var c := new int[][1,2,3,4,5];\n var d:= join(a,b);\n // print n[..];\n\n}\n" }, { "test_ID": "221", "test_file": "FlexWeek_tmp_tmpc_tfdj_3_reverse.dfy", "ground_truth": "// Write an *iterative* Dafny method Reverse with signature:\n// method Reverse(a: array) returns (b: array)\n\n// which takes an input array of characters 'a' and outputs array 'b' consisting of\n// the elements of the input array in reverse order. The following conditions apply:\n// - the input array cannot be empty\n// - the input array is not modified\n// - you must use iteration\n// - not permitted is an *executable* (parallel) forall statement\n// - not permitted are any other predicates, functions or methods\n\n// For the purposes of this practice exercise, I'll include a test method.\n\nmethod Reverse(a: array) returns (b: array)\nrequires a.Length > 0\nensures a.Length == b.Length\nensures forall k :: 0 <= k < a.Length ==> b[k] == a[(a.Length-1) - k];\n{\n b := new char[a.Length];\n assert b.Length == a.Length;\n var i:= 0;\n\n\n while(i < a.Length)\n invariant 0<=i<=a.Length\n // invariant 0 < i <= a.Length-1 ==> b[i-1] == a[(a.Length-1) - i+1] // Not good enough\n invariant forall k :: 0 <= k < i ==> b[k] == a[(a.Length-1) - k]\n {\n b[i] := a[(a.Length-1) - i];\n i := i + 1;\n }\n \n // assert forall k :: 0 <= k < a.Length ==> a[k] == b[(a.Length-1) - k];\n\n\n}\n\n\n\nmethod Main()\n{\n var a := new char[8];\n a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7] := 'd', 'e', 's', 'r', 'e', 'v', 'e', 'r';\n var b := Reverse(a);\n assert b[..] == [ 'r', 'e', 'v', 'e', 'r', 's', 'e', 'd' ];\n print b[..];\n\n a := new char[1];\n a[0] := '!';\n b := Reverse(a);\n assert b[..] == [ '!' ];\n print b[..], '\\n';\n}\n\n// Notice it compiles and the executable generates output (just to see the arrays printed in reverse).\n", "hints_removed": "// Write an *iterative* Dafny method Reverse with signature:\n// method Reverse(a: array) returns (b: array)\n\n// which takes an input array of characters 'a' and outputs array 'b' consisting of\n// the elements of the input array in reverse order. The following conditions apply:\n// - the input array cannot be empty\n// - the input array is not modified\n// - you must use iteration\n// - not permitted is an *executable* (parallel) forall statement\n// - not permitted are any other predicates, functions or methods\n\n// For the purposes of this practice exercise, I'll include a test method.\n\nmethod Reverse(a: array) returns (b: array)\nrequires a.Length > 0\nensures a.Length == b.Length\nensures forall k :: 0 <= k < a.Length ==> b[k] == a[(a.Length-1) - k];\n{\n b := new char[a.Length];\n var i:= 0;\n\n\n while(i < a.Length)\n // invariant 0 < i <= a.Length-1 ==> b[i-1] == a[(a.Length-1) - i+1] // Not good enough\n {\n b[i] := a[(a.Length-1) - i];\n i := i + 1;\n }\n \n // assert forall k :: 0 <= k < a.Length ==> a[k] == b[(a.Length-1) - k];\n\n\n}\n\n\n\nmethod Main()\n{\n var a := new char[8];\n a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7] := 'd', 'e', 's', 'r', 'e', 'v', 'e', 'r';\n var b := Reverse(a);\n print b[..];\n\n a := new char[1];\n a[0] := '!';\n b := Reverse(a);\n print b[..], '\\n';\n}\n\n// Notice it compiles and the executable generates output (just to see the arrays printed in reverse).\n" }, { "test_ID": "222", "test_file": "Formal-Methods-Project_tmp_tmphh2ar2xv_BubbleSort.dfy", "ground_truth": "predicate sorted(a: array?, l: int, u: int)\n reads a;\n requires a != null;\n {\n forall i, j :: 0 <= l <= i <= j <= u < a.Length ==> a[i] <= a[j]\n }\npredicate partitioned(a: array?, i: int)\n reads a\n requires a != null\n {\n forall k, k' :: 0 <= k <= i < k' < a.Length ==> a[k] <= a[k']\n }\n\nmethod BubbleSort(a: array?)\n modifies a\n requires a != null\n {\n var i := a.Length - 1;\n while(i > 0)\n invariant sorted(a, i, a.Length-1)\n invariant partitioned(a, i)\n {\n var j := 0;\n while (j < i)\n invariant 0 < i < a.Length && 0 <= j <= i\n invariant sorted(a, i, a.Length-1)\n invariant partitioned(a, i)\n invariant forall k :: 0 <= k <= j ==> a[k] <= a[j]\n {\n if(a[j] > a[j+1])\n {\n a[j], a[j+1] := a[j+1], a[j];\n }\n j := j + 1;\n }\n i := i -1;\n }\n }\n \nmethod Main() {\n var a := new int[5];\n a[0], a[1], a[2], a[3], a[4] := 9, 4, 6, 3, 8;\n BubbleSort(a);\n var k := 0;\n while(k < 5) { print a[k], \"\\n\"; k := k+1;}\n}\n", "hints_removed": "predicate sorted(a: array?, l: int, u: int)\n reads a;\n requires a != null;\n {\n forall i, j :: 0 <= l <= i <= j <= u < a.Length ==> a[i] <= a[j]\n }\npredicate partitioned(a: array?, i: int)\n reads a\n requires a != null\n {\n forall k, k' :: 0 <= k <= i < k' < a.Length ==> a[k] <= a[k']\n }\n\nmethod BubbleSort(a: array?)\n modifies a\n requires a != null\n {\n var i := a.Length - 1;\n while(i > 0)\n {\n var j := 0;\n while (j < i)\n {\n if(a[j] > a[j+1])\n {\n a[j], a[j+1] := a[j+1], a[j];\n }\n j := j + 1;\n }\n i := i -1;\n }\n }\n \nmethod Main() {\n var a := new int[5];\n a[0], a[1], a[2], a[3], a[4] := 9, 4, 6, 3, 8;\n BubbleSort(a);\n var k := 0;\n while(k < 5) { print a[k], \"\\n\"; k := k+1;}\n}\n" }, { "test_ID": "223", "test_file": "Formal-Methods-Project_tmp_tmphh2ar2xv_Factorial.dfy", "ground_truth": "\nmethod Fact(x: int) returns (y: int)\n requires x >= 0; \n{\n y := 1;\n var z := 0;\n while(z != x)\n decreases x - z;\n invariant 0 <= x-z;\n {\n z := z + 1;\n y := y * z;\n }\n}\nmethod Main() {\n var a := Fact(87);\n print a;\n}\n\n", "hints_removed": "\nmethod Fact(x: int) returns (y: int)\n requires x >= 0; \n{\n y := 1;\n var z := 0;\n while(z != x)\n {\n z := z + 1;\n y := y * z;\n }\n}\nmethod Main() {\n var a := Fact(87);\n print a;\n}\n\n" }, { "test_ID": "224", "test_file": "Formal-Verification-Project_tmp_tmp9gmwsmyp_strings3.dfy", "ground_truth": "predicate isPrefixPred(pre:string, str:string)\n{\n\t(|pre| <= |str|) && \n\tpre == str[..|pre|]\n}\n\npredicate isNotPrefixPred(pre:string, str:string)\n{\n\t(|pre| > |str|) || \n\tpre != str[..|pre|]\n}\n\nlemma PrefixNegationLemma(pre:string, str:string)\n\tensures isPrefixPred(pre,str) <==> !isNotPrefixPred(pre,str)\n\tensures !isPrefixPred(pre,str) <==> isNotPrefixPred(pre,str)\n{}\n\nmethod isPrefix(pre: string, str: string) returns (res:bool)\n\tensures !res <==> isNotPrefixPred(pre,str)\n\tensures res <==> isPrefixPred(pre,str)\n{\n\tif |str| < |pre| \n {\n return false;\n }\n else if pre[..] == str[..|pre|]\n {\n return true;\n }\n else{\n return false;\n }\n}\npredicate isSubstringPred(sub:string, str:string)\n{\n\t(exists i :: 0 <= i <= |str| && isPrefixPred(sub, str[i..]))\n}\n\npredicate isNotSubstringPred(sub:string, str:string)\n{\n\t(forall i :: 0 <= i <= |str| ==> isNotPrefixPred(sub,str[i..]))\n}\n\nlemma SubstringNegationLemma(sub:string, str:string)\n\tensures isSubstringPred(sub,str) <==> !isNotSubstringPred(sub,str)\n\tensures !isSubstringPred(sub,str) <==> isNotSubstringPred(sub,str)\n{}\n\nmethod isSubstring(sub: string, str: string) returns (res:bool)\n\tensures res <==> isSubstringPred(sub, str)\n\t//ensures !res <==> isNotSubstringPred(sub, str) // This postcondition follows from the above lemma.\n{\n // Initializing variables\n\tvar i := 0;\n res := false;\n // Check if sub is a prefix of str[i..] and if not, keep incrementing until i = |str| \n while i <= |str|\n // Invariant to stay within bounds\n invariant 0 <= i <= |str| + 1\n // Invariant to show that for all j that came before i, no prefix has been found\n invariant forall j :: (0 <= j < i ==> isNotPrefixPred(sub, str[j..]))\n // Telling dafny that i is that value that is increasing\n decreases |str| - i\n //invariant res <==> isSubstringPred(sub, str)\n {\n // Check if the substring is a prefix\n var temp := isPrefix(sub, str[i..]);\n // If so, return true as the prefix is a substring of the string\n if temp == true \n {\n return true;\n }\n // Otherwise, increment i and try again\n i := i + 1;\n } \n // If we have reached this point, it means that no substring has been found, hence return false\n return false;\n}\n\n\npredicate haveCommonKSubstringPred(k:nat, str1:string, str2:string)\n{\n\texists i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k && isSubstringPred(str1[i1..j1],str2)\n}\n\npredicate haveNotCommonKSubstringPred(k:nat, str1:string, str2:string)\n{\n\tforall i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k ==> isNotSubstringPred(str1[i1..j1],str2)\n}\n\nlemma commonKSubstringLemma(k:nat, str1:string, str2:string)\n\tensures haveCommonKSubstringPred(k,str1,str2) <==> !haveNotCommonKSubstringPred(k,str1,str2)\n\tensures !haveCommonKSubstringPred(k,str1,str2) <==> haveNotCommonKSubstringPred(k,str1,str2)\n{}\n\nmethod haveCommonKSubstring(k: nat, str1: string, str2: string) returns (found: bool)\n\tensures found <==> haveCommonKSubstringPred(k,str1,str2)\n\t//ensures !found <==> haveNotCommonKSubstringPred(k,str1,str2) // This postcondition follows from the above lemma.\n{\n // Check that both strings are larger than k \n if (k > |str1| || k > |str2| ){\n return false;\n\t}\n // Initialize variables\n\tvar i := 0;\n var temp := false;\n\n\t// Don't want to exceed the bounds of str1 when checking for the element that is k entries away\n while i <= |str1|-k\n // Invariant to stay within bounds\n invariant 0 <= i <= (|str1|-k) + 1\n // Invariant to show that when temp is true, it is a substring\n invariant temp ==> 0 <= i <= (|str1| - k) && isSubstringPred(str1[i..i+k], str2)\n // Invariant to show that when temp is false, it is not a substring\n invariant !temp ==> (forall m,n :: (0 <= m < i && n == m+k) ==> isNotSubstringPred(str1[m..n], str2))\n // Telling dafny that i is that value that is increasing\n decreases |str1| - k - i\n {\n // Get an index from the array position were are at to the array position that is k away and check the substring\n temp := isSubstring(str1[i..(i + k)], str2);\n if temp == true \n {\n return true;\n }\n i := i + 1;\n }\n return false;\n}\n\nlemma haveCommon0SubstringLemma(str1:string, str2:string)\n ensures haveCommonKSubstringPred(0,str1,str2)\n{\n assert isPrefixPred(str1[0..0], str2[0..]);\n}\n\nmethod maxCommonSubstringLength(str1: string, str2: string) returns (len:nat)\n\trequires (|str1| <= |str2|)\n\tensures (forall k :: len < k <= |str1| ==> !haveCommonKSubstringPred(k,str1,str2))\n\tensures haveCommonKSubstringPred(len,str1,str2)\n{\n var temp := false;\n var i := |str1|+1;\n len := i;\n // Idea is to start the counter at |str1| and decrement until common string is found\n while i > 0\n decreases i\n // Invariant to stay within bounds\n invariant 0 <= i <= |str1| + 1\n // When temp is true, there is a common sub string of size i\n invariant temp ==> haveCommonKSubstringPred(i, str1, str2)\n // When temp is false, there is not a common sub string of size i\n invariant !temp ==> haveNotCommonKSubstringPred(i, str1, str2)\n // When temp is false, there is no common sub string of sizes >= i\n invariant !temp ==> (forall k :: i <= k <= |str1| ==> !haveCommonKSubstringPred(k,str1,str2))\n // When temp is true, there is no common sub string of sizes > i\n invariant temp ==> (forall k :: (i < k <= |str1|) ==> !haveCommonKSubstringPred(k,str1,str2))\n {\n i:= i-1;\n len := i;\n temp := haveCommonKSubstring(i, str1, str2);\n if temp == true\n { \n break;\n }\n }\n haveCommon0SubstringLemma(str1, str2);\n return len;\n}\n\n\n\n\n\n", "hints_removed": "predicate isPrefixPred(pre:string, str:string)\n{\n\t(|pre| <= |str|) && \n\tpre == str[..|pre|]\n}\n\npredicate isNotPrefixPred(pre:string, str:string)\n{\n\t(|pre| > |str|) || \n\tpre != str[..|pre|]\n}\n\nlemma PrefixNegationLemma(pre:string, str:string)\n\tensures isPrefixPred(pre,str) <==> !isNotPrefixPred(pre,str)\n\tensures !isPrefixPred(pre,str) <==> isNotPrefixPred(pre,str)\n{}\n\nmethod isPrefix(pre: string, str: string) returns (res:bool)\n\tensures !res <==> isNotPrefixPred(pre,str)\n\tensures res <==> isPrefixPred(pre,str)\n{\n\tif |str| < |pre| \n {\n return false;\n }\n else if pre[..] == str[..|pre|]\n {\n return true;\n }\n else{\n return false;\n }\n}\npredicate isSubstringPred(sub:string, str:string)\n{\n\t(exists i :: 0 <= i <= |str| && isPrefixPred(sub, str[i..]))\n}\n\npredicate isNotSubstringPred(sub:string, str:string)\n{\n\t(forall i :: 0 <= i <= |str| ==> isNotPrefixPred(sub,str[i..]))\n}\n\nlemma SubstringNegationLemma(sub:string, str:string)\n\tensures isSubstringPred(sub,str) <==> !isNotSubstringPred(sub,str)\n\tensures !isSubstringPred(sub,str) <==> isNotSubstringPred(sub,str)\n{}\n\nmethod isSubstring(sub: string, str: string) returns (res:bool)\n\tensures res <==> isSubstringPred(sub, str)\n\t//ensures !res <==> isNotSubstringPred(sub, str) // This postcondition follows from the above lemma.\n{\n // Initializing variables\n\tvar i := 0;\n res := false;\n // Check if sub is a prefix of str[i..] and if not, keep incrementing until i = |str| \n while i <= |str|\n // Invariant to stay within bounds\n // Invariant to show that for all j that came before i, no prefix has been found\n // Telling dafny that i is that value that is increasing\n //invariant res <==> isSubstringPred(sub, str)\n {\n // Check if the substring is a prefix\n var temp := isPrefix(sub, str[i..]);\n // If so, return true as the prefix is a substring of the string\n if temp == true \n {\n return true;\n }\n // Otherwise, increment i and try again\n i := i + 1;\n } \n // If we have reached this point, it means that no substring has been found, hence return false\n return false;\n}\n\n\npredicate haveCommonKSubstringPred(k:nat, str1:string, str2:string)\n{\n\texists i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k && isSubstringPred(str1[i1..j1],str2)\n}\n\npredicate haveNotCommonKSubstringPred(k:nat, str1:string, str2:string)\n{\n\tforall i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k ==> isNotSubstringPred(str1[i1..j1],str2)\n}\n\nlemma commonKSubstringLemma(k:nat, str1:string, str2:string)\n\tensures haveCommonKSubstringPred(k,str1,str2) <==> !haveNotCommonKSubstringPred(k,str1,str2)\n\tensures !haveCommonKSubstringPred(k,str1,str2) <==> haveNotCommonKSubstringPred(k,str1,str2)\n{}\n\nmethod haveCommonKSubstring(k: nat, str1: string, str2: string) returns (found: bool)\n\tensures found <==> haveCommonKSubstringPred(k,str1,str2)\n\t//ensures !found <==> haveNotCommonKSubstringPred(k,str1,str2) // This postcondition follows from the above lemma.\n{\n // Check that both strings are larger than k \n if (k > |str1| || k > |str2| ){\n return false;\n\t}\n // Initialize variables\n\tvar i := 0;\n var temp := false;\n\n\t// Don't want to exceed the bounds of str1 when checking for the element that is k entries away\n while i <= |str1|-k\n // Invariant to stay within bounds\n // Invariant to show that when temp is true, it is a substring\n // Invariant to show that when temp is false, it is not a substring\n // Telling dafny that i is that value that is increasing\n {\n // Get an index from the array position were are at to the array position that is k away and check the substring\n temp := isSubstring(str1[i..(i + k)], str2);\n if temp == true \n {\n return true;\n }\n i := i + 1;\n }\n return false;\n}\n\nlemma haveCommon0SubstringLemma(str1:string, str2:string)\n ensures haveCommonKSubstringPred(0,str1,str2)\n{\n}\n\nmethod maxCommonSubstringLength(str1: string, str2: string) returns (len:nat)\n\trequires (|str1| <= |str2|)\n\tensures (forall k :: len < k <= |str1| ==> !haveCommonKSubstringPred(k,str1,str2))\n\tensures haveCommonKSubstringPred(len,str1,str2)\n{\n var temp := false;\n var i := |str1|+1;\n len := i;\n // Idea is to start the counter at |str1| and decrement until common string is found\n while i > 0\n // Invariant to stay within bounds\n // When temp is true, there is a common sub string of size i\n // When temp is false, there is not a common sub string of size i\n // When temp is false, there is no common sub string of sizes >= i\n // When temp is true, there is no common sub string of sizes > i\n {\n i:= i-1;\n len := i;\n temp := haveCommonKSubstring(i, str1, str2);\n if temp == true\n { \n break;\n }\n }\n haveCommon0SubstringLemma(str1, str2);\n return len;\n}\n\n\n\n\n\n" }, { "test_ID": "225", "test_file": "Formal-Verification_tmp_tmpuyt21wjt_Dafny_strings1.dfy", "ground_truth": "predicate isPrefixPredicate(pre: string, str:string)\n{\n |str| >= |pre| && pre <= str\n}\n\nmethod isPrefix(pre: string, str: string) returns (res: bool)\n ensures |pre| > |str| ==> !res\n ensures res == isPrefixPredicate(pre, str)\n{\n if |pre| > |str|\n {return false;}\n\n var i := 0;\n while i < |pre|\n decreases |pre| - i\n invariant 0 <= i <= |pre|\n invariant forall j :: 0 <= j < i ==> pre[j] == str[j]\n {\n if pre[i] != str[i]\n {\n return false;\n } \n i := i + 1;\n }\n return true;\n}\n\npredicate isSubstringPredicate (sub: string, str:string)\n{\n |str| >= |sub| && (exists i :: 0 <= i <= |str| && isPrefixPredicate(sub, str[i..]))\n}\n\nmethod isSubstring(sub: string, str: string) returns (res:bool)\nensures res == isSubstringPredicate(sub, str)\n{\n if |sub| > |str| {\n return false;\n }\n\n var i := |str| - |sub|;\n while i >= 0 \n decreases i\n invariant i >= -1\n invariant forall j :: i < j <= |str|-|sub| ==> !(isPrefixPredicate(sub, str[j..]))\n {\n var isPref := isPrefix(sub, str[i..]);\n if isPref\n {\n return true;\n }\n i := i-1;\n }\n return false;\n}\n\npredicate haveCommonKSubstringPredicate(k: nat, str1: string, str2: string)\n{\n |str1| >= k && |str2| >= k && (exists i :: 0 <= i <= |str1| - k && isSubstringPredicate((str1[i..])[..k], str2))\n}\n\n\nmethod haveCommonKSubstring(k: nat, str1: string, str2: string) returns (found: bool)\n ensures |str1| < k || |str2| < k ==> !found\n ensures haveCommonKSubstringPredicate(k,str1,str2) == found\n{\n if( |str1| < k || |str2| < k){\n return false;\n }\n var i := |str1| - k;\n while i >= 0\n decreases i\n invariant i >= -1 \n invariant forall j :: i < j <= |str1| - k ==> !isSubstringPredicate(str1[j..][..k], str2)\n {\n var isSub := isSubstring(str1[i..][..k], str2);\n if isSub \n {\n return true;\n }\n i := i-1;\n }\n return false;\n}\n\n\npredicate maxCommonSubstringPredicate(str1: string, str2: string, len:nat)\n{\n forall k :: len < k <= |str1| ==> !haveCommonKSubstringPredicate(k, str1, str2)\n}\n\nmethod maxCommonSubstringLength(str1: string, str2: string) returns (len:nat)\nensures len <= |str1| && len <= |str2|\nensures len >= 0\nensures maxCommonSubstringPredicate(str1, str2, len)\n{\n \n var i := |str1|;\n\n while i > 0\n decreases i\n invariant i >= 0\n invariant forall j :: i < j <= |str1| ==> !haveCommonKSubstringPredicate(j, str1, str2)\n {\n var ans := haveCommonKSubstring(i, str1, str2);\n if ans {\n return i;\n }\n i := i -1;\n }\n assert i == 0;\n return 0;\n\n}\n", "hints_removed": "predicate isPrefixPredicate(pre: string, str:string)\n{\n |str| >= |pre| && pre <= str\n}\n\nmethod isPrefix(pre: string, str: string) returns (res: bool)\n ensures |pre| > |str| ==> !res\n ensures res == isPrefixPredicate(pre, str)\n{\n if |pre| > |str|\n {return false;}\n\n var i := 0;\n while i < |pre|\n {\n if pre[i] != str[i]\n {\n return false;\n } \n i := i + 1;\n }\n return true;\n}\n\npredicate isSubstringPredicate (sub: string, str:string)\n{\n |str| >= |sub| && (exists i :: 0 <= i <= |str| && isPrefixPredicate(sub, str[i..]))\n}\n\nmethod isSubstring(sub: string, str: string) returns (res:bool)\nensures res == isSubstringPredicate(sub, str)\n{\n if |sub| > |str| {\n return false;\n }\n\n var i := |str| - |sub|;\n while i >= 0 \n {\n var isPref := isPrefix(sub, str[i..]);\n if isPref\n {\n return true;\n }\n i := i-1;\n }\n return false;\n}\n\npredicate haveCommonKSubstringPredicate(k: nat, str1: string, str2: string)\n{\n |str1| >= k && |str2| >= k && (exists i :: 0 <= i <= |str1| - k && isSubstringPredicate((str1[i..])[..k], str2))\n}\n\n\nmethod haveCommonKSubstring(k: nat, str1: string, str2: string) returns (found: bool)\n ensures |str1| < k || |str2| < k ==> !found\n ensures haveCommonKSubstringPredicate(k,str1,str2) == found\n{\n if( |str1| < k || |str2| < k){\n return false;\n }\n var i := |str1| - k;\n while i >= 0\n {\n var isSub := isSubstring(str1[i..][..k], str2);\n if isSub \n {\n return true;\n }\n i := i-1;\n }\n return false;\n}\n\n\npredicate maxCommonSubstringPredicate(str1: string, str2: string, len:nat)\n{\n forall k :: len < k <= |str1| ==> !haveCommonKSubstringPredicate(k, str1, str2)\n}\n\nmethod maxCommonSubstringLength(str1: string, str2: string) returns (len:nat)\nensures len <= |str1| && len <= |str2|\nensures len >= 0\nensures maxCommonSubstringPredicate(str1, str2, len)\n{\n \n var i := |str1|;\n\n while i > 0\n {\n var ans := haveCommonKSubstring(i, str1, str2);\n if ans {\n return i;\n }\n i := i -1;\n }\n return 0;\n\n}\n" }, { "test_ID": "226", "test_file": "Formal-Verification_tmp_tmpuyt21wjt_Dafny_strings3.dfy", "ground_truth": "// We spent 2h each on this assignment\n\npredicate isPrefixPred(pre:string, str:string)\n{\n\t(|pre| <= |str|) && \n\tpre == str[..|pre|]\n}\n\npredicate isNotPrefixPred(pre:string, str:string)\n{\n\t(|pre| > |str|) || \n\tpre != str[..|pre|]\n}\n\nlemma PrefixNegationLemma(pre:string, str:string)\n\tensures isPrefixPred(pre,str) <==> !isNotPrefixPred(pre,str)\n\tensures !isPrefixPred(pre,str) <==> isNotPrefixPred(pre,str)\n{}\n\nmethod isPrefix(pre: string, str: string) returns (res:bool)\n\tensures !res <==> isNotPrefixPred(pre,str)\n\tensures res <==> isPrefixPred(pre,str)\n{\n\tif |pre| > |str|\n \t{return false;}\n\n \tvar i := 0;\n \twhile i < |pre|\n \tdecreases |pre| - i\n \tinvariant 0 <= i <= |pre|\n \tinvariant forall j :: 0 <= j < i ==> pre[j] == str[j]\n \t{\n \tif pre[i] != str[i]\n \t{\n \t\treturn false;\n \t} \n \ti := i + 1;\n \t}\n \treturn true;\n}\npredicate isSubstringPred(sub:string, str:string)\n{\n\t(exists i :: 0 <= i <= |str| && isPrefixPred(sub, str[i..]))\n}\n\npredicate isNotSubstringPred(sub:string, str:string)\n{\n\t(forall i :: 0 <= i <= |str| ==> isNotPrefixPred(sub,str[i..]))\n}\n\nlemma SubstringNegationLemma(sub:string, str:string)\n\tensures isSubstringPred(sub,str) <==> !isNotSubstringPred(sub,str)\n\tensures !isSubstringPred(sub,str) <==> isNotSubstringPred(sub,str)\n{}\n\nmethod isSubstring(sub: string, str: string) returns (res:bool)\n\tensures res <==> isSubstringPred(sub, str)\n\t//ensures !res <==> isNotSubstringPred(sub, str) // This postcondition follows from the above lemma.\n{\n\tif |sub| > |str| {\n return false;\n }\n\n var i := |str| - |sub|;\n while i >= 0 \n decreases i\n invariant i >= -1\n invariant forall j :: i < j <= |str|-|sub| ==> !(isPrefixPred(sub, str[j..]))\n {\n var isPref := isPrefix(sub, str[i..]);\n if isPref\n {\n return true;\n }\n i := i-1;\n }\n return false;\n}\n\npredicate haveCommonKSubstringPred(k:nat, str1:string, str2:string)\n{\n\texists i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k && isSubstringPred(str1[i1..j1],str2)\n}\n\npredicate haveNotCommonKSubstringPred(k:nat, str1:string, str2:string)\n{\n\tforall i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k ==> isNotSubstringPred(str1[i1..j1],str2)\n}\n\nlemma commonKSubstringLemma(k:nat, str1:string, str2:string)\n\tensures haveCommonKSubstringPred(k,str1,str2) <==> !haveNotCommonKSubstringPred(k,str1,str2)\n\tensures !haveCommonKSubstringPred(k,str1,str2) <==> haveNotCommonKSubstringPred(k,str1,str2)\n{}\n\nmethod haveCommonKSubstring(k: nat, str1: string, str2: string) returns (found: bool)\n\tensures found <==> haveCommonKSubstringPred(k,str1,str2)\n\t//ensures !found <==> haveNotCommonKSubstringPred(k,str1,str2) // This postcondition follows from the above lemma.\n{\n\t if( |str1| < k || |str2| < k){\n return false;\n }\n var i := |str1| - k;\n while i >= 0\n decreases i\n invariant i >= -1 \n invariant forall j,t :: i < j <= |str1| - k && t==j+k ==> !isSubstringPred(str1[j..t], str2)\n {\n\t\t\t\tvar t := i+k;\n var isSub := isSubstring(str1[i..t], str2);\n if isSub \n {\n return true;\n }\n i := i-1;\n }\n return false;\n}\n\nmethod maxCommonSubstringLength(str1: string, str2: string) returns (len:nat)\n\trequires (|str1| <= |str2|)\n\tensures (forall k :: len < k <= |str1| ==> !haveCommonKSubstringPred(k,str1,str2))\n\tensures haveCommonKSubstringPred(len,str1,str2)\n{\n\tvar i := |str1|;\n\n \twhile i > 0\n \tdecreases i\n \tinvariant i >= 0\n \tinvariant forall j :: i < j <= |str1| ==> !haveCommonKSubstringPred(j, str1, str2)\n \t{\n \tvar ans := haveCommonKSubstring(i, str1, str2);\n \tif ans {\n \t\treturn i;\n \t}\n \ti := i -1;\n \t}\n \tassert i == 0;\n\tassert isPrefixPred(str1[0..0],str2[0..]);\n \treturn 0;\n}\n\n\n\n", "hints_removed": "// We spent 2h each on this assignment\n\npredicate isPrefixPred(pre:string, str:string)\n{\n\t(|pre| <= |str|) && \n\tpre == str[..|pre|]\n}\n\npredicate isNotPrefixPred(pre:string, str:string)\n{\n\t(|pre| > |str|) || \n\tpre != str[..|pre|]\n}\n\nlemma PrefixNegationLemma(pre:string, str:string)\n\tensures isPrefixPred(pre,str) <==> !isNotPrefixPred(pre,str)\n\tensures !isPrefixPred(pre,str) <==> isNotPrefixPred(pre,str)\n{}\n\nmethod isPrefix(pre: string, str: string) returns (res:bool)\n\tensures !res <==> isNotPrefixPred(pre,str)\n\tensures res <==> isPrefixPred(pre,str)\n{\n\tif |pre| > |str|\n \t{return false;}\n\n \tvar i := 0;\n \twhile i < |pre|\n \t{\n \tif pre[i] != str[i]\n \t{\n \t\treturn false;\n \t} \n \ti := i + 1;\n \t}\n \treturn true;\n}\npredicate isSubstringPred(sub:string, str:string)\n{\n\t(exists i :: 0 <= i <= |str| && isPrefixPred(sub, str[i..]))\n}\n\npredicate isNotSubstringPred(sub:string, str:string)\n{\n\t(forall i :: 0 <= i <= |str| ==> isNotPrefixPred(sub,str[i..]))\n}\n\nlemma SubstringNegationLemma(sub:string, str:string)\n\tensures isSubstringPred(sub,str) <==> !isNotSubstringPred(sub,str)\n\tensures !isSubstringPred(sub,str) <==> isNotSubstringPred(sub,str)\n{}\n\nmethod isSubstring(sub: string, str: string) returns (res:bool)\n\tensures res <==> isSubstringPred(sub, str)\n\t//ensures !res <==> isNotSubstringPred(sub, str) // This postcondition follows from the above lemma.\n{\n\tif |sub| > |str| {\n return false;\n }\n\n var i := |str| - |sub|;\n while i >= 0 \n {\n var isPref := isPrefix(sub, str[i..]);\n if isPref\n {\n return true;\n }\n i := i-1;\n }\n return false;\n}\n\npredicate haveCommonKSubstringPred(k:nat, str1:string, str2:string)\n{\n\texists i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k && isSubstringPred(str1[i1..j1],str2)\n}\n\npredicate haveNotCommonKSubstringPred(k:nat, str1:string, str2:string)\n{\n\tforall i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k ==> isNotSubstringPred(str1[i1..j1],str2)\n}\n\nlemma commonKSubstringLemma(k:nat, str1:string, str2:string)\n\tensures haveCommonKSubstringPred(k,str1,str2) <==> !haveNotCommonKSubstringPred(k,str1,str2)\n\tensures !haveCommonKSubstringPred(k,str1,str2) <==> haveNotCommonKSubstringPred(k,str1,str2)\n{}\n\nmethod haveCommonKSubstring(k: nat, str1: string, str2: string) returns (found: bool)\n\tensures found <==> haveCommonKSubstringPred(k,str1,str2)\n\t//ensures !found <==> haveNotCommonKSubstringPred(k,str1,str2) // This postcondition follows from the above lemma.\n{\n\t if( |str1| < k || |str2| < k){\n return false;\n }\n var i := |str1| - k;\n while i >= 0\n {\n\t\t\t\tvar t := i+k;\n var isSub := isSubstring(str1[i..t], str2);\n if isSub \n {\n return true;\n }\n i := i-1;\n }\n return false;\n}\n\nmethod maxCommonSubstringLength(str1: string, str2: string) returns (len:nat)\n\trequires (|str1| <= |str2|)\n\tensures (forall k :: len < k <= |str1| ==> !haveCommonKSubstringPred(k,str1,str2))\n\tensures haveCommonKSubstringPred(len,str1,str2)\n{\n\tvar i := |str1|;\n\n \twhile i > 0\n \t{\n \tvar ans := haveCommonKSubstring(i, str1, str2);\n \tif ans {\n \t\treturn i;\n \t}\n \ti := i -1;\n \t}\n \treturn 0;\n}\n\n\n\n" }, { "test_ID": "227", "test_file": "Formal-methods-of-software-development_tmp_tmppryvbyty_Bloque 1_Lab3.dfy", "ground_truth": "\nmethod multipleReturns (x:int, y:int) returns (more:int, less:int)\nrequires y > 0\nensures less < x < more\n\n\nmethod multipleReturns2 (x:int, y:int) returns (more:int, less:int)\nrequires y > 0\nensures more + less == 2*x\n\n// TODO: Hacer en casa\nmethod multipleReturns3 (x:int, y:int) returns (more:int, less:int)\nrequires y > 0\nensures more - less == 2*y\n\nfunction factorial(n:int):int\nrequires n>=0\n{\n if n==0 || n==1 then 1 else n*factorial(n-1)\n}\n\n// PROGRAMA VERIFICADOR DE WHILE\nmethod ComputeFact (n:int) returns (f:int)\nrequires n >=0\nensures f== factorial(n)\n\n{ \n assert 0 <= n <= n && 1*factorial(n) == factorial(n);\n f:=1;\n assert 0 <= n <= n && f*factorial(n) == factorial(n);\n var x:=n;\n assert 0 <= x <= n && f*factorial(x) == factorial(n);\n while x > 0 \n invariant 0 <= x <= n;\n invariant f*factorial(x)== factorial(n);\n decreases x-0;\n {\n assert 0 <= x-1 <= n && (f*x)*factorial(x-1) == factorial(n);\n f:= f*x;\n assert 0 <= x-1 <= n && f*factorial(x-1) == factorial(n);\n x:=x-1;\n assert 0 <= x <= n && f*factorial(x) == factorial(n);\n }\n assert 0 <= x <= n && f*factorial(x) == factorial(n);\n}\n\nmethod ComputeFact2 (n:int) returns (f:int)\nrequires n >=0\nensures f== factorial(n)\n{\n var x:= 0;\n f:= 1;\n while x=1 ==> 1 + 3 + 5 + ... + (2*n-1) = n*n\n\nmethod Sqare(a:int) returns (x:int)\nrequires a>=1\nensures x == a*a\n{\n assert 1==1 && 1 <= 1 <= a;\n var y:=1;\n assert y*y==1 && 1 <= y <= a;\n x:=1;\n while y < a \n invariant 1 <= y <= a;\n invariant y*y==x;\n {\n assert (y+1)*(y+1)==x+ (2*(y+1)-1) && 1 <= (y+1) <= a;\n y:= y+1;\n assert y*y==x+ (2*y-1) && 1 <= y <= a;\n x:= x+ (2*y-1);\n assert y*y==x && 1 <= y <= a;\n }\n assert y*y==x && 1 <= y <= a;\n}\n\n\nfunction sumSerie(n:int):int\nrequires n >=1 \n{\n if n==1 then 1 else sumSerie(n-1) + 2*n -1\n}\n\nlemma {:induction false} Sqare_Lemma (n:int)\nrequires n>=1\nensures sumSerie(n) == n*n\n{\n if n==1 {}\n else{\n Sqare_Lemma(n-1);\n assert sumSerie(n-1) ==(n-1)*(n-1);\n\n calc == {\n sumSerie(n);\n sumSerie(n-1) + 2*n -1;\n {\n Sqare_Lemma(n-1);\n assert sumSerie(n-1) ==(n-1)*(n-1);\n }\n (n-1)*(n-1) + 2*n -1;\n n*n-2*n+1 +2*n -1;\n n*n;\n }\n assert sumSerie(n) == n*n;\n }\n}\n\n\nmethod Sqare2(a:int) returns (x:int)\nrequires a>=1\nensures x == a*a\n\n{\n assert 1 <= 1 <= a && 1==1*1;\n var y:=1;\n assert 1 <= y <= a && 1==y*y;\n x:=1;\n assert 1 <= y <= a && x==y*y;\n while y < a \n invariant 1 <= y <= a\n invariant x==y*y\n decreases a - y\n {\n assert 1 <= (y+1) <= a && (x+2*(y+1)-1)==(y+1)*(y+1);\n y:= y+1;\n assert 1 <= y <= a && (x+2*y-1)==y*y;\n x:= x +2*y -1;\n assert 1 <= y <= a && x==y*y;\n }\n assert 1 <= y <= a && x==y*y;\n}\n\n\n", "hints_removed": "\nmethod multipleReturns (x:int, y:int) returns (more:int, less:int)\nrequires y > 0\nensures less < x < more\n\n\nmethod multipleReturns2 (x:int, y:int) returns (more:int, less:int)\nrequires y > 0\nensures more + less == 2*x\n\n// TODO: Hacer en casa\nmethod multipleReturns3 (x:int, y:int) returns (more:int, less:int)\nrequires y > 0\nensures more - less == 2*y\n\nfunction factorial(n:int):int\nrequires n>=0\n{\n if n==0 || n==1 then 1 else n*factorial(n-1)\n}\n\n// PROGRAMA VERIFICADOR DE WHILE\nmethod ComputeFact (n:int) returns (f:int)\nrequires n >=0\nensures f== factorial(n)\n\n{ \n f:=1;\n var x:=n;\n while x > 0 \n {\n f:= f*x;\n x:=x-1;\n }\n}\n\nmethod ComputeFact2 (n:int) returns (f:int)\nrequires n >=0\nensures f== factorial(n)\n{\n var x:= 0;\n f:= 1;\n while x=1 ==> 1 + 3 + 5 + ... + (2*n-1) = n*n\n\nmethod Sqare(a:int) returns (x:int)\nrequires a>=1\nensures x == a*a\n{\n var y:=1;\n x:=1;\n while y < a \n {\n y:= y+1;\n x:= x+ (2*y-1);\n }\n}\n\n\nfunction sumSerie(n:int):int\nrequires n >=1 \n{\n if n==1 then 1 else sumSerie(n-1) + 2*n -1\n}\n\nlemma {:induction false} Sqare_Lemma (n:int)\nrequires n>=1\nensures sumSerie(n) == n*n\n{\n if n==1 {}\n else{\n Sqare_Lemma(n-1);\n\n calc == {\n sumSerie(n);\n sumSerie(n-1) + 2*n -1;\n {\n Sqare_Lemma(n-1);\n }\n (n-1)*(n-1) + 2*n -1;\n n*n-2*n+1 +2*n -1;\n n*n;\n }\n }\n}\n\n\nmethod Sqare2(a:int) returns (x:int)\nrequires a>=1\nensures x == a*a\n\n{\n var y:=1;\n x:=1;\n while y < a \n {\n y:= y+1;\n x:= x +2*y -1;\n }\n}\n\n\n" }, { "test_ID": "228", "test_file": "Formal-methods-of-software-development_tmp_tmppryvbyty_Bloque 2_Lab6.dfy", "ground_truth": "/*predicate palindrome (s:seq)\n{\n forall i:: 0<=i<|s| ==> s[i] == s[|s|-i-1]\n}\n*/\n// SUM OF A SEQUENCE OF INTEGERS\nfunction sum(v: seq): int \ndecreases v\n{\n if v==[] then 0\n else if |v|==1 then v[0]\n else v[0]+sum(v[1..])\n}\n\n/*\nmethod vector_Sum(v:seq) returns (x:int)\nensures x == sum(v) \n{\n var n := 0 ;\n x := 0;\n while n != |v|\n invariant 0 <= n <= |v|\n invariant x==sum(v[..n])\n\t{\n assert x == sum(v[..n]) && 0 <= n+1 <= |v|;\n assert x + v[n] == sum(v[..n])+ v[n] && 0 <= n+1 <= |v|;\n left_sum_Lemma(v, n+1);\n assert x + v[n] == sum(v[..n+1]) && 0 <= n+1 <= |v|;\n x, n := x + v[n], n + 1;\n assert x==sum(v[..n]) && 0 <= n <= |v|;\n }\n assert v== v[..v];\n assert sum(v)==sum(v[..n]);\n assert x == sum(v) && 0 <= n <= |v|;\n assert x==sum(v[..n]) && 0 <= n <= |v|;\n}\n\n// Structural Induction on Sequences\nlemma left_sum_Lemma(r:seq, k:int)\nrequires 0 <= k < |r|\nensures sum(r[..k]) + r[k] == sum(r[..k+1]);\n{\n if |r|==1 || k==0{\n assert sum(r[..0])+r[0]== sum(r[..1]);\n }\n else {\n left_sum_Lemma(r[1..], k);\n assert sum(r[1..][..k]) + r[k] == sum(r[1..][..k+1]);\n\n calc {\n sum(r[..k+1]);\n sum(r[..k]) + [r[k]];\n }\n }\n}\n\n// MAXIMUM OF A SEQUENCE\nmethod maxSeq(v: seq) returns (max:int)\nrequires |v| >= 1\nensures forall i :: 0 <= i < |v| ==> max >= v[i]\nensures max in v\n{\n max := v[0];\n var v' := v[1..];\n ghost var t := [v[0]];\n while |v'| >= 1\n invariant forall i :: 0 <= i < |t| ==> max >= t[i]\n invariant v == t + v'\n invariant max in t\n decreases |v'| - 1\n\t{\n if v'[0] > max { max := v'[0]; }\n v', t := v'[1..], t + [v'[0]];\n\t}\n}\n\n// TODO: Hacer\n// Derivar formalmente un calculo incremental de j*j*j\nmethod Cubes (n:int) returns (s:seq)\nrequires n >= 0\nensures |s| == n\nensures forall i:int :: 0 <= i < n ==> s[i] == i*i*i\n{\ns := [];\nvar c, j, k, m := 0,0,1,6;\nwhile j < n\n\tinvariant 0 <= j ==|s| <= n\n\tinvariant forall i:int :: 0 <= i < j ==> s[i] == i*i*i\n\tinvariant c == j*j*j\n\tinvariant k == 3*j*j + 3*j + 1\n\tinvariant m == 6*j + 6\n\t{\n\ts := s+[c]; \n\t//c := (j+1)*(j+1)*(j+1);\n\tc := c + k;\n\tk := k + 6*j + 6;\n\tm := m + 6;\n\t//assert m == 6*(j+1) + 6 == 6*j + 6 + 6;\n\tassert k == 3*(j+1)*(j+1) + 3*(j+1) + 1 \n == 3*j*j + 9*j + 7\n == 3*j*j + 3*j + 1 + (6*j + 6);\n\t//assert c == (j+1)*(j+1)*(j+1) == j*j*j + 3*j*j + 3*j + 1;\n\tj := j+1;\n\t//assert m == 6*j + 6;\n\t//assert k == 3*j*j + 3*j + 1;\n\t//assert c == j*j*j;\n\t}\n}\n\n\n// REVERSE OF A SEQUENCE\nfunction reverse (s:seq):seq \n{\n if s==[] then []\n else reverse(s[1..])+[s[0]]\n}\n\nfunction seq2set (s:seq): set\n{\n if s==[] then {}\n else {s[0]}+seq2set(s[1..])\n}\n\n\nlemma seq2setRev_Lemma (s:seq)\nensures seq2set(reverse(s)) == seq2set(s)\n{\n if s==[]{}\n else {\n seq2setRev_Lemma(s[1..]);\n assert seq2set(reverse(s[1..])) == seq2set(s[1..]);\n\n calc {\n seq2set(s);\n seq2set([s[0]]+s[1..]);\n {\n concat_seq2set_Lemma([s[0]], s[1..]);\n assert seq2set([s[0]]+s[1..]) == seq2set([s[0]]) + seq2set(s[1..]);\n }\n seq2set([s[0]]) + seq2set(s[1..]);\n {\n seq2setRev_Lemma(s[1..]);\n assert seq2set(reverse(s[1..])) == seq2set(s[1..]);\n }\n seq2set([s[0]]) + seq2set(reverse(s[1..]));\n seq2set(reverse(s[1..])) + seq2set([s[0]]); \n {\n concat_seq2set_Lemma(reverse(s[1..]), [s[0]]);\n }\n seq2set(reverse(s[1..]) + [s[0]]);\n {\n assert reverse([s[0]]+s[1..]) == reverse(s);\n assert [s[0]]+s[1..] == s;\n assert reverse(s[1..])+[s[0]] == reverse(s);\n }\n seq2set(reverse(s));\n }\n }\n}\n\n\nlemma concat_seq2set_Lemma(s1:seq,s2:seq)\nensures seq2set(s1+s2) == seq2set(s1) + seq2set(s2)\n{\n if s1==[]{\n assert seq2set(s2) == seq2set([]) + seq2set(s2);\n assert []==s1;\n\t\tassert []+s2==s2;\n\t\tassert s1+s2==s2;\n\t\tassert seq2set(s1+s2)==seq2set(s2);\n }\n else {\n concat_seq2set_Lemma(s1[1..], s2);\n assert seq2set(s1[1..]+s2) == seq2set(s1[1..]) + seq2set(s2);\n\n calc{\n seq2set(s1) + seq2set(s2);\n seq2set([s1[0]]+s1[1..]) + seq2set(s2);\n seq2set([s1[0]]) + seq2set(s1[1..]) + seq2set(s2);\n {\n concat_seq2set_Lemma(s1[1..], s2);\n assert seq2set(s1[1..]+s2) == seq2set(s1[1..]) + seq2set(s2);\n }\n seq2set([s1[0]]) + seq2set(s1[1..]+s2);\n {\n assert s1[1..]+s2 == (s1+s2)[1..];\n }\n seq2set([s1[0]]) + seq2set((s1+s2)[1..]);\n {\n // assert seq2set([s1[0]]) + seq2set((s1+s2)[1..]) == seq2set(s1+s2);\n var ls:= s1+s2;\n calc {\n seq2set([s1[0]]) + seq2set((s1+s2)[1..]);\n seq2set([ls[0]])+ seq2set(ls[1..]);\n seq2set([ls[0]]+ ls[1..]);\n seq2set(ls);\n seq2set(s1+s2);\n }\n }\n seq2set(s1+s2);\n }\n }\n}\n\n\n// REVERSE IS ITS OWN INVERSE\n\nlemma Rev_Lemma(s:seq)\n//ensures forall i :: 0 <= i < |s| ==> s[i] == reverse(s)[|s|-1-i]\n\nlemma ItsOwnInverse_Lemma (s:seq)\nensures s == reverse(reverse(s))\n{\n if s==[]{}\n else{\n ItsOwnInverse_Lemma(s[1..]);\n assert s[1..] == reverse(reverse(s[1..]));\n\n calc {\n reverse(reverse(s));\n reverse(reverse(s[1..])+[s[0]]);\n reverse(reverse([s[0]]+s[1..]));\n {\n assert reverse([s[0]]+ s[1..]) == reverse(s[1..]) + [s[0]];\n assert reverse(reverse([s[0]]+ s[1..])) == reverse(reverse(s[1..]) + [s[0]]);\n }\n reverse(reverse(s[1..]) + [s[0]]);\n {\n // TODO: Demostrar este assume\n assume reverse(reverse(s[1..]) + [s[0]]) == [s[0]] + reverse(reverse(s[1..]));\n }\n [s[0]] + reverse(reverse(s[1..]));\n {\n ItsOwnInverse_Lemma(s[1..]);\n assert s[1..] == reverse(reverse(s[1..]));\n }\n [s[0]]+s[1..];\n s;\n }\n }\n}\n\n// SCALAR PRODUCT OF TWO VECTORS OF INTEGER\nfunction scalar_product (v1:seq, v2:seq):int\nrequires |v1| == |v2|\n{\n if v1 == [] then 0 else v1[0]*v2[0] + scalar_product(v1[1..],v2[1..])\n}\n\n\nlemma scalar_product_Lemma (v1:seq, v2:seq)\nrequires |v1| == |v2| > 0\nensures scalar_product(v1,v2) == scalar_product(v1[..|v1|-1],v2[..|v2|-1]) + v1[|v1|-1] * v2[|v2|-1]\n{\n // INDUCCION EN LA LONGITUD DE V1\n if |v1| == 0 && |v2| == 0 {}\n else if |v1| == 1 {}\n else {\n // Se crean estas variables para simplificar las operaciones\n var v1r:= v1[1..];\n var v2r:= v2[1..];\n var t1:= |v1[1..]|-1;\n var t2:= |v2[1..]|-1;\n\n // Se realiza la induccion utilizando las variables\n scalar_product_Lemma(v1r, v2r);\n assert scalar_product(v1r,v2r) == \n scalar_product(v1r[..t1],v2r[..t2]) + v1r[t1] * v2r[t2]; //HI\n \n // Se demuestra que la propiedad se mantiene\n calc{\n scalar_product(v1,v2);\n v1[0]*v2[0] + scalar_product(v1r, v2r);\n v1[0]*v2[0] + scalar_product(v1r[..t1],v2r[..t2]) + v1r[t1] * v2r[t2];\n {\n scalar_product_Lemma(v1r, v2r);\n assert scalar_product(v1r,v2r) == \n scalar_product(v1r[..t1],v2r[..t2]) + v1r[t1] * v2r[t2]; //HI\n }\n v1[0]*v2[0] + scalar_product(v1r,v2r);\n v1[0]*v2[0] + scalar_product(v1[1..],v2[1..]);\n scalar_product(v1,v2);\n }\n }\n}\n\n// MULTISETS\n\nmethod multiplicity_examples ()\n{\nvar m := multiset{2,4,6,2,1,3,1,7,1,5,4,7,8,1,6};\nassert m[7] == 2;\nassert m[1] == 4;\n\nassert forall m1: multiset, m2 :: m1 == m2 <==> forall z:T :: m1[z] == m2[z];\n}\n\n// REVERSE HAS THE SAME MULTISET \n\nlemma seqMultiset_Lemma (s:seq)\nensures multiset(reverse(s)) == multiset(s)\n{\n if s==[]{}\n else {\n seqMultiset_Lemma(s[1..]);\n assert multiset(reverse(s[1..])) == multiset(s[1..]);\n\n calc {\n multiset(reverse(s));\n multiset(reverse(s[1..]) + [s[0]]);\n multiset(reverse(s[1..])) + multiset{[s[0]]};\n multiset(s[1..]) + multiset{[s[0]]};\n multiset(s);\n }\n assert multiset(reverse(s)) == multiset(s);\n }\n}\n*/\nlemma empty_Lemma (r:seq)\nrequires multiset(r) == multiset{} \nensures r == []\n{\n\tif r != []\t{\n\t\tassert r[0] in multiset(r);\n\t}\n}\n\nlemma elem_Lemma (s:seq,r:seq)\nrequires s != [] && multiset(s) == multiset(r)\nensures exists i :: 0 <= i < |r| && r[i] == s[0] && multiset(s[1..]) == multiset(r[..i]+r[i+1..]);\n\n// SEQUENCES WITH EQUAL MULTISETS HAVE EQUAL SUMS\n\nlemma sumElems_Lemma(s:seq, r:seq) \nrequires multiset(s) == multiset(r)\nensures sum(s) == sum(r)\n{\n if s==[]{\n empty_Lemma(r);\n }\n else {\n // Con este lema demuestro que el elemento que le quito a s tambien se lo quito a r y de esta manera\n // poder hacer la induccion\n elem_Lemma(s,r);\n\t\tvar i :| 0 <= i < |r| && r[i] == s[0] && multiset(s[1..]) == multiset(r[..i]+r[i+1..]);\n\t\tsumElems_Lemma(s[1..], r[..i]+r[i+1..]);\n\t\tassert sum(s[1..]) == sum(r[..i]+r[i+1..]); //HI\n \n // Hago la llamada recursiva\n sumElems_Lemma(s[1..], r[..i]+r[i+1..]);\n assert sum(s[1..]) == sum(r[..i]+r[i+1..]);\n\n calc {\n sum(s);\n s[0]+sum(s[1..]);\n {\n sumElems_Lemma(s[1..], r[..i]+r[i+1..]);\n assert sum(s[1..]) == sum(r[..i]+r[i+1..]);\n }\n s[0]+sum(r[..i]+r[i+1..]);\n {\n assert s[0] == r[i];\n }\n r[i]+sum(r[..i]+r[i+1..]);\n {\n // TODO: No consigo acertarlo\n assume r[i]+sum(r[..i]+r[i+1..]) == sum([r[i]]+r[..i] + r[i+1..]) == sum(r);\n }\n sum(r);\n }\n }\n}\n", "hints_removed": "/*predicate palindrome (s:seq)\n{\n forall i:: 0<=i<|s| ==> s[i] == s[|s|-i-1]\n}\n*/\n// SUM OF A SEQUENCE OF INTEGERS\nfunction sum(v: seq): int \n{\n if v==[] then 0\n else if |v|==1 then v[0]\n else v[0]+sum(v[1..])\n}\n\n/*\nmethod vector_Sum(v:seq) returns (x:int)\nensures x == sum(v) \n{\n var n := 0 ;\n x := 0;\n while n != |v|\n\t{\n left_sum_Lemma(v, n+1);\n x, n := x + v[n], n + 1;\n }\n}\n\n// Structural Induction on Sequences\nlemma left_sum_Lemma(r:seq, k:int)\nrequires 0 <= k < |r|\nensures sum(r[..k]) + r[k] == sum(r[..k+1]);\n{\n if |r|==1 || k==0{\n }\n else {\n left_sum_Lemma(r[1..], k);\n\n calc {\n sum(r[..k+1]);\n sum(r[..k]) + [r[k]];\n }\n }\n}\n\n// MAXIMUM OF A SEQUENCE\nmethod maxSeq(v: seq) returns (max:int)\nrequires |v| >= 1\nensures forall i :: 0 <= i < |v| ==> max >= v[i]\nensures max in v\n{\n max := v[0];\n var v' := v[1..];\n ghost var t := [v[0]];\n while |v'| >= 1\n\t{\n if v'[0] > max { max := v'[0]; }\n v', t := v'[1..], t + [v'[0]];\n\t}\n}\n\n// TODO: Hacer\n// Derivar formalmente un calculo incremental de j*j*j\nmethod Cubes (n:int) returns (s:seq)\nrequires n >= 0\nensures |s| == n\nensures forall i:int :: 0 <= i < n ==> s[i] == i*i*i\n{\ns := [];\nvar c, j, k, m := 0,0,1,6;\nwhile j < n\n\t{\n\ts := s+[c]; \n\t//c := (j+1)*(j+1)*(j+1);\n\tc := c + k;\n\tk := k + 6*j + 6;\n\tm := m + 6;\n\t//assert m == 6*(j+1) + 6 == 6*j + 6 + 6;\n == 3*j*j + 9*j + 7\n == 3*j*j + 3*j + 1 + (6*j + 6);\n\t//assert c == (j+1)*(j+1)*(j+1) == j*j*j + 3*j*j + 3*j + 1;\n\tj := j+1;\n\t//assert m == 6*j + 6;\n\t//assert k == 3*j*j + 3*j + 1;\n\t//assert c == j*j*j;\n\t}\n}\n\n\n// REVERSE OF A SEQUENCE\nfunction reverse (s:seq):seq \n{\n if s==[] then []\n else reverse(s[1..])+[s[0]]\n}\n\nfunction seq2set (s:seq): set\n{\n if s==[] then {}\n else {s[0]}+seq2set(s[1..])\n}\n\n\nlemma seq2setRev_Lemma (s:seq)\nensures seq2set(reverse(s)) == seq2set(s)\n{\n if s==[]{}\n else {\n seq2setRev_Lemma(s[1..]);\n\n calc {\n seq2set(s);\n seq2set([s[0]]+s[1..]);\n {\n concat_seq2set_Lemma([s[0]], s[1..]);\n }\n seq2set([s[0]]) + seq2set(s[1..]);\n {\n seq2setRev_Lemma(s[1..]);\n }\n seq2set([s[0]]) + seq2set(reverse(s[1..]));\n seq2set(reverse(s[1..])) + seq2set([s[0]]); \n {\n concat_seq2set_Lemma(reverse(s[1..]), [s[0]]);\n }\n seq2set(reverse(s[1..]) + [s[0]]);\n {\n }\n seq2set(reverse(s));\n }\n }\n}\n\n\nlemma concat_seq2set_Lemma(s1:seq,s2:seq)\nensures seq2set(s1+s2) == seq2set(s1) + seq2set(s2)\n{\n if s1==[]{\n }\n else {\n concat_seq2set_Lemma(s1[1..], s2);\n\n calc{\n seq2set(s1) + seq2set(s2);\n seq2set([s1[0]]+s1[1..]) + seq2set(s2);\n seq2set([s1[0]]) + seq2set(s1[1..]) + seq2set(s2);\n {\n concat_seq2set_Lemma(s1[1..], s2);\n }\n seq2set([s1[0]]) + seq2set(s1[1..]+s2);\n {\n }\n seq2set([s1[0]]) + seq2set((s1+s2)[1..]);\n {\n // assert seq2set([s1[0]]) + seq2set((s1+s2)[1..]) == seq2set(s1+s2);\n var ls:= s1+s2;\n calc {\n seq2set([s1[0]]) + seq2set((s1+s2)[1..]);\n seq2set([ls[0]])+ seq2set(ls[1..]);\n seq2set([ls[0]]+ ls[1..]);\n seq2set(ls);\n seq2set(s1+s2);\n }\n }\n seq2set(s1+s2);\n }\n }\n}\n\n\n// REVERSE IS ITS OWN INVERSE\n\nlemma Rev_Lemma(s:seq)\n//ensures forall i :: 0 <= i < |s| ==> s[i] == reverse(s)[|s|-1-i]\n\nlemma ItsOwnInverse_Lemma (s:seq)\nensures s == reverse(reverse(s))\n{\n if s==[]{}\n else{\n ItsOwnInverse_Lemma(s[1..]);\n\n calc {\n reverse(reverse(s));\n reverse(reverse(s[1..])+[s[0]]);\n reverse(reverse([s[0]]+s[1..]));\n {\n }\n reverse(reverse(s[1..]) + [s[0]]);\n {\n // TODO: Demostrar este assume\n assume reverse(reverse(s[1..]) + [s[0]]) == [s[0]] + reverse(reverse(s[1..]));\n }\n [s[0]] + reverse(reverse(s[1..]));\n {\n ItsOwnInverse_Lemma(s[1..]);\n }\n [s[0]]+s[1..];\n s;\n }\n }\n}\n\n// SCALAR PRODUCT OF TWO VECTORS OF INTEGER\nfunction scalar_product (v1:seq, v2:seq):int\nrequires |v1| == |v2|\n{\n if v1 == [] then 0 else v1[0]*v2[0] + scalar_product(v1[1..],v2[1..])\n}\n\n\nlemma scalar_product_Lemma (v1:seq, v2:seq)\nrequires |v1| == |v2| > 0\nensures scalar_product(v1,v2) == scalar_product(v1[..|v1|-1],v2[..|v2|-1]) + v1[|v1|-1] * v2[|v2|-1]\n{\n // INDUCCION EN LA LONGITUD DE V1\n if |v1| == 0 && |v2| == 0 {}\n else if |v1| == 1 {}\n else {\n // Se crean estas variables para simplificar las operaciones\n var v1r:= v1[1..];\n var v2r:= v2[1..];\n var t1:= |v1[1..]|-1;\n var t2:= |v2[1..]|-1;\n\n // Se realiza la induccion utilizando las variables\n scalar_product_Lemma(v1r, v2r);\n scalar_product(v1r[..t1],v2r[..t2]) + v1r[t1] * v2r[t2]; //HI\n \n // Se demuestra que la propiedad se mantiene\n calc{\n scalar_product(v1,v2);\n v1[0]*v2[0] + scalar_product(v1r, v2r);\n v1[0]*v2[0] + scalar_product(v1r[..t1],v2r[..t2]) + v1r[t1] * v2r[t2];\n {\n scalar_product_Lemma(v1r, v2r);\n scalar_product(v1r[..t1],v2r[..t2]) + v1r[t1] * v2r[t2]; //HI\n }\n v1[0]*v2[0] + scalar_product(v1r,v2r);\n v1[0]*v2[0] + scalar_product(v1[1..],v2[1..]);\n scalar_product(v1,v2);\n }\n }\n}\n\n// MULTISETS\n\nmethod multiplicity_examples ()\n{\nvar m := multiset{2,4,6,2,1,3,1,7,1,5,4,7,8,1,6};\n\n}\n\n// REVERSE HAS THE SAME MULTISET \n\nlemma seqMultiset_Lemma (s:seq)\nensures multiset(reverse(s)) == multiset(s)\n{\n if s==[]{}\n else {\n seqMultiset_Lemma(s[1..]);\n\n calc {\n multiset(reverse(s));\n multiset(reverse(s[1..]) + [s[0]]);\n multiset(reverse(s[1..])) + multiset{[s[0]]};\n multiset(s[1..]) + multiset{[s[0]]};\n multiset(s);\n }\n }\n}\n*/\nlemma empty_Lemma (r:seq)\nrequires multiset(r) == multiset{} \nensures r == []\n{\n\tif r != []\t{\n\t}\n}\n\nlemma elem_Lemma (s:seq,r:seq)\nrequires s != [] && multiset(s) == multiset(r)\nensures exists i :: 0 <= i < |r| && r[i] == s[0] && multiset(s[1..]) == multiset(r[..i]+r[i+1..]);\n\n// SEQUENCES WITH EQUAL MULTISETS HAVE EQUAL SUMS\n\nlemma sumElems_Lemma(s:seq, r:seq) \nrequires multiset(s) == multiset(r)\nensures sum(s) == sum(r)\n{\n if s==[]{\n empty_Lemma(r);\n }\n else {\n // Con este lema demuestro que el elemento que le quito a s tambien se lo quito a r y de esta manera\n // poder hacer la induccion\n elem_Lemma(s,r);\n\t\tvar i :| 0 <= i < |r| && r[i] == s[0] && multiset(s[1..]) == multiset(r[..i]+r[i+1..]);\n\t\tsumElems_Lemma(s[1..], r[..i]+r[i+1..]);\n \n // Hago la llamada recursiva\n sumElems_Lemma(s[1..], r[..i]+r[i+1..]);\n\n calc {\n sum(s);\n s[0]+sum(s[1..]);\n {\n sumElems_Lemma(s[1..], r[..i]+r[i+1..]);\n }\n s[0]+sum(r[..i]+r[i+1..]);\n {\n }\n r[i]+sum(r[..i]+r[i+1..]);\n {\n // TODO: No consigo acertarlo\n assume r[i]+sum(r[..i]+r[i+1..]) == sum([r[i]]+r[..i] + r[i+1..]) == sum(r);\n }\n sum(r);\n }\n }\n}\n" }, { "test_ID": "229", "test_file": "Formal-methods-of-software-development_tmp_tmppryvbyty_Examenes_Beni_Heusel-Benedikt-Ass-1.dfy", "ground_truth": "// APELLIDOS: Heusel\n// NOMBRE: Benedikt\n// ESPECIALIDAD: ninguna (Erasmus)\n\n// EST\u00c1 PERFECTO, NO HAY NINGUN COMENTARIO MAS ABAJO\n\n// EJERCICIO 1 \n// Demostrar el lemma div10_Lemma por inducci\u00f3n en n \n// y luego usarlo para demostrar el lemma div10Forall_Lemma\n\nfunction exp (x:int,e:nat):int\n{\nif e == 0 then 1 else x * exp(x,e-1) \n}\n\nlemma div10_Lemma (n:nat)\nrequires n >= 3;\nensures (exp(3,4*n)+9)%10 == 0\n{\n if n == 3 { //paso base\n calc { //s\u00f3lo para m\u00ed, comprobado automaticamente\n (exp(3,4*n)+9);\n (exp(3,4*3)+9);\n exp(3, 12) + 9;\n 531441 + 9;\n 531450;\n 10 * 53145;\n }\n } else { //paso inductivo\n div10_Lemma(n-1);\n //assert (exp(3,4*(n-1))+9)%10 == 0; // HI\n var k := (exp(3,4*(n-1))+9) / 10;\n assert 10 * k == (exp(3,4*(n-1))+9);\n calc {\n exp(3, 4*n) + 9;\n 3 * 3 * exp(3,4*n - 2) + 9;\n 3 * 3 * 3 * 3 * exp(3,4*n - 4) + 9;\n 81 * exp(3,4*n - 4) + 9;\n 81 * exp(3,4 * (n-1)) + 9;\n 80 * exp(3,4 * (n-1)) + (exp(3,4 * (n-1)) + 9);\n 80 * exp(3,4 * (n-1)) + 10*k;\n 10 * (8 * exp(3,4 * (n-1)) + k);\n }\n }\n}\n//Por inducci\u00f3n en n\n\nlemma div10Forall_Lemma ()\nensures forall n :: n>=3 ==> (exp(3,4*n)+9)%10==0\n{\n forall n | n>=3 {div10_Lemma(n);}\n}\n//Llamando al lemma anterior\n\n// EJERCICIO 2\n// Demostrar por inducci\u00f3n en n el lemma de abajo acerca de la funci\u00f3n sumSerie que se define primero.\n// Recuerda que debes JUSTIFICAR como se obtiene la propiedad del ensures a partir de la hip\u00f3tesis de inducci\u00f3n.\n\nfunction sumSerie (x:int,n:nat):int\n{\nif n == 0 then 1 else sumSerie(x,n-1) + exp(x,n)\n}\n\nlemma {:induction false} sumSerie_Lemma (x:int,n:nat)\nensures (1-x) * sumSerie(x,n) == 1 - exp(x,n+1)\n{\n if n == 0 { //paso base\n calc { \n (1-x) * sumSerie(x,n);\n (1-x) * sumSerie(x,0);\n (1-x) * 1;\n 1 - x;\n 1 - exp(x,1);\n 1 - exp(x,n+1);\n }\n } else{ //paso inductivo\n calc {\n (1-x) * sumSerie(x,n);\n (1-x) * (sumSerie(x,n-1) + exp(x,n));\n (1-x) * sumSerie(x,n-1) + (1-x) * exp(x,n);\n {\n sumSerie_Lemma(x, n-1);\n //assert (1-x) * sumSerie(x,n-1) == 1 - exp(x,n); // HI\n }\n 1 - exp(x,n) + (1-x) * exp(x,n);\n 1 - exp(x,n) + exp(x,n) - x * exp(x,n);\n 1 - x * exp(x,n);\n 1 - exp(x,n + 1);\n }\n }\n}\n\n\n// EJERCICIO 3 \n// Probar el lemma noSq_Lemma por contradicci\u00f3n + casos (ver el esquema de abajo).\n// Se niega la propiedad en el ensures y luego se hacen dos casos (1) z%2 == 0 y (2) z%2 == 1.\n// En cada uno de los dos casos hay que llegar a probar \"assert false\"\n\nlemma notSq_Lemma (n:int)\nensures !exists z :: z*z == 4*n + 2\n{ //Por contradicci\u00f3n con dos casos:\nif exists z :: \t4*n + 2 == z*z \n {\n var z :| z*z == 4*n + 2 == z*z;\n if z%2 == 0 {\n //llegar aqu\u00ed a una contradicci\u00f3n y cambiar el \"assume false\" por \"assert false\"\n var k := z/2;\n assert z == 2*k;\n calc ==> {\n 4*n + 2 == z*z;\n 4*n + 2 == (2*k)*(2*k);\n 2 * (2*n+1) == 2 * (2*k*k);\n 2*n+1 == 2*k*k;\n 2*n+1 == 2*(k*k);\n }\n assert 0 == 2*(k*k) % 2 == (2*n+1) % 2 == 1;\n assert false;\n }\n else {\n\t //llegar aqu\u00ed a una contradicci\u00f3n y cambiar el \"assume false\" por \"assert false\"\n //assert z % 2 == 1;\n var k := (z-1) / 2;\n assert z == 2*k + 1;\n calc ==> {\n 4*n + 2 == z*z;\n 4*n + 2 == (2*k + 1)*(2*k + 1);\n 4*n + 2 == 4*k*k + 4*k + 1;\n 4*n + 2 == 2 * (2*k*k + 2*k) + 1;\n 2 * (2*n + 1) == 2 * (2*k*k + 2*k) + 1;\n }\n assert 0 == (2 * (2*n + 1)) % 2 == (2 * (2*k*k + 2*k) + 1) % 2 == 1;\n assert false;\n } \n }\n}\n\n\n\n// EJERCICIO 4\n//Probar el lemma oneIsEven_Lemma por contradicci\u00f3n, usando tambi\u00e9n el lemma del EJERCICIO 3.\n\nlemma oneIsEven_Lemma (x:int,y:int,z:int)\nrequires z*z == x*x + y*y \nensures x%2 == 0 || y%2 == 0\n{\n if !(x%2 == 0 || y%2 == 0) {\n //assert x%2 == 1 && y%2 == 1;\n assert x == 2 * ((x-1)/2) + 1;\n var k: int :| 2*k + 1 == x;\n \n assert y == 2 * ((y-1)/2) + 1;\n var b: int :| 2*b + 1 == y;\n\n calc {\n x*x + y*y;\n (2*k + 1) * (2*k + 1) + (2*b + 1) * (2*b + 1);\n 4*k*k + 4*k + 1 + (2*b + 1) * (2*b + 1);\n 4*k*k + 4*k + 1 + 4*b*b + 4*b + 1;\n 4*k*k + 4*k + 4*b*b + 4*b + 2;\n 4 * (k*k + k + b*b + b) + 2;\n }\n assert z * z == 4 * (k*k + k + b*b + b) + 2;\n notSq_Lemma(k*k + k + b*b + b);\n //assert !exists z :: z*z == 4*(k*k + k + b*b + b) + 2;\n assert false;\n }\n}\n// Por contradicci\u00f3n, y usando notSq_Lemma.\n\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n/* ESTE EJERCICIO S\u00d3LO DEBES HACERLO SI HAS CONSEGUIDO DEMOSTRAR CON EXITO LOS EJERCICIOS 1 y 2\n\nEJERCICIO 5 \nEn este ejercicio se dan dos lemma: exp_Lemma y prod_Lemma, que Dafny demuestra autom\u00e1ticamente.\nLo que se pide es probar expPlus1_Lemma, por inducci\u00f3n en n, haciendo una calculation con == y >=,\nque en las pistas (hints) use la HI y tambi\u00e9n llamadas a esos dos lemas.\n*/\nlemma exp_Lemma(x:int, e:nat)\t\t\t\nrequires x >= 1 \nensures exp(x,e) >= 1\n{} //NO DEMOSTRAR, USAR PARA PROBAR EL DE ABAJO\n\nlemma prod_Lemma(z:int, a:int, b:int)\nrequires z >= 1 && a >= b >= 1\nensures z*a >= z*b\n{} //NO DEMOSTRAR, USAR PARA PROBAR EL DE ABAJO\n\nlemma expPlus1_Lemma(x:int,n:nat)\n\trequires x >= 1 && n >= 1\n\tensures exp(x+1,n) >= exp(x,n) + 1 \n {\n if n == 1 {\n calc {\n exp(x+1,n);\n ==\n exp(x+1,1);\n ==\n x + 1;\n >= //efectivamente en el caso base tenemos igualdad\n x + 1;\n ==\n exp(x,1) + 1;\n ==\n exp(x,n) + 1;\n }\n } else {\n calc {\n exp(x+1,n);\n ==\n (x + 1) * exp(x+1,n-1);\n >= {\n expPlus1_Lemma(x, n-1);\n //assert exp(x+1,n-1) >= exp(x,n-1) + 1; HI\n\n //assert exp(x+1,n-1) >= exp(x,n-1) + 1; // HI\n //aqu\u00ed se necesitar\u00eda tambien prod_lemma,\n //pero parece que el paso se demuestra tambien\n //sin la llamada\n }\n (x + 1) * (exp(x,n-1) + 1);\n ==\n x * exp(x,n-1) + x + exp(x,n-1) + 1;\n ==\n exp(x,n) + x + exp(x,n-1) + 1;\n == \n exp(x,n) + 1 + exp(x,n-1) + x;\n >= {\n exp_Lemma(x, n-1);\n }\n exp(x,n) + 1;\n }\n }\n }\n// Por inducci\u00f3n en n, y usando exp_Lemma y prod_Lemma.\n", "hints_removed": "// APELLIDOS: Heusel\n// NOMBRE: Benedikt\n// ESPECIALIDAD: ninguna (Erasmus)\n\n// EST\u00c1 PERFECTO, NO HAY NINGUN COMENTARIO MAS ABAJO\n\n// EJERCICIO 1 \n// Demostrar el lemma div10_Lemma por inducci\u00f3n en n \n// y luego usarlo para demostrar el lemma div10Forall_Lemma\n\nfunction exp (x:int,e:nat):int\n{\nif e == 0 then 1 else x * exp(x,e-1) \n}\n\nlemma div10_Lemma (n:nat)\nrequires n >= 3;\nensures (exp(3,4*n)+9)%10 == 0\n{\n if n == 3 { //paso base\n calc { //s\u00f3lo para m\u00ed, comprobado automaticamente\n (exp(3,4*n)+9);\n (exp(3,4*3)+9);\n exp(3, 12) + 9;\n 531441 + 9;\n 531450;\n 10 * 53145;\n }\n } else { //paso inductivo\n div10_Lemma(n-1);\n //assert (exp(3,4*(n-1))+9)%10 == 0; // HI\n var k := (exp(3,4*(n-1))+9) / 10;\n calc {\n exp(3, 4*n) + 9;\n 3 * 3 * exp(3,4*n - 2) + 9;\n 3 * 3 * 3 * 3 * exp(3,4*n - 4) + 9;\n 81 * exp(3,4*n - 4) + 9;\n 81 * exp(3,4 * (n-1)) + 9;\n 80 * exp(3,4 * (n-1)) + (exp(3,4 * (n-1)) + 9);\n 80 * exp(3,4 * (n-1)) + 10*k;\n 10 * (8 * exp(3,4 * (n-1)) + k);\n }\n }\n}\n//Por inducci\u00f3n en n\n\nlemma div10Forall_Lemma ()\nensures forall n :: n>=3 ==> (exp(3,4*n)+9)%10==0\n{\n forall n | n>=3 {div10_Lemma(n);}\n}\n//Llamando al lemma anterior\n\n// EJERCICIO 2\n// Demostrar por inducci\u00f3n en n el lemma de abajo acerca de la funci\u00f3n sumSerie que se define primero.\n// Recuerda que debes JUSTIFICAR como se obtiene la propiedad del ensures a partir de la hip\u00f3tesis de inducci\u00f3n.\n\nfunction sumSerie (x:int,n:nat):int\n{\nif n == 0 then 1 else sumSerie(x,n-1) + exp(x,n)\n}\n\nlemma {:induction false} sumSerie_Lemma (x:int,n:nat)\nensures (1-x) * sumSerie(x,n) == 1 - exp(x,n+1)\n{\n if n == 0 { //paso base\n calc { \n (1-x) * sumSerie(x,n);\n (1-x) * sumSerie(x,0);\n (1-x) * 1;\n 1 - x;\n 1 - exp(x,1);\n 1 - exp(x,n+1);\n }\n } else{ //paso inductivo\n calc {\n (1-x) * sumSerie(x,n);\n (1-x) * (sumSerie(x,n-1) + exp(x,n));\n (1-x) * sumSerie(x,n-1) + (1-x) * exp(x,n);\n {\n sumSerie_Lemma(x, n-1);\n //assert (1-x) * sumSerie(x,n-1) == 1 - exp(x,n); // HI\n }\n 1 - exp(x,n) + (1-x) * exp(x,n);\n 1 - exp(x,n) + exp(x,n) - x * exp(x,n);\n 1 - x * exp(x,n);\n 1 - exp(x,n + 1);\n }\n }\n}\n\n\n// EJERCICIO 3 \n// Probar el lemma noSq_Lemma por contradicci\u00f3n + casos (ver el esquema de abajo).\n// Se niega la propiedad en el ensures y luego se hacen dos casos (1) z%2 == 0 y (2) z%2 == 1.\n// En cada uno de los dos casos hay que llegar a probar \"assert false\"\n\nlemma notSq_Lemma (n:int)\nensures !exists z :: z*z == 4*n + 2\n{ //Por contradicci\u00f3n con dos casos:\nif exists z :: \t4*n + 2 == z*z \n {\n var z :| z*z == 4*n + 2 == z*z;\n if z%2 == 0 {\n //llegar aqu\u00ed a una contradicci\u00f3n y cambiar el \"assume false\" por \"assert false\"\n var k := z/2;\n calc ==> {\n 4*n + 2 == z*z;\n 4*n + 2 == (2*k)*(2*k);\n 2 * (2*n+1) == 2 * (2*k*k);\n 2*n+1 == 2*k*k;\n 2*n+1 == 2*(k*k);\n }\n }\n else {\n\t //llegar aqu\u00ed a una contradicci\u00f3n y cambiar el \"assume false\" por \"assert false\"\n //assert z % 2 == 1;\n var k := (z-1) / 2;\n calc ==> {\n 4*n + 2 == z*z;\n 4*n + 2 == (2*k + 1)*(2*k + 1);\n 4*n + 2 == 4*k*k + 4*k + 1;\n 4*n + 2 == 2 * (2*k*k + 2*k) + 1;\n 2 * (2*n + 1) == 2 * (2*k*k + 2*k) + 1;\n }\n } \n }\n}\n\n\n\n// EJERCICIO 4\n//Probar el lemma oneIsEven_Lemma por contradicci\u00f3n, usando tambi\u00e9n el lemma del EJERCICIO 3.\n\nlemma oneIsEven_Lemma (x:int,y:int,z:int)\nrequires z*z == x*x + y*y \nensures x%2 == 0 || y%2 == 0\n{\n if !(x%2 == 0 || y%2 == 0) {\n //assert x%2 == 1 && y%2 == 1;\n var k: int :| 2*k + 1 == x;\n \n var b: int :| 2*b + 1 == y;\n\n calc {\n x*x + y*y;\n (2*k + 1) * (2*k + 1) + (2*b + 1) * (2*b + 1);\n 4*k*k + 4*k + 1 + (2*b + 1) * (2*b + 1);\n 4*k*k + 4*k + 1 + 4*b*b + 4*b + 1;\n 4*k*k + 4*k + 4*b*b + 4*b + 2;\n 4 * (k*k + k + b*b + b) + 2;\n }\n notSq_Lemma(k*k + k + b*b + b);\n //assert !exists z :: z*z == 4*(k*k + k + b*b + b) + 2;\n }\n}\n// Por contradicci\u00f3n, y usando notSq_Lemma.\n\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n/* ESTE EJERCICIO S\u00d3LO DEBES HACERLO SI HAS CONSEGUIDO DEMOSTRAR CON EXITO LOS EJERCICIOS 1 y 2\n\nEJERCICIO 5 \nEn este ejercicio se dan dos lemma: exp_Lemma y prod_Lemma, que Dafny demuestra autom\u00e1ticamente.\nLo que se pide es probar expPlus1_Lemma, por inducci\u00f3n en n, haciendo una calculation con == y >=,\nque en las pistas (hints) use la HI y tambi\u00e9n llamadas a esos dos lemas.\n*/\nlemma exp_Lemma(x:int, e:nat)\t\t\t\nrequires x >= 1 \nensures exp(x,e) >= 1\n{} //NO DEMOSTRAR, USAR PARA PROBAR EL DE ABAJO\n\nlemma prod_Lemma(z:int, a:int, b:int)\nrequires z >= 1 && a >= b >= 1\nensures z*a >= z*b\n{} //NO DEMOSTRAR, USAR PARA PROBAR EL DE ABAJO\n\nlemma expPlus1_Lemma(x:int,n:nat)\n\trequires x >= 1 && n >= 1\n\tensures exp(x+1,n) >= exp(x,n) + 1 \n {\n if n == 1 {\n calc {\n exp(x+1,n);\n ==\n exp(x+1,1);\n ==\n x + 1;\n >= //efectivamente en el caso base tenemos igualdad\n x + 1;\n ==\n exp(x,1) + 1;\n ==\n exp(x,n) + 1;\n }\n } else {\n calc {\n exp(x+1,n);\n ==\n (x + 1) * exp(x+1,n-1);\n >= {\n expPlus1_Lemma(x, n-1);\n //assert exp(x+1,n-1) >= exp(x,n-1) + 1; HI\n\n //assert exp(x+1,n-1) >= exp(x,n-1) + 1; // HI\n //aqu\u00ed se necesitar\u00eda tambien prod_lemma,\n //pero parece que el paso se demuestra tambien\n //sin la llamada\n }\n (x + 1) * (exp(x,n-1) + 1);\n ==\n x * exp(x,n-1) + x + exp(x,n-1) + 1;\n ==\n exp(x,n) + x + exp(x,n-1) + 1;\n == \n exp(x,n) + 1 + exp(x,n-1) + x;\n >= {\n exp_Lemma(x, n-1);\n }\n exp(x,n) + 1;\n }\n }\n }\n// Por inducci\u00f3n en n, y usando exp_Lemma y prod_Lemma.\n" }, { "test_ID": "230", "test_file": "FormalMethods_tmp_tmpvda2r3_o_dafny_Invariants_ex1.dfy", "ground_truth": "method Mult(x:nat, y:nat) returns (r:nat)\nensures r == x * y\n{\n // Valores passados por par\u00e2metros s\u00e3o imut\u00e1veis\n var m := x;\n var n := y;\n r := 0;\n // Soma sucessiva para multiplicar dois n\u00fameros.\n while m > 0\n invariant m*n+r == x*y\n invariant m>=0\n {\n r := r + n;\n m := m - 1;\n }\n return r; // NOT(m>0) ^ Inv ==> r = x*y\n}\n\n/*\nInv = m*n + r = x*y\nMult(5,3)\nTeste de mesa\nx y m n r Inv --> m*n + r = x*y\n5 3 5 3 0 5x3+0 = 5*3\n5 3 4 3 3 4x3+3 = 5*3\n5 3 3 3 6 3x3+6 = 5*3\n5 3 2 3 9 2x3+9 = 5*3\n5 3 1 3 12 1x3+12 = 5*3\n5 3 0 3 15 0x3+15 = 5*3\n*/\n\n", "hints_removed": "method Mult(x:nat, y:nat) returns (r:nat)\nensures r == x * y\n{\n // Valores passados por par\u00e2metros s\u00e3o imut\u00e1veis\n var m := x;\n var n := y;\n r := 0;\n // Soma sucessiva para multiplicar dois n\u00fameros.\n while m > 0\n {\n r := r + n;\n m := m - 1;\n }\n return r; // NOT(m>0) ^ Inv ==> r = x*y\n}\n\n/*\nInv = m*n + r = x*y\nMult(5,3)\nTeste de mesa\nx y m n r Inv --> m*n + r = x*y\n5 3 5 3 0 5x3+0 = 5*3\n5 3 4 3 3 4x3+3 = 5*3\n5 3 3 3 6 3x3+6 = 5*3\n5 3 2 3 9 2x3+9 = 5*3\n5 3 1 3 12 1x3+12 = 5*3\n5 3 0 3 15 0x3+15 = 5*3\n*/\n\n" }, { "test_ID": "231", "test_file": "FormalMethods_tmp_tmpvda2r3_o_dafny_Invariants_ex2.dfy", "ground_truth": "function Potencia(x:nat, y:nat):nat\n{\n if y == 0\n then 1\n else x * Potencia(x, y-1)\n}\n\nmethod Pot(x:nat, y:nat) returns (r:nat)\nensures r == Potencia(x,y)\n{\n r := 1;\n var b := x;\n var e := y;\n while e > 0\n invariant Potencia(b,e) * r == Potencia(x,y)\n {\n r := r * b;\n e := e - 1;\n }\n\n return r;\n}\n/*\nInv = \nPot(2,3)\nTeste de mesa\nx y b e r Inv --> b^e * r = x^y\n2 3 2 3 1 2^3 * 2^0 = 2^3\n2 3 2 2 1*2 2^2 * 2^1 = 2^3\n2 3 2 1 1*2*2 2^1 * 2^2 = 2^3\n2 3 2 0 1*2*2*2 2^0 * 2^3 = 2^3\n*/\n", "hints_removed": "function Potencia(x:nat, y:nat):nat\n{\n if y == 0\n then 1\n else x * Potencia(x, y-1)\n}\n\nmethod Pot(x:nat, y:nat) returns (r:nat)\nensures r == Potencia(x,y)\n{\n r := 1;\n var b := x;\n var e := y;\n while e > 0\n {\n r := r * b;\n e := e - 1;\n }\n\n return r;\n}\n/*\nInv = \nPot(2,3)\nTeste de mesa\nx y b e r Inv --> b^e * r = x^y\n2 3 2 3 1 2^3 * 2^0 = 2^3\n2 3 2 2 1*2 2^2 * 2^1 = 2^3\n2 3 2 1 1*2*2 2^1 * 2^2 = 2^3\n2 3 2 0 1*2*2*2 2^0 * 2^3 = 2^3\n*/\n" }, { "test_ID": "232", "test_file": "Formal_Verification_With_Dafny_tmp_tmp5j79rq48_Counter.dfy", "ground_truth": "class Counter {\n \n var value : int ;\n \n constructor init() \n ensures value == 0;\n {\n value := 0 ;\n }\n \n method getValue() returns (x:int)\n ensures x == value;\n {\n x := value ;\n }\n \n method inc()\n modifies this`value\n requires value >= 0;\n ensures value == old(value) + 1; \n {\n value := value + 1;\n }\n \n method dec()\n modifies this`value\n requires value > 0;\n ensures value == old(value) - 1; \n { \n value := value - 1 ;\n }\n \n method Main ()\n {\n var count := new Counter.init() ;\n count.inc();\n count.inc();\n count.dec();\n count.inc();\n var aux : int := count.getValue();\n assert (aux == 2) ;\n }\n}\n\n", "hints_removed": "class Counter {\n \n var value : int ;\n \n constructor init() \n ensures value == 0;\n {\n value := 0 ;\n }\n \n method getValue() returns (x:int)\n ensures x == value;\n {\n x := value ;\n }\n \n method inc()\n modifies this`value\n requires value >= 0;\n ensures value == old(value) + 1; \n {\n value := value + 1;\n }\n \n method dec()\n modifies this`value\n requires value > 0;\n ensures value == old(value) - 1; \n { \n value := value - 1 ;\n }\n \n method Main ()\n {\n var count := new Counter.init() ;\n count.inc();\n count.inc();\n count.dec();\n count.inc();\n var aux : int := count.getValue();\n }\n}\n\n" }, { "test_ID": "233", "test_file": "Formal_Verification_With_Dafny_tmp_tmp5j79rq48_LimitedStack.dfy", "ground_truth": "// A LIFO queue (aka a stack) with limited capacity.\nclass LimitedStack{\n \n var capacity : int; // capacity, max number of elements allowed on the stack.\n var arr : array; // contents of stack.\n var top : int; // The index of the top of the stack, or -1 if the stack is empty\n\n // This predicate express a class invariant: All objects of this calls should satisfy this.\n predicate Valid()\n reads this;\n {\n arr != null && capacity > 0 && capacity == arr.Length && top >= -1 && top < capacity \n }\n\n predicate Empty()\n reads this`top;\n {\n top == -1\n }\n\n predicate Full()\n reads this`top, this`capacity;\n {\n top == (capacity - 1)\n }\n \n method Init(c : int)\n modifies this;\n requires c > 0\n ensures Valid() && Empty() && c == capacity\n ensures fresh(arr); // ensures arr is a newly created object.\n // Additional post-condition to be given here!\n {\n capacity := c;\n arr := new int[c];\n top := -1;\n }\n\n\n \n method isEmpty() returns (res : bool)\n ensures res == Empty()\n {\n if(top == -1)\n { return true; }\n else {\n return false;\n }\n }\n\n\n\n // Returns the top element of the stack, without removing it.\n method Peek() returns (elem : int) \n requires Valid() && !Empty()\n ensures elem == arr[top]\n {\n return arr[top]; \n }\n\n\n\n // Pushed an element to the top of a (non full) stack. \n method Push(elem : int)\n modifies this`top, this.arr \n requires Valid()\n requires !Full() \n ensures Valid() && top == old(top) + 1 && arr[top] == elem\n ensures !old(Empty()) ==> forall i : int :: 0 <= i <= old(top) ==> arr[i] == old(arr[i]);\n {\n top := top + 1;\n arr[top] := elem;\n }\n\n // Pops the top element off the stack.\n\n method Pop() returns (elem : int)\n modifies this`top\n requires Valid() && !Empty() \n ensures Valid() && top == old(top) - 1 \n ensures elem == arr[old(top)] \n {\n elem := arr[top];\n top := top - 1;\n return elem;\n }\n\n \n method Shift()\n requires Valid() && !Empty();\n ensures Valid();\n ensures forall i : int :: 0 <= i < capacity - 1 ==> arr[i] == old(arr[i + 1]);\n ensures top == old(top) - 1;\n modifies this.arr, this`top;\n {\n var i : int := 0;\n while (i < capacity - 1 )\n invariant 0 <= i < capacity;\n invariant top == old(top);\n invariant forall j : int :: 0 <= j < i ==> arr[j] == old(arr[j + 1]);\n invariant forall j : int :: i <= j < capacity ==> arr[j] == old(arr[j]);\n {\n arr[i] := arr[i + 1];\n i := i + 1;\n }\n top := top - 1;\n }\n\n \n //Push onto full stack, oldest element is discarded.\n method Push2(elem : int)\n modifies this.arr, this`top\n requires Valid()\n ensures Valid() && !Empty() \n ensures arr[top] == elem\n ensures old(!Full()) ==> top == old(top) + 1 && old(Full()) ==> top == old(top)\n ensures ((old(Full()) ==> arr[capacity - 1] == elem) && (old(!Full()) ==> (top == old(top) + 1 && arr[top] == elem) ))\n ensures old(Full()) ==> forall i : int :: 0 <= i < capacity - 1 ==> arr[i] == old(arr[i + 1]);\n {\n if(top == capacity - 1){\n Shift();\n top := top + 1;\n arr[top] := elem;\n }\n else{\n top := top + 1;\n arr[top] := elem;\n }\n }\n \n\n \n\n// When you are finished, all the below assertions should be provable. \n// Feel free to add extra ones as well.\n method Main(){\n var s := new LimitedStack;\n s.Init(3);\n\n assert s.Empty() && !s.Full(); \n\n s.Push(27);\n assert !s.Empty();\n\n var e := s.Pop();\n assert e == 27;\n\n assert s.top == -1; \n assert s.Empty() && !s.Full(); \n \n s.Push(5);\n\n assert s.top == 0;\n assert s.capacity == 3;\n s.Push(32);\n s.Push(9);\n assert s.Full();\n\n assert s.arr[0] == 5;\n\n var e2 := s.Pop();\n \n assert e2 == 9 && !s.Full(); \n assert s.arr[0] == 5;\n\n s.Push(e2);\n s.Push2(99);\n\n var e3 := s.Peek();\n assert e3 == 99;\n assert s.arr[0] == 32;\n \n }\n\n}\n\n", "hints_removed": "// A LIFO queue (aka a stack) with limited capacity.\nclass LimitedStack{\n \n var capacity : int; // capacity, max number of elements allowed on the stack.\n var arr : array; // contents of stack.\n var top : int; // The index of the top of the stack, or -1 if the stack is empty\n\n // This predicate express a class invariant: All objects of this calls should satisfy this.\n predicate Valid()\n reads this;\n {\n arr != null && capacity > 0 && capacity == arr.Length && top >= -1 && top < capacity \n }\n\n predicate Empty()\n reads this`top;\n {\n top == -1\n }\n\n predicate Full()\n reads this`top, this`capacity;\n {\n top == (capacity - 1)\n }\n \n method Init(c : int)\n modifies this;\n requires c > 0\n ensures Valid() && Empty() && c == capacity\n ensures fresh(arr); // ensures arr is a newly created object.\n // Additional post-condition to be given here!\n {\n capacity := c;\n arr := new int[c];\n top := -1;\n }\n\n\n \n method isEmpty() returns (res : bool)\n ensures res == Empty()\n {\n if(top == -1)\n { return true; }\n else {\n return false;\n }\n }\n\n\n\n // Returns the top element of the stack, without removing it.\n method Peek() returns (elem : int) \n requires Valid() && !Empty()\n ensures elem == arr[top]\n {\n return arr[top]; \n }\n\n\n\n // Pushed an element to the top of a (non full) stack. \n method Push(elem : int)\n modifies this`top, this.arr \n requires Valid()\n requires !Full() \n ensures Valid() && top == old(top) + 1 && arr[top] == elem\n ensures !old(Empty()) ==> forall i : int :: 0 <= i <= old(top) ==> arr[i] == old(arr[i]);\n {\n top := top + 1;\n arr[top] := elem;\n }\n\n // Pops the top element off the stack.\n\n method Pop() returns (elem : int)\n modifies this`top\n requires Valid() && !Empty() \n ensures Valid() && top == old(top) - 1 \n ensures elem == arr[old(top)] \n {\n elem := arr[top];\n top := top - 1;\n return elem;\n }\n\n \n method Shift()\n requires Valid() && !Empty();\n ensures Valid();\n ensures forall i : int :: 0 <= i < capacity - 1 ==> arr[i] == old(arr[i + 1]);\n ensures top == old(top) - 1;\n modifies this.arr, this`top;\n {\n var i : int := 0;\n while (i < capacity - 1 )\n {\n arr[i] := arr[i + 1];\n i := i + 1;\n }\n top := top - 1;\n }\n\n \n //Push onto full stack, oldest element is discarded.\n method Push2(elem : int)\n modifies this.arr, this`top\n requires Valid()\n ensures Valid() && !Empty() \n ensures arr[top] == elem\n ensures old(!Full()) ==> top == old(top) + 1 && old(Full()) ==> top == old(top)\n ensures ((old(Full()) ==> arr[capacity - 1] == elem) && (old(!Full()) ==> (top == old(top) + 1 && arr[top] == elem) ))\n ensures old(Full()) ==> forall i : int :: 0 <= i < capacity - 1 ==> arr[i] == old(arr[i + 1]);\n {\n if(top == capacity - 1){\n Shift();\n top := top + 1;\n arr[top] := elem;\n }\n else{\n top := top + 1;\n arr[top] := elem;\n }\n }\n \n\n \n\n// When you are finished, all the below assertions should be provable. \n// Feel free to add extra ones as well.\n method Main(){\n var s := new LimitedStack;\n s.Init(3);\n\n\n s.Push(27);\n\n var e := s.Pop();\n\n \n s.Push(5);\n\n s.Push(32);\n s.Push(9);\n\n\n var e2 := s.Pop();\n \n\n s.Push(e2);\n s.Push2(99);\n\n var e3 := s.Peek();\n \n }\n\n}\n\n" }, { "test_ID": "234", "test_file": "HATRA-2022-Paper_tmp_tmp5texxy8l_copilot_verification_Binary Search_binary_search.dfy", "ground_truth": "// Dafny verification of binary search alogirthm from binary_search.py\n// Inspired by: https://ece.uwaterloo.ca/~agurfink/stqam/rise4fun-Dafny/#h211\n\nmethod BinarySearch(arr: array, target: int) returns (index: int)\n requires distinct(arr)\n requires sorted(arr)\n ensures -1 <= index < arr.Length\n ensures index == -1 ==> not_found(arr, target)\n ensures index != -1 ==> found(arr, target, index)\n{\n var low, high := 0 , arr.Length-1;\n while low <= high\n invariant 0 <= low <= high + 1\n invariant low-1 <= high < arr.Length\n invariant forall i :: 0 <= i <= low && high <= i < arr.Length ==> arr[i] != target\n { \n var mid := (low + high) / 2;\n if arr[mid] == target\n {\n return mid;\n }\n else if arr[mid] < target\n {\n low := mid + 1;\n }\n else\n {\n high := mid - 1;\n }\n }\n\n return -1;\n}\n\n// Predicate to check that the array is sorted\npredicate sorted(a: array)\nreads a\n{\n forall j, k :: 0 <= j < k < a.Length ==> a[j] <= a[k] \n}\n\n// Predicate to that each element is unique\npredicate distinct(arr: array)\n reads arr\n{\n forall i, j :: 0 <= i < arr.Length && 0 <= j < arr.Length ==> arr[i] != arr[j]\n}\n\n// Predicate to that the target is not in the array\npredicate not_found(arr: array, target: int)\nreads arr\n{\n (forall j :: 0 <= j < arr.Length ==> arr[j] != target)\n}\n\n// Predicate to that the target is in the array\npredicate found(arr: array, target: int, index: int)\nrequires -1 <= index < arr.Length;\nreads arr\n{\n if index == -1 then false\n else if arr[index] == target then true\n else false\n}\n\n\n\n", "hints_removed": "// Dafny verification of binary search alogirthm from binary_search.py\n// Inspired by: https://ece.uwaterloo.ca/~agurfink/stqam/rise4fun-Dafny/#h211\n\nmethod BinarySearch(arr: array, target: int) returns (index: int)\n requires distinct(arr)\n requires sorted(arr)\n ensures -1 <= index < arr.Length\n ensures index == -1 ==> not_found(arr, target)\n ensures index != -1 ==> found(arr, target, index)\n{\n var low, high := 0 , arr.Length-1;\n while low <= high\n { \n var mid := (low + high) / 2;\n if arr[mid] == target\n {\n return mid;\n }\n else if arr[mid] < target\n {\n low := mid + 1;\n }\n else\n {\n high := mid - 1;\n }\n }\n\n return -1;\n}\n\n// Predicate to check that the array is sorted\npredicate sorted(a: array)\nreads a\n{\n forall j, k :: 0 <= j < k < a.Length ==> a[j] <= a[k] \n}\n\n// Predicate to that each element is unique\npredicate distinct(arr: array)\n reads arr\n{\n forall i, j :: 0 <= i < arr.Length && 0 <= j < arr.Length ==> arr[i] != arr[j]\n}\n\n// Predicate to that the target is not in the array\npredicate not_found(arr: array, target: int)\nreads arr\n{\n (forall j :: 0 <= j < arr.Length ==> arr[j] != target)\n}\n\n// Predicate to that the target is in the array\npredicate found(arr: array, target: int, index: int)\nrequires -1 <= index < arr.Length;\nreads arr\n{\n if index == -1 then false\n else if arr[index] == target then true\n else false\n}\n\n\n\n" }, { "test_ID": "235", "test_file": "HATRA-2022-Paper_tmp_tmp5texxy8l_copilot_verification_Largest Sum_largest_sum.dfy", "ground_truth": "// CoPilot function converted to dafny\nmethod largest_sum(nums: array, k: int) returns (sum: int)\n requires nums.Length > 0 \n ensures max_sum_subarray(nums, sum, 0, nums.Length)\n{\n var max_sum := 0;\n var current_sum := 0;\n \n var i := 0;\n while (i < nums.Length)\n invariant 0 <= i <= nums.Length\n invariant max_sum_subarray(nums, max_sum, 0, i) // Invariant for the max_sum \n invariant forall j :: 0 <= j < i ==> Sum_Array(nums, j, i) <= current_sum // Invariant for the current_sum\n {\n current_sum := current_sum + nums[i];\n if (current_sum > max_sum)\n {\n max_sum := current_sum;\n }\n if (current_sum < 0)\n {\n current_sum := 0;\n }\n i := i + 1;\n }\n return max_sum;\n}\n\n// Predicate to confirm that sum is the maximum summation of element [start, stop) \npredicate max_sum_subarray(arr: array, sum: int, start: int, stop: int)\n requires arr.Length > 0\n requires 0 <= start <= stop <= arr.Length\n reads arr\n{\n forall u, v :: start <= u < v <= stop ==> Sum_Array(arr, u, v) <= sum\n}\n\n\n//Sums array elements between [start, stop)\nfunction Sum_Array(arr: array, start: int, stop: int): int\n requires 0 <= start <= stop <= arr.Length\n decreases stop - start\n reads arr\n{\n if start >= stop then 0\n else arr[stop-1] + Sum_Array(arr, start, stop-1)\n}\n\n\n\n\n", "hints_removed": "// CoPilot function converted to dafny\nmethod largest_sum(nums: array, k: int) returns (sum: int)\n requires nums.Length > 0 \n ensures max_sum_subarray(nums, sum, 0, nums.Length)\n{\n var max_sum := 0;\n var current_sum := 0;\n \n var i := 0;\n while (i < nums.Length)\n {\n current_sum := current_sum + nums[i];\n if (current_sum > max_sum)\n {\n max_sum := current_sum;\n }\n if (current_sum < 0)\n {\n current_sum := 0;\n }\n i := i + 1;\n }\n return max_sum;\n}\n\n// Predicate to confirm that sum is the maximum summation of element [start, stop) \npredicate max_sum_subarray(arr: array, sum: int, start: int, stop: int)\n requires arr.Length > 0\n requires 0 <= start <= stop <= arr.Length\n reads arr\n{\n forall u, v :: start <= u < v <= stop ==> Sum_Array(arr, u, v) <= sum\n}\n\n\n//Sums array elements between [start, stop)\nfunction Sum_Array(arr: array, start: int, stop: int): int\n requires 0 <= start <= stop <= arr.Length\n reads arr\n{\n if start >= stop then 0\n else arr[stop-1] + Sum_Array(arr, start, stop-1)\n}\n\n\n\n\n" }, { "test_ID": "236", "test_file": "HATRA-2022-Paper_tmp_tmp5texxy8l_copilot_verification_Sort Array_sort_array.dfy", "ground_truth": "method sortArray(arr: array) returns (arr_sorted: array)\n // Requires array length to be between 0 and 10000\n requires 0 <= arr.Length < 10000\n // Ensuring the arry has been sorted\n ensures sorted(arr_sorted, 0, arr_sorted.Length)\n // Ensuring that we have not modified elements but have only changed their indices\n ensures multiset(arr[..]) == multiset(arr_sorted[..])\n\n // Modifies arr\n modifies arr\n{\n var i := 0;\n while i < arr.Length\n invariant i <= arr.Length\n invariant sorted(arr, 0, i)\n invariant multiset(old(arr[..])) == multiset(arr[..])\n invariant forall u, v :: 0 <= u < i && i <= v < arr.Length ==> arr[u] <= arr[v]\n invariant pivot(arr, i)\n {\n var j := i;\n while j < arr.Length\n invariant j <= arr.Length\n invariant multiset(old(arr[..])) == multiset(arr[..])\n invariant pivot(arr, i)\n invariant forall u :: i < u < j ==> arr[i] <= arr[u]\n invariant forall u :: 0 <= u < i ==> arr[u] <= arr[i]\n invariant sorted(arr, 0, i+1)\n {\n if arr[i] > arr[j]\n {\n var temp := arr[i];\n arr[i] := arr[j];\n arr[j] := temp;\n }\n j := j + 1;\n }\n i := i + 1;\n }\n return arr;\n} \n\n// Predicate to determine whether the list is sorted between [start, stop)\npredicate sorted(arr: array, start: int, end: int)\nrequires 0 <= start <= end <= arr.Length\nreads arr\n{\n forall i, j :: start <= i <= j < end ==> arr[i] <= arr[j]\n}\n\n// Predicate to determine whether element arr[pivot] is a pivot point\n// Based on: https://github.com/stqam/dafny/blob/master/BubbleSort.dfy\npredicate pivot(arr: array, pivot: int)\nrequires 0 <= pivot <= arr.Length\nreads arr\n{\n forall u, v :: 0 <= u < pivot < v < arr.Length ==> arr[u] <= arr[v]\n}\n\n", "hints_removed": "method sortArray(arr: array) returns (arr_sorted: array)\n // Requires array length to be between 0 and 10000\n requires 0 <= arr.Length < 10000\n // Ensuring the arry has been sorted\n ensures sorted(arr_sorted, 0, arr_sorted.Length)\n // Ensuring that we have not modified elements but have only changed their indices\n ensures multiset(arr[..]) == multiset(arr_sorted[..])\n\n // Modifies arr\n modifies arr\n{\n var i := 0;\n while i < arr.Length\n {\n var j := i;\n while j < arr.Length\n {\n if arr[i] > arr[j]\n {\n var temp := arr[i];\n arr[i] := arr[j];\n arr[j] := temp;\n }\n j := j + 1;\n }\n i := i + 1;\n }\n return arr;\n} \n\n// Predicate to determine whether the list is sorted between [start, stop)\npredicate sorted(arr: array, start: int, end: int)\nrequires 0 <= start <= end <= arr.Length\nreads arr\n{\n forall i, j :: start <= i <= j < end ==> arr[i] <= arr[j]\n}\n\n// Predicate to determine whether element arr[pivot] is a pivot point\n// Based on: https://github.com/stqam/dafny/blob/master/BubbleSort.dfy\npredicate pivot(arr: array, pivot: int)\nrequires 0 <= pivot <= arr.Length\nreads arr\n{\n forall u, v :: 0 <= u < pivot < v < arr.Length ==> arr[u] <= arr[v]\n}\n\n" }, { "test_ID": "237", "test_file": "HATRA-2022-Paper_tmp_tmp5texxy8l_copilot_verification_Two Sum_two_sum.dfy", "ground_truth": "method twoSum(nums: array, target: int) returns (index1: int, index2: int)\n requires 2 <= nums.Length\n requires exists i, j :: (0 <= i < j < nums.Length && nums[i] + nums[j] == target)\n ensures index1 != index2\n ensures 0 <= index1 < nums.Length\n ensures 0 <= index2 < nums.Length\n ensures nums[index1] + nums[index2] == target\n{\n var i := 0;\n while i < nums.Length\n invariant 0 <= i < nums.Length\n invariant forall u, v :: 0 <= u < v < nums.Length && u < i ==> nums[u] + nums[v] != target\n invariant exists u, v :: i <= u < v < nums.Length && nums[u] + nums[v] == target\n {\n var j := i + 1;\n while j < nums.Length\n invariant 0 <= i < j <= nums.Length\n invariant forall u, v :: 0 <= u < v < nums.Length && u < i ==> nums[u] + nums[v] != target\n invariant exists u, v :: i <= u < v < nums.Length && nums[u] + nums[v] == target\n invariant forall u :: i < u < j ==> nums[i] + nums[u] != target\n {\n if nums[i] + nums[j] == target\n {\n return i, j;\n } \n j := j + 1;\n }\n i := i + 1;\n }\n}\n\n", "hints_removed": "method twoSum(nums: array, target: int) returns (index1: int, index2: int)\n requires 2 <= nums.Length\n requires exists i, j :: (0 <= i < j < nums.Length && nums[i] + nums[j] == target)\n ensures index1 != index2\n ensures 0 <= index1 < nums.Length\n ensures 0 <= index2 < nums.Length\n ensures nums[index1] + nums[index2] == target\n{\n var i := 0;\n while i < nums.Length\n {\n var j := i + 1;\n while j < nums.Length\n {\n if nums[i] + nums[j] == target\n {\n return i, j;\n } \n j := j + 1;\n }\n i := i + 1;\n }\n}\n\n" }, { "test_ID": "238", "test_file": "Invoker_tmp_tmpypx0gs8x_dafny_abstract-interpreter_SimpleVerifier.dfy", "ground_truth": "module Ints {\n const U32_BOUND: nat := 0x1_0000_0000\n newtype u32 = x:int | 0 <= x < 0x1_0000_0000\n newtype i32 = x: int | -0x8000_0000 <= x < 0x8000_0000\n}\n\nmodule Lang {\n import opened Ints\n\n datatype Reg = R0 | R1 | R2 | R3\n\n datatype Expr =\n | Const(n: u32)\n // overflow during addition is an error\n | Add(r1: Reg, r2: Reg)\n // this is saturating subtraction (to allow comparing numbers)\n | Sub(r1: Reg, r2: Reg)\n\n datatype Stmt =\n | Assign(r: Reg, e: Expr)\n // Jump by offset if condition is true\n | JmpZero(r: Reg, offset: i32)\n\n datatype Program = Program(stmts: seq)\n\n}\n\n/* Well-formed check: offsets are all within the program */\n/* Main safety property: additions do not overflow */\n\n/* First, we give the concrete semantics of programs. */\n\nmodule ConcreteEval {\n import opened Ints\n import opened Lang\n\n type State = Reg -> u32\n\n function update_state(s: State, r0: Reg, v: u32): State {\n ((r: Reg) => if r == r0 then v else s(r))\n }\n\n datatype Option = Some(v: T) | None\n\n function expr_eval(env: State, e: Expr): Option\n {\n match e {\n case Const(n) => Some(n)\n case Add(r1, r2) =>\n (if (env(r1) as int + env(r2) as int >= U32_BOUND) then None\n else Some(env(r1) + env(r2)))\n case Sub(r1, r2) =>\n (if env(r1) as int - env(r2) as int < 0 then Some(0)\n else Some(env(r1) - env(r2)))\n }\n }\n\n // stmt_step executes a single statement\n //\n // Returns a new state and a relative PC offset (which is 1 for non-jump\n // statements).\n function stmt_step(env: State, s: Stmt): Option<(State, int)> {\n match s {\n case Assign(r, e) =>\n var e' := expr_eval(env, e);\n match e' {\n case Some(v) => Some((update_state(env, r, v), 1))\n case None => None\n }\n case JmpZero(r, offset) =>\n Some((env, (if env(r) == 0 then offset else 1) as int))\n }\n }\n\n datatype ExecResult = Ok(env: State) | NoFuel | Error\n\n // Run a program starting at pc.\n //\n // The sequence of statements is constant, meant to reflect a static program.\n // Termination occurs if the pc ever reaches exactly the end.\n //\n // Errors can come from either executing statements (see stmt_step for those\n // errors), or from an out-of-bounds pc (negative or not past the end of ss).\n //\n // fuel is needed to make this function terminate; the idea is that if there\n // exists some fuel that makes the program terminate, that is it's complete\n // execution, and if it always runs out of fuel it has an infinite loop.\n function stmts_step(env: State, ss: seq, pc: nat, fuel: nat): ExecResult\n requires pc <= |ss|\n decreases fuel\n {\n if fuel == 0 then NoFuel\n else if pc == |ss| then Ok(env)\n else match stmt_step(env, ss[pc]) {\n case None => Error\n case Some((env', offset)) =>\n if !(0 <= pc + offset <= |ss|) then Error\n else stmts_step(env', ss, pc + offset, fuel - 1)\n }\n }\n\n}\n\n/* Now we turn to analyzing programs */\n\nmodule AbstractEval {\n import opened Ints\n import opened Lang\n\n datatype Val = Interval(lo: int, hi: int)\n\n datatype AbstractState = AbstractState(rs: Reg -> Val)\n\n function expr_eval(env: AbstractState, e: Expr): Val {\n match e {\n case Const(n) => Interval(n as int, n as int)\n case Add(r1, r2) =>\n var v1 := env.rs(r1);\n var v2 := env.rs(r2);\n Interval(v1.lo + v2.lo, v1.hi + v2.hi)\n case Sub(r1, r2) =>\n // this was quite buggy initially: low is bounded (due to saturating\n // subtraction), and upper bound also should cannot go negative\n var v1 := env.rs(r1);\n var v2 := env.rs(r2);\n Interval(0, if v1.hi - v2.lo >= 0 then v1.hi - v2.lo else 0)\n }\n }\n\n function update_state(env: AbstractState, r0: Reg, v: Val): AbstractState {\n AbstractState((r: Reg) => if r == r0 then v else env.rs(r))\n }\n\n // function stmt_step(env: State, s: Stmt): Option<(State, int)>\n function stmt_eval(env: AbstractState, s: Stmt): (AbstractState, set) {\n match s {\n case Assign(r, e) => var v := expr_eval(env, e);\n (update_state(env, r, v), {1 as int})\n case JmpZero(r, offset) =>\n // imprecise analysis: we don't try to prove that this jump is or isn't taken\n (env, {offset as int, 1})\n }\n }\n\n /* TODO(tej): to interpret a program, we need to explore all paths. Along the\n * way, we would have to look for loops - our plan is to disallow them (unlike\n * a normal abstract interpretation which would try to run till a fixpoint). */\n\n // Implement a check for just the jump targets, which are static and thus\n // don't even need abstract interpretation.\n\n // Check that jump targets ss[from..] are valid.\n function has_valid_jump_targets(ss: seq, from: nat): bool\n decreases |ss|-from\n requires from <= |ss|\n {\n if from == |ss| then true\n else (match ss[from] {\n case JmpZero(_, offset) =>\n 0 <= from + offset as int <= |ss|\n case _ => true\n } &&\n has_valid_jump_targets(ss, from+1))\n }\n\n ghost predicate valid_jump_targets(ss: seq) {\n forall i | 0 <= i < |ss| :: ss[i].JmpZero? ==> 0 <= i + ss[i].offset as int <= |ss|\n }\n\n lemma has_valid_jump_targets_ok_helper(ss: seq, from: nat)\n requires from <= |ss|\n decreases |ss|-from\n ensures has_valid_jump_targets(ss, from) <==>\n (forall i | from <= i < |ss| :: ss[i].JmpZero? ==> 0 <= i + ss[i].offset as int <= |ss|)\n {\n }\n\n lemma has_valid_jump_targets_ok(ss: seq)\n ensures has_valid_jump_targets(ss, 0) <==> valid_jump_targets(ss)\n {\n has_valid_jump_targets_ok_helper(ss, 0);\n }\n}\n\nmodule AbstractEvalProof {\n import opened Ints\n import opened Lang\n import E = ConcreteEval\n import opened AbstractEval\n\n /* What does it mean for a concrete state to be captured by an abstract state?\n * (Alternately, interpret each abstract state as a set of concrete states) */\n\n ghost predicate reg_included(c_v: u32, v: Val) {\n v.lo <= c_v as int <= v.hi\n }\n\n ghost predicate state_included(env: E.State, abs: AbstractState) {\n forall r: Reg :: reg_included(env(r), abs.rs(r))\n }\n\n lemma expr_eval_ok(env: E.State, abs: AbstractState, e: Expr)\n requires state_included(env, abs)\n requires E.expr_eval(env, e).Some?\n ensures reg_included(E.expr_eval(env, e).v, expr_eval(abs, e))\n {\n match e {\n case Add(_, _) => { return; }\n case Const(_) => { return; }\n case Sub(r1, r2) => {\n /* debugging bug in the abstract interpretation */\n assert reg_included(env(r1), abs.rs(r1));\n assert reg_included(env(r2), abs.rs(r2));\n assert env(r1) as int <= abs.rs(r1).hi;\n assert env(r2) as int >= abs.rs(r2).lo;\n if env(r1) <= env(r2) {\n assert E.expr_eval(env, e).v == 0;\n return;\n }\n assert E.expr_eval(env, e).v as int == env(r1) as int - env(r2) as int;\n return;\n }\n }\n }\n\n lemma stmt_eval_ok(env: E.State, abs: AbstractState, stmt: Stmt)\n requires state_included(env, abs)\n requires E.stmt_step(env, stmt).Some?\n ensures state_included(E.stmt_step(env, stmt).v.0, stmt_eval(abs, stmt).0)\n {}\n}\n\n", "hints_removed": "module Ints {\n const U32_BOUND: nat := 0x1_0000_0000\n newtype u32 = x:int | 0 <= x < 0x1_0000_0000\n newtype i32 = x: int | -0x8000_0000 <= x < 0x8000_0000\n}\n\nmodule Lang {\n import opened Ints\n\n datatype Reg = R0 | R1 | R2 | R3\n\n datatype Expr =\n | Const(n: u32)\n // overflow during addition is an error\n | Add(r1: Reg, r2: Reg)\n // this is saturating subtraction (to allow comparing numbers)\n | Sub(r1: Reg, r2: Reg)\n\n datatype Stmt =\n | Assign(r: Reg, e: Expr)\n // Jump by offset if condition is true\n | JmpZero(r: Reg, offset: i32)\n\n datatype Program = Program(stmts: seq)\n\n}\n\n/* Well-formed check: offsets are all within the program */\n/* Main safety property: additions do not overflow */\n\n/* First, we give the concrete semantics of programs. */\n\nmodule ConcreteEval {\n import opened Ints\n import opened Lang\n\n type State = Reg -> u32\n\n function update_state(s: State, r0: Reg, v: u32): State {\n ((r: Reg) => if r == r0 then v else s(r))\n }\n\n datatype Option = Some(v: T) | None\n\n function expr_eval(env: State, e: Expr): Option\n {\n match e {\n case Const(n) => Some(n)\n case Add(r1, r2) =>\n (if (env(r1) as int + env(r2) as int >= U32_BOUND) then None\n else Some(env(r1) + env(r2)))\n case Sub(r1, r2) =>\n (if env(r1) as int - env(r2) as int < 0 then Some(0)\n else Some(env(r1) - env(r2)))\n }\n }\n\n // stmt_step executes a single statement\n //\n // Returns a new state and a relative PC offset (which is 1 for non-jump\n // statements).\n function stmt_step(env: State, s: Stmt): Option<(State, int)> {\n match s {\n case Assign(r, e) =>\n var e' := expr_eval(env, e);\n match e' {\n case Some(v) => Some((update_state(env, r, v), 1))\n case None => None\n }\n case JmpZero(r, offset) =>\n Some((env, (if env(r) == 0 then offset else 1) as int))\n }\n }\n\n datatype ExecResult = Ok(env: State) | NoFuel | Error\n\n // Run a program starting at pc.\n //\n // The sequence of statements is constant, meant to reflect a static program.\n // Termination occurs if the pc ever reaches exactly the end.\n //\n // Errors can come from either executing statements (see stmt_step for those\n // errors), or from an out-of-bounds pc (negative or not past the end of ss).\n //\n // fuel is needed to make this function terminate; the idea is that if there\n // exists some fuel that makes the program terminate, that is it's complete\n // execution, and if it always runs out of fuel it has an infinite loop.\n function stmts_step(env: State, ss: seq, pc: nat, fuel: nat): ExecResult\n requires pc <= |ss|\n {\n if fuel == 0 then NoFuel\n else if pc == |ss| then Ok(env)\n else match stmt_step(env, ss[pc]) {\n case None => Error\n case Some((env', offset)) =>\n if !(0 <= pc + offset <= |ss|) then Error\n else stmts_step(env', ss, pc + offset, fuel - 1)\n }\n }\n\n}\n\n/* Now we turn to analyzing programs */\n\nmodule AbstractEval {\n import opened Ints\n import opened Lang\n\n datatype Val = Interval(lo: int, hi: int)\n\n datatype AbstractState = AbstractState(rs: Reg -> Val)\n\n function expr_eval(env: AbstractState, e: Expr): Val {\n match e {\n case Const(n) => Interval(n as int, n as int)\n case Add(r1, r2) =>\n var v1 := env.rs(r1);\n var v2 := env.rs(r2);\n Interval(v1.lo + v2.lo, v1.hi + v2.hi)\n case Sub(r1, r2) =>\n // this was quite buggy initially: low is bounded (due to saturating\n // subtraction), and upper bound also should cannot go negative\n var v1 := env.rs(r1);\n var v2 := env.rs(r2);\n Interval(0, if v1.hi - v2.lo >= 0 then v1.hi - v2.lo else 0)\n }\n }\n\n function update_state(env: AbstractState, r0: Reg, v: Val): AbstractState {\n AbstractState((r: Reg) => if r == r0 then v else env.rs(r))\n }\n\n // function stmt_step(env: State, s: Stmt): Option<(State, int)>\n function stmt_eval(env: AbstractState, s: Stmt): (AbstractState, set) {\n match s {\n case Assign(r, e) => var v := expr_eval(env, e);\n (update_state(env, r, v), {1 as int})\n case JmpZero(r, offset) =>\n // imprecise analysis: we don't try to prove that this jump is or isn't taken\n (env, {offset as int, 1})\n }\n }\n\n /* TODO(tej): to interpret a program, we need to explore all paths. Along the\n * way, we would have to look for loops - our plan is to disallow them (unlike\n * a normal abstract interpretation which would try to run till a fixpoint). */\n\n // Implement a check for just the jump targets, which are static and thus\n // don't even need abstract interpretation.\n\n // Check that jump targets ss[from..] are valid.\n function has_valid_jump_targets(ss: seq, from: nat): bool\n requires from <= |ss|\n {\n if from == |ss| then true\n else (match ss[from] {\n case JmpZero(_, offset) =>\n 0 <= from + offset as int <= |ss|\n case _ => true\n } &&\n has_valid_jump_targets(ss, from+1))\n }\n\n ghost predicate valid_jump_targets(ss: seq) {\n forall i | 0 <= i < |ss| :: ss[i].JmpZero? ==> 0 <= i + ss[i].offset as int <= |ss|\n }\n\n lemma has_valid_jump_targets_ok_helper(ss: seq, from: nat)\n requires from <= |ss|\n ensures has_valid_jump_targets(ss, from) <==>\n (forall i | from <= i < |ss| :: ss[i].JmpZero? ==> 0 <= i + ss[i].offset as int <= |ss|)\n {\n }\n\n lemma has_valid_jump_targets_ok(ss: seq)\n ensures has_valid_jump_targets(ss, 0) <==> valid_jump_targets(ss)\n {\n has_valid_jump_targets_ok_helper(ss, 0);\n }\n}\n\nmodule AbstractEvalProof {\n import opened Ints\n import opened Lang\n import E = ConcreteEval\n import opened AbstractEval\n\n /* What does it mean for a concrete state to be captured by an abstract state?\n * (Alternately, interpret each abstract state as a set of concrete states) */\n\n ghost predicate reg_included(c_v: u32, v: Val) {\n v.lo <= c_v as int <= v.hi\n }\n\n ghost predicate state_included(env: E.State, abs: AbstractState) {\n forall r: Reg :: reg_included(env(r), abs.rs(r))\n }\n\n lemma expr_eval_ok(env: E.State, abs: AbstractState, e: Expr)\n requires state_included(env, abs)\n requires E.expr_eval(env, e).Some?\n ensures reg_included(E.expr_eval(env, e).v, expr_eval(abs, e))\n {\n match e {\n case Add(_, _) => { return; }\n case Const(_) => { return; }\n case Sub(r1, r2) => {\n /* debugging bug in the abstract interpretation */\n if env(r1) <= env(r2) {\n return;\n }\n return;\n }\n }\n }\n\n lemma stmt_eval_ok(env: E.State, abs: AbstractState, stmt: Stmt)\n requires state_included(env, abs)\n requires E.stmt_step(env, stmt).Some?\n ensures state_included(E.stmt_step(env, stmt).v.0, stmt_eval(abs, stmt).0)\n {}\n}\n\n" }, { "test_ID": "239", "test_file": "M2_tmp_tmp2laaavvl_Software Verification_Exercices_Exo4-CountAndReturn.dfy", "ground_truth": "method CountToAndReturnN(n: int) returns (r: int)\n requires n >= 0\n ensures r == n \n{\n var i := 0;\n while i < n\n invariant 0 <= i <= n\n {\n i := i + 1;\n }\n r := i;\n}\n", "hints_removed": "method CountToAndReturnN(n: int) returns (r: int)\n requires n >= 0\n ensures r == n \n{\n var i := 0;\n while i < n\n {\n i := i + 1;\n }\n r := i;\n}\n" }, { "test_ID": "240", "test_file": "M2_tmp_tmp2laaavvl_Software Verification_Exercices_Exo7-ComputeSum.dfy", "ground_truth": "function Sum(n:nat):nat\n \n{\n if n==0 then 0 else n + Sum(n-1)\n}\n\nmethod ComputeSum(n:nat) returns (s:nat)\n ensures s ==Sum(n)\n{\n s := 0;\n var i := 0;\n while i< n\n invariant 0 <= i <= n\n invariant s == Sum(i)\n {\n s := s + i + 1;\n i := i+1;\n }\n}\n", "hints_removed": "function Sum(n:nat):nat\n \n{\n if n==0 then 0 else n + Sum(n-1)\n}\n\nmethod ComputeSum(n:nat) returns (s:nat)\n ensures s ==Sum(n)\n{\n s := 0;\n var i := 0;\n while i< n\n {\n s := s + i + 1;\n i := i+1;\n }\n}\n" }, { "test_ID": "241", "test_file": "M2_tmp_tmp2laaavvl_Software Verification_Exercices_Exo9-Carre.dfy", "ground_truth": "method Carre(a: nat) returns (c: nat)\nensures c == a*a\n{\n var i := 0;\n c := 0;\n while i != a\n invariant 0 <= i <= a\n invariant c == i*i\n decreases a - i\n {\n c := c + 2*i +1;\n i := i + 1;\n }\n}\n", "hints_removed": "method Carre(a: nat) returns (c: nat)\nensures c == a*a\n{\n var i := 0;\n c := 0;\n while i != a\n {\n c := c + 2*i +1;\n i := i + 1;\n }\n}\n" }, { "test_ID": "242", "test_file": "MFDS_tmp_tmpvvr5y1t9_Assignments_Ass-1-2020-21-Sol-eGela.dfy", "ground_truth": "// Ejercicio 1: Demostrar por inducci\ufffdn el siguiente lema:\n\nlemma EcCuadDiv2_Lemma (x:int)\n requires x >= 1 \n ensures (x*x + x) % 2 == 0\n{\n if x != 1 { \n EcCuadDiv2_Lemma(x-1);\n assert x*x+x == ((x-1)*(x-1) + (x-1)) + 2*x;\n }\n}\n\n\n// Ejercicio 2: Demostrar por inducci\ufffdn el siguiente lema\n// Indicaciones: (1) Puedes llamar al lema del ejercicio anterior, si lo necesitas.\n// (2) Recuerda que, a veces, simplificar la HI puede ayudar a saber donde utilizarla.\n\nlemma EcCubicaDiv6_Lemma (x:int)\n requires x >= 1\n ensures (x*x*x + 3*x*x + 2*x) % 6 == 0\n{\n if x>1 {\n EcCubicaDiv6_Lemma(x-1);\n //assert ((x-1)*(x-1)*(x-1) + 3*(x-1)*(x-1) + 2*(x-1)) % 6 == 0; //HI\n assert (x*x*x - 3*x*x + 3*x -1 + 3*x*x - 6*x + 3 + 2*x -2) % 6 == 0; //HI\n assert (x*x*x - x) % 6 == 0; //HI\n assert x*x*x + 3*x*x + 2*x == (x*x*x - x) + 3*(x*x + x);\n EcCuadDiv2_Lemma(x);\n }\n}\n\n// Ejercicio 3: Probar por contradicci\ufffdn el siguiente lemma:\n\nlemma cubEven_Lemma (x:int)\n requires (x*x*x + 5) % 2 == 1\n ensures x % 2 == 0\n{\n if x%2 == 1 {\n var k := (x-1)/2;\n assert x*x*x + 5 == (2*k+1)*(2*k+1)*(2*k+1) + 5\n == 8*k*k*k + 12*k*k + 6*k + 6\n == 2*(4*k*k*k + 6*k*k + 3*k + 3);\n assert false;\n }\n}\n\n// Ejercicio 4: Prueba el siguiente lemma por casos (de acuerdo a los tres valores posibles de x%3)\nlemma perfectCube_Lemma (x:int)\n ensures exists z :: (x*x*x == 3*z || x*x*x == 3*z + 1 || x*x*x == 3*z - 1);\n{\n if x%3 == 0 {\n var k := x/3;\n assert x*x*x == 27*k*k*k == 3*(9*k*k*k);\n }\n else if x%3 == 1 {\n var k := (x-1)/3;\n assert x*x*x == (3*k+1)*(3*k+1)*(3*k+1) == 27*k*k*k + 27*k*k + 9*k + 1;\n assert x*x*x == 3*(9*k*k*k + 9*k*k + 3*k) + 1;\n }\n else {\n var k := (x-2)/3;\n assert x*x*x == (3*k+2)*(3*k+2)*(3*k+2) == 27*k*k*k + 54*k*k + 36*k + 8;\n assert x*x*x == 3*(9*k*k*k + 18*k*k + 12*k + 3) - 1;\n }\n}\n\n// Ejercicio 5: Dada la siguiente funci\ufffdn exp y los dos lemmas expGET1_Lemma y prodMon_Lemma (que Dafny demuestra autom\ufffdticamente)\n// demostrar el lemma expMon_Lemma por inducci\ufffdn en n. Usar calc {} y poner como \"hints\" las llamadas a los lemmas en los \n// pasos del c\ufffdlculo donde son utilizadas.\n\nfunction exp(x:int, e:nat):int\n{\n if e == 0 then 1 else x * exp(x,e-1)\n}\n\nlemma expGET1_Lemma(x:int, e:nat)\t\t\t\n requires x >= 1 \n ensures exp(x,e) >= 1\n{}\n\nlemma prodMon_Lemma(z:int, a:int, b:int)\n requires z >= 1 && a >= b >= 1\n ensures z*a >= z*b\n{}\n\nlemma expMon_Lemma(x:int, n:nat)\n\trequires x >= 1 && n >= 1\n\tensures exp(x+1,n) >= exp(x,n) + 1 \n{\n if n != 1 { \n calc {\n exp(x+1,n);\n ==\n (x+1)*exp(x+1,n-1);\n == \n x*exp(x+1,n-1) + exp(x+1,n-1);\n >= {\n expGET1_Lemma(x+1,n-1);\n }\n x*exp(x+1,n-1);\n >= {\n expMon_Lemma(x,n-1);\n //assert exp(x+1,n-1) >= (exp(x,n-1) + 1);\n expGET1_Lemma(x+1,n-1);\n //assert exp(x+1,n-1) >= 1;\n expGET1_Lemma(x,n-1);\n //assert (exp(x,n-1) + 1) >= 1;\n prodMon_Lemma(x, exp(x+1,n-1), exp(x,n-1) + 1);\n //assert x*exp(x+1,n-1) >= x*(exp(x,n-1) + 1);\n }\n x*(exp(x,n-1) + 1); \n ==\n x*exp(x,n-1) + x;\n >=\n exp(x,n)+1;\n }\n }\n}\n\n", "hints_removed": "// Ejercicio 1: Demostrar por inducci\ufffdn el siguiente lema:\n\nlemma EcCuadDiv2_Lemma (x:int)\n requires x >= 1 \n ensures (x*x + x) % 2 == 0\n{\n if x != 1 { \n EcCuadDiv2_Lemma(x-1);\n }\n}\n\n\n// Ejercicio 2: Demostrar por inducci\ufffdn el siguiente lema\n// Indicaciones: (1) Puedes llamar al lema del ejercicio anterior, si lo necesitas.\n// (2) Recuerda que, a veces, simplificar la HI puede ayudar a saber donde utilizarla.\n\nlemma EcCubicaDiv6_Lemma (x:int)\n requires x >= 1\n ensures (x*x*x + 3*x*x + 2*x) % 6 == 0\n{\n if x>1 {\n EcCubicaDiv6_Lemma(x-1);\n //assert ((x-1)*(x-1)*(x-1) + 3*(x-1)*(x-1) + 2*(x-1)) % 6 == 0; //HI\n EcCuadDiv2_Lemma(x);\n }\n}\n\n// Ejercicio 3: Probar por contradicci\ufffdn el siguiente lemma:\n\nlemma cubEven_Lemma (x:int)\n requires (x*x*x + 5) % 2 == 1\n ensures x % 2 == 0\n{\n if x%2 == 1 {\n var k := (x-1)/2;\n == 8*k*k*k + 12*k*k + 6*k + 6\n == 2*(4*k*k*k + 6*k*k + 3*k + 3);\n }\n}\n\n// Ejercicio 4: Prueba el siguiente lemma por casos (de acuerdo a los tres valores posibles de x%3)\nlemma perfectCube_Lemma (x:int)\n ensures exists z :: (x*x*x == 3*z || x*x*x == 3*z + 1 || x*x*x == 3*z - 1);\n{\n if x%3 == 0 {\n var k := x/3;\n }\n else if x%3 == 1 {\n var k := (x-1)/3;\n }\n else {\n var k := (x-2)/3;\n }\n}\n\n// Ejercicio 5: Dada la siguiente funci\ufffdn exp y los dos lemmas expGET1_Lemma y prodMon_Lemma (que Dafny demuestra autom\ufffdticamente)\n// demostrar el lemma expMon_Lemma por inducci\ufffdn en n. Usar calc {} y poner como \"hints\" las llamadas a los lemmas en los \n// pasos del c\ufffdlculo donde son utilizadas.\n\nfunction exp(x:int, e:nat):int\n{\n if e == 0 then 1 else x * exp(x,e-1)\n}\n\nlemma expGET1_Lemma(x:int, e:nat)\t\t\t\n requires x >= 1 \n ensures exp(x,e) >= 1\n{}\n\nlemma prodMon_Lemma(z:int, a:int, b:int)\n requires z >= 1 && a >= b >= 1\n ensures z*a >= z*b\n{}\n\nlemma expMon_Lemma(x:int, n:nat)\n\trequires x >= 1 && n >= 1\n\tensures exp(x+1,n) >= exp(x,n) + 1 \n{\n if n != 1 { \n calc {\n exp(x+1,n);\n ==\n (x+1)*exp(x+1,n-1);\n == \n x*exp(x+1,n-1) + exp(x+1,n-1);\n >= {\n expGET1_Lemma(x+1,n-1);\n }\n x*exp(x+1,n-1);\n >= {\n expMon_Lemma(x,n-1);\n //assert exp(x+1,n-1) >= (exp(x,n-1) + 1);\n expGET1_Lemma(x+1,n-1);\n //assert exp(x+1,n-1) >= 1;\n expGET1_Lemma(x,n-1);\n //assert (exp(x,n-1) + 1) >= 1;\n prodMon_Lemma(x, exp(x+1,n-1), exp(x,n-1) + 1);\n //assert x*exp(x+1,n-1) >= x*(exp(x,n-1) + 1);\n }\n x*(exp(x,n-1) + 1); \n ==\n x*exp(x,n-1) + x;\n >=\n exp(x,n)+1;\n }\n }\n}\n\n" }, { "test_ID": "243", "test_file": "MFES_2021_tmp_tmpuljn8zd9_Exams_Special_Exam_03_2020_4_CatalanNumbers.dfy", "ground_truth": "function C(n: nat): nat \n decreases n\n{\n if n == 0 then 1 else (4 * n - 2) * C(n-1) / (n + 1) \n}\n\nmethod calcC(n: nat) returns (res: nat)\n ensures res == C(n)\n{\n var i := 0;\n res := 1;\n\n assert res == C(i) && 0 <= i <= n;\n while i < n \n decreases n - i //a - loop variant\n invariant res == C(i) && 0 <= i <= n //b - loop invariant\n {\n ghost var v0 := n - i;\n assert res == C(i) && 0 <= i <= n && i < n && n - i == v0;\n i := i + 1;\n res := (4 * i - 2) * res / (i + 1);\n assert res == C(i) && 0 <= i <= n && 0 <= n - i < v0;\n }\n assert res == C(i) && 0 <= i <= n && i >= n; \n}\n\n", "hints_removed": "function C(n: nat): nat \n{\n if n == 0 then 1 else (4 * n - 2) * C(n-1) / (n + 1) \n}\n\nmethod calcC(n: nat) returns (res: nat)\n ensures res == C(n)\n{\n var i := 0;\n res := 1;\n\n while i < n \n {\n ghost var v0 := n - i;\n i := i + 1;\n res := (4 * i - 2) * res / (i + 1);\n }\n}\n\n" }, { "test_ID": "244", "test_file": "MFES_2021_tmp_tmpuljn8zd9_FCUL_Exercises_10_find.dfy", "ground_truth": "method find(a: array, key: int) returns(index: int)\n requires a.Length > 0;\n ensures 0 <= index <= a.Length;\n ensures index < a.Length ==> a[index] == key;\n{\n index := 0;\n while index < a.Length && a[index] != key \n decreases a.Length - index \n invariant 0 <= index <= a.Length\n invariant forall x :: 0 <= x < index ==> a[x] != key\n {\n index := index + 1;\n }\n}\n", "hints_removed": "method find(a: array, key: int) returns(index: int)\n requires a.Length > 0;\n ensures 0 <= index <= a.Length;\n ensures index < a.Length ==> a[index] == key;\n{\n index := 0;\n while index < a.Length && a[index] != key \n {\n index := index + 1;\n }\n}\n" }, { "test_ID": "245", "test_file": "MFES_2021_tmp_tmpuljn8zd9_FCUL_Exercises_8_sum.dfy", "ground_truth": "function calcSum(n: nat) : nat \n{ \n n * (n - 1) / 2\n}\n\nmethod sum(n: nat) returns(s: nat)\n ensures s == calcSum(n + 1)\n{\n s := 0;\n var i := 0;\n while i < n \n decreases n - i\n invariant 0 <= i <= n\n invariant s == calcSum(i + 1)\n {\n i := i + 1;\n s := s + i;\n }\n}\n", "hints_removed": "function calcSum(n: nat) : nat \n{ \n n * (n - 1) / 2\n}\n\nmethod sum(n: nat) returns(s: nat)\n ensures s == calcSum(n + 1)\n{\n s := 0;\n var i := 0;\n while i < n \n {\n i := i + 1;\n s := s + i;\n }\n}\n" }, { "test_ID": "246", "test_file": "MFES_2021_tmp_tmpuljn8zd9_PracticalClasses_TP3_2_Insertion_Sort.dfy", "ground_truth": "// Sorts array 'a' using the insertion sort algorithm.\nmethod insertionSort(a: array) \n modifies a\n ensures isSorted(a, 0, a.Length)\n ensures multiset(a[..]) == multiset(old(a[..]))\n{\n var i := 0;\n while i < a.Length \n decreases a.Length - i \n invariant 0 <= i <= a.Length\n invariant isSorted(a, 0, i)\n invariant multiset(a[..]) == multiset(old(a[..]))\n {\n var j := i;\n while j > 0 && a[j-1] > a[j] \n decreases j\n invariant 0 <= j <= i \n invariant multiset(a[..]) == multiset(old(a[..]))\n invariant forall l, r :: 0 <= l < r <= i && r != j ==> a[l] <= a[r]\n {\n a[j-1], a[j] := a[j], a[j-1];\n j := j - 1;\n }\n i := i + 1;\n }\n}\n\n// Checks if array 'a' is sorted.\npredicate isSorted(a: array, from: nat, to: nat)\n reads a\n requires 0 <= from <= to <= a.Length\n{\n forall i, j :: from <= i < j < to ==> a[i] <= a[j]\n}\n\n// Simple test case to check the postcondition\nmethod testInsertionSort() {\n var a := new int[] [ 9, 4, 3, 6, 8];\n assert a[..] == [9, 4, 3, 6, 8];\n insertionSort(a);\n assert a[..] == [3, 4, 6, 8, 9];\n}\n\n", "hints_removed": "// Sorts array 'a' using the insertion sort algorithm.\nmethod insertionSort(a: array) \n modifies a\n ensures isSorted(a, 0, a.Length)\n ensures multiset(a[..]) == multiset(old(a[..]))\n{\n var i := 0;\n while i < a.Length \n {\n var j := i;\n while j > 0 && a[j-1] > a[j] \n {\n a[j-1], a[j] := a[j], a[j-1];\n j := j - 1;\n }\n i := i + 1;\n }\n}\n\n// Checks if array 'a' is sorted.\npredicate isSorted(a: array, from: nat, to: nat)\n reads a\n requires 0 <= from <= to <= a.Length\n{\n forall i, j :: from <= i < j < to ==> a[i] <= a[j]\n}\n\n// Simple test case to check the postcondition\nmethod testInsertionSort() {\n var a := new int[] [ 9, 4, 3, 6, 8];\n insertionSort(a);\n}\n\n" }, { "test_ID": "247", "test_file": "MFES_2021_tmp_tmpuljn8zd9_TheoreticalClasses_Power.dfy", "ground_truth": "/* \n* Formal verification of O(n) and O(log n) algorithms to calculate the natural\n* power of a real number (x^n), illustrating the usage of lemmas.\n* FEUP, MIEIC, MFES, 2020/21.\n*/\n\n// Initial specification/definition of x^n, recursive, functional style, \n// with time and space complexity O(n).\nfunction power(x: real, n: nat) : real\n decreases n\n{\n if n == 0 then 1.0 else x * power(x, n-1)\n}\n\n// Iterative version, imperative, with time complexity O(n) and space complexity O(1).\nmethod powerIter(x: real, n: nat) returns (p : real)\n ensures p == power(x, n)\n{\n // start with p = x^0\n var i := 0;\n p := 1.0; // x ^ i\n // iterate until reaching p = x^n\n while i < n\n decreases n - i\n invariant 0 <= i <= n && p == power(x, i)\n {\n p := p * x;\n i := i + 1;\n }\n}\n\n// Recursive version, imperative, with time and space complexity O(log n).\nmethod powerOpt(x: real, n: nat) returns (p : real)\n ensures p == power(x, n);\n decreases n;\n{\n if n == 0 {\n return 1.0;\n }\n else if n == 1 {\n return x;\n }\n else if n % 2 == 0 {\n distributiveProperty(x, n/2, n/2); // recall lemma here\n var temp := powerOpt(x, n/2);\n return temp * temp;\n }\n else {\n distributiveProperty(x, (n-1)/2, (n-1)/2); // recall lemma here \n var temp := powerOpt(x, (n-1)/2);\n return temp * temp * x;\n } \n}\n\n// States the property x^a * x^b = x^(a+b), that powerOpt takes advantage of. \n// The annotation {:induction a} guides Dafny to prove the property\n// by automatic induction on 'a'.\nlemma {:induction a} distributiveProperty(x: real, a: nat, b: nat) \n ensures power(x, a) * power(x, b) == power(x, a + b) \n{\n // \n // To use the proof below, deactivate automatic induction, with {:induction false}.\n /* if a == 0 {\n // base case\n calc == {\n power(x, a) * power(x, b);\n power(x, 0) * power(x, b); // substitution\n 1.0 * power(x, b); // by the definition of power\n power(x, b); // neutral element of \"*\"\n power(x, a + b); // neutral element of \"+\"\n }\n }\n else {\n // recursive case, assuming property holds for a-1 (proof by induction)\n distributiveProperty(x, a-1, b); \n // now do the proof\n calc == {\n power(x, a) * power(x, b);\n (x * power(x, a-1)) * power(x, b); // by the definition of power\n x * (power(x, a-1) * power(x, b)); // associative property\n x * power(x, a + b - 1); // this same property for a-1\n power(x, a + b); // definition of power\n }\n }*/\n}\n\n// A simple test case to make sure the specification is adequate.\nmethod testPowerIter(){\n var p1 := powerIter(2.0, 5);\n assert p1 == 32.0;\n}\n\nmethod testPowerOpt(){\n var p1 := powerOpt(2.0, 5);\n assert p1 == 32.0;\n}\n", "hints_removed": "/* \n* Formal verification of O(n) and O(log n) algorithms to calculate the natural\n* power of a real number (x^n), illustrating the usage of lemmas.\n* FEUP, MIEIC, MFES, 2020/21.\n*/\n\n// Initial specification/definition of x^n, recursive, functional style, \n// with time and space complexity O(n).\nfunction power(x: real, n: nat) : real\n{\n if n == 0 then 1.0 else x * power(x, n-1)\n}\n\n// Iterative version, imperative, with time complexity O(n) and space complexity O(1).\nmethod powerIter(x: real, n: nat) returns (p : real)\n ensures p == power(x, n)\n{\n // start with p = x^0\n var i := 0;\n p := 1.0; // x ^ i\n // iterate until reaching p = x^n\n while i < n\n {\n p := p * x;\n i := i + 1;\n }\n}\n\n// Recursive version, imperative, with time and space complexity O(log n).\nmethod powerOpt(x: real, n: nat) returns (p : real)\n ensures p == power(x, n);\n{\n if n == 0 {\n return 1.0;\n }\n else if n == 1 {\n return x;\n }\n else if n % 2 == 0 {\n distributiveProperty(x, n/2, n/2); // recall lemma here\n var temp := powerOpt(x, n/2);\n return temp * temp;\n }\n else {\n distributiveProperty(x, (n-1)/2, (n-1)/2); // recall lemma here \n var temp := powerOpt(x, (n-1)/2);\n return temp * temp * x;\n } \n}\n\n// States the property x^a * x^b = x^(a+b), that powerOpt takes advantage of. \n// The annotation {:induction a} guides Dafny to prove the property\n// by automatic induction on 'a'.\nlemma {:induction a} distributiveProperty(x: real, a: nat, b: nat) \n ensures power(x, a) * power(x, b) == power(x, a + b) \n{\n // \n // To use the proof below, deactivate automatic induction, with {:induction false}.\n /* if a == 0 {\n // base case\n calc == {\n power(x, a) * power(x, b);\n power(x, 0) * power(x, b); // substitution\n 1.0 * power(x, b); // by the definition of power\n power(x, b); // neutral element of \"*\"\n power(x, a + b); // neutral element of \"+\"\n }\n }\n else {\n // recursive case, assuming property holds for a-1 (proof by induction)\n distributiveProperty(x, a-1, b); \n // now do the proof\n calc == {\n power(x, a) * power(x, b);\n (x * power(x, a-1)) * power(x, b); // by the definition of power\n x * (power(x, a-1) * power(x, b)); // associative property\n x * power(x, a + b - 1); // this same property for a-1\n power(x, a + b); // definition of power\n }\n }*/\n}\n\n// A simple test case to make sure the specification is adequate.\nmethod testPowerIter(){\n var p1 := powerIter(2.0, 5);\n}\n\nmethod testPowerOpt(){\n var p1 := powerOpt(2.0, 5);\n}\n" }, { "test_ID": "248", "test_file": "MFS_tmp_tmpmmnu354t_Praticas_TP9_Power.dfy", "ground_truth": "/* \n* Formal verification of O(n) and O(log n) algorithms to calculate the natural\n* power of a real number (x^n), illustrating the usage of lemmas.\n* FEUP, M.EIC, MFS, 2021/22.\n*/\n\n// Initial specification/definition of x^n, recursive, functional style, \n// with time and space complexity O(n).\nfunction power(x: real, n: nat) : real\n{\n if n == 0 then 1.0 else x * power(x, n-1)\n}\n\n// Iterative version, imperative, with time complexity O(n) and space complexity O(1).\nmethod powerIter(b: real, n: nat) returns (p : real)\n ensures p == power(b, n)\n{\n // start with p = b^0\n p := 1.0;\n var i := 0;\n // iterate until reaching p = b^n\n while i < n\n invariant p == power(b, i) && 0 <= i <= n\n {\n p := p * b;\n i := i + 1;\n }\n}\n\nlemma {:induction e1} powDist(b: real, e1: nat, e2: nat)\n ensures power(b, e1+e2) == power(b, e1) * power(b, e2)\n{}\n\nlemma {:induction false} distributiveProperty(x: real, a: nat, b: nat)\n ensures power(x, a) * power(x, b) == power(x, a+b)\n{\n if a == 0 {\n assert\n power(x, a) * power(x, b) ==\n 1.0 * power(x, b) ==\n power(x, b) ==\n power(x, a + b);\n }\n else {\n distributiveProperty(x, a-1, b);\n assert\n power(x, a) * power(x, b) ==\n (x * power(x, a-1)) * power(x, b) ==\n x * (power(x, a-1) * power(x, b)) ==\n x * power(x, a - 1 + b) ==\n power(x, a + b);\n }\n}\n// Recursive version, imperative, with time and space complexity O(log n).\nmethod powerOpt(b: real, n: nat) returns (p : real)\n ensures p == power(b, n)\n{\n if n == 0 {\n return 1.0;\n }\n else if n % 2 == 0 {\n distributiveProperty(b, n/2, n/2);\n var r := powerOpt(b, n/2);\n return r * r;\n }\n else {\n distributiveProperty(b, (n-1)/2, (n-1)/2);\n var r := powerOpt(b, (n-1)/2);\n return r * r * b;\n } \n}\n\n// A simple test case to make sure the specification is adequate.\nmethod testPower() {\n var p1 := powerIter(2.0, 5);\n var p2 := powerOpt(2.0, 5);\n\n print \"P1: \", p1, \"\\n\";\n print \"P2: \", p2, \"\\n\";\n\n assert p1 == 32.0;\n assert p2 == 32.0;\n}\n", "hints_removed": "/* \n* Formal verification of O(n) and O(log n) algorithms to calculate the natural\n* power of a real number (x^n), illustrating the usage of lemmas.\n* FEUP, M.EIC, MFS, 2021/22.\n*/\n\n// Initial specification/definition of x^n, recursive, functional style, \n// with time and space complexity O(n).\nfunction power(x: real, n: nat) : real\n{\n if n == 0 then 1.0 else x * power(x, n-1)\n}\n\n// Iterative version, imperative, with time complexity O(n) and space complexity O(1).\nmethod powerIter(b: real, n: nat) returns (p : real)\n ensures p == power(b, n)\n{\n // start with p = b^0\n p := 1.0;\n var i := 0;\n // iterate until reaching p = b^n\n while i < n\n {\n p := p * b;\n i := i + 1;\n }\n}\n\nlemma {:induction e1} powDist(b: real, e1: nat, e2: nat)\n ensures power(b, e1+e2) == power(b, e1) * power(b, e2)\n{}\n\nlemma {:induction false} distributiveProperty(x: real, a: nat, b: nat)\n ensures power(x, a) * power(x, b) == power(x, a+b)\n{\n if a == 0 {\n power(x, a) * power(x, b) ==\n 1.0 * power(x, b) ==\n power(x, b) ==\n power(x, a + b);\n }\n else {\n distributiveProperty(x, a-1, b);\n power(x, a) * power(x, b) ==\n (x * power(x, a-1)) * power(x, b) ==\n x * (power(x, a-1) * power(x, b)) ==\n x * power(x, a - 1 + b) ==\n power(x, a + b);\n }\n}\n// Recursive version, imperative, with time and space complexity O(log n).\nmethod powerOpt(b: real, n: nat) returns (p : real)\n ensures p == power(b, n)\n{\n if n == 0 {\n return 1.0;\n }\n else if n % 2 == 0 {\n distributiveProperty(b, n/2, n/2);\n var r := powerOpt(b, n/2);\n return r * r;\n }\n else {\n distributiveProperty(b, (n-1)/2, (n-1)/2);\n var r := powerOpt(b, (n-1)/2);\n return r * r * b;\n } \n}\n\n// A simple test case to make sure the specification is adequate.\nmethod testPower() {\n var p1 := powerIter(2.0, 5);\n var p2 := powerOpt(2.0, 5);\n\n print \"P1: \", p1, \"\\n\";\n print \"P2: \", p2, \"\\n\";\n\n}\n" }, { "test_ID": "249", "test_file": "MFS_tmp_tmpmmnu354t_Testes anteriores_T2_ex5_2020_2.dfy", "ground_truth": "method leq(a: array, b: array) returns (result: bool) \n ensures result <==> (a.Length <= b.Length && a[..] == b[..a.Length]) || (exists k :: 0 <= k < a.Length && k < b.Length && a[..k] == b[..k] && a[k] < b[k])\n{\n var i := 0;\n while i < a.Length && i < b.Length \n decreases a.Length - i\n invariant 0 <= i <= a.Length && 0 <= i <= b.Length\n invariant a[..i] == b[..i]\n {\n if a[i] < b[i] { return true; }\n else if a[i] > b[i] { return false; }\n else {i := i + 1; }\n }\n return a.Length <= b.Length;\n}\n\nmethod testLeq() {\n var b := new int[][1, 2];\n var a1 := new int[][]; var r1 := leq(a1, b); assert r1;\n var a2 := new int[][1]; var r2 := leq(a2, b); assert r2;\n var a3 := new int[][1, 2]; var r3 := leq(a3, b); assert r3;\n var a4 := new int[][1, 1, 2]; var r4 := leq(a4, b); assert a4[1], b: array) returns (result: bool) \n ensures result <==> (a.Length <= b.Length && a[..] == b[..a.Length]) || (exists k :: 0 <= k < a.Length && k < b.Length && a[..k] == b[..k] && a[k] < b[k])\n{\n var i := 0;\n while i < a.Length && i < b.Length \n {\n if a[i] < b[i] { return true; }\n else if a[i] > b[i] { return false; }\n else {i := i + 1; }\n }\n return a.Length <= b.Length;\n}\n\nmethod testLeq() {\n var b := new int[][1, 2];\n var a1 := new int[][]; var r1 := leq(a1, b); assert r1;\n var a2 := new int[][1]; var r2 := leq(a2, b); assert r2;\n var a3 := new int[][1, 2]; var r3 := leq(a3, b); assert r3;\n var a4 := new int[][1, 1, 2]; var r4 := leq(a4, b); assert a4[1])\n reads a\n{\n forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j]\n}\n\n// Finds a value 'x' in a sorted array 'a', and returns its index,\n// or -1 if not found. \nmethod binarySearch(a: array, x: int) returns (index: int) \n requires isSorted(a)\n ensures -1 <= index < a.Length\n ensures if index != -1 then a[index] == x \n else x !in a[..] //forall i :: 0 <= i < a.Length ==> a[i] != x\n{ \n var low, high := 0, a.Length;\n while low < high \n decreases high - low\n invariant 0 <= low <= high <= a.Length && \n x !in a[..low] && x !in a[high..]\n {\n\n var mid := low + (high - low) / 2;\n if {\n case a[mid] < x => low := mid + 1;\n case a[mid] > x => high := mid;\n case a[mid] == x => return mid;\n }\n }\n return -1;\n}\n\n// Simple test cases to check the post-condition.\nmethod testBinarySearch() {\n var a := new int[] [1, 4, 4, 6, 8];\n assert a[..] == [1, 4, 4, 6, 8];\n var id1 := binarySearch(a, 6);\n assert a[3] == 6; // added\n assert id1 == 3;\n var id2 := binarySearch(a, 3);\n assert id2 == -1; \n var id3 := binarySearch(a, 4);\n assert a[1] == 4 && a[2] == 4; // added\n assert id3 in {1, 2};\n}\n\n/*\na) Identify adequate pre and post-conditions for this method, \nand encode them as \u201crequires\u201d and \u201censures\u201d clauses in Dafny. \nYou can use the predicate below if needed.\n\nb) Identify an adequate loop variant and loop invariant, and encode them \nas \u201cdecreases\u201d and \u201cinvariant\u201d clauses in Dafny.\n*/\n", "hints_removed": "// Checks if array 'a' is sorted.\npredicate isSorted(a: array)\n reads a\n{\n forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j]\n}\n\n// Finds a value 'x' in a sorted array 'a', and returns its index,\n// or -1 if not found. \nmethod binarySearch(a: array, x: int) returns (index: int) \n requires isSorted(a)\n ensures -1 <= index < a.Length\n ensures if index != -1 then a[index] == x \n else x !in a[..] //forall i :: 0 <= i < a.Length ==> a[i] != x\n{ \n var low, high := 0, a.Length;\n while low < high \n x !in a[..low] && x !in a[high..]\n {\n\n var mid := low + (high - low) / 2;\n if {\n case a[mid] < x => low := mid + 1;\n case a[mid] > x => high := mid;\n case a[mid] == x => return mid;\n }\n }\n return -1;\n}\n\n// Simple test cases to check the post-condition.\nmethod testBinarySearch() {\n var a := new int[] [1, 4, 4, 6, 8];\n var id1 := binarySearch(a, 6);\n var id2 := binarySearch(a, 3);\n var id3 := binarySearch(a, 4);\n}\n\n/*\na) Identify adequate pre and post-conditions for this method, \nand encode them as \u201crequires\u201d and \u201censures\u201d clauses in Dafny. \nYou can use the predicate below if needed.\n\nb) Identify an adequate loop variant and loop invariant, and encode them \nas \u201cdecreases\u201d and \u201cinvariant\u201d clauses in Dafny.\n*/\n" }, { "test_ID": "251", "test_file": "MIEIC_mfes_tmp_tmpq3ho7nve_exams_appeal_20_p4.dfy", "ground_truth": "function F(n: nat): nat { if n <= 2 then n else F(n-1) + F(n-3)}\n\nmethod calcF(n: nat) returns (res: nat) \n ensures res == F(n) \n{\n var a, b, c := 0, 1, 2;\n var i := 0;\n while i < n\n decreases n-i\n invariant 0 <= i <= n\n invariant a == F(i) && b == F(i+1) && c == F(i+2)\n {\n a, b, c := b, c, a + c; \n i := i + 1;\n }\n res := a;\n}\n", "hints_removed": "function F(n: nat): nat { if n <= 2 then n else F(n-1) + F(n-3)}\n\nmethod calcF(n: nat) returns (res: nat) \n ensures res == F(n) \n{\n var a, b, c := 0, 1, 2;\n var i := 0;\n while i < n\n {\n a, b, c := b, c, a + c; \n i := i + 1;\n }\n res := a;\n}\n" }, { "test_ID": "252", "test_file": "MIEIC_mfes_tmp_tmpq3ho7nve_exams_mt2_19_p4.dfy", "ground_truth": "function R(n: nat): nat {\n if n == 0 then 0 else if R(n-1) > n then R(n-1) - n else R(n-1) + n\n}\n\nmethod calcR(n: nat) returns (r: nat)\n ensures r == R(n) \n{\n r := 0;\n var i := 0;\n while i < n \n decreases n-i\n invariant 0 <= i <= n\n invariant r == R(i)\n {\n i := i + 1;\n if r > i {\n r := r - i;\n } \n else {\n r := r + i;\n }\n }\n}\n", "hints_removed": "function R(n: nat): nat {\n if n == 0 then 0 else if R(n-1) > n then R(n-1) - n else R(n-1) + n\n}\n\nmethod calcR(n: nat) returns (r: nat)\n ensures r == R(n) \n{\n r := 0;\n var i := 0;\n while i < n \n {\n i := i + 1;\n if r > i {\n r := r - i;\n } \n else {\n r := r + i;\n }\n }\n}\n" }, { "test_ID": "253", "test_file": "MIEIC_mfes_tmp_tmpq3ho7nve_exams_mt2_19_p5.dfy", "ground_truth": "type T = int // example\n\n // Partitions a nonempty array 'a', by reordering the elements in the array,\n// so that elements smaller than a chosen pivot are placed to the left of the\n// pivot, and values greater or equal than the pivot are placed to the right of \n// the pivot. Returns the pivot position.\nmethod partition(a: array) returns(pivotPos: int) \n requires a.Length > 0\n ensures 0 <= pivotPos < a.Length\n ensures forall i :: 0 <= i < pivotPos ==> a[i] < a[pivotPos]\n ensures forall i :: pivotPos < i < a.Length ==> a[i] >= a[pivotPos]\n ensures multiset(a[..]) == multiset(old(a[..]))\n modifies a\n{\n pivotPos := a.Length - 1; // chooses pivot at end of array \n var i := 0; // index that separates values smaller than pivot (0 to i-1), \n // and values greater or equal than pivot (i to j-1) \n var j := 0; // index to scan the array\n \n // Scan the array and move elements as needed\n while j < a.Length-1 \n decreases a.Length-1-j\n invariant 0 <= i <= j < a.Length \n invariant forall k :: 0 <= k < i ==> a[k] < a[pivotPos]\n invariant forall k :: i <= k < j ==> a[k] >= a[pivotPos]\n invariant multiset(a[..]) == multiset(old(a[..]))\n {\n if a[j] < a[pivotPos] {\n a[i], a[j] := a[j], a[i];\n i := i + 1;\n }\n j := j+1;\n }\n \n // Swap pivot to the 'mid' of the array\n a[a.Length-1], a[i] := a[i], a[a.Length-1];\n pivotPos := i; \n}\n", "hints_removed": "type T = int // example\n\n // Partitions a nonempty array 'a', by reordering the elements in the array,\n// so that elements smaller than a chosen pivot are placed to the left of the\n// pivot, and values greater or equal than the pivot are placed to the right of \n// the pivot. Returns the pivot position.\nmethod partition(a: array) returns(pivotPos: int) \n requires a.Length > 0\n ensures 0 <= pivotPos < a.Length\n ensures forall i :: 0 <= i < pivotPos ==> a[i] < a[pivotPos]\n ensures forall i :: pivotPos < i < a.Length ==> a[i] >= a[pivotPos]\n ensures multiset(a[..]) == multiset(old(a[..]))\n modifies a\n{\n pivotPos := a.Length - 1; // chooses pivot at end of array \n var i := 0; // index that separates values smaller than pivot (0 to i-1), \n // and values greater or equal than pivot (i to j-1) \n var j := 0; // index to scan the array\n \n // Scan the array and move elements as needed\n while j < a.Length-1 \n {\n if a[j] < a[pivotPos] {\n a[i], a[j] := a[j], a[i];\n i := i + 1;\n }\n j := j+1;\n }\n \n // Swap pivot to the 'mid' of the array\n a[a.Length-1], a[i] := a[i], a[a.Length-1];\n pivotPos := i; \n}\n" }, { "test_ID": "254", "test_file": "MIEIC_mfes_tmp_tmpq3ho7nve_exams_special_20_p5.dfy", "ground_truth": "type T = int // for demo purposes, but could be another type\npredicate sorted(a: array, n: nat) \n requires n <= a.Length\n reads a\n{\n forall i,j :: 0 <= i < j < n ==> a[i] <= a[j]\n}\n\n// Use binary search to find an appropriate position to insert a value 'x'\n// in a sorted array 'a', so that it remains sorted.\nmethod binarySearch(a: array, x: T) returns (index: int) \n requires sorted(a, a.Length)\n ensures sorted(a, a.Length)\n //ensures a[..] == old(a)[..]\n ensures 0 <= index <= a.Length\n //ensures forall i :: 0 <= i < index ==> a[i] <= x\n //ensures forall i :: index <= i < a.Length ==> a[i] >= x\n\n ensures index > 0 ==> a[index-1] <= x\n ensures index < a.Length ==> a[index] >= x\n{\n var low, high := 0, a.Length;\n while low < high \n decreases high-low\n invariant 0 <= low <= high <= a.Length\n invariant low > 0 ==> a[low-1] <= x\n invariant high < a.Length ==> a[high] >= x\n\n {\n var mid := low + (high - low) / 2;\n if {\n case a[mid] < x => low := mid + 1;\n case a[mid] > x => high := mid;\n case a[mid] == x => return mid;\n }\n }\n return low;\n}\n\n// Simple test cases to check the post-condition\nmethod testBinarySearch() {\n var a := new int[2] [1, 3];\n var id0 := binarySearch(a, 0);\n assert id0 == 0;\n var id1 := binarySearch(a, 1);\n assert id1 in {0, 1};\n var id2 := binarySearch(a, 2);\n assert id2 == 1;\n var id3 := binarySearch(a, 3);\n assert id3 in {1, 2};\n var id4 := binarySearch(a, 4);\n assert id4 == 2;\n}\n\n", "hints_removed": "type T = int // for demo purposes, but could be another type\npredicate sorted(a: array, n: nat) \n requires n <= a.Length\n reads a\n{\n forall i,j :: 0 <= i < j < n ==> a[i] <= a[j]\n}\n\n// Use binary search to find an appropriate position to insert a value 'x'\n// in a sorted array 'a', so that it remains sorted.\nmethod binarySearch(a: array, x: T) returns (index: int) \n requires sorted(a, a.Length)\n ensures sorted(a, a.Length)\n //ensures a[..] == old(a)[..]\n ensures 0 <= index <= a.Length\n //ensures forall i :: 0 <= i < index ==> a[i] <= x\n //ensures forall i :: index <= i < a.Length ==> a[i] >= x\n\n ensures index > 0 ==> a[index-1] <= x\n ensures index < a.Length ==> a[index] >= x\n{\n var low, high := 0, a.Length;\n while low < high \n\n {\n var mid := low + (high - low) / 2;\n if {\n case a[mid] < x => low := mid + 1;\n case a[mid] > x => high := mid;\n case a[mid] == x => return mid;\n }\n }\n return low;\n}\n\n// Simple test cases to check the post-condition\nmethod testBinarySearch() {\n var a := new int[2] [1, 3];\n var id0 := binarySearch(a, 0);\n var id1 := binarySearch(a, 1);\n var id2 := binarySearch(a, 2);\n var id3 := binarySearch(a, 3);\n var id4 := binarySearch(a, 4);\n}\n\n" }, { "test_ID": "255", "test_file": "Metodos_Formais_tmp_tmpbez22nnn_Aula_2_ex1.dfy", "ground_truth": "method Mult(x:nat, y:nat) returns (r: nat)\nensures r == x * y\n{\n var m := x;\n var n := y;\n r:=0;\n\n while m > 0\n invariant m >= 0\n invariant m*n+r == x*y\n {\n r := r + n;\n m := m - 1;\n }\n\n return r;\n}\n", "hints_removed": "method Mult(x:nat, y:nat) returns (r: nat)\nensures r == x * y\n{\n var m := x;\n var n := y;\n r:=0;\n\n while m > 0\n {\n r := r + n;\n m := m - 1;\n }\n\n return r;\n}\n" }, { "test_ID": "256", "test_file": "Metodos_Formais_tmp_tmpbez22nnn_Aula_2_ex2.dfy", "ground_truth": "function Potencia(x: nat, y: nat): nat\n{\n if y == 0\n then 1\n else x * Potencia(x, y-1) \n}\n\nmethod Pot(x: nat, y: nat) returns (r: nat)\nensures r == Potencia(x,y)\n{\n var b := x;\n var e := y;\n r := 1;\n\n while e > 0\n invariant Potencia(b, e) * r == Potencia(x,y)\n {\n r := b * r;\n e := e - 1;\n }\n\n return r;\n}\n", "hints_removed": "function Potencia(x: nat, y: nat): nat\n{\n if y == 0\n then 1\n else x * Potencia(x, y-1) \n}\n\nmethod Pot(x: nat, y: nat) returns (r: nat)\nensures r == Potencia(x,y)\n{\n var b := x;\n var e := y;\n r := 1;\n\n while e > 0\n {\n r := b * r;\n e := e - 1;\n }\n\n return r;\n}\n" }, { "test_ID": "257", "test_file": "Metodos_Formais_tmp_tmpbez22nnn_Aula_4_ex1.dfy", "ground_truth": "predicate Par(n:int)\n{\n n % 2 == 0\n}\n\nmethod FazAlgo (a:int, b:int) returns (x:int, y:int)\nrequires a >= b && Par (a-b)\n{\n x := a;\n y := b;\n while x != y\n invariant x >= y\n invariant Par(x-y)\n decreases x-y\n {\n x := x - 1;\n y := y + 1;\n }\n}\n", "hints_removed": "predicate Par(n:int)\n{\n n % 2 == 0\n}\n\nmethod FazAlgo (a:int, b:int) returns (x:int, y:int)\nrequires a >= b && Par (a-b)\n{\n x := a;\n y := b;\n while x != y\n {\n x := x - 1;\n y := y + 1;\n }\n}\n" }, { "test_ID": "258", "test_file": "Metodos_Formais_tmp_tmpbez22nnn_Aula_4_ex3.dfy", "ground_truth": "function Fib(n:nat):nat\n{\n if n < 2\n then n\n else Fib(n-2) + Fib(n-1)\n}\n\nmethod ComputeFib(n:nat) returns (x:nat)\nensures x == Fib(n)\n{\n var i := 0;\n x := 0;\n var y := 1;\n while i < n\n decreases n - i\n invariant 0 <= i <= n\n invariant x == Fib(i)\n invariant y == Fib(i+1)\n {\n x, y := y, x + y;\n i := i + 1;\n }\n}\n\nmethod Teste()\n{\n var n := 3;\n var f := ComputeFib(n);\n assert f == 2;\n}\n", "hints_removed": "function Fib(n:nat):nat\n{\n if n < 2\n then n\n else Fib(n-2) + Fib(n-1)\n}\n\nmethod ComputeFib(n:nat) returns (x:nat)\nensures x == Fib(n)\n{\n var i := 0;\n x := 0;\n var y := 1;\n while i < n\n {\n x, y := y, x + y;\n i := i + 1;\n }\n}\n\nmethod Teste()\n{\n var n := 3;\n var f := ComputeFib(n);\n}\n" }, { "test_ID": "259", "test_file": "Metodos_Formais_tmp_tmpql2hwcsh_Arrays_explicacao.dfy", "ground_truth": "// Array = visualiza\u00e7\u00e3o de um array\n// Uma busca ordenada em um array\n// Buscar: ArrayxZ -> Z (Z \u00e9 inteiro)\n// Pr\u00e9: True (pr\u00e9-condi\u00e7\u00e3o \u00e9 sempre verdadeira)\n// Pos: R < 0 => Para todo i pertencente aos naturais(0 <= i < A.length => A[i] != X) e\n// 0 <= R < A.length => A[R] = x \n//\n// m\u00e9todo em qualquer linguagem:\n// R = 0\n// Enquanto(R < |A|) {\n// Se (A[R] == X) retorne E\n// R = R + 1\n// }\n// retorne -1 \n// \n// X | R | |A|\n// 10 | 0 | 5\n// 10 | 1 | 5\n// 10 | 2 | \n// invariante detectada: 0 <= R <= |A| e Para todo i pertencente aos naturais(0 <= i < R => A[i] != X)\n\n// no dafy\n// forall = \u00e9 o para todo logico\n// :: \u00e9 igual ao tal que l\u00f3gico\n// ==> \u00e9 o ent\u00e3o l\u00f3gico\n// forall i :: 0 <= i < a.Length ==> a[i] != x (para todo i tal que i e maior ou igual a zero e menor que o tamanho do array, ent\u00e3o a posi\u00e7\u00e3o i do array a \u00e9 diferente de x)\n\nmethod buscar(a:array, x:int) returns (r:int)\n ensures r < 0 ==> forall i :: 0 <= i < a.Length ==> a[i] != x\n ensures 0 <= r < a.Length ==> a[r] == x\n{\n r := 0;\n while r < a.Length\n decreases a.Length - r //variante, decrescendo a cada passo com o r\n invariant 0 <= r <= a.Length //a invariante \u00e9 quando nao \u00e9 encontado o x depois de rodado todo o projeto\n invariant forall i :: 0 <= i < r ==> a[i] != x\n {\n if a[r] == x\n {\n return r;\n }\n r := r + 1;\n }\n return -1;\n}\n\n", "hints_removed": "// Array = visualiza\u00e7\u00e3o de um array\n// Uma busca ordenada em um array\n// Buscar: ArrayxZ -> Z (Z \u00e9 inteiro)\n// Pr\u00e9: True (pr\u00e9-condi\u00e7\u00e3o \u00e9 sempre verdadeira)\n// Pos: R < 0 => Para todo i pertencente aos naturais(0 <= i < A.length => A[i] != X) e\n// 0 <= R < A.length => A[R] = x \n//\n// m\u00e9todo em qualquer linguagem:\n// R = 0\n// Enquanto(R < |A|) {\n// Se (A[R] == X) retorne E\n// R = R + 1\n// }\n// retorne -1 \n// \n// X | R | |A|\n// 10 | 0 | 5\n// 10 | 1 | 5\n// 10 | 2 | \n// invariante detectada: 0 <= R <= |A| e Para todo i pertencente aos naturais(0 <= i < R => A[i] != X)\n\n// no dafy\n// forall = \u00e9 o para todo logico\n// :: \u00e9 igual ao tal que l\u00f3gico\n// ==> \u00e9 o ent\u00e3o l\u00f3gico\n// forall i :: 0 <= i < a.Length ==> a[i] != x (para todo i tal que i e maior ou igual a zero e menor que o tamanho do array, ent\u00e3o a posi\u00e7\u00e3o i do array a \u00e9 diferente de x)\n\nmethod buscar(a:array, x:int) returns (r:int)\n ensures r < 0 ==> forall i :: 0 <= i < a.Length ==> a[i] != x\n ensures 0 <= r < a.Length ==> a[r] == x\n{\n r := 0;\n while r < a.Length\n {\n if a[r] == x\n {\n return r;\n }\n r := r + 1;\n }\n return -1;\n}\n\n" }, { "test_ID": "260", "test_file": "Metodos_Formais_tmp_tmpql2hwcsh_Arrays_somatorioArray.dfy", "ground_truth": "// Deve ser criado uma fun\u00e7\u00e3o explicando o que \u00e9 um somat\u00f3rio\n// Somatorio: Array -> N\n// Pre: True\n// Pos: Somatorio(A) = somat\u00f3rio de i = 0 at\u00e9 |A|-1 os valores das posi\u00e7\u00f5es do array pelo i\n//\n\n// function \u00e9 uma f\u00f3rmula matem\u00e1tica, ele n\u00e3o possui variaveis globais\n// Soma: ArrayxN -> N\n// { Soma(A,0) = A[0]\n// { Soma(A,i) = A[i] + soma(A, i-1) , se i > 0\n// Teste\n// |A| = 4\n// Soma(A, |A|-1) = Soma(A,3)\n// A[3] + Soma(A,2)\n// A[3] + A[2] + Soma(A,1)\n// A[3] + A[2] + A[1] + Soma(A,0)\n// A[3] + A[2] + A[1] + A[0]\nfunction soma(a:array, i:nat):nat\n requires i <= a.Length //Tem que dizer que o i s\u00f3 vai at\u00e9 um valor antes do tamanho do array\n reads a //serve para dizer que est\u00e1 sendo lido da memoria o array a (\u00e1reas de mem\u00f3ria)\n{\n if i == 0\n then 0\n else a[i-1] + soma(a,i-1)\n}\n\n\nmethod somatorio(a:array) returns (s:nat)\n ensures s == soma(a, a.Length)\n{\n s := 0;\n for i := 0 to a.Length\n invariant s == soma(a,i)\n {\n s := s + a[i];\n }\n}\n", "hints_removed": "// Deve ser criado uma fun\u00e7\u00e3o explicando o que \u00e9 um somat\u00f3rio\n// Somatorio: Array -> N\n// Pre: True\n// Pos: Somatorio(A) = somat\u00f3rio de i = 0 at\u00e9 |A|-1 os valores das posi\u00e7\u00f5es do array pelo i\n//\n\n// function \u00e9 uma f\u00f3rmula matem\u00e1tica, ele n\u00e3o possui variaveis globais\n// Soma: ArrayxN -> N\n// { Soma(A,0) = A[0]\n// { Soma(A,i) = A[i] + soma(A, i-1) , se i > 0\n// Teste\n// |A| = 4\n// Soma(A, |A|-1) = Soma(A,3)\n// A[3] + Soma(A,2)\n// A[3] + A[2] + Soma(A,1)\n// A[3] + A[2] + A[1] + Soma(A,0)\n// A[3] + A[2] + A[1] + A[0]\nfunction soma(a:array, i:nat):nat\n requires i <= a.Length //Tem que dizer que o i s\u00f3 vai at\u00e9 um valor antes do tamanho do array\n reads a //serve para dizer que est\u00e1 sendo lido da memoria o array a (\u00e1reas de mem\u00f3ria)\n{\n if i == 0\n then 0\n else a[i-1] + soma(a,i-1)\n}\n\n\nmethod somatorio(a:array) returns (s:nat)\n ensures s == soma(a, a.Length)\n{\n s := 0;\n for i := 0 to a.Length\n {\n s := s + a[i];\n }\n}\n" }, { "test_ID": "261", "test_file": "Metodos_Formais_tmp_tmpql2hwcsh_Invariantes_fatorial2.dfy", "ground_truth": "function Fat(n:nat):nat\n{\n if n == 0 then 1 else n*Fat(n-1)\n}\n\nmethod Fatorial(n:nat) returns (f:nat)\nensures f == Fat(n)\n{\n f := 1;\n var i := 1;\n while i <= n\n decreases n-i //variante\n invariant 1 <= i <= n+1 //invariante\n invariant f == Fat(i-1) //invariante\n {\n f := f * i;\n i := i + 1;\n }\n return f;\n}\n\n// i | n | variante\n// 1 | 3 | 2\n// 2 | 3 | 1\n// 3 | 3 | 0\n// 4 | 3 | -1\n// variante = n - i\n// ent\u00e3o \u00e9 usado o decreases n-1\n", "hints_removed": "function Fat(n:nat):nat\n{\n if n == 0 then 1 else n*Fat(n-1)\n}\n\nmethod Fatorial(n:nat) returns (f:nat)\nensures f == Fat(n)\n{\n f := 1;\n var i := 1;\n while i <= n\n {\n f := f * i;\n i := i + 1;\n }\n return f;\n}\n\n// i | n | variante\n// 1 | 3 | 2\n// 2 | 3 | 1\n// 3 | 3 | 0\n// 4 | 3 | -1\n// variante = n - i\n// ent\u00e3o \u00e9 usado o decreases n-1\n" }, { "test_ID": "262", "test_file": "Metodos_Formais_tmp_tmpql2hwcsh_Invariantes_fibonacci.dfy", "ground_truth": "// Provando fibonacci\nfunction Fib(n:nat):nat\n{\n if n < 2\n then n\n else Fib(n-2) + Fib(n-1)\n}\n\nmethod ComputeFib(n:nat) returns (x:nat)\nensures x == Fib(n)\n{\n var i := 0;\n x := 0;\n var y := 1;\n while i < n\n decreases n-i\n invariant 0 <= i <= n\n invariant x == Fib(i)\n invariant y == Fib(i+1)\n {\n x, y := y, x + y; //multiplas atribui\u00e7\u00f5es\n i := i + 1;\n }\n}\n\n// Fibonnaci\n// n | Fib\n// 0 | 0\n// 1 | 1\n// 2 | 1\n// 3 | 2\n// 4 | 3\n// 5 | 5\n// Teste da computa\u00e7\u00e3o do Fibonnaci\n// i | n | x | y | n-1\n// 0 | 3 | 0 | 1 | 3\n// 1 | 3 | 1 | 1 | 2\n// 2 | 3 | 1 | 2 | 1\n// 3 | 3 | 2 | 3 | 0\n// Variante: n - 1\n// Invariante: x = Fib(i) = x sempre \u00e9 o resultado do fibonnaci do valor de i\n// Invariante: 0 <= i <= n = i deve ter um valor entre 0 e o valor de n\n// Invariante: y = Fib(i+1) = o valor de y sempre vai ser o valor de fibonnaci mais um\n\n", "hints_removed": "// Provando fibonacci\nfunction Fib(n:nat):nat\n{\n if n < 2\n then n\n else Fib(n-2) + Fib(n-1)\n}\n\nmethod ComputeFib(n:nat) returns (x:nat)\nensures x == Fib(n)\n{\n var i := 0;\n x := 0;\n var y := 1;\n while i < n\n {\n x, y := y, x + y; //multiplas atribui\u00e7\u00f5es\n i := i + 1;\n }\n}\n\n// Fibonnaci\n// n | Fib\n// 0 | 0\n// 1 | 1\n// 2 | 1\n// 3 | 2\n// 4 | 3\n// 5 | 5\n// Teste da computa\u00e7\u00e3o do Fibonnaci\n// i | n | x | y | n-1\n// 0 | 3 | 0 | 1 | 3\n// 1 | 3 | 1 | 1 | 2\n// 2 | 3 | 1 | 2 | 1\n// 3 | 3 | 2 | 3 | 0\n// Variante: n - 1\n// Invariante: x = Fib(i) = x sempre \u00e9 o resultado do fibonnaci do valor de i\n// Invariante: 0 <= i <= n = i deve ter um valor entre 0 e o valor de n\n// Invariante: y = Fib(i+1) = o valor de y sempre vai ser o valor de fibonnaci mais um\n\n" }, { "test_ID": "263", "test_file": "Metodos_Formais_tmp_tmpql2hwcsh_Invariantes_multiplicador.dfy", "ground_truth": "// Exemplo de invariantes\n// Invariante significa que o valor n\u00e3o muda desde a pr\u00e9-condi\u00e7\u00e3o at\u00e9 a p\u00f3s-condi\u00e7\u00e3o\n\nmethod Mult(x:nat, y:nat) returns (r:nat)\nensures r == x * y\n{\n // par\u00e2metros de entrada s\u00e3o imut\u00e1veis, por isso\n // \u00e9 preciso a atribuir a vari\u00e1veis locais para usar em blocos de c\u00f3digos para mudar\n\n var m := x;\n var n := y;\n\n r := 0;\n while m > 0 \n invariant m >= 0\n invariant m*n+r == x*y\n {\n r := r + n;\n m := m -1;\n }\n return r;\n}\n\n// Teste do m\u00e9todo para encontrar a invariante\n// x | y | m | n | r\n// 5 | 3 | 5 | 3 | 0\n// 5 | 3 | 4 | 3 | 3\n// 5 | 3 | 3 | 3 | 6\n// 5 | 3 | 2 | 3 | 9\n// 5 | 3 | 1 | 3 | 12\n// 5 | 3 | 0 | 3 | 15\n\n// vimos o seguinte:\n// m * n + r = x * y\n// 5 * 3 + 0 (15) = 5 * 3 (15)\n// portanto a f\u00f3rmula m*n+r == x*y \u00e9 uma invariante\n// mas s\u00f3 isso n\u00e3o serve, o m ele \u00e9 maior ou igual a zero quando acaba o while\n// por isso, tamb\u00e9m \u00e9 a invariante que necessita\n// com isso dizemos para o programa as altera\u00e7\u00f5es do m de maior ou igual a zero\n// e mostramos a fun\u00e7\u00e3o encontrada que alterava o valor de m e n das variaveis criadas\n\n// SE OS ALGORITMOS TIVEREM REPETI\u00c7\u00c3O OU RECURS\u00c3O, DEVEM SER MOSTRADOS QUAIS S\u00c3O AS INVARIANTES\n// OU SEJA, OS VALORES QUE N\u00c3O EST\u00c3O SENDO MUDADOS E COLOCAR A F\u00d3RMULA DELE COMO ACIMA\n", "hints_removed": "// Exemplo de invariantes\n// Invariante significa que o valor n\u00e3o muda desde a pr\u00e9-condi\u00e7\u00e3o at\u00e9 a p\u00f3s-condi\u00e7\u00e3o\n\nmethod Mult(x:nat, y:nat) returns (r:nat)\nensures r == x * y\n{\n // par\u00e2metros de entrada s\u00e3o imut\u00e1veis, por isso\n // \u00e9 preciso a atribuir a vari\u00e1veis locais para usar em blocos de c\u00f3digos para mudar\n\n var m := x;\n var n := y;\n\n r := 0;\n while m > 0 \n {\n r := r + n;\n m := m -1;\n }\n return r;\n}\n\n// Teste do m\u00e9todo para encontrar a invariante\n// x | y | m | n | r\n// 5 | 3 | 5 | 3 | 0\n// 5 | 3 | 4 | 3 | 3\n// 5 | 3 | 3 | 3 | 6\n// 5 | 3 | 2 | 3 | 9\n// 5 | 3 | 1 | 3 | 12\n// 5 | 3 | 0 | 3 | 15\n\n// vimos o seguinte:\n// m * n + r = x * y\n// 5 * 3 + 0 (15) = 5 * 3 (15)\n// portanto a f\u00f3rmula m*n+r == x*y \u00e9 uma invariante\n// mas s\u00f3 isso n\u00e3o serve, o m ele \u00e9 maior ou igual a zero quando acaba o while\n// por isso, tamb\u00e9m \u00e9 a invariante que necessita\n// com isso dizemos para o programa as altera\u00e7\u00f5es do m de maior ou igual a zero\n// e mostramos a fun\u00e7\u00e3o encontrada que alterava o valor de m e n das variaveis criadas\n\n// SE OS ALGORITMOS TIVEREM REPETI\u00c7\u00c3O OU RECURS\u00c3O, DEVEM SER MOSTRADOS QUAIS S\u00c3O AS INVARIANTES\n// OU SEJA, OS VALORES QUE N\u00c3O EST\u00c3O SENDO MUDADOS E COLOCAR A F\u00d3RMULA DELE COMO ACIMA\n" }, { "test_ID": "264", "test_file": "Metodos_Formais_tmp_tmpql2hwcsh_Invariantes_potencia.dfy", "ground_truth": "// Pot\u00eancia\n\n// deve ser especificado a pot\u00eancia, porque ele n\u00e3o existe n dafny\n\n// Fun\u00e7\u00e3o recursiva da pot\u00eancia\nfunction Potencia(x:nat, y:nat):nat\n{\n if y == 0\n then 1\n else x * Potencia(x,y-1)\n}\n\n// Quero agora implementar como uma fun\u00e7\u00e3o n\u00e3o recursiva\nmethod Pot(x:nat, y:nat) returns (r:nat)\nensures r == Potencia(x,y)\n{\n r := 1; //sempre r come\u00e7a com 1\n var b := x; //base\n var e := y; //expoente\n\n while e > 0 \n invariant Potencia(b,e)*r == Potencia(x,y) \n {\n r := r * b;\n e := e - 1;\n }\n return r;\n}\n\n// Devemos sempre construir uma tabela para vermos passo a passo o processo\n// POT(2,3)\n// x | y | b | e | r | \n// 2 | 3 | 2 | 3 | 1 |\n// 2 | 3 | 2 | 2 | 1x2 |\n// 2 | 3 | 2 | 1 | 1x2x2 |\n// 2 | 3 | 2 | 0 | 1x2x2x2 |\n// temos que na invariante queremos a f\u00f3rmula x^y\n// INV ... = x^y\n// vendo pelo que foi processado fica dando o seguinte\n// x | y | b | e | r | \n// 2 | 3 | 2 | 3 | 1 (2^0) | 2^3 x 2^0 = 2^3\n// 2 | 3 | 2 | 2 | 1x2 (2^1) | 2^2 x 2^1 = 2^3\n// 2 | 3 | 2 | 1 | 1x2x2 (2^2) | 2^1 x 2^2 = 2^3\n// 2 | 3 | 2 | 0 | 1x2x2x2 (2^3)| 2^0 x 2^3 = 2^3\n// portanto a base est\u00e1 sendo feito a potencia de e (usando o potencia) e multiplicado pelo valor de r\n// b^e * r\n// assim temos a f\u00f3rmula: b^e * r = x^y\n// dai utilizamos a function potencia para construir a f\u00f3rmula\n// Potencia(b,e)*r == Potencia(x,y)\n", "hints_removed": "// Pot\u00eancia\n\n// deve ser especificado a pot\u00eancia, porque ele n\u00e3o existe n dafny\n\n// Fun\u00e7\u00e3o recursiva da pot\u00eancia\nfunction Potencia(x:nat, y:nat):nat\n{\n if y == 0\n then 1\n else x * Potencia(x,y-1)\n}\n\n// Quero agora implementar como uma fun\u00e7\u00e3o n\u00e3o recursiva\nmethod Pot(x:nat, y:nat) returns (r:nat)\nensures r == Potencia(x,y)\n{\n r := 1; //sempre r come\u00e7a com 1\n var b := x; //base\n var e := y; //expoente\n\n while e > 0 \n {\n r := r * b;\n e := e - 1;\n }\n return r;\n}\n\n// Devemos sempre construir uma tabela para vermos passo a passo o processo\n// POT(2,3)\n// x | y | b | e | r | \n// 2 | 3 | 2 | 3 | 1 |\n// 2 | 3 | 2 | 2 | 1x2 |\n// 2 | 3 | 2 | 1 | 1x2x2 |\n// 2 | 3 | 2 | 0 | 1x2x2x2 |\n// temos que na invariante queremos a f\u00f3rmula x^y\n// INV ... = x^y\n// vendo pelo que foi processado fica dando o seguinte\n// x | y | b | e | r | \n// 2 | 3 | 2 | 3 | 1 (2^0) | 2^3 x 2^0 = 2^3\n// 2 | 3 | 2 | 2 | 1x2 (2^1) | 2^2 x 2^1 = 2^3\n// 2 | 3 | 2 | 1 | 1x2x2 (2^2) | 2^1 x 2^2 = 2^3\n// 2 | 3 | 2 | 0 | 1x2x2x2 (2^3)| 2^0 x 2^3 = 2^3\n// portanto a base est\u00e1 sendo feito a potencia de e (usando o potencia) e multiplicado pelo valor de r\n// b^e * r\n// assim temos a f\u00f3rmula: b^e * r = x^y\n// dai utilizamos a function potencia para construir a f\u00f3rmula\n// Potencia(b,e)*r == Potencia(x,y)\n" }, { "test_ID": "265", "test_file": "Prog-Fun-Solutions_tmp_tmp7_gmnz5f_extra_mod.dfy", "ground_truth": "ghost function f(n: nat): nat {\n if n == 0 then 1 \n else if n%2 == 0 then 1 + 2*f(n/2)\n else 2*f(n/2)\n}\n\nmethod mod(n:nat) returns (a:nat) \nensures a == f(n)\n{\n\n var x:nat := 0;\n var y:nat := 1;\n var k:nat := n;\n while k > 0\n invariant f(n) == x + y*f(k)\n invariant 0 <= k <= n\n decreases k\n {\n assert f(n) == x + y*f(k);\n if (k%2 == 0) {\n assert f(n) == x + y*f(k);\n assert f(n) == x + y*(1+2*f(k/2));\n assert f(n) == x + y + 2*y*f(k/2);\n x := x + y;\n assert f(n) == x + 2*y*f(k/2);\n } else {\n assert f(n) == x + y*(2*f(k/2));\n assert f(n) == x + 2*y*f(k/2);\n }\n y := 2*y;\n assert f(n) == x + y*f(k/2);\n k := k/2;\n assert f(n) == x + y*f(k);\n }\n assert k == 0;\n assert f(n) == x+y*f(0);\n assert f(n) == x+y;\n a := x+y;\n}\n\n", "hints_removed": "ghost function f(n: nat): nat {\n if n == 0 then 1 \n else if n%2 == 0 then 1 + 2*f(n/2)\n else 2*f(n/2)\n}\n\nmethod mod(n:nat) returns (a:nat) \nensures a == f(n)\n{\n\n var x:nat := 0;\n var y:nat := 1;\n var k:nat := n;\n while k > 0\n {\n if (k%2 == 0) {\n x := x + y;\n } else {\n }\n y := 2*y;\n k := k/2;\n }\n a := x+y;\n}\n\n" }, { "test_ID": "266", "test_file": "Prog-Fun-Solutions_tmp_tmp7_gmnz5f_extra_mod2.dfy", "ground_truth": "\nghost function f2(n: nat): nat {\n if n == 0 then 0\n else 5*f2(n/3) + n%4\n}\n\nmethod mod2(n:nat) returns (a:nat) \nensures a == f2(n)\n{\n\n var x:nat := 1;\n var y:nat := 0;\n var k:nat := n;\n while k > 0\n invariant f2(n) == x*f2(k) + y\n invariant 0 <= k <= n\n decreases k\n {\n assert f2(n) == x*f2(k) + y;\n assert f2(n) == x*(5*f2(k/3) + k%4) + y;\n assert f2(n) == 5*x*f2(k/3) + x*(k%4) + y;\n y := x*(k%4) + y;\n assert f2(n) == 5*x*f2(k/3) + y;\n x := 5*x;\n assert f2(n) == x*f2(k/3) + y;\n k := k/3;\n assert f2(n) == x*f2(k) + y;\n }\n assert k == 0;\n assert f2(n) == x*f2(0) + y;\n assert f2(n) == x*0 + y;\n assert f2(n) == y;\n a := y;\n}\n", "hints_removed": "\nghost function f2(n: nat): nat {\n if n == 0 then 0\n else 5*f2(n/3) + n%4\n}\n\nmethod mod2(n:nat) returns (a:nat) \nensures a == f2(n)\n{\n\n var x:nat := 1;\n var y:nat := 0;\n var k:nat := n;\n while k > 0\n {\n y := x*(k%4) + y;\n x := 5*x;\n k := k/3;\n }\n a := y;\n}\n" }, { "test_ID": "267", "test_file": "Prog-Fun-Solutions_tmp_tmp7_gmnz5f_extra_pow.dfy", "ground_truth": "ghost function pow(a: int, e: nat): int {\n if e == 0 then 1 else a*pow(a, e-1)\n}\n\nmethod Pow(a: nat, n: nat) returns (y: nat)\nensures y == pow(a, n)\n{\n\n var x:nat := 1;\n var k:nat := 0;\n while k < n\n invariant x == pow(a, k)\n invariant 0 <= k <= n\n decreases n-k\n {\n assert x == pow(a, k);\n x := a*x;\n assert x == a*pow(a, k);\n assert x == pow(a, k+1);\n \n k := k + 1;\n assert x == pow(a, k);\n\n }\n assert k == n;\n y := x;\n assert y == pow(a, n);\n\n}\n", "hints_removed": "ghost function pow(a: int, e: nat): int {\n if e == 0 then 1 else a*pow(a, e-1)\n}\n\nmethod Pow(a: nat, n: nat) returns (y: nat)\nensures y == pow(a, n)\n{\n\n var x:nat := 1;\n var k:nat := 0;\n while k < n\n {\n x := a*x;\n \n k := k + 1;\n\n }\n y := x;\n\n}\n" }, { "test_ID": "268", "test_file": "Prog-Fun-Solutions_tmp_tmp7_gmnz5f_extra_sum.dfy", "ground_truth": "\n\nghost function sum(n: nat): int\n{\n if n == 0 then 0 else n + sum(n - 1)\n}\n\nmethod Sum(n: nat) returns (s: int)\nensures s == sum(n)\n{\n\n var x:nat := 0;\n var y:nat := 1;\n var k:nat := n;\n while k > 0\n invariant sum(n) == x + y*sum(k)\n invariant 0 <= k <= n\n decreases k\n {\n assert sum(n) == x + y*sum(k);\n assert sum(n) == x + y*(k+sum(k-1));\n assert sum(n) == x + y*k + y*sum(k-1);\n x := x + y*k;\n assert sum(n) == x + y*sum(k-1);\n \n assert sum(n) == x + y*sum(k-1);\n k := k-1;\n assert sum(n) == x + y*sum(k);\n }\n assert k == 0;\n assert sum(n) == x + y*sum(0);\n assert sum(n) == x + y*0;\n s := x;\n assert sum(n) == s;\n\n}\n", "hints_removed": "\n\nghost function sum(n: nat): int\n{\n if n == 0 then 0 else n + sum(n - 1)\n}\n\nmethod Sum(n: nat) returns (s: int)\nensures s == sum(n)\n{\n\n var x:nat := 0;\n var y:nat := 1;\n var k:nat := n;\n while k > 0\n {\n x := x + y*k;\n \n k := k-1;\n }\n s := x;\n\n}\n" }, { "test_ID": "269", "test_file": "Prog-Fun-Solutions_tmp_tmp7_gmnz5f_mockExam2_p2.dfy", "ground_truth": "// problem 2:\n// name: Gabriele Berardi\n// s-number: s4878728\n// table: XXX\n\nmethod problem2(p:int, q:int, X:int, Y:int) returns (r:int, s:int)\nrequires p == 2*X + Y && q == X + 3\nensures r == X && s == Y\n{\n assert p == 2*X + Y && q == X + 3;\n r, s := p, q;\n assert r == 2*X + Y && s == X + 3;\n r := r - 2*s + 6;\n assert r == 2*X + Y-2*X-6 + 6 && s == X + 3;\n assert r == Y && s == X + 3;\n s := s - 3;\n assert r == Y && s == X;\n r,s := s, r;\n assert s == Y && r == X;\n\n\n}\n\n", "hints_removed": "// problem 2:\n// name: Gabriele Berardi\n// s-number: s4878728\n// table: XXX\n\nmethod problem2(p:int, q:int, X:int, Y:int) returns (r:int, s:int)\nrequires p == 2*X + Y && q == X + 3\nensures r == X && s == Y\n{\n r, s := p, q;\n r := r - 2*s + 6;\n s := s - 3;\n r,s := s, r;\n\n\n}\n\n" }, { "test_ID": "270", "test_file": "Prog-Fun-Solutions_tmp_tmp7_gmnz5f_mockExam2_p3.dfy", "ground_truth": "// problem 3:\n// name: ....... (fill in your name)\n// s-number: s....... (fill in your student number)\n// table: ....... (fill in your table number)\n\nmethod problem3(m:int, X:int) returns (r:int)\nrequires X >= 0 && (2*m == 1 - X || m == X + 3)\nensures r == X\n{\n assert X >= 0 && (X == 1 - 2*m || m-3 == X);\n r := m;\n assert X >= 0 && (1 - 2*r >= 0 || r-3 >= 0);\n\n if (1-2*r >= 0) {\n assert X >= 0 && 2*r == 1-X;\n r := 2*r;\n assert X >= 0 && r == 1-X;\n r := -r+1;\n } else {\n assert r == X + 3;\n r := r -3;\n }\n assert r == X;\n\n}\n\n", "hints_removed": "// problem 3:\n// name: ....... (fill in your name)\n// s-number: s....... (fill in your student number)\n// table: ....... (fill in your table number)\n\nmethod problem3(m:int, X:int) returns (r:int)\nrequires X >= 0 && (2*m == 1 - X || m == X + 3)\nensures r == X\n{\n r := m;\n\n if (1-2*r >= 0) {\n r := 2*r;\n r := -r+1;\n } else {\n r := r -3;\n }\n\n}\n\n" }, { "test_ID": "271", "test_file": "Prog-Fun-Solutions_tmp_tmp7_gmnz5f_mockExam2_p5.dfy", "ground_truth": "// problem 5:\n// name: Gabriele Berardi\n// s-number: s4878728\n// table: XXXX\n\nghost function f(n: int): int {\n if n < 0 then 0 else 3*f(n-5) + n\n}\n\nmethod problem5(n:nat) returns (x: int)\nensures x == f(n)\n{\n\n var a := 1;\n var b := 0;\n var k := n;\n while k >= 0\n invariant f(n) == a*f(k) + b\n invariant -5 <= k <= n\n decreases k\n {\n assert f(n) == a*f(k) + b;\n assert f(n) == a*(3*f(k-5)+k) + b;\n\n assert f(n) == 3*a*f(k-5) + a*k + b;\n b := a*k + b;\n assert f(n) == 3*a*f(k-5) + b;\n a := 3*a;\n assert f(n) == a*f(k-5) + b;\n k := k - 5;\n assert f(n) == a*f(k) + b;\n }\n \n assert k < 0;\n assert f(n) == a*f(k) + b;\n assert f(n) == a*0 + b;\n x := b;\n assert x== f(n);\n\n}\n", "hints_removed": "// problem 5:\n// name: Gabriele Berardi\n// s-number: s4878728\n// table: XXXX\n\nghost function f(n: int): int {\n if n < 0 then 0 else 3*f(n-5) + n\n}\n\nmethod problem5(n:nat) returns (x: int)\nensures x == f(n)\n{\n\n var a := 1;\n var b := 0;\n var k := n;\n while k >= 0\n {\n\n b := a*k + b;\n a := 3*a;\n k := k - 5;\n }\n \n x := b;\n\n}\n" }, { "test_ID": "272", "test_file": "Prog-Fun-Solutions_tmp_tmp7_gmnz5f_mockExam2_p6.dfy", "ground_truth": "// problem 6:\n// name: Gabriele Berardi\n// s-number: s4878728\n// table: XXXXX\n\nghost function f(n: int): int {\n if n <= 0 then 1 else n + f(n-1)*f(n-2)\n}\n\nghost function fSum(n: nat): int {\n // give the body of this function\n // it should return Sum(i: 0<=i < n: f(i))\n if n <= 0 then 0 else f(n-1) + fSum(n-1)\n}\n\nmethod problem6(n:nat) returns (a: int)\nensures a == fSum(n)\n{\n a := 0;\n var k := 0;\n var x := 1;\n var y := 2;\n while k < n\n invariant 0 <= k <= n && x == f(k) && y == f(k+1) && a == fSum(k)\n decreases n-k\n {\n assert x == f(k) && y == f(k+1) && a == fSum(k);\n k := k + 1;\n assert x == f(k-1) && y == f(k) && a == fSum(k-1);\n assert x == f(k-1) && y == f(k) && a == fSum(k) - f(k-1);\n a := a + x;\n assert x == f(k-1) && y == f(k) && a == fSum(k) - f(k-1) + f(k-1);\n assert x == f(k-1) && y == f(k) && a == fSum(k);\n\n x, y := y, k+1 + x*y; \n assert x == f(k) && y == k+1+f(k-1)*f(k) && a == fSum(k);\n assert x == f(k) && y == k+1+f(k+1-2)*f(k+1-1) && a == fSum(k);\n assert x == f(k) && y == f(k+1) && a == fSum(k);\n }\n assert a == fSum(k);\n}\n\n", "hints_removed": "// problem 6:\n// name: Gabriele Berardi\n// s-number: s4878728\n// table: XXXXX\n\nghost function f(n: int): int {\n if n <= 0 then 1 else n + f(n-1)*f(n-2)\n}\n\nghost function fSum(n: nat): int {\n // give the body of this function\n // it should return Sum(i: 0<=i < n: f(i))\n if n <= 0 then 0 else f(n-1) + fSum(n-1)\n}\n\nmethod problem6(n:nat) returns (a: int)\nensures a == fSum(n)\n{\n a := 0;\n var k := 0;\n var x := 1;\n var y := 2;\n while k < n\n {\n k := k + 1;\n a := a + x;\n\n x, y := y, k+1 + x*y; \n }\n}\n\n" }, { "test_ID": "273", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_advanced examples_ArrayMap.dfy", "ground_truth": "// RUN: /print:log.bpl\n\nmethod ArrayMap(f: int -> A, a: array)\n requires a != null\n requires forall j :: 0 <= j < a.Length ==> f.requires(j)\n requires forall j :: 0 <= j < a.Length ==> a !in f.reads(j)\n modifies a\n ensures forall j :: 0 <= j < a.Length ==> a[j] == f(j)\n{\n var i := 0;\n while i < a.Length\n invariant 0 <= i <= a.Length;\n invariant forall j :: 0 <= j < i ==> a[j] == f(j)\n {\n a[i] := f(i);\n i := i + 1;\n }\n}\n\n\n/*method GenericSort(cmp: (A, A) -> bool, a: array)\n requires a != null\n requires forall x, y :: a !in cmp.reads(x, y)\n requires forall x, y :: cmp.requires(x, y)\n modifies a\n ensures forall x, y :: cmp.requires(x, y)\n ensures forall x, y :: 0 <= x < y < a.Length ==> cmp(a[x], a[y])\n{\n\n var i := 0;\n\n while i < a.Length\n modifies a\n {\n var j := i - 1;\n while j >= 0 && !cmp(a[j], a[i])\n modifies a\n {\n a[i], a[j] := a[j], a[i];\n j := j - 1;\n }\n\n i := i + 1;\n }\n\n}*/\n\n", "hints_removed": "// RUN: /print:log.bpl\n\nmethod ArrayMap(f: int -> A, a: array)\n requires a != null\n requires forall j :: 0 <= j < a.Length ==> f.requires(j)\n requires forall j :: 0 <= j < a.Length ==> a !in f.reads(j)\n modifies a\n ensures forall j :: 0 <= j < a.Length ==> a[j] == f(j)\n{\n var i := 0;\n while i < a.Length\n {\n a[i] := f(i);\n i := i + 1;\n }\n}\n\n\n/*method GenericSort(cmp: (A, A) -> bool, a: array)\n requires a != null\n requires forall x, y :: a !in cmp.reads(x, y)\n requires forall x, y :: cmp.requires(x, y)\n modifies a\n ensures forall x, y :: cmp.requires(x, y)\n ensures forall x, y :: 0 <= x < y < a.Length ==> cmp(a[x], a[y])\n{\n\n var i := 0;\n\n while i < a.Length\n modifies a\n {\n var j := i - 1;\n while j >= 0 && !cmp(a[j], a[i])\n modifies a\n {\n a[i], a[j] := a[j], a[i];\n j := j - 1;\n }\n\n i := i + 1;\n }\n\n}*/\n\n" }, { "test_ID": "274", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_advanced examples_EvenPredicate.dfy", "ground_truth": "// RUN: /compile:0 /nologo\n\nfunction IsEven(a : int) : bool\n requires a >= 0\n{\n if a == 0 then true \n else if a == 1 then false \n else IsEven(a - 2)\n}\n\nlemma EvenSquare(a : int)\nrequires a >= 0\nensures IsEven(a) ==> IsEven(a * a)\n{\n if a >= 2 && IsEven(a) {\n EvenSquare(a - 2);\n assert a * a == (a - 2) * (a - 2) + 4 * a - 4;\n EvenDouble(2 * a - 2);\n EvenPlus((a - 2) * (a - 2), 4 * a - 4);\n }\n}\n\nlemma EvenDouble(a: int)\n requires a >= 0\n ensures IsEven(a + a)\n{\n if a >= 2 {\n EvenDouble(a - 2);\n }\n}\n\nlemma {:induction x} EvenPlus(x: int, y: int)\n requires x >= 0\n requires y >= 0\n requires IsEven(x)\n requires IsEven(y)\n ensures IsEven(x + y)\n{\n if x >= 2 {\n EvenPlus(x - 2, y);\n }\n}\n\n\n/*\nlemma {:induction x} EvenTimes(x: int, y: int)\n requires x >= 0\n requires y >= 0\n requires IsEven(x)\n requires IsEven(y)\n ensures IsEven(x * y)\n{\n if x >= 2 {\n calc {\n IsEven(x * y);\n IsEven((x - 2) * y + 2 * y); { Check1(y); EvenPlus((x - 2) * y, 2 * y); }\n true;\n }\n }\n}\n*/\n\n", "hints_removed": "// RUN: /compile:0 /nologo\n\nfunction IsEven(a : int) : bool\n requires a >= 0\n{\n if a == 0 then true \n else if a == 1 then false \n else IsEven(a - 2)\n}\n\nlemma EvenSquare(a : int)\nrequires a >= 0\nensures IsEven(a) ==> IsEven(a * a)\n{\n if a >= 2 && IsEven(a) {\n EvenSquare(a - 2);\n EvenDouble(2 * a - 2);\n EvenPlus((a - 2) * (a - 2), 4 * a - 4);\n }\n}\n\nlemma EvenDouble(a: int)\n requires a >= 0\n ensures IsEven(a + a)\n{\n if a >= 2 {\n EvenDouble(a - 2);\n }\n}\n\nlemma {:induction x} EvenPlus(x: int, y: int)\n requires x >= 0\n requires y >= 0\n requires IsEven(x)\n requires IsEven(y)\n ensures IsEven(x + y)\n{\n if x >= 2 {\n EvenPlus(x - 2, y);\n }\n}\n\n\n/*\nlemma {:induction x} EvenTimes(x: int, y: int)\n requires x >= 0\n requires y >= 0\n requires IsEven(x)\n requires IsEven(y)\n ensures IsEven(x * y)\n{\n if x >= 2 {\n calc {\n IsEven(x * y);\n IsEven((x - 2) * y + 2 * y); { Check1(y); EvenPlus((x - 2) * y, 2 * y); }\n true;\n }\n }\n}\n*/\n\n" }, { "test_ID": "275", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_advanced examples_GenericMax.dfy", "ground_truth": "method GenericMax(cmp: (A, A) -> bool, a: array) returns (max: A)\n requires a != null && a.Length > 0\n requires forall x, y :: cmp.requires(x, y)\n requires forall x, y :: cmp(x, y) || cmp(y, x);\n requires forall x, y, z :: cmp(x, y) && cmp(y, z) ==> cmp(x, z);\n\n ensures forall x :: 0 <= x < a.Length ==>\n // uncommenting the following line causes the program to verify\n // assume cmp.requires(a[x], max);\n cmp(a[x], max)\n{\n max := a[0];\n var i := 0;\n while i < a.Length\n invariant 0 <= i <= a.Length\n invariant forall x :: 0 <= x < i ==> cmp(a[x], max)\n {\n if !cmp(a[i], max) {\n max := a[i];\n }\n i := i + 1;\n }\n}\n\n", "hints_removed": "method GenericMax(cmp: (A, A) -> bool, a: array) returns (max: A)\n requires a != null && a.Length > 0\n requires forall x, y :: cmp.requires(x, y)\n requires forall x, y :: cmp(x, y) || cmp(y, x);\n requires forall x, y, z :: cmp(x, y) && cmp(y, z) ==> cmp(x, z);\n\n ensures forall x :: 0 <= x < a.Length ==>\n // uncommenting the following line causes the program to verify\n // assume cmp.requires(a[x], max);\n cmp(a[x], max)\n{\n max := a[0];\n var i := 0;\n while i < a.Length\n {\n if !cmp(a[i], max) {\n max := a[i];\n }\n i := i + 1;\n }\n}\n\n" }, { "test_ID": "276", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_advanced examples_InsertionSort.dfy", "ground_truth": " predicate sorted (a:array, start:int, end:int) // all \"before\" end are sorted \n requires a!=null \n requires 0<=start<=end<=a.Length \n reads a \n { \n forall j,k:: start<=j a[j]<=a[k]\n }\n\n\nmethod InsertionSort (a:array)\nrequires a!=null && a.Length>1 \nensures sorted(a, 0, a.Length) \nmodifies a\n{ \n var up := 1; \n \n while (up < a.Length) // outer loop \n invariant 1 <= up <= a.Length \n invariant sorted(a,0,up)\n { \n var down := up-1; \n var temp := a[up]; \n while down >= 0 && a[down+1] < a[down] // inner loop\n invariant forall j,k | 0 <= j < k < up+1 && k != down+1 :: a[j]<=a[k]\n {\n a[down],a[down+1] := a[down+1],a[down]; \n down := down-1; \n } \n up := up+1;\n \n }\n} \nmethod Main(){\n var a := new int[5];\n a[0],a[1],a[2],a[3],a[4] := 3,2,5,1,8;\n InsertionSort(a);\n print a[..];\n}\n\n", "hints_removed": " predicate sorted (a:array, start:int, end:int) // all \"before\" end are sorted \n requires a!=null \n requires 0<=start<=end<=a.Length \n reads a \n { \n forall j,k:: start<=j a[j]<=a[k]\n }\n\n\nmethod InsertionSort (a:array)\nrequires a!=null && a.Length>1 \nensures sorted(a, 0, a.Length) \nmodifies a\n{ \n var up := 1; \n \n while (up < a.Length) // outer loop \n { \n var down := up-1; \n var temp := a[up]; \n while down >= 0 && a[down+1] < a[down] // inner loop\n {\n a[down],a[down+1] := a[down+1],a[down]; \n down := down-1; \n } \n up := up+1;\n \n }\n} \nmethod Main(){\n var a := new int[5];\n a[0],a[1],a[2],a[3],a[4] := 3,2,5,1,8;\n InsertionSort(a);\n print a[..];\n}\n\n" }, { "test_ID": "277", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_advanced examples_MatrixMultiplication.dfy", "ground_truth": "function RowColumnProduct(m1: array2, m2: array2, row: nat, column: nat): int\n reads m1\n reads m2\n requires m1 != null && m2 != null && m1.Length1 == m2.Length0\n requires row < m1.Length0 && column < m2.Length1\n{\n RowColumnProductFrom(m1, m2, row, column, 0)\n}\n\nfunction RowColumnProductFrom(m1: array2, m2: array2, row: nat, column: nat, k: nat): int\n reads m1\n reads m2\n requires m1 != null && m2 != null && k <= m1.Length1 == m2.Length0\n requires row < m1.Length0 && column < m2.Length1\n decreases m1.Length1 - k\n{\n if k == m1.Length1 then\n 0\n else\n m1[row,k]*m2[k,column] + RowColumnProductFrom(m1, m2, row, column, k+1)\n}\n\nmethod multiply(m1: array2, m2: array2) returns (m3: array2)\n requires m1 != null && m2 != null\n requires m1.Length1 == m2.Length0\n ensures m3 != null && m3.Length0 == m1.Length0 && m3.Length1 == m2.Length1\n ensures forall i, j | 0 <= i < m3.Length0 && 0 <= j < m3.Length1 ::\n m3[i, j] == RowColumnProduct(m1, m2, i, j)\n{\n m3 := new int[m1.Length0, m2.Length1];\n var i := 0;\n while i < m1.Length0\n invariant 0 <= i <= m1.Length0\n invariant forall i', j' | 0 <= i' < i && 0 <= j' < m2.Length1 ::\n m3[i',j'] == RowColumnProduct(m1, m2, i', j')\n {\n var j := 0;\n\n while j < m2.Length1\n invariant 0 <= j <= m2.Length1\n invariant forall i', j' | 0 <= i' < i && 0 <= j' < m2.Length1 ::\n m3[i',j'] == RowColumnProduct(m1, m2, i', j')\n invariant forall j' | 0 <= j' < j ::\n m3[i,j'] == RowColumnProduct(m1, m2, i, j')\n {\n var k :=0;\n m3[i, j] := 0;\n while k < m1.Length1\n invariant 0 <= k <= m1.Length1\n invariant forall i', j' | 0 <= i' < i && 0 <= j' < m2.Length1 ::\n m3[i',j'] == RowColumnProduct(m1, m2, i', j')\n invariant forall j' | 0 <= j' < j ::\n m3[i,j'] == RowColumnProduct(m1, m2, i, j')\n invariant RowColumnProduct(m1, m2, i, j) ==\n m3[i,j] + RowColumnProductFrom(m1, m2, i, j, k)\n {\n m3[i,j] := m3[i,j] + m1[i,k] * m2[k,j];\n k := k+1; \n\n }\n j := j+1;\n }\n i := i+1;\n }\n}\n\n", "hints_removed": "function RowColumnProduct(m1: array2, m2: array2, row: nat, column: nat): int\n reads m1\n reads m2\n requires m1 != null && m2 != null && m1.Length1 == m2.Length0\n requires row < m1.Length0 && column < m2.Length1\n{\n RowColumnProductFrom(m1, m2, row, column, 0)\n}\n\nfunction RowColumnProductFrom(m1: array2, m2: array2, row: nat, column: nat, k: nat): int\n reads m1\n reads m2\n requires m1 != null && m2 != null && k <= m1.Length1 == m2.Length0\n requires row < m1.Length0 && column < m2.Length1\n{\n if k == m1.Length1 then\n 0\n else\n m1[row,k]*m2[k,column] + RowColumnProductFrom(m1, m2, row, column, k+1)\n}\n\nmethod multiply(m1: array2, m2: array2) returns (m3: array2)\n requires m1 != null && m2 != null\n requires m1.Length1 == m2.Length0\n ensures m3 != null && m3.Length0 == m1.Length0 && m3.Length1 == m2.Length1\n ensures forall i, j | 0 <= i < m3.Length0 && 0 <= j < m3.Length1 ::\n m3[i, j] == RowColumnProduct(m1, m2, i, j)\n{\n m3 := new int[m1.Length0, m2.Length1];\n var i := 0;\n while i < m1.Length0\n m3[i',j'] == RowColumnProduct(m1, m2, i', j')\n {\n var j := 0;\n\n while j < m2.Length1\n m3[i',j'] == RowColumnProduct(m1, m2, i', j')\n m3[i,j'] == RowColumnProduct(m1, m2, i, j')\n {\n var k :=0;\n m3[i, j] := 0;\n while k < m1.Length1\n m3[i',j'] == RowColumnProduct(m1, m2, i', j')\n m3[i,j'] == RowColumnProduct(m1, m2, i, j')\n m3[i,j] + RowColumnProductFrom(m1, m2, i, j, k)\n {\n m3[i,j] := m3[i,j] + m1[i,k] * m2[k,j];\n k := k+1; \n\n }\n j := j+1;\n }\n i := i+1;\n }\n}\n\n" }, { "test_ID": "278", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_advanced examples_Modules.dfy", "ground_truth": "// RUN: /compile:1\n\nabstract module Interface {\n type T\n function F(): T\n predicate P(x: T)\n lemma FP()\n ensures P(F())\n}\n\nmodule Implementation refines Interface {\n predicate P(x: T) {\n false\n }\n\n}\n\nabstract module User {\n import I : Interface\n\n lemma Main()\n ensures I.P(I.F());\n {\n I.FP();\n assert I.P(I.F());\n }\n}\n\nmodule Main refines User {\n import I = Implementation\n\n lemma Main()\n ensures I.P(I.F())\n {\n I.FP();\n assert false;\n }\n}\n\n", "hints_removed": "// RUN: /compile:1\n\nabstract module Interface {\n type T\n function F(): T\n predicate P(x: T)\n lemma FP()\n ensures P(F())\n}\n\nmodule Implementation refines Interface {\n predicate P(x: T) {\n false\n }\n\n}\n\nabstract module User {\n import I : Interface\n\n lemma Main()\n ensures I.P(I.F());\n {\n I.FP();\n }\n}\n\nmodule Main refines User {\n import I = Implementation\n\n lemma Main()\n ensures I.P(I.F())\n {\n I.FP();\n }\n}\n\n" }, { "test_ID": "279", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_advanced examples_OneHundredPrisonersAndALightbulb.dfy", "ground_truth": "// RUN: /compile:0 /nologo\n\nmethod CardinalitySubsetLt(A: set, B: set)\n requires A < B\n ensures |A| < |B|\n decreases B\n{\n var b :| b in B && b !in A;\n var B' := B - {b};\n assert |B| == |B'| + 1;\n if A < B' {\n CardinalitySubsetLt(A, B');\n } else {\n assert A == B';\n }\n}\n\nmethod strategy(P: set, Special: T) returns (count: int)\n requires |P| > 1 && Special in P\n ensures count == |P| - 1\n decreases *\n{\n count := 0;\n var I := {};\n var S := {};\n var switch := false;\n\n while count < |P| - 1\n invariant count <= |P| - 1\n invariant count > 0 ==> Special in I\n invariant Special !in S && S < P && S <= I <= P\n invariant if switch then |S| == count + 1 else |S| == count\n decreases *\n { \n var p :| p in P;\n I := I + {p};\n\n if p == Special {\n if switch {\n switch := false;\n count := count + 1;\n }\n } else {\n if p !in S && !switch {\n S := S + {p};\n switch := true;\n }\n }\n } \n\n CardinalitySubsetLt(S, I);\n\n if I < P {\n CardinalitySubsetLt(I, P);\n }\n assert P <= I;\n\n assert I == P;\n}\n\n", "hints_removed": "// RUN: /compile:0 /nologo\n\nmethod CardinalitySubsetLt(A: set, B: set)\n requires A < B\n ensures |A| < |B|\n{\n var b :| b in B && b !in A;\n var B' := B - {b};\n if A < B' {\n CardinalitySubsetLt(A, B');\n } else {\n }\n}\n\nmethod strategy(P: set, Special: T) returns (count: int)\n requires |P| > 1 && Special in P\n ensures count == |P| - 1\n{\n count := 0;\n var I := {};\n var S := {};\n var switch := false;\n\n while count < |P| - 1\n { \n var p :| p in P;\n I := I + {p};\n\n if p == Special {\n if switch {\n switch := false;\n count := count + 1;\n }\n } else {\n if p !in S && !switch {\n S := S + {p};\n switch := true;\n }\n }\n } \n\n CardinalitySubsetLt(S, I);\n\n if I < P {\n CardinalitySubsetLt(I, P);\n }\n\n}\n\n" }, { "test_ID": "280", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_advanced examples_Percentile.dfy", "ground_truth": "// Sum of elements of A from indices 0 to end.\n// end is inclusive! (not James's normal way of thinking!!)\nfunction SumUpto(A: array, end: int): real\n requires -1 <= end < A.Length\n reads A\n{\n if end == -1 then\n 0.0\n else\n A[end] + SumUpto(A, end-1)\n}\n\nfunction Sum(A: array): real\n reads A\n{\n SumUpto(A, A.Length-1)\n}\n\nmethod Percentile(p: real, A: array, total: real) returns (i: int)\n requires forall i | 0 <= i < A.Length :: A[i] > 0.0\n requires 0.0 <= p <= 100.0\n requires total == Sum(A)\n requires total > 0.0\n ensures -1 <= i < A.Length\n ensures SumUpto(A, i) <= (p/100.0) * total\n ensures i+1 < A.Length ==> SumUpto(A, i+1) > (p/100.0) * total\n{\n i := -1;\n var s: real := 0.0;\n\n while i+1 != A.Length && s + A[i+1] <= (p/100.0) * total\n invariant -1 <= i < A.Length\n invariant s == SumUpto(A, i)\n invariant s <= (p/100.0) * total\n {\n i := i + 1;\n s := s + A[i];\n }\n}\n\n// example showing that, with the original postcondition, the answer is non-unique!\nmethod PercentileNonUniqueAnswer() returns (p: real, A: array, total: real, i1: int, i2: int)\n ensures forall i | 0 <= i < A.Length :: A[i] > 0.0\n ensures 0.0 <= p <= 100.0\n ensures total == Sum(A)\n ensures total > 0.0\n\n ensures -1 <= i1 < A.Length\n ensures SumUpto(A, i1) <= (p/100.0) * total\n ensures i1+1 < A.Length ==> SumUpto(A, i1+1) >= (p/100.0) * total\n\n ensures -1 <= i2 < A.Length\n ensures SumUpto(A, i2) <= (p/100.0) * total\n ensures i2+1 < A.Length ==> SumUpto(A, i2+1) >= (p/100.0) * total\n\n ensures i1 != i2\n{\n p := 100.0;\n A := new real[1];\n A[0] := 1.0;\n total := 1.0;\n assert SumUpto(A, 0) == 1.0;\n i1 := -1;\n i2 := 0;\n}\n\n\n// proof that, with the corrected postcondition, the answer is unique\nlemma PercentileUniqueAnswer(p: real, A: array, total: real, i1: int, i2: int)\n requires forall i | 0 <= i < A.Length :: A[i] > 0.0\n requires 0.0 <= p <= 100.0\n requires total == Sum(A)\n requires total > 0.0\n\n requires -1 <= i1 < A.Length\n requires SumUpto(A, i1) <= (p/100.0) * total\n requires i1+1 < A.Length ==> SumUpto(A, i1+1) > (p/100.0) * total\n\n requires -1 <= i2 < A.Length\n requires SumUpto(A, i2) <= (p/100.0) * total\n requires i2+1 < A.Length ==> SumUpto(A, i2+1) > (p/100.0) * total\n\n decreases if i2 < i1 then 1 else 0 // wlog i1 <= i2\n\n ensures i1 == i2\n{\n if i1+1< i2 {\n SumUpto_increase(A, i1+1, i2);\n }\n}\n// lemma for previous proof: when an array has strictly positive elements, the\n// sums strictly increase left to right\nlemma SumUpto_increase(A: array, end1: int, end2: int)\n requires forall i | 0 <= i < A.Length :: A[i] > 0.0\n requires -1 <= end1 < A.Length\n requires -1 <= end2 < A.Length\n requires end1 < end2\n ensures SumUpto(A, end1) < SumUpto(A, end2)\n{}\n\n", "hints_removed": "// Sum of elements of A from indices 0 to end.\n// end is inclusive! (not James's normal way of thinking!!)\nfunction SumUpto(A: array, end: int): real\n requires -1 <= end < A.Length\n reads A\n{\n if end == -1 then\n 0.0\n else\n A[end] + SumUpto(A, end-1)\n}\n\nfunction Sum(A: array): real\n reads A\n{\n SumUpto(A, A.Length-1)\n}\n\nmethod Percentile(p: real, A: array, total: real) returns (i: int)\n requires forall i | 0 <= i < A.Length :: A[i] > 0.0\n requires 0.0 <= p <= 100.0\n requires total == Sum(A)\n requires total > 0.0\n ensures -1 <= i < A.Length\n ensures SumUpto(A, i) <= (p/100.0) * total\n ensures i+1 < A.Length ==> SumUpto(A, i+1) > (p/100.0) * total\n{\n i := -1;\n var s: real := 0.0;\n\n while i+1 != A.Length && s + A[i+1] <= (p/100.0) * total\n {\n i := i + 1;\n s := s + A[i];\n }\n}\n\n// example showing that, with the original postcondition, the answer is non-unique!\nmethod PercentileNonUniqueAnswer() returns (p: real, A: array, total: real, i1: int, i2: int)\n ensures forall i | 0 <= i < A.Length :: A[i] > 0.0\n ensures 0.0 <= p <= 100.0\n ensures total == Sum(A)\n ensures total > 0.0\n\n ensures -1 <= i1 < A.Length\n ensures SumUpto(A, i1) <= (p/100.0) * total\n ensures i1+1 < A.Length ==> SumUpto(A, i1+1) >= (p/100.0) * total\n\n ensures -1 <= i2 < A.Length\n ensures SumUpto(A, i2) <= (p/100.0) * total\n ensures i2+1 < A.Length ==> SumUpto(A, i2+1) >= (p/100.0) * total\n\n ensures i1 != i2\n{\n p := 100.0;\n A := new real[1];\n A[0] := 1.0;\n total := 1.0;\n i1 := -1;\n i2 := 0;\n}\n\n\n// proof that, with the corrected postcondition, the answer is unique\nlemma PercentileUniqueAnswer(p: real, A: array, total: real, i1: int, i2: int)\n requires forall i | 0 <= i < A.Length :: A[i] > 0.0\n requires 0.0 <= p <= 100.0\n requires total == Sum(A)\n requires total > 0.0\n\n requires -1 <= i1 < A.Length\n requires SumUpto(A, i1) <= (p/100.0) * total\n requires i1+1 < A.Length ==> SumUpto(A, i1+1) > (p/100.0) * total\n\n requires -1 <= i2 < A.Length\n requires SumUpto(A, i2) <= (p/100.0) * total\n requires i2+1 < A.Length ==> SumUpto(A, i2+1) > (p/100.0) * total\n\n\n ensures i1 == i2\n{\n if i1+1< i2 {\n SumUpto_increase(A, i1+1, i2);\n }\n}\n// lemma for previous proof: when an array has strictly positive elements, the\n// sums strictly increase left to right\nlemma SumUpto_increase(A: array, end1: int, end2: int)\n requires forall i | 0 <= i < A.Length :: A[i] > 0.0\n requires -1 <= end1 < A.Length\n requires -1 <= end2 < A.Length\n requires end1 < end2\n ensures SumUpto(A, end1) < SumUpto(A, end2)\n{}\n\n" }, { "test_ID": "281", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_advanced examples_Refinement.dfy", "ground_truth": "// RUN: /nologo /rlimit:10000000 /noNLarith\n\nabstract module Interface {\n function addSome(n: nat): nat\n ensures addSome(n) > n\n}\n\nabstract module Mod {\n import A : Interface\n method m() {\n assert 6 <= A.addSome(5);\n print \"Test\\n\";\n }\n}\n\nmodule Implementation refines Interface {\n function addSome(n: nat): nat\n ensures addSome(n) == n + 1\n {\n n + 1\n }\n}\n\nmodule Mod2 refines Mod {\n import A = Implementation\n}\n\nmethod Main() {\n Mod2.m();\n}\n\n", "hints_removed": "// RUN: /nologo /rlimit:10000000 /noNLarith\n\nabstract module Interface {\n function addSome(n: nat): nat\n ensures addSome(n) > n\n}\n\nabstract module Mod {\n import A : Interface\n method m() {\n print \"Test\\n\";\n }\n}\n\nmodule Implementation refines Interface {\n function addSome(n: nat): nat\n ensures addSome(n) == n + 1\n {\n n + 1\n }\n}\n\nmodule Mod2 refines Mod {\n import A = Implementation\n}\n\nmethod Main() {\n Mod2.m();\n}\n\n" }, { "test_ID": "282", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_advanced examples_ReverseString.dfy", "ground_truth": "// RUN: /compile:0\n\npredicate reversed (arr : array, outarr: array)\nrequires arr != null && outarr != null\n//requires 0<=k<=arr.Length-1\nrequires arr.Length == outarr.Length\nreads arr, outarr\n{\n forall k :: 0<=k<=arr.Length-1 ==> outarr[k] == arr[(arr.Length-1-k)]\n}\n\nmethod yarra(arr : array) returns (outarr : array)\nrequires arr != null && arr.Length > 0\nensures outarr != null && arr.Length == outarr.Length && reversed(arr,outarr)\n{\n var i:= 0;\n var j:= arr.Length-1;\n outarr := new char[arr.Length];\n outarr[0] := arr[j];\n i := i+1;\n j := j-1;\n while i -2;\n //assert d[0] == a[0];\n //print c; print a;\n}\n\n\n", "hints_removed": "// RUN: /compile:0\n\npredicate reversed (arr : array, outarr: array)\nrequires arr != null && outarr != null\n//requires 0<=k<=arr.Length-1\nrequires arr.Length == outarr.Length\nreads arr, outarr\n{\n forall k :: 0<=k<=arr.Length-1 ==> outarr[k] == arr[(arr.Length-1-k)]\n}\n\nmethod yarra(arr : array) returns (outarr : array)\nrequires arr != null && arr.Length > 0\nensures outarr != null && arr.Length == outarr.Length && reversed(arr,outarr)\n{\n var i:= 0;\n var j:= arr.Length-1;\n outarr := new char[arr.Length];\n outarr[0] := arr[j];\n i := i+1;\n j := j-1;\n while i -2;\n //assert d[0] == a[0];\n //print c; print a;\n}\n\n\n" }, { "test_ID": "283", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_advanced examples_demo.dfy", "ground_truth": "method Partition(a: array) returns (lo: int, hi: int)\n modifies a\n ensures 0 <= lo <= hi <= a.Length\n ensures forall x | 0 <= x < lo :: a[x] < 0\n ensures forall x | lo <= x < hi :: a[x] == 0\n ensures forall x | hi <= x < a.Length :: a[x] > 0\n{\n var i := 0;\n var j := a.Length;\n var k := a.Length;\n\n while i < j\n invariant 0 <= i <= j <= k <= a.Length\n invariant forall x | 0 <= x < i :: a[x] < 0\n invariant forall x | j <= x < k :: a[x] == 0\n invariant forall x | k <= x < a.Length :: a[x] > 0\n {\n if a[i] < 0 {\n i := i + 1;\n } else if a[i] == 0 {\n var current := a[i];\n a[i] := a[j-1];\n a[j-1] := current;\n j := j - 1;\n } else {\n assert a[i] > 0;\n var current := a[i];\n a[i] := a[j-1];\n a[j-1] := a[k-1];\n a[k-1] := current;\n j := j - 1;\n k := k - 1;\n }\n }\n\n return i, k;\n}\n\n\n", "hints_removed": "method Partition(a: array) returns (lo: int, hi: int)\n modifies a\n ensures 0 <= lo <= hi <= a.Length\n ensures forall x | 0 <= x < lo :: a[x] < 0\n ensures forall x | lo <= x < hi :: a[x] == 0\n ensures forall x | hi <= x < a.Length :: a[x] > 0\n{\n var i := 0;\n var j := a.Length;\n var k := a.Length;\n\n while i < j\n {\n if a[i] < 0 {\n i := i + 1;\n } else if a[i] == 0 {\n var current := a[i];\n a[i] := a[j-1];\n a[j-1] := current;\n j := j - 1;\n } else {\n var current := a[i];\n a[i] := a[j-1];\n a[j-1] := a[k-1];\n a[k-1] := current;\n j := j - 1;\n k := k - 1;\n }\n }\n\n return i, k;\n}\n\n\n" }, { "test_ID": "284", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_ProgramProofs_ch15.dfy", "ground_truth": "predicate SplitPoint(a: array, n: int)\n reads a\n requires 0 <= n <= n\n\n{\n forall i,j :: 0 <= i < n <= j < a.Length ==> a[i] <= a[j]\n}\n\nmethod SelectionSort(a: array)\n modifies a\n ensures forall i,j :: 0 <= i < j < a.Length ==> a[i] <= a[j]\n ensures multiset(a[..]) == old(multiset(a[..]))\n{\n var n := 0;\n while n != a.Length \n invariant 0 <= n <= a.Length\n invariant forall i,j :: 0 <= i < j < n ==> a[i] <= a[j]\n // invariant forall i,j :: 0 <= i < n <= j < a.Length ==> a[i] <= a[j]\n invariant SplitPoint(a, n)\n invariant multiset(a[..]) == old(multiset(a[..]))\n {\n var mindex, m := n, n;\n while m != a.Length \n invariant n <= m <= a.Length && n <= mindex < a.Length\n invariant forall i :: n <= i < m ==> a[mindex] <= a[i]\n {\n if a[m] < a[mindex] {\n mindex := m;\n }\n m := m + 1;\n }\n a[n], a[mindex] := a[mindex], a[n];\n assert forall i,j :: 0 <= i < j < n ==> a[i] <= a[j];\n n := n + 1;\n }\n}\n\nmethod QuickSort(a: array)\n modifies a\n ensures forall i,j :: 0 <= i < j < a.Length ==> a[i] <= a[j]\n ensures multiset(a[..]) == old(multiset(a[..]))\n{\n QuickSortAux(a, 0, a.Length);\n}\n\ntwostate predicate SwapFrame(a: array, lo: int, hi: int)\n requires 0 <= lo <= hi <= a.Length\n reads a\n{\n (forall i :: 0 <= i < lo || hi <= i < a.Length ==> a[i] == old(a[i])) && multiset(a[..]) == old(multiset(a[..]))\n}\n\nmethod QuickSortAux(a: array, lo: int, hi: int)\n requires 0 <= lo <= hi <= a.Length\n requires SplitPoint(a, lo) && SplitPoint(a, hi)\n modifies a\n ensures forall i,j :: lo <= i < j < hi ==> a[i] <= a[j]\n ensures SwapFrame(a, lo, hi)\n ensures SplitPoint(a, lo) && SplitPoint(a, hi)\n decreases hi - lo\n{\n if 2 <= hi - lo {\n var p := Partition(a, lo, hi);\n QuickSortAux(a, lo, p);\n QuickSortAux(a, p + 1, hi);\n }\n}\n\nmethod Partition(a: array, lo: int, hi: int) returns (p: int)\n requires 0 <= lo < hi <= a.Length\n requires SplitPoint(a, lo) && SplitPoint(a, hi)\n modifies a\n ensures lo <= p < hi\n ensures forall i :: lo <= i < p ==> a[i] < a[p]\n ensures forall i :: p <= i < hi ==> a[p] <= a[i]\n ensures SplitPoint(a, lo) && SplitPoint(a, hi)\n ensures SwapFrame(a, lo, hi)\n{\n var pivot := a[lo];\n var m, n := lo + 1, hi;\n while m < n\n invariant lo + 1 <= m <= n <= hi\n invariant a[lo] == pivot\n invariant forall i :: lo + 1 <= i < m ==> a[i] < pivot\n invariant forall i :: n <= i < hi ==> pivot <= a[i]\n invariant SplitPoint(a, lo) && SplitPoint(a, hi)\n invariant SwapFrame(a, lo, hi)\n {\n if a[m] < pivot {\n m := m + 1;\n } else {\n a[m], a[n-1] := a[n-1], a[m];\n n := n - 1;\n }\n\n }\n a[lo], a[m - 1] := a[m - 1], a[lo];\n return m - 1;\n}\n", "hints_removed": "predicate SplitPoint(a: array, n: int)\n reads a\n requires 0 <= n <= n\n\n{\n forall i,j :: 0 <= i < n <= j < a.Length ==> a[i] <= a[j]\n}\n\nmethod SelectionSort(a: array)\n modifies a\n ensures forall i,j :: 0 <= i < j < a.Length ==> a[i] <= a[j]\n ensures multiset(a[..]) == old(multiset(a[..]))\n{\n var n := 0;\n while n != a.Length \n // invariant forall i,j :: 0 <= i < n <= j < a.Length ==> a[i] <= a[j]\n {\n var mindex, m := n, n;\n while m != a.Length \n {\n if a[m] < a[mindex] {\n mindex := m;\n }\n m := m + 1;\n }\n a[n], a[mindex] := a[mindex], a[n];\n n := n + 1;\n }\n}\n\nmethod QuickSort(a: array)\n modifies a\n ensures forall i,j :: 0 <= i < j < a.Length ==> a[i] <= a[j]\n ensures multiset(a[..]) == old(multiset(a[..]))\n{\n QuickSortAux(a, 0, a.Length);\n}\n\ntwostate predicate SwapFrame(a: array, lo: int, hi: int)\n requires 0 <= lo <= hi <= a.Length\n reads a\n{\n (forall i :: 0 <= i < lo || hi <= i < a.Length ==> a[i] == old(a[i])) && multiset(a[..]) == old(multiset(a[..]))\n}\n\nmethod QuickSortAux(a: array, lo: int, hi: int)\n requires 0 <= lo <= hi <= a.Length\n requires SplitPoint(a, lo) && SplitPoint(a, hi)\n modifies a\n ensures forall i,j :: lo <= i < j < hi ==> a[i] <= a[j]\n ensures SwapFrame(a, lo, hi)\n ensures SplitPoint(a, lo) && SplitPoint(a, hi)\n{\n if 2 <= hi - lo {\n var p := Partition(a, lo, hi);\n QuickSortAux(a, lo, p);\n QuickSortAux(a, p + 1, hi);\n }\n}\n\nmethod Partition(a: array, lo: int, hi: int) returns (p: int)\n requires 0 <= lo < hi <= a.Length\n requires SplitPoint(a, lo) && SplitPoint(a, hi)\n modifies a\n ensures lo <= p < hi\n ensures forall i :: lo <= i < p ==> a[i] < a[p]\n ensures forall i :: p <= i < hi ==> a[p] <= a[i]\n ensures SplitPoint(a, lo) && SplitPoint(a, hi)\n ensures SwapFrame(a, lo, hi)\n{\n var pivot := a[lo];\n var m, n := lo + 1, hi;\n while m < n\n {\n if a[m] < pivot {\n m := m + 1;\n } else {\n a[m], a[n-1] := a[n-1], a[m];\n n := n - 1;\n }\n\n }\n a[lo], a[m - 1] := a[m - 1], a[lo];\n return m - 1;\n}\n" }, { "test_ID": "285", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_examples_bubblesort.dfy", "ground_truth": "//https://stackoverflow.com/questions/69364687/how-to-prove-time-complexity-of-bubble-sort-using-dafny\nfunction NChoose2(n: int): int\n{\n n * (n - 1) / 2\n}\n\n// sum of all integers in the range [lo, hi)\n// (inclusive of lo, exclusive of hi)\nfunction SumRange(lo: int, hi: int): int\n decreases hi - lo\n{\n if lo >= hi then 0\n else SumRange(lo, hi - 1) + hi - 1\n}\n\n// dafny proves this automatically by induction\nlemma SumRangeNChoose2(n: nat)\n ensures SumRange(0, n) == NChoose2(n)\n{}\n\n// dafny proves this automatically by induction\n// (given the correct decreases clause)\nlemma SumRangeUnrollLeft(lo: int, hi: int)\n decreases hi - lo\n ensures SumRange(lo, hi) ==\n if lo >= hi then 0 else lo + SumRange(lo + 1, hi)\n{}\n\nmethod BubbleSort(a: array) returns (n: nat) \n modifies a\n ensures n <= NChoose2(a.Length)\n{\n // it simplifies the remaining invariants to handle the empty array here\n if a.Length == 0 { return 0; } \n\n var i := a.Length - 1;\n n := 0;\n\n while i > 0\n invariant 0 <= i < a.Length\n invariant n <= SumRange(i+1, a.Length)\n {\n var j := 0;\n while j < i\n invariant n <= SumRange(i+1, a.Length) + j\n invariant j <= i\n {\n if a[j] > a[j+1]\n {\n a[j], a[j+1] := a[j+1], a[j];\n n := n + 1;\n }\n j := j + 1;\n }\n\n assert n <= SumRange(i, a.Length) by {\n SumRangeUnrollLeft(i, a.Length); // see lemma below\n }\n\n i := i - 1;\n }\n\n calc <= {\n n; // less or equal to next line by the loop invariant\n SumRange(1, a.Length);\n { SumRangeUnrollLeft(0, a.Length); }\n SumRange(0, a.Length);\n { SumRangeNChoose2(a.Length); } // see lemma below\n NChoose2(a.Length);\n }\n}\n", "hints_removed": "//https://stackoverflow.com/questions/69364687/how-to-prove-time-complexity-of-bubble-sort-using-dafny\nfunction NChoose2(n: int): int\n{\n n * (n - 1) / 2\n}\n\n// sum of all integers in the range [lo, hi)\n// (inclusive of lo, exclusive of hi)\nfunction SumRange(lo: int, hi: int): int\n{\n if lo >= hi then 0\n else SumRange(lo, hi - 1) + hi - 1\n}\n\n// dafny proves this automatically by induction\nlemma SumRangeNChoose2(n: nat)\n ensures SumRange(0, n) == NChoose2(n)\n{}\n\n// dafny proves this automatically by induction\n// (given the correct decreases clause)\nlemma SumRangeUnrollLeft(lo: int, hi: int)\n ensures SumRange(lo, hi) ==\n if lo >= hi then 0 else lo + SumRange(lo + 1, hi)\n{}\n\nmethod BubbleSort(a: array) returns (n: nat) \n modifies a\n ensures n <= NChoose2(a.Length)\n{\n // it simplifies the remaining invariants to handle the empty array here\n if a.Length == 0 { return 0; } \n\n var i := a.Length - 1;\n n := 0;\n\n while i > 0\n {\n var j := 0;\n while j < i\n {\n if a[j] > a[j+1]\n {\n a[j], a[j+1] := a[j+1], a[j];\n n := n + 1;\n }\n j := j + 1;\n }\n\n SumRangeUnrollLeft(i, a.Length); // see lemma below\n }\n\n i := i - 1;\n }\n\n calc <= {\n n; // less or equal to next line by the loop invariant\n SumRange(1, a.Length);\n { SumRangeUnrollLeft(0, a.Length); }\n SumRange(0, a.Length);\n { SumRangeNChoose2(a.Length); } // see lemma below\n NChoose2(a.Length);\n }\n}\n" }, { "test_ID": "286", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_examples_relativeOrder.dfy", "ground_truth": "\npredicate IsEven (n: int)\n{\n n % 2 == 0\n}\n\nmethod FindEvenNumbers (arr: array)\n returns (evenNumbers: array)\n ensures forall x :: x in arr[..] && IsEven(x) ==> x in evenNumbers[..];\n ensures forall x :: x !in arr[..] ==> x !in evenNumbers[..]\n ensures forall k, l :: 0 <= k < l < evenNumbers.Length ==>\n exists n, m :: 0 <= n < m < arr.Length && evenNumbers[k] == arr[n] && evenNumbers[l] == arr[m]\n{\n var evenList: seq := [];\n ghost var indices: seq := [];\n\n for i := 0 to arr.Length\n invariant 0 <= i <= arr.Length\n invariant 0 <= |evenList| <= i\n invariant forall x :: x in arr[..i] && IsEven(x) ==> x in evenList[..]\n invariant forall x :: x !in arr[..i] ==> x !in evenList\n invariant |evenList| == |indices|\n invariant forall k :: 0 <= k < |indices| ==> indices[k] < i\n invariant forall k, l :: 0 <= k < l < |indices| ==> indices[k] < indices[l]\n invariant forall k :: 0 <= k < |evenList| ==> 0 <= indices[k] < i <= arr.Length && arr[indices[k]] == evenList[k]\n invariant forall k, l :: 0 <= k < l < |evenList| ==>\n exists n, m :: 0 <= n < m < i && evenList[k] == arr[n] && evenList[l] == arr[m]\n {\n if IsEven(arr[i])\n {\n evenList := evenList + [arr[i]];\n indices := indices + [i];\n }\n }\n\n evenNumbers := new int[|evenList|](i requires 0 <= i < |evenList| => evenList[i]);\n assert evenList == evenNumbers[..];\n}\n", "hints_removed": "\npredicate IsEven (n: int)\n{\n n % 2 == 0\n}\n\nmethod FindEvenNumbers (arr: array)\n returns (evenNumbers: array)\n ensures forall x :: x in arr[..] && IsEven(x) ==> x in evenNumbers[..];\n ensures forall x :: x !in arr[..] ==> x !in evenNumbers[..]\n ensures forall k, l :: 0 <= k < l < evenNumbers.Length ==>\n exists n, m :: 0 <= n < m < arr.Length && evenNumbers[k] == arr[n] && evenNumbers[l] == arr[m]\n{\n var evenList: seq := [];\n ghost var indices: seq := [];\n\n for i := 0 to arr.Length\n exists n, m :: 0 <= n < m < i && evenList[k] == arr[n] && evenList[l] == arr[m]\n {\n if IsEven(arr[i])\n {\n evenList := evenList + [arr[i]];\n indices := indices + [i];\n }\n }\n\n evenNumbers := new int[|evenList|](i requires 0 <= i < |evenList| => evenList[i]);\n}\n" }, { "test_ID": "287", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_examples_simpleMultiplication.dfy", "ground_truth": "\nmethod Foo(y: int, x: int) returns (z: int) \n requires 0 <= y\n ensures z == x*y\n{\n var a: int := 0;\n z := 0;\n while a != y \n invariant 0 <= a <= y\n invariant z == a*x\n decreases y-a\n {\n z := z + x;\n a := a + 1;\n }\n return z;\n}\n\nfunction stringToSet(s: string): (r: set)\nensures forall x :: 0 <= x < |s| ==> s[x] in r\n{\n set x | 0 <= x < |s| :: s[x]\n}\n//ensures forall a, b :: 0 <= a < b < |s| ==> forall k, j :: a <=k < j <=b ==> k !=j ==> s[k] != s[j] ==> b-a <= longest\n// lemma stringSet(s: string)\n// \n// {\n// if |s| != 0 {\n\n\n// }\n// }\n\n\nmethod Main() {\n\tvar sample: string := \"test\";\n\tvar foof := Foo(3,4);\n \tvar test: set := stringToSet(sample);\n \t// var test := set x | 0 <= x < |sample| :: sample[x];\n assert test == stringToSet(sample);\n assert forall x :: 0 <= x < |sample| ==> sample[x] in test;\n assert 't' in sample;\n assert 't' in test;\n\tprint foof;\n}\n", "hints_removed": "\nmethod Foo(y: int, x: int) returns (z: int) \n requires 0 <= y\n ensures z == x*y\n{\n var a: int := 0;\n z := 0;\n while a != y \n {\n z := z + x;\n a := a + 1;\n }\n return z;\n}\n\nfunction stringToSet(s: string): (r: set)\nensures forall x :: 0 <= x < |s| ==> s[x] in r\n{\n set x | 0 <= x < |s| :: s[x]\n}\n//ensures forall a, b :: 0 <= a < b < |s| ==> forall k, j :: a <=k < j <=b ==> k !=j ==> s[k] != s[j] ==> b-a <= longest\n// lemma stringSet(s: string)\n// \n// {\n// if |s| != 0 {\n\n\n// }\n// }\n\n\nmethod Main() {\n\tvar sample: string := \"test\";\n\tvar foof := Foo(3,4);\n \tvar test: set := stringToSet(sample);\n \t// var test := set x | 0 <= x < |sample| :: sample[x];\n\tprint foof;\n}\n" }, { "test_ID": "288", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_heap2.dfy", "ground_truth": "class Heap {\n var arr: array\n\n constructor Heap (input: array)\n ensures this.arr == input {\n this.arr := input;\n }\n\n function parent(idx: int): int\n {\n if idx == 0 then -1\n else if idx % 2 == 0 then (idx-2)/2\n else (idx-1)/2\n }\n\n predicate IsMaxHeap(input: seq)\n {\n forall i :: 0 <= i < |input| ==>\n && (2*i+1 < |input| ==> input[i] >= input[2*i+1])\n && (2*i+2 < |input| ==> input[i] >= input[2*i+2])\n }\n\n predicate IsAlmostMaxHeap(input: seq, idx: int)\n requires 0 <= idx\n {\n && (forall i :: 0 <= i < |input| ==>\n && (2*i+1 < |input| && i != idx ==> input[i] >= input[2*i+1])\n && (2*i+2 < |input| && i != idx ==> input[i] >= input[2*i+2]))\n && (0 <= parent(idx) < |input| && 2*idx+1 < |input| ==> input[parent(idx)] >= input[2*idx+1])\n && (0 <= parent(idx) < |input| && 2*idx+2 < |input| ==> input[parent(idx)] >= input[2*idx+2])\n }\n\n method heapify(idx: int)\n returns (nidx: int)\n modifies this, this.arr\n requires 0 <= idx < this.arr.Length\n requires IsAlmostMaxHeap(this.arr[..], idx)\n ensures nidx == -1 || idx < nidx < this.arr.Length\n ensures nidx == -1 ==> IsMaxHeap(this.arr[..])\n ensures idx < nidx < this.arr.Length ==> IsAlmostMaxHeap(this.arr[..], nidx)\n {\n if (2*idx+1 >= this.arr.Length) && (2*idx+2 >= this.arr.Length) {\n nidx := -1;\n assert IsMaxHeap(this.arr[..]);\n return;\n }\n else {\n assert 2*idx+1 < this.arr.Length || 2*idx+2 < this.arr.Length;\n nidx := idx;\n if 2*idx+1 < this.arr.Length && this.arr[nidx] < this.arr[2*idx+1] {\n nidx := 2*idx+1;\n }\n if 2*idx+2 < this.arr.Length && this.arr[nidx] < this.arr[2*idx+2] {\n nidx := 2*idx+2;\n }\n if nidx == idx {\n nidx := -1;\n return;\n }\n else {\n assert nidx == 2*idx+1 || nidx == 2*idx+2;\n this.arr[idx], this.arr[nidx] := this.arr[nidx], this.arr[idx];\n forall i | 0 <= i < this.arr.Length\n ensures (i != nidx) && (2*i+1 < this.arr.Length) ==> (this.arr[i] >= this.arr[2*i+1]) {\n if (i != nidx) && (2*i+1 < this.arr.Length) {\n if 2*i+1 == idx {\n assert this.arr[i] >= this.arr[2*i+1];\n }\n }\n }\n forall i | 0 <= i < this.arr.Length\n ensures (i != nidx) && (2*i+2 < this.arr.Length) ==> (this.arr[i] >= this.arr[2*i+2]) {\n if (i != nidx) && (2*i+2 < this.arr.Length) {\n if 2*i+2 == idx {\n assert this.arr[i] >= this.arr[2*i+2];\n }\n }\n }\n }\n }\n }\n}\n", "hints_removed": "class Heap {\n var arr: array\n\n constructor Heap (input: array)\n ensures this.arr == input {\n this.arr := input;\n }\n\n function parent(idx: int): int\n {\n if idx == 0 then -1\n else if idx % 2 == 0 then (idx-2)/2\n else (idx-1)/2\n }\n\n predicate IsMaxHeap(input: seq)\n {\n forall i :: 0 <= i < |input| ==>\n && (2*i+1 < |input| ==> input[i] >= input[2*i+1])\n && (2*i+2 < |input| ==> input[i] >= input[2*i+2])\n }\n\n predicate IsAlmostMaxHeap(input: seq, idx: int)\n requires 0 <= idx\n {\n && (forall i :: 0 <= i < |input| ==>\n && (2*i+1 < |input| && i != idx ==> input[i] >= input[2*i+1])\n && (2*i+2 < |input| && i != idx ==> input[i] >= input[2*i+2]))\n && (0 <= parent(idx) < |input| && 2*idx+1 < |input| ==> input[parent(idx)] >= input[2*idx+1])\n && (0 <= parent(idx) < |input| && 2*idx+2 < |input| ==> input[parent(idx)] >= input[2*idx+2])\n }\n\n method heapify(idx: int)\n returns (nidx: int)\n modifies this, this.arr\n requires 0 <= idx < this.arr.Length\n requires IsAlmostMaxHeap(this.arr[..], idx)\n ensures nidx == -1 || idx < nidx < this.arr.Length\n ensures nidx == -1 ==> IsMaxHeap(this.arr[..])\n ensures idx < nidx < this.arr.Length ==> IsAlmostMaxHeap(this.arr[..], nidx)\n {\n if (2*idx+1 >= this.arr.Length) && (2*idx+2 >= this.arr.Length) {\n nidx := -1;\n return;\n }\n else {\n nidx := idx;\n if 2*idx+1 < this.arr.Length && this.arr[nidx] < this.arr[2*idx+1] {\n nidx := 2*idx+1;\n }\n if 2*idx+2 < this.arr.Length && this.arr[nidx] < this.arr[2*idx+2] {\n nidx := 2*idx+2;\n }\n if nidx == idx {\n nidx := -1;\n return;\n }\n else {\n this.arr[idx], this.arr[nidx] := this.arr[nidx], this.arr[idx];\n forall i | 0 <= i < this.arr.Length\n ensures (i != nidx) && (2*i+1 < this.arr.Length) ==> (this.arr[i] >= this.arr[2*i+1]) {\n if (i != nidx) && (2*i+1 < this.arr.Length) {\n if 2*i+1 == idx {\n }\n }\n }\n forall i | 0 <= i < this.arr.Length\n ensures (i != nidx) && (2*i+2 < this.arr.Length) ==> (this.arr[i] >= this.arr[2*i+2]) {\n if (i != nidx) && (2*i+2 < this.arr.Length) {\n if 2*i+2 == idx {\n }\n }\n }\n }\n }\n }\n}\n" }, { "test_ID": "289", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_leetcode_BoatsToSavePeople.dfy", "ground_truth": "/*\nfunction numRescueBoats(people: number[], limit: number): number {\n //people.sort((a,b) => a-b);\n binsort(people, limit);\n let boats = 0;\n let lower = 0, upper = people.length-1; \n while(lower <= upper) {\n if(people[upper] == limit || people[upper]+people[lower] > limit) {\n boats++\n upper--;\n }else if(people[upper]+people[lower] <= limit) {\n upper--;\n lower++;\n boats++;\n }\n }\n\n return boats;\n};\nnums[k++] = i+1;\nfunction binsort(nums: number[], limit: number) {\n let result = new Array(limit);\n result.fill(0);\n for(let i = 0; i < nums.length; i++) {\n result[nums[i]-1]++;\n }\n var k = 0;\n for(let i=0; i < result.length; i++) {\n for(let j = 0; j < result[i]; j++) {\n nums[k++] = i+1;\n }\n }\n}\n*/\n\nfunction sumBoat(s: seq): nat \n requires 1 <= |s| <= 2\n{\n if |s| == 1 then s[0] else s[0] + s[1]\n}\n\npredicate isSafeBoat(boat: seq, limit: nat) {\n 1 <= |boat| <= 2 && sumBoat(boat) <= limit\n}\n\nfunction multisetAdd(ss: seq>): multiset {\n if ss == [] then multiset{} else multiset(ss[0]) + multisetAdd(ss[1..])\n}\n\npredicate multisetEqual(ss: seq>, xs: seq) {\n multiset(xs) == multisetAdd(ss)\n}\n\npredicate allSafe(boats: seq>, limit: nat) {\n forall boat :: boat in boats ==> isSafeBoat(boat, limit)\n}\n\npredicate sorted(list: seq)\n{\n forall i,j :: 0 <= i < j < |list| ==> list[i] <= list[j]\n}\n\nmethod numRescueBoats(people: seq, limit: nat) returns (boats: nat)\n requires |people| >= 1\n requires sorted(people)\n requires forall i: nat :: i < |people| ==> 1 <= people[i] <= limit\n ensures exists boatConfig: seq> :: multisetEqual(boatConfig, people) && allSafe(boatConfig, limit) && boats == |boatConfig|// && forall boatConfigs :: multisetEqual(boatConfigs, people) && allSafe(boatConfigs, limit) ==> boats <= |boatConfigs|\n{\n boats := 0;\n var lower: nat := 0;\n var upper: int := |people| - 1;\n ghost var visitedUpper: multiset := multiset{};\n ghost var visitedLower: multiset := multiset{};\n ghost var remaining: multiset := multiset(people);\n ghost var safeBoats: seq> := [];\n while lower <= upper \n invariant 0 <= lower <= |people|\n invariant lower-1 <= upper < |people|\n invariant visitedUpper == multiset(people[upper+1..])\n invariant visitedLower == multiset(people[..lower])\n invariant allSafe(safeBoats, limit)\n invariant multisetAdd(safeBoats) == visitedLower + visitedUpper;\n invariant |safeBoats| == boats\n {\n if people[upper] == limit || people[upper] + people[lower] > limit {\n boats := boats + 1;\n assert isSafeBoat([people[upper]], limit);\n safeBoats := [[people[upper]]] + safeBoats;\n assert visitedUpper == multiset(people[upper+1..]);\n ghost var gu := people[upper+1..];\n assert multiset(gu) == visitedUpper;\n assert people[upper..] == [people[upper]] + gu;\n visitedUpper := visitedUpper + multiset{people[upper]};\n upper := upper - 1;\n assert people[(upper+1)..] == [people[upper+1]] + gu;\n }else{\n ghost var gl := people[..lower];\n boats := boats + 1;\n if lower == upper {\n visitedLower := visitedLower + multiset{people[lower]};\n assert isSafeBoat([people[lower]], limit);\n safeBoats := [[people[lower]]] + safeBoats;\n }else{\n ghost var gu := people[upper+1..];\n assert multiset(gu) == visitedUpper;\n visitedUpper := visitedUpper + multiset{people[upper]};\n visitedLower := visitedLower + multiset{people[lower]};\n assert isSafeBoat([people[upper], people[lower]], limit);\n safeBoats := [[people[upper], people[lower]]] + safeBoats;\n upper := upper - 1;\n assert people[(upper+1)..] == [people[upper+1]] + gu;\n }\n lower := lower + 1;\n assert people[..lower] == gl + [people[lower-1]];\n }\n }\n assert visitedLower == multiset(people[..lower]);\n assert visitedUpper == multiset(people[upper+1..]);\n assert upper+1 == lower;\n assert people == people[..lower] + people[upper+1..];\n assert visitedLower + visitedUpper == multiset(people);\n}\n\n/*\nlimit 3\n[3,2,2,1]\nlower = 0\nupper = 3\n\nupper = 2\nlower= 0\n\nlower = 1\nupper = 1\n\nlower = 2 [..2]\nupper = 1 [2..]\n*/\n", "hints_removed": "/*\nfunction numRescueBoats(people: number[], limit: number): number {\n //people.sort((a,b) => a-b);\n binsort(people, limit);\n let boats = 0;\n let lower = 0, upper = people.length-1; \n while(lower <= upper) {\n if(people[upper] == limit || people[upper]+people[lower] > limit) {\n boats++\n upper--;\n }else if(people[upper]+people[lower] <= limit) {\n upper--;\n lower++;\n boats++;\n }\n }\n\n return boats;\n};\nnums[k++] = i+1;\nfunction binsort(nums: number[], limit: number) {\n let result = new Array(limit);\n result.fill(0);\n for(let i = 0; i < nums.length; i++) {\n result[nums[i]-1]++;\n }\n var k = 0;\n for(let i=0; i < result.length; i++) {\n for(let j = 0; j < result[i]; j++) {\n nums[k++] = i+1;\n }\n }\n}\n*/\n\nfunction sumBoat(s: seq): nat \n requires 1 <= |s| <= 2\n{\n if |s| == 1 then s[0] else s[0] + s[1]\n}\n\npredicate isSafeBoat(boat: seq, limit: nat) {\n 1 <= |boat| <= 2 && sumBoat(boat) <= limit\n}\n\nfunction multisetAdd(ss: seq>): multiset {\n if ss == [] then multiset{} else multiset(ss[0]) + multisetAdd(ss[1..])\n}\n\npredicate multisetEqual(ss: seq>, xs: seq) {\n multiset(xs) == multisetAdd(ss)\n}\n\npredicate allSafe(boats: seq>, limit: nat) {\n forall boat :: boat in boats ==> isSafeBoat(boat, limit)\n}\n\npredicate sorted(list: seq)\n{\n forall i,j :: 0 <= i < j < |list| ==> list[i] <= list[j]\n}\n\nmethod numRescueBoats(people: seq, limit: nat) returns (boats: nat)\n requires |people| >= 1\n requires sorted(people)\n requires forall i: nat :: i < |people| ==> 1 <= people[i] <= limit\n ensures exists boatConfig: seq> :: multisetEqual(boatConfig, people) && allSafe(boatConfig, limit) && boats == |boatConfig|// && forall boatConfigs :: multisetEqual(boatConfigs, people) && allSafe(boatConfigs, limit) ==> boats <= |boatConfigs|\n{\n boats := 0;\n var lower: nat := 0;\n var upper: int := |people| - 1;\n ghost var visitedUpper: multiset := multiset{};\n ghost var visitedLower: multiset := multiset{};\n ghost var remaining: multiset := multiset(people);\n ghost var safeBoats: seq> := [];\n while lower <= upper \n {\n if people[upper] == limit || people[upper] + people[lower] > limit {\n boats := boats + 1;\n safeBoats := [[people[upper]]] + safeBoats;\n ghost var gu := people[upper+1..];\n visitedUpper := visitedUpper + multiset{people[upper]};\n upper := upper - 1;\n }else{\n ghost var gl := people[..lower];\n boats := boats + 1;\n if lower == upper {\n visitedLower := visitedLower + multiset{people[lower]};\n safeBoats := [[people[lower]]] + safeBoats;\n }else{\n ghost var gu := people[upper+1..];\n visitedUpper := visitedUpper + multiset{people[upper]};\n visitedLower := visitedLower + multiset{people[lower]};\n safeBoats := [[people[upper], people[lower]]] + safeBoats;\n upper := upper - 1;\n }\n lower := lower + 1;\n }\n }\n}\n\n/*\nlimit 3\n[3,2,2,1]\nlower = 0\nupper = 3\n\nupper = 2\nlower= 0\n\nlower = 1\nupper = 1\n\nlower = 2 [..2]\nupper = 1 [2..]\n*/\n" }, { "test_ID": "290", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_leetcode_FindPivotIndex.dfy", "ground_truth": "/*\nhttps://leetcode.com/problems/find-pivot-index/description/\nGiven an array of integers nums, calculate the pivot index of this array.\n\nThe pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.\n\nIf the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.\n\nReturn the leftmost pivot index. If no such index exists, return -1.\n\n \n\nExample 1:\n\nInput: nums = [1,7,3,6,5,6]\nOutput: 3\nExplanation:\nThe pivot index is 3.\nLeft sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11\nRight sum = nums[4] + nums[5] = 5 + 6 = 11\nExample 2:\n\nInput: nums = [1,2,3]\nOutput: -1\nExplanation:\nThere is no index that satisfies the conditions in the problem statement.\nExample 3:\n\nInput: nums = [2,1,-1]\nOutput: 0\nExplanation:\nThe pivot index is 0.\nLeft sum = 0 (no elements to the left of index 0)\nRight sum = nums[1] + nums[2] = 1 + -1 = 0\n\n```TypeScript\nfunction pivotIndex(nums: number[]): number {\n const n = nums.length;\n let leftsums = [0], rightsums = [0];\n for(let i=1; i < n+1; i++) {\n leftsums.push(nums[i-1]+leftsums[i-1]);\n rightsums.push(nums[n-i]+rightsums[i-1]);\n }\n for(let i=0; i <= n; i++) {\n if(leftsums[i] == rightsums[n-(i+1)]) return i;\n }\n return -1;\n};\n```\n*/\n\nfunction sum(nums: seq): int {\n // if |nums| == 0 then 0 else nums[0]+sum(nums[1..])\n if |nums| == 0 then 0 else sum(nums[0..(|nums|-1)])+nums[|nums|-1]\n}\n\n\nfunction sumUp(nums: seq): int {\n if |nums| == 0 then 0 else nums[0]+sumUp(nums[1..])\n}\n\n// By Divyanshu Ranjan\nlemma sumUpLemma(a: seq, b: seq)\n ensures sumUp(a + b) == sumUp(a) + sumUp(b)\n{\n if a == [] {\n assert a + b == b;\n }\n else {\n sumUpLemma(a[1..], b);\n calc {\n sumUp(a + b);\n {\n assert (a + b)[0] == a[0];\n assert (a + b)[1..] == a[1..] + b;\n }\n a[0] + sumUp(a[1..] + b);\n a[0] + sumUp(a[1..]) + sumUp(b);\n }\n }\n}\n\n// By Divyanshu Ranjan\nlemma sumsEqual(nums: seq)\n decreases |nums|\n ensures sum(nums) == sumUp(nums)\n{\n if nums == [] {}\n else {\n var ln := |nums|-1;\n calc {\n sumUp(nums[..]);\n {\n assert nums[..] == nums[0..ln] + [nums[ln]];\n sumUpLemma(nums[0..ln], [nums[ln]]);\n }\n sumUp(nums[0..ln]) + sumUp([nums[ln]]);\n {\n assert forall a:: sumUp([a]) == a;\n }\n sumUp(nums[0..ln]) + nums[ln];\n {\n sumsEqual(nums[0..ln]);\n }\n sum(nums[0..ln]) + nums[ln];\n }\n }\n}\n\n\nmethod FindPivotIndex(nums: seq) returns (index: int)\n requires |nums| > 0\n ensures index == -1 ==> forall k: nat :: k < |nums| ==> sum(nums[0..k]) != sum(nums[(k+1)..])\n ensures 0 <= index < |nums| ==> sum(nums[0..index]) == sum(nums[(index+1)..])\n{\n var leftsums: seq := [0];\n var rightsums: seq := [0];\n var i := 1;\n assert leftsums[0] == sum(nums[0..0]);\n assert rightsums[0] == sumUp(nums[|nums|..]);\n while i < |nums|+1\n invariant 1 <= i <= |nums|+1\n invariant |leftsums| == i\n invariant |rightsums| == i\n invariant forall k: nat :: 0 <= k < i && k <= |nums| ==> leftsums[k] == sum(nums[0..k])\n invariant forall k: nat :: 0 <= k < i && k <= |nums| ==> rightsums[k] == sumUp(nums[(|nums|-k)..])\n {\n leftsums := leftsums + [leftsums[i-1]+nums[i-1]]; \n assert nums[0..i] == nums[0..i-1]+[nums[i-1]];\n rightsums := rightsums + [nums[|nums|-i]+rightsums[i-1]];\n i := i + 1;\n }\n\n assert forall k: nat :: 0 <= k < i && k <= |nums| ==> rightsums[k] == sum(nums[(|nums|-k)..]) by {\n forall k: nat | 0 <= k < i && k <= |nums|\n ensures sumUp(nums[(|nums|-k)..]) == sum(nums[(|nums|-k)..])\n ensures rightsums[k] == sumUp(nums[(|nums|-k)..])\n {\n sumsEqual(nums[(|nums|-k)..]);\n }\n }\n i :=0;\n while i < |nums| \n invariant 0 <= i <= |nums|\n invariant forall k: nat :: k < i ==> sum(nums[0..k]) != sum(nums[(k+1)..])\n {\n var x := |nums|-(i+1);\n if leftsums[i] == rightsums[x] {\n assert sum(nums[0..i]) == sum(nums[(i+1)..]);\n // assert rightsums[i+1] == sum(nums[(|nums|-(i+1))..]);\n return i;\n }\n assert sum(nums[0..i]) != sum(nums[(i+1)..]);\n i := i + 1;\n }\n return -1;\n}\n\n", "hints_removed": "/*\nhttps://leetcode.com/problems/find-pivot-index/description/\nGiven an array of integers nums, calculate the pivot index of this array.\n\nThe pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.\n\nIf the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.\n\nReturn the leftmost pivot index. If no such index exists, return -1.\n\n \n\nExample 1:\n\nInput: nums = [1,7,3,6,5,6]\nOutput: 3\nExplanation:\nThe pivot index is 3.\nLeft sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11\nRight sum = nums[4] + nums[5] = 5 + 6 = 11\nExample 2:\n\nInput: nums = [1,2,3]\nOutput: -1\nExplanation:\nThere is no index that satisfies the conditions in the problem statement.\nExample 3:\n\nInput: nums = [2,1,-1]\nOutput: 0\nExplanation:\nThe pivot index is 0.\nLeft sum = 0 (no elements to the left of index 0)\nRight sum = nums[1] + nums[2] = 1 + -1 = 0\n\n```TypeScript\nfunction pivotIndex(nums: number[]): number {\n const n = nums.length;\n let leftsums = [0], rightsums = [0];\n for(let i=1; i < n+1; i++) {\n leftsums.push(nums[i-1]+leftsums[i-1]);\n rightsums.push(nums[n-i]+rightsums[i-1]);\n }\n for(let i=0; i <= n; i++) {\n if(leftsums[i] == rightsums[n-(i+1)]) return i;\n }\n return -1;\n};\n```\n*/\n\nfunction sum(nums: seq): int {\n // if |nums| == 0 then 0 else nums[0]+sum(nums[1..])\n if |nums| == 0 then 0 else sum(nums[0..(|nums|-1)])+nums[|nums|-1]\n}\n\n\nfunction sumUp(nums: seq): int {\n if |nums| == 0 then 0 else nums[0]+sumUp(nums[1..])\n}\n\n// By Divyanshu Ranjan\nlemma sumUpLemma(a: seq, b: seq)\n ensures sumUp(a + b) == sumUp(a) + sumUp(b)\n{\n if a == [] {\n }\n else {\n sumUpLemma(a[1..], b);\n calc {\n sumUp(a + b);\n {\n }\n a[0] + sumUp(a[1..] + b);\n a[0] + sumUp(a[1..]) + sumUp(b);\n }\n }\n}\n\n// By Divyanshu Ranjan\nlemma sumsEqual(nums: seq)\n ensures sum(nums) == sumUp(nums)\n{\n if nums == [] {}\n else {\n var ln := |nums|-1;\n calc {\n sumUp(nums[..]);\n {\n sumUpLemma(nums[0..ln], [nums[ln]]);\n }\n sumUp(nums[0..ln]) + sumUp([nums[ln]]);\n {\n }\n sumUp(nums[0..ln]) + nums[ln];\n {\n sumsEqual(nums[0..ln]);\n }\n sum(nums[0..ln]) + nums[ln];\n }\n }\n}\n\n\nmethod FindPivotIndex(nums: seq) returns (index: int)\n requires |nums| > 0\n ensures index == -1 ==> forall k: nat :: k < |nums| ==> sum(nums[0..k]) != sum(nums[(k+1)..])\n ensures 0 <= index < |nums| ==> sum(nums[0..index]) == sum(nums[(index+1)..])\n{\n var leftsums: seq := [0];\n var rightsums: seq := [0];\n var i := 1;\n while i < |nums|+1\n {\n leftsums := leftsums + [leftsums[i-1]+nums[i-1]]; \n rightsums := rightsums + [nums[|nums|-i]+rightsums[i-1]];\n i := i + 1;\n }\n\n forall k: nat | 0 <= k < i && k <= |nums|\n ensures sumUp(nums[(|nums|-k)..]) == sum(nums[(|nums|-k)..])\n ensures rightsums[k] == sumUp(nums[(|nums|-k)..])\n {\n sumsEqual(nums[(|nums|-k)..]);\n }\n }\n i :=0;\n while i < |nums| \n {\n var x := |nums|-(i+1);\n if leftsums[i] == rightsums[x] {\n // assert rightsums[i+1] == sum(nums[(|nums|-(i+1))..]);\n return i;\n }\n i := i + 1;\n }\n return -1;\n}\n\n" }, { "test_ID": "291", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_leetcode_ReverseLinkedList.dfy", "ground_truth": "/*\nhttps://leetcode.com/problems/reverse-linked-list/description/\n * class ListNode {\n * val: number\n * next: ListNode | null\n * constructor(val?: number, next?: ListNode | null) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n * }\n\nfunction reverseList(head: ListNode | null): ListNode | null {\n if (head == null) return null;\n\n let curr = head;\n let prev = null;\n while(curr !== null && curr.next !== null) {\n let next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n\n curr.next = prev;\n\n return curr;\n\n};\n*/\n\ndatatype ListNode = Null | Node(val: nat, next: ListNode)\n\nfunction reverse(x: seq): seq \n\n{\n if x == [] then [] else reverse(x[1..])+[x[0]]\n}\n\nfunction nodeConcat(xs: ListNode, end: ListNode): ListNode {\n if xs == Null then end else Node(xs.val, nodeConcat(xs.next, end))\n}\n\nfunction reverseList(xs: ListNode): ListNode\n\n{\n if xs == Null then Null else nodeConcat(reverseList(xs.next), Node(xs.val, Null))\n}\n\nlemma ConcatNullIsRightIdentity(xs: ListNode) \n ensures xs == nodeConcat(xs, Null)\n{\n\n}\n\nlemma ConcatNullIsLeftIdentity(xs: ListNode) \n ensures xs == nodeConcat(Null, xs)\n{\n\n}\n\nlemma ConcatExtensionality(xs: ListNode)\n requires xs != Null\n ensures nodeConcat(Node(xs.val, Null), xs.next) == xs;\n{\n\n}\n\nlemma ConcatAssociative(xs: ListNode, ys: ListNode, zs: ListNode)\n ensures nodeConcat(nodeConcat(xs, ys), zs) == nodeConcat(xs, nodeConcat(ys, zs))\n{\n\n}\n\nlemma reverseSingleList(xs: ListNode) \n requires xs != Null;\n requires xs.next == Null;\n ensures reverseList(xs) == xs;\n{\n\n}\n\n\n\nlemma {:verify true} ConcatReverseList(xs:ListNode, ys: ListNode) \n ensures reverseList(nodeConcat(xs,ys)) == nodeConcat(reverseList(ys), reverseList(xs))\n decreases xs;\n{\n if xs == Null {\n calc {\n reverseList(nodeConcat(xs,ys));\n == {ConcatNullIsLeftIdentity(ys);}\n reverseList(ys);\n == {ConcatNullIsRightIdentity(reverseList(ys));}\n nodeConcat(reverseList(ys), Null);\n nodeConcat(reverseList(ys), xs);\n nodeConcat(reverseList(ys), reverseList(xs));\n }\n }else{\n var x := Node(xs.val, Null);\n calc {\n reverseList(nodeConcat(xs, ys));\n reverseList(nodeConcat(nodeConcat(x, xs.next), ys));\n == {ConcatAssociative(x, xs.next, ys);}\n reverseList(nodeConcat(x, nodeConcat(xs.next, ys)));\n nodeConcat(reverseList(nodeConcat(xs.next, ys)), x);\n == {ConcatReverseList(xs.next, ys);}\n nodeConcat(nodeConcat(reverseList(ys) , reverseList(xs.next)), x);\n == {ConcatAssociative(reverseList(ys), reverseList(xs.next), x);}\n nodeConcat(reverseList(ys) , nodeConcat(reverseList(xs.next), x));\n nodeConcat(reverseList(ys) , reverseList(xs));\n }\n\n }\n}\n\nlemma reverseReverseListIsIdempotent(xs: ListNode)\n ensures reverseList(reverseList(xs)) == xs\n{\n if xs == Null {\n\n }else{\n var x := Node(xs.val, Null);\n calc {\n reverseList(reverseList(xs));\n reverseList(reverseList(nodeConcat(x, xs.next)));\n == {ConcatReverseList(x, xs.next);}\n reverseList(nodeConcat(reverseList(xs.next), reverseList(x)));\n reverseList(nodeConcat(reverseList(xs.next), x));\n == {ConcatReverseList(reverseList(xs.next),x);}\n nodeConcat(reverseList(x), reverseList(reverseList(xs.next))); //dafny can figure out the rest from here\n nodeConcat(x, reverseList(reverseList(xs.next)));\n nodeConcat(x, xs.next);\n xs;\n }\n }\n}\n\nlemma {:induction false} reversePreservesMultiset(xs: seq) \n ensures multiset(xs) == multiset(reverse(xs))\n{\n if xs == [] {\n\n }else {\n var x := xs[0];\n assert xs == [x] + xs[1..];\n assert multiset(xs) == multiset([x]) + multiset(xs[1..]);\n assert reverse(xs) == reverse(xs[1..])+[x];\n reversePreservesMultiset(xs[1..]);\n assert multiset(xs[1..]) == multiset(reverse(xs[1..]));\n }\n}\n\nlemma reversePreservesLength(xs: seq)\n ensures |xs| == |reverse(xs)|\n{\n\n}\n\nlemma lastReverseIsFirst(xs: seq)\n requires |xs| > 0\n ensures xs[0] == reverse(xs)[|reverse(xs)|-1]\n{\n reversePreservesLength(xs);\n assert |xs| == |reverse(xs)|;\n}\n\nlemma firstReverseIsLast(xs: seq)\n requires |xs| > 0\n ensures reverse(xs)[0] == xs[|xs|-1]\n{\n\n}\n\n lemma ReverseConcat(xs: seq, ys: seq)\n ensures reverse(xs + ys) == reverse(ys) + reverse(xs)\n {\n // reveal Reverse();\n if |xs| == 0 {\n assert xs + ys == ys;\n } else {\n assert xs + ys == [xs[0]] + (xs[1..] + ys);\n }\n }\n\n\nlemma reverseRest(xs: seq)\n requires |xs| > 0\n ensures reverse(xs) == [xs[ |xs| -1 ] ] + reverse(xs[0..|xs|-1])\n{\n firstReverseIsLast(xs);\n assert xs == xs[0..|xs|-1] + [xs[|xs|-1]];\n assert reverse(xs)[0] == xs[ |xs| -1];\n assert reverse(xs) == [xs[ |xs| -1]] + reverse(xs)[1..];\n calc {\n reverse(xs);\n reverse(xs[0..|xs|-1] + [xs[|xs|-1]]);\n == {ReverseConcat(xs[0..|xs|-1], [xs[ |xs|-1 ]]);}\n reverse([xs[ |xs|-1 ]]) + reverse(xs[0..|xs|-1]);\n\n }\n\n}\n\n\nlemma SeqEq(xs: seq, ys: seq)\n requires |xs| == |ys|\n requires forall i :: 0 <= i < |xs| ==> xs[i] == ys[i]\n ensures xs == ys\n{\n}\n\nlemma ReverseIndexAll(xs: seq)\n ensures |reverse(xs)| == |xs|\n ensures forall i :: 0 <= i < |xs| ==> reverse(xs)[i] == xs[|xs| - i - 1]\n{\n// reveal Reverse();\n}\n\n lemma ReverseIndex(xs: seq, i: int)\n requires 0 <= i < |xs|\n ensures |reverse(xs)| == |xs|\n ensures reverse(xs)[i] == xs[|xs| - i - 1]\n {\n ReverseIndexAll(xs);\n assert forall i :: 0 <= i < |xs| ==> reverse(xs)[i] == xs[|xs| - i - 1];\n }\n\nlemma ReverseSingle(xs: seq) \n requires |xs| == 1\n ensures reverse(xs) == xs\n{\n\n}\n\nlemma reverseReverseIdempotent(xs: seq) \n ensures reverse(reverse(xs)) == xs\n{\n if xs == [] {\n\n }else{\n calc {\n reverse(reverse(xs));\n reverse(reverse([xs[0]] + xs[1..]));\n == {ReverseConcat([xs[0]] , xs[1..]);}\n reverse(reverse(xs[1..]) + reverse([xs[0]]));\n == {ReverseSingle([xs[0]]);}\n reverse(reverse(xs[1..]) + [xs[0]]);\n == {ReverseConcat(reverse(xs[1..]), [xs[0]]);}\n reverse([xs[0]]) + reverse(reverse(xs[1..]));\n [xs[0]] + reverse(reverse(xs[1..]));\n == {reverseReverseIdempotent(xs[1..]);}\n xs;\n }\n }\n /* Alternatively */\n // ReverseIndexAll(reverse(xs));\n // ReverseIndexAll(xs);\n // SeqEq(reverse(reverse(xs)), xs);\n}\n\n// var x := xs[0];\n// assert xs == [x] + xs[1..];\n// reversePreservesLength(xs);\n// assert |xs| == |reverse(xs)|;\n// calc {\n// x;\n// reverse(xs)[|xs|-1];\n// == {firstReverseIsLast(reverse(xs));}\n// reverse(reverse(xs))[0];\n// }\n// var y := xs[|xs|-1];\n// calc{\n// y;\n// == {firstReverseIsLast(xs);}\n// reverse(xs)[0];\n// }\n// assert xs == xs[0..|xs|-1] + [y];\n// lastReverseIsFirst(xs);\n// lastReverseIsFirst(reverse(xs));\n\n// assert reverse(reverse(xs))[0] == x;\n\n/*\n/**\nhttps://leetcode.com/problems/linked-list-cycle/description/\n * Definition for singly-linked list.\n * class ListNode {\n * val: number\n * next: ListNode | null\n * constructor(val?: number, next?: ListNode | null) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n * }\n */\n\nfunction hasCycle(head: ListNode | null): boolean {\n let leader = head;\n let follower = head;\n while(leader !== null) {\n leader = leader.next;\n if(follower && follower.next) {\n follower = follower.next.next;\n }else if(follower && follower.next == null){\n follower=follower.next;\n }\n if(follower == leader && follower != null) return true;\n }\n return false;\n};\n*/\n\nmethod test() {\n var cycle := Node(1, Null);\n var next := Node(2, cycle);\n // cycle.next := next;\n}\n", "hints_removed": "/*\nhttps://leetcode.com/problems/reverse-linked-list/description/\n * class ListNode {\n * val: number\n * next: ListNode | null\n * constructor(val?: number, next?: ListNode | null) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n * }\n\nfunction reverseList(head: ListNode | null): ListNode | null {\n if (head == null) return null;\n\n let curr = head;\n let prev = null;\n while(curr !== null && curr.next !== null) {\n let next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n\n curr.next = prev;\n\n return curr;\n\n};\n*/\n\ndatatype ListNode = Null | Node(val: nat, next: ListNode)\n\nfunction reverse(x: seq): seq \n\n{\n if x == [] then [] else reverse(x[1..])+[x[0]]\n}\n\nfunction nodeConcat(xs: ListNode, end: ListNode): ListNode {\n if xs == Null then end else Node(xs.val, nodeConcat(xs.next, end))\n}\n\nfunction reverseList(xs: ListNode): ListNode\n\n{\n if xs == Null then Null else nodeConcat(reverseList(xs.next), Node(xs.val, Null))\n}\n\nlemma ConcatNullIsRightIdentity(xs: ListNode) \n ensures xs == nodeConcat(xs, Null)\n{\n\n}\n\nlemma ConcatNullIsLeftIdentity(xs: ListNode) \n ensures xs == nodeConcat(Null, xs)\n{\n\n}\n\nlemma ConcatExtensionality(xs: ListNode)\n requires xs != Null\n ensures nodeConcat(Node(xs.val, Null), xs.next) == xs;\n{\n\n}\n\nlemma ConcatAssociative(xs: ListNode, ys: ListNode, zs: ListNode)\n ensures nodeConcat(nodeConcat(xs, ys), zs) == nodeConcat(xs, nodeConcat(ys, zs))\n{\n\n}\n\nlemma reverseSingleList(xs: ListNode) \n requires xs != Null;\n requires xs.next == Null;\n ensures reverseList(xs) == xs;\n{\n\n}\n\n\n\nlemma {:verify true} ConcatReverseList(xs:ListNode, ys: ListNode) \n ensures reverseList(nodeConcat(xs,ys)) == nodeConcat(reverseList(ys), reverseList(xs))\n{\n if xs == Null {\n calc {\n reverseList(nodeConcat(xs,ys));\n == {ConcatNullIsLeftIdentity(ys);}\n reverseList(ys);\n == {ConcatNullIsRightIdentity(reverseList(ys));}\n nodeConcat(reverseList(ys), Null);\n nodeConcat(reverseList(ys), xs);\n nodeConcat(reverseList(ys), reverseList(xs));\n }\n }else{\n var x := Node(xs.val, Null);\n calc {\n reverseList(nodeConcat(xs, ys));\n reverseList(nodeConcat(nodeConcat(x, xs.next), ys));\n == {ConcatAssociative(x, xs.next, ys);}\n reverseList(nodeConcat(x, nodeConcat(xs.next, ys)));\n nodeConcat(reverseList(nodeConcat(xs.next, ys)), x);\n == {ConcatReverseList(xs.next, ys);}\n nodeConcat(nodeConcat(reverseList(ys) , reverseList(xs.next)), x);\n == {ConcatAssociative(reverseList(ys), reverseList(xs.next), x);}\n nodeConcat(reverseList(ys) , nodeConcat(reverseList(xs.next), x));\n nodeConcat(reverseList(ys) , reverseList(xs));\n }\n\n }\n}\n\nlemma reverseReverseListIsIdempotent(xs: ListNode)\n ensures reverseList(reverseList(xs)) == xs\n{\n if xs == Null {\n\n }else{\n var x := Node(xs.val, Null);\n calc {\n reverseList(reverseList(xs));\n reverseList(reverseList(nodeConcat(x, xs.next)));\n == {ConcatReverseList(x, xs.next);}\n reverseList(nodeConcat(reverseList(xs.next), reverseList(x)));\n reverseList(nodeConcat(reverseList(xs.next), x));\n == {ConcatReverseList(reverseList(xs.next),x);}\n nodeConcat(reverseList(x), reverseList(reverseList(xs.next))); //dafny can figure out the rest from here\n nodeConcat(x, reverseList(reverseList(xs.next)));\n nodeConcat(x, xs.next);\n xs;\n }\n }\n}\n\nlemma {:induction false} reversePreservesMultiset(xs: seq) \n ensures multiset(xs) == multiset(reverse(xs))\n{\n if xs == [] {\n\n }else {\n var x := xs[0];\n reversePreservesMultiset(xs[1..]);\n }\n}\n\nlemma reversePreservesLength(xs: seq)\n ensures |xs| == |reverse(xs)|\n{\n\n}\n\nlemma lastReverseIsFirst(xs: seq)\n requires |xs| > 0\n ensures xs[0] == reverse(xs)[|reverse(xs)|-1]\n{\n reversePreservesLength(xs);\n}\n\nlemma firstReverseIsLast(xs: seq)\n requires |xs| > 0\n ensures reverse(xs)[0] == xs[|xs|-1]\n{\n\n}\n\n lemma ReverseConcat(xs: seq, ys: seq)\n ensures reverse(xs + ys) == reverse(ys) + reverse(xs)\n {\n // reveal Reverse();\n if |xs| == 0 {\n } else {\n }\n }\n\n\nlemma reverseRest(xs: seq)\n requires |xs| > 0\n ensures reverse(xs) == [xs[ |xs| -1 ] ] + reverse(xs[0..|xs|-1])\n{\n firstReverseIsLast(xs);\n calc {\n reverse(xs);\n reverse(xs[0..|xs|-1] + [xs[|xs|-1]]);\n == {ReverseConcat(xs[0..|xs|-1], [xs[ |xs|-1 ]]);}\n reverse([xs[ |xs|-1 ]]) + reverse(xs[0..|xs|-1]);\n\n }\n\n}\n\n\nlemma SeqEq(xs: seq, ys: seq)\n requires |xs| == |ys|\n requires forall i :: 0 <= i < |xs| ==> xs[i] == ys[i]\n ensures xs == ys\n{\n}\n\nlemma ReverseIndexAll(xs: seq)\n ensures |reverse(xs)| == |xs|\n ensures forall i :: 0 <= i < |xs| ==> reverse(xs)[i] == xs[|xs| - i - 1]\n{\n// reveal Reverse();\n}\n\n lemma ReverseIndex(xs: seq, i: int)\n requires 0 <= i < |xs|\n ensures |reverse(xs)| == |xs|\n ensures reverse(xs)[i] == xs[|xs| - i - 1]\n {\n ReverseIndexAll(xs);\n }\n\nlemma ReverseSingle(xs: seq) \n requires |xs| == 1\n ensures reverse(xs) == xs\n{\n\n}\n\nlemma reverseReverseIdempotent(xs: seq) \n ensures reverse(reverse(xs)) == xs\n{\n if xs == [] {\n\n }else{\n calc {\n reverse(reverse(xs));\n reverse(reverse([xs[0]] + xs[1..]));\n == {ReverseConcat([xs[0]] , xs[1..]);}\n reverse(reverse(xs[1..]) + reverse([xs[0]]));\n == {ReverseSingle([xs[0]]);}\n reverse(reverse(xs[1..]) + [xs[0]]);\n == {ReverseConcat(reverse(xs[1..]), [xs[0]]);}\n reverse([xs[0]]) + reverse(reverse(xs[1..]));\n [xs[0]] + reverse(reverse(xs[1..]));\n == {reverseReverseIdempotent(xs[1..]);}\n xs;\n }\n }\n /* Alternatively */\n // ReverseIndexAll(reverse(xs));\n // ReverseIndexAll(xs);\n // SeqEq(reverse(reverse(xs)), xs);\n}\n\n// var x := xs[0];\n// assert xs == [x] + xs[1..];\n// reversePreservesLength(xs);\n// assert |xs| == |reverse(xs)|;\n// calc {\n// x;\n// reverse(xs)[|xs|-1];\n// == {firstReverseIsLast(reverse(xs));}\n// reverse(reverse(xs))[0];\n// }\n// var y := xs[|xs|-1];\n// calc{\n// y;\n// == {firstReverseIsLast(xs);}\n// reverse(xs)[0];\n// }\n// assert xs == xs[0..|xs|-1] + [y];\n// lastReverseIsFirst(xs);\n// lastReverseIsFirst(reverse(xs));\n\n// assert reverse(reverse(xs))[0] == x;\n\n/*\n/**\nhttps://leetcode.com/problems/linked-list-cycle/description/\n * Definition for singly-linked list.\n * class ListNode {\n * val: number\n * next: ListNode | null\n * constructor(val?: number, next?: ListNode | null) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n * }\n */\n\nfunction hasCycle(head: ListNode | null): boolean {\n let leader = head;\n let follower = head;\n while(leader !== null) {\n leader = leader.next;\n if(follower && follower.next) {\n follower = follower.next.next;\n }else if(follower && follower.next == null){\n follower=follower.next;\n }\n if(follower == leader && follower != null) return true;\n }\n return false;\n};\n*/\n\nmethod test() {\n var cycle := Node(1, Null);\n var next := Node(2, cycle);\n // cycle.next := next;\n}\n" }, { "test_ID": "292", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_leetcode_lc-remove-element.dfy", "ground_truth": "//https://leetcode.com/problems/remove-element/\nmethod removeElement(nums: array, val: int) returns (i: int)\n ensures forall k :: 0 < k < i < nums.Length ==> nums[k] != val\n modifies nums\n{\n i := 0;\n var end := nums.Length - 1;\n while i <= end \n invariant 0 <= i <= nums.Length\n invariant end < nums.Length\n invariant forall k :: 0 <= k < i ==> nums[k] != val\n {\n if(nums[i] == val) {\n if(nums[end] == val) {\n end := end - 1;\n }else{\n nums[i], nums[end] := nums[end], nums[i];\n i := i + 1;\n end := end - 1;\n }\n }else{\n i := i + 1;\n }\n }\n}\n///compileTarget:js\nmethod Main() {\n var elems := new int[5][1,2,3,4,5];\n var res := removeElement(elems, 5);\n print res, \"\\n\", elems;\n\n}\n", "hints_removed": "//https://leetcode.com/problems/remove-element/\nmethod removeElement(nums: array, val: int) returns (i: int)\n ensures forall k :: 0 < k < i < nums.Length ==> nums[k] != val\n modifies nums\n{\n i := 0;\n var end := nums.Length - 1;\n while i <= end \n {\n if(nums[i] == val) {\n if(nums[end] == val) {\n end := end - 1;\n }else{\n nums[i], nums[end] := nums[end], nums[i];\n i := i + 1;\n end := end - 1;\n }\n }else{\n i := i + 1;\n }\n }\n}\n///compileTarget:js\nmethod Main() {\n var elems := new int[5][1,2,3,4,5];\n var res := removeElement(elems, 5);\n print res, \"\\n\", elems;\n\n}\n" }, { "test_ID": "293", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_leetcode_pathSum.dfy", "ground_truth": "//https://leetcode.com/problems/path-sum\n/**\nfunction hasPathSum(root: TreeNode | null, targetSum: number): boolean {\n if(root == null) {\n return false;\n }\n if(root.val-targetSum == 0 && root.left == null && root.right == null) {\n return true;\n }\n return hasPathSum(root.left, targetSum-root.val) || hasPathSum(root.right, targetSum-root.val);\n};\n */\n\ndatatype TreeNode = Nil | Cons(val: nat, left: TreeNode, right: TreeNode)\n\nfunction TreeSeq(root: TreeNode): seq {\n match root {\n case Nil => [Nil]\n case Cons(val, left, right) => [root]+TreeSeq(left)+TreeSeq(right)\n }\n}\n\nfunction TreeSet(root: TreeNode): set {\n match root {\n case Nil => {Nil}\n case Cons(val, left, right) => TreeSet(left)+{root}+TreeSet(right)\n }\n}\n\npredicate isPath(paths: seq, root: TreeNode) {\n if |paths| == 0 then false else match paths[0] {\n case Nil => false\n case Cons(val, left, right) => if |paths| == 1 then root == paths[0] else root == paths[0] && (isPath(paths[1..], left) || isPath(paths[1..], right))\n }\n}\n\nfunction pathSum(paths: seq): nat {\n if |paths| == 0 then 0 else match paths[0] {\n case Nil => 0\n case Cons(val, left, right) => val + pathSum(paths[1..])\n }\n}\n\nmethod hasPathSum(root: TreeNode, targetSum: int) returns (b: bool) \n ensures b ==> exists p: seq :: isPath(p, root) && pathSum(p) == targetSum\n{\n if root == Nil {\n return false;\n }\n\n if(root.val - targetSum == 0 && root.left == Nil && root.right == Nil) {\n assert isPath([root], root) && pathSum([root]) == targetSum;\n return true;\n }\n var leftPath := hasPathSum(root.left, targetSum-root.val);\n var rightPath := hasPathSum(root.right, targetSum-root.val);\n\n if leftPath {\n ghost var p: seq :| isPath(p, root.left) && pathSum(p) == targetSum-root.val;\n assert isPath([root]+p, root) && pathSum([root]+p) == targetSum;\n }\n if rightPath {\n ghost var p: seq :| isPath(p, root.right) && pathSum(p) == targetSum-root.val;\n assert isPath([root]+p, root) && pathSum([root]+p) == targetSum;\n }\n return leftPath || rightPath;\n}\n\nmethod Test() {\n var c := Cons(3, Nil, Nil);\n var b := Cons(2, c, Nil);\n var a := Cons(1, b, Nil);\n assert isPath([a], a);\n assert a.left == b;\n assert isPath([a,b], a);\n assert isPath([a,b,c], a);\n}\n\n\n\n", "hints_removed": "//https://leetcode.com/problems/path-sum\n/**\nfunction hasPathSum(root: TreeNode | null, targetSum: number): boolean {\n if(root == null) {\n return false;\n }\n if(root.val-targetSum == 0 && root.left == null && root.right == null) {\n return true;\n }\n return hasPathSum(root.left, targetSum-root.val) || hasPathSum(root.right, targetSum-root.val);\n};\n */\n\ndatatype TreeNode = Nil | Cons(val: nat, left: TreeNode, right: TreeNode)\n\nfunction TreeSeq(root: TreeNode): seq {\n match root {\n case Nil => [Nil]\n case Cons(val, left, right) => [root]+TreeSeq(left)+TreeSeq(right)\n }\n}\n\nfunction TreeSet(root: TreeNode): set {\n match root {\n case Nil => {Nil}\n case Cons(val, left, right) => TreeSet(left)+{root}+TreeSet(right)\n }\n}\n\npredicate isPath(paths: seq, root: TreeNode) {\n if |paths| == 0 then false else match paths[0] {\n case Nil => false\n case Cons(val, left, right) => if |paths| == 1 then root == paths[0] else root == paths[0] && (isPath(paths[1..], left) || isPath(paths[1..], right))\n }\n}\n\nfunction pathSum(paths: seq): nat {\n if |paths| == 0 then 0 else match paths[0] {\n case Nil => 0\n case Cons(val, left, right) => val + pathSum(paths[1..])\n }\n}\n\nmethod hasPathSum(root: TreeNode, targetSum: int) returns (b: bool) \n ensures b ==> exists p: seq :: isPath(p, root) && pathSum(p) == targetSum\n{\n if root == Nil {\n return false;\n }\n\n if(root.val - targetSum == 0 && root.left == Nil && root.right == Nil) {\n return true;\n }\n var leftPath := hasPathSum(root.left, targetSum-root.val);\n var rightPath := hasPathSum(root.right, targetSum-root.val);\n\n if leftPath {\n ghost var p: seq :| isPath(p, root.left) && pathSum(p) == targetSum-root.val;\n }\n if rightPath {\n ghost var p: seq :| isPath(p, root.right) && pathSum(p) == targetSum-root.val;\n }\n return leftPath || rightPath;\n}\n\nmethod Test() {\n var c := Cons(3, Nil, Nil);\n var b := Cons(2, c, Nil);\n var a := Cons(1, b, Nil);\n}\n\n\n\n" }, { "test_ID": "294", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_leetcode_stairClimbing.dfy", "ground_truth": "/*\nYou are climbing a staircase. It takes n steps to reach the top.\n\nEach time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?\nfunction climbStairs(n: number): number {\n let steps = new Array(n+1);\n steps[0] = 0;\n steps[1] = 1;\n steps[2] = 2;\n for(let i = 3; i <= n; i++) {\n steps[i] = steps[i-1] + steps[i-2];\n }\n return steps[n];\n};\n*/\n\ndatatype Steps = One | Two\n\nfunction stepSum(xs: seq): nat {\n if xs == [] then 0 else (match xs[0] {\n case One => 1\n case Two => 2\n } + stepSum(xs[1..]))\n}\n\nghost predicate stepEndsAt(xs: seq, n: nat) {\n stepSum(xs) == n\n}\nghost predicate allEndAtN(ss: set >, n: nat) {\n forall xs :: xs in ss ==> stepEndsAt(xs, n)\n}\n\nlemma stepBaseZero() \n ensures exists ss: set< seq > :: allEndAtN(ss, 0) && |ss| == 0\n{\n assert allEndAtN({[]}, 0);\n}\nlemma stepBaseOne() \n ensures exists ss: set< seq > :: allEndAtN(ss, 1) && |ss| == 1\n{\n assert allEndAtN({[One]}, 1);\n}\n\nlemma stepBaseTwo() \n ensures exists ss: set< seq > :: allEndAtN(ss, 2) && |ss| == 2\n{\n assert allEndAtN({[One,One], [Two]}, 2);\n}\n\nghost function plusOne(x: seq): seq {\n [One]+x\n}\n\nghost function addOne(ss: set>): set> \n ensures forall x :: x in ss ==> plusOne(x) in addOne(ss)\n ensures addOne(ss) == set x | x in ss :: plusOne(x)\n{\n set x | x in ss :: plusOne(x)\n}\n\nlemma SeqsNotEqualImplication(xs: seq, ys: seq, someT: T)\n requires xs != ys\n ensures (exists i: nat :: i < |xs| && i <|ys| && xs[i] != ys[i]) || |xs| < |ys| || |ys| < |xs|\n{}\n\nlemma UnequalSeqs(xs: seq, ys: seq, someT: T)\n requires xs != ys\n ensures [someT]+xs != [someT]+ys\n{\n if |xs| < |ys| {} else if |ys| > |xs| {}\n else if i: nat :| i < |xs| && i <|ys| && xs[i] != ys[i] {\n assert ([someT]+xs)[i+1] != ([someT]+ys)[i+1];\n }\n}\n\nlemma plusOneNotIn(ss: set>, x: seq)\n requires x !in ss\n ensures plusOne(x) !in addOne(ss)\n{\n if x == [] {\n assert [] !in ss;\n assert [One]+[] !in addOne(ss);\n }\n if plusOne(x) in addOne(ss) {\n forall y | y in ss \n ensures y != x\n ensures plusOne(y) in addOne(ss)\n ensures plusOne(y) != plusOne(x)\n {\n UnequalSeqs(x, y, One);\n assert plusOne(y) != [One]+x;\n }\n assert false;\n }\n}\n\nlemma addOneSize(ss: set>)\n ensures |addOne(ss)| == |ss|\n{\n var size := |ss|;\n if x :| x in ss {\n assert |ss - {x}| == size - 1;\n addOneSize(ss - {x});\n assert |addOne(ss-{x})| == size - 1;\n assert addOne(ss) == addOne(ss-{x}) + {[One]+x};\n assert x !in ss-{x};\n plusOneNotIn(ss-{x}, x);\n assert plusOne(x) !in addOne(ss-{x});\n assert |addOne(ss)| == |addOne(ss-{x})| + |{[One]+x}|;\n }else{\n\n }\n}\n\nlemma addOneSum(ss: set>, sum: nat) \n requires allEndAtN(ss, sum)\n ensures allEndAtN(addOne(ss), sum+1)\n{\n\n}\n\nlemma endAtNPlus(ss: set>, sz: set>, sum: nat)\n requires allEndAtN(ss, sum)\n requires allEndAtN(sz, sum)\n ensures allEndAtN(ss+sz, sum)\n{\n\n}\n\nghost function plusTwo(x: seq): seq {\n [Two]+x\n}\n\nghost function addTwo(ss: set>): set> \n ensures forall x :: x in ss ==> plusTwo(x) in addTwo(ss)\n ensures addTwo(ss) == set x | x in ss :: plusTwo(x)\n{\n set x | x in ss :: plusTwo(x)\n}\n\nlemma plusTwoNotIn(ss: set>, x: seq)\n requires x !in ss\n ensures plusTwo(x) !in addTwo(ss)\n{\n if x == [] {\n assert [] !in ss;\n assert [Two]+[] !in addTwo(ss);\n }\n if plusTwo(x) in addTwo(ss) {\n forall y | y in ss \n ensures y != x\n ensures plusTwo(y) in addTwo(ss)\n ensures plusTwo(y) != plusTwo(x)\n {\n UnequalSeqs(x, y, Two);\n assert plusTwo(y) != [Two]+x;\n }\n }\n}\n\nlemma addTwoSize(ss: set>)\n ensures |addTwo(ss)| == |ss|\n{\n var size := |ss|;\n if x :| x in ss {\n // assert |ss - {x}| == size - 1;\n addTwoSize(ss - {x});\n // assert |addTwo(ss-{x})| == size - 1;\n assert addTwo(ss) == addTwo(ss-{x}) + {[Two]+x};\n // assert x !in ss-{x};\n plusTwoNotIn(ss-{x}, x);\n // assert plusTwo(x) !in addTwo(ss-{x});\n assert |addTwo(ss)| == |addTwo(ss-{x})| + |{[Two]+x}|;\n }\n}\n\nlemma addTwoSum(ss: set>, sum: nat) \n requires allEndAtN(ss, sum)\n ensures allEndAtN(addTwo(ss), sum+2)\n{\n\n}\n\nlemma setSizeAddition(sx: set, sy: set, sz: set) \n requires sx !! sy\n requires sz == sx + sy\n ensures |sx + sy| == |sx| + |sy|\n ensures |sz| == |sx| + |sy|\n{\n\n}\n\nlemma stepSetsAdd(i: nat, steps: array) \n requires i >= 2\n requires steps.Length >= i+1\n requires forall k: nat :: k < i ==> exists ss: set< seq > :: steps[k] == |ss| && allEndAtN(ss, k)\n ensures exists sp : set< seq > :: |sp| == steps[i-1] + steps[i-2] && allEndAtN(sp, i)\n{\n var oneStepBack :| steps[i-1] == |oneStepBack| && allEndAtN(oneStepBack, i-1);\n var twoStepBack :| steps[i-2] == |twoStepBack| && allEndAtN(twoStepBack, i-2);\n var stepForward := addOne(oneStepBack);\n var stepTwoForward := addTwo(twoStepBack);\n assert forall x :: x in stepForward ==> x[0] == One;\n // assert stepForward !! stepTwoForward;\n addOneSize(oneStepBack);\n addTwoSize(twoStepBack);\n var sumSet := stepForward + stepTwoForward;\n // assert |sumSet| == steps[i-1]+steps[i-2];\n}\n\nmethod climbStairs(n: nat) returns (count: nat) \n ensures exists ss: set< seq > :: count == |ss| && allEndAtN(ss, n)\n{\n var steps := new nat[n+1];\n steps[0] := 0;\n if n > 0 {\n steps[1] := 1;\n }\n if n > 1 {\n steps[2] := 2;\n }\n stepBaseZero();\n stepBaseOne();\n stepBaseTwo();\n if n < 3 {\n return steps[n];\n }\n assert steps[0] == 0;\n assert steps[1] == 1;\n assert steps[2] == 2;\n assert forall k: nat :: k < 3 ==> exists ss: set< seq > :: steps[k] == |ss| && allEndAtN(ss, k);\n var i := 3;\n while i <= n \n invariant 3 <= i <= n+1\n invariant forall k: nat :: k < i ==> exists ss: set< seq > :: steps[k] == |ss| && allEndAtN(ss, k)\n { \n steps[i] := steps[i-1] + steps[i-2];\n stepSetsAdd(i, steps);\n i := i + 1;\n }\n return steps[n];\n}\n\n\nmethod Test() {\n var foo := [One, One, Two];\n assert stepSum(foo) == 4;\n}\n", "hints_removed": "/*\nYou are climbing a staircase. It takes n steps to reach the top.\n\nEach time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?\nfunction climbStairs(n: number): number {\n let steps = new Array(n+1);\n steps[0] = 0;\n steps[1] = 1;\n steps[2] = 2;\n for(let i = 3; i <= n; i++) {\n steps[i] = steps[i-1] + steps[i-2];\n }\n return steps[n];\n};\n*/\n\ndatatype Steps = One | Two\n\nfunction stepSum(xs: seq): nat {\n if xs == [] then 0 else (match xs[0] {\n case One => 1\n case Two => 2\n } + stepSum(xs[1..]))\n}\n\nghost predicate stepEndsAt(xs: seq, n: nat) {\n stepSum(xs) == n\n}\nghost predicate allEndAtN(ss: set >, n: nat) {\n forall xs :: xs in ss ==> stepEndsAt(xs, n)\n}\n\nlemma stepBaseZero() \n ensures exists ss: set< seq > :: allEndAtN(ss, 0) && |ss| == 0\n{\n}\nlemma stepBaseOne() \n ensures exists ss: set< seq > :: allEndAtN(ss, 1) && |ss| == 1\n{\n}\n\nlemma stepBaseTwo() \n ensures exists ss: set< seq > :: allEndAtN(ss, 2) && |ss| == 2\n{\n}\n\nghost function plusOne(x: seq): seq {\n [One]+x\n}\n\nghost function addOne(ss: set>): set> \n ensures forall x :: x in ss ==> plusOne(x) in addOne(ss)\n ensures addOne(ss) == set x | x in ss :: plusOne(x)\n{\n set x | x in ss :: plusOne(x)\n}\n\nlemma SeqsNotEqualImplication(xs: seq, ys: seq, someT: T)\n requires xs != ys\n ensures (exists i: nat :: i < |xs| && i <|ys| && xs[i] != ys[i]) || |xs| < |ys| || |ys| < |xs|\n{}\n\nlemma UnequalSeqs(xs: seq, ys: seq, someT: T)\n requires xs != ys\n ensures [someT]+xs != [someT]+ys\n{\n if |xs| < |ys| {} else if |ys| > |xs| {}\n else if i: nat :| i < |xs| && i <|ys| && xs[i] != ys[i] {\n }\n}\n\nlemma plusOneNotIn(ss: set>, x: seq)\n requires x !in ss\n ensures plusOne(x) !in addOne(ss)\n{\n if x == [] {\n }\n if plusOne(x) in addOne(ss) {\n forall y | y in ss \n ensures y != x\n ensures plusOne(y) in addOne(ss)\n ensures plusOne(y) != plusOne(x)\n {\n UnequalSeqs(x, y, One);\n }\n }\n}\n\nlemma addOneSize(ss: set>)\n ensures |addOne(ss)| == |ss|\n{\n var size := |ss|;\n if x :| x in ss {\n addOneSize(ss - {x});\n plusOneNotIn(ss-{x}, x);\n }else{\n\n }\n}\n\nlemma addOneSum(ss: set>, sum: nat) \n requires allEndAtN(ss, sum)\n ensures allEndAtN(addOne(ss), sum+1)\n{\n\n}\n\nlemma endAtNPlus(ss: set>, sz: set>, sum: nat)\n requires allEndAtN(ss, sum)\n requires allEndAtN(sz, sum)\n ensures allEndAtN(ss+sz, sum)\n{\n\n}\n\nghost function plusTwo(x: seq): seq {\n [Two]+x\n}\n\nghost function addTwo(ss: set>): set> \n ensures forall x :: x in ss ==> plusTwo(x) in addTwo(ss)\n ensures addTwo(ss) == set x | x in ss :: plusTwo(x)\n{\n set x | x in ss :: plusTwo(x)\n}\n\nlemma plusTwoNotIn(ss: set>, x: seq)\n requires x !in ss\n ensures plusTwo(x) !in addTwo(ss)\n{\n if x == [] {\n }\n if plusTwo(x) in addTwo(ss) {\n forall y | y in ss \n ensures y != x\n ensures plusTwo(y) in addTwo(ss)\n ensures plusTwo(y) != plusTwo(x)\n {\n UnequalSeqs(x, y, Two);\n }\n }\n}\n\nlemma addTwoSize(ss: set>)\n ensures |addTwo(ss)| == |ss|\n{\n var size := |ss|;\n if x :| x in ss {\n // assert |ss - {x}| == size - 1;\n addTwoSize(ss - {x});\n // assert |addTwo(ss-{x})| == size - 1;\n // assert x !in ss-{x};\n plusTwoNotIn(ss-{x}, x);\n // assert plusTwo(x) !in addTwo(ss-{x});\n }\n}\n\nlemma addTwoSum(ss: set>, sum: nat) \n requires allEndAtN(ss, sum)\n ensures allEndAtN(addTwo(ss), sum+2)\n{\n\n}\n\nlemma setSizeAddition(sx: set, sy: set, sz: set) \n requires sx !! sy\n requires sz == sx + sy\n ensures |sx + sy| == |sx| + |sy|\n ensures |sz| == |sx| + |sy|\n{\n\n}\n\nlemma stepSetsAdd(i: nat, steps: array) \n requires i >= 2\n requires steps.Length >= i+1\n requires forall k: nat :: k < i ==> exists ss: set< seq > :: steps[k] == |ss| && allEndAtN(ss, k)\n ensures exists sp : set< seq > :: |sp| == steps[i-1] + steps[i-2] && allEndAtN(sp, i)\n{\n var oneStepBack :| steps[i-1] == |oneStepBack| && allEndAtN(oneStepBack, i-1);\n var twoStepBack :| steps[i-2] == |twoStepBack| && allEndAtN(twoStepBack, i-2);\n var stepForward := addOne(oneStepBack);\n var stepTwoForward := addTwo(twoStepBack);\n // assert stepForward !! stepTwoForward;\n addOneSize(oneStepBack);\n addTwoSize(twoStepBack);\n var sumSet := stepForward + stepTwoForward;\n // assert |sumSet| == steps[i-1]+steps[i-2];\n}\n\nmethod climbStairs(n: nat) returns (count: nat) \n ensures exists ss: set< seq > :: count == |ss| && allEndAtN(ss, n)\n{\n var steps := new nat[n+1];\n steps[0] := 0;\n if n > 0 {\n steps[1] := 1;\n }\n if n > 1 {\n steps[2] := 2;\n }\n stepBaseZero();\n stepBaseOne();\n stepBaseTwo();\n if n < 3 {\n return steps[n];\n }\n var i := 3;\n while i <= n \n { \n steps[i] := steps[i-1] + steps[i-2];\n stepSetsAdd(i, steps);\n i := i + 1;\n }\n return steps[n];\n}\n\n\nmethod Test() {\n var foo := [One, One, Two];\n}\n" }, { "test_ID": "295", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_leetcode_validAnagram.dfy", "ground_truth": "\nmethod toMultiset(s: string) returns (mset: multiset)\n ensures multiset(s) == mset\n{\n mset := multiset{};\n for i := 0 to |s| \n invariant mset == multiset(s[0..i])\n {\n assert s == s[0..i] + [s[i]] + s[(i+1)..];\n // assert multiset(s) == multiset(s[0..i])+multiset{s[i]}+multiset(s[(i+1)..]);\n mset := mset + multiset{s[i]};\n }\n assert s == s[0..|s|];\n // assert mset == multiset(s[0..|s|]);\n return mset;\n}\n\nmethod msetEqual(s: multiset, t: multiset) returns (equal: bool)\n ensures s == t <==> equal\n{\n ghost var sremoved: multiset := multiset{};\n var scopy := s;\n while scopy != multiset{} \n invariant s - sremoved == scopy\n invariant sremoved !! scopy\n invariant sremoved <= s\n invariant forall x :: x in sremoved ==> x in s && x in t && t[x] == s[x]\n {\n var x :| x in scopy;\n if !(x in t && s[x] == t[x]) {\n return false; \n }\n var removed := multiset{};\n // assert removed[x := s[x]] <= s;\n sremoved := sremoved + removed[x := s[x]];\n scopy := scopy - removed[x := s[x]];\n }\n // assert scopy == multiset{};\n // assert s - sremoved == scopy;\n // assert sremoved == s;\n // assert forall x :: x in sremoved ==> x in s && x in t && t[x] == s[x];\n\n ghost var tremoved: multiset := multiset{};\n var tcopy := t;\n while tcopy != multiset{} \n invariant t - tremoved == tcopy\n invariant tremoved !! tcopy\n invariant tremoved <= t\n invariant forall x :: x in tremoved ==> x in s && x in t && t[x] == s[x]\n {\n var x :| x in tcopy;\n if !(x in t && s[x] == t[x]) {\n return false; \n }\n var removed := multiset{};\n tremoved := tremoved + removed[x := s[x]];\n tcopy := tcopy - removed[x := s[x]];\n }\n // assert forall x :: x in tremoved ==> x in s && x in t && t[x] == s[x];\n\n return true;\n}\n\nmethod isAnagram(s: string, t: string) returns (equal: bool)\n ensures (multiset(s) == multiset(t)) == equal\n{\n var smset := toMultiset(s);\n var tmset := toMultiset(t);\n equal := msetEqual(smset, tmset);\n}\n", "hints_removed": "\nmethod toMultiset(s: string) returns (mset: multiset)\n ensures multiset(s) == mset\n{\n mset := multiset{};\n for i := 0 to |s| \n {\n // assert multiset(s) == multiset(s[0..i])+multiset{s[i]}+multiset(s[(i+1)..]);\n mset := mset + multiset{s[i]};\n }\n // assert mset == multiset(s[0..|s|]);\n return mset;\n}\n\nmethod msetEqual(s: multiset, t: multiset) returns (equal: bool)\n ensures s == t <==> equal\n{\n ghost var sremoved: multiset := multiset{};\n var scopy := s;\n while scopy != multiset{} \n {\n var x :| x in scopy;\n if !(x in t && s[x] == t[x]) {\n return false; \n }\n var removed := multiset{};\n // assert removed[x := s[x]] <= s;\n sremoved := sremoved + removed[x := s[x]];\n scopy := scopy - removed[x := s[x]];\n }\n // assert scopy == multiset{};\n // assert s - sremoved == scopy;\n // assert sremoved == s;\n // assert forall x :: x in sremoved ==> x in s && x in t && t[x] == s[x];\n\n ghost var tremoved: multiset := multiset{};\n var tcopy := t;\n while tcopy != multiset{} \n {\n var x :| x in tcopy;\n if !(x in t && s[x] == t[x]) {\n return false; \n }\n var removed := multiset{};\n tremoved := tremoved + removed[x := s[x]];\n tcopy := tcopy - removed[x := s[x]];\n }\n // assert forall x :: x in tremoved ==> x in s && x in t && t[x] == s[x];\n\n return true;\n}\n\nmethod isAnagram(s: string, t: string) returns (equal: bool)\n ensures (multiset(s) == multiset(t)) == equal\n{\n var smset := toMultiset(s);\n var tmset := toMultiset(t);\n equal := msetEqual(smset, tmset);\n}\n" }, { "test_ID": "296", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_lib_seq.dfy", "ground_truth": "\nmodule Seq {\n export reveals *\n function ToSet(xs: seq): set\n ensures forall x :: x in ToSet(xs) ==> x in xs\n ensures forall x :: x !in ToSet(xs) ==> x !in xs\n {\n if xs == [] then {} else {xs[0]}+ToSet(xs[1..])\n }\n\n predicate substring1(sub: seq, super: seq) {\n exists k :: 0 <= k < |super| && sub <= super[k..]\n }\n\n\n ghost predicate isSubstringAlt(sub: seq, super: seq) {\n |sub| <= |super| && exists xs: seq :: IsSuffix(xs, super) && sub <= xs\n }\n\n predicate isSubstring(sub: seq, super: seq) {\n |sub| <= |super| && exists k,j :: 0 <= k < j <= |super| && sub == super[k..j]\n }\n\n lemma SliceOfSliceIsSlice(xs: seq, k: int, j: int, s: int, t: int)\n requires 0 <= k <= j <= |xs|\n requires 0 <= s <= t <= j-k\n ensures xs[k..j][s..t] == xs[(k+s)..(k+s+(t-s))]\n {\n if j-k == 0 {\n }else if t-s == 0 {\n }else if t-s > 0 {\n SliceOfSliceIsSlice(xs, k, j, s,t-1);\n assert xs[k..j][s..t] == xs[k..j][s..(t-1)]+[xs[k..j][t-1]];\n }\n }\n\n\n\n lemma AllSubstringsAreSubstrings(subsub: seq, sub: seq, super: seq)\n requires isSubstring(sub, super)\n requires isSubstring(subsub, sub)\n ensures isSubstring(subsub, super)\n {\n assert |sub| <= |super|;\n assert |subsub| <= |super|;\n var k,j :| 0 <= k < j <= |super| && sub == super[k..j];\n var s,t :| 0 <= s < t <= |sub| && subsub == sub[s..t];\n assert t <= (j-k) <= j;\n //[3,4,5,6,7,8,9,10,11,12,13][2,7] //k,j\n //[5,6,7,8,9,10][1..3] //s,t\n //[5,7,8]\n // var example:= [3,4,5,6,7,8,9,10,11,12,13];\n // assert example[2..7] == [5,6,7,8,9];\n // assert example[2..7][1..3] == [6,7];\n // assert example[3..5] == [6,7];\n // assert k+s+(t-s)\n // assert 2+1+(3-1) == 5;\n /*\n assert s[..idx] == [s[0]] + s[1..idx];\n assert s[1..idx] == s[1..][..(idx-1)];\n assert s[1..][(idx-1)..] == s[idx..];\n */\n assert super[..j][..t] == super[..(t)];\n assert super[k..][s..] == super[(k+s)..];\n if t < j {\n calc {\n subsub;\n super[k..j][s..t];\n {SliceOfSliceIsSlice(super,k,j,s,t);}\n super[(k+s)..(k+s+(t-s))];\n }\n } else if t <= j {\n\n }\n // var z,q :| 0 <= z <= q <= |super| && super[z..q] == super[k..j][s..t];\n }\n\n predicate IsSuffix(xs: seq, ys: seq) {\n |xs| <= |ys| && xs == ys[|ys| - |xs|..]\n }\n \n predicate IsPrefix(xs: seq, ys: seq) {\n |xs| <= |ys| && xs == ys[..|xs|]\n }\n\n lemma PrefixRest(xs: seq, ys: seq)\n requires IsPrefix(xs, ys)\n ensures exists yss: seq :: ys == xs + yss && |yss| == |ys|-|xs|;\n {\n assert ys == ys[..|xs|] + ys[|xs|..];\n }\n\n lemma IsSuffixReversed(xs: seq, ys: seq)\n requires IsSuffix(xs, ys)\n ensures IsPrefix(reverse(xs), reverse(ys))\n {\n ReverseIndexAll(xs);\n ReverseIndexAll(ys);\n }\n\n lemma IsPrefixReversed(xs: seq, ys: seq)\n requires IsPrefix(xs, ys)\n ensures IsSuffix(reverse(xs), reverse(ys))\n {\n ReverseIndexAll(xs);\n ReverseIndexAll(ys);\n }\n\n lemma IsPrefixReversedAll(xs: seq, ys: seq)\n requires IsPrefix(reverse(xs), reverse(ys))\n ensures IsSuffix(reverse(reverse(xs)), reverse(reverse(ys)))\n {\n ReverseIndexAll(xs);\n ReverseIndexAll(ys);\n assert |ys| == |reverse(ys)|;\n assert reverse(xs) == reverse(ys)[..|reverse(xs)|];\n assert reverse(xs) == reverse(ys)[..|xs|];\n PrefixRest(reverse(xs), reverse(ys));\n var yss :| reverse(ys) == reverse(xs) + yss && |yss| == |ys|-|xs|;\n reverseReverseIdempotent(ys);\n ReverseConcat(reverse(xs), yss);\n calc {\n reverse(reverse(ys));\n ys;\n reverse(reverse(xs) + yss);\n reverse(yss)+reverse(reverse(xs));\n == {reverseReverseIdempotent(xs);}\n reverse(yss)+xs;\n }\n }\n\n predicate IsSuffix2(xs: seq, ys: seq) {\n |xs| <= |ys| && exists K :: 0 <= K <= |ys|-|xs| && ys == ys[0..K] + xs + ys[(K+|xs|)..]\n }\n\n function reverse(x: seq): seq \n\n {\n if x == [] then [] else reverse(x[1..])+[x[0]]\n }\n\n lemma {:induction false} reversePreservesMultiset(xs: seq) \n ensures multiset(xs) == multiset(reverse(xs))\n {\n if xs == [] {\n\n }else {\n var x := xs[0];\n assert xs == [x] + xs[1..];\n assert multiset(xs) == multiset([x]) + multiset(xs[1..]);\n assert reverse(xs) == reverse(xs[1..])+[x];\n reversePreservesMultiset(xs[1..]);\n assert multiset(xs[1..]) == multiset(reverse(xs[1..]));\n }\n }\n\n lemma reversePreservesLength(xs: seq)\n ensures |xs| == |reverse(xs)|\n {\n\n }\n\n lemma lastReverseIsFirst(xs: seq)\n requires |xs| > 0\n ensures xs[0] == reverse(xs)[|reverse(xs)|-1]\n {\n reversePreservesLength(xs);\n assert |xs| == |reverse(xs)|;\n }\n\n lemma firstReverseIsLast(xs: seq)\n requires |xs| > 0\n ensures reverse(xs)[0] == xs[|xs|-1]\n {\n\n }\n\n lemma ReverseConcat(xs: seq, ys: seq)\n ensures reverse(xs + ys) == reverse(ys) + reverse(xs)\n {\n // reveal Reverse();\n if |xs| == 0 {\n assert xs + ys == ys;\n } else {\n assert xs + ys == [xs[0]] + (xs[1..] + ys);\n }\n }\n\n\n lemma reverseRest(xs: seq)\n requires |xs| > 0\n ensures reverse(xs) == [xs[ |xs| -1 ] ] + reverse(xs[0..|xs|-1])\n {\n firstReverseIsLast(xs);\n assert xs == xs[0..|xs|-1] + [xs[|xs|-1]];\n assert reverse(xs)[0] == xs[ |xs| -1];\n assert reverse(xs) == [xs[ |xs| -1]] + reverse(xs)[1..];\n calc {\n reverse(xs);\n reverse(xs[0..|xs|-1] + [xs[|xs|-1]]);\n == {ReverseConcat(xs[0..|xs|-1], [xs[ |xs|-1 ]]);}\n reverse([xs[ |xs|-1 ]]) + reverse(xs[0..|xs|-1]);\n\n }\n\n }\n\n lemma ReverseIndexAll(xs: seq)\n ensures |reverse(xs)| == |xs|\n ensures forall i :: 0 <= i < |xs| ==> reverse(xs)[i] == xs[|xs| - i - 1]\n {\n // reveal Reverse();\n }\n\n lemma ReverseIndex(xs: seq, i: int)\n requires 0 <= i < |xs|\n ensures |reverse(xs)| == |xs|\n ensures reverse(xs)[i] == xs[|xs| - i - 1]\n {\n ReverseIndexAll(xs);\n assert forall i :: 0 <= i < |xs| ==> reverse(xs)[i] == xs[|xs| - i - 1];\n }\n lemma ReverseIndexBack(xs: seq, i: int)\n requires 0 <= i < |xs|\n ensures |reverse(xs)| == |xs|\n ensures reverse(xs)[|xs| - i - 1] == xs[i]\n {\n ReverseIndexAll(xs);\n assert forall i :: 0 <= i < |xs| ==> reverse(xs)[i] == xs[|xs| - i - 1];\n }\n\n lemma ReverseSingle(xs: seq) \n requires |xs| == 1\n ensures reverse(xs) == xs\n {\n\n }\n\n lemma SeqEq(xs: seq, ys: seq)\n requires |xs| == |ys|\n requires forall i :: 0 <= i < |xs| ==> xs[i] == ys[i]\n ensures xs == ys\n {\n }\n\n lemma reverseReverseIdempotent(xs: seq) \n ensures reverse(reverse(xs)) == xs\n {\n if xs == [] {\n\n }else{\n calc {\n reverse(reverse(xs));\n reverse(reverse([xs[0]] + xs[1..]));\n == {ReverseConcat([xs[0]] , xs[1..]);}\n reverse(reverse(xs[1..]) + reverse([xs[0]]));\n == {ReverseSingle([xs[0]]);}\n reverse(reverse(xs[1..]) + [xs[0]]);\n == {ReverseConcat(reverse(xs[1..]), [xs[0]]);}\n reverse([xs[0]]) + reverse(reverse(xs[1..]));\n [xs[0]] + reverse(reverse(xs[1..]));\n == {reverseReverseIdempotent(xs[1..]);}\n xs;\n }\n }\n /* Alternatively */\n // ReverseIndexAll(reverse(xs));\n // ReverseIndexAll(xs);\n // SeqEq(reverse(reverse(xs)), xs);\n }\n\n lemma notInNotEqual(xs: seq, elem: A)\n requires elem !in xs\n ensures forall k :: 0 <= k < |xs| ==> xs[k] != elem\n {\n\n }\n\n predicate distinct(s: seq) {\n forall x,y :: x != y && 0 <= x <= y < |s| ==> s[x] != s[y]\n }\n\n lemma distincts(xs: seq, ys: seq)\n requires distinct(xs)\n requires distinct(ys)\n requires forall x :: x in xs ==> x !in ys \n requires forall y :: y in ys ==> y !in xs \n ensures distinct(xs+ys)\n {\n var len := |xs + ys|;\n forall x,y | x != y && 0 <= x <= y < |xs+ys| \n ensures (xs+ys)[x] != (xs+ys)[y] \n {\n if 0 <= x < |xs| && 0 <= y < |xs| {\n assert (xs+ys)[x] != (xs+ys)[y];\n }else if |xs| <= x < |xs+ys| && |xs| <= y < |xs+ys| {\n assert (xs+ys)[x] != (xs+ys)[y];\n\n }else if 0 <= x < |xs| && |xs| <= y < |xs+ys| {\n notInNotEqual(ys, xs[x]);\n assert (xs+ys)[x] != (xs+ys)[y];\n }\n }\n\n }\n\n lemma reverseDistinct(list: seq)\n requires distinct(list)\n ensures distinct(reverse(list))\n {\n ReverseIndexAll(list);\n }\n\n lemma distinctSplits(list: seq)\n requires distinct(list)\n ensures forall i :: 1 <= i < |list| ==> distinct(list[..i])\n {}\n\n lemma multisetItems(list: seq, item: A)\n requires item in list\n requires multiset(list)[item] > 1\n ensures exists i,j :: 0 <= i < j < |list| && list[i] == item && list[j] == item && i != j\n {\n var k :| 0 <= k < |list| && list[k] == item;\n var rest := list[..k]+list[k+1..];\n assert list == list[..k]+[item]+list[k+1..];\n assert multiset(list) == multiset(list[..k])+multiset(list[k+1..])+multiset{item};\n }\n\n lemma distinctMultisetIs1(list: seq, item: A) \n requires distinct(list)\n requires item in list\n ensures multiset(list)[item] == 1\n {\n if multiset(list)[item] == 0 {\n assert false;\n }\n if multiset(list)[item] > 1 {\n multisetItems(list, item);\n var i,j :| 0 <= i < j < |list| && list[i] == item && list[j] == item && i != j;\n }\n }\n\n lemma indistinctMultisetIsGreaterThan1(list: seq) \n requires !distinct(list)\n ensures exists item :: multiset(list)[item] > 1\n {\n var x,y :| x != y && 0 <= x <= y < |list| && list[x] == list[y];\n var item := list[x];\n assert x < y;\n assert list == list[..x] + [item] + list[(x+1)..y] + [item] + list[y+1..];\n assert multiset(list)[item] > 1;\n }\n\n lemma multisetIsGreaterThan1Indistinct(list: seq) \n requires exists item :: multiset(list)[item] > 1\n ensures !distinct(list)\n {\n var item :| multiset(list)[item] > 1;\n var x :| 0 <= x < |list| && list[x] == item;\n assert list == list[..x] + [item] + list[x+1..];\n var y :| x != y && 0 <= y < |list| && list[y] == item;\n }\n\n lemma indistinctPlusX(items: seq, x: A)\n requires !distinct(items)\n ensures forall i :: 0 <= i < |items| ==> !distinct(items[..i]+[x]+items[i..])\n {\n forall i | 0 <= i < |items| \n ensures !distinct(items[..i]+[x]+items[i..])\n {\n indistinctMultisetIsGreaterThan1(items);\n var item :| multiset(items)[item] > 1;\n var itemsPlus := items[..i]+[x]+items[i..];\n assert items == items[..i]+items[i..];\n calc {\n multiset(itemsPlus);\n multiset(items[..i])+multiset(items[i..])+multiset{x};\n multiset(items)+multiset{x};\n }\n assert multiset(itemsPlus)[item] > 1;\n multisetIsGreaterThan1Indistinct(itemsPlus);\n }\n }\n\n lemma pigeonHolesMultiset(items: set, list: seq, n: nat)\n requires |items| == n\n requires forall x :: x in list ==> x in items\n requires |list| > n\n ensures exists item :: multiset(list)[item] > 1\n {\n\n if x :| multiset(list)[x] > 1 {\n }else if x :| multiset(list)[x] == 1 {\n assert x in list;\n var i :| 0 <= i < |list| && list[i] == x;\n assert list == list[..i] + [x] + list[i+1..];\n assert list == list[..i] + list[i..];\n assert multiset(list) == multiset(list[..i])+multiset(list[i+1..])+multiset{x};\n var rest := list[..i]+list[i+1..];\n assert multiset(rest)[x] == 0;\n\n forall y | y in rest \n ensures y in items-{x}\n {\n assert y in items; \n assert y != x;\n }\n if n -1 == 0 {\n // assert |items| == 1;\n // assert x in items;\n assert |items-{x}| == 0;\n assert list[0] in list;\n assert list[0] == x;\n assert list[1] in list;\n assert list[1] == x;\n assert false;\n }else{\n pigeonHolesMultiset(items-{x}, rest, n-1);\n var item :| multiset(rest)[item] > 1;\n assert multiset(list) == multiset(rest) + multiset{x};\n assert multiset(list)[item] > 1;\n }\n }else if x :| multiset(list)[x] == 0 {}\n }\n\n lemma pigeonHoles(items: set, list: seq, n: nat)\n requires |items| == n\n requires forall x :: x in list ==> x in items\n requires |list| > n\n ensures !distinct(list)\n {\n if x :| multiset(list)[x] > 1 {\n multisetItems(list, x);\n var i,j :| 0 <= i < j < |list| && list[i] == x && list[j] == x && i != j;\n }else if x :| multiset(list)[x] == 1 {\n assert x in list;\n var i :| 0 <= i < |list| && list[i] == x;\n assert list == list[..i] + [x] + list[i+1..];\n assert list == list[..i] + list[i..];\n assert multiset(list) == multiset(list[..i])+multiset(list[i+1..])+multiset{x};\n assert multiset(list)[x] == 1;\n var rest := list[..i]+list[i+1..];\n assert multiset(rest)[x] == 0;\n forall y | y in rest \n ensures y in items-{x}\n {\n assert y in items; \n assert y != x;\n }\n pigeonHoles(items-{x}, rest, n-1);\n assert !distinct(rest);\n indistinctPlusX(rest, x);\n\n assert !distinct(list);\n\n }else if x :| multiset(list)[x] == 0 {}\n }\n\n lemma reverseInitList(xs: seq)\n requires |xs| > 1\n requires |reverse(xs)| == |xs|\n ensures reverse(reverse(xs)[..|xs|-1]) == xs[1..]\n {\n assert xs == [xs[0]] + xs[1..];\n assert |reverse(xs)| == |xs|;\n calc {\n reverse(xs);\n reverse(xs[1..])+reverse([xs[0]]);\n reverse(xs[1..])+[xs[0]];\n }\n assert reverse(xs)[..|xs|-1] == reverse(xs[1..]);\n calc {\n reverse(reverse(xs)[..|xs|-1]);\n reverse(reverse(xs[1..]));\n == {reverseReverseIdempotent(xs[1..]);}\n xs[1..];\n }\n }\n \n method SeqTest() {\n var t1 := [4,5,6,1,2,3];\n // assert t1 == [4,5,6]+[1,2,3];\n var s1 := [1,2,3];\n assert IsSuffix(s1,t1);\n // assert isSubstring(s1,t1);\n assert substring1(s1, t1);\n\n }\n\n}\n", "hints_removed": "\nmodule Seq {\n export reveals *\n function ToSet(xs: seq): set\n ensures forall x :: x in ToSet(xs) ==> x in xs\n ensures forall x :: x !in ToSet(xs) ==> x !in xs\n {\n if xs == [] then {} else {xs[0]}+ToSet(xs[1..])\n }\n\n predicate substring1(sub: seq, super: seq) {\n exists k :: 0 <= k < |super| && sub <= super[k..]\n }\n\n\n ghost predicate isSubstringAlt(sub: seq, super: seq) {\n |sub| <= |super| && exists xs: seq :: IsSuffix(xs, super) && sub <= xs\n }\n\n predicate isSubstring(sub: seq, super: seq) {\n |sub| <= |super| && exists k,j :: 0 <= k < j <= |super| && sub == super[k..j]\n }\n\n lemma SliceOfSliceIsSlice(xs: seq, k: int, j: int, s: int, t: int)\n requires 0 <= k <= j <= |xs|\n requires 0 <= s <= t <= j-k\n ensures xs[k..j][s..t] == xs[(k+s)..(k+s+(t-s))]\n {\n if j-k == 0 {\n }else if t-s == 0 {\n }else if t-s > 0 {\n SliceOfSliceIsSlice(xs, k, j, s,t-1);\n }\n }\n\n\n\n lemma AllSubstringsAreSubstrings(subsub: seq, sub: seq, super: seq)\n requires isSubstring(sub, super)\n requires isSubstring(subsub, sub)\n ensures isSubstring(subsub, super)\n {\n var k,j :| 0 <= k < j <= |super| && sub == super[k..j];\n var s,t :| 0 <= s < t <= |sub| && subsub == sub[s..t];\n //[3,4,5,6,7,8,9,10,11,12,13][2,7] //k,j\n //[5,6,7,8,9,10][1..3] //s,t\n //[5,7,8]\n // var example:= [3,4,5,6,7,8,9,10,11,12,13];\n // assert example[2..7] == [5,6,7,8,9];\n // assert example[2..7][1..3] == [6,7];\n // assert example[3..5] == [6,7];\n // assert k+s+(t-s)\n // assert 2+1+(3-1) == 5;\n /*\n */\n if t < j {\n calc {\n subsub;\n super[k..j][s..t];\n {SliceOfSliceIsSlice(super,k,j,s,t);}\n super[(k+s)..(k+s+(t-s))];\n }\n } else if t <= j {\n\n }\n // var z,q :| 0 <= z <= q <= |super| && super[z..q] == super[k..j][s..t];\n }\n\n predicate IsSuffix(xs: seq, ys: seq) {\n |xs| <= |ys| && xs == ys[|ys| - |xs|..]\n }\n \n predicate IsPrefix(xs: seq, ys: seq) {\n |xs| <= |ys| && xs == ys[..|xs|]\n }\n\n lemma PrefixRest(xs: seq, ys: seq)\n requires IsPrefix(xs, ys)\n ensures exists yss: seq :: ys == xs + yss && |yss| == |ys|-|xs|;\n {\n }\n\n lemma IsSuffixReversed(xs: seq, ys: seq)\n requires IsSuffix(xs, ys)\n ensures IsPrefix(reverse(xs), reverse(ys))\n {\n ReverseIndexAll(xs);\n ReverseIndexAll(ys);\n }\n\n lemma IsPrefixReversed(xs: seq, ys: seq)\n requires IsPrefix(xs, ys)\n ensures IsSuffix(reverse(xs), reverse(ys))\n {\n ReverseIndexAll(xs);\n ReverseIndexAll(ys);\n }\n\n lemma IsPrefixReversedAll(xs: seq, ys: seq)\n requires IsPrefix(reverse(xs), reverse(ys))\n ensures IsSuffix(reverse(reverse(xs)), reverse(reverse(ys)))\n {\n ReverseIndexAll(xs);\n ReverseIndexAll(ys);\n PrefixRest(reverse(xs), reverse(ys));\n var yss :| reverse(ys) == reverse(xs) + yss && |yss| == |ys|-|xs|;\n reverseReverseIdempotent(ys);\n ReverseConcat(reverse(xs), yss);\n calc {\n reverse(reverse(ys));\n ys;\n reverse(reverse(xs) + yss);\n reverse(yss)+reverse(reverse(xs));\n == {reverseReverseIdempotent(xs);}\n reverse(yss)+xs;\n }\n }\n\n predicate IsSuffix2(xs: seq, ys: seq) {\n |xs| <= |ys| && exists K :: 0 <= K <= |ys|-|xs| && ys == ys[0..K] + xs + ys[(K+|xs|)..]\n }\n\n function reverse(x: seq): seq \n\n {\n if x == [] then [] else reverse(x[1..])+[x[0]]\n }\n\n lemma {:induction false} reversePreservesMultiset(xs: seq) \n ensures multiset(xs) == multiset(reverse(xs))\n {\n if xs == [] {\n\n }else {\n var x := xs[0];\n reversePreservesMultiset(xs[1..]);\n }\n }\n\n lemma reversePreservesLength(xs: seq)\n ensures |xs| == |reverse(xs)|\n {\n\n }\n\n lemma lastReverseIsFirst(xs: seq)\n requires |xs| > 0\n ensures xs[0] == reverse(xs)[|reverse(xs)|-1]\n {\n reversePreservesLength(xs);\n }\n\n lemma firstReverseIsLast(xs: seq)\n requires |xs| > 0\n ensures reverse(xs)[0] == xs[|xs|-1]\n {\n\n }\n\n lemma ReverseConcat(xs: seq, ys: seq)\n ensures reverse(xs + ys) == reverse(ys) + reverse(xs)\n {\n // reveal Reverse();\n if |xs| == 0 {\n } else {\n }\n }\n\n\n lemma reverseRest(xs: seq)\n requires |xs| > 0\n ensures reverse(xs) == [xs[ |xs| -1 ] ] + reverse(xs[0..|xs|-1])\n {\n firstReverseIsLast(xs);\n calc {\n reverse(xs);\n reverse(xs[0..|xs|-1] + [xs[|xs|-1]]);\n == {ReverseConcat(xs[0..|xs|-1], [xs[ |xs|-1 ]]);}\n reverse([xs[ |xs|-1 ]]) + reverse(xs[0..|xs|-1]);\n\n }\n\n }\n\n lemma ReverseIndexAll(xs: seq)\n ensures |reverse(xs)| == |xs|\n ensures forall i :: 0 <= i < |xs| ==> reverse(xs)[i] == xs[|xs| - i - 1]\n {\n // reveal Reverse();\n }\n\n lemma ReverseIndex(xs: seq, i: int)\n requires 0 <= i < |xs|\n ensures |reverse(xs)| == |xs|\n ensures reverse(xs)[i] == xs[|xs| - i - 1]\n {\n ReverseIndexAll(xs);\n }\n lemma ReverseIndexBack(xs: seq, i: int)\n requires 0 <= i < |xs|\n ensures |reverse(xs)| == |xs|\n ensures reverse(xs)[|xs| - i - 1] == xs[i]\n {\n ReverseIndexAll(xs);\n }\n\n lemma ReverseSingle(xs: seq) \n requires |xs| == 1\n ensures reverse(xs) == xs\n {\n\n }\n\n lemma SeqEq(xs: seq, ys: seq)\n requires |xs| == |ys|\n requires forall i :: 0 <= i < |xs| ==> xs[i] == ys[i]\n ensures xs == ys\n {\n }\n\n lemma reverseReverseIdempotent(xs: seq) \n ensures reverse(reverse(xs)) == xs\n {\n if xs == [] {\n\n }else{\n calc {\n reverse(reverse(xs));\n reverse(reverse([xs[0]] + xs[1..]));\n == {ReverseConcat([xs[0]] , xs[1..]);}\n reverse(reverse(xs[1..]) + reverse([xs[0]]));\n == {ReverseSingle([xs[0]]);}\n reverse(reverse(xs[1..]) + [xs[0]]);\n == {ReverseConcat(reverse(xs[1..]), [xs[0]]);}\n reverse([xs[0]]) + reverse(reverse(xs[1..]));\n [xs[0]] + reverse(reverse(xs[1..]));\n == {reverseReverseIdempotent(xs[1..]);}\n xs;\n }\n }\n /* Alternatively */\n // ReverseIndexAll(reverse(xs));\n // ReverseIndexAll(xs);\n // SeqEq(reverse(reverse(xs)), xs);\n }\n\n lemma notInNotEqual(xs: seq, elem: A)\n requires elem !in xs\n ensures forall k :: 0 <= k < |xs| ==> xs[k] != elem\n {\n\n }\n\n predicate distinct(s: seq) {\n forall x,y :: x != y && 0 <= x <= y < |s| ==> s[x] != s[y]\n }\n\n lemma distincts(xs: seq, ys: seq)\n requires distinct(xs)\n requires distinct(ys)\n requires forall x :: x in xs ==> x !in ys \n requires forall y :: y in ys ==> y !in xs \n ensures distinct(xs+ys)\n {\n var len := |xs + ys|;\n forall x,y | x != y && 0 <= x <= y < |xs+ys| \n ensures (xs+ys)[x] != (xs+ys)[y] \n {\n if 0 <= x < |xs| && 0 <= y < |xs| {\n }else if |xs| <= x < |xs+ys| && |xs| <= y < |xs+ys| {\n\n }else if 0 <= x < |xs| && |xs| <= y < |xs+ys| {\n notInNotEqual(ys, xs[x]);\n }\n }\n\n }\n\n lemma reverseDistinct(list: seq)\n requires distinct(list)\n ensures distinct(reverse(list))\n {\n ReverseIndexAll(list);\n }\n\n lemma distinctSplits(list: seq)\n requires distinct(list)\n ensures forall i :: 1 <= i < |list| ==> distinct(list[..i])\n {}\n\n lemma multisetItems(list: seq, item: A)\n requires item in list\n requires multiset(list)[item] > 1\n ensures exists i,j :: 0 <= i < j < |list| && list[i] == item && list[j] == item && i != j\n {\n var k :| 0 <= k < |list| && list[k] == item;\n var rest := list[..k]+list[k+1..];\n }\n\n lemma distinctMultisetIs1(list: seq, item: A) \n requires distinct(list)\n requires item in list\n ensures multiset(list)[item] == 1\n {\n if multiset(list)[item] == 0 {\n }\n if multiset(list)[item] > 1 {\n multisetItems(list, item);\n var i,j :| 0 <= i < j < |list| && list[i] == item && list[j] == item && i != j;\n }\n }\n\n lemma indistinctMultisetIsGreaterThan1(list: seq) \n requires !distinct(list)\n ensures exists item :: multiset(list)[item] > 1\n {\n var x,y :| x != y && 0 <= x <= y < |list| && list[x] == list[y];\n var item := list[x];\n }\n\n lemma multisetIsGreaterThan1Indistinct(list: seq) \n requires exists item :: multiset(list)[item] > 1\n ensures !distinct(list)\n {\n var item :| multiset(list)[item] > 1;\n var x :| 0 <= x < |list| && list[x] == item;\n var y :| x != y && 0 <= y < |list| && list[y] == item;\n }\n\n lemma indistinctPlusX(items: seq, x: A)\n requires !distinct(items)\n ensures forall i :: 0 <= i < |items| ==> !distinct(items[..i]+[x]+items[i..])\n {\n forall i | 0 <= i < |items| \n ensures !distinct(items[..i]+[x]+items[i..])\n {\n indistinctMultisetIsGreaterThan1(items);\n var item :| multiset(items)[item] > 1;\n var itemsPlus := items[..i]+[x]+items[i..];\n calc {\n multiset(itemsPlus);\n multiset(items[..i])+multiset(items[i..])+multiset{x};\n multiset(items)+multiset{x};\n }\n multisetIsGreaterThan1Indistinct(itemsPlus);\n }\n }\n\n lemma pigeonHolesMultiset(items: set, list: seq, n: nat)\n requires |items| == n\n requires forall x :: x in list ==> x in items\n requires |list| > n\n ensures exists item :: multiset(list)[item] > 1\n {\n\n if x :| multiset(list)[x] > 1 {\n }else if x :| multiset(list)[x] == 1 {\n var i :| 0 <= i < |list| && list[i] == x;\n var rest := list[..i]+list[i+1..];\n\n forall y | y in rest \n ensures y in items-{x}\n {\n }\n if n -1 == 0 {\n // assert |items| == 1;\n // assert x in items;\n }else{\n pigeonHolesMultiset(items-{x}, rest, n-1);\n var item :| multiset(rest)[item] > 1;\n }\n }else if x :| multiset(list)[x] == 0 {}\n }\n\n lemma pigeonHoles(items: set, list: seq, n: nat)\n requires |items| == n\n requires forall x :: x in list ==> x in items\n requires |list| > n\n ensures !distinct(list)\n {\n if x :| multiset(list)[x] > 1 {\n multisetItems(list, x);\n var i,j :| 0 <= i < j < |list| && list[i] == x && list[j] == x && i != j;\n }else if x :| multiset(list)[x] == 1 {\n var i :| 0 <= i < |list| && list[i] == x;\n var rest := list[..i]+list[i+1..];\n forall y | y in rest \n ensures y in items-{x}\n {\n }\n pigeonHoles(items-{x}, rest, n-1);\n indistinctPlusX(rest, x);\n\n\n }else if x :| multiset(list)[x] == 0 {}\n }\n\n lemma reverseInitList(xs: seq)\n requires |xs| > 1\n requires |reverse(xs)| == |xs|\n ensures reverse(reverse(xs)[..|xs|-1]) == xs[1..]\n {\n calc {\n reverse(xs);\n reverse(xs[1..])+reverse([xs[0]]);\n reverse(xs[1..])+[xs[0]];\n }\n calc {\n reverse(reverse(xs)[..|xs|-1]);\n reverse(reverse(xs[1..]));\n == {reverseReverseIdempotent(xs[1..]);}\n xs[1..];\n }\n }\n \n method SeqTest() {\n var t1 := [4,5,6,1,2,3];\n // assert t1 == [4,5,6]+[1,2,3];\n var s1 := [1,2,3];\n // assert isSubstring(s1,t1);\n\n }\n\n}\n" }, { "test_ID": "297", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_math_pearson.dfy", "ground_truth": "\n\nfunction eight(x: nat):nat {\n 9 * x + 5\n}\n\npredicate isOdd(x: nat) {\n x % 2 == 1\n}\n\npredicate isEven(x: nat) {\n x % 2 == 0\n}\n\nlemma eightL(x: nat)\n requires isOdd(x)\n ensures isEven(eight(x))\n{\n\n}\n\nfunction nineteenf(x: nat): nat {\n 7*x+4\n}\nfunction nineteens(x: nat): nat {\n 3*x+11\n}\n\nlemma nineteenlemma(x: nat) \n requires isEven(nineteenf(x))\n ensures isOdd(nineteens(x))\n{\n\n}\n\nfunction relationDomain(s: set<(T,T)>): set {\n set z | z in s :: z.1\n}\n\npredicate reflexive(R: set<(T,T)>, S: set) \n requires relationOnASet(R, S)\n{\n forall s :: s in S ==> (s,s) in R\n}\n\npredicate symmetric(R: set<(T,T)>, S: set)\n requires relationOnASet(R, S)\n{\n forall x: T, y:T :: x in S && y in S && (x,y) in R ==> (y, x) in R\n}\n\npredicate transitive(R: set<(T,T)>, S: set) \n requires relationOnASet(R, S)\n{\n forall a,b,c :: a in S && b in S && c in S && (a,b) in R && (b,c) in R ==> (a,c) in R\n}\n\npredicate equivalenceRelation(R: set<(T,T)>, S: set) \n requires relationOnASet(R, S)\n{\n reflexive(R, S) && symmetric(R, S) && transitive(R, S)\n}\n\npredicate relationOnASet(R: set<(T,T)>, S: set) {\n forall ts :: ts in R ==> ts.0 in S && ts.1 in S\n}\n\n// lemma equivUnion(R_1: set<(T,T)>, S_1: set, R_2: set<(T,T)>, S_2: set)\n// requires |R_1| > 0\n// requires |R_2| > 0\n// requires |S_1| > 0\n// requires |S_2| > 0\n// requires relationOnASet(R_1, S_1)\n// requires relationOnASet(R_2, S_2)\n// requires equivalenceRelation(R_1, S_1)\n// requires equivalenceRelation(R_2, S_2)\n// ensures equivalenceRelation(R_1+R_2, S_1+S_2)\n// {\n// reflexiveUnion(R_1, S_1, R_2, S_2);\n// symmetricUnion(R_1, S_1, R_2, S_2);\n// transitiveUnion(R_1, S_1, R_2, S_2);\n// }\n\nlemma reflexiveUnion(R_1: set<(T,T)>, S_1: set, R_2: set<(T,T)>, S_2: set)\n requires |R_1| > 0\n requires |R_2| > 0\n requires |S_1| > 0\n requires |S_2| > 0\n requires relationOnASet(R_1, S_1)\n requires relationOnASet(R_2, S_2)\n requires reflexive(R_1, S_1)\n requires reflexive(R_2, S_2)\n ensures reflexive(R_1+R_2, S_1+S_2)\n{\n\n}\n\nlemma symmetricUnion(R_1: set<(T,T)>, S_1: set, R_2: set<(T,T)>, S_2: set)\n requires |R_1| > 0\n requires |R_2| > 0\n requires |S_1| > 0\n requires |S_2| > 0\n requires relationOnASet(R_1, S_1)\n requires relationOnASet(R_2, S_2)\n requires symmetric(R_1, S_1)\n requires symmetric(R_2, S_2)\n ensures symmetric(R_1+R_2, S_1+S_2)\n{\n // assert R_1 <= (R_1+R_2);\n // assert R_2 <= (R_1+R_2);\n // assert symmetric(R_1, S_1);\n // assert symmetric(R_2, S_2);\n forall x,y | x in S_1+S_2 && y in S_1+S_2 && (x,y) in R_1+R_2\n ensures (y,x) in R_1+R_2\n {\n // assert x in S_1+S_2;\n // assert y in S_1+S_2;\n // assert (x,y) in R_1+R_2;\n // calc {\n // (x,y) in R_1+R_2;\n // ==>\n // (x,y) in R_1 || (x,y) in R_2;\n // }\n // calc {\n // x in S_1+S_2;\n // ==>\n // x in S_1 || x in S_2;\n // }\n\n // calc {\n // y in S_1+S_2;\n // ==>\n // y in S_1 || y in S_2;\n // }\n // assert (x,y) in R_1 ==> x in S_1 && y in S_1;\n // assert (x,y) in R_2 ==> x in S_2 && y in S_2;\n\n // assert (x,y) in R_1 || (x,y) in R_2;\n if x in S_1 && y in S_1 && (x,y) in R_1 {\n // assert x in S_1;\n // assert y in S_1;\n // assert (x,y) in R_1;\n // assert (y,x) in R_1;\n assert (y,x) in R_1+R_2;\n }else if x in S_2 && y in S_2 && (x,y) in R_2 {\n // assert x in S_2;\n // assert y in S_2;\n // assert (x,y) in R_2;\n // assert (y,x) in R_2;\n assert (y,x) in R_1+R_2;\n }\n }\n}\n\n \nlemma transitiveUnion(R_1: set<(T,T)>, S_1: set, R_2: set<(T,T)>, S_2: set)\n requires |R_1| > 0\n requires |R_2| > 0\n requires |S_1| > 0\n requires |S_2| > 0\n requires relationOnASet(R_1, S_1)\n requires relationOnASet(R_2, S_2)\n requires transitive(R_1, S_1)\n requires transitive(R_2, S_2)\n ensures transitive(R_1+R_2, S_1+S_2) \n{\n assert R_1 <= (R_1+R_2);\n assert R_2 <= (R_1+R_2);\n\n assume forall a :: a in S_1+S_2 ==> a !in S_1 || a !in S_2;\n\n forall a,b,c | a in S_1+S_2 && b in S_1+S_2 && c in S_1+S_2 && (a,b) in R_1+R_2 && (b,c) in R_1+R_2 \n ensures (a,c) in R_1+R_2\n {\n assert a in S_1 ==> b !in S_2;\n if a in S_1 && b in S_1 && c in S_1 && (a,b) in R_1 && (b,c) in R_1 {\n assert (a,c) in R_1;\n assert (a,c) in R_1+R_2;\n }else if a in S_2 && b in S_2 && c in S_2 && (a,b) in R_2 && (b,c) in R_2 {\n assert (a,c) in R_2;\n assert (a,c) in R_1+R_2;\n }\n } \n}\n\n// lemma transitiveUnionContra(R_1: set<(T,T)>, S_1: set, R_2: set<(T,T)>, S_2: set)\n// requires |R_1| > 0\n// requires |R_2| > 0\n// requires |S_1| > 0\n// requires |S_2| > 0\n// requires relationOnASet(R_1, S_1)\n// requires relationOnASet(R_2, S_2)\n// requires transitive(R_1, S_1)\n// requires transitive(R_2, S_2)\n// ensures exists (R_1+R_2, S_1+S_2) :: !transitive(R_1+R_2, S_1+S_2) \n// {\n// assume S_1 * S_2 != {};\n// if transitive(R_1 + R_2, S_1+S_2) {\n// forall a,b,c | a in S_1+S_2 && b in S_1+S_2 && c in S_1+S_2 && (a,b) in R_1+R_2 && (b,c) in R_1+R_2 \n// ensures (a,c) in R_1+R_2 \n// {\n// if a in S_1 && a !in S_2 && b in S_1 && b in S_2 && c in S_2 && c !in S_1 {\n// assert (a,c) !in R_1;\n// assert (a,c) !in R_2;\n// assert (a,c) !in R_1+R_2;\n// assert false;\n// }\n// } \n// }\n// }\n\nlemma transitiveUnionContra()\n returns (\n R1: set<(T, T)>, S1: set,\n R2: set<(T, T)>, S2: set)\n ensures relationOnASet(R1, S1)\n ensures relationOnASet(R2, S2)\n ensures transitive(R1, S1)\n ensures transitive(R2, S2)\n ensures ! transitive(R1 + R2, S1 + S2)\n{\n var a : T :| assume true;\n var b : T :| assume a != b;\n var c : T :| assume a != c && b != c;\n S1 := {a, b};\n S2 := {b, c};\n R1 := {(a, b)};\n R2 := {(b, c)};\n}\n\nlemma notTrueAlways()\n ensures !\n (forall S1 : set, S2 : set, R1 : set<(T,T)>, R2 : set<(T, T)> ::\n relationOnASet(R1, S1) &&\n relationOnASet(R2, S2) &&\n transitive(R1, S1) &&\n transitive(R2, S2) ==> transitive(R1 + R2, S1 + S2)\n )\n{\n var a, b, c, d := transitiveUnionContra();\n}\n\nmethod test() {\n var x := 7;\n // assert isEven(eight(7));\n var four := 4;\n // var test := set x: nat,y: nat | 1 <= x <= y <= 5 :: (x,y);\n var sample := {1,2,3,4,5,6};\n var test := set x,y | x in sample && y in sample :: (x,y);\n var modulos := set x,y | x in sample && y in sample && x % y == 0 :: (x,y);\n // assert reflexive(test, set x | 1 <=x <= 5);\n assert reflexive(test, sample);\n assert symmetric(test, sample);\n assert transitive(test, sample);\n assert equivalenceRelation(test, sample);\n // assert equivalenceRelation(modulos, sample);\n\n\n var hmm := (1,2,3);\n assert hmm.2 == 3;\n assert (1,2) in test;\n // assert 0 <= four < 100 && isEven(nineteenf(four));\n ghost var y: nat :| isEven(nineteenf(y));\n assert isOdd(nineteens(y));\n}\n", "hints_removed": "\n\nfunction eight(x: nat):nat {\n 9 * x + 5\n}\n\npredicate isOdd(x: nat) {\n x % 2 == 1\n}\n\npredicate isEven(x: nat) {\n x % 2 == 0\n}\n\nlemma eightL(x: nat)\n requires isOdd(x)\n ensures isEven(eight(x))\n{\n\n}\n\nfunction nineteenf(x: nat): nat {\n 7*x+4\n}\nfunction nineteens(x: nat): nat {\n 3*x+11\n}\n\nlemma nineteenlemma(x: nat) \n requires isEven(nineteenf(x))\n ensures isOdd(nineteens(x))\n{\n\n}\n\nfunction relationDomain(s: set<(T,T)>): set {\n set z | z in s :: z.1\n}\n\npredicate reflexive(R: set<(T,T)>, S: set) \n requires relationOnASet(R, S)\n{\n forall s :: s in S ==> (s,s) in R\n}\n\npredicate symmetric(R: set<(T,T)>, S: set)\n requires relationOnASet(R, S)\n{\n forall x: T, y:T :: x in S && y in S && (x,y) in R ==> (y, x) in R\n}\n\npredicate transitive(R: set<(T,T)>, S: set) \n requires relationOnASet(R, S)\n{\n forall a,b,c :: a in S && b in S && c in S && (a,b) in R && (b,c) in R ==> (a,c) in R\n}\n\npredicate equivalenceRelation(R: set<(T,T)>, S: set) \n requires relationOnASet(R, S)\n{\n reflexive(R, S) && symmetric(R, S) && transitive(R, S)\n}\n\npredicate relationOnASet(R: set<(T,T)>, S: set) {\n forall ts :: ts in R ==> ts.0 in S && ts.1 in S\n}\n\n// lemma equivUnion(R_1: set<(T,T)>, S_1: set, R_2: set<(T,T)>, S_2: set)\n// requires |R_1| > 0\n// requires |R_2| > 0\n// requires |S_1| > 0\n// requires |S_2| > 0\n// requires relationOnASet(R_1, S_1)\n// requires relationOnASet(R_2, S_2)\n// requires equivalenceRelation(R_1, S_1)\n// requires equivalenceRelation(R_2, S_2)\n// ensures equivalenceRelation(R_1+R_2, S_1+S_2)\n// {\n// reflexiveUnion(R_1, S_1, R_2, S_2);\n// symmetricUnion(R_1, S_1, R_2, S_2);\n// transitiveUnion(R_1, S_1, R_2, S_2);\n// }\n\nlemma reflexiveUnion(R_1: set<(T,T)>, S_1: set, R_2: set<(T,T)>, S_2: set)\n requires |R_1| > 0\n requires |R_2| > 0\n requires |S_1| > 0\n requires |S_2| > 0\n requires relationOnASet(R_1, S_1)\n requires relationOnASet(R_2, S_2)\n requires reflexive(R_1, S_1)\n requires reflexive(R_2, S_2)\n ensures reflexive(R_1+R_2, S_1+S_2)\n{\n\n}\n\nlemma symmetricUnion(R_1: set<(T,T)>, S_1: set, R_2: set<(T,T)>, S_2: set)\n requires |R_1| > 0\n requires |R_2| > 0\n requires |S_1| > 0\n requires |S_2| > 0\n requires relationOnASet(R_1, S_1)\n requires relationOnASet(R_2, S_2)\n requires symmetric(R_1, S_1)\n requires symmetric(R_2, S_2)\n ensures symmetric(R_1+R_2, S_1+S_2)\n{\n // assert R_1 <= (R_1+R_2);\n // assert R_2 <= (R_1+R_2);\n // assert symmetric(R_1, S_1);\n // assert symmetric(R_2, S_2);\n forall x,y | x in S_1+S_2 && y in S_1+S_2 && (x,y) in R_1+R_2\n ensures (y,x) in R_1+R_2\n {\n // assert x in S_1+S_2;\n // assert y in S_1+S_2;\n // assert (x,y) in R_1+R_2;\n // calc {\n // (x,y) in R_1+R_2;\n // ==>\n // (x,y) in R_1 || (x,y) in R_2;\n // }\n // calc {\n // x in S_1+S_2;\n // ==>\n // x in S_1 || x in S_2;\n // }\n\n // calc {\n // y in S_1+S_2;\n // ==>\n // y in S_1 || y in S_2;\n // }\n // assert (x,y) in R_1 ==> x in S_1 && y in S_1;\n // assert (x,y) in R_2 ==> x in S_2 && y in S_2;\n\n // assert (x,y) in R_1 || (x,y) in R_2;\n if x in S_1 && y in S_1 && (x,y) in R_1 {\n // assert x in S_1;\n // assert y in S_1;\n // assert (x,y) in R_1;\n // assert (y,x) in R_1;\n }else if x in S_2 && y in S_2 && (x,y) in R_2 {\n // assert x in S_2;\n // assert y in S_2;\n // assert (x,y) in R_2;\n // assert (y,x) in R_2;\n }\n }\n}\n\n \nlemma transitiveUnion(R_1: set<(T,T)>, S_1: set, R_2: set<(T,T)>, S_2: set)\n requires |R_1| > 0\n requires |R_2| > 0\n requires |S_1| > 0\n requires |S_2| > 0\n requires relationOnASet(R_1, S_1)\n requires relationOnASet(R_2, S_2)\n requires transitive(R_1, S_1)\n requires transitive(R_2, S_2)\n ensures transitive(R_1+R_2, S_1+S_2) \n{\n\n assume forall a :: a in S_1+S_2 ==> a !in S_1 || a !in S_2;\n\n forall a,b,c | a in S_1+S_2 && b in S_1+S_2 && c in S_1+S_2 && (a,b) in R_1+R_2 && (b,c) in R_1+R_2 \n ensures (a,c) in R_1+R_2\n {\n if a in S_1 && b in S_1 && c in S_1 && (a,b) in R_1 && (b,c) in R_1 {\n }else if a in S_2 && b in S_2 && c in S_2 && (a,b) in R_2 && (b,c) in R_2 {\n }\n } \n}\n\n// lemma transitiveUnionContra(R_1: set<(T,T)>, S_1: set, R_2: set<(T,T)>, S_2: set)\n// requires |R_1| > 0\n// requires |R_2| > 0\n// requires |S_1| > 0\n// requires |S_2| > 0\n// requires relationOnASet(R_1, S_1)\n// requires relationOnASet(R_2, S_2)\n// requires transitive(R_1, S_1)\n// requires transitive(R_2, S_2)\n// ensures exists (R_1+R_2, S_1+S_2) :: !transitive(R_1+R_2, S_1+S_2) \n// {\n// assume S_1 * S_2 != {};\n// if transitive(R_1 + R_2, S_1+S_2) {\n// forall a,b,c | a in S_1+S_2 && b in S_1+S_2 && c in S_1+S_2 && (a,b) in R_1+R_2 && (b,c) in R_1+R_2 \n// ensures (a,c) in R_1+R_2 \n// {\n// if a in S_1 && a !in S_2 && b in S_1 && b in S_2 && c in S_2 && c !in S_1 {\n// assert (a,c) !in R_1;\n// assert (a,c) !in R_2;\n// assert (a,c) !in R_1+R_2;\n// assert false;\n// }\n// } \n// }\n// }\n\nlemma transitiveUnionContra()\n returns (\n R1: set<(T, T)>, S1: set,\n R2: set<(T, T)>, S2: set)\n ensures relationOnASet(R1, S1)\n ensures relationOnASet(R2, S2)\n ensures transitive(R1, S1)\n ensures transitive(R2, S2)\n ensures ! transitive(R1 + R2, S1 + S2)\n{\n var a : T :| assume true;\n var b : T :| assume a != b;\n var c : T :| assume a != c && b != c;\n S1 := {a, b};\n S2 := {b, c};\n R1 := {(a, b)};\n R2 := {(b, c)};\n}\n\nlemma notTrueAlways()\n ensures !\n (forall S1 : set, S2 : set, R1 : set<(T,T)>, R2 : set<(T, T)> ::\n relationOnASet(R1, S1) &&\n relationOnASet(R2, S2) &&\n transitive(R1, S1) &&\n transitive(R2, S2) ==> transitive(R1 + R2, S1 + S2)\n )\n{\n var a, b, c, d := transitiveUnionContra();\n}\n\nmethod test() {\n var x := 7;\n // assert isEven(eight(7));\n var four := 4;\n // var test := set x: nat,y: nat | 1 <= x <= y <= 5 :: (x,y);\n var sample := {1,2,3,4,5,6};\n var test := set x,y | x in sample && y in sample :: (x,y);\n var modulos := set x,y | x in sample && y in sample && x % y == 0 :: (x,y);\n // assert reflexive(test, set x | 1 <=x <= 5);\n // assert equivalenceRelation(modulos, sample);\n\n\n var hmm := (1,2,3);\n // assert 0 <= four < 100 && isEven(nineteenf(four));\n ghost var y: nat :| isEven(nineteenf(y));\n}\n" }, { "test_ID": "298", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_basic examples_BubbleSort.dfy", "ground_truth": "predicate sorted(a:array, from:int, to:int)\n requires a != null;\n reads a;\n requires 0 <= from <= to <= a.Length;\n{\n forall u, v :: from <= u < v < to ==> a[u] <= a[v]\n}\n\npredicate pivot(a:array, to:int, pvt:int)\n requires a != null;\n reads a;\n requires 0 <= pvt < to <= a.Length;\n{\n forall u, v :: 0 <= u < pvt < v < to ==> a[u] <= a[v]\n}\n\nmethod bubbleSort (a: array)\n requires a != null && a.Length > 0;\n modifies a;\n ensures sorted(a, 0, a.Length);\n ensures multiset(a[..]) == multiset(old(a[..]));\n{\n var i:nat := 1;\n\n while (i < a.Length)\n invariant i <= a.Length;\n invariant sorted(a, 0, i);\n invariant multiset(a[..]) == multiset(old(a[..]));\n {\n var j:nat := i;\n while (j > 0)\n invariant multiset(a[..]) == multiset(old(a[..]));\n invariant sorted(a, 0, j);\n invariant sorted(a, j, i+1);\n invariant pivot(a, i+1, j);\n {\n if (a[j-1] > a[j]) {\n var temp:int := a[j-1];\n a[j-1] := a[j];\n a[j] := temp;\n }\n j := j - 1;\n }\n i := i+1;\n }\n}\n\n", "hints_removed": "predicate sorted(a:array, from:int, to:int)\n requires a != null;\n reads a;\n requires 0 <= from <= to <= a.Length;\n{\n forall u, v :: from <= u < v < to ==> a[u] <= a[v]\n}\n\npredicate pivot(a:array, to:int, pvt:int)\n requires a != null;\n reads a;\n requires 0 <= pvt < to <= a.Length;\n{\n forall u, v :: 0 <= u < pvt < v < to ==> a[u] <= a[v]\n}\n\nmethod bubbleSort (a: array)\n requires a != null && a.Length > 0;\n modifies a;\n ensures sorted(a, 0, a.Length);\n ensures multiset(a[..]) == multiset(old(a[..]));\n{\n var i:nat := 1;\n\n while (i < a.Length)\n {\n var j:nat := i;\n while (j > 0)\n {\n if (a[j-1] > a[j]) {\n var temp:int := a[j-1];\n a[j-1] := a[j];\n a[j] := temp;\n }\n j := j - 1;\n }\n i := i+1;\n }\n}\n\n" }, { "test_ID": "299", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_basic examples_BubbleSort_sol.dfy", "ground_truth": "predicate sorted_between (a:array, from:nat, to:nat)\n reads a;\n requires a != null;\n requires from <= to;\n requires to <= a.Length;\n{\n forall i,j :: from <= i < j < to && 0 <= i < j < a.Length ==> a[i] <= a[j]\n}\n \npredicate sorted (a:array)\n reads a;\n requires a!=null;\n{\n sorted_between (a, 0, a.Length)\n}\n\nmethod bubbleSort (a: array)\n modifies a;\n requires a != null;\n requires a.Length > 0;\n ensures sorted(a);\n ensures multiset(old(a[..])) == multiset(a[..]);\n{\n var i:nat := 1;\n\n while (i < a.Length)\n invariant i <= a.Length;\n invariant sorted_between (a, 0, i);\n invariant multiset(old (a[..])) == multiset(a[..]);\n {\n var j:nat := i;\n while (j > 0)\n invariant 0 <= j <= i;\n invariant sorted_between (a, 0, j);\n invariant forall u,v:: 0 <= u < j < v < i+1 ==> a[u] <= a[v];\n invariant sorted_between (a, j, i+1);\n invariant multiset(old (a[..])) == multiset(a[..]);\n {\n if (a[j-1] > a[j]) {\n var temp:int := a[j-1];\n // Introduced bug for permutation\n a[j-1] := a[j];\n //a[j-1] := a[j-1];\n a[j] := temp;\n }\n j := j - 1;\n }\n i := i+1;\n }\n}\n\n", "hints_removed": "predicate sorted_between (a:array, from:nat, to:nat)\n reads a;\n requires a != null;\n requires from <= to;\n requires to <= a.Length;\n{\n forall i,j :: from <= i < j < to && 0 <= i < j < a.Length ==> a[i] <= a[j]\n}\n \npredicate sorted (a:array)\n reads a;\n requires a!=null;\n{\n sorted_between (a, 0, a.Length)\n}\n\nmethod bubbleSort (a: array)\n modifies a;\n requires a != null;\n requires a.Length > 0;\n ensures sorted(a);\n ensures multiset(old(a[..])) == multiset(a[..]);\n{\n var i:nat := 1;\n\n while (i < a.Length)\n {\n var j:nat := i;\n while (j > 0)\n {\n if (a[j-1] > a[j]) {\n var temp:int := a[j-1];\n // Introduced bug for permutation\n a[j-1] := a[j];\n //a[j-1] := a[j-1];\n a[j] := temp;\n }\n j := j - 1;\n }\n i := i+1;\n }\n}\n\n" }, { "test_ID": "300", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_basic examples_add_by_one.dfy", "ground_truth": "method add_by_one (x:int, y:int) returns (r:int)\n requires y >= 0;\n ensures r == x + y;\n{\n var i:int := 0;\n r := x;\n while (i < y)\n invariant i <= y;\n invariant r == x + i;\n decreases y-i;\n {\n r := r + 1;\n i := i + 1;\n }\n return r;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/*\n * Illustrates de-sugaring of the while loop.\n*/\nmethod bar (x:int, y:int) returns (r:int)\n requires y >= 0;\n ensures r == x + y;\n{\n var i := 0;\n r := x;\n // the invariant is true before the loop\n assert (i <= y && r == x + i);\n // the ranking function is positive before the loop\n assert (y-i >= 0);\n\n // havoc variables assigned by the loop\n i, r := *, *;\n // assume the invariant holds\n assume (i <= y && r == x + i);\n // assume the ranking function is positive\n assume (y-i >= 0);\n // store the value of ranking function to compare against later\n ghost var rank_before := y-i;\n\n // one body of the loop\n if (i < y)\n {\n r := r + 1;\n i := i + 1;\n // invariant is true at the end of the loop\n assert (i <= y && r == x + i);\n // ranking function is positive at the end of the loop\n assert (y-i >= 0);\n // ranking function has decreased\n assert (rank_before - (y-i) > 0);\n // if got to here, stop verification of this branch\n assume (false);\n }\n // at this point only know the invariant of the loop + negation of\n // the loop condition\n return r;\n}\n\n", "hints_removed": "method add_by_one (x:int, y:int) returns (r:int)\n requires y >= 0;\n ensures r == x + y;\n{\n var i:int := 0;\n r := x;\n while (i < y)\n {\n r := r + 1;\n i := i + 1;\n }\n return r;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/*\n * Illustrates de-sugaring of the while loop.\n*/\nmethod bar (x:int, y:int) returns (r:int)\n requires y >= 0;\n ensures r == x + y;\n{\n var i := 0;\n r := x;\n // the invariant is true before the loop\n // the ranking function is positive before the loop\n\n // havoc variables assigned by the loop\n i, r := *, *;\n // assume the invariant holds\n assume (i <= y && r == x + i);\n // assume the ranking function is positive\n assume (y-i >= 0);\n // store the value of ranking function to compare against later\n ghost var rank_before := y-i;\n\n // one body of the loop\n if (i < y)\n {\n r := r + 1;\n i := i + 1;\n // invariant is true at the end of the loop\n // ranking function is positive at the end of the loop\n // ranking function has decreased\n // if got to here, stop verification of this branch\n assume (false);\n }\n // at this point only know the invariant of the loop + negation of\n // the loop condition\n return r;\n}\n\n" }, { "test_ID": "301", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_basic examples_add_by_one_details.dfy", "ground_truth": "method plus_one (x: int) returns (r:int)\n requires x >= 0;\n ensures r == x + 1;\n{return x+1;}\nmethod add_by_one (x:int, y:int) returns (r:int)\n{\n assume (y >= 0);\n var i:int := 0;\n r := x;\n\n assert (i <= y);\n assert (r == x + i);\n\n r := *;\n i := *;\n assume (i <= y);\n assume (r == x + i);\n if (i < y)\n // decreases y-i;\n {\n // assert (i >= -2);\n assume (i < -2);\n var t := y - i;\n r := r + 1;\n i := i + 1;\n assert (i <= y);\n assert (r == x + i);\n assert (y-i >= 0);\n assert (y-i < t);\n assume (false);\n }\n\n assert (r == x + y);\n return r;\n}\n\n", "hints_removed": "method plus_one (x: int) returns (r:int)\n requires x >= 0;\n ensures r == x + 1;\n{return x+1;}\nmethod add_by_one (x:int, y:int) returns (r:int)\n{\n assume (y >= 0);\n var i:int := 0;\n r := x;\n\n\n r := *;\n i := *;\n assume (i <= y);\n assume (r == x + i);\n if (i < y)\n // decreases y-i;\n {\n // assert (i >= -2);\n assume (i < -2);\n var t := y - i;\n r := r + 1;\n i := i + 1;\n assume (false);\n }\n\n return r;\n}\n\n" }, { "test_ID": "302", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_basic examples_find_max.dfy", "ground_truth": "method FindMax(a: array) returns (max: int)\n requires a != null && a.Length > 0;\n ensures 0 <= max < a.Length;\n ensures forall x :: 0 <= x < a.Length ==> a[max] >= a[x];\n{\n var i := 0;\n max := 0;\n\n while (i < a.Length)\n invariant i <= a.Length;\n invariant 0 <= max;\n invariant max == 0 || 0 < max < i;\n invariant forall k :: 0 <= k < i ==> a[max] >= a[k]\n {\n if (a[i] > a[max]) { max := i; }\n i := i + 1;\n }\n return max;\n}\n\n", "hints_removed": "method FindMax(a: array) returns (max: int)\n requires a != null && a.Length > 0;\n ensures 0 <= max < a.Length;\n ensures forall x :: 0 <= x < a.Length ==> a[max] >= a[x];\n{\n var i := 0;\n max := 0;\n\n while (i < a.Length)\n {\n if (a[i] > a[max]) { max := i; }\n i := i + 1;\n }\n return max;\n}\n\n" }, { "test_ID": "303", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_basic examples_product_details.dfy", "ground_truth": "method CalcProduct(m: nat, n: nat) returns (res: nat)\n ensures res == m*n;\n{ \n var m1: nat := m;\n res := 0;\n \n assert res == (m-m1)*n;\n m1, res := *, *;\n assume res == (m-m1)*n;\n if (m1!=0) \n { \n var n1: nat := n;\n assert (res == (m-m1)*n + (n-n1));\n // havoc res, n1;\n res, n1 := *, *;\n assume res == (m-m1)*n + (n-n1);\n if (n1 != 0)\n {\n ghost var old_n1 := n1;\n res := res+1;\n n1 := n1-1; \n assert (res == (m-m1)*n + (n-n1));\n assert n1 < old_n1;\n assert n1 >= 0;\n assume (false);\n } \n m1 := m1-1;\n assert res == (m-m1)*n;\n assume false;\n }\n}\n\n\n\n", "hints_removed": "method CalcProduct(m: nat, n: nat) returns (res: nat)\n ensures res == m*n;\n{ \n var m1: nat := m;\n res := 0;\n \n m1, res := *, *;\n assume res == (m-m1)*n;\n if (m1!=0) \n { \n var n1: nat := n;\n // havoc res, n1;\n res, n1 := *, *;\n assume res == (m-m1)*n + (n-n1);\n if (n1 != 0)\n {\n ghost var old_n1 := n1;\n res := res+1;\n n1 := n1-1; \n assume (false);\n } \n m1 := m1-1;\n assume false;\n }\n}\n\n\n\n" }, { "test_ID": "304", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_basic examples_sumto_sol.dfy", "ground_truth": "function sum_up_to (n: nat): nat\n{\n if (n == 0) then 0\n else sum_up_to (n-1) + 1\n}\n\n\nmethod SumUpTo (n: nat) returns (r: nat)\n ensures r == sum_up_to (n);\n{\n var i := 0;\n r := 0;\n while (i < n)\n invariant 0 <= i <= n;\n invariant r == sum_up_to (i);\n {\n r := r + 1;\n i := i + 1;\n }\n}\n\nfunction total (a: seq) : nat\n{\n if |a| == 0 then 0\n else total (a[0..|a|-1]) + a[|a|-1]\n}\n\nlemma total_lemma (a: seq, i:nat) \n requires |a| > 0;\n requires 0 <= i < |a|;\n ensures total (a[0..i]) + a[i] == total (a[0..i+1]);\n{\n ghost var b := a[0..i+1];\n calc\n {\n total (a[0..i+1]);\n total (b);\n total (b[0..|b|-1]) + b[|b|-1];\n total (b[0..|b|-1]) + a[i];\n {assert (b[0..|b|-1] == a[0..i]);}\n total (a[0..i]) + a[i];\n }\n}\n\nmethod Total (a: seq) returns (r:nat)\n ensures r == total (a[0..|a|]); \n{\n var i := 0;\n r := 0;\n while i < |a|\n invariant 0 <= i <= |a|;\n invariant r == total (a[0..i]);\n { \n total_lemma (a, i);\n r := r + a[i];\n i := i + 1;\n }\n}\n\n", "hints_removed": "function sum_up_to (n: nat): nat\n{\n if (n == 0) then 0\n else sum_up_to (n-1) + 1\n}\n\n\nmethod SumUpTo (n: nat) returns (r: nat)\n ensures r == sum_up_to (n);\n{\n var i := 0;\n r := 0;\n while (i < n)\n {\n r := r + 1;\n i := i + 1;\n }\n}\n\nfunction total (a: seq) : nat\n{\n if |a| == 0 then 0\n else total (a[0..|a|-1]) + a[|a|-1]\n}\n\nlemma total_lemma (a: seq, i:nat) \n requires |a| > 0;\n requires 0 <= i < |a|;\n ensures total (a[0..i]) + a[i] == total (a[0..i+1]);\n{\n ghost var b := a[0..i+1];\n calc\n {\n total (a[0..i+1]);\n total (b);\n total (b[0..|b|-1]) + b[|b|-1];\n total (b[0..|b|-1]) + a[i];\n {assert (b[0..|b|-1] == a[0..i]);}\n total (a[0..i]) + a[i];\n }\n}\n\nmethod Total (a: seq) returns (r:nat)\n ensures r == total (a[0..|a|]); \n{\n var i := 0;\n r := 0;\n while i < |a|\n { \n total_lemma (a, i);\n r := r + a[i];\n i := i + 1;\n }\n}\n\n" }, { "test_ID": "305", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_from dafny main repo_dafny0_GhostITECompilation.dfy", "ground_truth": "// RUN: %testDafnyForEachCompiler --refresh-exit-code=0 \"%s\" -- --function-syntax:4 --relax-definite-assignment\n\nfunction F(x: nat, ghost y: nat): nat\n{\n if x == 0 then\n 0\n else if y != 0 then\n F(x, y - 1) // this branch is not compiled (which even makes F auto-accumulator tail recursive)\n else\n F(x - 1, 60) + 13\n}\n\nlemma AboutF(x: nat, y: nat)\n ensures F(x, y) == 13 * x\n{\n}\n\nfunction G(x: nat, ghost y: nat): nat\n{\n if x == 0 then\n 0\n else if y != 0 then\n var z := x + x;\n var a, b, c := 100, if x < z then G(x, y - 1) else G(x, y - 1), 200;\n assert a + b + c == G(x, y - 1) + 300;\n b // this branch is not compiled (which even makes G auto-accumulator tail recursive)\n else\n G(x - 1, 60) + 13\n}\n\n// Ostensibly, the following function is tail recursive. But the ghost-ITE optimization\n// removes the tail call. This test ensures that the unused setup for the tail optimization\n// does not cause problems.\nfunction H(x: int, ghost y: nat): int {\n if y == 0 then\n x\n else\n H(x, y - 1)\n}\n\n// Like function H, function J looks like it's tail recursive. The compiler probably will\n// emit the tail-call label, even though the tail-call is never taken.\nfunction J(x: int): int {\n if true then\n x\n else\n J(x)\n}\n\n// The following function would never verify, and its execution wouldn't terminate.\n// Nevertheless, we'll test here that it compiles into legal target code.\nfunction {:verify false} K(x: int, ghost y: nat): int {\n K(x, y - 1)\n}\n\nmethod Main() {\n print F(5, 3), \"\\n\"; // 65\n print G(5, 3), \"\\n\"; // 65\n print H(65, 3), \"\\n\"; // 65\n print J(65), \"\\n\"; // 65\n}\n\n", "hints_removed": "// RUN: %testDafnyForEachCompiler --refresh-exit-code=0 \"%s\" -- --function-syntax:4 --relax-definite-assignment\n\nfunction F(x: nat, ghost y: nat): nat\n{\n if x == 0 then\n 0\n else if y != 0 then\n F(x, y - 1) // this branch is not compiled (which even makes F auto-accumulator tail recursive)\n else\n F(x - 1, 60) + 13\n}\n\nlemma AboutF(x: nat, y: nat)\n ensures F(x, y) == 13 * x\n{\n}\n\nfunction G(x: nat, ghost y: nat): nat\n{\n if x == 0 then\n 0\n else if y != 0 then\n var z := x + x;\n var a, b, c := 100, if x < z then G(x, y - 1) else G(x, y - 1), 200;\n b // this branch is not compiled (which even makes G auto-accumulator tail recursive)\n else\n G(x - 1, 60) + 13\n}\n\n// Ostensibly, the following function is tail recursive. But the ghost-ITE optimization\n// removes the tail call. This test ensures that the unused setup for the tail optimization\n// does not cause problems.\nfunction H(x: int, ghost y: nat): int {\n if y == 0 then\n x\n else\n H(x, y - 1)\n}\n\n// Like function H, function J looks like it's tail recursive. The compiler probably will\n// emit the tail-call label, even though the tail-call is never taken.\nfunction J(x: int): int {\n if true then\n x\n else\n J(x)\n}\n\n// The following function would never verify, and its execution wouldn't terminate.\n// Nevertheless, we'll test here that it compiles into legal target code.\nfunction {:verify false} K(x: int, ghost y: nat): int {\n K(x, y - 1)\n}\n\nmethod Main() {\n print F(5, 3), \"\\n\"; // 65\n print G(5, 3), \"\\n\"; // 65\n print H(65, 3), \"\\n\"; // 65\n print J(65), \"\\n\"; // 65\n}\n\n" }, { "test_ID": "306", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_from dafny main repo_dafny0_ModulePrint.dfy", "ground_truth": "// NONUNIFORM: Tests printing much more than compilation\n// RUN: %dafny /dafnyVerify:0 /compile:0 /env:0 /dprint:\"%t.dfy\" \"%s\" > \"%t\"\n// RUN: %dafny /dafnyVerify:0 /compile:0 /env:0 /printMode:DllEmbed /dprint:\"%t1.dfy\" \"%t.dfy\" >> \"%t\"\n// RUN: %dafny /env:0 /compile:3 /printMode:DllEmbed /dprint:\"%t2.dfy\" \"%t1.dfy\" >> \"%t\"\n// RUN: %diff \"%t1.dfy\" \"%t2.dfy\" >> \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nabstract module S {\n class C {\n var f: int\n ghost var g: int\n var h: int\n method m()\n modifies this\n }\n}\n\nmodule T refines S {\n class C ... {\n ghost var h: int // change from non-ghost to ghost\n ghost var j: int\n var k: int\n constructor () { }\n method m()\n ensures h == h\n ensures j == j\n {\n assert k == k;\n }\n }\n}\n\nmethod Main() {\n var c := new T.C();\n c.m();\n}\n\n", "hints_removed": "// NONUNIFORM: Tests printing much more than compilation\n// RUN: %dafny /dafnyVerify:0 /compile:0 /env:0 /dprint:\"%t.dfy\" \"%s\" > \"%t\"\n// RUN: %dafny /dafnyVerify:0 /compile:0 /env:0 /printMode:DllEmbed /dprint:\"%t1.dfy\" \"%t.dfy\" >> \"%t\"\n// RUN: %dafny /env:0 /compile:3 /printMode:DllEmbed /dprint:\"%t2.dfy\" \"%t1.dfy\" >> \"%t\"\n// RUN: %diff \"%t1.dfy\" \"%t2.dfy\" >> \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nabstract module S {\n class C {\n var f: int\n ghost var g: int\n var h: int\n method m()\n modifies this\n }\n}\n\nmodule T refines S {\n class C ... {\n ghost var h: int // change from non-ghost to ghost\n ghost var j: int\n var k: int\n constructor () { }\n method m()\n ensures h == h\n ensures j == j\n {\n }\n }\n}\n\nmethod Main() {\n var c := new T.C();\n c.m();\n}\n\n" }, { "test_ID": "307", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_from dafny main repo_dafny1_BDD.dfy", "ground_truth": "// RUN: %testDafnyForEachResolver \"%s\"\n\n\nmodule SimpleBDD\n{\n class BDDNode\n {\n static ghost predicate bitfunc(f: map, bool>, n: nat)\n {\n forall i:seq :: i in f <==> |i| == n\n }\n ghost var Contents: map, bool>\n ghost var Repr: set\n ghost var n: nat\n var f: BDDNode?, t: BDDNode?\n var b: bool\n ghost predicate valid()\n reads this, Repr\n {\n bitfunc(Contents,n) &&\n (0 == n ==> (b <==> Contents[[]])) &&\n (0 < n ==>\n this in Repr &&\n f != null && t != null && t in Repr && f in Repr &&\n t.Repr <= Repr && f.Repr <= Repr &&\n this !in f.Repr && this !in t.Repr &&\n t.valid() && f.valid() &&\n t.n == f.n == n-1 &&\n (forall s | s in t.Contents :: Contents[[true] + s] <==> t.Contents[s]) &&\n (forall s | s in f.Contents :: Contents[[false] + s] <==> f.Contents[s]))\n }\n }\n class BDD\n {\n var root: BDDNode\n ghost predicate valid()\n reads this, Repr\n {\n root in Repr && root.Repr <= Repr && root.valid() &&\n n == root.n && Contents == root.Contents\n }\n constructor () {\n root := new BDDNode;\n }\n\n ghost var Contents: map, bool>\n var n: nat\n ghost var Repr: set\n\n method Eval(s: seq) returns(b: bool)\n requires valid() && |s| == n\n ensures b == Contents[s]\n {\n var node: BDDNode := root;\n var i := n;\n assert s[n-i..] == s;\n while i > 0\n invariant node.valid()\n invariant 0 <= i == node.n <= n\n invariant Contents[s] == node.Contents[s[n-i..]]\n {\n assert s[n-i..] == [s[n-i]] + s[n-i+1..];\n node := if s[n-i] then node.t else node.f;\n i := i - 1;\n }\n assert s[n-i..] == [];\n b := node.b;\n }\n }\n}\n\n", "hints_removed": "// RUN: %testDafnyForEachResolver \"%s\"\n\n\nmodule SimpleBDD\n{\n class BDDNode\n {\n static ghost predicate bitfunc(f: map, bool>, n: nat)\n {\n forall i:seq :: i in f <==> |i| == n\n }\n ghost var Contents: map, bool>\n ghost var Repr: set\n ghost var n: nat\n var f: BDDNode?, t: BDDNode?\n var b: bool\n ghost predicate valid()\n reads this, Repr\n {\n bitfunc(Contents,n) &&\n (0 == n ==> (b <==> Contents[[]])) &&\n (0 < n ==>\n this in Repr &&\n f != null && t != null && t in Repr && f in Repr &&\n t.Repr <= Repr && f.Repr <= Repr &&\n this !in f.Repr && this !in t.Repr &&\n t.valid() && f.valid() &&\n t.n == f.n == n-1 &&\n (forall s | s in t.Contents :: Contents[[true] + s] <==> t.Contents[s]) &&\n (forall s | s in f.Contents :: Contents[[false] + s] <==> f.Contents[s]))\n }\n }\n class BDD\n {\n var root: BDDNode\n ghost predicate valid()\n reads this, Repr\n {\n root in Repr && root.Repr <= Repr && root.valid() &&\n n == root.n && Contents == root.Contents\n }\n constructor () {\n root := new BDDNode;\n }\n\n ghost var Contents: map, bool>\n var n: nat\n ghost var Repr: set\n\n method Eval(s: seq) returns(b: bool)\n requires valid() && |s| == n\n ensures b == Contents[s]\n {\n var node: BDDNode := root;\n var i := n;\n while i > 0\n {\n node := if s[n-i] then node.t else node.f;\n i := i - 1;\n }\n b := node.b;\n }\n }\n}\n\n" }, { "test_ID": "308", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_from dafny main repo_dafny1_ListContents.dfy", "ground_truth": "// RUN: %testDafnyForEachResolver \"%s\"\n\n\nclass Node {\n ghost var List: seq\n ghost var Repr: set>\n\n var data: T\n var next: Node?\n\n ghost predicate Valid()\n reads this, Repr\n {\n this in Repr &&\n (next == null ==> List == [data]) &&\n (next != null ==>\n next in Repr && next.Repr <= Repr &&\n this !in next.Repr &&\n List == [data] + next.List &&\n next.Valid())\n }\n\n constructor (d: T)\n ensures Valid() && fresh(Repr)\n ensures List == [d]\n {\n data, next := d, null;\n List, Repr := [d], {this};\n }\n\n constructor InitAsPredecessor(d: T, succ: Node)\n requires succ.Valid()\n ensures Valid() && fresh(Repr - succ.Repr)\n ensures List == [d] + succ.List\n {\n data, next := d, succ;\n List := [d] + succ.List;\n Repr := {this} + succ.Repr;\n }\n\n method Prepend(d: T) returns (r: Node)\n requires Valid()\n ensures r.Valid() && fresh(r.Repr - old(Repr))\n ensures r.List == [d] + List\n {\n r := new Node.InitAsPredecessor(d, this);\n }\n\n method SkipHead() returns (r: Node?)\n requires Valid()\n ensures r == null ==> |List| == 1\n ensures r != null ==> r.Valid() && r.List == List[1..] && r.Repr <= Repr\n {\n r := next;\n }\n\n method ReverseInPlace() returns (reverse: Node)\n requires Valid()\n modifies Repr\n ensures reverse.Valid() && reverse.Repr <= old(Repr)\n ensures |reverse.List| == |old(List)|\n ensures forall i :: 0 <= i < |reverse.List| ==> reverse.List[i] == old(List)[|old(List)|-1-i]\n {\n var current := next;\n reverse := this;\n reverse.next := null;\n reverse.Repr := {reverse};\n reverse.List := [data];\n\n while current != null\n invariant reverse.Valid() && reverse.Repr <= old(Repr)\n invariant current == null ==> |old(List)| == |reverse.List|\n invariant current != null ==>\n current.Valid() &&\n current in old(Repr) && current.Repr <= old(Repr) &&\n current.Repr !! reverse.Repr\n invariant current != null ==>\n |old(List)| == |reverse.List| + |current.List| &&\n current.List == old(List)[|reverse.List|..]\n invariant forall i :: 0 <= i < |reverse.List| ==> reverse.List[i] == old(List)[|reverse.List|-1-i]\n decreases if current != null then |current.List| else -1\n {\n var nx := current.next;\n\n // ..., reverse, current, nx, ...\n current.next := reverse;\n current.Repr := {current} + reverse.Repr;\n current.List := [current.data] + reverse.List;\n\n reverse := current;\n current := nx;\n }\n }\n}\n\n", "hints_removed": "// RUN: %testDafnyForEachResolver \"%s\"\n\n\nclass Node {\n ghost var List: seq\n ghost var Repr: set>\n\n var data: T\n var next: Node?\n\n ghost predicate Valid()\n reads this, Repr\n {\n this in Repr &&\n (next == null ==> List == [data]) &&\n (next != null ==>\n next in Repr && next.Repr <= Repr &&\n this !in next.Repr &&\n List == [data] + next.List &&\n next.Valid())\n }\n\n constructor (d: T)\n ensures Valid() && fresh(Repr)\n ensures List == [d]\n {\n data, next := d, null;\n List, Repr := [d], {this};\n }\n\n constructor InitAsPredecessor(d: T, succ: Node)\n requires succ.Valid()\n ensures Valid() && fresh(Repr - succ.Repr)\n ensures List == [d] + succ.List\n {\n data, next := d, succ;\n List := [d] + succ.List;\n Repr := {this} + succ.Repr;\n }\n\n method Prepend(d: T) returns (r: Node)\n requires Valid()\n ensures r.Valid() && fresh(r.Repr - old(Repr))\n ensures r.List == [d] + List\n {\n r := new Node.InitAsPredecessor(d, this);\n }\n\n method SkipHead() returns (r: Node?)\n requires Valid()\n ensures r == null ==> |List| == 1\n ensures r != null ==> r.Valid() && r.List == List[1..] && r.Repr <= Repr\n {\n r := next;\n }\n\n method ReverseInPlace() returns (reverse: Node)\n requires Valid()\n modifies Repr\n ensures reverse.Valid() && reverse.Repr <= old(Repr)\n ensures |reverse.List| == |old(List)|\n ensures forall i :: 0 <= i < |reverse.List| ==> reverse.List[i] == old(List)[|old(List)|-1-i]\n {\n var current := next;\n reverse := this;\n reverse.next := null;\n reverse.Repr := {reverse};\n reverse.List := [data];\n\n while current != null\n current.Valid() &&\n current in old(Repr) && current.Repr <= old(Repr) &&\n current.Repr !! reverse.Repr\n |old(List)| == |reverse.List| + |current.List| &&\n current.List == old(List)[|reverse.List|..]\n {\n var nx := current.next;\n\n // ..., reverse, current, nx, ...\n current.next := reverse;\n current.Repr := {current} + reverse.Repr;\n current.List := [current.data] + reverse.List;\n\n reverse := current;\n current := nx;\n }\n }\n}\n\n" }, { "test_ID": "309", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_from dafny main repo_dafny1_Queue.dfy", "ground_truth": "// RUN: %testDafnyForEachResolver \"%s\"\n\n\n// Queue.dfy\n// Dafny version of Queue.bpl\n// Rustan Leino, 2008\n\nclass Queue {\n var head: Node\n var tail: Node\n\n ghost var contents: seq\n ghost var footprint: set\n ghost var spine: set>\n\n ghost predicate Valid()\n reads this, footprint\n {\n this in footprint && spine <= footprint &&\n head in spine &&\n tail in spine &&\n tail.next == null &&\n (forall n ::\n n in spine ==>\n n.footprint <= footprint && this !in n.footprint &&\n n.Valid() &&\n (n.next == null ==> n == tail)) &&\n (forall n ::\n n in spine ==>\n n.next != null ==> n.next in spine) &&\n contents == head.tailContents\n }\n\n constructor Init()\n ensures Valid() && fresh(footprint - {this})\n ensures |contents| == 0\n {\n var n: Node := new Node.Init();\n head := n;\n tail := n;\n contents := n.tailContents;\n footprint := {this} + n.footprint;\n spine := {n};\n }\n\n method Rotate()\n requires Valid()\n requires 0 < |contents|\n modifies footprint\n ensures Valid() && fresh(footprint - old(footprint))\n ensures contents == old(contents)[1..] + old(contents)[..1]\n {\n var t := Front();\n Dequeue();\n Enqueue(t);\n }\n\n method RotateAny()\n requires Valid()\n requires 0 < |contents|\n modifies footprint\n ensures Valid() && fresh(footprint - old(footprint))\n ensures |contents| == |old(contents)|\n ensures exists i :: 0 <= i && i <= |contents| &&\n contents == old(contents)[i..] + old(contents)[..i]\n {\n var t := Front();\n Dequeue();\n Enqueue(t);\n }\n\n method IsEmpty() returns (isEmpty: bool)\n requires Valid()\n ensures isEmpty <==> |contents| == 0\n {\n isEmpty := head == tail;\n }\n\n method Enqueue(t: T)\n requires Valid()\n modifies footprint\n ensures Valid() && fresh(footprint - old(footprint))\n ensures contents == old(contents) + [t]\n {\n var n := new Node.Init();\n n.data := t;\n tail.next := n;\n tail := n;\n\n forall m | m in spine {\n m.tailContents := m.tailContents + [t];\n }\n contents := head.tailContents;\n\n forall m | m in spine {\n m.footprint := m.footprint + n.footprint;\n }\n footprint := footprint + n.footprint;\n\n spine := spine + {n};\n }\n\n method Front() returns (t: T)\n requires Valid()\n requires 0 < |contents|\n ensures t == contents[0]\n {\n t := head.next.data;\n }\n\n method Dequeue()\n requires Valid()\n requires 0 < |contents|\n modifies footprint\n ensures Valid() && fresh(footprint - old(footprint))\n ensures contents == old(contents)[1..]\n {\n var n := head.next;\n head := n;\n contents := n.tailContents;\n }\n}\n\nclass Node {\n var data: T\n var next: Node?\n\n ghost var tailContents: seq\n ghost var footprint: set\n\n ghost predicate Valid()\n reads this, footprint\n {\n this in footprint &&\n (next != null ==> next in footprint && next.footprint <= footprint) &&\n (next == null ==> tailContents == []) &&\n (next != null ==> tailContents == [next.data] + next.tailContents)\n }\n\n constructor Init()\n ensures Valid() && fresh(footprint - {this})\n ensures next == null\n {\n next := null;\n tailContents := [];\n footprint := {this};\n }\n}\n\nclass Main {\n method A(t: T, u: T, v: T)\n {\n var q0 := new Queue.Init();\n var q1 := new Queue.Init();\n\n q0.Enqueue(t);\n q0.Enqueue(u);\n\n q1.Enqueue(v);\n\n assert |q0.contents| == 2;\n\n var w := q0.Front();\n assert w == t;\n q0.Dequeue();\n\n w := q0.Front();\n assert w == u;\n\n assert |q0.contents| == 1;\n assert |q1.contents| == 1;\n }\n\n method Main2(t: U, u: U, v: U, q0: Queue, q1: Queue)\n requires q0.Valid()\n requires q1.Valid()\n requires q0.footprint !! q1.footprint\n requires |q0.contents| == 0\n modifies q0.footprint, q1.footprint\n ensures fresh(q0.footprint - old(q0.footprint))\n ensures fresh(q1.footprint - old(q1.footprint))\n {\n q0.Enqueue(t);\n q0.Enqueue(u);\n\n q1.Enqueue(v);\n\n assert |q0.contents| == 2;\n\n var w := q0.Front();\n assert w == t;\n q0.Dequeue();\n\n w := q0.Front();\n assert w == u;\n\n assert |q0.contents| == 1;\n assert |q1.contents| == old(|q1.contents|) + 1;\n }\n}\n\n", "hints_removed": "// RUN: %testDafnyForEachResolver \"%s\"\n\n\n// Queue.dfy\n// Dafny version of Queue.bpl\n// Rustan Leino, 2008\n\nclass Queue {\n var head: Node\n var tail: Node\n\n ghost var contents: seq\n ghost var footprint: set\n ghost var spine: set>\n\n ghost predicate Valid()\n reads this, footprint\n {\n this in footprint && spine <= footprint &&\n head in spine &&\n tail in spine &&\n tail.next == null &&\n (forall n ::\n n in spine ==>\n n.footprint <= footprint && this !in n.footprint &&\n n.Valid() &&\n (n.next == null ==> n == tail)) &&\n (forall n ::\n n in spine ==>\n n.next != null ==> n.next in spine) &&\n contents == head.tailContents\n }\n\n constructor Init()\n ensures Valid() && fresh(footprint - {this})\n ensures |contents| == 0\n {\n var n: Node := new Node.Init();\n head := n;\n tail := n;\n contents := n.tailContents;\n footprint := {this} + n.footprint;\n spine := {n};\n }\n\n method Rotate()\n requires Valid()\n requires 0 < |contents|\n modifies footprint\n ensures Valid() && fresh(footprint - old(footprint))\n ensures contents == old(contents)[1..] + old(contents)[..1]\n {\n var t := Front();\n Dequeue();\n Enqueue(t);\n }\n\n method RotateAny()\n requires Valid()\n requires 0 < |contents|\n modifies footprint\n ensures Valid() && fresh(footprint - old(footprint))\n ensures |contents| == |old(contents)|\n ensures exists i :: 0 <= i && i <= |contents| &&\n contents == old(contents)[i..] + old(contents)[..i]\n {\n var t := Front();\n Dequeue();\n Enqueue(t);\n }\n\n method IsEmpty() returns (isEmpty: bool)\n requires Valid()\n ensures isEmpty <==> |contents| == 0\n {\n isEmpty := head == tail;\n }\n\n method Enqueue(t: T)\n requires Valid()\n modifies footprint\n ensures Valid() && fresh(footprint - old(footprint))\n ensures contents == old(contents) + [t]\n {\n var n := new Node.Init();\n n.data := t;\n tail.next := n;\n tail := n;\n\n forall m | m in spine {\n m.tailContents := m.tailContents + [t];\n }\n contents := head.tailContents;\n\n forall m | m in spine {\n m.footprint := m.footprint + n.footprint;\n }\n footprint := footprint + n.footprint;\n\n spine := spine + {n};\n }\n\n method Front() returns (t: T)\n requires Valid()\n requires 0 < |contents|\n ensures t == contents[0]\n {\n t := head.next.data;\n }\n\n method Dequeue()\n requires Valid()\n requires 0 < |contents|\n modifies footprint\n ensures Valid() && fresh(footprint - old(footprint))\n ensures contents == old(contents)[1..]\n {\n var n := head.next;\n head := n;\n contents := n.tailContents;\n }\n}\n\nclass Node {\n var data: T\n var next: Node?\n\n ghost var tailContents: seq\n ghost var footprint: set\n\n ghost predicate Valid()\n reads this, footprint\n {\n this in footprint &&\n (next != null ==> next in footprint && next.footprint <= footprint) &&\n (next == null ==> tailContents == []) &&\n (next != null ==> tailContents == [next.data] + next.tailContents)\n }\n\n constructor Init()\n ensures Valid() && fresh(footprint - {this})\n ensures next == null\n {\n next := null;\n tailContents := [];\n footprint := {this};\n }\n}\n\nclass Main {\n method A(t: T, u: T, v: T)\n {\n var q0 := new Queue.Init();\n var q1 := new Queue.Init();\n\n q0.Enqueue(t);\n q0.Enqueue(u);\n\n q1.Enqueue(v);\n\n\n var w := q0.Front();\n q0.Dequeue();\n\n w := q0.Front();\n\n }\n\n method Main2(t: U, u: U, v: U, q0: Queue, q1: Queue)\n requires q0.Valid()\n requires q1.Valid()\n requires q0.footprint !! q1.footprint\n requires |q0.contents| == 0\n modifies q0.footprint, q1.footprint\n ensures fresh(q0.footprint - old(q0.footprint))\n ensures fresh(q1.footprint - old(q1.footprint))\n {\n q0.Enqueue(t);\n q0.Enqueue(u);\n\n q1.Enqueue(v);\n\n\n var w := q0.Front();\n q0.Dequeue();\n\n w := q0.Front();\n\n }\n}\n\n" }, { "test_ID": "310", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_from dafny main repo_dafny2_COST-verif-comp-2011-2-MaxTree-class.dfy", "ground_truth": "// RUN: %testDafnyForEachResolver \"%s\" -- --warn-deprecation:false\n\n\n/*\nRustan Leino, 5 Oct 2011\n\nCOST Verification Competition, Challenge 2: Maximum in a tree\nhttp://foveoos2011.cost-ic0701.org/verification-competition\n\nGiven: A non-empty binary tree, where every node carries an integer.\n\nImplement and verify a program that computes the maximum of the values\nin the tree.\n\nPlease base your program on the following data structure signature:\n\npublic class Tree {\n int value;\n Tree left;\n Tree right;\n}\n\nYou may represent empty trees as null references or as you consider\nappropriate.\n*/\n\n// Remarks:\n\n// The specification of this program uses the common dynamic-frames idiom in Dafny: the\n// ghost field 'Contents' stores the abstract value of an object, the ghost field 'Repr'\n// stores the set of (references to) objects that make up the representation of the object\n// (which in this case is the Tree itself plus the 'Repr' sets of the left and right\n// subtrees), and a function 'Valid()' that returns 'true' when an object is in a\n// consistent state (that is, when an object satisfies the \"class invariant\").\n\n// The design I used was to represent an empty tree as a Tree object whose left and\n// right pointers point to the object iself. This is convenient, because it lets\n// clients of Tree and the implementation of Tree always use non-null pointers to\n// Tree objects.\n\n// What needs to be human-trusted about this program is that the 'requires' and\n// 'ensures' clauses (that is, the pre- and postconditions, respectively) of\n// 'ComputeMax' are correct. And, since the specification talks about the ghost\n// variable 'Contents', one also needs to trust that the 'Valid()' function\n// constrains 'Contents' in a way that a human thinks matches the intuitive\n// definition of what the contents of a tree is.\n\n// To give a taste of that the 'Valid()' function does not over-constrain the\n// object, I have included two instance constructors, 'Empty()' and 'Node(...)'.\n// To take this a step further, one could also write a 'Main' method that\n// builds somme tree and then calls 'ComputeMax', but I didn't do that here.\n\n// About Dafny:\n// As always (when it is successful), Dafny verifies that the program does not\n// cause any run-time errors (like array index bounds errors), that the program\n// terminates, that expressions and functions are well defined, and that all\n// specifications are satisfied. The language prevents type errors by being type\n// safe, prevents dangling pointers by not having an \"address-of\" or \"deallocate\"\n// operation (which is accommodated at run time by a garbage collector), and\n// prevents arithmetic overflow errors by using mathematical integers (which\n// is accommodated at run time by using BigNum's). By proving that programs\n// terminate, Dafny proves that a program's time usage is finite, which implies\n// that the program's space usage is finite too. However, executing the\n// program may fall short of your hopes if you don't have enough time or\n// space; that is, the program may run out of space or may fail to terminate in\n// your lifetime, because Dafny does not prove that the time or space needed by\n// the program matches your execution environment. The only input fed to\n// the Dafny verifier/compiler is the program text below; Dafny then automatically\n// verifies and compiles the program (for this program in less than 2.5 seconds)\n// without further human intervention.\n\nclass Tree {\n // an empty tree is represented by a Tree object with left==this==right\n var value: int\n var left: Tree?\n var right: Tree?\n\n ghost var Contents: seq\n ghost var Repr: set\n ghost predicate Valid()\n reads this, Repr\n ensures Valid() ==> this in Repr\n {\n this in Repr &&\n left != null && right != null &&\n ((left == this == right && Contents == []) ||\n (left in Repr && left.Repr <= Repr && this !in left.Repr &&\n right in Repr && right.Repr <= Repr && this !in right.Repr &&\n left.Valid() && right.Valid() &&\n Contents == left.Contents + [value] + right.Contents))\n }\n\n function IsEmpty(): bool\n requires Valid();\n reads this, Repr;\n ensures IsEmpty() <==> Contents == [];\n {\n left == this\n }\n\n constructor Empty()\n ensures Valid() && Contents == [];\n {\n left, right := this, this;\n Contents := [];\n Repr := {this};\n }\n\n constructor Node(lft: Tree, val: int, rgt: Tree)\n requires lft.Valid() && rgt.Valid();\n ensures Valid() && Contents == lft.Contents + [val] + rgt.Contents;\n {\n left, value, right := lft, val, rgt;\n Contents := lft.Contents + [val] + rgt.Contents;\n Repr := lft.Repr + {this} + rgt.Repr;\n }\n\n lemma exists_intro(P: T ~> bool, x: T)\n requires P.requires(x)\n requires P(x)\n ensures exists y :: P.requires(y) && P(y)\n {\n }\n\n method ComputeMax() returns (mx: int)\n requires Valid() && !IsEmpty();\n ensures forall x :: x in Contents ==> x <= mx;\n ensures exists x :: x in Contents && x == mx;\n decreases Repr;\n {\n mx := value;\n\n if (!left.IsEmpty()) {\n var m := left.ComputeMax();\n mx := if mx < m then m else mx;\n }\n\n if (!right.IsEmpty()) {\n var m := right.ComputeMax();\n mx := if mx < m then m else mx;\n }\n\n exists_intro(x reads this => x in Contents && x == mx, mx);\n }\n}\n\n", "hints_removed": "// RUN: %testDafnyForEachResolver \"%s\" -- --warn-deprecation:false\n\n\n/*\nRustan Leino, 5 Oct 2011\n\nCOST Verification Competition, Challenge 2: Maximum in a tree\nhttp://foveoos2011.cost-ic0701.org/verification-competition\n\nGiven: A non-empty binary tree, where every node carries an integer.\n\nImplement and verify a program that computes the maximum of the values\nin the tree.\n\nPlease base your program on the following data structure signature:\n\npublic class Tree {\n int value;\n Tree left;\n Tree right;\n}\n\nYou may represent empty trees as null references or as you consider\nappropriate.\n*/\n\n// Remarks:\n\n// The specification of this program uses the common dynamic-frames idiom in Dafny: the\n// ghost field 'Contents' stores the abstract value of an object, the ghost field 'Repr'\n// stores the set of (references to) objects that make up the representation of the object\n// (which in this case is the Tree itself plus the 'Repr' sets of the left and right\n// subtrees), and a function 'Valid()' that returns 'true' when an object is in a\n// consistent state (that is, when an object satisfies the \"class invariant\").\n\n// The design I used was to represent an empty tree as a Tree object whose left and\n// right pointers point to the object iself. This is convenient, because it lets\n// clients of Tree and the implementation of Tree always use non-null pointers to\n// Tree objects.\n\n// What needs to be human-trusted about this program is that the 'requires' and\n// 'ensures' clauses (that is, the pre- and postconditions, respectively) of\n// 'ComputeMax' are correct. And, since the specification talks about the ghost\n// variable 'Contents', one also needs to trust that the 'Valid()' function\n// constrains 'Contents' in a way that a human thinks matches the intuitive\n// definition of what the contents of a tree is.\n\n// To give a taste of that the 'Valid()' function does not over-constrain the\n// object, I have included two instance constructors, 'Empty()' and 'Node(...)'.\n// To take this a step further, one could also write a 'Main' method that\n// builds somme tree and then calls 'ComputeMax', but I didn't do that here.\n\n// About Dafny:\n// As always (when it is successful), Dafny verifies that the program does not\n// cause any run-time errors (like array index bounds errors), that the program\n// terminates, that expressions and functions are well defined, and that all\n// specifications are satisfied. The language prevents type errors by being type\n// safe, prevents dangling pointers by not having an \"address-of\" or \"deallocate\"\n// operation (which is accommodated at run time by a garbage collector), and\n// prevents arithmetic overflow errors by using mathematical integers (which\n// is accommodated at run time by using BigNum's). By proving that programs\n// terminate, Dafny proves that a program's time usage is finite, which implies\n// that the program's space usage is finite too. However, executing the\n// program may fall short of your hopes if you don't have enough time or\n// space; that is, the program may run out of space or may fail to terminate in\n// your lifetime, because Dafny does not prove that the time or space needed by\n// the program matches your execution environment. The only input fed to\n// the Dafny verifier/compiler is the program text below; Dafny then automatically\n// verifies and compiles the program (for this program in less than 2.5 seconds)\n// without further human intervention.\n\nclass Tree {\n // an empty tree is represented by a Tree object with left==this==right\n var value: int\n var left: Tree?\n var right: Tree?\n\n ghost var Contents: seq\n ghost var Repr: set\n ghost predicate Valid()\n reads this, Repr\n ensures Valid() ==> this in Repr\n {\n this in Repr &&\n left != null && right != null &&\n ((left == this == right && Contents == []) ||\n (left in Repr && left.Repr <= Repr && this !in left.Repr &&\n right in Repr && right.Repr <= Repr && this !in right.Repr &&\n left.Valid() && right.Valid() &&\n Contents == left.Contents + [value] + right.Contents))\n }\n\n function IsEmpty(): bool\n requires Valid();\n reads this, Repr;\n ensures IsEmpty() <==> Contents == [];\n {\n left == this\n }\n\n constructor Empty()\n ensures Valid() && Contents == [];\n {\n left, right := this, this;\n Contents := [];\n Repr := {this};\n }\n\n constructor Node(lft: Tree, val: int, rgt: Tree)\n requires lft.Valid() && rgt.Valid();\n ensures Valid() && Contents == lft.Contents + [val] + rgt.Contents;\n {\n left, value, right := lft, val, rgt;\n Contents := lft.Contents + [val] + rgt.Contents;\n Repr := lft.Repr + {this} + rgt.Repr;\n }\n\n lemma exists_intro(P: T ~> bool, x: T)\n requires P.requires(x)\n requires P(x)\n ensures exists y :: P.requires(y) && P(y)\n {\n }\n\n method ComputeMax() returns (mx: int)\n requires Valid() && !IsEmpty();\n ensures forall x :: x in Contents ==> x <= mx;\n ensures exists x :: x in Contents && x == mx;\n {\n mx := value;\n\n if (!left.IsEmpty()) {\n var m := left.ComputeMax();\n mx := if mx < m then m else mx;\n }\n\n if (!right.IsEmpty()) {\n var m := right.ComputeMax();\n mx := if mx < m then m else mx;\n }\n\n exists_intro(x reads this => x in Contents && x == mx, mx);\n }\n}\n\n" }, { "test_ID": "311", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_from dafny main repo_dafny2_COST-verif-comp-2011-3-TwoDuplicates.dfy", "ground_truth": "// RUN: %testDafnyForEachResolver \"%s\" -- --warn-deprecation:false\n\n\n/*\nRustan Leino, 5 Oct 2011\n\nCOST Verification Competition, Challenge 3: Two equal elements\nhttp://foveoos2011.cost-ic0701.org/verification-competition\n\nGiven: An integer array a of length n+2 with n>=2. It is known that at\nleast two values stored in the array appear twice (i.e., there are at\nleast two duplets).\n\nImplement and verify a program finding such two values.\n\nYou may assume that the array contains values between 0 and n-1.\n*/\n\n// Remarks:\n\n// The implementation of method 'Search' takes one pass through the elements of\n// the given array. To keep track of what it has seen, it allocates an array as\n// temporary storage--I imagine that this is what the competition designers\n// had in mind, since the problem description says one can assume the values\n// of the given array to lie in the range 0..n.\n\n// To keep track of whether it already has found one duplicate, the method\n// sets the output variables p and q as follows:\n// p != q - no duplicates found yet\n// p == q - one duplicate found so far, namely the value stored in p and q\n// Note, the loop invariant does not need to say anything about the state\n// of two duplicates having been found, because when the second duplicate is\n// found, the method returns.\n\n// What needs to be human-trusted about this program is the specification of\n// 'Search'. The specification straightforwardly lists the assumptions stated\n// in the problem description, including the given fact that the array contains\n// (at least) two distinct elements that each occurs (at least) twice. To\n// trust the specification of 'Search', a human also needs to trust the definition\n// of 'IsDuplicate' and its auxiliary function 'IsPrefixDuplicate'.\n\n// About Dafny:\n// As always (when it is successful), Dafny verifies that the program does not\n// cause any run-time errors (like array index bounds errors), that the program\n// terminates, that expressions and functions are well defined, and that all\n// specifications are satisfied. The language prevents type errors by being type\n// safe, prevents dangling pointers by not having an \"address-of\" or \"deallocate\"\n// operation (which is accommodated at run time by a garbage collector), and\n// prevents arithmetic overflow errors by using mathematical integers (which\n// is accommodated at run time by using BigNum's). By proving that programs\n// terminate, Dafny proves that a program's time usage is finite, which implies\n// that the program's space usage is finite too. However, executing the\n// program may fall short of your hopes if you don't have enough time or\n// space; that is, the program may run out of space or may fail to terminate in\n// your lifetime, because Dafny does not prove that the time or space needed by\n// the program matches your execution environment. The only input fed to\n// the Dafny verifier/compiler is the program text below; Dafny then automatically\n// verifies and compiles the program (for this program in less than 11 seconds)\n// without further human intervention.\n\nghost predicate IsDuplicate(a: array, p: int)\n reads a\n{\n IsPrefixDuplicate(a, a.Length, p)\n}\n\nghost predicate IsPrefixDuplicate(a: array, k: int, p: int)\n requires 0 <= k <= a.Length;\n reads a;\n{\n exists i,j :: 0 <= i < j < k && a[i] == a[j] == p\n}\n\nmethod Search(a: array) returns (p: int, q: int)\n requires 4 <= a.Length;\n requires exists p,q :: p != q && IsDuplicate(a, p) && IsDuplicate(a, q); // two distinct duplicates exist\n requires forall i :: 0 <= i < a.Length ==> 0 <= a[i] < a.Length - 2; // the elements of \"a\" in the range [0.. a.Length-2]\n ensures p != q && IsDuplicate(a, p) && IsDuplicate(a, q);\n{\n // allocate an array \"d\" and initialize its elements to -1.\n var d := new int[a.Length-2];\n var i := 0;\n while (i < d.Length)\n invariant 0 <= i <= d.Length && forall j :: 0 <= j < i ==> d[j] == -1;\n {\n d[i], i := -1, i+1;\n }\n\n i, p, q := 0, 0, 1;\n while (true)\n invariant 0 <= i < a.Length;\n invariant forall j :: 0 <= j < d.Length ==>\n (d[j] == -1 && forall k :: 0 <= k < i ==> a[k] != j) ||\n (0 <= d[j] < i && a[d[j]] == j);\n invariant p == q ==> IsDuplicate(a, p); //WISH remove the trigger on the next line\n invariant forall k {:trigger old(a[k])} :: 0 <= k < i && IsPrefixDuplicate(a, i, a[k]) ==> p == q == a[k];\n decreases a.Length - i;\n {\n var k := d[a[i]];\n assert k < i; // note, this assertion is really for human consumption; it is not needed by the verifier, and it does not change the performance of the verifier\n if (k == -1) {\n // a[i] does not exist in a[..i]\n d[a[i]] := i;\n } else {\n // we have encountered a duplicate\n assert a[i] == a[k] && IsDuplicate(a, a[i]); // note, this assertion is really for human consumption; it is not needed by the verifier, and it does not change the performance of the verifier\n if (p != q) {\n // this is the first duplicate encountered\n p, q := a[i], a[i];\n } else if (p == a[i]) {\n // this is another copy of the same duplicate we have seen before\n } else {\n // this is the second duplicate\n q := a[i];\n return;\n }\n }\n i := i + 1;\n }\n}\n\n", "hints_removed": "// RUN: %testDafnyForEachResolver \"%s\" -- --warn-deprecation:false\n\n\n/*\nRustan Leino, 5 Oct 2011\n\nCOST Verification Competition, Challenge 3: Two equal elements\nhttp://foveoos2011.cost-ic0701.org/verification-competition\n\nGiven: An integer array a of length n+2 with n>=2. It is known that at\nleast two values stored in the array appear twice (i.e., there are at\nleast two duplets).\n\nImplement and verify a program finding such two values.\n\nYou may assume that the array contains values between 0 and n-1.\n*/\n\n// Remarks:\n\n// The implementation of method 'Search' takes one pass through the elements of\n// the given array. To keep track of what it has seen, it allocates an array as\n// temporary storage--I imagine that this is what the competition designers\n// had in mind, since the problem description says one can assume the values\n// of the given array to lie in the range 0..n.\n\n// To keep track of whether it already has found one duplicate, the method\n// sets the output variables p and q as follows:\n// p != q - no duplicates found yet\n// p == q - one duplicate found so far, namely the value stored in p and q\n// Note, the loop invariant does not need to say anything about the state\n// of two duplicates having been found, because when the second duplicate is\n// found, the method returns.\n\n// What needs to be human-trusted about this program is the specification of\n// 'Search'. The specification straightforwardly lists the assumptions stated\n// in the problem description, including the given fact that the array contains\n// (at least) two distinct elements that each occurs (at least) twice. To\n// trust the specification of 'Search', a human also needs to trust the definition\n// of 'IsDuplicate' and its auxiliary function 'IsPrefixDuplicate'.\n\n// About Dafny:\n// As always (when it is successful), Dafny verifies that the program does not\n// cause any run-time errors (like array index bounds errors), that the program\n// terminates, that expressions and functions are well defined, and that all\n// specifications are satisfied. The language prevents type errors by being type\n// safe, prevents dangling pointers by not having an \"address-of\" or \"deallocate\"\n// operation (which is accommodated at run time by a garbage collector), and\n// prevents arithmetic overflow errors by using mathematical integers (which\n// is accommodated at run time by using BigNum's). By proving that programs\n// terminate, Dafny proves that a program's time usage is finite, which implies\n// that the program's space usage is finite too. However, executing the\n// program may fall short of your hopes if you don't have enough time or\n// space; that is, the program may run out of space or may fail to terminate in\n// your lifetime, because Dafny does not prove that the time or space needed by\n// the program matches your execution environment. The only input fed to\n// the Dafny verifier/compiler is the program text below; Dafny then automatically\n// verifies and compiles the program (for this program in less than 11 seconds)\n// without further human intervention.\n\nghost predicate IsDuplicate(a: array, p: int)\n reads a\n{\n IsPrefixDuplicate(a, a.Length, p)\n}\n\nghost predicate IsPrefixDuplicate(a: array, k: int, p: int)\n requires 0 <= k <= a.Length;\n reads a;\n{\n exists i,j :: 0 <= i < j < k && a[i] == a[j] == p\n}\n\nmethod Search(a: array) returns (p: int, q: int)\n requires 4 <= a.Length;\n requires exists p,q :: p != q && IsDuplicate(a, p) && IsDuplicate(a, q); // two distinct duplicates exist\n requires forall i :: 0 <= i < a.Length ==> 0 <= a[i] < a.Length - 2; // the elements of \"a\" in the range [0.. a.Length-2]\n ensures p != q && IsDuplicate(a, p) && IsDuplicate(a, q);\n{\n // allocate an array \"d\" and initialize its elements to -1.\n var d := new int[a.Length-2];\n var i := 0;\n while (i < d.Length)\n {\n d[i], i := -1, i+1;\n }\n\n i, p, q := 0, 0, 1;\n while (true)\n (d[j] == -1 && forall k :: 0 <= k < i ==> a[k] != j) ||\n (0 <= d[j] < i && a[d[j]] == j);\n {\n var k := d[a[i]];\n if (k == -1) {\n // a[i] does not exist in a[..i]\n d[a[i]] := i;\n } else {\n // we have encountered a duplicate\n if (p != q) {\n // this is the first duplicate encountered\n p, q := a[i], a[i];\n } else if (p == a[i]) {\n // this is another copy of the same duplicate we have seen before\n } else {\n // this is the second duplicate\n q := a[i];\n return;\n }\n }\n i := i + 1;\n }\n}\n\n" }, { "test_ID": "312", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_from dafny main repo_dafny2_Classics.dfy", "ground_truth": "// RUN: %testDafnyForEachResolver \"%s\" -- --warn-deprecation:false\n\n\n// A version of Turing's additive factorial program [Dr. A. Turing, \"Checking a large routine\",\n// In \"Report of a Conference of High Speed Automatic Calculating Machines\", pp. 67-69, 1949].\n\nghost function Factorial(n: nat): nat\n{\n if n == 0 then 1 else n * Factorial(n-1)\n}\n\nmethod AdditiveFactorial(n: nat) returns (u: nat)\n ensures u == Factorial(n);\n{\n u := 1;\n var r := 0;\n while (r < n)\n invariant 0 <= r <= n;\n invariant u == Factorial(r);\n {\n var v := u;\n var s := 1;\n while (s <= r)\n invariant 1 <= s <= r+1;\n invariant u == s * Factorial(r);\n {\n u := u + v;\n s := s + 1;\n }\n r := r + 1;\n }\n}\n\n// Hoare's FIND program [C.A.R. Hoare, \"Proof of a program: FIND\", CACM 14(1): 39-45, 1971].\n// The proof annotations here are not the same as in Hoare's article.\n\n// In Hoare's words:\n// This program operates on an array A[1:N], and a value of f (1 <= f <= N).\n// Its effect is to rearrange the elements of A in such a way that:\n// forall p,q (1 <= p <= f <= q <= N ==> A[p] <= A[f] <= A[q]).\n//\n// Here, we use 0-based indices, so we would say:\n// This method operates on an array A[0..N], and a value of f (0 <= f < N).\n// Its effect is to rearrange the elements of A in such a way that:\n// forall p,q :: 0 <= p <= f <= q < N ==> A[p] <= A[f] <= A[q]).\n\nmethod FIND(A: array, N: int, f: int)\n requires A.Length == N;\n requires 0 <= f < N;\n modifies A;\n ensures forall p,q :: 0 <= p <= f <= q < N ==> A[p] <= A[q];\n{\n var m, n := 0, N-1;\n while (m < n)\n invariant 0 <= m <= f <= n < N;\n invariant forall p,q :: 0 <= p < m <= q < N ==> A[p] <= A[q];\n invariant forall p,q :: 0 <= p <= n < q < N ==> A[p] <= A[q];\n {\n var r, i, j := A[f], m, n;\n while (i <= j)\n invariant m <= i && j <= n;\n invariant -1 <= j && i <= N;\n invariant i <= j ==> exists g :: i <= g < N && r <= A[g];\n invariant i <= j ==> exists g :: 0 <= g <= j && A[g] <= r;\n invariant forall p :: 0 <= p < i ==> A[p] <= r;\n invariant forall q :: j < q < N ==> r <= A[q];\n // the following two invariants capture (and follow from) the fact that the array is not modified outside the [m:n] range\n invariant forall p,q :: 0 <= p < m <= q < N ==> A[p] <= A[q];\n invariant forall p,q :: 0 <= p <= n < q < N ==> A[p] <= A[q];\n // the following invariant is used to prove progress of the outer loop\n invariant (i==m && j==n && r==A[f]) || (m i <= f);\n invariant exists g :: i <= g < N && r <= A[g];\n invariant exists g :: 0 <= g <= j && A[g] <= r;\n invariant forall p :: 0 <= p < i ==> A[p] <= r;\n decreases j - i;\n { i := i + 1; }\n\n while (r < A[j])\n invariant 0 <= j <= n && (firstIteration ==> f <= j);\n invariant exists g :: i <= g < N && r <= A[g];\n invariant exists g :: 0 <= g <= j && A[g] <= r;\n invariant forall q :: j < q < N ==> r <= A[q];\n decreases j;\n { j := j - 1; }\n\n assert A[j] <= r <= A[i];\n if (i <= j) {\n var w := A[i]; A[i] := A[j]; A[j] := w; // swap A[i] and A[j] (which may be referring to the same location)\n assert A[i] <= r <= A[j];\n i, j := i + 1, j - 1;\n }\n }\n\n if (f <= j) {\n n := j;\n } else if (i <= f) {\n m := i;\n } else {\n break; // Hoare used a goto\n }\n }\n}\n\n", "hints_removed": "// RUN: %testDafnyForEachResolver \"%s\" -- --warn-deprecation:false\n\n\n// A version of Turing's additive factorial program [Dr. A. Turing, \"Checking a large routine\",\n// In \"Report of a Conference of High Speed Automatic Calculating Machines\", pp. 67-69, 1949].\n\nghost function Factorial(n: nat): nat\n{\n if n == 0 then 1 else n * Factorial(n-1)\n}\n\nmethod AdditiveFactorial(n: nat) returns (u: nat)\n ensures u == Factorial(n);\n{\n u := 1;\n var r := 0;\n while (r < n)\n {\n var v := u;\n var s := 1;\n while (s <= r)\n {\n u := u + v;\n s := s + 1;\n }\n r := r + 1;\n }\n}\n\n// Hoare's FIND program [C.A.R. Hoare, \"Proof of a program: FIND\", CACM 14(1): 39-45, 1971].\n// The proof annotations here are not the same as in Hoare's article.\n\n// In Hoare's words:\n// This program operates on an array A[1:N], and a value of f (1 <= f <= N).\n// Its effect is to rearrange the elements of A in such a way that:\n// forall p,q (1 <= p <= f <= q <= N ==> A[p] <= A[f] <= A[q]).\n//\n// Here, we use 0-based indices, so we would say:\n// This method operates on an array A[0..N], and a value of f (0 <= f < N).\n// Its effect is to rearrange the elements of A in such a way that:\n// forall p,q :: 0 <= p <= f <= q < N ==> A[p] <= A[f] <= A[q]).\n\nmethod FIND(A: array, N: int, f: int)\n requires A.Length == N;\n requires 0 <= f < N;\n modifies A;\n ensures forall p,q :: 0 <= p <= f <= q < N ==> A[p] <= A[q];\n{\n var m, n := 0, N-1;\n while (m < n)\n {\n var r, i, j := A[f], m, n;\n while (i <= j)\n // the following two invariants capture (and follow from) the fact that the array is not modified outside the [m:n] range\n // the following invariant is used to prove progress of the outer loop\n {\n ghost var firstIteration := i==m && j==n;\n while (A[i] < r)\n { i := i + 1; }\n\n while (r < A[j])\n { j := j - 1; }\n\n if (i <= j) {\n var w := A[i]; A[i] := A[j]; A[j] := w; // swap A[i] and A[j] (which may be referring to the same location)\n i, j := i + 1, j - 1;\n }\n }\n\n if (f <= j) {\n n := j;\n } else if (i <= f) {\n m := i;\n } else {\n break; // Hoare used a goto\n }\n }\n}\n\n" }, { "test_ID": "313", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_from dafny main repo_dafny2_MajorityVote.dfy", "ground_truth": "// RUN: %testDafnyForEachResolver \"%s\"\n\n\n// Rustan Leino, June 2012.\n// This file verifies an algorithm, due to Boyer and Moore, that finds the majority choice\n// among a sequence of votes, see http://www.cs.utexas.edu/~moore/best-ideas/mjrty/.\n// Actually, this algorithm is a slight variation on theirs, but the general idea for why\n// it is correct is the same. In the Boyer and Moore algorithm, the loop counter is advanced\n// by exactly 1 each iteration, which means that there may or may not be a \"current leader\".\n// In my program below, I had instead written the loop invariant to say there is always a\n// \"current leader\", which requires the loop index sometimes to skip a value.\n//\n// This file has two versions of the algorithm. In the first version, the given sequence\n// of votes is assumed to have a (strict) majority choice, meaning that strictly more than\n// 50% of the votes are for one candidate. It is convenient to have a name for the majority\n// choice, in order to talk about it in specifications. The easiest way to do this in\n// Dafny is probably to introduce a ghost parameter with the given properties. That's what\n// the algorithm does, see parameter K. The postcondition is thus to output the value of\n// K, which is done in the non-ghost out-parameter k.\n// The proof of the algorithm requires two lemmas. These lemmas are proved automatically\n// by Dafny's induction tactic.\n//\n// In the second version of the program, the main method does not assume there is a majority\n// choice. Rather, it eseentially uses the first algorithm and then checks if what it\n// returns really is a majority choice. To do this, the specification of the first algorithm\n// needs to be changed slightly to accommodate the possibility that there is no majority\n// choice. That change in specification is also reflected in the loop invariant. Moreover,\n// the algorithm itself now needs to extra 'if' statements to see if the entire sequence\n// has been searched through. (This extra 'if' is essentially already handled by Boyer and\n// Moore's algorithm, because it increments the loop index by 1 each iteration and therefore\n// already has a special case for the case of running out of sequence elements without a\n// current leader.)\n// The calling harness, DetermineElection, somewhat existentially comes up with the majority\n// choice, if there is such a choice, and then passes in that choice as the ghost parameter K\n// to the main algorithm. Neat, huh?\n\n// Language comment:\n// The \"(==)\" that sits after some type parameters in this program says that the actual\n// type argument must support equality.\n\n// Advanced remark:\n// There is a subtle situation in the verification of DetermineElection. Suppose the type\n// parameter Candidate denotes some type whose instances depend on which object are\n// allocated. For example, if Candidate is some class type, then more candidates can come\n// into being by object allocations (using \"new\"). What does the quantification of\n// candidates \"c\" in the postcondition of DetermineElection now mean--all candidates that\n// existed in the pre-state or (the possibly larger set of) all candidates that exist in the\n// post-state? (It means the latter.) And if there does not exist a candidate in majority\n// in the pre-state, could there be a (newly created) candidate in majority in the post-state?\n// This will require some proof. The simplest argument seems to be that even if more candidates\n// are created during the course of DetermineElection, such candidates cannot possibly\n// be in majority in the sequence \"a\", since \"a\" can only contain candidates that were already\n// created in the pre-state. This property is easily specified by adding a postcondition\n// to the Count function. Alternatively, one could have added the antecedent \"c in a\" or\n// \"old(allocated(c))\" to the \"forall c\" quantification in the postcondition of DetermineElection.\n\n// About reading the proofs:\n// Dafny proves the FindWinner algorithm from the given loop invariants and the two lemmas\n// Lemma_Unique and Lemma_Split. In showing this proof to some colleagues, they found they\n// were not as quick as Dafny in constructing the proof from these ingredients. For a human\n// to understand the situation better, it helps to take smaller (and more) steps in the proof.\n// At the end of this file, Nadia Polikarpova has written two versions of FindWinner that does\n// that, using Dafny's support for calculational proofs.\n\nfunction Count(a: seq, s: int, t: int, x: T): int\n requires 0 <= s <= t <= |a|\n{\n if s == t then 0 else\n Count(a, s, t-1, x) + if a[t-1] == x then 1 else 0\n}\n\nghost predicate HasMajority(a: seq, s: int, t: int, x: T)\n requires 0 <= s <= t <= |a|\n{\n 2 * Count(a, s, t, x) > t - s\n}\n\n// Here is the first version of the algorithm, the one that assumes there is a majority choice.\n\nmethod FindWinner(a: seq, ghost K: Candidate) returns (k: Candidate)\n requires HasMajority(a, 0, |a|, K) // K has a (strict) majority of the votes\n ensures k == K // find K\n{\n k := a[0];\n var n, c, s := 1, 1, 0;\n while n < |a|\n invariant 0 <= s <= n <= |a|\n invariant 2 * Count(a, s, |a|, K) > |a| - s // K has majority among a[s..]\n invariant 2 * Count(a, s, n, k) > n - s // k has majority among a[s..n]\n invariant c == Count(a, s, n, k)\n {\n if a[n] == k {\n n, c := n + 1, c + 1;\n } else if 2 * c > n + 1 - s {\n n := n + 1;\n } else {\n n := n + 1;\n // We have 2*Count(a, s, n, k) == n-s, and thus the following lemma\n // lets us conclude 2*Count(a, s, n, K) <= n-s.\n Lemma_Unique(a, s, n, K, k);\n // We also have 2*Count(a, s, |a|, K) > |a|-s, and the following lemma\n // tells us Count(a, s, |a|, K) == Count(a, s, n, K) + Count(a, n, |a|, K),\n // and thus we can conclude 2*Count(a, n, |a|, K) > |a|-n.\n Lemma_Split(a, s, n, |a|, K);\n k, n, c, s := a[n], n + 1, 1, n;\n }\n }\n Lemma_Unique(a, s, |a|, K, k); // both k and K have a majority, so K == k\n}\n\n// ------------------------------------------------------------------------------\n\n// Here is the second version of the program, the one that also computes whether or not\n// there is a majority choice.\n\ndatatype Result = NoWinner | Winner(cand: Candidate)\n\nmethod DetermineElection(a: seq) returns (result: Result)\n ensures result.Winner? ==> 2 * Count(a, 0, |a|, result.cand) > |a|\n ensures result.NoWinner? ==> forall c :: 2 * Count(a, 0, |a|, c) <= |a|\n{\n if |a| == 0 { return NoWinner; }\n ghost var b := exists c :: 2 * Count(a, 0, |a|, c) > |a|;\n ghost var w :| b ==> 2 * Count(a, 0, |a|, w) > |a|;\n var cand := SearchForWinner(a, b, w);\n return if 2 * Count(a, 0, |a|, cand) > |a| then Winner(cand) else NoWinner;\n}\n\n// The difference between SearchForWinner for FindWinner above are the occurrences of the\n// antecedent \"hasWinner ==>\" and the two checks for no-more-votes that may result in a \"return\"\n// statement.\n\nmethod SearchForWinner(a: seq, ghost hasWinner: bool, ghost K: Candidate) returns (k: Candidate)\n requires |a| != 0\n requires hasWinner ==> 2 * Count(a, 0, |a|, K) > |a| // K has a (strict) majority of the votes\n ensures hasWinner ==> k == K // find K\n{\n k := a[0];\n var n, c, s := 1, 1, 0;\n while n < |a|\n invariant 0 <= s <= n <= |a|\n invariant hasWinner ==> 2 * Count(a, s, |a|, K) > |a| - s // K has majority among a[s..]\n invariant 2 * Count(a, s, n, k) > n - s // k has majority among a[s..n]\n invariant c == Count(a, s, n, k)\n {\n if a[n] == k {\n n, c := n + 1, c + 1;\n } else if 2 * c > n + 1 - s {\n n := n + 1;\n } else {\n n := n + 1;\n // We have 2*Count(a, s, n, k) == n-s, and thus the following lemma\n // lets us conclude 2*Count(a, s, n, K) <= n-s.\n Lemma_Unique(a, s, n, K, k);\n // We also have 2*Count(a, s, |a|, K) > |a|-s, and the following lemma\n // tells us Count(a, s, |a|, K) == Count(a, s, n, K) + Count(a, n, |a|, K),\n // and thus we can conclude 2*Count(a, n, |a|, K) > |a|-n.\n Lemma_Split(a, s, n, |a|, K);\n if |a| == n { return; }\n k, n, c, s := a[n], n + 1, 1, n;\n }\n }\n Lemma_Unique(a, s, |a|, K, k); // both k and K have a majority, so K == k\n}\n\n// ------------------------------------------------------------------------------\n\n// Here are two lemmas about Count that are used in the methods above.\n\nlemma Lemma_Split(a: seq, s: int, t: int, u: int, x: T)\n requires 0 <= s <= t <= u <= |a|\n ensures Count(a, s, t, x) + Count(a, t, u, x) == Count(a, s, u, x)\n{\n /* The postcondition of this method is proved automatically via Dafny's\n induction tactic. But if a manual proof had to be provided, it would\n look like this:\n if s != t {\n Lemma_Split(a, s, t-1, u, x);\n }\n */\n}\n\nlemma Lemma_Unique(a: seq, s: int, t: int, x: T, y: T)\n requires 0 <= s <= t <= |a|\n ensures x != y ==> Count(a, s, t, x) + Count(a, s, t, y) <= t - s\n{\n /* The postcondition of this method is proved automatically via Dafny's\n induction tactic. But if a manual proof had to be provided, it would\n look like this:\n if s != t {\n Lemma_Unique(a, s, t-1, x, y);\n }\n */\n}\n\n// ------------------------------------------------------------------------------\n\n// This version uses more calculations with integer formulas\nmethod FindWinner'(a: seq, ghost K: Candidate) returns (k: Candidate)\n requires HasMajority(a, 0, |a|, K) // K has a (strict) majority of the votes\n ensures k == K // find K\n{\n k := a[0]; // Current candidate: the first element\n var lo, up, c := 0, 1, 1; // Window: [0..1], number of occurrences of k in the window: 1\n while up < |a|\n invariant 0 <= lo < up <= |a| // (0)\n invariant HasMajority(a, lo, |a|, K) // (1) K has majority among a[lo..]\n invariant HasMajority(a, lo, up, k) // (2) k has majority among a[lo..up] (in the current window)\n invariant c == Count(a, lo, up, k) // (3)\n {\n if a[up] == k {\n // One more occurrence of k\n up, c := up + 1, c + 1;\n } else if 2 * c > up + 1 - lo {\n // An occurrence of another value, but k still has the majority\n up := up + 1;\n } else {\n // An occurrence of another value and k just lost the majority.\n // Prove that k has exactly 50% in the future window a[lo..up + 1]:\n calc /* k has 50% among a[lo..up + 1] */ {\n true;\n == // negation of the previous branch condition;\n 2 * c <= up + 1 - lo;\n == // loop invariant (3)\n 2 * Count(a, lo, up, k) <= up + 1 - lo;\n == calc {\n true;\n == // loop invariant (2)\n HasMajority(a, lo, up, k);\n == // def. HasMajority\n 2 * Count(a, lo, up, k) > up - lo;\n ==\n 2 * Count(a, lo, up, k) >= up + 1 - lo;\n }\n 2 * Count(a, lo, up, k) == up + 1 - lo;\n }\n up := up + 1;\n assert 2 * Count(a, lo, up, k) == up - lo; // k has exactly 50% in the current window a[lo..up]\n\n // We are going to start a new window a[up..up + 1] and choose a new candidate,\n // so invariants (2) and (3) will be easy to re-establish.\n // To re-establish (1) we have to prove that K has majority among a[up..], as up will become the new lo.\n // The main idea is that we had enough K's in a[lo..], and there cannot be too many in a[lo..up].\n calc /* K has majority among a[up..] */ {\n 2 * Count(a, up, |a|, K);\n == { Lemma_Split(a, lo, up, |a|, K); }\n 2 * Count(a, lo, |a|, K) - 2 * Count(a, lo, up, K);\n > { assert HasMajority(a, lo, |a|, K); } // loop invariant (1)\n |a| - lo - 2 * Count(a, lo, up, K);\n >= { if k == K {\n calc {\n 2 * Count(a, lo, up, K);\n ==\n 2 * Count(a, lo, up, k);\n == { assert 2 * Count(a, lo, up, k) == up - lo; } // k has 50% among a[lo..up]\n up - lo;\n }\n } else {\n calc {\n 2 * Count(a, lo, up, K);\n <= { Lemma_Unique(a, lo, up, k, K); }\n 2 * ((up - lo) - Count(a, lo, up, k));\n == { assert 2 * Count(a, lo, up, k) == up - lo; } // k has 50% among a[lo..up]\n up - lo;\n }\n }\n assert 2 * Count(a, lo, up, K) <= up - lo;\n }\n |a| - lo - (up - lo);\n ==\n |a| - up;\n }\n assert HasMajority(a, up, |a|, K);\n\n k, lo, up, c := a[up], up, up + 1, 1;\n assert HasMajority(a, lo, |a|, K);\n }\n }\n Lemma_Unique(a, lo, |a|, K, k); // both k and K have a majority among a[lo..], so K == k\n}\n\n// This version uses more calculations with boolean formulas\nmethod FindWinner''(a: seq, ghost K: Candidate) returns (k: Candidate)\n requires HasMajority(a, 0, |a|, K) // K has a (strict) majority of the votes\n ensures k == K // find K\n{\n k := a[0]; // Current candidate: the first element\n var lo, up, c := 0, 1, 1; // Window: [0..1], number of occurrences of k in the window: 1\n while up < |a|\n invariant 0 <= lo < up <= |a| // (0)\n invariant HasMajority(a, lo, |a|, K) // (1) K has majority among a[lo..]\n invariant HasMajority(a, lo, up, k) // (2) k has majority among a[lo..up] (in the current window)\n invariant c == Count(a, lo, up, k) // (3)\n {\n if a[up] == k {\n // One more occurrence of k\n up, c := up + 1, c + 1;\n } else if 2 * c > up + 1 - lo {\n // An occurrence of another value, but k still has the majority\n up := up + 1;\n } else {\n // An occurrence of another value and k just lost the majority.\n // Prove that k has exactly 50% in the future window a[lo..up + 1]:\n calc /* k has 50% among a[lo..up + 1] */ {\n true;\n == // negation of the previous branch condition\n 2 * c <= up + 1 - lo;\n == // loop invariant (3)\n 2 * Count(a, lo, up, k) <= up + 1 - lo;\n == calc {\n true;\n == // loop invariant (2)\n HasMajority(a, lo, up, k);\n == // def. HasMajority\n 2 * Count(a, lo, up, k) > up - lo;\n ==\n 2 * Count(a, lo, up, k) >= up + 1 - lo;\n }\n 2 * Count(a, lo, up, k) == up + 1 - lo;\n }\n up := up + 1;\n assert 2 * Count(a, lo, up, k) == up - lo; // k has exactly 50% in the current window a[lo..up]\n\n // We are going to start a new window a[up..up + 1] and choose a new candidate,\n // so invariants (2) and (3) will be easy to re-establish.\n // To re-establish (1) we have to prove that K has majority among a[up..], as up will become the new lo.\n // The main idea is that we had enough K's in a[lo..], and there cannot be too many in a[lo..up].\n calc /* K has majority among a[up..] */ {\n true;\n == // loop invariant (1)\n HasMajority(a, lo, |a|, K);\n ==\n 2 * Count(a, lo, |a|, K) > |a| - lo;\n == { Lemma_Split(a, lo, up, |a|, K); }\n 2 * Count(a, lo, up, K) + 2 * Count(a, up, |a|, K) > |a| - lo;\n ==>\n { if k == K {\n calc {\n 2 * Count(a, lo, up, K);\n ==\n 2 * Count(a, lo, up, k);\n == { assert 2 * Count(a, lo, up, k) == up - lo; } // k has 50% among a[lo..up]\n up - lo;\n }\n } else {\n calc {\n true;\n == { Lemma_Unique(a, lo, up, k, K); }\n Count(a, lo, up, K) + Count(a, lo, up, k) <= up - lo;\n ==\n 2 * Count(a, lo, up, K) + 2 * Count(a, lo, up, k) <= 2 * (up - lo);\n == { assert 2 * Count(a, lo, up, k) == up - lo; } // k has 50% among a[lo..up]\n 2 * Count(a, lo, up, K) <= up - lo;\n }\n }\n assert 2 * Count(a, lo, up, K) <= up - lo;\n }\n // subtract off Count(a, lo, up, K) from the LHS and subtract off the larger amount up - lo from the RHS\n 2 * Count(a, up, |a|, K) > (|a| - lo) - (up - lo);\n ==\n 2 * Count(a, up, |a|, K) > |a| - up;\n ==\n HasMajority(a, up, |a|, K);\n }\n k, lo, up, c := a[up], up, up + 1, 1;\n assert HasMajority(a, lo, |a|, K);\n }\n }\n Lemma_Unique(a, lo, |a|, K, k); // both k and K have a majority among a[lo..], so K == k\n}\n\n", "hints_removed": "// RUN: %testDafnyForEachResolver \"%s\"\n\n\n// Rustan Leino, June 2012.\n// This file verifies an algorithm, due to Boyer and Moore, that finds the majority choice\n// among a sequence of votes, see http://www.cs.utexas.edu/~moore/best-ideas/mjrty/.\n// Actually, this algorithm is a slight variation on theirs, but the general idea for why\n// it is correct is the same. In the Boyer and Moore algorithm, the loop counter is advanced\n// by exactly 1 each iteration, which means that there may or may not be a \"current leader\".\n// In my program below, I had instead written the loop invariant to say there is always a\n// \"current leader\", which requires the loop index sometimes to skip a value.\n//\n// This file has two versions of the algorithm. In the first version, the given sequence\n// of votes is assumed to have a (strict) majority choice, meaning that strictly more than\n// 50% of the votes are for one candidate. It is convenient to have a name for the majority\n// choice, in order to talk about it in specifications. The easiest way to do this in\n// Dafny is probably to introduce a ghost parameter with the given properties. That's what\n// the algorithm does, see parameter K. The postcondition is thus to output the value of\n// K, which is done in the non-ghost out-parameter k.\n// The proof of the algorithm requires two lemmas. These lemmas are proved automatically\n// by Dafny's induction tactic.\n//\n// In the second version of the program, the main method does not assume there is a majority\n// choice. Rather, it eseentially uses the first algorithm and then checks if what it\n// returns really is a majority choice. To do this, the specification of the first algorithm\n// needs to be changed slightly to accommodate the possibility that there is no majority\n// choice. That change in specification is also reflected in the loop invariant. Moreover,\n// the algorithm itself now needs to extra 'if' statements to see if the entire sequence\n// has been searched through. (This extra 'if' is essentially already handled by Boyer and\n// Moore's algorithm, because it increments the loop index by 1 each iteration and therefore\n// already has a special case for the case of running out of sequence elements without a\n// current leader.)\n// The calling harness, DetermineElection, somewhat existentially comes up with the majority\n// choice, if there is such a choice, and then passes in that choice as the ghost parameter K\n// to the main algorithm. Neat, huh?\n\n// Language comment:\n// The \"(==)\" that sits after some type parameters in this program says that the actual\n// type argument must support equality.\n\n// Advanced remark:\n// There is a subtle situation in the verification of DetermineElection. Suppose the type\n// parameter Candidate denotes some type whose instances depend on which object are\n// allocated. For example, if Candidate is some class type, then more candidates can come\n// into being by object allocations (using \"new\"). What does the quantification of\n// candidates \"c\" in the postcondition of DetermineElection now mean--all candidates that\n// existed in the pre-state or (the possibly larger set of) all candidates that exist in the\n// post-state? (It means the latter.) And if there does not exist a candidate in majority\n// in the pre-state, could there be a (newly created) candidate in majority in the post-state?\n// This will require some proof. The simplest argument seems to be that even if more candidates\n// are created during the course of DetermineElection, such candidates cannot possibly\n// be in majority in the sequence \"a\", since \"a\" can only contain candidates that were already\n// created in the pre-state. This property is easily specified by adding a postcondition\n// to the Count function. Alternatively, one could have added the antecedent \"c in a\" or\n// \"old(allocated(c))\" to the \"forall c\" quantification in the postcondition of DetermineElection.\n\n// About reading the proofs:\n// Dafny proves the FindWinner algorithm from the given loop invariants and the two lemmas\n// Lemma_Unique and Lemma_Split. In showing this proof to some colleagues, they found they\n// were not as quick as Dafny in constructing the proof from these ingredients. For a human\n// to understand the situation better, it helps to take smaller (and more) steps in the proof.\n// At the end of this file, Nadia Polikarpova has written two versions of FindWinner that does\n// that, using Dafny's support for calculational proofs.\n\nfunction Count(a: seq, s: int, t: int, x: T): int\n requires 0 <= s <= t <= |a|\n{\n if s == t then 0 else\n Count(a, s, t-1, x) + if a[t-1] == x then 1 else 0\n}\n\nghost predicate HasMajority(a: seq, s: int, t: int, x: T)\n requires 0 <= s <= t <= |a|\n{\n 2 * Count(a, s, t, x) > t - s\n}\n\n// Here is the first version of the algorithm, the one that assumes there is a majority choice.\n\nmethod FindWinner(a: seq, ghost K: Candidate) returns (k: Candidate)\n requires HasMajority(a, 0, |a|, K) // K has a (strict) majority of the votes\n ensures k == K // find K\n{\n k := a[0];\n var n, c, s := 1, 1, 0;\n while n < |a|\n {\n if a[n] == k {\n n, c := n + 1, c + 1;\n } else if 2 * c > n + 1 - s {\n n := n + 1;\n } else {\n n := n + 1;\n // We have 2*Count(a, s, n, k) == n-s, and thus the following lemma\n // lets us conclude 2*Count(a, s, n, K) <= n-s.\n Lemma_Unique(a, s, n, K, k);\n // We also have 2*Count(a, s, |a|, K) > |a|-s, and the following lemma\n // tells us Count(a, s, |a|, K) == Count(a, s, n, K) + Count(a, n, |a|, K),\n // and thus we can conclude 2*Count(a, n, |a|, K) > |a|-n.\n Lemma_Split(a, s, n, |a|, K);\n k, n, c, s := a[n], n + 1, 1, n;\n }\n }\n Lemma_Unique(a, s, |a|, K, k); // both k and K have a majority, so K == k\n}\n\n// ------------------------------------------------------------------------------\n\n// Here is the second version of the program, the one that also computes whether or not\n// there is a majority choice.\n\ndatatype Result = NoWinner | Winner(cand: Candidate)\n\nmethod DetermineElection(a: seq) returns (result: Result)\n ensures result.Winner? ==> 2 * Count(a, 0, |a|, result.cand) > |a|\n ensures result.NoWinner? ==> forall c :: 2 * Count(a, 0, |a|, c) <= |a|\n{\n if |a| == 0 { return NoWinner; }\n ghost var b := exists c :: 2 * Count(a, 0, |a|, c) > |a|;\n ghost var w :| b ==> 2 * Count(a, 0, |a|, w) > |a|;\n var cand := SearchForWinner(a, b, w);\n return if 2 * Count(a, 0, |a|, cand) > |a| then Winner(cand) else NoWinner;\n}\n\n// The difference between SearchForWinner for FindWinner above are the occurrences of the\n// antecedent \"hasWinner ==>\" and the two checks for no-more-votes that may result in a \"return\"\n// statement.\n\nmethod SearchForWinner(a: seq, ghost hasWinner: bool, ghost K: Candidate) returns (k: Candidate)\n requires |a| != 0\n requires hasWinner ==> 2 * Count(a, 0, |a|, K) > |a| // K has a (strict) majority of the votes\n ensures hasWinner ==> k == K // find K\n{\n k := a[0];\n var n, c, s := 1, 1, 0;\n while n < |a|\n {\n if a[n] == k {\n n, c := n + 1, c + 1;\n } else if 2 * c > n + 1 - s {\n n := n + 1;\n } else {\n n := n + 1;\n // We have 2*Count(a, s, n, k) == n-s, and thus the following lemma\n // lets us conclude 2*Count(a, s, n, K) <= n-s.\n Lemma_Unique(a, s, n, K, k);\n // We also have 2*Count(a, s, |a|, K) > |a|-s, and the following lemma\n // tells us Count(a, s, |a|, K) == Count(a, s, n, K) + Count(a, n, |a|, K),\n // and thus we can conclude 2*Count(a, n, |a|, K) > |a|-n.\n Lemma_Split(a, s, n, |a|, K);\n if |a| == n { return; }\n k, n, c, s := a[n], n + 1, 1, n;\n }\n }\n Lemma_Unique(a, s, |a|, K, k); // both k and K have a majority, so K == k\n}\n\n// ------------------------------------------------------------------------------\n\n// Here are two lemmas about Count that are used in the methods above.\n\nlemma Lemma_Split(a: seq, s: int, t: int, u: int, x: T)\n requires 0 <= s <= t <= u <= |a|\n ensures Count(a, s, t, x) + Count(a, t, u, x) == Count(a, s, u, x)\n{\n /* The postcondition of this method is proved automatically via Dafny's\n induction tactic. But if a manual proof had to be provided, it would\n look like this:\n if s != t {\n Lemma_Split(a, s, t-1, u, x);\n }\n */\n}\n\nlemma Lemma_Unique(a: seq, s: int, t: int, x: T, y: T)\n requires 0 <= s <= t <= |a|\n ensures x != y ==> Count(a, s, t, x) + Count(a, s, t, y) <= t - s\n{\n /* The postcondition of this method is proved automatically via Dafny's\n induction tactic. But if a manual proof had to be provided, it would\n look like this:\n if s != t {\n Lemma_Unique(a, s, t-1, x, y);\n }\n */\n}\n\n// ------------------------------------------------------------------------------\n\n// This version uses more calculations with integer formulas\nmethod FindWinner'(a: seq, ghost K: Candidate) returns (k: Candidate)\n requires HasMajority(a, 0, |a|, K) // K has a (strict) majority of the votes\n ensures k == K // find K\n{\n k := a[0]; // Current candidate: the first element\n var lo, up, c := 0, 1, 1; // Window: [0..1], number of occurrences of k in the window: 1\n while up < |a|\n {\n if a[up] == k {\n // One more occurrence of k\n up, c := up + 1, c + 1;\n } else if 2 * c > up + 1 - lo {\n // An occurrence of another value, but k still has the majority\n up := up + 1;\n } else {\n // An occurrence of another value and k just lost the majority.\n // Prove that k has exactly 50% in the future window a[lo..up + 1]:\n calc /* k has 50% among a[lo..up + 1] */ {\n true;\n == // negation of the previous branch condition;\n 2 * c <= up + 1 - lo;\n == // loop invariant (3)\n 2 * Count(a, lo, up, k) <= up + 1 - lo;\n == calc {\n true;\n == // loop invariant (2)\n HasMajority(a, lo, up, k);\n == // def. HasMajority\n 2 * Count(a, lo, up, k) > up - lo;\n ==\n 2 * Count(a, lo, up, k) >= up + 1 - lo;\n }\n 2 * Count(a, lo, up, k) == up + 1 - lo;\n }\n up := up + 1;\n\n // We are going to start a new window a[up..up + 1] and choose a new candidate,\n // so invariants (2) and (3) will be easy to re-establish.\n // To re-establish (1) we have to prove that K has majority among a[up..], as up will become the new lo.\n // The main idea is that we had enough K's in a[lo..], and there cannot be too many in a[lo..up].\n calc /* K has majority among a[up..] */ {\n 2 * Count(a, up, |a|, K);\n == { Lemma_Split(a, lo, up, |a|, K); }\n 2 * Count(a, lo, |a|, K) - 2 * Count(a, lo, up, K);\n > { assert HasMajority(a, lo, |a|, K); } // loop invariant (1)\n |a| - lo - 2 * Count(a, lo, up, K);\n >= { if k == K {\n calc {\n 2 * Count(a, lo, up, K);\n ==\n 2 * Count(a, lo, up, k);\n == { assert 2 * Count(a, lo, up, k) == up - lo; } // k has 50% among a[lo..up]\n up - lo;\n }\n } else {\n calc {\n 2 * Count(a, lo, up, K);\n <= { Lemma_Unique(a, lo, up, k, K); }\n 2 * ((up - lo) - Count(a, lo, up, k));\n == { assert 2 * Count(a, lo, up, k) == up - lo; } // k has 50% among a[lo..up]\n up - lo;\n }\n }\n }\n |a| - lo - (up - lo);\n ==\n |a| - up;\n }\n\n k, lo, up, c := a[up], up, up + 1, 1;\n }\n }\n Lemma_Unique(a, lo, |a|, K, k); // both k and K have a majority among a[lo..], so K == k\n}\n\n// This version uses more calculations with boolean formulas\nmethod FindWinner''(a: seq, ghost K: Candidate) returns (k: Candidate)\n requires HasMajority(a, 0, |a|, K) // K has a (strict) majority of the votes\n ensures k == K // find K\n{\n k := a[0]; // Current candidate: the first element\n var lo, up, c := 0, 1, 1; // Window: [0..1], number of occurrences of k in the window: 1\n while up < |a|\n {\n if a[up] == k {\n // One more occurrence of k\n up, c := up + 1, c + 1;\n } else if 2 * c > up + 1 - lo {\n // An occurrence of another value, but k still has the majority\n up := up + 1;\n } else {\n // An occurrence of another value and k just lost the majority.\n // Prove that k has exactly 50% in the future window a[lo..up + 1]:\n calc /* k has 50% among a[lo..up + 1] */ {\n true;\n == // negation of the previous branch condition\n 2 * c <= up + 1 - lo;\n == // loop invariant (3)\n 2 * Count(a, lo, up, k) <= up + 1 - lo;\n == calc {\n true;\n == // loop invariant (2)\n HasMajority(a, lo, up, k);\n == // def. HasMajority\n 2 * Count(a, lo, up, k) > up - lo;\n ==\n 2 * Count(a, lo, up, k) >= up + 1 - lo;\n }\n 2 * Count(a, lo, up, k) == up + 1 - lo;\n }\n up := up + 1;\n\n // We are going to start a new window a[up..up + 1] and choose a new candidate,\n // so invariants (2) and (3) will be easy to re-establish.\n // To re-establish (1) we have to prove that K has majority among a[up..], as up will become the new lo.\n // The main idea is that we had enough K's in a[lo..], and there cannot be too many in a[lo..up].\n calc /* K has majority among a[up..] */ {\n true;\n == // loop invariant (1)\n HasMajority(a, lo, |a|, K);\n ==\n 2 * Count(a, lo, |a|, K) > |a| - lo;\n == { Lemma_Split(a, lo, up, |a|, K); }\n 2 * Count(a, lo, up, K) + 2 * Count(a, up, |a|, K) > |a| - lo;\n ==>\n { if k == K {\n calc {\n 2 * Count(a, lo, up, K);\n ==\n 2 * Count(a, lo, up, k);\n == { assert 2 * Count(a, lo, up, k) == up - lo; } // k has 50% among a[lo..up]\n up - lo;\n }\n } else {\n calc {\n true;\n == { Lemma_Unique(a, lo, up, k, K); }\n Count(a, lo, up, K) + Count(a, lo, up, k) <= up - lo;\n ==\n 2 * Count(a, lo, up, K) + 2 * Count(a, lo, up, k) <= 2 * (up - lo);\n == { assert 2 * Count(a, lo, up, k) == up - lo; } // k has 50% among a[lo..up]\n 2 * Count(a, lo, up, K) <= up - lo;\n }\n }\n }\n // subtract off Count(a, lo, up, K) from the LHS and subtract off the larger amount up - lo from the RHS\n 2 * Count(a, up, |a|, K) > (|a| - lo) - (up - lo);\n ==\n 2 * Count(a, up, |a|, K) > |a| - up;\n ==\n HasMajority(a, up, |a|, K);\n }\n k, lo, up, c := a[up], up, up + 1, 1;\n }\n }\n Lemma_Unique(a, lo, |a|, K, k); // both k and K have a majority among a[lo..], so K == k\n}\n\n" }, { "test_ID": "314", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_from dafny main repo_dafny2_StoreAndRetrieve.dfy", "ground_truth": "// RUN: %testDafnyForEachCompiler --refresh-exit-code=0 \"%s\" -- --relax-definite-assignment\n\n// This file shows an example program that uses both refinement and :autocontracts\n// specify a class that stores a set of things that can be retrieved using a query.\n//\n// (For another example that uses these features, see Test/dafny3/CachedContainer.dfy.)\n\nabstract module AbstractInterface {\n class {:autocontracts} StoreAndRetrieve {\n ghost var Contents: set\n ghost predicate Valid() {\n Valid'()\n }\n ghost predicate {:autocontracts false} Valid'()\n reads this, Repr\n constructor Init()\n ensures Contents == {}\n method Store(t: Thing)\n ensures Contents == old(Contents) + {t}\n method Retrieve(matchCriterion: Thing -> bool) returns (thing: Thing)\n requires exists t :: t in Contents && matchCriterion(t)\n ensures Contents == old(Contents)\n ensures thing in Contents && matchCriterion(thing)\n }\n}\n\nabstract module A refines AbstractInterface {\n class StoreAndRetrieve ... {\n constructor Init...\n {\n Contents := {};\n Repr := {this};\n new;\n assume Valid'(); // to be checked in module B\n }\n method Store...\n {\n Contents := Contents + {t};\n assume Valid'(); // to be checked in module B\n }\n method Retrieve...\n {\n var k :| assume k in Contents && matchCriterion(k);\n thing := k;\n }\n }\n}\n\nabstract module B refines A {\n class StoreAndRetrieve ... {\n var arr: seq\n ghost predicate Valid'...\n {\n Contents == set x | x in arr\n }\n constructor Init...\n {\n arr := [];\n new;\n assert ...;\n }\n method Store...\n {\n arr := arr + [t];\n ...;\n assert ...;\n }\n method Retrieve...\n {\n var i := 0;\n while (i < |arr|)\n invariant i < |arr|\n invariant forall j :: 0 <= j < i ==> !matchCriterion(arr[j])\n {\n if matchCriterion(arr[i]) {\n break;\n }\n i := i + 1;\n }\n var k := arr[i];\n ...;\n var a: seq :| assume Contents == set x | x in a;\n arr := a;\n }\n }\n}\n\nmodule abC refines B { // TODO module C causes Go to fail\n class StoreAndRetrieve ... {\n method Retrieve...\n {\n ...;\n var a := [thing] + arr[..i] + arr[i+1..]; // LRU behavior\n }\n }\n}\n\nabstract module AbstractClient {\n import S : AbstractInterface\n\n method Test() {\n var s := new S.StoreAndRetrieve.Init();\n s.Store(20.3);\n var fn := r => true;\n var r := s.Retrieve(fn);\n print r, \"\\n\"; // 20.3\n }\n}\n\nmodule Client refines AbstractClient {\n import S = abC\n method Main() {\n Test();\n }\n}\n\n", "hints_removed": "// RUN: %testDafnyForEachCompiler --refresh-exit-code=0 \"%s\" -- --relax-definite-assignment\n\n// This file shows an example program that uses both refinement and :autocontracts\n// specify a class that stores a set of things that can be retrieved using a query.\n//\n// (For another example that uses these features, see Test/dafny3/CachedContainer.dfy.)\n\nabstract module AbstractInterface {\n class {:autocontracts} StoreAndRetrieve {\n ghost var Contents: set\n ghost predicate Valid() {\n Valid'()\n }\n ghost predicate {:autocontracts false} Valid'()\n reads this, Repr\n constructor Init()\n ensures Contents == {}\n method Store(t: Thing)\n ensures Contents == old(Contents) + {t}\n method Retrieve(matchCriterion: Thing -> bool) returns (thing: Thing)\n requires exists t :: t in Contents && matchCriterion(t)\n ensures Contents == old(Contents)\n ensures thing in Contents && matchCriterion(thing)\n }\n}\n\nabstract module A refines AbstractInterface {\n class StoreAndRetrieve ... {\n constructor Init...\n {\n Contents := {};\n Repr := {this};\n new;\n assume Valid'(); // to be checked in module B\n }\n method Store...\n {\n Contents := Contents + {t};\n assume Valid'(); // to be checked in module B\n }\n method Retrieve...\n {\n var k :| assume k in Contents && matchCriterion(k);\n thing := k;\n }\n }\n}\n\nabstract module B refines A {\n class StoreAndRetrieve ... {\n var arr: seq\n ghost predicate Valid'...\n {\n Contents == set x | x in arr\n }\n constructor Init...\n {\n arr := [];\n new;\n }\n method Store...\n {\n arr := arr + [t];\n ...;\n }\n method Retrieve...\n {\n var i := 0;\n while (i < |arr|)\n {\n if matchCriterion(arr[i]) {\n break;\n }\n i := i + 1;\n }\n var k := arr[i];\n ...;\n var a: seq :| assume Contents == set x | x in a;\n arr := a;\n }\n }\n}\n\nmodule abC refines B { // TODO module C causes Go to fail\n class StoreAndRetrieve ... {\n method Retrieve...\n {\n ...;\n var a := [thing] + arr[..i] + arr[i+1..]; // LRU behavior\n }\n }\n}\n\nabstract module AbstractClient {\n import S : AbstractInterface\n\n method Test() {\n var s := new S.StoreAndRetrieve.Init();\n s.Store(20.3);\n var fn := r => true;\n var r := s.Retrieve(fn);\n print r, \"\\n\"; // 20.3\n }\n}\n\nmodule Client refines AbstractClient {\n import S = abC\n method Main() {\n Test();\n }\n}\n\n" }, { "test_ID": "315", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_from dafny main repo_dafny3_CachedContainer.dfy", "ground_truth": "// RUN: %testDafnyForEachCompiler --refresh-exit-code=0 \"%s\" -- --relax-definite-assignment\n\n// This file contains an example chain of module refinements, starting from a\n// simple interface M0 to an implementation M3. Module Client.Test() is\n// verified against the original M0 module. Module CachedClient instantiates\n// the abstract import of M0 with the concrete module M3, and then gets to\n// reuse the proof done in Client.\n//\n// At a sufficiently abstract level, the concepts used are all standard.\n// However, it can be tricky to set these things up in Dafny, if you want\n// the final program to be a composition of smaller refinement steps.\n//\n// Textually, refinement modules in Dafny are written with \"...\", rather\n// than by repeating the program text from the module being refined.\n// This can be difficult to both author and read, so this file can be\n// used as a guide for what to aim for. Undoubtedly, use of the /rprint:-\n// option on the command line will be useful, since it lets you see what\n// all the ...'s expand to.\n//\n// As a convenience, this program also uses a second experimental feature,\n// namely the preprocessing requested by :autocontracts, which supplies\n// much of the boilerplate specifications that one uses with the\n// dynamic-frames idiom in Dafny. This feature was designed to reduce clutter\n// in the program text, but can increase the mystery behind what's really\n// going on. Here, too, using the /rprint:- option will be useful, since\n// it shows the automatically generated specifications and code.\n//\n// (For another example that uses these features, see Test/dafny2/StoreAndRetrieve.dfy.)\n\n\n// give the method signatures and specs\nabstract module M0 {\n class {:autocontracts} Container {\n ghost var Contents: set\n ghost predicate Valid() {\n Valid'()\n }\n ghost predicate {:autocontracts false} Valid'()\n reads this, Repr\n constructor ()\n ensures Contents == {}\n method Add(t: T)\n ensures Contents == old(Contents) + {t}\n method Remove(t: T)\n ensures Contents == old(Contents) - {t}\n method Contains(t: T) returns (b: bool)\n ensures Contents == old(Contents)\n ensures b <==> t in Contents\n }\n}\n\n// provide bodies for the methods\nabstract module M1 refines M0 {\n class Container ... {\n constructor... {\n Contents := {};\n Repr := {this};\n new;\n label CheckPost:\n assume Valid'(); // to be checked in further refinements\n }\n method Add... {\n Contents := Contents + {t};\n label CheckPost:\n assume Valid'(); // to be checked in further refinements\n }\n method Remove... {\n Contents := Contents - {t};\n label CheckPost:\n assume Valid'(); // to be checked in further refinements\n }\n method Contains... {\n // b := t in Contents;\n b :| assume b <==> t in Contents;\n }\n }\n}\n\n// implement the set in terms of a sequence\nabstract module M2 refines M1 {\n class Container ... {\n var elems: seq\n ghost predicate Valid'...\n {\n Contents == (set x | x in elems) &&\n (forall i,j :: 0 <= i < j < |elems| ==> elems[i] != elems[j]) &&\n Valid''()\n }\n ghost predicate {:autocontracts false} Valid''()\n reads this, Repr\n method FindIndex(t: T) returns (j: nat)\n ensures j <= |elems|\n ensures if j < |elems| then elems[j] == t else t !in elems\n {\n j := 0;\n while (j < |elems|)\n invariant j <= |elems|\n invariant forall i :: 0 <= i < j ==> elems[i] != t\n {\n if (elems[j] == t) {\n return;\n }\n j := j + 1;\n }\n }\n\n constructor... {\n elems := [];\n new;\n label CheckPost:\n assume Valid''(); // to be checked in further refinements\n assert ...;\n }\n method Add... {\n var j := FindIndex(t);\n if j == |elems| {\n elems := elems + [t];\n }\n ...;\n label CheckPost:\n assume Valid''(); // to be checked in further refinements\n assert ...;\n }\n method Remove... {\n var j := FindIndex(t);\n if j < |elems| {\n elems := elems[..j] + elems[j+1..];\n }\n ...;\n label CheckPost:\n assume Valid''(); // to be checked in further refinements\n assert ...;\n }\n method Contains... {\n var j := FindIndex(t);\n b := j < |elems|;\n }\n }\n}\n\n// implement a cache\n\nmodule M3 refines M2 {\n datatype Cache = None | Some(index: nat, value: T)\n class Container ... {\n var cache: Cache\n ghost predicate Valid''... {\n cache.Some? ==> cache.index < |elems| && elems[cache.index] == cache.value\n }\n constructor... {\n cache := None;\n new;\n ...;\n assert ...;\n }\n method FindIndex... {\n if cache.Some? && cache.value == t {\n return cache.index;\n }\n }\n method Add... {\n ...;\n assert ...;\n }\n method Remove... {\n ...;\n if ... {\n if cache.Some? {\n if cache.index == j {\n // clear the cache\n cache := None;\n } else if j < cache.index {\n // adjust for the shifting down\n cache := cache.(index := cache.index - 1);\n }\n }\n }\n ...;\n assert ...;\n }\n }\n}\n\n// here a client of the Container\nabstract module Client {\n import M : M0\n method Test() {\n var c := new M.Container();\n c.Add(56);\n c.Add(12);\n var b := c.Contains(17);\n assert !b;\n print b, \" \"; // false (does not contain 17)\n b := c.Contains(12);\n assert b;\n print b, \" \"; // true (contains 12)\n c.Remove(12);\n b := c.Contains(12);\n assert !b;\n print b, \" \"; // false (no longer contains 12)\n assert c.Contents == {56};\n b := c.Contains(56);\n assert b;\n print b, \"\\n\"; // true (still contains 56)\n }\n}\n\nmodule CachedClient refines Client {\n import M = M3\n method Main() {\n Test();\n }\n}\n\n", "hints_removed": "// RUN: %testDafnyForEachCompiler --refresh-exit-code=0 \"%s\" -- --relax-definite-assignment\n\n// This file contains an example chain of module refinements, starting from a\n// simple interface M0 to an implementation M3. Module Client.Test() is\n// verified against the original M0 module. Module CachedClient instantiates\n// the abstract import of M0 with the concrete module M3, and then gets to\n// reuse the proof done in Client.\n//\n// At a sufficiently abstract level, the concepts used are all standard.\n// However, it can be tricky to set these things up in Dafny, if you want\n// the final program to be a composition of smaller refinement steps.\n//\n// Textually, refinement modules in Dafny are written with \"...\", rather\n// than by repeating the program text from the module being refined.\n// This can be difficult to both author and read, so this file can be\n// used as a guide for what to aim for. Undoubtedly, use of the /rprint:-\n// option on the command line will be useful, since it lets you see what\n// all the ...'s expand to.\n//\n// As a convenience, this program also uses a second experimental feature,\n// namely the preprocessing requested by :autocontracts, which supplies\n// much of the boilerplate specifications that one uses with the\n// dynamic-frames idiom in Dafny. This feature was designed to reduce clutter\n// in the program text, but can increase the mystery behind what's really\n// going on. Here, too, using the /rprint:- option will be useful, since\n// it shows the automatically generated specifications and code.\n//\n// (For another example that uses these features, see Test/dafny2/StoreAndRetrieve.dfy.)\n\n\n// give the method signatures and specs\nabstract module M0 {\n class {:autocontracts} Container {\n ghost var Contents: set\n ghost predicate Valid() {\n Valid'()\n }\n ghost predicate {:autocontracts false} Valid'()\n reads this, Repr\n constructor ()\n ensures Contents == {}\n method Add(t: T)\n ensures Contents == old(Contents) + {t}\n method Remove(t: T)\n ensures Contents == old(Contents) - {t}\n method Contains(t: T) returns (b: bool)\n ensures Contents == old(Contents)\n ensures b <==> t in Contents\n }\n}\n\n// provide bodies for the methods\nabstract module M1 refines M0 {\n class Container ... {\n constructor... {\n Contents := {};\n Repr := {this};\n new;\n label CheckPost:\n assume Valid'(); // to be checked in further refinements\n }\n method Add... {\n Contents := Contents + {t};\n label CheckPost:\n assume Valid'(); // to be checked in further refinements\n }\n method Remove... {\n Contents := Contents - {t};\n label CheckPost:\n assume Valid'(); // to be checked in further refinements\n }\n method Contains... {\n // b := t in Contents;\n b :| assume b <==> t in Contents;\n }\n }\n}\n\n// implement the set in terms of a sequence\nabstract module M2 refines M1 {\n class Container ... {\n var elems: seq\n ghost predicate Valid'...\n {\n Contents == (set x | x in elems) &&\n (forall i,j :: 0 <= i < j < |elems| ==> elems[i] != elems[j]) &&\n Valid''()\n }\n ghost predicate {:autocontracts false} Valid''()\n reads this, Repr\n method FindIndex(t: T) returns (j: nat)\n ensures j <= |elems|\n ensures if j < |elems| then elems[j] == t else t !in elems\n {\n j := 0;\n while (j < |elems|)\n {\n if (elems[j] == t) {\n return;\n }\n j := j + 1;\n }\n }\n\n constructor... {\n elems := [];\n new;\n label CheckPost:\n assume Valid''(); // to be checked in further refinements\n }\n method Add... {\n var j := FindIndex(t);\n if j == |elems| {\n elems := elems + [t];\n }\n ...;\n label CheckPost:\n assume Valid''(); // to be checked in further refinements\n }\n method Remove... {\n var j := FindIndex(t);\n if j < |elems| {\n elems := elems[..j] + elems[j+1..];\n }\n ...;\n label CheckPost:\n assume Valid''(); // to be checked in further refinements\n }\n method Contains... {\n var j := FindIndex(t);\n b := j < |elems|;\n }\n }\n}\n\n// implement a cache\n\nmodule M3 refines M2 {\n datatype Cache = None | Some(index: nat, value: T)\n class Container ... {\n var cache: Cache\n ghost predicate Valid''... {\n cache.Some? ==> cache.index < |elems| && elems[cache.index] == cache.value\n }\n constructor... {\n cache := None;\n new;\n ...;\n }\n method FindIndex... {\n if cache.Some? && cache.value == t {\n return cache.index;\n }\n }\n method Add... {\n ...;\n }\n method Remove... {\n ...;\n if ... {\n if cache.Some? {\n if cache.index == j {\n // clear the cache\n cache := None;\n } else if j < cache.index {\n // adjust for the shifting down\n cache := cache.(index := cache.index - 1);\n }\n }\n }\n ...;\n }\n }\n}\n\n// here a client of the Container\nabstract module Client {\n import M : M0\n method Test() {\n var c := new M.Container();\n c.Add(56);\n c.Add(12);\n var b := c.Contains(17);\n print b, \" \"; // false (does not contain 17)\n b := c.Contains(12);\n print b, \" \"; // true (contains 12)\n c.Remove(12);\n b := c.Contains(12);\n print b, \" \"; // false (no longer contains 12)\n b := c.Contains(56);\n print b, \"\\n\"; // true (still contains 56)\n }\n}\n\nmodule CachedClient refines Client {\n import M = M3\n method Main() {\n Test();\n }\n}\n\n" }, { "test_ID": "316", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_from dafny main repo_dafny3_CalcExample.dfy", "ground_truth": "// RUN: %testDafnyForEachResolver \"%s\"\n\n\n// Here is a function \"f\" and three axioms (that is, unproved lemmas) about \"f\":\n\nghost function f(x: int, y: int): int\n\nlemma Associativity(x: int, y: int, z: int)\n ensures f(x, f(y, z)) == f(f(x, y), z)\n\nlemma Monotonicity(y: int, z: int)\n requires y <= z\n ensures forall x :: f(x, y) <= f(x, z)\n\nlemma DiagonalIdentity(x: int)\n ensures f(x, x) == x\n\n// From these axioms, we can prove a lemma about \"f\":\n\nmethod CalculationalStyleProof(a: int, b: int, c: int, x: int)\n requires c <= x == f(a, b)\n ensures f(a, f(b, c)) <= x\n{\n calc {\n f(a, f(b, c));\n == { Associativity(a, b, c); }\n f(f(a, b), c);\n == { assert f(a, b) == x; }\n f(x, c);\n <= { assert c <= x; Monotonicity(c, x); }\n f(x, x);\n == { DiagonalIdentity(x); }\n x;\n }\n}\n\n// Here's the same lemma, but with a proof written in a different style.\n// (An explanation of the constructs in this lemma is found below.)\n\nmethod DifferentStyleProof(a: int, b: int, c: int, x: int)\n requires A: c <= x\n requires B: x == f(a, b)\n ensures f(a, f(b, c)) <= x\n{\n assert 0: f(a, f(b, c)) == f(f(a, b), c) by {\n Associativity(a, b, c);\n }\n\n assert 1: f(f(a, b), c) == f(x, c) by {\n reveal B;\n }\n\n assert 2: f(x, c) <= f(x, x) by {\n assert c <= x by { reveal A; }\n Monotonicity(c, x);\n }\n\n assert 3: f(x, x) == x by {\n DiagonalIdentity(x);\n }\n\n assert 4: f(a, f(b, c)) == f(x, c) by {\n reveal 0, 1;\n }\n\n assert 5: f(x, c) <= x by {\n reveal 2, 3;\n }\n\n assert f(a, f(b, c)) <= x by {\n reveal 4, 5;\n }\n}\n\n// To understand the lemma above, here's what you need to know (and then some):\n//\n// * An ordinary \"assert P;\" statement instructs the verifier to verify\n// the boolean condition \"P\" and then to assume \"P\" from here on (that\n// is, in the control flow that continues from here).\n//\n// * An assert with a proof is written \"assert P by { S }\" where \"S\" is\n// a list of statements (typically other assertions and lemma calls).\n// This statement instructs the verifier to do \"S\" and then prove \"P\".\n// Once this is done, the verifier assumes \"P\" from here on, but it\n// \"forgets\" anything it learnt or was able to assume on account of\n// doing \"S\". In other words, an assertion like this is like a local\n// lemma--the proof \"S\" is used only to establish \"P\" and is then\n// forgotten, and after the statement, only \"P\" remains. Note, the\n// body of the \"by\" clause does \"S\" and then stops; that is, there are\n// no control paths out of the body of the \"by\" clause.\n//\n// * An assertion (either an ordinary assertion or an assertion with a\n// proof) can start with a label, as in:\n//\n// assert L: P;\n//\n// or:\n//\n// assert L: P by { S }\n//\n// This instructs the verifier to prove the assertion as described in the\n// previous two bullets, but then to forget about \"P\". In other words, the\n// difference between a labeled assertion and and an unlabeled assertion\n// is that an unlabeled assertion ends by assuming \"P\" whereas the labeled\n// assertion does not assume anything.\n//\n// * Syntactically, the label \"L\" in a labeled assertion is the same as in\n// a statement prefix \"label L:\", namely, \"L\" is either an identifier or\n// a (decimal) numeric literal.\n//\n// * The condition \"P\" proved by a labeled assertion can later be recalled\n// using a \"reveal\" statement. The \"reveal\" statement takes a list of\n// arguments, each of which can be a label occurring in a previous\n// assertion.\n//\n// * A precondition (or think of it as an antecedent of a lemma) is given by\n// a \"requires\" clause. Ordinarily, the precondition is assumed on entry\n// to the body of a method or lemma. Like an assert statement, a precondition\n// can also be labeled. Such a precondition is not automatically assumed on\n// entry to the body, but can be recalled by a \"reveal\" statement.\n//\n// * Fine points: Some exclusions apply. For example, labeled preconditions are\n// not supported for functions and cannot be used to hide/reveal conditions\n// while checking the well-formedness of a specification. Labeled assertions are\n// not supported in expression contexts. The \"reveal\" described is the \"reveal\"\n// statement. A labeled assertion can be revealed only at those program points\n// that are dominated by the assertion, that is, in places that are reached\n// only after definitely first having reached the assertion.\n//\n// * Fine point: The label \"L\" introduced by an assertion can also be used in\n// \"old@L(E)\" expressions, where \"E\" is an expression. However, note that\n// \"old@L(E)\" differs from \"E\" only in how the heap is dereferenced. That is,\n// \"old@L\" has no effect on local variables. In contrast, a labeled assertion\n// speaks about the values of the heap and locals at the time the assertion is\n// mentioned. So, even if the heap or locals mentioned in a labeled assertion\n// change after the assertion is mentioned, recalling the assertion condition\n// with a \"reveal\" statement always recall the condition with the heap and locals\n// as they were when the assert was stated. For example, suppose \"P\" is an\n// expression that mentions a local variable \"x\". Then, the second assertion in\n//\n// assert L: P by { ... }\n// x := x + 1;\n// ...make changes to the heap...\n// reveal L;\n// assert old@L(P);\n//\n// does not necessarily hold. The first assertion uses the initial value of the\n// heap and the initial value of \"x\". Consequently, \"reveal L;\" recalls the\n// asserted condition, with that initial heap and that initial value of \"x\",\n// despite the fact that the code changes both \"x\" and the heap between the\n// assert and the reveal. The expression \"old@L(P)\" essentially rolls\n// back to the initial heap, but it uses the current value of \"x\".\n\n", "hints_removed": "// RUN: %testDafnyForEachResolver \"%s\"\n\n\n// Here is a function \"f\" and three axioms (that is, unproved lemmas) about \"f\":\n\nghost function f(x: int, y: int): int\n\nlemma Associativity(x: int, y: int, z: int)\n ensures f(x, f(y, z)) == f(f(x, y), z)\n\nlemma Monotonicity(y: int, z: int)\n requires y <= z\n ensures forall x :: f(x, y) <= f(x, z)\n\nlemma DiagonalIdentity(x: int)\n ensures f(x, x) == x\n\n// From these axioms, we can prove a lemma about \"f\":\n\nmethod CalculationalStyleProof(a: int, b: int, c: int, x: int)\n requires c <= x == f(a, b)\n ensures f(a, f(b, c)) <= x\n{\n calc {\n f(a, f(b, c));\n == { Associativity(a, b, c); }\n f(f(a, b), c);\n == { assert f(a, b) == x; }\n f(x, c);\n <= { assert c <= x; Monotonicity(c, x); }\n f(x, x);\n == { DiagonalIdentity(x); }\n x;\n }\n}\n\n// Here's the same lemma, but with a proof written in a different style.\n// (An explanation of the constructs in this lemma is found below.)\n\nmethod DifferentStyleProof(a: int, b: int, c: int, x: int)\n requires A: c <= x\n requires B: x == f(a, b)\n ensures f(a, f(b, c)) <= x\n{\n Associativity(a, b, c);\n }\n\n reveal B;\n }\n\n Monotonicity(c, x);\n }\n\n DiagonalIdentity(x);\n }\n\n reveal 0, 1;\n }\n\n reveal 2, 3;\n }\n\n reveal 4, 5;\n }\n}\n\n// To understand the lemma above, here's what you need to know (and then some):\n//\n// * An ordinary \"assert P;\" statement instructs the verifier to verify\n// the boolean condition \"P\" and then to assume \"P\" from here on (that\n// is, in the control flow that continues from here).\n//\n// * An assert with a proof is written \"assert P by { S }\" where \"S\" is\n// a list of statements (typically other assertions and lemma calls).\n// This statement instructs the verifier to do \"S\" and then prove \"P\".\n// Once this is done, the verifier assumes \"P\" from here on, but it\n// \"forgets\" anything it learnt or was able to assume on account of\n// doing \"S\". In other words, an assertion like this is like a local\n// lemma--the proof \"S\" is used only to establish \"P\" and is then\n// forgotten, and after the statement, only \"P\" remains. Note, the\n// body of the \"by\" clause does \"S\" and then stops; that is, there are\n// no control paths out of the body of the \"by\" clause.\n//\n// * An assertion (either an ordinary assertion or an assertion with a\n// proof) can start with a label, as in:\n//\n// assert L: P;\n//\n// or:\n//\n// assert L: P by { S }\n//\n// This instructs the verifier to prove the assertion as described in the\n// previous two bullets, but then to forget about \"P\". In other words, the\n// difference between a labeled assertion and and an unlabeled assertion\n// is that an unlabeled assertion ends by assuming \"P\" whereas the labeled\n// assertion does not assume anything.\n//\n// * Syntactically, the label \"L\" in a labeled assertion is the same as in\n// a statement prefix \"label L:\", namely, \"L\" is either an identifier or\n// a (decimal) numeric literal.\n//\n// * The condition \"P\" proved by a labeled assertion can later be recalled\n// using a \"reveal\" statement. The \"reveal\" statement takes a list of\n// arguments, each of which can be a label occurring in a previous\n// assertion.\n//\n// * A precondition (or think of it as an antecedent of a lemma) is given by\n// a \"requires\" clause. Ordinarily, the precondition is assumed on entry\n// to the body of a method or lemma. Like an assert statement, a precondition\n// can also be labeled. Such a precondition is not automatically assumed on\n// entry to the body, but can be recalled by a \"reveal\" statement.\n//\n// * Fine points: Some exclusions apply. For example, labeled preconditions are\n// not supported for functions and cannot be used to hide/reveal conditions\n// while checking the well-formedness of a specification. Labeled assertions are\n// not supported in expression contexts. The \"reveal\" described is the \"reveal\"\n// statement. A labeled assertion can be revealed only at those program points\n// that are dominated by the assertion, that is, in places that are reached\n// only after definitely first having reached the assertion.\n//\n// * Fine point: The label \"L\" introduced by an assertion can also be used in\n// \"old@L(E)\" expressions, where \"E\" is an expression. However, note that\n// \"old@L(E)\" differs from \"E\" only in how the heap is dereferenced. That is,\n// \"old@L\" has no effect on local variables. In contrast, a labeled assertion\n// speaks about the values of the heap and locals at the time the assertion is\n// mentioned. So, even if the heap or locals mentioned in a labeled assertion\n// change after the assertion is mentioned, recalling the assertion condition\n// with a \"reveal\" statement always recall the condition with the heap and locals\n// as they were when the assert was stated. For example, suppose \"P\" is an\n// expression that mentions a local variable \"x\". Then, the second assertion in\n//\n// assert L: P by { ... }\n// x := x + 1;\n// ...make changes to the heap...\n// reveal L;\n// assert old@L(P);\n//\n// does not necessarily hold. The first assertion uses the initial value of the\n// heap and the initial value of \"x\". Consequently, \"reveal L;\" recalls the\n// asserted condition, with that initial heap and that initial value of \"x\",\n// despite the fact that the code changes both \"x\" and the heap between the\n// assert and the reveal. The expression \"old@L(P)\" essentially rolls\n// back to the initial heap, but it uses the current value of \"x\".\n\n" }, { "test_ID": "317", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_from dafny main repo_dafny3_InfiniteTrees.dfy", "ground_truth": "// RUN: %dafny /compile:0 /deprecation:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// Here is the usual definition of possibly infinite lists, along with a function Tail(s, n), which drops\n// n heads from s, and two lemmas that prove properties of Tail.\n\ncodatatype Stream = Nil | Cons(head: T, tail: Stream)\n\nghost function Tail(s: Stream, n: nat): Stream\n{\n if n == 0 then s else\n var t := Tail(s, n-1);\n if t == Nil then t else t.tail\n}\n\nlemma Tail_Lemma0(s: Stream, n: nat)\n requires s.Cons? && Tail(s, n).Cons?;\n ensures Tail(s, n).tail == Tail(s.tail, n);\n{\n}\nlemma Tail_Lemma1(s: Stream, k: nat, n: nat)\n requires k <= n;\n ensures Tail(s, n).Cons? ==> Tail(s, k).Cons?;\n // Note, the contrapositive of this lemma says: Tail(s, k) == Nil ==> Tail(s, n) == Nil\n{\n if k < n && Tail(s, n).Cons? {\n assert Tail(s, n) == Tail(s, n-1).tail;\n }\n}\nlemma Tail_Lemma2(s: Stream, n: nat)\n requires s.Cons? && Tail(s.tail, n).Cons?;\n ensures Tail(s, n).Cons?;\n{\n if n != 0 {\n Tail_Lemma0(s, n-1);\n }\n}\n\n// Co-predicate IsNeverEndingStream(s) answers whether or not s ever contains Nil.\n\ngreatest predicate IsNeverEndingStream(s: Stream)\n{\n match s\n case Nil => false\n case Cons(_, tail) => IsNeverEndingStream(tail)\n}\n\n// Here is an example of an infinite stream.\n\nghost function AnInfiniteStream(): Stream\n{\n Cons(0, AnInfiniteStream())\n}\ngreatest lemma Proposition0()\n ensures IsNeverEndingStream(AnInfiniteStream());\n{\n}\n\n// Now, consider a Tree definition, where each node can have a possibly infinite number of children.\n\ndatatype Tree = Node(children: Stream)\n\n// Such a tree might have not just infinite width but also infinite height. The following predicate\n// holds if there is, for every path down from the root, a common bound on the height of each such path.\n// Note that the definition needs a co-predicate in order to say something about all of a node's children.\n\nghost predicate HasBoundedHeight(t: Tree)\n{\n exists n :: 0 <= n && LowerThan(t.children, n)\n}\ngreatest predicate LowerThan(s: Stream, n: nat)\n{\n match s\n case Nil => true\n case Cons(t, tail) =>\n 1 <= n && LowerThan(t.children, n-1) && LowerThan(tail, n)\n}\n\n// Co-predicate LowerThan(s, n) recurses on LowerThan(s.tail, n). Thus, a property of LowerThan is that\n// LowerThan(s, h) implies LowerThan(s', h) for any suffix s' of s.\n\nlemma LowerThan_Lemma(s: Stream, n: nat, h: nat)\n ensures LowerThan(s, h) ==> LowerThan(Tail(s, n), h);\n{\n Tail_Lemma1(s, 0, n);\n if n == 0 || Tail(s, n) == Nil {\n } else {\n match s {\n case Cons(t, tail) =>\n LowerThan_Lemma(tail, n-1, h);\n Tail_Lemma0(s, n-1);\n }\n }\n}\n\n// A tree t where every node has an infinite number of children satisfies InfiniteEverywhere(t.children).\n// Otherwise, IsFiniteSomewhere(t) holds. That is, IsFiniteSomewhere says that the tree has some node\n// with less than infinite width. Such a tree may or may not be of finite height, as we'll see in an\n// example below.\n\nghost predicate IsFiniteSomewhere(t: Tree)\n{\n !InfiniteEverywhere(t.children)\n}\ngreatest predicate InfiniteEverywhere(s: Stream)\n{\n match s\n case Nil => false\n case Cons(t, tail) => InfiniteEverywhere(t.children) && InfiniteEverywhere(tail)\n}\n\n// Here is a tree where every node has exactly 1 child. Such a tree is finite in width (which implies\n// it is finite somewhere) and infinite in height (which implies there is no bound on its height).\n\nghost function SkinnyTree(): Tree\n{\n Node(Cons(SkinnyTree(), Nil))\n}\nlemma Proposition1()\n ensures IsFiniteSomewhere(SkinnyTree()) && !HasBoundedHeight(SkinnyTree());\n{\n assert forall n {:induction} :: 0 <= n ==> !LowerThan(SkinnyTree().children, n);\n}\n\n// Any tree where all paths have bounded height are finite somewhere.\n\nlemma Theorem0(t: Tree)\n requires HasBoundedHeight(t);\n ensures IsFiniteSomewhere(t);\n{\n var n :| 0 <= n && LowerThan(t.children, n);\n /*\n assert (forall k :: 0 <= k ==> InfiniteEverywhere#[k](t.children)) ==> InfiniteEverywhere(t.children);\n assert InfiniteEverywhere(t.children) ==> (forall k :: 0 <= k ==> InfiniteEverywhere#[k](t.children));\n assert InfiniteEverywhere(t.children) <==> (forall k :: 0 <= k ==> InfiniteEverywhere#[k](t.children)); // TODO: why does this not follow from the previous two?\n */\n var k := FindNil(t.children, n);\n}\nlemma FindNil(s: Stream, n: nat) returns (k: nat)\n requires LowerThan(s, n);\n ensures !InfiniteEverywhere#[k as ORDINAL](s);\n{\n match s {\n case Nil => k := 1;\n case Cons(t, _) =>\n\t k := FindNil(t.children, n-1);\n\t k := k + 1;\n }\n}\n\n// We defined an InfiniteEverywhere property above and negated it to get an IsFiniteSomewhere predicate.\n// If we had an InfiniteHeightSomewhere property, then we could negate it to obtain a predicate\n// HasFiniteHeightEverywhere. Consider the following definitions:\n\nghost predicate HasFiniteHeightEverywhere_Bad(t: Tree)\n{\n !InfiniteHeightSomewhere_Bad(t.children)\n}\ngreatest predicate InfiniteHeightSomewhere_Bad(s: Stream)\n{\n match s\n case Nil => false\n case Cons(t, tail) => InfiniteHeightSomewhere_Bad(t.children) || InfiniteHeightSomewhere_Bad(tail)\n}\n\n// In some ways, this definition may look reasonable--a list of trees is infinite somewhere\n// if it is nonempty, and either the list of children of the first node satisfies the property\n// or the tail of the list does. However, because co-predicates are defined by greatest\n// fix-points, there is nothing in this definition that \"forces\" the list to ever get to a\n// node whose list of children satisfy the property. The following example shows that a\n// shallow, infinitely wide tree satisfies the negation of HasFiniteHeightEverywhere_Bad.\n\nghost function ATree(): Tree\n{\n Node(ATreeChildren())\n}\nghost function ATreeChildren(): Stream\n{\n Cons(Node(Nil), ATreeChildren())\n}\nlemma Proposition2()\n ensures !HasFiniteHeightEverywhere_Bad(ATree());\n{\n Proposition2_Lemma0();\n Proposition2_Lemma1(ATreeChildren());\n}\ngreatest lemma Proposition2_Lemma0()\n ensures IsNeverEndingStream(ATreeChildren());\n{\n}\ngreatest lemma Proposition2_Lemma1(s: Stream)\n requires IsNeverEndingStream(s);\n ensures InfiniteHeightSomewhere_Bad(s);\n{\n calc {\n InfiniteHeightSomewhere_Bad#[_k](s);\n InfiniteHeightSomewhere_Bad#[_k-1](s.head.children) || InfiniteHeightSomewhere_Bad#[_k-1](s.tail);\n <==\n InfiniteHeightSomewhere_Bad#[_k-1](s.tail); // induction hypothesis\n }\n}\n\n// What was missing from the InfiniteHeightSomewhere_Bad definition was the existence of a child\n// node that satisfies the property recursively. To address that problem, we may consider\n// a definition like the following:\n\n/*\nghost predicate HasFiniteHeightEverywhere_Attempt(t: Tree)\n{\n !InfiniteHeightSomewhere_Attempt(t.children)\n}\ngreatest predicate InfiniteHeightSomewhere_Attempt(s: Stream)\n{\n exists n ::\n 0 <= n &&\n var ch := Tail(s, n);\n ch.Cons? && InfiniteHeightSomewhere_Attempt(ch.head.children)\n}\n*/\n\n// However, Dafny does not allow this definition: the recursive call to InfiniteHeightSomewhere_Attempt\n// sits inside an unbounded existential quantifier, which means the co-predicate's connection with its prefix\n// predicate is not guaranteed to hold, so Dafny disallows this co-predicate definition.\n\n// We will use a different way to express the HasFiniteHeightEverywhere property. Instead of\n// using an existential quantifier inside the recursively defined co-predicate, we can place a \"larger\"\n// existential quantifier outside the call to the co-predicate. This existential quantifier is going to be\n// over the possible paths down the tree (it is \"larger\" in the sense that it selects a child tree at each\n// level down the path, not just at one level).\n\n// A path is a possibly infinite list of indices, each selecting the next child tree to navigate to. A path\n// is valid when it uses valid indices and does not stop at a node with children.\n\ngreatest predicate ValidPath(t: Tree, p: Stream)\n{\n match p\n case Nil => t == Node(Nil)\n case Cons(index, tail) =>\n 0 <= index &&\n var ch := Tail(t.children, index);\n ch.Cons? && ValidPath(ch.head, tail)\n}\nlemma ValidPath_Lemma(p: Stream)\n ensures ValidPath(Node(Nil), p) ==> p == Nil;\n{\n if ValidPath(Node(Nil), p) {\n match p {\n case Nil =>\n case Cons(index, tail) => // proof by contradiction\n var nil : Stream := Nil;\n Tail_Lemma1(nil, 0, index);\n }\n }\n}\n\n// A tree has finite height (everywhere) if it has no valid infinite paths.\n\nghost predicate HasFiniteHeight(t: Tree)\n{\n forall p :: ValidPath(t, p) ==> !IsNeverEndingStream(p)\n}\n\n// From this definition, we can prove that any tree of bounded height is also of finite height.\n\nlemma Theorem1(t: Tree)\n requires HasBoundedHeight(t);\n ensures HasFiniteHeight(t);\n{\n var n :| 0 <= n && LowerThan(t.children, n);\n forall p | ValidPath(t, p) {\n Theorem1_Lemma(t, n, p);\n }\n}\nlemma Theorem1_Lemma(t: Tree, n: nat, p: Stream)\n requires LowerThan(t.children, n) && ValidPath(t, p);\n ensures !IsNeverEndingStream(p);\n decreases n;\n{\n match p {\n case Nil =>\n case Cons(index, tail) =>\n var ch := Tail(t.children, index);\n calc {\n LowerThan(t.children, n);\n ==> { LowerThan_Lemma(t.children, index, n); }\n LowerThan(ch, n);\n ==> // def. LowerThan\n LowerThan(ch.head.children, n-1);\n ==> //{ Theorem1_Lemma(ch.head, n-1, tail); }\n !IsNeverEndingStream(tail);\n ==> // def. IsNeverEndingStream\n !IsNeverEndingStream(p);\n }\n }\n}\n\n// In fact, HasBoundedHeight is strictly strong than HasFiniteHeight, as we'll show with an example.\n// Define SkinnyFiniteTree(n) to be a skinny (that is, of width 1) tree of height n.\n\nghost function SkinnyFiniteTree(n: nat): Tree\n ensures forall k: nat :: LowerThan(SkinnyFiniteTree(n).children, k) <==> n <= k;\n{\n if n == 0 then Node(Nil) else Node(Cons(SkinnyFiniteTree(n-1), Nil))\n}\n\n// Next, we define a tree whose root has an infinite number of children, child i of which\n// is a SkinnyFiniteTree(i).\n\nghost function FiniteUnboundedTree(): Tree\n{\n Node(EverLongerSkinnyTrees(0))\n}\nghost function EverLongerSkinnyTrees(n: nat): Stream\n{\n Cons(SkinnyFiniteTree(n), EverLongerSkinnyTrees(n+1))\n}\n\nlemma EverLongerSkinnyTrees_Lemma(k: nat, n: nat)\n ensures Tail(EverLongerSkinnyTrees(k), n).Cons?;\n ensures Tail(EverLongerSkinnyTrees(k), n).head == SkinnyFiniteTree(k+n);\n decreases n;\n{\n if n == 0 {\n } else {\n calc {\n Tail(EverLongerSkinnyTrees(k), n);\n { EverLongerSkinnyTrees_Lemma(k, n-1); } // this ensures that .tail on the next line is well-defined\n Tail(EverLongerSkinnyTrees(k), n-1).tail;\n { Tail_Lemma0(EverLongerSkinnyTrees(k), n-1); }\n Tail(EverLongerSkinnyTrees(k).tail, n-1);\n Tail(EverLongerSkinnyTrees(k+1), n-1);\n }\n EverLongerSkinnyTrees_Lemma(k+1, n-1);\n }\n}\n\nlemma Proposition3()\n ensures !HasBoundedHeight(FiniteUnboundedTree()) && HasFiniteHeight(FiniteUnboundedTree());\n{\n Proposition3a();\n Proposition3b();\n}\nlemma Proposition3a()\n ensures !HasBoundedHeight(FiniteUnboundedTree());\n{\n var ch := FiniteUnboundedTree().children;\n forall n | 0 <= n\n ensures !LowerThan(ch, n);\n {\n var cn := Tail(ch, n+1);\n EverLongerSkinnyTrees_Lemma(0, n+1);\n assert cn.head == SkinnyFiniteTree(n+1);\n assert !LowerThan(cn.head.children, n);\n LowerThan_Lemma(ch, n+1, n);\n }\n}\nlemma Proposition3b()\n ensures HasFiniteHeight(FiniteUnboundedTree());\n{\n var t := FiniteUnboundedTree();\n forall p | ValidPath(t, p)\n ensures !IsNeverEndingStream(p);\n {\n assert p.Cons?;\n var index := p.head;\n assert 0 <= index;\n var ch := Tail(t.children, index);\n assert ch.Cons? && ValidPath(ch.head, p.tail);\n EverLongerSkinnyTrees_Lemma(0, index);\n assert ch.head == SkinnyFiniteTree(index);\n var si := SkinnyFiniteTree(index);\n assert LowerThan(si.children, index);\n Proposition3b_Lemma(si, index, p.tail);\n }\n}\nlemma Proposition3b_Lemma(t: Tree, h: nat, p: Stream)\n requires LowerThan(t.children, h) && ValidPath(t, p)\n ensures !IsNeverEndingStream(p)\n decreases h\n{\n match p {\n case Nil =>\n case Cons(index, tail) =>\n // From the definition of ValidPath(t, p), we get the following:\n var ch := Tail(t.children, index);\n // assert ch.Cons? && ValidPath(ch.head, tail);\n // From the definition of LowerThan(t.children, h), we get the following:\n match t.children {\n case Nil =>\n ValidPath_Lemma(p);\n assert false; // absurd case\n case Cons(_, _) =>\n // assert 1 <= h;\n LowerThan_Lemma(t.children, index, h);\n // assert LowerThan(ch, h);\n }\n // Putting these together, by ch.Cons? and the definition of LowerThan(ch, h), we get:\n assert LowerThan(ch.head.children, h-1);\n // And now we can invoke the induction hypothesis:\n // Proposition3b_Lemma(ch.head, h-1, tail);\n }\n}\n\n// Using a stream of integers to denote a path is convenient, because it allows us to\n// use Tail to quickly select the next child tree. But we can also define paths in a\n// way that more directly follows the navigation steps required to get to the next child,\n// using Peano numbers instead of the built-in integers. This means that each Succ\n// constructor among the Peano numbers corresponds to moving \"right\" among the children\n// of a tree node. A path is valid only if it always selects a child from a list\n// of children; this implies we must avoid infinite \"right\" moves. The appropriate type\n// Numbers (which is really just a stream of natural numbers) is defined as a combination\n// two mutually recursive datatypes, one inductive and the other co-inductive.\n\ncodatatype CoOption = None | Some(get: T)\ndatatype Number = Succ(Number) | Zero(CoOption)\n\n// Note that the use of an inductive datatype for Number guarantees that sequences of successive\n// \"right\" moves are finite (analogously, each Peano number is finite). Yet the use of a co-inductive\n// CoOption in between allows paths to go on forever. In contrast, a definition like:\n\ncodatatype InfPath = Right(InfPath) | Down(InfPath) | Stop\n\n// does not guarantee the absence of infinitely long sequences of \"right\" moves. In other words,\n// InfPath also gives rise to indecisive paths--those that never select a child node. Also,\n// compare the definition of Number with:\n\ncodatatype FinPath = Right(FinPath) | Down(FinPath) | Stop\n\n// where the type can only represent finite paths. As a final alternative to consider, had we\n// wanted only infinite, decisive paths, we would just drop the None constructor, forcing each\n// CoOption to be some Number. As it is, we want to allow both finite and infinite paths, but we\n// want to be able to distinguish them, so we define a co-predicate that does so:\n\ngreatest predicate InfinitePath(r: CoOption)\n{\n match r\n case None => false\n case Some(num) => InfinitePath'(num)\n}\ngreatest predicate InfinitePath'(num: Number)\n{\n match num\n case Succ(next) => InfinitePath'(next)\n case Zero(r) => InfinitePath(r)\n}\n\n// As before, a path is valid for a tree when it navigates to existing nodes and does not stop\n// in a node with more children.\n\ngreatest predicate ValidPath_Alt(t: Tree, r: CoOption)\n{\n match r\n case None => t == Node(Nil)\n case Some(num) => ValidPath_Alt'(t.children, num)\n}\ngreatest predicate ValidPath_Alt'(s: Stream, num: Number)\n{\n match num\n case Succ(next) => s.Cons? && ValidPath_Alt'(s.tail, next)\n case Zero(r) => s.Cons? && ValidPath_Alt(s.head, r)\n}\n\n// Here is the alternative definition of a tree that has finite height everywhere, using the\n// new paths.\n\nghost predicate HasFiniteHeight_Alt(t: Tree)\n{\n forall r :: ValidPath_Alt(t, r) ==> !InfinitePath(r)\n}\n\n// We will prove that this new definition is equivalent to the previous. To do that, we\n// first definite functions S2N and N2S to map between the path representations\n// Stream and CoOption, and then prove some lemmas about this correspondence.\n\nghost function S2N(p: Stream): CoOption\n decreases 0;\n{\n match p\n case Nil => None\n case Cons(n, tail) => Some(S2N'(if n < 0 then 0 else n, tail))\n}\nghost function S2N'(n: nat, tail: Stream): Number\n decreases n + 1;\n{\n if n <= 0 then Zero(S2N(tail)) else Succ(S2N'(n-1, tail))\n}\n\nghost function N2S(r: CoOption): Stream\n{\n match r\n case None => Nil\n case Some(num) => N2S'(0, num)\n}\nghost function N2S'(n: nat, num: Number): Stream\n decreases num;\n{\n match num\n case Zero(r) => Cons(n, N2S(r))\n case Succ(next) => N2S'(n + 1, next)\n}\n\nlemma Path_Lemma0(t: Tree, p: Stream)\n requires ValidPath(t, p);\n ensures ValidPath_Alt(t, S2N(p));\n{\n if ValidPath(t, p) {\n Path_Lemma0'(t, p);\n }\n}\ngreatest lemma Path_Lemma0'(t: Tree, p: Stream)\n requires ValidPath(t, p);\n ensures ValidPath_Alt(t, S2N(p));\n{\n match p {\n case Nil =>\n assert t == Node(Nil);\n case Cons(index, tail) =>\n assert 0 <= index;\n var ch := Tail(t.children, index);\n assert ch.Cons? && ValidPath(ch.head, tail);\n\n calc {\n ValidPath_Alt#[_k](t, S2N(p));\n { assert S2N(p) == Some(S2N'(index, tail)); }\n ValidPath_Alt#[_k](t, Some(S2N'(index, tail)));\n // def. ValidPath_Alt#\n ValidPath_Alt'#[_k-1](t.children, S2N'(index, tail));\n { Path_Lemma0''(t.children, index, tail); }\n true;\n }\n }\n}\ngreatest lemma Path_Lemma0''(tChildren: Stream, n: nat, tail: Stream)\n requires var ch := Tail(tChildren, n); ch.Cons? && ValidPath(ch.head, tail);\n ensures ValidPath_Alt'(tChildren, S2N'(n, tail));\n{\n Tail_Lemma1(tChildren, 0, n);\n match S2N'(n, tail) {\n case Succ(next) =>\n calc {\n Tail(tChildren, n);\n { Tail_Lemma1(tChildren, n-1, n); }\n Tail(tChildren, n-1).tail;\n { Tail_Lemma0(tChildren, n-1); }\n Tail(tChildren.tail, n-1);\n }\n Path_Lemma0''(tChildren.tail, n-1, tail);\n case Zero(r) =>\n Path_Lemma0'(tChildren.head, tail);\n }\n}\nlemma Path_Lemma1(t: Tree, r: CoOption)\n requires ValidPath_Alt(t, r);\n ensures ValidPath(t, N2S(r));\n{\n if ValidPath_Alt(t, r) {\n Path_Lemma1'(t, r);\n }\n}\ngreatest lemma Path_Lemma1'(t: Tree, r: CoOption)\n requires ValidPath_Alt(t, r);\n ensures ValidPath(t, N2S(r));\n decreases 1;\n{\n match r {\n case None =>\n assert t == Node(Nil);\n assert N2S(r) == Nil;\n case Some(num) =>\n assert ValidPath_Alt'(t.children, num);\n // assert N2S'(0, num).Cons?;\n // Path_Lemma1''(t.children, 0, num);\n var p := N2S'(0, num);\n calc {\n ValidPath#[_k](t, N2S(r));\n ValidPath#[_k](t, N2S(Some(num)));\n ValidPath#[_k](t, N2S'(0, num));\n { Path_Lemma1''#[_k](t.children, 0, num); }\n true;\n }\n }\n}\ngreatest lemma Path_Lemma1''(s: Stream, n: nat, num: Number)\n requires ValidPath_Alt'(Tail(s, n), num);\n ensures ValidPath(Node(s), N2S'(n, num));\n decreases 0, num;\n{\n match num {\n case Succ(next) =>\n Path_Lemma1''#[_k](s, n+1, next);\n case Zero(r) =>\n calc {\n ValidPath#[_k](Node(s), N2S'(n, num));\n ValidPath#[_k](Node(s), Cons(n, N2S(r)));\n Tail(s, n).Cons? && ValidPath#[_k-1](Tail(s, n).head, N2S(r));\n { assert Tail(s, n).Cons?; }\n ValidPath#[_k-1](Tail(s, n).head, N2S(r));\n { Path_Lemma1'(Tail(s, n).head, r); }\n true;\n }\n }\n}\nlemma Path_Lemma2(p: Stream)\n ensures IsNeverEndingStream(p) ==> InfinitePath(S2N(p));\n{\n if IsNeverEndingStream(p) {\n Path_Lemma2'(p);\n }\n}\ngreatest lemma Path_Lemma2'(p: Stream)\n requires IsNeverEndingStream(p);\n ensures InfinitePath(S2N(p));\n{\n match p {\n case Cons(n, tail) =>\n calc {\n InfinitePath#[_k](S2N(p));\n // def. S2N\n InfinitePath#[_k](Some(S2N'(if n < 0 then 0 else n, tail)));\n // def. InfinitePath\n InfinitePath'#[_k-1](S2N'(if n < 0 then 0 else n, tail));\n <== { Path_Lemma2''(p, if n < 0 then 0 else n, tail); }\n InfinitePath#[_k-1](S2N(tail));\n { Path_Lemma2'(tail); }\n true;\n }\n }\n}\ngreatest lemma Path_Lemma2''(p: Stream, n: nat, tail: Stream)\n requires IsNeverEndingStream(p) && p.tail == tail\n ensures InfinitePath'(S2N'(n, tail))\n{\n Path_Lemma2'(tail);\n}\nlemma Path_Lemma3(r: CoOption)\n ensures InfinitePath(r) ==> IsNeverEndingStream(N2S(r));\n{\n if InfinitePath(r) {\n match r {\n case Some(num) => Path_Lemma3'(0, num);\n }\n }\n}\ngreatest lemma Path_Lemma3'(n: nat, num: Number)\n requires InfinitePath'(num);\n ensures IsNeverEndingStream(N2S'(n, num));\n decreases num;\n{\n match num {\n case Zero(r) =>\n calc {\n IsNeverEndingStream#[_k](N2S'(n, num));\n // def. N2S'\n IsNeverEndingStream#[_k](Cons(n, N2S(r)));\n // def. IsNeverEndingStream\n IsNeverEndingStream#[_k-1](N2S(r));\n { Path_Lemma3'(0, r.get); }\n true;\n }\n case Succ(next) =>\n Path_Lemma3'#[_k](n + 1, next);\n }\n}\n\nlemma Theorem2(t: Tree)\n ensures HasFiniteHeight(t) <==> HasFiniteHeight_Alt(t);\n{\n if HasFiniteHeight_Alt(t) {\n forall p {\n calc ==> {\n ValidPath(t, p);\n { Path_Lemma0(t, p); }\n ValidPath_Alt(t, S2N(p));\n // assumption HasFiniteHeight(t)\n !InfinitePath(S2N(p));\n { Path_Lemma2(p); }\n !IsNeverEndingStream(p);\n }\n }\n }\n if HasFiniteHeight(t) {\n forall r {\n calc ==> {\n ValidPath_Alt(t, r);\n { Path_Lemma1(t, r); }\n ValidPath(t, N2S(r));\n // assumption HasFiniteHeight_Alt(t)\n !IsNeverEndingStream(N2S(r));\n { Path_Lemma3(r); }\n !InfinitePath(r);\n }\n }\n }\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 /deprecation:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// Here is the usual definition of possibly infinite lists, along with a function Tail(s, n), which drops\n// n heads from s, and two lemmas that prove properties of Tail.\n\ncodatatype Stream = Nil | Cons(head: T, tail: Stream)\n\nghost function Tail(s: Stream, n: nat): Stream\n{\n if n == 0 then s else\n var t := Tail(s, n-1);\n if t == Nil then t else t.tail\n}\n\nlemma Tail_Lemma0(s: Stream, n: nat)\n requires s.Cons? && Tail(s, n).Cons?;\n ensures Tail(s, n).tail == Tail(s.tail, n);\n{\n}\nlemma Tail_Lemma1(s: Stream, k: nat, n: nat)\n requires k <= n;\n ensures Tail(s, n).Cons? ==> Tail(s, k).Cons?;\n // Note, the contrapositive of this lemma says: Tail(s, k) == Nil ==> Tail(s, n) == Nil\n{\n if k < n && Tail(s, n).Cons? {\n }\n}\nlemma Tail_Lemma2(s: Stream, n: nat)\n requires s.Cons? && Tail(s.tail, n).Cons?;\n ensures Tail(s, n).Cons?;\n{\n if n != 0 {\n Tail_Lemma0(s, n-1);\n }\n}\n\n// Co-predicate IsNeverEndingStream(s) answers whether or not s ever contains Nil.\n\ngreatest predicate IsNeverEndingStream(s: Stream)\n{\n match s\n case Nil => false\n case Cons(_, tail) => IsNeverEndingStream(tail)\n}\n\n// Here is an example of an infinite stream.\n\nghost function AnInfiniteStream(): Stream\n{\n Cons(0, AnInfiniteStream())\n}\ngreatest lemma Proposition0()\n ensures IsNeverEndingStream(AnInfiniteStream());\n{\n}\n\n// Now, consider a Tree definition, where each node can have a possibly infinite number of children.\n\ndatatype Tree = Node(children: Stream)\n\n// Such a tree might have not just infinite width but also infinite height. The following predicate\n// holds if there is, for every path down from the root, a common bound on the height of each such path.\n// Note that the definition needs a co-predicate in order to say something about all of a node's children.\n\nghost predicate HasBoundedHeight(t: Tree)\n{\n exists n :: 0 <= n && LowerThan(t.children, n)\n}\ngreatest predicate LowerThan(s: Stream, n: nat)\n{\n match s\n case Nil => true\n case Cons(t, tail) =>\n 1 <= n && LowerThan(t.children, n-1) && LowerThan(tail, n)\n}\n\n// Co-predicate LowerThan(s, n) recurses on LowerThan(s.tail, n). Thus, a property of LowerThan is that\n// LowerThan(s, h) implies LowerThan(s', h) for any suffix s' of s.\n\nlemma LowerThan_Lemma(s: Stream, n: nat, h: nat)\n ensures LowerThan(s, h) ==> LowerThan(Tail(s, n), h);\n{\n Tail_Lemma1(s, 0, n);\n if n == 0 || Tail(s, n) == Nil {\n } else {\n match s {\n case Cons(t, tail) =>\n LowerThan_Lemma(tail, n-1, h);\n Tail_Lemma0(s, n-1);\n }\n }\n}\n\n// A tree t where every node has an infinite number of children satisfies InfiniteEverywhere(t.children).\n// Otherwise, IsFiniteSomewhere(t) holds. That is, IsFiniteSomewhere says that the tree has some node\n// with less than infinite width. Such a tree may or may not be of finite height, as we'll see in an\n// example below.\n\nghost predicate IsFiniteSomewhere(t: Tree)\n{\n !InfiniteEverywhere(t.children)\n}\ngreatest predicate InfiniteEverywhere(s: Stream)\n{\n match s\n case Nil => false\n case Cons(t, tail) => InfiniteEverywhere(t.children) && InfiniteEverywhere(tail)\n}\n\n// Here is a tree where every node has exactly 1 child. Such a tree is finite in width (which implies\n// it is finite somewhere) and infinite in height (which implies there is no bound on its height).\n\nghost function SkinnyTree(): Tree\n{\n Node(Cons(SkinnyTree(), Nil))\n}\nlemma Proposition1()\n ensures IsFiniteSomewhere(SkinnyTree()) && !HasBoundedHeight(SkinnyTree());\n{\n}\n\n// Any tree where all paths have bounded height are finite somewhere.\n\nlemma Theorem0(t: Tree)\n requires HasBoundedHeight(t);\n ensures IsFiniteSomewhere(t);\n{\n var n :| 0 <= n && LowerThan(t.children, n);\n /*\n */\n var k := FindNil(t.children, n);\n}\nlemma FindNil(s: Stream, n: nat) returns (k: nat)\n requires LowerThan(s, n);\n ensures !InfiniteEverywhere#[k as ORDINAL](s);\n{\n match s {\n case Nil => k := 1;\n case Cons(t, _) =>\n\t k := FindNil(t.children, n-1);\n\t k := k + 1;\n }\n}\n\n// We defined an InfiniteEverywhere property above and negated it to get an IsFiniteSomewhere predicate.\n// If we had an InfiniteHeightSomewhere property, then we could negate it to obtain a predicate\n// HasFiniteHeightEverywhere. Consider the following definitions:\n\nghost predicate HasFiniteHeightEverywhere_Bad(t: Tree)\n{\n !InfiniteHeightSomewhere_Bad(t.children)\n}\ngreatest predicate InfiniteHeightSomewhere_Bad(s: Stream)\n{\n match s\n case Nil => false\n case Cons(t, tail) => InfiniteHeightSomewhere_Bad(t.children) || InfiniteHeightSomewhere_Bad(tail)\n}\n\n// In some ways, this definition may look reasonable--a list of trees is infinite somewhere\n// if it is nonempty, and either the list of children of the first node satisfies the property\n// or the tail of the list does. However, because co-predicates are defined by greatest\n// fix-points, there is nothing in this definition that \"forces\" the list to ever get to a\n// node whose list of children satisfy the property. The following example shows that a\n// shallow, infinitely wide tree satisfies the negation of HasFiniteHeightEverywhere_Bad.\n\nghost function ATree(): Tree\n{\n Node(ATreeChildren())\n}\nghost function ATreeChildren(): Stream\n{\n Cons(Node(Nil), ATreeChildren())\n}\nlemma Proposition2()\n ensures !HasFiniteHeightEverywhere_Bad(ATree());\n{\n Proposition2_Lemma0();\n Proposition2_Lemma1(ATreeChildren());\n}\ngreatest lemma Proposition2_Lemma0()\n ensures IsNeverEndingStream(ATreeChildren());\n{\n}\ngreatest lemma Proposition2_Lemma1(s: Stream)\n requires IsNeverEndingStream(s);\n ensures InfiniteHeightSomewhere_Bad(s);\n{\n calc {\n InfiniteHeightSomewhere_Bad#[_k](s);\n InfiniteHeightSomewhere_Bad#[_k-1](s.head.children) || InfiniteHeightSomewhere_Bad#[_k-1](s.tail);\n <==\n InfiniteHeightSomewhere_Bad#[_k-1](s.tail); // induction hypothesis\n }\n}\n\n// What was missing from the InfiniteHeightSomewhere_Bad definition was the existence of a child\n// node that satisfies the property recursively. To address that problem, we may consider\n// a definition like the following:\n\n/*\nghost predicate HasFiniteHeightEverywhere_Attempt(t: Tree)\n{\n !InfiniteHeightSomewhere_Attempt(t.children)\n}\ngreatest predicate InfiniteHeightSomewhere_Attempt(s: Stream)\n{\n exists n ::\n 0 <= n &&\n var ch := Tail(s, n);\n ch.Cons? && InfiniteHeightSomewhere_Attempt(ch.head.children)\n}\n*/\n\n// However, Dafny does not allow this definition: the recursive call to InfiniteHeightSomewhere_Attempt\n// sits inside an unbounded existential quantifier, which means the co-predicate's connection with its prefix\n// predicate is not guaranteed to hold, so Dafny disallows this co-predicate definition.\n\n// We will use a different way to express the HasFiniteHeightEverywhere property. Instead of\n// using an existential quantifier inside the recursively defined co-predicate, we can place a \"larger\"\n// existential quantifier outside the call to the co-predicate. This existential quantifier is going to be\n// over the possible paths down the tree (it is \"larger\" in the sense that it selects a child tree at each\n// level down the path, not just at one level).\n\n// A path is a possibly infinite list of indices, each selecting the next child tree to navigate to. A path\n// is valid when it uses valid indices and does not stop at a node with children.\n\ngreatest predicate ValidPath(t: Tree, p: Stream)\n{\n match p\n case Nil => t == Node(Nil)\n case Cons(index, tail) =>\n 0 <= index &&\n var ch := Tail(t.children, index);\n ch.Cons? && ValidPath(ch.head, tail)\n}\nlemma ValidPath_Lemma(p: Stream)\n ensures ValidPath(Node(Nil), p) ==> p == Nil;\n{\n if ValidPath(Node(Nil), p) {\n match p {\n case Nil =>\n case Cons(index, tail) => // proof by contradiction\n var nil : Stream := Nil;\n Tail_Lemma1(nil, 0, index);\n }\n }\n}\n\n// A tree has finite height (everywhere) if it has no valid infinite paths.\n\nghost predicate HasFiniteHeight(t: Tree)\n{\n forall p :: ValidPath(t, p) ==> !IsNeverEndingStream(p)\n}\n\n// From this definition, we can prove that any tree of bounded height is also of finite height.\n\nlemma Theorem1(t: Tree)\n requires HasBoundedHeight(t);\n ensures HasFiniteHeight(t);\n{\n var n :| 0 <= n && LowerThan(t.children, n);\n forall p | ValidPath(t, p) {\n Theorem1_Lemma(t, n, p);\n }\n}\nlemma Theorem1_Lemma(t: Tree, n: nat, p: Stream)\n requires LowerThan(t.children, n) && ValidPath(t, p);\n ensures !IsNeverEndingStream(p);\n{\n match p {\n case Nil =>\n case Cons(index, tail) =>\n var ch := Tail(t.children, index);\n calc {\n LowerThan(t.children, n);\n ==> { LowerThan_Lemma(t.children, index, n); }\n LowerThan(ch, n);\n ==> // def. LowerThan\n LowerThan(ch.head.children, n-1);\n ==> //{ Theorem1_Lemma(ch.head, n-1, tail); }\n !IsNeverEndingStream(tail);\n ==> // def. IsNeverEndingStream\n !IsNeverEndingStream(p);\n }\n }\n}\n\n// In fact, HasBoundedHeight is strictly strong than HasFiniteHeight, as we'll show with an example.\n// Define SkinnyFiniteTree(n) to be a skinny (that is, of width 1) tree of height n.\n\nghost function SkinnyFiniteTree(n: nat): Tree\n ensures forall k: nat :: LowerThan(SkinnyFiniteTree(n).children, k) <==> n <= k;\n{\n if n == 0 then Node(Nil) else Node(Cons(SkinnyFiniteTree(n-1), Nil))\n}\n\n// Next, we define a tree whose root has an infinite number of children, child i of which\n// is a SkinnyFiniteTree(i).\n\nghost function FiniteUnboundedTree(): Tree\n{\n Node(EverLongerSkinnyTrees(0))\n}\nghost function EverLongerSkinnyTrees(n: nat): Stream\n{\n Cons(SkinnyFiniteTree(n), EverLongerSkinnyTrees(n+1))\n}\n\nlemma EverLongerSkinnyTrees_Lemma(k: nat, n: nat)\n ensures Tail(EverLongerSkinnyTrees(k), n).Cons?;\n ensures Tail(EverLongerSkinnyTrees(k), n).head == SkinnyFiniteTree(k+n);\n{\n if n == 0 {\n } else {\n calc {\n Tail(EverLongerSkinnyTrees(k), n);\n { EverLongerSkinnyTrees_Lemma(k, n-1); } // this ensures that .tail on the next line is well-defined\n Tail(EverLongerSkinnyTrees(k), n-1).tail;\n { Tail_Lemma0(EverLongerSkinnyTrees(k), n-1); }\n Tail(EverLongerSkinnyTrees(k).tail, n-1);\n Tail(EverLongerSkinnyTrees(k+1), n-1);\n }\n EverLongerSkinnyTrees_Lemma(k+1, n-1);\n }\n}\n\nlemma Proposition3()\n ensures !HasBoundedHeight(FiniteUnboundedTree()) && HasFiniteHeight(FiniteUnboundedTree());\n{\n Proposition3a();\n Proposition3b();\n}\nlemma Proposition3a()\n ensures !HasBoundedHeight(FiniteUnboundedTree());\n{\n var ch := FiniteUnboundedTree().children;\n forall n | 0 <= n\n ensures !LowerThan(ch, n);\n {\n var cn := Tail(ch, n+1);\n EverLongerSkinnyTrees_Lemma(0, n+1);\n LowerThan_Lemma(ch, n+1, n);\n }\n}\nlemma Proposition3b()\n ensures HasFiniteHeight(FiniteUnboundedTree());\n{\n var t := FiniteUnboundedTree();\n forall p | ValidPath(t, p)\n ensures !IsNeverEndingStream(p);\n {\n var index := p.head;\n var ch := Tail(t.children, index);\n EverLongerSkinnyTrees_Lemma(0, index);\n var si := SkinnyFiniteTree(index);\n Proposition3b_Lemma(si, index, p.tail);\n }\n}\nlemma Proposition3b_Lemma(t: Tree, h: nat, p: Stream)\n requires LowerThan(t.children, h) && ValidPath(t, p)\n ensures !IsNeverEndingStream(p)\n{\n match p {\n case Nil =>\n case Cons(index, tail) =>\n // From the definition of ValidPath(t, p), we get the following:\n var ch := Tail(t.children, index);\n // assert ch.Cons? && ValidPath(ch.head, tail);\n // From the definition of LowerThan(t.children, h), we get the following:\n match t.children {\n case Nil =>\n ValidPath_Lemma(p);\n case Cons(_, _) =>\n // assert 1 <= h;\n LowerThan_Lemma(t.children, index, h);\n // assert LowerThan(ch, h);\n }\n // Putting these together, by ch.Cons? and the definition of LowerThan(ch, h), we get:\n // And now we can invoke the induction hypothesis:\n // Proposition3b_Lemma(ch.head, h-1, tail);\n }\n}\n\n// Using a stream of integers to denote a path is convenient, because it allows us to\n// use Tail to quickly select the next child tree. But we can also define paths in a\n// way that more directly follows the navigation steps required to get to the next child,\n// using Peano numbers instead of the built-in integers. This means that each Succ\n// constructor among the Peano numbers corresponds to moving \"right\" among the children\n// of a tree node. A path is valid only if it always selects a child from a list\n// of children; this implies we must avoid infinite \"right\" moves. The appropriate type\n// Numbers (which is really just a stream of natural numbers) is defined as a combination\n// two mutually recursive datatypes, one inductive and the other co-inductive.\n\ncodatatype CoOption = None | Some(get: T)\ndatatype Number = Succ(Number) | Zero(CoOption)\n\n// Note that the use of an inductive datatype for Number guarantees that sequences of successive\n// \"right\" moves are finite (analogously, each Peano number is finite). Yet the use of a co-inductive\n// CoOption in between allows paths to go on forever. In contrast, a definition like:\n\ncodatatype InfPath = Right(InfPath) | Down(InfPath) | Stop\n\n// does not guarantee the absence of infinitely long sequences of \"right\" moves. In other words,\n// InfPath also gives rise to indecisive paths--those that never select a child node. Also,\n// compare the definition of Number with:\n\ncodatatype FinPath = Right(FinPath) | Down(FinPath) | Stop\n\n// where the type can only represent finite paths. As a final alternative to consider, had we\n// wanted only infinite, decisive paths, we would just drop the None constructor, forcing each\n// CoOption to be some Number. As it is, we want to allow both finite and infinite paths, but we\n// want to be able to distinguish them, so we define a co-predicate that does so:\n\ngreatest predicate InfinitePath(r: CoOption)\n{\n match r\n case None => false\n case Some(num) => InfinitePath'(num)\n}\ngreatest predicate InfinitePath'(num: Number)\n{\n match num\n case Succ(next) => InfinitePath'(next)\n case Zero(r) => InfinitePath(r)\n}\n\n// As before, a path is valid for a tree when it navigates to existing nodes and does not stop\n// in a node with more children.\n\ngreatest predicate ValidPath_Alt(t: Tree, r: CoOption)\n{\n match r\n case None => t == Node(Nil)\n case Some(num) => ValidPath_Alt'(t.children, num)\n}\ngreatest predicate ValidPath_Alt'(s: Stream, num: Number)\n{\n match num\n case Succ(next) => s.Cons? && ValidPath_Alt'(s.tail, next)\n case Zero(r) => s.Cons? && ValidPath_Alt(s.head, r)\n}\n\n// Here is the alternative definition of a tree that has finite height everywhere, using the\n// new paths.\n\nghost predicate HasFiniteHeight_Alt(t: Tree)\n{\n forall r :: ValidPath_Alt(t, r) ==> !InfinitePath(r)\n}\n\n// We will prove that this new definition is equivalent to the previous. To do that, we\n// first definite functions S2N and N2S to map between the path representations\n// Stream and CoOption, and then prove some lemmas about this correspondence.\n\nghost function S2N(p: Stream): CoOption\n{\n match p\n case Nil => None\n case Cons(n, tail) => Some(S2N'(if n < 0 then 0 else n, tail))\n}\nghost function S2N'(n: nat, tail: Stream): Number\n{\n if n <= 0 then Zero(S2N(tail)) else Succ(S2N'(n-1, tail))\n}\n\nghost function N2S(r: CoOption): Stream\n{\n match r\n case None => Nil\n case Some(num) => N2S'(0, num)\n}\nghost function N2S'(n: nat, num: Number): Stream\n{\n match num\n case Zero(r) => Cons(n, N2S(r))\n case Succ(next) => N2S'(n + 1, next)\n}\n\nlemma Path_Lemma0(t: Tree, p: Stream)\n requires ValidPath(t, p);\n ensures ValidPath_Alt(t, S2N(p));\n{\n if ValidPath(t, p) {\n Path_Lemma0'(t, p);\n }\n}\ngreatest lemma Path_Lemma0'(t: Tree, p: Stream)\n requires ValidPath(t, p);\n ensures ValidPath_Alt(t, S2N(p));\n{\n match p {\n case Nil =>\n case Cons(index, tail) =>\n var ch := Tail(t.children, index);\n\n calc {\n ValidPath_Alt#[_k](t, S2N(p));\n { assert S2N(p) == Some(S2N'(index, tail)); }\n ValidPath_Alt#[_k](t, Some(S2N'(index, tail)));\n // def. ValidPath_Alt#\n ValidPath_Alt'#[_k-1](t.children, S2N'(index, tail));\n { Path_Lemma0''(t.children, index, tail); }\n true;\n }\n }\n}\ngreatest lemma Path_Lemma0''(tChildren: Stream, n: nat, tail: Stream)\n requires var ch := Tail(tChildren, n); ch.Cons? && ValidPath(ch.head, tail);\n ensures ValidPath_Alt'(tChildren, S2N'(n, tail));\n{\n Tail_Lemma1(tChildren, 0, n);\n match S2N'(n, tail) {\n case Succ(next) =>\n calc {\n Tail(tChildren, n);\n { Tail_Lemma1(tChildren, n-1, n); }\n Tail(tChildren, n-1).tail;\n { Tail_Lemma0(tChildren, n-1); }\n Tail(tChildren.tail, n-1);\n }\n Path_Lemma0''(tChildren.tail, n-1, tail);\n case Zero(r) =>\n Path_Lemma0'(tChildren.head, tail);\n }\n}\nlemma Path_Lemma1(t: Tree, r: CoOption)\n requires ValidPath_Alt(t, r);\n ensures ValidPath(t, N2S(r));\n{\n if ValidPath_Alt(t, r) {\n Path_Lemma1'(t, r);\n }\n}\ngreatest lemma Path_Lemma1'(t: Tree, r: CoOption)\n requires ValidPath_Alt(t, r);\n ensures ValidPath(t, N2S(r));\n{\n match r {\n case None =>\n case Some(num) =>\n // assert N2S'(0, num).Cons?;\n // Path_Lemma1''(t.children, 0, num);\n var p := N2S'(0, num);\n calc {\n ValidPath#[_k](t, N2S(r));\n ValidPath#[_k](t, N2S(Some(num)));\n ValidPath#[_k](t, N2S'(0, num));\n { Path_Lemma1''#[_k](t.children, 0, num); }\n true;\n }\n }\n}\ngreatest lemma Path_Lemma1''(s: Stream, n: nat, num: Number)\n requires ValidPath_Alt'(Tail(s, n), num);\n ensures ValidPath(Node(s), N2S'(n, num));\n{\n match num {\n case Succ(next) =>\n Path_Lemma1''#[_k](s, n+1, next);\n case Zero(r) =>\n calc {\n ValidPath#[_k](Node(s), N2S'(n, num));\n ValidPath#[_k](Node(s), Cons(n, N2S(r)));\n Tail(s, n).Cons? && ValidPath#[_k-1](Tail(s, n).head, N2S(r));\n { assert Tail(s, n).Cons?; }\n ValidPath#[_k-1](Tail(s, n).head, N2S(r));\n { Path_Lemma1'(Tail(s, n).head, r); }\n true;\n }\n }\n}\nlemma Path_Lemma2(p: Stream)\n ensures IsNeverEndingStream(p) ==> InfinitePath(S2N(p));\n{\n if IsNeverEndingStream(p) {\n Path_Lemma2'(p);\n }\n}\ngreatest lemma Path_Lemma2'(p: Stream)\n requires IsNeverEndingStream(p);\n ensures InfinitePath(S2N(p));\n{\n match p {\n case Cons(n, tail) =>\n calc {\n InfinitePath#[_k](S2N(p));\n // def. S2N\n InfinitePath#[_k](Some(S2N'(if n < 0 then 0 else n, tail)));\n // def. InfinitePath\n InfinitePath'#[_k-1](S2N'(if n < 0 then 0 else n, tail));\n <== { Path_Lemma2''(p, if n < 0 then 0 else n, tail); }\n InfinitePath#[_k-1](S2N(tail));\n { Path_Lemma2'(tail); }\n true;\n }\n }\n}\ngreatest lemma Path_Lemma2''(p: Stream, n: nat, tail: Stream)\n requires IsNeverEndingStream(p) && p.tail == tail\n ensures InfinitePath'(S2N'(n, tail))\n{\n Path_Lemma2'(tail);\n}\nlemma Path_Lemma3(r: CoOption)\n ensures InfinitePath(r) ==> IsNeverEndingStream(N2S(r));\n{\n if InfinitePath(r) {\n match r {\n case Some(num) => Path_Lemma3'(0, num);\n }\n }\n}\ngreatest lemma Path_Lemma3'(n: nat, num: Number)\n requires InfinitePath'(num);\n ensures IsNeverEndingStream(N2S'(n, num));\n{\n match num {\n case Zero(r) =>\n calc {\n IsNeverEndingStream#[_k](N2S'(n, num));\n // def. N2S'\n IsNeverEndingStream#[_k](Cons(n, N2S(r)));\n // def. IsNeverEndingStream\n IsNeverEndingStream#[_k-1](N2S(r));\n { Path_Lemma3'(0, r.get); }\n true;\n }\n case Succ(next) =>\n Path_Lemma3'#[_k](n + 1, next);\n }\n}\n\nlemma Theorem2(t: Tree)\n ensures HasFiniteHeight(t) <==> HasFiniteHeight_Alt(t);\n{\n if HasFiniteHeight_Alt(t) {\n forall p {\n calc ==> {\n ValidPath(t, p);\n { Path_Lemma0(t, p); }\n ValidPath_Alt(t, S2N(p));\n // assumption HasFiniteHeight(t)\n !InfinitePath(S2N(p));\n { Path_Lemma2(p); }\n !IsNeverEndingStream(p);\n }\n }\n }\n if HasFiniteHeight(t) {\n forall r {\n calc ==> {\n ValidPath_Alt(t, r);\n { Path_Lemma1(t, r); }\n ValidPath(t, N2S(r));\n // assumption HasFiniteHeight_Alt(t)\n !IsNeverEndingStream(N2S(r));\n { Path_Lemma3(r); }\n !InfinitePath(r);\n }\n }\n }\n}\n\n" }, { "test_ID": "318", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_from dafny main repo_dafny3_Iter.dfy", "ground_truth": "// RUN: %testDafnyForEachCompiler --refresh-exit-code=0 \"%s\" -- --relax-definite-assignment\n\nclass List {\n ghost var Contents: seq\n ghost var Repr: set\n\n var a: array\n var n: nat\n\n ghost predicate Valid()\n reads this, Repr\n ensures Valid() ==> this in Repr\n {\n this in Repr &&\n a in Repr &&\n n <= a.Length &&\n Contents == a[..n]\n }\n\n constructor Init()\n ensures Valid() && fresh(Repr)\n ensures Contents == []\n {\n Contents, n := [], 0;\n a := new T[0];\n Repr := {this, a};\n }\n\n method Add(t: T)\n requires Valid()\n modifies Repr\n ensures Valid() && fresh(Repr - old(Repr))\n ensures Contents == old(Contents) + [t]\n {\n if (n == a.Length) {\n var b := new T[2 * a.Length + 1](i requires 0 <= i reads this, a =>\n if i < a.Length then a[i] else t);\n assert b[..n] == a[..n] == Contents;\n a, Repr := b, Repr + {b};\n assert b[..n] == Contents;\n }\n a[n], n, Contents := t, n + 1, Contents + [t];\n }\n}\n\nclass Cell { var data: int }\n\niterator M(l: List, c: Cell) yields (x: T)\n requires l.Valid()\n reads l.Repr\n modifies c\n yield requires true\n yield ensures xs <= l.Contents // this is needed in order for the next line to be well-formed\n yield ensures x == l.Contents[|xs|-1]\n ensures xs == l.Contents\n{\n var i := 0;\n while i < l.n\n invariant i <= l.n && i == |xs| && xs <= l.Contents\n {\n if (*) { assert l.Valid(); } // this property is maintained, due to the reads clause\n if (*) {\n x := l.a[i]; yield; // or, equivalently, 'yield l.a[i]'\n i := i + 1;\n } else {\n x, i := l.a[i], i + 1;\n yield;\n }\n }\n}\n\nmethod Client(l: List, stop: T) returns (s: seq)\n requires l.Valid()\n{\n var c := new Cell;\n var iter := new M(l, c);\n s := [];\n while true\n invariant iter.Valid() && fresh(iter._new)\n invariant iter.xs <= l.Contents\n decreases |l.Contents| - |iter.xs|\n {\n var more := iter.MoveNext();\n if (!more) { break; }\n s := s + [iter.x];\n if (iter.x == stop) { return; } // if we ever see 'stop', then just end\n }\n}\n\nmethod PrintSequence(s: seq)\n{\n var i := 0;\n while i < |s|\n {\n print s[i], \" \";\n i := i + 1;\n }\n print \"\\n\";\n}\n\nmethod Main()\n{\n var myList := new List.Init();\n var i := 0;\n while i < 100\n invariant myList.Valid() && fresh(myList.Repr)\n {\n myList.Add(i);\n i := i + 2;\n }\n var s := Client(myList, 89);\n PrintSequence(s);\n s := Client(myList, 14);\n PrintSequence(s);\n}\n\n", "hints_removed": "// RUN: %testDafnyForEachCompiler --refresh-exit-code=0 \"%s\" -- --relax-definite-assignment\n\nclass List {\n ghost var Contents: seq\n ghost var Repr: set\n\n var a: array\n var n: nat\n\n ghost predicate Valid()\n reads this, Repr\n ensures Valid() ==> this in Repr\n {\n this in Repr &&\n a in Repr &&\n n <= a.Length &&\n Contents == a[..n]\n }\n\n constructor Init()\n ensures Valid() && fresh(Repr)\n ensures Contents == []\n {\n Contents, n := [], 0;\n a := new T[0];\n Repr := {this, a};\n }\n\n method Add(t: T)\n requires Valid()\n modifies Repr\n ensures Valid() && fresh(Repr - old(Repr))\n ensures Contents == old(Contents) + [t]\n {\n if (n == a.Length) {\n var b := new T[2 * a.Length + 1](i requires 0 <= i reads this, a =>\n if i < a.Length then a[i] else t);\n a, Repr := b, Repr + {b};\n }\n a[n], n, Contents := t, n + 1, Contents + [t];\n }\n}\n\nclass Cell { var data: int }\n\niterator M(l: List, c: Cell) yields (x: T)\n requires l.Valid()\n reads l.Repr\n modifies c\n yield requires true\n yield ensures xs <= l.Contents // this is needed in order for the next line to be well-formed\n yield ensures x == l.Contents[|xs|-1]\n ensures xs == l.Contents\n{\n var i := 0;\n while i < l.n\n {\n if (*) { assert l.Valid(); } // this property is maintained, due to the reads clause\n if (*) {\n x := l.a[i]; yield; // or, equivalently, 'yield l.a[i]'\n i := i + 1;\n } else {\n x, i := l.a[i], i + 1;\n yield;\n }\n }\n}\n\nmethod Client(l: List, stop: T) returns (s: seq)\n requires l.Valid()\n{\n var c := new Cell;\n var iter := new M(l, c);\n s := [];\n while true\n {\n var more := iter.MoveNext();\n if (!more) { break; }\n s := s + [iter.x];\n if (iter.x == stop) { return; } // if we ever see 'stop', then just end\n }\n}\n\nmethod PrintSequence(s: seq)\n{\n var i := 0;\n while i < |s|\n {\n print s[i], \" \";\n i := i + 1;\n }\n print \"\\n\";\n}\n\nmethod Main()\n{\n var myList := new List.Init();\n var i := 0;\n while i < 100\n {\n myList.Add(i);\n i := i + 2;\n }\n var s := Client(myList, 89);\n PrintSequence(s);\n s := Client(myList, 14);\n PrintSequence(s);\n}\n\n" }, { "test_ID": "319", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_from dafny main repo_dafny3_Streams.dfy", "ground_truth": "// RUN: %testDafnyForEachResolver \"%s\" -- --warn-deprecation:false\n\n\n// ----- Stream\n\ncodatatype Stream = Nil | Cons(head: T, tail: Stream)\n\nghost function append(M: Stream, N: Stream): Stream\n{\n match M\n case Nil => N\n case Cons(t, M') => Cons(t, append(M', N))\n}\n\n// ----- f, g, and maps\n\ntype X\n\nghost function f(x: X): X\nghost function g(x: X): X\n\nghost function map_f(M: Stream): Stream\n{\n match M\n case Nil => Nil\n case Cons(x, N) => Cons(f(x), map_f(N))\n}\n\nghost function map_g(M: Stream): Stream\n{\n match M\n case Nil => Nil\n case Cons(x, N) => Cons(g(x), map_g(N))\n}\n\nghost function map_fg(M: Stream): Stream\n{\n match M\n case Nil => Nil\n case Cons(x, N) => Cons(f(g(x)), map_fg(N))\n}\n\n// ----- Theorems\n\n// map (f * g) M = map f (map g M)\ngreatest lemma Theorem0(M: Stream)\n ensures map_fg(M) == map_f(map_g(M));\n{\n match (M) {\n case Nil =>\n case Cons(x, N) =>\n Theorem0(N);\n }\n}\ngreatest lemma Theorem0_Alt(M: Stream)\n ensures map_fg(M) == map_f(map_g(M));\n{\n if (M.Cons?) {\n Theorem0_Alt(M.tail);\n }\n}\nlemma Theorem0_Par(M: Stream)\n ensures map_fg(M) == map_f(map_g(M));\n{\n forall k: nat {\n Theorem0_Ind(k, M);\n }\n}\nlemma Theorem0_Ind(k: nat, M: Stream)\n ensures map_fg(M) ==#[k] map_f(map_g(M));\n{\n if (k != 0) {\n match (M) {\n case Nil =>\n case Cons(x, N) =>\n Theorem0_Ind(k-1, N);\n }\n }\n}\nlemma Theorem0_AutoInd(k: nat, M: Stream)\n ensures map_fg(M) ==#[k] map_f(map_g(M));\n{\n}\n\n// map f (append M N) = append (map f M) (map f N)\ngreatest lemma Theorem1(M: Stream, N: Stream)\n ensures map_f(append(M, N)) == append(map_f(M), map_f(N));\n{\n match (M) {\n case Nil =>\n case Cons(x, M') =>\n Theorem1(M', N);\n }\n}\ngreatest lemma Theorem1_Alt(M: Stream, N: Stream)\n ensures map_f(append(M, N)) == append(map_f(M), map_f(N));\n{\n if (M.Cons?) {\n Theorem1_Alt(M.tail, N);\n }\n}\nlemma Theorem1_Par(M: Stream, N: Stream)\n ensures map_f(append(M, N)) == append(map_f(M), map_f(N));\n{\n forall k: nat {\n Theorem1_Ind(k, M, N);\n }\n}\nlemma Theorem1_Ind(k: nat, M: Stream, N: Stream)\n ensures map_f(append(M, N)) ==#[k] append(map_f(M), map_f(N));\n{\n // this time, try doing the 'if' inside the 'match' (instead of the other way around)\n match (M) {\n case Nil =>\n case Cons(x, M') =>\n if (k != 0) {\n Theorem1_Ind(k-1, M', N);\n }\n }\n}\nlemma Theorem1_AutoInd(k: nat, M: Stream, N: Stream)\n ensures map_f(append(M, N)) ==#[k] append(map_f(M), map_f(N));\n{\n}\nlemma Theorem1_AutoForall()\n{\n // assert forall k: nat, M, N :: map_f(append(M, N)) ==#[k] append(map_f(M), map_f(N)); // TODO: this is not working yet, apparently\n}\n\n// append NIL M = M\nlemma Theorem2(M: Stream)\n ensures append(Nil, M) == M;\n{\n // trivial\n}\n\n// append M NIL = M\ngreatest lemma Theorem3(M: Stream)\n ensures append(M, Nil) == M;\n{\n match (M) {\n case Nil =>\n case Cons(x, N) =>\n Theorem3(N);\n }\n}\ngreatest lemma Theorem3_Alt(M: Stream)\n ensures append(M, Nil) == M;\n{\n if (M.Cons?) {\n Theorem3_Alt(M.tail);\n }\n}\n\n// append M (append N P) = append (append M N) P\ngreatest lemma Theorem4(M: Stream, N: Stream, P: Stream)\n ensures append(M, append(N, P)) == append(append(M, N), P);\n{\n match (M) {\n case Nil =>\n case Cons(x, M') =>\n Theorem4(M', N, P);\n }\n}\ngreatest lemma Theorem4_Alt(M: Stream, N: Stream, P: Stream)\n ensures append(M, append(N, P)) == append(append(M, N), P);\n{\n if (M.Cons?) {\n Theorem4_Alt(M.tail, N, P);\n }\n}\n\n// ----- Flatten\n\n// Flatten can't be written as just:\n//\n// function SimpleFlatten(M: Stream): Stream\n// {\n// match M\n// case Nil => Nil\n// case Cons(s, N) => append(s, SimpleFlatten(N))\n// }\n//\n// because this function fails to be productive given an infinite stream of Nil's.\n// Instead, here are two variations of SimpleFlatten. The first variation (FlattenStartMarker)\n// prepends a \"startMarker\" to each of the streams in \"M\". The other (FlattenNonEmpties)\n// insists that \"M\" contain no empty streams. One can prove a theorem that relates these\n// two versions.\n\n// This first variation of Flatten returns a stream of the streams in M, each preceded with\n// \"startMarker\".\n\nghost function FlattenStartMarker(M: Stream, startMarker: T): Stream\n{\n PrependThenFlattenStartMarker(Nil, M, startMarker)\n}\n\nghost function PrependThenFlattenStartMarker(prefix: Stream, M: Stream, startMarker: T): Stream\n{\n match prefix\n case Cons(hd, tl) =>\n Cons(hd, PrependThenFlattenStartMarker(tl, M, startMarker))\n case Nil =>\n match M\n case Nil => Nil\n case Cons(s, N) => Cons(startMarker, PrependThenFlattenStartMarker(s, N, startMarker))\n}\n\n// The next variation of Flatten requires M to contain no empty streams.\n\ngreatest predicate StreamOfNonEmpties(M: Stream)\n{\n match M\n case Nil => true\n case Cons(s, N) => s.Cons? && StreamOfNonEmpties(N)\n}\n\nghost function FlattenNonEmpties(M: Stream): Stream\n requires StreamOfNonEmpties(M);\n{\n PrependThenFlattenNonEmpties(Nil, M)\n}\n\nghost function PrependThenFlattenNonEmpties(prefix: Stream, M: Stream): Stream\n requires StreamOfNonEmpties(M);\n{\n match prefix\n case Cons(hd, tl) =>\n Cons(hd, PrependThenFlattenNonEmpties(tl, M))\n case Nil =>\n match M\n case Nil => Nil\n case Cons(s, N) => Cons(s.head, PrependThenFlattenNonEmpties(s.tail, N))\n}\n\n// We can prove a theorem that links the previous two variations of flatten. To\n// do that, we first define a function that prepends an element to each stream\n// of a given stream of streams.\n\nghost function Prepend(x: T, M: Stream): Stream\n{\n match M\n case Nil => Nil\n case Cons(s, N) => Cons(Cons(x, s), Prepend(x, N))\n}\n\ngreatest lemma Prepend_Lemma(x: T, M: Stream)\n ensures StreamOfNonEmpties(Prepend(x, M));\n{\n match M {\n case Nil =>\n case Cons(s, N) => Prepend_Lemma(x, N);\n }\n}\n\nlemma Theorem_Flatten(M: Stream, startMarker: T)\n ensures\n StreamOfNonEmpties(Prepend(startMarker, M)) ==> // always holds, on account of Prepend_Lemma;\n // but until (co-)method can be called from functions,\n // this condition is used as an antecedent here\n FlattenStartMarker(M, startMarker) == FlattenNonEmpties(Prepend(startMarker, M));\n{\n Prepend_Lemma(startMarker, M);\n Lemma_Flatten(Nil, M, startMarker);\n}\n\ngreatest lemma Lemma_Flatten(prefix: Stream, M: Stream, startMarker: T)\n ensures\n StreamOfNonEmpties(Prepend(startMarker, M)) ==> // always holds, on account of Prepend_Lemma;\n // but until (co-)method can be called from functions,\n // this condition is used as an antecedent here\n PrependThenFlattenStartMarker(prefix, M, startMarker) == PrependThenFlattenNonEmpties(prefix, Prepend(startMarker, M));\n{\n Prepend_Lemma(startMarker, M);\n match (prefix) {\n case Cons(hd, tl) =>\n Lemma_Flatten(tl, M, startMarker);\n case Nil =>\n match (M) {\n case Nil =>\n case Cons(s, N) =>\n if (*) {\n // This is all that's needed for the proof\n Lemma_Flatten(s, N, startMarker);\n } else {\n // ...but here are some calculations that try to show more of what's going on\n // (It would be nice to have ==#[...] available as an operator in calculations.)\n\n // massage the LHS:\n calc {\n PrependThenFlattenStartMarker(prefix, M, startMarker);\n == // def. PrependThenFlattenStartMarker\n Cons(startMarker, PrependThenFlattenStartMarker(s, N, startMarker));\n }\n // massage the RHS:\n calc {\n PrependThenFlattenNonEmpties(prefix, Prepend(startMarker, M));\n == // M == Cons(s, N)\n PrependThenFlattenNonEmpties(prefix, Prepend(startMarker, Cons(s, N)));\n == // def. Prepend\n PrependThenFlattenNonEmpties(prefix, Cons(Cons(startMarker, s), Prepend(startMarker, N)));\n == // def. PrependThenFlattenNonEmpties\n Cons(Cons(startMarker, s).head, PrependThenFlattenNonEmpties(Cons(startMarker, s).tail, Prepend(startMarker, N)));\n == // Cons, head, tail\n Cons(startMarker, PrependThenFlattenNonEmpties(s, Prepend(startMarker, N)));\n }\n\n // all together now:\n calc {\n PrependThenFlattenStartMarker(prefix, M, startMarker) ==#[_k] PrependThenFlattenNonEmpties(prefix, Prepend(startMarker, M));\n { // by the calculation above, we have:\n assert PrependThenFlattenStartMarker(prefix, M, startMarker) == Cons(startMarker, PrependThenFlattenStartMarker(s, N, startMarker)); }\n Cons(startMarker, PrependThenFlattenStartMarker(s, N, startMarker)) ==#[_k] PrependThenFlattenNonEmpties(prefix, Prepend(startMarker, M));\n { // and by the other calculation above, we have:\n assert PrependThenFlattenNonEmpties(prefix, Prepend(startMarker, M)) == Cons(startMarker, PrependThenFlattenNonEmpties(s, Prepend(startMarker, N))); }\n Cons(startMarker, PrependThenFlattenStartMarker(s, N, startMarker)) ==#[_k] Cons(startMarker, PrependThenFlattenNonEmpties(s, Prepend(startMarker, N)));\n == // def. of ==#[_k] for _k != 0\n startMarker == startMarker &&\n PrependThenFlattenStartMarker(s, N, startMarker) ==#[_k-1] PrependThenFlattenNonEmpties(s, Prepend(startMarker, N));\n { Lemma_Flatten(s, N, startMarker);\n // the postcondition of the call we just made (which invokes the co-induction hypothesis) is:\n assert PrependThenFlattenStartMarker(s, N, startMarker) ==#[_k-1] PrependThenFlattenNonEmpties(s, Prepend(startMarker, N));\n }\n true;\n }\n }\n }\n }\n}\n\ngreatest lemma Lemma_FlattenAppend0(s: Stream, M: Stream, startMarker: T)\n ensures PrependThenFlattenStartMarker(s, M, startMarker) == append(s, PrependThenFlattenStartMarker(Nil, M, startMarker));\n{\n match (s) {\n case Nil =>\n case Cons(hd, tl) =>\n Lemma_FlattenAppend0(tl, M, startMarker);\n }\n}\n\ngreatest lemma Lemma_FlattenAppend1(s: Stream, M: Stream)\n requires StreamOfNonEmpties(M);\n ensures PrependThenFlattenNonEmpties(s, M) == append(s, PrependThenFlattenNonEmpties(Nil, M));\n{\n match (s) {\n case Nil =>\n case Cons(hd, tl) =>\n Lemma_FlattenAppend1(tl, M);\n }\n}\n\n", "hints_removed": "// RUN: %testDafnyForEachResolver \"%s\" -- --warn-deprecation:false\n\n\n// ----- Stream\n\ncodatatype Stream = Nil | Cons(head: T, tail: Stream)\n\nghost function append(M: Stream, N: Stream): Stream\n{\n match M\n case Nil => N\n case Cons(t, M') => Cons(t, append(M', N))\n}\n\n// ----- f, g, and maps\n\ntype X\n\nghost function f(x: X): X\nghost function g(x: X): X\n\nghost function map_f(M: Stream): Stream\n{\n match M\n case Nil => Nil\n case Cons(x, N) => Cons(f(x), map_f(N))\n}\n\nghost function map_g(M: Stream): Stream\n{\n match M\n case Nil => Nil\n case Cons(x, N) => Cons(g(x), map_g(N))\n}\n\nghost function map_fg(M: Stream): Stream\n{\n match M\n case Nil => Nil\n case Cons(x, N) => Cons(f(g(x)), map_fg(N))\n}\n\n// ----- Theorems\n\n// map (f * g) M = map f (map g M)\ngreatest lemma Theorem0(M: Stream)\n ensures map_fg(M) == map_f(map_g(M));\n{\n match (M) {\n case Nil =>\n case Cons(x, N) =>\n Theorem0(N);\n }\n}\ngreatest lemma Theorem0_Alt(M: Stream)\n ensures map_fg(M) == map_f(map_g(M));\n{\n if (M.Cons?) {\n Theorem0_Alt(M.tail);\n }\n}\nlemma Theorem0_Par(M: Stream)\n ensures map_fg(M) == map_f(map_g(M));\n{\n forall k: nat {\n Theorem0_Ind(k, M);\n }\n}\nlemma Theorem0_Ind(k: nat, M: Stream)\n ensures map_fg(M) ==#[k] map_f(map_g(M));\n{\n if (k != 0) {\n match (M) {\n case Nil =>\n case Cons(x, N) =>\n Theorem0_Ind(k-1, N);\n }\n }\n}\nlemma Theorem0_AutoInd(k: nat, M: Stream)\n ensures map_fg(M) ==#[k] map_f(map_g(M));\n{\n}\n\n// map f (append M N) = append (map f M) (map f N)\ngreatest lemma Theorem1(M: Stream, N: Stream)\n ensures map_f(append(M, N)) == append(map_f(M), map_f(N));\n{\n match (M) {\n case Nil =>\n case Cons(x, M') =>\n Theorem1(M', N);\n }\n}\ngreatest lemma Theorem1_Alt(M: Stream, N: Stream)\n ensures map_f(append(M, N)) == append(map_f(M), map_f(N));\n{\n if (M.Cons?) {\n Theorem1_Alt(M.tail, N);\n }\n}\nlemma Theorem1_Par(M: Stream, N: Stream)\n ensures map_f(append(M, N)) == append(map_f(M), map_f(N));\n{\n forall k: nat {\n Theorem1_Ind(k, M, N);\n }\n}\nlemma Theorem1_Ind(k: nat, M: Stream, N: Stream)\n ensures map_f(append(M, N)) ==#[k] append(map_f(M), map_f(N));\n{\n // this time, try doing the 'if' inside the 'match' (instead of the other way around)\n match (M) {\n case Nil =>\n case Cons(x, M') =>\n if (k != 0) {\n Theorem1_Ind(k-1, M', N);\n }\n }\n}\nlemma Theorem1_AutoInd(k: nat, M: Stream, N: Stream)\n ensures map_f(append(M, N)) ==#[k] append(map_f(M), map_f(N));\n{\n}\nlemma Theorem1_AutoForall()\n{\n // assert forall k: nat, M, N :: map_f(append(M, N)) ==#[k] append(map_f(M), map_f(N)); // TODO: this is not working yet, apparently\n}\n\n// append NIL M = M\nlemma Theorem2(M: Stream)\n ensures append(Nil, M) == M;\n{\n // trivial\n}\n\n// append M NIL = M\ngreatest lemma Theorem3(M: Stream)\n ensures append(M, Nil) == M;\n{\n match (M) {\n case Nil =>\n case Cons(x, N) =>\n Theorem3(N);\n }\n}\ngreatest lemma Theorem3_Alt(M: Stream)\n ensures append(M, Nil) == M;\n{\n if (M.Cons?) {\n Theorem3_Alt(M.tail);\n }\n}\n\n// append M (append N P) = append (append M N) P\ngreatest lemma Theorem4(M: Stream, N: Stream, P: Stream)\n ensures append(M, append(N, P)) == append(append(M, N), P);\n{\n match (M) {\n case Nil =>\n case Cons(x, M') =>\n Theorem4(M', N, P);\n }\n}\ngreatest lemma Theorem4_Alt(M: Stream, N: Stream, P: Stream)\n ensures append(M, append(N, P)) == append(append(M, N), P);\n{\n if (M.Cons?) {\n Theorem4_Alt(M.tail, N, P);\n }\n}\n\n// ----- Flatten\n\n// Flatten can't be written as just:\n//\n// function SimpleFlatten(M: Stream): Stream\n// {\n// match M\n// case Nil => Nil\n// case Cons(s, N) => append(s, SimpleFlatten(N))\n// }\n//\n// because this function fails to be productive given an infinite stream of Nil's.\n// Instead, here are two variations of SimpleFlatten. The first variation (FlattenStartMarker)\n// prepends a \"startMarker\" to each of the streams in \"M\". The other (FlattenNonEmpties)\n// insists that \"M\" contain no empty streams. One can prove a theorem that relates these\n// two versions.\n\n// This first variation of Flatten returns a stream of the streams in M, each preceded with\n// \"startMarker\".\n\nghost function FlattenStartMarker(M: Stream, startMarker: T): Stream\n{\n PrependThenFlattenStartMarker(Nil, M, startMarker)\n}\n\nghost function PrependThenFlattenStartMarker(prefix: Stream, M: Stream, startMarker: T): Stream\n{\n match prefix\n case Cons(hd, tl) =>\n Cons(hd, PrependThenFlattenStartMarker(tl, M, startMarker))\n case Nil =>\n match M\n case Nil => Nil\n case Cons(s, N) => Cons(startMarker, PrependThenFlattenStartMarker(s, N, startMarker))\n}\n\n// The next variation of Flatten requires M to contain no empty streams.\n\ngreatest predicate StreamOfNonEmpties(M: Stream)\n{\n match M\n case Nil => true\n case Cons(s, N) => s.Cons? && StreamOfNonEmpties(N)\n}\n\nghost function FlattenNonEmpties(M: Stream): Stream\n requires StreamOfNonEmpties(M);\n{\n PrependThenFlattenNonEmpties(Nil, M)\n}\n\nghost function PrependThenFlattenNonEmpties(prefix: Stream, M: Stream): Stream\n requires StreamOfNonEmpties(M);\n{\n match prefix\n case Cons(hd, tl) =>\n Cons(hd, PrependThenFlattenNonEmpties(tl, M))\n case Nil =>\n match M\n case Nil => Nil\n case Cons(s, N) => Cons(s.head, PrependThenFlattenNonEmpties(s.tail, N))\n}\n\n// We can prove a theorem that links the previous two variations of flatten. To\n// do that, we first define a function that prepends an element to each stream\n// of a given stream of streams.\n\nghost function Prepend(x: T, M: Stream): Stream\n{\n match M\n case Nil => Nil\n case Cons(s, N) => Cons(Cons(x, s), Prepend(x, N))\n}\n\ngreatest lemma Prepend_Lemma(x: T, M: Stream)\n ensures StreamOfNonEmpties(Prepend(x, M));\n{\n match M {\n case Nil =>\n case Cons(s, N) => Prepend_Lemma(x, N);\n }\n}\n\nlemma Theorem_Flatten(M: Stream, startMarker: T)\n ensures\n StreamOfNonEmpties(Prepend(startMarker, M)) ==> // always holds, on account of Prepend_Lemma;\n // but until (co-)method can be called from functions,\n // this condition is used as an antecedent here\n FlattenStartMarker(M, startMarker) == FlattenNonEmpties(Prepend(startMarker, M));\n{\n Prepend_Lemma(startMarker, M);\n Lemma_Flatten(Nil, M, startMarker);\n}\n\ngreatest lemma Lemma_Flatten(prefix: Stream, M: Stream, startMarker: T)\n ensures\n StreamOfNonEmpties(Prepend(startMarker, M)) ==> // always holds, on account of Prepend_Lemma;\n // but until (co-)method can be called from functions,\n // this condition is used as an antecedent here\n PrependThenFlattenStartMarker(prefix, M, startMarker) == PrependThenFlattenNonEmpties(prefix, Prepend(startMarker, M));\n{\n Prepend_Lemma(startMarker, M);\n match (prefix) {\n case Cons(hd, tl) =>\n Lemma_Flatten(tl, M, startMarker);\n case Nil =>\n match (M) {\n case Nil =>\n case Cons(s, N) =>\n if (*) {\n // This is all that's needed for the proof\n Lemma_Flatten(s, N, startMarker);\n } else {\n // ...but here are some calculations that try to show more of what's going on\n // (It would be nice to have ==#[...] available as an operator in calculations.)\n\n // massage the LHS:\n calc {\n PrependThenFlattenStartMarker(prefix, M, startMarker);\n == // def. PrependThenFlattenStartMarker\n Cons(startMarker, PrependThenFlattenStartMarker(s, N, startMarker));\n }\n // massage the RHS:\n calc {\n PrependThenFlattenNonEmpties(prefix, Prepend(startMarker, M));\n == // M == Cons(s, N)\n PrependThenFlattenNonEmpties(prefix, Prepend(startMarker, Cons(s, N)));\n == // def. Prepend\n PrependThenFlattenNonEmpties(prefix, Cons(Cons(startMarker, s), Prepend(startMarker, N)));\n == // def. PrependThenFlattenNonEmpties\n Cons(Cons(startMarker, s).head, PrependThenFlattenNonEmpties(Cons(startMarker, s).tail, Prepend(startMarker, N)));\n == // Cons, head, tail\n Cons(startMarker, PrependThenFlattenNonEmpties(s, Prepend(startMarker, N)));\n }\n\n // all together now:\n calc {\n PrependThenFlattenStartMarker(prefix, M, startMarker) ==#[_k] PrependThenFlattenNonEmpties(prefix, Prepend(startMarker, M));\n { // by the calculation above, we have:\n Cons(startMarker, PrependThenFlattenStartMarker(s, N, startMarker)) ==#[_k] PrependThenFlattenNonEmpties(prefix, Prepend(startMarker, M));\n { // and by the other calculation above, we have:\n Cons(startMarker, PrependThenFlattenStartMarker(s, N, startMarker)) ==#[_k] Cons(startMarker, PrependThenFlattenNonEmpties(s, Prepend(startMarker, N)));\n == // def. of ==#[_k] for _k != 0\n startMarker == startMarker &&\n PrependThenFlattenStartMarker(s, N, startMarker) ==#[_k-1] PrependThenFlattenNonEmpties(s, Prepend(startMarker, N));\n { Lemma_Flatten(s, N, startMarker);\n // the postcondition of the call we just made (which invokes the co-induction hypothesis) is:\n }\n true;\n }\n }\n }\n }\n}\n\ngreatest lemma Lemma_FlattenAppend0(s: Stream, M: Stream, startMarker: T)\n ensures PrependThenFlattenStartMarker(s, M, startMarker) == append(s, PrependThenFlattenStartMarker(Nil, M, startMarker));\n{\n match (s) {\n case Nil =>\n case Cons(hd, tl) =>\n Lemma_FlattenAppend0(tl, M, startMarker);\n }\n}\n\ngreatest lemma Lemma_FlattenAppend1(s: Stream, M: Stream)\n requires StreamOfNonEmpties(M);\n ensures PrependThenFlattenNonEmpties(s, M) == append(s, PrependThenFlattenNonEmpties(Nil, M));\n{\n match (s) {\n case Nil =>\n case Cons(hd, tl) =>\n Lemma_FlattenAppend1(tl, M);\n }\n}\n\n" }, { "test_ID": "320", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_from dafny main repo_dafny4_ACL2-extractor.dfy", "ground_truth": "// RUN: %dafny /compile:0 /deprecation:0 /proverOpt:O:smt.qi.eager_threshold=30 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// This is the Extractor Problem from section 11.8 of the ACL2 book,\n// \"Computer-Aided Reasoning: An Approach\" by Kaufmann, Manolios, and\n// Moore (2011 edition).\n\ndatatype List = Nil | Cons(head: T, tail: List)\n\nghost function length(xs: List): nat\n{\n match xs\n case Nil => 0\n case Cons(_, rest) => 1 + length(rest)\n}\n\n// If \"0 <= n < length(xs)\", then return the element of \"xs\" that is preceded by\n// \"n\" elements; otherwise, return an arbitrary value.\nghost opaque function nth(n: int, xs: List): T\n{\n if 0 <= n < length(xs) then\n nthWorker(n, xs)\n else\n var t :| true; t\n}\n\nghost function nthWorker(n: int, xs: List): T\n requires 0 <= n < length(xs);\n{\n if n == 0 then xs.head else nthWorker(n-1, xs.tail)\n}\n\nghost function append(xs: List, ys: List): List\n{\n match xs\n case Nil => ys\n case Cons(x, rest) => Cons(x, append(rest, ys))\n}\n\nghost function rev(xs: List): List\n{\n match xs\n case Nil => Nil\n case Cons(x, rest) => append(rev(rest), Cons(x, Nil))\n}\n\nghost function nats(n: nat): List\n{\n if n == 0 then Nil else Cons(n-1, nats(n-1))\n}\n\nghost function xtr(mp: List, lst: List): List\n{\n match mp\n case Nil => Nil\n case Cons(n, rest) => Cons(nth(n, lst), xtr(rest, lst))\n}\n\nlemma ExtractorTheorem(xs: List)\n ensures xtr(nats(length(xs)), xs) == rev(xs);\n{\n var a, b := xtr(nats(length(xs)), xs), rev(xs);\n calc {\n length(a);\n { XtrLength(nats(length(xs)), xs); }\n length(nats(length(xs)));\n { NatsLength(length(xs)); }\n length(xs);\n }\n calc {\n length(xs);\n { RevLength(xs); }\n length(b);\n }\n forall i | 0 <= i < length(xs)\n ensures nth(i, a) == nth(i, b);\n {\n reveal nth();\n ExtractorLemma(i, xs);\n }\n EqualElementsMakeEqualLists(a, b);\n}\n\n// auxiliary lemmas and proofs follow\n\n// lemmas about length\n\nlemma XtrLength(mp: List, lst: List)\n ensures length(xtr(mp, lst)) == length(mp);\n{\n}\n\nlemma NatsLength(n: nat)\n ensures length(nats(n)) == n;\n{\n}\n\nlemma AppendLength(xs: List, ys: List)\n ensures length(append(xs, ys)) == length(xs) + length(ys);\n{\n}\n\nlemma RevLength(xs: List)\n ensures length(rev(xs)) == length(xs);\n{\n match xs {\n case Nil =>\n case Cons(x, rest) =>\n calc {\n length(append(rev(rest), Cons(x, Nil)));\n { AppendLength(rev(rest), Cons(x, Nil)); }\n length(rev(rest)) + length(Cons(x, Nil));\n length(rev(rest)) + 1;\n }\n }\n}\n\n// you can prove two lists equal by proving their elements equal\n\nlemma EqualElementsMakeEqualLists(xs: List, ys: List)\n requires length(xs) == length(ys)\n requires forall i :: 0 <= i < length(xs) ==> nth(i, xs) == nth(i, ys)\n ensures xs == ys\n{\n reveal nth();\n match xs {\n case Nil =>\n case Cons(x, rest) =>\n assert nth(0, xs) == nth(0, ys);\n forall i | 0 <= i < length(xs.tail)\n {\n calc {\n nth(i, xs.tail) == nth(i, ys.tail);\n nth(i+1, Cons(xs.head, xs.tail)) == nth(i+1, Cons(ys.head, ys.tail));\n nth(i+1, xs) == nth(i+1, ys);\n }\n }\n // EqualElementsMakeEqualLists(xs.tail, ys.tail);\n }\n}\n\n// here is the theorem, but applied to the ith element\n\nlemma {:vcs_split_on_every_assert} ExtractorLemma(i: int, xs: List)\n requires 0 <= i < length(xs);\n ensures nth(i, xtr(nats(length(xs)), xs)) == nth(i, rev(xs));\n{\n calc {\n nth(i, xtr(nats(length(xs)), xs));\n { NatsLength(length(xs));\n NthXtr(i, nats(length(xs)), xs); }\n nth(nth(i, nats(length(xs))), xs);\n { NthNats(i, length(xs)); }\n nth(length(xs) - 1 - i, xs);\n { reveal nth(); RevLength(xs); NthRev(i, xs); }\n nth(i, rev(xs));\n }\n}\n\n// lemmas about what nth gives on certain lists\n\nlemma NthXtr(i: int, mp: List, lst: List)\n requires 0 <= i < length(mp);\n ensures nth(i, xtr(mp, lst)) == nth(nth(i, mp), lst);\n{\n reveal nth();\n XtrLength(mp, lst);\n assert nth(i, xtr(mp, lst)) == nthWorker(i, xtr(mp, lst));\n if i == 0 {\n } else {\n calc {\n nth(i-1, xtr(mp, lst).tail);\n // def. xtr\n nth(i-1, xtr(mp.tail, lst));\n { NthXtr(i-1, mp.tail, lst); }\n nth(nth(i-1, mp.tail), lst);\n }\n }\n}\n\nlemma NthNats(i: int, n: nat)\n requires 0 <= i < n;\n ensures nth(i, nats(n)) == n - 1 - i;\n{\n reveal nth();\n NatsLength(n);\n NthNatsWorker(i, n);\n}\n\nlemma NthNatsWorker(i: int, n: nat)\n requires 0 <= i < n && length(nats(n)) == n;\n ensures nthWorker(i, nats(n)) == n - 1 - i;\n{\n}\n\nlemma NthRev(i: int, xs: List)\n requires 0 <= i < length(xs) == length(rev(xs));\n ensures nthWorker(i, rev(xs)) == nthWorker(length(xs) - 1 - i, xs);\n{\n reveal nth();\n assert xs.Cons?;\n assert 1 <= length(rev(xs)) && rev(xs).Cons?;\n RevLength(xs.tail);\n if i < length(rev(xs.tail)) {\n calc {\n nth(i, rev(xs));\n nthWorker(i, rev(xs));\n // def. rev\n nthWorker(i, append(rev(xs.tail), Cons(xs.head, Nil)));\n { NthAppendA(i, rev(xs.tail), Cons(xs.head, Nil)); }\n nthWorker(i, rev(xs.tail));\n { NthRev(i, xs.tail); } // induction hypothesis\n nthWorker(length(xs.tail) - 1 - i, xs.tail);\n // def. nthWorker\n nthWorker(length(xs.tail) - 1 - i + 1, xs);\n nthWorker(length(xs) - 1 - i, xs);\n }\n } else {\n assert i == length(rev(xs.tail));\n calc {\n nth(i, rev(xs));\n nthWorker(i, rev(xs));\n // def. rev\n nthWorker(i, append(rev(xs.tail), Cons(xs.head, Nil)));\n { NthAppendB(i, rev(xs.tail), Cons(xs.head, Nil)); }\n nthWorker(i - length(rev(xs.tail)), Cons(xs.head, Nil));\n nthWorker(0, Cons(xs.head, Nil));\n nthWorker(0, xs);\n nthWorker(length(xs) - 1 - length(xs.tail), xs);\n { RevLength(xs.tail); }\n nthWorker(length(xs) - 1 - length(rev(xs.tail)), xs);\n nth(length(xs) - 1 - length(rev(xs.tail)), xs);\n nth(length(xs) - 1 - i, xs);\n }\n }\n}\n\nlemma NthAppendA(i: int, xs: List, ys: List)\n requires 0 <= i < length(xs);\n ensures nth(i, append(xs, ys)) == nth(i, xs);\n{\n reveal nth();\n if i == 0 {\n calc {\n nth(0, append(xs, ys));\n nth(0, Cons(xs.head, append(xs.tail, ys)));\n xs.head;\n }\n } else {\n calc {\n nth(i, append(xs, ys));\n nth(i, Cons(xs.head, append(xs.tail, ys)));\n nth(i-1, append(xs.tail, ys));\n { NthAppendA(i-1, xs.tail, ys); }\n nth(i-1, xs.tail);\n }\n }\n}\n\nlemma NthAppendB(i: int, xs: List, ys: List)\n requires length(xs) <= i < length(xs) + length(ys);\n ensures nth(i, append(xs, ys)) == nth(i - length(xs), ys);\n{\n reveal nth();\n AppendLength(xs, ys);\n match xs {\n case Nil =>\n assert nth(i, append(xs, ys)) == nth(i, ys);\n case Cons(x, rest) =>\n calc {\n nth(i, append(xs, ys));\n nth(i, append(Cons(x, rest), ys));\n // def. append\n nth(i, Cons(x, append(rest, ys)));\n nth(i-1, append(rest, ys));\n { NthAppendB(i-1, rest, ys); }\n nth(i-1 - length(rest), ys);\n }\n }\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 /deprecation:0 /proverOpt:O:smt.qi.eager_threshold=30 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// This is the Extractor Problem from section 11.8 of the ACL2 book,\n// \"Computer-Aided Reasoning: An Approach\" by Kaufmann, Manolios, and\n// Moore (2011 edition).\n\ndatatype List = Nil | Cons(head: T, tail: List)\n\nghost function length(xs: List): nat\n{\n match xs\n case Nil => 0\n case Cons(_, rest) => 1 + length(rest)\n}\n\n// If \"0 <= n < length(xs)\", then return the element of \"xs\" that is preceded by\n// \"n\" elements; otherwise, return an arbitrary value.\nghost opaque function nth(n: int, xs: List): T\n{\n if 0 <= n < length(xs) then\n nthWorker(n, xs)\n else\n var t :| true; t\n}\n\nghost function nthWorker(n: int, xs: List): T\n requires 0 <= n < length(xs);\n{\n if n == 0 then xs.head else nthWorker(n-1, xs.tail)\n}\n\nghost function append(xs: List, ys: List): List\n{\n match xs\n case Nil => ys\n case Cons(x, rest) => Cons(x, append(rest, ys))\n}\n\nghost function rev(xs: List): List\n{\n match xs\n case Nil => Nil\n case Cons(x, rest) => append(rev(rest), Cons(x, Nil))\n}\n\nghost function nats(n: nat): List\n{\n if n == 0 then Nil else Cons(n-1, nats(n-1))\n}\n\nghost function xtr(mp: List, lst: List): List\n{\n match mp\n case Nil => Nil\n case Cons(n, rest) => Cons(nth(n, lst), xtr(rest, lst))\n}\n\nlemma ExtractorTheorem(xs: List)\n ensures xtr(nats(length(xs)), xs) == rev(xs);\n{\n var a, b := xtr(nats(length(xs)), xs), rev(xs);\n calc {\n length(a);\n { XtrLength(nats(length(xs)), xs); }\n length(nats(length(xs)));\n { NatsLength(length(xs)); }\n length(xs);\n }\n calc {\n length(xs);\n { RevLength(xs); }\n length(b);\n }\n forall i | 0 <= i < length(xs)\n ensures nth(i, a) == nth(i, b);\n {\n reveal nth();\n ExtractorLemma(i, xs);\n }\n EqualElementsMakeEqualLists(a, b);\n}\n\n// auxiliary lemmas and proofs follow\n\n// lemmas about length\n\nlemma XtrLength(mp: List, lst: List)\n ensures length(xtr(mp, lst)) == length(mp);\n{\n}\n\nlemma NatsLength(n: nat)\n ensures length(nats(n)) == n;\n{\n}\n\nlemma AppendLength(xs: List, ys: List)\n ensures length(append(xs, ys)) == length(xs) + length(ys);\n{\n}\n\nlemma RevLength(xs: List)\n ensures length(rev(xs)) == length(xs);\n{\n match xs {\n case Nil =>\n case Cons(x, rest) =>\n calc {\n length(append(rev(rest), Cons(x, Nil)));\n { AppendLength(rev(rest), Cons(x, Nil)); }\n length(rev(rest)) + length(Cons(x, Nil));\n length(rev(rest)) + 1;\n }\n }\n}\n\n// you can prove two lists equal by proving their elements equal\n\nlemma EqualElementsMakeEqualLists(xs: List, ys: List)\n requires length(xs) == length(ys)\n requires forall i :: 0 <= i < length(xs) ==> nth(i, xs) == nth(i, ys)\n ensures xs == ys\n{\n reveal nth();\n match xs {\n case Nil =>\n case Cons(x, rest) =>\n forall i | 0 <= i < length(xs.tail)\n {\n calc {\n nth(i, xs.tail) == nth(i, ys.tail);\n nth(i+1, Cons(xs.head, xs.tail)) == nth(i+1, Cons(ys.head, ys.tail));\n nth(i+1, xs) == nth(i+1, ys);\n }\n }\n // EqualElementsMakeEqualLists(xs.tail, ys.tail);\n }\n}\n\n// here is the theorem, but applied to the ith element\n\nlemma {:vcs_split_on_every_assert} ExtractorLemma(i: int, xs: List)\n requires 0 <= i < length(xs);\n ensures nth(i, xtr(nats(length(xs)), xs)) == nth(i, rev(xs));\n{\n calc {\n nth(i, xtr(nats(length(xs)), xs));\n { NatsLength(length(xs));\n NthXtr(i, nats(length(xs)), xs); }\n nth(nth(i, nats(length(xs))), xs);\n { NthNats(i, length(xs)); }\n nth(length(xs) - 1 - i, xs);\n { reveal nth(); RevLength(xs); NthRev(i, xs); }\n nth(i, rev(xs));\n }\n}\n\n// lemmas about what nth gives on certain lists\n\nlemma NthXtr(i: int, mp: List, lst: List)\n requires 0 <= i < length(mp);\n ensures nth(i, xtr(mp, lst)) == nth(nth(i, mp), lst);\n{\n reveal nth();\n XtrLength(mp, lst);\n if i == 0 {\n } else {\n calc {\n nth(i-1, xtr(mp, lst).tail);\n // def. xtr\n nth(i-1, xtr(mp.tail, lst));\n { NthXtr(i-1, mp.tail, lst); }\n nth(nth(i-1, mp.tail), lst);\n }\n }\n}\n\nlemma NthNats(i: int, n: nat)\n requires 0 <= i < n;\n ensures nth(i, nats(n)) == n - 1 - i;\n{\n reveal nth();\n NatsLength(n);\n NthNatsWorker(i, n);\n}\n\nlemma NthNatsWorker(i: int, n: nat)\n requires 0 <= i < n && length(nats(n)) == n;\n ensures nthWorker(i, nats(n)) == n - 1 - i;\n{\n}\n\nlemma NthRev(i: int, xs: List)\n requires 0 <= i < length(xs) == length(rev(xs));\n ensures nthWorker(i, rev(xs)) == nthWorker(length(xs) - 1 - i, xs);\n{\n reveal nth();\n RevLength(xs.tail);\n if i < length(rev(xs.tail)) {\n calc {\n nth(i, rev(xs));\n nthWorker(i, rev(xs));\n // def. rev\n nthWorker(i, append(rev(xs.tail), Cons(xs.head, Nil)));\n { NthAppendA(i, rev(xs.tail), Cons(xs.head, Nil)); }\n nthWorker(i, rev(xs.tail));\n { NthRev(i, xs.tail); } // induction hypothesis\n nthWorker(length(xs.tail) - 1 - i, xs.tail);\n // def. nthWorker\n nthWorker(length(xs.tail) - 1 - i + 1, xs);\n nthWorker(length(xs) - 1 - i, xs);\n }\n } else {\n calc {\n nth(i, rev(xs));\n nthWorker(i, rev(xs));\n // def. rev\n nthWorker(i, append(rev(xs.tail), Cons(xs.head, Nil)));\n { NthAppendB(i, rev(xs.tail), Cons(xs.head, Nil)); }\n nthWorker(i - length(rev(xs.tail)), Cons(xs.head, Nil));\n nthWorker(0, Cons(xs.head, Nil));\n nthWorker(0, xs);\n nthWorker(length(xs) - 1 - length(xs.tail), xs);\n { RevLength(xs.tail); }\n nthWorker(length(xs) - 1 - length(rev(xs.tail)), xs);\n nth(length(xs) - 1 - length(rev(xs.tail)), xs);\n nth(length(xs) - 1 - i, xs);\n }\n }\n}\n\nlemma NthAppendA(i: int, xs: List, ys: List)\n requires 0 <= i < length(xs);\n ensures nth(i, append(xs, ys)) == nth(i, xs);\n{\n reveal nth();\n if i == 0 {\n calc {\n nth(0, append(xs, ys));\n nth(0, Cons(xs.head, append(xs.tail, ys)));\n xs.head;\n }\n } else {\n calc {\n nth(i, append(xs, ys));\n nth(i, Cons(xs.head, append(xs.tail, ys)));\n nth(i-1, append(xs.tail, ys));\n { NthAppendA(i-1, xs.tail, ys); }\n nth(i-1, xs.tail);\n }\n }\n}\n\nlemma NthAppendB(i: int, xs: List, ys: List)\n requires length(xs) <= i < length(xs) + length(ys);\n ensures nth(i, append(xs, ys)) == nth(i - length(xs), ys);\n{\n reveal nth();\n AppendLength(xs, ys);\n match xs {\n case Nil =>\n case Cons(x, rest) =>\n calc {\n nth(i, append(xs, ys));\n nth(i, append(Cons(x, rest), ys));\n // def. append\n nth(i, Cons(x, append(rest, ys)));\n nth(i-1, append(rest, ys));\n { NthAppendB(i-1, rest, ys); }\n nth(i-1 - length(rest), ys);\n }\n }\n}\n\n" }, { "test_ID": "321", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_from dafny main repo_dafny4_Bug170.dfy", "ground_truth": "// RUN: %dafny /compile:0 /printTooltips \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nmodule InductiveThings {\n ghost predicate P(x: int)\n ghost predicate Q(x: int)\n\n least predicate A(x: int)\n {\n P(x) || B(x+1)\n }\n\n least predicate B(x: int)\n {\n Q(x) || A(x+1)\n }\n\n least lemma AA(x: int) // should be specialized not just for A, but also for B, which is in the same strongly connected component as A in the call graph\n requires A(x)\n {\n if B(x+1) { // this one should be replaced by B#[_k-1](x+1)\n BB(x+1);\n }\n }\n\n least lemma BB(x: int) // should be specialized not just for B, but also for A, which is in the same strongly connected component as B in the call graph\n requires B(x)\n {\n if A(x+1) { // this one should be replaced by A#[_k-1](x+1)\n AA(x+1);\n }\n }\n}\n\nmodule CoThings {\n greatest predicate A(x: int)\n {\n B(x+1)\n }\n\n greatest predicate B(x: int)\n {\n A(x+1)\n }\n\n greatest lemma AA(x: int) // should be specialized not just for A, but also for B, which is in the same strongly connected component as A in the call graph\n ensures A(x)\n {\n BB(x+1);\n assert B(x+1); // this one should be replaced by B#[_k-1] (which will happen, provided that AA is listed as also being specialized for B)\n }\n\n greatest lemma BB(x: int) // should be specialized not just for B, but also for A, which is in the same strongly connected component as B in the call graph\n ensures B(x)\n {\n AA(x+1);\n assert A(x+1); // this one should be replaced by A#[_k-1] (which will happen, provided that BB is listed as also being specialized for A)\n }\n}\n\nmodule SingleThings {\n ghost predicate P(x: int)\n\n least predicate A(x: int)\n {\n P(x) || A(x+1)\n }\n\n least lemma AA(x: int) // should be specialized just for A\n requires A(x)\n {\n if A(x+1) { // this one should be replaced by B#[_k-1](x+1)\n AA(x+1);\n }\n }\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 /printTooltips \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nmodule InductiveThings {\n ghost predicate P(x: int)\n ghost predicate Q(x: int)\n\n least predicate A(x: int)\n {\n P(x) || B(x+1)\n }\n\n least predicate B(x: int)\n {\n Q(x) || A(x+1)\n }\n\n least lemma AA(x: int) // should be specialized not just for A, but also for B, which is in the same strongly connected component as A in the call graph\n requires A(x)\n {\n if B(x+1) { // this one should be replaced by B#[_k-1](x+1)\n BB(x+1);\n }\n }\n\n least lemma BB(x: int) // should be specialized not just for B, but also for A, which is in the same strongly connected component as B in the call graph\n requires B(x)\n {\n if A(x+1) { // this one should be replaced by A#[_k-1](x+1)\n AA(x+1);\n }\n }\n}\n\nmodule CoThings {\n greatest predicate A(x: int)\n {\n B(x+1)\n }\n\n greatest predicate B(x: int)\n {\n A(x+1)\n }\n\n greatest lemma AA(x: int) // should be specialized not just for A, but also for B, which is in the same strongly connected component as A in the call graph\n ensures A(x)\n {\n BB(x+1);\n }\n\n greatest lemma BB(x: int) // should be specialized not just for B, but also for A, which is in the same strongly connected component as B in the call graph\n ensures B(x)\n {\n AA(x+1);\n }\n}\n\nmodule SingleThings {\n ghost predicate P(x: int)\n\n least predicate A(x: int)\n {\n P(x) || A(x+1)\n }\n\n least lemma AA(x: int) // should be specialized just for A\n requires A(x)\n {\n if A(x+1) { // this one should be replaced by B#[_k-1](x+1)\n AA(x+1);\n }\n }\n}\n\n" }, { "test_ID": "322", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_from dafny main repo_dafny4_ClassRefinement.dfy", "ground_truth": "// RUN: %testDafnyForEachCompiler \"%s\" -- --relax-definite-assignment\n\nabstract module M0 {\n class Counter {\n ghost var N: int\n ghost var Repr: set\n ghost predicate Valid()\n reads this, Repr\n ensures Valid() ==> this in Repr\n\n constructor Init()\n ensures N == 0\n ensures Valid() && fresh(Repr)\n {\n Repr := {};\n new;\n ghost var repr :| {this} <= repr && fresh(repr - {this});\n N, Repr := 0, repr;\n assume Valid(); // to be verified in refinement module\n }\n\n method Inc()\n requires Valid()\n modifies Repr\n ensures N == old(N) + 1\n ensures Valid() && fresh(Repr - old(Repr))\n {\n N := N + 1;\n modify Repr - {this};\n assume Valid(); // to be verified in refinement module\n }\n\n method Get() returns (n: int)\n requires Valid()\n ensures n == N\n {\n n :| assume n == N;\n }\n }\n}\n\nmodule M1 refines M0 {\n class Cell {\n var data: int\n constructor (d: int)\n ensures data == d\n { data := d; }\n }\n\n class Counter ... {\n var c: Cell\n var d: Cell\n ghost predicate Valid...\n {\n this in Repr &&\n c in Repr &&\n d in Repr &&\n c != d &&\n N == c.data - d.data\n }\n\n constructor Init...\n {\n c := new Cell(0);\n d := new Cell(0);\n new;\n ghost var repr := Repr + {this} + {c,d};\n ...;\n assert ...;\n }\n\n method Inc...\n {\n ...;\n modify ... {\n c.data := c.data + 1;\n }\n assert ...;\n }\n\n method Get...\n {\n n := c.data - d.data;\n }\n }\n}\n\nmethod Main() {\n var mx := new M1.Counter.Init();\n var my := new M1.Counter.Init();\n assert mx.N == 0 && my.N == 0;\n mx.Inc();\n my.Inc();\n mx.Inc();\n var nx := mx.Get();\n var ny := my.Get();\n assert nx == 2 && ny == 1;\n print nx, \" \", ny, \"\\n\";\n}\n\n", "hints_removed": "// RUN: %testDafnyForEachCompiler \"%s\" -- --relax-definite-assignment\n\nabstract module M0 {\n class Counter {\n ghost var N: int\n ghost var Repr: set\n ghost predicate Valid()\n reads this, Repr\n ensures Valid() ==> this in Repr\n\n constructor Init()\n ensures N == 0\n ensures Valid() && fresh(Repr)\n {\n Repr := {};\n new;\n ghost var repr :| {this} <= repr && fresh(repr - {this});\n N, Repr := 0, repr;\n assume Valid(); // to be verified in refinement module\n }\n\n method Inc()\n requires Valid()\n modifies Repr\n ensures N == old(N) + 1\n ensures Valid() && fresh(Repr - old(Repr))\n {\n N := N + 1;\n modify Repr - {this};\n assume Valid(); // to be verified in refinement module\n }\n\n method Get() returns (n: int)\n requires Valid()\n ensures n == N\n {\n n :| assume n == N;\n }\n }\n}\n\nmodule M1 refines M0 {\n class Cell {\n var data: int\n constructor (d: int)\n ensures data == d\n { data := d; }\n }\n\n class Counter ... {\n var c: Cell\n var d: Cell\n ghost predicate Valid...\n {\n this in Repr &&\n c in Repr &&\n d in Repr &&\n c != d &&\n N == c.data - d.data\n }\n\n constructor Init...\n {\n c := new Cell(0);\n d := new Cell(0);\n new;\n ghost var repr := Repr + {this} + {c,d};\n ...;\n }\n\n method Inc...\n {\n ...;\n modify ... {\n c.data := c.data + 1;\n }\n }\n\n method Get...\n {\n n := c.data - d.data;\n }\n }\n}\n\nmethod Main() {\n var mx := new M1.Counter.Init();\n var my := new M1.Counter.Init();\n mx.Inc();\n my.Inc();\n mx.Inc();\n var nx := mx.Get();\n var ny := my.Get();\n print nx, \" \", ny, \"\\n\";\n}\n\n" }, { "test_ID": "323", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_from dafny main repo_dafny4_NipkowKlein-chapter3.dfy", "ground_truth": "// RUN: %dafny /proverOpt:O:smt.qi.eager_threshold=30 /compile:0 /rprint:\"%t.rprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// This file is a Dafny encoding of chapter 3 from \"Concrete Semantics: With Isabelle/HOL\" by\n// Tobias Nipkow and Gerwin Klein.\n\n// ----- lists -----\n\ndatatype List = Nil | Cons(head: T, tail: List)\n\nghost function append(xs: List, ys: List): List\n{\n match xs\n case Nil => ys\n case Cons(x, tail) => Cons(x, append(tail, ys))\n}\n\n// ----- arithmetic expressions -----\n\ntype vname = string // variable names\ndatatype aexp = N(n: int) | V(vname) | Plus(aexp, aexp) // arithmetic expressions\n\ntype val = int\ntype state = vname -> val\n\nghost function aval(a: aexp, s: state): val\n{\n match a\n case N(n) => n\n case V(x) => s(x)\n case Plus(a0, a1) => aval(a0, s) + aval(a1, s)\n}\n\nlemma Example0()\n{\n var y := aval(Plus(N(3), V(\"x\")), x => 0);\n // The following line confirms that y is 3. If you don't know what y is, you can use the\n // verification debugger to figure it out, like this: Put any value in the assert (for example,\n // \"assert y == 0;\". If you're lucky and picked the right value, the verifier will prove the\n // assertion for you. If the verifier says it's unable to prove it, then click on the error\n // (in the Dafny IDE), which brings up the verification debugger. There, inspect the value\n // of y. This is probably the right value, but due to incompleteness in the verifier, it\n // could happen that the value you see is some value that verifier wasn't able to properly\n // exclude. Therefore, it's best to now take the value you see in the verification debugger,\n // say K, and put that into the assert (\"assert y == K;\"), to have the verifier confirm that\n // K really is the answer.\n assert y == 3;\n}\n\n// ----- constant folding -----\n\nghost function asimp_const(a: aexp): aexp\n{\n match a\n case N(n) => a\n case V(x) => a\n case Plus(a0, a1) =>\n var as0, as1 := asimp_const(a0), asimp_const(a1);\n if as0.N? && as1.N? then\n N(as0.n + as1.n)\n else\n Plus(as0, as1)\n}\n\nlemma AsimpConst(a: aexp, s: state)\n ensures aval(asimp_const(a), s) == aval(a, s)\n{\n // by induction\n forall a' | a' < a {\n AsimpConst(a', s); // this invokes the induction hypothesis for every a' that is structurally smaller than a\n }\n/* Here is an alternative proof. In the first two cases, the proof is trivial. The Plus case uses two invocations\n of the induction hypothesis.\n match a\n case N(n) =>\n case V(x) =>\n case Plus(a0, a1) =>\n AsimpConst(a0, s);\n AsimpConst(a1, s);\n*/\n}\n\n// more constant folding\n\nghost function plus(a0: aexp, a1: aexp): aexp\n{\n if a0.N? && a1.N? then\n N(a0.n + a1.n)\n else if a0.N? then\n if a0.n == 0 then a1 else Plus(a0, a1)\n else if a1.N? then\n if a1.n == 0 then a0 else Plus(a0, a1)\n else\n Plus(a0, a1)\n}\n\nlemma AvalPlus(a0: aexp, a1: aexp, s: state)\n ensures aval(plus(a0, a1), s) == aval(a0, s) + aval(a1, s)\n{\n // this proof is done automatically\n}\n\nghost function asimp(a: aexp): aexp\n{\n match a\n case N(n) => a\n case V(x) => a\n case Plus(a0, a1) => plus(asimp(a0), asimp(a1))\n}\n\nlemma AsimpCorrect(a: aexp, s: state)\n ensures aval(asimp(a), s) == aval(a, s)\n{\n // call the induction hypothesis on every value a' that is structurally smaller than a\n forall a' | a' < a { AsimpCorrect(a', s); }\n}\n\n// The following lemma is not in the Nipkow and Klein book, but it's a fun one to prove.\nlemma ASimplInvolutive(a: aexp)\n ensures asimp(asimp(a)) == asimp(a)\n{\n}\n\n// ----- boolean expressions -----\n\ndatatype bexp = Bc(v: bool) | Not(bexp) | And(bexp, bexp) | Less(aexp, aexp)\n\nghost function bval(b: bexp, s: state): bool\n{\n match b\n case Bc(v) => v\n case Not(b) => !bval(b, s)\n case And(b0, b1) => bval(b0, s) && bval(b1, s)\n case Less(a0, a1) => aval(a0, s) < aval(a1, s)\n}\n\n// constant folding for booleans\n\nghost function not(b: bexp): bexp\n{\n match b\n case Bc(b0) => Bc(!b0)\n case Not(b0) => b0 // this case is not in the Nipkow and Klein book, but it seems a nice one to include\n case And(_, _) => Not(b)\n case Less(_, _) => Not(b)\n}\n\nghost function and(b0: bexp, b1: bexp): bexp\n{\n if b0.Bc? then\n if b0.v then b1 else b0\n else if b1.Bc? then\n if b1.v then b0 else b1\n else\n And(b0, b1)\n}\n\nghost function less(a0: aexp, a1: aexp): bexp\n{\n if a0.N? && a1.N? then\n Bc(a0.n < a1.n)\n else\n Less(a0, a1)\n}\n\nghost function bsimp(b: bexp): bexp\n{\n match b\n case Bc(v) => b\n case Not(b0) => not(bsimp(b0))\n case And(b0, b1) => and(bsimp(b0), bsimp(b1))\n case Less(a0, a1) => less(asimp(a0), asimp(a1))\n}\n\nlemma BsimpCorrect(b: bexp, s: state)\n ensures bval(bsimp(b), s) == bval(b, s)\n{\n/* Here is one proof, which uses the induction hypothesis any anything smaller than b and also invokes\n the lemma AsimpCorrect on every arithmetic expression.\n forall b' | b' < b { BsimpCorrect(b', s); }\n forall a { AsimpCorrect(a, s); }\n Yet another possibility is to mark the lemma with {:induction b} and to use the following line in\n the body:\n forall a { AsimpCorrect(a, s); }\n*/\n // Here is another proof, which makes explicit the uses of the induction hypothesis and the other lemma.\n match b\n case Bc(v) =>\n case Not(b0) =>\n BsimpCorrect(b0, s);\n case And(b0, b1) =>\n BsimpCorrect(b0, s); BsimpCorrect(b1, s);\n case Less(a0, a1) =>\n AsimpCorrect(a0, s); AsimpCorrect(a1, s);\n}\n\n// ----- stack machine -----\n\ndatatype instr = LOADI(val) | LOAD(vname) | ADD\n\ntype stack = List\n\nghost function exec1(i: instr, s: state, stk: stack): stack\n{\n match i\n case LOADI(n) => Cons(n, stk)\n case LOAD(x) => Cons(s(x), stk)\n case ADD =>\n if stk.Cons? && stk.tail.Cons? then\n var Cons(a1, Cons(a0, tail)) := stk;\n Cons(a0 + a1, tail)\n else // stack underflow\n Nil // an alternative would be to return Cons(n, Nil) for an arbitrary value n--that is what Nipkow and Klein do\n}\n\nghost function exec(ii: List, s: state, stk: stack): stack\n{\n match ii\n case Nil => stk\n case Cons(i, rest) => exec(rest, s, exec1(i, s, stk))\n}\n\n// ----- compilation -----\n\nghost function comp(a: aexp): List\n{\n match a\n case N(n) => Cons(LOADI(n), Nil)\n case V(x) => Cons(LOAD(x), Nil)\n case Plus(a0, a1) => append(append(comp(a0), comp(a1)), Cons(ADD, Nil))\n}\n\nlemma CorrectCompilation(a: aexp, s: state, stk: stack)\n ensures exec(comp(a), s, stk) == Cons(aval(a, s), stk)\n{\n match a\n case N(n) =>\n case V(x) =>\n case Plus(a0, a1) =>\n // This proof spells out the proof as a series of equality-preserving steps. Each\n // expression in the calculation is terminated by a semi-colon. In some cases, a hint\n // for the step is needed. Such hints are given in curly braces.\n calc {\n exec(comp(a), s, stk);\n // definition of comp on Plus\n exec(append(append(comp(a0), comp(a1)), Cons(ADD, Nil)), s, stk);\n { ExecAppend(append(comp(a0), comp(a1)), Cons(ADD, Nil), s, stk); }\n exec(Cons(ADD, Nil), s, exec(append(comp(a0), comp(a1)), s, stk));\n { ExecAppend(comp(a0), comp(a1), s, stk); }\n exec(Cons(ADD, Nil), s, exec(comp(a1), s, exec(comp(a0), s, stk)));\n { CorrectCompilation(a0, s, stk); }\n exec(Cons(ADD, Nil), s, exec(comp(a1), s, Cons(aval(a0, s), stk)));\n { CorrectCompilation(a1, s, Cons(aval(a0, s), stk)); }\n exec(Cons(ADD, Nil), s, Cons(aval(a1, s), Cons(aval(a0, s), stk)));\n // definition of comp on ADD\n Cons(aval(a1, s) + aval(a0, s), stk);\n // definition of aval on Plus\n Cons(aval(a, s), stk);\n }\n}\n\nlemma ExecAppend(ii0: List, ii1: List, s: state, stk: stack)\n ensures exec(append(ii0, ii1), s, stk) == exec(ii1, s, exec(ii0, s, stk))\n{\n // the proof (which is by induction) is done automatically\n}\n\n", "hints_removed": "// RUN: %dafny /proverOpt:O:smt.qi.eager_threshold=30 /compile:0 /rprint:\"%t.rprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// This file is a Dafny encoding of chapter 3 from \"Concrete Semantics: With Isabelle/HOL\" by\n// Tobias Nipkow and Gerwin Klein.\n\n// ----- lists -----\n\ndatatype List = Nil | Cons(head: T, tail: List)\n\nghost function append(xs: List, ys: List): List\n{\n match xs\n case Nil => ys\n case Cons(x, tail) => Cons(x, append(tail, ys))\n}\n\n// ----- arithmetic expressions -----\n\ntype vname = string // variable names\ndatatype aexp = N(n: int) | V(vname) | Plus(aexp, aexp) // arithmetic expressions\n\ntype val = int\ntype state = vname -> val\n\nghost function aval(a: aexp, s: state): val\n{\n match a\n case N(n) => n\n case V(x) => s(x)\n case Plus(a0, a1) => aval(a0, s) + aval(a1, s)\n}\n\nlemma Example0()\n{\n var y := aval(Plus(N(3), V(\"x\")), x => 0);\n // The following line confirms that y is 3. If you don't know what y is, you can use the\n // verification debugger to figure it out, like this: Put any value in the assert (for example,\n // \"assert y == 0;\". If you're lucky and picked the right value, the verifier will prove the\n // assertion for you. If the verifier says it's unable to prove it, then click on the error\n // (in the Dafny IDE), which brings up the verification debugger. There, inspect the value\n // of y. This is probably the right value, but due to incompleteness in the verifier, it\n // could happen that the value you see is some value that verifier wasn't able to properly\n // exclude. Therefore, it's best to now take the value you see in the verification debugger,\n // say K, and put that into the assert (\"assert y == K;\"), to have the verifier confirm that\n // K really is the answer.\n}\n\n// ----- constant folding -----\n\nghost function asimp_const(a: aexp): aexp\n{\n match a\n case N(n) => a\n case V(x) => a\n case Plus(a0, a1) =>\n var as0, as1 := asimp_const(a0), asimp_const(a1);\n if as0.N? && as1.N? then\n N(as0.n + as1.n)\n else\n Plus(as0, as1)\n}\n\nlemma AsimpConst(a: aexp, s: state)\n ensures aval(asimp_const(a), s) == aval(a, s)\n{\n // by induction\n forall a' | a' < a {\n AsimpConst(a', s); // this invokes the induction hypothesis for every a' that is structurally smaller than a\n }\n/* Here is an alternative proof. In the first two cases, the proof is trivial. The Plus case uses two invocations\n of the induction hypothesis.\n match a\n case N(n) =>\n case V(x) =>\n case Plus(a0, a1) =>\n AsimpConst(a0, s);\n AsimpConst(a1, s);\n*/\n}\n\n// more constant folding\n\nghost function plus(a0: aexp, a1: aexp): aexp\n{\n if a0.N? && a1.N? then\n N(a0.n + a1.n)\n else if a0.N? then\n if a0.n == 0 then a1 else Plus(a0, a1)\n else if a1.N? then\n if a1.n == 0 then a0 else Plus(a0, a1)\n else\n Plus(a0, a1)\n}\n\nlemma AvalPlus(a0: aexp, a1: aexp, s: state)\n ensures aval(plus(a0, a1), s) == aval(a0, s) + aval(a1, s)\n{\n // this proof is done automatically\n}\n\nghost function asimp(a: aexp): aexp\n{\n match a\n case N(n) => a\n case V(x) => a\n case Plus(a0, a1) => plus(asimp(a0), asimp(a1))\n}\n\nlemma AsimpCorrect(a: aexp, s: state)\n ensures aval(asimp(a), s) == aval(a, s)\n{\n // call the induction hypothesis on every value a' that is structurally smaller than a\n forall a' | a' < a { AsimpCorrect(a', s); }\n}\n\n// The following lemma is not in the Nipkow and Klein book, but it's a fun one to prove.\nlemma ASimplInvolutive(a: aexp)\n ensures asimp(asimp(a)) == asimp(a)\n{\n}\n\n// ----- boolean expressions -----\n\ndatatype bexp = Bc(v: bool) | Not(bexp) | And(bexp, bexp) | Less(aexp, aexp)\n\nghost function bval(b: bexp, s: state): bool\n{\n match b\n case Bc(v) => v\n case Not(b) => !bval(b, s)\n case And(b0, b1) => bval(b0, s) && bval(b1, s)\n case Less(a0, a1) => aval(a0, s) < aval(a1, s)\n}\n\n// constant folding for booleans\n\nghost function not(b: bexp): bexp\n{\n match b\n case Bc(b0) => Bc(!b0)\n case Not(b0) => b0 // this case is not in the Nipkow and Klein book, but it seems a nice one to include\n case And(_, _) => Not(b)\n case Less(_, _) => Not(b)\n}\n\nghost function and(b0: bexp, b1: bexp): bexp\n{\n if b0.Bc? then\n if b0.v then b1 else b0\n else if b1.Bc? then\n if b1.v then b0 else b1\n else\n And(b0, b1)\n}\n\nghost function less(a0: aexp, a1: aexp): bexp\n{\n if a0.N? && a1.N? then\n Bc(a0.n < a1.n)\n else\n Less(a0, a1)\n}\n\nghost function bsimp(b: bexp): bexp\n{\n match b\n case Bc(v) => b\n case Not(b0) => not(bsimp(b0))\n case And(b0, b1) => and(bsimp(b0), bsimp(b1))\n case Less(a0, a1) => less(asimp(a0), asimp(a1))\n}\n\nlemma BsimpCorrect(b: bexp, s: state)\n ensures bval(bsimp(b), s) == bval(b, s)\n{\n/* Here is one proof, which uses the induction hypothesis any anything smaller than b and also invokes\n the lemma AsimpCorrect on every arithmetic expression.\n forall b' | b' < b { BsimpCorrect(b', s); }\n forall a { AsimpCorrect(a, s); }\n Yet another possibility is to mark the lemma with {:induction b} and to use the following line in\n the body:\n forall a { AsimpCorrect(a, s); }\n*/\n // Here is another proof, which makes explicit the uses of the induction hypothesis and the other lemma.\n match b\n case Bc(v) =>\n case Not(b0) =>\n BsimpCorrect(b0, s);\n case And(b0, b1) =>\n BsimpCorrect(b0, s); BsimpCorrect(b1, s);\n case Less(a0, a1) =>\n AsimpCorrect(a0, s); AsimpCorrect(a1, s);\n}\n\n// ----- stack machine -----\n\ndatatype instr = LOADI(val) | LOAD(vname) | ADD\n\ntype stack = List\n\nghost function exec1(i: instr, s: state, stk: stack): stack\n{\n match i\n case LOADI(n) => Cons(n, stk)\n case LOAD(x) => Cons(s(x), stk)\n case ADD =>\n if stk.Cons? && stk.tail.Cons? then\n var Cons(a1, Cons(a0, tail)) := stk;\n Cons(a0 + a1, tail)\n else // stack underflow\n Nil // an alternative would be to return Cons(n, Nil) for an arbitrary value n--that is what Nipkow and Klein do\n}\n\nghost function exec(ii: List, s: state, stk: stack): stack\n{\n match ii\n case Nil => stk\n case Cons(i, rest) => exec(rest, s, exec1(i, s, stk))\n}\n\n// ----- compilation -----\n\nghost function comp(a: aexp): List\n{\n match a\n case N(n) => Cons(LOADI(n), Nil)\n case V(x) => Cons(LOAD(x), Nil)\n case Plus(a0, a1) => append(append(comp(a0), comp(a1)), Cons(ADD, Nil))\n}\n\nlemma CorrectCompilation(a: aexp, s: state, stk: stack)\n ensures exec(comp(a), s, stk) == Cons(aval(a, s), stk)\n{\n match a\n case N(n) =>\n case V(x) =>\n case Plus(a0, a1) =>\n // This proof spells out the proof as a series of equality-preserving steps. Each\n // expression in the calculation is terminated by a semi-colon. In some cases, a hint\n // for the step is needed. Such hints are given in curly braces.\n calc {\n exec(comp(a), s, stk);\n // definition of comp on Plus\n exec(append(append(comp(a0), comp(a1)), Cons(ADD, Nil)), s, stk);\n { ExecAppend(append(comp(a0), comp(a1)), Cons(ADD, Nil), s, stk); }\n exec(Cons(ADD, Nil), s, exec(append(comp(a0), comp(a1)), s, stk));\n { ExecAppend(comp(a0), comp(a1), s, stk); }\n exec(Cons(ADD, Nil), s, exec(comp(a1), s, exec(comp(a0), s, stk)));\n { CorrectCompilation(a0, s, stk); }\n exec(Cons(ADD, Nil), s, exec(comp(a1), s, Cons(aval(a0, s), stk)));\n { CorrectCompilation(a1, s, Cons(aval(a0, s), stk)); }\n exec(Cons(ADD, Nil), s, Cons(aval(a1, s), Cons(aval(a0, s), stk)));\n // definition of comp on ADD\n Cons(aval(a1, s) + aval(a0, s), stk);\n // definition of aval on Plus\n Cons(aval(a, s), stk);\n }\n}\n\nlemma ExecAppend(ii0: List, ii1: List, s: state, stk: stack)\n ensures exec(append(ii0, ii1), s, stk) == exec(ii1, s, exec(ii0, s, stk))\n{\n // the proof (which is by induction) is done automatically\n}\n\n" }, { "test_ID": "324", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_from dafny main repo_dafny4_Primes.dfy", "ground_truth": "// RUN: %testDafnyForEachResolver \"%s\"\n\n\nghost predicate IsPrime(n: int)\n{\n 2 <= n && forall m :: 2 <= m < n ==> n % m != 0 // WISH It would be great to think about the status of modulo as a trigger\n}\n\n// The following theorem shows that there is an infinite number of primes\nlemma AlwaysMorePrimes(k: int)\n ensures exists p :: k <= p && IsPrime(p)\n{\n var j, s := 0, {};\n while true\n invariant AllPrimes(s, j)\n decreases k - j\n {\n var p := GetLargerPrime(s, j);\n if k <= p { return; }\n j, s := p, set x | 2 <= x <= p && IsPrime(x);\n }\n}\n\n// Here is an alternative formulation of the theorem\nlemma NoFiniteSetContainsAllPrimes(s: set)\n ensures exists p :: IsPrime(p) && p !in s\n{\n AlwaysMorePrimes(if s == {} then 0 else PickLargest(s) + 1);\n}\n\n// ------------------------- lemmas and auxiliary definitions\n\nghost predicate AllPrimes(s: set, bound: int)\n{\n // s contains only primes\n (forall x :: x in s ==> IsPrime(x)) &&\n // every prime up to \"bound\" is included in s\n (forall p :: IsPrime(p) && p <= bound ==> p in s)\n}\n\nlemma GetLargerPrime(s: set, bound: int) returns (p: int)\n requires AllPrimes(s, bound)\n ensures bound < p && IsPrime(p)\n{\n var q := product(s);\n if exists p :: bound < p <= q && IsPrime(p) {\n p :| bound < p <= q && IsPrime(p);\n } else {\n ProductPlusOneIsPrime(s, q);\n p := q+1;\n if p <= bound { // by contradction, establish bound < p\n assert p in s;\n product_property(s);\n assert false;\n }\n }\n}\n\nghost function product(s: set): int\n{\n if s == {} then 1 else\n var a := PickLargest(s); a * product(s - {a})\n}\n\nlemma product_property(s: set)\n requires forall x :: x in s ==> 1 <= x\n ensures 1 <= product(s) && forall x :: x in s ==> x <= product(s)\n{\n if s != {} {\n var a := PickLargest(s);\n var s' := s - {a};\n assert s == s' + {a};\n product_property(s');\n MulPos(a, product(s'));\n }\n}\n\nlemma ProductPlusOneIsPrime(s: set, q: int)\n requires AllPrimes(s, q) && q == product(s)\n ensures IsPrime(q+1)\n{\n var p := q+1;\n calc {\n true;\n { product_property(s); }\n 2 <= p;\n }\n\n forall m | 2 <= m <= q && IsPrime(m)\n ensures p % m != 0\n {\n assert m in s; // because AllPrimes(s, q) && m <= q && IsPrime(m)\n RemoveFactor(m, s);\n var l := product(s-{m});\n assert m*l == q;\n MulDivMod(m, l, q, 1);\n }\n assert IsPrime_Alt(q+1);\n AltPrimeDefinition(q+1);\n}\n\n// The following lemma is essentially just associativity and commutativity of multiplication.\n// To get this proof through, it is necessary to know that if x!=y and y==Pick...(s), then\n// also y==Pick...(s - {x}). It is for this reason that we use PickLargest, instead of\n// picking an arbitrary element from s.\nlemma RemoveFactor(x: int, s: set)\n requires x in s\n ensures product(s) == x * product(s - {x})\n{\n var y := PickLargest(s);\n if x != y {\n calc {\n product(s);\n y * product(s - {y});\n { RemoveFactor(x, s - {y}); }\n y * x * product(s - {y} - {x});\n x * y * product(s - {y} - {x});\n { assert s - {y} - {x} == s - {x} - {y}; }\n x * y * product(s - {x} - {y});\n /* FIXME: This annotation wasn't needed before the introduction\n * of auto-triggers. It's not needed if one adds {:no_trigger}\n * to the forall y :: y in s ==> y <= x part of PickLargest, but that\n * boils down to z3 picking $Box(...) as good trigger\n */\n // FIXME: the parens shouldn't be needed around (s - {x})\n { assert y in (s - {x}); }\n { assert y == PickLargest(s - {x}); }\n x * product(s - {x});\n }\n }\n}\n\n// This definition is like IsPrime above, except that the quantification is only over primes.\nghost predicate IsPrime_Alt(n: int)\n{\n 2 <= n && forall m :: 2 <= m < n && IsPrime(m) ==> n % m != 0\n}\n\n// To show that n is prime, it suffices to prove that it satisfies the alternate definition\nlemma AltPrimeDefinition(n: int)\n requires IsPrime_Alt(n)\n ensures IsPrime(n)\n{\n forall m | 2 <= m < n\n ensures n % m != 0\n {\n if !IsPrime(m) {\n var a, b := Composite(m);\n if n % m == 0 { // proof by contradiction\n var k := n / m;\n calc {\n true;\n k == n / m;\n m * k == n;\n a * b * k == n;\n ==> { MulDivMod(a, b*k, n, 0); }\n n % a == 0;\n ==> // IsPrime_Alt\n !(2 <= a < n && IsPrime(a));\n { assert 2 <= a < m < n; }\n !IsPrime(a);\n false;\n }\n }\n }\n }\n}\n\nlemma Composite(c: int) returns (a: int, b: int)\n requires 2 <= c && !IsPrime(c)\n ensures 2 <= a < c && 2 <= b && a * b == c\n ensures IsPrime(a)\n{\n calc {\n true;\n !IsPrime(c);\n !(2 <= c && forall m :: 2 <= m < c ==> c % m != 0);\n exists m :: 2 <= m < c && c % m == 0;\n }\n a :| 2 <= a < c && c % a == 0;\n b := c / a;\n assert 2 <= a < c && 2 <= b && a * b == c;\n if !IsPrime(a) {\n var x, y := Composite(a);\n a, b := x, y*b;\n }\n}\n\nghost function PickLargest(s: set): int\n requires s != {}\n{\n LargestElementExists(s);\n var x :| x in s && forall y :: y in s ==> y <= x;\n x\n}\n\nlemma LargestElementExists(s: set)\n requires s != {}\n ensures exists x :: x in s && forall y :: y in s ==> y <= x\n{\n var s' := s;\n while true\n invariant s' != {} && s' <= s\n invariant forall x,y :: x in s' && y in s && y !in s' ==> y <= x\n decreases s'\n {\n var x :| x in s'; // pick something\n if forall y :: y in s' ==> y <= x {\n // good pick\n return;\n } else {\n // constrain the pick further\n var y :| y in s' && x < y;\n s' := set z | z in s && x < z;\n assert y in s';\n }\n }\n}\n\nlemma MulPos(a: int, b: int)\n requires 1 <= a && 1 <= b\n ensures a <= a * b\n{\n if b == 1 {\n assert a * b == a;\n } else {\n assert a * b == a * (b - 1) + a;\n MulPos(a, b - 1);\n }\n}\n\n// This axiom about % is needed. Unfortunately, Z3 seems incapable of proving it.\nlemma MulDivMod(a: nat, b: nat, c: nat, j: nat)\n requires a * b == c && j < a\n ensures (c+j) % a == j\n\n", "hints_removed": "// RUN: %testDafnyForEachResolver \"%s\"\n\n\nghost predicate IsPrime(n: int)\n{\n 2 <= n && forall m :: 2 <= m < n ==> n % m != 0 // WISH It would be great to think about the status of modulo as a trigger\n}\n\n// The following theorem shows that there is an infinite number of primes\nlemma AlwaysMorePrimes(k: int)\n ensures exists p :: k <= p && IsPrime(p)\n{\n var j, s := 0, {};\n while true\n {\n var p := GetLargerPrime(s, j);\n if k <= p { return; }\n j, s := p, set x | 2 <= x <= p && IsPrime(x);\n }\n}\n\n// Here is an alternative formulation of the theorem\nlemma NoFiniteSetContainsAllPrimes(s: set)\n ensures exists p :: IsPrime(p) && p !in s\n{\n AlwaysMorePrimes(if s == {} then 0 else PickLargest(s) + 1);\n}\n\n// ------------------------- lemmas and auxiliary definitions\n\nghost predicate AllPrimes(s: set, bound: int)\n{\n // s contains only primes\n (forall x :: x in s ==> IsPrime(x)) &&\n // every prime up to \"bound\" is included in s\n (forall p :: IsPrime(p) && p <= bound ==> p in s)\n}\n\nlemma GetLargerPrime(s: set, bound: int) returns (p: int)\n requires AllPrimes(s, bound)\n ensures bound < p && IsPrime(p)\n{\n var q := product(s);\n if exists p :: bound < p <= q && IsPrime(p) {\n p :| bound < p <= q && IsPrime(p);\n } else {\n ProductPlusOneIsPrime(s, q);\n p := q+1;\n if p <= bound { // by contradction, establish bound < p\n product_property(s);\n }\n }\n}\n\nghost function product(s: set): int\n{\n if s == {} then 1 else\n var a := PickLargest(s); a * product(s - {a})\n}\n\nlemma product_property(s: set)\n requires forall x :: x in s ==> 1 <= x\n ensures 1 <= product(s) && forall x :: x in s ==> x <= product(s)\n{\n if s != {} {\n var a := PickLargest(s);\n var s' := s - {a};\n product_property(s');\n MulPos(a, product(s'));\n }\n}\n\nlemma ProductPlusOneIsPrime(s: set, q: int)\n requires AllPrimes(s, q) && q == product(s)\n ensures IsPrime(q+1)\n{\n var p := q+1;\n calc {\n true;\n { product_property(s); }\n 2 <= p;\n }\n\n forall m | 2 <= m <= q && IsPrime(m)\n ensures p % m != 0\n {\n RemoveFactor(m, s);\n var l := product(s-{m});\n MulDivMod(m, l, q, 1);\n }\n AltPrimeDefinition(q+1);\n}\n\n// The following lemma is essentially just associativity and commutativity of multiplication.\n// To get this proof through, it is necessary to know that if x!=y and y==Pick...(s), then\n// also y==Pick...(s - {x}). It is for this reason that we use PickLargest, instead of\n// picking an arbitrary element from s.\nlemma RemoveFactor(x: int, s: set)\n requires x in s\n ensures product(s) == x * product(s - {x})\n{\n var y := PickLargest(s);\n if x != y {\n calc {\n product(s);\n y * product(s - {y});\n { RemoveFactor(x, s - {y}); }\n y * x * product(s - {y} - {x});\n x * y * product(s - {y} - {x});\n { assert s - {y} - {x} == s - {x} - {y}; }\n x * y * product(s - {x} - {y});\n /* FIXME: This annotation wasn't needed before the introduction\n * of auto-triggers. It's not needed if one adds {:no_trigger}\n * to the forall y :: y in s ==> y <= x part of PickLargest, but that\n * boils down to z3 picking $Box(...) as good trigger\n */\n // FIXME: the parens shouldn't be needed around (s - {x})\n { assert y in (s - {x}); }\n { assert y == PickLargest(s - {x}); }\n x * product(s - {x});\n }\n }\n}\n\n// This definition is like IsPrime above, except that the quantification is only over primes.\nghost predicate IsPrime_Alt(n: int)\n{\n 2 <= n && forall m :: 2 <= m < n && IsPrime(m) ==> n % m != 0\n}\n\n// To show that n is prime, it suffices to prove that it satisfies the alternate definition\nlemma AltPrimeDefinition(n: int)\n requires IsPrime_Alt(n)\n ensures IsPrime(n)\n{\n forall m | 2 <= m < n\n ensures n % m != 0\n {\n if !IsPrime(m) {\n var a, b := Composite(m);\n if n % m == 0 { // proof by contradiction\n var k := n / m;\n calc {\n true;\n k == n / m;\n m * k == n;\n a * b * k == n;\n ==> { MulDivMod(a, b*k, n, 0); }\n n % a == 0;\n ==> // IsPrime_Alt\n !(2 <= a < n && IsPrime(a));\n { assert 2 <= a < m < n; }\n !IsPrime(a);\n false;\n }\n }\n }\n }\n}\n\nlemma Composite(c: int) returns (a: int, b: int)\n requires 2 <= c && !IsPrime(c)\n ensures 2 <= a < c && 2 <= b && a * b == c\n ensures IsPrime(a)\n{\n calc {\n true;\n !IsPrime(c);\n !(2 <= c && forall m :: 2 <= m < c ==> c % m != 0);\n exists m :: 2 <= m < c && c % m == 0;\n }\n a :| 2 <= a < c && c % a == 0;\n b := c / a;\n if !IsPrime(a) {\n var x, y := Composite(a);\n a, b := x, y*b;\n }\n}\n\nghost function PickLargest(s: set): int\n requires s != {}\n{\n LargestElementExists(s);\n var x :| x in s && forall y :: y in s ==> y <= x;\n x\n}\n\nlemma LargestElementExists(s: set)\n requires s != {}\n ensures exists x :: x in s && forall y :: y in s ==> y <= x\n{\n var s' := s;\n while true\n {\n var x :| x in s'; // pick something\n if forall y :: y in s' ==> y <= x {\n // good pick\n return;\n } else {\n // constrain the pick further\n var y :| y in s' && x < y;\n s' := set z | z in s && x < z;\n }\n }\n}\n\nlemma MulPos(a: int, b: int)\n requires 1 <= a && 1 <= b\n ensures a <= a * b\n{\n if b == 1 {\n } else {\n MulPos(a, b - 1);\n }\n}\n\n// This axiom about % is needed. Unfortunately, Z3 seems incapable of proving it.\nlemma MulDivMod(a: nat, b: nat, c: nat, j: nat)\n requires a * b == c && j < a\n ensures (c+j) % a == j\n\n" }, { "test_ID": "325", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_from_dafny_main_repo_dafny0_snapshots_Inputs_Snapshots1.dfy", "ground_truth": "method M()\n{\n N();\n assert false;\n}\n\nmethod N()\n ensures P();\n\npredicate P()\n{\n false\n}\n\n", "hints_removed": "method M()\n{\n N();\n}\n\nmethod N()\n ensures P();\n\npredicate P()\n{\n false\n}\n\n" }, { "test_ID": "326", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_from_dafny_main_repo_dafny0_snapshots_Inputs_Snapshots5.dfy", "ground_truth": "method M()\n{\n N();\n if (*)\n {\n\n }\n else\n {\n assert (forall b: bool :: b || !b) || 0 != 0;\n }\n N();\n assert (forall b: bool :: b || !b) || 3 != 3;\n if (*)\n {\n\n }\n else\n {\n assert (forall b: bool :: b || !b) || 1 != 1;\n }\n}\n\n\nmethod N()\n ensures (forall b: bool :: b || !b) || 2 != 2;\n\n", "hints_removed": "method M()\n{\n N();\n if (*)\n {\n\n }\n else\n {\n }\n N();\n if (*)\n {\n\n }\n else\n {\n }\n}\n\n\nmethod N()\n ensures (forall b: bool :: b || !b) || 2 != 2;\n\n" }, { "test_ID": "327", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_lightening_verifier.dfy", "ground_truth": "class CrashableMem {\n var mem_ : array;\n method read(off : int) returns (r : T)\n requires 0 <= off < mem_.Length;\n {\n return mem_[off];\n }\n\n method write(off : int, val : T)\n requires 0 <= off < mem_.Length;\n modifies mem_;\n {\n mem_[off] := val;\n }\n}\n\ndatatype GhostState = GS(\n num_entry : int,\n log : seq,\n\n mem_len : int,\n mem : seq,\n old_mem : seq,\n ideal_mem : seq,\n countdown : int,\n first_log_pos : map\n)\n\ndatatype GhostOp = WriteMem(off : int, val : int)\n | WriteLog(off : int, val : int)\npredicate ghost_state_inv(s : GhostState) {\n 0 <= s.num_entry * 2 < |s.log|\n && |s.log| > 0\n && |s.mem| == s.mem_len && |s.ideal_mem| == s.mem_len && |s.old_mem| == s.mem_len\n && s.countdown >= 0\n}\n\nfunction init_ghost_state(log : seq, mem : seq, countdown : int) : GhostState\n requires |log| > 0;\n requires countdown >= 0;\n ensures ghost_state_inv(init_ghost_state(log, mem, countdown));\n{\n GS(0, log[..], |mem|, mem[..], mem[..], mem[..], countdown, map[])\n}\n\nfunction mem_write(s : GhostState, off: int, val: int) : GhostState\n requires ghost_state_inv(s);\n requires 0 <= off < s.mem_len;\n ensures ghost_state_inv(mem_write(s, off, val));\n{\n var new_mem := s.mem[off := val];\n var new_ideal_mem := s.ideal_mem[off := val];\n s.(mem := new_mem,\n ideal_mem := new_ideal_mem)\n}\n\nfunction log_write(s : GhostState, off : int, val: int) : GhostState\n requires ghost_state_inv(s);\n requires 0 <= off < |s.log|;\n ensures ghost_state_inv(log_write(s, off, val));\n{\n s.(log := s.log[off := val])\n}\n\npredicate valid_op(s : GhostState, op : GhostOp)\n{\n match op\n case WriteMem(off, val) => 0 <= off < |s.mem|\n case WriteLog(off, val) => 0 <= off < |s.log|\n}\n\nfunction countdown (s : GhostState) : GhostState\n{\n if s.countdown > 0 then\n s.(countdown := s.countdown - 1)\n else\n s\n}\n\nfunction normal_step (s : GhostState, op : GhostOp) : GhostState\n requires valid_op(s, op);\n requires ghost_state_inv(s);\n ensures ghost_state_inv(normal_step(s, op));\n{\n match op\n case WriteMem(off, val) => mem_write(s, off, val)\n case WriteLog(off, val) => log_write(s, off, val)\n}\n\nfunction ghost_step (s : GhostState, op : GhostOp) : (GhostState, bool)\n requires valid_op(s, op);\n requires ghost_state_inv(s);\n ensures ghost_state_inv(normal_step(s, op));\n{\n if s.countdown > 0 then\n var s' := normal_step(s, op);\n (s'.(countdown := s.countdown - 1), true)\n else\n (s, false)\n}\n\nfunction mem_write_step (s : GhostState, off : int, val : int) : (GhostState, bool)\n requires 0 <= off < s.mem_len;\n requires ghost_state_inv(s);\n{\n ghost_step(s, WriteMem(off, val))\n}\n\nfunction log_write_step (s : GhostState, off : int, val : int) : (GhostState, bool)\n requires 0 <= off < |s.log|;\n requires ghost_state_inv(s);\n{\n ghost_step(s, WriteLog(off, val))\n}\n\nfunction set_num_entry (s : GhostState, n : int) : (GhostState, bool)\n requires 0 <= n * 2 < |s.log|;\n{\n if s.countdown > 0 then\n (s.(num_entry := n,\n countdown := s.countdown - 1),\n true)\n else\n (s, false)\n}\n\npredicate crashed (s : GhostState)\n{\n s.countdown <= 0\n}\n\npredicate old_mem_equiv (s : GhostState)\n requires ghost_state_inv(s);\n{\n (forall o :: !(o in s.first_log_pos) && 0 <= o < |s.mem| ==> s.mem[o] == s.old_mem[o])\n}\n\npredicate ghost_tx_inv (s : GhostState)\n{\n ghost_state_inv(s) &&\n (forall o :: o in s.first_log_pos ==> 0 <= o < s.mem_len) &&\n (forall o :: o in s.first_log_pos ==> 0 <= s.first_log_pos[o] < s.num_entry) &&\n (forall o :: o in s.first_log_pos ==> 0 <= s.first_log_pos[o] * 2 + 1 < |s.log|) &&\n (forall o :: o in s.first_log_pos ==> s.log[s.first_log_pos[o] * 2] == o) &&\n (forall o :: o in s.first_log_pos ==> s.log[s.first_log_pos[o] * 2 + 1] == s.old_mem[o]) &&\n (forall o :: o in s.first_log_pos ==> forall i :: 0 <= i < s.first_log_pos[o] ==> s.log[i * 2] != o) &&\n (forall i :: 0 <= i < s.num_entry ==> s.log[i * 2] in s.first_log_pos)\n}\n\nfunction ghost_begin_tx (s : GhostState) : GhostState\n requires ghost_state_inv(s);\n requires s.num_entry == 0;\n ensures ghost_state_inv(ghost_begin_tx(s));\n ensures ghost_tx_inv(ghost_begin_tx(s));\n ensures old_mem_equiv(ghost_begin_tx(s));\n{\n var (s', f) := set_num_entry(s, 0);\n var s' := s'.(first_log_pos := map[], old_mem := s.mem[..]);\n s'\n}\n\nfunction ghost_commit_tx (s : GhostState) : (GhostState, bool)\n requires ghost_tx_inv(s);\n requires old_mem_equiv(s);\n ensures ghost_state_inv(ghost_commit_tx(s).0);\n ensures ghost_tx_inv(ghost_commit_tx(s).0);\n ensures !ghost_commit_tx(s).1 ==> old_mem_equiv(ghost_commit_tx(s).0);\n ensures ghost_commit_tx(s).1 ==> ghost_commit_tx(s).0.num_entry == 0;\n{\n var s' := s;\n var (s', f) := set_num_entry(s', 0);\n var s' := if f then s'.(first_log_pos := map[]) else s';\n (s', f)\n}\n\nfunction ghost_tx_write (s0 : GhostState, off : int, val : int) : GhostState\n requires ghost_tx_inv(s0);\n requires old_mem_equiv(s0);\n requires 0 <= off < s0.mem_len;\n requires 0 <= s0.num_entry * 2 + 2 < |s0.log|;\n ensures ghost_tx_inv(ghost_tx_write(s0, off, val));\n ensures old_mem_equiv(ghost_tx_write(s0, off, val));\n ensures |ghost_tx_write(s0, off, val).mem| == s0.mem_len;\n ensures !crashed(ghost_tx_write(s0, off, val)) ==> ghost_tx_write(s0, off, val).mem[off] == val;\n{\n var s := s0;\n var log_idx := s.num_entry;\n var log_off := log_idx * 2;\n var old_val := s.mem[off];\n var (s, f) := log_write_step(s, log_off, off);\n var (s, f) := log_write_step(s, log_off + 1, old_val);\n var (s, f) := set_num_entry(s, log_idx + 1);\n var s := if f && !(off in s.first_log_pos)\n then s.(first_log_pos := s.first_log_pos[off := log_idx])\n else s;\n var (s, f) := mem_write_step(s, off, val);\n s\n}\n\nfunction reverse_recovery (s0 : GhostState, idx : int) : GhostState\n decreases idx;\n requires ghost_tx_inv(s0);\n requires old_mem_equiv(s0);\n requires 0 <= idx <= s0.num_entry;\n ensures ghost_tx_inv(reverse_recovery(s0, idx));\n ensures old_mem_equiv(reverse_recovery(s0, idx));\n ensures s0.old_mem == reverse_recovery(s0, idx).old_mem;\n ensures s0.first_log_pos == reverse_recovery(s0, idx).first_log_pos;\n ensures forall o :: o in s0.first_log_pos && s0.first_log_pos[o] >= idx ==>\n reverse_recovery(s0, idx).mem[o] == s0.mem[o];\n ensures forall o :: o in s0.first_log_pos && 0 <= s0.first_log_pos[o] < idx ==>\n reverse_recovery(s0, idx).mem[o] == s0.old_mem[o];\n{\n if idx == 0 then\n assert old_mem_equiv(s0);\n s0\n else\n var s := s0;\n var i := idx - 1;\n var off := s.log[i * 2];\n var val := s.log[i * 2 + 1];\n var s := s.(mem := s.mem[off := val]);\n assert off in s.first_log_pos;\n var s := reverse_recovery(s, idx - 1);\n assert i == idx - 1;\n assert forall o :: o in s.first_log_pos && 0 <= s.first_log_pos[o] < i ==>\n s.mem[o] == s.old_mem[o];\n assert forall o :: o in s.first_log_pos && s.first_log_pos[o] == i ==>\n o == off && val == s.old_mem[o];\n assert forall o :: o in s.first_log_pos && s.first_log_pos[o] == i ==>\n s.mem[o] == val;\n assert old_mem_equiv(s);\n s\n}\n\nfunction ghost_recover (s0 : GhostState) : GhostState\n requires ghost_tx_inv(s0);\n requires old_mem_equiv(s0);\n ensures ghost_recover(s0).mem == s0.old_mem;\n ensures ghost_recover(s0).num_entry == 0;\n{\n var s := reverse_recovery(s0, s0.num_entry);\n assert (old_mem_equiv(s));\n assert (forall o :: o in s.first_log_pos ==> s.mem[o] == s0.old_mem[o]);\n assert forall i :: 0 <= i < |s.mem| ==> s.mem[i] == s0.old_mem[i];\n s.(num_entry := 0)\n}\n\n\nclass UndoLog {\n var log_ : array;\n var mem_ : array;\n\n var impl_countdown : int;\n ghost var gs : GhostState;\n\n constructor () {}\n\n predicate ghost_state_equiv(gs : GhostState)\n reads this;\n reads mem_;\n reads log_;\n {\n log_.Length > 0 &&\n mem_[..] == gs.mem &&\n log_[1..] == gs.log &&\n log_[0] == gs.num_entry &&\n impl_countdown == gs.countdown\n }\n predicate state_inv()\n reads this;\n reads log_;\n {\n log_.Length > 1 && 0 <= log_[0] && (log_[0] * 2) < log_.Length\n && log_.Length < 0xffffffff && mem_ != log_\n && forall i : int :: 0 <= i < log_[0] ==> 0 <= log_[i * 2 + 1] < mem_.Length\n && impl_countdown >= 0\n }\n\n method init(log_size : int, mem_size : int, countdown : int)\n requires log_size > 1;\n requires mem_size > 0;\n requires log_size < 0xffffffff;\n modifies this;\n ensures fresh(log_);\n ensures fresh(mem_);\n ensures state_inv();\n ensures ghost_state_equiv(gs);\n {\n log_ := new int[log_size];\n mem_ := new int[mem_size];\n log_[0] := 0;\n\n impl_countdown := countdown;\n gs := GS(0, log_[1..], mem_size, mem_[..], mem_[..], mem_[..], countdown, map[]);\n }\n\n method impl_countdown_dec()\n modifies this;\n requires impl_countdown > 0;\n requires mem_ != log_;\n ensures mem_ != log_;\n ensures impl_countdown == old(impl_countdown) - 1;\n ensures impl_countdown >= 0;\n ensures gs == old(gs);\n ensures log_[..] == old(log_)[..];\n ensures mem_[..] == old(mem_)[..];\n {\n impl_countdown := impl_countdown - 1;\n }\n\n method write_mem(off : int, val : int)\n modifies this;\n modifies mem_;\n requires 0 <= off < mem_.Length;\n requires mem_ != log_;\n requires ghost_state_inv(gs);\n requires ghost_state_equiv(gs);\n requires 0 <= off < gs.mem_len;\n ensures mem_ == old(mem_);\n ensures log_ == old(log_);\n ensures gs == old(gs);\n ensures ghost_state_equiv(mem_write_step(gs, off, val).0);\n {\n if (impl_countdown > 0) {\n mem_[off] := val;\n impl_countdown := impl_countdown - 1;\n }\n }\n\n method write_log(off : int, val : int)\n modifies this;\n modifies log_;\n requires 0 <= off <= |gs.log|;\n requires mem_ != log_;\n requires ghost_state_inv(gs);\n requires ghost_state_equiv(gs);\n requires off == 0 ==> 0 <= val * 2 < |gs.log|;\n ensures mem_ != log_;\n ensures mem_ == old(mem_);\n ensures log_ == old(log_);\n ensures log_.Length == old(log_).Length;\n ensures mem_[..] == old(mem_)[..];\n ensures log_[off] == val || log_[off] == old(log_)[off];\n ensures forall i :: 0 <= i < log_.Length && i != off ==> log_[i] == old(log_)[i];\n ensures gs == old(gs);\n ensures off > 0 ==> ghost_state_equiv(log_write_step(gs, off - 1, val).0);\n ensures off == 0 ==> ghost_state_equiv(set_num_entry(gs, val).0);\n {\n if (impl_countdown > 0) {\n log_[off] := val;\n impl_countdown := impl_countdown - 1;\n }\n }\n\n method begin_tx()\n modifies log_;\n modifies this;\n requires state_inv();\n requires ghost_state_equiv(gs);\n requires ghost_state_inv(gs);\n requires log_[0] == 0;\n ensures mem_ == old(mem_);\n ensures log_ == old(log_);\n ensures state_inv();\n ensures ghost_state_equiv(gs);\n ensures ghost_tx_inv(gs);\n {\n write_log(0, 0);\n\n gs := ghost_begin_tx(gs);\n assert state_inv();\n }\n\n method commit_tx()\n modifies log_;\n modifies this;\n requires state_inv();\n requires ghost_state_equiv(gs);\n requires ghost_state_inv(gs);\n requires ghost_tx_inv(gs);\n requires old_mem_equiv(gs);\n ensures mem_ == old(mem_);\n ensures log_ == old(log_);\n ensures ghost_state_equiv(gs);\n ensures state_inv();\n {\n write_log(0, 0);\n\n gs := ghost_commit_tx(gs).0;\n }\n\n method tx_write(offset: int, val : int)\n modifies this;\n modifies log_;\n modifies mem_;\n requires state_inv();\n requires mem_ != log_;\n requires 0 <= offset < mem_.Length;\n requires ghost_state_equiv(gs);\n requires ghost_tx_inv(gs);\n requires old_mem_equiv(gs);\n requires 0 <= log_[0] * 2 + 3 < log_.Length;\n ensures ghost_state_equiv(gs);\n ensures ghost_tx_inv(gs);\n ensures old_mem_equiv(gs);\n {\n var log_idx := log_[0];\n var log_off := log_idx * 2;\n ghost var old_gs := gs;\n write_log(log_off + 1, offset);\n gs := log_write_step(gs, log_off, offset).0;\n assert log_off + 1 > 0;\n assert ghost_state_equiv(gs);\n assert mem_ != log_;\n var old_val := mem_[offset];\n assert old_val == gs.mem[offset];\n write_log(log_off + 2, old_val);\n \n gs := log_write_step(gs, log_off + 1, old_val).0;\n\n assert ghost_tx_inv(gs);\n assert log_[0] == gs.num_entry;\n assert log_.Length == |gs.log| + 1;\n assert 0 <= gs.num_entry * 2 < |gs.log|;\n \n write_log(0, log_idx + 1);\n\n ghost var (s, f) := set_num_entry(gs, log_idx + 1);\n s := if f && !(offset in s.first_log_pos)\n then s.(first_log_pos := s.first_log_pos[offset := log_idx])\n else s;\n gs := s;\n write_mem(offset, val);\n gs := mem_write_step(gs, offset, val).0;\n\n assert gs == ghost_tx_write(old_gs, offset, val);\n }\n\n // we assume that recover won't crash (though this code works when recover can fail)\n method recover()\n modifies log_;\n modifies mem_;\n modifies this;\n requires state_inv();\n requires ghost_tx_inv(gs);\n requires old_mem_equiv(gs);\n requires ghost_state_equiv(gs);\n ensures gs == ghost_recover(old(gs));\n ensures ghost_state_equiv(gs);\n {\n var log_len := log_[0];\n assert log_len == gs.num_entry;\n if (log_len > 0) {\n var i := log_len - 1;\n\n ghost var gs0 := gs;\n while i >= 0\n modifies mem_;\n modifies this;\n invariant log_ == old(log_);\n invariant mem_ == old(mem_);\n invariant unchanged(log_);\n invariant -1 <= i < log_len;\n invariant |gs.log| == |gs0.log|;\n invariant ghost_state_equiv(gs);\n invariant ghost_tx_inv(gs);\n invariant old_mem_equiv(gs);\n invariant reverse_recovery(gs0, log_len) == reverse_recovery(gs, i + 1);\n decreases i;\n {\n assert ghost_state_equiv(gs);\n assert 0 <= i < log_[0];\n var o := i * 2 + 1;\n var off := log_[o];\n var val := log_[o + 1];\n mem_[off] := val;\n assert 0 <= off < mem_.Length;\n\n assert gs.log[i * 2] == off;\n assert gs.log[i * 2 + 1] == val;\n gs := gs.(mem := gs.mem[off := val]);\n i := i - 1;\n }\n assert ghost_state_equiv(gs);\n } else {\n assert ghost_state_equiv(gs);\n }\n log_[0] := 0;\n gs := ghost_recover(old(gs));\n assert ghost_state_equiv(gs);\n }\n}\n\nlemma crash_safe_single_tx(init_log : seq, init_mem : seq,\n countdown : int,\n writes : seq<(int, int)>)\n requires |init_log| > 0;\n requires countdown >= 0;\n requires forall i :: 0 <= i < |writes| ==>\n 0 <= writes[i].0 < |init_mem|;\n requires 0 < |writes| * 2 < |init_log|;\n{\n var s := init_ghost_state(init_log, init_mem, countdown);\n\n var end_mem := init_mem;\n\n s := ghost_begin_tx(s);\n assert s.num_entry == 0;\n assert init_mem == s.old_mem;\n\n var i := 0;\n while i < |writes|\n decreases |writes| - i;\n invariant 0 <= i <= |writes|;\n invariant s.mem_len == |init_mem|;\n invariant s.mem_len == |end_mem|;\n invariant 0 <= s.num_entry <= i;\n invariant |init_log| == |s.log|;\n invariant i * 2 < |s.log|;\n invariant 0 <= s.num_entry * 2 < |s.log|;\n invariant ghost_tx_inv(s);\n invariant old_mem_equiv(s);\n invariant init_mem == s.old_mem;\n invariant !crashed(s) ==> forall i :: 0 <= i < |s.mem| ==> s.mem[i] == end_mem[i];\n {\n assert 0 <= i < |writes|;\n assert 0 <= writes[i].0 < s.mem_len;\n assert 0 <= s.num_entry * 2 + 2 < |s.log|;\n s := ghost_tx_write(s, writes[i].0, writes[i].1);\n\n end_mem := end_mem[writes[i].0 := writes[i].1];\n\n assert !crashed(s) ==> s.mem[writes[i].0] == writes[i].1;\n i := i + 1;\n }\n\n assert ghost_tx_inv(s);\n assert old_mem_equiv(s);\n\n var (s', c) := ghost_commit_tx(s);\n assert c ==> !crashed(s);\n\n if (c) {\n assert !crashed(s);\n assert s.mem == end_mem;\n } else {\n var recovered := ghost_recover(s');\n assert recovered.mem == init_mem;\n }\n}\n", "hints_removed": "class CrashableMem {\n var mem_ : array;\n method read(off : int) returns (r : T)\n requires 0 <= off < mem_.Length;\n {\n return mem_[off];\n }\n\n method write(off : int, val : T)\n requires 0 <= off < mem_.Length;\n modifies mem_;\n {\n mem_[off] := val;\n }\n}\n\ndatatype GhostState = GS(\n num_entry : int,\n log : seq,\n\n mem_len : int,\n mem : seq,\n old_mem : seq,\n ideal_mem : seq,\n countdown : int,\n first_log_pos : map\n)\n\ndatatype GhostOp = WriteMem(off : int, val : int)\n | WriteLog(off : int, val : int)\npredicate ghost_state_inv(s : GhostState) {\n 0 <= s.num_entry * 2 < |s.log|\n && |s.log| > 0\n && |s.mem| == s.mem_len && |s.ideal_mem| == s.mem_len && |s.old_mem| == s.mem_len\n && s.countdown >= 0\n}\n\nfunction init_ghost_state(log : seq, mem : seq, countdown : int) : GhostState\n requires |log| > 0;\n requires countdown >= 0;\n ensures ghost_state_inv(init_ghost_state(log, mem, countdown));\n{\n GS(0, log[..], |mem|, mem[..], mem[..], mem[..], countdown, map[])\n}\n\nfunction mem_write(s : GhostState, off: int, val: int) : GhostState\n requires ghost_state_inv(s);\n requires 0 <= off < s.mem_len;\n ensures ghost_state_inv(mem_write(s, off, val));\n{\n var new_mem := s.mem[off := val];\n var new_ideal_mem := s.ideal_mem[off := val];\n s.(mem := new_mem,\n ideal_mem := new_ideal_mem)\n}\n\nfunction log_write(s : GhostState, off : int, val: int) : GhostState\n requires ghost_state_inv(s);\n requires 0 <= off < |s.log|;\n ensures ghost_state_inv(log_write(s, off, val));\n{\n s.(log := s.log[off := val])\n}\n\npredicate valid_op(s : GhostState, op : GhostOp)\n{\n match op\n case WriteMem(off, val) => 0 <= off < |s.mem|\n case WriteLog(off, val) => 0 <= off < |s.log|\n}\n\nfunction countdown (s : GhostState) : GhostState\n{\n if s.countdown > 0 then\n s.(countdown := s.countdown - 1)\n else\n s\n}\n\nfunction normal_step (s : GhostState, op : GhostOp) : GhostState\n requires valid_op(s, op);\n requires ghost_state_inv(s);\n ensures ghost_state_inv(normal_step(s, op));\n{\n match op\n case WriteMem(off, val) => mem_write(s, off, val)\n case WriteLog(off, val) => log_write(s, off, val)\n}\n\nfunction ghost_step (s : GhostState, op : GhostOp) : (GhostState, bool)\n requires valid_op(s, op);\n requires ghost_state_inv(s);\n ensures ghost_state_inv(normal_step(s, op));\n{\n if s.countdown > 0 then\n var s' := normal_step(s, op);\n (s'.(countdown := s.countdown - 1), true)\n else\n (s, false)\n}\n\nfunction mem_write_step (s : GhostState, off : int, val : int) : (GhostState, bool)\n requires 0 <= off < s.mem_len;\n requires ghost_state_inv(s);\n{\n ghost_step(s, WriteMem(off, val))\n}\n\nfunction log_write_step (s : GhostState, off : int, val : int) : (GhostState, bool)\n requires 0 <= off < |s.log|;\n requires ghost_state_inv(s);\n{\n ghost_step(s, WriteLog(off, val))\n}\n\nfunction set_num_entry (s : GhostState, n : int) : (GhostState, bool)\n requires 0 <= n * 2 < |s.log|;\n{\n if s.countdown > 0 then\n (s.(num_entry := n,\n countdown := s.countdown - 1),\n true)\n else\n (s, false)\n}\n\npredicate crashed (s : GhostState)\n{\n s.countdown <= 0\n}\n\npredicate old_mem_equiv (s : GhostState)\n requires ghost_state_inv(s);\n{\n (forall o :: !(o in s.first_log_pos) && 0 <= o < |s.mem| ==> s.mem[o] == s.old_mem[o])\n}\n\npredicate ghost_tx_inv (s : GhostState)\n{\n ghost_state_inv(s) &&\n (forall o :: o in s.first_log_pos ==> 0 <= o < s.mem_len) &&\n (forall o :: o in s.first_log_pos ==> 0 <= s.first_log_pos[o] < s.num_entry) &&\n (forall o :: o in s.first_log_pos ==> 0 <= s.first_log_pos[o] * 2 + 1 < |s.log|) &&\n (forall o :: o in s.first_log_pos ==> s.log[s.first_log_pos[o] * 2] == o) &&\n (forall o :: o in s.first_log_pos ==> s.log[s.first_log_pos[o] * 2 + 1] == s.old_mem[o]) &&\n (forall o :: o in s.first_log_pos ==> forall i :: 0 <= i < s.first_log_pos[o] ==> s.log[i * 2] != o) &&\n (forall i :: 0 <= i < s.num_entry ==> s.log[i * 2] in s.first_log_pos)\n}\n\nfunction ghost_begin_tx (s : GhostState) : GhostState\n requires ghost_state_inv(s);\n requires s.num_entry == 0;\n ensures ghost_state_inv(ghost_begin_tx(s));\n ensures ghost_tx_inv(ghost_begin_tx(s));\n ensures old_mem_equiv(ghost_begin_tx(s));\n{\n var (s', f) := set_num_entry(s, 0);\n var s' := s'.(first_log_pos := map[], old_mem := s.mem[..]);\n s'\n}\n\nfunction ghost_commit_tx (s : GhostState) : (GhostState, bool)\n requires ghost_tx_inv(s);\n requires old_mem_equiv(s);\n ensures ghost_state_inv(ghost_commit_tx(s).0);\n ensures ghost_tx_inv(ghost_commit_tx(s).0);\n ensures !ghost_commit_tx(s).1 ==> old_mem_equiv(ghost_commit_tx(s).0);\n ensures ghost_commit_tx(s).1 ==> ghost_commit_tx(s).0.num_entry == 0;\n{\n var s' := s;\n var (s', f) := set_num_entry(s', 0);\n var s' := if f then s'.(first_log_pos := map[]) else s';\n (s', f)\n}\n\nfunction ghost_tx_write (s0 : GhostState, off : int, val : int) : GhostState\n requires ghost_tx_inv(s0);\n requires old_mem_equiv(s0);\n requires 0 <= off < s0.mem_len;\n requires 0 <= s0.num_entry * 2 + 2 < |s0.log|;\n ensures ghost_tx_inv(ghost_tx_write(s0, off, val));\n ensures old_mem_equiv(ghost_tx_write(s0, off, val));\n ensures |ghost_tx_write(s0, off, val).mem| == s0.mem_len;\n ensures !crashed(ghost_tx_write(s0, off, val)) ==> ghost_tx_write(s0, off, val).mem[off] == val;\n{\n var s := s0;\n var log_idx := s.num_entry;\n var log_off := log_idx * 2;\n var old_val := s.mem[off];\n var (s, f) := log_write_step(s, log_off, off);\n var (s, f) := log_write_step(s, log_off + 1, old_val);\n var (s, f) := set_num_entry(s, log_idx + 1);\n var s := if f && !(off in s.first_log_pos)\n then s.(first_log_pos := s.first_log_pos[off := log_idx])\n else s;\n var (s, f) := mem_write_step(s, off, val);\n s\n}\n\nfunction reverse_recovery (s0 : GhostState, idx : int) : GhostState\n requires ghost_tx_inv(s0);\n requires old_mem_equiv(s0);\n requires 0 <= idx <= s0.num_entry;\n ensures ghost_tx_inv(reverse_recovery(s0, idx));\n ensures old_mem_equiv(reverse_recovery(s0, idx));\n ensures s0.old_mem == reverse_recovery(s0, idx).old_mem;\n ensures s0.first_log_pos == reverse_recovery(s0, idx).first_log_pos;\n ensures forall o :: o in s0.first_log_pos && s0.first_log_pos[o] >= idx ==>\n reverse_recovery(s0, idx).mem[o] == s0.mem[o];\n ensures forall o :: o in s0.first_log_pos && 0 <= s0.first_log_pos[o] < idx ==>\n reverse_recovery(s0, idx).mem[o] == s0.old_mem[o];\n{\n if idx == 0 then\n s0\n else\n var s := s0;\n var i := idx - 1;\n var off := s.log[i * 2];\n var val := s.log[i * 2 + 1];\n var s := s.(mem := s.mem[off := val]);\n var s := reverse_recovery(s, idx - 1);\n s.mem[o] == s.old_mem[o];\n o == off && val == s.old_mem[o];\n s.mem[o] == val;\n s\n}\n\nfunction ghost_recover (s0 : GhostState) : GhostState\n requires ghost_tx_inv(s0);\n requires old_mem_equiv(s0);\n ensures ghost_recover(s0).mem == s0.old_mem;\n ensures ghost_recover(s0).num_entry == 0;\n{\n var s := reverse_recovery(s0, s0.num_entry);\n s.(num_entry := 0)\n}\n\n\nclass UndoLog {\n var log_ : array;\n var mem_ : array;\n\n var impl_countdown : int;\n ghost var gs : GhostState;\n\n constructor () {}\n\n predicate ghost_state_equiv(gs : GhostState)\n reads this;\n reads mem_;\n reads log_;\n {\n log_.Length > 0 &&\n mem_[..] == gs.mem &&\n log_[1..] == gs.log &&\n log_[0] == gs.num_entry &&\n impl_countdown == gs.countdown\n }\n predicate state_inv()\n reads this;\n reads log_;\n {\n log_.Length > 1 && 0 <= log_[0] && (log_[0] * 2) < log_.Length\n && log_.Length < 0xffffffff && mem_ != log_\n && forall i : int :: 0 <= i < log_[0] ==> 0 <= log_[i * 2 + 1] < mem_.Length\n && impl_countdown >= 0\n }\n\n method init(log_size : int, mem_size : int, countdown : int)\n requires log_size > 1;\n requires mem_size > 0;\n requires log_size < 0xffffffff;\n modifies this;\n ensures fresh(log_);\n ensures fresh(mem_);\n ensures state_inv();\n ensures ghost_state_equiv(gs);\n {\n log_ := new int[log_size];\n mem_ := new int[mem_size];\n log_[0] := 0;\n\n impl_countdown := countdown;\n gs := GS(0, log_[1..], mem_size, mem_[..], mem_[..], mem_[..], countdown, map[]);\n }\n\n method impl_countdown_dec()\n modifies this;\n requires impl_countdown > 0;\n requires mem_ != log_;\n ensures mem_ != log_;\n ensures impl_countdown == old(impl_countdown) - 1;\n ensures impl_countdown >= 0;\n ensures gs == old(gs);\n ensures log_[..] == old(log_)[..];\n ensures mem_[..] == old(mem_)[..];\n {\n impl_countdown := impl_countdown - 1;\n }\n\n method write_mem(off : int, val : int)\n modifies this;\n modifies mem_;\n requires 0 <= off < mem_.Length;\n requires mem_ != log_;\n requires ghost_state_inv(gs);\n requires ghost_state_equiv(gs);\n requires 0 <= off < gs.mem_len;\n ensures mem_ == old(mem_);\n ensures log_ == old(log_);\n ensures gs == old(gs);\n ensures ghost_state_equiv(mem_write_step(gs, off, val).0);\n {\n if (impl_countdown > 0) {\n mem_[off] := val;\n impl_countdown := impl_countdown - 1;\n }\n }\n\n method write_log(off : int, val : int)\n modifies this;\n modifies log_;\n requires 0 <= off <= |gs.log|;\n requires mem_ != log_;\n requires ghost_state_inv(gs);\n requires ghost_state_equiv(gs);\n requires off == 0 ==> 0 <= val * 2 < |gs.log|;\n ensures mem_ != log_;\n ensures mem_ == old(mem_);\n ensures log_ == old(log_);\n ensures log_.Length == old(log_).Length;\n ensures mem_[..] == old(mem_)[..];\n ensures log_[off] == val || log_[off] == old(log_)[off];\n ensures forall i :: 0 <= i < log_.Length && i != off ==> log_[i] == old(log_)[i];\n ensures gs == old(gs);\n ensures off > 0 ==> ghost_state_equiv(log_write_step(gs, off - 1, val).0);\n ensures off == 0 ==> ghost_state_equiv(set_num_entry(gs, val).0);\n {\n if (impl_countdown > 0) {\n log_[off] := val;\n impl_countdown := impl_countdown - 1;\n }\n }\n\n method begin_tx()\n modifies log_;\n modifies this;\n requires state_inv();\n requires ghost_state_equiv(gs);\n requires ghost_state_inv(gs);\n requires log_[0] == 0;\n ensures mem_ == old(mem_);\n ensures log_ == old(log_);\n ensures state_inv();\n ensures ghost_state_equiv(gs);\n ensures ghost_tx_inv(gs);\n {\n write_log(0, 0);\n\n gs := ghost_begin_tx(gs);\n }\n\n method commit_tx()\n modifies log_;\n modifies this;\n requires state_inv();\n requires ghost_state_equiv(gs);\n requires ghost_state_inv(gs);\n requires ghost_tx_inv(gs);\n requires old_mem_equiv(gs);\n ensures mem_ == old(mem_);\n ensures log_ == old(log_);\n ensures ghost_state_equiv(gs);\n ensures state_inv();\n {\n write_log(0, 0);\n\n gs := ghost_commit_tx(gs).0;\n }\n\n method tx_write(offset: int, val : int)\n modifies this;\n modifies log_;\n modifies mem_;\n requires state_inv();\n requires mem_ != log_;\n requires 0 <= offset < mem_.Length;\n requires ghost_state_equiv(gs);\n requires ghost_tx_inv(gs);\n requires old_mem_equiv(gs);\n requires 0 <= log_[0] * 2 + 3 < log_.Length;\n ensures ghost_state_equiv(gs);\n ensures ghost_tx_inv(gs);\n ensures old_mem_equiv(gs);\n {\n var log_idx := log_[0];\n var log_off := log_idx * 2;\n ghost var old_gs := gs;\n write_log(log_off + 1, offset);\n gs := log_write_step(gs, log_off, offset).0;\n var old_val := mem_[offset];\n write_log(log_off + 2, old_val);\n \n gs := log_write_step(gs, log_off + 1, old_val).0;\n\n \n write_log(0, log_idx + 1);\n\n ghost var (s, f) := set_num_entry(gs, log_idx + 1);\n s := if f && !(offset in s.first_log_pos)\n then s.(first_log_pos := s.first_log_pos[offset := log_idx])\n else s;\n gs := s;\n write_mem(offset, val);\n gs := mem_write_step(gs, offset, val).0;\n\n }\n\n // we assume that recover won't crash (though this code works when recover can fail)\n method recover()\n modifies log_;\n modifies mem_;\n modifies this;\n requires state_inv();\n requires ghost_tx_inv(gs);\n requires old_mem_equiv(gs);\n requires ghost_state_equiv(gs);\n ensures gs == ghost_recover(old(gs));\n ensures ghost_state_equiv(gs);\n {\n var log_len := log_[0];\n if (log_len > 0) {\n var i := log_len - 1;\n\n ghost var gs0 := gs;\n while i >= 0\n modifies mem_;\n modifies this;\n {\n var o := i * 2 + 1;\n var off := log_[o];\n var val := log_[o + 1];\n mem_[off] := val;\n\n gs := gs.(mem := gs.mem[off := val]);\n i := i - 1;\n }\n } else {\n }\n log_[0] := 0;\n gs := ghost_recover(old(gs));\n }\n}\n\nlemma crash_safe_single_tx(init_log : seq, init_mem : seq,\n countdown : int,\n writes : seq<(int, int)>)\n requires |init_log| > 0;\n requires countdown >= 0;\n requires forall i :: 0 <= i < |writes| ==>\n 0 <= writes[i].0 < |init_mem|;\n requires 0 < |writes| * 2 < |init_log|;\n{\n var s := init_ghost_state(init_log, init_mem, countdown);\n\n var end_mem := init_mem;\n\n s := ghost_begin_tx(s);\n\n var i := 0;\n while i < |writes|\n {\n s := ghost_tx_write(s, writes[i].0, writes[i].1);\n\n end_mem := end_mem[writes[i].0 := writes[i].1];\n\n i := i + 1;\n }\n\n\n var (s', c) := ghost_commit_tx(s);\n\n if (c) {\n } else {\n var recovered := ghost_recover(s');\n }\n}\n" }, { "test_ID": "328", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_mathematical objects verification_examples_fast_exp.dfy", "ground_truth": "function exp(b: nat, n: nat): nat {\n if n == 0 then 1\n else b * exp(b, n-1)\n}\n\nlemma exp_sum(b: nat, n1: nat, n2: nat)\n ensures exp(b, n1 + n2) == exp(b, n1) * exp(b, n2)\n{\n if n1 == 0 {\n return;\n } else {\n exp_sum(b, n1-1, n2);\n }\n}\n\nlemma exp_sum_auto(b: nat)\n ensures forall n1: nat, n2: nat :: exp(b, n1 + n2) == exp(b, n1) * exp(b, n2)\n{\n forall n1: nat, n2: nat\n ensures exp(b, n1 + n2) == exp(b, n1) * exp(b, n2) {\n exp_sum(b, n1, n2);\n }\n}\n\nfunction bits(n: nat): seq\n decreases n\n{\n if n == 0 then []\n else [if (n % 2 == 0) then false else true] + bits(n/2)\n}\n\nfunction from_bits(s: seq): nat {\n if s == [] then 0\n else (if s[0] then 1 else 0) + 2 * from_bits(s[1..])\n}\n\nlemma bits_from_bits(n: nat)\n ensures from_bits(bits(n)) == n\n{\n}\n\nlemma bits_trim_front(n: nat)\n requires n > 0\n ensures from_bits(bits(n)[1..]) == n/2\n{}\n\nlemma from_bits_append(s: seq, b: bool)\n ensures from_bits(s + [b]) == from_bits(s) + exp(2, |s|) * (if b then 1 else 0)\n{\n if s == [] {\n return;\n }\n assert s == [s[0]] + s[1..];\n from_bits_append(s[1..], b);\n // from recursive call\n assert from_bits(s[1..] + [b]) == from_bits(s[1..]) + exp(2, |s|-1) * (if b then 1 else 0);\n exp_sum(2, |s|-1, 1);\n assert (s + [b])[1..] == s[1..] + [b]; // observe\n assert from_bits(s + [b]) == (if s[0] then 1 else 0) + 2 * from_bits(s[1..] + [b]);\n}\n\nlemma from_bits_sum(s1: seq, s2: seq)\n decreases s2\n ensures from_bits(s1 + s2) == from_bits(s1) + exp(2, |s1|) * from_bits(s2)\n{\n if s2 == [] {\n assert s1 + s2 == s1;\n return;\n }\n from_bits_sum(s1 + [s2[0]], s2[1..]);\n assert s1 + [s2[0]] + s2[1..] == s1 + s2;\n from_bits_append(s1, s2[0]);\n assume false; // TODO\n}\n\nmethod fast_exp(b: nat, n: nat) returns (r: nat)\n ensures r == exp(b, n)\n{\n var a := 1;\n var c := b;\n ghost var n0 := n;\n var n := n;\n ghost var i: nat := 0;\n bits_from_bits(n);\n while n > 0\n decreases n\n invariant c == exp(b, exp(2, i))\n invariant n <= n0\n invariant i <= |bits(n0)|\n invariant bits(n) == bits(n0)[i..]\n invariant n == from_bits(bits(n0)[i..])\n invariant a == exp(b, from_bits(bits(n0)[..i]))\n {\n ghost var n_loop_top := n;\n if n % 2 == 1 {\n assert bits(n)[0] == true;\n // a accumulates sum(i => b^(2^n_i), i) where n_i are the 1 bits of n\n // TODO: n0-n is sum(i => 2^n_i, i), right?\n a := a * c;\n exp_sum(b, n0-n, i);\n // (n-1)/2 == n/2 in this case, but we want to be extra clear that we're\n // \"dropping\" a 1 bit here and so something interesting is happening\n n := (n-1) / 2;\n assert 2 * exp(2, i) == exp(2, i+1);\n assert a == exp(b, from_bits(bits(n0)[..i]) + exp(2, i)) by {\n exp_sum_auto(b);\n }\n assume false;\n assert a == exp(b, from_bits(bits(n0)[..i+1]));\n } else {\n assert bits(n)[0] == false;\n n := n / 2;\n assume false;\n assert a == exp(b, from_bits(bits(n0)[..i+1]));\n }\n assert n == n_loop_top/2;\n c := c * c;\n exp_sum(b, exp(2, i), exp(2, i));\n // assert bits(n0)[i+1..] == bits(n0)[i..][1..];\n i := i + 1;\n }\n assert bits(n0)[..i] == bits(n0);\n return a;\n}\n\n", "hints_removed": "function exp(b: nat, n: nat): nat {\n if n == 0 then 1\n else b * exp(b, n-1)\n}\n\nlemma exp_sum(b: nat, n1: nat, n2: nat)\n ensures exp(b, n1 + n2) == exp(b, n1) * exp(b, n2)\n{\n if n1 == 0 {\n return;\n } else {\n exp_sum(b, n1-1, n2);\n }\n}\n\nlemma exp_sum_auto(b: nat)\n ensures forall n1: nat, n2: nat :: exp(b, n1 + n2) == exp(b, n1) * exp(b, n2)\n{\n forall n1: nat, n2: nat\n ensures exp(b, n1 + n2) == exp(b, n1) * exp(b, n2) {\n exp_sum(b, n1, n2);\n }\n}\n\nfunction bits(n: nat): seq\n{\n if n == 0 then []\n else [if (n % 2 == 0) then false else true] + bits(n/2)\n}\n\nfunction from_bits(s: seq): nat {\n if s == [] then 0\n else (if s[0] then 1 else 0) + 2 * from_bits(s[1..])\n}\n\nlemma bits_from_bits(n: nat)\n ensures from_bits(bits(n)) == n\n{\n}\n\nlemma bits_trim_front(n: nat)\n requires n > 0\n ensures from_bits(bits(n)[1..]) == n/2\n{}\n\nlemma from_bits_append(s: seq, b: bool)\n ensures from_bits(s + [b]) == from_bits(s) + exp(2, |s|) * (if b then 1 else 0)\n{\n if s == [] {\n return;\n }\n from_bits_append(s[1..], b);\n // from recursive call\n exp_sum(2, |s|-1, 1);\n}\n\nlemma from_bits_sum(s1: seq, s2: seq)\n ensures from_bits(s1 + s2) == from_bits(s1) + exp(2, |s1|) * from_bits(s2)\n{\n if s2 == [] {\n return;\n }\n from_bits_sum(s1 + [s2[0]], s2[1..]);\n from_bits_append(s1, s2[0]);\n assume false; // TODO\n}\n\nmethod fast_exp(b: nat, n: nat) returns (r: nat)\n ensures r == exp(b, n)\n{\n var a := 1;\n var c := b;\n ghost var n0 := n;\n var n := n;\n ghost var i: nat := 0;\n bits_from_bits(n);\n while n > 0\n {\n ghost var n_loop_top := n;\n if n % 2 == 1 {\n // a accumulates sum(i => b^(2^n_i), i) where n_i are the 1 bits of n\n // TODO: n0-n is sum(i => 2^n_i, i), right?\n a := a * c;\n exp_sum(b, n0-n, i);\n // (n-1)/2 == n/2 in this case, but we want to be extra clear that we're\n // \"dropping\" a 1 bit here and so something interesting is happening\n n := (n-1) / 2;\n exp_sum_auto(b);\n }\n assume false;\n } else {\n n := n / 2;\n assume false;\n }\n c := c * c;\n exp_sum(b, exp(2, i), exp(2, i));\n // assert bits(n0)[i+1..] == bits(n0)[i..][1..];\n i := i + 1;\n }\n return a;\n}\n\n" }, { "test_ID": "329", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_mathematical objects verification_examples_interval_example.dfy", "ground_truth": "/* Here's a small but realistic setting where you could use Dafny.\n\n The setting is that we're implementing an interval library that manages a\n data structure with a low and a high value. It implements some computations\n on intervals, and we want to make sure those are right.\n */\n\n// Interval is the Dafny model of the data structure itself. We're using `real`\n// here for the numbers; the specifics don't really matter, as long as we can\n// compare them with <.\ndatatype Interval = Interval(lo: real, hi: real)\n\n// Contains is one of the core operations on intervals, both because we support\n// it in the API and because in some ways it defines what the interval means.\npredicate contains(i: Interval, r: real) {\n i.lo <= r <= i.hi\n}\n\n// We also provide a way to check if an interval is empty.\npredicate empty(i: Interval) {\n i.lo > i.hi\n}\n\n/* Now we can already do our first proof! Empty is a way to check if an interval\n * doesn't contain any numbers - let's prove that empty and contains agree with\n * each other. */\n\nlemma empty_ok(i: Interval)\n // this is the sort of property that's easy to express logically but hard to test for\n ensures empty(i) <==> !exists r :: contains(i, r)\n{\n if empty(i) {\n } else {\n assert contains(i, i.lo);\n }\n}\n\n// min and max are just helper functions for the implementation\nfunction min(r1: real, r2: real): real {\n if r1 < r2 then r1 else r2\n}\n\nfunction max(r1: real, r2: real): real {\n if r1 > r2 then r1 else r2\n}\n\n/* The first complicated operation we expose is a function to intersect two\n * intervals. It's not so easy to think about whether this is correct - for\n * example, does it handle empty intervals correctly? Maybe two empty intervals\n * could intersect to a non-empty one? */\n\nfunction intersect(i1: Interval, i2: Interval): Interval {\n Interval(max(i1.lo, i2.lo), min(i1.hi, i2.hi))\n}\n\n// This theorem proves that intersect does exactly what we wanted it to, using\n// `contains` as the specification.\nlemma intersect_ok(i1: Interval, i2: Interval)\n ensures forall r :: contains(intersect(i1, i2), r) <==> contains(i1, r) && contains(i2, r)\n{\n}\n\n/* Next we'll define the union of intervals. This is more complicated because if\n * the intervals have no overlap, a single interval can't capture their union\n * exactly. */\n\n// Intersect gives us an easy way to define overlap, and we already know it\n// handles empty intervals correctly.\npredicate overlap(i1: Interval, i2: Interval) {\n !empty(intersect(i1, i2))\n}\n\nlemma overlap_ok(i1: Interval, i2: Interval)\n ensures overlap(i1, i2) <==> exists r :: contains(i1, r) && contains(i2, r)\n{\n if overlap(i1, i2) {\n if i1.lo >= i2.lo {\n assert contains(i2, i1.lo);\n } else {\n assert contains(i1, i2.lo);\n }\n }\n}\n\n// We'll give this function a precondition so that it always does the right thing.\nfunction union(i1: Interval, i2: Interval): Interval\n requires overlap(i1, i2)\n{\n Interval(min(i1.lo, i2.lo), max(i1.hi, i2.hi))\n}\n\n// We can prove union correct in much the same way as intersect, with a similar\n// specification, although notice that now we require that the intervals\n// overlap.\nlemma union_ok(i1: Interval, i2: Interval)\n requires overlap(i1, i2)\n ensures forall r :: contains(union(i1, i2), r) <==> contains(i1, r) || contains(i2, r)\n{\n}\n\n// Though not used elsewhere here, if two intervals overlap its possible to show\n// that there's a common real contained in both of them. We also show off new\n// syntax: this lemma returns a value which is used in the postcondition, and\n// which the calling lemma can make use of.\nlemma overlap_witness(i1: Interval, i2: Interval) returns (r: real)\n requires overlap(i1, i2)\n ensures contains(i1, r) && contains(i2, r)\n{\n if i1.lo >= i2.lo {\n r := i1.lo;\n } else {\n r := i2.lo;\n }\n}\n\n/* One extension you might try is adding is an operation to check if an interval\n * is contained in another and proving that correct. Or, try implementing a\n * similar library for 2D rectangles. */\n\n", "hints_removed": "/* Here's a small but realistic setting where you could use Dafny.\n\n The setting is that we're implementing an interval library that manages a\n data structure with a low and a high value. It implements some computations\n on intervals, and we want to make sure those are right.\n */\n\n// Interval is the Dafny model of the data structure itself. We're using `real`\n// here for the numbers; the specifics don't really matter, as long as we can\n// compare them with <.\ndatatype Interval = Interval(lo: real, hi: real)\n\n// Contains is one of the core operations on intervals, both because we support\n// it in the API and because in some ways it defines what the interval means.\npredicate contains(i: Interval, r: real) {\n i.lo <= r <= i.hi\n}\n\n// We also provide a way to check if an interval is empty.\npredicate empty(i: Interval) {\n i.lo > i.hi\n}\n\n/* Now we can already do our first proof! Empty is a way to check if an interval\n * doesn't contain any numbers - let's prove that empty and contains agree with\n * each other. */\n\nlemma empty_ok(i: Interval)\n // this is the sort of property that's easy to express logically but hard to test for\n ensures empty(i) <==> !exists r :: contains(i, r)\n{\n if empty(i) {\n } else {\n }\n}\n\n// min and max are just helper functions for the implementation\nfunction min(r1: real, r2: real): real {\n if r1 < r2 then r1 else r2\n}\n\nfunction max(r1: real, r2: real): real {\n if r1 > r2 then r1 else r2\n}\n\n/* The first complicated operation we expose is a function to intersect two\n * intervals. It's not so easy to think about whether this is correct - for\n * example, does it handle empty intervals correctly? Maybe two empty intervals\n * could intersect to a non-empty one? */\n\nfunction intersect(i1: Interval, i2: Interval): Interval {\n Interval(max(i1.lo, i2.lo), min(i1.hi, i2.hi))\n}\n\n// This theorem proves that intersect does exactly what we wanted it to, using\n// `contains` as the specification.\nlemma intersect_ok(i1: Interval, i2: Interval)\n ensures forall r :: contains(intersect(i1, i2), r) <==> contains(i1, r) && contains(i2, r)\n{\n}\n\n/* Next we'll define the union of intervals. This is more complicated because if\n * the intervals have no overlap, a single interval can't capture their union\n * exactly. */\n\n// Intersect gives us an easy way to define overlap, and we already know it\n// handles empty intervals correctly.\npredicate overlap(i1: Interval, i2: Interval) {\n !empty(intersect(i1, i2))\n}\n\nlemma overlap_ok(i1: Interval, i2: Interval)\n ensures overlap(i1, i2) <==> exists r :: contains(i1, r) && contains(i2, r)\n{\n if overlap(i1, i2) {\n if i1.lo >= i2.lo {\n } else {\n }\n }\n}\n\n// We'll give this function a precondition so that it always does the right thing.\nfunction union(i1: Interval, i2: Interval): Interval\n requires overlap(i1, i2)\n{\n Interval(min(i1.lo, i2.lo), max(i1.hi, i2.hi))\n}\n\n// We can prove union correct in much the same way as intersect, with a similar\n// specification, although notice that now we require that the intervals\n// overlap.\nlemma union_ok(i1: Interval, i2: Interval)\n requires overlap(i1, i2)\n ensures forall r :: contains(union(i1, i2), r) <==> contains(i1, r) || contains(i2, r)\n{\n}\n\n// Though not used elsewhere here, if two intervals overlap its possible to show\n// that there's a common real contained in both of them. We also show off new\n// syntax: this lemma returns a value which is used in the postcondition, and\n// which the calling lemma can make use of.\nlemma overlap_witness(i1: Interval, i2: Interval) returns (r: real)\n requires overlap(i1, i2)\n ensures contains(i1, r) && contains(i2, r)\n{\n if i1.lo >= i2.lo {\n r := i1.lo;\n } else {\n r := i2.lo;\n }\n}\n\n/* One extension you might try is adding is an operation to check if an interval\n * is contained in another and proving that correct. Or, try implementing a\n * similar library for 2D rectangles. */\n\n" }, { "test_ID": "330", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_mathematical objects verification_examples_library.dfy", "ground_truth": "/*\n A simple state machine modeling checking out and returning books in a library.\n*/\n\n// Status will track where one book is\ndatatype Status = Shelf | Patron(name: string)\ndatatype Book = Book(title: string)\n\n// The state of the whole library is just the status of every book owned by the\n// library.\ndatatype Variables = Variables(library: map)\n{\n // New syntax (member function): the curly braces below the datatype introduce\n // a set of _member functions_, which can be called as v.f(), just like Java,\n // C++, or Rust methods. Just like in Java or C++, the body can use the `this`\n // keyword to refer to an implicit argument of type Variables.\n ghost predicate WellFormed()\n {\n // New syntax (x in m for maps): maps have a domain and we can write x in m\n // to say x is in the domain of m (similarly, `x !in m` is a more readable\n // version of `!(x in m)`). As with sequences where indices need to be in\n // bounds, to write `m[x]` you'll need to show that `x in m` holds.\n //\n // What we're saying here is that the empty-titled book is not owned by the\n // library.\n forall b: Book :: b.title == \"\" ==> b !in this.library\n }\n}\n\nghost predicate Init(v: Variables)\n{\n && v.WellFormed()\n && forall b :: b in v.library ==> v.library[b].Shelf?\n}\n\n// The transitions of the library state machine.\n\ndatatype Step = Checkout(b: Book, to: string) | Return(b: Book)\n\nghost predicate CheckoutStep(v: Variables, v': Variables, step: Step)\n requires step.Checkout?\n{\n && v.WellFormed()\n && step.b in v.library\n && v.library[step.b].Shelf?\n // New syntax (datatype update): here we define the new Variables from the old\n // one by updating one field: v.(library := ...). This is much like a sequence\n // update. In fact, we also introduce a map update `v.library[step.b := ...]`\n // which works in pretty much the same way.\n && v' == v.(library := v.library[step.b := Patron(step.to)])\n}\n\nghost predicate ReturnStep(v: Variables, v': Variables, step: Step)\n requires step.Return?\n{\n && v.WellFormed()\n && step.b in v.library\n && v.library[step.b].Patron?\n && v' == v.(library := v.library[step.b := Shelf])\n}\n\nghost predicate NextStep(v: Variables, v': Variables, step: Step)\n{\n match step {\n case Checkout(_, _) => CheckoutStep(v, v', step)\n case Return(_) => ReturnStep(v, v', step)\n }\n}\n\nghost predicate Next(v: Variables, v': Variables)\n{\n exists step :: NextStep(v, v', step)\n}\n\nlemma NextStepDeterministicGivenStep(v:Variables, v':Variables, step: Step)\n requires NextStep(v, v', step)\n ensures forall v'' | NextStep(v, v'', step) :: v' == v''\n{}\n\n/*\nIn this lemma we'll write a concrete sequence of states which forms a (short)\nexecution of this state machine, and prove that it really is an execution.\n\nThis can be a good sanity check on the definitions (for example, to make sure\nthat it's at least possible to take every transition).\n*/\nlemma ExampleExec() {\n var e := [\n Variables(library := map[Book(\"Snow Crash\") := Shelf, Book(\"The Stand\") := Shelf]),\n Variables(library := map[Book(\"Snow Crash\") := Patron(\"Jon\"), Book(\"The Stand\") := Shelf]),\n Variables(library := map[Book(\"Snow Crash\") := Patron(\"Jon\"), Book(\"The Stand\") := Patron(\"Tej\")]),\n Variables(library := map[Book(\"Snow Crash\") := Shelf, Book(\"The Stand\") := Patron(\"Tej\")])\n ];\n\n // Next we'll prove that e is a valid execution.\n\n assert Init(e[0]);\n\n // These steps will be witnesses to help prove Next between every pair of Variables.\n var steps := [\n Checkout(Book(\"Snow Crash\"), \"Jon\"),\n Checkout(Book(\"The Stand\"), \"Tej\"),\n Return(Book(\"Snow Crash\"))\n ];\n assert forall n: nat | n < |e|-1 :: NextStep(e[n], e[n+1], steps[n]);\n assert forall n: nat | n < |e|-1 :: Next(e[n], e[n+1]);\n}\n\n", "hints_removed": "/*\n A simple state machine modeling checking out and returning books in a library.\n*/\n\n// Status will track where one book is\ndatatype Status = Shelf | Patron(name: string)\ndatatype Book = Book(title: string)\n\n// The state of the whole library is just the status of every book owned by the\n// library.\ndatatype Variables = Variables(library: map)\n{\n // New syntax (member function): the curly braces below the datatype introduce\n // a set of _member functions_, which can be called as v.f(), just like Java,\n // C++, or Rust methods. Just like in Java or C++, the body can use the `this`\n // keyword to refer to an implicit argument of type Variables.\n ghost predicate WellFormed()\n {\n // New syntax (x in m for maps): maps have a domain and we can write x in m\n // to say x is in the domain of m (similarly, `x !in m` is a more readable\n // version of `!(x in m)`). As with sequences where indices need to be in\n // bounds, to write `m[x]` you'll need to show that `x in m` holds.\n //\n // What we're saying here is that the empty-titled book is not owned by the\n // library.\n forall b: Book :: b.title == \"\" ==> b !in this.library\n }\n}\n\nghost predicate Init(v: Variables)\n{\n && v.WellFormed()\n && forall b :: b in v.library ==> v.library[b].Shelf?\n}\n\n// The transitions of the library state machine.\n\ndatatype Step = Checkout(b: Book, to: string) | Return(b: Book)\n\nghost predicate CheckoutStep(v: Variables, v': Variables, step: Step)\n requires step.Checkout?\n{\n && v.WellFormed()\n && step.b in v.library\n && v.library[step.b].Shelf?\n // New syntax (datatype update): here we define the new Variables from the old\n // one by updating one field: v.(library := ...). This is much like a sequence\n // update. In fact, we also introduce a map update `v.library[step.b := ...]`\n // which works in pretty much the same way.\n && v' == v.(library := v.library[step.b := Patron(step.to)])\n}\n\nghost predicate ReturnStep(v: Variables, v': Variables, step: Step)\n requires step.Return?\n{\n && v.WellFormed()\n && step.b in v.library\n && v.library[step.b].Patron?\n && v' == v.(library := v.library[step.b := Shelf])\n}\n\nghost predicate NextStep(v: Variables, v': Variables, step: Step)\n{\n match step {\n case Checkout(_, _) => CheckoutStep(v, v', step)\n case Return(_) => ReturnStep(v, v', step)\n }\n}\n\nghost predicate Next(v: Variables, v': Variables)\n{\n exists step :: NextStep(v, v', step)\n}\n\nlemma NextStepDeterministicGivenStep(v:Variables, v':Variables, step: Step)\n requires NextStep(v, v', step)\n ensures forall v'' | NextStep(v, v'', step) :: v' == v''\n{}\n\n/*\nIn this lemma we'll write a concrete sequence of states which forms a (short)\nexecution of this state machine, and prove that it really is an execution.\n\nThis can be a good sanity check on the definitions (for example, to make sure\nthat it's at least possible to take every transition).\n*/\nlemma ExampleExec() {\n var e := [\n Variables(library := map[Book(\"Snow Crash\") := Shelf, Book(\"The Stand\") := Shelf]),\n Variables(library := map[Book(\"Snow Crash\") := Patron(\"Jon\"), Book(\"The Stand\") := Shelf]),\n Variables(library := map[Book(\"Snow Crash\") := Patron(\"Jon\"), Book(\"The Stand\") := Patron(\"Tej\")]),\n Variables(library := map[Book(\"Snow Crash\") := Shelf, Book(\"The Stand\") := Patron(\"Tej\")])\n ];\n\n // Next we'll prove that e is a valid execution.\n\n\n // These steps will be witnesses to help prove Next between every pair of Variables.\n var steps := [\n Checkout(Book(\"Snow Crash\"), \"Jon\"),\n Checkout(Book(\"The Stand\"), \"Tej\"),\n Return(Book(\"Snow Crash\"))\n ];\n}\n\n" }, { "test_ID": "331", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_mathematical objects verification_examples_logic.dfy", "ground_truth": "/* Review of logical connectives and properties of first-order logic. */\n\n/* We'll be using boolean logic both to define protocols and to state their\n * properties, so it helps if you have an understanding of what the connectives\n * of logic mean and have a little fluency with manipulating them. */\n\n/* The first section of \"An Introduction to Abstract Mathematics\" by Neil\n * Donaldson and Alessandra Pantano might be helpful:\n * https://www.math.uci.edu/~ndonalds/math13/notes.pdf\n */\n\n/* The core of logic is the _proposition_. For us, a proposition like `2 < 3` is\n * going to be a boolean, with the interpretation that the proposition is true,\n * well, if the boolean is true, and false if not. That proposition is clearly\n * true.\n */\n\nlemma ExampleProposition()\n{\n assert 2 < 3;\n}\n\n/* Another example: `7 - 3 == 3` is clearly false, but it's still a\n * proposition.\n */\nlemma SomethingFalse()\n{\n // you'll get an error if you uncomment this line\n // assert 7 - 3 == 3;\n}\n\n/* On the other hand something like `7 * false < 8` isn't a\n * proposition at all since it has a type error - we won't have to worry too\n * much about these because Dafny will quickly and easily catch such mistakes.\n */\nlemma SomethingNonsensical()\n{\n // you'll get an error if you uncomment this line\n //\n // unlike the above, it will be a type-checking error and not a verification\n // failure\n // assert 7 * false < 8;\n}\n\n/* In Dafny, we can write lemmas with arguments, which are logical variables (of\n * the appropriate types). From here on we'll shift to stating logical properties\n * as ensures clauses of lemmas, the typical way they'd be packaged in Dafny. */\nlemma AdditionCommutes(n: int, m: int)\n ensures n + m == m + n\n{\n // The proof of this lemma goes here. In this case (and in many others), no\n // additional assistance is needed so an empty proof suffices.\n //\n // In Dafny, we won't talk much about proofs on their own - in a course on\n // logic you might go over logical rules or proof trees - because Dafny is\n // going to have all the power you need to prove things (as long as they're true!).\n}\n\n/* Let's start by going over the simplest logical connectives: && (\"and\") and ||\n * (\"or\"). In these examples think of the input booleans as being arbitrary\n * predicates, except that by the time we've passed them to these lemmas their\n * represented as just a truth value. */\n\nlemma ProveAndFromBoth(p1: bool, p2: bool)\n requires p1\n requires p2\n ensures p1 && p2\n{}\n\nlemma FromAndProveRight(p1: bool, p2: bool)\n requires p1 && p2\n ensures p2\n{}\n\nlemma ProveOrFromLeft(p1: bool, p2: bool)\n requires p1\n ensures p1 || p2\n{}\n\n/* Let's also see _negation_ written `!p`, boolean negation. Asserting or\n * ensuring `!p` is the way we prove it's false. */\nlemma DoubleNegation(p: bool)\n requires p\n ensures !!p\n{}\n\nlemma LawOfExcludedMiddle(p: bool)\n ensures p || !p\n{}\n\n/* Now we'll introduce boolean implication, `p ==> q`, read as \"if p, then q\". In \"p\n * ==> q\" we'll sometimes refer to \"p\" as a hypothesis and \"q\" as a conclusion.\n * Here are some alternative English logical\n * statements and how they map to implication:\n *\n * \"p if q\" means \"q ==> p\"\n * \"p only if q\" means \"p ==> q\" (this one can be tricky!)\n * \"p implies q\" means \"p ==> q\"\n */\n\n/* Note that p ==> q is itself a proposition! Here's its \"truth table\", showing\n * all possible combinations of p and q and whether p ==> q is true: */\nlemma ImplicationTruthTable()\n ensures false ==> false\n ensures false ==> true\n ensures !(true ==> false)\n ensures false ==> true\n{}\n\n/* One of the most famous rules of logic, which allows us to take an implication\n * (already proven correct) and a proof of its hypothesis to derive its\n * conclusion.\n *\n * Note that both parts are important! We can prove `false ==> 2 < 1` but will\n * never be able to use ModusPonens on this to prove `2 < 1`. Well we could, but\n * since this is obviously false it would mean we accidentally assumed false\n * somewhere else - this is also called an _inconsistency_.\n */\nlemma ModusPonens(p1: bool, p2: bool)\n requires p1 ==> p2\n requires p1\n ensures p2\n{}\n\n/* We can write a lemma above as implications in ensures clauses, rather than\n * using preconditions. The key difference is that calling `FromAndProveLeft(p1,\n * p2)` for example will cause Dafny to immediately prove `p1 && p2`, whereas we\n * can always call `AndProvesBoth(p1, p2)` and Dafny won't check anything\n * (because the implications are true regardless of p1 and p2). */\nlemma AndProvesBoth(p1: bool, p2: bool)\n ensures p1 && p2 ==> p1\n ensures p1 && p2 ==> p2\n{}\n\n/* Let's introduce one more logical connective: `p <==> q`, \"p if and only if q\"\n * (also written \"iff\" and pronounced \"if and only if\"). This has the same truth\n * value as `p == q`. The whole thing is sometimes called a \"biconditional\".\n * This rule is a little like modus ponens but requiring the implication is\n * stronger than needed. */\nlemma ProveFromBiconditional(p1: bool, p2: bool)\n requires p1\n requires p1 <==> p2\n ensures p2\n{}\n\n/* Simplifying and comprehending logical expressions is something you'll\n * gradually get practice with. It can get quite complicated! */\nlemma SomeEquivalences(p1: bool, p2: bool)\n ensures ((p1 ==> p2) && p1) ==> p2\n // !p2 ==> !p1 is called the \"contrapositive\" of p1 ==> p2. It has the same\n // truth value.\n ensures (p1 ==> p2) <==> (!p2 ==> !p1)\n ensures !(p1 ==> !p2) <==> p1 && p2\n ensures ((p1 ==> p2) && (!p1 ==> p2)) <==> p2\n // you might want to think about this one:\n ensures (!p1 || (p1 ==> p2)) <==> (p1 ==> p2)\n{}\n\nlemma SomeMoreEquivalences(p1: bool, p2: bool, p3: bool)\n // note on parsing: <==> has the lowest priority, so all of these statements are\n // equivalences at the top level\n ensures (p1 && p2) && p3 <==> p1 && p2 && p3\n // this is what chained implications mean\n ensures p1 ==> p2 ==> p3 <==> p1 && p2 ==> p3\n ensures p1 ==> (p2 ==> p3) <==> p1 && p2 ==> p3\n{}\n\n/* Quantifiers */\n\n/* To express and state more interesting properties, we'll need quantifiers -\n * that is, forall and exists. Dafny supports these as a way to write\n * propositions, and they produce a boolean value just like the other logical\n * connectives. */\n\nlemma AdditionCommutesAsForall()\n{\n // (ignore the warning \"No terms found to trigger on\")\n assert forall n: int, m: int :: n + m == m + n;\n\n // Just to emphasize this is a proposition (a boolean) just like everything\n // else we've seen. The big difference is that this forall is clearly not a\n // boolean we could evaluate in the normal sense of running it to produce true\n // or false - nonetheless Dafny can reason about it mathematically.\n var does_addition_commute: bool := forall n: int, m: int :: n + m == m + n;\n assert does_addition_commute == true;\n}\n\n/* In order to illustrate some properties of forall, we'll introduce some\n * arbitrary _predicates_ over integers to put in our examples. By not putting a\n * body we tell Dafny to define these terms, but not to assume anything about their\n * values except that they are deterministic. */\npredicate P(x: int)\npredicate Q(x: int)\n// This is a predicate over two integers, often called a relation. You might\n// also hear propositions, predicates, and predicates over multiple values all\n// called relations - propositions are just 0-arity and predicates are 1-arity.\npredicate R(x: int, y: int)\n\n/* One operation you'll eventually want some fluency in is the ability to negate\n * logical expressions. Let's go through the rules. */\nlemma SimplifyingNegations(p: bool, q: bool)\n ensures !(p && q) <==> !p || !q\n ensures !(p || q) <==> !p && !q\n ensures !(p ==> q) <==> p && !q\n ensures !!p <==> p\n ensures !(forall x :: P(x)) <==> (exists x :: !P(x))\n ensures !(exists x :: P(x)) <==> (forall x :: !P(x))\n{}\n\n/* Dafny supports a \"where\" clause in a forall. It's a shorthand for implication. */\nlemma WhereIsJustImplies()\n // we need parentheses around each side for this to have the desired meaning\n ensures (forall x | P(x) :: Q(x)) <==> (forall x :: P(x) ==> Q(x))\n{}\n\nlemma NotForallWhere()\n ensures !(forall x | P(x) :: Q(x)) <==> exists x :: P(x) && !Q(x)\n{}\n\n/* Dafny also supports a \"where\" clause in an exists, as a shorthand for &&. */\nlemma ExistsWhereIsJustAnd()\n // we need parentheses around each side for this to have the desired meaning\n ensures (exists x | P(x) :: Q(x)) <==> (exists x :: P(x) && Q(x))\n // Why this choice? It's so that the following property holds. Notice that for\n // all the negation rules we reverse && and ||, and exists and forall; this\n // preserves that _duality_ (a formal and pervasive concept in math and\n // logic).\n ensures !(forall x | P(x) :: Q(x)) <==> (exists x | P(x) :: !Q(x))\n{}\n\n", "hints_removed": "/* Review of logical connectives and properties of first-order logic. */\n\n/* We'll be using boolean logic both to define protocols and to state their\n * properties, so it helps if you have an understanding of what the connectives\n * of logic mean and have a little fluency with manipulating them. */\n\n/* The first section of \"An Introduction to Abstract Mathematics\" by Neil\n * Donaldson and Alessandra Pantano might be helpful:\n * https://www.math.uci.edu/~ndonalds/math13/notes.pdf\n */\n\n/* The core of logic is the _proposition_. For us, a proposition like `2 < 3` is\n * going to be a boolean, with the interpretation that the proposition is true,\n * well, if the boolean is true, and false if not. That proposition is clearly\n * true.\n */\n\nlemma ExampleProposition()\n{\n}\n\n/* Another example: `7 - 3 == 3` is clearly false, but it's still a\n * proposition.\n */\nlemma SomethingFalse()\n{\n // you'll get an error if you uncomment this line\n // assert 7 - 3 == 3;\n}\n\n/* On the other hand something like `7 * false < 8` isn't a\n * proposition at all since it has a type error - we won't have to worry too\n * much about these because Dafny will quickly and easily catch such mistakes.\n */\nlemma SomethingNonsensical()\n{\n // you'll get an error if you uncomment this line\n //\n // unlike the above, it will be a type-checking error and not a verification\n // failure\n // assert 7 * false < 8;\n}\n\n/* In Dafny, we can write lemmas with arguments, which are logical variables (of\n * the appropriate types). From here on we'll shift to stating logical properties\n * as ensures clauses of lemmas, the typical way they'd be packaged in Dafny. */\nlemma AdditionCommutes(n: int, m: int)\n ensures n + m == m + n\n{\n // The proof of this lemma goes here. In this case (and in many others), no\n // additional assistance is needed so an empty proof suffices.\n //\n // In Dafny, we won't talk much about proofs on their own - in a course on\n // logic you might go over logical rules or proof trees - because Dafny is\n // going to have all the power you need to prove things (as long as they're true!).\n}\n\n/* Let's start by going over the simplest logical connectives: && (\"and\") and ||\n * (\"or\"). In these examples think of the input booleans as being arbitrary\n * predicates, except that by the time we've passed them to these lemmas their\n * represented as just a truth value. */\n\nlemma ProveAndFromBoth(p1: bool, p2: bool)\n requires p1\n requires p2\n ensures p1 && p2\n{}\n\nlemma FromAndProveRight(p1: bool, p2: bool)\n requires p1 && p2\n ensures p2\n{}\n\nlemma ProveOrFromLeft(p1: bool, p2: bool)\n requires p1\n ensures p1 || p2\n{}\n\n/* Let's also see _negation_ written `!p`, boolean negation. Asserting or\n * ensuring `!p` is the way we prove it's false. */\nlemma DoubleNegation(p: bool)\n requires p\n ensures !!p\n{}\n\nlemma LawOfExcludedMiddle(p: bool)\n ensures p || !p\n{}\n\n/* Now we'll introduce boolean implication, `p ==> q`, read as \"if p, then q\". In \"p\n * ==> q\" we'll sometimes refer to \"p\" as a hypothesis and \"q\" as a conclusion.\n * Here are some alternative English logical\n * statements and how they map to implication:\n *\n * \"p if q\" means \"q ==> p\"\n * \"p only if q\" means \"p ==> q\" (this one can be tricky!)\n * \"p implies q\" means \"p ==> q\"\n */\n\n/* Note that p ==> q is itself a proposition! Here's its \"truth table\", showing\n * all possible combinations of p and q and whether p ==> q is true: */\nlemma ImplicationTruthTable()\n ensures false ==> false\n ensures false ==> true\n ensures !(true ==> false)\n ensures false ==> true\n{}\n\n/* One of the most famous rules of logic, which allows us to take an implication\n * (already proven correct) and a proof of its hypothesis to derive its\n * conclusion.\n *\n * Note that both parts are important! We can prove `false ==> 2 < 1` but will\n * never be able to use ModusPonens on this to prove `2 < 1`. Well we could, but\n * since this is obviously false it would mean we accidentally assumed false\n * somewhere else - this is also called an _inconsistency_.\n */\nlemma ModusPonens(p1: bool, p2: bool)\n requires p1 ==> p2\n requires p1\n ensures p2\n{}\n\n/* We can write a lemma above as implications in ensures clauses, rather than\n * using preconditions. The key difference is that calling `FromAndProveLeft(p1,\n * p2)` for example will cause Dafny to immediately prove `p1 && p2`, whereas we\n * can always call `AndProvesBoth(p1, p2)` and Dafny won't check anything\n * (because the implications are true regardless of p1 and p2). */\nlemma AndProvesBoth(p1: bool, p2: bool)\n ensures p1 && p2 ==> p1\n ensures p1 && p2 ==> p2\n{}\n\n/* Let's introduce one more logical connective: `p <==> q`, \"p if and only if q\"\n * (also written \"iff\" and pronounced \"if and only if\"). This has the same truth\n * value as `p == q`. The whole thing is sometimes called a \"biconditional\".\n * This rule is a little like modus ponens but requiring the implication is\n * stronger than needed. */\nlemma ProveFromBiconditional(p1: bool, p2: bool)\n requires p1\n requires p1 <==> p2\n ensures p2\n{}\n\n/* Simplifying and comprehending logical expressions is something you'll\n * gradually get practice with. It can get quite complicated! */\nlemma SomeEquivalences(p1: bool, p2: bool)\n ensures ((p1 ==> p2) && p1) ==> p2\n // !p2 ==> !p1 is called the \"contrapositive\" of p1 ==> p2. It has the same\n // truth value.\n ensures (p1 ==> p2) <==> (!p2 ==> !p1)\n ensures !(p1 ==> !p2) <==> p1 && p2\n ensures ((p1 ==> p2) && (!p1 ==> p2)) <==> p2\n // you might want to think about this one:\n ensures (!p1 || (p1 ==> p2)) <==> (p1 ==> p2)\n{}\n\nlemma SomeMoreEquivalences(p1: bool, p2: bool, p3: bool)\n // note on parsing: <==> has the lowest priority, so all of these statements are\n // equivalences at the top level\n ensures (p1 && p2) && p3 <==> p1 && p2 && p3\n // this is what chained implications mean\n ensures p1 ==> p2 ==> p3 <==> p1 && p2 ==> p3\n ensures p1 ==> (p2 ==> p3) <==> p1 && p2 ==> p3\n{}\n\n/* Quantifiers */\n\n/* To express and state more interesting properties, we'll need quantifiers -\n * that is, forall and exists. Dafny supports these as a way to write\n * propositions, and they produce a boolean value just like the other logical\n * connectives. */\n\nlemma AdditionCommutesAsForall()\n{\n // (ignore the warning \"No terms found to trigger on\")\n\n // Just to emphasize this is a proposition (a boolean) just like everything\n // else we've seen. The big difference is that this forall is clearly not a\n // boolean we could evaluate in the normal sense of running it to produce true\n // or false - nonetheless Dafny can reason about it mathematically.\n var does_addition_commute: bool := forall n: int, m: int :: n + m == m + n;\n}\n\n/* In order to illustrate some properties of forall, we'll introduce some\n * arbitrary _predicates_ over integers to put in our examples. By not putting a\n * body we tell Dafny to define these terms, but not to assume anything about their\n * values except that they are deterministic. */\npredicate P(x: int)\npredicate Q(x: int)\n// This is a predicate over two integers, often called a relation. You might\n// also hear propositions, predicates, and predicates over multiple values all\n// called relations - propositions are just 0-arity and predicates are 1-arity.\npredicate R(x: int, y: int)\n\n/* One operation you'll eventually want some fluency in is the ability to negate\n * logical expressions. Let's go through the rules. */\nlemma SimplifyingNegations(p: bool, q: bool)\n ensures !(p && q) <==> !p || !q\n ensures !(p || q) <==> !p && !q\n ensures !(p ==> q) <==> p && !q\n ensures !!p <==> p\n ensures !(forall x :: P(x)) <==> (exists x :: !P(x))\n ensures !(exists x :: P(x)) <==> (forall x :: !P(x))\n{}\n\n/* Dafny supports a \"where\" clause in a forall. It's a shorthand for implication. */\nlemma WhereIsJustImplies()\n // we need parentheses around each side for this to have the desired meaning\n ensures (forall x | P(x) :: Q(x)) <==> (forall x :: P(x) ==> Q(x))\n{}\n\nlemma NotForallWhere()\n ensures !(forall x | P(x) :: Q(x)) <==> exists x :: P(x) && !Q(x)\n{}\n\n/* Dafny also supports a \"where\" clause in an exists, as a shorthand for &&. */\nlemma ExistsWhereIsJustAnd()\n // we need parentheses around each side for this to have the desired meaning\n ensures (exists x | P(x) :: Q(x)) <==> (exists x :: P(x) && Q(x))\n // Why this choice? It's so that the following property holds. Notice that for\n // all the negation rules we reverse && and ||, and exists and forall; this\n // preserves that _duality_ (a formal and pervasive concept in math and\n // logic).\n ensures !(forall x | P(x) :: Q(x)) <==> (exists x | P(x) :: !Q(x))\n{}\n\n" }, { "test_ID": "332", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_pregel algorithms_skeleton_nondet-permutation.dfy", "ground_truth": "\ufeffmodule Permutation\n{\n\t/**\n\t * Given n >= 0, generate a permuation of {0,...,n-1} nondeterministically.\n\t */\n\tmethod Generate(n: int) returns (perm: array)\n\t\trequires n >= 0\n\t\tensures perm != null\n\t\tensures perm.Length == n\n\t\tensures fresh(perm)\n\t\tensures isValid(perm, n)\n\t{\n\t\tvar all := set x | 0 <= x < n;\n\t\tvar used := {};\n\t\tperm := new int[n];\n\n\t\tCardinalityLemma(n, all);\n\n\t\twhile used < all\n\t\t\tinvariant used <= all\n\t\t\tinvariant |used| <= |all|\n\t\t\tinvariant forall i | 0 <= i < |used| :: perm[i] in used\n\t\t\tinvariant distinct'(perm, |used|)\n\t\t\tdecreases |all| - |used|\n\t\t{\n\t\t\tCardinalityOrderingLemma(used, all);\n\n\t\t\tvar dst :| dst in all && dst !in used;\n\t\t\tperm[|used|] := dst;\n\t\t\tused := used + {dst};\n\t\t}\n\t\tassert used == all;\n\t\tprint perm;\n\t}\n\n\tpredicate isValid(a: array, n: nat)\n\t\trequires a != null && a.Length == n\n\t\treads a\n\t{\n\t\tassume forall i | 0 <= i < n :: i in a[..];\n\t\tdistinct(a)\n\t\t&& (forall i | 0 <= i < a.Length :: 0 <= a[i] < n)\n\t\t&& (forall i | 0 <= i < n :: i in a[..])\n\t}\n\n\tpredicate distinct(a: array)\n\t\trequires a != null\n\t\treads a\n\t{\n\t\tdistinct'(a, a.Length)\n\t}\n\n\tpredicate distinct'(a: array, n: int)\n\t\trequires a != null\n\t\trequires a.Length >= n\n\t\treads a\n\t{\n\t\tforall i,j | 0 <= i < n && 0 <= j < n && i != j :: a[i] != a[j]\n\t}\n\n\tlemma CardinalityLemma (size: int, s: set)\n\t\trequires size >= 0\n\t\trequires s == set x | 0 <= x < size\n\t\tensures\tsize == |s|\n\t{\n\t\tif(size == 0) {\n\t\t\tassert size == |(set x | 0 <= x < size)|;\n\t\t} else {\n\t\t\tCardinalityLemma(size - 1, s - {size - 1});\n\t\t}\n\t}\n\n\tlemma CardinalityOrderingLemma (s1: set, s2: set)\n\t\trequires s1 < s2\n\t\tensures |s1| < |s2|\n\t{\n\t\tvar e :| e in s2 - s1;\n\t\tif s1 != s2 - {e} {\n\t\t\tCardinalityOrderingLemma(s1, s2 - {e});\n\t\t}\n\t}\n\n\tlemma SetDiffLemma (s1: set, s2: set)\n\t\trequires s1 < s2\n\t\tensures s2 - s1 != {}\n\t{\n\t\tvar e :| e in s2 - s1;\n\t\tif s2 - s1 != {e} {} // What does Dafny prove here???\n\t}\n}\n", "hints_removed": "\ufeffmodule Permutation\n{\n\t/**\n\t * Given n >= 0, generate a permuation of {0,...,n-1} nondeterministically.\n\t */\n\tmethod Generate(n: int) returns (perm: array)\n\t\trequires n >= 0\n\t\tensures perm != null\n\t\tensures perm.Length == n\n\t\tensures fresh(perm)\n\t\tensures isValid(perm, n)\n\t{\n\t\tvar all := set x | 0 <= x < n;\n\t\tvar used := {};\n\t\tperm := new int[n];\n\n\t\tCardinalityLemma(n, all);\n\n\t\twhile used < all\n\t\t{\n\t\t\tCardinalityOrderingLemma(used, all);\n\n\t\t\tvar dst :| dst in all && dst !in used;\n\t\t\tperm[|used|] := dst;\n\t\t\tused := used + {dst};\n\t\t}\n\t\tprint perm;\n\t}\n\n\tpredicate isValid(a: array, n: nat)\n\t\trequires a != null && a.Length == n\n\t\treads a\n\t{\n\t\tassume forall i | 0 <= i < n :: i in a[..];\n\t\tdistinct(a)\n\t\t&& (forall i | 0 <= i < a.Length :: 0 <= a[i] < n)\n\t\t&& (forall i | 0 <= i < n :: i in a[..])\n\t}\n\n\tpredicate distinct(a: array)\n\t\trequires a != null\n\t\treads a\n\t{\n\t\tdistinct'(a, a.Length)\n\t}\n\n\tpredicate distinct'(a: array, n: int)\n\t\trequires a != null\n\t\trequires a.Length >= n\n\t\treads a\n\t{\n\t\tforall i,j | 0 <= i < n && 0 <= j < n && i != j :: a[i] != a[j]\n\t}\n\n\tlemma CardinalityLemma (size: int, s: set)\n\t\trequires size >= 0\n\t\trequires s == set x | 0 <= x < size\n\t\tensures\tsize == |s|\n\t{\n\t\tif(size == 0) {\n\t\t} else {\n\t\t\tCardinalityLemma(size - 1, s - {size - 1});\n\t\t}\n\t}\n\n\tlemma CardinalityOrderingLemma (s1: set, s2: set)\n\t\trequires s1 < s2\n\t\tensures |s1| < |s2|\n\t{\n\t\tvar e :| e in s2 - s1;\n\t\tif s1 != s2 - {e} {\n\t\t\tCardinalityOrderingLemma(s1, s2 - {e});\n\t\t}\n\t}\n\n\tlemma SetDiffLemma (s1: set, s2: set)\n\t\trequires s1 < s2\n\t\tensures s2 - s1 != {}\n\t{\n\t\tvar e :| e in s2 - s1;\n\t\tif s2 - s1 != {e} {} // What does Dafny prove here???\n\t}\n}\n" }, { "test_ID": "333", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_vampire project_original_Searching.dfy", "ground_truth": "// Assuming Array is Object Blood\n// Blood Array\n// index\n\nmethod Find(blood: array, key: int) returns (index: int)\nrequires blood != null\nensures 0 <= index ==> index < blood.Length && blood[index] == key\nensures index < 0 ==> forall k :: 0 <= k < blood.Length ==> blood[k] != key\n{\n index := 0;\n while index < blood.Length\n invariant 0 <= index <= blood.Length\n invariant forall k :: 0 <= k < index ==> blood[k] != key\n {\n if blood[index] == key { return; }\n index := index + 1;\n }\n index := -1;\n}\n\n", "hints_removed": "// Assuming Array is Object Blood\n// Blood Array\n// index\n\nmethod Find(blood: array, key: int) returns (index: int)\nrequires blood != null\nensures 0 <= index ==> index < blood.Length && blood[index] == key\nensures index < 0 ==> forall k :: 0 <= k < blood.Length ==> blood[k] != key\n{\n index := 0;\n while index < blood.Length\n {\n if blood[index] == key { return; }\n index := index + 1;\n }\n index := -1;\n}\n\n" }, { "test_ID": "334", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_variant examples_KatzManna.dfy", "ground_truth": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nmethod NinetyOne(x: int, ghost proveFunctionalPostcondition: bool) returns (z: int)\n ensures proveFunctionalPostcondition ==> z == if x > 101 then x-10 else 91;\n{\n var y1 := x;\n var y2 := 1;\n while (true)\n // the following two invariants are needed only to prove the postcondition\n invariant proveFunctionalPostcondition ==> 100 < x ==> y1 == x;\n invariant proveFunctionalPostcondition ==> x <= 100 < y1 && y2 == 1 ==> y1 == 101;\n // the following two lines justify termination, as in the paper by Katz and Manna\n invariant (y1 <= 111 && y2 >= 1) || (y1 == x && y2 == 1);\n decreases -2*y1 + 21*y2 + 2*(if x < 111 then 111 else x);\n {\n if (y1 > 100) {\n if (y2 == 1) {\n break;\n } else {\n y1 := y1 - 10;\n y2 := y2 - 1;\n }\n } else {\n y1 := y1 + 11;\n y2 := y2 + 1;\n }\n }\n z := y1 - 10;\n}\n\nmethod Gcd(x1: int, x2: int)\n requires 1 <= x1 && 1 <= x2;\n{\n var y1 := x1;\n var y2 := x2;\n while (y1 != y2)\n invariant 1 <= y1 && 1 <= y2;\n decreases y1 + y2;\n {\n while (y1 > y2)\n invariant 1 <= y1 && 1 <= y2;\n {\n y1 := y1 - y2;\n }\n while (y2 > y1)\n invariant 1 <= y1 && 1 <= y2;\n {\n y2 := y2 - y1;\n }\n }\n}\n\nmethod Determinant(X: array2, M: int) returns (z: int)\n requires 1 <= M;\n requires X != null && M == X.Length0 && M == X.Length1;\n modifies X;\n{\n var y := X[1-1,1-1];\n var a := 1;\n while (a != M)\n invariant 1 <= a <= M;\n {\n var b := a + 1;\n while (b != M+1)\n invariant a+1 <= b <= M+1;\n {\n var c := M;\n while (c != a)\n invariant a <= c <= M;\n {\n assume X[a-1,a-1] != 0;\n X[b-1, c-1] := X[b-1,c-1] - X[b-1,a-1] / X[a-1,a-1] * X[a-1,c-1];\n c := c - 1;\n }\n b := b + 1;\n }\n a := a + 1;\n y := y * X[a-1,a-1];\n }\n z := y;\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nmethod NinetyOne(x: int, ghost proveFunctionalPostcondition: bool) returns (z: int)\n ensures proveFunctionalPostcondition ==> z == if x > 101 then x-10 else 91;\n{\n var y1 := x;\n var y2 := 1;\n while (true)\n // the following two invariants are needed only to prove the postcondition\n // the following two lines justify termination, as in the paper by Katz and Manna\n {\n if (y1 > 100) {\n if (y2 == 1) {\n break;\n } else {\n y1 := y1 - 10;\n y2 := y2 - 1;\n }\n } else {\n y1 := y1 + 11;\n y2 := y2 + 1;\n }\n }\n z := y1 - 10;\n}\n\nmethod Gcd(x1: int, x2: int)\n requires 1 <= x1 && 1 <= x2;\n{\n var y1 := x1;\n var y2 := x2;\n while (y1 != y2)\n {\n while (y1 > y2)\n {\n y1 := y1 - y2;\n }\n while (y2 > y1)\n {\n y2 := y2 - y1;\n }\n }\n}\n\nmethod Determinant(X: array2, M: int) returns (z: int)\n requires 1 <= M;\n requires X != null && M == X.Length0 && M == X.Length1;\n modifies X;\n{\n var y := X[1-1,1-1];\n var a := 1;\n while (a != M)\n {\n var b := a + 1;\n while (b != M+1)\n {\n var c := M;\n while (c != a)\n {\n assume X[a-1,a-1] != 0;\n X[b-1, c-1] := X[b-1,c-1] - X[b-1,a-1] / X[a-1,a-1] * X[a-1,c-1];\n c := c - 1;\n }\n b := b + 1;\n }\n a := a + 1;\n y := y * X[a-1,a-1];\n }\n z := y;\n}\n\n" }, { "test_ID": "335", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_variant examples_SumOfCubes.dfy", "ground_truth": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nclass SumOfCubes {\n static function SumEmUp(n: int, m: int): int\n requires 0 <= n && n <= m;\n decreases m - n;\n {\n if m == n then 0 else n*n*n + SumEmUp(n+1, m)\n }\n\n static method Socu(n: int, m: int) returns (r: int)\n requires 0 <= n && n <= m;\n ensures r == SumEmUp(n, m);\n {\n var a := SocuFromZero(m);\n var b := SocuFromZero(n);\n r := a - b;\n Lemma0(n, m);\n }\n\n static method SocuFromZero(k: int) returns (r: int)\n requires 0 <= k;\n ensures r == SumEmUp(0, k);\n {\n var g := Gauss(k);\n r := g * g;\n Lemma1(k);\n }\n\n ghost static method Lemma0(n: int, m: int)\n requires 0 <= n && n <= m;\n ensures SumEmUp(n, m) == SumEmUp(0, m) - SumEmUp(0, n);\n {\n var k := n;\n while (k < m) \n invariant n <= k && k <= m;\n invariant SumEmDown(0, n) + SumEmDown(n, k) == SumEmDown(0, k);\n {\n k := k + 1;\n }\n Lemma3(0, n);\n Lemma3(n, k);\n Lemma3(0, k);\n }\n\n static function GSum(k: int): int\n requires 0 <= k;\n {\n if k == 0 then 0 else GSum(k-1) + k-1\n }\n\n static method Gauss(k: int) returns (r: int)\n requires 0 <= k;\n ensures r == GSum(k);\n {\n r := k * (k - 1) / 2;\n Lemma2(k);\n }\n\n ghost static method Lemma1(k: int)\n requires 0 <= k;\n ensures SumEmUp(0, k) == GSum(k) * GSum(k);\n {\n var i := 0;\n while (i < k)\n invariant i <= k;\n invariant SumEmDown(0, i) == GSum(i) * GSum(i);\n {\n Lemma2(i);\n i := i + 1;\n }\n Lemma3(0, k);\n }\n\n ghost static method Lemma2(k: int)\n requires 0 <= k;\n ensures 2 * GSum(k) == k * (k - 1);\n {\n var i := 0;\n while (i < k)\n invariant i <= k;\n invariant 2 * GSum(i) == i * (i - 1);\n {\n i := i + 1;\n }\n }\n\n static function SumEmDown(n: int, m: int): int\n requires 0 <= n && n <= m;\n {\n if m == n then 0 else SumEmDown(n, m-1) + (m-1)*(m-1)*(m-1)\n }\n\n ghost static method Lemma3(n: int, m: int)\n requires 0 <= n && n <= m;\n ensures SumEmUp(n, m) == SumEmDown(n, m);\n {\n var k := n;\n while (k < m)\n invariant n <= k && k <= m;\n invariant SumEmUp(n, m) == SumEmDown(n, k) + SumEmUp(k, m);\n {\n k := k + 1;\n }\n }\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nclass SumOfCubes {\n static function SumEmUp(n: int, m: int): int\n requires 0 <= n && n <= m;\n {\n if m == n then 0 else n*n*n + SumEmUp(n+1, m)\n }\n\n static method Socu(n: int, m: int) returns (r: int)\n requires 0 <= n && n <= m;\n ensures r == SumEmUp(n, m);\n {\n var a := SocuFromZero(m);\n var b := SocuFromZero(n);\n r := a - b;\n Lemma0(n, m);\n }\n\n static method SocuFromZero(k: int) returns (r: int)\n requires 0 <= k;\n ensures r == SumEmUp(0, k);\n {\n var g := Gauss(k);\n r := g * g;\n Lemma1(k);\n }\n\n ghost static method Lemma0(n: int, m: int)\n requires 0 <= n && n <= m;\n ensures SumEmUp(n, m) == SumEmUp(0, m) - SumEmUp(0, n);\n {\n var k := n;\n while (k < m) \n {\n k := k + 1;\n }\n Lemma3(0, n);\n Lemma3(n, k);\n Lemma3(0, k);\n }\n\n static function GSum(k: int): int\n requires 0 <= k;\n {\n if k == 0 then 0 else GSum(k-1) + k-1\n }\n\n static method Gauss(k: int) returns (r: int)\n requires 0 <= k;\n ensures r == GSum(k);\n {\n r := k * (k - 1) / 2;\n Lemma2(k);\n }\n\n ghost static method Lemma1(k: int)\n requires 0 <= k;\n ensures SumEmUp(0, k) == GSum(k) * GSum(k);\n {\n var i := 0;\n while (i < k)\n {\n Lemma2(i);\n i := i + 1;\n }\n Lemma3(0, k);\n }\n\n ghost static method Lemma2(k: int)\n requires 0 <= k;\n ensures 2 * GSum(k) == k * (k - 1);\n {\n var i := 0;\n while (i < k)\n {\n i := i + 1;\n }\n }\n\n static function SumEmDown(n: int, m: int): int\n requires 0 <= n && n <= m;\n {\n if m == n then 0 else SumEmDown(n, m-1) + (m-1)*(m-1)*(m-1)\n }\n\n ghost static method Lemma3(n: int, m: int)\n requires 0 <= n && n <= m;\n ensures SumEmUp(n, m) == SumEmDown(n, m);\n {\n var k := n;\n while (k < m)\n {\n k := k + 1;\n }\n }\n}\n\n" }, { "test_ID": "336", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_verified algorithms_inductive_props.dfy", "ground_truth": "// This file demonstrates how to \"close\" a critical \"gap\" between definitions\n// between Dafny and Coq.\n\n// In general, most commonly-used \"building blocks\" in Coq can be mapped to Dafny:\n// [Coq] [Dafny]\n// --------------------------------------------------------------------\n// Inductive (Set) datatype\n// Definition function/predicate\n// Fixpoint function/predicate (with `decreases`)\n// Theorem & Proof lemma\n// Type (Set, e.g. `list nat`) still a type (e.g. `seq`)\n// Type (Prop, e.g. `1+1==2`) encode in `requires` or `ensures`\n// N/A (at least NOT built-in) method (imperative programming)\n//\n// Inductive (Prop) ??? (discussed in this file)\n\n\n// Dafny's way to define Coq's `Fixpoint` predicate:\nghost predicate even(n: nat) {\n match n {\n case 0 => true\n case 1 => false\n case _ => even(n - 2)\n }\n}\n// all below are automatically proved:\nlemma a0() ensures even(4) {}\nlemma a1() ensures !even(3) {}\nlemma a2(n: nat) requires even(n) ensures even(n + 2) {}\nlemma a3(n: nat) requires even(n + 2) ensures even(n) {}\n\n\n// Dafny lacks syntax to define `Inductive` Prop like in Coq.\n// We'll show two workarounds for this.\n\n// Workaround 1: simulate with \"rules\"\ndatatype EvenRule =\n | ev_0\n | ev_SS(r: EvenRule)\n{\n ghost function apply(): nat {\n match this {\n case ev_0 => 0\n case ev_SS(r) => r.apply() + 2\n }\n }\n}\nghost predicate Even(n: nat) {\n exists r: EvenRule :: r.apply() == n\n}\n// then we can prove by \"constructing\" or \"destructing\" just like in Coq:\nlemma b0() ensures Even(4) {\n assert ev_SS(ev_SS(ev_0)).apply() == 4;\n}\nlemma b1() ensures !Even(3) {\n if r: EvenRule :| r.apply() == 3 {\n assert r.ev_SS? && r.r.apply() == 1;\n }\n}\nlemma b2(n: nat) requires Even(n) ensures Even(n + 2) {\n var r: EvenRule :| r.apply() == n;\n assert ev_SS(r).apply() == n + 2;\n}\nlemma b3(n: nat) requires Even(n + 2) ensures Even(n) {\n var r: EvenRule :| r.apply() == n + 2;\n assert r.ev_SS? && r.r.apply() == n;\n}\n\n\n// Workaround 2: using \"higher-order\" predicates\ntype P = nat -> bool\nghost predicate Ev(ev: P) {\n && ev(0)\n && (forall n: nat | ev(n) :: ev(n + 2))\n}\n// we explicitly say that `ev` is the \"strictest\" `P` that satisfies `Ev`:\nghost predicate Minimal(Ev: P -> bool, ev: P) {\n && Ev(ev)\n && (forall ev': P, n: nat | Ev(ev') :: ev(n) ==> ev'(n))\n}\n// In this approach, some lemmas are a bit tricky to prove...\nlemma c0(ev: P) requires Minimal(Ev, ev) ensures ev(4) {\n assert ev(2);\n}\nlemma c1(ev: P) requires Minimal(Ev, ev) ensures !ev(3) {\n var cex := (n: nat) => ( // `cex` stands for \"counterexample\"\n n != 1 && n != 3\n );\n assert Ev(cex);\n}\nlemma c2(ev: P, n: nat) requires Minimal(Ev, ev) && ev(n) ensures ev(n + 2) {}\nlemma c3(ev: P, n: nat) requires Minimal(Ev, ev) && ev(n + 2) ensures ev(n) {\n if !ev(n) {\n var cex := (m: nat) => (\n m != n + 2 && ev(m)\n );\n assert Ev(cex);\n }\n}\n\n\n// Finally, we \"circularly\" prove the equivalence among these three:\nlemma a_implies_b(n: nat) requires even(n) ensures Even(n) {\n if n == 0 {\n assert ev_0.apply() == 0;\n } else {\n a_implies_b(n - 2);\n var r: EvenRule :| r.apply() == n - 2;\n assert ev_SS(r).apply() == n;\n }\n}\nlemma b_implies_c(ev: P, n: nat) requires Minimal(Ev, ev) && Even(n) ensures ev(n) {\n var r: EvenRule :| r.apply() == n;\n if r.ev_SS? {\n assert r.r.apply() == n - 2;\n b_implies_c(ev, n - 2);\n }\n}\nlemma c_implies_a(ev: P, n: nat) requires Minimal(Ev, ev) && ev(n) ensures even(n) {\n if n == 1 {\n var cex := (m: nat) => (\n m != 1\n );\n assert Ev(cex);\n } else if n >= 2 {\n c3(ev, n - 2);\n c_implies_a(ev, n - 2);\n }\n}\n\n", "hints_removed": "// This file demonstrates how to \"close\" a critical \"gap\" between definitions\n// between Dafny and Coq.\n\n// In general, most commonly-used \"building blocks\" in Coq can be mapped to Dafny:\n// [Coq] [Dafny]\n// --------------------------------------------------------------------\n// Inductive (Set) datatype\n// Definition function/predicate\n// Fixpoint function/predicate (with `decreases`)\n// Theorem & Proof lemma\n// Type (Set, e.g. `list nat`) still a type (e.g. `seq`)\n// Type (Prop, e.g. `1+1==2`) encode in `requires` or `ensures`\n// N/A (at least NOT built-in) method (imperative programming)\n//\n// Inductive (Prop) ??? (discussed in this file)\n\n\n// Dafny's way to define Coq's `Fixpoint` predicate:\nghost predicate even(n: nat) {\n match n {\n case 0 => true\n case 1 => false\n case _ => even(n - 2)\n }\n}\n// all below are automatically proved:\nlemma a0() ensures even(4) {}\nlemma a1() ensures !even(3) {}\nlemma a2(n: nat) requires even(n) ensures even(n + 2) {}\nlemma a3(n: nat) requires even(n + 2) ensures even(n) {}\n\n\n// Dafny lacks syntax to define `Inductive` Prop like in Coq.\n// We'll show two workarounds for this.\n\n// Workaround 1: simulate with \"rules\"\ndatatype EvenRule =\n | ev_0\n | ev_SS(r: EvenRule)\n{\n ghost function apply(): nat {\n match this {\n case ev_0 => 0\n case ev_SS(r) => r.apply() + 2\n }\n }\n}\nghost predicate Even(n: nat) {\n exists r: EvenRule :: r.apply() == n\n}\n// then we can prove by \"constructing\" or \"destructing\" just like in Coq:\nlemma b0() ensures Even(4) {\n}\nlemma b1() ensures !Even(3) {\n if r: EvenRule :| r.apply() == 3 {\n }\n}\nlemma b2(n: nat) requires Even(n) ensures Even(n + 2) {\n var r: EvenRule :| r.apply() == n;\n}\nlemma b3(n: nat) requires Even(n + 2) ensures Even(n) {\n var r: EvenRule :| r.apply() == n + 2;\n}\n\n\n// Workaround 2: using \"higher-order\" predicates\ntype P = nat -> bool\nghost predicate Ev(ev: P) {\n && ev(0)\n && (forall n: nat | ev(n) :: ev(n + 2))\n}\n// we explicitly say that `ev` is the \"strictest\" `P` that satisfies `Ev`:\nghost predicate Minimal(Ev: P -> bool, ev: P) {\n && Ev(ev)\n && (forall ev': P, n: nat | Ev(ev') :: ev(n) ==> ev'(n))\n}\n// In this approach, some lemmas are a bit tricky to prove...\nlemma c0(ev: P) requires Minimal(Ev, ev) ensures ev(4) {\n}\nlemma c1(ev: P) requires Minimal(Ev, ev) ensures !ev(3) {\n var cex := (n: nat) => ( // `cex` stands for \"counterexample\"\n n != 1 && n != 3\n );\n}\nlemma c2(ev: P, n: nat) requires Minimal(Ev, ev) && ev(n) ensures ev(n + 2) {}\nlemma c3(ev: P, n: nat) requires Minimal(Ev, ev) && ev(n + 2) ensures ev(n) {\n if !ev(n) {\n var cex := (m: nat) => (\n m != n + 2 && ev(m)\n );\n }\n}\n\n\n// Finally, we \"circularly\" prove the equivalence among these three:\nlemma a_implies_b(n: nat) requires even(n) ensures Even(n) {\n if n == 0 {\n } else {\n a_implies_b(n - 2);\n var r: EvenRule :| r.apply() == n - 2;\n }\n}\nlemma b_implies_c(ev: P, n: nat) requires Minimal(Ev, ev) && Even(n) ensures ev(n) {\n var r: EvenRule :| r.apply() == n;\n if r.ev_SS? {\n b_implies_c(ev, n - 2);\n }\n}\nlemma c_implies_a(ev: P, n: nat) requires Minimal(Ev, ev) && ev(n) ensures even(n) {\n if n == 1 {\n var cex := (m: nat) => (\n m != 1\n );\n } else if n >= 2 {\n c3(ev, n - 2);\n c_implies_a(ev, n - 2);\n }\n}\n\n" }, { "test_ID": "337", "test_file": "Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_verified algorithms_lol_sort.dfy", "ground_truth": "// By `lol sort` here, I refer to a seemingly-broken sorting algorithm,\n// which actually somehow manages to work perfectly:\n//\n// for i in 0..n\n// for j in 0..n\n// if i < j\n// swap a[i], a[j]\n//\n// It is perhaps the simpliest sorting algorithm to \"memorize\",\n// even \"symmetrically beautiful\" as if `i` and `j` just played highly\n// similar roles. And technically it's still O(n^2) time lol...\n//\n// Proving its correctness is tricky (interesting) though.\n\n// Successfully verified with [Dafny 3.3.0.31104] in about 5 seconds.\n\n\n\n// We define \"valid permutation\" using multiset:\npredicate valid_permut(a: seq, b: seq)\n requires |a| == |b|\n{\n multiset(a) == multiset(b)\n}\n\n// This is a swap-based sorting algorithm, so permutedness is trivial:\n// note that: if i == j, the spec just says a[..] remains the same.\nmethod swap(a: array, i: int, j: int)\n requires 0 <= i < a.Length && 0 <= j < a.Length\n modifies a\n ensures a[..] == old(a[..]) [i := old(a[j])] [j := old(a[i])]\n ensures valid_permut(a[..], old(a[..]))\n{\n a[i], a[j] := a[j], a[i];\n}\n\n// We then define \"sorted\" (by increasing order):\npredicate sorted(a: seq)\n{\n forall i, j | 0 <= i <= j < |a| :: a[i] <= a[j]\n}\n\n\n// Now, the lol sort algorithm:\n// (Some invariants were tricky to find, but Dafny was smart enough otherwise)\nmethod lol_sort(a: array)\n modifies a\n ensures valid_permut(a[..], old(a[..]))\n ensures sorted(a[..])\n{\n for i := 0 to a.Length\n invariant valid_permut(a[..], old(a[..]))\n invariant sorted(a[..i])\n {\n for j := 0 to a.Length\n invariant valid_permut(a[..], old(a[..]))\n invariant j < i ==> forall k | 0 <= k < j :: a[k] <= a[i]\n invariant j < i ==> sorted(a[..i])\n invariant j >= i ==> sorted(a[..i+1])\n {\n if a[i] < a[j] {\n swap(a, i, j);\n }\n }\n }\n}\n\n\n\nmethod Main() {\n var a := new int[] [3,1,4,1,5,9,2,6];\n lol_sort(a);\n print a[..];\n // `expect` is a run-time assert, more suitable than `assert` on complicated testcases:\n expect a[..] == [1,1,2,3,4,5,6,9]; \n\n var empty := new int[] [];\n lol_sort(empty);\n assert empty[..] == [];\n}\n", "hints_removed": "// By `lol sort` here, I refer to a seemingly-broken sorting algorithm,\n// which actually somehow manages to work perfectly:\n//\n// for i in 0..n\n// for j in 0..n\n// if i < j\n// swap a[i], a[j]\n//\n// It is perhaps the simpliest sorting algorithm to \"memorize\",\n// even \"symmetrically beautiful\" as if `i` and `j` just played highly\n// similar roles. And technically it's still O(n^2) time lol...\n//\n// Proving its correctness is tricky (interesting) though.\n\n// Successfully verified with [Dafny 3.3.0.31104] in about 5 seconds.\n\n\n\n// We define \"valid permutation\" using multiset:\npredicate valid_permut(a: seq, b: seq)\n requires |a| == |b|\n{\n multiset(a) == multiset(b)\n}\n\n// This is a swap-based sorting algorithm, so permutedness is trivial:\n// note that: if i == j, the spec just says a[..] remains the same.\nmethod swap(a: array, i: int, j: int)\n requires 0 <= i < a.Length && 0 <= j < a.Length\n modifies a\n ensures a[..] == old(a[..]) [i := old(a[j])] [j := old(a[i])]\n ensures valid_permut(a[..], old(a[..]))\n{\n a[i], a[j] := a[j], a[i];\n}\n\n// We then define \"sorted\" (by increasing order):\npredicate sorted(a: seq)\n{\n forall i, j | 0 <= i <= j < |a| :: a[i] <= a[j]\n}\n\n\n// Now, the lol sort algorithm:\n// (Some invariants were tricky to find, but Dafny was smart enough otherwise)\nmethod lol_sort(a: array)\n modifies a\n ensures valid_permut(a[..], old(a[..]))\n ensures sorted(a[..])\n{\n for i := 0 to a.Length\n {\n for j := 0 to a.Length\n {\n if a[i] < a[j] {\n swap(a, i, j);\n }\n }\n }\n}\n\n\n\nmethod Main() {\n var a := new int[] [3,1,4,1,5,9,2,6];\n lol_sort(a);\n print a[..];\n // `expect` is a run-time assert, more suitable than `assert` on complicated testcases:\n expect a[..] == [1,1,2,3,4,5,6,9]; \n\n var empty := new int[] [];\n lol_sort(empty);\n}\n" }, { "test_ID": "338", "test_file": "Programmverifikation-und-synthese_tmp_tmppurk6ime_PVS_Assignment_ex_04_Hoangkim_ex_04_Hoangkim.dfy", "ground_truth": "//Problem 01\nmethod sumOdds(n: nat) returns (sum: nat)\n requires n > 0;\n ensures sum == n * n;\n{\n sum := 1;\n var i := 0;\n\n while i < n-1\n invariant 0 <= i < n;\n invariant sum == (i + 1) * (i + 1);\n {\n i := i + 1;\n sum := sum + 2 * i + 1;\n }\n\n assert sum == n * n;\n\n}\n\n//problem02\n//a)\nmethod intDiv(n:int, d:int) returns (q:int, r:int)\nrequires n >= d && n >= 0 && d > 0 ;\nensures (d*q)+r == n && 0 <= q <= n/2 && 0 <= r < d; \n\n//b)c)\n\nmethod intDivImpl(n:int, d:int) returns (q:int, r:int)\nrequires n >= d && n >= 0 && d > 0;\nensures (d*q)+r == n && 0 <= q <= n/2 && 0 <= r < d; \n{\n q := 0;\n r := n;\n while r >= d\n invariant r == n - q * d;\n invariant d <= r;\n r := r-1;\n {\n r := r - d;\n q := q + 1;\n } \n assert n == (d * q) + r;\n}\n\n\n", "hints_removed": "//Problem 01\nmethod sumOdds(n: nat) returns (sum: nat)\n requires n > 0;\n ensures sum == n * n;\n{\n sum := 1;\n var i := 0;\n\n while i < n-1\n {\n i := i + 1;\n sum := sum + 2 * i + 1;\n }\n\n\n}\n\n//problem02\n//a)\nmethod intDiv(n:int, d:int) returns (q:int, r:int)\nrequires n >= d && n >= 0 && d > 0 ;\nensures (d*q)+r == n && 0 <= q <= n/2 && 0 <= r < d; \n\n//b)c)\n\nmethod intDivImpl(n:int, d:int) returns (q:int, r:int)\nrequires n >= d && n >= 0 && d > 0;\nensures (d*q)+r == n && 0 <= q <= n/2 && 0 <= r < d; \n{\n q := 0;\n r := n;\n while r >= d\n r := r-1;\n {\n r := r - d;\n q := q + 1;\n } \n}\n\n\n" }, { "test_ID": "339", "test_file": "Programmverifikation-und-synthese_tmp_tmppurk6ime_PVS_Assignment_ex_05_Hoangkim_ex_05_Hoangkim.dfy", "ground_truth": "\n//Problem01\nfunction fib(n: nat):nat\n{\n if n < 2 then n else fib(n-2)+fib(n-1)\n}\n\nmethod fibIter(n:nat) returns (a:nat)\nrequires n > 0\nensures a == fib(n)\n{\n a := 0;\n var b,x := 1,0;\n while x < n \n invariant 0 <= x <= n\n invariant a == fib(x)\n invariant b == fib(x+1)\n {\n a,b := b,a+b;\n //why a,b := b,a+b is okay\n //but when I write a := b; //# Because this \n // b := a+b; //# is not the same !! \n //is error? //# {a = 1 , b = 2 } a := b ; b := a+b { b = 4 }, but \n x := x+1; //# {a = 1 , b = 2 } a, b := b,a+b { b = 3 }\n }\n assert a == fib(n); \n}\n//# 2 pts\n\n//Problem02\nfunction fact(n:nat):nat\n{if n==0 then 1 else n*fact(n-1)}\n\nmethod factIter(n:nat) returns (a:nat)\nrequires n >= 0;\nensures a == fact(n)\n{\n a := 1;\n var i := 1;\n while i <= n\n invariant 1 <= i <= n+1\n invariant a == fact(i-1)\n {\n a := a * i;\n i := i + 1;\n }\n assert a == fact(n);\n} \n//# 3 pts\n//Problem03\nfunction gcd(m: nat, n: nat): nat\n requires m > 0 && n > 0\n{\n if m == n then m\n else if m > n then gcd(m - n, n)\n else gcd(m, n - m)\n}\n\nmethod gcdI(m: int, n: int) returns (g: int)\n requires m > 0 && n > 0 \n ensures g == gcd(m, n);\n {\n var x: int;\n g := m;\n x := n;\n while (g != x)\n invariant x > 0;\n invariant g > 0;\n invariant gcd(g, x) == gcd(m, n);\n decreases x+g;\n {\n if (g > x)\n {\n g := g - x;\n }\n else\n {\n x := x - g;\n }\n }\n }\n//# 3 pts\n\n\n// # sum: 9 pts\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "hints_removed": "\n//Problem01\nfunction fib(n: nat):nat\n{\n if n < 2 then n else fib(n-2)+fib(n-1)\n}\n\nmethod fibIter(n:nat) returns (a:nat)\nrequires n > 0\nensures a == fib(n)\n{\n a := 0;\n var b,x := 1,0;\n while x < n \n {\n a,b := b,a+b;\n //why a,b := b,a+b is okay\n //but when I write a := b; //# Because this \n // b := a+b; //# is not the same !! \n //is error? //# {a = 1 , b = 2 } a := b ; b := a+b { b = 4 }, but \n x := x+1; //# {a = 1 , b = 2 } a, b := b,a+b { b = 3 }\n }\n}\n//# 2 pts\n\n//Problem02\nfunction fact(n:nat):nat\n{if n==0 then 1 else n*fact(n-1)}\n\nmethod factIter(n:nat) returns (a:nat)\nrequires n >= 0;\nensures a == fact(n)\n{\n a := 1;\n var i := 1;\n while i <= n\n {\n a := a * i;\n i := i + 1;\n }\n} \n//# 3 pts\n//Problem03\nfunction gcd(m: nat, n: nat): nat\n requires m > 0 && n > 0\n{\n if m == n then m\n else if m > n then gcd(m - n, n)\n else gcd(m, n - m)\n}\n\nmethod gcdI(m: int, n: int) returns (g: int)\n requires m > 0 && n > 0 \n ensures g == gcd(m, n);\n {\n var x: int;\n g := m;\n x := n;\n while (g != x)\n {\n if (g > x)\n {\n g := g - x;\n }\n else\n {\n x := x - g;\n }\n }\n }\n//# 3 pts\n\n\n// # sum: 9 pts\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "test_ID": "340", "test_file": "Programmverifikation-und-synthese_tmp_tmppurk6ime_PVS_Assignment_ex_06_Hoangkim_ex06-solution.dfy", "ground_truth": "ghost function gcd(x:int,y:int):int\n requires x > 0 && y > 0 \n{\n if x==y then x\n else if x > y then gcd(x-y,y)\n else gcd(x,y-x)\n}\n\n\nmethod gcdI(m:int, n:int) returns (d:int)\n requires m > 0 && n > 0\n ensures d == gcd(m,n) \n{\n var x,y := m,n;\n d := 1;\n while x != y\n decreases x+y\n invariant x > 0 && y > 0\n invariant gcd(x,y) == gcd(m,n) \n { if x > y { x := x-y; } else { y := y-x; }\n }\n d := x;\n}\n\nghost function gcd'(x:int,y:int):int\n requires x > 0 && y > 0\n decreases x+y,y // x+y decreases or x+y remains unchanged while y decreases\n{\n if x==y then x\n else if x > y then gcd'(x-y,y)\n else gcd'(y,x)\n}\n\n", "hints_removed": "ghost function gcd(x:int,y:int):int\n requires x > 0 && y > 0 \n{\n if x==y then x\n else if x > y then gcd(x-y,y)\n else gcd(x,y-x)\n}\n\n\nmethod gcdI(m:int, n:int) returns (d:int)\n requires m > 0 && n > 0\n ensures d == gcd(m,n) \n{\n var x,y := m,n;\n d := 1;\n while x != y\n { if x > y { x := x-y; } else { y := y-x; }\n }\n d := x;\n}\n\nghost function gcd'(x:int,y:int):int\n requires x > 0 && y > 0\n{\n if x==y then x\n else if x > y then gcd'(x-y,y)\n else gcd'(y,x)\n}\n\n" }, { "test_ID": "341", "test_file": "Programmverifikation-und-synthese_tmp_tmppurk6ime_PVS_Assignment_ex_06_Hoangkim_ex_06_hoangkim.dfy", "ground_truth": "\n//Problem01\n//a)\nghost function gcd(x: int, y: int): int\n requires x > 0 && y > 0\n{\n if x == y then x\n else if x > y then gcd(x - y, y)\n else gcd(x, y - x)\n}\n\nmethod gcdI(m: int, n: int) returns (d: int)\nrequires m > 0 && n > 0 \nensures d == gcd(m, n);\n{\n var x: int;\n d := m;\n x := n;\n while (d != x)\n invariant x > 0;\n invariant d > 0;\n invariant gcd(d, x) == gcd(m, n);\n decreases x+d;\n {\n if (d > x)\n {\n d := d - x;\n }\n else\n {\n x := x - d;\n }\n }\n}\n\n//b)\nghost function gcd'(x: int, y: int): int\n requires x > 0 && y > 0\n decreases if x > y then x else y\n{\n if x == y then x\n else if x > y then gcd'(x - y, y)\n else gcd(y, x)\n}\n\n \n\n", "hints_removed": "\n//Problem01\n//a)\nghost function gcd(x: int, y: int): int\n requires x > 0 && y > 0\n{\n if x == y then x\n else if x > y then gcd(x - y, y)\n else gcd(x, y - x)\n}\n\nmethod gcdI(m: int, n: int) returns (d: int)\nrequires m > 0 && n > 0 \nensures d == gcd(m, n);\n{\n var x: int;\n d := m;\n x := n;\n while (d != x)\n {\n if (d > x)\n {\n d := d - x;\n }\n else\n {\n x := x - d;\n }\n }\n}\n\n//b)\nghost function gcd'(x: int, y: int): int\n requires x > 0 && y > 0\n{\n if x == y then x\n else if x > y then gcd'(x - y, y)\n else gcd(y, x)\n}\n\n \n\n" }, { "test_ID": "342", "test_file": "Programmverifikation-und-synthese_tmp_tmppurk6ime_PVS_Assignment_ex_07_Hoangkim_ex07_Hoangkim.dfy", "ground_truth": "//Problem01\n//a)\nmethod swap(a: array, i: nat, j: nat)\n modifies a\n requires a != null && a.Length > 0 && i < a.Length && j < a.Length\n ensures a[i] == old(a[j])\n ensures a[j] == old(a[i])\n{\n a[i], a[j] := a[j], a[i];\n}\n\n//b)\n//Problem04\nmethod FindMin(a: array, lo: nat) returns (minIdx: nat)\n requires a != null && a.Length > 0 && lo < a.Length\n ensures lo <= minIdx < a.Length\n ensures forall x :: lo <= x < a.Length ==> a[minIdx] <= a[x]\n{\n var j := lo;\n\tminIdx := lo;\n\twhile j < a.Length\n\t\tinvariant lo <= j <= a.Length\n\t\tinvariant lo <= minIdx < a.Length\n\t\tinvariant forall k :: lo <= k < j ==> a[k] >= a[minIdx]\n\t\tdecreases a.Length - j\n\t{\n\t\tif(a[j] < a[minIdx]) { minIdx := j; }\n\t\tj := j + 1;\n\t}\n}\n\n//Problem02\nghost predicate sorted(a:seq)\n{\n forall i | 0 < i < |a| :: a[i-1] <= a[i] \n}\n\nmethod selectionSort(a: array)\n modifies a\n //ensures multiset(a[..]) == multiset(old(a[..]))\n //ensures sorted(a[..])\n{\n\tvar i := 0;\n\twhile(i < a.Length)\n\t\tinvariant 0 <= i <= a.Length\n\t\tinvariant forall k, l :: 0 <= k < i <= l < a.Length ==> a[k] <= a[l]\n\t\tinvariant sorted(a[..i])\n\t{\n\t\tvar mx := FindMin(a, i);\n\t\t//swap(a,i,mx);\n a[i], a[mx] := a[mx], a[i];\n\t\ti := i + 1;\n\t}\n\n}\n\n\n//Problem03\n\n\n\n", "hints_removed": "//Problem01\n//a)\nmethod swap(a: array, i: nat, j: nat)\n modifies a\n requires a != null && a.Length > 0 && i < a.Length && j < a.Length\n ensures a[i] == old(a[j])\n ensures a[j] == old(a[i])\n{\n a[i], a[j] := a[j], a[i];\n}\n\n//b)\n//Problem04\nmethod FindMin(a: array, lo: nat) returns (minIdx: nat)\n requires a != null && a.Length > 0 && lo < a.Length\n ensures lo <= minIdx < a.Length\n ensures forall x :: lo <= x < a.Length ==> a[minIdx] <= a[x]\n{\n var j := lo;\n\tminIdx := lo;\n\twhile j < a.Length\n\t{\n\t\tif(a[j] < a[minIdx]) { minIdx := j; }\n\t\tj := j + 1;\n\t}\n}\n\n//Problem02\nghost predicate sorted(a:seq)\n{\n forall i | 0 < i < |a| :: a[i-1] <= a[i] \n}\n\nmethod selectionSort(a: array)\n modifies a\n //ensures multiset(a[..]) == multiset(old(a[..]))\n //ensures sorted(a[..])\n{\n\tvar i := 0;\n\twhile(i < a.Length)\n\t{\n\t\tvar mx := FindMin(a, i);\n\t\t//swap(a,i,mx);\n a[i], a[mx] := a[mx], a[i];\n\t\ti := i + 1;\n\t}\n\n}\n\n\n//Problem03\n\n\n\n" }, { "test_ID": "343", "test_file": "Programmverifikation-und-synthese_tmp_tmppurk6ime_PVS_Assignment_ex_10_Hoangkim_ex10_hoangkim.dfy", "ground_truth": "//Problem01\nmethod square0(n:nat) returns (sqn : nat)\nensures sqn == n*n\n{\n sqn := 0;\n var i:= 0;\n var x;\n while i < n\n invariant i <= n && sqn == i*i \n {\n x := 2*i+1;\n sqn := sqn+x;\n i := i+1;\n }\n \n}\n\n/*\n3 Verification conditions\n\n1. VC1: Precondiotion implies the loop variant\nn \u2208 \u2115 => sqn = 0*0 \u2227 i = 0 \u2227 x=? \u2227 i\u2264n \nn >= 0 => 0 = 0*0 \u2227 i = 0 \u2227 i\u2264n \nn >= 0 => 0 = 0*0 \u2227 0 \u2264 n \n2. VC2: Loop invariant and loop guard preserve the loop invariant.\nVC2: i < n \u2227 i+1 \u2264 n \u2227 sqn = i * i \u21d2 sqn = sqn + x \u2227 i = i + 1 \u2227 x = 2 * i + 1\n3.VC3: Loop terminates, and the loop invariant implies the postcondition.\nVC3: \u00ac(i < n) \u2227 i \u2264 n \u2227 sqn = i * i \u21d2 sqn = n * n\n\nSimplified VC for square0\n1. true, since 0 = 0 and n >= 0 => 0 \u2264 n\n2. true, i < n => i + 1 <= n\n3. true, \u00ac(i < n) \u2227 i \u2264 n \u2227 sqn = i * i \u21d2 sqn = n * n since \u00ac(i < n) \u2227 i \u2264 n imply i = n\n\n*/\n\nmethod square1(n:nat) returns (sqn : nat)\nensures sqn == n*n\n{\n sqn := 0;\n var i:= 0;\n\n while i < n\n invariant i <= n && sqn == i*i \n {\n var x := 2*i+1;\n sqn := sqn+x;\n i := i+1;\n }\n \n}\n\n//Problem02\n//As you can see below, Dafny claims that after executing the following method\n//strange() we will have that 1=2;\nmethod q(x:nat, y:nat) returns (z:nat)\nrequires y - x > 2\nensures x < z*z < y\n\nmethod strange()\nensures 1==2\n{\n var x := 4;\n var c:nat := q(x,2*x); \n}\n/*(a). Do you have an explanation for this behaviour?\n Answer: \n the method strange() doesn't have any input or output. This method initializes\n variable x with value 4. Then it calculates variable c as a result of calling\n method 'q' with x as first var and 2*x as second var.the strange method does not \n specify any postcondition. Therefore, we cannot make any assumptions about the \n behavior or the value of c after calling q.\n We can change ensures in strange() to false and it's still verified\n*/\n\n/*(b) {true}var x:nat := 4; var c := q(x,2*x); {1 = 2 }\n precond in strange(): difference between 'y' and 'x' muss be greater than 2,\n square from 'z' will be a value between 'x' and 'y'\n\n apply the Hoare rules step by step:\n 1. {true} as a precondition\n 2. we assign 4 to 'x' and having {4=4}\n 3. assign value q(x, 2 * x) to c, substitute the postcondition of 'q' in place of 'c'\n post cond of q will be x < z*z < 2*x. Replacing c we having {x < z * z < 2 * x}\n 4. we having the statement {x < z*z < 2*x} => {1 = 2} as postcondtion\n\n as we know the statment {1 = 2} is always false. true => false is always false \n\n\n\n*/\n\n//Problem 3\n//Use what you know about the weakest preconditions/strongest postconditions to ex-\n//plain why the following code verifies:\nmethod test0(){\n var x:int := *;\n assume x*x < 100;\n assert x<= 9;\n}\n\n/*\nWP: is a condition that, if satisfied before the execution of a program, guarantees the \nsatisfaction of a specified postcondition\nSP: is a condition that must hold after the execution of a program, assuming a specified \nprecondition\n\nThe strongest postcondition for assert is x<=9\nAnalyze the code: \nThe strongest postcondition for the assert statement assert x <= 9; is x <= 9. This \npostcondition asserts that the value of x should be less than or equal to 9 after the \nexecution of the program. To ensure this postcondition, we need to find a weakest precondition \n(WP) that guarantees x <= 9 after executing the code.\n\nThe \"assume\" statement introduces a precondition.\nIt assumes that the square of x is less than 100. In other words, it assumes that x is \nwithin the range (0, 10) since the largest possible square less than 100 is 9 * 9 = 81.\n\n\n*/\n\n\n\n", "hints_removed": "//Problem01\nmethod square0(n:nat) returns (sqn : nat)\nensures sqn == n*n\n{\n sqn := 0;\n var i:= 0;\n var x;\n while i < n\n {\n x := 2*i+1;\n sqn := sqn+x;\n i := i+1;\n }\n \n}\n\n/*\n3 Verification conditions\n\n1. VC1: Precondiotion implies the loop variant\nn \u2208 \u2115 => sqn = 0*0 \u2227 i = 0 \u2227 x=? \u2227 i\u2264n \nn >= 0 => 0 = 0*0 \u2227 i = 0 \u2227 i\u2264n \nn >= 0 => 0 = 0*0 \u2227 0 \u2264 n \n2. VC2: Loop invariant and loop guard preserve the loop invariant.\nVC2: i < n \u2227 i+1 \u2264 n \u2227 sqn = i * i \u21d2 sqn = sqn + x \u2227 i = i + 1 \u2227 x = 2 * i + 1\n3.VC3: Loop terminates, and the loop invariant implies the postcondition.\nVC3: \u00ac(i < n) \u2227 i \u2264 n \u2227 sqn = i * i \u21d2 sqn = n * n\n\nSimplified VC for square0\n1. true, since 0 = 0 and n >= 0 => 0 \u2264 n\n2. true, i < n => i + 1 <= n\n3. true, \u00ac(i < n) \u2227 i \u2264 n \u2227 sqn = i * i \u21d2 sqn = n * n since \u00ac(i < n) \u2227 i \u2264 n imply i = n\n\n*/\n\nmethod square1(n:nat) returns (sqn : nat)\nensures sqn == n*n\n{\n sqn := 0;\n var i:= 0;\n\n while i < n\n {\n var x := 2*i+1;\n sqn := sqn+x;\n i := i+1;\n }\n \n}\n\n//Problem02\n//As you can see below, Dafny claims that after executing the following method\n//strange() we will have that 1=2;\nmethod q(x:nat, y:nat) returns (z:nat)\nrequires y - x > 2\nensures x < z*z < y\n\nmethod strange()\nensures 1==2\n{\n var x := 4;\n var c:nat := q(x,2*x); \n}\n/*(a). Do you have an explanation for this behaviour?\n Answer: \n the method strange() doesn't have any input or output. This method initializes\n variable x with value 4. Then it calculates variable c as a result of calling\n method 'q' with x as first var and 2*x as second var.the strange method does not \n specify any postcondition. Therefore, we cannot make any assumptions about the \n behavior or the value of c after calling q.\n We can change ensures in strange() to false and it's still verified\n*/\n\n/*(b) {true}var x:nat := 4; var c := q(x,2*x); {1 = 2 }\n precond in strange(): difference between 'y' and 'x' muss be greater than 2,\n square from 'z' will be a value between 'x' and 'y'\n\n apply the Hoare rules step by step:\n 1. {true} as a precondition\n 2. we assign 4 to 'x' and having {4=4}\n 3. assign value q(x, 2 * x) to c, substitute the postcondition of 'q' in place of 'c'\n post cond of q will be x < z*z < 2*x. Replacing c we having {x < z * z < 2 * x}\n 4. we having the statement {x < z*z < 2*x} => {1 = 2} as postcondtion\n\n as we know the statment {1 = 2} is always false. true => false is always false \n\n\n\n*/\n\n//Problem 3\n//Use what you know about the weakest preconditions/strongest postconditions to ex-\n//plain why the following code verifies:\nmethod test0(){\n var x:int := *;\n assume x*x < 100;\n}\n\n/*\nWP: is a condition that, if satisfied before the execution of a program, guarantees the \nsatisfaction of a specified postcondition\nSP: is a condition that must hold after the execution of a program, assuming a specified \nprecondition\n\nThe strongest postcondition for assert is x<=9\nAnalyze the code: \nThe strongest postcondition for the assert statement assert x <= 9; is x <= 9. This \npostcondition asserts that the value of x should be less than or equal to 9 after the \nexecution of the program. To ensure this postcondition, we need to find a weakest precondition \n(WP) that guarantees x <= 9 after executing the code.\n\nThe \"assume\" statement introduces a precondition.\nIt assumes that the square of x is less than 100. In other words, it assumes that x is \nwithin the range (0, 10) since the largest possible square less than 100 is 9 * 9 = 81.\n\n\n*/\n\n\n\n" }, { "test_ID": "344", "test_file": "Programmverifikation-und-synthese_tmp_tmppurk6ime_example_DafnyIntro_01_Simple_Loops.dfy", "ground_truth": "// ****************************************************************************************\n// DafnyIntro.dfy\n// ****************************************************************************************\n// We write a program to sum all numbers from 1 to n\n// \n// Gauss' formula states that 1 + 2 + 3 + ... + (n-1) + n == n*(n+1)/2 \n//\n// We take this a specification, thus in effect we use Dafny to prove Gauss' formula: \n\n// In essence Dafny does an inductive proof. It needs help with a loop \"invariant\".\n// This is a condition which is \n\n// - true at the beginning of the loop\n// - maintained with each passage through the loop body.\n\n// These requirements correspond to an inductive proof\n\n// - the invariant is the inductive hypothesis H(i)\n// - it must be true for i=0\n// - it must remain true when stepping from i to i+1, \n\n// Here we use two invariants I1 and I2, which amounts to the same as using I1 && I2: \n\nmethod Gauss(n:int) returns (sum:int)\nrequires n >= 0\nensures sum == n*(n+1)/2 // \n{\n sum := 0; \n var i := 0;\n while i < n\n invariant sum == i*(i+1)/2 \n invariant i <= n\n {\n i := i+1;\n sum := sum + i;\n }\n}\n\n// As a second example, we add the first n odd numbers \n// This yields n*n, i.e.\n//\n// 1 + 3 + 5 + 7 + 9 + 11 + ... 2n+1 == n*n\n//\n// Here is the proof using Dafny:\n\nmethod sumOdds(n:nat) returns (sum:nat)\nensures sum == n*n;\n{\n sum := 0; \n var i := 0;\n while i < n\n invariant sum == i*i // the inductive hypothesis\n invariant i <= n\n {\n sum := sum + 2*i+1;\n i := i+1; // the step from i to i+1\n }\n}\n\n// This verifies, so the proof is complete !!\n\n", "hints_removed": "// ****************************************************************************************\n// DafnyIntro.dfy\n// ****************************************************************************************\n// We write a program to sum all numbers from 1 to n\n// \n// Gauss' formula states that 1 + 2 + 3 + ... + (n-1) + n == n*(n+1)/2 \n//\n// We take this a specification, thus in effect we use Dafny to prove Gauss' formula: \n\n// In essence Dafny does an inductive proof. It needs help with a loop \"invariant\".\n// This is a condition which is \n\n// - true at the beginning of the loop\n// - maintained with each passage through the loop body.\n\n// These requirements correspond to an inductive proof\n\n// - the invariant is the inductive hypothesis H(i)\n// - it must be true for i=0\n// - it must remain true when stepping from i to i+1, \n\n// Here we use two invariants I1 and I2, which amounts to the same as using I1 && I2: \n\nmethod Gauss(n:int) returns (sum:int)\nrequires n >= 0\nensures sum == n*(n+1)/2 // \n{\n sum := 0; \n var i := 0;\n while i < n\n {\n i := i+1;\n sum := sum + i;\n }\n}\n\n// As a second example, we add the first n odd numbers \n// This yields n*n, i.e.\n//\n// 1 + 3 + 5 + 7 + 9 + 11 + ... 2n+1 == n*n\n//\n// Here is the proof using Dafny:\n\nmethod sumOdds(n:nat) returns (sum:nat)\nensures sum == n*n;\n{\n sum := 0; \n var i := 0;\n while i < n\n {\n sum := sum + 2*i+1;\n i := i+1; // the step from i to i+1\n }\n}\n\n// This verifies, so the proof is complete !!\n\n" }, { "test_ID": "345", "test_file": "ProjectosCVS_tmp_tmp_02_gmcw_Handout 1_CVS_handout1_55754_55780.dfy", "ground_truth": "/**\nCVS 2021-22 Handout 1\nAuthors\nGon\u00e7alo Martins Louren\u00e7o n\u00ba55780\nJoana Soares Faria n\u00ba55754\n */\n\n// First Exercise\nlemma peasantMultLemma(a:int, b:int)\n requires b >= 0\n ensures b % 2 == 0 ==> (a * b == 2 * a * b / 2)\n ensures b % 2 == 1 ==> (a * b == a + 2 * a * (b - 1) / 2)\n {\n if (b % 2 == 0 && b > 0) { \n peasantMultLemma(a, b - 2);\n }\n\n if (b % 2 == 1 && b > 1) {\n peasantMultLemma(a, b - 2);\n }\n\n }\n\nmethod peasantMult(a: int, b: int) returns (r: int)\n requires b > 0\n ensures r == a * b\n {\n r := 0;\n var aa := a;\n var bb := b;\n \n while(bb > 0)\n decreases bb \n invariant 0 <= bb <= b\n invariant r + aa * bb == a * b\n { \n // Use of lemma was not necessary for a successful verification\n // peasantMultLemma(aa, bb);\n if (bb % 2 == 0)\n {\n aa := 2 * aa;\n bb := bb / 2;\n\n } else if (bb % 2 == 1)\n {\n r := r + aa;\n aa := 2 * aa;\n bb := (bb-1) / 2;\n }\n } \n }\n\n\n//Second Exercise\nmethod euclidianDiv(a: int,b : int) returns (q: int,r: int)\n requires a >= 0\n requires b > 0\n ensures a == b * q + r\n {\n r := a;\n q := 0;\n while(r - b >= 0)\n decreases r - b\n invariant 0 <= r <= a\n // invariant a == b * q + r\n invariant r == a - b * q\n {\n r := r - b;\n q := q + 1;\n }\n\n }\n\n", "hints_removed": "/**\nCVS 2021-22 Handout 1\nAuthors\nGon\u00e7alo Martins Louren\u00e7o n\u00ba55780\nJoana Soares Faria n\u00ba55754\n */\n\n// First Exercise\nlemma peasantMultLemma(a:int, b:int)\n requires b >= 0\n ensures b % 2 == 0 ==> (a * b == 2 * a * b / 2)\n ensures b % 2 == 1 ==> (a * b == a + 2 * a * (b - 1) / 2)\n {\n if (b % 2 == 0 && b > 0) { \n peasantMultLemma(a, b - 2);\n }\n\n if (b % 2 == 1 && b > 1) {\n peasantMultLemma(a, b - 2);\n }\n\n }\n\nmethod peasantMult(a: int, b: int) returns (r: int)\n requires b > 0\n ensures r == a * b\n {\n r := 0;\n var aa := a;\n var bb := b;\n \n while(bb > 0)\n { \n // Use of lemma was not necessary for a successful verification\n // peasantMultLemma(aa, bb);\n if (bb % 2 == 0)\n {\n aa := 2 * aa;\n bb := bb / 2;\n\n } else if (bb % 2 == 1)\n {\n r := r + aa;\n aa := 2 * aa;\n bb := (bb-1) / 2;\n }\n } \n }\n\n\n//Second Exercise\nmethod euclidianDiv(a: int,b : int) returns (q: int,r: int)\n requires a >= 0\n requires b > 0\n ensures a == b * q + r\n {\n r := a;\n q := 0;\n while(r - b >= 0)\n // invariant a == b * q + r\n {\n r := r - b;\n q := q + 1;\n }\n\n }\n\n" }, { "test_ID": "346", "test_file": "QS_BoilerPlate1_tmp_tmpa29vtz9__Ex2.dfy", "ground_truth": "function sorted(s : seq) : bool {\n forall k1, k2 :: 0 <= k1 <= k2 < |s| ==> s[k1] <= s[k2]\n}\n\n\n// Ex1\n\nmethod copyArr(a : array, l : int, r : int) returns (ret : array)\n requires 0 <= l < r <= a.Length \n ensures ret[..] == a[l..r]\n{\n var size := r - l;\n ret := new int[size];\n var i := 0;\n \n while(i < size)\n invariant a[..] == old(a[..])\n invariant 0 <= i <= size\n invariant ret[..i] == a[l..(l + i)]\n decreases size - i\n {\n ret[i] := a[i + l];\n i := i + 1;\n }\n return;\n}\n\n\n// Ex2\n\nmethod mergeArr(a : array, l : int, m : int, r : int)\n requires 0 <= l < m < r <= a.Length \n requires sorted(a[l..m]) && sorted(a[m..r])\n ensures sorted(a[l..r]) \n ensures a[..l] == old(a[..l])\n ensures a[r..] == old(a[r..])\n modifies a \n{\n var left := copyArr(a, l, m);\n var right := copyArr(a, m, r);\n var i := 0;\n var j := 0;\n var cur := l;\n ghost var old_arr := a[..];\n while(cur < r) \n decreases a.Length - cur\n invariant 0 <= i <= left.Length\n invariant 0 <= j <= right.Length\n invariant l <= cur <= r\n invariant cur == i + j + l\n invariant a[..l] == old_arr[..l]\n invariant a[r..] == old_arr[r..]\n invariant sorted(a[l..cur])\n invariant sorted(left[..])\n invariant sorted(right[..])\n invariant i < left.Length && cur > l ==> a[cur - 1] <= left[i] \n invariant j < right.Length && cur > l ==> a[cur - 1] <= right[j]\n {\n if((i == left.Length && j < right.Length) || (j != right.Length && left[i] > right[j])) {\n a[cur] := right[j];\n j := j + 1;\n }\n else if((j == right.Length && i < left.Length) || (i != left.Length && left[i] <= right[j])) {\n a[cur] := left[i];\n i := i + 1;\n }\n cur := cur + 1;\n }\n return;\n}\n\n// Ex3\n\nmethod sort(a : array) \n ensures sorted(a[..])\n modifies a\n{\n if(a.Length == 0) { return; }\n else { sortAux(a, 0, a.Length); }\n}\n\nmethod sortAux(a : array, l : int, r : int)\n ensures sorted(a[l..r])\n ensures a[..l] == old(a[..l])\n ensures a[r..] == old(a[r..])\n requires 0 <= l < r <= a.Length\n modifies a\n decreases r - l\n{\n if(l >= (r - 1)) {return;}\n else {\n var m := l + (r - l) / 2;\n sortAux(a, l, m);\n sortAux(a, m, r);\n mergeArr(a, l, m, r);\n return;\n }\n}\n", "hints_removed": "function sorted(s : seq) : bool {\n forall k1, k2 :: 0 <= k1 <= k2 < |s| ==> s[k1] <= s[k2]\n}\n\n\n// Ex1\n\nmethod copyArr(a : array, l : int, r : int) returns (ret : array)\n requires 0 <= l < r <= a.Length \n ensures ret[..] == a[l..r]\n{\n var size := r - l;\n ret := new int[size];\n var i := 0;\n \n while(i < size)\n {\n ret[i] := a[i + l];\n i := i + 1;\n }\n return;\n}\n\n\n// Ex2\n\nmethod mergeArr(a : array, l : int, m : int, r : int)\n requires 0 <= l < m < r <= a.Length \n requires sorted(a[l..m]) && sorted(a[m..r])\n ensures sorted(a[l..r]) \n ensures a[..l] == old(a[..l])\n ensures a[r..] == old(a[r..])\n modifies a \n{\n var left := copyArr(a, l, m);\n var right := copyArr(a, m, r);\n var i := 0;\n var j := 0;\n var cur := l;\n ghost var old_arr := a[..];\n while(cur < r) \n {\n if((i == left.Length && j < right.Length) || (j != right.Length && left[i] > right[j])) {\n a[cur] := right[j];\n j := j + 1;\n }\n else if((j == right.Length && i < left.Length) || (i != left.Length && left[i] <= right[j])) {\n a[cur] := left[i];\n i := i + 1;\n }\n cur := cur + 1;\n }\n return;\n}\n\n// Ex3\n\nmethod sort(a : array) \n ensures sorted(a[..])\n modifies a\n{\n if(a.Length == 0) { return; }\n else { sortAux(a, 0, a.Length); }\n}\n\nmethod sortAux(a : array, l : int, r : int)\n ensures sorted(a[l..r])\n ensures a[..l] == old(a[..l])\n ensures a[r..] == old(a[r..])\n requires 0 <= l < r <= a.Length\n modifies a\n{\n if(l >= (r - 1)) {return;}\n else {\n var m := l + (r - l) / 2;\n sortAux(a, l, m);\n sortAux(a, m, r);\n mergeArr(a, l, m, r);\n return;\n }\n}\n" }, { "test_ID": "347", "test_file": "SENG2011_tmp_tmpgk5jq85q_ass1_ex7.dfy", "ground_truth": "// successfully verifies\nmethod BigFoot(step: nat) // DO NOT CHANGE\nrequires 0 < step <= 42;\n{\n var indx := 0; // DO NOT CHANGE\n while indx<=42 // DO NOT CHANGE\n invariant 0 <= indx <= step + 42 && indx % step == 0\n decreases 42 - indx\n { indx := indx+step; } // DO NOT CHANGE\n assert 0 <= indx <= step + 42 && indx % step == 0 && indx > 42;\n}\n\n", "hints_removed": "// successfully verifies\nmethod BigFoot(step: nat) // DO NOT CHANGE\nrequires 0 < step <= 42;\n{\n var indx := 0; // DO NOT CHANGE\n while indx<=42 // DO NOT CHANGE\n { indx := indx+step; } // DO NOT CHANGE\n}\n\n" }, { "test_ID": "348", "test_file": "SENG2011_tmp_tmpgk5jq85q_ass1_ex8.dfy", "ground_truth": "// successfully verifies\nmethod GetEven(a: array)\nrequires true;\nensures forall i:int :: 0<=i a[i] % 2 == 0\nmodifies a\n{\n var i := 0;\n while i < a.Length\n invariant 0 <= i <= a.Length && forall j:int :: 0<=j a[j] % 2 == 0\n decreases a.Length - i\n {\n if a[i] % 2 != 0\n {\n a[i] := a[i] + 1;\n }\n i := i + 1;\n }\n}\n", "hints_removed": "// successfully verifies\nmethod GetEven(a: array)\nrequires true;\nensures forall i:int :: 0<=i a[i] % 2 == 0\nmodifies a\n{\n var i := 0;\n while i < a.Length\n {\n if a[i] % 2 != 0\n {\n a[i] := a[i] + 1;\n }\n i := i + 1;\n }\n}\n" }, { "test_ID": "349", "test_file": "SENG2011_tmp_tmpgk5jq85q_ass2_ex1.dfy", "ground_truth": "// method verifies\nmethod StringSwap(s: string, i:nat, j:nat) returns (t: string)\nrequires i >= 0 && j >= 0 && |s| >= 0;\nrequires |s| > 0 ==> i < |s| && j < |s|;\nensures multiset(s[..]) == multiset(t[..]);\nensures |s| == |t|;\nensures |s| > 0 ==> forall k:nat :: k != i && k != j && k < |s| ==> t[k] == s[k]\nensures |s| > 0 ==> t[i] == s[j] && t[j] == s[i];\nensures |s| == 0 ==> t == s;\n{\n t := s;\n if |s| == 0 {\n return t;\n }\n t := t[i := s[j]];\n t := t[j := s[i]];\n}\n\nmethod check() {\n var a:string := \"1scow2\";\n var b:string := StringSwap(a, 1, 5);\n assert b == \"12cows\";\n var c:string := \"\";\n var d:string := StringSwap(c, 1, 2);\n assert c == d;\n}\n// string == seq\n//give se2011 ass2 ex1.dfy\n\n", "hints_removed": "// method verifies\nmethod StringSwap(s: string, i:nat, j:nat) returns (t: string)\nrequires i >= 0 && j >= 0 && |s| >= 0;\nrequires |s| > 0 ==> i < |s| && j < |s|;\nensures multiset(s[..]) == multiset(t[..]);\nensures |s| == |t|;\nensures |s| > 0 ==> forall k:nat :: k != i && k != j && k < |s| ==> t[k] == s[k]\nensures |s| > 0 ==> t[i] == s[j] && t[j] == s[i];\nensures |s| == 0 ==> t == s;\n{\n t := s;\n if |s| == 0 {\n return t;\n }\n t := t[i := s[j]];\n t := t[j := s[i]];\n}\n\nmethod check() {\n var a:string := \"1scow2\";\n var b:string := StringSwap(a, 1, 5);\n var c:string := \"\";\n var d:string := StringSwap(c, 1, 2);\n}\n// string == seq\n//give se2011 ass2 ex1.dfy\n\n" }, { "test_ID": "350", "test_file": "SENG2011_tmp_tmpgk5jq85q_ass2_ex2.dfy", "ground_truth": "// verifies\n// check that string between indexes low and high-1 are sorted\npredicate Sorted(a: string, low:int, high:int)\nrequires 0 <= low <= high <= |a|\n{ \n forall j, k :: low <= j < k < high ==> a[j] <= a[k] \n}\n\nmethod String3Sort(a: string) returns (b: string) \nrequires |a| == 3;\nensures Sorted(b, 0, |b|);\nensures |a| == |b|;\nensures multiset{b[0], b[1], b[2]} == multiset{a[0], a[1], a[2]};\n\n{\n b := a;\n if (b[0] > b[1]) {\n b := b[0 := b[1]][1 := b[0]];\n }\n if (b[1] > b[2]) {\n b := b[1 := b[2]][2 := b[1]];\n }\n if (b[0] > b[1]) {\n b := b[0 := b[1]][1 := b[0]];\n }\n}\n\nmethod check() {\n var a:string := \"cba\";\n var b:string := String3Sort(a);\n assert b==\"abc\";\n\n var a1:string := \"aaa\";\n var b1:string := String3Sort(a1);\n assert b1==\"aaa\";\n\n var a2:string := \"abc\";\n var b2:string := String3Sort(a2);\n assert b2==\"abc\";\n\n var a3:string := \"cab\";\n var b3:string := String3Sort(a3);\n assert b3==\"abc\";\n\n var a4:string := \"bac\";\n var b4:string := String3Sort(a4);\n assert b4==\"abc\";\n\n var a5:string := \"bba\";\n var b5:string := String3Sort(a5);\n assert b5==\"abb\";\n\n var a6:string := \"aba\";\n var b6:string := String3Sort(a6);\n assert b6==\"aab\";\n\n var a7:string := \"acb\";\n var b7:string := String3Sort(a7);\n assert b7==\"abc\";\n\n var a8:string := \"bca\";\n var b8:string := String3Sort(a8);\n assert b8==\"abc\";\n\n var a9:string := \"bab\";\n var b9:string := String3Sort(a9);\n assert b9==\"abb\";\n\n var a10:string := \"abb\";\n var b10:string := String3Sort(a10);\n assert b10==\"abb\";\n}\n", "hints_removed": "// verifies\n// check that string between indexes low and high-1 are sorted\npredicate Sorted(a: string, low:int, high:int)\nrequires 0 <= low <= high <= |a|\n{ \n forall j, k :: low <= j < k < high ==> a[j] <= a[k] \n}\n\nmethod String3Sort(a: string) returns (b: string) \nrequires |a| == 3;\nensures Sorted(b, 0, |b|);\nensures |a| == |b|;\nensures multiset{b[0], b[1], b[2]} == multiset{a[0], a[1], a[2]};\n\n{\n b := a;\n if (b[0] > b[1]) {\n b := b[0 := b[1]][1 := b[0]];\n }\n if (b[1] > b[2]) {\n b := b[1 := b[2]][2 := b[1]];\n }\n if (b[0] > b[1]) {\n b := b[0 := b[1]][1 := b[0]];\n }\n}\n\nmethod check() {\n var a:string := \"cba\";\n var b:string := String3Sort(a);\n\n var a1:string := \"aaa\";\n var b1:string := String3Sort(a1);\n\n var a2:string := \"abc\";\n var b2:string := String3Sort(a2);\n\n var a3:string := \"cab\";\n var b3:string := String3Sort(a3);\n\n var a4:string := \"bac\";\n var b4:string := String3Sort(a4);\n\n var a5:string := \"bba\";\n var b5:string := String3Sort(a5);\n\n var a6:string := \"aba\";\n var b6:string := String3Sort(a6);\n\n var a7:string := \"acb\";\n var b7:string := String3Sort(a7);\n\n var a8:string := \"bca\";\n var b8:string := String3Sort(a8);\n\n var a9:string := \"bab\";\n var b9:string := String3Sort(a9);\n\n var a10:string := \"abb\";\n var b10:string := String3Sort(a10);\n}\n" }, { "test_ID": "351", "test_file": "SENG2011_tmp_tmpgk5jq85q_ass2_ex3.dfy", "ground_truth": "// verifies\n// all bs are before all as which are before all ds\npredicate sortedbad(s:string) \n{\n // all b's are before all a's and d's\n forall i,j :: 0 <= i < |s| && 0 <= j < |s| && s[i] == 'b' && (s[j] == 'a' || s[j] == 'd') ==> i < j &&\n // all a's are after all b's\n forall i,j :: 0 <= i < |s| && 0 <= j < |s| && s[i] == 'a' && s[j] == 'b' ==> i > j &&\n // all a's are before all d's\n forall i,j :: 0 <= i < |s| && 0 <= j < |s| && s[i] == 'a' && s[j] == 'd' ==> i < j &&\n // all d's are after a;; b's and a's\n forall i,j :: 0 <= i < |s| && 0 <= j < |s| && s[i] == 'd' && (s[j] == 'a' || s[j] == 'b') ==> i > j\n}\n\nmethod BadSort(a: string) returns (b: string)\nrequires forall k :: 0 <= k < |a| ==> a[k] == 'b' || a[k] == 'a' || a[k] == 'd';\nensures sortedbad(b);\nensures multiset(a[..]) == multiset(b[..]);\nensures |a| == |b|;\n{\n b := a;\n var next := 0;\n var white := 0;\n var blue := |b|; // colours between next and blue unsorted\n while (next != blue) // if next==blue, no colours left to sort\n invariant forall k :: 0 <= k < |b| ==> b[k] == 'b' || b[k] == 'a' || b[k] == 'd';\n invariant 0 <= white <= next <= blue <= |b|;\n // ensure next, white, blue are correct\n invariant forall i :: 0 <= i < white ==> b[i] == 'b';\n invariant forall i :: white <= i < next ==> b[i] == 'a';\n invariant forall i :: blue <= i < |b| ==> b[i] == 'd';\n // all b's are before all a's and d's\n invariant forall i,j :: 0 <= i < next && 0 <= j < next && b[i] == 'b' && (b[j] == 'a' || b[j] == 'd') ==> i < j\n // all a's are after all b's\n invariant forall i,j :: 0 <= i < next && 0 <= j < next && b[i] == 'a' && b[j] == 'b' ==> i > j\n // all a's are before all d's\n invariant forall i,j :: 0 <= i < next && 0 <= j < next && b[i] == 'a' && b[j] == 'd' ==> i < j\n // all d's are after a;; b's and a's\n invariant forall i,j :: 0 <= i < next && 0 <= j < next && b[i] == 'd' && (b[j] == 'a' || b[j] == 'b') ==> i > j\n invariant multiset(b[..]) == multiset(a[..]);\n invariant |a| == |b|;\n { \n if b[next] == 'b' {\n var tmp := b[next];\n b := b[next := b[white]];\n b := b[white := tmp];\n next := next + 1;\n white := white + 1;\n } else if b[next] == 'a' {\n next := next + 1;\n } else if b[next] == 'd'{\n blue := blue - 1;\n var tmp := b[next];\n b := b[next := b[blue]];\n b := b[blue := tmp];\n } \n }\n}\nmethod check() {\n var f:string := \"dabdabdab\";\n var g:string := BadSort(f);\n assert multiset(f)==multiset(g);\n assert sortedbad(g);\n /*\n f := \"dba\"; // testcase1\n g := BadSort(f);\n assert g==\"bad\"; \n f := \"aaaaaaaa\"; // testcase 2\n g := BadSort(f);\n assert g==\"aaaaaaaa\";\n */\n /*\n var a:string := \"dabdabdab\";\n var b:string := BadSort(a);\n assert multiset(a) == multiset(b);\n assert b == \"bbbaaaddd\";\n // apparently not possible ot verify this\n */\n}\n\n", "hints_removed": "// verifies\n// all bs are before all as which are before all ds\npredicate sortedbad(s:string) \n{\n // all b's are before all a's and d's\n forall i,j :: 0 <= i < |s| && 0 <= j < |s| && s[i] == 'b' && (s[j] == 'a' || s[j] == 'd') ==> i < j &&\n // all a's are after all b's\n forall i,j :: 0 <= i < |s| && 0 <= j < |s| && s[i] == 'a' && s[j] == 'b' ==> i > j &&\n // all a's are before all d's\n forall i,j :: 0 <= i < |s| && 0 <= j < |s| && s[i] == 'a' && s[j] == 'd' ==> i < j &&\n // all d's are after a;; b's and a's\n forall i,j :: 0 <= i < |s| && 0 <= j < |s| && s[i] == 'd' && (s[j] == 'a' || s[j] == 'b') ==> i > j\n}\n\nmethod BadSort(a: string) returns (b: string)\nrequires forall k :: 0 <= k < |a| ==> a[k] == 'b' || a[k] == 'a' || a[k] == 'd';\nensures sortedbad(b);\nensures multiset(a[..]) == multiset(b[..]);\nensures |a| == |b|;\n{\n b := a;\n var next := 0;\n var white := 0;\n var blue := |b|; // colours between next and blue unsorted\n while (next != blue) // if next==blue, no colours left to sort\n // ensure next, white, blue are correct\n // all b's are before all a's and d's\n // all a's are after all b's\n // all a's are before all d's\n // all d's are after a;; b's and a's\n { \n if b[next] == 'b' {\n var tmp := b[next];\n b := b[next := b[white]];\n b := b[white := tmp];\n next := next + 1;\n white := white + 1;\n } else if b[next] == 'a' {\n next := next + 1;\n } else if b[next] == 'd'{\n blue := blue - 1;\n var tmp := b[next];\n b := b[next := b[blue]];\n b := b[blue := tmp];\n } \n }\n}\nmethod check() {\n var f:string := \"dabdabdab\";\n var g:string := BadSort(f);\n /*\n f := \"dba\"; // testcase1\n g := BadSort(f);\n f := \"aaaaaaaa\"; // testcase 2\n g := BadSort(f);\n */\n /*\n var a:string := \"dabdabdab\";\n var b:string := BadSort(a);\n // apparently not possible ot verify this\n */\n}\n\n" }, { "test_ID": "352", "test_file": "SENG2011_tmp_tmpgk5jq85q_ass2_ex5.dfy", "ground_truth": "// verifies\nfunction expo(x:int, n:nat): int\nrequires n >= 0;\n{\n if (n == 0) then 1\n else x * expo(x, n - 1)\n}\n\nlemma {:induction false} Expon23(n: nat)\nrequires n >= 0;\nensures ((expo(2, 3 * n) - expo(3, n))) % 5 == 0;\n{\n if (n == 0) { \n assert (expo(2, 3 * 0) - expo(3, 0)) % 5 == 0;\n } else if (n == 1) {\n assert (expo(2, 3 * 1) - expo(3, 1)) % 5 == 0;\n } else {\n var i:nat := n;\n var j:nat := n;\n // assume true for n\n // prove for n - 1\n Expon23(n - 1);\n assert (expo(2, 3 * (i - 1)) - expo(3, i - 1)) % 5 == 0;\n assert (expo(2, (3 * i) - 3) - expo(3, (n - 1))) % 5 == 0;\n //assert expo(2, 2 + 3) == expo(2, 2) * expo(2, 3);\n assert expo(2, i - 0) == expo(2, i);\n assert expo(2, i - 1) == expo(2, i) / expo(2, 1);\n //assert expo(2, i - 2) == expo(2, i) / expo(2, 2);\n //assert expo(2, i - 3) == expo(2, i) / expo(2, 3); // training\n assert expo(2, (1 * i) - 0) == expo(2, (1 * i));\n assert expo(2, (2 * i) - 1) == expo(2, (2 * i)) / expo(2, 1);\n assert expo(2, (3 * 1) - 3) == expo(2, (3 * 1)) / expo(2, 3);\n assert expo(2, (3 * i) - 0) == expo(2, (3 * i));\n assert expo(2, (3 * i) - 1) == expo(2, (3 * i)) / expo(2, 1);\n assert expo(2, (3 * i) - 2) == expo(2, (3 * i)) / expo(2, 2);\n assert expo(2, (3 * i) - 3) == expo(2, (3 * i)) / expo(2, 3); \n assert expo(3, (i - 1)) == expo(3, i) / expo (3, 1);\n assert expo(2, (3 * i) - 3) - expo(3, (i - 1)) == expo(2, (3 * i)) / expo(2,3) - expo(3, i) / expo (3, 1);\n assert expo(2, 3) % 5 == expo(3, 1);\n assert (expo(2, (3 * i)) * 6) % 5 == expo(2, (3 * i)) % 5;\n assert (expo(2, (3 * i)) * expo(2, 3)) % 5 == (expo(2, (3 * i)) * expo(3, 1)) % 5;\n assert (expo(2, (3 * i)) * expo(2,3) - expo(3, i) * expo (3, 1)) % 5 == (expo(2, (3 * i)) * expo(3, 1) - expo(3, i) * expo (3, 1)) % 5;\n assert (expo(2, (3 * i)) * expo(3, 1) - expo(3, i) * expo (3, 1)) % 5 == (expo(3, 1) * (expo(2, (3 * i)) - expo(3, i))) % 5;\n assert (expo(2, (3 * i)) - expo(3, i)) % 5 == 0;\n }\n}\n\nmethod check() {\n assert expo(2, 3) == 8;\n assert expo(-2, 3) == -8;\n assert expo(3, 0) == 1;\n assert expo(0, 0) == 1;\n assert expo(10, 2) == 100;\n}\n", "hints_removed": "// verifies\nfunction expo(x:int, n:nat): int\nrequires n >= 0;\n{\n if (n == 0) then 1\n else x * expo(x, n - 1)\n}\n\nlemma {:induction false} Expon23(n: nat)\nrequires n >= 0;\nensures ((expo(2, 3 * n) - expo(3, n))) % 5 == 0;\n{\n if (n == 0) { \n } else if (n == 1) {\n } else {\n var i:nat := n;\n var j:nat := n;\n // assume true for n\n // prove for n - 1\n Expon23(n - 1);\n //assert expo(2, 2 + 3) == expo(2, 2) * expo(2, 3);\n //assert expo(2, i - 2) == expo(2, i) / expo(2, 2);\n //assert expo(2, i - 3) == expo(2, i) / expo(2, 3); // training\n }\n}\n\nmethod check() {\n}\n" }, { "test_ID": "353", "test_file": "SENG2011_tmp_tmpgk5jq85q_exam_ex2.dfy", "ground_truth": "method Getmini(a:array) returns(mini:nat) \nrequires a.Length > 0\nensures 0 <= mini < a.Length // mini is an index of a\nensures forall x :: 0 <= x < a.Length ==> a[mini] <= a[x] // a[mini] is the minimum value\nensures forall x :: 0 <= x < mini ==> a[mini] < a[x] // a[mini] is the first min\n{\n // find mini\n var min:int := a[0];\n var i:int := 0;\n while i < a.Length\n invariant 0 <= i <= a.Length\n invariant forall x :: 0 <= x < i ==> min <= a[x] // min is the smallest so far\n invariant min in a[..] // min is always in a\n {\n if a[i] < min {\n min := a[i];\n }\n i := i + 1;\n }\n\n //assert min in a[..]; // min is in a -> it will be found by this loop\n // find first occurance\n var k:int := 0;\n while k < a.Length \n invariant 0 <= k <= a.Length\n invariant forall x :: 0 <= x < k ==> min < a[x]\n {\n if a[k] == min {\n return k;\n }\n k := k + 1;\n }\n}\n\n/*\nmethod check() {\n var data := new int[][9,5,42,5,5]; // minimum 5 first at index 1\nvar mini := Getmini(data);\n//print mini;\nassert mini==1;\n\n}\n*/\n\n", "hints_removed": "method Getmini(a:array) returns(mini:nat) \nrequires a.Length > 0\nensures 0 <= mini < a.Length // mini is an index of a\nensures forall x :: 0 <= x < a.Length ==> a[mini] <= a[x] // a[mini] is the minimum value\nensures forall x :: 0 <= x < mini ==> a[mini] < a[x] // a[mini] is the first min\n{\n // find mini\n var min:int := a[0];\n var i:int := 0;\n while i < a.Length\n {\n if a[i] < min {\n min := a[i];\n }\n i := i + 1;\n }\n\n //assert min in a[..]; // min is in a -> it will be found by this loop\n // find first occurance\n var k:int := 0;\n while k < a.Length \n {\n if a[k] == min {\n return k;\n }\n k := k + 1;\n }\n}\n\n/*\nmethod check() {\n var data := new int[][9,5,42,5,5]; // minimum 5 first at index 1\nvar mini := Getmini(data);\n//print mini;\n\n}\n*/\n\n" }, { "test_ID": "354", "test_file": "SENG2011_tmp_tmpgk5jq85q_exam_ex3.dfy", "ground_truth": "method Symmetric(a: array) returns (flag: bool)\nensures flag == true ==> forall x :: 0 <= x < a.Length ==> a[x] == a[a.Length - x - 1]\nensures flag == false ==> exists x :: 0 <= x < a.Length && a[x] != a[a.Length - x - 1]\n{\n // empty == symmetrical\n if a.Length == 0 {\n return true;\n } \n\n var i:int := 0;\n while i < a.Length\n invariant 0 <= i <= a.Length // probably only need to check to halfway but this works as well\n invariant forall x :: 0 <= x < i ==> a[x] == a[a.Length - x - 1]\n {\n if a[i] != a[a.Length - i - 1] {\n return false;\n }\n i := i + 1;\n }\n return true;\n}\n/*\nmethod Main() {\n var data1 := new int[][1,2,3,2,1];\nvar f1 := Symmetric(data1);\nassert f1;\nvar data2 := new int[][1,2];\nvar f2 := Symmetric(data2);\nassert !f2;\n//print f2;\n}\n*/\n", "hints_removed": "method Symmetric(a: array) returns (flag: bool)\nensures flag == true ==> forall x :: 0 <= x < a.Length ==> a[x] == a[a.Length - x - 1]\nensures flag == false ==> exists x :: 0 <= x < a.Length && a[x] != a[a.Length - x - 1]\n{\n // empty == symmetrical\n if a.Length == 0 {\n return true;\n } \n\n var i:int := 0;\n while i < a.Length\n {\n if a[i] != a[a.Length - i - 1] {\n return false;\n }\n i := i + 1;\n }\n return true;\n}\n/*\nmethod Main() {\n var data1 := new int[][1,2,3,2,1];\nvar f1 := Symmetric(data1);\nvar data2 := new int[][1,2];\nvar f2 := Symmetric(data2);\n//print f2;\n}\n*/\n" }, { "test_ID": "355", "test_file": "SENG2011_tmp_tmpgk5jq85q_exam_ex4.dfy", "ground_truth": "lemma {:induction false} Divby2(n: nat)\nensures (n*(n-1))%2 == 0\n{\n if n == 0 {\n assert (1*(1-1))%2 == 0; // base case\n } else {\n Divby2(n - 1); // proved in case n - 1\n assert (n-1)*(n-2) == n*n -3*n + 2; // expanded case n - 1\n }\n}\n\n", "hints_removed": "lemma {:induction false} Divby2(n: nat)\nensures (n*(n-1))%2 == 0\n{\n if n == 0 {\n } else {\n Divby2(n - 1); // proved in case n - 1\n }\n}\n\n" }, { "test_ID": "356", "test_file": "SENG2011_tmp_tmpgk5jq85q_flex_ex1.dfy", "ground_truth": "// sums from index 0 -> i - 1\nfunction sumcheck(s: array, i: int): int\nrequires 0 <= i <= s.Length\nreads s\n{\n if i == 0 then 0\n else s[i - 1] + sumcheck(s, i - 1)\n}\n\n// returns sum of array\nmethod sum(s: array) returns (a:int)\nrequires s.Length > 0\nensures sumcheck(s, s.Length) == a\n{\n a := 0;\n var i:int := 0;\n while i < s.Length\n invariant 0 <= i <= s.Length && a == sumcheck(s, i)\n {\n a := a + s[i];\n i := i + 1;\n }\n}\n\nmethod Main() {\n var a: array := new int[4];\n a[0] := 1;\n a[1] := 3;\n a[2] := 3;\n a[3] := 2;\n assert a[..] == [1,3,3,2];\n\n var s:= sum(a);\n assert a[0] == 1 && a[1] == 3 && a[2] == 3 && a[3] == 2;\n assert s == sumcheck(a, a.Length);\n print \"\\nThe sum of all elements in [1,3,3,2] is \";\n print s;\n}\n\n\n", "hints_removed": "// sums from index 0 -> i - 1\nfunction sumcheck(s: array, i: int): int\nrequires 0 <= i <= s.Length\nreads s\n{\n if i == 0 then 0\n else s[i - 1] + sumcheck(s, i - 1)\n}\n\n// returns sum of array\nmethod sum(s: array) returns (a:int)\nrequires s.Length > 0\nensures sumcheck(s, s.Length) == a\n{\n a := 0;\n var i:int := 0;\n while i < s.Length\n {\n a := a + s[i];\n i := i + 1;\n }\n}\n\nmethod Main() {\n var a: array := new int[4];\n a[0] := 1;\n a[1] := 3;\n a[2] := 3;\n a[3] := 2;\n\n var s:= sum(a);\n print \"\\nThe sum of all elements in [1,3,3,2] is \";\n print s;\n}\n\n\n" }, { "test_ID": "357", "test_file": "SENG2011_tmp_tmpgk5jq85q_flex_ex2.dfy", "ground_truth": "function maxcheck(s: array, i: int, max: int): int\nrequires 0 <= i <= s.Length\nreads s\n{\n if i == 0 then max\n else if s[i - 1] > max then maxcheck(s, i - 1, s[i - 1])\n else maxcheck(s, i - 1, max)\n}\n\nmethod max(s: array) returns (a:int)\nrequires s.Length > 0\nensures forall x :: 0 <= x < s.Length ==> a >= s[x]\nensures a in s[..]\n{\n a := s[0];\n var i:int := 0;\n while i < s.Length\n invariant 0 <= i <= s.Length\n invariant forall x :: 0 <= x < i ==> a >= s[x]\n invariant a in s[..]\n {\n if (s[i] > a) {\n a := s[i];\n }\n i := i + 1;\n }\n}\n\nmethod Checker() { \n var a := new nat[][1,2,3,50,5,51]; \n // ghost var a := [1,2,3]; \n var n := max(a); \n // assert a[..] == [1,2,3]; \n assert n == 51; \n // assert MAXIMUM(1,2) == 2; \n // assert ret_max(a,a.Length-1) == 12; \n // assert ret_max(a,a.Length-1) == x+3; \n }\n", "hints_removed": "function maxcheck(s: array, i: int, max: int): int\nrequires 0 <= i <= s.Length\nreads s\n{\n if i == 0 then max\n else if s[i - 1] > max then maxcheck(s, i - 1, s[i - 1])\n else maxcheck(s, i - 1, max)\n}\n\nmethod max(s: array) returns (a:int)\nrequires s.Length > 0\nensures forall x :: 0 <= x < s.Length ==> a >= s[x]\nensures a in s[..]\n{\n a := s[0];\n var i:int := 0;\n while i < s.Length\n {\n if (s[i] > a) {\n a := s[i];\n }\n i := i + 1;\n }\n}\n\nmethod Checker() { \n var a := new nat[][1,2,3,50,5,51]; \n // ghost var a := [1,2,3]; \n var n := max(a); \n // assert a[..] == [1,2,3]; \n // assert MAXIMUM(1,2) == 2; \n // assert ret_max(a,a.Length-1) == 12; \n // assert ret_max(a,a.Length-1) == x+3; \n }\n" }, { "test_ID": "358", "test_file": "SENG2011_tmp_tmpgk5jq85q_flex_ex5.dfy", "ground_truth": "method firste(a: array) returns (c:int)\nensures -1 <= c < a.Length\nensures 0 <= c < a.Length ==> a[c] == 'e' && forall x :: 0 <= x < c ==> a[x] != 'e'\nensures c == -1 ==> forall x :: 0 <= x < a.Length ==> a[x] != 'e'\n{\n var i:int := 0;\n while i < a.Length\n invariant 0 <= i <= a.Length\n invariant forall x :: 0 <= x < i ==> a[x] != 'e'\n {\n if a[i] == 'e' {\n return i;\n }\n i := i + 1;\n }\n return -1;\n}\n\nmethod Main(){\n var a := new char[6]['c','h','e','e','s','e'];\n\n var p := firste(a);\n print p;\n //assert p == 2;\n\n}\n", "hints_removed": "method firste(a: array) returns (c:int)\nensures -1 <= c < a.Length\nensures 0 <= c < a.Length ==> a[c] == 'e' && forall x :: 0 <= x < c ==> a[x] != 'e'\nensures c == -1 ==> forall x :: 0 <= x < a.Length ==> a[x] != 'e'\n{\n var i:int := 0;\n while i < a.Length\n {\n if a[i] == 'e' {\n return i;\n }\n i := i + 1;\n }\n return -1;\n}\n\nmethod Main(){\n var a := new char[6]['c','h','e','e','s','e'];\n\n var p := firste(a);\n print p;\n //assert p == 2;\n\n}\n" }, { "test_ID": "359", "test_file": "SENG2011_tmp_tmpgk5jq85q_p1.dfy", "ground_truth": "method Reverse(a: array) returns (b: array)\nrequires a.Length > 0\nensures a.Length == b.Length\nensures forall x :: 0 <= x < a.Length ==> b[x] == a[a.Length - x - 1]\n{\n // copy array a to new array b\n b := new char[a.Length];\n var k := 0;\n while (k < a.Length) \n invariant 0 <= k <= a.Length;\n invariant forall x :: 0 <= x < k ==> b[x] == a[a.Length - x - 1]\n decreases a.Length - k\n {\n b[k] := a[a.Length - 1 - k];\n k := k + 1;\n }\n /*\n var i:int := 0;\n while i < a.Length\n invariant a.Length == b.Length\n invariant 0 <= i <= a.Length\n invariant 0 <= i <= b.Length\n //invariant multiset(a[..]) == multiset(b[..])\n invariant forall x :: 0 <= x < i ==> b[x] == a[a.Length - x - 1]\n decreases a.Length - i\n {\n b[i] := a[a.Length - 1 - i];\n i := i + 1;\n }\n */\n}\n\nmethod Main()\n{\n var a := new char[8];\n a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7] := 'd', 'e', 's', 'r', 'e', 'v', 'e', 'r';\n var b := Reverse(a);\n assert b[..] == [ 'r', 'e', 'v', 'e', 'r', 's', 'e', 'd' ];\n print b[..];\n\n a := new char[1];\n a[0] := '!';\n b := Reverse(a);\n assert b[..] == [ '!' ];\n print b[..], '\\n';\n}\n", "hints_removed": "method Reverse(a: array) returns (b: array)\nrequires a.Length > 0\nensures a.Length == b.Length\nensures forall x :: 0 <= x < a.Length ==> b[x] == a[a.Length - x - 1]\n{\n // copy array a to new array b\n b := new char[a.Length];\n var k := 0;\n while (k < a.Length) \n {\n b[k] := a[a.Length - 1 - k];\n k := k + 1;\n }\n /*\n var i:int := 0;\n while i < a.Length\n //invariant multiset(a[..]) == multiset(b[..])\n {\n b[i] := a[a.Length - 1 - i];\n i := i + 1;\n }\n */\n}\n\nmethod Main()\n{\n var a := new char[8];\n a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7] := 'd', 'e', 's', 'r', 'e', 'v', 'e', 'r';\n var b := Reverse(a);\n print b[..];\n\n a := new char[1];\n a[0] := '!';\n b := Reverse(a);\n print b[..], '\\n';\n}\n" }, { "test_ID": "360", "test_file": "SENG2011_tmp_tmpgk5jq85q_p2.dfy", "ground_truth": "method AbsIt(s: array) modifies s;\n//requires \nensures forall x :: 0 <= x < s.Length ==> old(s[x]) < 0 ==> s[x] == -old(s[x])\nensures forall x :: 0 <= x < s.Length ==> old(s[x]) >= 0 ==> s[x] == old(s[x])\n\n{\n var i:int := 0;\n while i < s.Length\n invariant 0 <= i <= s.Length\n //invariant forall x :: 0 <= x < i ==> s[x] >= 0\n //invariant forall x :: 0 <= x < i ==> old(s[x]) < 0 ==> s[x] == -old(s[x])\n //invariant forall x :: 0 <= x < i ==> old(s[x]) >= 0 ==> s[x] == old(s[x])\n\n invariant forall k :: 0 <= k < i ==> old(s[k]) < 0 ==> s[k] == -old(s[k])// negatives are abs'ed \n invariant forall k :: 0 <= k < i ==> old(s[k]) >= 0 ==> s[k] == old(s[k]) // positives left alone \n invariant forall k:: i <= k < s.Length ==> old(s[k]) == s[k] // not yet touched \n {\n if (s[i] < 0) {\n s[i] := -s[i];\n }\n i := i + 1;\n }\n}\n\n\n", "hints_removed": "method AbsIt(s: array) modifies s;\n//requires \nensures forall x :: 0 <= x < s.Length ==> old(s[x]) < 0 ==> s[x] == -old(s[x])\nensures forall x :: 0 <= x < s.Length ==> old(s[x]) >= 0 ==> s[x] == old(s[x])\n\n{\n var i:int := 0;\n while i < s.Length\n //invariant forall x :: 0 <= x < i ==> s[x] >= 0\n //invariant forall x :: 0 <= x < i ==> old(s[x]) < 0 ==> s[x] == -old(s[x])\n //invariant forall x :: 0 <= x < i ==> old(s[x]) >= 0 ==> s[x] == old(s[x])\n\n {\n if (s[i] < 0) {\n s[i] := -s[i];\n }\n i := i + 1;\n }\n}\n\n\n" }, { "test_ID": "361", "test_file": "SiLemma_tmp_tmpfxtryv2w_utils.dfy", "ground_truth": "module Utils {\n\n lemma AllBelowBoundSize(bound: nat)\n ensures\n var below := set n : nat | n < bound :: n;\n |below| == bound\n decreases bound\n {\n if bound == 0 {\n } else {\n AllBelowBoundSize(bound-1);\n var belowminus := set n : nat | n < bound-1 :: n;\n var below := set n : nat | n < bound :: n;\n assert below == belowminus + {bound-1};\n }\n }\n\n lemma SizeOfContainedSet(a: set, b: set)\n requires forall n: nat :: n in a ==> n in b\n ensures |a| <= |b|\n decreases |a|\n {\n if |a| == 0 {\n } else {\n var y :| y in a;\n var new_a := a - {y};\n var new_b := b - {y};\n SizeOfContainedSet(new_a, new_b);\n }\n }\n\n lemma BoundedSetSize(bound: nat, values: set)\n requires forall n :: n in values ==> n < bound\n ensures |values| <= bound\n {\n var all_below_bound := set n : nat | n < bound :: n;\n AllBelowBoundSize(bound);\n assert |all_below_bound| == bound;\n assert forall n :: n in values ==> n in all_below_bound;\n SizeOfContainedSet(values, all_below_bound);\n }\n\n lemma MappedSetSize(s: set, f: T->U, t: set)\n requires forall n: T, m: T :: m != n ==> f(n) != f(m)\n requires t == set n | n in s :: f(n)\n ensures |s| == |t|\n decreases |s|\n {\n var t := set n | n in s :: f(n);\n if |s| == 0 {\n } else {\n var y :| y in s;\n var new_s := s - {y};\n var new_t := t - {f(y)};\n assert new_t == set n | n in new_s :: f(n);\n MappedSetSize(new_s, f, new_t);\n }\n }\n\n lemma SetSizes(a: set, b: set, c: set)\n requires c == a + b\n requires forall t: T :: t in a ==> t !in b\n requires forall t: T :: t in b ==> t !in a\n ensures |c| == |a| + |b|\n {\n }\n\n}\n", "hints_removed": "module Utils {\n\n lemma AllBelowBoundSize(bound: nat)\n ensures\n var below := set n : nat | n < bound :: n;\n |below| == bound\n {\n if bound == 0 {\n } else {\n AllBelowBoundSize(bound-1);\n var belowminus := set n : nat | n < bound-1 :: n;\n var below := set n : nat | n < bound :: n;\n }\n }\n\n lemma SizeOfContainedSet(a: set, b: set)\n requires forall n: nat :: n in a ==> n in b\n ensures |a| <= |b|\n {\n if |a| == 0 {\n } else {\n var y :| y in a;\n var new_a := a - {y};\n var new_b := b - {y};\n SizeOfContainedSet(new_a, new_b);\n }\n }\n\n lemma BoundedSetSize(bound: nat, values: set)\n requires forall n :: n in values ==> n < bound\n ensures |values| <= bound\n {\n var all_below_bound := set n : nat | n < bound :: n;\n AllBelowBoundSize(bound);\n SizeOfContainedSet(values, all_below_bound);\n }\n\n lemma MappedSetSize(s: set, f: T->U, t: set)\n requires forall n: T, m: T :: m != n ==> f(n) != f(m)\n requires t == set n | n in s :: f(n)\n ensures |s| == |t|\n {\n var t := set n | n in s :: f(n);\n if |s| == 0 {\n } else {\n var y :| y in s;\n var new_s := s - {y};\n var new_t := t - {f(y)};\n MappedSetSize(new_s, f, new_t);\n }\n }\n\n lemma SetSizes(a: set, b: set, c: set)\n requires c == a + b\n requires forall t: T :: t in a ==> t !in b\n requires forall t: T :: t in b ==> t !in a\n ensures |c| == |a| + |b|\n {\n }\n\n}\n" }, { "test_ID": "362", "test_file": "Simulink-To_dafny_tmp_tmpbcuesj2t_Tank.dfy", "ground_truth": "datatype Valve = ON | OFF\n\nclass Pipe{\n var v1: Valve; //outlet valve \n var v2: Valve; //inlet Valve\n var v3: Valve; //outlet valve\n var in_flowv1: int; //flow in valve v1\n var in_flowv2: int; //flow in vave v2\n var in_flowv3: int; //flow in valve v3\n\n constructor()\n {\n this.v1:= OFF;\n this.v2:= ON;\n }\n \n}\nclass Tank\n{\n var pipe: Pipe;\n var height: int;\n constructor()\n {\n pipe := new Pipe();\n }\n} \n\nmethod checkRegulation(tank: Tank)\n //requires tank.pipe.v1==OFF && tank.pipe.v2==ON && (tank.pipe.v3==OFF || tank.pipe.v2==ON) \nensures (tank.height>10 && tank.pipe.v1==OFF && tank.pipe.v3==ON && tank.pipe.v2==old(tank.pipe.v2)) \n|| (tank.height <8 && tank.pipe.v1== OFF && tank.pipe.v2== ON && tank.pipe.v3==old(tank.pipe.v3))\n|| ((tank.pipe.in_flowv3 >5 || tank.pipe.in_flowv1 >5 ) && tank.pipe.v2==OFF && tank.pipe.v3==old(tank.pipe.v3) && tank.pipe.v1==old(tank.pipe.v1))\nmodifies tank.pipe;\n {\n if(tank.height >10)\n {\n tank.pipe.v1:= OFF;\n tank.pipe.v3:= ON;\n assert((tank.height>10 && tank.pipe.v1==OFF && tank.pipe.v3==ON && tank.pipe.v2==old(tank.pipe.v2)));\n }\n else if(tank.height <8)\n {\n \n tank.pipe.v1:= OFF;\n tank.pipe.v2:= ON;\n assert((tank.height <8 && tank.pipe.v1== OFF && tank.pipe.v2== ON && tank.pipe.v3==old(tank.pipe.v3)));\n }\n \n assume(((tank.pipe.in_flowv3 >5 || tank.pipe.in_flowv1 >5 ) && tank.pipe.v2==OFF && tank.pipe.v3==old(tank.pipe.v3) && tank.pipe.v1==old(tank.pipe.v1)));\n /*else if(tank.pipe.in_flowv3 >5 || tank.pipe.in_flowv1> 5)\n {\n\n tank.pipe.v2:= OFF;\n assume(((tank.pipe.in_flowv3 >5 || tank.pipe.in_flowv1 >5 ) && tank.pipe.v2==OFF && tank.pipe.v3==old(tank.pipe.v3) && tank.pipe.v1==old(tank.pipe.v1)));\n } */\n \n } \n", "hints_removed": "datatype Valve = ON | OFF\n\nclass Pipe{\n var v1: Valve; //outlet valve \n var v2: Valve; //inlet Valve\n var v3: Valve; //outlet valve\n var in_flowv1: int; //flow in valve v1\n var in_flowv2: int; //flow in vave v2\n var in_flowv3: int; //flow in valve v3\n\n constructor()\n {\n this.v1:= OFF;\n this.v2:= ON;\n }\n \n}\nclass Tank\n{\n var pipe: Pipe;\n var height: int;\n constructor()\n {\n pipe := new Pipe();\n }\n} \n\nmethod checkRegulation(tank: Tank)\n //requires tank.pipe.v1==OFF && tank.pipe.v2==ON && (tank.pipe.v3==OFF || tank.pipe.v2==ON) \nensures (tank.height>10 && tank.pipe.v1==OFF && tank.pipe.v3==ON && tank.pipe.v2==old(tank.pipe.v2)) \n|| (tank.height <8 && tank.pipe.v1== OFF && tank.pipe.v2== ON && tank.pipe.v3==old(tank.pipe.v3))\n|| ((tank.pipe.in_flowv3 >5 || tank.pipe.in_flowv1 >5 ) && tank.pipe.v2==OFF && tank.pipe.v3==old(tank.pipe.v3) && tank.pipe.v1==old(tank.pipe.v1))\nmodifies tank.pipe;\n {\n if(tank.height >10)\n {\n tank.pipe.v1:= OFF;\n tank.pipe.v3:= ON;\n }\n else if(tank.height <8)\n {\n \n tank.pipe.v1:= OFF;\n tank.pipe.v2:= ON;\n }\n \n assume(((tank.pipe.in_flowv3 >5 || tank.pipe.in_flowv1 >5 ) && tank.pipe.v2==OFF && tank.pipe.v3==old(tank.pipe.v3) && tank.pipe.v1==old(tank.pipe.v1)));\n /*else if(tank.pipe.in_flowv3 >5 || tank.pipe.in_flowv1> 5)\n {\n\n tank.pipe.v2:= OFF;\n assume(((tank.pipe.in_flowv3 >5 || tank.pipe.in_flowv1 >5 ) && tank.pipe.v2==OFF && tank.pipe.v3==old(tank.pipe.v3) && tank.pipe.v1==old(tank.pipe.v1)));\n } */\n \n } \n" }, { "test_ID": "363", "test_file": "Software-Verification_tmp_tmpv4ueky2d_Best Time to Buy and Sell Stock_best_time_to_buy_and_sell_stock.dfy", "ground_truth": "method best_time_to_buy_and_sell_stock(prices: array) returns (max_profit: int)\n requires 1 <= prices.Length <= 100000\n requires forall i :: 0 <= i < prices.Length ==> 0 <= prices[i] <= 10000\n ensures forall i, j :: 0 <= i < j < prices.Length ==> max_profit >= prices[j] - prices[i]\n{\n var min_price := 10001;\n max_profit := 0;\n \n var i := 0;\n while (i < prices.Length)\n invariant 0 <= i <= prices.Length\n invariant forall j :: 0 <= j < i ==> min_price <= prices[j]\n invariant forall j, k :: 0 <= j < k < i ==> max_profit >= prices[k] - prices[j]\n {\n var price := prices[i];\n if (price < min_price)\n {\n min_price := price;\n }\n if (price - min_price > max_profit) {\n max_profit := price - min_price;\n }\n\n i := i + 1;\n }\n}\n\n", "hints_removed": "method best_time_to_buy_and_sell_stock(prices: array) returns (max_profit: int)\n requires 1 <= prices.Length <= 100000\n requires forall i :: 0 <= i < prices.Length ==> 0 <= prices[i] <= 10000\n ensures forall i, j :: 0 <= i < j < prices.Length ==> max_profit >= prices[j] - prices[i]\n{\n var min_price := 10001;\n max_profit := 0;\n \n var i := 0;\n while (i < prices.Length)\n {\n var price := prices[i];\n if (price < min_price)\n {\n min_price := price;\n }\n if (price - min_price > max_profit) {\n max_profit := price - min_price;\n }\n\n i := i + 1;\n }\n}\n\n" }, { "test_ID": "364", "test_file": "Software-Verification_tmp_tmpv4ueky2d_Contains Duplicate_contains_duplicate.dfy", "ground_truth": "method contains_duplicate(nums: seq) returns (result: bool)\n requires 1 <= |nums| <= 100000\n requires forall i :: 0 <= i < |nums| ==> -1000000000 <= nums[i] <= 1000000000\n ensures result <==> distinct(nums)\n{ \n var i := 0;\n var s: set := {};\n while (i < |nums|)\n invariant i <= |nums|\n invariant forall j :: j in nums[..i] <==> j in s\n invariant distinct(nums[..i])\n {\n var num := nums[i];\n if (num in s)\n {\n return false;\n }\n\n s := s + {num};\n i := i + 1;\n }\n\n return true;\n}\n\npredicate distinct(nums: seq) {\n forall i, j :: 0 <= i < j < |nums| ==> nums[i] != nums[j]\n}\n\n", "hints_removed": "method contains_duplicate(nums: seq) returns (result: bool)\n requires 1 <= |nums| <= 100000\n requires forall i :: 0 <= i < |nums| ==> -1000000000 <= nums[i] <= 1000000000\n ensures result <==> distinct(nums)\n{ \n var i := 0;\n var s: set := {};\n while (i < |nums|)\n {\n var num := nums[i];\n if (num in s)\n {\n return false;\n }\n\n s := s + {num};\n i := i + 1;\n }\n\n return true;\n}\n\npredicate distinct(nums: seq) {\n forall i, j :: 0 <= i < j < |nums| ==> nums[i] != nums[j]\n}\n\n" }, { "test_ID": "365", "test_file": "Software-Verification_tmp_tmpv4ueky2d_Counting Bits_counting_bits.dfy", "ground_truth": "method counting_bits(n: int) returns (result: array)\n requires 0 <= n <= 100000\n ensures result.Length == n + 1\n ensures forall i :: 1 <= i < n + 1 ==> result[i] == result[i / 2] + i % 2\n{\n result := new int[n + 1](i => 0);\n\n var i := 1;\n while (i < n + 1)\n invariant 1 <= i <= n + 1\n invariant forall j :: 1 <= j < i ==> result[j] == result[j / 2] + j % 2\n {\n result[i] := result[i / 2] + i % 2;\n\n i := i + 1;\n }\n}\n\n", "hints_removed": "method counting_bits(n: int) returns (result: array)\n requires 0 <= n <= 100000\n ensures result.Length == n + 1\n ensures forall i :: 1 <= i < n + 1 ==> result[i] == result[i / 2] + i % 2\n{\n result := new int[n + 1](i => 0);\n\n var i := 1;\n while (i < n + 1)\n {\n result[i] := result[i / 2] + i % 2;\n\n i := i + 1;\n }\n}\n\n" }, { "test_ID": "366", "test_file": "Software-Verification_tmp_tmpv4ueky2d_Longest Increasing Subsequence_longest_increasing_subsequence.dfy", "ground_truth": "method longest_increasing_subsequence(nums: array) returns (max: int)\n requires 1 <= nums.Length <= 2500\n requires forall i :: 0 <= i < nums.Length ==> -10000 <= nums[i] <= 10000\n // TODO: modify the ensures clause so that max is indeed equal to the longest increasing subsequence\n ensures max >= 1\n{\n var length := nums.Length;\n if (length == 1)\n {\n return 1;\n }\n\n max := 1;\n var dp := new int[length](_ => 1);\n\n var i := 1;\n while (i < length)\n modifies dp\n invariant 1 <= i <= length\n invariant max >= 1\n {\n var j := 0;\n while (j < i)\n invariant 0 <= j <= i\n {\n if (nums[j] < nums[i])\n {\n dp[i] := find_max(dp[i], dp[j] + 1);\n }\n\n j := j + 1;\n }\n\n max := find_max(max, dp[i]);\n i := i + 1;\n }\n}\n\n\n// Function\nfunction find_max(x: int, y: int): int\n{\n if x > y then x\n else y\n}\n\n", "hints_removed": "method longest_increasing_subsequence(nums: array) returns (max: int)\n requires 1 <= nums.Length <= 2500\n requires forall i :: 0 <= i < nums.Length ==> -10000 <= nums[i] <= 10000\n // TODO: modify the ensures clause so that max is indeed equal to the longest increasing subsequence\n ensures max >= 1\n{\n var length := nums.Length;\n if (length == 1)\n {\n return 1;\n }\n\n max := 1;\n var dp := new int[length](_ => 1);\n\n var i := 1;\n while (i < length)\n modifies dp\n {\n var j := 0;\n while (j < i)\n {\n if (nums[j] < nums[i])\n {\n dp[i] := find_max(dp[i], dp[j] + 1);\n }\n\n j := j + 1;\n }\n\n max := find_max(max, dp[i]);\n i := i + 1;\n }\n}\n\n\n// Function\nfunction find_max(x: int, y: int): int\n{\n if x > y then x\n else y\n}\n\n" }, { "test_ID": "367", "test_file": "Software-Verification_tmp_tmpv4ueky2d_Non-overlapping Intervals_non_overlapping_intervals.dfy", "ground_truth": "method non_overlapping_intervals(intervals: array2) returns (count: int)\n modifies intervals\n requires 1 <= intervals.Length0 <= 100000\n requires intervals.Length1 == 2\n requires forall i :: 0 <= i < intervals.Length0 ==> -50000 <= intervals[i, 0] <= 50000\n requires forall i :: 0 <= i < intervals.Length0 ==> -50000 <= intervals[i, 1] <= 50000\n // TODO: modify the ensures clause so that count is indeed equal to the minimum number of intervals we need to remove to make the rest of the intervals non-overlapping.\n ensures count >= 0\n{\n var row := intervals.Length0;\n if (row == 0)\n {\n return 0;\n }\n\n bubble_sort(intervals);\n \n var i := 1;\n count := 1;\n var end := intervals[0, 1];\n while (i < row)\n invariant 1 <= i <= row\n invariant 1 <= count <= i\n invariant intervals[0, 1] <= end <= intervals[i - 1, 1]\n {\n if (intervals[i, 0] >= end)\n {\n count := count + 1;\n end := intervals[i, 1];\n }\n\n i := i + 1;\n }\n\n return row - count;\n}\n\n\n// Bubble Sort\nmethod bubble_sort(a: array2)\n modifies a\n requires a.Length1 == 2\n ensures sorted(a, 0, a.Length0 - 1)\n{\n var i := a.Length0 - 1;\n while (i > 0)\n invariant i < 0 ==> a.Length0 == 0\n invariant sorted(a, i, a.Length0 - 1)\n invariant partitioned(a, i)\n {\n var j := 0;\n while (j < i)\n invariant 0 < i < a.Length0 && 0 <= j <= i\n invariant sorted(a, i, a.Length0 - 1)\n invariant partitioned(a, i)\n invariant forall k :: 0 <= k <= j ==> a[k, 1] <= a[j, 1]\n {\n if (a[j, 1] > a[j + 1, 1])\n {\n a[j, 1], a[j + 1, 1] := a[j + 1, 1], a[j, 1];\n }\n j := j + 1;\n }\n i := i -1;\n }\n}\n\n\n// Predicates for Bubble Sort\npredicate sorted(a: array2, l: int, u: int)\n reads a\n requires a.Length1 == 2\n{\n forall i, j :: 0 <= l <= i <= j <= u < a.Length0 ==> a[i, 1] <= a[j, 1]\n}\n\npredicate partitioned(a: array2, i: int)\n reads a\n requires a.Length1 == 2\n{\n forall k, k' :: 0 <= k <= i < k' < a.Length0 ==> a[k, 1] <= a[k', 1]\n}\n\n", "hints_removed": "method non_overlapping_intervals(intervals: array2) returns (count: int)\n modifies intervals\n requires 1 <= intervals.Length0 <= 100000\n requires intervals.Length1 == 2\n requires forall i :: 0 <= i < intervals.Length0 ==> -50000 <= intervals[i, 0] <= 50000\n requires forall i :: 0 <= i < intervals.Length0 ==> -50000 <= intervals[i, 1] <= 50000\n // TODO: modify the ensures clause so that count is indeed equal to the minimum number of intervals we need to remove to make the rest of the intervals non-overlapping.\n ensures count >= 0\n{\n var row := intervals.Length0;\n if (row == 0)\n {\n return 0;\n }\n\n bubble_sort(intervals);\n \n var i := 1;\n count := 1;\n var end := intervals[0, 1];\n while (i < row)\n {\n if (intervals[i, 0] >= end)\n {\n count := count + 1;\n end := intervals[i, 1];\n }\n\n i := i + 1;\n }\n\n return row - count;\n}\n\n\n// Bubble Sort\nmethod bubble_sort(a: array2)\n modifies a\n requires a.Length1 == 2\n ensures sorted(a, 0, a.Length0 - 1)\n{\n var i := a.Length0 - 1;\n while (i > 0)\n {\n var j := 0;\n while (j < i)\n {\n if (a[j, 1] > a[j + 1, 1])\n {\n a[j, 1], a[j + 1, 1] := a[j + 1, 1], a[j, 1];\n }\n j := j + 1;\n }\n i := i -1;\n }\n}\n\n\n// Predicates for Bubble Sort\npredicate sorted(a: array2, l: int, u: int)\n reads a\n requires a.Length1 == 2\n{\n forall i, j :: 0 <= l <= i <= j <= u < a.Length0 ==> a[i, 1] <= a[j, 1]\n}\n\npredicate partitioned(a: array2, i: int)\n reads a\n requires a.Length1 == 2\n{\n forall k, k' :: 0 <= k <= i < k' < a.Length0 ==> a[k, 1] <= a[k', 1]\n}\n\n" }, { "test_ID": "368", "test_file": "Software-Verification_tmp_tmpv4ueky2d_Remove Duplicates from Sorted Array_remove_duplicates_from_sorted_array.dfy", "ground_truth": "method remove_duplicates_from_sorted_array(nums: seq) returns (result: seq) \n requires is_sorted(nums)\n requires 1 <= |nums| <= 30000\n requires forall i :: 0 <= i < |nums| ==> -100 <= nums[i] <= 100\n ensures is_sorted_and_distinct(result)\n ensures forall i :: i in nums <==> i in result\n{\n var previous := nums[0];\n result := [nums[0]];\n\n var i := 1;\n while (i < |nums|)\n invariant 0 <= i <= |nums|\n invariant |result| >= 1;\n invariant previous in nums[0..i]; \n invariant previous == result[|result| - 1];\n invariant is_sorted_and_distinct(result)\n invariant forall j :: j in nums[0..i] <==> j in result\n {\n if (previous != nums[i])\n { \n result := result + [nums[i]];\n previous := nums[i];\n }\n\n i := i + 1;\n }\n}\n\n\n// Helper predicate\npredicate is_sorted(nums: seq)\n{\n forall i, j :: 0 <= i < j < |nums| ==> nums[i] <= nums[j]\n}\n\npredicate is_sorted_and_distinct(nums: seq)\n{\n forall i, j :: 0 <= i < j < |nums| ==> nums[i] < nums[j]\n}\n\n", "hints_removed": "method remove_duplicates_from_sorted_array(nums: seq) returns (result: seq) \n requires is_sorted(nums)\n requires 1 <= |nums| <= 30000\n requires forall i :: 0 <= i < |nums| ==> -100 <= nums[i] <= 100\n ensures is_sorted_and_distinct(result)\n ensures forall i :: i in nums <==> i in result\n{\n var previous := nums[0];\n result := [nums[0]];\n\n var i := 1;\n while (i < |nums|)\n {\n if (previous != nums[i])\n { \n result := result + [nums[i]];\n previous := nums[i];\n }\n\n i := i + 1;\n }\n}\n\n\n// Helper predicate\npredicate is_sorted(nums: seq)\n{\n forall i, j :: 0 <= i < j < |nums| ==> nums[i] <= nums[j]\n}\n\npredicate is_sorted_and_distinct(nums: seq)\n{\n forall i, j :: 0 <= i < j < |nums| ==> nums[i] < nums[j]\n}\n\n" }, { "test_ID": "369", "test_file": "Software-Verification_tmp_tmpv4ueky2d_Remove Element_remove_element.dfy", "ground_truth": "method remove_element(nums: array, val: int) returns (i: int)\n modifies nums\n requires 0 <= nums.Length <= 100\n requires forall i :: 0 <= i < nums.Length ==> 0 <= nums[i] <= 50\n requires 0 <= val <= 100\n ensures forall j :: 0 < j < i < nums.Length ==> nums[j] != val\n{\n i := 0;\n var end := nums.Length - 1;\n\n while i <= end \n invariant 0 <= i <= nums.Length\n invariant end < nums.Length\n invariant forall k :: 0 <= k < i ==> nums[k] != val\n {\n if (nums[i] == val)\n {\n if (nums[end] == val)\n {\n end := end - 1;\n }\n else {\n nums[i] := nums[end];\n i := i + 1;\n end := end - 1;\n }\n }\n else {\n i := i + 1;\n }\n }\n}\n\n", "hints_removed": "method remove_element(nums: array, val: int) returns (i: int)\n modifies nums\n requires 0 <= nums.Length <= 100\n requires forall i :: 0 <= i < nums.Length ==> 0 <= nums[i] <= 50\n requires 0 <= val <= 100\n ensures forall j :: 0 < j < i < nums.Length ==> nums[j] != val\n{\n i := 0;\n var end := nums.Length - 1;\n\n while i <= end \n {\n if (nums[i] == val)\n {\n if (nums[end] == val)\n {\n end := end - 1;\n }\n else {\n nums[i] := nums[end];\n i := i + 1;\n end := end - 1;\n }\n }\n else {\n i := i + 1;\n }\n }\n}\n\n" }, { "test_ID": "370", "test_file": "Software-Verification_tmp_tmpv4ueky2d_Valid Anagram_valid_anagram.dfy", "ground_truth": "method is_anagram(s: string, t: string) returns (result: bool)\n requires |s| == |t|\n ensures (multiset(s) == multiset(t)) == result\n{\n result := is_equal(multiset(s), multiset(t));\n}\n\n\nmethod is_equal(s: multiset, t: multiset) returns (result: bool)\n ensures (s == t) <==> result\n{\n var s_removed := multiset{};\n var s_remaining := s;\n while (|s_remaining| > 0)\n invariant s_remaining == s - s_removed\n invariant forall removed :: removed in s_removed ==> (removed in s &&\n removed in t &&\n s[removed] == t[removed])\n {\n var remaining :| remaining in s_remaining;\n if !(remaining in s &&\n remaining in t &&\n s[remaining] == t[remaining]) {\n return false; \n }\n\n var temp := multiset{};\n s_removed := s_removed + temp[remaining := s[remaining]];\n s_remaining := s_remaining - temp[remaining := s[remaining]];\n }\n\n\n var t_removed := multiset{};\n var t_remaining := t;\n while (|t_remaining| > 0)\n invariant t_remaining == t - t_removed\n invariant forall removed :: removed in t_removed ==> (removed in s &&\n removed in t &&\n s[removed] == t[removed])\n {\n var remaining :| remaining in t_remaining;\n if !(remaining in s &&\n remaining in t &&\n s[remaining] == t[remaining]) {\n return false; \n }\n \n var temp := multiset{};\n t_removed := t_removed + temp[remaining := t[remaining]];\n t_remaining := t_remaining - temp[remaining := t[remaining]];\n }\n\n return true;\n}\n\n", "hints_removed": "method is_anagram(s: string, t: string) returns (result: bool)\n requires |s| == |t|\n ensures (multiset(s) == multiset(t)) == result\n{\n result := is_equal(multiset(s), multiset(t));\n}\n\n\nmethod is_equal(s: multiset, t: multiset) returns (result: bool)\n ensures (s == t) <==> result\n{\n var s_removed := multiset{};\n var s_remaining := s;\n while (|s_remaining| > 0)\n removed in t &&\n s[removed] == t[removed])\n {\n var remaining :| remaining in s_remaining;\n if !(remaining in s &&\n remaining in t &&\n s[remaining] == t[remaining]) {\n return false; \n }\n\n var temp := multiset{};\n s_removed := s_removed + temp[remaining := s[remaining]];\n s_remaining := s_remaining - temp[remaining := s[remaining]];\n }\n\n\n var t_removed := multiset{};\n var t_remaining := t;\n while (|t_remaining| > 0)\n removed in t &&\n s[removed] == t[removed])\n {\n var remaining :| remaining in t_remaining;\n if !(remaining in s &&\n remaining in t &&\n s[remaining] == t[remaining]) {\n return false; \n }\n \n var temp := multiset{};\n t_removed := t_removed + temp[remaining := t[remaining]];\n t_remaining := t_remaining - temp[remaining := t[remaining]];\n }\n\n return true;\n}\n\n" }, { "test_ID": "371", "test_file": "Software-Verification_tmp_tmpv4ueky2d_Valid Palindrome_valid_panlindrome.dfy", "ground_truth": "method isPalindrome(s: array) returns (result: bool)\n requires 1<= s.Length <= 200000\n ensures result <==> (forall i:: 0 <= i < s.Length / 2 ==> s[i] == s[s.Length - 1 - i])\n{\n var length := s.Length;\n\n var i := 0;\n while i < length / 2 \n invariant 0 <= i <= length\n invariant forall j:: 0 <= j < i ==> s[j] == s[length - 1 - j]\n {\n if s[i] != s[length - 1 - i]\n {\n return false;\n }\n\n i := i + 1;\n }\n\n return true;\n}\n\n", "hints_removed": "method isPalindrome(s: array) returns (result: bool)\n requires 1<= s.Length <= 200000\n ensures result <==> (forall i:: 0 <= i < s.Length / 2 ==> s[i] == s[s.Length - 1 - i])\n{\n var length := s.Length;\n\n var i := 0;\n while i < length / 2 \n {\n if s[i] != s[length - 1 - i]\n {\n return false;\n }\n\n i := i + 1;\n }\n\n return true;\n}\n\n" }, { "test_ID": "372", "test_file": "Software-building-and-verification-Projects_tmp_tmp5tm1srrn_CVS-projeto_aula1.dfy", "ground_truth": "method factImp(n: int) returns (r: int)\n{\n r := 1;\n var m := n;\n while (m > 0) {\n r := r*m;\n m := m-1;\n }\n}\n\nfunction power(n: int, m: nat) : int {\n if m==0 then 1 else n*power(n,m-1)\n}\n\nfunction pow(n: int, m: nat,r: int) : int {\n if m==0 then r else pow(n,m-1,r*n)\n}\n\nfunction powerAlt(n: int,m: nat) : int {\n pow(n,m,1)\n}\n\n// 3\n\nfunction equivalentes(n: int,m: nat,r: int) : int\n ensures power(n,m) == pow(n,m,r)\n\nlemma l1(n: int,m: nat, r: int)\n ensures equivalentes(n,m, r) == powerAlt(n,m)\n\n\n// 4.\n\nfunction fact(n: nat) : nat\n{\n if n==0 then 1 else n*fact(n-1)\n}\n\nfunction factAcc(n: nat,a: int) : int\n decreases n\n{\n if (n == 0) then a else factAcc(n-1,n*a)\n}\n\nfunction factAlt(n: nat) : int { factAcc(n,1) }\n\nlemma factAcc_correct(n: nat,a: int)\n ensures factAcc(n,a) == fact(n)*a\n\nlemma equiv(n: nat)\n ensures fact(n) == factAlt(n) {\n factAcc_correct(n, 1);\n assert factAcc(n, 1) == fact(n)*1;\n assert factAlt(n) == factAcc(n, 1);\n assert fact(n) == fact(n)*1;\n}\n\n// 5. a)\nfunction mystery1(n: nat,m: nat) : nat\n decreases n, m;\n ensures mystery1(n,m) == n+m\n{ if n==0 then m else mystery1(n-1,m+1) }\n\n\n// 5. b)\nfunction mystery2(n: nat,m: nat) : nat\n decreases m\n ensures mystery2(n,m) == n+m\n{ if m==0 then n else mystery2(n+1,m-1) }\n\n// 5. c)\nfunction mystery3(n: nat,m: nat) : nat\n ensures mystery3(n,m) == n*m\n{ if n==0 then 0 else mystery1(m,mystery3(n-1,m)) }\n\n// 5. d)\nfunction mystery4(n: nat,m: nat) : nat\n ensures mystery4(n,m) == power(n,m)\n{ if m==0 then 1 else mystery3(n,mystery4(n,m-1)) }\n\n// 6\n\n// 8\n\n// 9\n\n// 10\n\n// 11\n", "hints_removed": "method factImp(n: int) returns (r: int)\n{\n r := 1;\n var m := n;\n while (m > 0) {\n r := r*m;\n m := m-1;\n }\n}\n\nfunction power(n: int, m: nat) : int {\n if m==0 then 1 else n*power(n,m-1)\n}\n\nfunction pow(n: int, m: nat,r: int) : int {\n if m==0 then r else pow(n,m-1,r*n)\n}\n\nfunction powerAlt(n: int,m: nat) : int {\n pow(n,m,1)\n}\n\n// 3\n\nfunction equivalentes(n: int,m: nat,r: int) : int\n ensures power(n,m) == pow(n,m,r)\n\nlemma l1(n: int,m: nat, r: int)\n ensures equivalentes(n,m, r) == powerAlt(n,m)\n\n\n// 4.\n\nfunction fact(n: nat) : nat\n{\n if n==0 then 1 else n*fact(n-1)\n}\n\nfunction factAcc(n: nat,a: int) : int\n{\n if (n == 0) then a else factAcc(n-1,n*a)\n}\n\nfunction factAlt(n: nat) : int { factAcc(n,1) }\n\nlemma factAcc_correct(n: nat,a: int)\n ensures factAcc(n,a) == fact(n)*a\n\nlemma equiv(n: nat)\n ensures fact(n) == factAlt(n) {\n factAcc_correct(n, 1);\n}\n\n// 5. a)\nfunction mystery1(n: nat,m: nat) : nat\n ensures mystery1(n,m) == n+m\n{ if n==0 then m else mystery1(n-1,m+1) }\n\n\n// 5. b)\nfunction mystery2(n: nat,m: nat) : nat\n ensures mystery2(n,m) == n+m\n{ if m==0 then n else mystery2(n+1,m-1) }\n\n// 5. c)\nfunction mystery3(n: nat,m: nat) : nat\n ensures mystery3(n,m) == n*m\n{ if n==0 then 0 else mystery1(m,mystery3(n-1,m)) }\n\n// 5. d)\nfunction mystery4(n: nat,m: nat) : nat\n ensures mystery4(n,m) == power(n,m)\n{ if m==0 then 1 else mystery3(n,mystery4(n,m-1)) }\n\n// 6\n\n// 8\n\n// 9\n\n// 10\n\n// 11\n" }, { "test_ID": "373", "test_file": "Software-building-and-verification-Projects_tmp_tmp5tm1srrn_CVS-projeto_aula2.dfy", "ground_truth": "//PRE-CONDITIONS -> REQUIRES\n//POST-CONDITIONS -> ENSURES\n\nmethod max(a: int, b: int) returns (z: int)\n requires true\n ensures z >= a || z >= b\n{\n if a > b {\n z :=a;\n }\n else {\n z := b;\n }\n}\n\nmethod Main() {\n var x;\n assert true;\n x:=max(23,50);\n\n assert x>=50 || x>=23;\n}\n\n// 3\nmethod mystery1(n: nat,m: nat) returns (res: nat)\n ensures n+m == res\n{\n if (n==0) {\n return m;\n }\n else {\n var aux := mystery1 (n-1,m);\n return 1+aux;\n }\n}\n\nmethod mystery2(n: nat,m: nat) returns (res: nat)\n ensures n*m == res\n{\n if (n==0) {\n return 0;\n }\n else {\n var aux := mystery2(n-1,m);\n var aux2 := mystery1(m,aux);\n return aux2;\n }\n}\n\n// 5a\nmethod m1(x: int,y: int) returns (z: int)\n requires 0 < x < y\n ensures z >= 0 && z < y && z != x\n{\n if (x > 0 && y > 0 && y > x) {\n z := x-1;\n }\n}\n\n// 5b\nmethod m2(x: nat) returns (y: int)\n requires x <= -1\n ensures y > x && y < x\n{\n if (x <= -1) {\n y := x+1;\n }\n}\n\n// 5c\n// pode dar false e eles nao serem iguais\n// \nmethod m3(x: int,y: int) returns (z: bool)\n ensures z ==> x==y\n{\n if (x == y) {\n z := true;\n }\n else {\n z := false;\n }\n}\n\n// 5d\nmethod m4(x: int,y: int) returns (z: bool)\n ensures z ==> x==y && x==y ==> z\n{\n if (x == y) {\n z := true;\n }\n else {\n z := false;\n }\n}\n", "hints_removed": "//PRE-CONDITIONS -> REQUIRES\n//POST-CONDITIONS -> ENSURES\n\nmethod max(a: int, b: int) returns (z: int)\n requires true\n ensures z >= a || z >= b\n{\n if a > b {\n z :=a;\n }\n else {\n z := b;\n }\n}\n\nmethod Main() {\n var x;\n x:=max(23,50);\n\n}\n\n// 3\nmethod mystery1(n: nat,m: nat) returns (res: nat)\n ensures n+m == res\n{\n if (n==0) {\n return m;\n }\n else {\n var aux := mystery1 (n-1,m);\n return 1+aux;\n }\n}\n\nmethod mystery2(n: nat,m: nat) returns (res: nat)\n ensures n*m == res\n{\n if (n==0) {\n return 0;\n }\n else {\n var aux := mystery2(n-1,m);\n var aux2 := mystery1(m,aux);\n return aux2;\n }\n}\n\n// 5a\nmethod m1(x: int,y: int) returns (z: int)\n requires 0 < x < y\n ensures z >= 0 && z < y && z != x\n{\n if (x > 0 && y > 0 && y > x) {\n z := x-1;\n }\n}\n\n// 5b\nmethod m2(x: nat) returns (y: int)\n requires x <= -1\n ensures y > x && y < x\n{\n if (x <= -1) {\n y := x+1;\n }\n}\n\n// 5c\n// pode dar false e eles nao serem iguais\n// \nmethod m3(x: int,y: int) returns (z: bool)\n ensures z ==> x==y\n{\n if (x == y) {\n z := true;\n }\n else {\n z := false;\n }\n}\n\n// 5d\nmethod m4(x: int,y: int) returns (z: bool)\n ensures z ==> x==y && x==y ==> z\n{\n if (x == y) {\n z := true;\n }\n else {\n z := false;\n }\n}\n" }, { "test_ID": "374", "test_file": "Software-building-and-verification-Projects_tmp_tmp5tm1srrn_CVS-projeto_aula3.dfy", "ground_truth": "function fib(n : nat) : nat\n{\n if (n==0) then 1 else\n if (n==1) then 1 else fib(n-1)+fib(n-2)\n}\n\nmethod Fib(n : nat) returns (r:nat)\n ensures r == fib(n)\n{\n\n if (n == 0) {\n return 1;\n }\n\n var next:= 2;\n r:=1;\n var i := 1;\n\n while (i < n)\n invariant next == fib(i+1)\n invariant r == fib(i)\n invariant 1 <= i <= n\n {\n var tmp := next;\n next := next + r;\n r := tmp;\n i := i + 1;\n }\n assert r == fib(n);\n return r;\n}\n\n// 2.\ndatatype List = Nil | Cons(head: T, tail: List)\n\nfunction add(l : List) : int {\n match l\n case Nil => 0\n case Cons(x,xs) => x + add(xs)\n}\n\nmethod addImp(l : List) returns (r: int)\n ensures r == add(l)\n{\n r := 0;\n var ll := l;\n while (ll != Nil)\n decreases ll\n invariant r==add(l) - add(ll)\n {\n r := r + ll.head;\n ll := ll.tail;\n\n }\n\n assert r == add(l);\n}\n\n// 3.\nmethod maxArray(arr : array) returns (max: int)\n requires arr.Length > 0\n ensures forall i: int :: 0 <= i < arr.Length ==> arr[i] <= max\n ensures exists x::0 <= x < arr.Length && arr[x] == max\n{\n max := arr[0];\n var index := 1;\n while(index < arr.Length)\n invariant 0 <= index <= arr.Length\n invariant forall i: int :: 0 <= i < index ==> arr[i] <= max\n invariant exists x::0 <= x < arr.Length && arr[x] == max\n\n {\n if (arr[index] > max) {\n max := arr[index];\n }\n index := index + 1;\n }\n}\n\n// 5.\nmethod maxArrayReverse(arr : array) returns (max: int)\n requires arr.Length > 0\n ensures forall i: int :: 0 <= i < arr.Length ==> arr[i] <= max\n ensures exists x::0 <= x < arr.Length && arr[x] == max\n{\n var ind := arr.Length - 1;\n max := arr[ind];\n\n while ind > 0\n invariant 0 <= ind <= arr.Length\n invariant forall i: int :: ind <= i < arr.Length ==> arr[i] <= max\n invariant exists x::0 <= x < arr.Length && arr[x] == max\n {\n\n if (arr[ind - 1] > max) {\n max := arr[ind - 1];\n }\n ind := ind - 1;\n }\n}\n\n// 6\nfunction sum(n: nat) : nat\n{\n if (n == 0) then 0 else n + sum(n-1)\n}\n\nmethod sumBackwards(n: nat) returns (r: nat)\n ensures r == sum(n)\n{\n var i := n;\n r := 0;\n\n while i > 0\n invariant 0 <= i <= n\n invariant r == sum(n) - sum(i)\n\n {\n r := r + i;\n i := i - 1;\n }\n}\n", "hints_removed": "function fib(n : nat) : nat\n{\n if (n==0) then 1 else\n if (n==1) then 1 else fib(n-1)+fib(n-2)\n}\n\nmethod Fib(n : nat) returns (r:nat)\n ensures r == fib(n)\n{\n\n if (n == 0) {\n return 1;\n }\n\n var next:= 2;\n r:=1;\n var i := 1;\n\n while (i < n)\n {\n var tmp := next;\n next := next + r;\n r := tmp;\n i := i + 1;\n }\n return r;\n}\n\n// 2.\ndatatype List = Nil | Cons(head: T, tail: List)\n\nfunction add(l : List) : int {\n match l\n case Nil => 0\n case Cons(x,xs) => x + add(xs)\n}\n\nmethod addImp(l : List) returns (r: int)\n ensures r == add(l)\n{\n r := 0;\n var ll := l;\n while (ll != Nil)\n {\n r := r + ll.head;\n ll := ll.tail;\n\n }\n\n}\n\n// 3.\nmethod maxArray(arr : array) returns (max: int)\n requires arr.Length > 0\n ensures forall i: int :: 0 <= i < arr.Length ==> arr[i] <= max\n ensures exists x::0 <= x < arr.Length && arr[x] == max\n{\n max := arr[0];\n var index := 1;\n while(index < arr.Length)\n\n {\n if (arr[index] > max) {\n max := arr[index];\n }\n index := index + 1;\n }\n}\n\n// 5.\nmethod maxArrayReverse(arr : array) returns (max: int)\n requires arr.Length > 0\n ensures forall i: int :: 0 <= i < arr.Length ==> arr[i] <= max\n ensures exists x::0 <= x < arr.Length && arr[x] == max\n{\n var ind := arr.Length - 1;\n max := arr[ind];\n\n while ind > 0\n {\n\n if (arr[ind - 1] > max) {\n max := arr[ind - 1];\n }\n ind := ind - 1;\n }\n}\n\n// 6\nfunction sum(n: nat) : nat\n{\n if (n == 0) then 0 else n + sum(n-1)\n}\n\nmethod sumBackwards(n: nat) returns (r: nat)\n ensures r == sum(n)\n{\n var i := n;\n r := 0;\n\n while i > 0\n\n {\n r := r + i;\n i := i - 1;\n }\n}\n" }, { "test_ID": "375", "test_file": "Software-building-and-verification-Projects_tmp_tmp5tm1srrn_CVS-projeto_aula5.dfy", "ground_truth": "/*Ex1 Given the leaky specification of class Set found in Appendix ??, use the techniques from\nclass (the use of ghost state and dynamic frames) so that the specification no longer leaks\nthe internal representation. Produce client code that correctly connects to your revised\nSet class. */\n\nclass Set {\n var store:array;\n var nelems: int;\n\n ghost var Repr : set\n ghost var elems : set\n\n\n ghost predicate RepInv()\n reads this, Repr\n {\n this in Repr && store in Repr &&\n 0 < store.Length\n && 0 <= nelems <= store.Length\n && (forall i :: 0 <= i < nelems ==> store[i] in elems)\n && (forall x :: x in elems ==> exists i :: 0 <= i < nelems && store[i] == x)\n }\n // the construction operation\n constructor(n: int)\n requires 0 < n\n ensures RepInv()\n ensures fresh(Repr-{this})\n {\n store := new int[n];\n Repr := {this,store};\n elems := {};\n nelems := 0;\n }\n // returns the number of elements in the set\n function size():int\n requires RepInv()\n ensures RepInv()\n reads Repr\n { nelems }\n // returns the maximum number of elements in the set\n function maxSize():int\n requires RepInv()\n ensures RepInv()\n reads Repr\n { store.Length }\n // checks if the element given is in the set\n method contains(v:int) returns (b:bool)\n requires RepInv()\n ensures RepInv()\n ensures b <==> v in elems\n {\n\n var i := find(v);\n return i >= 0;\n }\n // adds a new element to the set if space available\n\n method add(v:int)\n requires RepInv()\n requires size() < maxSize()\n ensures RepInv()\n modifies this,Repr\n ensures fresh(Repr - old(Repr))\n {\n var f:int := find(v);\n if (f < 0) {\n store[nelems] := v;\n elems := elems + {v};\n assert forall i:: 0 <= i < nelems ==> old(store[i]) == store[i];\n nelems := nelems + 1;\n }\n }\n // private method that should not be in the\n method find(x:int) returns (r:int)\n requires RepInv()\n ensures RepInv()\n ensures r < 0 ==> x !in elems\n ensures r >=0 ==> x in elems;\n {\n var i:int := 0;\n while (i x != store[j];\n {\n if (store[i]==x) { return i; }\n i := i + 1;\n }\n return -1;\n }\n method Main()\n {\n var s := new Set(10);\n if (s.size() < s.maxSize()) {\n s.add(2);\n var b := s.contains(2);\n if (s.size() < s.maxSize()) {\n s.add(3);\n }\n }\n }\n}\n\n/*2. Using the corrected version of Set as a baseline, implement a PositiveSet class that\nenforces the invariant that all numbers in the set are strictly positive. */\n\nclass PositiveSet {\n var store:array;\n var nelems: int;\n\n ghost var Repr : set\n ghost var elems : set\n\n\n ghost predicate RepInv()\n reads this, Repr\n {\n this in Repr && store in Repr &&\n 0 < store.Length\n && 0 <= nelems <= store.Length\n && (forall i :: 0 <= i < nelems ==> store[i] in elems)\n && (forall x :: x in elems ==> exists i :: 0 <= i < nelems && store[i] == x)\n && (forall x :: x in elems ==> x > 0)\n }\n // the construction operation\n constructor(n: int)\n requires 0 < n\n ensures RepInv()\n ensures fresh(Repr-{this})\n {\n store := new int[n];\n Repr := {this,store};\n elems := {};\n nelems := 0;\n }\n // returns the number of elements in the set\n function size():int\n requires RepInv()\n ensures RepInv()\n reads Repr\n { nelems }\n // returns the maximum number of elements in the set\n function maxSize():int\n requires RepInv()\n ensures RepInv()\n reads Repr\n { store.Length }\n // checks if the element given is in the set\n method contains(v:int) returns (b:bool)\n requires RepInv()\n ensures RepInv()\n ensures b <==> v in elems\n {\n\n var i := find(v);\n return i >= 0;\n }\n // adds a new element to the set if space available\n\n method add(v:int)\n requires RepInv()\n requires size() < maxSize()\n ensures RepInv()\n modifies this,Repr\n ensures fresh(Repr - old(Repr))\n {\n if(v > 0) {\n var f:int := find(v);\n if (f < 0) {\n store[nelems] := v;\n elems := elems + {v};\n assert forall i:: 0 <= i < nelems ==> old(store[i]) == store[i];\n nelems := nelems + 1;\n }\n }\n }\n // private method that should not be in the\n method find(x:int) returns (r:int)\n requires RepInv()\n ensures RepInv()\n ensures r < 0 ==> x !in elems\n ensures r >=0 ==> x in elems;\n {\n var i:int := 0;\n while (i x != store[j];\n {\n if (store[i]==x) { return i; }\n i := i + 1;\n }\n return -1;\n }\n method Main()\n {\n var s := new PositiveSet(10);\n if (s.size() < s.maxSize()) {\n s.add(2);\n var b := s.contains(2);\n if (s.size() < s.maxSize()) {\n s.add(3);\n }\n }\n }\n}\n\n/*\n * Implement a savings account.\n * A savings account is actually made up of two balances.\n *\n * One is the checking balance, here account owner can deposit and withdraw\n * money at will. There is only one restriction on withdrawing. In a regular\n * bank account, the account owner can make withdrawals as long as he has the\n * balance for it, i.e., the user cannot withdraw more money than the user has.\n * In a savings account, the checking balance can go negative as long as it does\n * not surpass half of what is saved in the savings balance. Consider the\n * following example:\n *\n * Savings = 10\n * Checking = 0\n * Operation 1: withdraw 10 This operation is not valid. Given that the\n * the user only has $$10, his checking account\n * can only decrease down to $$-5 (10/2).\n *\n * Operation 2: withdraw 2 Despite the fact that the checking balance of\n * the user is zero,\n * money in his savings account, therefore, this\n * operation is valid, and the result would be\n * something like:\n * Savings = 10;\n * Checking = -2\n *\n * Regarding depositing money in the savings balance (save), this operation has\n * one small restrictions. It is only possible to save money to the savings\n * balance when the user is not in debt; i.e. to save money into savings, the\n * checking must be non-negative.\n *\n * Given the states:\n * STATE 1 STATE 2\n * Savings = 10 Savings = 10\n * Checking = -5 Checking = 0\n *\n * and the operation save($$60000000000), the operation is valid when executed\n * in STATE 2 but not in STATE 1.\n *\n * Finally, when withdrawing from the savings balance, an operation we will\n * call rescue, the amount the user can withdraw depends on the negativity of\n * the user\u2019s checking account. For instance:\n *\n * Savings: 12\n * Checking: -5\n *\n * In the case, the user could withdraw at most two double dollars ($$). If the\n * user withdrew more than that, the balance of the checking account would\n * go beyond the -50% of the savings account; big no no.\n *\n */\n\nclass SavingsAccount {\n\n var cbalance: int;\n var sbalance: int;\n\n ghost var Repr:set;\n\n ghost predicate RepInv()\n reads this,Repr\n {\n this in Repr\n && cbalance >= -sbalance/2\n }\n\n ghost predicate PositiveChecking()\n reads this,Repr\n {\n cbalance >= 0\n }\n\n constructor()\n ensures fresh(Repr-{this})\n ensures RepInv()\n {\n Repr := {this};\n cbalance := 0;\n sbalance := 0;\n }\n\n method deposit(amount:int)\n requires amount > 0\n requires RepInv()\n ensures RepInv()\n modifies Repr\n {\n cbalance := cbalance + amount;\n }\n\n method withdraw(amount:int)\n requires amount > 0\n requires RepInv()\n ensures RepInv()\n modifies Repr\n {\n if(cbalance-amount >= -sbalance/2)\n {\n cbalance := cbalance - amount;\n }\n }\n\n method save(amount: int)\n requires amount > 0\n requires PositiveChecking()\n requires RepInv()\n ensures RepInv()\n modifies Repr\n {\n if(cbalance >= 0)\n {\n sbalance := sbalance + amount;\n }\n }\n\n method rescue(amount: int)\n requires amount > 0\n requires RepInv()\n ensures RepInv()\n modifies Repr\n {\n\n if(cbalance >= -(sbalance-amount)/2)\n {\n sbalance := sbalance - amount;\n }\n }\n}\n\n\n\n/*Ex 4 Change your specification and implementation of the ASet ADT to include a growing\narray of integer values. */\nclass GrowingSet {\n var store:array;\n var nelems: int;\n\n ghost var Repr : set\n ghost var elems : set\n\n\n ghost predicate RepInv()\n reads this, Repr\n {\n this in Repr && store in Repr &&\n 0 < store.Length\n && 0 <= nelems <= store.Length\n && (forall i :: 0 <= i < nelems ==> store[i] in elems)\n && (forall x :: x in elems ==> exists i :: 0 <= i < nelems && store[i] == x)\n }\n // the construction operation\n constructor(n: int)\n requires 0 < n\n ensures RepInv()\n ensures fresh(Repr-{this})\n {\n store := new int[n];\n Repr := {this,store};\n elems := {};\n nelems := 0;\n }\n // returns the number of elements in the set\n function size():int\n requires RepInv()\n ensures RepInv()\n reads Repr\n { nelems }\n // returns the maximum number of elements in the set\n function maxSize():int\n requires RepInv()\n ensures RepInv()\n reads Repr\n { store.Length }\n // checks if the element given is in the set\n method contains(v:int) returns (b:bool)\n requires RepInv()\n ensures RepInv()\n ensures b <==> v in elems\n {\n\n var i := find(v);\n return i >= 0;\n }\n // adds a new element to the set if space available\n\n method add(v:int)\n requires RepInv()\n ensures RepInv()\n modifies Repr\n ensures fresh(Repr - old(Repr))\n {\n var f:int := find(v);\n assert forall i:: 0 <= i < nelems ==> old(store[i]) == store[i];\n if (f < 0) {\n if(nelems == store.Length) {\n var tmp := new int[store.Length * 2];\n var i:= 0;\n while i < store.Length\n invariant 0 <= i <= store.Length < tmp.Length\n invariant forall j :: 0 <= j < i ==> old(store[j]) == tmp[j]\n modifies tmp\n {\n tmp[i] := store[i];\n i := i + 1;\n }\n Repr := Repr - {store} + {tmp};\n store := tmp;\n\n }\n\n store[nelems] := v;\n elems := elems + {v};\n assert forall i:: 0 <= i < nelems ==> old(store[i]) == store[i];\n nelems := nelems + 1;\n\n }\n }\n \n // private method that should not be in the\n method find(x:int) returns (r:int)\n requires RepInv()\n ensures RepInv()\n ensures r < 0 ==> x !in elems\n ensures r >=0 ==> x in elems;\n {\n var i:int := 0;\n while (i x != store[j];\n {\n if (store[i]==x) { return i; }\n i := i + 1;\n }\n return -1;\n }\n method Main()\n {\n var s := new GrowingSet(10);\n if (s.size() < s.maxSize()) {\n s.add(2);\n var b := s.contains(2);\n if (s.size() < s.maxSize()) {\n s.add(3);\n }\n }\n }\n}\n\n", "hints_removed": "/*Ex1 Given the leaky specification of class Set found in Appendix ??, use the techniques from\nclass (the use of ghost state and dynamic frames) so that the specification no longer leaks\nthe internal representation. Produce client code that correctly connects to your revised\nSet class. */\n\nclass Set {\n var store:array;\n var nelems: int;\n\n ghost var Repr : set\n ghost var elems : set\n\n\n ghost predicate RepInv()\n reads this, Repr\n {\n this in Repr && store in Repr &&\n 0 < store.Length\n && 0 <= nelems <= store.Length\n && (forall i :: 0 <= i < nelems ==> store[i] in elems)\n && (forall x :: x in elems ==> exists i :: 0 <= i < nelems && store[i] == x)\n }\n // the construction operation\n constructor(n: int)\n requires 0 < n\n ensures RepInv()\n ensures fresh(Repr-{this})\n {\n store := new int[n];\n Repr := {this,store};\n elems := {};\n nelems := 0;\n }\n // returns the number of elements in the set\n function size():int\n requires RepInv()\n ensures RepInv()\n reads Repr\n { nelems }\n // returns the maximum number of elements in the set\n function maxSize():int\n requires RepInv()\n ensures RepInv()\n reads Repr\n { store.Length }\n // checks if the element given is in the set\n method contains(v:int) returns (b:bool)\n requires RepInv()\n ensures RepInv()\n ensures b <==> v in elems\n {\n\n var i := find(v);\n return i >= 0;\n }\n // adds a new element to the set if space available\n\n method add(v:int)\n requires RepInv()\n requires size() < maxSize()\n ensures RepInv()\n modifies this,Repr\n ensures fresh(Repr - old(Repr))\n {\n var f:int := find(v);\n if (f < 0) {\n store[nelems] := v;\n elems := elems + {v};\n nelems := nelems + 1;\n }\n }\n // private method that should not be in the\n method find(x:int) returns (r:int)\n requires RepInv()\n ensures RepInv()\n ensures r < 0 ==> x !in elems\n ensures r >=0 ==> x in elems;\n {\n var i:int := 0;\n while (i;\n var nelems: int;\n\n ghost var Repr : set\n ghost var elems : set\n\n\n ghost predicate RepInv()\n reads this, Repr\n {\n this in Repr && store in Repr &&\n 0 < store.Length\n && 0 <= nelems <= store.Length\n && (forall i :: 0 <= i < nelems ==> store[i] in elems)\n && (forall x :: x in elems ==> exists i :: 0 <= i < nelems && store[i] == x)\n && (forall x :: x in elems ==> x > 0)\n }\n // the construction operation\n constructor(n: int)\n requires 0 < n\n ensures RepInv()\n ensures fresh(Repr-{this})\n {\n store := new int[n];\n Repr := {this,store};\n elems := {};\n nelems := 0;\n }\n // returns the number of elements in the set\n function size():int\n requires RepInv()\n ensures RepInv()\n reads Repr\n { nelems }\n // returns the maximum number of elements in the set\n function maxSize():int\n requires RepInv()\n ensures RepInv()\n reads Repr\n { store.Length }\n // checks if the element given is in the set\n method contains(v:int) returns (b:bool)\n requires RepInv()\n ensures RepInv()\n ensures b <==> v in elems\n {\n\n var i := find(v);\n return i >= 0;\n }\n // adds a new element to the set if space available\n\n method add(v:int)\n requires RepInv()\n requires size() < maxSize()\n ensures RepInv()\n modifies this,Repr\n ensures fresh(Repr - old(Repr))\n {\n if(v > 0) {\n var f:int := find(v);\n if (f < 0) {\n store[nelems] := v;\n elems := elems + {v};\n nelems := nelems + 1;\n }\n }\n }\n // private method that should not be in the\n method find(x:int) returns (r:int)\n requires RepInv()\n ensures RepInv()\n ensures r < 0 ==> x !in elems\n ensures r >=0 ==> x in elems;\n {\n var i:int := 0;\n while (i;\n\n ghost predicate RepInv()\n reads this,Repr\n {\n this in Repr\n && cbalance >= -sbalance/2\n }\n\n ghost predicate PositiveChecking()\n reads this,Repr\n {\n cbalance >= 0\n }\n\n constructor()\n ensures fresh(Repr-{this})\n ensures RepInv()\n {\n Repr := {this};\n cbalance := 0;\n sbalance := 0;\n }\n\n method deposit(amount:int)\n requires amount > 0\n requires RepInv()\n ensures RepInv()\n modifies Repr\n {\n cbalance := cbalance + amount;\n }\n\n method withdraw(amount:int)\n requires amount > 0\n requires RepInv()\n ensures RepInv()\n modifies Repr\n {\n if(cbalance-amount >= -sbalance/2)\n {\n cbalance := cbalance - amount;\n }\n }\n\n method save(amount: int)\n requires amount > 0\n requires PositiveChecking()\n requires RepInv()\n ensures RepInv()\n modifies Repr\n {\n if(cbalance >= 0)\n {\n sbalance := sbalance + amount;\n }\n }\n\n method rescue(amount: int)\n requires amount > 0\n requires RepInv()\n ensures RepInv()\n modifies Repr\n {\n\n if(cbalance >= -(sbalance-amount)/2)\n {\n sbalance := sbalance - amount;\n }\n }\n}\n\n\n\n/*Ex 4 Change your specification and implementation of the ASet ADT to include a growing\narray of integer values. */\nclass GrowingSet {\n var store:array;\n var nelems: int;\n\n ghost var Repr : set\n ghost var elems : set\n\n\n ghost predicate RepInv()\n reads this, Repr\n {\n this in Repr && store in Repr &&\n 0 < store.Length\n && 0 <= nelems <= store.Length\n && (forall i :: 0 <= i < nelems ==> store[i] in elems)\n && (forall x :: x in elems ==> exists i :: 0 <= i < nelems && store[i] == x)\n }\n // the construction operation\n constructor(n: int)\n requires 0 < n\n ensures RepInv()\n ensures fresh(Repr-{this})\n {\n store := new int[n];\n Repr := {this,store};\n elems := {};\n nelems := 0;\n }\n // returns the number of elements in the set\n function size():int\n requires RepInv()\n ensures RepInv()\n reads Repr\n { nelems }\n // returns the maximum number of elements in the set\n function maxSize():int\n requires RepInv()\n ensures RepInv()\n reads Repr\n { store.Length }\n // checks if the element given is in the set\n method contains(v:int) returns (b:bool)\n requires RepInv()\n ensures RepInv()\n ensures b <==> v in elems\n {\n\n var i := find(v);\n return i >= 0;\n }\n // adds a new element to the set if space available\n\n method add(v:int)\n requires RepInv()\n ensures RepInv()\n modifies Repr\n ensures fresh(Repr - old(Repr))\n {\n var f:int := find(v);\n if (f < 0) {\n if(nelems == store.Length) {\n var tmp := new int[store.Length * 2];\n var i:= 0;\n while i < store.Length\n modifies tmp\n {\n tmp[i] := store[i];\n i := i + 1;\n }\n Repr := Repr - {store} + {tmp};\n store := tmp;\n\n }\n\n store[nelems] := v;\n elems := elems + {v};\n nelems := nelems + 1;\n\n }\n }\n \n // private method that should not be in the\n method find(x:int) returns (r:int)\n requires RepInv()\n ensures RepInv()\n ensures r < 0 ==> x !in elems\n ensures r >=0 ==> x in elems;\n {\n var i:int := 0;\n while (i, i: int, j: int) : int\n requires 0 <= i <= j <= a.Length\n reads a\n decreases j\n{\n if i == j then 0\n else a[j-1] + sum(a, i, j-1)\n}\n\n// 1 b)\nmethod query(a: array, i: int, j: int) returns (res : int)\n requires 0 <= i <= j <= a.Length\n ensures res == sum(a, i, j)\n{\n res := 0;\n var ind := j-1;\n\n while ind >= i\n invariant i-1 <= ind < j\n invariant res == sum(a, i, j) - sum(a, i, ind+1)\n decreases ind\n {\n res := res + a[ind];\n ind := ind - 1;\n }\n}\n\n// 1 c)\n// a -> [1, 10, 3, \u22124, 5]\n// c -> [0, 1, 11, 14, 10, 15]\nmethod queryFast(a: array, c: array, i: int, j: int) returns (r: int)\n requires 0 <= i <= j <= a.Length\n requires is_prefix_sum_for(a,c)\n ensures r == sum(a, i, j)\n{\n var k := i;\n proof(a, 0, j, k);\n r := c[j] - c[i];\n}\n\npredicate is_prefix_sum_for (a: array, c: array)\n reads c, a\n{\n a.Length + 1 == c.Length && forall i: int :: 0 <= i <= a.Length ==> c[i] == sum(a, 0, i)\n}\n\nlemma proof(a: array, i: int, j: int, k:int)\n requires 0 <= i <= k <= j <= a.Length\n ensures sum(a, i, k) + sum(a, k, j) == sum(a, i, j)\n\n\n// 2\n\ndatatype List = Nil | Cons(head: T, tail: List)\n\nmethod from_array(a: array) returns (l: List)\n ensures forall i: int :: 0 <= i < a.Length ==> mem(a[i], l)\n ensures forall x: T :: mem(x, l) ==> exists y: int :: 0 <= y < a.Length && a[y] == x\n{\n l := Nil;\n var i := a.Length - 1;\n while i >= 0\n invariant 0 <= i+1 <= a.Length\n invariant forall j: int :: i < j < a.Length ==> mem(a[j], l)\n invariant forall x: T :: mem(x, l) ==> exists y: int :: i+1 <= y < a.Length && a[y] == x\n decreases i\n {\n l := Cons(a[i], l);\n i := i - 1;\n }\n}\n\nfunction mem (x: T, l: List) : bool\n{\n match l\n case Nil => false\n case Cons(h, t) => h == x || mem(x, t)\n}\n", "hints_removed": "// 1 a)\n\n// [ai, aj[\nfunction sum(a: array, i: int, j: int) : int\n requires 0 <= i <= j <= a.Length\n reads a\n{\n if i == j then 0\n else a[j-1] + sum(a, i, j-1)\n}\n\n// 1 b)\nmethod query(a: array, i: int, j: int) returns (res : int)\n requires 0 <= i <= j <= a.Length\n ensures res == sum(a, i, j)\n{\n res := 0;\n var ind := j-1;\n\n while ind >= i\n {\n res := res + a[ind];\n ind := ind - 1;\n }\n}\n\n// 1 c)\n// a -> [1, 10, 3, \u22124, 5]\n// c -> [0, 1, 11, 14, 10, 15]\nmethod queryFast(a: array, c: array, i: int, j: int) returns (r: int)\n requires 0 <= i <= j <= a.Length\n requires is_prefix_sum_for(a,c)\n ensures r == sum(a, i, j)\n{\n var k := i;\n proof(a, 0, j, k);\n r := c[j] - c[i];\n}\n\npredicate is_prefix_sum_for (a: array, c: array)\n reads c, a\n{\n a.Length + 1 == c.Length && forall i: int :: 0 <= i <= a.Length ==> c[i] == sum(a, 0, i)\n}\n\nlemma proof(a: array, i: int, j: int, k:int)\n requires 0 <= i <= k <= j <= a.Length\n ensures sum(a, i, k) + sum(a, k, j) == sum(a, i, j)\n\n\n// 2\n\ndatatype List = Nil | Cons(head: T, tail: List)\n\nmethod from_array(a: array) returns (l: List)\n ensures forall i: int :: 0 <= i < a.Length ==> mem(a[i], l)\n ensures forall x: T :: mem(x, l) ==> exists y: int :: 0 <= y < a.Length && a[y] == x\n{\n l := Nil;\n var i := a.Length - 1;\n while i >= 0\n {\n l := Cons(a[i], l);\n i := i - 1;\n }\n}\n\nfunction mem (x: T, l: List) : bool\n{\n match l\n case Nil => false\n case Cons(h, t) => h == x || mem(x, t)\n}\n" }, { "test_ID": "377", "test_file": "Software-building-and-verification-Projects_tmp_tmp5tm1srrn_CVS-projeto_handout2.dfy", "ground_truth": "datatype List = Nil | Cons(head:T,tail:List)\ndatatype Option = None | Some(elem:T)\n\nghost function mem(x:T,l:List) : bool {\n match l {\n case Nil => false\n case Cons(y,xs) => x==y || mem(x,xs)\n }\n}\n\nghost function length(l:List) : int {\n match l {\n case Nil => 0\n case Cons(_,xs) => 1 + length(xs)\n }\n}\n\nfunction list_find(k:K,l:List<(K,V)>) : Option\n ensures match list_find(k,l) {\n case None => forall v :: !mem((k,v),l)\n case Some(v) => mem((k,v),l)\n }\n decreases l\n{\n match l {\n case Nil => None\n case Cons((k',v),xs) => if k==k' then Some(v) else list_find(k,xs)\n }\n}\n\nfunction list_remove(k:K, l:List<(K,V)>) : List<(K,V)>\n decreases l\n ensures forall k',v :: mem((k',v),list_remove(k,l)) <==> (mem((k',v),l) && k != k')\n{\n match l {\n case Nil => Nil\n case Cons((k',v),xs) => if k==k' then list_remove(k,xs) else\n Cons((k',v),list_remove(k,xs))\n }\n}\n\n\nclass Hashtable {\n var size : int\n var data : array>\n\n ghost var Repr : set\n ghost var elems : map>\n\n ghost predicate RepInv()\n reads this, Repr\n {\n this in Repr && data in Repr && data.Length > 0 &&\n (forall i :: 0 <= i < data.Length ==> valid_hash(data, i)) &&\n (forall k,v :: valid_data(k,v,elems,data))\n }\n\n ghost predicate valid_hash(data: array>, i: int)\n requires 0 <= i < data.Length\n reads data\n {\n forall k,v :: mem((k,v), data[i]) ==> (bucket(k,data.Length) == i)\n }\n\n\n ghost predicate valid_data(k: K,v: V,elems: map>, data: array>)\n reads this, Repr, data\n requires data.Length > 0\n {\n (k in elems && elems[k] == Some(v)) <==> mem((k,v), data[bucket(k, data.Length)])\n }\n\n\n function hash(key:K) : int\n ensures hash(key) >= 0\n\n function bucket(k: K, n: int) : int\n requires n > 0\n ensures 0 <= bucket(k, n) < n\n {\n hash(k) % n\n }\n\n constructor(n:int)\n requires n > 0\n ensures RepInv()\n ensures fresh(Repr-{this})\n ensures elems == map[]\n ensures size == 0\n {\n size := 0;\n data := new List<(K,V)>[n](i => Nil);\n Repr := {this, data};\n elems := map[];\n }\n\n method clear()\n requires RepInv()\n ensures RepInv()\n ensures elems == map[]\n ensures fresh(Repr - old(Repr))\n modifies Repr\n {\n var i := 0;\n while i < data.Length\n invariant 0 <= i <= data.Length\n invariant forall j :: 0 <= j < i ==> data[j] == Nil\n modifies data\n {\n data[i] := Nil;\n i := i + 1;\n }\n size := 0;\n elems := map[];\n }\n\n method resize()\n requires RepInv()\n ensures RepInv()\n ensures fresh(Repr - old(Repr))\n ensures forall key :: key in old(elems) ==> key in elems\n ensures forall k,v :: k in old(elems) && old(elems)[k] == Some(v) ==> k in elems && elems[k] == Some(v)\n modifies Repr\n {\n var newData := new List<(K,V)>[data.Length * 2](i => Nil);\n var i := 0;\n var oldSize := data.Length;\n var newSize := newData.Length;\n\n assert forall i :: 0 <= i < data.Length ==> valid_hash(data,i);\n\n while i < data.Length\n modifies newData\n invariant RepInv()\n invariant 0 <= i <= data.Length\n invariant newData != data\n invariant old(data) == data\n invariant old(size) == size\n invariant Repr == old(Repr)\n invariant 0 < oldSize == data.Length\n invariant data.Length*2 == newData.Length == newSize\n invariant forall j :: 0 <= j < newSize ==> valid_hash(newData, j)\n invariant forall k,v :: (\n if 0<= bucket(k, oldSize) < i then\n valid_data(k,v,elems,newData)\n else\n !mem((k,v), newData[bucket(k, newSize)]))\n {\n assert valid_hash(data,i);\n assert forall k,v :: (\n if 0 <= bucket(k, oldSize) < i then\n valid_data(k,v,elems,data)\n else if bucket(k, oldSize) == i then\n ((k in elems && elems[k] == Some(v))\n <==> mem((k,v), data[bucket(k,data.Length)]) || mem((k,v), newData[bucket(k, newSize)]))\n else\n !mem((k,v), newData[bucket(k, newSize)]));\n rehash(data[i],newData,i,oldSize,newSize);\n i := i + 1;\n }\n Repr := Repr - {data} + {newData};\n data := newData;\n }\n\n\n method rehash(l: List<(K,V)>, newData: array>,i: int, oldSize: int, newSize: int)\n requires newData != data\n requires 0 < oldSize == data.Length\n requires newData.Length == 2 * oldSize == newSize\n requires forall k,v :: mem((k,v), l) ==> bucket(k, oldSize) == i\n requires forall j :: 0 <= j < newSize ==> valid_hash(newData, j)\n requires forall k,v :: (\n if 0 <= bucket(k, oldSize) < i then\n valid_data(k,v,elems,newData)\n else if bucket(k, oldSize) == i then\n ((k in elems && elems[k] == Some(v))\n <==> mem((k,v), l) || mem((k,v),newData[bucket(k, newSize)]))\n else\n !mem((k,v),newData[bucket(k, newSize)]))\n ensures forall j :: 0 <= j < newSize ==> valid_hash(newData, j)\n ensures forall k,v ::\n (if 0 <= bucket(k, oldSize) <= i then\n valid_data(k,v,elems,newData)\n else\n !mem((k,v),newData[bucket(k, newSize)]))\n modifies newData\n decreases l\n {\n match l {\n case Nil => return;\n case Cons((k,v), r) => {\n var b := bucket(k, newSize);\n newData[b] := Cons((k,v), newData[b]);\n rehash(r, newData, i, oldSize, newSize);\n }\n }\n }\n\n method find(k: K) returns (r: Option)\n requires RepInv()\n ensures RepInv()\n ensures match r\n case None => (k !in elems || (k in elems && elems[k] == None))\n case Some(v) => (k in elems && elems[k] == Some(v))\n {\n assert forall k, v :: valid_data(k,v,elems,data) && ((k in elems && elems[k] == Some(v)) <==> (mem((k,v),data[bucket(k,data.Length)])));\n var idx := bucket(k, data.Length);\n r := list_find(k, data[idx]);\n assert match list_find(k,data[bucket(k, data.Length)])\n case None => forall v :: idx == bucket(k,data.Length) && !mem((k,v),data[idx])\n case Some(v) => mem((k,v),data[bucket(k,data.Length)]);\n }\n\n\n method remove(k: K)\n requires RepInv()\n ensures RepInv()\n ensures fresh(Repr - old(Repr))\n ensures k !in elems || elems[k] == None\n ensures forall key :: key != k && key in old(elems) ==> key in elems && elems[key] == old(elems[key])\n modifies Repr\n {\n assert forall i :: 0 <= i < data.Length ==> valid_hash(data, i);\n assert forall k,v :: valid_data(k,v,elems,data);\n\n var idx := bucket(k, data.Length);\n var opt := list_find(k, data[idx]);\n assert forall i :: 0 <= i < data.Length ==> valid_hash(data,i) && (forall k,v:: mem((k,v), data[i]) ==> (bucket(k,data.Length) == i));\n\n match opt\n case None =>\n assert forall k,v :: valid_data(k,v,elems, data) && ((k in elems && elems[k] == Some(v)) <==> (mem((k,v), data[bucket(k, data.Length)])));\n assert forall i :: 0 <= i < data.Length ==> valid_hash(data,i);\n assert forall v :: !mem((k,v),data[bucket(k,data.Length)]);\n case Some(v) =>\n assert forall k,v :: valid_data(k,v,elems,data) && ((k in elems && elems[k] == Some(v)) <==> (mem((k,v),data[bucket(k,data.Length)])));\n var idx := bucket(k, data.Length);\n data[idx] := list_remove(k, data[idx]);\n elems := elems[k := None];\n size := size - 1;\n }\n\n method add(k:K,v:V)\n requires RepInv()\n ensures RepInv()\n ensures fresh(Repr - old(Repr))\n ensures k in elems && elems[k] == Some(v)\n ensures forall key :: key != k && key in old(elems) ==> key in elems\n modifies Repr\n {\n if(size >= data.Length * 3/4) {\n resize();\n }\n\n remove(k);\n assert forall i :: 0 <= i < data.Length ==> valid_hash(data, i);\n\n var ind := bucket(k,data.Length);\n\n assert forall i :: 0 <= i < data.Length ==> valid_hash(data, i) && (forall k,v:: mem((k,v), data[i]) ==> (bucket(k,data.Length) == i));\n assert forall k,v :: valid_data(k,v,elems, data) && ((k in elems && elems[k] == Some(v)) <==> (mem((k,v), data[bucket(k, data.Length)])));\n assert forall k,v :: mem((k,v), data[ind]) ==> (bucket(k,data.Length) == ind);\n\n data[ind] := Cons((k,v), data[ind]);\n elems := elems[k := Some(v)];\n\n assert bucket(k,data.Length) == ind;\n assert mem((k,v), data[bucket(k,data.Length)]);\n\n size := size + 1;\n\n assert k in elems && elems[k] == Some(v);\n }\n\n}\n", "hints_removed": "datatype List = Nil | Cons(head:T,tail:List)\ndatatype Option = None | Some(elem:T)\n\nghost function mem(x:T,l:List) : bool {\n match l {\n case Nil => false\n case Cons(y,xs) => x==y || mem(x,xs)\n }\n}\n\nghost function length(l:List) : int {\n match l {\n case Nil => 0\n case Cons(_,xs) => 1 + length(xs)\n }\n}\n\nfunction list_find(k:K,l:List<(K,V)>) : Option\n ensures match list_find(k,l) {\n case None => forall v :: !mem((k,v),l)\n case Some(v) => mem((k,v),l)\n }\n{\n match l {\n case Nil => None\n case Cons((k',v),xs) => if k==k' then Some(v) else list_find(k,xs)\n }\n}\n\nfunction list_remove(k:K, l:List<(K,V)>) : List<(K,V)>\n ensures forall k',v :: mem((k',v),list_remove(k,l)) <==> (mem((k',v),l) && k != k')\n{\n match l {\n case Nil => Nil\n case Cons((k',v),xs) => if k==k' then list_remove(k,xs) else\n Cons((k',v),list_remove(k,xs))\n }\n}\n\n\nclass Hashtable {\n var size : int\n var data : array>\n\n ghost var Repr : set\n ghost var elems : map>\n\n ghost predicate RepInv()\n reads this, Repr\n {\n this in Repr && data in Repr && data.Length > 0 &&\n (forall i :: 0 <= i < data.Length ==> valid_hash(data, i)) &&\n (forall k,v :: valid_data(k,v,elems,data))\n }\n\n ghost predicate valid_hash(data: array>, i: int)\n requires 0 <= i < data.Length\n reads data\n {\n forall k,v :: mem((k,v), data[i]) ==> (bucket(k,data.Length) == i)\n }\n\n\n ghost predicate valid_data(k: K,v: V,elems: map>, data: array>)\n reads this, Repr, data\n requires data.Length > 0\n {\n (k in elems && elems[k] == Some(v)) <==> mem((k,v), data[bucket(k, data.Length)])\n }\n\n\n function hash(key:K) : int\n ensures hash(key) >= 0\n\n function bucket(k: K, n: int) : int\n requires n > 0\n ensures 0 <= bucket(k, n) < n\n {\n hash(k) % n\n }\n\n constructor(n:int)\n requires n > 0\n ensures RepInv()\n ensures fresh(Repr-{this})\n ensures elems == map[]\n ensures size == 0\n {\n size := 0;\n data := new List<(K,V)>[n](i => Nil);\n Repr := {this, data};\n elems := map[];\n }\n\n method clear()\n requires RepInv()\n ensures RepInv()\n ensures elems == map[]\n ensures fresh(Repr - old(Repr))\n modifies Repr\n {\n var i := 0;\n while i < data.Length\n modifies data\n {\n data[i] := Nil;\n i := i + 1;\n }\n size := 0;\n elems := map[];\n }\n\n method resize()\n requires RepInv()\n ensures RepInv()\n ensures fresh(Repr - old(Repr))\n ensures forall key :: key in old(elems) ==> key in elems\n ensures forall k,v :: k in old(elems) && old(elems)[k] == Some(v) ==> k in elems && elems[k] == Some(v)\n modifies Repr\n {\n var newData := new List<(K,V)>[data.Length * 2](i => Nil);\n var i := 0;\n var oldSize := data.Length;\n var newSize := newData.Length;\n\n\n while i < data.Length\n modifies newData\n if 0<= bucket(k, oldSize) < i then\n valid_data(k,v,elems,newData)\n else\n !mem((k,v), newData[bucket(k, newSize)]))\n {\n if 0 <= bucket(k, oldSize) < i then\n valid_data(k,v,elems,data)\n else if bucket(k, oldSize) == i then\n ((k in elems && elems[k] == Some(v))\n <==> mem((k,v), data[bucket(k,data.Length)]) || mem((k,v), newData[bucket(k, newSize)]))\n else\n !mem((k,v), newData[bucket(k, newSize)]));\n rehash(data[i],newData,i,oldSize,newSize);\n i := i + 1;\n }\n Repr := Repr - {data} + {newData};\n data := newData;\n }\n\n\n method rehash(l: List<(K,V)>, newData: array>,i: int, oldSize: int, newSize: int)\n requires newData != data\n requires 0 < oldSize == data.Length\n requires newData.Length == 2 * oldSize == newSize\n requires forall k,v :: mem((k,v), l) ==> bucket(k, oldSize) == i\n requires forall j :: 0 <= j < newSize ==> valid_hash(newData, j)\n requires forall k,v :: (\n if 0 <= bucket(k, oldSize) < i then\n valid_data(k,v,elems,newData)\n else if bucket(k, oldSize) == i then\n ((k in elems && elems[k] == Some(v))\n <==> mem((k,v), l) || mem((k,v),newData[bucket(k, newSize)]))\n else\n !mem((k,v),newData[bucket(k, newSize)]))\n ensures forall j :: 0 <= j < newSize ==> valid_hash(newData, j)\n ensures forall k,v ::\n (if 0 <= bucket(k, oldSize) <= i then\n valid_data(k,v,elems,newData)\n else\n !mem((k,v),newData[bucket(k, newSize)]))\n modifies newData\n {\n match l {\n case Nil => return;\n case Cons((k,v), r) => {\n var b := bucket(k, newSize);\n newData[b] := Cons((k,v), newData[b]);\n rehash(r, newData, i, oldSize, newSize);\n }\n }\n }\n\n method find(k: K) returns (r: Option)\n requires RepInv()\n ensures RepInv()\n ensures match r\n case None => (k !in elems || (k in elems && elems[k] == None))\n case Some(v) => (k in elems && elems[k] == Some(v))\n {\n var idx := bucket(k, data.Length);\n r := list_find(k, data[idx]);\n case None => forall v :: idx == bucket(k,data.Length) && !mem((k,v),data[idx])\n case Some(v) => mem((k,v),data[bucket(k,data.Length)]);\n }\n\n\n method remove(k: K)\n requires RepInv()\n ensures RepInv()\n ensures fresh(Repr - old(Repr))\n ensures k !in elems || elems[k] == None\n ensures forall key :: key != k && key in old(elems) ==> key in elems && elems[key] == old(elems[key])\n modifies Repr\n {\n\n var idx := bucket(k, data.Length);\n var opt := list_find(k, data[idx]);\n\n match opt\n case None =>\n case Some(v) =>\n var idx := bucket(k, data.Length);\n data[idx] := list_remove(k, data[idx]);\n elems := elems[k := None];\n size := size - 1;\n }\n\n method add(k:K,v:V)\n requires RepInv()\n ensures RepInv()\n ensures fresh(Repr - old(Repr))\n ensures k in elems && elems[k] == Some(v)\n ensures forall key :: key != k && key in old(elems) ==> key in elems\n modifies Repr\n {\n if(size >= data.Length * 3/4) {\n resize();\n }\n\n remove(k);\n\n var ind := bucket(k,data.Length);\n\n\n data[ind] := Cons((k,v), data[ind]);\n elems := elems[k := Some(v)];\n\n\n size := size + 1;\n\n }\n\n}\n" }, { "test_ID": "378", "test_file": "TFG_tmp_tmpbvsao41w_Algoritmos Dafny_div_ent_it.dfy", "ground_truth": "method div_ent_it(a: int, b: int) returns (c: int, r: int)\n\n// Algoritmo iterativo de la divisi\u00f3n de enteros\n// que calcula su cociente y resto\n\n requires a >= 0 && b > 0\n ensures a == b*c + r && 0 <= r < b\n{\n c := 0; r := a ;\n while (r >= b)\n invariant a == b * c + r && r >= 0 && b > 0\n decreases r \n {\n c := c + 1 ;\n r := r - b ;\n }\n}\n\nmethod Main()\n{\n var c, r := div_ent_it(6 , 2) ;\n print \"Cociente: \", c, \", Resto: \", r ;\n}\n", "hints_removed": "method div_ent_it(a: int, b: int) returns (c: int, r: int)\n\n// Algoritmo iterativo de la divisi\u00f3n de enteros\n// que calcula su cociente y resto\n\n requires a >= 0 && b > 0\n ensures a == b*c + r && 0 <= r < b\n{\n c := 0; r := a ;\n while (r >= b)\n {\n c := c + 1 ;\n r := r - b ;\n }\n}\n\nmethod Main()\n{\n var c, r := div_ent_it(6 , 2) ;\n print \"Cociente: \", c, \", Resto: \", r ;\n}\n" }, { "test_ID": "379", "test_file": "TFG_tmp_tmpbvsao41w_Algoritmos Dafny_suma_it.dfy", "ground_truth": "method suma_it(V: array) returns (x: int)\n\n// Algoritmo iterativo que calcula la\n// suma de las componentes de un vector\n\n ensures x == suma_vector(V, 0)\n{\n var n := V.Length ;\n x := 0 ;\n while (n != 0)\n invariant 0 <= n <= V.Length && x == suma_vector(V, n)\n decreases n\n {\n x := x + V[n - 1] ;\n n := n - 1 ;\n }\n}\n\n\nfunction suma_vector(V: array, n: nat): int\n\n// x = V[n] + V[n + 1] + ... + V[N - 1]\n// Funcion auxiliar para la suma de\n// las componentes de un vector\n\n requires 0 <= n <= V.Length \n decreases V.Length - n \n reads V \n{ \n if (n == V.Length) then 0 \n else V[n] + suma_vector(V, n + 1) \n}\n\nmethod Main()\n{\n var v := new int[] [-1, 2, 5, -5, 8] ;\n var w := new int[] [ 1, 0, 5, 5, 8] ;\n var s1 := suma_it(v) ;\n var s2 := suma_it(w) ;\n\n print \"La suma del vector v es: \", s1, \"\\n\" ;\n print \"La suma del vector w es: \", s2 ;\n}\n", "hints_removed": "method suma_it(V: array) returns (x: int)\n\n// Algoritmo iterativo que calcula la\n// suma de las componentes de un vector\n\n ensures x == suma_vector(V, 0)\n{\n var n := V.Length ;\n x := 0 ;\n while (n != 0)\n {\n x := x + V[n - 1] ;\n n := n - 1 ;\n }\n}\n\n\nfunction suma_vector(V: array, n: nat): int\n\n// x = V[n] + V[n + 1] + ... + V[N - 1]\n// Funcion auxiliar para la suma de\n// las componentes de un vector\n\n requires 0 <= n <= V.Length \n reads V \n{ \n if (n == V.Length) then 0 \n else V[n] + suma_vector(V, n + 1) \n}\n\nmethod Main()\n{\n var v := new int[] [-1, 2, 5, -5, 8] ;\n var w := new int[] [ 1, 0, 5, 5, 8] ;\n var s1 := suma_it(v) ;\n var s2 := suma_it(w) ;\n\n print \"La suma del vector v es: \", s1, \"\\n\" ;\n print \"La suma del vector w es: \", s2 ;\n}\n" }, { "test_ID": "380", "test_file": "Trab1-Metodos-Formais_tmp_tmp_8fa4trr_circular-array.dfy", "ground_truth": "/*\n Class CircularArray.\n\n Names:\n Arthur Sudbrack Ibarra,\n Miguel Torres de Castro,\n Felipe Grosze Nipper,\n Willian Magnum Albeche,\n Luiz Eduardo Mello dos Reis.\n*/\nclass {:autocontracts} CircularArray {\n /*\n Implementation\n */\n var arr: array; // The array.\n var start: nat; // The index of the first element.\n var size: nat; // The number of elements in the queue.\n\n /*\n Abstraction.\n */\n ghost const Capacity: nat; // The capacity of the queue. (WE WERE UNABLE TO MAKE THE SIZE OF THE ARRAY DYNAMIC).\n ghost var Elements: seq; // The elements in the array represented as a sequence.\n\n /*\n Class invariant.\n */\n ghost predicate Valid()\n {\n 0 <= start < arr.Length &&\n 0 <= size <= arr.Length &&\n Capacity == arr.Length &&\n Elements == if start + size <= arr.Length\n then arr[start..start + size]\n else arr[start..] + arr[..size - (arr.Length - start)]\n }\n\n /*\n Constructor.\n */\n constructor EmptyQueue(capacity: nat)\n requires capacity > 0\n ensures Elements == []\n ensures Capacity == capacity\n {\n arr := new int[capacity];\n start := 0;\n size := 0;\n Capacity := capacity;\n Elements := [];\n }\n\n /*\n Enqueue Method\n */\n method Enqueue(e: int)\n requires !IsFull()\n ensures Elements == old(Elements) + [e]\n {\n arr[(start + size) % arr.Length] := e;\n size := size + 1;\n Elements := Elements + [e];\n }\n\n /*\n Dequeue method.\n */\n method Dequeue() returns (e: int)\n requires !IsEmpty()\n ensures Elements == old(Elements)[1..]\n ensures e == old(Elements)[0]\n {\n e := arr[start];\n if start + 1 < arr.Length {\n start := start + 1;\n }\n else {\n start := 0;\n }\n size := size - 1;\n Elements := Elements[1..];\n }\n\n /*\n Contains predicate.\n */\n predicate Contains(e: int)\n ensures Contains(e) == (e in Elements)\n {\n if start + size < arr.Length then\n e in arr[start..start + size]\n else\n e in arr[start..] + arr[..size - (arr.Length - start)]\n }\n\n /*\n Size function.\n */\n function Size(): nat\n ensures Size() == |Elements|\n {\n size\n }\n\n /*\n IsEmpty predicate.\n */\n predicate IsEmpty()\n ensures IsEmpty() <==> (|Elements| == 0)\n {\n size == 0\n }\n\n /*\n IsFull predicate.\n */\n predicate IsFull()\n ensures IsFull() <==> |Elements| == Capacity\n {\n size == arr.Length\n }\n\n /*\n GetAt method.\n (Not requested in the assignment, but useful).\n */\n method GetAt(i: nat) returns (e: int)\n requires i < size\n ensures e == Elements[i]\n {\n e := arr[(start + i) % arr.Length];\n }\n\n /*\n AsSequence method.\n (Auxiliary method for the Concatenate method)\n */\n method AsSequence() returns (s: seq)\n ensures s == Elements\n {\n s := if start + size <= arr.Length\n then arr[start..start + size]\n else arr[start..] + arr[..size - (arr.Length - start)];\n }\n\n /*\n Concatenate method.\n */\n method Concatenate(q1: CircularArray) returns(q2: CircularArray)\n requires q1.Valid()\n requires q1 != this\n ensures fresh(q2)\n ensures q2.Capacity == Capacity + q1.Capacity\n ensures q2.Elements == Elements + q1.Elements\n {\n q2 := new CircularArray.EmptyQueue(arr.Length + q1.arr.Length);\n var s1 := AsSequence();\n var s2 := q1.AsSequence();\n var both := s1 + s2;\n forall i | 0 <= i < size\n {\n q2.arr[i] := both[i];\n }\n q2.size := size + q1.size;\n q2.start := 0;\n q2.Elements := Elements + q1.Elements;\n \n print q2.arr.Length;\n print q2.size;\n }\n}\n\n/*\n Main method.\n Here the the CircularArray class is demonstrated.\n*/\nmethod Main()\n{\n var q := new CircularArray.EmptyQueue(10); // Create a new queue.\n assert q.IsEmpty(); // The queue must be empty.\n\n q.Enqueue(1); // Enqueue the element 1.\n assert !q.IsEmpty(); // The queue must now not be empty.\n assert q.Size() == 1; // The queue must have size 1 after the enqueue.\n assert q.Contains(1); // The queue must contain the element 1.\n var e1 := q.GetAt(0); // Get the element at index 0.\n assert e1 == 1; // The element at index 0 must be 1.\n\n q.Enqueue(2); // Enqueue the element 2.\n assert q.Size() == 2; // The queue must have size 2 after the enqueue.\n assert q.Contains(2); // The queue must contain the element 2.\n var e2 := q.GetAt(1); // Get the element at index 1.\n assert e2 == 2; // The element at index 1 must be 2.\n\n var e := q.Dequeue(); // Dequeue the element 1.\n assert e == 1; // The dequeued element must be 1.\n assert q.Size() == 1; // The queue must have size 1 after the dequeue.\n assert !q.Contains(1); // The queue must NOT contain the element 1 anymore.\n\n q.Enqueue(3); // Enqueue the element 3.\n assert q.Size() == 2; // The queue must have size 2 after the enqueue.\n assert q.Contains(3); // The queue must contain the element 3.\n\n e := q.Dequeue(); // Dequeue the element 2.\n assert e == 2; // The dequeued element must be 2.\n assert q.Size() == 1; // The queue must have size 1 after the dequeue.\n assert !q.Contains(2); // The queue must NOT contain the element 2 anymore.\n\n e := q.Dequeue(); // Dequeue the element 3.\n assert e == 3; // The dequeued element must be 3.\n assert q.Size() == 0; // The queue must have size 0 after the dequeue.\n assert !q.Contains(3); // The queue must NOT contain the element 3 anymore.\n\n assert q.IsEmpty(); // The queue must now be empty.\n assert q.Size() == 0; // The queue must now have size 0.\n}\n\n", "hints_removed": "/*\n Class CircularArray.\n\n Names:\n Arthur Sudbrack Ibarra,\n Miguel Torres de Castro,\n Felipe Grosze Nipper,\n Willian Magnum Albeche,\n Luiz Eduardo Mello dos Reis.\n*/\nclass {:autocontracts} CircularArray {\n /*\n Implementation\n */\n var arr: array; // The array.\n var start: nat; // The index of the first element.\n var size: nat; // The number of elements in the queue.\n\n /*\n Abstraction.\n */\n ghost const Capacity: nat; // The capacity of the queue. (WE WERE UNABLE TO MAKE THE SIZE OF THE ARRAY DYNAMIC).\n ghost var Elements: seq; // The elements in the array represented as a sequence.\n\n /*\n Class invariant.\n */\n ghost predicate Valid()\n {\n 0 <= start < arr.Length &&\n 0 <= size <= arr.Length &&\n Capacity == arr.Length &&\n Elements == if start + size <= arr.Length\n then arr[start..start + size]\n else arr[start..] + arr[..size - (arr.Length - start)]\n }\n\n /*\n Constructor.\n */\n constructor EmptyQueue(capacity: nat)\n requires capacity > 0\n ensures Elements == []\n ensures Capacity == capacity\n {\n arr := new int[capacity];\n start := 0;\n size := 0;\n Capacity := capacity;\n Elements := [];\n }\n\n /*\n Enqueue Method\n */\n method Enqueue(e: int)\n requires !IsFull()\n ensures Elements == old(Elements) + [e]\n {\n arr[(start + size) % arr.Length] := e;\n size := size + 1;\n Elements := Elements + [e];\n }\n\n /*\n Dequeue method.\n */\n method Dequeue() returns (e: int)\n requires !IsEmpty()\n ensures Elements == old(Elements)[1..]\n ensures e == old(Elements)[0]\n {\n e := arr[start];\n if start + 1 < arr.Length {\n start := start + 1;\n }\n else {\n start := 0;\n }\n size := size - 1;\n Elements := Elements[1..];\n }\n\n /*\n Contains predicate.\n */\n predicate Contains(e: int)\n ensures Contains(e) == (e in Elements)\n {\n if start + size < arr.Length then\n e in arr[start..start + size]\n else\n e in arr[start..] + arr[..size - (arr.Length - start)]\n }\n\n /*\n Size function.\n */\n function Size(): nat\n ensures Size() == |Elements|\n {\n size\n }\n\n /*\n IsEmpty predicate.\n */\n predicate IsEmpty()\n ensures IsEmpty() <==> (|Elements| == 0)\n {\n size == 0\n }\n\n /*\n IsFull predicate.\n */\n predicate IsFull()\n ensures IsFull() <==> |Elements| == Capacity\n {\n size == arr.Length\n }\n\n /*\n GetAt method.\n (Not requested in the assignment, but useful).\n */\n method GetAt(i: nat) returns (e: int)\n requires i < size\n ensures e == Elements[i]\n {\n e := arr[(start + i) % arr.Length];\n }\n\n /*\n AsSequence method.\n (Auxiliary method for the Concatenate method)\n */\n method AsSequence() returns (s: seq)\n ensures s == Elements\n {\n s := if start + size <= arr.Length\n then arr[start..start + size]\n else arr[start..] + arr[..size - (arr.Length - start)];\n }\n\n /*\n Concatenate method.\n */\n method Concatenate(q1: CircularArray) returns(q2: CircularArray)\n requires q1.Valid()\n requires q1 != this\n ensures fresh(q2)\n ensures q2.Capacity == Capacity + q1.Capacity\n ensures q2.Elements == Elements + q1.Elements\n {\n q2 := new CircularArray.EmptyQueue(arr.Length + q1.arr.Length);\n var s1 := AsSequence();\n var s2 := q1.AsSequence();\n var both := s1 + s2;\n forall i | 0 <= i < size\n {\n q2.arr[i] := both[i];\n }\n q2.size := size + q1.size;\n q2.start := 0;\n q2.Elements := Elements + q1.Elements;\n \n print q2.arr.Length;\n print q2.size;\n }\n}\n\n/*\n Main method.\n Here the the CircularArray class is demonstrated.\n*/\nmethod Main()\n{\n var q := new CircularArray.EmptyQueue(10); // Create a new queue.\n\n q.Enqueue(1); // Enqueue the element 1.\n var e1 := q.GetAt(0); // Get the element at index 0.\n\n q.Enqueue(2); // Enqueue the element 2.\n var e2 := q.GetAt(1); // Get the element at index 1.\n\n var e := q.Dequeue(); // Dequeue the element 1.\n\n q.Enqueue(3); // Enqueue the element 3.\n\n e := q.Dequeue(); // Dequeue the element 2.\n\n e := q.Dequeue(); // Dequeue the element 3.\n\n}\n\n" }, { "test_ID": "381", "test_file": "VerifiedMergeSortDafny_tmp_tmpva7qms1b_MergeSort.dfy", "ground_truth": "method mergeSimple(a1: seq, a2: seq, start: int, end: int, b: array)\n modifies b\n requires sorted_seq(a1)\n requires sorted_seq(a2)\n requires 0 <= start <= end <= b.Length\n requires |a1| + |a2| == end - start + 1\n ensures sorted_slice(b, start, end)\n{\n var a1Pos := 0;\n var a2Pos := 0;\n var k := start;\n\n while k < end\n invariant (0 <= k && k <= end)\n invariant sorted_slice(b, start, k)\n invariant (|a1| - a1Pos) + (|a2| - a2Pos) == end - k + 1\n invariant 0 <= a1Pos <= |a1|\n invariant 0 <= a2Pos <= |a2|\n invariant forall i :: start <= i < k && a1Pos < |a1| ==> b[i] <= a1[a1Pos]\n invariant forall i :: start <= i < k && a2Pos < |a2| ==> b[i] <= a2[a2Pos]\n {\n if a1Pos < |a1| && a2Pos < |a2| && a1[a1Pos] <= a2[a2Pos] {\n b[k] := a1[a1Pos];\n a1Pos := a1Pos + 1;\n } else if a1Pos < |a1| && a2Pos < |a2| && a1[a1Pos] > a2[a2Pos] {\n b[k] := a2[a2Pos];\n a2Pos := a2Pos + 1;\n } else if a1Pos < |a1| {\n assert(a2Pos >= |a2|);\n b[k] := a1[a1Pos];\n a1Pos := a1Pos + 1;\n } else {\n assert(a1Pos >= |a1|);\n b[k] := a2[a2Pos];\n a2Pos := a2Pos + 1;\n }\n k := k + 1;\n }\n}\n\nmethod merge(a1: seq, a2: seq, start: int, end: int, b: array)\n modifies b\n requires sorted_seq(a1)\n requires sorted_seq(a2)\n requires end - start == |a1| + |a2|\n requires 0 <= start < end < |a1| && end <= |a2| < b.Length\n requires end < |a1| && end < |a2|\n ensures sorted_slice(b, start, end)\n requires b.Length == |a2| + |a1|\n ensures merged(a1, a2, b, start, end)\n{\n assert forall xs : seq :: xs[0..|xs|] == xs;\n assert forall xs : seq, a,b : int :: 0 <= a < b < |xs| ==> xs[a..b+1] == xs[a..b] + [xs[b]];\n var a1Pos := 0;\n var a2Pos := 0;\n var k := start;\n while k < end\n invariant (0 <= k && k <= end)\n invariant sorted_slice(b, start, k)\n invariant (|a1| - a1Pos) + (|a2| - a2Pos) == end - k\n invariant 0 <= a1Pos <= |a1|\n invariant 0 <= a2Pos <= |a2|\n invariant forall i :: start <= i < k && a1Pos < |a1| ==> b[i] <= a1[a1Pos]\n invariant forall i :: start <= i < k && a2Pos < |a2| ==> b[i] <= a2[a2Pos]\n invariant merged(a1[0..a1Pos], a2[0..a2Pos], b, start, k)\n {\n if a1Pos < |a1| && a2Pos < |a2| && a1[a1Pos] <= a2[a2Pos] {\n b[k] := a1[a1Pos];\n a1Pos := a1Pos + 1;\n } else if a1Pos < |a1| && a2Pos < |a2| && a1[a1Pos] > a2[a2Pos] {\n b[k] := a2[a2Pos];\n a2Pos := a2Pos + 1;\n } else if a1Pos < |a1| {\n assert(a2Pos >= |a2|);\n b[k] := a1[a1Pos];\n a1Pos := a1Pos + 1;\n } else {\n assert(a1Pos >= |a1|);\n b[k] := a2[a2Pos];\n a2Pos := a2Pos + 1;\n }\n k := k + 1;\n }\n}\n\n\npredicate merged(a1: seq, a2: seq, b: array, start: int, end: int)\n reads b\n requires end - start == |a2| + |a1|\n requires 0 <= start <= end <= b.Length\n{\n multiset(a1) + multiset(a2) == multiset(b[start..end])\n}\n\npredicate sorted_slice(a: array, start: int, end: int)\n requires 0 <= start <= end <= a.Length\n reads a\n{\n forall i, j :: start <= i <= j < end ==> a[i] <= a[j]\n}\n\npredicate sorted_seq(a: seq)\n{\n forall i, j :: 0 <= i <= j < |a| ==> a[i] <= a[j]\n}\n\npredicate sorted(a: array)\n reads a\n{\n forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j]\n}\n\n", "hints_removed": "method mergeSimple(a1: seq, a2: seq, start: int, end: int, b: array)\n modifies b\n requires sorted_seq(a1)\n requires sorted_seq(a2)\n requires 0 <= start <= end <= b.Length\n requires |a1| + |a2| == end - start + 1\n ensures sorted_slice(b, start, end)\n{\n var a1Pos := 0;\n var a2Pos := 0;\n var k := start;\n\n while k < end\n {\n if a1Pos < |a1| && a2Pos < |a2| && a1[a1Pos] <= a2[a2Pos] {\n b[k] := a1[a1Pos];\n a1Pos := a1Pos + 1;\n } else if a1Pos < |a1| && a2Pos < |a2| && a1[a1Pos] > a2[a2Pos] {\n b[k] := a2[a2Pos];\n a2Pos := a2Pos + 1;\n } else if a1Pos < |a1| {\n b[k] := a1[a1Pos];\n a1Pos := a1Pos + 1;\n } else {\n b[k] := a2[a2Pos];\n a2Pos := a2Pos + 1;\n }\n k := k + 1;\n }\n}\n\nmethod merge(a1: seq, a2: seq, start: int, end: int, b: array)\n modifies b\n requires sorted_seq(a1)\n requires sorted_seq(a2)\n requires end - start == |a1| + |a2|\n requires 0 <= start < end < |a1| && end <= |a2| < b.Length\n requires end < |a1| && end < |a2|\n ensures sorted_slice(b, start, end)\n requires b.Length == |a2| + |a1|\n ensures merged(a1, a2, b, start, end)\n{\n var a1Pos := 0;\n var a2Pos := 0;\n var k := start;\n while k < end\n {\n if a1Pos < |a1| && a2Pos < |a2| && a1[a1Pos] <= a2[a2Pos] {\n b[k] := a1[a1Pos];\n a1Pos := a1Pos + 1;\n } else if a1Pos < |a1| && a2Pos < |a2| && a1[a1Pos] > a2[a2Pos] {\n b[k] := a2[a2Pos];\n a2Pos := a2Pos + 1;\n } else if a1Pos < |a1| {\n b[k] := a1[a1Pos];\n a1Pos := a1Pos + 1;\n } else {\n b[k] := a2[a2Pos];\n a2Pos := a2Pos + 1;\n }\n k := k + 1;\n }\n}\n\n\npredicate merged(a1: seq, a2: seq, b: array, start: int, end: int)\n reads b\n requires end - start == |a2| + |a1|\n requires 0 <= start <= end <= b.Length\n{\n multiset(a1) + multiset(a2) == multiset(b[start..end])\n}\n\npredicate sorted_slice(a: array, start: int, end: int)\n requires 0 <= start <= end <= a.Length\n reads a\n{\n forall i, j :: start <= i <= j < end ==> a[i] <= a[j]\n}\n\npredicate sorted_seq(a: seq)\n{\n forall i, j :: 0 <= i <= j < |a| ==> a[i] <= a[j]\n}\n\npredicate sorted(a: array)\n reads a\n{\n forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j]\n}\n\n" }, { "test_ID": "382", "test_file": "Workshop_tmp_tmp0cu11bdq_Lecture_Answers_max_array.dfy", "ground_truth": "// http://verifythus.cost-ic0701.org/common-example/arraymax-in-dafny\n\nmethod max(a:array) returns(max:int)\n requires a != null;\n ensures forall j :: j >= 0 && j < a.Length ==> max >= a[j]; //max is larger then anything in the array\n ensures a.Length > 0 ==> exists j :: j >= 0 && j < a.Length && max == a[j]; //max is an element in the array\n{\n if (a.Length == 0) { \n max := 0;\n return;\n }\n\n max := a[0];\n var i := 1;\n\n while i < a.Length\n invariant i <= a.Length //i is bounded by the array\n invariant forall j :: 0 <= j < i ==> max >= a[j] //max is bigger or equal to anything seen so far (up to j)\n invariant exists j :: 0 <= j < i && max==a[j] //max exists somewhere in the seen portion of the array\n {\n if a[i] > max\n {\n max := a[i];\n }\n i := i + 1;\n }\n \n} \n", "hints_removed": "// http://verifythus.cost-ic0701.org/common-example/arraymax-in-dafny\n\nmethod max(a:array) returns(max:int)\n requires a != null;\n ensures forall j :: j >= 0 && j < a.Length ==> max >= a[j]; //max is larger then anything in the array\n ensures a.Length > 0 ==> exists j :: j >= 0 && j < a.Length && max == a[j]; //max is an element in the array\n{\n if (a.Length == 0) { \n max := 0;\n return;\n }\n\n max := a[0];\n var i := 1;\n\n while i < a.Length\n {\n if a[i] > max\n {\n max := a[i];\n }\n i := i + 1;\n }\n \n} \n" }, { "test_ID": "383", "test_file": "Workshop_tmp_tmp0cu11bdq_Lecture_Answers_selection_sort.dfy", "ground_truth": "//https://homepage.cs.uiowa.edu/~tinelli/classes/181/Fall21/Tools/Dafny/Examples/selection-sort.shtml\n\npredicate sorted (a: array)\n\trequires a != null\n\treads a\n{\n\tsorted'(a, a.Length)\n}\n\npredicate sorted' (a: array, i: int)\n\trequires a != null\n\trequires 0 <= i <= a.Length\n\treads a\n{\n\tforall k :: 0 < k < i ==> a[k-1] <= a[k]\n}\n\n\n// Selection sort on arrays\n\nmethod SelectionSort(a: array) \n modifies a\n ensures sorted(a)\n //ensures multiset(old(a[..])) == multiset(a[..])\n{\n var n := 0;\n while (n != a.Length)\n invariant 0 <= n <= a.Length\n invariant forall i, j :: 0 <= i < n <= j < a.Length ==> a[i] <= a[j] //all the values in the sorted section will be lower then any value in the non sorted section \n invariant forall k1, k2 :: 0 <= k1 < k2 < n ==> a[k1] <= a[k2] //all values in the sorted section are sorted with respect to one another\n {\n var mindex := n;\n var m := n + 1;\n while (m != a.Length)\n invariant n <= m <= a.Length //m (search idx) between valid range\n invariant n <= mindex < m <= a.Length // minIndex between valid range\n invariant forall i :: n <= i < m ==> a[mindex] <= a[i] //mindex is current smallest in range n < m\n {\n if (a[m] < a[mindex]) {\n mindex := m;\n }\n m := m + 1;\n }\n a[n], a[mindex] := a[mindex], a[n];\n n := n + 1;\n }\n}\n", "hints_removed": "//https://homepage.cs.uiowa.edu/~tinelli/classes/181/Fall21/Tools/Dafny/Examples/selection-sort.shtml\n\npredicate sorted (a: array)\n\trequires a != null\n\treads a\n{\n\tsorted'(a, a.Length)\n}\n\npredicate sorted' (a: array, i: int)\n\trequires a != null\n\trequires 0 <= i <= a.Length\n\treads a\n{\n\tforall k :: 0 < k < i ==> a[k-1] <= a[k]\n}\n\n\n// Selection sort on arrays\n\nmethod SelectionSort(a: array) \n modifies a\n ensures sorted(a)\n //ensures multiset(old(a[..])) == multiset(a[..])\n{\n var n := 0;\n while (n != a.Length)\n {\n var mindex := n;\n var m := n + 1;\n while (m != a.Length)\n {\n if (a[m] < a[mindex]) {\n mindex := m;\n }\n m := m + 1;\n }\n a[n], a[mindex] := a[mindex], a[n];\n n := n + 1;\n }\n}\n" }, { "test_ID": "384", "test_file": "Workshop_tmp_tmp0cu11bdq_Lecture_Answers_sum_array.dfy", "ground_truth": "function sumTo( a:array, n:int ) : int\n requires a != null;\n requires 0 <= n && n <= a.Length;\n reads a;\n{\n if (n == 0) then 0 else sumTo(a, n-1) + a[n-1]\n}\n\nmethod sum_array( a: array) returns (sum: int)\n requires a != null;\n ensures sum == sumTo(a, a.Length);\n{\n var i := 0;\n sum := 0;\n while (i < a.Length)\n invariant 0 <= i <= a.Length;\n invariant sum == sumTo(a, i);\n {\n sum := sum + a[i];\n i := i + 1;\n }\n}\n\n", "hints_removed": "function sumTo( a:array, n:int ) : int\n requires a != null;\n requires 0 <= n && n <= a.Length;\n reads a;\n{\n if (n == 0) then 0 else sumTo(a, n-1) + a[n-1]\n}\n\nmethod sum_array( a: array) returns (sum: int)\n requires a != null;\n ensures sum == sumTo(a, a.Length);\n{\n var i := 0;\n sum := 0;\n while (i < a.Length)\n {\n sum := sum + a[i];\n i := i + 1;\n }\n}\n\n" }, { "test_ID": "385", "test_file": "Workshop_tmp_tmp0cu11bdq_Lecture_Answers_triangle_number.dfy", "ground_truth": "method TriangleNumber(N: int) returns (t: int)\n requires N >= 0\n ensures t == N * (N + 1) / 2\n{\n t := 0;\n var n := 0;\n while n < N\n invariant 0 <= n <= N\n invariant t == n * (n + 1) / 2\n decreases N - n;// can be left out because it is guessed correctly by Dafny\n {\n n:= n + 1;\n t := t + n;\n }\n}\n", "hints_removed": "method TriangleNumber(N: int) returns (t: int)\n requires N >= 0\n ensures t == N * (N + 1) / 2\n{\n t := 0;\n var n := 0;\n while n < N\n {\n n:= n + 1;\n t := t + n;\n }\n}\n" }, { "test_ID": "386", "test_file": "Workshop_tmp_tmp0cu11bdq_Workshop_Answers_Question5.dfy", "ground_truth": "method rev(a : array)\n requires a != null;\n modifies a;\n ensures forall k :: 0 <= k < a.Length ==> a[k] == old(a[(a.Length - 1) - k]);\n{\n var i := 0;\n while (i < a.Length - 1 - i)\n invariant 0 <= i <= a.Length/2;\n invariant forall k :: 0 <= k < i || a.Length - 1 - i < k <= a.Length - 1 ==> a[k] == old(a[a.Length - 1 - k]); //The reversed region contains the opposing values\n\t\tinvariant forall k :: i <= k <= a.Length - 1 - i ==> a[k] == old(a[k]); // The non reversed region contains the original values\n {\n a[i], a[a.Length - 1 - i] := a[a.Length - 1 - i], a[i];\n i := i + 1;\n }\n}\n", "hints_removed": "method rev(a : array)\n requires a != null;\n modifies a;\n ensures forall k :: 0 <= k < a.Length ==> a[k] == old(a[(a.Length - 1) - k]);\n{\n var i := 0;\n while (i < a.Length - 1 - i)\n {\n a[i], a[a.Length - 1 - i] := a[a.Length - 1 - i], a[i];\n i := i + 1;\n }\n}\n" }, { "test_ID": "387", "test_file": "Workshop_tmp_tmp0cu11bdq_Workshop_Answers_Question6.dfy", "ground_truth": "method arrayUpToN(n: int) returns (a: array)\n requires n >= 0\n ensures a.Length == n\n ensures forall j :: 0 < j < n ==> a[j] >= 0\n ensures forall j, k : int :: 0 <= j <= k < n ==> a[j] <= a[k]\n{\n var i := 0;\n a := new int[n];\n while i < n\n invariant 0 <= i <= n\n invariant forall k :: 0 <= k < i ==> a[k] >= 0\n invariant forall k :: 0 <= k < i ==> a[k] == k\n invariant forall j, k :: 0 <= j <= k < i ==> a[j] <= a[k]\n {\n a[i] := i;\n i := i + 1;\n }\n}\n", "hints_removed": "method arrayUpToN(n: int) returns (a: array)\n requires n >= 0\n ensures a.Length == n\n ensures forall j :: 0 < j < n ==> a[j] >= 0\n ensures forall j, k : int :: 0 <= j <= k < n ==> a[j] <= a[k]\n{\n var i := 0;\n a := new int[n];\n while i < n\n {\n a[i] := i;\n i := i + 1;\n }\n}\n" }, { "test_ID": "388", "test_file": "WrappedEther.dfy", "ground_truth": "/*\n * Copyright 2022 ConsenSys Software Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n * not use this file except in compliance with the License. You may obtain\n * a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software dis-\n * tributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n */\nmodule Int {\n const TWO_7 : int := 0x0_80\n const TWO_8 : int := 0x1_00\n const TWO_15 : int := 0x0_8000\n const TWO_16 : int := 0x1_0000\n const TWO_24 : int := 0x1_0000_00\n const TWO_31 : int := 0x0_8000_0000\n const TWO_32 : int := 0x1_0000_0000\n const TWO_40 : int := 0x1_0000_0000_00\n const TWO_48 : int := 0x1_0000_0000_0000\n const TWO_56 : int := 0x1_0000_0000_0000_00\n const TWO_63 : int := 0x0_8000_0000_0000_0000\n const TWO_64 : int := 0x1_0000_0000_0000_0000\n const TWO_127 : int := 0x0_8000_0000_0000_0000_0000_0000_0000_0000\n const TWO_128 : int := 0x1_0000_0000_0000_0000_0000_0000_0000_0000\n const TWO_160 : int := 0x1_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000\n const TWO_255 : int := 0x0_8000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000\n const TWO_256 : int := 0x1_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000\n\n // Signed Integers\n const MIN_I8 : int := -TWO_7\n const MAX_I8 : int := TWO_7 - 1\n const MIN_I16 : int := -TWO_15\n const MAX_I16 : int := TWO_15 - 1\n const MIN_I32 : int := -TWO_31\n const MAX_I32 : int := TWO_31 - 1\n const MIN_I64 : int := -TWO_63\n const MAX_I64 : int := TWO_63 - 1\n const MIN_I128 : int := -TWO_127\n const MAX_I128 : int := TWO_127 - 1\n const MIN_I256 : int := -TWO_255\n const MAX_I256 : int := TWO_255 - 1\n\n newtype{:nativeType \"sbyte\"} i8 = i:int | MIN_I8 <= i <= MAX_I8\n newtype{:nativeType \"short\"} i16 = i:int | MIN_I16 <= i <= MAX_I16\n newtype{:nativeType \"int\"} i32 = i:int | MIN_I32 <= i <= MAX_I32\n newtype{:nativeType \"long\"} i64 = i:int | MIN_I64 <= i <= MAX_I64\n newtype i128 = i:int | MIN_I128 <= i <= MAX_I128\n newtype i256 = i:int | MIN_I256 <= i <= MAX_I256\n\n // Unsigned Integers\n const MAX_U8 : int := TWO_8 - 1\n const MAX_U16 : int := TWO_16 - 1\n const MAX_U24 : int := TWO_24 - 1\n const MAX_U32 : int := TWO_32 - 1\n const MAX_U40 : int := TWO_40 - 1\n const MAX_U48 : int := TWO_48 - 1\n const MAX_U56 : int := TWO_56 - 1\n const MAX_U64 : int := TWO_64 - 1\n const MAX_U128 : int := TWO_128 - 1\n const MAX_U160: int := TWO_160 - 1\n const MAX_U256: int := TWO_256 - 1\n\n newtype{:nativeType \"byte\"} u8 = i:int | 0 <= i <= MAX_U8\n newtype{:nativeType \"ushort\"} u16 = i:int | 0 <= i <= MAX_U16\n newtype{:nativeType \"uint\"} u24 = i:int | 0 <= i <= MAX_U24\n newtype{:nativeType \"uint\"} u32 = i:int | 0 <= i <= MAX_U32\n newtype{:nativeType \"ulong\"} u40 = i:int | 0 <= i <= MAX_U40\n newtype{:nativeType \"ulong\"} u48 = i:int | 0 <= i <= MAX_U48\n newtype{:nativeType \"ulong\"} u56 = i:int | 0 <= i <= MAX_U56\n newtype{:nativeType \"ulong\"} u64 = i:int | 0 <= i <= MAX_U64\n newtype u128 = i:int | 0 <= i <= MAX_U128\n newtype u160 = i:int | 0 <= i <= MAX_U160\n newtype u256 = i:int | 0 <= i <= MAX_U256\n\n\n // Determine maximum of two u256 integers.\n function Max(i1: int, i2: int) : int {\n if i1 >= i2 then i1 else i2\n }\n\n // Determine maximum of two u256 integers.\n function Min(i1: int, i2: int) : int {\n if i1 < i2 then i1 else i2\n }\n\n // Round up a given number (i) by a given multiple (r).\n function RoundUp(i: int, r: nat) : int\n requires r > 0 {\n if (i % r) == 0 then i\n else\n ((i/r)*r) + r\n }\n\n // Return the maximum value representable using exactly n unsigned bytes.\n // This is essentially computing (2^n - 1). However, the point of doing it\n // in this fashion is to avoid using Pow() as this is challenging for the\n // verifier.\n function MaxUnsignedN(n:nat) : (r:nat)\n requires 1 <= n <= 32 {\n match n\n case 1 => MAX_U8\n case 2 => MAX_U16\n case 3 => MAX_U24\n case 4 => MAX_U32\n case 5 => MAX_U40\n case 6 => MAX_U48\n case 7 => MAX_U56\n case 8 => MAX_U64\n case 16 => MAX_U128\n case 20 => MAX_U160\n case 32 => MAX_U256\n // Fall back case (for now)\n case _ =>\n Pow(2,n) - 1\n }\n\n\n // =========================================================\n // Exponent\n // =========================================================\n\n /**\n * Compute n^k.\n */\n function Pow(n:nat, k:nat) : (r:nat)\n // Following needed for some proofs\n ensures n > 0 ==> r > 0 {\n if k == 0 then 1\n else if k == 1 then n\n else\n var p := k / 2;\n var np := Pow(n,p);\n if p*2 == k then np * np\n else np * np * n\n }\n\n // Simple lemma about POW.\n lemma lemma_pow2(k:nat)\n ensures Pow(2,k) > 0 {\n if k == 0 {\n assert Pow(2,k) == 1;\n } else if k == 1 {\n assert Pow(2,k) == 2;\n } else {\n lemma_pow2(k/2);\n }\n }\n\n // =========================================================\n // Non-Euclidean Division / Remainder\n // =========================================================\n\n // This provides a non-Euclidean division operator and is necessary\n // because Dafny (unlike just about every other programming\n // language) supports Euclidean division. This operator, therefore,\n // always divides *towards* zero.\n function Div(lhs: int, rhs: int) : int\n requires rhs != 0 {\n if lhs >= 0 then lhs / rhs\n else\n -((-lhs) / rhs)\n }\n\n // This provides a non-Euclidean Remainder operator and is necessary\n // because Dafny (unlike just about every other programming\n // language) supports Euclidean division. Observe that this is a\n // true Remainder operator, and not a modulus operator. For\n // emxaple, this means the result can be negative.\n function Rem(lhs: int, rhs: int) : int\n requires rhs != 0 {\n if lhs >= 0 then (lhs % rhs)\n else\n var d := -((-lhs) / rhs);\n lhs - (d * rhs)\n }\n}\n\n/**\n * Various helper methods related to unsigned 8bit integers.\n */\nmodule U8 {\n import opened Int\n // Compute the log of a value at base 2 where the result is rounded down.\n function Log2(v:u8) : (r:nat)\n ensures r < 8 {\n // Split 4 bits\n if v <= 15 then\n // Split 2 bits\n if v <= 3 then\n // Split 1 bit\n if v <= 1 then 0 else 1\n else\n // Split 1 bit\n if v <= 7 then 2 else 3\n else\n // Split 2 bits\n if v <= 63 then\n // Split 1 bit\n if v <= 31 then 4 else 5\n else\n // Split 1 bit\n if v <= 127 then 6 else 7\n }\n}\n\n/**\n * Various helper methods related to unsigned 16bit integers.\n */\nmodule U16 {\n import opened Int\n import U8\n\n // Read nth 8bit word (i.e. byte) out of this u16, where 0\n // identifies the most significant byte.\n function NthUint8(v:u16, k: nat) : u8\n // Cannot read more than two words!\n requires k < 2 {\n if k == 0\n then (v / (TWO_8 as u16)) as u8\n else\n (v % (TWO_8 as u16)) as u8\n }\n\n /**\n * Compute the log of a value at base 2 where the result is rounded down.\n */\n function Log2(v:u16) : (r:nat)\n ensures r < 16 {\n var low := (v % (TWO_8 as u16)) as u8;\n var high := (v / (TWO_8 as u16)) as u8;\n if high != 0 then U8.Log2(high)+8 else U8.Log2(low)\n }\n\n /**\n * Compute the log of a value at base 256 where the result is rounded down.\n */\n function Log256(v:u16) : (r:nat)\n ensures r <= 1 {\n var low := (v % (TWO_8 as u16)) as u8;\n var high := (v / (TWO_8 as u16)) as u8;\n if high != 0 then 1 else 0\n }\n\n /**\n * Convert a u16 into a sequence of 2 bytes (in big endian representation).\n */\n function ToBytes(v:u16) : (r:seq)\n ensures |r| == 2 {\n var low := (v % (TWO_8 as u16)) as u8;\n var high := (v / (TWO_8 as u16)) as u8;\n [high,low]\n }\n\n function Read(bytes: seq, address:nat) : u16\n requires (address+1) < |bytes| {\n var b1 := bytes[address] as u16;\n var b2 := bytes[address+1] as u16;\n (b1 * (TWO_8 as u16)) + b2\n }\n}\n\n/**\n * Various helper methods related to unsigned 32bit integers.\n */\nmodule U32 {\n import U16\n import opened Int\n\n // Read nth 16bit word out of this u32, where 0 identifies the most\n // significant word.\n function NthUint16(v:u32, k: nat) : u16\n // Cannot read more than two words!\n requires k < 2 {\n if k == 0\n then (v / (TWO_16 as u32)) as u16\n else\n (v % (TWO_16 as u32)) as u16\n }\n\n /**\n * Compute the log of a value at base 256 where the result is rounded down.\n */\n function Log2(v:u32) : (r:nat)\n ensures r < 32 {\n var low := (v % (TWO_16 as u32)) as u16;\n var high := (v / (TWO_16 as u32)) as u16;\n if high != 0 then U16.Log2(high)+16 else U16.Log2(low)\n }\n\n /**\n * Compute the log of a value at base 256 where the result is rounded down.\n */\n function Log256(v:u32) : (r:nat)\n ensures r <= 3 {\n var low := (v % (TWO_16 as u32)) as u16;\n var high := (v / (TWO_16 as u32)) as u16;\n if high != 0 then U16.Log256(high)+2 else U16.Log256(low)\n }\n\n /**\n * Convert a u32 into a sequence of 4 bytes (in big endian representation).\n */\n function ToBytes(v:u32) : (r:seq)\n ensures |r| == 4 {\n var low := (v % (TWO_16 as u32)) as u16;\n var high := (v / (TWO_16 as u32)) as u16;\n U16.ToBytes(high) + U16.ToBytes(low)\n }\n\n function Read(bytes: seq, address:nat) : u32\n requires (address+3) < |bytes| {\n var b1 := U16.Read(bytes, address) as u32;\n var b2 := U16.Read(bytes, address+2) as u32;\n (b1 * (TWO_16 as u32)) + b2\n }\n}\n\n/**\n * Various helper methods related to unsigned 64bit integers.\n */\nmodule U64 {\n import U32\n import opened Int\n\n // Read nth 32bit word out of this u64, where 0 identifies the most\n // significant word.\n function NthUint32(v:u64, k: nat) : u32\n // Cannot read more than two words!\n requires k < 2 {\n if k == 0\n then (v / (TWO_32 as u64)) as u32\n else\n (v % (TWO_32 as u64)) as u32\n }\n\n /**\n * Compute the log of a value at base 256 where the result is rounded down.\n */\n function Log2(v:u64) : (r:nat)\n ensures r < 64 {\n var low := (v % (TWO_32 as u64)) as u32;\n var high := (v / (TWO_32 as u64)) as u32;\n if high != 0 then U32.Log2(high)+32 else U32.Log2(low)\n }\n\n /**\n * Compute the log of a value at base 256 where the result is rounded down.\n */\n function Log256(v:u64) : (r:nat)\n ensures r <= 7 {\n var low := (v % (TWO_32 as u64)) as u32;\n var high := (v / (TWO_32 as u64)) as u32;\n if high != 0 then U32.Log256(high)+4 else U32.Log256(low)\n }\n\n /**\n * Convert a u64 into a sequence of 8bytes (in big endian representation).\n */\n function ToBytes(v:u64) : (r:seq)\n ensures |r| == 8 {\n var low := (v % (TWO_32 as u64)) as u32;\n var high := (v / (TWO_32 as u64)) as u32;\n U32.ToBytes(high) + U32.ToBytes(low)\n }\n\n function Read(bytes: seq, address:nat) : u64\n requires (address+7) < |bytes| {\n var b1 := U32.Read(bytes, address) as u64;\n var b2 := U32.Read(bytes, address+4) as u64;\n (b1 * (TWO_32 as u64)) + b2\n }\n}\n\n/**\n * Various helper methods related to unsigned 128bit integers.\n */\nmodule U128 {\n import U64\n import opened Int\n\n // Read nth 64bit word out of this u128, where 0 identifies the most\n // significant word.\n function NthUint64(v:u128, k: nat) : u64\n // Cannot read more than two words!\n requires k < 2 {\n if k == 0\n then (v / (TWO_64 as u128)) as u64\n else\n (v % (TWO_64 as u128)) as u64\n }\n\n /**\n * Compute the log of a value at base 256 where the result is rounded down.\n */\n function Log2(v:u128) : (r:nat)\n ensures r < 128 {\n var low := (v % (TWO_64 as u128)) as u64;\n var high := (v / (TWO_64 as u128)) as u64;\n if high != 0 then U64.Log2(high)+64 else U64.Log2(low)\n }\n\n /**\n * Compute the log of a value at base 256 where the result is rounded down.\n */\n function Log256(v:u128) : (r:nat)\n ensures r <= 15 {\n var low := (v % (TWO_64 as u128)) as u64;\n var high := (v / (TWO_64 as u128)) as u64;\n if high != 0 then U64.Log256(high)+8 else U64.Log256(low)\n }\n\n /**\n * Convert a u128 into a sequence of 16bytes (in big endian representation).\n */\n function ToBytes(v:u128) : (r:seq)\n ensures |r| == 16 {\n var low := (v % (TWO_64 as u128)) as u64;\n var high := (v / (TWO_64 as u128)) as u64;\n U64.ToBytes(high) + U64.ToBytes(low)\n }\n\n function Read(bytes: seq, address:nat) : u128\n requires (address+15) < |bytes| {\n var b1 := U64.Read(bytes, address) as u128;\n var b2 := U64.Read(bytes, address+8) as u128;\n (b1 * (TWO_64 as u128)) + b2\n }\n}\n\n/**\n * Various helper methods related to unsigned 256bit integers.\n */\nmodule U256 {\n import opened Int\n import U8\n import U16\n import U32\n import U64\n import U128\n\n /** An axiom stating that a bv256 converted as a nat is bounded by 2^256. */\n lemma {:axiom} as_bv256_as_u256(v: bv256)\n ensures v as nat < TWO_256\n\n function Shl(lhs: u256, rhs: u256) : u256\n {\n var lbv := lhs as bv256;\n // NOTE: unclear whether shifting is optimal choice here.\n var res := if rhs < 256 then (lbv << rhs) else 0;\n //\n res as u256\n }\n\n function Shr(lhs: u256, rhs: u256) : u256 {\n var lbv := lhs as bv256;\n // NOTE: unclear whether shifting is optimal choice here.\n var res := if rhs < 256 then (lbv >> rhs) else 0;\n //\n res as u256\n }\n\n /**\n * Compute the log of a value at base 2, where the result in rounded down.\n * This effectively determines the position of the highest on bit.\n */\n function Log2(v:u256) : (r:nat)\n ensures r < 256 {\n var low := (v % (TWO_128 as u256)) as u128;\n var high := (v / (TWO_128 as u256)) as u128;\n if high != 0 then U128.Log2(high)+128 else U128.Log2(low)\n }\n\n /**\n * Compute the log of a value at base 256 where the result is rounded down.\n */\n function Log256(v:u256) : (r:nat)\n ensures r <= 31 {\n var low := (v % (TWO_128 as u256)) as u128;\n var high := (v / (TWO_128 as u256)) as u128;\n if high != 0 then U128.Log256(high)+16 else U128.Log256(low)\n }\n\n // Read nth 128bit word out of this u256, where 0 identifies the most\n // significant word.\n function NthUint128(v:u256, k: nat) : u128\n // Cannot read more than two words!\n requires k < 2 {\n if k == 0\n then (v / (TWO_128 as u256)) as u128\n else\n (v % (TWO_128 as u256)) as u128\n }\n\n // Read nth byte out of this u256, where 0 identifies the most\n // significant byte.\n function NthUint8(v:u256, k: nat) : u8\n // Cannot read more than 32bytes!\n requires k < 32 {\n // This is perhaps a tad ugly. Happy to take suggestions on\n // a better approach :)\n var w128 := NthUint128(v,k / 16);\n var w64 := U128.NthUint64(w128,(k % 16) / 8);\n var w32 := U64.NthUint32(w64,(k % 8) / 4);\n var w16 := U32.NthUint16(w32,(k % 4) / 2);\n U16.NthUint8(w16,k%2)\n }\n\n function Read(bytes: seq, address:nat) : u256\n requires (address+31) < |bytes| {\n var b1 := U128.Read(bytes, address) as u256;\n var b2 := U128.Read(bytes, address+16) as u256;\n (b1 * (TWO_128 as u256)) + b2\n }\n\n /**\n * Convert a u256 into a sequence of 32bytes in big endian representation.\n */\n function ToBytes(v:u256) : (r:seq)\n ensures |r| == 32 {\n var low := (v % (TWO_128 as u256)) as u128;\n var high := (v / (TWO_128 as u256)) as u128;\n U128.ToBytes(high) + U128.ToBytes(low)\n }\n\n /**\n *\n */\n function SignExtend(v: u256, k: nat) : u256 {\n if k >= 31 then v\n else\n // Reinterpret k as big endian\n var ith := 31 - k;\n // Extract byte containing sign bit\n var byte := NthUint8(v,ith);\n // Extract sign bit\n var signbit := ((byte as bv8) & 0x80) == 0x80;\n // Replicate sign bit.\n var signs := if signbit then seq(31-k, i => 0xff)\n else seq(31-k, i => 0);\n // Extract unchanged bytes\n var bytes := ToBytes(v)[ith..];\n // Sanity check\n assert |signs + bytes| == 32;\n // Done\n Read(signs + bytes,0)\n }\n}\n\nmodule I256 {\n import U256\n import Word\n import opened Int\n\n // This provides a non-Euclidean division operator and is necessary\n // because Dafny (unlike just about every other programming\n // language) supports Euclidean division. This operator, therefore,\n // always divides *towards* zero.\n function Div(lhs: i256, rhs: i256) : i256\n // Cannot divide by zero!\n requires rhs != 0\n // Range restriction to prevent overflow\n requires (rhs != -1 || lhs != (-TWO_255 as i256)) {\n Int.Div(lhs as int, rhs as int) as i256\n }\n\n // This provides a non-Euclidean Remainder operator and is necessary\n // because Dafny (unlike just about every other programming\n // language) supports Euclidean division. Observe that this is a\n // true Remainder operator, and not a modulus operator. For\n // emxaple, this means the result can be negative.\n function Rem(lhs: i256, rhs: i256) : i256\n // Cannot divide by zero!\n requires rhs != 0 {\n Int.Rem(lhs as int, rhs as int) as i256\n }\n\n /**\n * Shifting 1 left less than 256 times produces a non-zero value.\n *\n * More generally, shifting-left 1 less than k times over k bits\n * yield a non-zero number.\n *\n * @example over 2 bits, left-shift 1 once: 01 -> 10\n * @example over 4 bits, left-shift 1 3 times: 0001 -> 0010 -> 0100 -> 1000\n */\n lemma ShiftYieldsNonZero(x: u256)\n requires 0 < x < 256\n ensures U256.Shl(1, x) > 0\n {\n // Thanks Dafny.\n }\n\n // Shift Arithmetic Right. This implementation follows the Yellow Paper quite\n // accurately.\n function Sar(lhs: i256, rhs: u256): i256 {\n if rhs == 0 then lhs\n else if rhs < 256\n then\n assert 0 < rhs < 256;\n var r := U256.Shl(1,rhs);\n ShiftYieldsNonZero(rhs);\n ((lhs as int) / (r as int)) as i256\n else if lhs < 0 then -1\n else 0\n }\n}\n\nmodule Word {\n import opened Int\n\n // Decode a 256bit word as a signed 256bit integer. Since words\n // are represented as u256, the parameter has type u256. However,\n // its important to note that this does not mean the value in\n // question represents an unsigned 256 bit integer. Rather, it is a\n // signed integer encoded into an unsigned integer.\n function asI256(w: u256) : i256 {\n if w > (MAX_I256 as u256)\n then\n var v := 1 + MAX_U256 - (w as int);\n (-v) as i256\n else\n w as i256\n }\n\n // Encode a 256bit signed integer as a 256bit word. Since words are\n // represented as u256, the return is represented as u256. However,\n // its important to note that this does not mean the value in\n // question represents an unsigned 256 bit integer. Rather, it is a\n // signed integer encoded into an unsigned integer.\n function fromI256(w: Int.i256) : u256 {\n if w < 0\n then\n var v := 1 + MAX_U256 + (w as int);\n v as u256\n else\n w as u256\n }\n}\n\n", "hints_removed": "/*\n * Copyright 2022 ConsenSys Software Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n * not use this file except in compliance with the License. You may obtain\n * a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software dis-\n * tributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n */\nmodule Int {\n const TWO_7 : int := 0x0_80\n const TWO_8 : int := 0x1_00\n const TWO_15 : int := 0x0_8000\n const TWO_16 : int := 0x1_0000\n const TWO_24 : int := 0x1_0000_00\n const TWO_31 : int := 0x0_8000_0000\n const TWO_32 : int := 0x1_0000_0000\n const TWO_40 : int := 0x1_0000_0000_00\n const TWO_48 : int := 0x1_0000_0000_0000\n const TWO_56 : int := 0x1_0000_0000_0000_00\n const TWO_63 : int := 0x0_8000_0000_0000_0000\n const TWO_64 : int := 0x1_0000_0000_0000_0000\n const TWO_127 : int := 0x0_8000_0000_0000_0000_0000_0000_0000_0000\n const TWO_128 : int := 0x1_0000_0000_0000_0000_0000_0000_0000_0000\n const TWO_160 : int := 0x1_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000\n const TWO_255 : int := 0x0_8000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000\n const TWO_256 : int := 0x1_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000\n\n // Signed Integers\n const MIN_I8 : int := -TWO_7\n const MAX_I8 : int := TWO_7 - 1\n const MIN_I16 : int := -TWO_15\n const MAX_I16 : int := TWO_15 - 1\n const MIN_I32 : int := -TWO_31\n const MAX_I32 : int := TWO_31 - 1\n const MIN_I64 : int := -TWO_63\n const MAX_I64 : int := TWO_63 - 1\n const MIN_I128 : int := -TWO_127\n const MAX_I128 : int := TWO_127 - 1\n const MIN_I256 : int := -TWO_255\n const MAX_I256 : int := TWO_255 - 1\n\n newtype{:nativeType \"sbyte\"} i8 = i:int | MIN_I8 <= i <= MAX_I8\n newtype{:nativeType \"short\"} i16 = i:int | MIN_I16 <= i <= MAX_I16\n newtype{:nativeType \"int\"} i32 = i:int | MIN_I32 <= i <= MAX_I32\n newtype{:nativeType \"long\"} i64 = i:int | MIN_I64 <= i <= MAX_I64\n newtype i128 = i:int | MIN_I128 <= i <= MAX_I128\n newtype i256 = i:int | MIN_I256 <= i <= MAX_I256\n\n // Unsigned Integers\n const MAX_U8 : int := TWO_8 - 1\n const MAX_U16 : int := TWO_16 - 1\n const MAX_U24 : int := TWO_24 - 1\n const MAX_U32 : int := TWO_32 - 1\n const MAX_U40 : int := TWO_40 - 1\n const MAX_U48 : int := TWO_48 - 1\n const MAX_U56 : int := TWO_56 - 1\n const MAX_U64 : int := TWO_64 - 1\n const MAX_U128 : int := TWO_128 - 1\n const MAX_U160: int := TWO_160 - 1\n const MAX_U256: int := TWO_256 - 1\n\n newtype{:nativeType \"byte\"} u8 = i:int | 0 <= i <= MAX_U8\n newtype{:nativeType \"ushort\"} u16 = i:int | 0 <= i <= MAX_U16\n newtype{:nativeType \"uint\"} u24 = i:int | 0 <= i <= MAX_U24\n newtype{:nativeType \"uint\"} u32 = i:int | 0 <= i <= MAX_U32\n newtype{:nativeType \"ulong\"} u40 = i:int | 0 <= i <= MAX_U40\n newtype{:nativeType \"ulong\"} u48 = i:int | 0 <= i <= MAX_U48\n newtype{:nativeType \"ulong\"} u56 = i:int | 0 <= i <= MAX_U56\n newtype{:nativeType \"ulong\"} u64 = i:int | 0 <= i <= MAX_U64\n newtype u128 = i:int | 0 <= i <= MAX_U128\n newtype u160 = i:int | 0 <= i <= MAX_U160\n newtype u256 = i:int | 0 <= i <= MAX_U256\n\n\n // Determine maximum of two u256 integers.\n function Max(i1: int, i2: int) : int {\n if i1 >= i2 then i1 else i2\n }\n\n // Determine maximum of two u256 integers.\n function Min(i1: int, i2: int) : int {\n if i1 < i2 then i1 else i2\n }\n\n // Round up a given number (i) by a given multiple (r).\n function RoundUp(i: int, r: nat) : int\n requires r > 0 {\n if (i % r) == 0 then i\n else\n ((i/r)*r) + r\n }\n\n // Return the maximum value representable using exactly n unsigned bytes.\n // This is essentially computing (2^n - 1). However, the point of doing it\n // in this fashion is to avoid using Pow() as this is challenging for the\n // verifier.\n function MaxUnsignedN(n:nat) : (r:nat)\n requires 1 <= n <= 32 {\n match n\n case 1 => MAX_U8\n case 2 => MAX_U16\n case 3 => MAX_U24\n case 4 => MAX_U32\n case 5 => MAX_U40\n case 6 => MAX_U48\n case 7 => MAX_U56\n case 8 => MAX_U64\n case 16 => MAX_U128\n case 20 => MAX_U160\n case 32 => MAX_U256\n // Fall back case (for now)\n case _ =>\n Pow(2,n) - 1\n }\n\n\n // =========================================================\n // Exponent\n // =========================================================\n\n /**\n * Compute n^k.\n */\n function Pow(n:nat, k:nat) : (r:nat)\n // Following needed for some proofs\n ensures n > 0 ==> r > 0 {\n if k == 0 then 1\n else if k == 1 then n\n else\n var p := k / 2;\n var np := Pow(n,p);\n if p*2 == k then np * np\n else np * np * n\n }\n\n // Simple lemma about POW.\n lemma lemma_pow2(k:nat)\n ensures Pow(2,k) > 0 {\n if k == 0 {\n } else if k == 1 {\n } else {\n lemma_pow2(k/2);\n }\n }\n\n // =========================================================\n // Non-Euclidean Division / Remainder\n // =========================================================\n\n // This provides a non-Euclidean division operator and is necessary\n // because Dafny (unlike just about every other programming\n // language) supports Euclidean division. This operator, therefore,\n // always divides *towards* zero.\n function Div(lhs: int, rhs: int) : int\n requires rhs != 0 {\n if lhs >= 0 then lhs / rhs\n else\n -((-lhs) / rhs)\n }\n\n // This provides a non-Euclidean Remainder operator and is necessary\n // because Dafny (unlike just about every other programming\n // language) supports Euclidean division. Observe that this is a\n // true Remainder operator, and not a modulus operator. For\n // emxaple, this means the result can be negative.\n function Rem(lhs: int, rhs: int) : int\n requires rhs != 0 {\n if lhs >= 0 then (lhs % rhs)\n else\n var d := -((-lhs) / rhs);\n lhs - (d * rhs)\n }\n}\n\n/**\n * Various helper methods related to unsigned 8bit integers.\n */\nmodule U8 {\n import opened Int\n // Compute the log of a value at base 2 where the result is rounded down.\n function Log2(v:u8) : (r:nat)\n ensures r < 8 {\n // Split 4 bits\n if v <= 15 then\n // Split 2 bits\n if v <= 3 then\n // Split 1 bit\n if v <= 1 then 0 else 1\n else\n // Split 1 bit\n if v <= 7 then 2 else 3\n else\n // Split 2 bits\n if v <= 63 then\n // Split 1 bit\n if v <= 31 then 4 else 5\n else\n // Split 1 bit\n if v <= 127 then 6 else 7\n }\n}\n\n/**\n * Various helper methods related to unsigned 16bit integers.\n */\nmodule U16 {\n import opened Int\n import U8\n\n // Read nth 8bit word (i.e. byte) out of this u16, where 0\n // identifies the most significant byte.\n function NthUint8(v:u16, k: nat) : u8\n // Cannot read more than two words!\n requires k < 2 {\n if k == 0\n then (v / (TWO_8 as u16)) as u8\n else\n (v % (TWO_8 as u16)) as u8\n }\n\n /**\n * Compute the log of a value at base 2 where the result is rounded down.\n */\n function Log2(v:u16) : (r:nat)\n ensures r < 16 {\n var low := (v % (TWO_8 as u16)) as u8;\n var high := (v / (TWO_8 as u16)) as u8;\n if high != 0 then U8.Log2(high)+8 else U8.Log2(low)\n }\n\n /**\n * Compute the log of a value at base 256 where the result is rounded down.\n */\n function Log256(v:u16) : (r:nat)\n ensures r <= 1 {\n var low := (v % (TWO_8 as u16)) as u8;\n var high := (v / (TWO_8 as u16)) as u8;\n if high != 0 then 1 else 0\n }\n\n /**\n * Convert a u16 into a sequence of 2 bytes (in big endian representation).\n */\n function ToBytes(v:u16) : (r:seq)\n ensures |r| == 2 {\n var low := (v % (TWO_8 as u16)) as u8;\n var high := (v / (TWO_8 as u16)) as u8;\n [high,low]\n }\n\n function Read(bytes: seq, address:nat) : u16\n requires (address+1) < |bytes| {\n var b1 := bytes[address] as u16;\n var b2 := bytes[address+1] as u16;\n (b1 * (TWO_8 as u16)) + b2\n }\n}\n\n/**\n * Various helper methods related to unsigned 32bit integers.\n */\nmodule U32 {\n import U16\n import opened Int\n\n // Read nth 16bit word out of this u32, where 0 identifies the most\n // significant word.\n function NthUint16(v:u32, k: nat) : u16\n // Cannot read more than two words!\n requires k < 2 {\n if k == 0\n then (v / (TWO_16 as u32)) as u16\n else\n (v % (TWO_16 as u32)) as u16\n }\n\n /**\n * Compute the log of a value at base 256 where the result is rounded down.\n */\n function Log2(v:u32) : (r:nat)\n ensures r < 32 {\n var low := (v % (TWO_16 as u32)) as u16;\n var high := (v / (TWO_16 as u32)) as u16;\n if high != 0 then U16.Log2(high)+16 else U16.Log2(low)\n }\n\n /**\n * Compute the log of a value at base 256 where the result is rounded down.\n */\n function Log256(v:u32) : (r:nat)\n ensures r <= 3 {\n var low := (v % (TWO_16 as u32)) as u16;\n var high := (v / (TWO_16 as u32)) as u16;\n if high != 0 then U16.Log256(high)+2 else U16.Log256(low)\n }\n\n /**\n * Convert a u32 into a sequence of 4 bytes (in big endian representation).\n */\n function ToBytes(v:u32) : (r:seq)\n ensures |r| == 4 {\n var low := (v % (TWO_16 as u32)) as u16;\n var high := (v / (TWO_16 as u32)) as u16;\n U16.ToBytes(high) + U16.ToBytes(low)\n }\n\n function Read(bytes: seq, address:nat) : u32\n requires (address+3) < |bytes| {\n var b1 := U16.Read(bytes, address) as u32;\n var b2 := U16.Read(bytes, address+2) as u32;\n (b1 * (TWO_16 as u32)) + b2\n }\n}\n\n/**\n * Various helper methods related to unsigned 64bit integers.\n */\nmodule U64 {\n import U32\n import opened Int\n\n // Read nth 32bit word out of this u64, where 0 identifies the most\n // significant word.\n function NthUint32(v:u64, k: nat) : u32\n // Cannot read more than two words!\n requires k < 2 {\n if k == 0\n then (v / (TWO_32 as u64)) as u32\n else\n (v % (TWO_32 as u64)) as u32\n }\n\n /**\n * Compute the log of a value at base 256 where the result is rounded down.\n */\n function Log2(v:u64) : (r:nat)\n ensures r < 64 {\n var low := (v % (TWO_32 as u64)) as u32;\n var high := (v / (TWO_32 as u64)) as u32;\n if high != 0 then U32.Log2(high)+32 else U32.Log2(low)\n }\n\n /**\n * Compute the log of a value at base 256 where the result is rounded down.\n */\n function Log256(v:u64) : (r:nat)\n ensures r <= 7 {\n var low := (v % (TWO_32 as u64)) as u32;\n var high := (v / (TWO_32 as u64)) as u32;\n if high != 0 then U32.Log256(high)+4 else U32.Log256(low)\n }\n\n /**\n * Convert a u64 into a sequence of 8bytes (in big endian representation).\n */\n function ToBytes(v:u64) : (r:seq)\n ensures |r| == 8 {\n var low := (v % (TWO_32 as u64)) as u32;\n var high := (v / (TWO_32 as u64)) as u32;\n U32.ToBytes(high) + U32.ToBytes(low)\n }\n\n function Read(bytes: seq, address:nat) : u64\n requires (address+7) < |bytes| {\n var b1 := U32.Read(bytes, address) as u64;\n var b2 := U32.Read(bytes, address+4) as u64;\n (b1 * (TWO_32 as u64)) + b2\n }\n}\n\n/**\n * Various helper methods related to unsigned 128bit integers.\n */\nmodule U128 {\n import U64\n import opened Int\n\n // Read nth 64bit word out of this u128, where 0 identifies the most\n // significant word.\n function NthUint64(v:u128, k: nat) : u64\n // Cannot read more than two words!\n requires k < 2 {\n if k == 0\n then (v / (TWO_64 as u128)) as u64\n else\n (v % (TWO_64 as u128)) as u64\n }\n\n /**\n * Compute the log of a value at base 256 where the result is rounded down.\n */\n function Log2(v:u128) : (r:nat)\n ensures r < 128 {\n var low := (v % (TWO_64 as u128)) as u64;\n var high := (v / (TWO_64 as u128)) as u64;\n if high != 0 then U64.Log2(high)+64 else U64.Log2(low)\n }\n\n /**\n * Compute the log of a value at base 256 where the result is rounded down.\n */\n function Log256(v:u128) : (r:nat)\n ensures r <= 15 {\n var low := (v % (TWO_64 as u128)) as u64;\n var high := (v / (TWO_64 as u128)) as u64;\n if high != 0 then U64.Log256(high)+8 else U64.Log256(low)\n }\n\n /**\n * Convert a u128 into a sequence of 16bytes (in big endian representation).\n */\n function ToBytes(v:u128) : (r:seq)\n ensures |r| == 16 {\n var low := (v % (TWO_64 as u128)) as u64;\n var high := (v / (TWO_64 as u128)) as u64;\n U64.ToBytes(high) + U64.ToBytes(low)\n }\n\n function Read(bytes: seq, address:nat) : u128\n requires (address+15) < |bytes| {\n var b1 := U64.Read(bytes, address) as u128;\n var b2 := U64.Read(bytes, address+8) as u128;\n (b1 * (TWO_64 as u128)) + b2\n }\n}\n\n/**\n * Various helper methods related to unsigned 256bit integers.\n */\nmodule U256 {\n import opened Int\n import U8\n import U16\n import U32\n import U64\n import U128\n\n /** An axiom stating that a bv256 converted as a nat is bounded by 2^256. */\n lemma {:axiom} as_bv256_as_u256(v: bv256)\n ensures v as nat < TWO_256\n\n function Shl(lhs: u256, rhs: u256) : u256\n {\n var lbv := lhs as bv256;\n // NOTE: unclear whether shifting is optimal choice here.\n var res := if rhs < 256 then (lbv << rhs) else 0;\n //\n res as u256\n }\n\n function Shr(lhs: u256, rhs: u256) : u256 {\n var lbv := lhs as bv256;\n // NOTE: unclear whether shifting is optimal choice here.\n var res := if rhs < 256 then (lbv >> rhs) else 0;\n //\n res as u256\n }\n\n /**\n * Compute the log of a value at base 2, where the result in rounded down.\n * This effectively determines the position of the highest on bit.\n */\n function Log2(v:u256) : (r:nat)\n ensures r < 256 {\n var low := (v % (TWO_128 as u256)) as u128;\n var high := (v / (TWO_128 as u256)) as u128;\n if high != 0 then U128.Log2(high)+128 else U128.Log2(low)\n }\n\n /**\n * Compute the log of a value at base 256 where the result is rounded down.\n */\n function Log256(v:u256) : (r:nat)\n ensures r <= 31 {\n var low := (v % (TWO_128 as u256)) as u128;\n var high := (v / (TWO_128 as u256)) as u128;\n if high != 0 then U128.Log256(high)+16 else U128.Log256(low)\n }\n\n // Read nth 128bit word out of this u256, where 0 identifies the most\n // significant word.\n function NthUint128(v:u256, k: nat) : u128\n // Cannot read more than two words!\n requires k < 2 {\n if k == 0\n then (v / (TWO_128 as u256)) as u128\n else\n (v % (TWO_128 as u256)) as u128\n }\n\n // Read nth byte out of this u256, where 0 identifies the most\n // significant byte.\n function NthUint8(v:u256, k: nat) : u8\n // Cannot read more than 32bytes!\n requires k < 32 {\n // This is perhaps a tad ugly. Happy to take suggestions on\n // a better approach :)\n var w128 := NthUint128(v,k / 16);\n var w64 := U128.NthUint64(w128,(k % 16) / 8);\n var w32 := U64.NthUint32(w64,(k % 8) / 4);\n var w16 := U32.NthUint16(w32,(k % 4) / 2);\n U16.NthUint8(w16,k%2)\n }\n\n function Read(bytes: seq, address:nat) : u256\n requires (address+31) < |bytes| {\n var b1 := U128.Read(bytes, address) as u256;\n var b2 := U128.Read(bytes, address+16) as u256;\n (b1 * (TWO_128 as u256)) + b2\n }\n\n /**\n * Convert a u256 into a sequence of 32bytes in big endian representation.\n */\n function ToBytes(v:u256) : (r:seq)\n ensures |r| == 32 {\n var low := (v % (TWO_128 as u256)) as u128;\n var high := (v / (TWO_128 as u256)) as u128;\n U128.ToBytes(high) + U128.ToBytes(low)\n }\n\n /**\n *\n */\n function SignExtend(v: u256, k: nat) : u256 {\n if k >= 31 then v\n else\n // Reinterpret k as big endian\n var ith := 31 - k;\n // Extract byte containing sign bit\n var byte := NthUint8(v,ith);\n // Extract sign bit\n var signbit := ((byte as bv8) & 0x80) == 0x80;\n // Replicate sign bit.\n var signs := if signbit then seq(31-k, i => 0xff)\n else seq(31-k, i => 0);\n // Extract unchanged bytes\n var bytes := ToBytes(v)[ith..];\n // Sanity check\n // Done\n Read(signs + bytes,0)\n }\n}\n\nmodule I256 {\n import U256\n import Word\n import opened Int\n\n // This provides a non-Euclidean division operator and is necessary\n // because Dafny (unlike just about every other programming\n // language) supports Euclidean division. This operator, therefore,\n // always divides *towards* zero.\n function Div(lhs: i256, rhs: i256) : i256\n // Cannot divide by zero!\n requires rhs != 0\n // Range restriction to prevent overflow\n requires (rhs != -1 || lhs != (-TWO_255 as i256)) {\n Int.Div(lhs as int, rhs as int) as i256\n }\n\n // This provides a non-Euclidean Remainder operator and is necessary\n // because Dafny (unlike just about every other programming\n // language) supports Euclidean division. Observe that this is a\n // true Remainder operator, and not a modulus operator. For\n // emxaple, this means the result can be negative.\n function Rem(lhs: i256, rhs: i256) : i256\n // Cannot divide by zero!\n requires rhs != 0 {\n Int.Rem(lhs as int, rhs as int) as i256\n }\n\n /**\n * Shifting 1 left less than 256 times produces a non-zero value.\n *\n * More generally, shifting-left 1 less than k times over k bits\n * yield a non-zero number.\n *\n * @example over 2 bits, left-shift 1 once: 01 -> 10\n * @example over 4 bits, left-shift 1 3 times: 0001 -> 0010 -> 0100 -> 1000\n */\n lemma ShiftYieldsNonZero(x: u256)\n requires 0 < x < 256\n ensures U256.Shl(1, x) > 0\n {\n // Thanks Dafny.\n }\n\n // Shift Arithmetic Right. This implementation follows the Yellow Paper quite\n // accurately.\n function Sar(lhs: i256, rhs: u256): i256 {\n if rhs == 0 then lhs\n else if rhs < 256\n then\n var r := U256.Shl(1,rhs);\n ShiftYieldsNonZero(rhs);\n ((lhs as int) / (r as int)) as i256\n else if lhs < 0 then -1\n else 0\n }\n}\n\nmodule Word {\n import opened Int\n\n // Decode a 256bit word as a signed 256bit integer. Since words\n // are represented as u256, the parameter has type u256. However,\n // its important to note that this does not mean the value in\n // question represents an unsigned 256 bit integer. Rather, it is a\n // signed integer encoded into an unsigned integer.\n function asI256(w: u256) : i256 {\n if w > (MAX_I256 as u256)\n then\n var v := 1 + MAX_U256 - (w as int);\n (-v) as i256\n else\n w as i256\n }\n\n // Encode a 256bit signed integer as a 256bit word. Since words are\n // represented as u256, the return is represented as u256. However,\n // its important to note that this does not mean the value in\n // question represents an unsigned 256 bit integer. Rather, it is a\n // signed integer encoded into an unsigned integer.\n function fromI256(w: Int.i256) : u256 {\n if w < 0\n then\n var v := 1 + MAX_U256 + (w as int);\n v as u256\n else\n w as u256\n }\n}\n\n" }, { "test_ID": "389", "test_file": "assertive-programming-assignment-1_tmp_tmp3h_cj44u_FindRange.dfy", "ground_truth": "method Main()\n{\n\tvar q := [1,2,2,5,10,10,10,23];\n\tassert Sorted(q);\n\tassert 10 in q;\n\tvar i,j := FindRange(q, 10);\n\tprint \"The number of occurrences of 10 in the sorted sequence [1,2,2,5,10,10,10,23] is \";\n\tprint j-i;\n\tprint \" (starting at index \";\n\tprint i;\n\tprint \" and ending in \";\n\tprint j;\n\tprint \").\\n\";\n\tassert i == 4 && j == 7 by {\n\t\tassert q[0] <= q[1] <= q[2] <= q[3] < 10;\n\t\tassert q[4] == q[5] == q[6] == 10;\n\t\tassert 10 < q[7];\n\t}\n\t\n\t// arr = [0, 1, 2] \t\t key = 10 -> left = right = |q| = 3\n\tq := [0,1,2];\n\tassert Sorted(q);\n\ti,j := FindRange(q, 10);\n\tprint \"The number of occurrences of 10 in the sorted sequence [0,1,2] is \";\n\tprint j-i;\n\tprint \" (starting at index \";\n\tprint i;\n\tprint \" and ending in \";\n\tprint j;\n\tprint \").\\n\";\n\t\n\t// arr = [10, 11, 12] \t\t key = 1 -> left = right = 0\n\tq := [10,11,12];\n\tassert Sorted(q);\n\ti,j := FindRange(q, 1);\n\tprint \"The number of occurrences of 1 in the sorted sequence [10,11,12] is \";\n\tprint j-i;\n\tprint \" (starting at index \";\n\tprint i;\n\tprint \" and ending in \";\n\tprint j;\n\tprint \").\\n\";\n\t\n\t// arr = [1, 11, 22] \t\t key = 10 -> left = right = i+1 = 1 i is the nearest index to key\n\tq := [1,11,22];\n\tassert Sorted(q);\n\ti,j := FindRange(q, 10);\n\tprint \"The number of occurrences of 10 in the sorted sequence [1,11,22] is \";\n\tprint j-i;\n\tprint \" (starting at index \";\n\tprint i;\n\tprint \" and ending in \";\n\tprint j;\n\tprint \").\\n\";\n\t\n\t// arr = [1 ,11, 22] \t\t key = 11 -> left = 1, right = 2 \n\tq := [1,11,22];\n\tassert Sorted(q);\n\ti,j := FindRange(q, 11);\n\tprint \"The number of occurrences of 11 in the sorted sequence [1,11,22] is \";\n\tprint j-i;\n\tprint \" (starting at index \";\n\tprint i;\n\tprint \" and ending in \";\n\tprint j;\n\tprint \").\\n\";\n\t\n\t// arr = [1 ,11, 11] \t\t key = 11 -> left = 1, right = 3\n\tq := [1,11,11];\n\tassert Sorted(q);\n\ti,j := FindRange(q, 11);\n\tprint \"The number of occurrences of 11 in the sorted sequence [1,11,11] is \";\n\tprint j-i;\n\tprint \" (starting at index \";\n\tprint i;\n\tprint \" and ending in \";\n\tprint j;\n\tprint \").\\n\";\n\t\n\t// arr = [11 ,11, 14] \t\t key = 11 -> left = 0, right = 2\n\tq := [11 ,11, 14];\n\tassert Sorted(q);\n\ti,j := FindRange(q, 11);\n\tprint \"The number of occurrences of 11 in the sorted sequence [11 ,11, 14] is \";\n\tprint j-i;\n\tprint \" (starting at index \";\n\tprint i;\n\tprint \" and ending in \";\n\tprint j;\n\tprint \").\\n\";\n\t\n\t// arr = [1 ,11, 11, 11, 13] key = 11 -> left = 1, right = 4\n\tq := [1,11,11,11,13];\n\tassert Sorted(q);\n\ti,j := FindRange(q, 11);\n\tprint \"The number of occurrences of 11 in the sorted sequence [1,11,11,11,13] is \";\n\tprint j-i;\n\tprint \" (starting at index \";\n\tprint i;\n\tprint \" and ending in \";\n\tprint j;\n\tprint \").\\n\";\n\t\n\t// arr = [] key = 11 -> left = 0, right = 0\n\tq := [];\n\tassert Sorted(q);\n\ti,j := FindRange(q, 11);\n\tprint \"The number of occurrences of 11 in the sorted sequence [] is \";\n\tprint j-i;\n\tprint \" (starting at index \";\n\tprint i;\n\tprint \" and ending in \";\n\tprint j;\n\tprint \").\\n\";\n\t\n\t// arr = [11] key = 10 -> left = 0, right = 0\n\tq := [11];\n\tassert Sorted(q);\n\ti,j := FindRange(q, 10);\n\tprint \"The number of occurrences of 10 in the sorted sequence [11] is \";\n\tprint j-i;\n\tprint \" (starting at index \";\n\tprint i;\n\tprint \" and ending in \";\n\tprint j;\n\tprint \").\\n\";\n\t\n\t// arr = [11] key = 11 -> left = 0, right = 1\n\tq := [11];\n\tassert Sorted(q);\n\ti,j := FindRange(q, 11);\n\tprint \"The number of occurrences of 11 in the sorted sequence [11] is \";\n\tprint j-i;\n\tprint \" (starting at index \";\n\tprint i;\n\tprint \" and ending in \";\n\tprint j;\n\tprint \").\\n\";\n}\n\npredicate Sorted(q: seq)\n{\n\tforall i,j :: 0 <= i <= j < |q| ==> q[i] <= q[j] \n}\n\nmethod {:verify true} FindRange(q: seq, key: int) returns (left: nat, right: nat)\n\trequires Sorted(q)\n\tensures left <= right <= |q|\n\tensures forall i :: 0 <= i < left ==> q[i] < key\n\tensures forall i :: left <= i < right ==> q[i] == key\n\tensures forall i :: right <= i < |q| ==> q[i] > key\n{\n\tleft := BinarySearch(q, key, 0, |q|, (n, m) => (n >= m));\n\tright := BinarySearch(q, key, left, |q|, (n, m) => (n > m));\n}\n\n// all the values in the range satisfy `comparer` (comparer(q[i], key) == true)\npredicate RangeSatisfiesComparer(q: seq, key: int, lowerBound: nat, upperBound: nat, comparer: (int, int) -> bool)\n\trequires 0 <= lowerBound <= upperBound <= |q|\n{\n\tforall i :: lowerBound <= i < upperBound ==> comparer(q[i], key)\n}\n\n// all the values in the range satisfy `!comparer` (comparer(q[i], key) == false)\npredicate RangeSatisfiesComparerNegation(q: seq, key: int, lowerBound: nat, upperBound: nat, comparer: (int, int) -> bool)\n\trequires 0 <= lowerBound <= upperBound <= |q|\n{\n\tRangeSatisfiesComparer(q, key, lowerBound, upperBound, (n1, n2) => !comparer(n1, n2))\n}\n\nmethod BinarySearch(q: seq, key: int, lowerBound: nat, upperBound: nat, comparer: (int, int) -> bool) returns (index: nat)\n\trequires Sorted(q)\n\trequires 0 <= lowerBound <= upperBound <= |q|\n\trequires RangeSatisfiesComparerNegation(q, key, 0, lowerBound, comparer)\n\trequires RangeSatisfiesComparer(q, key, upperBound, |q|, comparer)\n\t// comparer is '>' or '>='\n\trequires\n\t\t(forall n1, n2 :: comparer(n1, n2) == (n1 > n2)) ||\n\t\t(forall n1, n2 :: comparer(n1, n2) == (n1 >= n2))\n\n\tensures lowerBound <= index <= upperBound\n\tensures RangeSatisfiesComparerNegation(q, key, 0, index, comparer)\n\tensures RangeSatisfiesComparer(q, key, index, |q|, comparer)\n{\n\tvar low : nat := lowerBound;\n\tvar high : nat := upperBound;\n\twhile (low < high)\n\t\tinvariant lowerBound <= low <= high <= upperBound\n\t\tinvariant RangeSatisfiesComparerNegation(q, key, 0, low, comparer)\n\t\tinvariant RangeSatisfiesComparer(q, key, high, |q|, comparer)\n\t\tdecreases high - low\n\t{\n\t\tvar middle:= low + ((high - low) / 2);\n\t\tif (comparer(q[middle], key))\n\t\t{\n\t\t\thigh := middle;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlow := middle + 1;\n\t\t}\n\t}\n\n\tindex := high;\n}\n\n", "hints_removed": "method Main()\n{\n\tvar q := [1,2,2,5,10,10,10,23];\n\tvar i,j := FindRange(q, 10);\n\tprint \"The number of occurrences of 10 in the sorted sequence [1,2,2,5,10,10,10,23] is \";\n\tprint j-i;\n\tprint \" (starting at index \";\n\tprint i;\n\tprint \" and ending in \";\n\tprint j;\n\tprint \").\\n\";\n\t}\n\t\n\t// arr = [0, 1, 2] \t\t key = 10 -> left = right = |q| = 3\n\tq := [0,1,2];\n\ti,j := FindRange(q, 10);\n\tprint \"The number of occurrences of 10 in the sorted sequence [0,1,2] is \";\n\tprint j-i;\n\tprint \" (starting at index \";\n\tprint i;\n\tprint \" and ending in \";\n\tprint j;\n\tprint \").\\n\";\n\t\n\t// arr = [10, 11, 12] \t\t key = 1 -> left = right = 0\n\tq := [10,11,12];\n\ti,j := FindRange(q, 1);\n\tprint \"The number of occurrences of 1 in the sorted sequence [10,11,12] is \";\n\tprint j-i;\n\tprint \" (starting at index \";\n\tprint i;\n\tprint \" and ending in \";\n\tprint j;\n\tprint \").\\n\";\n\t\n\t// arr = [1, 11, 22] \t\t key = 10 -> left = right = i+1 = 1 i is the nearest index to key\n\tq := [1,11,22];\n\ti,j := FindRange(q, 10);\n\tprint \"The number of occurrences of 10 in the sorted sequence [1,11,22] is \";\n\tprint j-i;\n\tprint \" (starting at index \";\n\tprint i;\n\tprint \" and ending in \";\n\tprint j;\n\tprint \").\\n\";\n\t\n\t// arr = [1 ,11, 22] \t\t key = 11 -> left = 1, right = 2 \n\tq := [1,11,22];\n\ti,j := FindRange(q, 11);\n\tprint \"The number of occurrences of 11 in the sorted sequence [1,11,22] is \";\n\tprint j-i;\n\tprint \" (starting at index \";\n\tprint i;\n\tprint \" and ending in \";\n\tprint j;\n\tprint \").\\n\";\n\t\n\t// arr = [1 ,11, 11] \t\t key = 11 -> left = 1, right = 3\n\tq := [1,11,11];\n\ti,j := FindRange(q, 11);\n\tprint \"The number of occurrences of 11 in the sorted sequence [1,11,11] is \";\n\tprint j-i;\n\tprint \" (starting at index \";\n\tprint i;\n\tprint \" and ending in \";\n\tprint j;\n\tprint \").\\n\";\n\t\n\t// arr = [11 ,11, 14] \t\t key = 11 -> left = 0, right = 2\n\tq := [11 ,11, 14];\n\ti,j := FindRange(q, 11);\n\tprint \"The number of occurrences of 11 in the sorted sequence [11 ,11, 14] is \";\n\tprint j-i;\n\tprint \" (starting at index \";\n\tprint i;\n\tprint \" and ending in \";\n\tprint j;\n\tprint \").\\n\";\n\t\n\t// arr = [1 ,11, 11, 11, 13] key = 11 -> left = 1, right = 4\n\tq := [1,11,11,11,13];\n\ti,j := FindRange(q, 11);\n\tprint \"The number of occurrences of 11 in the sorted sequence [1,11,11,11,13] is \";\n\tprint j-i;\n\tprint \" (starting at index \";\n\tprint i;\n\tprint \" and ending in \";\n\tprint j;\n\tprint \").\\n\";\n\t\n\t// arr = [] key = 11 -> left = 0, right = 0\n\tq := [];\n\ti,j := FindRange(q, 11);\n\tprint \"The number of occurrences of 11 in the sorted sequence [] is \";\n\tprint j-i;\n\tprint \" (starting at index \";\n\tprint i;\n\tprint \" and ending in \";\n\tprint j;\n\tprint \").\\n\";\n\t\n\t// arr = [11] key = 10 -> left = 0, right = 0\n\tq := [11];\n\ti,j := FindRange(q, 10);\n\tprint \"The number of occurrences of 10 in the sorted sequence [11] is \";\n\tprint j-i;\n\tprint \" (starting at index \";\n\tprint i;\n\tprint \" and ending in \";\n\tprint j;\n\tprint \").\\n\";\n\t\n\t// arr = [11] key = 11 -> left = 0, right = 1\n\tq := [11];\n\ti,j := FindRange(q, 11);\n\tprint \"The number of occurrences of 11 in the sorted sequence [11] is \";\n\tprint j-i;\n\tprint \" (starting at index \";\n\tprint i;\n\tprint \" and ending in \";\n\tprint j;\n\tprint \").\\n\";\n}\n\npredicate Sorted(q: seq)\n{\n\tforall i,j :: 0 <= i <= j < |q| ==> q[i] <= q[j] \n}\n\nmethod {:verify true} FindRange(q: seq, key: int) returns (left: nat, right: nat)\n\trequires Sorted(q)\n\tensures left <= right <= |q|\n\tensures forall i :: 0 <= i < left ==> q[i] < key\n\tensures forall i :: left <= i < right ==> q[i] == key\n\tensures forall i :: right <= i < |q| ==> q[i] > key\n{\n\tleft := BinarySearch(q, key, 0, |q|, (n, m) => (n >= m));\n\tright := BinarySearch(q, key, left, |q|, (n, m) => (n > m));\n}\n\n// all the values in the range satisfy `comparer` (comparer(q[i], key) == true)\npredicate RangeSatisfiesComparer(q: seq, key: int, lowerBound: nat, upperBound: nat, comparer: (int, int) -> bool)\n\trequires 0 <= lowerBound <= upperBound <= |q|\n{\n\tforall i :: lowerBound <= i < upperBound ==> comparer(q[i], key)\n}\n\n// all the values in the range satisfy `!comparer` (comparer(q[i], key) == false)\npredicate RangeSatisfiesComparerNegation(q: seq, key: int, lowerBound: nat, upperBound: nat, comparer: (int, int) -> bool)\n\trequires 0 <= lowerBound <= upperBound <= |q|\n{\n\tRangeSatisfiesComparer(q, key, lowerBound, upperBound, (n1, n2) => !comparer(n1, n2))\n}\n\nmethod BinarySearch(q: seq, key: int, lowerBound: nat, upperBound: nat, comparer: (int, int) -> bool) returns (index: nat)\n\trequires Sorted(q)\n\trequires 0 <= lowerBound <= upperBound <= |q|\n\trequires RangeSatisfiesComparerNegation(q, key, 0, lowerBound, comparer)\n\trequires RangeSatisfiesComparer(q, key, upperBound, |q|, comparer)\n\t// comparer is '>' or '>='\n\trequires\n\t\t(forall n1, n2 :: comparer(n1, n2) == (n1 > n2)) ||\n\t\t(forall n1, n2 :: comparer(n1, n2) == (n1 >= n2))\n\n\tensures lowerBound <= index <= upperBound\n\tensures RangeSatisfiesComparerNegation(q, key, 0, index, comparer)\n\tensures RangeSatisfiesComparer(q, key, index, |q|, comparer)\n{\n\tvar low : nat := lowerBound;\n\tvar high : nat := upperBound;\n\twhile (low < high)\n\t{\n\t\tvar middle:= low + ((high - low) / 2);\n\t\tif (comparer(q[middle], key))\n\t\t{\n\t\t\thigh := middle;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlow := middle + 1;\n\t\t}\n\t}\n\n\tindex := high;\n}\n\n" }, { "test_ID": "390", "test_file": "assertive-programming-assignment-1_tmp_tmp3h_cj44u_ProdAndCount.dfy", "ground_truth": "method Main() {\n\tvar q := [7, -2, 3, -2];\n\n\tvar p, c := ProdAndCount(q, -2);\n\tprint \"The product of all positive elements in [7,-2,3,-2] is \";\n\tprint p;\n\tassert p == RecursivePositiveProduct(q) == 21;\n\tprint \"\\nThe number of occurrences of -2 in [7,-2,3,-2] is \";\n\tprint c;\n\tassert c == RecursiveCount(-2, q) == 2 by {\n\t\tcalc {\n\t\t\tRecursiveCount(-2, q);\n\t\t== { assert q[3] == -2; AppendOne(q, 3); }\n\t\t\t1 + RecursiveCount(-2, q[..3]);\n\t\t== { assert q[2] != -2; AppendOne(q, 2); }\n\t\t\t1 + RecursiveCount(-2, q[..2]);\n\t\t== { assert q[1] == -2; AppendOne(q, 1); }\n\t\t\t1 + 1 + RecursiveCount(-2, q[..1]);\n\t\t== { assert q[0] != -2; AppendOne(q, 0); }\n\t\t\t1 + 1 + RecursiveCount(-2, q[..0]);\n\t\t}\n\t}\n}\n\nlemma AppendOne(q: seq, n: nat)\n\trequires n < |q|\n\tensures q[..n]+[q[n]] == q[..n+1]\n{}\n\nfunction RecursivePositiveProduct(q: seq): int\n\tdecreases |q|\n{\n\tif q == [] then 1\n\telse if q[0] <= 0 then RecursivePositiveProduct(q[1..])\n\telse q[0] * RecursivePositiveProduct(q[1..])\n}\n\nfunction RecursiveCount(key: int, q: seq): int\n\tdecreases |q|\n{\n\tif q == [] then 0\n\telse if q[|q|-1] == key then 1+RecursiveCount(key, q[..|q|-1])\n\telse RecursiveCount(key, q[..|q|-1])\n}\n\nmethod ProdAndCount(q: seq, key: int) returns (prod: int, count: nat)\n\tensures prod == RecursivePositiveProduct(q)\n\tensures count == RecursiveCount(key, q)\n{\n prod := 1; \n count := 0;\n var size := |q|;\n var i := 0;\n\n var curr := 0;\n\twhile i < size\n\t\tinvariant 0 <= i <= size && // legal index\n\t\t\t\tcount == RecursiveCount(key, q[..i]) && // count invar\n\t\t\t\tprod == RecursivePositiveProduct(q[..i])\n \tdecreases size-i\n\t{\n\t\tLemma_Count_Inv(q, i, count, key);\n\t\tLemma_Prod_Inv(q, i, prod);\n curr := q[i];\n if curr > 0 {\n prod := prod*curr; \n }\n\n if curr == key {\n count := count+1; \n }\n i := i+1; \n }\n\t\tLemma_Count_Finish(q, i, count, key);\n\t\tLemma_Prod_Finish(q, i, prod);\n}\n\nfunction county(elem: int, key: int): int{\n\tif elem==key then 1 else 0\n}\n\nfunction prody(elem: int): int{\n\tif elem <= 0 then 1 else elem\n}\n\nlemma Lemma_Count_Inv(q: seq, i: nat, count: int, key: int)\n\trequires 0 <= i < |q| && count == RecursiveCount(key, q[..i])\n\tensures 0 <= i+1 <= |q| && county(q[i],key)+count == RecursiveCount(key, q[..i+1])\n{\n\tassert q[..i+1] == q[..i] + [q[i]];\n\tvar q1 := q[..i+1];\n\tcalc {\n\t\t\tRecursiveCount(key, q[..i+1]);\n\t\t\t== // def.\n\t\t\t\tif q1 == [] then 0\n\t\t\t\telse if q1[i] == key then 1+RecursiveCount(key,q1[..i])\n\t\t\t\telse RecursiveCount(key, q1[..i]);\n\t\t\t== { assert q1 != []; } // simplification for a non-empty sequence\n\t\t\t\tif q1[i] == key then 1+RecursiveCount(key, q1[..i])\n\t\t\t\telse RecursiveCount(key,q1[..i]);\n\t\t\t== {KibutzLaw1(q1,key,i);} // the kibutz law \n\t\t\t\t(if q1[i] == key then 1 else 0) + RecursiveCount(key, q1[..i]);\n\t\t\t== \n\t\t\t\tcounty(q1[i],key) + RecursiveCount(key, q1[..i]);\n\t\t\t==\n\t\t\t\tcounty(q[i],key) + RecursiveCount(key, q[..i]);\n\t}\n\n}\n\n\nlemma Lemma_Prod_Inv(q: seq, i: nat, prod: int)\n\trequires 0 <= i < |q| && prod == RecursivePositiveProduct(q[..i])\n\tensures 0 <= i+1 <= |q| && prody(q[i])*prod == RecursivePositiveProduct(q[..i+1])\n{\n\tassert q[..i+1] == q[..i] + [q[i]];\n\tvar q1 := q[..i+1];\n\tcalc {\n\t\tRecursivePositiveProduct(q[..i+1]);\n\t== // def.\n\t\tif q1 == [] then 1\n\t\telse if q1[0] <= 0 then RecursivePositiveProduct(q1[1..])\n\t\telse q1[0] * RecursivePositiveProduct(q1[1..]);\n\t== { assert q1 != []; } // simplification for a non-empty sequence\n\t\tif q1[0] <= 0 then RecursivePositiveProduct(q1[1..])\n\t\telse q1[0] * RecursivePositiveProduct(q1[1..]);\n\t== // def. of q1\n\t\tif q[0] <= 0 then RecursivePositiveProduct(q[1..i+1])\n\t\telse q[0] * RecursivePositiveProduct(q[1..i+1]);\n\t== { KibutzLaw2(q);}\n\t\t(if q[0] <= 0 then 1 else q[0])*RecursivePositiveProduct(q[1..i+1]);\n\t==\n\t\tprody(q[0])*RecursivePositiveProduct(q[1..i+1]);\n\t== {PrependProd(q);}\n\t\tRecursivePositiveProduct(q[..i+1]);\n\t== {AppendProd(q[..i+1]);}\n\t\tprody(q[i])*RecursivePositiveProduct(q[..i]);\n\t==\n\t\tprody(q[i])*prod;\n\t}\n}\n\nlemma Lemma_Count_Finish(q: seq, i: nat, count: int, key: int)\n\trequires inv: 0 <= i <= |q| && count == RecursiveCount(key, q[..i])\n\trequires neg_of_guard: i >= |q|\n\tensures count == RecursiveCount(key, q)\n{\n\tassert i <= |q| && count == RecursiveCount(key, q[..i]) by { reveal inv; }\n\tassert i == |q| by { reveal inv,neg_of_guard; }\n\tassert q[..i] == q[..|q|] == q;\n}\n\nlemma Lemma_Prod_Finish(q: seq, i: nat, prod: int)\n\trequires inv: 0 <= i <= |q| && prod == RecursivePositiveProduct(q[..i])\n\trequires neg_of_guard: i >= |q|\n\tensures prod == RecursivePositiveProduct(q)\n{\n\tassert i <= |q| && prod == RecursivePositiveProduct(q[..i]) by { reveal inv; }\n\tassert i == |q| by { reveal inv,neg_of_guard; }\n\tassert q[..i] == q[..|q|] == q;\n}\n\nlemma KibutzLaw1(q: seq,key: int,i: nat)\nrequires q != [] && i < |q|\nensures \t\t\n\t(if q[|q|-1] == key then 1 + RecursiveCount(key, q[1..i+1])\n\telse 0 + RecursiveCount(key, q[1..i+1]))\n\t== \n\t(if q[|q|-1] == key then 1 else 0) + RecursiveCount(key, q[1..i+1])\n{\n\tif q[|q|-1] == key {\n\t\tcalc {\n\t\t\t(if q[|q|-1] == key then 1 + RecursiveCount(key, q[1..i+1])\n\t\t\telse 0 + RecursiveCount(key, q[1..i+1]));\n\t\t\t==\n\t\t\t1 + RecursiveCount(key, q[1..i+1]);\n\t\t\t==\n\t\t\t(if q[|q|-1] == key then 1 else 0) + RecursiveCount(key, q[1..i+1]);\n\t\t}\n\t} else {\n\t\tcalc {\n\t\t\t(if q[|q|-1] == key then 1 + RecursiveCount(key, q[1..i+1])\n\t\t\telse 0 + RecursiveCount(key, q[1..i+1]));\n\t\t\t==\n\t\t\t0 + RecursiveCount(key, q[1..i+1]);\n\t\t\t==\n\t\t\t(if q[|q|-1] == key then 1 else 0) + RecursiveCount(key, q[1..i+1]);\n\t\t}\n\t}\n\n}\n\nlemma {:verify true} KibutzLaw2(q: seq)\nrequires q != [] \nensures \t\t\n\t(if q[0] <= 0 then RecursivePositiveProduct(q[1..])\n\t\telse q[0] * RecursivePositiveProduct(q[1..]))\n\t== \n\t(if q[0] <= 0 then 1 else q[0])*RecursivePositiveProduct(q[1..])\n{\n\tif q[0] <= 0 {\n\t\tcalc {\n\t\t(if q[0] <= 0 then RecursivePositiveProduct(q[1..])\n\t\t\telse q[0] * RecursivePositiveProduct(q[1..]));\n\t\t\t==\n\t\t\tRecursivePositiveProduct(q[1..]);\n\t\t\t==\n\t\t\t(if q[0] <= 0 then 1 else q[0])*RecursivePositiveProduct(q[1..]);\n\t\t}\n\t} else {\n\t\tcalc {\n\t\t(if q[0] <= 0 then RecursivePositiveProduct(q[1..])\n\t\t\telse q[0] * RecursivePositiveProduct(q[1..]));\n\t\t\t==\n\t\t\tq[0] * RecursivePositiveProduct(q[1..]);\n\t\t\t==\n\t\t\t(if q[0] <= 0 then 1 else q[0])*RecursivePositiveProduct(q[1..]);\n\t\t}\n\t}\n}\n\t\t\nlemma AppendCount(key: int, q: seq)\n\trequires q != [] \n\tensures RecursiveCount(key, q) == RecursiveCount(key,q[..|q|-1])+county(q[|q|-1], key)\t\n{\n\tif |q| == 1\n\t{\n\t\tassert\n\t\tRecursiveCount(key,q[..|q|-1])+county(q[|q|-1], key) == \n\t\tRecursiveCount(key,q[..0])+county(q[0], key) == \n\t\tRecursiveCount(key, [])+county(q[0], key) ==\n\t\t0+county(q[0], key) == \n\t\tcounty(q[0], key);\n\t\tassert RecursiveCount(key, q) == county(q[0], key);\n\t}\n\telse\n\t{\t\t// inductive step\n\t\tvar q1 := q[1..];\n\t\tcalc {\n\t\t\tRecursiveCount(key, q);\n\t\t== // def. for a non-empty sequence\n\t\t\tif q == [] then 0\n\t\t\telse if q[|q|-1] == key then 1+RecursiveCount(key, q[..|q|-1])\n\t\t\telse RecursiveCount(key, q[..|q|-1]);\n\t\t== \n\t\t\tRecursiveCount(key, q[..|q|-1]) + county(q[|q|-1], key);\n\t\t}\n\t}\n}\n\nlemma PrependProd(q: seq)\n\trequires q != []\n\tensures RecursivePositiveProduct(q) == prody(q[0])*RecursivePositiveProduct(q[1..])\n{\n\tcalc {\n\t\t\tRecursivePositiveProduct(q);\n\t\t== \n\t\t\tif q == [] then 1\n\t\t\telse if q[0] <= 0 then RecursivePositiveProduct(q[1..])\n\t\t\telse q[0] * RecursivePositiveProduct(q[1..]);\n\t\t== { assert q != []; } // simplification for a non-empty sequence\n\t\t\tif q[0] <= 0 then RecursivePositiveProduct(q[1..])\n\t\t\telse q[0] * RecursivePositiveProduct(q[1..]);\n\t\t== { KibutzLaw2(q);}\n\t\t\t(if q[0] <= 0 then 1 else q[0])*RecursivePositiveProduct(q[1..]);\n\t\t==\n\t\t\tprody(q[0])*RecursivePositiveProduct(q[1..]);\n\t\t}\n}\n\nlemma AppendProd(q: seq)\n\trequires q != [] \n\tensures RecursivePositiveProduct(q) == RecursivePositiveProduct(q[..|q|-1])*prody(q[|q|-1])\t\n{\n\tif |q| == 1\n\t{\n\t\tassert\n\t\tRecursivePositiveProduct(q[..|q|-1])*prody(q[|q|-1]) == \n\t\tRecursivePositiveProduct(q[..0])*prody(q[0]) == \n\t\tRecursivePositiveProduct([])*prody(q[0]) ==\n\t\t1*prody(q[0]) == \n\t\tprody(q[0]);\n\t\tassert RecursivePositiveProduct(q) == prody(q[0]);\n\t}\n\telse\n\t{\t\t// inductive step\n\t\tvar q1 := q[1..];\n\t\tcalc {\n\t\t\tRecursivePositiveProduct(q);\n\t\t== // def. for a non-empty sequence\n\t\t\tprody(q[0]) * RecursivePositiveProduct(q[1..]);\n\t\t== { assert q1 != []; assert |q1| < |q|; AppendProd(q1); } // induction hypothesis (one assertion for the precondition, another for termination)\n\t\t\tprody(q[0]) * RecursivePositiveProduct(q1[..|q1|-1]) * prody(q1[|q1|-1]);\n\t\t== { assert q1[..|q1|-1] == q[1..|q|-1]; assert q1[|q1|-1] == q[|q|-1]; }\n\t\t\tprody(q[0]) * RecursivePositiveProduct(q[1..|q|-1]) * prody(q[|q|-1]);\n\t\t== {PrependProd(q[..|q|-1]);}\n\t\t\tRecursivePositiveProduct(q[..|q|-1]) * prody(q[|q|-1]);\n\t\t}\n\t}\n}\n", "hints_removed": "method Main() {\n\tvar q := [7, -2, 3, -2];\n\n\tvar p, c := ProdAndCount(q, -2);\n\tprint \"The product of all positive elements in [7,-2,3,-2] is \";\n\tprint p;\n\tprint \"\\nThe number of occurrences of -2 in [7,-2,3,-2] is \";\n\tprint c;\n\t\tcalc {\n\t\t\tRecursiveCount(-2, q);\n\t\t== { assert q[3] == -2; AppendOne(q, 3); }\n\t\t\t1 + RecursiveCount(-2, q[..3]);\n\t\t== { assert q[2] != -2; AppendOne(q, 2); }\n\t\t\t1 + RecursiveCount(-2, q[..2]);\n\t\t== { assert q[1] == -2; AppendOne(q, 1); }\n\t\t\t1 + 1 + RecursiveCount(-2, q[..1]);\n\t\t== { assert q[0] != -2; AppendOne(q, 0); }\n\t\t\t1 + 1 + RecursiveCount(-2, q[..0]);\n\t\t}\n\t}\n}\n\nlemma AppendOne(q: seq, n: nat)\n\trequires n < |q|\n\tensures q[..n]+[q[n]] == q[..n+1]\n{}\n\nfunction RecursivePositiveProduct(q: seq): int\n{\n\tif q == [] then 1\n\telse if q[0] <= 0 then RecursivePositiveProduct(q[1..])\n\telse q[0] * RecursivePositiveProduct(q[1..])\n}\n\nfunction RecursiveCount(key: int, q: seq): int\n{\n\tif q == [] then 0\n\telse if q[|q|-1] == key then 1+RecursiveCount(key, q[..|q|-1])\n\telse RecursiveCount(key, q[..|q|-1])\n}\n\nmethod ProdAndCount(q: seq, key: int) returns (prod: int, count: nat)\n\tensures prod == RecursivePositiveProduct(q)\n\tensures count == RecursiveCount(key, q)\n{\n prod := 1; \n count := 0;\n var size := |q|;\n var i := 0;\n\n var curr := 0;\n\twhile i < size\n\t\t\t\tcount == RecursiveCount(key, q[..i]) && // count invar\n\t\t\t\tprod == RecursivePositiveProduct(q[..i])\n\t{\n\t\tLemma_Count_Inv(q, i, count, key);\n\t\tLemma_Prod_Inv(q, i, prod);\n curr := q[i];\n if curr > 0 {\n prod := prod*curr; \n }\n\n if curr == key {\n count := count+1; \n }\n i := i+1; \n }\n\t\tLemma_Count_Finish(q, i, count, key);\n\t\tLemma_Prod_Finish(q, i, prod);\n}\n\nfunction county(elem: int, key: int): int{\n\tif elem==key then 1 else 0\n}\n\nfunction prody(elem: int): int{\n\tif elem <= 0 then 1 else elem\n}\n\nlemma Lemma_Count_Inv(q: seq, i: nat, count: int, key: int)\n\trequires 0 <= i < |q| && count == RecursiveCount(key, q[..i])\n\tensures 0 <= i+1 <= |q| && county(q[i],key)+count == RecursiveCount(key, q[..i+1])\n{\n\tvar q1 := q[..i+1];\n\tcalc {\n\t\t\tRecursiveCount(key, q[..i+1]);\n\t\t\t== // def.\n\t\t\t\tif q1 == [] then 0\n\t\t\t\telse if q1[i] == key then 1+RecursiveCount(key,q1[..i])\n\t\t\t\telse RecursiveCount(key, q1[..i]);\n\t\t\t== { assert q1 != []; } // simplification for a non-empty sequence\n\t\t\t\tif q1[i] == key then 1+RecursiveCount(key, q1[..i])\n\t\t\t\telse RecursiveCount(key,q1[..i]);\n\t\t\t== {KibutzLaw1(q1,key,i);} // the kibutz law \n\t\t\t\t(if q1[i] == key then 1 else 0) + RecursiveCount(key, q1[..i]);\n\t\t\t== \n\t\t\t\tcounty(q1[i],key) + RecursiveCount(key, q1[..i]);\n\t\t\t==\n\t\t\t\tcounty(q[i],key) + RecursiveCount(key, q[..i]);\n\t}\n\n}\n\n\nlemma Lemma_Prod_Inv(q: seq, i: nat, prod: int)\n\trequires 0 <= i < |q| && prod == RecursivePositiveProduct(q[..i])\n\tensures 0 <= i+1 <= |q| && prody(q[i])*prod == RecursivePositiveProduct(q[..i+1])\n{\n\tvar q1 := q[..i+1];\n\tcalc {\n\t\tRecursivePositiveProduct(q[..i+1]);\n\t== // def.\n\t\tif q1 == [] then 1\n\t\telse if q1[0] <= 0 then RecursivePositiveProduct(q1[1..])\n\t\telse q1[0] * RecursivePositiveProduct(q1[1..]);\n\t== { assert q1 != []; } // simplification for a non-empty sequence\n\t\tif q1[0] <= 0 then RecursivePositiveProduct(q1[1..])\n\t\telse q1[0] * RecursivePositiveProduct(q1[1..]);\n\t== // def. of q1\n\t\tif q[0] <= 0 then RecursivePositiveProduct(q[1..i+1])\n\t\telse q[0] * RecursivePositiveProduct(q[1..i+1]);\n\t== { KibutzLaw2(q);}\n\t\t(if q[0] <= 0 then 1 else q[0])*RecursivePositiveProduct(q[1..i+1]);\n\t==\n\t\tprody(q[0])*RecursivePositiveProduct(q[1..i+1]);\n\t== {PrependProd(q);}\n\t\tRecursivePositiveProduct(q[..i+1]);\n\t== {AppendProd(q[..i+1]);}\n\t\tprody(q[i])*RecursivePositiveProduct(q[..i]);\n\t==\n\t\tprody(q[i])*prod;\n\t}\n}\n\nlemma Lemma_Count_Finish(q: seq, i: nat, count: int, key: int)\n\trequires inv: 0 <= i <= |q| && count == RecursiveCount(key, q[..i])\n\trequires neg_of_guard: i >= |q|\n\tensures count == RecursiveCount(key, q)\n{\n}\n\nlemma Lemma_Prod_Finish(q: seq, i: nat, prod: int)\n\trequires inv: 0 <= i <= |q| && prod == RecursivePositiveProduct(q[..i])\n\trequires neg_of_guard: i >= |q|\n\tensures prod == RecursivePositiveProduct(q)\n{\n}\n\nlemma KibutzLaw1(q: seq,key: int,i: nat)\nrequires q != [] && i < |q|\nensures \t\t\n\t(if q[|q|-1] == key then 1 + RecursiveCount(key, q[1..i+1])\n\telse 0 + RecursiveCount(key, q[1..i+1]))\n\t== \n\t(if q[|q|-1] == key then 1 else 0) + RecursiveCount(key, q[1..i+1])\n{\n\tif q[|q|-1] == key {\n\t\tcalc {\n\t\t\t(if q[|q|-1] == key then 1 + RecursiveCount(key, q[1..i+1])\n\t\t\telse 0 + RecursiveCount(key, q[1..i+1]));\n\t\t\t==\n\t\t\t1 + RecursiveCount(key, q[1..i+1]);\n\t\t\t==\n\t\t\t(if q[|q|-1] == key then 1 else 0) + RecursiveCount(key, q[1..i+1]);\n\t\t}\n\t} else {\n\t\tcalc {\n\t\t\t(if q[|q|-1] == key then 1 + RecursiveCount(key, q[1..i+1])\n\t\t\telse 0 + RecursiveCount(key, q[1..i+1]));\n\t\t\t==\n\t\t\t0 + RecursiveCount(key, q[1..i+1]);\n\t\t\t==\n\t\t\t(if q[|q|-1] == key then 1 else 0) + RecursiveCount(key, q[1..i+1]);\n\t\t}\n\t}\n\n}\n\nlemma {:verify true} KibutzLaw2(q: seq)\nrequires q != [] \nensures \t\t\n\t(if q[0] <= 0 then RecursivePositiveProduct(q[1..])\n\t\telse q[0] * RecursivePositiveProduct(q[1..]))\n\t== \n\t(if q[0] <= 0 then 1 else q[0])*RecursivePositiveProduct(q[1..])\n{\n\tif q[0] <= 0 {\n\t\tcalc {\n\t\t(if q[0] <= 0 then RecursivePositiveProduct(q[1..])\n\t\t\telse q[0] * RecursivePositiveProduct(q[1..]));\n\t\t\t==\n\t\t\tRecursivePositiveProduct(q[1..]);\n\t\t\t==\n\t\t\t(if q[0] <= 0 then 1 else q[0])*RecursivePositiveProduct(q[1..]);\n\t\t}\n\t} else {\n\t\tcalc {\n\t\t(if q[0] <= 0 then RecursivePositiveProduct(q[1..])\n\t\t\telse q[0] * RecursivePositiveProduct(q[1..]));\n\t\t\t==\n\t\t\tq[0] * RecursivePositiveProduct(q[1..]);\n\t\t\t==\n\t\t\t(if q[0] <= 0 then 1 else q[0])*RecursivePositiveProduct(q[1..]);\n\t\t}\n\t}\n}\n\t\t\nlemma AppendCount(key: int, q: seq)\n\trequires q != [] \n\tensures RecursiveCount(key, q) == RecursiveCount(key,q[..|q|-1])+county(q[|q|-1], key)\t\n{\n\tif |q| == 1\n\t{\n\t\tRecursiveCount(key,q[..|q|-1])+county(q[|q|-1], key) == \n\t\tRecursiveCount(key,q[..0])+county(q[0], key) == \n\t\tRecursiveCount(key, [])+county(q[0], key) ==\n\t\t0+county(q[0], key) == \n\t\tcounty(q[0], key);\n\t}\n\telse\n\t{\t\t// inductive step\n\t\tvar q1 := q[1..];\n\t\tcalc {\n\t\t\tRecursiveCount(key, q);\n\t\t== // def. for a non-empty sequence\n\t\t\tif q == [] then 0\n\t\t\telse if q[|q|-1] == key then 1+RecursiveCount(key, q[..|q|-1])\n\t\t\telse RecursiveCount(key, q[..|q|-1]);\n\t\t== \n\t\t\tRecursiveCount(key, q[..|q|-1]) + county(q[|q|-1], key);\n\t\t}\n\t}\n}\n\nlemma PrependProd(q: seq)\n\trequires q != []\n\tensures RecursivePositiveProduct(q) == prody(q[0])*RecursivePositiveProduct(q[1..])\n{\n\tcalc {\n\t\t\tRecursivePositiveProduct(q);\n\t\t== \n\t\t\tif q == [] then 1\n\t\t\telse if q[0] <= 0 then RecursivePositiveProduct(q[1..])\n\t\t\telse q[0] * RecursivePositiveProduct(q[1..]);\n\t\t== { assert q != []; } // simplification for a non-empty sequence\n\t\t\tif q[0] <= 0 then RecursivePositiveProduct(q[1..])\n\t\t\telse q[0] * RecursivePositiveProduct(q[1..]);\n\t\t== { KibutzLaw2(q);}\n\t\t\t(if q[0] <= 0 then 1 else q[0])*RecursivePositiveProduct(q[1..]);\n\t\t==\n\t\t\tprody(q[0])*RecursivePositiveProduct(q[1..]);\n\t\t}\n}\n\nlemma AppendProd(q: seq)\n\trequires q != [] \n\tensures RecursivePositiveProduct(q) == RecursivePositiveProduct(q[..|q|-1])*prody(q[|q|-1])\t\n{\n\tif |q| == 1\n\t{\n\t\tRecursivePositiveProduct(q[..|q|-1])*prody(q[|q|-1]) == \n\t\tRecursivePositiveProduct(q[..0])*prody(q[0]) == \n\t\tRecursivePositiveProduct([])*prody(q[0]) ==\n\t\t1*prody(q[0]) == \n\t\tprody(q[0]);\n\t}\n\telse\n\t{\t\t// inductive step\n\t\tvar q1 := q[1..];\n\t\tcalc {\n\t\t\tRecursivePositiveProduct(q);\n\t\t== // def. for a non-empty sequence\n\t\t\tprody(q[0]) * RecursivePositiveProduct(q[1..]);\n\t\t== { assert q1 != []; assert |q1| < |q|; AppendProd(q1); } // induction hypothesis (one assertion for the precondition, another for termination)\n\t\t\tprody(q[0]) * RecursivePositiveProduct(q1[..|q1|-1]) * prody(q1[|q1|-1]);\n\t\t== { assert q1[..|q1|-1] == q[1..|q|-1]; assert q1[|q1|-1] == q[|q|-1]; }\n\t\t\tprody(q[0]) * RecursivePositiveProduct(q[1..|q|-1]) * prody(q[|q|-1]);\n\t\t== {PrependProd(q[..|q|-1]);}\n\t\t\tRecursivePositiveProduct(q[..|q|-1]) * prody(q[|q|-1]);\n\t\t}\n\t}\n}\n" }, { "test_ID": "391", "test_file": "assertive-programming-assignment-1_tmp_tmp3h_cj44u_SearchAddends.dfy", "ground_truth": "method Main()\n{\n\tvar q := [1,2,4,5,6,7,10,23];\n\tassert Sorted(q);\n\tassert HasAddends(q,10) by { assert q[2]+q[4] == 4+6 == 10; }\n\tvar i,j := FindAddends(q, 10);\n\tprint \"Searching for addends of 10 in q == [1,2,4,5,6,7,10,23]:\\n\";\n\tprint \"Found that q[\";\n\tprint i;\n\tprint \"] + q[\";\n\tprint j;\n\tprint \"] == \";\n\tprint q[i];\n\tprint \" + \";\n\tprint q[j];\n\tprint \" == 10\";\n\tassert i == 2 && j == 4;\n}\n\npredicate Sorted(q: seq)\n{\n\tforall i,j :: 0 <= i <= j < |q| ==> q[i] <= q[j] \n}\n\npredicate HasAddends(q: seq, x: int)\n{\n\texists i,j :: 0 <= i < j < |q| && q[i] + q[j] == x\n}\n\nmethod FindAddends(q: seq, x: int) returns (i: nat, j: nat)\n\trequires Sorted(q) && HasAddends(q, x)\n\tensures i < j < |q| && q[i]+q[j] == x\n{\n\ti := 0;\n\tj := |q| - 1;\n\tvar sum := q[i] + q[j];\n\n\twhile sum != x\n\t\tinvariant LoopInv(q, x, i, j, sum)\n\t\tdecreases j - i\n\t{\n\t\tif (sum > x)\n\t\t{\n\t\t\t// Sum it too big, lower it by decreasing the high index\n\t\t\tLoopInvWhenSumIsBigger(q, x, i, j, sum);\n\t\t\tj := j - 1;\n\t\t}\n\t\t// 'sum == x' cannot occur because the loop's guard is 'sum !=x'.\n\t\telse // (sum < x)\n\t\t{\n\t\t\t// Sum is too small, make it bigger by increasing the low index.\n\t\t\ti := i + 1;\n\t\t}\n\n\t\tsum := q[i] + q[j];\n\t}\n}\n\npredicate IsValidIndex(q: seq, i: nat)\n{\n\t0 <= i < |q|\n}\n\npredicate AreOreredIndices(q: seq, i: nat, j: nat)\n{\n\t0 <= i < j < |q|\n}\n\npredicate AreAddendsIndices(q: seq, x: int, i: nat, j: nat)\n\trequires IsValidIndex(q, i) && IsValidIndex(q, j)\n{\n\tq[i] + q[j] == x\n}\n\npredicate HasAddendsInIndicesRange(q: seq, x: int, i: nat, j: nat)\n\trequires AreOreredIndices(q, i, j)\n{\n\tHasAddends(q[i..(j + 1)], x)\n}\n\npredicate LoopInv(q: seq, x: int, i: nat, j: nat, sum: int)\n{\n\tAreOreredIndices(q, i, j) &&\n\tHasAddendsInIndicesRange(q, x, i, j) &&\n\tAreAddendsIndices(q, sum, i, j)\n}\n\nlemma LoopInvWhenSumIsBigger(q: seq, x: int, i: nat, j: nat, sum: int)\n\trequires HasAddends(q, x)\n\trequires Sorted(q)\n\trequires sum > x;\n\trequires LoopInv(q, x, i, j, sum)\n\tensures HasAddendsInIndicesRange(q, x, i, j - 1)\n{\n\tassert q[i..j] < q[i..(j + 1)];\n}\n\n", "hints_removed": "method Main()\n{\n\tvar q := [1,2,4,5,6,7,10,23];\n\tvar i,j := FindAddends(q, 10);\n\tprint \"Searching for addends of 10 in q == [1,2,4,5,6,7,10,23]:\\n\";\n\tprint \"Found that q[\";\n\tprint i;\n\tprint \"] + q[\";\n\tprint j;\n\tprint \"] == \";\n\tprint q[i];\n\tprint \" + \";\n\tprint q[j];\n\tprint \" == 10\";\n}\n\npredicate Sorted(q: seq)\n{\n\tforall i,j :: 0 <= i <= j < |q| ==> q[i] <= q[j] \n}\n\npredicate HasAddends(q: seq, x: int)\n{\n\texists i,j :: 0 <= i < j < |q| && q[i] + q[j] == x\n}\n\nmethod FindAddends(q: seq, x: int) returns (i: nat, j: nat)\n\trequires Sorted(q) && HasAddends(q, x)\n\tensures i < j < |q| && q[i]+q[j] == x\n{\n\ti := 0;\n\tj := |q| - 1;\n\tvar sum := q[i] + q[j];\n\n\twhile sum != x\n\t{\n\t\tif (sum > x)\n\t\t{\n\t\t\t// Sum it too big, lower it by decreasing the high index\n\t\t\tLoopInvWhenSumIsBigger(q, x, i, j, sum);\n\t\t\tj := j - 1;\n\t\t}\n\t\t// 'sum == x' cannot occur because the loop's guard is 'sum !=x'.\n\t\telse // (sum < x)\n\t\t{\n\t\t\t// Sum is too small, make it bigger by increasing the low index.\n\t\t\ti := i + 1;\n\t\t}\n\n\t\tsum := q[i] + q[j];\n\t}\n}\n\npredicate IsValidIndex(q: seq, i: nat)\n{\n\t0 <= i < |q|\n}\n\npredicate AreOreredIndices(q: seq, i: nat, j: nat)\n{\n\t0 <= i < j < |q|\n}\n\npredicate AreAddendsIndices(q: seq, x: int, i: nat, j: nat)\n\trequires IsValidIndex(q, i) && IsValidIndex(q, j)\n{\n\tq[i] + q[j] == x\n}\n\npredicate HasAddendsInIndicesRange(q: seq, x: int, i: nat, j: nat)\n\trequires AreOreredIndices(q, i, j)\n{\n\tHasAddends(q[i..(j + 1)], x)\n}\n\npredicate LoopInv(q: seq, x: int, i: nat, j: nat, sum: int)\n{\n\tAreOreredIndices(q, i, j) &&\n\tHasAddendsInIndicesRange(q, x, i, j) &&\n\tAreAddendsIndices(q, sum, i, j)\n}\n\nlemma LoopInvWhenSumIsBigger(q: seq, x: int, i: nat, j: nat, sum: int)\n\trequires HasAddends(q, x)\n\trequires Sorted(q)\n\trequires sum > x;\n\trequires LoopInv(q, x, i, j, sum)\n\tensures HasAddendsInIndicesRange(q, x, i, j - 1)\n{\n}\n\n" }, { "test_ID": "392", "test_file": "bbfny_tmp_tmpw4m0jvl0_enjoying.dfy", "ground_truth": "// shenanigans going through the dafny tutorial\n\nmethod MultipleReturns(x: int, y: int) returns (more: int, less: int)\n requires 0 < y\n ensures less < x < more\n{\n more := x + y;\n less := x - y;\n}\n\nmethod Max(a: int, b: int) returns (c: int)\n ensures a <= c && b <= c\n ensures a == c || b == c\n{\n if a > b {\n c := a;\n } else { c := b; }\n}\n\nmethod Testing() {\n var x := Max(3,15);\n assert x >= 3 && x >= 15;\n assert x == 15;\n}\n\nfunction max(a: int, b: int): int\n{\n if a > b then a else b\n}\nmethod Testing'() {\n assert max(1,2) == 2;\n assert forall a,b : int :: max (a,b) == a || max (a,b) == b;\n}\n\nfunction abs(x: int): int\n{\n if x < 0 then -x else x\n}\nmethod Abs(x: int) returns (y: int)\n ensures y == abs(x)\n{\n return abs(x);\n}\n\nmethod m(n: nat)\n{\n var i := 0;\n while i != n\n invariant 0 <= i <= n \n {\n i := i + 1;\n }\n assert i == n;\n}\n\nfunction fib(n: nat): nat\n{\n if n == 0 then 0\n else if n == 1 then 1\n else fib(n - 1) + fib(n - 2)\n}\n\nmethod Find(a: array, key: int) returns (index: int)\n ensures 0 <= index ==> index < a.Length && a[index] == key\n ensures index < 0 ==> forall k :: 0 <= k < a.Length ==> a[k] != key\n{\n var i := 0;\n while i < a.Length\n invariant 0 <= i <= a.Length\n invariant forall k :: 0 <= k < i ==> a[k] != key\n {\n if a[i] == key {return i;}\n i := i+1;\n }\n assert i == a.Length;\n return -1;\n}\n\nmethod FindMax(a: array) returns (i: int)\n requires a.Length >= 1 \n ensures 0 <= i < a.Length\n ensures forall k :: 0 <= k < a.Length ==> a[k] <= a[i]\n{\n i := 0;\n var max := a[i];\n var j := 1;\n while j < a.Length \n invariant 0 < j <= a.Length\n invariant i < j\n invariant max == a[i]\n invariant forall k :: 0 <= k < j ==> a[k] <= max\n {\n if max < a[j] { max := a[j]; i := j; }\n j := j+1;\n }\n}\npredicate sorted(a: array)\n reads a\n{\n forall j, k :: 0 <= j < k < a.Length ==> a[j] < a[k]\n}\n\npredicate sorted'(a: array?) // Change the type\n reads a\n{\n forall j, k :: a != null && 0 <= j < k < a.Length ==> a[j] <= a[k]\n}\n", "hints_removed": "// shenanigans going through the dafny tutorial\n\nmethod MultipleReturns(x: int, y: int) returns (more: int, less: int)\n requires 0 < y\n ensures less < x < more\n{\n more := x + y;\n less := x - y;\n}\n\nmethod Max(a: int, b: int) returns (c: int)\n ensures a <= c && b <= c\n ensures a == c || b == c\n{\n if a > b {\n c := a;\n } else { c := b; }\n}\n\nmethod Testing() {\n var x := Max(3,15);\n}\n\nfunction max(a: int, b: int): int\n{\n if a > b then a else b\n}\nmethod Testing'() {\n}\n\nfunction abs(x: int): int\n{\n if x < 0 then -x else x\n}\nmethod Abs(x: int) returns (y: int)\n ensures y == abs(x)\n{\n return abs(x);\n}\n\nmethod m(n: nat)\n{\n var i := 0;\n while i != n\n {\n i := i + 1;\n }\n}\n\nfunction fib(n: nat): nat\n{\n if n == 0 then 0\n else if n == 1 then 1\n else fib(n - 1) + fib(n - 2)\n}\n\nmethod Find(a: array, key: int) returns (index: int)\n ensures 0 <= index ==> index < a.Length && a[index] == key\n ensures index < 0 ==> forall k :: 0 <= k < a.Length ==> a[k] != key\n{\n var i := 0;\n while i < a.Length\n {\n if a[i] == key {return i;}\n i := i+1;\n }\n return -1;\n}\n\nmethod FindMax(a: array) returns (i: int)\n requires a.Length >= 1 \n ensures 0 <= i < a.Length\n ensures forall k :: 0 <= k < a.Length ==> a[k] <= a[i]\n{\n i := 0;\n var max := a[i];\n var j := 1;\n while j < a.Length \n {\n if max < a[j] { max := a[j]; i := j; }\n j := j+1;\n }\n}\npredicate sorted(a: array)\n reads a\n{\n forall j, k :: 0 <= j < k < a.Length ==> a[j] < a[k]\n}\n\npredicate sorted'(a: array?) // Change the type\n reads a\n{\n forall j, k :: a != null && 0 <= j < k < a.Length ==> a[j] <= a[k]\n}\n" }, { "test_ID": "393", "test_file": "circular-queue-implemetation_tmp_tmpnulfdc9l_Queue.dfy", "ground_truth": "class {:autocontracts} Queue {\n\n // Atributos\n var circularQueue: array;\n var rear: nat; // cauda\n var front: nat; // head\n var counter: nat;\n\n // Abstra\u00e7\u00e3o\n ghost var Content: seq;\n\n // Predicado\n ghost predicate Valid()\n {\n 0 <= counter <= circularQueue.Length &&\n 0 <= front &&\n 0 <= rear &&\n Content == circularQueue[..]\n }\n\n // Construtor\n constructor()\n ensures circularQueue.Length == 0\n ensures front == 0 && rear == 0\n ensures Content == [] // REVISAR\n ensures counter == 0\n {\n circularQueue := new int[0];\n rear := 0;\n front := 0;\n Content := [];\n counter := 0;\n } //[tam] ; [1, 2, 3, 4]\n\n method insert(item: int)\n // requires rear <= circularQueue.Length\n // ensures (front == 0 && rear == 0 && circularQueue.Length == 1) ==>\n // (\n // Content == [item] &&\n // |Content| == 1\n // )\n // ensures circularQueue.Length != 0 ==>\n // (\n // (front == 0 && rear == 0 && circularQueue.Length == 1) ==>\n // (\n // Content == old(Content) &&\n // |Content| == old(|Content|)\n\n // )\n // ||\n // (front == 0 && rear == circularQueue.Length-1 ) ==> \n // (\n // Content == old(Content) + [item] &&\n // |Content| == old(|Content|) + 1\n // )\n // ||\n // (rear + 1 != front && rear != circularQueue.Length-1 && rear + 1 < circularQueue.Length - 1) ==> \n // (\n // Content == old(Content[0..rear]) + [item] + old(Content[rear..circularQueue.Length])\n // )\n // ||\n // (rear + 1 == front) ==> \n // (\n // Content[0..rear + 1] == old(Content[0..rear]) + [item] &&\n // forall i :: rear + 2 <= i <= circularQueue.Length ==> Content[i] == old(Content[i-1])\n // )\n // )\n {\n\n //counter := counter + 1;\n // if front == 0 && rear == 0 && circularQueue.Length == 0\n // {\n // var queueInsert: array;\n // queueInsert := new int [circularQueue.Length + 1];\n // queueInsert[0] := item;\n // circularQueue := queueInsert;\n // Content := [item];\n // rear := rear + 1;\n // } \n // else if front == 0 && rear == circularQueue.Length-1 && circularQueue.Length > 0\n // {\n // var queueInsert: array;\n // queueInsert := new int [circularQueue.Length + 1];\n // var i: nat := 0;\n // while i < circularQueue.Length\n // invariant circularQueue.Length + 1 == queueInsert.Length\n // {\n // queueInsert[i] := circularQueue[i];\n // i := i + 1;\n // }\n // queueInsert[queueInsert.Length - 1] := item;\n // Content := Content + [item];\n // rear := rear + 1;\n // circularQueue := queueInsert;\n // }\n }\n\n method auxInsertEmptyQueue(item:int)\n requires front == 0 && rear == 0 && circularQueue.Length == 0\n ensures circularQueue.Length == 1\n ensures Content == [item]\n ensures |Content| == 1\n ensures rear == 1\n ensures counter == old(counter) + 1\n ensures front == 0\n {\n counter := counter + 1;\n var queueInsert: array;\n queueInsert := new int [circularQueue.Length + 1];\n queueInsert[0] := item;\n circularQueue := queueInsert;\n Content := [item];\n rear := rear + 1;\n }\n\n method auxInsertEndQueue(item:int)\n requires front == 0 && rear == circularQueue.Length && circularQueue.Length >= 1\n ensures Content == old(Content) + [item]\n ensures |Content| == old(|Content|) + 1\n ensures front == 0\n ensures rear == old(rear) + 1\n ensures counter == old(counter) + 1\n // {\n // counter := counter + 1;\n // var queueInsert: array;\n // queueInsert := new int [circularQueue.Length + 1];\n // var i: nat := 0;\n // while i < circularQueue.Length\n // invariant circularQueue.Length + 1 == queueInsert.Length\n // invariant 0 <= i <= circularQueue.Length\n // invariant forall j :: 0 <= j < i ==> queueInsert[j] == circularQueue[j]\n // {\n // queueInsert[i] := circularQueue[i];\n // i := i + 1;\n // }\n // queueInsert[queueInsert.Length - 1] := item;\n // Content := Content + [item];\n // rear := rear + 1;\n // circularQueue := queueInsert;\n // }\n\n method auxInsertSpaceQueue(item:int)\n requires rear < front && front < circularQueue.Length\n ensures rear == old(rear) + 1\n ensures counter == old(counter) + 1\n ensures Content == old(Content[0..rear]) + [item] + old(Content[rear+1..circularQueue.Length])\n ensures |Content| == old(|Content|) + 1\n\n method auxInsertInitQueue(item:int)\n\n method auxInsertBetweenQueue(item:int)\n\n // remove apenas mudando o ponteiro\n // sem resetar o valor na posi\u00e7\u00e3o, pois, provavelmente,\n // vai ser sobrescrito pela inser\u00e7\u00e3o\n method remove() returns (item: int)\n requires front < circularQueue.Length\n requires circularQueue.Length > 0\n ensures rear <= |old(Content)|\n ensures circularQueue.Length > 0\n ensures item == old(Content)[old(front)]\n ensures front == (old(front) + 1) % circularQueue.Length\n ensures old(front) < rear ==> Content == old(Content)[old(front)..rear]\n ensures old(front) > rear ==> Content == old(Content)[0 .. rear] + old(Content)[old(front)..|old(Content)|]\n /*{\n if counter == 0 {\n item := -1;\n\n } else {\n item := circularQueue[front];\n front := (front + 1) % circularQueue.Length;\n counter := counter - 1;\n }\n }*/\n\n method size() returns (size:nat)\n ensures size == counter\n {\n size := counter;\n }\n\n method isEmpty() returns (isEmpty: bool)\n ensures isEmpty == true ==> counter == 0;\n ensures isEmpty == false ==> counter != 0;\n {\n isEmpty := if counter == 0 then true else false;\n }\n\n method contains(item: int) returns (contains: bool)\n ensures contains == true ==> item in circularQueue[..]\n ensures contains == false ==> item !in circularQueue[..]\n {\n var i: nat := 0;\n contains := false;\n\n while (i < circularQueue.Length)\n decreases circularQueue.Length - i\n invariant 0 <= i <= circularQueue.Length\n invariant !contains ==> forall j :: 0 <= j < i ==> circularQueue[j] != item\n {\n if (circularQueue[i] == item) {\n contains := true;\n break;\n }\n i := i + 1;\n }\n }\n\n // TODO\n method mergeQueues(otherQueue: Queue) returns (mergedQueue: Queue) \n {\n \n // queue1.merge(queue2)\n var newQueueSize : int := otherQueue.circularQueue.Length + circularQueue.Length;\n var newFront: int := front;\n var newRear: int := otherQueue.rear;\n\n var tmp: array := new int[newQueueSize];\n\n forall i | 0 <= i < circularQueue.Length\n { \n tmp[i] := circularQueue[i];\n }\n\n // vamos copiar valores vazios?\n // como identificamos os vazios? entre o rear e o front\n // como iteramos entre rear e front? front -> rear\n // [1, 3, 5, 7, 9] + [0, 2, 4, 6, 8] => [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]\n // front => 8 \n // rear => 0\n \n mergedQueue := new Queue(); \n }\n}\n\nmethod Main ()\n{\n var circularQueue := new Queue();\n assert circularQueue.circularQueue.Length == 0;\n assert circularQueue.Content == [];\n assert circularQueue.Content != [1];\n\n var isQueueEmpty := circularQueue.isEmpty();\n assert isQueueEmpty == true;\n\n var queueSize := circularQueue.size();\n assert queueSize == 0;\n\n circularQueue.auxInsertEmptyQueue(2);\n assert circularQueue.Content == [2];\n assert circularQueue.counter == 1;\n assert circularQueue.circularQueue.Length == 1;\n assert circularQueue.front == 0;\n assert circularQueue.rear == 1;\n assert circularQueue.rear != 2;\n assert circularQueue.front != 2;\n\n circularQueue.auxInsertEndQueue(4);\n assert circularQueue.Content == [2,4];\n assert circularQueue.counter == 2;\n assert circularQueue.front == 0;\n assert circularQueue.rear == 2;\n\n circularQueue.auxInsertEndQueue(4);\n assert circularQueue.Content == [2,4,4];\n assert circularQueue.counter == 3;\n\n circularQueue.auxInsertEndQueue(56);\n assert circularQueue.Content == [2,4,4,56];\n assert circularQueue.counter == 4;\n\n var contains56 := circularQueue.contains(56);\n assert contains56 == true;\n\n var contains4 := circularQueue.contains(4);\n assert contains4 == true;\n\n var item := circularQueue.remove();\n assert item == 2;\n //assert circularQueue.Content == [2, 4, 4, 56];\n\n assert (0 + 1) % 6 == 1;\n assert (1 + 1) % 6 == 2;\n assert (2 + 1) % 6 == 3;\n assert (3 + 1) % 6 == 4;\n assert (4 + 1) % 6 == 5;\n assert (5 + 1) % 6 == 0;\n assert (0 + 1) % 6 == 1;\n\n}\n", "hints_removed": "class {:autocontracts} Queue {\n\n // Atributos\n var circularQueue: array;\n var rear: nat; // cauda\n var front: nat; // head\n var counter: nat;\n\n // Abstra\u00e7\u00e3o\n ghost var Content: seq;\n\n // Predicado\n ghost predicate Valid()\n {\n 0 <= counter <= circularQueue.Length &&\n 0 <= front &&\n 0 <= rear &&\n Content == circularQueue[..]\n }\n\n // Construtor\n constructor()\n ensures circularQueue.Length == 0\n ensures front == 0 && rear == 0\n ensures Content == [] // REVISAR\n ensures counter == 0\n {\n circularQueue := new int[0];\n rear := 0;\n front := 0;\n Content := [];\n counter := 0;\n } //[tam] ; [1, 2, 3, 4]\n\n method insert(item: int)\n // requires rear <= circularQueue.Length\n // ensures (front == 0 && rear == 0 && circularQueue.Length == 1) ==>\n // (\n // Content == [item] &&\n // |Content| == 1\n // )\n // ensures circularQueue.Length != 0 ==>\n // (\n // (front == 0 && rear == 0 && circularQueue.Length == 1) ==>\n // (\n // Content == old(Content) &&\n // |Content| == old(|Content|)\n\n // )\n // ||\n // (front == 0 && rear == circularQueue.Length-1 ) ==> \n // (\n // Content == old(Content) + [item] &&\n // |Content| == old(|Content|) + 1\n // )\n // ||\n // (rear + 1 != front && rear != circularQueue.Length-1 && rear + 1 < circularQueue.Length - 1) ==> \n // (\n // Content == old(Content[0..rear]) + [item] + old(Content[rear..circularQueue.Length])\n // )\n // ||\n // (rear + 1 == front) ==> \n // (\n // Content[0..rear + 1] == old(Content[0..rear]) + [item] &&\n // forall i :: rear + 2 <= i <= circularQueue.Length ==> Content[i] == old(Content[i-1])\n // )\n // )\n {\n\n //counter := counter + 1;\n // if front == 0 && rear == 0 && circularQueue.Length == 0\n // {\n // var queueInsert: array;\n // queueInsert := new int [circularQueue.Length + 1];\n // queueInsert[0] := item;\n // circularQueue := queueInsert;\n // Content := [item];\n // rear := rear + 1;\n // } \n // else if front == 0 && rear == circularQueue.Length-1 && circularQueue.Length > 0\n // {\n // var queueInsert: array;\n // queueInsert := new int [circularQueue.Length + 1];\n // var i: nat := 0;\n // while i < circularQueue.Length\n // invariant circularQueue.Length + 1 == queueInsert.Length\n // {\n // queueInsert[i] := circularQueue[i];\n // i := i + 1;\n // }\n // queueInsert[queueInsert.Length - 1] := item;\n // Content := Content + [item];\n // rear := rear + 1;\n // circularQueue := queueInsert;\n // }\n }\n\n method auxInsertEmptyQueue(item:int)\n requires front == 0 && rear == 0 && circularQueue.Length == 0\n ensures circularQueue.Length == 1\n ensures Content == [item]\n ensures |Content| == 1\n ensures rear == 1\n ensures counter == old(counter) + 1\n ensures front == 0\n {\n counter := counter + 1;\n var queueInsert: array;\n queueInsert := new int [circularQueue.Length + 1];\n queueInsert[0] := item;\n circularQueue := queueInsert;\n Content := [item];\n rear := rear + 1;\n }\n\n method auxInsertEndQueue(item:int)\n requires front == 0 && rear == circularQueue.Length && circularQueue.Length >= 1\n ensures Content == old(Content) + [item]\n ensures |Content| == old(|Content|) + 1\n ensures front == 0\n ensures rear == old(rear) + 1\n ensures counter == old(counter) + 1\n // {\n // counter := counter + 1;\n // var queueInsert: array;\n // queueInsert := new int [circularQueue.Length + 1];\n // var i: nat := 0;\n // while i < circularQueue.Length\n // invariant circularQueue.Length + 1 == queueInsert.Length\n // invariant 0 <= i <= circularQueue.Length\n // invariant forall j :: 0 <= j < i ==> queueInsert[j] == circularQueue[j]\n // {\n // queueInsert[i] := circularQueue[i];\n // i := i + 1;\n // }\n // queueInsert[queueInsert.Length - 1] := item;\n // Content := Content + [item];\n // rear := rear + 1;\n // circularQueue := queueInsert;\n // }\n\n method auxInsertSpaceQueue(item:int)\n requires rear < front && front < circularQueue.Length\n ensures rear == old(rear) + 1\n ensures counter == old(counter) + 1\n ensures Content == old(Content[0..rear]) + [item] + old(Content[rear+1..circularQueue.Length])\n ensures |Content| == old(|Content|) + 1\n\n method auxInsertInitQueue(item:int)\n\n method auxInsertBetweenQueue(item:int)\n\n // remove apenas mudando o ponteiro\n // sem resetar o valor na posi\u00e7\u00e3o, pois, provavelmente,\n // vai ser sobrescrito pela inser\u00e7\u00e3o\n method remove() returns (item: int)\n requires front < circularQueue.Length\n requires circularQueue.Length > 0\n ensures rear <= |old(Content)|\n ensures circularQueue.Length > 0\n ensures item == old(Content)[old(front)]\n ensures front == (old(front) + 1) % circularQueue.Length\n ensures old(front) < rear ==> Content == old(Content)[old(front)..rear]\n ensures old(front) > rear ==> Content == old(Content)[0 .. rear] + old(Content)[old(front)..|old(Content)|]\n /*{\n if counter == 0 {\n item := -1;\n\n } else {\n item := circularQueue[front];\n front := (front + 1) % circularQueue.Length;\n counter := counter - 1;\n }\n }*/\n\n method size() returns (size:nat)\n ensures size == counter\n {\n size := counter;\n }\n\n method isEmpty() returns (isEmpty: bool)\n ensures isEmpty == true ==> counter == 0;\n ensures isEmpty == false ==> counter != 0;\n {\n isEmpty := if counter == 0 then true else false;\n }\n\n method contains(item: int) returns (contains: bool)\n ensures contains == true ==> item in circularQueue[..]\n ensures contains == false ==> item !in circularQueue[..]\n {\n var i: nat := 0;\n contains := false;\n\n while (i < circularQueue.Length)\n {\n if (circularQueue[i] == item) {\n contains := true;\n break;\n }\n i := i + 1;\n }\n }\n\n // TODO\n method mergeQueues(otherQueue: Queue) returns (mergedQueue: Queue) \n {\n \n // queue1.merge(queue2)\n var newQueueSize : int := otherQueue.circularQueue.Length + circularQueue.Length;\n var newFront: int := front;\n var newRear: int := otherQueue.rear;\n\n var tmp: array := new int[newQueueSize];\n\n forall i | 0 <= i < circularQueue.Length\n { \n tmp[i] := circularQueue[i];\n }\n\n // vamos copiar valores vazios?\n // como identificamos os vazios? entre o rear e o front\n // como iteramos entre rear e front? front -> rear\n // [1, 3, 5, 7, 9] + [0, 2, 4, 6, 8] => [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]\n // front => 8 \n // rear => 0\n \n mergedQueue := new Queue(); \n }\n}\n\nmethod Main ()\n{\n var circularQueue := new Queue();\n\n var isQueueEmpty := circularQueue.isEmpty();\n\n var queueSize := circularQueue.size();\n\n circularQueue.auxInsertEmptyQueue(2);\n\n circularQueue.auxInsertEndQueue(4);\n\n circularQueue.auxInsertEndQueue(4);\n\n circularQueue.auxInsertEndQueue(56);\n\n var contains56 := circularQueue.contains(56);\n\n var contains4 := circularQueue.contains(4);\n\n var item := circularQueue.remove();\n //assert circularQueue.Content == [2, 4, 4, 56];\n\n\n}\n" }, { "test_ID": "394", "test_file": "cmsc433_tmp_tmpe3ob3a0o_dafny_project1_p1-assignment-2.dfy", "ground_truth": "// ASSIGNMENT P1\n// CMSC 433 FALL 2023\n// PERFECT SCORE: 100 POINTS\n//\n// This assignment contains nine questions, each of which involves writing Dafny\n// code. You should include your solutions in a single Dafny file and submit it using\n// Gradescope.\n//\n// Revision history\n//\n// 2023-09-22 2:50 pm Fixed typo in Problem 3.\n\n\n// Question 1 (5 points)\n//\n// Fill in a requires clause that enables Dafny to verify\n// method PlusOne\n\nmethod PlusOne (x : int) returns (y : int)\n requires x >= 0\n ensures y > 0\n{\n y := x+1;\n}\n\n\n// Question 2 (5 points)\n//\n// Fill in requires clause(s) that enable(s) Dafny to verify the array bounds\n// in method Swap (which swaps elements i and j in array a).\n\nmethod Swap (a : array?, i : int, j : int)\n requires a != null && 0 <= i < a.Length && 0 <= j < a.Length// TODO\n modifies a // Dafny requires listing of objects modified in a method\n{\n var tmp : int := a[i];\n a[i] := a[j];\n a[j] := a[i];\n}\n\n// Question 3 (5 points)\n//\n// Give ensures clause(s) asserting that d is the result, and r the\n// remainder, of dividing m by n. Your clauses cannot use \"/\" or \"%\" (which are\n// the Dafny division and mod operators, respectively). By definition, the\n// remainder must be non-negative.\n\nmethod IntDiv (m : int, n : int) returns (d : int, r : int)\n requires n > 0\n ensures m == n * d + r && 0 <= r < n // TODO\n{\n return m / n, m % n;\n}\n\n// Question 4 (5 points)\n//\n// Give ensures clause(s) asserting that the return value has the same\n// length as array a and contains as its elements the sum of the\n// corresponding elements in arrays a and b.\n\nmethod ArraySum (a : array, b : array) returns (c : array)\n requires a.Length == b.Length\n ensures c.Length == a.Length && \n forall i : int :: 0 <= i < c.Length ==> c[i] == a[i] + b[i] // TODO\n{\n c := new int [a.Length]; // Creates new array of size a.Length\n var i : int := 0;\n while (i < a.Length)\n invariant i <= a.Length\n invariant forall j : int :: 0 <= j < i ==> c[j] == a[j] + b[j]\n {\n c[i] := a[i] + b[i];\n i := i + 1;\n }\n}\n\n// Question 5 (10 points)\n\n// Euclid's algorithm is used to compute the greatest common divisor of two\n// positive integers. If m and n are two such integers, then gcd(m,n) is the\n// largest positve integer that evenly divides both m and n, where j evenly divides i\n// if and only if i % j == 0 (% is the Dafny mod operator). Write requires and\n// ensures clauses for the method header Euclid below. Your requires clauses\n// should also specify that the first argument is at least as large as the second.\n// You do *not* need to implement the method!\n\nmethod Euclid (m : int, n : int) returns (gcd : int)\n requires m > 1 && n > 1 && m >= n // TODO\n ensures gcd > 0 && gcd <= n && gcd <= m && m % gcd == 0 && n % gcd == 0 // TODO\n \n\n // YOU DO NOT NEED TO IMPLEMENT Euclid!!\n\n// Question 6 (10 points)\n//\n// Give invariant(s) that enable(s) Dafny to verify the following program, which\n// returns true if and only if array a is sorted.\n\nmethod IsSorted (a : array) returns (isSorted : bool)\n ensures isSorted <==> forall j : int :: 1 <= j < a.Length ==> a[j-1] <= a[j]\n{\n isSorted := true;\n var i : int := 1;\n if (a.Length < 2)\n {\n return;\n }\n else\n {\n while (i < a.Length)\n invariant 1 <= i <= a.Length\n invariant isSorted <==> forall j: int :: 1 <= j < i ==> a[j-1] <= a[j] // TODO\n {\n if a[i-1] > a[i]\n {\n return false;\n }\n i := i+1;\n }\n }\n}\n\n// Question 7 (20 points)\n//\n// Implement, and have Dafny verify, the method IsPrime below, which returns true\n// if and only if the given positive integer is prime.\n\nmethod IsPrime (m : int) returns (isPrime : bool)\n requires m > 0 // m must be greater than 0\n ensures isPrime <==> (m > 1 && forall j : int :: 2 <= j < m ==> m % j != 0) \n\t// ensures states that \"isPrime is true iff m > 1 && not divisible by [2, m-1)\"\n{\n isPrime := true; // asume is prime initially\n \n if m <= 1 {\n isPrime := false;\n } else {\n var i : int := 2;\n \n while (i < m)\n invariant isPrime <==> forall j : int :: 2 <= j < i ==> m % j != 0\n // invariant specifies that isPrime is true iff at each j from 2 to i-1, not j | m\n {\n if (m % i == 0)\n {\n isPrime := false;\n break;\n }\n i := i + 1;\n }\n }\n \n}\n\n// Question 8 (20 points)\n//\n// Implement, and have Dafny verify, the method Reverse below, which returns a new array\n// aRev consisting of the elements of a, but in reverse order. To create a new \n// array of ints use the Dafny command \"new int[...]\", where \"...\" is the number\n// of elements in the array.\n\nmethod Reverse (a : array) returns (aRev : array)\n ensures aRev.Length == a.Length\n ensures forall i : int :: 0 <= i < a.Length ==> a[i] == aRev[aRev.Length-i-1]\n ensures fresh(aRev) // Indicates returned object is newly created in method body\n{\n aRev := new int[a.Length];\n var i : int := 0;\n while (i < a.Length)\n invariant 0 <= i <= a.Length\n invariant forall j : int :: 0 <= j < i ==> aRev[j] == a[a.Length-j-1]\n {\n aRev[i] := a[a.Length-i-1];\n i := i + 1;\n }\n}\n\n// Question 9 (20 points)\n//\n// Implement and verify method NoDups, which returns true if and only if there\n// are no duplicate elements in array a. Note that the requires clause allows\n// you to assume that a is sorted, and that this precondition is necessary for\n// the ensures clause to imply a lack of duplicates.\n\nmethod NoDups (a : array) returns (noDups : bool)\n requires forall j : int :: 0 < j < a.Length ==> a[j-1] <= a[j] // a sorted\n ensures noDups <==> forall j : int :: 1 <= j < a.Length ==> a[j-1] != a[j]\n{\n noDups := true;\n var i : int := 1;\n\n if (a.Length < 2)\n {\n return;\n }\n\n while (i < a.Length)\n invariant 1 <= i <= a.Length\n invariant noDups <==> forall j : int :: 1 <= j < i ==> a[j-1] != a[j]\n {\n if (a[i-1] == a[i])\n {\n noDups := false;\n break;\n }\n i := i + 1;\n }\n}\n", "hints_removed": "// ASSIGNMENT P1\n// CMSC 433 FALL 2023\n// PERFECT SCORE: 100 POINTS\n//\n// This assignment contains nine questions, each of which involves writing Dafny\n// code. You should include your solutions in a single Dafny file and submit it using\n// Gradescope.\n//\n// Revision history\n//\n// 2023-09-22 2:50 pm Fixed typo in Problem 3.\n\n\n// Question 1 (5 points)\n//\n// Fill in a requires clause that enables Dafny to verify\n// method PlusOne\n\nmethod PlusOne (x : int) returns (y : int)\n requires x >= 0\n ensures y > 0\n{\n y := x+1;\n}\n\n\n// Question 2 (5 points)\n//\n// Fill in requires clause(s) that enable(s) Dafny to verify the array bounds\n// in method Swap (which swaps elements i and j in array a).\n\nmethod Swap (a : array?, i : int, j : int)\n requires a != null && 0 <= i < a.Length && 0 <= j < a.Length// TODO\n modifies a // Dafny requires listing of objects modified in a method\n{\n var tmp : int := a[i];\n a[i] := a[j];\n a[j] := a[i];\n}\n\n// Question 3 (5 points)\n//\n// Give ensures clause(s) asserting that d is the result, and r the\n// remainder, of dividing m by n. Your clauses cannot use \"/\" or \"%\" (which are\n// the Dafny division and mod operators, respectively). By definition, the\n// remainder must be non-negative.\n\nmethod IntDiv (m : int, n : int) returns (d : int, r : int)\n requires n > 0\n ensures m == n * d + r && 0 <= r < n // TODO\n{\n return m / n, m % n;\n}\n\n// Question 4 (5 points)\n//\n// Give ensures clause(s) asserting that the return value has the same\n// length as array a and contains as its elements the sum of the\n// corresponding elements in arrays a and b.\n\nmethod ArraySum (a : array, b : array) returns (c : array)\n requires a.Length == b.Length\n ensures c.Length == a.Length && \n forall i : int :: 0 <= i < c.Length ==> c[i] == a[i] + b[i] // TODO\n{\n c := new int [a.Length]; // Creates new array of size a.Length\n var i : int := 0;\n while (i < a.Length)\n {\n c[i] := a[i] + b[i];\n i := i + 1;\n }\n}\n\n// Question 5 (10 points)\n\n// Euclid's algorithm is used to compute the greatest common divisor of two\n// positive integers. If m and n are two such integers, then gcd(m,n) is the\n// largest positve integer that evenly divides both m and n, where j evenly divides i\n// if and only if i % j == 0 (% is the Dafny mod operator). Write requires and\n// ensures clauses for the method header Euclid below. Your requires clauses\n// should also specify that the first argument is at least as large as the second.\n// You do *not* need to implement the method!\n\nmethod Euclid (m : int, n : int) returns (gcd : int)\n requires m > 1 && n > 1 && m >= n // TODO\n ensures gcd > 0 && gcd <= n && gcd <= m && m % gcd == 0 && n % gcd == 0 // TODO\n \n\n // YOU DO NOT NEED TO IMPLEMENT Euclid!!\n\n// Question 6 (10 points)\n//\n// Give invariant(s) that enable(s) Dafny to verify the following program, which\n// returns true if and only if array a is sorted.\n\nmethod IsSorted (a : array) returns (isSorted : bool)\n ensures isSorted <==> forall j : int :: 1 <= j < a.Length ==> a[j-1] <= a[j]\n{\n isSorted := true;\n var i : int := 1;\n if (a.Length < 2)\n {\n return;\n }\n else\n {\n while (i < a.Length)\n {\n if a[i-1] > a[i]\n {\n return false;\n }\n i := i+1;\n }\n }\n}\n\n// Question 7 (20 points)\n//\n// Implement, and have Dafny verify, the method IsPrime below, which returns true\n// if and only if the given positive integer is prime.\n\nmethod IsPrime (m : int) returns (isPrime : bool)\n requires m > 0 // m must be greater than 0\n ensures isPrime <==> (m > 1 && forall j : int :: 2 <= j < m ==> m % j != 0) \n\t// ensures states that \"isPrime is true iff m > 1 && not divisible by [2, m-1)\"\n{\n isPrime := true; // asume is prime initially\n \n if m <= 1 {\n isPrime := false;\n } else {\n var i : int := 2;\n \n while (i < m)\n // invariant specifies that isPrime is true iff at each j from 2 to i-1, not j | m\n {\n if (m % i == 0)\n {\n isPrime := false;\n break;\n }\n i := i + 1;\n }\n }\n \n}\n\n// Question 8 (20 points)\n//\n// Implement, and have Dafny verify, the method Reverse below, which returns a new array\n// aRev consisting of the elements of a, but in reverse order. To create a new \n// array of ints use the Dafny command \"new int[...]\", where \"...\" is the number\n// of elements in the array.\n\nmethod Reverse (a : array) returns (aRev : array)\n ensures aRev.Length == a.Length\n ensures forall i : int :: 0 <= i < a.Length ==> a[i] == aRev[aRev.Length-i-1]\n ensures fresh(aRev) // Indicates returned object is newly created in method body\n{\n aRev := new int[a.Length];\n var i : int := 0;\n while (i < a.Length)\n {\n aRev[i] := a[a.Length-i-1];\n i := i + 1;\n }\n}\n\n// Question 9 (20 points)\n//\n// Implement and verify method NoDups, which returns true if and only if there\n// are no duplicate elements in array a. Note that the requires clause allows\n// you to assume that a is sorted, and that this precondition is necessary for\n// the ensures clause to imply a lack of duplicates.\n\nmethod NoDups (a : array) returns (noDups : bool)\n requires forall j : int :: 0 < j < a.Length ==> a[j-1] <= a[j] // a sorted\n ensures noDups <==> forall j : int :: 1 <= j < a.Length ==> a[j-1] != a[j]\n{\n noDups := true;\n var i : int := 1;\n\n if (a.Length < 2)\n {\n return;\n }\n\n while (i < a.Length)\n {\n if (a[i-1] == a[i])\n {\n noDups := false;\n break;\n }\n i := i + 1;\n }\n}\n" }, { "test_ID": "395", "test_file": "cs245-verification_tmp_tmp0h_nxhqp_A8_Q1.dfy", "ground_truth": "// A8Q1 \u2014 Steph Renee McIntyre\n// Following the solutions from Carmen Bruni\n\n// There is no definition for power, so this function will be used for validating that our imperative program is correct. This is just for Dafny.\nfunction power(a: int, n: int): int //function for a to the power of n\n requires 0 <= n;\n decreases n;{if (n == 0) then 1 else a * power(a, n - 1)}\n\n\nmethod A8Q1(y0: int, x: int) returns (z: int)\nrequires y0 >= 0;\n/*Post-Condition*/ ensures z==power(x,y0);\n{var y := y0; //This is here for Dafny's sake and immutable inputs...\n \n /* (| y=y0 ^ y>=0 |) - Pre-Condition */\n /* (| 1=power(x,y0-y) ^ y>=0 |) - implied (a) */\n z := 1;\n /* (| z=power(x,y0-y) ^ y>=0 |) - assignment */ \n while (y>0)\n invariant z==power(x,y0-y) && y>=0; \n decreases y; /* variant */\n {\n /* (| z=power(x,y0-y) ^ y>=0 ^ y>0 |) - partial-while */ \n /* (| z*x=power(x,y0-(y-1)) ^ (y-1)>=0 |) - implied (b) */ \n z := z*x;\n /* (| z=power(x,y0-(y-1)) ^ (y-1)>=0 |) - assignment */ \n y := y-1;\n /* (| z=power(x,y0-y) ^ y>=0 |) - assignment */ \n }\n /* (| z=power(x,y0-y) ^ y>=0 ^ -(y>0) |) - partial-while */ \n /* (| z=power(x,y0-y) |) - implied (c) */ \n}\n\n/* Proof of implieds can be seen on LEARN.\n Note: If you are unconvinced, putting asserts for each condition will demonstrate the correctness of the statements. \n*/\n\n", "hints_removed": "// A8Q1 \u2014 Steph Renee McIntyre\n// Following the solutions from Carmen Bruni\n\n// There is no definition for power, so this function will be used for validating that our imperative program is correct. This is just for Dafny.\nfunction power(a: int, n: int): int //function for a to the power of n\n requires 0 <= n;\n\n\nmethod A8Q1(y0: int, x: int) returns (z: int)\nrequires y0 >= 0;\n/*Post-Condition*/ ensures z==power(x,y0);\n{var y := y0; //This is here for Dafny's sake and immutable inputs...\n \n /* (| y=y0 ^ y>=0 |) - Pre-Condition */\n /* (| 1=power(x,y0-y) ^ y>=0 |) - implied (a) */\n z := 1;\n /* (| z=power(x,y0-y) ^ y>=0 |) - assignment */ \n while (y>0)\n {\n /* (| z=power(x,y0-y) ^ y>=0 ^ y>0 |) - partial-while */ \n /* (| z*x=power(x,y0-(y-1)) ^ (y-1)>=0 |) - implied (b) */ \n z := z*x;\n /* (| z=power(x,y0-(y-1)) ^ (y-1)>=0 |) - assignment */ \n y := y-1;\n /* (| z=power(x,y0-y) ^ y>=0 |) - assignment */ \n }\n /* (| z=power(x,y0-y) ^ y>=0 ^ -(y>0) |) - partial-while */ \n /* (| z=power(x,y0-y) |) - implied (c) */ \n}\n\n/* Proof of implieds can be seen on LEARN.\n Note: If you are unconvinced, putting asserts for each condition will demonstrate the correctness of the statements. \n*/\n\n" }, { "test_ID": "396", "test_file": "cs245-verification_tmp_tmp0h_nxhqp_A8_Q2.dfy", "ground_truth": "// A8Q2 \u2014 Steph Renee McIntyre\n// Following the solutions from Carmen Bruni\n\nmethod A8Q1(x: int, y: int, z: int) returns (m: int)\n/*Pre-Condition*/ requires true;\n/*Post-Condition*/ ensures m<=x && m<=y && m<=z;\n{ \n /* (| true |) - Pre-Condition */\n if(z, n: int)\nmodifies A;\nrequires A.Length>=0 && n==A.Length;\n{\n \n var i := 0;\n var j := 0;\n \n while(i < n-1){\n while(j < n-i-1){\n if(A[j], n: int)\nmodifies A;\nrequires A.Length>=0 && n==A.Length;\n{\n \n var i := 0;\n var j := 0;\n \n while(i < n-1){\n while(j < n-i-1){\n if(A[j], n: int)\nmodifies A; requires n==A.Length;\n/* Pre-Condition */ requires n>=0; \n/* Post-Condition */ ensures forall i,j:: 0<=i<=j A[i]<=A[j]; //This states that A is sorted.\n\n//Can we write code that does not sort A that still satisfies the requirements? \n//Consider the following program:\n{\n var k := 0;\n while(k A[i]==i;\n {\n A[k] := k;\n k := k+1;\n }\n}\n\n", "hints_removed": "// Sorting: \n// Pre/Post Condition Issues - An investigation \n// -- Stephanie McIntyre\n// Based on examples in class \n\n// First Attempt at specifying requirements for sorting array A in incrementing order\n// We want our Hoare triple of (|Pre-Condition|) Code (|Post-Condition|) to hold iff A is properly sorted.\n\nmethod sort(A: array, n: int)\nmodifies A; requires n==A.Length;\n/* Pre-Condition */ requires n>=0; \n/* Post-Condition */ ensures forall i,j:: 0<=i<=j A[i]<=A[j]; //This states that A is sorted.\n\n//Can we write code that does not sort A that still satisfies the requirements? \n//Consider the following program:\n{\n var k := 0;\n while(k= 0 && a >= 0;\n/*Post-Condition*/ ensures s == power(a,n);\n{\n /* (| a >= 0 ^ n >= 0 |) - Pre-Condition: requires statement above */\n /* (| 1 = power(a,0) ^ 0<=n |) - implied (a) */ assert 1 == power(a,0) && 0<=n;\n s := 1;\n /* (| s = power(a,0) ^ 0<=n |) - assignment */ assert s == power(a,0) && 0<=n;\n var i := 0; \n /* (| s = power(a,i) ^ i<=n |) - assignment */ assert s == power(a,i) && i<=n;\n while (i < n)\n invariant s==power(a,i) && i<=n;\n decreases n-i; //this is the variant\n {\n /* (| s = power(a,i) ^ i<=n ^ i=0.\n Prior to the loop, n>=0 and i=0.\n Each iteration of the loop, i increases by 1 and thus n-i decreases by 1. Thus n-i will eventually reach 0.\n When the n-i=0, n=i and thus the loop guard ends the loop as it is no longer the case that i= 0 && a >= 0;\n/*Post-Condition*/ ensures s == power(a,n);\n{\n /* (| a >= 0 ^ n >= 0 |) - Pre-Condition: requires statement above */\n /* (| 1 = power(a,0) ^ 0<=n |) - implied (a) */ assert 1 == power(a,0) && 0<=n;\n s := 1;\n /* (| s = power(a,0) ^ 0<=n |) - assignment */ assert s == power(a,0) && 0<=n;\n var i := 0; \n /* (| s = power(a,i) ^ i<=n |) - assignment */ assert s == power(a,i) && i<=n;\n while (i < n)\n {\n /* (| s = power(a,i) ^ i<=n ^ i=0.\n Prior to the loop, n>=0 and i=0.\n Each iteration of the loop, i increases by 1 and thus n-i decreases by 1. Thus n-i will eventually reach 0.\n 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: int, p: int) returns (a: int, b: int)\nmodifies X;\n/*Pre-Condition*/ requires X.Length>=1 && n == X.Length;\n/*Post-Condition*/ ensures b>=n;\n ensures forall x:: 0<=x X[x] <= p;\n ensures forall x:: a==n || (0<=a<=x X[x] > p);\n ensures multiset(X[..])==multiset(old(X[..])) //This says the new X is a permutation of our old version of X.\n{\n a := 0;\n while ( a < n && X[a] <= p ) \n invariant 0<=a<=n\n invariant forall x:: (0<=x<=a-1 ==> X[x]<=p)\n { \n a := a+1;\n }\n \n b := a+1;\n \n while ( b a==n //This is for Dafny for access issues. Don't worry about it in our stuff.\n invariant forall x:: (0<=x<=a-1 ==> X[x]<=p);\n invariant forall x:: a==n || (0<=a<=x X[x] > p);\n invariant multiset(X[..])==multiset(old(X[..])) //This says the new X is a permutation of our old version of X.\n { \n if ( X[b] <= p ) {\n var t := X[b]; \n X[b] := X[a]; \n X[a] := t; \n a := a+1;\n }\n b := b+1;\n }\n}\n\n/* The annotations and implied proofs are left for you.\n I might do them later on next week. */\n\n", "hints_removed": "// Quicksort Partition -- Stephanie McIntyre\n// Based on examples in class \n// Parts have been modified cause you know, arrays are different...\n \nmethod QuicksortPartition(X: array, n: int, p: int) returns (a: int, b: int)\nmodifies X;\n/*Pre-Condition*/ requires X.Length>=1 && n == X.Length;\n/*Post-Condition*/ ensures b>=n;\n ensures forall x:: 0<=x X[x] <= p;\n ensures forall x:: a==n || (0<=a<=x X[x] > p);\n ensures multiset(X[..])==multiset(old(X[..])) //This says the new X is a permutation of our old version of X.\n{\n a := 0;\n while ( a < n && X[a] <= p ) \n { \n a := a+1;\n }\n \n b := a+1;\n \n while ( b x == 0) && (x - 1!= 0 ==> a == x +1);\n if(a - 1 == 0){\n y:= 1;\n } else {\n y:= a;\n }\n}\n", "hints_removed": "method Two(x: int) returns (y: int)\nensures y == x + 1\n{\n var a:= x+1;\n if(a - 1 == 0){\n y:= 1;\n } else {\n y:= a;\n }\n}\n" }, { "test_ID": "403", "test_file": "cs357_tmp_tmpn4fsvwzs_lab7_question5.dfy", "ground_truth": "method M1(x: int, y: int) returns (r: int)\nensures r == x*y\ndecreases x < 0, x\n{\n if (x == 0){\n r:= 0;\n } else if( x < 0){\n r:= M1(-x, y);\n r:= -r;\n } else {\n r:= M1(x-1, y);\n r:= A1(r, y); \n }\n}\n\nmethod A1(x: int, y: int) returns (r: int)\nensures r == x + y\n{\n r:= x;\n if( y < 0){\n var n:= y;\n while(n != 0)\n invariant r == x + y - n\n invariant -n >= 0\n {\n r:= r-1;\n n:= n + 1;\n }\n } else {\n var n := y;\n while(n!= 0)\n invariant r == x+ y - n\n invariant n >= 0\n {\n r:= r + 1;\n n:= n - 1;\n }\n }\n}\n", "hints_removed": "method M1(x: int, y: int) returns (r: int)\nensures r == x*y\n{\n if (x == 0){\n r:= 0;\n } else if( x < 0){\n r:= M1(-x, y);\n r:= -r;\n } else {\n r:= M1(x-1, y);\n r:= A1(r, y); \n }\n}\n\nmethod A1(x: int, y: int) returns (r: int)\nensures r == x + y\n{\n r:= x;\n if( y < 0){\n var n:= y;\n while(n != 0)\n {\n r:= r-1;\n n:= n + 1;\n }\n } else {\n var n := y;\n while(n!= 0)\n {\n r:= r + 1;\n n:= n - 1;\n }\n }\n}\n" }, { "test_ID": "404", "test_file": "cs686_tmp_tmpdhuh5dza_classNotes_notes-9-8-21.dfy", "ground_truth": "// Forall\nmethod Q1(){\n var a := new int[6];\n a[0], a[1], a[2], a[3], a[4], a[5] := 1,0,0,0,1,1;\n var b := new int[3];\n b[0], b[1], b[2] := 1, 0, 1;\n\n var j,k := 1,3;\n var p,r := 4,5;\n\n\n // a) All elements in the range a[j..k] == 0\n assert(forall i : int :: j<= i <= k ==> a[i] == 0);\n assert(forall i : int :: if j <= i <= k then a[i] == 0 else true);\n\n // b) All zeros in a occur in the interval a[j..k]\n assert(forall i : int :: (0 <= i < a.Length && a[i] == 0) ==> j <= i <= k);\n\n // c) It is *not* the case that all ones of a occur in the interval in a[p..r]\n\n assert(a[0] == 1); // helps the next assertion verify\n\n assert(!(forall i : int :: (0 <= i < a.Length && a[i] == 1) ==> p <= i <= r));\n\n // d) a[0..n-1] contains at least two zeros\n\n assert(a[1] == 0 && a[2] == 0);\n assert(exists i, j : int :: 0 <= i < j < a.Length && a[i] == 0 && a[j] == 0);\n\n // e) b[0..n-1] contains at the most two zeros (Note: *not* true for array a)\n assert(!(exists i, j, k : int :: 0 <= i < j< k < b.Length && b[i] == 0 && b[j] == 0 && b[k] == k));\n}\n\n// Quantifiers\nclass Secret{\n var secret : int;\n var known : bool;\n var count : int;\n\n method Init(x : int)\n modifies `secret, `known, `count\n requires 1 <= x <= 10\n ensures secret == x\n ensures known == false\n ensures count == 0\n {\n known := false;\n count := 0;\n secret := x;\n }\n\n method Guess(g : int) returns (result : bool, guesses : int)\n modifies `known, `count\n requires known == false\n ensures if g == secret then \n result == true && known == true \n else \n result == false && known == false\n ensures count == old(count) + 1 && guesses == count\n {\n if (g == secret)\n {\n known := true;\n result := true;\n }\n else\n {\n result := false;\n }\n count := count + 1;\n guesses := count;\n }\n\n method Main()\n {\n var testObject : Secret := new Secret.Init(5);\n assert(1 <= testObject.secret <= 10);\n assert(testObject.secret == 5);\n var x, y := testObject.Guess(0);\n\n assert(x == false && y == 1);\n\n x,y := testObject.Guess(5);\n\n assert(x == true && y == 2);\n\n //x,y := testObject.Guess(5);\n\n }\n}\n\n", "hints_removed": "// Forall\nmethod Q1(){\n var a := new int[6];\n a[0], a[1], a[2], a[3], a[4], a[5] := 1,0,0,0,1,1;\n var b := new int[3];\n b[0], b[1], b[2] := 1, 0, 1;\n\n var j,k := 1,3;\n var p,r := 4,5;\n\n\n // a) All elements in the range a[j..k] == 0\n\n // b) All zeros in a occur in the interval a[j..k]\n\n // c) It is *not* the case that all ones of a occur in the interval in a[p..r]\n\n\n\n // d) a[0..n-1] contains at least two zeros\n\n\n // e) b[0..n-1] contains at the most two zeros (Note: *not* true for array a)\n}\n\n// Quantifiers\nclass Secret{\n var secret : int;\n var known : bool;\n var count : int;\n\n method Init(x : int)\n modifies `secret, `known, `count\n requires 1 <= x <= 10\n ensures secret == x\n ensures known == false\n ensures count == 0\n {\n known := false;\n count := 0;\n secret := x;\n }\n\n method Guess(g : int) returns (result : bool, guesses : int)\n modifies `known, `count\n requires known == false\n ensures if g == secret then \n result == true && known == true \n else \n result == false && known == false\n ensures count == old(count) + 1 && guesses == count\n {\n if (g == secret)\n {\n known := true;\n result := true;\n }\n else\n {\n result := false;\n }\n count := count + 1;\n guesses := count;\n }\n\n method Main()\n {\n var testObject : Secret := new Secret.Init(5);\n var x, y := testObject.Guess(0);\n\n\n x,y := testObject.Guess(5);\n\n\n //x,y := testObject.Guess(5);\n\n }\n}\n\n" }, { "test_ID": "405", "test_file": "dafl_tmp_tmp_r3_8w3y_dafny_examples_dafny0_ContainerRanks.dfy", "ground_truth": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\ndatatype Abc = End | Wrapper(seq)\n\nlemma SeqRank0(a: Abc)\n ensures a != Wrapper([a])\n{\n assert [a][0] == a; // TODO: one could consider strengthening axioms to eliminate the need for this assert\n // The reason we need the assert is to match the trigger in the rank axioms produced\n // for datatypes containing sequences.\n // See \"is SeqType\" case of AddDatatype in Translator.cs\n}\n\nlemma SeqRank1(s: seq)\n requires s != []\n ensures s[0] != Wrapper(s)\n{\n}\n\ndatatype Def = End | MultiWrapper(multiset)\n\nlemma MultisetRank(a: Def)\n ensures a != MultiWrapper(multiset{a})\n{\n}\n\ndatatype Ghi = End | SetWrapper(set)\n\nlemma SetRank(a: Ghi)\n ensures a != SetWrapper({a})\n{\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\ndatatype Abc = End | Wrapper(seq)\n\nlemma SeqRank0(a: Abc)\n ensures a != Wrapper([a])\n{\n // The reason we need the assert is to match the trigger in the rank axioms produced\n // for datatypes containing sequences.\n // See \"is SeqType\" case of AddDatatype in Translator.cs\n}\n\nlemma SeqRank1(s: seq)\n requires s != []\n ensures s[0] != Wrapper(s)\n{\n}\n\ndatatype Def = End | MultiWrapper(multiset)\n\nlemma MultisetRank(a: Def)\n ensures a != MultiWrapper(multiset{a})\n{\n}\n\ndatatype Ghi = End | SetWrapper(set)\n\nlemma SetRank(a: Ghi)\n ensures a != SetWrapper({a})\n{\n}\n\n" }, { "test_ID": "406", "test_file": "dafl_tmp_tmp_r3_8w3y_dafny_examples_dafny0_DividedConstructors.dfy", "ground_truth": "// RUN: %dafny /compile:3 /env:0 /dprint:- \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nmethod Main() {\n var m := new M0.MyClass.Init(20);\n print m.a, \", \", m.b, \", \", m.c, \"\\n\";\n var r0 := new Regression.A.Make0();\n var r1 := new Regression.A.Make1();\n assert r0.b != r1.b;\n print r0.b, \", \", r1.b, \"\\n\";\n}\n\nmodule M0 {\n class MyClass {\n var a: nat\n const b := 17\n var c: real\n\n constructor Init(x: nat)\n {\n this.a := x;\n c := 3.14;\n new;\n a := a + b;\n assert c == 3.14;\n assert this.a == 17 + x;\n }\n\n constructor (z: real)\n ensures c <= 2.0 * z\n {\n a, c := 50, 2.0 * z;\n new;\n }\n\n constructor Make()\n ensures 10 <= a\n {\n new;\n a := a + b;\n }\n\n constructor Create()\n ensures 30 <= a\n {\n new;\n a := a + 2*b;\n }\n }\n}\n\nmodule M1 refines M0 {\n class MyClass ... {\n const d := 'D';\n var e: char;\n\n constructor Init...\n {\n e := 'e';\n new;\n e := 'x';\n ...;\n assert e == 'x';\n }\n\n constructor ...\n {\n e := 'y';\n new;\n }\n\n constructor Make...\n {\n new;\n e := 'z';\n }\n\n constructor Create...\n {\n e := 'w';\n }\n }\n}\n\nmodule TypeOfThis {\n class LinkedList {\n ghost var Repr: set>\n ghost var Rapr: set>\n ghost var S: set\n ghost var T: set\n\n constructor Init()\n {\n Repr := {this}; // regression test: this should pass, but once upon a time didn't\n }\n\n constructor Init'()\n {\n Rapr := {this};\n }\n\n constructor Create()\n {\n S := {this}; // regression test: this should pass, but once upon a time didn't\n }\n\n constructor Create'()\n {\n T := {this};\n }\n\n constructor Two()\n {\n new;\n var ll: LinkedList? := this;\n var o: object? := this;\n if\n case true => T := {o};\n case true => S := {o};\n case true => Repr := {ll};\n case true => Rapr := {ll};\n case true => S := {ll};\n case true => T := {ll};\n }\n\n method Mutate()\n modifies this\n {\n Repr := {this};\n Rapr := {this};\n S := {this};\n T := {this};\n }\n }\n}\n\nmodule Regression {\n class A {\n var b: bool\n var y: int\n\n constructor Make0()\n ensures b == false // regression test: this didn't used to be provable :O\n {\n b := false;\n }\n constructor Make1()\n ensures b == true\n {\n b := true;\n }\n constructor Make2()\n {\n b := false;\n new; // this sets \"alloc\" to \"true\", and the verifier previously was not\n // able to distinguish the internal field \"alloc\" from other boolean\n // fields\n assert !b; // regression test: this didn't used to be provable :O\n }\n constructor Make3()\n ensures b == false && y == 65\n {\n b := false;\n y := 65;\n new;\n assert !b; // regression test: this didn't used to be provable :O\n assert y == 65;\n }\n constructor Make4(bb: bool, yy: int)\n ensures b == bb && y == yy\n {\n b, y := bb, yy;\n }\n }\n}\n\n\n", "hints_removed": "// RUN: %dafny /compile:3 /env:0 /dprint:- \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nmethod Main() {\n var m := new M0.MyClass.Init(20);\n print m.a, \", \", m.b, \", \", m.c, \"\\n\";\n var r0 := new Regression.A.Make0();\n var r1 := new Regression.A.Make1();\n print r0.b, \", \", r1.b, \"\\n\";\n}\n\nmodule M0 {\n class MyClass {\n var a: nat\n const b := 17\n var c: real\n\n constructor Init(x: nat)\n {\n this.a := x;\n c := 3.14;\n new;\n a := a + b;\n }\n\n constructor (z: real)\n ensures c <= 2.0 * z\n {\n a, c := 50, 2.0 * z;\n new;\n }\n\n constructor Make()\n ensures 10 <= a\n {\n new;\n a := a + b;\n }\n\n constructor Create()\n ensures 30 <= a\n {\n new;\n a := a + 2*b;\n }\n }\n}\n\nmodule M1 refines M0 {\n class MyClass ... {\n const d := 'D';\n var e: char;\n\n constructor Init...\n {\n e := 'e';\n new;\n e := 'x';\n ...;\n }\n\n constructor ...\n {\n e := 'y';\n new;\n }\n\n constructor Make...\n {\n new;\n e := 'z';\n }\n\n constructor Create...\n {\n e := 'w';\n }\n }\n}\n\nmodule TypeOfThis {\n class LinkedList {\n ghost var Repr: set>\n ghost var Rapr: set>\n ghost var S: set\n ghost var T: set\n\n constructor Init()\n {\n Repr := {this}; // regression test: this should pass, but once upon a time didn't\n }\n\n constructor Init'()\n {\n Rapr := {this};\n }\n\n constructor Create()\n {\n S := {this}; // regression test: this should pass, but once upon a time didn't\n }\n\n constructor Create'()\n {\n T := {this};\n }\n\n constructor Two()\n {\n new;\n var ll: LinkedList? := this;\n var o: object? := this;\n if\n case true => T := {o};\n case true => S := {o};\n case true => Repr := {ll};\n case true => Rapr := {ll};\n case true => S := {ll};\n case true => T := {ll};\n }\n\n method Mutate()\n modifies this\n {\n Repr := {this};\n Rapr := {this};\n S := {this};\n T := {this};\n }\n }\n}\n\nmodule Regression {\n class A {\n var b: bool\n var y: int\n\n constructor Make0()\n ensures b == false // regression test: this didn't used to be provable :O\n {\n b := false;\n }\n constructor Make1()\n ensures b == true\n {\n b := true;\n }\n constructor Make2()\n {\n b := false;\n new; // this sets \"alloc\" to \"true\", and the verifier previously was not\n // able to distinguish the internal field \"alloc\" from other boolean\n // fields\n }\n constructor Make3()\n ensures b == false && y == 65\n {\n b := false;\n y := 65;\n new;\n }\n constructor Make4(bb: bool, yy: int)\n ensures b == bb && y == yy\n {\n b, y := bb, yy;\n }\n }\n}\n\n\n" }, { "test_ID": "407", "test_file": "dafl_tmp_tmp_r3_8w3y_dafny_examples_dafny0_ForallCompilationNewSyntax.dfy", "ground_truth": "// RUN: %baredafny run %args --relax-definite-assignment --quantifier-syntax:4 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nmethod Main() {\n var c := new MyClass;\n c.arr := new int[10,20];\n c.K0(3, 12);\n c.K1(3, 12);\n c.K2(3, 12);\n c.K3(3, 12);\n c.K4(12);\n c.M();\n c.N();\n c.P();\n c.Q();\n}\n\nclass MyClass\n{\n var arr: array2\n\n method K0(i: int, j: int)\n requires 0 <= i < arr.Length0 && 0 <= j < arr.Length1\n modifies arr\n {\n forall k <- {-3, 4} {\n arr[i,j] := 50;\n }\n }\n\n method K1(i: int, j: int)\n requires 0 <= i < arr.Length0 && 0 <= j < arr.Length1\n // note the absence of a modifies clause\n {\n forall k <- {} {\n arr[i,j] := k; // fine, since control will never reach here\n }\n }\n\n method K2(i: int, j: int)\n requires 0 <= i < arr.Length0 && 0 <= j < arr.Length1\n modifies arr\n {\n forall k <- {-3, 4} {\n // The following would have been an error (since this test file tests\n // compilation, we don't include the test here):\n // arr[i,j] := k; // error: k can take on more than one value\n }\n }\n\n method K3(i: int, j: int)\n requires 0 <= i < arr.Length0 && 0 <= j < arr.Length1\n modifies arr\n {\n forall k: nat <- {-3, 4} | k <= i {\n arr[k,j] := 50; // fine, since k:nat is at least 0\n }\n }\n\n method K4(j: int)\n requires 0 <= j < arr.Length1\n modifies arr\n {\n forall i | 0 <= i < arr.Length0, k: nat <- {-3, 4} {\n arr[i,j] := k; // fine, since k can only take on one value\n }\n }\n\n method M()\n {\n var ar := new int [3,3];\n var S: set := {2,0};\n forall k | k in S {\n ar[k,1]:= 0;\n }\n forall k <- S, j <- S {\n ar[k,j]:= 0;\n }\n }\n\n method N() {\n var ar := new int[3, 3];\n ar[2,2] := 0;\n }\n\n method P() {\n var ar := new int[3];\n var prev := ar[..];\n var S: set := {};\n forall k <- S {\n ar[k] := 0;\n }\n assert ar[..] == prev;\n }\n\n method Q() {\n var ar := new int[3,3];\n var S: set := {1,2};\n forall k <- S {\n ar[0,0] := 0;\n }\n assert ar[0,0] == 0;\n }\n}\n\n", "hints_removed": "// RUN: %baredafny run %args --relax-definite-assignment --quantifier-syntax:4 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nmethod Main() {\n var c := new MyClass;\n c.arr := new int[10,20];\n c.K0(3, 12);\n c.K1(3, 12);\n c.K2(3, 12);\n c.K3(3, 12);\n c.K4(12);\n c.M();\n c.N();\n c.P();\n c.Q();\n}\n\nclass MyClass\n{\n var arr: array2\n\n method K0(i: int, j: int)\n requires 0 <= i < arr.Length0 && 0 <= j < arr.Length1\n modifies arr\n {\n forall k <- {-3, 4} {\n arr[i,j] := 50;\n }\n }\n\n method K1(i: int, j: int)\n requires 0 <= i < arr.Length0 && 0 <= j < arr.Length1\n // note the absence of a modifies clause\n {\n forall k <- {} {\n arr[i,j] := k; // fine, since control will never reach here\n }\n }\n\n method K2(i: int, j: int)\n requires 0 <= i < arr.Length0 && 0 <= j < arr.Length1\n modifies arr\n {\n forall k <- {-3, 4} {\n // The following would have been an error (since this test file tests\n // compilation, we don't include the test here):\n // arr[i,j] := k; // error: k can take on more than one value\n }\n }\n\n method K3(i: int, j: int)\n requires 0 <= i < arr.Length0 && 0 <= j < arr.Length1\n modifies arr\n {\n forall k: nat <- {-3, 4} | k <= i {\n arr[k,j] := 50; // fine, since k:nat is at least 0\n }\n }\n\n method K4(j: int)\n requires 0 <= j < arr.Length1\n modifies arr\n {\n forall i | 0 <= i < arr.Length0, k: nat <- {-3, 4} {\n arr[i,j] := k; // fine, since k can only take on one value\n }\n }\n\n method M()\n {\n var ar := new int [3,3];\n var S: set := {2,0};\n forall k | k in S {\n ar[k,1]:= 0;\n }\n forall k <- S, j <- S {\n ar[k,j]:= 0;\n }\n }\n\n method N() {\n var ar := new int[3, 3];\n ar[2,2] := 0;\n }\n\n method P() {\n var ar := new int[3];\n var prev := ar[..];\n var S: set := {};\n forall k <- S {\n ar[k] := 0;\n }\n }\n\n method Q() {\n var ar := new int[3,3];\n var S: set := {1,2};\n forall k <- S {\n ar[0,0] := 0;\n }\n }\n}\n\n" }, { "test_ID": "408", "test_file": "dafl_tmp_tmp_r3_8w3y_dafny_examples_dafny0_InSetComprehension.dfy", "ground_truth": "// RUN: %dafny /compile:0 /print:\"%t.print\" /dprint:\"%t.dprint\" /printTooltips \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nlemma Tests(t: T, uu: seq) returns (z: bool)\n requires 10 <= |uu| && uu[4] == t\n ensures !z\n{\n if {\n case true =>\n z := 72 in set i | 0 <= i < 10;\n case true =>\n z := -8 in set k: nat | k < 10;\n case true =>\n z := 6 in set m | 0 <= m < 10 && Even(m) :: m + 1;\n case true =>\n z := t !in set u | u in uu;\n case true =>\n z := t !in set u {:autotriggers false} | u in uu :: Id(u);\n }\n}\n\nlemma TestsWhereTriggersMatter(t: T, uu: seq) returns (z: bool)\n requires 10 <= |uu| && uu[4] == t\n ensures z\n{\n if {\n case true =>\n z := 7 in set i | 0 <= i < 10;\n case true =>\n z := 8 in set k: nat | k < 10;\n case true =>\n // In the line below, auto-triggers should pick Even(m)\n z := 5 in set m | 0 <= m < 10 && Even(m) :: m + 1;\n // a necessary lemma:\n assert Even(4);\n case true =>\n z := t in set u | u in uu;\n case true =>\n z := t in set u {:autotriggers false} | u in uu :: Id(u);\n }\n}\n\nfunction Id(t: T): T { t }\npredicate Even(x: int) { x % 2 == 0 }\n\nclass Container {\n ghost var Contents: set\n var elems: seq\n\n method Add(t: T)\n requires Contents == set x | x in elems\n modifies this\n ensures Contents == set x | x in elems\n {\n elems := elems + [t];\n Contents := Contents + {t};\n }\n}\n\nclass IntContainer {\n ghost var Contents: set\n var elems: seq\n\n method Add(t: int)\n requires Contents == set x | x in elems\n modifies this\n ensures Contents == set x | x in elems\n {\n elems := elems + [t];\n Contents := Contents + {t};\n }\n}\n\nmethod UnboxedBoundVariables(si: seq)\n{\n var iii := set x | x in si;\n var ti := si + [115];\n var jjj := set y | y in ti;\n assert iii + {115} == jjj;\n\n var nnn := set n: nat | n in si;\n if forall i :: 0 <= i < |si| ==> 0 <= si[i] {\n assert nnn == iii;\n }\n}\n\n\n", "hints_removed": "// RUN: %dafny /compile:0 /print:\"%t.print\" /dprint:\"%t.dprint\" /printTooltips \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nlemma Tests(t: T, uu: seq) returns (z: bool)\n requires 10 <= |uu| && uu[4] == t\n ensures !z\n{\n if {\n case true =>\n z := 72 in set i | 0 <= i < 10;\n case true =>\n z := -8 in set k: nat | k < 10;\n case true =>\n z := 6 in set m | 0 <= m < 10 && Even(m) :: m + 1;\n case true =>\n z := t !in set u | u in uu;\n case true =>\n z := t !in set u {:autotriggers false} | u in uu :: Id(u);\n }\n}\n\nlemma TestsWhereTriggersMatter(t: T, uu: seq) returns (z: bool)\n requires 10 <= |uu| && uu[4] == t\n ensures z\n{\n if {\n case true =>\n z := 7 in set i | 0 <= i < 10;\n case true =>\n z := 8 in set k: nat | k < 10;\n case true =>\n // In the line below, auto-triggers should pick Even(m)\n z := 5 in set m | 0 <= m < 10 && Even(m) :: m + 1;\n // a necessary lemma:\n case true =>\n z := t in set u | u in uu;\n case true =>\n z := t in set u {:autotriggers false} | u in uu :: Id(u);\n }\n}\n\nfunction Id(t: T): T { t }\npredicate Even(x: int) { x % 2 == 0 }\n\nclass Container {\n ghost var Contents: set\n var elems: seq\n\n method Add(t: T)\n requires Contents == set x | x in elems\n modifies this\n ensures Contents == set x | x in elems\n {\n elems := elems + [t];\n Contents := Contents + {t};\n }\n}\n\nclass IntContainer {\n ghost var Contents: set\n var elems: seq\n\n method Add(t: int)\n requires Contents == set x | x in elems\n modifies this\n ensures Contents == set x | x in elems\n {\n elems := elems + [t];\n Contents := Contents + {t};\n }\n}\n\nmethod UnboxedBoundVariables(si: seq)\n{\n var iii := set x | x in si;\n var ti := si + [115];\n var jjj := set y | y in ti;\n\n var nnn := set n: nat | n in si;\n if forall i :: 0 <= i < |si| ==> 0 <= si[i] {\n }\n}\n\n\n" }, { "test_ID": "409", "test_file": "dafl_tmp_tmp_r3_8w3y_dafny_examples_dafny0_PrecedenceLinter.dfy", "ground_truth": "// RUN: %dafny /compile:0 /functionSyntax:4 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\npredicate P0(A: bool, B: bool, C: bool) {\n A &&\n B ==> C // warning: suspicious lack of parentheses (lhs of ==>)\n}\n\npredicate P1(A: bool, B: bool, C: bool) {\n A && B ==>\n C\n}\n\npredicate P2(A: bool, B: bool, C: bool) {\n A &&\n B\n ==>\n C\n}\n\npredicate P3(A: bool, B: bool, C: bool, D: bool) {\n A &&\n B ==>\n C &&\n D\n}\n\npredicate P4(A: bool, B: bool, C: bool, D: bool) {\n A &&\n B\n ==>\n C &&\n D\n}\n\npredicate P5(A: bool, B: bool, C: bool) {\n A ==>\n && B\n && C\n}\n\npredicate P6(A: bool, B: bool, C: bool) {\n A ==>\n || B\n || C\n}\n\npredicate Q0(A: bool, B: bool, C: bool, D: bool) {\n A &&\n B ==> C && // warning (x2): suspicious lack of parentheses (lhs and rhs of ==>)\n D\n}\n\npredicate Q1(A: bool, B: bool, C: bool, D: bool) {\n A &&\n B ==> C && // warning: suspicious lack of parentheses (lhs of ==>)\n D\n}\n\npredicate Q2(A: bool, B: bool, C: bool, D: bool) {\n A &&\n B ==> (C && // warning: suspicious lack of parentheses (lhs of ==>)\n D)\n}\n\npredicate Q3(A: bool, B: bool, C: bool, D: bool) {\n (A &&\n B) ==> (C &&\n D)\n}\n\npredicate Q4(A: bool, B: bool, C: bool, D: bool) {\n && A\n && B ==> C // warning (x2): suspicious lack of parentheses (lhs and rhs of ==>)\n && D\n}\n\npredicate Q4a(A: bool, B: bool, C: bool, D: bool) {\n && A\n && B ==>\n C && D\n}\n\npredicate Q4b(A: bool, B: bool, C: bool, D: bool) {\n && A\n && B ==>\n C &&\n D\n}\n\npredicate Q4c(A: bool, B: bool, C: bool, D: bool) {\n && A\n && B ==>\n && C\n && D\n}\n\npredicate Q4d(A: bool, B: bool, C: bool, D: bool) {\n && A\n && B ==>\n && C\n && D\n}\n\npredicate Q5(A: bool, B: bool, C: bool, D: bool) {\n && A\n && B ==> C // warning: suspicious lack of parentheses (lhs of ==>)\n && D\n}\n\npredicate Q6(A: bool, B: bool, C: bool, D: bool) {\n && A\n && B ==> && C // warning (x2): suspicious lack of parentheses (lhs and rhs of ==>)\n && D\n}\n\npredicate Q7(A: bool, B: bool, C: bool, D: bool) {\n A\n ==> // warning: suspicious lack of parentheses (rhs of ==>)\n B && C &&\n D\n}\n\npredicate Q8(A: bool, B: bool, C: bool, D: bool) {\n A\n ==>\n B && C &&\n D\n}\n\npredicate Q8a(A: bool, B: bool, C: bool, D: bool) {\n (A\n ==>\n B && C &&\n D\n ) &&\n (B || C)\n}\n\npredicate Q8b(A: bool, B: bool, C: bool, D: bool) {\n A &&\n B\n ==>\n B &&\n D\n}\n\npredicate Q8c(t: int, x: int, y: int)\n{\n && (t == 2 ==> x < y)\n && (|| t == 3\n || t == 2\n ==>\n && x == 100\n && y == 1000\n )\n && (t == 4 ==> || 0 <= x || 0 <= y)\n}\n\npredicate Q8d(t: int, x: int, y: int)\n{\n || t == 3\n || t == 2\n ==>\n && x == 100\n && y == 1000\n}\n\npredicate Q9(A: bool, B: bool, C: bool) {\n A ==> B ==>\n C\n}\n\nghost predicate R0(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x :: P(x) ==>\n Q(x) &&\n R(x)\n}\n\nghost predicate R1(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x :: P(x) && Q(x) ==>\n R(x)\n}\n\nghost predicate R2(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x :: P(x) ==> Q(x) ==>\n R(x)\n}\n\nghost predicate R3(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x :: P(x) ==>\n Q(x) ==>\n R(x)\n}\n\nghost predicate R4(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x :: P(x) ==> Q(x) ==>\n R(x)\n}\n\nghost predicate R5(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x :: P(x) ==>\n forall y :: Q(y) ==>\n R(x)\n}\n\nghost predicate R6(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x :: (P(x) ==> Q(x)) && // warning: suspicious lack of parentheses (forall)\n R(x)\n}\n\nghost predicate R7(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x ::\n (P(x) ==> Q(x)) &&\n R(x)\n}\n\nghost predicate R8(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x ::\n (P(x) ==> Q(x)) &&\n R(x)\n}\n\nghost predicate R9(P: int -> bool, Q: int -> bool, R: int -> bool) {\n exists x :: (P(x) ==> Q(x)) && // warning: suspicious lack of parentheses (exists)\n R(x)\n}\n\nghost predicate R10(P: int -> bool, Q: int -> bool, R: int -> bool) {\n exists x :: P(x) && // warning: suspicious lack of parentheses (exists)\n exists y :: Q(y) && // warning: suspicious lack of parentheses (exists)\n R(x)\n}\n\nlemma Injective()\n ensures forall x, y ::\n Negate(x) == Negate(y)\n ==> x == y\n{\n}\n\nfunction Negate(x: int): int {\n -x\n}\n\npredicate Quant0(s: string) {\n && s != []\n && (|| 'a' <= s[0] <= 'z'\n || 'A' <= s[0] <= 'Z')\n && forall i :: 1 <= i < |s| ==>\n || 'a' <= s[i] <= 'z'\n || 'A' <= s[i] <= 'Z'\n || '0' <= s[i] <= '9'\n}\n\npredicate Quant1(m: array2, P: int -> bool)\n reads m\n{\n forall i :: 0 <= i < m.Length0 && P(i) ==> forall j :: 0 <= j < m.Length1 ==>\n m[i, j] != \"\"\n}\n\npredicate Quant2(s: string) {\n forall i :: 0 <= i < |s| ==> if s[i] == '*' then false else\n s[i] == 'a' || s[i] == 'b'\n}\n\nghost predicate Quant3(f: int -> int, g: int -> int) {\n forall x ::\n f(x) == g(x)\n}\n\nghost predicate Quant4(f: int -> int, g: int -> int) {\n forall x :: f(x) ==\n g(x)\n}\n\nghost predicate Quant5(f: int -> int, g: int -> int) {\n forall x :: f(x)\n == g(x)\n}\n\nfunction If0(s: string): int {\n if |s| == 3 then 2 else 3 + // warning: suspicious lack of parentheses (if-then-else)\n (2 * |s|)\n}\n\nfunction If1(s: string): int {\n if |s| == 3 then 2 else\n 3 + (2 * |s|)\n}\n\nfunction If2(s: string): int {\n if |s| == 3 then 2 else (3 +\n 2 * |s|)\n}\n\nfunction If3(s: string): int {\n if |s| == 3 then 2 else\n 3 +\n 2 * |s|\n}\n\npredicate Waterfall(A: bool, B: bool, C: bool, D: bool, E: bool) {\n A ==>\n B ==>\n C ==>\n D ==>\n E\n}\n\nghost predicate MoreOps0(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x :: P(x) <== Q(x) <== // warning: suspicious lack of parentheses (rhs of <==)\n R(x)\n}\n\nghost predicate MoreOps1(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x :: P(x) <== Q(x) <==>\n R(x)\n}\n\nghost predicate MoreOps2(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x :: P(x) ==> Q(x) <==>\n R(x)\n}\n\nghost predicate MoreOps3(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x :: P(x) ==> Q(x) <==>\n R(x) ==>\n P(x)\n}\n\nghost predicate MoreOps4(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x :: P(x) <==> Q(x) && // warning: suspicious lack of parentheses (rhs of <==>)\n R(x)\n}\n\nlemma IntLemma(x: int)\n\nfunction StmtExpr0(x: int): int {\n if x == 17 then\n 2\n else\n IntLemma(x);\n 3\n}\n\nfunction StmtExpr1(x: int): int {\n if x == 17 then // warning: suspicious lack of parentheses (if-then-else)\n 2\n else\n IntLemma(x);\n 3\n}\n\nfunction StmtExpr2(x: int): int {\n if x == 17 then\n 2\n else\n assert x != 17;\n 3\n}\n\nfunction StmtExpr3(x: int): int {\n if x == 17 then // warning: suspicious lack of parentheses (if-then-else)\n 2\n else\n assert x != 17;\n 3\n}\n\nfunction FunctionWithDefaultParameterValue(x: int, y: int := 100): int\n\nfunction UseDefaultValues(x: int): int {\n if x <= 0 then 0 else\n FunctionWithDefaultParameterValue(x - 1)\n}\n\nfunction Square(x: int): int {\n x * x\n}\n\npredicate Let0(lo: int, hi: int)\n requires lo <= hi\n{\n forall x :: lo <= x < hi ==> var square := Square(x);\n 0 <= square\n}\n\nghost predicate Let1(P: int -> bool) {\n forall x :: 0 <= x && P(x) ==> var bigger :| x <= bigger;\n 0 <= bigger\n}\n\npredicate SomeProperty(x: X)\n\nmethod Parentheses0(arr: array, P: int -> bool)\n{\n assert forall i :: 0 <= i < arr.Length ==> arr[i] == old(arr\n [i]);\n var x := forall i :: 0 <= i < arr.Length ==> SomeProperty(\n arr[i]);\n var y := forall i :: 0 <= i < arr.Length ==> P(\n arr[i]);\n assert forall i :: 0 <= i < arr.Length && SomeProperty(i) ==> unchanged(\n arr);\n var u := if arr.Length == 3 then true else fresh(\n arr);\n}\n\nmethod Parentheses1(w: bool, x: int)\n{\n var a := if w then {} else {x,\n x, x};\n var b := if w then iset{} else iset{x,\n x, x};\n var c := if w then [] else [x,\n x, x];\n var d := if w then multiset{} else multiset{x,\n x, x};\n var e := if w then map[] else map[x :=\n x];\n var f := if w then imap[] else imap[\n x := x];\n}\n\ndatatype Record = Record(x: int, y: int)\n\nmethod Parentheses2(w: bool, x: int, y: int)\n{\n var a := if w then Record(0,\n 0\n ) else Record(x,\n y);\n var b := if w then\n a else a\n .\n (\n x\n :=\n y\n )\n ;\n}\n\nmethod Parentheses3(w: bool, arr: array, m: array2, i: nat, j: nat)\n requires i < j < arr.Length <= m.Length0 <= m.Length1\n{\n var a := if w then 0 else arr\n [\n i];\n var b := if w then [] else arr\n [ i .. ];\n var c := if w then [] else arr\n [..\n i];\n var d := if w then [] else arr\n [\n i..j];\n var e := if w then [] else arr\n [\n ..j][i..];\n var f := if w then [] else arr // warning: suspicious lack of parentheses (if-then-else)\n [..i] + arr[i..];\n var g := if w then 0 else m\n [i,\n j];\n var h := if w then arr[..] else arr[..j]\n [0 := 25];\n}\n\ncodatatype Stream = More(head: int, tail: Stream)\n\nmethod Parentheses4(w: bool, s: Stream, t: Stream)\n{\n ghost var a := if w then true else s ==#[\n 12] t;\n ghost var b := if w then true else s ==#[ // warning: suspicious lack of parentheses (ternary)\n 12] t;\n ghost var c := if w then true else s // warning: suspicious lack of parentheses (ternary)\n !=#[12] t;\n ghost var d := if w then true else s\n !=#[12] t;\n}\n/**** revisit the following when the original match'es are being resolved (https://github.com/dafny-lang/dafny/pull/2734)\ndatatype Color = Red | Blue\n\nmethod Parentheses5(w: bool, color: Color) {\n var a := if w then 5 else match color\n case Red => 6\n case\n Blue => 7;\n var b := if w then 5 else match\n color\n case Red => 6\n case\n Blue => 7;\n var c := if w then 5 else match color { // warning: suspicious lack of parentheses (if-then-else)\n case Red => 6\n case\n Blue => 7} + 10;\n var d :=\n match color\n case Red => 6\n case Blue => 7 // warning: suspicious lack of parentheses (case)\n + 10;\n var e :=\n match color\n case Red => 6\n + 10\n case Blue => 7;\n var f :=\n match color {\n case Red => 6\n case Blue => 7\n + 10 };\n var g :=\n if w then 5 else match color { // warning: suspicious lack of parentheses (if-then-else)\n case Red => 6\n case Blue => 7\n + 10 }\n + 20;\n}\n***/\n\nmodule MyModule {\n function MyFunction(x: int): int\n lemma Lemma(x: int)\n}\n\nmodule QualifiedNames {\n import MyModule\n\n predicate P(x: int) {\n var u := x;\n MyModule.MyFunction(x) ==\n x\n }\n\n predicate Q(x: int) {\n var u := x;\n MyModule.Lemma(x);\n x == MyModule.MyFunction(x)\n }\n\n function F(): int\n {\n var p := 1000;\n MyModule.Lemma(p);\n p\n }\n\n predicate R(x: int) {\n var u := x; // warning: suspicious lack of parentheses (let)\n MyModule.\n Lemma(x);\n x ==\n MyModule.MyFunction(x)\n }\n} \n\nmodule MatchAcrossMultipleLines {\n datatype PQ = P(int) | Q(bool)\n\n method M(s: set)\n requires\n (forall pq | pq in s :: match pq {\n case P(x) => true\n case Q(y) => y == false\n })\n {\n }\n\n datatype YZ = Y | Z\n\n function F(A: bool, B: int, C: YZ): int\n requires C != Y\n {\n if A then B else match C {\n case Z => 3\n }\n }\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 /functionSyntax:4 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\npredicate P0(A: bool, B: bool, C: bool) {\n A &&\n B ==> C // warning: suspicious lack of parentheses (lhs of ==>)\n}\n\npredicate P1(A: bool, B: bool, C: bool) {\n A && B ==>\n C\n}\n\npredicate P2(A: bool, B: bool, C: bool) {\n A &&\n B\n ==>\n C\n}\n\npredicate P3(A: bool, B: bool, C: bool, D: bool) {\n A &&\n B ==>\n C &&\n D\n}\n\npredicate P4(A: bool, B: bool, C: bool, D: bool) {\n A &&\n B\n ==>\n C &&\n D\n}\n\npredicate P5(A: bool, B: bool, C: bool) {\n A ==>\n && B\n && C\n}\n\npredicate P6(A: bool, B: bool, C: bool) {\n A ==>\n || B\n || C\n}\n\npredicate Q0(A: bool, B: bool, C: bool, D: bool) {\n A &&\n B ==> C && // warning (x2): suspicious lack of parentheses (lhs and rhs of ==>)\n D\n}\n\npredicate Q1(A: bool, B: bool, C: bool, D: bool) {\n A &&\n B ==> C && // warning: suspicious lack of parentheses (lhs of ==>)\n D\n}\n\npredicate Q2(A: bool, B: bool, C: bool, D: bool) {\n A &&\n B ==> (C && // warning: suspicious lack of parentheses (lhs of ==>)\n D)\n}\n\npredicate Q3(A: bool, B: bool, C: bool, D: bool) {\n (A &&\n B) ==> (C &&\n D)\n}\n\npredicate Q4(A: bool, B: bool, C: bool, D: bool) {\n && A\n && B ==> C // warning (x2): suspicious lack of parentheses (lhs and rhs of ==>)\n && D\n}\n\npredicate Q4a(A: bool, B: bool, C: bool, D: bool) {\n && A\n && B ==>\n C && D\n}\n\npredicate Q4b(A: bool, B: bool, C: bool, D: bool) {\n && A\n && B ==>\n C &&\n D\n}\n\npredicate Q4c(A: bool, B: bool, C: bool, D: bool) {\n && A\n && B ==>\n && C\n && D\n}\n\npredicate Q4d(A: bool, B: bool, C: bool, D: bool) {\n && A\n && B ==>\n && C\n && D\n}\n\npredicate Q5(A: bool, B: bool, C: bool, D: bool) {\n && A\n && B ==> C // warning: suspicious lack of parentheses (lhs of ==>)\n && D\n}\n\npredicate Q6(A: bool, B: bool, C: bool, D: bool) {\n && A\n && B ==> && C // warning (x2): suspicious lack of parentheses (lhs and rhs of ==>)\n && D\n}\n\npredicate Q7(A: bool, B: bool, C: bool, D: bool) {\n A\n ==> // warning: suspicious lack of parentheses (rhs of ==>)\n B && C &&\n D\n}\n\npredicate Q8(A: bool, B: bool, C: bool, D: bool) {\n A\n ==>\n B && C &&\n D\n}\n\npredicate Q8a(A: bool, B: bool, C: bool, D: bool) {\n (A\n ==>\n B && C &&\n D\n ) &&\n (B || C)\n}\n\npredicate Q8b(A: bool, B: bool, C: bool, D: bool) {\n A &&\n B\n ==>\n B &&\n D\n}\n\npredicate Q8c(t: int, x: int, y: int)\n{\n && (t == 2 ==> x < y)\n && (|| t == 3\n || t == 2\n ==>\n && x == 100\n && y == 1000\n )\n && (t == 4 ==> || 0 <= x || 0 <= y)\n}\n\npredicate Q8d(t: int, x: int, y: int)\n{\n || t == 3\n || t == 2\n ==>\n && x == 100\n && y == 1000\n}\n\npredicate Q9(A: bool, B: bool, C: bool) {\n A ==> B ==>\n C\n}\n\nghost predicate R0(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x :: P(x) ==>\n Q(x) &&\n R(x)\n}\n\nghost predicate R1(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x :: P(x) && Q(x) ==>\n R(x)\n}\n\nghost predicate R2(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x :: P(x) ==> Q(x) ==>\n R(x)\n}\n\nghost predicate R3(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x :: P(x) ==>\n Q(x) ==>\n R(x)\n}\n\nghost predicate R4(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x :: P(x) ==> Q(x) ==>\n R(x)\n}\n\nghost predicate R5(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x :: P(x) ==>\n forall y :: Q(y) ==>\n R(x)\n}\n\nghost predicate R6(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x :: (P(x) ==> Q(x)) && // warning: suspicious lack of parentheses (forall)\n R(x)\n}\n\nghost predicate R7(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x ::\n (P(x) ==> Q(x)) &&\n R(x)\n}\n\nghost predicate R8(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x ::\n (P(x) ==> Q(x)) &&\n R(x)\n}\n\nghost predicate R9(P: int -> bool, Q: int -> bool, R: int -> bool) {\n exists x :: (P(x) ==> Q(x)) && // warning: suspicious lack of parentheses (exists)\n R(x)\n}\n\nghost predicate R10(P: int -> bool, Q: int -> bool, R: int -> bool) {\n exists x :: P(x) && // warning: suspicious lack of parentheses (exists)\n exists y :: Q(y) && // warning: suspicious lack of parentheses (exists)\n R(x)\n}\n\nlemma Injective()\n ensures forall x, y ::\n Negate(x) == Negate(y)\n ==> x == y\n{\n}\n\nfunction Negate(x: int): int {\n -x\n}\n\npredicate Quant0(s: string) {\n && s != []\n && (|| 'a' <= s[0] <= 'z'\n || 'A' <= s[0] <= 'Z')\n && forall i :: 1 <= i < |s| ==>\n || 'a' <= s[i] <= 'z'\n || 'A' <= s[i] <= 'Z'\n || '0' <= s[i] <= '9'\n}\n\npredicate Quant1(m: array2, P: int -> bool)\n reads m\n{\n forall i :: 0 <= i < m.Length0 && P(i) ==> forall j :: 0 <= j < m.Length1 ==>\n m[i, j] != \"\"\n}\n\npredicate Quant2(s: string) {\n forall i :: 0 <= i < |s| ==> if s[i] == '*' then false else\n s[i] == 'a' || s[i] == 'b'\n}\n\nghost predicate Quant3(f: int -> int, g: int -> int) {\n forall x ::\n f(x) == g(x)\n}\n\nghost predicate Quant4(f: int -> int, g: int -> int) {\n forall x :: f(x) ==\n g(x)\n}\n\nghost predicate Quant5(f: int -> int, g: int -> int) {\n forall x :: f(x)\n == g(x)\n}\n\nfunction If0(s: string): int {\n if |s| == 3 then 2 else 3 + // warning: suspicious lack of parentheses (if-then-else)\n (2 * |s|)\n}\n\nfunction If1(s: string): int {\n if |s| == 3 then 2 else\n 3 + (2 * |s|)\n}\n\nfunction If2(s: string): int {\n if |s| == 3 then 2 else (3 +\n 2 * |s|)\n}\n\nfunction If3(s: string): int {\n if |s| == 3 then 2 else\n 3 +\n 2 * |s|\n}\n\npredicate Waterfall(A: bool, B: bool, C: bool, D: bool, E: bool) {\n A ==>\n B ==>\n C ==>\n D ==>\n E\n}\n\nghost predicate MoreOps0(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x :: P(x) <== Q(x) <== // warning: suspicious lack of parentheses (rhs of <==)\n R(x)\n}\n\nghost predicate MoreOps1(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x :: P(x) <== Q(x) <==>\n R(x)\n}\n\nghost predicate MoreOps2(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x :: P(x) ==> Q(x) <==>\n R(x)\n}\n\nghost predicate MoreOps3(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x :: P(x) ==> Q(x) <==>\n R(x) ==>\n P(x)\n}\n\nghost predicate MoreOps4(P: int -> bool, Q: int -> bool, R: int -> bool) {\n forall x :: P(x) <==> Q(x) && // warning: suspicious lack of parentheses (rhs of <==>)\n R(x)\n}\n\nlemma IntLemma(x: int)\n\nfunction StmtExpr0(x: int): int {\n if x == 17 then\n 2\n else\n IntLemma(x);\n 3\n}\n\nfunction StmtExpr1(x: int): int {\n if x == 17 then // warning: suspicious lack of parentheses (if-then-else)\n 2\n else\n IntLemma(x);\n 3\n}\n\nfunction StmtExpr2(x: int): int {\n if x == 17 then\n 2\n else\n 3\n}\n\nfunction StmtExpr3(x: int): int {\n if x == 17 then // warning: suspicious lack of parentheses (if-then-else)\n 2\n else\n 3\n}\n\nfunction FunctionWithDefaultParameterValue(x: int, y: int := 100): int\n\nfunction UseDefaultValues(x: int): int {\n if x <= 0 then 0 else\n FunctionWithDefaultParameterValue(x - 1)\n}\n\nfunction Square(x: int): int {\n x * x\n}\n\npredicate Let0(lo: int, hi: int)\n requires lo <= hi\n{\n forall x :: lo <= x < hi ==> var square := Square(x);\n 0 <= square\n}\n\nghost predicate Let1(P: int -> bool) {\n forall x :: 0 <= x && P(x) ==> var bigger :| x <= bigger;\n 0 <= bigger\n}\n\npredicate SomeProperty(x: X)\n\nmethod Parentheses0(arr: array, P: int -> bool)\n{\n [i]);\n var x := forall i :: 0 <= i < arr.Length ==> SomeProperty(\n arr[i]);\n var y := forall i :: 0 <= i < arr.Length ==> P(\n arr[i]);\n arr);\n var u := if arr.Length == 3 then true else fresh(\n arr);\n}\n\nmethod Parentheses1(w: bool, x: int)\n{\n var a := if w then {} else {x,\n x, x};\n var b := if w then iset{} else iset{x,\n x, x};\n var c := if w then [] else [x,\n x, x];\n var d := if w then multiset{} else multiset{x,\n x, x};\n var e := if w then map[] else map[x :=\n x];\n var f := if w then imap[] else imap[\n x := x];\n}\n\ndatatype Record = Record(x: int, y: int)\n\nmethod Parentheses2(w: bool, x: int, y: int)\n{\n var a := if w then Record(0,\n 0\n ) else Record(x,\n y);\n var b := if w then\n a else a\n .\n (\n x\n :=\n y\n )\n ;\n}\n\nmethod Parentheses3(w: bool, arr: array, m: array2, i: nat, j: nat)\n requires i < j < arr.Length <= m.Length0 <= m.Length1\n{\n var a := if w then 0 else arr\n [\n i];\n var b := if w then [] else arr\n [ i .. ];\n var c := if w then [] else arr\n [..\n i];\n var d := if w then [] else arr\n [\n i..j];\n var e := if w then [] else arr\n [\n ..j][i..];\n var f := if w then [] else arr // warning: suspicious lack of parentheses (if-then-else)\n [..i] + arr[i..];\n var g := if w then 0 else m\n [i,\n j];\n var h := if w then arr[..] else arr[..j]\n [0 := 25];\n}\n\ncodatatype Stream = More(head: int, tail: Stream)\n\nmethod Parentheses4(w: bool, s: Stream, t: Stream)\n{\n ghost var a := if w then true else s ==#[\n 12] t;\n ghost var b := if w then true else s ==#[ // warning: suspicious lack of parentheses (ternary)\n 12] t;\n ghost var c := if w then true else s // warning: suspicious lack of parentheses (ternary)\n !=#[12] t;\n ghost var d := if w then true else s\n !=#[12] t;\n}\n/**** revisit the following when the original match'es are being resolved (https://github.com/dafny-lang/dafny/pull/2734)\ndatatype Color = Red | Blue\n\nmethod Parentheses5(w: bool, color: Color) {\n var a := if w then 5 else match color\n case Red => 6\n case\n Blue => 7;\n var b := if w then 5 else match\n color\n case Red => 6\n case\n Blue => 7;\n var c := if w then 5 else match color { // warning: suspicious lack of parentheses (if-then-else)\n case Red => 6\n case\n Blue => 7} + 10;\n var d :=\n match color\n case Red => 6\n case Blue => 7 // warning: suspicious lack of parentheses (case)\n + 10;\n var e :=\n match color\n case Red => 6\n + 10\n case Blue => 7;\n var f :=\n match color {\n case Red => 6\n case Blue => 7\n + 10 };\n var g :=\n if w then 5 else match color { // warning: suspicious lack of parentheses (if-then-else)\n case Red => 6\n case Blue => 7\n + 10 }\n + 20;\n}\n***/\n\nmodule MyModule {\n function MyFunction(x: int): int\n lemma Lemma(x: int)\n}\n\nmodule QualifiedNames {\n import MyModule\n\n predicate P(x: int) {\n var u := x;\n MyModule.MyFunction(x) ==\n x\n }\n\n predicate Q(x: int) {\n var u := x;\n MyModule.Lemma(x);\n x == MyModule.MyFunction(x)\n }\n\n function F(): int\n {\n var p := 1000;\n MyModule.Lemma(p);\n p\n }\n\n predicate R(x: int) {\n var u := x; // warning: suspicious lack of parentheses (let)\n MyModule.\n Lemma(x);\n x ==\n MyModule.MyFunction(x)\n }\n} \n\nmodule MatchAcrossMultipleLines {\n datatype PQ = P(int) | Q(bool)\n\n method M(s: set)\n requires\n (forall pq | pq in s :: match pq {\n case P(x) => true\n case Q(y) => y == false\n })\n {\n }\n\n datatype YZ = Y | Z\n\n function F(A: bool, B: int, C: YZ): int\n requires C != Y\n {\n if A then B else match C {\n case Z => 3\n }\n }\n}\n\n" }, { "test_ID": "410", "test_file": "dafl_tmp_tmp_r3_8w3y_dafny_examples_dafny0_SeqFromArray.dfy", "ground_truth": "// RUN: %dafny /compile:3 /print:\"%t.print\" /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// /autoTriggers:1 added to suppress instabilities\n\nmethod Main() { }\n\nmethod H(a: array, c: array, n: nat, j: nat)\n requires j < n == a.Length == c.Length\n{\n var A := a[..];\n var C := c[..];\n\n if {\n case A[j] == C[j] =>\n assert a[j] == c[j];\n case forall i :: 0 <= i < n ==> A[i] == C[i] =>\n assert a[j] == c[j];\n case forall i :: 0 <= i < n ==> A[i] == C[i] =>\n assert forall i :: 0 <= i < n ==> a[i] == c[i];\n case A == C =>\n assert forall i :: 0 <= i < n ==> A[i] == C[i];\n case A == C =>\n assert forall i :: 0 <= i < n ==> a[i] == c[i];\n case true =>\n }\n}\n\nmethod K(a: array, c: array, n: nat)\n requires n <= a.Length && n <= c.Length\n{\n var A := a[..n];\n var C := c[..n];\n if {\n case A == C =>\n assert forall i :: 0 <= i < n ==> A[i] == C[i];\n case A == C =>\n assert forall i :: 0 <= i < n ==> a[i] == c[i];\n case true =>\n }\n}\n\nmethod L(a: array, c: array, n: nat)\n requires n <= a.Length == c.Length\n{\n var A := a[n..];\n var C := c[n..];\n var h := a.Length - n;\n if {\n case A == C =>\n assert forall i :: 0 <= i < h ==> A[i] == C[i];\n case A == C =>\n assert forall i :: n <= i < n + h ==> a[i] == c[i];\n case true =>\n }\n}\n\nmethod M(a: array, c: array, m: nat, n: nat, k: nat, l: nat)\n requires k + m <= a.Length\n requires l + n <= c.Length\n{\n var A := a[k..k+m];\n var C := c[l..l+n];\n if A == C {\n if * {\n assert m == n;\n } else if * {\n assert forall i :: 0 <= i < n ==> A[i] == C[i];\n } else if * {\n assert forall i {:nowarn} :: k <= i < k+n ==> A[i-k] == C[i-k];\n } else if * {\n assert forall i :: 0 <= i < n ==> A[i] == a[k+i];\n } else if * {\n assert forall i :: 0 <= i < n ==> C[i] == c[l+i];\n } else if * {\n assert forall i {:nowarn} :: 0 <= i < n ==> a[k+i] == c[l+i];\n }\n }\n}\n\nmethod M'(a: array, c: array, m: nat, n: nat, k: nat, l: nat)\n requires k + m <= a.Length\n requires l + n <= c.Length\n{\n if {\n case l+m <= c.Length && forall i :: 0 <= i < m ==> a[i] == c[l+i] =>\n assert a[..m] == c[l..l+m];\n case l+a.Length <= c.Length && forall i :: k <= i < a.Length ==> a[i] == c[l+i] =>\n assert a[k..] == c[l+k..l+a.Length];\n case l+k+m <= c.Length && forall i :: k <= i < k+m ==> a[i] == c[l+i] =>\n assert a[k..k+m] == c[l+k..l+k+m];\n case true =>\n }\n}\n\n", "hints_removed": "// RUN: %dafny /compile:3 /print:\"%t.print\" /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// /autoTriggers:1 added to suppress instabilities\n\nmethod Main() { }\n\nmethod H(a: array, c: array, n: nat, j: nat)\n requires j < n == a.Length == c.Length\n{\n var A := a[..];\n var C := c[..];\n\n if {\n case A[j] == C[j] =>\n case forall i :: 0 <= i < n ==> A[i] == C[i] =>\n case forall i :: 0 <= i < n ==> A[i] == C[i] =>\n case A == C =>\n case A == C =>\n case true =>\n }\n}\n\nmethod K(a: array, c: array, n: nat)\n requires n <= a.Length && n <= c.Length\n{\n var A := a[..n];\n var C := c[..n];\n if {\n case A == C =>\n case A == C =>\n case true =>\n }\n}\n\nmethod L(a: array, c: array, n: nat)\n requires n <= a.Length == c.Length\n{\n var A := a[n..];\n var C := c[n..];\n var h := a.Length - n;\n if {\n case A == C =>\n case A == C =>\n case true =>\n }\n}\n\nmethod M(a: array, c: array, m: nat, n: nat, k: nat, l: nat)\n requires k + m <= a.Length\n requires l + n <= c.Length\n{\n var A := a[k..k+m];\n var C := c[l..l+n];\n if A == C {\n if * {\n } else if * {\n } else if * {\n } else if * {\n } else if * {\n } else if * {\n }\n }\n}\n\nmethod M'(a: array, c: array, m: nat, n: nat, k: nat, l: nat)\n requires k + m <= a.Length\n requires l + n <= c.Length\n{\n if {\n case l+m <= c.Length && forall i :: 0 <= i < m ==> a[i] == c[l+i] =>\n case l+a.Length <= c.Length && forall i :: k <= i < a.Length ==> a[i] == c[l+i] =>\n case l+k+m <= c.Length && forall i :: k <= i < k+m ==> a[i] == c[l+i] =>\n case true =>\n }\n}\n\n" }, { "test_ID": "411", "test_file": "dafl_tmp_tmp_r3_8w3y_dafny_examples_dafny0_SharedDestructorsCompile.dfy", "ground_truth": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %dafny /noVerify /compile:4 /compileTarget:cs \"%s\" >> \"%t\"\n// RUN: %dafny /noVerify /compile:4 /compileTarget:py \"%s\" >> \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\ndatatype Dt =\n | A(x: int, y: real)\n | B(h: MyClass, x: int)\n | C(y: real)\n\nclass MyClass { }\n\nmethod Main()\n{\n var o := new MyClass;\n var s := [A(10, 12.0), B(o, 6), C(3.14)];\n assert s[0].x == 10 && s[0].y == 12.0;\n assert s[1].h == o && s[1].x == 6;\n assert s[2].y == 3.14;\n\n var d := s[0];\n print d, \": x=\", d.x, \" y=\", d.y, \"\\n\";\n d := s[1];\n print d, \": h=\", d.h, \" x=\", d.x, \"\\n\";\n d := s[2];\n print d, \": y=\", d.y, \"\\n\";\n\n s := [A(71, 0.1), B(o, 71)];\n var i := 0;\n while i < |s|\n {\n print d, \"\\n\";\n d := s[i];\n assert d.x == 71;\n i := i + 1;\n }\n\n BaseKlef(C3(44, 55, 66, 77));\n Matte(AA(10, 2));\n}\n\ndatatype Klef =\n | C0(0: int, 1: int, 2: int, c0: int)\n | C1(1: int, 2: int, 3: int, c1: int)\n | C2(2: int, 3: int, 0: int, c2: int)\n | C3(3: int, 0: int, 1: int, c3: int)\n\nmethod BaseKlef(k: Klef)\n requires !k.C0? && !k.C2? && !k.C1?\n{\n var k' := k.(0 := 100, c3 := 200); // makes a C3\n assert k' == C3(k.3, 100, k.1, 200);\n print k', \"\\n\";\n}\n\ndatatype Datte = AA(a: int, x: int) | BB(b: bool, x: int) | CC(c: real) | DD(x: int, o: set, p: bv27, q: T)\n\nmethod Matte(d: Datte)\n requires !d.CC?\n{\n var d := d;\n\n var s := d.(x := 5);\n print d, \" \", s, \"\\n\"; // AA(10, 2) AA(10, 5)\n\n d := BB(false, 12);\n s := d.(x := 6);\n print d, \" \", s, \"\\n\"; // BB(false, 12) BB(false, 6)\n\n d := CC(3.2);\n s := d.(c := 3.4);\n print d, \" \", s, \"\\n\"; // CC(3.2) CC(3.4)\n\n d := DD(100, {7}, 5, 9.0);\n s := d.(x := 30);\n print d, \" \", s, \"\\n\"; // DD(100, {7}, 5, 9.0) DD(30, {7}, 5, 9.0)\n s := s.(q := 2.0, p := d.p);\n print d, \" \", s, \"\\n\"; // DD(100, {7}, 5, 9.0) DD(30, {7}, 5, 2.0)\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %dafny /noVerify /compile:4 /compileTarget:cs \"%s\" >> \"%t\"\n// RUN: %dafny /noVerify /compile:4 /compileTarget:py \"%s\" >> \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\ndatatype Dt =\n | A(x: int, y: real)\n | B(h: MyClass, x: int)\n | C(y: real)\n\nclass MyClass { }\n\nmethod Main()\n{\n var o := new MyClass;\n var s := [A(10, 12.0), B(o, 6), C(3.14)];\n\n var d := s[0];\n print d, \": x=\", d.x, \" y=\", d.y, \"\\n\";\n d := s[1];\n print d, \": h=\", d.h, \" x=\", d.x, \"\\n\";\n d := s[2];\n print d, \": y=\", d.y, \"\\n\";\n\n s := [A(71, 0.1), B(o, 71)];\n var i := 0;\n while i < |s|\n {\n print d, \"\\n\";\n d := s[i];\n i := i + 1;\n }\n\n BaseKlef(C3(44, 55, 66, 77));\n Matte(AA(10, 2));\n}\n\ndatatype Klef =\n | C0(0: int, 1: int, 2: int, c0: int)\n | C1(1: int, 2: int, 3: int, c1: int)\n | C2(2: int, 3: int, 0: int, c2: int)\n | C3(3: int, 0: int, 1: int, c3: int)\n\nmethod BaseKlef(k: Klef)\n requires !k.C0? && !k.C2? && !k.C1?\n{\n var k' := k.(0 := 100, c3 := 200); // makes a C3\n print k', \"\\n\";\n}\n\ndatatype Datte = AA(a: int, x: int) | BB(b: bool, x: int) | CC(c: real) | DD(x: int, o: set, p: bv27, q: T)\n\nmethod Matte(d: Datte)\n requires !d.CC?\n{\n var d := d;\n\n var s := d.(x := 5);\n print d, \" \", s, \"\\n\"; // AA(10, 2) AA(10, 5)\n\n d := BB(false, 12);\n s := d.(x := 6);\n print d, \" \", s, \"\\n\"; // BB(false, 12) BB(false, 6)\n\n d := CC(3.2);\n s := d.(c := 3.4);\n print d, \" \", s, \"\\n\"; // CC(3.2) CC(3.4)\n\n d := DD(100, {7}, 5, 9.0);\n s := d.(x := 30);\n print d, \" \", s, \"\\n\"; // DD(100, {7}, 5, 9.0) DD(30, {7}, 5, 9.0)\n s := s.(q := 2.0, p := d.p);\n print d, \" \", s, \"\\n\"; // DD(100, {7}, 5, 9.0) DD(30, {7}, 5, 2.0)\n}\n\n" }, { "test_ID": "412", "test_file": "dafl_tmp_tmp_r3_8w3y_dafny_examples_uiowa_binary-search.dfy", "ground_truth": "\n///////////////////\n// Binary search\n///////////////////\n\n\npredicate isSorted(a:array)\n reads a\n{\n forall i:nat, j:nat :: i <= j < a.Length ==> a[i] <= a[j]\n}\n\n\n// a[lo] <= a[lo+1] <= ... <= a[hi-2] <= a[hi-1] \nmethod binSearch(a:array, K:int) returns (b:bool)\n requires isSorted(a)\n ensures b == exists i:nat :: i < a.Length && a[i] == K\n{\n\tvar lo: nat := 0 ;\n\tvar hi: nat := a.Length ;\n\twhile (lo < hi)\n decreases hi - lo\n invariant 0 <= lo <= hi <= a.Length\n //invariant forall j:nat :: j < lo ==> a[j] < K\n invariant forall i:nat :: (i < lo || hi <= i < a.Length) ==> a[i] != K\n\t{\n\t\tvar mid: nat := (lo + hi) / 2 ; assert lo <= mid <= hi ;\n\t\tif (a[mid] < K) { assert a[lo] <= a[mid]; \n assert a[mid] < K ;\n\t\t\tlo := mid + 1 ; assert mid < lo <= hi;\n\t\t} else if (a[mid] > K) { assert K < a[mid];\n\t\t\thi := mid ; assert lo <= hi == mid;\n\t\t} else {\n\t\t\treturn true ; assert a[mid] == K;\n\t\t}\n\t}\n\treturn false ; \n}\n\n/* Note: the following definition of isSorted:\n\npredicate isSorted(a:array)\n reads a\n{\n forall i:nat :: i < a.Length - 1 ==> a[i] <= a[i+1]\n}\n\nalthough equivalent to the one above is not enough for Dafny to be able \nto prove the invariants for the loop in binSearch.\n\nThe given one works because it *explicitly* states that every element \nof the input array is smaller than or equal to all later elements. \nThis fact is implied by the alternative definition of isSorted given \nhere (which only talks about array elements and their successors). \nHowever, it needs to be derived as an auxiliary lemma first, something \nthat Dafny is not currently able to do automatically. \n*/\n\n\n", "hints_removed": "\n///////////////////\n// Binary search\n///////////////////\n\n\npredicate isSorted(a:array)\n reads a\n{\n forall i:nat, j:nat :: i <= j < a.Length ==> a[i] <= a[j]\n}\n\n\n// a[lo] <= a[lo+1] <= ... <= a[hi-2] <= a[hi-1] \nmethod binSearch(a:array, K:int) returns (b:bool)\n requires isSorted(a)\n ensures b == exists i:nat :: i < a.Length && a[i] == K\n{\n\tvar lo: nat := 0 ;\n\tvar hi: nat := a.Length ;\n\twhile (lo < hi)\n //invariant forall j:nat :: j < lo ==> a[j] < K\n\t{\n\t\tvar mid: nat := (lo + hi) / 2 ; assert lo <= mid <= hi ;\n\t\tif (a[mid] < K) { assert a[lo] <= a[mid]; \n\t\t\tlo := mid + 1 ; assert mid < lo <= hi;\n\t\t} else if (a[mid] > K) { assert K < a[mid];\n\t\t\thi := mid ; assert lo <= hi == mid;\n\t\t} else {\n\t\t\treturn true ; assert a[mid] == K;\n\t\t}\n\t}\n\treturn false ; \n}\n\n/* Note: the following definition of isSorted:\n\npredicate isSorted(a:array)\n reads a\n{\n forall i:nat :: i < a.Length - 1 ==> a[i] <= a[i+1]\n}\n\nalthough equivalent to the one above is not enough for Dafny to be able \nto prove the invariants for the loop in binSearch.\n\nThe given one works because it *explicitly* states that every element \nof the input array is smaller than or equal to all later elements. \nThis fact is implied by the alternative definition of isSorted given \nhere (which only talks about array elements and their successors). \nHowever, it needs to be derived as an auxiliary lemma first, something \nthat Dafny is not currently able to do automatically. \n*/\n\n\n" }, { "test_ID": "413", "test_file": "dafl_tmp_tmp_r3_8w3y_dafny_examples_uiowa_fibonacci.dfy", "ground_truth": "/*\n CS:5810 Formal Methods in Software Engineering\n Fall 2017\n The University of Iowa\n \n Instructor: Cesare Tinelli\n\n Credits: Example adapted from Dafny tutorial\n*/\n\n\n// n = 0, 1, 2, 3, 4, 5, 6, 7, 8, ...\n// fib(n) = 0, 1, 1, 2, 3, 5, 8, 13, 21, ...\nfunction fib(n: nat): nat\n decreases n;\n{\n if n == 0 then 0 \n else if n == 1 then 1 \n else fib(n - 1) + fib(n - 2)\n}\n\nmethod ComputeFib(n: nat) returns (f: nat)\n ensures f == fib(n);\n{\n if (n == 0) \n { f := 0; }\n else {\n var i := 1;\n var f_2 := 0;\n var f_1 := 0;\n f := 1; \n while (i < n) \n decreases n - i;\n invariant i <= n;\n invariant f_1 == fib(i - 1);\n invariant f == fib(i);\n {\n f_2 := f_1;\n f_1 := f; \n f := f_1 + f_2;\n\n i := i + 1;\n }\n }\n}\n", "hints_removed": "/*\n CS:5810 Formal Methods in Software Engineering\n Fall 2017\n The University of Iowa\n \n Instructor: Cesare Tinelli\n\n Credits: Example adapted from Dafny tutorial\n*/\n\n\n// n = 0, 1, 2, 3, 4, 5, 6, 7, 8, ...\n// fib(n) = 0, 1, 1, 2, 3, 5, 8, 13, 21, ...\nfunction fib(n: nat): nat\n{\n if n == 0 then 0 \n else if n == 1 then 1 \n else fib(n - 1) + fib(n - 2)\n}\n\nmethod ComputeFib(n: nat) returns (f: nat)\n ensures f == fib(n);\n{\n if (n == 0) \n { f := 0; }\n else {\n var i := 1;\n var f_2 := 0;\n var f_1 := 0;\n f := 1; \n while (i < n) \n {\n f_2 := f_1;\n f_1 := f; \n f := f_1 + f_2;\n\n i := i + 1;\n }\n }\n}\n" }, { "test_ID": "414", "test_file": "dafl_tmp_tmp_r3_8w3y_dafny_examples_uiowa_find.dfy", "ground_truth": "/*\n CS:5810 Formal Methods in Software Engineering\n Fall 2017\n The University of Iowa\n \n Instructor: Cesare Tinelli\n\n Credits: Example adapted from Dafny tutorial\n*/\n\nmethod Find(a: array, key: int) returns (i: int)\n requires a != null;\n // if i is non-negative then \n ensures 0 <= i ==> (// (1) i is smaller than the length of a\n i < a.Length && \n // (2) key is at position i in a\n a[i] == key && \n // (3) i is the smallest position where key appears\n forall k :: 0 <= k < i ==> a[k] != key\n );\n // if index is negative then\n ensures i < 0 ==> \n // a does not contain key\n forall k :: 0 <= k < a.Length ==> a[k] != key;\n{\n i := 0;\n while (i < a.Length)\n decreases a.Length - i;\n invariant 0 <= i <= a.Length;\n // key is at none of the positions seen so far\n invariant forall k :: 0 <= k < i ==> a[k] != key;\n {\n if (a[i] == key) { return; }\n i := i + 1;\n }\n i := -1;\n}\n\n\n", "hints_removed": "/*\n CS:5810 Formal Methods in Software Engineering\n Fall 2017\n The University of Iowa\n \n Instructor: Cesare Tinelli\n\n Credits: Example adapted from Dafny tutorial\n*/\n\nmethod Find(a: array, key: int) returns (i: int)\n requires a != null;\n // if i is non-negative then \n ensures 0 <= i ==> (// (1) i is smaller than the length of a\n i < a.Length && \n // (2) key is at position i in a\n a[i] == key && \n // (3) i is the smallest position where key appears\n forall k :: 0 <= k < i ==> a[k] != key\n );\n // if index is negative then\n ensures i < 0 ==> \n // a does not contain key\n forall k :: 0 <= k < a.Length ==> a[k] != key;\n{\n i := 0;\n while (i < a.Length)\n // key is at none of the positions seen so far\n {\n if (a[i] == key) { return; }\n i := i + 1;\n }\n i := -1;\n}\n\n\n" }, { "test_ID": "415", "test_file": "dafl_tmp_tmp_r3_8w3y_dafny_examples_uiowa_modifying-arrays.dfy", "ground_truth": "/*\n CS:5810 Formal Methods in Software Engineering\n Fall 2021\n The University of Iowa\n \n Instructor: Cesare Tinelli\n\n Credits: Example adapted from material by Graeme Smith\n*/\n\n/////////////////////\n// Modifying arrays \n/////////////////////\n\n\nmethod SetEndPoints(a: array, left: int, right: int)\n requires a.Length != 0 \n modifies a \n{ \n a[0] := left; \n a[a.Length - 1] := right; \n}\n\n\nmethod Aliases(a: array, b: array) \n\trequires a.Length >= b.Length > 100 \n\tmodifies a \n{ \n a[0] := 10; \n var c := a; \n if b == a { \n b[10] := b[0] + 1; // ok since b == a\n } \n c[20] := a[14] + 2; // ok since c == a\n // b[0] := 4;\n}\n\n\n// Creating new arrays\t\n\nmethod NewArray() returns (a: array) \n ensures a.Length == 20 \n ensures fresh(a)\n{ \n a := new int[20]; \n var b := new int[30]; \n a[6] := 216; \n b[7] := 343; \n} \t\t\n\nmethod Caller() \n{ \n var a := NewArray();\n a[8] := 512; // allowed only if `a` is fresh \n}\n\n\n// Initializing arrays \n\nmethod InitArray(a: array, d: T) \n modifies a \n ensures forall i :: 0 <= i < a.Length ==> a[i] == d\n{ \n var n := 0; \n while n != a.Length \n invariant 0 <= n <= a.Length \n invariant forall i :: 0 <= i < n ==> a[i] == d\n {\n a[n] := d; \n n := n + 1; \n\t}\n}\n\n\n// Referring to prestate values of variables\n\nmethod UpdateElements(a: array) \n requires a.Length == 10 \n modifies a \n ensures old(a[4]) < a[4] \n ensures a[6] <= old(a[6]) \n ensures a[8] == old(a[8]) \n{ \n a[4] := a[4] + 3; \n a[8] := a[8] + 1; \n a[7] := 516; \n a[8] := a[8] - 1; \n}\n\n\n// Incrementing arrays \n\nmethod IncrementArray(a: array) \n modifies a \n ensures forall i :: 0 <= i < a.Length ==> a[i] == old(a[i]) + 1\n{ \n var n := 0; \n while n != a.Length \n invariant 0 <= n <= a.Length \n invariant forall i :: 0 <= i < n ==> a[i] == old(a[i]) + 1\n invariant forall i :: n <= i < a.Length ==> a[i] == old(a[i])\n { \n a[n] := a[n] + 1; \n n := n + 1; \n }\n}\n\n\n// Copying arrays \n\nmethod CopyArray(a: array, b: array) \n\t requires a.Length == b.Length \n\t modifies b \n\t ensures forall i :: 0 <= i < a.Length ==> b[i] == old(a[i])\n\t{ \n\t var n := 0; \n\t while n != a.Length \n\t invariant 0 <= n <= a.Length \n\t invariant forall i :: 0 <= i < n ==> b[i] == old(a[i]) \n\t invariant forall i :: \n\t 0 <= i < a.Length ==> a[i] == old(a[i]) \n\t { \n b[n] := a[n];\n\t n := n + 1;\n\t }\n\t}\n\n", "hints_removed": "/*\n CS:5810 Formal Methods in Software Engineering\n Fall 2021\n The University of Iowa\n \n Instructor: Cesare Tinelli\n\n Credits: Example adapted from material by Graeme Smith\n*/\n\n/////////////////////\n// Modifying arrays \n/////////////////////\n\n\nmethod SetEndPoints(a: array, left: int, right: int)\n requires a.Length != 0 \n modifies a \n{ \n a[0] := left; \n a[a.Length - 1] := right; \n}\n\n\nmethod Aliases(a: array, b: array) \n\trequires a.Length >= b.Length > 100 \n\tmodifies a \n{ \n a[0] := 10; \n var c := a; \n if b == a { \n b[10] := b[0] + 1; // ok since b == a\n } \n c[20] := a[14] + 2; // ok since c == a\n // b[0] := 4;\n}\n\n\n// Creating new arrays\t\n\nmethod NewArray() returns (a: array) \n ensures a.Length == 20 \n ensures fresh(a)\n{ \n a := new int[20]; \n var b := new int[30]; \n a[6] := 216; \n b[7] := 343; \n} \t\t\n\nmethod Caller() \n{ \n var a := NewArray();\n a[8] := 512; // allowed only if `a` is fresh \n}\n\n\n// Initializing arrays \n\nmethod InitArray(a: array, d: T) \n modifies a \n ensures forall i :: 0 <= i < a.Length ==> a[i] == d\n{ \n var n := 0; \n while n != a.Length \n {\n a[n] := d; \n n := n + 1; \n\t}\n}\n\n\n// Referring to prestate values of variables\n\nmethod UpdateElements(a: array) \n requires a.Length == 10 \n modifies a \n ensures old(a[4]) < a[4] \n ensures a[6] <= old(a[6]) \n ensures a[8] == old(a[8]) \n{ \n a[4] := a[4] + 3; \n a[8] := a[8] + 1; \n a[7] := 516; \n a[8] := a[8] - 1; \n}\n\n\n// Incrementing arrays \n\nmethod IncrementArray(a: array) \n modifies a \n ensures forall i :: 0 <= i < a.Length ==> a[i] == old(a[i]) + 1\n{ \n var n := 0; \n while n != a.Length \n { \n a[n] := a[n] + 1; \n n := n + 1; \n }\n}\n\n\n// Copying arrays \n\nmethod CopyArray(a: array, b: array) \n\t requires a.Length == b.Length \n\t modifies b \n\t ensures forall i :: 0 <= i < a.Length ==> b[i] == old(a[i])\n\t{ \n\t var n := 0; \n\t while n != a.Length \n\t 0 <= i < a.Length ==> a[i] == old(a[i]) \n\t { \n b[n] := a[n];\n\t n := n + 1;\n\t }\n\t}\n\n" }, { "test_ID": "416", "test_file": "dafleet_tmp_tmpa2e4kb9v_0001-0050_0001-two-sum.dfy", "ground_truth": "/* https://leetcode.com/problems/two-sum/\nGiven an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.\nYou may assume that each input would have exactly one solution, and you may not use the same element twice.\nYou can return the answer in any order.\n\nExample 1:\nInput: nums = [2,7,11,15], target = 9\nOutput: [0,1]\nExplanation: Because nums[0] + nums[1] == 9, we return [0, 1].\n*/\n\n\nghost predicate correct_pair(pair: (int, int), nums: seq, target: int) {\n var (i, j) := pair;\n && 0 <= i < |nums|\n && 0 <= j < |nums|\n && i != j // \"you may not use the same element twice\"\n && nums[i] + nums[j] == target\n}\n\n// We actually make a weaker pre-condition: there exists at least one solution.\n// For verification simplicity, we pretend as if:\n// - `seq` were Python list\n// - `map` were Python dict\nmethod twoSum(nums: seq, target: int) returns (pair: (int, int))\n requires exists i, j :: correct_pair((i, j), nums, target)\n ensures correct_pair(pair, nums, target)\n{\n // use a map whose keys are elements of `nums`, values are indices,\n // so that we can look up, in constant time, the \"complementary partner\" for any index.\n var e_to_i := map[];\n\n // iterate though `nums`, building the map on the fly:\n for j := 0 to |nums|\n // the following states the properties of map `e_to_i`:\n invariant forall i' | 0 <= i' < j :: nums[i'] in e_to_i /* (A) */\n invariant forall e | e in e_to_i :: 0 <= e_to_i[e] < j && nums[e_to_i[e]] == e /* (B) */\n // the following says no correct pairs exist among what we've seen so far:\n invariant forall i', j' | i' < j && j' < j :: !correct_pair((i', j'), nums, target)\n {\n var element := nums[j];\n var rest := target - element;\n if rest in e_to_i { // partner found!\n var i := e_to_i[rest];\n return (i, j);\n } else {\n e_to_i := e_to_i[element := j];\n }\n }\n // unreachable here, since there's at least one solution\n}\n\n/* Discussions\n1. It may be tempting to append `&& e_to_i[nums[i']] == i'` to the invariant (formula A),\n but this is wrong, because `nums` may contain redundant elements.\n Redundant elements will share the same key in `e_to_i`, the newer overwriting the older.\n \n2. Tip: Generally, we often need invariants when copying data from a container to another.\n To specify a set/map, we often need \"back and forth\" assertions, namely:\n (a) What elements are in the map/set (like in formula A)\n (b) What do elements in the set/map satisfy (like in formula B)\n*/\n\n", "hints_removed": "/* https://leetcode.com/problems/two-sum/\nGiven an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.\nYou may assume that each input would have exactly one solution, and you may not use the same element twice.\nYou can return the answer in any order.\n\nExample 1:\nInput: nums = [2,7,11,15], target = 9\nOutput: [0,1]\nExplanation: Because nums[0] + nums[1] == 9, we return [0, 1].\n*/\n\n\nghost predicate correct_pair(pair: (int, int), nums: seq, target: int) {\n var (i, j) := pair;\n && 0 <= i < |nums|\n && 0 <= j < |nums|\n && i != j // \"you may not use the same element twice\"\n && nums[i] + nums[j] == target\n}\n\n// We actually make a weaker pre-condition: there exists at least one solution.\n// For verification simplicity, we pretend as if:\n// - `seq` were Python list\n// - `map` were Python dict\nmethod twoSum(nums: seq, target: int) returns (pair: (int, int))\n requires exists i, j :: correct_pair((i, j), nums, target)\n ensures correct_pair(pair, nums, target)\n{\n // use a map whose keys are elements of `nums`, values are indices,\n // so that we can look up, in constant time, the \"complementary partner\" for any index.\n var e_to_i := map[];\n\n // iterate though `nums`, building the map on the fly:\n for j := 0 to |nums|\n // the following states the properties of map `e_to_i`:\n // the following says no correct pairs exist among what we've seen so far:\n {\n var element := nums[j];\n var rest := target - element;\n if rest in e_to_i { // partner found!\n var i := e_to_i[rest];\n return (i, j);\n } else {\n e_to_i := e_to_i[element := j];\n }\n }\n // unreachable here, since there's at least one solution\n}\n\n/* Discussions\n1. It may be tempting to append `&& e_to_i[nums[i']] == i'` to the invariant (formula A),\n but this is wrong, because `nums` may contain redundant elements.\n Redundant elements will share the same key in `e_to_i`, the newer overwriting the older.\n \n2. Tip: Generally, we often need invariants when copying data from a container to another.\n To specify a set/map, we often need \"back and forth\" assertions, namely:\n (a) What elements are in the map/set (like in formula A)\n (b) What do elements in the set/map satisfy (like in formula B)\n*/\n\n" }, { "test_ID": "417", "test_file": "dafleet_tmp_tmpa2e4kb9v_0001-0050_0003-longest-substring-without-repeating-characters.dfy", "ground_truth": "/* https://leetcode.com/problems/longest-substring-without-repeating-characters/\nGiven a string s, find the length of the longest substring without repeating characters.\n\nExample 1:\nInput: s = \"abcabcbb\"\nOutput: 3\nExplanation: The answer is \"abc\", with the length of 3.\n*/\n\n\n// a left-inclusive right-exclusive interval:\ntype interval = iv: (int, int) | iv.0 <= iv.1 witness (0, 0)\n\nghost function length(iv: interval): int {\n iv.1 - iv.0\n}\n\nghost predicate valid_interval(s: string, iv: interval) {\n && (0 <= iv.0 <= iv.1 <= |s|) // interval is in valid range\n && (forall i, j | iv.0 <= i < j < iv.1 :: s[i] != s[j]) // no repeating characters in interval\n}\n\n// Below shows an efficient solution using standard \"sliding window\" technique. \n// For verification simplicity, we pretend as if:\n// - `set` were Python set (or even better, a fixed-size array -- if the \"alphabet\" is small)\n//\n// `best_iv` is for verification purpose, not returned by the real program, thus `ghost`.\nmethod lengthOfLongestSubstring(s: string) returns (n: int, ghost best_iv: interval)\n ensures valid_interval(s, best_iv) && length(best_iv) == n /** `best_iv` is valid */\n ensures forall iv | valid_interval(s, iv) :: length(iv) <= n /** `best_iv` is longest */\n{\n var lo, hi := 0, 0; // initialize the interval [lo, hi)\n var char_set: set := {}; // `char_set` stores all chars within the interval\n n, best_iv := 0, (0, 0); // keep track of the max length and corresponding interval\n\n while hi < |s|\n decreases |s| - hi, |s| - lo\n // Below are \"mundane\" invariants, maintaining the relationships between variables:\n invariant 0 <= lo <= hi <= |s|\n invariant valid_interval(s, (lo, hi))\n invariant char_set == set i | lo <= i < hi :: s[i]\n invariant valid_interval(s, best_iv) && length(best_iv) == n\n // The invariant below reflects the insights behind the \"sliding window\":\n invariant forall iv: interval | iv.1 <= hi && valid_interval(s, iv) :: length(iv) <= n /* (A) */\n invariant forall iv: interval | iv.1 > hi && iv.0 < lo :: !valid_interval(s, iv) /* (B) */\n {\n if s[hi] !in char_set { // sliding `hi` to lengthen the interval:\n char_set := char_set + {s[hi]};\n hi := hi + 1;\n if hi - lo > n { // update the max length: \n n := hi - lo;\n best_iv := (lo, hi);\n }\n } else { // sliding `lo` to shorten the interval: \n char_set := char_set - {s[lo]};\n lo := lo + 1;\n }\n }\n}\n\n\n/* Discussions\n1. The \"sliding window\" technique is the most \"fancy\" part of the solution,\n ensuring an O(n) time despite the O(n^2) search space.\n The reason why it works lies in the last two invariants: (A) and (B).\n\n Invariant (A) is simply a \"partial\" guarantee for the longest valid substring in `s[..hi]`,\n so once the loop finishes, as `hi == |s|`, this \"partial\" guarantee becomes \"full\".\n\n Invariant (B) is crucial: it encodes why we can monotonically increase `lo` as we increase `hi`.\n What's the \"intuition\" behind that? Let me share an \"informal proof\" below:\n \n Let `sub(i)` be the longest valid substring whose last character is `s[i]`.\n Apparently, the final answer will be \"the longest among the longests\", i.e.\n `max(|sub(0)|, |sub(1)|, ..., |sub(|s|-1)|)`.\n\n Now, notice that the \"starting position\" of `sub(i)` is monotonically increasing regarding `i`!\n Otherwise, imagine `sub(i+1)` started at `j` while `sub(i)` started at `j+1` (or even worse),\n then `sub(i)` could be made longer (by starting at `j` instead).\n This is an obvious contradiction.\n\n Therefore, when we search for the starting position of `sub(i)` (the `lo`) for each `i` (the `hi`),\n there's no need to \"look back\".\n\n2. The solution above can be made more efficient, using \"jumping window\" instead of \"sliding window\".\n Namely, we use a dict (instead of set) to look up the \"position of repetition\",\n and move `lo` right after that position at once.\n\n You can even \"early terminate\" (based on `lo`) when all remaining intervals are doomed \"no longer\",\n resulting in even fewer number of loop iterations.\n (Time complexity will still be O(n), though.)\n\n The corresponding verification code is shown below:\n*/\n\n\n// For verification simplicity, we pretend as if:\n// - `map` were Python dict (or even better, a fixed-size array -- if the \"alphabet\" is small)\nmethod lengthOfLongestSubstring'(s: string) returns (n: int, ghost best_iv: interval)\n ensures valid_interval(s, best_iv) && length(best_iv) == n\n ensures forall iv | valid_interval(s, iv) :: length(iv) <= n\n{\n var lo, hi := 0, 0;\n var char_to_index: map := map[]; // records the \"most recent\" index of a given char\n n, best_iv := 0, (0, 0); \n\n // Once |s| - lo <= n, there will be no more chance, so early-terminate:\n while |s| - lo > n /* (C) */\n // while hi < |s| && |s| - lo > n /* (D) */\n decreases |s| - hi\n invariant 0 <= lo <= hi <= |s|\n invariant valid_interval(s, (lo, hi))\n invariant forall i | 0 <= i < hi :: s[i] in char_to_index\n invariant forall c | c in char_to_index ::\n var i := char_to_index[c]; // the \"Dafny way\" to denote `char_to_index[c]` as `i` for brevity\n 0 <= i < hi && s[i] == c\n && (forall i' | i < i' < hi :: s[i'] != c) // note: this line captures that `i` is the \"most recent\"\n invariant valid_interval(s, best_iv) && length(best_iv) == n\n invariant forall iv: interval | iv.1 <= hi && valid_interval(s, iv) :: length(iv) <= n\n invariant forall iv: interval | iv.1 > hi && iv.0 < lo :: !valid_interval(s, iv)\n {\n if s[hi] in char_to_index && char_to_index[s[hi]] >= lo { // has repetition!\n lo := char_to_index[s[hi]] + 1;\n }\n char_to_index := char_to_index[s[hi] := hi];\n hi := hi + 1;\n if hi - lo > n {\n n := hi - lo;\n best_iv := (lo, hi);\n }\n }\n}\n\n// Bonus Question:\n// \"Why can we safely use (C) instead of (D) as the loop condition? Won't `hi` go out-of-bound?\"\n// Can you figure it out?\n\n", "hints_removed": "/* https://leetcode.com/problems/longest-substring-without-repeating-characters/\nGiven a string s, find the length of the longest substring without repeating characters.\n\nExample 1:\nInput: s = \"abcabcbb\"\nOutput: 3\nExplanation: The answer is \"abc\", with the length of 3.\n*/\n\n\n// a left-inclusive right-exclusive interval:\ntype interval = iv: (int, int) | iv.0 <= iv.1 witness (0, 0)\n\nghost function length(iv: interval): int {\n iv.1 - iv.0\n}\n\nghost predicate valid_interval(s: string, iv: interval) {\n && (0 <= iv.0 <= iv.1 <= |s|) // interval is in valid range\n && (forall i, j | iv.0 <= i < j < iv.1 :: s[i] != s[j]) // no repeating characters in interval\n}\n\n// Below shows an efficient solution using standard \"sliding window\" technique. \n// For verification simplicity, we pretend as if:\n// - `set` were Python set (or even better, a fixed-size array -- if the \"alphabet\" is small)\n//\n// `best_iv` is for verification purpose, not returned by the real program, thus `ghost`.\nmethod lengthOfLongestSubstring(s: string) returns (n: int, ghost best_iv: interval)\n ensures valid_interval(s, best_iv) && length(best_iv) == n /** `best_iv` is valid */\n ensures forall iv | valid_interval(s, iv) :: length(iv) <= n /** `best_iv` is longest */\n{\n var lo, hi := 0, 0; // initialize the interval [lo, hi)\n var char_set: set := {}; // `char_set` stores all chars within the interval\n n, best_iv := 0, (0, 0); // keep track of the max length and corresponding interval\n\n while hi < |s|\n // Below are \"mundane\" invariants, maintaining the relationships between variables:\n // The invariant below reflects the insights behind the \"sliding window\":\n {\n if s[hi] !in char_set { // sliding `hi` to lengthen the interval:\n char_set := char_set + {s[hi]};\n hi := hi + 1;\n if hi - lo > n { // update the max length: \n n := hi - lo;\n best_iv := (lo, hi);\n }\n } else { // sliding `lo` to shorten the interval: \n char_set := char_set - {s[lo]};\n lo := lo + 1;\n }\n }\n}\n\n\n/* Discussions\n1. The \"sliding window\" technique is the most \"fancy\" part of the solution,\n ensuring an O(n) time despite the O(n^2) search space.\n The reason why it works lies in the last two invariants: (A) and (B).\n\n Invariant (A) is simply a \"partial\" guarantee for the longest valid substring in `s[..hi]`,\n so once the loop finishes, as `hi == |s|`, this \"partial\" guarantee becomes \"full\".\n\n Invariant (B) is crucial: it encodes why we can monotonically increase `lo` as we increase `hi`.\n What's the \"intuition\" behind that? Let me share an \"informal proof\" below:\n \n Let `sub(i)` be the longest valid substring whose last character is `s[i]`.\n Apparently, the final answer will be \"the longest among the longests\", i.e.\n `max(|sub(0)|, |sub(1)|, ..., |sub(|s|-1)|)`.\n\n Now, notice that the \"starting position\" of `sub(i)` is monotonically increasing regarding `i`!\n Otherwise, imagine `sub(i+1)` started at `j` while `sub(i)` started at `j+1` (or even worse),\n then `sub(i)` could be made longer (by starting at `j` instead).\n This is an obvious contradiction.\n\n Therefore, when we search for the starting position of `sub(i)` (the `lo`) for each `i` (the `hi`),\n there's no need to \"look back\".\n\n2. The solution above can be made more efficient, using \"jumping window\" instead of \"sliding window\".\n Namely, we use a dict (instead of set) to look up the \"position of repetition\",\n and move `lo` right after that position at once.\n\n You can even \"early terminate\" (based on `lo`) when all remaining intervals are doomed \"no longer\",\n resulting in even fewer number of loop iterations.\n (Time complexity will still be O(n), though.)\n\n The corresponding verification code is shown below:\n*/\n\n\n// For verification simplicity, we pretend as if:\n// - `map` were Python dict (or even better, a fixed-size array -- if the \"alphabet\" is small)\nmethod lengthOfLongestSubstring'(s: string) returns (n: int, ghost best_iv: interval)\n ensures valid_interval(s, best_iv) && length(best_iv) == n\n ensures forall iv | valid_interval(s, iv) :: length(iv) <= n\n{\n var lo, hi := 0, 0;\n var char_to_index: map := map[]; // records the \"most recent\" index of a given char\n n, best_iv := 0, (0, 0); \n\n // Once |s| - lo <= n, there will be no more chance, so early-terminate:\n while |s| - lo > n /* (C) */\n // while hi < |s| && |s| - lo > n /* (D) */\n var i := char_to_index[c]; // the \"Dafny way\" to denote `char_to_index[c]` as `i` for brevity\n 0 <= i < hi && s[i] == c\n && (forall i' | i < i' < hi :: s[i'] != c) // note: this line captures that `i` is the \"most recent\"\n {\n if s[hi] in char_to_index && char_to_index[s[hi]] >= lo { // has repetition!\n lo := char_to_index[s[hi]] + 1;\n }\n char_to_index := char_to_index[s[hi] := hi];\n hi := hi + 1;\n if hi - lo > n {\n n := hi - lo;\n best_iv := (lo, hi);\n }\n }\n}\n\n// Bonus Question:\n// \"Why can we safely use (C) instead of (D) as the loop condition? Won't `hi` go out-of-bound?\"\n// Can you figure it out?\n\n" }, { "test_ID": "418", "test_file": "dafleet_tmp_tmpa2e4kb9v_0001-0050_0005-longest-palindromic-substring.dfy", "ground_truth": "/* https://leetcode.com/problems/longest-palindromic-substring/\nGiven a string s, return the longest palindromic substring in s.\n\nExample 1:\nInput: s = \"babad\"\nOutput: \"bab\"\nExplanation: \"aba\" is also a valid answer.\n*/\n\n\n// Specifying the problem: whether `s[i..j]` is palindromic\nghost predicate palindromic(s: string, i: int, j: int)\n requires 0 <= i <= j <= |s|\n decreases j - i\n{\n j - i < 2 || (s[i] == s[j-1] && palindromic(s, i+1, j-1))\n}\n\n// A \"common sense\" about palindromes:\nlemma lemma_palindromic_contains(s: string, lo: int, hi: int, lo': int, hi': int)\n requires 0 <= lo <= lo' <= hi' <= hi <= |s|\n requires lo + hi == lo' + hi'\n requires palindromic(s, lo, hi)\n ensures palindromic(s, lo', hi')\n decreases lo' - lo\n{\n if lo < lo' {\n lemma_palindromic_contains(s, lo + 1, hi - 1, lo', hi');\n }\n}\n\n// A useful \"helper function\" that returns the longest palindrome at a given center (i0, j0).\nmethod expand_from_center(s: string, i0: int, j0: int) returns (lo: int, hi: int)\n requires 0 <= i0 <= j0 <= |s|\n requires palindromic(s, i0, j0)\n ensures 0 <= lo <= hi <= |s| && palindromic(s, lo, hi)\n ensures forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) // Among all palindromes\n && i + j == i0 + j0 // sharing the same center,\n :: j - i <= hi - lo // `s[lo..hi]` is longest.\n{\n lo, hi := i0, j0;\n\n // we try expanding whenever possible:\n while lo - 1 >= 0 && hi < |s| && s[lo - 1] == s[hi]\n invariant 0 <= lo <= hi <= |s| && lo + hi == i0 + j0\n invariant palindromic(s, lo, hi)\n {\n lo, hi := lo - 1, hi + 1;\n }\n\n // proves that we cannot go further:\n forall i, j | 0 <= i <= j <= |s| && i + j == i0 + j0 && j - i > hi - lo ensures !palindromic(s, i, j) {\n if palindromic(s, i, j) { // prove by contradiction:\n lemma_palindromic_contains(s, i, j, lo - 1, hi + 1);\n }\n }\n}\n\n\n// The main algorithm.\n// We traverse all centers from left to right, and \"expand\" each of them, to find the longest palindrome.\nmethod longestPalindrome(s: string) returns (ans: string, lo: int, hi: int)\n ensures 0 <= lo <= hi <= |s| && ans == s[lo..hi] // `ans` is indeed a substring in `s`\n ensures palindromic(s, lo, hi) // `ans` is palindromic\n ensures forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) :: j - i <= hi - lo // `ans` is longest\n{\n lo, hi := 0, 0;\n for k := 0 to |s|\n invariant 0 <= lo <= hi <= |s|\n invariant palindromic(s, lo, hi)\n invariant forall i, j | 0 <= i <= j <= |s| && i + j < 2 * k && palindromic(s, i, j) :: j - i <= hi - lo\n {\n var a, b := expand_from_center(s, k, k);\n if b - a > hi - lo {\n lo, hi := a, b;\n }\n var c, d := expand_from_center(s, k, k + 1);\n if d - c > hi - lo {\n lo, hi := c, d;\n }\n }\n return s[lo..hi], lo, hi;\n}\n\n\n/* Discussions\n1. Dafny is super bad at slicing (esp. nested slicing).\n Do circumvent it whenever possible. It can save you a lot of assertions & lemmas!\n\n For example, instead of `palindromic(s[i..j])`, use the pattern `palindromic(s, i, j)` instead.\n I didn't realize this (ref: https://github.com/Nangos/dafleet/commit/3302ddd7642240ff2b2f6a8c51e8becd5c9b6437),\n Resulting in a couple of clumsy lemmas.\n\n2. Bonus -- Manacher's algorithm\n Our above solution needs `O(|s|^2)` time in the worst case. Can we improve it? Yes.\n\n Manacher's algorithm guarantees an `O(|s|)` time.\n To get the intuition, ask yourself: when will it really take `O(|s|^2)` time?\n When there are a lot of \"nesting and overlapping\" palindromes. like in `abcbcbcba` or even `aaaaaa`.\n\n Imagine each palindrome as a \"mirror\". \"Large mirrors\" reflect \"small mirrors\".\n Therefore, when we \"expand\" from some \"center\", we can \"reuse\" some information from its \"mirrored center\".\n For example, we move the \"center\", from left to right, in the string `aiaOaia...`\n Here, the char `O` is the \"large mirror\".\n When the current center is the second `i`, it is \"mirrored\" to the first `i` (which we've calculated for),\n so we know the palindrome centered at the second `i` must have at least a length of 3 (`aia`).\n So we can expand directly from `aia`, instead of expanding from scratch.\n\n Manacher's algorithm is verified below.\n Also, I will verify that \"every loop is entered for only `O(|s|)` times\",\n which \"indirectly\" proves that the entire algorithm runs in `O(|s|)` time.\n*/\n\n\n// A reference implementation of Manacher's algorithm:\n// (Ref. https://en.wikipedia.org/wiki/Longest_palindromic_substring#Manacher's_algorithm) for details...\nmethod {:vcs_split_on_every_assert} longestPalindrome'(s: string) returns (ans: string, lo: int, hi: int)\n ensures 0 <= lo <= hi <= |s| && ans == s[lo..hi]\n ensures palindromic(s, lo, hi)\n ensures forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) :: j - i <= hi - lo\n{\n var bogus: char :| true; // an arbitrary character\n var s' := insert_bogus_chars(s, bogus);\n var radii := new int[|s'|];\n var center, radius := 0, 0;\n // vars below are just for verifying time complexity:\n ghost var loop_counter_outer, loop_counter_inner1, loop_counter_inner2 := 0, 0, 0;\n\n while center < |s'|\n invariant 0 <= center <= |s'|\n invariant forall c | 0 <= c < center :: max_radius(s', c, radii[c])\n invariant center < |s'| ==> inbound_radius(s', center, radius) && palindromic_radius(s', center, radius)\n invariant center == |s'| ==> radius == 0\n invariant loop_counter_outer <= center\n invariant loop_counter_inner1 <= center + radius && loop_counter_inner2 <= center\n {\n loop_counter_outer := loop_counter_outer + 1;\n\n // Stage 1: Still the normal \"expand from center\" routine, except `radius` is NOT necessarily zero:\n while center - (radius + 1) >= 0 && center + (radius + 1) < |s'|\n && s'[center - (radius + 1)] == s'[center + (radius + 1)]\n decreases center - radius\n invariant inbound_radius(s', center, radius) && palindromic_radius(s', center, radius)\n invariant loop_counter_inner1 <= center + radius\n {\n loop_counter_inner1 := loop_counter_inner1 + 1;\n radius := radius + 1;\n }\n lemma_end_of_expansion(s', center, radius);\n\n radii[center] := radius;\n var old_center, old_radius := center, radius;\n center := center + 1;\n radius := 0;\n\n // Stage 2: Quickly infer the maximal radius, using the symmetry of known palindromes. \n while center <= old_center + old_radius\n invariant 0 <= center <= |s'|\n invariant forall c | 0 <= c < center :: max_radius(s', c, radii[c])\n invariant center < |s'| ==> inbound_radius(s', center, radius) && palindromic_radius(s', center, radius)\n invariant loop_counter_inner2 <= center - 1\n {\n loop_counter_inner2 := loop_counter_inner2 + 1;\n\n var mirrored_center := old_center - (center - old_center);\n var max_mirrored_radius := old_center + old_radius - center;\n lemma_mirrored_palindrome(s', old_center, old_radius, mirrored_center, radii[mirrored_center], center);\n\n if radii[mirrored_center] < max_mirrored_radius {\n radii[center] := radii[mirrored_center];\n center := center + 1;\n } else if radii[mirrored_center] > max_mirrored_radius {\n radii[center] := max_mirrored_radius;\n center := center + 1;\n } else {\n radius := max_mirrored_radius;\n break;\n }\n }\n }\n // verify that the worst time complexity (measured by loop iterations) is O(|s'|) == O(|s|):\n assert |s'| == 2 * |s| + 1;\n assert loop_counter_outer <= |s'|;\n assert loop_counter_inner1 <= |s'|;\n assert loop_counter_inner2 <= |s'|; \n\n // wrap up results:\n var (c, r) := argmax(radii, 0);\n lo, hi := (c - r) / 2, (c + r) / 2; // notice that both ends are bogus chars at position 0, 2, 4, 6, etc.!\n lemma_result_transfer(s, s', bogus, radii, c, r, hi, lo);\n return s[lo..hi], lo, hi; \n}\n\n\n// Below are helper functions and lemmas we used:\n\n// Inserts bogus characters to the original string (e.g. from `abc` to `|a|b|c|`).\n// Note that this is neither efficient nor necessary in reality, but just for the ease of understanding.\nfunction {:opaque} insert_bogus_chars(s: string, bogus: char): (s': string)\n ensures |s'| == 2 * |s| + 1\n ensures forall i | 0 <= i <= |s| :: s'[i * 2] == bogus\n ensures forall i | 0 <= i < |s| :: s'[i * 2 + 1] == s[i]\n{\n if s == \"\" then\n [bogus]\n else\n var s'_old := insert_bogus_chars(s[1..], bogus);\n var s'_new := [bogus] + [s[0]] + s'_old;\n assert forall i | 1 <= i <= |s| :: s'_new[i * 2] == s'_old[(i-1) * 2];\n s'_new\n}\n\n// Returns (max_index, max_value) of array `a` starting from index `start`.\nfunction {:opaque} argmax(a: array, start: int): (res: (int, int))\n reads a\n requires 0 <= start < a.Length\n ensures start <= res.0 < a.Length && a[res.0] == res.1\n ensures forall i | start <= i < a.Length :: a[i] <= res.1\n decreases a.Length - start\n{\n if start == a.Length - 1 then\n (start, a[start])\n else\n var (i, v) := argmax(a, start + 1);\n if a[start] >= v then (start, a[start]) else (i, v)\n}\n\n// Whether an interval at center `c` with a radius `r` is within the boundary of `s'`.\nghost predicate inbound_radius(s': string, c: int, r: int)\n{\n r >= 0 && 0 <= c-r && c+r < |s'|\n}\n\n// Whether `r` is a valid palindromic radius at center `c`.\nghost predicate palindromic_radius(s': string, c: int, r: int)\n requires inbound_radius(s', c, r)\n{\n palindromic(s', c-r, c+r+1)\n}\n\n// Whether `r` is the maximal palindromic radius at center `c`.\nghost predicate max_radius(s': string, c: int, r: int)\n{\n && inbound_radius(s', c, r)\n && palindromic_radius(s', c, r)\n && (forall r' | r' > r && inbound_radius(s', c, r') :: !palindromic_radius(s', c, r'))\n}\n\n// Basically, just \"rephrasing\" the `lemma_palindromic_contains`,\n// talking about center and radius, instead of interval\nlemma lemma_palindromic_radius_contains(s': string, c: int, r: int, r': int)\n requires inbound_radius(s', c, r) && palindromic_radius(s', c, r)\n requires 0 <= r' <= r\n ensures inbound_radius(s', c, r') && palindromic_radius(s', c, r')\n{\n lemma_palindromic_contains(s', c-r, c+r+1, c-r', c+r'+1);\n}\n\n// When \"expand from center\" ends, we've find the max radius:\nlemma lemma_end_of_expansion(s': string, c: int, r: int)\n requires inbound_radius(s', c, r) && palindromic_radius(s', c, r)\n requires inbound_radius(s', c, r + 1) ==> s'[c - (r + 1)] != s'[c + (r + 1)]\n ensures max_radius(s', c, r)\n{\n forall r' | r' > r && inbound_radius(s', c, r') ensures !palindromic_radius(s', c, r') {\n if palindromic_radius(s', c, r') { // proof by contradiction\n lemma_palindromic_radius_contains(s', c, r', r+1);\n }\n }\n}\n\n// The critical insight behind Manacher's algorithm.\n//\n// Given the longest palindrome centered at `c` has length `r`, consider the interval from `c-r` to `c+r`.\n// Consider a pair of centers in the interval: `c1` (left half) and `c2` (right half), equally away from `c`.\n// Then, the length of longest palindromes at `c1` and `c2` are related as follows:\nlemma lemma_mirrored_palindrome(s': string, c: int, r: int, c1: int, r1: int, c2: int)\n requires max_radius(s', c, r) && max_radius(s', c1, r1)\n requires c - r <= c1 < c < c2 <= c + r\n requires c2 - c == c - c1\n ensures c2 + r1 < c + r ==> max_radius(s', c2, r1)\n ensures c2 + r1 > c + r ==> max_radius(s', c2, c + r - c2)\n ensures c2 + r1 == c + r ==> palindromic_radius(s', c2, c + r - c2)\n{\n // proof looks long, but is quite straightforward at each step:\n if c2 + r1 < c + r {\n for r2 := 0 to r1\n invariant palindromic_radius(s', c2, r2)\n {\n var r2' := r2 + 1;\n assert s'[c1+r2'] == s'[c2-r2'] by { lemma_palindromic_radius_contains(s', c, r, abs(c - c1 - r2')); }\n assert s'[c1-r2'] == s'[c2+r2'] by { lemma_palindromic_radius_contains(s', c, r, abs(c - c1 + r2')); }\n assert s'[c1-r2'] == s'[c1+r2'] by { lemma_palindromic_radius_contains(s', c1, r1, r2'); }\n }\n var r2' := r1 + 1;\n assert s'[c1+r2'] == s'[c2-r2'] by { lemma_palindromic_radius_contains(s', c, r, abs(c - c1 - r2')); }\n assert s'[c1-r2'] == s'[c2+r2'] by { lemma_palindromic_radius_contains(s', c, r, abs(c - c1 + r2')); }\n assert s'[c1-r2'] != s'[c1+r2'] by { assert !palindromic_radius(s', c1, r2'); }\n lemma_end_of_expansion(s', c2, r1);\n } else {\n for r2 := 0 to c + r - c2\n invariant palindromic_radius(s', c2, r2)\n {\n var r2' := r2 + 1;\n assert s'[c1+r2'] == s'[c2-r2'] by { lemma_palindromic_radius_contains(s', c, r, abs(c - c1 - r2')); }\n assert s'[c1-r2'] == s'[c2+r2'] by { lemma_palindromic_radius_contains(s', c, r, abs(c - c1 + r2')); }\n assert s'[c1-r2'] == s'[c1+r2'] by { lemma_palindromic_radius_contains(s', c1, r1, r2'); }\n }\n if c2 + r1 > c + r {\n var r2' := (c + r - c2) + 1;\n if inbound_radius(s', c, r + 1) {\n assert s'[c1+r2'] == s'[c2-r2'] by { lemma_palindromic_radius_contains(s', c, r, abs(c - c1 - r2')); }\n assert s'[c1-r2'] != s'[c2+r2'] by { assert !palindromic_radius(s', c, r + 1); }\n assert s'[c1-r2'] == s'[c1+r2'] by { lemma_palindromic_radius_contains(s', c1, r1, r2'); }\n lemma_end_of_expansion(s', c2, c + r - c2);\n }\n }\n }\n}\n//, where:\nghost function abs(x: int): int {\n if x >= 0 then x else -x\n}\n\n// Transfering our final result on `s'` to that on `s`:\nlemma lemma_result_transfer(s: string, s': string, bogus: char, radii: array, c: int, r: int, hi: int, lo: int)\n requires s' == insert_bogus_chars(s, bogus)\n requires radii.Length == |s'|\n requires forall i | 0 <= i < radii.Length :: max_radius(s', i, radii[i])\n requires (c, r) == argmax(radii, 0)\n requires lo == (c - r) / 2 && hi == (c + r) / 2\n ensures 0 <= lo <= hi <= |s|\n ensures palindromic(s, lo, hi)\n ensures forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) :: j - i <= hi - lo\n{\n // For each center, rephrase [maximal radius in `s'`] into [maximal interval in `s`]:\n forall k | 0 <= k < radii.Length\n ensures max_interval_for_same_center(s, k, (k - radii[k]) / 2, (k + radii[k]) / 2) {\n // We need to show `k` and `radii[k]` are either \"both odd\" or \"both even\". We prove by contradiction:\n if (k + radii[k]) % 2 == 1 {\n lemma_palindrome_bogus(s, s', bogus, k, radii[k]);\n }\n // We then relate `s` and `s'` using their \"isomorphism\":\n var lo, hi := (k - radii[k]) / 2, (k + radii[k]) / 2;\n lemma_palindrome_isomorph(s, s', bogus, lo, hi);\n forall i, j | 0 <= i <= j <= |s| && i + j == k && j - i > radii[k] ensures !palindromic(s, i, j) {\n lemma_palindrome_isomorph(s, s', bogus, i, j);\n }\n }\n\n // We then iteratively build the last post-condition: \n for k := 0 to radii.Length - 1\n invariant forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) && i + j <= k :: j - i <= hi - lo\n {\n forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) && i + j == k + 1 ensures j - i <= hi - lo {\n var k := k + 1;\n assert max_interval_for_same_center(s, k, (k - radii[k]) / 2, (k + radii[k]) / 2);\n }\n }\n}\n\n// The following returns whether `s[lo..hi]` is the longest palindrome s.t. `lo + hi == k`:\nghost predicate max_interval_for_same_center(s: string, k: int, lo: int, hi: int) {\n && 0 <= lo <= hi <= |s|\n && lo + hi == k\n && palindromic(s, lo, hi)\n && (forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) && i + j == k :: j - i <= hi - lo)\n}\n\n// Establishes the \"palindromic isomorphism\" between `s` and `s'`.\nlemma lemma_palindrome_isomorph(s: string, s': string, bogus: char, lo: int, hi: int)\n requires s' == insert_bogus_chars(s, bogus)\n requires 0 <= lo <= hi <= |s| \n ensures palindromic(s, lo, hi) <==> palindromic_radius(s', lo + hi, hi - lo)\n{\n if palindromic(s, lo, hi) { // ==>\n for r := 0 to hi - lo\n invariant palindromic_radius(s', lo + hi, r)\n {\n if (lo + hi - r) % 2 == 1 {\n lemma_palindrome_bogus(s, s', bogus, lo + hi, r);\n } else { \n var i', j' := lo + hi - (r + 1), lo + hi + (r + 1);\n var i, j := i' / 2, j' / 2;\n assert s[i] == s[j] by { lemma_palindromic_contains(s, lo, hi, i, j + 1); }\n // Notice that `s'[i'] == s[i] && s'[j'] == s[j]`; apparently Dafny does\n }\n }\n }\n if palindromic_radius(s', lo + hi, hi - lo) { // <==\n var lo', hi' := lo, hi;\n while lo' + 1 <= hi' - 1\n invariant lo <= lo' <= hi' <= hi\n invariant lo' + hi' == lo + hi\n invariant palindromic_radius(s', lo + hi, hi' - lo')\n invariant palindromic(s, lo', hi') ==> palindromic(s, lo, hi) // \"reversed construction\"\n {\n assert palindromic_radius(s', lo + hi, hi' - lo' - 1); // ignore bogus chars and move on\n lo', hi' := lo' + 1, hi' - 1;\n }\n }\n}\n\n// Implies that whenever `c + r` is odd, the corresponding palindrome can be \"lengthened for free\"\n// because its both ends are the bogus char.\nlemma lemma_palindrome_bogus(s: string, s': string, bogus: char, c: int, r: int)\n requires s' == insert_bogus_chars(s, bogus)\n requires inbound_radius(s', c, r) && palindromic_radius(s', c, r)\n requires (c + r) % 2 == 1\n ensures inbound_radius(s', c, r + 1) && palindromic_radius(s', c, r + 1)\n{\n var left, right := c - (r + 1), c + (r + 1);\n assert left == (left / 2) * 2;\n assert right == (right / 2) * 2;\n assert s'[left] == s'[right] == bogus;\n}\n\n", "hints_removed": "/* https://leetcode.com/problems/longest-palindromic-substring/\nGiven a string s, return the longest palindromic substring in s.\n\nExample 1:\nInput: s = \"babad\"\nOutput: \"bab\"\nExplanation: \"aba\" is also a valid answer.\n*/\n\n\n// Specifying the problem: whether `s[i..j]` is palindromic\nghost predicate palindromic(s: string, i: int, j: int)\n requires 0 <= i <= j <= |s|\n{\n j - i < 2 || (s[i] == s[j-1] && palindromic(s, i+1, j-1))\n}\n\n// A \"common sense\" about palindromes:\nlemma lemma_palindromic_contains(s: string, lo: int, hi: int, lo': int, hi': int)\n requires 0 <= lo <= lo' <= hi' <= hi <= |s|\n requires lo + hi == lo' + hi'\n requires palindromic(s, lo, hi)\n ensures palindromic(s, lo', hi')\n{\n if lo < lo' {\n lemma_palindromic_contains(s, lo + 1, hi - 1, lo', hi');\n }\n}\n\n// A useful \"helper function\" that returns the longest palindrome at a given center (i0, j0).\nmethod expand_from_center(s: string, i0: int, j0: int) returns (lo: int, hi: int)\n requires 0 <= i0 <= j0 <= |s|\n requires palindromic(s, i0, j0)\n ensures 0 <= lo <= hi <= |s| && palindromic(s, lo, hi)\n ensures forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) // Among all palindromes\n && i + j == i0 + j0 // sharing the same center,\n :: j - i <= hi - lo // `s[lo..hi]` is longest.\n{\n lo, hi := i0, j0;\n\n // we try expanding whenever possible:\n while lo - 1 >= 0 && hi < |s| && s[lo - 1] == s[hi]\n {\n lo, hi := lo - 1, hi + 1;\n }\n\n // proves that we cannot go further:\n forall i, j | 0 <= i <= j <= |s| && i + j == i0 + j0 && j - i > hi - lo ensures !palindromic(s, i, j) {\n if palindromic(s, i, j) { // prove by contradiction:\n lemma_palindromic_contains(s, i, j, lo - 1, hi + 1);\n }\n }\n}\n\n\n// The main algorithm.\n// We traverse all centers from left to right, and \"expand\" each of them, to find the longest palindrome.\nmethod longestPalindrome(s: string) returns (ans: string, lo: int, hi: int)\n ensures 0 <= lo <= hi <= |s| && ans == s[lo..hi] // `ans` is indeed a substring in `s`\n ensures palindromic(s, lo, hi) // `ans` is palindromic\n ensures forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) :: j - i <= hi - lo // `ans` is longest\n{\n lo, hi := 0, 0;\n for k := 0 to |s|\n {\n var a, b := expand_from_center(s, k, k);\n if b - a > hi - lo {\n lo, hi := a, b;\n }\n var c, d := expand_from_center(s, k, k + 1);\n if d - c > hi - lo {\n lo, hi := c, d;\n }\n }\n return s[lo..hi], lo, hi;\n}\n\n\n/* Discussions\n1. Dafny is super bad at slicing (esp. nested slicing).\n Do circumvent it whenever possible. It can save you a lot of assertions & lemmas!\n\n For example, instead of `palindromic(s[i..j])`, use the pattern `palindromic(s, i, j)` instead.\n I didn't realize this (ref: https://github.com/Nangos/dafleet/commit/3302ddd7642240ff2b2f6a8c51e8becd5c9b6437),\n Resulting in a couple of clumsy lemmas.\n\n2. Bonus -- Manacher's algorithm\n Our above solution needs `O(|s|^2)` time in the worst case. Can we improve it? Yes.\n\n Manacher's algorithm guarantees an `O(|s|)` time.\n To get the intuition, ask yourself: when will it really take `O(|s|^2)` time?\n When there are a lot of \"nesting and overlapping\" palindromes. like in `abcbcbcba` or even `aaaaaa`.\n\n Imagine each palindrome as a \"mirror\". \"Large mirrors\" reflect \"small mirrors\".\n Therefore, when we \"expand\" from some \"center\", we can \"reuse\" some information from its \"mirrored center\".\n For example, we move the \"center\", from left to right, in the string `aiaOaia...`\n Here, the char `O` is the \"large mirror\".\n When the current center is the second `i`, it is \"mirrored\" to the first `i` (which we've calculated for),\n so we know the palindrome centered at the second `i` must have at least a length of 3 (`aia`).\n So we can expand directly from `aia`, instead of expanding from scratch.\n\n Manacher's algorithm is verified below.\n Also, I will verify that \"every loop is entered for only `O(|s|)` times\",\n which \"indirectly\" proves that the entire algorithm runs in `O(|s|)` time.\n*/\n\n\n// A reference implementation of Manacher's algorithm:\n// (Ref. https://en.wikipedia.org/wiki/Longest_palindromic_substring#Manacher's_algorithm) for details...\nmethod {:vcs_split_on_every_assert} longestPalindrome'(s: string) returns (ans: string, lo: int, hi: int)\n ensures 0 <= lo <= hi <= |s| && ans == s[lo..hi]\n ensures palindromic(s, lo, hi)\n ensures forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) :: j - i <= hi - lo\n{\n var bogus: char :| true; // an arbitrary character\n var s' := insert_bogus_chars(s, bogus);\n var radii := new int[|s'|];\n var center, radius := 0, 0;\n // vars below are just for verifying time complexity:\n ghost var loop_counter_outer, loop_counter_inner1, loop_counter_inner2 := 0, 0, 0;\n\n while center < |s'|\n {\n loop_counter_outer := loop_counter_outer + 1;\n\n // Stage 1: Still the normal \"expand from center\" routine, except `radius` is NOT necessarily zero:\n while center - (radius + 1) >= 0 && center + (radius + 1) < |s'|\n && s'[center - (radius + 1)] == s'[center + (radius + 1)]\n {\n loop_counter_inner1 := loop_counter_inner1 + 1;\n radius := radius + 1;\n }\n lemma_end_of_expansion(s', center, radius);\n\n radii[center] := radius;\n var old_center, old_radius := center, radius;\n center := center + 1;\n radius := 0;\n\n // Stage 2: Quickly infer the maximal radius, using the symmetry of known palindromes. \n while center <= old_center + old_radius\n {\n loop_counter_inner2 := loop_counter_inner2 + 1;\n\n var mirrored_center := old_center - (center - old_center);\n var max_mirrored_radius := old_center + old_radius - center;\n lemma_mirrored_palindrome(s', old_center, old_radius, mirrored_center, radii[mirrored_center], center);\n\n if radii[mirrored_center] < max_mirrored_radius {\n radii[center] := radii[mirrored_center];\n center := center + 1;\n } else if radii[mirrored_center] > max_mirrored_radius {\n radii[center] := max_mirrored_radius;\n center := center + 1;\n } else {\n radius := max_mirrored_radius;\n break;\n }\n }\n }\n // verify that the worst time complexity (measured by loop iterations) is O(|s'|) == O(|s|):\n\n // wrap up results:\n var (c, r) := argmax(radii, 0);\n lo, hi := (c - r) / 2, (c + r) / 2; // notice that both ends are bogus chars at position 0, 2, 4, 6, etc.!\n lemma_result_transfer(s, s', bogus, radii, c, r, hi, lo);\n return s[lo..hi], lo, hi; \n}\n\n\n// Below are helper functions and lemmas we used:\n\n// Inserts bogus characters to the original string (e.g. from `abc` to `|a|b|c|`).\n// Note that this is neither efficient nor necessary in reality, but just for the ease of understanding.\nfunction {:opaque} insert_bogus_chars(s: string, bogus: char): (s': string)\n ensures |s'| == 2 * |s| + 1\n ensures forall i | 0 <= i <= |s| :: s'[i * 2] == bogus\n ensures forall i | 0 <= i < |s| :: s'[i * 2 + 1] == s[i]\n{\n if s == \"\" then\n [bogus]\n else\n var s'_old := insert_bogus_chars(s[1..], bogus);\n var s'_new := [bogus] + [s[0]] + s'_old;\n s'_new\n}\n\n// Returns (max_index, max_value) of array `a` starting from index `start`.\nfunction {:opaque} argmax(a: array, start: int): (res: (int, int))\n reads a\n requires 0 <= start < a.Length\n ensures start <= res.0 < a.Length && a[res.0] == res.1\n ensures forall i | start <= i < a.Length :: a[i] <= res.1\n{\n if start == a.Length - 1 then\n (start, a[start])\n else\n var (i, v) := argmax(a, start + 1);\n if a[start] >= v then (start, a[start]) else (i, v)\n}\n\n// Whether an interval at center `c` with a radius `r` is within the boundary of `s'`.\nghost predicate inbound_radius(s': string, c: int, r: int)\n{\n r >= 0 && 0 <= c-r && c+r < |s'|\n}\n\n// Whether `r` is a valid palindromic radius at center `c`.\nghost predicate palindromic_radius(s': string, c: int, r: int)\n requires inbound_radius(s', c, r)\n{\n palindromic(s', c-r, c+r+1)\n}\n\n// Whether `r` is the maximal palindromic radius at center `c`.\nghost predicate max_radius(s': string, c: int, r: int)\n{\n && inbound_radius(s', c, r)\n && palindromic_radius(s', c, r)\n && (forall r' | r' > r && inbound_radius(s', c, r') :: !palindromic_radius(s', c, r'))\n}\n\n// Basically, just \"rephrasing\" the `lemma_palindromic_contains`,\n// talking about center and radius, instead of interval\nlemma lemma_palindromic_radius_contains(s': string, c: int, r: int, r': int)\n requires inbound_radius(s', c, r) && palindromic_radius(s', c, r)\n requires 0 <= r' <= r\n ensures inbound_radius(s', c, r') && palindromic_radius(s', c, r')\n{\n lemma_palindromic_contains(s', c-r, c+r+1, c-r', c+r'+1);\n}\n\n// When \"expand from center\" ends, we've find the max radius:\nlemma lemma_end_of_expansion(s': string, c: int, r: int)\n requires inbound_radius(s', c, r) && palindromic_radius(s', c, r)\n requires inbound_radius(s', c, r + 1) ==> s'[c - (r + 1)] != s'[c + (r + 1)]\n ensures max_radius(s', c, r)\n{\n forall r' | r' > r && inbound_radius(s', c, r') ensures !palindromic_radius(s', c, r') {\n if palindromic_radius(s', c, r') { // proof by contradiction\n lemma_palindromic_radius_contains(s', c, r', r+1);\n }\n }\n}\n\n// The critical insight behind Manacher's algorithm.\n//\n// Given the longest palindrome centered at `c` has length `r`, consider the interval from `c-r` to `c+r`.\n// Consider a pair of centers in the interval: `c1` (left half) and `c2` (right half), equally away from `c`.\n// Then, the length of longest palindromes at `c1` and `c2` are related as follows:\nlemma lemma_mirrored_palindrome(s': string, c: int, r: int, c1: int, r1: int, c2: int)\n requires max_radius(s', c, r) && max_radius(s', c1, r1)\n requires c - r <= c1 < c < c2 <= c + r\n requires c2 - c == c - c1\n ensures c2 + r1 < c + r ==> max_radius(s', c2, r1)\n ensures c2 + r1 > c + r ==> max_radius(s', c2, c + r - c2)\n ensures c2 + r1 == c + r ==> palindromic_radius(s', c2, c + r - c2)\n{\n // proof looks long, but is quite straightforward at each step:\n if c2 + r1 < c + r {\n for r2 := 0 to r1\n {\n var r2' := r2 + 1;\n }\n var r2' := r1 + 1;\n lemma_end_of_expansion(s', c2, r1);\n } else {\n for r2 := 0 to c + r - c2\n {\n var r2' := r2 + 1;\n }\n if c2 + r1 > c + r {\n var r2' := (c + r - c2) + 1;\n if inbound_radius(s', c, r + 1) {\n lemma_end_of_expansion(s', c2, c + r - c2);\n }\n }\n }\n}\n//, where:\nghost function abs(x: int): int {\n if x >= 0 then x else -x\n}\n\n// Transfering our final result on `s'` to that on `s`:\nlemma lemma_result_transfer(s: string, s': string, bogus: char, radii: array, c: int, r: int, hi: int, lo: int)\n requires s' == insert_bogus_chars(s, bogus)\n requires radii.Length == |s'|\n requires forall i | 0 <= i < radii.Length :: max_radius(s', i, radii[i])\n requires (c, r) == argmax(radii, 0)\n requires lo == (c - r) / 2 && hi == (c + r) / 2\n ensures 0 <= lo <= hi <= |s|\n ensures palindromic(s, lo, hi)\n ensures forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) :: j - i <= hi - lo\n{\n // For each center, rephrase [maximal radius in `s'`] into [maximal interval in `s`]:\n forall k | 0 <= k < radii.Length\n ensures max_interval_for_same_center(s, k, (k - radii[k]) / 2, (k + radii[k]) / 2) {\n // We need to show `k` and `radii[k]` are either \"both odd\" or \"both even\". We prove by contradiction:\n if (k + radii[k]) % 2 == 1 {\n lemma_palindrome_bogus(s, s', bogus, k, radii[k]);\n }\n // We then relate `s` and `s'` using their \"isomorphism\":\n var lo, hi := (k - radii[k]) / 2, (k + radii[k]) / 2;\n lemma_palindrome_isomorph(s, s', bogus, lo, hi);\n forall i, j | 0 <= i <= j <= |s| && i + j == k && j - i > radii[k] ensures !palindromic(s, i, j) {\n lemma_palindrome_isomorph(s, s', bogus, i, j);\n }\n }\n\n // We then iteratively build the last post-condition: \n for k := 0 to radii.Length - 1\n {\n forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) && i + j == k + 1 ensures j - i <= hi - lo {\n var k := k + 1;\n }\n }\n}\n\n// The following returns whether `s[lo..hi]` is the longest palindrome s.t. `lo + hi == k`:\nghost predicate max_interval_for_same_center(s: string, k: int, lo: int, hi: int) {\n && 0 <= lo <= hi <= |s|\n && lo + hi == k\n && palindromic(s, lo, hi)\n && (forall i, j | 0 <= i <= j <= |s| && palindromic(s, i, j) && i + j == k :: j - i <= hi - lo)\n}\n\n// Establishes the \"palindromic isomorphism\" between `s` and `s'`.\nlemma lemma_palindrome_isomorph(s: string, s': string, bogus: char, lo: int, hi: int)\n requires s' == insert_bogus_chars(s, bogus)\n requires 0 <= lo <= hi <= |s| \n ensures palindromic(s, lo, hi) <==> palindromic_radius(s', lo + hi, hi - lo)\n{\n if palindromic(s, lo, hi) { // ==>\n for r := 0 to hi - lo\n {\n if (lo + hi - r) % 2 == 1 {\n lemma_palindrome_bogus(s, s', bogus, lo + hi, r);\n } else { \n var i', j' := lo + hi - (r + 1), lo + hi + (r + 1);\n var i, j := i' / 2, j' / 2;\n // Notice that `s'[i'] == s[i] && s'[j'] == s[j]`; apparently Dafny does\n }\n }\n }\n if palindromic_radius(s', lo + hi, hi - lo) { // <==\n var lo', hi' := lo, hi;\n while lo' + 1 <= hi' - 1\n {\n lo', hi' := lo' + 1, hi' - 1;\n }\n }\n}\n\n// Implies that whenever `c + r` is odd, the corresponding palindrome can be \"lengthened for free\"\n// because its both ends are the bogus char.\nlemma lemma_palindrome_bogus(s: string, s': string, bogus: char, c: int, r: int)\n requires s' == insert_bogus_chars(s, bogus)\n requires inbound_radius(s', c, r) && palindromic_radius(s', c, r)\n requires (c + r) % 2 == 1\n ensures inbound_radius(s', c, r + 1) && palindromic_radius(s', c, r + 1)\n{\n var left, right := c - (r + 1), c + (r + 1);\n}\n\n" }, { "test_ID": "419", "test_file": "dafny-aoc-2019_tmp_tmpj6suy_rv_parser_split.dfy", "ground_truth": "module Split {\n function splitHelper(s: string, separator: string, index: nat, sindex: nat, results: seq): seq>\n requires index <= |s|\n requires sindex <= |s|\n requires sindex <= index\n // requires forall ss: string :: ss in results ==> NotContains(ss,separator)\n // ensures forall ss :: ss in splitHelper(s, separator, index, sindex, results) ==> NotContains(ss, separator)\n decreases |s| - index\n {\n if index >= |s| then results + [s[sindex..index]]\n else if |separator| == 0 && index == |s|-1 then splitHelper(s, separator, index+1, index, results)\n else if |separator| == 0 then \n assert separator == [];\n assert s[sindex..index+1] != [];\n splitHelper(s, separator, index+1, index+1, results + [s[sindex..(index+1)]])\n else if index+|separator| > |s| then splitHelper(s, separator, |s|, sindex, results)\n else if s[index..index+|separator|] == separator then splitHelper(s, separator, index+|separator|, index+|separator|, results + [s[sindex..index]])\n else splitHelper(s, separator, index+1, sindex, results)\n }\n\n function split(s: string, separator: string): seq \n ensures split(s, separator) == splitHelper(s, separator, 0,0, [])\n {\n splitHelper(s, separator, 0, 0, [])\n }\n\n predicate Contains(haystack: string, needle: string)\n // ensures !NotContainsThree(haystack, needle)\n ensures Contains(haystack, needle) <==> exists k :: 0 <= k <= |haystack| && needle <= haystack[k..] \n ensures Contains(haystack, needle) <==> exists i :: 0 <= i <= |haystack| && (needle <= haystack[i..])\n ensures !Contains(haystack, needle) <==> forall i :: 0 <= i <= |haystack| ==> !(needle <= haystack[i..])\n {\n if needle <= haystack then \n assert haystack[0..] == haystack;\n true \n else if |haystack| > 0 then \n assert forall i :: 1 <= i <= |haystack| ==> haystack[i..] == haystack[1..][(i-1)..];\n Contains(haystack[1..], needle)\n else \n false\n }\n\n function splitOnBreak(s: string): seq {\n if Contains(s, \"\\r\\n\") then split(s,\"\\r\\n\") else split(s,\"\\n\")\n }\n\n function splitOnDoubleBreak(s: string): seq {\n if Contains(s, \"\\r\\n\") then split(s,\"\\r\\n\\r\\n\") else split(s,\"\\n\\n\")\n }\n}\n", "hints_removed": "module Split {\n function splitHelper(s: string, separator: string, index: nat, sindex: nat, results: seq): seq>\n requires index <= |s|\n requires sindex <= |s|\n requires sindex <= index\n // requires forall ss: string :: ss in results ==> NotContains(ss,separator)\n // ensures forall ss :: ss in splitHelper(s, separator, index, sindex, results) ==> NotContains(ss, separator)\n {\n if index >= |s| then results + [s[sindex..index]]\n else if |separator| == 0 && index == |s|-1 then splitHelper(s, separator, index+1, index, results)\n else if |separator| == 0 then \n splitHelper(s, separator, index+1, index+1, results + [s[sindex..(index+1)]])\n else if index+|separator| > |s| then splitHelper(s, separator, |s|, sindex, results)\n else if s[index..index+|separator|] == separator then splitHelper(s, separator, index+|separator|, index+|separator|, results + [s[sindex..index]])\n else splitHelper(s, separator, index+1, sindex, results)\n }\n\n function split(s: string, separator: string): seq \n ensures split(s, separator) == splitHelper(s, separator, 0,0, [])\n {\n splitHelper(s, separator, 0, 0, [])\n }\n\n predicate Contains(haystack: string, needle: string)\n // ensures !NotContainsThree(haystack, needle)\n ensures Contains(haystack, needle) <==> exists k :: 0 <= k <= |haystack| && needle <= haystack[k..] \n ensures Contains(haystack, needle) <==> exists i :: 0 <= i <= |haystack| && (needle <= haystack[i..])\n ensures !Contains(haystack, needle) <==> forall i :: 0 <= i <= |haystack| ==> !(needle <= haystack[i..])\n {\n if needle <= haystack then \n true \n else if |haystack| > 0 then \n Contains(haystack[1..], needle)\n else \n false\n }\n\n function splitOnBreak(s: string): seq {\n if Contains(s, \"\\r\\n\") then split(s,\"\\r\\n\") else split(s,\"\\n\")\n }\n\n function splitOnDoubleBreak(s: string): seq {\n if Contains(s, \"\\r\\n\") then split(s,\"\\r\\n\\r\\n\") else split(s,\"\\n\\n\")\n }\n}\n" }, { "test_ID": "420", "test_file": "dafny-duck_tmp_tmplawbgxjo_ex3.dfy", "ground_truth": "// program verifies\npredicate sortedbad(s: string)\n{\n // no b's after non-b's\n forall i, j :: 0 <= i <= j < |s| && s[i] == 'b' && s[j] != 'b' ==> i < j &&\n // only non-d's before d's\n forall i, j :: 0 <= i <= j < |s| && s[i] != 'd' && s[j] == 'd' ==> i < j\n}\n\nmethod BadSort(a: string) returns (b: string)\nrequires forall i :: 0<=i<|a| ==> a[i] in {'b', 'a', 'd'}\nensures sortedbad(b)\nensures multiset(b[..]) == multiset(a[..])\n{\n b := a;\n var next:int := 0;\n var aPointer:int := 0;\n var dPointer:int := |b|;\n\n while (next != dPointer)\n decreases if next <= dPointer then dPointer - next else next - dPointer\n invariant 0 <= aPointer <= next <= dPointer <= |b|\n invariant forall i :: 0 <= i < aPointer ==> b[i] == 'b'\n invariant forall i :: aPointer <= i < next ==> b[i] == 'a'\n invariant forall i :: dPointer <= i < |b| ==> b[i] == 'd'\n invariant forall i :: 0<=i<|b| ==> b[i] in {'b', 'a', 'd'}\n invariant sortedbad(b)\n invariant multiset(b[..]) == multiset(a[..])\n {\n \n if(b[next] == 'a'){\n next := next + 1;\n } \n \n else if(b[next] == 'b'){\n b := b[next := b[aPointer]][aPointer := b[next]];\n next := next + 1;\n aPointer := aPointer + 1;\n }\n \n else{\n dPointer := dPointer - 1;\n b := b[next := b[dPointer]][dPointer := b[next]];\n } \n } \n}\n\n", "hints_removed": "// program verifies\npredicate sortedbad(s: string)\n{\n // no b's after non-b's\n forall i, j :: 0 <= i <= j < |s| && s[i] == 'b' && s[j] != 'b' ==> i < j &&\n // only non-d's before d's\n forall i, j :: 0 <= i <= j < |s| && s[i] != 'd' && s[j] == 'd' ==> i < j\n}\n\nmethod BadSort(a: string) returns (b: string)\nrequires forall i :: 0<=i<|a| ==> a[i] in {'b', 'a', 'd'}\nensures sortedbad(b)\nensures multiset(b[..]) == multiset(a[..])\n{\n b := a;\n var next:int := 0;\n var aPointer:int := 0;\n var dPointer:int := |b|;\n\n while (next != dPointer)\n {\n \n if(b[next] == 'a'){\n next := next + 1;\n } \n \n else if(b[next] == 'b'){\n b := b[next := b[aPointer]][aPointer := b[next]];\n next := next + 1;\n aPointer := aPointer + 1;\n }\n \n else{\n dPointer := dPointer - 1;\n b := b[next := b[dPointer]][dPointer := b[next]];\n } \n } \n}\n\n" }, { "test_ID": "421", "test_file": "dafny-duck_tmp_tmplawbgxjo_ex5.dfy", "ground_truth": "// program verifies\nfunction expo(x:int, n:nat): int\n{\n if n == 0 then 1\n else x * expo(x, n-1)\n}\n\nlemma {:induction false} Expon23(n: nat)\nrequires n >= 0\nensures ((expo(2,3*n) - expo(3,n)) % (2+3)) == 0\n{ \n // base case\n if (n == 0) {\n assert (expo(2,3*0)-expo(3,0)) % 5 == 0;\n }\n\n else if (n == 1) {\n assert (expo(2,3*1)-expo(3,1)) % 5 == 0;\n }\n else {\n Expon23(n-1); // lemma proved for case n-1 \n assert (expo(2,3*(n-1)) - expo(3,n-1)) % 5 == 0;\n \n // training dafny up\n assert expo(2,3*n) == expo(2,3*(n-1)+2)*expo(2,1);\n assert expo(2,3*n) == expo(2,3*(n-1)+3);\n\n // training dafny up\n assert expo(2,3*(n-1)+3) == expo(2,3*(n-1)+1)*expo(2,2);\n assert expo(2,3*(n-1)+3) == expo(2,3*(n-1))*expo(2,3);\n assert expo(3,(n-1)+1) == expo(3,(n-1))*expo(3,1);\n\n // some more training\n assert expo(3,n) == expo(3,n-1)*expo(3,1);\n assert expo(3,n) == expo(3,(n-1)+1);\n\n // not really needed\n assert expo(2,3*(n-1))*expo(2,3) == expo(2,3*(n-1))*8;\n assert expo(3,(n-1))*expo(3,1) == expo(3,(n-1))*3;\n\n\n assert expo(2,3*n) - expo(3,n) == expo(2,3*(n-1)+3) - expo(3,(n-1)+1);\n \n assert (expo(2,3*n) - expo(3,n)) % 5 == (expo(2,3*(n-1)+3) - expo(3,(n-1)+1)) % 5; // rewriting it\n 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; \n assert (expo(2,3*n) - expo(3,n)) % 5 == (expo(2,3*(n-1))*8 - expo(3,(n-1))*3) % 5;\n 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\n 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;\n 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;\n 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;\n assert (expo(2,3*n) - expo(3,n)) % 5 == 0;\n }\n}\n\n \n", "hints_removed": "// program verifies\nfunction expo(x:int, n:nat): int\n{\n if n == 0 then 1\n else x * expo(x, n-1)\n}\n\nlemma {:induction false} Expon23(n: nat)\nrequires n >= 0\nensures ((expo(2,3*n) - expo(3,n)) % (2+3)) == 0\n{ \n // base case\n if (n == 0) {\n }\n\n else if (n == 1) {\n }\n else {\n Expon23(n-1); // lemma proved for case n-1 \n \n // training dafny up\n\n // training dafny up\n\n // some more training\n\n // not really needed\n\n\n \n }\n}\n\n \n" }, { "test_ID": "422", "test_file": "dafny-duck_tmp_tmplawbgxjo_p1.dfy", "ground_truth": "// Given an array of integers, it returns the sum. [1,3,3,2]->9\n\nfunction Sum(xs: seq): int {\n if |xs| == 0 then 0 else Sum(xs[..|xs|-1]) + xs[|xs|-1]\n}\n\nmethod SumArray(xs: array) returns (s: int)\n ensures s == Sum(xs[..])\n{\n s := 0;\n var i := 0;\n while i < xs.Length\n invariant 0 <= i <= xs.Length\n invariant s == Sum(xs[..i])\n {\n s := s + xs[i];\n assert xs[..i+1] == xs[..i] + [xs[i]];\n i := i + 1;\n }\n assert xs[..] == xs[..i];\n}\n", "hints_removed": "// Given an array of integers, it returns the sum. [1,3,3,2]->9\n\nfunction Sum(xs: seq): int {\n if |xs| == 0 then 0 else Sum(xs[..|xs|-1]) + xs[|xs|-1]\n}\n\nmethod SumArray(xs: array) returns (s: int)\n ensures s == Sum(xs[..])\n{\n s := 0;\n var i := 0;\n while i < xs.Length\n {\n s := s + xs[i];\n i := i + 1;\n }\n}\n" }, { "test_ID": "423", "test_file": "dafny-duck_tmp_tmplawbgxjo_p2.dfy", "ground_truth": "// Given an array of positive and negative integers,\n// it returns an array of the absolute value of all the integers. [-4,1,5,-2,-5]->[4,1,5,2,5]\n\nfunction abs(x:int):nat {\n\n if x < 0 then -x else x\n}\n\n\n\nmethod absx(x:array) returns (y:array) \nensures y.Length == x.Length\nensures forall i :: 0 <= i < y.Length ==> y[i] == abs(x[i])\n{ \n // put the old array in to new array (declare a new array)\n // loop through the new array\n // convert negative to positive by assigning new to be old\n // increment \n y:= new int [x.Length];\n var j:= 0;\n assert y.Length == x.Length;\n while (j < y.Length)\n invariant 0<=j<=y.Length\n // need to have here equals to make sure we cover the last element \n invariant forall i :: 0 <= i < j <= y.Length ==> y[i] == abs(x[i])\n {\n if(x[j] < 0) {\n y[j] := -x[j];\n } else {\n y[j] := x[j];\n }\n j:= j + 1;\n }\n}\n\n\n\n\nmethod Main() {\n var d := new int [5];\n var c := new int [5];\n d[0], d[1], d[2], d[3], d[4] := -4, 1, 5, -2 , -5;\n //c[0], c[1], c[2], c[3], c[4] := 4, 1, 5, 2 , 5;\n c:=absx(d);\n assert c[..] == [4, 1, 5, 2 ,5];\n //assert forall x :: 0<=x c[x] >= 0;\n print c[..];\n\n}\n", "hints_removed": "// Given an array of positive and negative integers,\n// it returns an array of the absolute value of all the integers. [-4,1,5,-2,-5]->[4,1,5,2,5]\n\nfunction abs(x:int):nat {\n\n if x < 0 then -x else x\n}\n\n\n\nmethod absx(x:array) returns (y:array) \nensures y.Length == x.Length\nensures forall i :: 0 <= i < y.Length ==> y[i] == abs(x[i])\n{ \n // put the old array in to new array (declare a new array)\n // loop through the new array\n // convert negative to positive by assigning new to be old\n // increment \n y:= new int [x.Length];\n var j:= 0;\n while (j < y.Length)\n // need to have here equals to make sure we cover the last element \n {\n if(x[j] < 0) {\n y[j] := -x[j];\n } else {\n y[j] := x[j];\n }\n j:= j + 1;\n }\n}\n\n\n\n\nmethod Main() {\n var d := new int [5];\n var c := new int [5];\n d[0], d[1], d[2], d[3], d[4] := -4, 1, 5, -2 , -5;\n //c[0], c[1], c[2], c[3], c[4] := 4, 1, 5, 2 , 5;\n c:=absx(d);\n //assert forall x :: 0<=x c[x] >= 0;\n print c[..];\n\n}\n" }, { "test_ID": "424", "test_file": "dafny-duck_tmp_tmplawbgxjo_p3.dfy", "ground_truth": "//Given an array of natural numbers, it returns the maximum value. [5,1,3,6,12,3]->12\n\nmethod max(x:array) returns (y:nat) \n// for index loop problems\nrequires x.Length > 0\n// ensuring that we maintain y as greater than the elements in the array \nensures forall j :: 0 <= j < x.Length ==> y >= x[j]\n// ensuring that the return value is in the array\nensures y in x[..]\n{\n \n y:= x[0];\n var i := 0;\n while(i < x.Length)\n invariant 0 <=i <=x.Length\n // create new index\n invariant forall j :: 0 <= j < i ==> y >= x[j]\n invariant y in x[..]\n {\n if(y <= x[i]){\n y := x[i];\n }\n\n i := i + 1;\n }\n assert y in x[..];\n}\n\nmethod Main()\n{\n // when we did the other way it didnt work \n var a:= new nat [6][5, 1, 3, 6, 12, 3];\n var c:= max(a);\n assert c == 12;\n // print c;\n \n\n}\n", "hints_removed": "//Given an array of natural numbers, it returns the maximum value. [5,1,3,6,12,3]->12\n\nmethod max(x:array) returns (y:nat) \n// for index loop problems\nrequires x.Length > 0\n// ensuring that we maintain y as greater than the elements in the array \nensures forall j :: 0 <= j < x.Length ==> y >= x[j]\n// ensuring that the return value is in the array\nensures y in x[..]\n{\n \n y:= x[0];\n var i := 0;\n while(i < x.Length)\n // create new index\n {\n if(y <= x[i]){\n y := x[i];\n }\n\n i := i + 1;\n }\n}\n\nmethod Main()\n{\n // when we did the other way it didnt work \n var a:= new nat [6][5, 1, 3, 6, 12, 3];\n var c:= max(a);\n // print c;\n \n\n}\n" }, { "test_ID": "425", "test_file": "dafny-duck_tmp_tmplawbgxjo_p4.dfy", "ground_truth": "//Given two arrays of integers, it returns a single array with all integers merged. \n// [1,5,2,3],[4,3,5]->[1,5,2,3,4,3,5]\n\nmethod single(x:array, y:array) returns (b:array) \nrequires x.Length > 0\nrequires y.Length > 0\n// ensuring that the new array is the two arrays joined\nensures b[..] == x[..] + y[..]\n\n{\n // getting the new array to have the length of the two arrays\n b:= new int [x.Length + y.Length];\n var i := 0;\n // to loop over the final array\n var index := 0;\n var sumi := x.Length + y.Length;\n\n while (i < x.Length && index < sumi) \n invariant 0 <= i <= x.Length\n invariant 0 <= index <= sumi\n // making sure all elements up to index and i in both arrays are same \n invariant b[..index] == x[..i]\n\n {\n b[index]:= x[i];\n i := i + 1;\n index:= index+1;\n }\n\n i := 0;\n\n while (i < y.Length && index < sumi)\n invariant 0 <= i <= y.Length\n invariant 0 <= index <= sumi\n // making sure that all elements in x and y are the same as b\n invariant b[..index] == x[..] + y[..i]\n {\n b[index]:= y[i];\n i := i + 1;\n index:= index + 1;\n }\n\n\n\n}\n\nmethod Main()\n{\n var a:= new int [4][1,5,2,3];\n var b:= new int [3][4,3,5];\n var c:= new int [7];\n c := single(a,b);\n assert c[..] == [1,5,2,3,4,3,5];\n //print c[..];\n\n}\n\n\n\n\n", "hints_removed": "//Given two arrays of integers, it returns a single array with all integers merged. \n// [1,5,2,3],[4,3,5]->[1,5,2,3,4,3,5]\n\nmethod single(x:array, y:array) returns (b:array) \nrequires x.Length > 0\nrequires y.Length > 0\n// ensuring that the new array is the two arrays joined\nensures b[..] == x[..] + y[..]\n\n{\n // getting the new array to have the length of the two arrays\n b:= new int [x.Length + y.Length];\n var i := 0;\n // to loop over the final array\n var index := 0;\n var sumi := x.Length + y.Length;\n\n while (i < x.Length && index < sumi) \n // making sure all elements up to index and i in both arrays are same \n\n {\n b[index]:= x[i];\n i := i + 1;\n index:= index+1;\n }\n\n i := 0;\n\n while (i < y.Length && index < sumi)\n // making sure that all elements in x and y are the same as b\n {\n b[index]:= y[i];\n i := i + 1;\n index:= index + 1;\n }\n\n\n\n}\n\nmethod Main()\n{\n var a:= new int [4][1,5,2,3];\n var b:= new int [3][4,3,5];\n var c:= new int [7];\n c := single(a,b);\n //print c[..];\n\n}\n\n\n\n\n" }, { "test_ID": "426", "test_file": "dafny-duck_tmp_tmplawbgxjo_p6.dfy", "ground_truth": "//Given an array of characters, it filters all the vowels. [\u2018d\u2019,\u2019e\u2019,\u2019l\u2019,\u2019i\u2019,\u2019g\u2019,\u2019h\u2019,\u2019t\u2019]-> [\u2019e\u2019,\u2019i\u2019]\nconst vowels: set := {'a', 'e', 'i', 'o', 'u'}\n\nfunction FilterVowels(xs: seq): seq\n{\n if |xs| == 0 then []\n else if xs[|xs|-1] in vowels then FilterVowels(xs[..|xs|-1]) + [xs[|xs|-1]]\n else FilterVowels(xs[..|xs|-1])\n}\n\nmethod FilterVowelsArray(xs: array) returns (ys: array)\n ensures fresh(ys)\n ensures FilterVowels(xs[..]) == ys[..]\n{\n var n := 0;\n var i := 0;\n while i < xs.Length\n invariant 0 <= i <= xs.Length\n invariant n == |FilterVowels(xs[..i])|\n invariant forall j :: 0 <= j <= i ==> n >= |FilterVowels(xs[..j])|\n {\n assert xs[..i+1] == xs[..i] + [xs[i]];\n if xs[i] in vowels {\n n := n + 1;\n }\n i := i + 1;\n }\n\n ys := new char[n];\n i := 0;\n var j := 0;\n while i < xs.Length\n invariant 0 <= i <= xs.Length\n invariant 0 <= j <= ys.Length\n invariant ys[..j] == FilterVowels(xs[..i])\n {\n assert xs[..i+1] == xs[..i] + [xs[i]];\n if xs[i] in vowels {\n assert ys.Length >= |FilterVowels(xs[..i+1])|;\n ys[j] := xs[i];\n j := j + 1;\n }\n i := i + 1;\n }\n\n assert xs[..] == xs[..i];\n assert ys[..] == ys[..j];\n}\n", "hints_removed": "//Given an array of characters, it filters all the vowels. [\u2018d\u2019,\u2019e\u2019,\u2019l\u2019,\u2019i\u2019,\u2019g\u2019,\u2019h\u2019,\u2019t\u2019]-> [\u2019e\u2019,\u2019i\u2019]\nconst vowels: set := {'a', 'e', 'i', 'o', 'u'}\n\nfunction FilterVowels(xs: seq): seq\n{\n if |xs| == 0 then []\n else if xs[|xs|-1] in vowels then FilterVowels(xs[..|xs|-1]) + [xs[|xs|-1]]\n else FilterVowels(xs[..|xs|-1])\n}\n\nmethod FilterVowelsArray(xs: array) returns (ys: array)\n ensures fresh(ys)\n ensures FilterVowels(xs[..]) == ys[..]\n{\n var n := 0;\n var i := 0;\n while i < xs.Length\n {\n if xs[i] in vowels {\n n := n + 1;\n }\n i := i + 1;\n }\n\n ys := new char[n];\n i := 0;\n var j := 0;\n while i < xs.Length\n {\n if xs[i] in vowels {\n ys[j] := xs[i];\n j := j + 1;\n }\n i := i + 1;\n }\n\n}\n" }, { "test_ID": "427", "test_file": "dafny-exercise_tmp_tmpouftptir_absIt.dfy", "ground_truth": "method AbsIt(s: array) \nmodifies s\nensures forall i :: 0 <= i < s.Length ==> if old(s[i]) < 0 then s[i] == -old(s[i]) else s[i] == old(s[i])\nensures s.Length == old(s).Length\n{\n\tvar i: int := 0;\n\t\n\twhile i < s.Length\n\tinvariant 0 <= i <= s.Length\n\tinvariant forall j :: 0 <= j < i ==> if old(s[j]) < 0 then s[j] == -old(s[j]) else s[j] == old(s[j])\n\tinvariant forall j :: i <= j < s.Length ==> s[j] == old(s[j])\n\t{\t\n\t\tif (s[i] < 0) {\n\t\t\ts[i] := -s[i];\n\t\t}\n\t\ti := i + 1;\n\t}\n}\n\nmethod Tester()\n{\n var a := new int[][-1,2,-3,4,-5,6,-7,8,-9]; \n // testcase 1\n assert a[0]==-1 && a[1]==2 && a[2]==-3 && a[3]==4 && a[4]==-5;\n assert a[5]==6 && a[6]==-7 && a[7]==8 && a[8]==-9;\n AbsIt(a);\n assert a[0]==1 && a[1]==2 && a[2]==3 && a[3]==4 && a[4]==5;\n assert a[5]==6 && a[6]==7 && a[7]==8 && a[8]==9;\n\n var b:array := new int[][-42,-2,-42,-2,-42,-2]; \n // testcase 2\n assert b[0]==-42 && b[1]==-2 && b[2]==-42;\n assert b[3]==-2 && b[4]==-42 && b[5]==-2;\n AbsIt(b);\n assert b[0]==42 && b[1]==2 && b[2]==42;\n assert b[3]==2 && b[4]==42 && b[5]==2;\n\n var c:array := new int[][-1]; \n // testcase 3\n assert c[0]==-1;\n AbsIt(c);\n assert c[0]==1;\n\n var d:array := new int[][42]; \n // testcase 4\n assert d[0]==42;\n AbsIt(b);\n assert d[0]==42;\n\n var e:array := new int[][]; \n // testcase 5\n AbsIt(e);\n assert e.Length==0; // array is empty\n}\n\n", "hints_removed": "method AbsIt(s: array) \nmodifies s\nensures forall i :: 0 <= i < s.Length ==> if old(s[i]) < 0 then s[i] == -old(s[i]) else s[i] == old(s[i])\nensures s.Length == old(s).Length\n{\n\tvar i: int := 0;\n\t\n\twhile i < s.Length\n\t{\t\n\t\tif (s[i] < 0) {\n\t\t\ts[i] := -s[i];\n\t\t}\n\t\ti := i + 1;\n\t}\n}\n\nmethod Tester()\n{\n var a := new int[][-1,2,-3,4,-5,6,-7,8,-9]; \n // testcase 1\n AbsIt(a);\n\n var b:array := new int[][-42,-2,-42,-2,-42,-2]; \n // testcase 2\n AbsIt(b);\n\n var c:array := new int[][-1]; \n // testcase 3\n AbsIt(c);\n\n var d:array := new int[][42]; \n // testcase 4\n AbsIt(b);\n\n var e:array := new int[][]; \n // testcase 5\n AbsIt(e);\n}\n\n" }, { "test_ID": "428", "test_file": "dafny-exercise_tmp_tmpouftptir_appendArray.dfy", "ground_truth": "method appendArray(a: array, b: array) returns (c: array)\nensures c.Length == a.Length + b.Length\nensures forall i :: 0 <= i < a.Length ==> a[i] == c[i]\nensures forall i :: 0 <= i < b.Length ==> b[i] == c[a.Length + i]\n{\n\tc := new int[a.Length + b.Length];\n\t\n\tvar i := 0;\n\twhile i < a.Length\n\tinvariant 0 <= i <= a.Length\n\tinvariant forall j :: 0 <= j < i ==> c[j] == a[j]\n\t{\n\t\tc[i] := a[i];\n\t\ti := i + 1;\n\t}\n\t\n\twhile i < b.Length + a.Length\n\tinvariant a.Length <= i <= b.Length + a.Length\n\tinvariant forall j :: 0 <= j < a.Length ==> a[j] == c[j]\n\tinvariant forall j :: a.Length <= j < i ==> c[j] == b[j - a.Length]\n\t{\n\t\tc[i] := b[i - a.Length];\n\t\ti := i + 1;\n\t}\n}\n\n", "hints_removed": "method appendArray(a: array, b: array) returns (c: array)\nensures c.Length == a.Length + b.Length\nensures forall i :: 0 <= i < a.Length ==> a[i] == c[i]\nensures forall i :: 0 <= i < b.Length ==> b[i] == c[a.Length + i]\n{\n\tc := new int[a.Length + b.Length];\n\t\n\tvar i := 0;\n\twhile i < a.Length\n\t{\n\t\tc[i] := a[i];\n\t\ti := i + 1;\n\t}\n\t\n\twhile i < b.Length + a.Length\n\t{\n\t\tc[i] := b[i - a.Length];\n\t\ti := i + 1;\n\t}\n}\n\n" }, { "test_ID": "429", "test_file": "dafny-exercise_tmp_tmpouftptir_countNeg.dfy", "ground_truth": "function verifyNeg(a: array, idx: int) : nat\nreads a\nrequires 0 <= idx <= a.Length\n{\n\tif idx == 0 then 0 \n\telse verifyNeg(a, idx - 1) + (if a[idx - 1] < 0 then 1 else 0)\n}\n\nmethod CountNeg(a: array) returns (cnt: nat) \nensures cnt == verifyNeg(a, a.Length)\n{\n\tvar i := 0;\n\tcnt := 0;\n\twhile i < a.Length\n\tinvariant 0 <= i <= a.Length\n\tinvariant cnt == verifyNeg(a, i)\n\t{\n\t\tif a[i] < 0 {\n\t\t\tcnt := cnt + 1;\n\t\t}\n\t\ti := i + 1;\n\t}\n}\n\nmethod Main()\n{\n\tvar arr: array := new int[][0,-1,-2,4];\n\tvar res := CountNeg(arr);\n\tassert res == verifyNeg(arr, arr.Length);\n}\n\n", "hints_removed": "function verifyNeg(a: array, idx: int) : nat\nreads a\nrequires 0 <= idx <= a.Length\n{\n\tif idx == 0 then 0 \n\telse verifyNeg(a, idx - 1) + (if a[idx - 1] < 0 then 1 else 0)\n}\n\nmethod CountNeg(a: array) returns (cnt: nat) \nensures cnt == verifyNeg(a, a.Length)\n{\n\tvar i := 0;\n\tcnt := 0;\n\twhile i < a.Length\n\t{\n\t\tif a[i] < 0 {\n\t\t\tcnt := cnt + 1;\n\t\t}\n\t\ti := i + 1;\n\t}\n}\n\nmethod Main()\n{\n\tvar arr: array := new int[][0,-1,-2,4];\n\tvar res := CountNeg(arr);\n}\n\n" }, { "test_ID": "430", "test_file": "dafny-exercise_tmp_tmpouftptir_filter.dfy", "ground_truth": "method Filter(a:seq, b:set) returns(c:set) \nensures forall x :: x in a && x in b <==> x in c\n{\n\tvar setA: set := set x | x in a;\n\tc := setA * b;\n}\n\nmethod TesterFilter()\n{\n var v:set := {'a','e','i','o','u'}; // vowels to be used as a filter\n\n var s:seq := \"ant-egg-ink-owl-urn\";\n var w:set := Filter(s, v);\n assert w == {'i','u','a','o','e'};\n\n s := \"nice-and-easy\";\n w := Filter(s, v);\n assert w == {'a','e','i'};\n\n s := \"mssyysywbrpqsxmnlsghrytx\"; // no vowels\n w := Filter(s, v);\n assert w == {};\n\n s := \"iiiiiiiiiiiii\"; // 1 vowel\n w := Filter(s, v);\n assert w == {'i'};\n\n s := \"aeiou\"; // s == v\n w := Filter(s, v);\n assert w == {'a','e','i','o','u'};\n\n s := \"u\"; // edge singleton\n w := Filter(s, v);\n assert w == {'u'};\n\n s := \"f\"; // edge singleton\n w := Filter(s, v);\n assert w == {};\n\n s := \"\"; // edge empty seq\n w := Filter(s, v);\n assert w == {};\n\n v := {}; // edge empty filter\n s := \"Any sequence that I like!!!\";\n w := Filter(s, v);\n assert w == {};\n}\n\n", "hints_removed": "method Filter(a:seq, b:set) returns(c:set) \nensures forall x :: x in a && x in b <==> x in c\n{\n\tvar setA: set := set x | x in a;\n\tc := setA * b;\n}\n\nmethod TesterFilter()\n{\n var v:set := {'a','e','i','o','u'}; // vowels to be used as a filter\n\n var s:seq := \"ant-egg-ink-owl-urn\";\n var w:set := Filter(s, v);\n\n s := \"nice-and-easy\";\n w := Filter(s, v);\n\n s := \"mssyysywbrpqsxmnlsghrytx\"; // no vowels\n w := Filter(s, v);\n\n s := \"iiiiiiiiiiiii\"; // 1 vowel\n w := Filter(s, v);\n\n s := \"aeiou\"; // s == v\n w := Filter(s, v);\n\n s := \"u\"; // edge singleton\n w := Filter(s, v);\n\n s := \"f\"; // edge singleton\n w := Filter(s, v);\n\n s := \"\"; // edge empty seq\n w := Filter(s, v);\n\n v := {}; // edge empty filter\n s := \"Any sequence that I like!!!\";\n w := Filter(s, v);\n}\n\n" }, { "test_ID": "431", "test_file": "dafny-exercise_tmp_tmpouftptir_firstE.dfy", "ground_truth": "method firstE(a: array) returns (x: int)\nensures if 'e' in a[..] then 0 <= x < a.Length && a[x] == 'e' && forall i | 0 <= i < x :: a[i] != 'e' else x == -1\n\n{\n\tvar i: int := 0;\n\twhile i < a.Length\n\tinvariant 0 <= i <= a.Length\n\tinvariant forall j :: 0 <= j < i ==> a[j] != 'e'\n\t{\n\t\tif (a[i] == 'e') {\n\t\t\treturn i;\n\t\t}\n\t\ti := i + 1;\n\t}\n\treturn -1;\n}\n\nmethod Main() {\n\tvar a: array := new char[]['c','h','e','e','s','e'];\n\tassert a[0] == 'c' && a[1] == 'h' && a[2] == 'e';\n\tvar res := firstE(a);\n\tassert res == 2;\n\t\n\ta := new char[]['e'];\n\tassert a[0] == 'e';\n\tres := firstE(a);\n\tassert res == 0;\n\t\n\ta := new char[][];\n\tres := firstE(a);\n\tassert res == -1;\n}\n\n", "hints_removed": "method firstE(a: array) returns (x: int)\nensures if 'e' in a[..] then 0 <= x < a.Length && a[x] == 'e' && forall i | 0 <= i < x :: a[i] != 'e' else x == -1\n\n{\n\tvar i: int := 0;\n\twhile i < a.Length\n\t{\n\t\tif (a[i] == 'e') {\n\t\t\treturn i;\n\t\t}\n\t\ti := i + 1;\n\t}\n\treturn -1;\n}\n\nmethod Main() {\n\tvar a: array := new char[]['c','h','e','e','s','e'];\n\tvar res := firstE(a);\n\t\n\ta := new char[]['e'];\n\tres := firstE(a);\n\t\n\ta := new char[][];\n\tres := firstE(a);\n}\n\n" }, { "test_ID": "432", "test_file": "dafny-exercise_tmp_tmpouftptir_maxArray.dfy", "ground_truth": "method MaxArray(a: array) returns (max:int)\nrequires a.Length > 0\nensures forall i :: 0 <= i < a.Length ==> a[i] <= max\nensures exists i :: 0 <= i < a.Length && a[i] == max\n{\n\tvar i: nat := 1;\n\tmax := a[0];\n\twhile i < a.Length\n\tinvariant 0 <= i <= a.Length\n\tinvariant forall j :: 0 <= j < i ==> a[j] <= max\n\tinvariant exists j :: 0 <= j < i && a[j] == max\n\t{\n\t\tif (a[i] > max) {\n\t\t\tmax := a[i];\n\t\t}\n\t\ti := i + 1;\n\t}\n}\n\nmethod Main() {\n\tvar arr : array := new int[][-11,2,42,-4];\n\tvar res := MaxArray(arr);\n\tassert arr[0] == -11 && arr[1] == 2 && arr[2] == 42 && arr[3] == -4;\n\tassert res == 42;\n}\n\n", "hints_removed": "method MaxArray(a: array) returns (max:int)\nrequires a.Length > 0\nensures forall i :: 0 <= i < a.Length ==> a[i] <= max\nensures exists i :: 0 <= i < a.Length && a[i] == max\n{\n\tvar i: nat := 1;\n\tmax := a[0];\n\twhile i < a.Length\n\t{\n\t\tif (a[i] > max) {\n\t\t\tmax := a[i];\n\t\t}\n\t\ti := i + 1;\n\t}\n}\n\nmethod Main() {\n\tvar arr : array := new int[][-11,2,42,-4];\n\tvar res := MaxArray(arr);\n}\n\n" }, { "test_ID": "433", "test_file": "dafny-exercise_tmp_tmpouftptir_prac1_ex1.dfy", "ground_truth": "predicate acheck(a: array, n: int)\nreads a\nrequires n >= 1\n{\n\ta.Length % 2 == 0 && \n\tforall i :: 0 <= i < a.Length ==> \n\t\tif i % n == 0 then a[i] == 0 else a[i] != 0\n}\n\nmethod Main()\n{\n\tvar arr: array := new int[][0,42,0,42];\n\tvar res := acheck(arr, 2);\n\tassert res;\n\t\n\tarr := new int[][];\n\tres := acheck(arr, 2);\n\tassert res;\n\t\n\tarr := new int[][0,4,2,0];\n\tassert arr[2] == 2;\n\tres := acheck(arr, 2);\n\tassert !res;\n}\n\n", "hints_removed": "predicate acheck(a: array, n: int)\nreads a\nrequires n >= 1\n{\n\ta.Length % 2 == 0 && \n\tforall i :: 0 <= i < a.Length ==> \n\t\tif i % n == 0 then a[i] == 0 else a[i] != 0\n}\n\nmethod Main()\n{\n\tvar arr: array := new int[][0,42,0,42];\n\tvar res := acheck(arr, 2);\n\t\n\tarr := new int[][];\n\tres := acheck(arr, 2);\n\t\n\tarr := new int[][0,4,2,0];\n\tres := acheck(arr, 2);\n}\n\n" }, { "test_ID": "434", "test_file": "dafny-exercise_tmp_tmpouftptir_prac1_ex2.dfy", "ground_truth": "method Deli(a: array, i: nat)\nmodifies a\nrequires a.Length > 0\nrequires 0 <= i < a.Length\nensures forall j :: 0 <= j < i ==> a[j] == old(a[j])\nensures forall j :: i <= j < a.Length - 1 ==> a[j] == old(a[j + 1])\nensures a[a.Length - 1] == '.'\n{\n\tvar c := i;\n\twhile c < a.Length - 1\n\tinvariant i <= c <= a.Length - 1\n\tinvariant forall j :: i <= j < c ==> a[j] == old(a[j + 1])\n\t// unchanged first half\n\tinvariant forall j :: 0 <= j < i ==> a[j] == old(a[j])\n\tinvariant forall j :: c <= j < a.Length ==> a[j] == old(a[j])\n\t{\n\t\ta[c] := a[c + 1];\n\t\tc := c + 1;\n\t}\n\ta[c] := '.';\n}\n\nmethod DeliChecker()\n{\n var z := new char[]['b','r','o','o','m'];\n Deli(z, 1);\n assert z[..] == \"boom.\";\n Deli(z, 3);\n assert z[..] == \"boo..\";\n Deli(z, 4);\n assert z[..] == \"boo..\";\n Deli(z, 3);\n assert z[..] == \"boo..\";\n Deli(z, 0);\n Deli(z, 0);\n Deli(z, 0);\n assert z[..] == \".....\";\n\n z := new char[]['x'];\n Deli(z, 0);\n assert z[..] == \".\";\n}\n\n", "hints_removed": "method Deli(a: array, i: nat)\nmodifies a\nrequires a.Length > 0\nrequires 0 <= i < a.Length\nensures forall j :: 0 <= j < i ==> a[j] == old(a[j])\nensures forall j :: i <= j < a.Length - 1 ==> a[j] == old(a[j + 1])\nensures a[a.Length - 1] == '.'\n{\n\tvar c := i;\n\twhile c < a.Length - 1\n\t// unchanged first half\n\t{\n\t\ta[c] := a[c + 1];\n\t\tc := c + 1;\n\t}\n\ta[c] := '.';\n}\n\nmethod DeliChecker()\n{\n var z := new char[]['b','r','o','o','m'];\n Deli(z, 1);\n Deli(z, 3);\n Deli(z, 4);\n Deli(z, 3);\n Deli(z, 0);\n Deli(z, 0);\n Deli(z, 0);\n\n z := new char[]['x'];\n Deli(z, 0);\n}\n\n" }, { "test_ID": "435", "test_file": "dafny-exercise_tmp_tmpouftptir_prac3_ex2.dfy", "ground_truth": "method GetEven(s: array) modifies s\nensures forall i :: 0 <= i < s.Length ==> \n\t\t\t\t\t\t\t\tif old(s[i]) % 2 == 1 then s[i] == old(s[i]) + 1\n\t\t\t\t\t\t\t\telse s[i] == old(s[i])\n{\n\tvar i := 0;\n\twhile i < s.Length \n\tinvariant 0 <= i <= s.Length\n\tinvariant forall j :: 0 <= j < i ==> \n\t\tif old(s[j]) % 2 == 1 then s[j] == old(s[j]) + 1\n\t\telse s[j] == old(s[j])\n\tinvariant forall j :: i <= j < s.Length ==> s[j] == old(s[j])\n\t{\n\t\tif s[i] % 2 == 1 {\n\t\t\ts[i] := s[i] + 1;\n\t\t}\n\t\ti := i + 1;\n\t}\n}\n\nmethod evenTest()\n{\n\tvar a:array := new nat[][0,9,4];\n \tassert a[0]==0 && a[1]==9 && a[2]==4;\n \tGetEven(a);\n \tassert a[0]==0 && a[1]==10 && a[2]==4;\n}\n\n", "hints_removed": "method GetEven(s: array) modifies s\nensures forall i :: 0 <= i < s.Length ==> \n\t\t\t\t\t\t\t\tif old(s[i]) % 2 == 1 then s[i] == old(s[i]) + 1\n\t\t\t\t\t\t\t\telse s[i] == old(s[i])\n{\n\tvar i := 0;\n\twhile i < s.Length \n\t\tif old(s[j]) % 2 == 1 then s[j] == old(s[j]) + 1\n\t\telse s[j] == old(s[j])\n\t{\n\t\tif s[i] % 2 == 1 {\n\t\t\ts[i] := s[i] + 1;\n\t\t}\n\t\ti := i + 1;\n\t}\n}\n\nmethod evenTest()\n{\n\tvar a:array := new nat[][0,9,4];\n \tGetEven(a);\n}\n\n" }, { "test_ID": "436", "test_file": "dafny-exercise_tmp_tmpouftptir_prac4_ex2.dfy", "ground_truth": "predicate triple(a: array) \nreads a\n{\n\texists i :: 0 <= i < a.Length - 2 && a[i] == a[i + 1] == a[i + 2]\n}\n\nmethod GetTriple(a: array) returns (index: int)\nensures 0 <= index < a.Length - 2 || index == a.Length\nensures index == a.Length <==> !triple(a)\nensures 0 <= index < a.Length - 2 <==> triple(a)\nensures 0 <= index < a.Length - 2 ==> a[index] == a[index + 1] == a[index + 2]\n{\n\tvar i: nat := 0;\n\tindex := a.Length;\n\tif a.Length < 3 {\n\t\treturn a.Length;\n\t}\n\twhile i < a.Length - 2\n\tdecreases a.Length - i\n\tinvariant 0 <= i <= a.Length - 2\n\tinvariant index == a.Length <==> (!exists j :: 0 <= j < i && a[j] == a[j + 1] == a[j + 2])\n\tinvariant 0 <= index < a.Length - 2 ==> a[index] == a[index + 1] == a[index + 2]\n\t{\n\t\tif a[i] == a[i + 1] == a[i + 2] {\n\t\t\treturn i;\n\t\t}\n\t\ti := i + 1;\n\t}\n}\n\nmethod TesterGetTriple()\n{\n var a: array := new int[1][42];\n assert a[0] == 42;\n var b := GetTriple(a);\n assert b==a.Length; // NO TRIPLE\n\n a := new int[2][42,42];\n assert a[0] == a[1] == 42;\n b := GetTriple(a);\n assert b==a.Length; // NO TRIPLE\n\n a := new int[3][42,42,0];\n assert a[0] == a[1] == 42 && a[2] == 0;\n b := GetTriple(a);\n assert b==a.Length; // NO TRIPLE\n\n a := new int[4][42,42,0,42];\n assert a[0] == a[1] == a[3] == 42 && a[2] == 0;\n b := GetTriple(a);\n assert b==a.Length; // NO TRIPLE\n\n a := new int[3][42,42,42];\n assert a[0] == a[1] == a[2] == 42;\n b := GetTriple(a);\n assert b==0; // A TRIPLE!\n\n a := new int[4][0,42,42,42];\n assert a[0] == 0 && a[1] == a[2] == a[3] == 42;\n b := GetTriple(a);\n assert b==1; // A TRIPLE!\n\n a := new int[6][0,0,42,42,42,0];\n assert a[0] == a[1] == a[5] == 0 && a[2] == a[3] == a[4] == 42;\n b := GetTriple(a);\n assert b==2; // A TRIPLE!\n}\n\n", "hints_removed": "predicate triple(a: array) \nreads a\n{\n\texists i :: 0 <= i < a.Length - 2 && a[i] == a[i + 1] == a[i + 2]\n}\n\nmethod GetTriple(a: array) returns (index: int)\nensures 0 <= index < a.Length - 2 || index == a.Length\nensures index == a.Length <==> !triple(a)\nensures 0 <= index < a.Length - 2 <==> triple(a)\nensures 0 <= index < a.Length - 2 ==> a[index] == a[index + 1] == a[index + 2]\n{\n\tvar i: nat := 0;\n\tindex := a.Length;\n\tif a.Length < 3 {\n\t\treturn a.Length;\n\t}\n\twhile i < a.Length - 2\n\t{\n\t\tif a[i] == a[i + 1] == a[i + 2] {\n\t\t\treturn i;\n\t\t}\n\t\ti := i + 1;\n\t}\n}\n\nmethod TesterGetTriple()\n{\n var a: array := new int[1][42];\n var b := GetTriple(a);\n\n a := new int[2][42,42];\n b := GetTriple(a);\n\n a := new int[3][42,42,0];\n b := GetTriple(a);\n\n a := new int[4][42,42,0,42];\n b := GetTriple(a);\n\n a := new int[3][42,42,42];\n b := GetTriple(a);\n\n a := new int[4][0,42,42,42];\n b := GetTriple(a);\n\n a := new int[6][0,0,42,42,42,0];\n b := GetTriple(a);\n}\n\n" }, { "test_ID": "437", "test_file": "dafny-exercise_tmp_tmpouftptir_reverse.dfy", "ground_truth": "method Reverse(a: array) returns (b: array)\nrequires a.Length > 0\nensures a == old(a)\nensures b.Length == a.Length\nensures forall i :: 0 <= i < a.Length ==> b[i] == a[a.Length - i - 1]\n{\n\tb := new char[a.Length];\n\tvar i := 0;\n\twhile i < a.Length\n\tinvariant 0 <= i <= a.Length\n\tinvariant forall j :: 0 <= j < i ==> b[j] == a[a.Length - j - 1]\n\t{\n\t\tb[i] := a[a.Length - i - 1];\n\t\ti := i + 1;\n\t}\n}\n\nmethod Main()\n{\n var a := new char[]['s', 'k', 'r', 'o', 'w', 't', 'i'];\n var b := Reverse(a);\n assert b[..] == [ 'i', 't', 'w', 'o', 'r', 'k', 's' ];\n print b[..];\n\n a := new char[]['!'];\n b := Reverse(a);\n assert b[..] == a[..];\n print b[..], '\\n';\n}\n\n", "hints_removed": "method Reverse(a: array) returns (b: array)\nrequires a.Length > 0\nensures a == old(a)\nensures b.Length == a.Length\nensures forall i :: 0 <= i < a.Length ==> b[i] == a[a.Length - i - 1]\n{\n\tb := new char[a.Length];\n\tvar i := 0;\n\twhile i < a.Length\n\t{\n\t\tb[i] := a[a.Length - i - 1];\n\t\ti := i + 1;\n\t}\n}\n\nmethod Main()\n{\n var a := new char[]['s', 'k', 'r', 'o', 'w', 't', 'i'];\n var b := Reverse(a);\n print b[..];\n\n a := new char[]['!'];\n b := Reverse(a);\n print b[..], '\\n';\n}\n\n" }, { "test_ID": "438", "test_file": "dafny-exercise_tmp_tmpouftptir_zapNegatives.dfy", "ground_truth": "method ZapNegatives(a: array) \nmodifies a\nensures forall i :: 0 <= i < a.Length ==> if old(a[i]) < 0 then a[i] == 0 \n\t\t\t\t\t\t\t\t\t\t\telse a[i] == old(a[i])\nensures a.Length == old(a).Length\n{\n\tvar i := 0;\n\twhile i < a.Length\n\tinvariant 0 <= i <= a.Length\n\tinvariant forall j :: 0 <= j < i ==> if old(a[j]) < 0 then a[j] == 0 \n\t\t\t\t\t\t\t\t\t\t\telse a[j] == old(a[j])\n\tinvariant forall j :: i <= j < a.Length ==> a[j] == old(a[j])\n\t{\n\t\tif a[i] < 0 {\n\t\t\ta[i] := 0;\n\t\t}\n\t\ti := i + 1;\n\t}\n}\n\nmethod Main() \n{\n\tvar arr: array := new int[][-1, 2, 3, -4];\n\tassert arr[0] == -1 && arr[1] == 2 && arr[2] == 3 && arr[3] == -4;\n\tZapNegatives(arr);\n\tassert arr[0] == 0 && arr[1] == 2 && arr[2] == 3 && arr[3] == 0;\n}\n\n", "hints_removed": "method ZapNegatives(a: array) \nmodifies a\nensures forall i :: 0 <= i < a.Length ==> if old(a[i]) < 0 then a[i] == 0 \n\t\t\t\t\t\t\t\t\t\t\telse a[i] == old(a[i])\nensures a.Length == old(a).Length\n{\n\tvar i := 0;\n\twhile i < a.Length\n\t\t\t\t\t\t\t\t\t\t\telse a[j] == old(a[j])\n\t{\n\t\tif a[i] < 0 {\n\t\t\ta[i] := 0;\n\t\t}\n\t\ti := i + 1;\n\t}\n}\n\nmethod Main() \n{\n\tvar arr: array := new int[][-1, 2, 3, -4];\n\tZapNegatives(arr);\n}\n\n" }, { "test_ID": "439", "test_file": "dafny-exercises_tmp_tmp5mvrowrx_leetcode_26-remove-duplicates-from-sorted-array.dfy", "ground_truth": "\nmethod RemoveDuplicates(nums: array) returns (num_length: int)\n modifies nums\n requires forall i, j | 0 <= i < j < nums.Length :: nums[i] <= nums[j]\n ensures nums.Length == old(nums).Length\n ensures 0 <= num_length <= nums.Length\n ensures forall i, j | 0 <= i < j < num_length :: nums[i] != nums[j]\n ensures forall i | 0 <= i < num_length :: nums[i] in old(nums[..])\n ensures forall i | 0 <= i < nums.Length :: old(nums[i]) in nums[..num_length]\n{\n if nums.Length <= 1 {\n return nums.Length;\n }\n var last := 0;\n var i := 1;\n ghost var nums_before := nums[..];\n while i < nums.Length\n // verify that `last` will strictly smaller than `i`\n invariant 0 <= last < i <= nums.Length\n // verify that `nums[i..]` is untouched.\n invariant nums[i..] == nums_before[i..]\n // verify that `nums[..last1]` are sorted and strictly ascending.\n invariant forall j, k | 0 <= j < k <= last :: nums[j] < nums[k]\n // verify that elements in `nums[..last1]` are contained in the origin `nums[..i]`\n invariant forall j | 0 <= j <= last :: nums[j] in nums_before[..i]\n // verify that elements in origin `nums[..i]` are contained in the `nums[..last1]`\n invariant forall j | 0 <= j < i :: nums_before[j] in nums[..last+1]\n {\n if nums[last] < nums[i] {\n last := last + 1;\n nums[last] := nums[i];\n // Theses two assertion are used for the last invariant, which\n // verifies that all elements in origin `nums[..i]` are contained in new `nums[..last+1]`\n assert forall j | 0 <= j < i :: nums_before[j] in nums[..last];\n assert forall j | 0 <= j <= i :: nums_before[j] in nums[..last+1];\n }\n i := i + 1;\n }\n return last + 1;\n}\n\nmethod Testing() {\n var nums1 := new int[3];\n nums1[0] := 1;\n nums1[1] := 1;\n nums1[2] := 2;\n var num_length1 := RemoveDuplicates(nums1);\n assert forall i, j | 0 <= i < j < num_length1 :: nums1[i] != nums1[j];\n assert num_length1 <= nums1.Length;\n print \"nums1: \", nums1[..], \", num_length1: \", num_length1, \"\\n\";\n\n var nums2 := new int[10];\n nums2[0] := 0;\n nums2[1] := 0;\n nums2[2] := 1;\n nums2[3] := 1;\n nums2[4] := 1;\n nums2[5] := 2;\n nums2[6] := 2;\n nums2[7] := 3;\n nums2[8] := 3;\n nums2[9] := 4;\n var num_length2 := RemoveDuplicates(nums2);\n assert forall i, j | 0 <= i < j < num_length1 :: nums1[i] != nums1[j];\n assert num_length2 <= nums2.Length;\n print \"nums2: \", nums2[..], \", num_length2: \", num_length2, \"\\n\";\n}\n\nmethod Main() {\n Testing();\n}\n", "hints_removed": "\nmethod RemoveDuplicates(nums: array) returns (num_length: int)\n modifies nums\n requires forall i, j | 0 <= i < j < nums.Length :: nums[i] <= nums[j]\n ensures nums.Length == old(nums).Length\n ensures 0 <= num_length <= nums.Length\n ensures forall i, j | 0 <= i < j < num_length :: nums[i] != nums[j]\n ensures forall i | 0 <= i < num_length :: nums[i] in old(nums[..])\n ensures forall i | 0 <= i < nums.Length :: old(nums[i]) in nums[..num_length]\n{\n if nums.Length <= 1 {\n return nums.Length;\n }\n var last := 0;\n var i := 1;\n ghost var nums_before := nums[..];\n while i < nums.Length\n // verify that `last` will strictly smaller than `i`\n // verify that `nums[i..]` is untouched.\n // verify that `nums[..last1]` are sorted and strictly ascending.\n // verify that elements in `nums[..last1]` are contained in the origin `nums[..i]`\n // verify that elements in origin `nums[..i]` are contained in the `nums[..last1]`\n {\n if nums[last] < nums[i] {\n last := last + 1;\n nums[last] := nums[i];\n // Theses two assertion are used for the last invariant, which\n // verifies that all elements in origin `nums[..i]` are contained in new `nums[..last+1]`\n }\n i := i + 1;\n }\n return last + 1;\n}\n\nmethod Testing() {\n var nums1 := new int[3];\n nums1[0] := 1;\n nums1[1] := 1;\n nums1[2] := 2;\n var num_length1 := RemoveDuplicates(nums1);\n print \"nums1: \", nums1[..], \", num_length1: \", num_length1, \"\\n\";\n\n var nums2 := new int[10];\n nums2[0] := 0;\n nums2[1] := 0;\n nums2[2] := 1;\n nums2[3] := 1;\n nums2[4] := 1;\n nums2[5] := 2;\n nums2[6] := 2;\n nums2[7] := 3;\n nums2[8] := 3;\n nums2[9] := 4;\n var num_length2 := RemoveDuplicates(nums2);\n print \"nums2: \", nums2[..], \", num_length2: \", num_length2, \"\\n\";\n}\n\nmethod Main() {\n Testing();\n}\n" }, { "test_ID": "440", "test_file": "dafny-exercises_tmp_tmp5mvrowrx_paper_krml190.dfy", "ground_truth": "// Examples used in paper:\n// Specification and Verification of Object-Oriented Software\n// by K. Rustan M. Leino\n// link of the paper:\n// http://leino.science/papers/krml190.pdf\n\n// Figure 0. An example linked-list program written in Dafny.\nclass Data { }\n\nclass Node {\n var list: seq;\n var footprint: set;\n\n var data: Data;\n var next: Node?;\n\n function Valid(): bool\n reads this, footprint\n {\n this in footprint &&\n (next == null ==> list == [data]) &&\n (next != null ==> next in footprint &&\n next.footprint <= footprint &&\n !(this in next.footprint) &&\n list == [data] + next.list &&\n next.Valid())\n }\n\n constructor(d: Data)\n ensures Valid() && fresh(footprint - {this})\n ensures list == [d]\n {\n data := d;\n next := null;\n list := [d];\n footprint := {this};\n }\n\n method SkipHead() returns (r: Node?)\n requires Valid()\n ensures r == null ==> |list| == 1\n ensures r != null ==> r.Valid() && r.footprint <= footprint\n {\n return next;\n }\n\n method Prepend(d: Data) returns (r: Node)\n requires Valid()\n ensures r.Valid() && fresh(r.footprint - old(footprint))\n ensures r.list == [d] + list\n {\n r := new Node(d);\n r.data := d;\n r.next := this;\n r.footprint := {r} + footprint;\n r.list := [r.data] + list;\n }\n\n // Figure 1: The Node.ReverseInPlace method,\n // which performs an in situ list reversal.\n method ReverseInPlace() returns (reverse: Node)\n requires Valid()\n modifies footprint\n ensures reverse.Valid()\n // isn't here a typo?\n ensures fresh(reverse.footprint - old(footprint))\n ensures |reverse.list| == |old(list)|\n ensures forall i | 0 <= i < |old(list)| :: old(list)[i] == reverse.list[|old(list)| - 1 - i]\n {\n var current: Node?;\n current := next;\n reverse := this;\n reverse.next := null;\n reverse.footprint := {reverse};\n reverse.list := [data];\n\n while current != null\n invariant reverse.Valid()\n invariant reverse.footprint <= old(footprint)\n invariant current == null ==> |old(list)| == |reverse.list|\n invariant current != null ==>\n current.Valid()\n invariant current != null ==>\n current in old(footprint) && current.footprint <= old(footprint)\n invariant current != null ==>\n current.footprint !! reverse.footprint\n invariant current != null ==>\n |old(list)| == |reverse.list| + |current.list|\n invariant current != null ==>\n forall i | 0 <= i < |current.list| ::\n current.list[i] == old(list)[|reverse.list| + i]\n invariant forall i | 0 <= i < |reverse.list| ::\n old(list)[i] == reverse.list[|reverse.list| - 1 - i]\n decreases |old(list)| - |reverse.list|\n {\n var nx: Node?;\n nx := current.next;\n assert nx != null ==>\n forall i | 0 <= i < |nx.list| ::\n current.list[i + 1] == nx.list[i];\n // The state looks like: ..., reverse, current, nx, ...\n assert current.data == current.list[0];\n current.next := reverse;\n current.footprint := {current} + reverse.footprint;\n current.list := [current.data] + reverse.list;\n\n reverse := current;\n current := nx;\n }\n }\n}\n", "hints_removed": "// Examples used in paper:\n// Specification and Verification of Object-Oriented Software\n// by K. Rustan M. Leino\n// link of the paper:\n// http://leino.science/papers/krml190.pdf\n\n// Figure 0. An example linked-list program written in Dafny.\nclass Data { }\n\nclass Node {\n var list: seq;\n var footprint: set;\n\n var data: Data;\n var next: Node?;\n\n function Valid(): bool\n reads this, footprint\n {\n this in footprint &&\n (next == null ==> list == [data]) &&\n (next != null ==> next in footprint &&\n next.footprint <= footprint &&\n !(this in next.footprint) &&\n list == [data] + next.list &&\n next.Valid())\n }\n\n constructor(d: Data)\n ensures Valid() && fresh(footprint - {this})\n ensures list == [d]\n {\n data := d;\n next := null;\n list := [d];\n footprint := {this};\n }\n\n method SkipHead() returns (r: Node?)\n requires Valid()\n ensures r == null ==> |list| == 1\n ensures r != null ==> r.Valid() && r.footprint <= footprint\n {\n return next;\n }\n\n method Prepend(d: Data) returns (r: Node)\n requires Valid()\n ensures r.Valid() && fresh(r.footprint - old(footprint))\n ensures r.list == [d] + list\n {\n r := new Node(d);\n r.data := d;\n r.next := this;\n r.footprint := {r} + footprint;\n r.list := [r.data] + list;\n }\n\n // Figure 1: The Node.ReverseInPlace method,\n // which performs an in situ list reversal.\n method ReverseInPlace() returns (reverse: Node)\n requires Valid()\n modifies footprint\n ensures reverse.Valid()\n // isn't here a typo?\n ensures fresh(reverse.footprint - old(footprint))\n ensures |reverse.list| == |old(list)|\n ensures forall i | 0 <= i < |old(list)| :: old(list)[i] == reverse.list[|old(list)| - 1 - i]\n {\n var current: Node?;\n current := next;\n reverse := this;\n reverse.next := null;\n reverse.footprint := {reverse};\n reverse.list := [data];\n\n while current != null\n current.Valid()\n current in old(footprint) && current.footprint <= old(footprint)\n current.footprint !! reverse.footprint\n |old(list)| == |reverse.list| + |current.list|\n forall i | 0 <= i < |current.list| ::\n current.list[i] == old(list)[|reverse.list| + i]\n old(list)[i] == reverse.list[|reverse.list| - 1 - i]\n {\n var nx: Node?;\n nx := current.next;\n forall i | 0 <= i < |nx.list| ::\n current.list[i + 1] == nx.list[i];\n // The state looks like: ..., reverse, current, nx, ...\n current.next := reverse;\n current.footprint := {current} + reverse.footprint;\n current.list := [current.data] + reverse.list;\n\n reverse := current;\n current := nx;\n }\n }\n}\n" }, { "test_ID": "441", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_LanguageServerTest_DafnyFiles_symbolTable_15_array.dfy", "ground_truth": "method Main() {\n var i := 2;\n var s := [1, i, 3, 4, 5];\n print |s|; //size\n assert s[|s|-1] == 5; //access the last element\n assert s[|s|-1..|s|] == [5]; //slice just the last element, as a singleton\n assert s[1..] == [2, 3, 4, 5]; // everything but the first\n assert s[..|s|-1] == [1, 2, 3, 4]; // everything but the last\n assert s == s[0..] == s[..|s|] == s[0..|s|] == s[..]; // the whole sequence\n\n}\n\nmethod foo (s: seq)\nrequires |s| > 1\n{\n print s[1];\n}\n", "hints_removed": "method Main() {\n var i := 2;\n var s := [1, i, 3, 4, 5];\n print |s|; //size\n\n}\n\nmethod foo (s: seq)\nrequires |s| > 1\n{\n print s[1];\n}\n" }, { "test_ID": "442", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_VSComp2010_Problem1-SumMax.dfy", "ground_truth": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// VSComp 2010, problem 1, compute the sum and max of the elements of an array and prove\n// that 'sum <= N * max'.\n// Rustan Leino, 18 August 2010.\n//\n// The problem statement gave the pseudo-code for the method, but did not ask to prove\n// that 'sum' or 'max' return as the sum and max, respectively, of the array. The\n// given assumption that the array's elements are non-negative is not needed to establish\n// the requested postcondition.\n\nmethod M(N: int, a: array) returns (sum: int, max: int)\n requires 0 <= N && a.Length == N && (forall k :: 0 <= k && k < N ==> 0 <= a[k]);\n ensures sum <= N * max;\n{\n sum := 0;\n max := 0;\n var i := 0;\n while (i < N)\n invariant i <= N && sum <= i * max;\n {\n if (max < a[i]) {\n max := a[i];\n }\n sum := sum + a[i];\n i := i + 1;\n }\n}\n\nmethod Main()\n{\n var a := new int[10];\n a[0] := 9;\n a[1] := 5;\n a[2] := 0;\n a[3] := 2;\n a[4] := 7;\n a[5] := 3;\n a[6] := 2;\n a[7] := 1;\n a[8] := 10;\n a[9] := 6;\n var s, m := M(10, a);\n print \"N = \", a.Length, \" sum = \", s, \" max = \", m, \"\\n\";\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// VSComp 2010, problem 1, compute the sum and max of the elements of an array and prove\n// that 'sum <= N * max'.\n// Rustan Leino, 18 August 2010.\n//\n// The problem statement gave the pseudo-code for the method, but did not ask to prove\n// that 'sum' or 'max' return as the sum and max, respectively, of the array. The\n// given assumption that the array's elements are non-negative is not needed to establish\n// the requested postcondition.\n\nmethod M(N: int, a: array) returns (sum: int, max: int)\n requires 0 <= N && a.Length == N && (forall k :: 0 <= k && k < N ==> 0 <= a[k]);\n ensures sum <= N * max;\n{\n sum := 0;\n max := 0;\n var i := 0;\n while (i < N)\n {\n if (max < a[i]) {\n max := a[i];\n }\n sum := sum + a[i];\n i := i + 1;\n }\n}\n\nmethod Main()\n{\n var a := new int[10];\n a[0] := 9;\n a[1] := 5;\n a[2] := 0;\n a[3] := 2;\n a[4] := 7;\n a[5] := 3;\n a[6] := 2;\n a[7] := 1;\n a[8] := 10;\n a[9] := 6;\n var s, m := M(10, a);\n print \"N = \", a.Length, \" sum = \", s, \" max = \", m, \"\\n\";\n}\n\n" }, { "test_ID": "443", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_VSI-Benchmarks_b1.dfy", "ground_truth": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// Spec# and Boogie and Chalice: The program will be\n// the same, except that these languages do not check\n// for any kind of termination. Also, in Spec#, there\n// is an issue of potential overflows.\n\n// Benchmark1\n\nmethod Add(x: int, y: int) returns (r: int)\n ensures r == x+y;\n{\n r := x;\n if (y < 0) {\n var n := y;\n while (n != 0)\n invariant r == x+y-n && 0 <= -n;\n {\n r := r - 1;\n n := n + 1;\n }\n } else {\n var n := y;\n while (n != 0)\n invariant r == x+y-n && 0 <= n;\n {\n r := r + 1;\n n := n - 1;\n }\n }\n}\n\nmethod Mul(x: int, y: int) returns (r: int)\n ensures r == x*y;\n decreases x < 0, x;\n{\n if (x == 0) {\n r := 0;\n } else if (x < 0) {\n r := Mul(-x, y);\n r := -r;\n } else {\n r := Mul(x-1, y);\n r := Add(r, y);\n }\n}\n\n// ---------------------------\n\nmethod Main() {\n TestAdd(3, 180);\n TestAdd(3, -180);\n TestAdd(0, 1);\n\n TestMul(3, 180);\n TestMul(3, -180);\n TestMul(180, 3);\n TestMul(-180, 3);\n TestMul(0, 1);\n TestMul(1, 0);\n}\n\nmethod TestAdd(x: int, y: int) {\n print x, \" + \", y, \" = \";\n var z := Add(x, y);\n print z, \"\\n\";\n}\n\nmethod TestMul(x: int, y: int) {\n print x, \" * \", y, \" = \";\n var z := Mul(x, y);\n print z, \"\\n\";\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// Spec# and Boogie and Chalice: The program will be\n// the same, except that these languages do not check\n// for any kind of termination. Also, in Spec#, there\n// is an issue of potential overflows.\n\n// Benchmark1\n\nmethod Add(x: int, y: int) returns (r: int)\n ensures r == x+y;\n{\n r := x;\n if (y < 0) {\n var n := y;\n while (n != 0)\n {\n r := r - 1;\n n := n + 1;\n }\n } else {\n var n := y;\n while (n != 0)\n {\n r := r + 1;\n n := n - 1;\n }\n }\n}\n\nmethod Mul(x: int, y: int) returns (r: int)\n ensures r == x*y;\n{\n if (x == 0) {\n r := 0;\n } else if (x < 0) {\n r := Mul(-x, y);\n r := -r;\n } else {\n r := Mul(x-1, y);\n r := Add(r, y);\n }\n}\n\n// ---------------------------\n\nmethod Main() {\n TestAdd(3, 180);\n TestAdd(3, -180);\n TestAdd(0, 1);\n\n TestMul(3, 180);\n TestMul(3, -180);\n TestMul(180, 3);\n TestMul(-180, 3);\n TestMul(0, 1);\n TestMul(1, 0);\n}\n\nmethod TestAdd(x: int, y: int) {\n print x, \" + \", y, \" = \";\n var z := Add(x, y);\n print z, \"\\n\";\n}\n\nmethod TestMul(x: int, y: int) {\n print x, \" * \", y, \" = \";\n var z := Mul(x, y);\n print z, \"\\n\";\n}\n\n" }, { "test_ID": "444", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_VSI-Benchmarks_b2.dfy", "ground_truth": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nclass Benchmark2 {\n method BinarySearch(a: array, key: int) returns (result: int)\n requires forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j];\n ensures -1 <= result < a.Length;\n ensures 0 <= result ==> a[result] == key;\n ensures result == -1 ==> forall i :: 0 <= i < a.Length ==> a[i] != key;\n {\n var low := 0;\n var high := a.Length;\n\n while (low < high)\n invariant 0 <= low <= high <= a.Length;\n invariant forall i :: 0 <= i < low ==> a[i] < key;\n invariant forall i :: high <= i < a.Length ==> key < a[i];\n {\n var mid := low + (high - low) / 2;\n var midVal := a[mid];\n\n if (midVal < key) {\n low := mid + 1;\n } else if (key < midVal) {\n high := mid;\n } else {\n result := mid; // key found\n return;\n }\n }\n result := -1; // key not present\n }\n}\n\nmethod Main() {\n var a := new int[5];\n a[0] := -4;\n a[1] := -2;\n a[2] := -2;\n a[3] := 0;\n a[4] := 25;\n TestSearch(a, 4);\n TestSearch(a, -8);\n TestSearch(a, -2);\n TestSearch(a, 0);\n TestSearch(a, 23);\n TestSearch(a, 25);\n TestSearch(a, 27);\n}\n\nmethod TestSearch(a: array, key: int)\n requires forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j];\n{\n var b := new Benchmark2;\n var r := b.BinarySearch(a, key);\n print \"Looking for key=\", key, \", result=\", r, \"\\n\";\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nclass Benchmark2 {\n method BinarySearch(a: array, key: int) returns (result: int)\n requires forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j];\n ensures -1 <= result < a.Length;\n ensures 0 <= result ==> a[result] == key;\n ensures result == -1 ==> forall i :: 0 <= i < a.Length ==> a[i] != key;\n {\n var low := 0;\n var high := a.Length;\n\n while (low < high)\n {\n var mid := low + (high - low) / 2;\n var midVal := a[mid];\n\n if (midVal < key) {\n low := mid + 1;\n } else if (key < midVal) {\n high := mid;\n } else {\n result := mid; // key found\n return;\n }\n }\n result := -1; // key not present\n }\n}\n\nmethod Main() {\n var a := new int[5];\n a[0] := -4;\n a[1] := -2;\n a[2] := -2;\n a[3] := 0;\n a[4] := 25;\n TestSearch(a, 4);\n TestSearch(a, -8);\n TestSearch(a, -2);\n TestSearch(a, 0);\n TestSearch(a, 23);\n TestSearch(a, 25);\n TestSearch(a, 27);\n}\n\nmethod TestSearch(a: array, key: int)\n requires forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j];\n{\n var b := new Benchmark2;\n var r := b.BinarySearch(a, key);\n print \"Looking for key=\", key, \", result=\", r, \"\\n\";\n}\n\n" }, { "test_ID": "445", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_allocated1_dafny0_fun-with-slices.dfy", "ground_truth": "// RUN: %dafny /verifyAllModules /allocated:1 /compile:0 /print:\"%t.print\" /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// This test was contributed by Bryan. It has shown some instabilities in the past.\n\nmethod seqIntoArray(s: seq, a: array, index: nat)\n requires index + |s| <= a.Length\n modifies a\n ensures a[..] == old(a[..index]) + s + old(a[index + |s|..])\n{\n var i := index;\n\n while i < index + |s|\n invariant index <= i <= index + |s| <= a.Length\n invariant a[..] == old(a[..index]) + s[..i - index] + old(a[i..])\n {\n label A:\n a[i] := s[i - index];\n calc {\n a[..];\n == // assignment statement above\n old@A(a[..])[i := s[i - index]];\n == // invariant on entry to loop\n (old(a[..index]) + s[..i - index] + old(a[i..]))[i := s[i - index]];\n == { assert old(a[..index]) + s[..i - index] + old(a[i..]) == (old(a[..index]) + s[..i - index]) + old(a[i..]); }\n ((old(a[..index]) + s[..i - index]) + old(a[i..]))[i := s[i - index]];\n == { assert |old(a[..index]) + s[..i - index]| == i; }\n (old(a[..index]) + s[..i - index]) + old(a[i..])[0 := s[i - index]];\n == { assert old(a[i..])[0 := s[i - index]] == [s[i - index]] + old(a[i..])[1..]; }\n (old(a[..index]) + s[..i - index]) + [s[i - index]] + old(a[i..])[1..];\n == { assert old(a[i..])[1..] == old(a[i + 1..]); }\n (old(a[..index]) + s[..i - index]) + [s[i - index]] + old(a[i + 1..]);\n == // redistribute +\n old(a[..index]) + (s[..i - index] + [s[i - index]]) + old(a[i + 1..]);\n == { assert s[..i - index] + [s[i - index]] == s[..i + 1 - index]; }\n old(a[..index]) + s[..i + 1 - index] + old(a[i + 1..]);\n }\n i := i + 1;\n }\n}\n\n", "hints_removed": "// RUN: %dafny /verifyAllModules /allocated:1 /compile:0 /print:\"%t.print\" /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// This test was contributed by Bryan. It has shown some instabilities in the past.\n\nmethod seqIntoArray(s: seq, a: array, index: nat)\n requires index + |s| <= a.Length\n modifies a\n ensures a[..] == old(a[..index]) + s + old(a[index + |s|..])\n{\n var i := index;\n\n while i < index + |s|\n {\n label A:\n a[i] := s[i - index];\n calc {\n a[..];\n == // assignment statement above\n old@A(a[..])[i := s[i - index]];\n == // invariant on entry to loop\n (old(a[..index]) + s[..i - index] + old(a[i..]))[i := s[i - index]];\n == { assert old(a[..index]) + s[..i - index] + old(a[i..]) == (old(a[..index]) + s[..i - index]) + old(a[i..]); }\n ((old(a[..index]) + s[..i - index]) + old(a[i..]))[i := s[i - index]];\n == { assert |old(a[..index]) + s[..i - index]| == i; }\n (old(a[..index]) + s[..i - index]) + old(a[i..])[0 := s[i - index]];\n == { assert old(a[i..])[0 := s[i - index]] == [s[i - index]] + old(a[i..])[1..]; }\n (old(a[..index]) + s[..i - index]) + [s[i - index]] + old(a[i..])[1..];\n == { assert old(a[i..])[1..] == old(a[i + 1..]); }\n (old(a[..index]) + s[..i - index]) + [s[i - index]] + old(a[i + 1..]);\n == // redistribute +\n old(a[..index]) + (s[..i - index] + [s[i - index]]) + old(a[i + 1..]);\n == { assert s[..i - index] + [s[i - index]] == s[..i + 1 - index]; }\n old(a[..index]) + s[..i + 1 - index] + old(a[i + 1..]);\n }\n i := i + 1;\n }\n}\n\n" }, { "test_ID": "446", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_comp_Arrays.dfy", "ground_truth": "// RUN: %dafny /compile:3 /spillTargetCode:2 /compileTarget:cs \"%s\" > \"%t\"\n// RUN: %dafny /compile:3 /spillTargetCode:2 /compileTarget:js \"%s\" >> \"%t\"\n// RUN: %dafny /compile:3 /spillTargetCode:2 /compileTarget:go \"%s\" >> \"%t\"\n// RUN: %dafny /compile:3 /spillTargetCode:2 /compileTarget:java \"%s\" >> \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nmethod LinearSearch(a: array, key: int) returns (n: nat)\n ensures 0 <= n <= a.Length\n ensures n == a.Length || a[n] == key\n{\n n := 0;\n while n < a.Length\n invariant n <= a.Length\n {\n if a[n] == key {\n return;\n }\n n := n + 1;\n }\n}\n\nmethod PrintArray(a: array?) {\n if (a == null) {\n print \"It's null\\n\";\n } else {\n var i := 0;\n while i < a.Length {\n print a[i], \" \";\n i := i + 1;\n }\n print \"\\n\";\n }\n}\n\nmethod Main() {\n var a := new int[23];\n var i := 0;\n while i < 23 {\n a[i] := i;\n i := i + 1;\n }\n PrintArray(a);\n var n := LinearSearch(a, 17);\n print n, \"\\n\";\n var s : seq := a[..];\n print s, \"\\n\";\n s := a[2..16];\n print s, \"\\n\";\n s := a[20..];\n print s, \"\\n\";\n s := a[..8];\n print s, \"\\n\";\n\n // Conversion to sequence should copy elements (sequences are immutable!)\n a[0] := 42;\n print s, \"\\n\";\n\n InitTests();\n\n MultipleDimensions();\n\n PrintArray(null);\n}\n\ntype lowercase = ch | 'a' <= ch <= 'z' witness 'd'\n\nmethod InitTests() {\n var aa := new lowercase[3];\n PrintArray(aa);\n var s := \"hello\";\n aa := new lowercase[|s|](i requires 0 <= i < |s| => s[i]);\n PrintArray(aa);\n}\n\nmethod MultipleDimensions() {\n var matrix := new int[2,8];\n PrintMatrix(matrix);\n matrix := DiagMatrix(3, 5, 0, 1);\n PrintMatrix(matrix);\n\n var cube := new int[3,0,4]((_,_,_) => 16);\n print \"cube dims: \", cube.Length0, \" \", cube.Length1, \" \", cube.Length2, \"\\n\";\n\n// FIXME: This breaks Java (and has for some time).\n//\n// var jagged := new array[5];\n// var i := 0;\n// while i < 5 {\n// jagged[i] := new int[i];\n// i := i + 1;\n// }\n// PrintArray(jagged);\n}\n\nmethod DiagMatrix(rows: int, cols: int, zero: A, one: A)\n returns (a: array2)\n requires rows >= 0 && cols >= 0\n{\n return new A[rows, cols]((x,y) => if x==y then one else zero);\n}\n\nmethod PrintMatrix(m: array2) {\n var i := 0;\n while i < m.Length0 {\n var j := 0;\n while j < m.Length1 {\n print m[i,j], \" \";\n j := j + 1;\n }\n print \"\\n\";\n i := i + 1;\n }\n}\n\n", "hints_removed": "// RUN: %dafny /compile:3 /spillTargetCode:2 /compileTarget:cs \"%s\" > \"%t\"\n// RUN: %dafny /compile:3 /spillTargetCode:2 /compileTarget:js \"%s\" >> \"%t\"\n// RUN: %dafny /compile:3 /spillTargetCode:2 /compileTarget:go \"%s\" >> \"%t\"\n// RUN: %dafny /compile:3 /spillTargetCode:2 /compileTarget:java \"%s\" >> \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nmethod LinearSearch(a: array, key: int) returns (n: nat)\n ensures 0 <= n <= a.Length\n ensures n == a.Length || a[n] == key\n{\n n := 0;\n while n < a.Length\n {\n if a[n] == key {\n return;\n }\n n := n + 1;\n }\n}\n\nmethod PrintArray(a: array?) {\n if (a == null) {\n print \"It's null\\n\";\n } else {\n var i := 0;\n while i < a.Length {\n print a[i], \" \";\n i := i + 1;\n }\n print \"\\n\";\n }\n}\n\nmethod Main() {\n var a := new int[23];\n var i := 0;\n while i < 23 {\n a[i] := i;\n i := i + 1;\n }\n PrintArray(a);\n var n := LinearSearch(a, 17);\n print n, \"\\n\";\n var s : seq := a[..];\n print s, \"\\n\";\n s := a[2..16];\n print s, \"\\n\";\n s := a[20..];\n print s, \"\\n\";\n s := a[..8];\n print s, \"\\n\";\n\n // Conversion to sequence should copy elements (sequences are immutable!)\n a[0] := 42;\n print s, \"\\n\";\n\n InitTests();\n\n MultipleDimensions();\n\n PrintArray(null);\n}\n\ntype lowercase = ch | 'a' <= ch <= 'z' witness 'd'\n\nmethod InitTests() {\n var aa := new lowercase[3];\n PrintArray(aa);\n var s := \"hello\";\n aa := new lowercase[|s|](i requires 0 <= i < |s| => s[i]);\n PrintArray(aa);\n}\n\nmethod MultipleDimensions() {\n var matrix := new int[2,8];\n PrintMatrix(matrix);\n matrix := DiagMatrix(3, 5, 0, 1);\n PrintMatrix(matrix);\n\n var cube := new int[3,0,4]((_,_,_) => 16);\n print \"cube dims: \", cube.Length0, \" \", cube.Length1, \" \", cube.Length2, \"\\n\";\n\n// FIXME: This breaks Java (and has for some time).\n//\n// var jagged := new array[5];\n// var i := 0;\n// while i < 5 {\n// jagged[i] := new int[i];\n// i := i + 1;\n// }\n// PrintArray(jagged);\n}\n\nmethod DiagMatrix(rows: int, cols: int, zero: A, one: A)\n returns (a: array2)\n requires rows >= 0 && cols >= 0\n{\n return new A[rows, cols]((x,y) => if x==y then one else zero);\n}\n\nmethod PrintMatrix(m: array2) {\n var i := 0;\n while i < m.Length0 {\n var j := 0;\n while j < m.Length1 {\n print m[i,j], \" \";\n j := j + 1;\n }\n print \"\\n\";\n i := i + 1;\n }\n}\n\n" }, { "test_ID": "447", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny0_FuelTriggers.dfy", "ground_truth": "// RUN: %dafny /ironDafny /compile:0 /print:\"%t.print\" /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// In one version of opaque + fuel, the following failed to verify\n// because the quantifier in the requires used a trigger that included\n// StartFuel_P, while the assert used StartFuelAssert_P. Since P is\n// opaque, we can't tell that those fuels are the same, and hence the\n// trigger never fires\n\npredicate {:opaque} P(x:int)\n\nmethod test(y:int)\n requires forall x :: P(x);\n{\n assert P(y);\n}\n\n", "hints_removed": "// RUN: %dafny /ironDafny /compile:0 /print:\"%t.print\" /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// In one version of opaque + fuel, the following failed to verify\n// because the quantifier in the requires used a trigger that included\n// StartFuel_P, while the assert used StartFuelAssert_P. Since P is\n// opaque, we can't tell that those fuels are the same, and hence the\n// trigger never fires\n\npredicate {:opaque} P(x:int)\n\nmethod test(y:int)\n requires forall x :: P(x);\n{\n}\n\n" }, { "test_ID": "448", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny0_snapshots_Inputs_Snapshots0.dfy", "ground_truth": "method foo()\n{\n bar();\n assert false;\n}\n\nmethod bar()\n ensures false;\n\n", "hints_removed": "method foo()\n{\n bar();\n}\n\nmethod bar()\n ensures false;\n\n" }, { "test_ID": "449", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny1_Cubes.dfy", "ground_truth": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nmethod Cubes(a: array)\n modifies a\n ensures forall i :: 0 <= i < a.Length ==> a[i] == i*i*i\n{\n var n := 0;\n var c := 0;\n var k := 1;\n var m := 6;\n while n < a.Length\n invariant 0 <= n <= a.Length\n invariant forall i :: 0 <= i < n ==> a[i] == i*i*i\n invariant c == n*n*n\n invariant k == 3*n*n + 3*n + 1\n invariant m == 6*n + 6\n {\n a[n] := c;\n c := c + k;\n k := k + m;\n m := m + 6;\n n := n + 1;\n }\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nmethod Cubes(a: array)\n modifies a\n ensures forall i :: 0 <= i < a.Length ==> a[i] == i*i*i\n{\n var n := 0;\n var c := 0;\n var k := 1;\n var m := 6;\n while n < a.Length\n {\n a[n] := c;\n c := c + k;\n k := k + m;\n m := m + 6;\n n := n + 1;\n }\n}\n\n" }, { "test_ID": "450", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny1_ListReverse.dfy", "ground_truth": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nclass Node {\n var nxt: Node?\n\n method ReverseInPlace(x: Node?, r: set) returns (reverse: Node?)\n requires x == null || x in r;\n requires (forall y :: y in r ==> y.nxt == null || y.nxt in r); // region closure\n modifies r;\n ensures reverse == null || reverse in r;\n ensures (forall y :: y in r ==> y.nxt == null || y.nxt in r); // region closure\n decreases *;\n {\n var current: Node? := x;\n reverse := null;\n while (current != null)\n invariant current == null || current in r;\n invariant reverse == null || reverse in r;\n invariant (forall y :: y in r ==> y.nxt == null || y.nxt in r); // region closure\n decreases *; // omit loop termination check\n {\n var tmp := current.nxt;\n current.nxt := reverse;\n reverse := current;\n current := tmp;\n }\n }\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nclass Node {\n var nxt: Node?\n\n method ReverseInPlace(x: Node?, r: set) returns (reverse: Node?)\n requires x == null || x in r;\n requires (forall y :: y in r ==> y.nxt == null || y.nxt in r); // region closure\n modifies r;\n ensures reverse == null || reverse in r;\n ensures (forall y :: y in r ==> y.nxt == null || y.nxt in r); // region closure\n {\n var current: Node? := x;\n reverse := null;\n while (current != null)\n {\n var tmp := current.nxt;\n current.nxt := reverse;\n reverse := current;\n current := tmp;\n }\n }\n}\n\n" }, { "test_ID": "451", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny1_MatrixFun.dfy", "ground_truth": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nmethod MirrorImage(m: array2)\n modifies m\n ensures forall i,j :: 0 <= i < m.Length0 && 0 <= j < m.Length1 ==>\n m[i,j] == old(m[i, m.Length1-1-j])\n{\n var a := 0;\n while a < m.Length0\n invariant a <= m.Length0\n invariant forall i,j :: 0 <= i && i < a && 0 <= j && j < m.Length1 ==>\n m[i,j] == old(m[i, m.Length1-1-j])\n invariant forall i,j :: a <= i && i < m.Length0 && 0 <= j && j < m.Length1 ==>\n m[i,j] == old(m[i,j])\n {\n var b := 0;\n while b < m.Length1 / 2\n invariant b <= m.Length1 / 2\n invariant forall i,j :: 0 <= i && i < a && 0 <= j && j < m.Length1 ==>\n m[i,j] == old(m[i, m.Length1-1-j])\n invariant forall j :: 0 <= j && j < b ==>\n m[a,j] == old(m[a, m.Length1-1-j]) &&\n old(m[a,j]) == m[a, m.Length1-1-j]\n invariant forall j :: b <= j && j < m.Length1-b ==> m[a,j] == old(m[a,j])\n invariant forall i,j :: a+1 <= i && i < m.Length0 && 0 <= j && j < m.Length1 ==>\n m[i,j] == old(m[i,j])\n {\n m[a, m.Length1-1-b], m[a, b] := m[a, b], m[a, m.Length1-1-b];\n b := b + 1;\n }\n a := a + 1;\n }\n}\n\nmethod Flip(m: array2)\n requires m.Length0 == m.Length1\n modifies m\n ensures forall i,j :: 0 <= i < m.Length0 && 0 <= j < m.Length1 ==> m[i,j] == old(m[j,i])\n{\n var N := m.Length0;\n var a := 0;\n var b := 1;\n while a != N\n invariant a < b <= N || (a == N && b == N+1)\n invariant forall i,j :: 0 <= i <= j < N ==>\n if i < a || (i == a && j < b)\n then m[i,j] == old(m[j,i]) && m[j,i] == old(m[i,j])\n else m[i,j] == old(m[i,j]) && m[j,i] == old(m[j,i])\n decreases N-a, N-b\n {\n if b < N {\n m[a,b], m[b,a] := m[b,a], m[a,b];\n b := b + 1;\n } else {\n a := a + 1; b := a + 1;\n }\n }\n}\n\nmethod Main()\n{\n var B := new bool[2,5];\n B[0,0] := true; B[0,1] := false; B[0,2] := false; B[0,3] := true; B[0,4] := false;\n B[1,0] := true; B[1,1] := true; B[1,2] := true; B[1,3] := true; B[1,4] := false;\n print \"Before:\\n\";\n PrintMatrix(B);\n MirrorImage(B);\n print \"Mirror image:\\n\";\n PrintMatrix(B);\n\n var A := new int[3,3];\n A[0,0] := 5; A[0,1] := 7; A[0,2] := 9;\n A[1,0] := 6; A[1,1] := 2; A[1,2] := 3;\n A[2,0] := 7; A[2,1] := 1; A[2,2] := 0;\n print \"Before:\\n\";\n PrintMatrix(A);\n Flip(A);\n print \"Flip:\\n\";\n PrintMatrix(A);\n}\n\nmethod PrintMatrix(m: array2)\n{\n var i := 0;\n while i < m.Length0 {\n var j := 0;\n while j < m.Length1 {\n print m[i,j];\n j := j + 1;\n if j == m.Length1 {\n print \"\\n\";\n } else {\n print \", \";\n }\n }\n i := i + 1;\n }\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nmethod MirrorImage(m: array2)\n modifies m\n ensures forall i,j :: 0 <= i < m.Length0 && 0 <= j < m.Length1 ==>\n m[i,j] == old(m[i, m.Length1-1-j])\n{\n var a := 0;\n while a < m.Length0\n m[i,j] == old(m[i, m.Length1-1-j])\n m[i,j] == old(m[i,j])\n {\n var b := 0;\n while b < m.Length1 / 2\n m[i,j] == old(m[i, m.Length1-1-j])\n m[a,j] == old(m[a, m.Length1-1-j]) &&\n old(m[a,j]) == m[a, m.Length1-1-j]\n m[i,j] == old(m[i,j])\n {\n m[a, m.Length1-1-b], m[a, b] := m[a, b], m[a, m.Length1-1-b];\n b := b + 1;\n }\n a := a + 1;\n }\n}\n\nmethod Flip(m: array2)\n requires m.Length0 == m.Length1\n modifies m\n ensures forall i,j :: 0 <= i < m.Length0 && 0 <= j < m.Length1 ==> m[i,j] == old(m[j,i])\n{\n var N := m.Length0;\n var a := 0;\n var b := 1;\n while a != N\n if i < a || (i == a && j < b)\n then m[i,j] == old(m[j,i]) && m[j,i] == old(m[i,j])\n else m[i,j] == old(m[i,j]) && m[j,i] == old(m[j,i])\n {\n if b < N {\n m[a,b], m[b,a] := m[b,a], m[a,b];\n b := b + 1;\n } else {\n a := a + 1; b := a + 1;\n }\n }\n}\n\nmethod Main()\n{\n var B := new bool[2,5];\n B[0,0] := true; B[0,1] := false; B[0,2] := false; B[0,3] := true; B[0,4] := false;\n B[1,0] := true; B[1,1] := true; B[1,2] := true; B[1,3] := true; B[1,4] := false;\n print \"Before:\\n\";\n PrintMatrix(B);\n MirrorImage(B);\n print \"Mirror image:\\n\";\n PrintMatrix(B);\n\n var A := new int[3,3];\n A[0,0] := 5; A[0,1] := 7; A[0,2] := 9;\n A[1,0] := 6; A[1,1] := 2; A[1,2] := 3;\n A[2,0] := 7; A[2,1] := 1; A[2,2] := 0;\n print \"Before:\\n\";\n PrintMatrix(A);\n Flip(A);\n print \"Flip:\\n\";\n PrintMatrix(A);\n}\n\nmethod PrintMatrix(m: array2)\n{\n var i := 0;\n while i < m.Length0 {\n var j := 0;\n while j < m.Length1 {\n print m[i,j];\n j := j + 1;\n if j == m.Length1 {\n print \"\\n\";\n } else {\n print \", \";\n }\n }\n i := i + 1;\n }\n}\n\n" }, { "test_ID": "452", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny2_COST-verif-comp-2011-1-MaxArray.dfy", "ground_truth": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n/*\nRustan Leino, 5 Oct 2011\n\nCOST Verification Competition, Challenge 1: Maximum in an array\nhttp://foveoos2011.cost-ic0701.org/verification-competition\n\nGiven: A non-empty integer array a.\n\nVerify that the index returned by the method max() given below points to\nan element maximal in the array.\n\npublic class Max {\n public static int max(int[] a) {\n int x = 0;\n int y = a.length-1;\n\n while (x != y) {\n if (a[x] <= a[y]) x++;\n else y--;\n }\n return x;\n }\n}\n*/\n\n// Remarks:\n\n// The verification of the loop makes use of a local ghost variable 'm'. To the\n// verifier, this variable is like any other, but the Dafny compiler ignores it.\n// In other words, ghost variables and ghost assignments (and specifications,\n// for that matter) are included in the program just for the purpose of reasoning\n// about the program, and they play no role at run time.\n\n// The only thing that needs to be human-trusted about this program is the\n// specification of 'max' (and, since verification challenge asked to prove\n// something about a particular piece of code, that the body of 'max', minus\n// the ghost constructs, is really that code).\n\n// About Dafny:\n// As always (when it is successful), Dafny verifies that the program does not\n// cause any run-time errors (like array index bounds errors), that the program\n// terminates, that expressions and functions are well defined, and that all\n// specifications are satisfied. The language prevents type errors by being type\n// safe, prevents dangling pointers by not having an \"address-of\" or \"deallocate\"\n// operation (which is accommodated at run time by a garbage collector), and\n// prevents arithmetic overflow errors by using mathematical integers (which\n// is accommodated at run time by using BigNum's). By proving that programs\n// terminate, Dafny proves that a program's time usage is finite, which implies\n// that the program's space usage is finite too. However, executing the\n// program may fall short of your hopes if you don't have enough time or\n// space; that is, the program may run out of space or may fail to terminate in\n// your lifetime, because Dafny does not prove that the time or space needed by\n// the program matches your execution environment. The only input fed to\n// the Dafny verifier/compiler is the program text below; Dafny then automatically\n// verifies and compiles the program (for this program in less than 2 seconds)\n// without further human intervention.\n\nmethod max(a: array) returns (x: int)\n requires a.Length != 0\n ensures 0 <= x < a.Length\n ensures forall i :: 0 <= i < a.Length ==> a[i] <= a[x]\n{\n x := 0;\n var y := a.Length - 1;\n ghost var m := y;\n while x != y\n invariant 0 <= x <= y < a.Length\n invariant m == x || m == y\n invariant forall i :: 0 <= i < x ==> a[i] <= a[m]\n invariant forall i :: y < i < a.Length ==> a[i] <= a[m]\n {\n if a[x] <= a[y] {\n x := x + 1; m := y;\n } else {\n y := y - 1; m := x;\n }\n }\n return x;\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n/*\nRustan Leino, 5 Oct 2011\n\nCOST Verification Competition, Challenge 1: Maximum in an array\nhttp://foveoos2011.cost-ic0701.org/verification-competition\n\nGiven: A non-empty integer array a.\n\nVerify that the index returned by the method max() given below points to\nan element maximal in the array.\n\npublic class Max {\n public static int max(int[] a) {\n int x = 0;\n int y = a.length-1;\n\n while (x != y) {\n if (a[x] <= a[y]) x++;\n else y--;\n }\n return x;\n }\n}\n*/\n\n// Remarks:\n\n// The verification of the loop makes use of a local ghost variable 'm'. To the\n// verifier, this variable is like any other, but the Dafny compiler ignores it.\n// In other words, ghost variables and ghost assignments (and specifications,\n// for that matter) are included in the program just for the purpose of reasoning\n// about the program, and they play no role at run time.\n\n// The only thing that needs to be human-trusted about this program is the\n// specification of 'max' (and, since verification challenge asked to prove\n// something about a particular piece of code, that the body of 'max', minus\n// the ghost constructs, is really that code).\n\n// About Dafny:\n// As always (when it is successful), Dafny verifies that the program does not\n// cause any run-time errors (like array index bounds errors), that the program\n// terminates, that expressions and functions are well defined, and that all\n// specifications are satisfied. The language prevents type errors by being type\n// safe, prevents dangling pointers by not having an \"address-of\" or \"deallocate\"\n// operation (which is accommodated at run time by a garbage collector), and\n// prevents arithmetic overflow errors by using mathematical integers (which\n// is accommodated at run time by using BigNum's). By proving that programs\n// terminate, Dafny proves that a program's time usage is finite, which implies\n// that the program's space usage is finite too. However, executing the\n// program may fall short of your hopes if you don't have enough time or\n// space; that is, the program may run out of space or may fail to terminate in\n// your lifetime, because Dafny does not prove that the time or space needed by\n// the program matches your execution environment. The only input fed to\n// the Dafny verifier/compiler is the program text below; Dafny then automatically\n// verifies and compiles the program (for this program in less than 2 seconds)\n// without further human intervention.\n\nmethod max(a: array) returns (x: int)\n requires a.Length != 0\n ensures 0 <= x < a.Length\n ensures forall i :: 0 <= i < a.Length ==> a[i] <= a[x]\n{\n x := 0;\n var y := a.Length - 1;\n ghost var m := y;\n while x != y\n {\n if a[x] <= a[y] {\n x := x + 1; m := y;\n } else {\n y := y - 1; m := x;\n }\n }\n return x;\n}\n\n" }, { "test_ID": "453", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny2_Intervals.dfy", "ground_truth": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// The RoundDown and RoundUp methods in this file are the ones in the Boogie\n// implementation Source/AbsInt/IntervalDomain.cs.\n\nclass Rounding {\n var thresholds: array\n\n function Valid(): bool\n reads this, thresholds\n {\n forall m,n :: 0 <= m < n < thresholds.Length ==> thresholds[m] <= thresholds[n]\n }\n\n method RoundDown(k: int) returns (r: int)\n requires Valid()\n ensures -1 <= r < thresholds.Length\n ensures forall m :: r < m < thresholds.Length ==> k < thresholds[m]\n ensures 0 <= r ==> thresholds[r] <= k\n {\n if (thresholds.Length == 0 || k < thresholds[0]) {\n return -1;\n }\n var i, j := 0, thresholds.Length - 1;\n while (i < j)\n invariant 0 <= i <= j < thresholds.Length\n invariant thresholds[i] <= k\n invariant forall m :: j < m < thresholds.Length ==> k < thresholds[m]\n {\n var mid := i + (j - i + 1) / 2;\n assert i < mid <= j;\n if (thresholds[mid] <= k) {\n i := mid;\n } else {\n j := mid - 1;\n }\n }\n return i;\n }\n\n method RoundUp(k: int) returns (r: int)\n requires Valid()\n ensures 0 <= r <= thresholds.Length\n ensures forall m :: 0 <= m < r ==> thresholds[m] < k\n ensures r < thresholds.Length ==> k <= thresholds[r]\n {\n if (thresholds.Length == 0 || thresholds[thresholds.Length-1] < k) {\n return thresholds.Length;\n }\n var i, j := 0, thresholds.Length - 1;\n while (i < j)\n invariant 0 <= i <= j < thresholds.Length\n invariant k <= thresholds[j]\n invariant forall m :: 0 <= m < i ==> thresholds[m] < k\n {\n var mid := i + (j - i) / 2;\n assert i <= mid < j;\n if (thresholds[mid] < k) {\n i := mid + 1;\n } else {\n j := mid;\n }\n }\n return i;\n }\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// The RoundDown and RoundUp methods in this file are the ones in the Boogie\n// implementation Source/AbsInt/IntervalDomain.cs.\n\nclass Rounding {\n var thresholds: array\n\n function Valid(): bool\n reads this, thresholds\n {\n forall m,n :: 0 <= m < n < thresholds.Length ==> thresholds[m] <= thresholds[n]\n }\n\n method RoundDown(k: int) returns (r: int)\n requires Valid()\n ensures -1 <= r < thresholds.Length\n ensures forall m :: r < m < thresholds.Length ==> k < thresholds[m]\n ensures 0 <= r ==> thresholds[r] <= k\n {\n if (thresholds.Length == 0 || k < thresholds[0]) {\n return -1;\n }\n var i, j := 0, thresholds.Length - 1;\n while (i < j)\n {\n var mid := i + (j - i + 1) / 2;\n if (thresholds[mid] <= k) {\n i := mid;\n } else {\n j := mid - 1;\n }\n }\n return i;\n }\n\n method RoundUp(k: int) returns (r: int)\n requires Valid()\n ensures 0 <= r <= thresholds.Length\n ensures forall m :: 0 <= m < r ==> thresholds[m] < k\n ensures r < thresholds.Length ==> k <= thresholds[r]\n {\n if (thresholds.Length == 0 || thresholds[thresholds.Length-1] < k) {\n return thresholds.Length;\n }\n var i, j := 0, thresholds.Length - 1;\n while (i < j)\n {\n var mid := i + (j - i) / 2;\n if (thresholds[mid] < k) {\n i := mid + 1;\n } else {\n j := mid;\n }\n }\n return i;\n }\n}\n\n" }, { "test_ID": "454", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny2_SegmentSum.dfy", "ground_truth": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nfunction Sum(a: seq, s: int, t: int): int\n requires 0 <= s <= t <= |a|\n{\n if s == t then 0 else Sum(a, s, t-1) + a[t-1]\n}\n\nmethod MaxSegSum(a: seq) returns (k: int, m: int)\n ensures 0 <= k <= m <= |a|\n ensures forall p,q :: 0 <= p <= q <= |a| ==> Sum(a, p, q) <= Sum(a, k, m)\n{\n k, m := 0, 0;\n var s := 0; // invariant s == Sum(a, k, m)\n var n := 0;\n var c, t := 0, 0; // invariant t == Sum(a, c, n)\n while n < |a|\n invariant 0 <= c <= n <= |a| && t == Sum(a, c, n)\n invariant forall b :: 0 <= b <= n ==> Sum(a, b, n) <= Sum(a, c, n)\n invariant 0 <= k <= m <= n && s == Sum(a, k, m)\n invariant forall p,q :: 0 <= p <= q <= n ==> Sum(a, p, q) <= Sum(a, k, m)\n {\n t, n := t + a[n], n + 1;\n if t < 0 {\n c, t := n, 0;\n } else if s < t {\n k, m, s := c, n, t;\n }\n }\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nfunction Sum(a: seq, s: int, t: int): int\n requires 0 <= s <= t <= |a|\n{\n if s == t then 0 else Sum(a, s, t-1) + a[t-1]\n}\n\nmethod MaxSegSum(a: seq) returns (k: int, m: int)\n ensures 0 <= k <= m <= |a|\n ensures forall p,q :: 0 <= p <= q <= |a| ==> Sum(a, p, q) <= Sum(a, k, m)\n{\n k, m := 0, 0;\n var s := 0; // invariant s == Sum(a, k, m)\n var n := 0;\n var c, t := 0, 0; // invariant t == Sum(a, c, n)\n while n < |a|\n {\n t, n := t + a[n], n + 1;\n if t < 0 {\n c, t := n, 0;\n } else if s < t {\n k, m, s := c, n, t;\n }\n }\n}\n\n" }, { "test_ID": "455", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny2_TreeBarrier.dfy", "ground_truth": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nclass Node {\n var left: Node?\n var right: Node?\n var parent: Node?\n var anc: set\n var desc: set\n var sense: bool\n var pc: int\n\n\n predicate validDown()\n reads this, desc\n {\n this !in desc &&\n left != right && // not needed, but speeds up verification\n\n (right != null ==> right in desc && left !in right.desc) &&\n\n (left != null ==>\n left in desc &&\n (right != null ==> desc == {left,right} + left.desc + right.desc) &&\n (right == null ==> desc == {left} + left.desc) &&\n left.validDown()) &&\n (left == null ==>\n (right != null ==> desc == {right} + right.desc) &&\n (right == null ==> desc == {})) &&\n\n (right != null ==> right.validDown()) &&\n\n (blocked() ==> forall m :: m in desc ==> m.blocked()) &&\n (after() ==> forall m :: m in desc ==> m.blocked() || m.after())\n// (left != null && right != null ==> left.desc !! right.desc) // not needed\n }\n\n\n\n\n predicate validUp()\n reads this, anc\n {\n this !in anc &&\n (parent != null ==> parent in anc && anc == { parent } + parent.anc && parent.validUp()) &&\n (parent == null ==> anc == {}) &&\n (after() ==> forall m :: m in anc ==> m.after())\n }\n\n predicate valid()\n reads this, desc, anc\n { validUp() && validDown() && desc !! anc }\n\n predicate before()\n reads this\n { !sense && pc <= 2 }\n\n predicate blocked()\n reads this\n { sense }\n\n predicate after()\n reads this\n { !sense && 3 <= pc }\n\n\n method barrier()\n requires valid()\n requires before()\n modifies this, left, right\n decreases * // allow the method to not terminate\n {\n//A\n pc := 1;\n if(left != null) {\n while(!left.sense)\n modifies left\n invariant validDown() // this seems necessary to get the necessary unfolding of functions\n invariant valid()\n decreases * // to by-pass termination checking for this loop\n {\n // this loop body is supposed to model what the \"left\" thread\n // might do to its node. This body models a transition from\n // \"before\" to \"blocked\" by setting sense to true. A transition\n // all the way to \"after\" is not permitted; this would require\n // a change of pc.\n // We assume that \"left\" preserves the validity of its subtree,\n // which means in particular that it goes to \"blocked\" only if\n // all its descendants are already blocked.\n left.sense := *;\n assume left.blocked() ==> forall m :: m in left.desc ==> m.blocked();\n }\n }\n if(right != null) {\n while(!right.sense)\n modifies right\n invariant validDown() // this seems necessary to get the necessary unfolding of functions\n invariant valid()\n decreases * // to by-pass termination checking for this loop\n {\n // analogous to the previous loop\n right.sense := *;\n assume right.blocked() ==> forall m :: m in right.desc ==> m.blocked();\n }\n }\n\n//B\n pc := 2;\n if(parent != null) {\n sense := true;\n }\n//C\n pc := 3;\n while(sense)\n modifies this\n invariant validUp() // this seems necessary to get the necessary unfolding of functions\n invariant valid()\n invariant left == old(left)\n invariant right == old(right)\n invariant sense ==> parent != null\n decreases * // to by-pass termination checking for this loop\n {\n // this loop body is supposed to model what the \"parent\" thread\n // might do to its node. The body models a transition from\n // \"blocked\" to \"after\" by setting sense to false.\n // We assume that \"parent\" initiates this transition only\n // after it went to state \"after\" itself.\n sense := *;\n assume !sense ==> parent.after();\n }\n//D\n pc := 4;\n if(left != null) {\n left.sense := false;\n }\n//E\n pc := 5;\n if(right != null) {\n right.sense := false;\n }\n//F\n pc := 6;\n }\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nclass Node {\n var left: Node?\n var right: Node?\n var parent: Node?\n var anc: set\n var desc: set\n var sense: bool\n var pc: int\n\n\n predicate validDown()\n reads this, desc\n {\n this !in desc &&\n left != right && // not needed, but speeds up verification\n\n (right != null ==> right in desc && left !in right.desc) &&\n\n (left != null ==>\n left in desc &&\n (right != null ==> desc == {left,right} + left.desc + right.desc) &&\n (right == null ==> desc == {left} + left.desc) &&\n left.validDown()) &&\n (left == null ==>\n (right != null ==> desc == {right} + right.desc) &&\n (right == null ==> desc == {})) &&\n\n (right != null ==> right.validDown()) &&\n\n (blocked() ==> forall m :: m in desc ==> m.blocked()) &&\n (after() ==> forall m :: m in desc ==> m.blocked() || m.after())\n// (left != null && right != null ==> left.desc !! right.desc) // not needed\n }\n\n\n\n\n predicate validUp()\n reads this, anc\n {\n this !in anc &&\n (parent != null ==> parent in anc && anc == { parent } + parent.anc && parent.validUp()) &&\n (parent == null ==> anc == {}) &&\n (after() ==> forall m :: m in anc ==> m.after())\n }\n\n predicate valid()\n reads this, desc, anc\n { validUp() && validDown() && desc !! anc }\n\n predicate before()\n reads this\n { !sense && pc <= 2 }\n\n predicate blocked()\n reads this\n { sense }\n\n predicate after()\n reads this\n { !sense && 3 <= pc }\n\n\n method barrier()\n requires valid()\n requires before()\n modifies this, left, right\n {\n//A\n pc := 1;\n if(left != null) {\n while(!left.sense)\n modifies left\n {\n // this loop body is supposed to model what the \"left\" thread\n // might do to its node. This body models a transition from\n // \"before\" to \"blocked\" by setting sense to true. A transition\n // all the way to \"after\" is not permitted; this would require\n // a change of pc.\n // We assume that \"left\" preserves the validity of its subtree,\n // which means in particular that it goes to \"blocked\" only if\n // all its descendants are already blocked.\n left.sense := *;\n assume left.blocked() ==> forall m :: m in left.desc ==> m.blocked();\n }\n }\n if(right != null) {\n while(!right.sense)\n modifies right\n {\n // analogous to the previous loop\n right.sense := *;\n assume right.blocked() ==> forall m :: m in right.desc ==> m.blocked();\n }\n }\n\n//B\n pc := 2;\n if(parent != null) {\n sense := true;\n }\n//C\n pc := 3;\n while(sense)\n modifies this\n {\n // this loop body is supposed to model what the \"parent\" thread\n // might do to its node. The body models a transition from\n // \"blocked\" to \"after\" by setting sense to false.\n // We assume that \"parent\" initiates this transition only\n // after it went to state \"after\" itself.\n sense := *;\n assume !sense ==> parent.after();\n }\n//D\n pc := 4;\n if(left != null) {\n left.sense := false;\n }\n//E\n pc := 5;\n if(right != null) {\n right.sense := false;\n }\n//F\n pc := 6;\n }\n}\n\n" }, { "test_ID": "456", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny2_TuringFactorial.dfy", "ground_truth": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nfunction Factorial(n: nat): nat\n{\n if n == 0 then 1 else n * Factorial(n-1)\n}\n\nmethod ComputeFactorial(n: int) returns (u: int)\n requires 1 <= n;\n ensures u == Factorial(n);\n{\n var r := 1;\n u := 1;\n while (r < n)\n invariant r <= n;\n invariant u == Factorial(r);\n {\n var v, s := u, 1;\n while (s < r + 1)\n invariant s <= r + 1;\n invariant v == Factorial(r) && u == s * Factorial(r);\n {\n u := u + v;\n s := s + 1;\n }\n r := r + 1;\n }\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nfunction Factorial(n: nat): nat\n{\n if n == 0 then 1 else n * Factorial(n-1)\n}\n\nmethod ComputeFactorial(n: int) returns (u: int)\n requires 1 <= n;\n ensures u == Factorial(n);\n{\n var r := 1;\n u := 1;\n while (r < n)\n {\n var v, s := u, 1;\n while (s < r + 1)\n {\n u := u + v;\n s := s + 1;\n }\n r := r + 1;\n }\n}\n\n" }, { "test_ID": "457", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny3_InductionVsCoinduction.dfy", "ground_truth": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// A definition of a co-inductive datatype Stream, whose values are possibly\n// infinite lists.\ncodatatype Stream = SNil | SCons(head: T, tail: Stream)\n\n/*\n A function that returns a stream consisting of all integers upwards of n.\n The self-call sits in a productive position and is therefore not subject to\n termination checks. The Dafny compiler turns this co-recursive call into a\n lazily evaluated call, evaluated at the time during the program execution\n when the SCons is destructed (if ever).\n*/\n\nfunction Up(n: int): Stream\n{\n SCons(n, Up(n+1))\n}\n\n/*\n A function that returns a stream consisting of all multiples\n of 5 upwards of n. Note that the first self-call sits in a\n productive position and is thus co-recursive. The second self-call\n is not in a productive position and therefore it is subject to\n termination checking; in particular, each recursive call must\n decrease the specific variant function.\n */\n\nfunction FivesUp(n: int): Stream\n decreases 4 - (n-1) % 5;\n{\n if n % 5 == 0 then SCons(n, FivesUp(n+1))\n else FivesUp(n+1)\n}\n\n// A co-predicate that holds for those integer streams where every value is greater than 0.\ncopredicate Pos(s: Stream)\n{\n match s\n case SNil => true\n case SCons(x, rest) => x > 0 && Pos(rest)\n}\n\n// SAppend looks almost exactly like Append, but cannot have 'decreases'\n// clause, as it is possible it will never terminate.\nfunction SAppend(xs: Stream, ys: Stream): Stream\n{\n match xs\n case SNil => ys\n case SCons(x, rest) => SCons(x, SAppend(rest, ys))\n}\n\n/*\n Example: associativity of append on streams.\n\n The first method proves that append is associative when we consider first\n \\S{k} elements of the resulting streams. Equality is treated as any other\n recursive co-predicate, and has it k-th unfolding denoted as ==#[k].\n\n The second method invokes the first one for all ks, which lets us prove the\n assertion (included for clarity only). The assertion implies the\n postcondition (by (F_=)). Interestingly, in the SNil case in the first\n method, we actually prove ==, but by (F_=) applied in the opposite direction\n we also get ==#[k].\n*/\n\nlemma {:induction false} SAppendIsAssociativeK(k:nat, a:Stream, b:Stream, c:Stream)\n ensures SAppend(SAppend(a, b), c) ==#[k] SAppend(a, SAppend(b, c));\n decreases k;\n{\n match (a) {\n case SNil =>\n case SCons(h, t) => if (k > 0) { SAppendIsAssociativeK(k - 1, t, b, c); }\n }\n}\n\nlemma SAppendIsAssociative(a:Stream, b:Stream, c:Stream)\n ensures SAppend(SAppend(a, b), c) == SAppend(a, SAppend(b, c));\n{\n forall k:nat { SAppendIsAssociativeK(k, a, b, c); }\n // assert for clarity only, postcondition follows directly from it\n 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?\n}\n\n// Equivalent proof using the colemma syntax.\ncolemma {:induction false} SAppendIsAssociativeC(a:Stream, b:Stream, c:Stream)\n ensures SAppend(SAppend(a, b), c) == SAppend(a, SAppend(b, c));\n{\n match (a) {\n case SNil =>\n case SCons(h, t) => SAppendIsAssociativeC(t, b, c);\n }\n}\n\n// In fact the proof can be fully automatic.\ncolemma SAppendIsAssociative_Auto(a:Stream, b:Stream, c:Stream)\n ensures SAppend(SAppend(a, b), c) == SAppend(a, SAppend(b, c));\n{\n}\n\ncolemma {:induction false} UpPos(n:int)\n requires n > 0;\n ensures Pos(Up(n));\n{\n UpPos(n+1);\n}\n\ncolemma UpPos_Auto(n:int)\n requires n > 0;\n ensures Pos(Up(n));\n{\n}\n\n// This does induction and coinduction in the same proof.\ncolemma {:induction false} FivesUpPos(n:int)\n requires n > 0;\n ensures Pos(FivesUp(n));\n decreases 4 - (n-1) % 5;\n{\n if (n % 5 == 0) {\n FivesUpPos#[_k - 1](n + 1);\n } else {\n FivesUpPos#[_k](n + 1);\n }\n}\n\n// Again, Dafny can just employ induction tactic and do it automatically.\n// The only hint required is the decrease clause.\ncolemma FivesUpPos_Auto(n:int)\n requires n > 0;\n ensures Pos(FivesUp(n));\n decreases 4 - (n-1) % 5;\n{\n}\n\n\n", "hints_removed": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// A definition of a co-inductive datatype Stream, whose values are possibly\n// infinite lists.\ncodatatype Stream = SNil | SCons(head: T, tail: Stream)\n\n/*\n A function that returns a stream consisting of all integers upwards of n.\n The self-call sits in a productive position and is therefore not subject to\n termination checks. The Dafny compiler turns this co-recursive call into a\n lazily evaluated call, evaluated at the time during the program execution\n when the SCons is destructed (if ever).\n*/\n\nfunction Up(n: int): Stream\n{\n SCons(n, Up(n+1))\n}\n\n/*\n A function that returns a stream consisting of all multiples\n of 5 upwards of n. Note that the first self-call sits in a\n productive position and is thus co-recursive. The second self-call\n is not in a productive position and therefore it is subject to\n termination checking; in particular, each recursive call must\n decrease the specific variant function.\n */\n\nfunction FivesUp(n: int): Stream\n{\n if n % 5 == 0 then SCons(n, FivesUp(n+1))\n else FivesUp(n+1)\n}\n\n// A co-predicate that holds for those integer streams where every value is greater than 0.\ncopredicate Pos(s: Stream)\n{\n match s\n case SNil => true\n case SCons(x, rest) => x > 0 && Pos(rest)\n}\n\n// SAppend looks almost exactly like Append, but cannot have 'decreases'\n// clause, as it is possible it will never terminate.\nfunction SAppend(xs: Stream, ys: Stream): Stream\n{\n match xs\n case SNil => ys\n case SCons(x, rest) => SCons(x, SAppend(rest, ys))\n}\n\n/*\n Example: associativity of append on streams.\n\n The first method proves that append is associative when we consider first\n \\S{k} elements of the resulting streams. Equality is treated as any other\n recursive co-predicate, and has it k-th unfolding denoted as ==#[k].\n\n The second method invokes the first one for all ks, which lets us prove the\n postcondition (by (F_=)). Interestingly, in the SNil case in the first\n method, we actually prove ==, but by (F_=) applied in the opposite direction\n we also get ==#[k].\n*/\n\nlemma {:induction false} SAppendIsAssociativeK(k:nat, a:Stream, b:Stream, c:Stream)\n ensures SAppend(SAppend(a, b), c) ==#[k] SAppend(a, SAppend(b, c));\n{\n match (a) {\n case SNil =>\n case SCons(h, t) => if (k > 0) { SAppendIsAssociativeK(k - 1, t, b, c); }\n }\n}\n\nlemma SAppendIsAssociative(a:Stream, b:Stream, c:Stream)\n ensures SAppend(SAppend(a, b), c) == SAppend(a, SAppend(b, c));\n{\n forall k:nat { SAppendIsAssociativeK(k, a, b, c); }\n // assert for clarity only, postcondition follows directly from it\n}\n\n// Equivalent proof using the colemma syntax.\ncolemma {:induction false} SAppendIsAssociativeC(a:Stream, b:Stream, c:Stream)\n ensures SAppend(SAppend(a, b), c) == SAppend(a, SAppend(b, c));\n{\n match (a) {\n case SNil =>\n case SCons(h, t) => SAppendIsAssociativeC(t, b, c);\n }\n}\n\n// In fact the proof can be fully automatic.\ncolemma SAppendIsAssociative_Auto(a:Stream, b:Stream, c:Stream)\n ensures SAppend(SAppend(a, b), c) == SAppend(a, SAppend(b, c));\n{\n}\n\ncolemma {:induction false} UpPos(n:int)\n requires n > 0;\n ensures Pos(Up(n));\n{\n UpPos(n+1);\n}\n\ncolemma UpPos_Auto(n:int)\n requires n > 0;\n ensures Pos(Up(n));\n{\n}\n\n// This does induction and coinduction in the same proof.\ncolemma {:induction false} FivesUpPos(n:int)\n requires n > 0;\n ensures Pos(FivesUp(n));\n{\n if (n % 5 == 0) {\n FivesUpPos#[_k - 1](n + 1);\n } else {\n FivesUpPos#[_k](n + 1);\n }\n}\n\n// Again, Dafny can just employ induction tactic and do it automatically.\n// The only hint required is the decrease clause.\ncolemma FivesUpPos_Auto(n:int)\n requires n > 0;\n ensures Pos(FivesUp(n));\n{\n}\n\n\n" }, { "test_ID": "458", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_Bug144.dfy", "ground_truth": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\npredicate p(i:int)\n\nmethod m1()\n\nmethod m2()\n{\n assume exists i :: p(i);\n assert exists i :: p(i);\n m1();\n assert exists i :: p(i); // FAILS\n}\n\nclass Test\n{\n var arr : array;\n predicate p(i: int)\n method foo()\n requires arr.Length > 0\n modifies arr\n {\n assume exists i :: p(i);\n arr[0] := 1;\n assert exists i :: p(i); // FAILS\n }\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\npredicate p(i:int)\n\nmethod m1()\n\nmethod m2()\n{\n assume exists i :: p(i);\n m1();\n}\n\nclass Test\n{\n var arr : array;\n predicate p(i: int)\n method foo()\n requires arr.Length > 0\n modifies arr\n {\n assume exists i :: p(i);\n arr[0] := 1;\n }\n}\n\n" }, { "test_ID": "459", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_Bug165.dfy", "ground_truth": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\ntype T\nfunction f(a: T) : bool\n\nmethod Select(s1: seq) returns (r: seq)\n ensures (forall e: T :: f(e) ==> multiset(s1)[e] == multiset(r)[e])\n ensures (forall e: T :: (!f(e)) ==> 0 == multiset(r)[e])\n\nmethod Main(s1: seq)\n{\n var r1, r2: seq;\n\n r1 := Select(s1);\n r2 := Select(s1);\n\n assert multiset(r1) == multiset(r2);\n\n}\n", "hints_removed": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\ntype T\nfunction f(a: T) : bool\n\nmethod Select(s1: seq) returns (r: seq)\n ensures (forall e: T :: f(e) ==> multiset(s1)[e] == multiset(r)[e])\n ensures (forall e: T :: (!f(e)) ==> 0 == multiset(r)[e])\n\nmethod Main(s1: seq)\n{\n var r1, r2: seq;\n\n r1 := Select(s1);\n r2 := Select(s1);\n\n\n}\n" }, { "test_ID": "460", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_Bug58.dfy", "ground_truth": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nfunction M1(f:map, i:int):bool\n\nfunction M2(f:map, i:int):bool\n{\n M1(map j | j in f :: f[j], i)\n}\n\nlemma L(f:map, i:int)\n requires i in f;\n requires M2(f, i);\n requires forall j:int, f:map :: M1(f, j) == (j in f && f[j]);\n{\n assert f[i];\n}\n", "hints_removed": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nfunction M1(f:map, i:int):bool\n\nfunction M2(f:map, i:int):bool\n{\n M1(map j | j in f :: f[j], i)\n}\n\nlemma L(f:map, i:int)\n requires i in f;\n requires M2(f, i);\n requires forall j:int, f:map :: M1(f, j) == (j in f && f[j]);\n{\n}\n" }, { "test_ID": "461", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_Bug92.dfy", "ground_truth": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\nmodule ModOpaque {\n function {:opaque} Hidden(x:int) : (int, int)\n {\n (5, 7)\n }\n\n function Visible(x:int) : (int, int)\n {\n Hidden(x)\n }\n\n lemma foo(x:int, y:int, z:int)\n requires (y, z) == Visible(x);\n {\n assert (y, z) == Hidden(x);\n }\n\n lemma bar(x:int, y:int, z:int)\n requires y == Visible(x).0;\n requires z == Visible(x).1;\n {\n assert (y, z) == Visible(x);\n }\n\n lemma baz(x:int, y:int, z:int)\n requires y == Visible(x).0;\n requires z == Visible(x).1;\n {\n assert (y, z) == Hidden(x);\n }\n}\n\nmodule ModVisible {\n function Hidden(x:int) : (int, int)\n {\n (5, 7)\n }\n\n function Visible(x:int) : (int, int)\n {\n Hidden(x)\n }\n\n lemma foo(x:int, y:int, z:int)\n requires (y, z) == Visible(x);\n {\n assert (y, z) == Hidden(x);\n }\n\n lemma bar(x:int, y:int, z:int)\n requires y == Visible(x).0;\n requires z == Visible(x).1;\n {\n assert (y, z) == Visible(x);\n }\n\n lemma baz(x:int, y:int, z:int)\n requires y == Visible(x).0;\n requires z == Visible(x).1;\n {\n assert (y, z) == Hidden(x);\n }\n}\n\nmodule ModFuel {\n function {:fuel 0,0} Hidden(x:int) : (int, int)\n {\n (5, 7)\n }\n\n function Visible(x:int) : (int, int)\n {\n Hidden(x)\n }\n\n lemma foo(x:int, y:int, z:int)\n requires (y, z) == Visible(x);\n {\n assert (y, z) == Hidden(x);\n }\n\n lemma bar(x:int, y:int, z:int)\n requires y == Visible(x).0;\n requires z == Visible(x).1;\n {\n assert (y, z) == Visible(x);\n }\n\n lemma baz(x:int, y:int, z:int)\n requires y == Visible(x).0;\n requires z == Visible(x).1;\n {\n assert (y, z) == Hidden(x);\n }\n}\n", "hints_removed": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\nmodule ModOpaque {\n function {:opaque} Hidden(x:int) : (int, int)\n {\n (5, 7)\n }\n\n function Visible(x:int) : (int, int)\n {\n Hidden(x)\n }\n\n lemma foo(x:int, y:int, z:int)\n requires (y, z) == Visible(x);\n {\n }\n\n lemma bar(x:int, y:int, z:int)\n requires y == Visible(x).0;\n requires z == Visible(x).1;\n {\n }\n\n lemma baz(x:int, y:int, z:int)\n requires y == Visible(x).0;\n requires z == Visible(x).1;\n {\n }\n}\n\nmodule ModVisible {\n function Hidden(x:int) : (int, int)\n {\n (5, 7)\n }\n\n function Visible(x:int) : (int, int)\n {\n Hidden(x)\n }\n\n lemma foo(x:int, y:int, z:int)\n requires (y, z) == Visible(x);\n {\n }\n\n lemma bar(x:int, y:int, z:int)\n requires y == Visible(x).0;\n requires z == Visible(x).1;\n {\n }\n\n lemma baz(x:int, y:int, z:int)\n requires y == Visible(x).0;\n requires z == Visible(x).1;\n {\n }\n}\n\nmodule ModFuel {\n function {:fuel 0,0} Hidden(x:int) : (int, int)\n {\n (5, 7)\n }\n\n function Visible(x:int) : (int, int)\n {\n Hidden(x)\n }\n\n lemma foo(x:int, y:int, z:int)\n requires (y, z) == Visible(x);\n {\n }\n\n lemma bar(x:int, y:int, z:int)\n requires y == Visible(x).0;\n requires z == Visible(x).1;\n {\n }\n\n lemma baz(x:int, y:int, z:int)\n requires y == Visible(x).0;\n requires z == Visible(x).1;\n {\n }\n}\n" }, { "test_ID": "462", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_Fstar-QuickSort.dfy", "ground_truth": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// A Dafny rendition of an F* version of QuickSort (included at the bottom of this file).\n// Unlike the F* version, Dafny also proves termination and does not use any axioms. However,\n// Dafny needs help with a couple of lemmas in places where F* does not need them.\n// Comments below show differences between the F* and Dafny versions.\n\ndatatype List = Nil | Cons(T, List)\n\nfunction length(list: List): nat // for termination proof\n{\n match list\n case Nil => 0\n case Cons(_, tl) => 1 + length(tl)\n}\n\n// In(x, list) returns the number of occurrences of x in list\nfunction In(x: int, list: List): nat\n{\n match list\n case Nil => 0\n case Cons(y, tl) => (if x == y then 1 else 0) + In(x, tl)\n}\n\npredicate SortedRange(m: int, n: int, list: List)\n decreases list // for termination proof\n{\n match list\n case Nil => m <= n\n case Cons(hd, tl) => m <= hd <= n && SortedRange(hd, n, tl)\n}\n\nfunction append(n0: int, n1: int, n2: int, n3: int, i: List, j: List): List\n requires n0 <= n1 <= n2 <= n3\n requires SortedRange(n0, n1, i) && SortedRange(n2, n3, j)\n ensures SortedRange(n0, n3, append(n0, n1, n2, n3, i, j))\n ensures forall x :: In(x, append(n0, n1, n2, n3, i, j)) == In(x, i) + In(x, j)\n decreases i // for termination proof\n{\n match i\n case Nil => j\n case Cons(hd, tl) => Cons(hd, append(hd, n1, n2, n3, tl, j))\n}\n\nfunction partition(x: int, l: List): (List, List)\n ensures var (lo, hi) := partition(x, l);\n (forall y :: In(y, lo) == if y <= x then In(y, l) else 0) &&\n (forall y :: In(y, hi) == if x < y then In(y, l) else 0) &&\n length(l) == length(lo) + length(hi) // for termination proof\n{\n match l\n case Nil => (Nil, Nil)\n case Cons(hd, tl) =>\n var (lo, hi) := partition(x, tl);\n if hd <= x then\n (Cons(hd, lo), hi)\n else\n (lo, Cons(hd, hi))\n}\n\nfunction sort(min: int, max: int, i: List): List\n requires min <= max\n requires forall x :: In(x, i) != 0 ==> min <= x <= max\n ensures SortedRange(min, max, sort(min, max, i))\n ensures forall x :: In(x, i) == In(x, sort(min, max, i))\n decreases length(i) // for termination proof\n{\n match i\n case Nil => Nil\n case Cons(hd, tl) =>\n assert In(hd, i) != 0; // this proof line not needed in F*\n var (lo, hi) := partition(hd, tl);\n assert forall y :: In(y, lo) <= In(y, i); // this proof line not needed in F*\n var i' := sort(min, hd, lo);\n var j' := sort(hd, max, hi);\n append(min, hd, hd, max, i', Cons(hd, j'))\n}\n\n/*\nmodule Sort\n\ntype SortedRange : int => int => list int => E\nassume Nil_Sorted : forall (n:int) (m:int). n <= m <==> SortedRange n m []\nassume Cons_Sorted: forall (n:int) (m:int) (hd:int) (tl:list int).\n SortedRange hd m tl && (n <= hd) && (hd <= m)\n <==> SortedRange n m (hd::tl)\n\nval append: n1:int -> n2:int{n1 <= n2} -> n3:int{n2 <= n3} -> n4:int{n3 <= n4}\n -> i:list int{SortedRange n1 n2 i}\n -> j:list int{SortedRange n3 n4 j}\n -> k:list int{SortedRange n1 n4 k\n /\\ (forall x. In x k <==> In x i \\/ In x j)}\nlet rec append n1 n2 n3 n4 i j = match i with\n | [] ->\n (match j with\n | [] -> j\n | _::_ -> j)\n | hd::tl -> hd::(append hd n2 n3 n4 tl j)\n\nval partition: x:int\n -> l:list int\n -> (lo:list int\n * hi:list int{(forall y. In y lo ==> y <= x /\\ In y l)\n /\\ (forall y. In y hi ==> x < y /\\ In y l)\n /\\ (forall y. In y l ==> In y lo \\/ In y hi)})\nlet rec partition x l = match l with\n | [] -> ([], [])\n | hd::tl ->\n let lo, hi = partition x tl in\n if hd <= x\n then (hd::lo, hi)\n else (lo, hd::hi)\n\nval sort: min:int\n -> max:int{min <= max}\n -> i:list int {forall x. In x i ==> (min <= x /\\ x <= max)}\n -> j:list int{SortedRange min max j /\\ (forall x. In x i <==> In x j)}\nlet rec sort min max i = match i with\n | [] -> []\n | hd::tl ->\n let lo,hi = partition hd tl in\n let i' = sort min hd lo in\n let j' = sort hd max hi in\n append min hd hd max i' (hd::j')\n\n*/\n\n", "hints_removed": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// A Dafny rendition of an F* version of QuickSort (included at the bottom of this file).\n// Unlike the F* version, Dafny also proves termination and does not use any axioms. However,\n// Dafny needs help with a couple of lemmas in places where F* does not need them.\n// Comments below show differences between the F* and Dafny versions.\n\ndatatype List = Nil | Cons(T, List)\n\nfunction length(list: List): nat // for termination proof\n{\n match list\n case Nil => 0\n case Cons(_, tl) => 1 + length(tl)\n}\n\n// In(x, list) returns the number of occurrences of x in list\nfunction In(x: int, list: List): nat\n{\n match list\n case Nil => 0\n case Cons(y, tl) => (if x == y then 1 else 0) + In(x, tl)\n}\n\npredicate SortedRange(m: int, n: int, list: List)\n{\n match list\n case Nil => m <= n\n case Cons(hd, tl) => m <= hd <= n && SortedRange(hd, n, tl)\n}\n\nfunction append(n0: int, n1: int, n2: int, n3: int, i: List, j: List): List\n requires n0 <= n1 <= n2 <= n3\n requires SortedRange(n0, n1, i) && SortedRange(n2, n3, j)\n ensures SortedRange(n0, n3, append(n0, n1, n2, n3, i, j))\n ensures forall x :: In(x, append(n0, n1, n2, n3, i, j)) == In(x, i) + In(x, j)\n{\n match i\n case Nil => j\n case Cons(hd, tl) => Cons(hd, append(hd, n1, n2, n3, tl, j))\n}\n\nfunction partition(x: int, l: List): (List, List)\n ensures var (lo, hi) := partition(x, l);\n (forall y :: In(y, lo) == if y <= x then In(y, l) else 0) &&\n (forall y :: In(y, hi) == if x < y then In(y, l) else 0) &&\n length(l) == length(lo) + length(hi) // for termination proof\n{\n match l\n case Nil => (Nil, Nil)\n case Cons(hd, tl) =>\n var (lo, hi) := partition(x, tl);\n if hd <= x then\n (Cons(hd, lo), hi)\n else\n (lo, Cons(hd, hi))\n}\n\nfunction sort(min: int, max: int, i: List): List\n requires min <= max\n requires forall x :: In(x, i) != 0 ==> min <= x <= max\n ensures SortedRange(min, max, sort(min, max, i))\n ensures forall x :: In(x, i) == In(x, sort(min, max, i))\n{\n match i\n case Nil => Nil\n case Cons(hd, tl) =>\n var (lo, hi) := partition(hd, tl);\n var i' := sort(min, hd, lo);\n var j' := sort(hd, max, hi);\n append(min, hd, hd, max, i', Cons(hd, j'))\n}\n\n/*\nmodule Sort\n\ntype SortedRange : int => int => list int => E\nassume Nil_Sorted : forall (n:int) (m:int). n <= m <==> SortedRange n m []\nassume Cons_Sorted: forall (n:int) (m:int) (hd:int) (tl:list int).\n SortedRange hd m tl && (n <= hd) && (hd <= m)\n <==> SortedRange n m (hd::tl)\n\nval append: n1:int -> n2:int{n1 <= n2} -> n3:int{n2 <= n3} -> n4:int{n3 <= n4}\n -> i:list int{SortedRange n1 n2 i}\n -> j:list int{SortedRange n3 n4 j}\n -> k:list int{SortedRange n1 n4 k\n /\\ (forall x. In x k <==> In x i \\/ In x j)}\nlet rec append n1 n2 n3 n4 i j = match i with\n | [] ->\n (match j with\n | [] -> j\n | _::_ -> j)\n | hd::tl -> hd::(append hd n2 n3 n4 tl j)\n\nval partition: x:int\n -> l:list int\n -> (lo:list int\n * hi:list int{(forall y. In y lo ==> y <= x /\\ In y l)\n /\\ (forall y. In y hi ==> x < y /\\ In y l)\n /\\ (forall y. In y l ==> In y lo \\/ In y hi)})\nlet rec partition x l = match l with\n | [] -> ([], [])\n | hd::tl ->\n let lo, hi = partition x tl in\n if hd <= x\n then (hd::lo, hi)\n else (lo, hd::hi)\n\nval sort: min:int\n -> max:int{min <= max}\n -> i:list int {forall x. In x i ==> (min <= x /\\ x <= max)}\n -> j:list int{SortedRange min max j /\\ (forall x. In x i <==> In x j)}\nlet rec sort min max i = match i with\n | [] -> []\n | hd::tl ->\n let lo,hi = partition hd tl in\n let i' = sort min hd lo in\n let j' = sort hd max hi in\n append min hd hd max i' (hd::j')\n\n*/\n\n" }, { "test_ID": "463", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_Lucas-down.dfy", "ground_truth": "// RUN: %dafny /compile:0 /arith:1 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// Proof of the Lucas theorem\n// Rustan Leino\n// 9 March 2018\n//\n// Instead of the lemmas doing \"up\", like:\n// P(k) == P(2*k)\n// P(k) == P(2*k + 1)\n// (see Lucas-up.dfy), the lemmas in this version go \"down\", like:\n// P(k%2) == P(k)\n\n// This file defines the ingredients of the Lucas theorem, proves some\n// properties of these, and then states and proves the Lucas theorem\n// itself.\n\n// The following predicate gives the boolean value of bit \"k\" in\n// the natural number \"n\".\npredicate Bit(k: nat, n: nat)\n{\n if k == 0 then n % 2 == 1\n else Bit(k-1, n / 2)\n}\n\n// Function \"BitSet\" returns the set of bits in the binary representation\n// of a number.\nfunction BitSet(n: nat): set\n{\n set i | 0 <= i < n && Bit(i, n)\n}\n\n// The following lemma shows that the \"i < n\" conjunct in\n// the set comprehension in \"BitSet\" does not restrict\n// the set any more than the conjunct \"Bit(i, n)\" does.\nlemma BitSize(i: nat, n: nat)\n requires Bit(i, n)\n ensures i < n\n{\n}\n\n// An easy-to-read name for the expression that checks if a number\n// is even.\npredicate EVEN(n: nat)\n{\n n % 2 == 0\n}\n\n// The binomial function is defined like in the Pascal triangle.\n// \"binom(a, b)\" is also knows as \"a choose b\".\nfunction binom(a: nat, b: nat): nat\n{\n if b == 0 then 1\n else if a == 0 then 0\n else binom(a-1, b) + binom(a-1, b-1)\n}\n\n// This lemma shows that the parity of \"binom\" is preserved if\n// div-2 is applied to both arguments--except in the case where\n// the first argument to \"binom\" is even and the second argument\n// is odd, in which case \"binom\" is always even.\nlemma Lucas_Binary''(a: nat, b: nat)\n ensures binom(a, b) % 2 == if EVEN(a) && !EVEN(b) then 0 else binom(a / 2, b / 2) % 2\n{\n if a == 0 || b == 0 {\n } else {\n Lucas_Binary''(a - 1, b);\n Lucas_Binary''(a - 1, b - 1);\n }\n}\n\n// \"Suc(S)\" returns the set constructed by incrementing\n// each number in \"S\" by 1. Stated differently, it is the\n// increment-by-1 (successor) function applied pointwise to the\n// set.\nfunction Suc(S: set): set\n{\n set x | x in S :: x + 1\n}\n\n// The following lemma clearly shows the correspondence between\n// \"S\" and \"Suc(S)\".\nlemma SucElements(S: set)\n ensures forall x :: x in S <==> (x+1) in Suc(S)\n{\n}\n\n// Here is a lemma that relates BitSet and Suc.\nlemma BitSet_Property(n: nat)\n ensures BitSet(n) - {0} == Suc(BitSet(n / 2))\n{\n if n == 0 {\n } else {\n forall x: nat {\n calc {\n x in BitSet(n) - {0};\n ==\n x != 0 && x in BitSet(n);\n == // def. BitSet\n 0 < x < n && Bit(x, n);\n == // def. Bit\n 0 < x < n && Bit(x-1, n / 2);\n == { if 0 < x && Bit(x-1, n / 2) { BitSize(x-1, n / 2); } }\n 0 <= x-1 < n / 2 && Bit(x-1, n / 2);\n == // def. BitSet\n (x-1) in BitSet(n / 2);\n == { SucElements(BitSet(n / 2)); }\n x in Suc(BitSet(n / 2));\n }\n }\n }\n}\n\nlemma Lucas_Theorem'(m: nat, n: nat)\n ensures BitSet(m) <= BitSet(n) <==> !EVEN(binom(n, m))\n{\n if m == 0 && n == 0 {\n } else if EVEN(n) && !EVEN(m) {\n calc {\n !EVEN(binom(n, m));\n == { Lucas_Binary''(n, m); }\n false;\n == { assert 0 in BitSet(m) && 0 !in BitSet(n); }\n BitSet(m) <= BitSet(n);\n }\n } else {\n var m', n' := m/2, n/2;\n calc {\n !EVEN(binom(n, m));\n == { Lucas_Binary''(n, m); }\n !EVEN(binom(n', m'));\n == { Lucas_Theorem'(m', n'); }\n BitSet(m') <= BitSet(n');\n == { SucElements(BitSet(m')); SucElements(BitSet(n')); }\n Suc(BitSet(m')) <= Suc(BitSet(n'));\n == { BitSet_Property(m); BitSet_Property(n); }\n BitSet(m) - {0} <= BitSet(n) - {0};\n == { assert 0 !in BitSet(m) ==> BitSet(m) == BitSet(m) - {0};\n assert 0 in BitSet(n) ==> BitSet(n) - {0} <= BitSet(n); }\n BitSet(m) <= BitSet(n);\n }\n }\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 /arith:1 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// Proof of the Lucas theorem\n// Rustan Leino\n// 9 March 2018\n//\n// Instead of the lemmas doing \"up\", like:\n// P(k) == P(2*k)\n// P(k) == P(2*k + 1)\n// (see Lucas-up.dfy), the lemmas in this version go \"down\", like:\n// P(k%2) == P(k)\n\n// This file defines the ingredients of the Lucas theorem, proves some\n// properties of these, and then states and proves the Lucas theorem\n// itself.\n\n// The following predicate gives the boolean value of bit \"k\" in\n// the natural number \"n\".\npredicate Bit(k: nat, n: nat)\n{\n if k == 0 then n % 2 == 1\n else Bit(k-1, n / 2)\n}\n\n// Function \"BitSet\" returns the set of bits in the binary representation\n// of a number.\nfunction BitSet(n: nat): set\n{\n set i | 0 <= i < n && Bit(i, n)\n}\n\n// The following lemma shows that the \"i < n\" conjunct in\n// the set comprehension in \"BitSet\" does not restrict\n// the set any more than the conjunct \"Bit(i, n)\" does.\nlemma BitSize(i: nat, n: nat)\n requires Bit(i, n)\n ensures i < n\n{\n}\n\n// An easy-to-read name for the expression that checks if a number\n// is even.\npredicate EVEN(n: nat)\n{\n n % 2 == 0\n}\n\n// The binomial function is defined like in the Pascal triangle.\n// \"binom(a, b)\" is also knows as \"a choose b\".\nfunction binom(a: nat, b: nat): nat\n{\n if b == 0 then 1\n else if a == 0 then 0\n else binom(a-1, b) + binom(a-1, b-1)\n}\n\n// This lemma shows that the parity of \"binom\" is preserved if\n// div-2 is applied to both arguments--except in the case where\n// the first argument to \"binom\" is even and the second argument\n// is odd, in which case \"binom\" is always even.\nlemma Lucas_Binary''(a: nat, b: nat)\n ensures binom(a, b) % 2 == if EVEN(a) && !EVEN(b) then 0 else binom(a / 2, b / 2) % 2\n{\n if a == 0 || b == 0 {\n } else {\n Lucas_Binary''(a - 1, b);\n Lucas_Binary''(a - 1, b - 1);\n }\n}\n\n// \"Suc(S)\" returns the set constructed by incrementing\n// each number in \"S\" by 1. Stated differently, it is the\n// increment-by-1 (successor) function applied pointwise to the\n// set.\nfunction Suc(S: set): set\n{\n set x | x in S :: x + 1\n}\n\n// The following lemma clearly shows the correspondence between\n// \"S\" and \"Suc(S)\".\nlemma SucElements(S: set)\n ensures forall x :: x in S <==> (x+1) in Suc(S)\n{\n}\n\n// Here is a lemma that relates BitSet and Suc.\nlemma BitSet_Property(n: nat)\n ensures BitSet(n) - {0} == Suc(BitSet(n / 2))\n{\n if n == 0 {\n } else {\n forall x: nat {\n calc {\n x in BitSet(n) - {0};\n ==\n x != 0 && x in BitSet(n);\n == // def. BitSet\n 0 < x < n && Bit(x, n);\n == // def. Bit\n 0 < x < n && Bit(x-1, n / 2);\n == { if 0 < x && Bit(x-1, n / 2) { BitSize(x-1, n / 2); } }\n 0 <= x-1 < n / 2 && Bit(x-1, n / 2);\n == // def. BitSet\n (x-1) in BitSet(n / 2);\n == { SucElements(BitSet(n / 2)); }\n x in Suc(BitSet(n / 2));\n }\n }\n }\n}\n\nlemma Lucas_Theorem'(m: nat, n: nat)\n ensures BitSet(m) <= BitSet(n) <==> !EVEN(binom(n, m))\n{\n if m == 0 && n == 0 {\n } else if EVEN(n) && !EVEN(m) {\n calc {\n !EVEN(binom(n, m));\n == { Lucas_Binary''(n, m); }\n false;\n == { assert 0 in BitSet(m) && 0 !in BitSet(n); }\n BitSet(m) <= BitSet(n);\n }\n } else {\n var m', n' := m/2, n/2;\n calc {\n !EVEN(binom(n, m));\n == { Lucas_Binary''(n, m); }\n !EVEN(binom(n', m'));\n == { Lucas_Theorem'(m', n'); }\n BitSet(m') <= BitSet(n');\n == { SucElements(BitSet(m')); SucElements(BitSet(n')); }\n Suc(BitSet(m')) <= Suc(BitSet(n'));\n == { BitSet_Property(m); BitSet_Property(n); }\n BitSet(m) - {0} <= BitSet(n) - {0};\n == { assert 0 !in BitSet(m) ==> BitSet(m) == BitSet(m) - {0};\n BitSet(m) <= BitSet(n);\n }\n }\n}\n\n" }, { "test_ID": "464", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_MonadicLaws.dfy", "ground_truth": "// RUN: %dafny /compile:0 /rprint:\"%t.rprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// Monadic Laws\n// Niki Vazou and Rustan Leino\n// 28 March 2016\n\ndatatype List = Nil | Cons(head: T, tail: List)\n\nfunction append(xs: List, ys: List): List\n{\n match xs\n case Nil => ys\n case Cons(x, xs') => Cons(x, append(xs', ys))\n}\n\nlemma AppendNil(xs: List)\n ensures append(xs, Nil) == xs\n{\n}\n\nlemma AppendAssoc(xs: List, ys: List, zs: List)\n ensures append(append(xs, ys), zs) == append(xs, append(ys, zs));\n{\n}\n\nfunction Return(a: T): List\n{\n Cons(a, Nil)\n}\n\nfunction Bind(xs: List, f: T -> List): List\n{\n match xs\n case Nil => Nil\n case Cons(x, xs') => append(f(x), Bind(xs', f))\n}\n\nlemma LeftIdentity(a: T, f: T -> List)\n ensures Bind(Return(a), f) == f(a)\n{\n AppendNil(f(a));\n}\n\nlemma RightIdentity(m: List)\n ensures Bind(m, Return) == m\n{\n match m\n case Nil =>\n assert Bind(Nil, Return) == Nil;\n case Cons(x, m') =>\n calc {\n Bind(Cons(x, m'), Return);\n append(Return(x), Bind(m', Return));\n Cons(x, Bind(m', Return));\n }\n}\n\nlemma Associativity(m: List, f: T -> List, g: T -> List)\n ensures Bind(Bind(m, f), g) == Bind(m, x => Bind(f(x), g))\n{\n match m\n case Nil =>\n assert Bind(m, x => Bind(f(x), g)) == Nil;\n case Cons(x, xs) =>\n match f(x)\n case Nil =>\n calc {\n Bind(xs, y => Bind(f(y), g));\n Bind(Cons(x, xs), y => Bind(f(y), g));\n }\n case Cons(y, ys) =>\n calc {\n append(g(y), Bind(append(ys, Bind(xs, f)), g));\n { BindOverAppend(ys, Bind(xs, f), g); }\n append(g(y), append(Bind(ys, g), Bind(Bind(xs, f), g)));\n { AppendAssoc(g(y), Bind(ys, g), Bind(Bind(xs, f), g)); }\n append(append(g(y), Bind(ys, g)), Bind(Bind(xs, f), g));\n Bind(Cons(x, xs), z => Bind(f(z), g));\n }\n}\n\nlemma BindOverAppend(xs: List, ys: List, g: T -> List)\n ensures Bind(append(xs, ys), g) == append(Bind(xs, g), Bind(ys, g))\n{\n match xs\n case Nil =>\n case Cons(x, xs') =>\n AppendAssoc(g(x), Bind(xs', g), Bind(ys, g));\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 /rprint:\"%t.rprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// Monadic Laws\n// Niki Vazou and Rustan Leino\n// 28 March 2016\n\ndatatype List = Nil | Cons(head: T, tail: List)\n\nfunction append(xs: List, ys: List): List\n{\n match xs\n case Nil => ys\n case Cons(x, xs') => Cons(x, append(xs', ys))\n}\n\nlemma AppendNil(xs: List)\n ensures append(xs, Nil) == xs\n{\n}\n\nlemma AppendAssoc(xs: List, ys: List, zs: List)\n ensures append(append(xs, ys), zs) == append(xs, append(ys, zs));\n{\n}\n\nfunction Return(a: T): List\n{\n Cons(a, Nil)\n}\n\nfunction Bind(xs: List, f: T -> List): List\n{\n match xs\n case Nil => Nil\n case Cons(x, xs') => append(f(x), Bind(xs', f))\n}\n\nlemma LeftIdentity(a: T, f: T -> List)\n ensures Bind(Return(a), f) == f(a)\n{\n AppendNil(f(a));\n}\n\nlemma RightIdentity(m: List)\n ensures Bind(m, Return) == m\n{\n match m\n case Nil =>\n case Cons(x, m') =>\n calc {\n Bind(Cons(x, m'), Return);\n append(Return(x), Bind(m', Return));\n Cons(x, Bind(m', Return));\n }\n}\n\nlemma Associativity(m: List, f: T -> List, g: T -> List)\n ensures Bind(Bind(m, f), g) == Bind(m, x => Bind(f(x), g))\n{\n match m\n case Nil =>\n case Cons(x, xs) =>\n match f(x)\n case Nil =>\n calc {\n Bind(xs, y => Bind(f(y), g));\n Bind(Cons(x, xs), y => Bind(f(y), g));\n }\n case Cons(y, ys) =>\n calc {\n append(g(y), Bind(append(ys, Bind(xs, f)), g));\n { BindOverAppend(ys, Bind(xs, f), g); }\n append(g(y), append(Bind(ys, g), Bind(Bind(xs, f), g)));\n { AppendAssoc(g(y), Bind(ys, g), Bind(Bind(xs, f), g)); }\n append(append(g(y), Bind(ys, g)), Bind(Bind(xs, f), g));\n Bind(Cons(x, xs), z => Bind(f(z), g));\n }\n}\n\nlemma BindOverAppend(xs: List, ys: List, g: T -> List)\n ensures Bind(append(xs, ys), g) == append(Bind(xs, g), Bind(ys, g))\n{\n match xs\n case Nil =>\n case Cons(x, xs') =>\n AppendAssoc(g(x), Bind(xs', g), Bind(ys, g));\n}\n\n" }, { "test_ID": "465", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_Regression19.dfy", "ground_truth": "// RUN: %dafny \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\npredicate ContainsNothingBut5(s: set)\n{\n forall q :: q in s ==> q == 5\n}\n\npredicate YeahContains5(s: set)\n{\n exists q :: q in s && q == 5\n}\n\npredicate ViaSetComprehension(s: set) {\n |set q | q in s && q == 5| != 0\n}\n\npredicate LambdaTest(s: set) {\n (q => q in s)(5)\n}\n\npredicate ViaMapComprehension(s: set) {\n |(map q | q in s && q == 5 :: true).Keys| != 0\n}\n\npredicate Contains5(s: set)\n{\n var q := 5; q in s\n}\n\ndatatype R = MakeR(int) | Other\n\npredicate RIs5(r: R) {\n match r case MakeR(q) => q == 5 case Other => false\n}\n\nlemma NonemptySet(x: int, s: set)\n requires x in s\n ensures |s| != 0\n{\n}\nlemma NonemptyMap(x: int, s: map)\n requires x in s.Keys\n ensures |s| != 0\n{\n}\n\nmethod M(s: set, r: R, q: int)\n requires s == {5} && r == MakeR(5)\n{\n assert ContainsNothingBut5(s); // forall\n assert YeahContains5(s); // exists\n\n NonemptySet(5, set q | q in s && q == 5);\n assert ViaSetComprehension(s); // set comprehension\n\n NonemptyMap(5, map q | q in s && q == 5 :: true);\n assert ViaMapComprehension(s); // map comprehension\n\n assert LambdaTest(s); // lambda expression\n assert Contains5(s); // let expression (once had generated malformed Boogie)\n\n assert RIs5(r); // match expression\n}\n\n", "hints_removed": "// RUN: %dafny \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\npredicate ContainsNothingBut5(s: set)\n{\n forall q :: q in s ==> q == 5\n}\n\npredicate YeahContains5(s: set)\n{\n exists q :: q in s && q == 5\n}\n\npredicate ViaSetComprehension(s: set) {\n |set q | q in s && q == 5| != 0\n}\n\npredicate LambdaTest(s: set) {\n (q => q in s)(5)\n}\n\npredicate ViaMapComprehension(s: set) {\n |(map q | q in s && q == 5 :: true).Keys| != 0\n}\n\npredicate Contains5(s: set)\n{\n var q := 5; q in s\n}\n\ndatatype R = MakeR(int) | Other\n\npredicate RIs5(r: R) {\n match r case MakeR(q) => q == 5 case Other => false\n}\n\nlemma NonemptySet(x: int, s: set)\n requires x in s\n ensures |s| != 0\n{\n}\nlemma NonemptyMap(x: int, s: map)\n requires x in s.Keys\n ensures |s| != 0\n{\n}\n\nmethod M(s: set, r: R, q: int)\n requires s == {5} && r == MakeR(5)\n{\n\n NonemptySet(5, set q | q in s && q == 5);\n\n NonemptyMap(5, map q | q in s && q == 5 :: true);\n\n\n}\n\n" }, { "test_ID": "466", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_git-issue133.dfy", "ground_truth": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\ndatatype State = State(m:map)\n\nlemma Test(s:State)\n requires 42 in s.m\n ensures s.(m := s.m[42 := s.m[42]]) == s\n{\n var s' := s.(m := s.m[42 := s.m[42]]);\n assert s'.m == s.m;\n}\n\ndatatype MyDt = MakeA(x: int, bool) | MakeB(s: multiset, t: State)\n\nlemma AnotherTest(a: MyDt, b: MyDt, c: bool)\n requires a.MakeB? && b.MakeB?\n requires a.s == multiset(a.t.m.Keys) && |b.s| == 0\n requires a.t.m == map[] && |b.t.m| == 0\n{\n assert a == b;\n}\n\ndatatype GenDt = Left(X) | Middle(X,int,Y) | Right(y: Y)\n\nmethod ChangeGen(g: GenDt)\n{\n match g\n case Left(_) =>\n case Middle(_,_,_) =>\n case Right(u) =>\n var h := g.(y := u);\n assert g == h;\n}\n\ndatatype Recursive = Red | Green(next: Recursive, m: set)\n\nlemma RecLem(r: Recursive) returns (s: Recursive)\n ensures r == s\n{\n match r\n case Red =>\n s := Red;\n case Green(next, m) =>\n var n := RecLem(next);\n s := Green(n, m + m);\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\ndatatype State = State(m:map)\n\nlemma Test(s:State)\n requires 42 in s.m\n ensures s.(m := s.m[42 := s.m[42]]) == s\n{\n var s' := s.(m := s.m[42 := s.m[42]]);\n}\n\ndatatype MyDt = MakeA(x: int, bool) | MakeB(s: multiset, t: State)\n\nlemma AnotherTest(a: MyDt, b: MyDt, c: bool)\n requires a.MakeB? && b.MakeB?\n requires a.s == multiset(a.t.m.Keys) && |b.s| == 0\n requires a.t.m == map[] && |b.t.m| == 0\n{\n}\n\ndatatype GenDt = Left(X) | Middle(X,int,Y) | Right(y: Y)\n\nmethod ChangeGen(g: GenDt)\n{\n match g\n case Left(_) =>\n case Middle(_,_,_) =>\n case Right(u) =>\n var h := g.(y := u);\n}\n\ndatatype Recursive = Red | Green(next: Recursive, m: set)\n\nlemma RecLem(r: Recursive) returns (s: Recursive)\n ensures r == s\n{\n match r\n case Red =>\n s := Red;\n case Green(next, m) =>\n var n := RecLem(next);\n s := Green(n, m + m);\n}\n\n" }, { "test_ID": "467", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_git-issue40.dfy", "ground_truth": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nfunction SeqRepeat(count:nat, elt:T) : seq\n ensures |SeqRepeat(count, elt)| == count\n ensures forall i :: 0 <= i < count ==> SeqRepeat(count, elt)[i] == elt\n\ndatatype Maybe = Nothing | Just(v: T)\ntype Num = x | 0 <= x < 10\ndatatype D = C(seq>)\n\nlemma test()\n{\n ghost var s := SeqRepeat(1, Nothing);\n ghost var e := C(s);\n assert e == C(SeqRepeat(1, Nothing));\n}\n\n\n\n\n", "hints_removed": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nfunction SeqRepeat(count:nat, elt:T) : seq\n ensures |SeqRepeat(count, elt)| == count\n ensures forall i :: 0 <= i < count ==> SeqRepeat(count, elt)[i] == elt\n\ndatatype Maybe = Nothing | Just(v: T)\ntype Num = x | 0 <= x < 10\ndatatype D = C(seq>)\n\nlemma test()\n{\n ghost var s := SeqRepeat(1, Nothing);\n ghost var e := C(s);\n}\n\n\n\n\n" }, { "test_ID": "468", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_git-issue41.dfy", "ground_truth": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\ntype uint32 = i:int | 0 <= i < 0x1_0000_0000\n\nfunction last(s:seq):T\n requires |s| > 0;\n{\n s[|s|-1]\n}\n\nfunction all_but_last(s:seq):seq\n requires |s| > 0;\n ensures |all_but_last(s)| == |s| - 1;\n{\n s[..|s|-1]\n}\n\nfunction ConcatenateSeqs(ss:seq>) : seq\n{\n if |ss| == 0 then [] else ss[0] + ConcatenateSeqs(ss[1..])\n}\n\nlemma {:axiom} lemma_ReverseConcatenateSeqs(ss:seq>)\n requires |ss| > 0;\n ensures ConcatenateSeqs(ss) == ConcatenateSeqs(all_but_last(ss)) + last(ss);\n\nlemma Test(word_seqs:seq>, words:seq)\n{\n var word_seqs' := word_seqs + [words];\n\n calc {\n ConcatenateSeqs(word_seqs');\n { lemma_ReverseConcatenateSeqs(word_seqs'); }\n ConcatenateSeqs(all_but_last(word_seqs')) + last(word_seqs');\n }\n}\n\nlemma AltTest(word_seqs:seq>, words:seq)\n{\n var word_seqs' := word_seqs + [words];\n assert last(word_seqs') == words;\n assert ConcatenateSeqs(word_seqs) + last(word_seqs') == ConcatenateSeqs(word_seqs) + words;\n}\n\nfunction f(s:seq):seq\n\nfunction g(ss:seq>) : seq\n\nlemma {:axiom} lemma_fg(s:seq>)\n ensures g(s) == g(f(s));\n\nlemma Test2(s:seq>)\n{\n calc {\n g(s);\n { lemma_fg(s); }\n g(f(s));\n }\n}\n\nlemma AltTest2(s:seq>)\n{\n lemma_fg(s);\n assert g(s) == g(f(s));\n}\n\n\n", "hints_removed": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\ntype uint32 = i:int | 0 <= i < 0x1_0000_0000\n\nfunction last(s:seq):T\n requires |s| > 0;\n{\n s[|s|-1]\n}\n\nfunction all_but_last(s:seq):seq\n requires |s| > 0;\n ensures |all_but_last(s)| == |s| - 1;\n{\n s[..|s|-1]\n}\n\nfunction ConcatenateSeqs(ss:seq>) : seq\n{\n if |ss| == 0 then [] else ss[0] + ConcatenateSeqs(ss[1..])\n}\n\nlemma {:axiom} lemma_ReverseConcatenateSeqs(ss:seq>)\n requires |ss| > 0;\n ensures ConcatenateSeqs(ss) == ConcatenateSeqs(all_but_last(ss)) + last(ss);\n\nlemma Test(word_seqs:seq>, words:seq)\n{\n var word_seqs' := word_seqs + [words];\n\n calc {\n ConcatenateSeqs(word_seqs');\n { lemma_ReverseConcatenateSeqs(word_seqs'); }\n ConcatenateSeqs(all_but_last(word_seqs')) + last(word_seqs');\n }\n}\n\nlemma AltTest(word_seqs:seq>, words:seq)\n{\n var word_seqs' := word_seqs + [words];\n}\n\nfunction f(s:seq):seq\n\nfunction g(ss:seq>) : seq\n\nlemma {:axiom} lemma_fg(s:seq>)\n ensures g(s) == g(f(s));\n\nlemma Test2(s:seq>)\n{\n calc {\n g(s);\n { lemma_fg(s); }\n g(f(s));\n }\n}\n\nlemma AltTest2(s:seq>)\n{\n lemma_fg(s);\n}\n\n\n" }, { "test_ID": "469", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_git-issue67.dfy", "ground_truth": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nclass Node { }\n\npredicate Q(x: Node)\npredicate P(x: Node)\n\nmethod AuxMethod(y: Node)\n modifies y\n\nmethod MainMethod(y: Node)\n modifies y\n{\n AuxMethod(y); // remove this call and the assertion below goes through (as it should)\n\n forall x | Q(x)\n ensures P(x)\n {\n assume false;\n }\n // The following assertion should be a direct consequence of the forall statement above\n assert forall x :: Q(x) ==> P(x);\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nclass Node { }\n\npredicate Q(x: Node)\npredicate P(x: Node)\n\nmethod AuxMethod(y: Node)\n modifies y\n\nmethod MainMethod(y: Node)\n modifies y\n{\n AuxMethod(y); // remove this call and the assertion below goes through (as it should)\n\n forall x | Q(x)\n ensures P(x)\n {\n assume false;\n }\n // The following assertion should be a direct consequence of the forall statement above\n}\n\n" }, { "test_ID": "470", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_git-issue74.dfy", "ground_truth": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nfunction{:opaque} f(x:int):int { x }\n\nlemma L()\n ensures forall x:int :: f(x) == x\n{\n forall x:int\n ensures f(x) == x\n {\n reveal f();\n }\n assert forall x:int :: f(x) == x;\n}\n\n\n", "hints_removed": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nfunction{:opaque} f(x:int):int { x }\n\nlemma L()\n ensures forall x:int :: f(x) == x\n{\n forall x:int\n ensures f(x) == x\n {\n reveal f();\n }\n}\n\n\n" }, { "test_ID": "471", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_dafny4_git-issue76.dfy", "ground_truth": "// RUN: %dafny /compile:3 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nmethod Main() {\n M0();\n M1();\n EqualityOfStrings0();\n EqualityOfStrings1();\n}\n\n// The verification of the following methods requires knowledge\n// about the injectivity of sequence displays.\n\nmethod M0()\n{\n assert {\"x\",\"y\",\"z\"}-{\"y\"} == {\"x\",\"z\"};\n}\n\nmethod M1()\n{\n var n :| (\"R\",n) in {(\"R\",2),(\"P\",1)};\n assert n == 2;\n print n, \"\\n\";\n}\n\nmethod EqualityOfStrings0() {\n assert \"a\" != \"b\";\n}\n\nmethod EqualityOfStrings1() {\n assert \"a\" + \"b\" == \"ab\";\n}\n\nmethod M2()\n{\n assert !( [0,0] in {[0,2],[1,2]} );\n}\n\nmethod M3()\n{\n assert [0,0] !in {[0,2],[1,2]};\n}\n\n", "hints_removed": "// RUN: %dafny /compile:3 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nmethod Main() {\n M0();\n M1();\n EqualityOfStrings0();\n EqualityOfStrings1();\n}\n\n// The verification of the following methods requires knowledge\n// about the injectivity of sequence displays.\n\nmethod M0()\n{\n}\n\nmethod M1()\n{\n var n :| (\"R\",n) in {(\"R\",2),(\"P\",1)};\n print n, \"\\n\";\n}\n\nmethod EqualityOfStrings0() {\n}\n\nmethod EqualityOfStrings1() {\n}\n\nmethod M2()\n{\n}\n\nmethod M3()\n{\n}\n\n" }, { "test_ID": "472", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_git-issues_git-issue-336.dfy", "ground_truth": "// RUN: %dafny \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nlemma TestMap(a: map) {\n // The following assertion used to not prove automatically\n assert (map k | k in a :: k := a[k].0)\n // the following map comprehension implicitly uses k as the key\n == (map k | k in a :: a[k].0);\n}\n\nlemma TestSet0(a: set) {\n assert (set k | k in a && k < 7 :: k)\n // the following set comprehension implicitly uses k as the term\n == (set k | k in a && k < 7);\n}\n\nlemma TestSet1(a: set, m: int) {\n assert (set k | k in a && k < 7 :: k)\n == (set k | k in a && k < 7 :: m + (k - m));\n}\n\nlemma TestSet2(a: set, m: int)\n requires m in a && m < 7\n{\n assert (set k | k < 7 && k in a)\n == (set k | k in a :: if k < 7 then k else m);\n}\n\n", "hints_removed": "// RUN: %dafny \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nlemma TestMap(a: map) {\n // The following assertion used to not prove automatically\n // the following map comprehension implicitly uses k as the key\n == (map k | k in a :: a[k].0);\n}\n\nlemma TestSet0(a: set) {\n // the following set comprehension implicitly uses k as the term\n == (set k | k in a && k < 7);\n}\n\nlemma TestSet1(a: set, m: int) {\n == (set k | k in a && k < 7 :: m + (k - m));\n}\n\nlemma TestSet2(a: set, m: int)\n requires m in a && m < 7\n{\n == (set k | k in a :: if k < 7 then k else m);\n}\n\n" }, { "test_ID": "473", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_hofs_Compilation.dfy", "ground_truth": "// RUN: %dafny /compile:3 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nclass Ref {\n var val : A\n constructor (a : A)\n ensures val == a\n {\n val := a;\n }\n}\n\nmethod Main() {\n // simple\n print \"1 = \", (x => x)(1), \"\\n\";\n print \"3 = \", (x => y => x + y)(1)(2), \"\\n\";\n print \"3 = \", ((x,y) => y + x)(1,2), \"\\n\";\n print \"0 = \", (() => 0)(), \"\\n\";\n\n // local variable\n var y := 1;\n var f := x => x + y;\n print \"3 = \", f(2), \"\\n\";\n print \"4 = \", f(3), \"\\n\";\n y := 2;\n print \"3 = \", f(2), \"\\n\";\n print \"4 = \", f(3), \"\\n\";\n\n // reference\n var z := new Ref(1);\n f := x reads z => x + z.val;\n print \"3 = \", f(2), \"\\n\";\n print \"4 = \", f(3), \"\\n\";\n z.val := 2;\n print \"4 = \", f(2), \"\\n\";\n print \"5 = \", f(3), \"\\n\";\n\n // loop\n f := x => x;\n y := 10;\n while y > 0\n invariant forall x :: f.requires(x)\n invariant forall x :: f.reads(x) == {}\n {\n f := x => f(x+y);\n y := y - 1;\n }\n print \"55 = \", f(0), \"\\n\";\n\n // substitution test\n print \"0 = \", (x => var y:=x;y)(0), \"\\n\";\n print \"1 = \", (y => (x => var y:=x;y))(0)(1), \"\\n\";\n}\n\n\n", "hints_removed": "// RUN: %dafny /compile:3 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nclass Ref {\n var val : A\n constructor (a : A)\n ensures val == a\n {\n val := a;\n }\n}\n\nmethod Main() {\n // simple\n print \"1 = \", (x => x)(1), \"\\n\";\n print \"3 = \", (x => y => x + y)(1)(2), \"\\n\";\n print \"3 = \", ((x,y) => y + x)(1,2), \"\\n\";\n print \"0 = \", (() => 0)(), \"\\n\";\n\n // local variable\n var y := 1;\n var f := x => x + y;\n print \"3 = \", f(2), \"\\n\";\n print \"4 = \", f(3), \"\\n\";\n y := 2;\n print \"3 = \", f(2), \"\\n\";\n print \"4 = \", f(3), \"\\n\";\n\n // reference\n var z := new Ref(1);\n f := x reads z => x + z.val;\n print \"3 = \", f(2), \"\\n\";\n print \"4 = \", f(3), \"\\n\";\n z.val := 2;\n print \"4 = \", f(2), \"\\n\";\n print \"5 = \", f(3), \"\\n\";\n\n // loop\n f := x => x;\n y := 10;\n while y > 0\n {\n f := x => f(x+y);\n y := y - 1;\n }\n print \"55 = \", f(0), \"\\n\";\n\n // substitution test\n print \"0 = \", (x => var y:=x;y)(0), \"\\n\";\n print \"1 = \", (y => (x => var y:=x;y))(0)(1), \"\\n\";\n}\n\n\n" }, { "test_ID": "474", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_hofs_Requires.dfy", "ground_truth": "// RUN: %dafny /compile:3 /print:\"%t.print\" /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nmethod Main()\n{\n test0(10);\n\ttest5(11);\n\ttest6(12);\n\ttest1();\n\ttest2();\n}\n\npredicate valid(x:int)\n{\n x > 0\n}\n\nfunction ref1(y:int) : int\n requires valid(y);\n{\n y - 1\n}\n\nlemma assumption1()\n ensures forall a, b :: valid(a) && valid(b) && ref1(a) == ref1(b) ==> a == b;\n{\n}\n\nmethod test0(a: int)\n{\n if ref1.requires(a) {\n // the precondition should suffice to let us call the method\n ghost var b := ref1(a);\n }\n}\nmethod test5(a: int)\n{\n if valid(a) {\n // valid(a) is the precondition of ref1\n assert ref1.requires(a);\n }\n}\nmethod test6(a: int)\n{\n if ref1.requires(a) {\n // the precondition of ref1 is valid(a)\n assert valid(a);\n }\n}\n\nmethod test1()\n{\n if * {\n assert forall a, b :: valid(a) && valid(b) && ref1(a) == ref1(b) ==> a == b;\n } else {\n assert forall a, b :: ref1.requires(a) && ref1.requires(b) && ref1(a) == ref1(b)\n ==> a == b;\n }\n}\n\nfunction {:opaque} ref2(y:int) : int // Now with an opaque attribute\n requires valid(y);\n{\n y - 1\n}\n\nlemma assumption2()\n ensures forall a, b :: valid(a) && valid(b) && ref2(a) == ref2(b) ==> a == b;\n{\n reveal ref2();\n}\n\nmethod test2()\n{\n assumption2();\n if * {\n assert forall a, b :: valid(a) && valid(b) && ref2(a) == ref2(b) ==> a == b;\n } else {\n assert forall a, b :: ref2.requires(a) && ref2.requires(b) && ref2(a) == ref2(b)\n ==> a == b;\n }\n}\n\n", "hints_removed": "// RUN: %dafny /compile:3 /print:\"%t.print\" /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nmethod Main()\n{\n test0(10);\n\ttest5(11);\n\ttest6(12);\n\ttest1();\n\ttest2();\n}\n\npredicate valid(x:int)\n{\n x > 0\n}\n\nfunction ref1(y:int) : int\n requires valid(y);\n{\n y - 1\n}\n\nlemma assumption1()\n ensures forall a, b :: valid(a) && valid(b) && ref1(a) == ref1(b) ==> a == b;\n{\n}\n\nmethod test0(a: int)\n{\n if ref1.requires(a) {\n // the precondition should suffice to let us call the method\n ghost var b := ref1(a);\n }\n}\nmethod test5(a: int)\n{\n if valid(a) {\n // valid(a) is the precondition of ref1\n }\n}\nmethod test6(a: int)\n{\n if ref1.requires(a) {\n // the precondition of ref1 is valid(a)\n }\n}\n\nmethod test1()\n{\n if * {\n } else {\n ==> a == b;\n }\n}\n\nfunction {:opaque} ref2(y:int) : int // Now with an opaque attribute\n requires valid(y);\n{\n y - 1\n}\n\nlemma assumption2()\n ensures forall a, b :: valid(a) && valid(b) && ref2(a) == ref2(b) ==> a == b;\n{\n reveal ref2();\n}\n\nmethod test2()\n{\n assumption2();\n if * {\n } else {\n ==> a == b;\n }\n}\n\n" }, { "test_ID": "475", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_hofs_SumSum.dfy", "ground_truth": "// RUN: %dafny /compile:0 /rprint:\"%t.rprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// Tests that come down to comparing the bodies of (possibly nested) functions.\n// Many of these currently require far more effort than one would like.\n// KRML, 2 May 2016\n\nfunction Sum(n: nat, f: int -> int): int\n{\n if n == 0 then 0 else f(n-1) + Sum(n-1, f)\n}\n\nlemma Exchange(n: nat, f: int -> int, g: int -> int)\n requires forall i :: 0 <= i < n ==> f(i) == g(i)\n ensures Sum(n, f) == Sum(n, g)\n{\n}\n\nlemma ExchangeEta(n: nat, f: int -> int, g: int -> int)\n requires forall i :: 0 <= i < n ==> f(i) == g(i)\n ensures Sum(n, x => f(x)) == Sum(n, x => g(x))\n{\n}\n\nlemma NestedAlphaRenaming(n: nat, g: (int,int) -> int)\n ensures Sum(n, x => Sum(n, y => g(x,y))) == Sum(n, a => Sum(n, b => g(a,b)))\n{\n}\n\nlemma DistributePlus1(n: nat, f: int -> int)\n ensures Sum(n, x => 1 + f(x)) == n + Sum(n, f)\n{\n}\n\nlemma Distribute(n: nat, f: int -> int, g: int -> int)\n ensures Sum(n, x => f(x) + g(x)) == Sum(n, f) + Sum(n, g)\n{\n}\n\nlemma {:induction false} PrettyBasicBetaReduction(n: nat, g: (int,int) -> int, i: int)\n ensures (x => Sum(n, y => g(x,y)))(i) == Sum(n, y => g(i,y))\n{\n // NOTE: This proof is by induction on n (it can be done automatically)\n if n == 0 {\n calc {\n (x => Sum(n, y => g(x,y)))(i);\n 0;\n Sum(n, y => g(i,y));\n }\n } else {\n calc {\n (x => Sum(n, y => g(x,y)))(i);\n g(i,n-1) + (x => Sum(n-1, y => g(x,y)))(i);\n { PrettyBasicBetaReduction(n-1, g, i); }\n g(i,n-1) + Sum(n-1, y => g(i,y));\n (y => g(i,y))(n-1) + Sum(n-1, y => g(i,y));\n Sum(n, y => g(i,y));\n }\n }\n}\n\nlemma BetaReduction0(n: nat, g: (int,int) -> int, i: int)\n ensures (x => Sum(n, y => g(x,y)))(i) == Sum(n, y => g(i,y))\n{\n // automatic proof by induction on n\n}\n\nlemma BetaReduction1(n': nat, g: (int,int) -> int, i: int)\n ensures g(i,n') + Sum(n', y => g(i,y)) == (x => g(x,n') + Sum(n', y => g(x,y)))(i);\n{\n}\n\nlemma BetaReductionInside(n': nat, g: (int,int) -> int)\n ensures Sum(n', x => g(x,n') + Sum(n', y => g(x,y)))\n == Sum(n', x => (w => g(w,n'))(x) + (w => Sum(n', y => g(w,y)))(x))\n{\n forall i | 0 <= i < n'\n {\n calc {\n (x => g(x,n') + Sum(n', y => g(x,y)))(i);\n (x => (w => g(w,n'))(x) + (w => Sum(n', y => g(w,y)))(x))(i);\n }\n }\n 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));\n}\n\nlemma L(n: nat, n': nat, g: (int, int) -> int)\n requires && n == n' + 1\n ensures Sum(n, x => Sum(n, y => g(x,y)))\n == Sum(n', x => Sum(n', y => g(x,y))) + Sum(n', x => g(x,n')) + Sum(n', y => g(n',y)) + g(n',n')\n{\n var A := w => g(w,n');\n var B := w => Sum(n', y => g(w,y));\n\n calc {\n Sum(n, x => Sum(n, y => g(x,y)));\n { assume false;/*TODO*/ }\n (x => Sum(n, y => g(x,y)))(n') + Sum(n', x => Sum(n, y => g(x,y)));\n { BetaReduction0(n, g, n'); }\n Sum(n, y => g(n',y)) + Sum(n', x => Sum(n, y => g(x,y)));\n { assume false;/*TODO*/ }\n (y => g(n',y))(n') + Sum(n', y => g(n',y)) + Sum(n', x => Sum(n, y => g(x,y)));\n { assert (y => g(n',y))(n') == g(n',n'); }\n g(n',n') + Sum(n', y => g(n',y)) + Sum(n', x => Sum(n, y => g(x,y)));\n {\n forall i | 0 <= i < n' {\n calc {\n (x => Sum(n, y => g(x,y)))(i);\n { PrettyBasicBetaReduction(n, g, i); }\n Sum(n, y => g(i,y));\n { assume false;/*TODO*/ }\n (y => g(i,y))(n') + Sum(n', y => g(i,y));\n // beta reduction\n g(i,n') + Sum(n', y => g(i,y));\n { BetaReduction1(n', g, i); }\n (x => g(x,n') + Sum(n', y => g(x,y)))(i);\n }\n }\n Exchange(n', x => Sum(n, y => g(x,y)), x => g(x,n') + Sum(n', y => g(x,y)));\n }\n g(n',n') + Sum(n', y => g(n',y)) + Sum(n', x => g(x,n') + Sum(n', y => g(x,y)));\n { BetaReductionInside(n', g); }\n 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));\n { Exchange(n', x => (w => g(w,n'))(x) + (w => Sum(n', y => g(w,y)))(x), x => A(x) + B(x)); }\n g(n',n') + Sum(n', y => g(n',y)) + Sum(n', x => A(x) + B(x));\n { Distribute(n', A, B); }\n g(n',n') + Sum(n', y => g(n',y)) + Sum(n', A) + Sum(n', B);\n // defs. A and B\n g(n',n') + Sum(n', y => g(n',y)) + Sum(n', w => g(w,n')) + Sum(n', w => Sum(n', y => g(w,y)));\n // alpha renamings, and commutativity of the 4 plus terms\n Sum(n', x => Sum(n', y => g(x,y))) + Sum(n', y => g(n',y)) + Sum(n', x => g(x,n')) + g(n',n');\n }\n}\n\nlemma Commute(n: nat, g: (int,int) -> int)\n ensures Sum(n, x => Sum(n, y => g(x,y))) == Sum(n, x => Sum(n, y => g(y,x)))\n// TODO\n\nlemma CommuteSum(n: nat, g: (int,int) -> int)\n ensures Sum(n, x => Sum(n, y => g(x,y))) == Sum(n, y => Sum(n, x => g(x,y)))\n// TODO\n\n", "hints_removed": "// RUN: %dafny /compile:0 /rprint:\"%t.rprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// Tests that come down to comparing the bodies of (possibly nested) functions.\n// Many of these currently require far more effort than one would like.\n// KRML, 2 May 2016\n\nfunction Sum(n: nat, f: int -> int): int\n{\n if n == 0 then 0 else f(n-1) + Sum(n-1, f)\n}\n\nlemma Exchange(n: nat, f: int -> int, g: int -> int)\n requires forall i :: 0 <= i < n ==> f(i) == g(i)\n ensures Sum(n, f) == Sum(n, g)\n{\n}\n\nlemma ExchangeEta(n: nat, f: int -> int, g: int -> int)\n requires forall i :: 0 <= i < n ==> f(i) == g(i)\n ensures Sum(n, x => f(x)) == Sum(n, x => g(x))\n{\n}\n\nlemma NestedAlphaRenaming(n: nat, g: (int,int) -> int)\n ensures Sum(n, x => Sum(n, y => g(x,y))) == Sum(n, a => Sum(n, b => g(a,b)))\n{\n}\n\nlemma DistributePlus1(n: nat, f: int -> int)\n ensures Sum(n, x => 1 + f(x)) == n + Sum(n, f)\n{\n}\n\nlemma Distribute(n: nat, f: int -> int, g: int -> int)\n ensures Sum(n, x => f(x) + g(x)) == Sum(n, f) + Sum(n, g)\n{\n}\n\nlemma {:induction false} PrettyBasicBetaReduction(n: nat, g: (int,int) -> int, i: int)\n ensures (x => Sum(n, y => g(x,y)))(i) == Sum(n, y => g(i,y))\n{\n // NOTE: This proof is by induction on n (it can be done automatically)\n if n == 0 {\n calc {\n (x => Sum(n, y => g(x,y)))(i);\n 0;\n Sum(n, y => g(i,y));\n }\n } else {\n calc {\n (x => Sum(n, y => g(x,y)))(i);\n g(i,n-1) + (x => Sum(n-1, y => g(x,y)))(i);\n { PrettyBasicBetaReduction(n-1, g, i); }\n g(i,n-1) + Sum(n-1, y => g(i,y));\n (y => g(i,y))(n-1) + Sum(n-1, y => g(i,y));\n Sum(n, y => g(i,y));\n }\n }\n}\n\nlemma BetaReduction0(n: nat, g: (int,int) -> int, i: int)\n ensures (x => Sum(n, y => g(x,y)))(i) == Sum(n, y => g(i,y))\n{\n // automatic proof by induction on n\n}\n\nlemma BetaReduction1(n': nat, g: (int,int) -> int, i: int)\n ensures g(i,n') + Sum(n', y => g(i,y)) == (x => g(x,n') + Sum(n', y => g(x,y)))(i);\n{\n}\n\nlemma BetaReductionInside(n': nat, g: (int,int) -> int)\n ensures Sum(n', x => g(x,n') + Sum(n', y => g(x,y)))\n == Sum(n', x => (w => g(w,n'))(x) + (w => Sum(n', y => g(w,y)))(x))\n{\n forall i | 0 <= i < n'\n {\n calc {\n (x => g(x,n') + Sum(n', y => g(x,y)))(i);\n (x => (w => g(w,n'))(x) + (w => Sum(n', y => g(w,y)))(x))(i);\n }\n }\n 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));\n}\n\nlemma L(n: nat, n': nat, g: (int, int) -> int)\n requires && n == n' + 1\n ensures Sum(n, x => Sum(n, y => g(x,y)))\n == Sum(n', x => Sum(n', y => g(x,y))) + Sum(n', x => g(x,n')) + Sum(n', y => g(n',y)) + g(n',n')\n{\n var A := w => g(w,n');\n var B := w => Sum(n', y => g(w,y));\n\n calc {\n Sum(n, x => Sum(n, y => g(x,y)));\n { assume false;/*TODO*/ }\n (x => Sum(n, y => g(x,y)))(n') + Sum(n', x => Sum(n, y => g(x,y)));\n { BetaReduction0(n, g, n'); }\n Sum(n, y => g(n',y)) + Sum(n', x => Sum(n, y => g(x,y)));\n { assume false;/*TODO*/ }\n (y => g(n',y))(n') + Sum(n', y => g(n',y)) + Sum(n', x => Sum(n, y => g(x,y)));\n { assert (y => g(n',y))(n') == g(n',n'); }\n g(n',n') + Sum(n', y => g(n',y)) + Sum(n', x => Sum(n, y => g(x,y)));\n {\n forall i | 0 <= i < n' {\n calc {\n (x => Sum(n, y => g(x,y)))(i);\n { PrettyBasicBetaReduction(n, g, i); }\n Sum(n, y => g(i,y));\n { assume false;/*TODO*/ }\n (y => g(i,y))(n') + Sum(n', y => g(i,y));\n // beta reduction\n g(i,n') + Sum(n', y => g(i,y));\n { BetaReduction1(n', g, i); }\n (x => g(x,n') + Sum(n', y => g(x,y)))(i);\n }\n }\n Exchange(n', x => Sum(n, y => g(x,y)), x => g(x,n') + Sum(n', y => g(x,y)));\n }\n g(n',n') + Sum(n', y => g(n',y)) + Sum(n', x => g(x,n') + Sum(n', y => g(x,y)));\n { BetaReductionInside(n', g); }\n 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));\n { Exchange(n', x => (w => g(w,n'))(x) + (w => Sum(n', y => g(w,y)))(x), x => A(x) + B(x)); }\n g(n',n') + Sum(n', y => g(n',y)) + Sum(n', x => A(x) + B(x));\n { Distribute(n', A, B); }\n g(n',n') + Sum(n', y => g(n',y)) + Sum(n', A) + Sum(n', B);\n // defs. A and B\n g(n',n') + Sum(n', y => g(n',y)) + Sum(n', w => g(w,n')) + Sum(n', w => Sum(n', y => g(w,y)));\n // alpha renamings, and commutativity of the 4 plus terms\n Sum(n', x => Sum(n', y => g(x,y))) + Sum(n', y => g(n',y)) + Sum(n', x => g(x,n')) + g(n',n');\n }\n}\n\nlemma Commute(n: nat, g: (int,int) -> int)\n ensures Sum(n, x => Sum(n, y => g(x,y))) == Sum(n, x => Sum(n, y => g(y,x)))\n// TODO\n\nlemma CommuteSum(n: nat, g: (int,int) -> int)\n ensures Sum(n, x => Sum(n, y => g(x,y))) == Sum(n, y => Sum(n, x => g(x,y)))\n// TODO\n\n" }, { "test_ID": "476", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_hofs_WhileLoop.dfy", "ground_truth": "// RUN: %dafny /compile:3 /print:\"%t.print\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nclass Ref {\n var val: A\n}\n\nmethod Nice(n: int) returns (k: int) {\n var f : int -> int := x => x;\n var i := new Ref;\n i.val := 0;\n while i.val < n\n invariant forall u :: f.requires(u)\n invariant forall u :: f.reads(u) == {}\n invariant forall u :: f(u) == u + i.val\n {\n i.val := i.val + 1;\n f := x => f(x) + 1;\n }\n return f(0);\n}\n\nmethod OneShot(n: int) returns (k: int) {\n var f : int -> int := x => x;\n var i := 0;\n while i < n\n invariant forall u :: f.requires(u)\n invariant forall u :: f(u) == u + i\n {\n i := i + 1;\n f := x requires f.requires(x) reads f.reads(x) => f(x) + 1;\n }\n k := f(0);\n}\n\nmethod HeapQuant(n: int) returns (k: int) {\n var f : int -> int := x => x;\n var i := new Ref;\n ghost var r := 0;\n i.val := 0;\n while i.val < n\n invariant forall u :: f.requires(u)\n invariant forall u :: f.reads(u) == {}\n invariant r == i.val\n invariant forall u :: f(u) == u + r\n {\n i.val, r := i.val + 1, r + 1;\n f := x => f(x) + 1;\n }\n k := f(0);\n}\n\nmethod Main() {\n var k0 := Nice(22);\n var k1 := OneShot(22);\n var k2 := HeapQuant(22);\n print k0, \" \", k1, \" \", k2, \"\\n\";\n}\n\n", "hints_removed": "// RUN: %dafny /compile:3 /print:\"%t.print\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nclass Ref {\n var val: A\n}\n\nmethod Nice(n: int) returns (k: int) {\n var f : int -> int := x => x;\n var i := new Ref;\n i.val := 0;\n while i.val < n\n {\n i.val := i.val + 1;\n f := x => f(x) + 1;\n }\n return f(0);\n}\n\nmethod OneShot(n: int) returns (k: int) {\n var f : int -> int := x => x;\n var i := 0;\n while i < n\n {\n i := i + 1;\n f := x requires f.requires(x) reads f.reads(x) => f(x) + 1;\n }\n k := f(0);\n}\n\nmethod HeapQuant(n: int) returns (k: int) {\n var f : int -> int := x => x;\n var i := new Ref;\n ghost var r := 0;\n i.val := 0;\n while i.val < n\n {\n i.val, r := i.val + 1, r + 1;\n f := x => f(x) + 1;\n }\n k := f(0);\n}\n\nmethod Main() {\n var k0 := Nice(22);\n var k1 := OneShot(22);\n var k2 := HeapQuant(22);\n print k0, \" \", k1, \" \", k2, \"\\n\";\n}\n\n" }, { "test_ID": "477", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_triggers_auto-triggers-fix-an-issue-listed-in-the-ironclad-notebook.dfy", "ground_truth": "// RUN: %dafny /compile:0 /print:\"%t.print\" /dprint:\"%t.dprint\" /printTooltips \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// This example was listed in IronClad's notebook as one place were z3 picked\n// much too liberal triggers. THe Boogie code for this is shown below:\n//\n// forall k#2: Seq Box :: $Is(k#2, TSeq(TInt)) && $IsAlloc(k#2, TSeq(TInt), $Heap)\n// ==> Seq#Equal(_module.__default.HashtableLookup($Heap, h1#0, k#2),\n// _module.__default.HashtableLookup($Heap, h2#0, k#2))\n//\n// and z3 would pick $Is(k#2, TSeq(TInt)) or $IsAlloc(k#2, TSeq(TInt), $Heap) as\n// triggers.\n\ntype Key = seq\ntype Value = seq\n\ntype Hashtable = map\nfunction HashtableLookup(h: Hashtable, k: Key): Value\n\nlemma HashtableAgreement(h1:Hashtable, h2:Hashtable, k:Key)\n requires forall k :: HashtableLookup(h1,k) == HashtableLookup(h2,k) {\n assert true || (k in h1) == (k in h2);\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 /print:\"%t.print\" /dprint:\"%t.dprint\" /printTooltips \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// This example was listed in IronClad's notebook as one place were z3 picked\n// much too liberal triggers. THe Boogie code for this is shown below:\n//\n// forall k#2: Seq Box :: $Is(k#2, TSeq(TInt)) && $IsAlloc(k#2, TSeq(TInt), $Heap)\n// ==> Seq#Equal(_module.__default.HashtableLookup($Heap, h1#0, k#2),\n// _module.__default.HashtableLookup($Heap, h2#0, k#2))\n//\n// and z3 would pick $Is(k#2, TSeq(TInt)) or $IsAlloc(k#2, TSeq(TInt), $Heap) as\n// triggers.\n\ntype Key = seq\ntype Value = seq\n\ntype Hashtable = map\nfunction HashtableLookup(h: Hashtable, k: Key): Value\n\nlemma HashtableAgreement(h1:Hashtable, h2:Hashtable, k:Key)\n requires forall k :: HashtableLookup(h1,k) == HashtableLookup(h2,k) {\n}\n\n" }, { "test_ID": "478", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_triggers_function-applications-are-triggers.dfy", "ground_truth": "// RUN: %dafny /compile:0 /print:\"%t.print\" /dprint:\"%t.dprint\" /printTooltips \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// This file checks that function applications yield trigger candidates\n\nmethod M(P: (int -> int) -> bool, g: int -> int)\n requires P.requires(g)\n requires P(g) {\n assume forall f: int -> int :: P.requires(f);\n assume forall f: int -> int :: P(f) ==> f.requires(10) && f(10) == 0;\n assert forall f: int -> int ::\n (forall x :: f.requires(x) && g.requires(x) ==> f(x) == g(x)) ==>\n f.requires(10) ==>\n f(10) == 0;\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 /print:\"%t.print\" /dprint:\"%t.dprint\" /printTooltips \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// This file checks that function applications yield trigger candidates\n\nmethod M(P: (int -> int) -> bool, g: int -> int)\n requires P.requires(g)\n requires P(g) {\n assume forall f: int -> int :: P.requires(f);\n assume forall f: int -> int :: P(f) ==> f.requires(10) && f(10) == 0;\n (forall x :: f.requires(x) && g.requires(x) ==> f(x) == g(x)) ==>\n f.requires(10) ==>\n f(10) == 0;\n}\n\n" }, { "test_ID": "479", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_triggers_large-quantifiers-dont-break-dafny.dfy", "ground_truth": "// RUN: %dafny /compile:0 /print:\"%t.print\" /dprint:\"%t.dprint\" /printTooltips \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// This test ensures that the trigger collector (the routine that picks trigger\n// candidates) does not actually consider all subsets of terms; if it did, the\n// following would take horribly long\n\npredicate P0(x: bool)\npredicate P1(x: bool)\npredicate P2(x: bool)\npredicate P3(x: bool)\npredicate P4(x: bool)\npredicate P5(x: bool)\npredicate P6(x: bool)\npredicate P7(x: bool)\npredicate P8(x: bool)\npredicate P9(x: bool)\npredicate P10(x: bool)\npredicate P11(x: bool)\npredicate P12(x: bool)\npredicate P13(x: bool)\npredicate P14(x: bool)\npredicate P15(x: bool)\npredicate P16(x: bool)\npredicate P17(x: bool)\npredicate P18(x: bool)\npredicate P19(x: bool)\npredicate P20(x: bool)\npredicate P21(x: bool)\npredicate P22(x: bool)\npredicate P23(x: bool)\npredicate P24(x: bool)\npredicate P25(x: bool)\npredicate P26(x: bool)\npredicate P27(x: bool)\npredicate P28(x: bool)\npredicate P29(x: bool)\npredicate P30(x: bool)\npredicate P31(x: bool)\npredicate P32(x: bool)\npredicate P33(x: bool)\npredicate P34(x: bool)\npredicate P35(x: bool)\npredicate P36(x: bool)\npredicate P37(x: bool)\npredicate P38(x: bool)\npredicate P39(x: bool)\npredicate P40(x: bool)\npredicate P41(x: bool)\npredicate P42(x: bool)\npredicate P43(x: bool)\npredicate P44(x: bool)\npredicate P45(x: bool)\npredicate P46(x: bool)\npredicate P47(x: bool)\npredicate P48(x: bool)\npredicate P49(x: bool)\n\nmethod M() {\n 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);\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 /print:\"%t.print\" /dprint:\"%t.dprint\" /printTooltips \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// This test ensures that the trigger collector (the routine that picks trigger\n// candidates) does not actually consider all subsets of terms; if it did, the\n// following would take horribly long\n\npredicate P0(x: bool)\npredicate P1(x: bool)\npredicate P2(x: bool)\npredicate P3(x: bool)\npredicate P4(x: bool)\npredicate P5(x: bool)\npredicate P6(x: bool)\npredicate P7(x: bool)\npredicate P8(x: bool)\npredicate P9(x: bool)\npredicate P10(x: bool)\npredicate P11(x: bool)\npredicate P12(x: bool)\npredicate P13(x: bool)\npredicate P14(x: bool)\npredicate P15(x: bool)\npredicate P16(x: bool)\npredicate P17(x: bool)\npredicate P18(x: bool)\npredicate P19(x: bool)\npredicate P20(x: bool)\npredicate P21(x: bool)\npredicate P22(x: bool)\npredicate P23(x: bool)\npredicate P24(x: bool)\npredicate P25(x: bool)\npredicate P26(x: bool)\npredicate P27(x: bool)\npredicate P28(x: bool)\npredicate P29(x: bool)\npredicate P30(x: bool)\npredicate P31(x: bool)\npredicate P32(x: bool)\npredicate P33(x: bool)\npredicate P34(x: bool)\npredicate P35(x: bool)\npredicate P36(x: bool)\npredicate P37(x: bool)\npredicate P38(x: bool)\npredicate P39(x: bool)\npredicate P40(x: bool)\npredicate P41(x: bool)\npredicate P42(x: bool)\npredicate P43(x: bool)\npredicate P44(x: bool)\npredicate P45(x: bool)\npredicate P46(x: bool)\npredicate P47(x: bool)\npredicate P48(x: bool)\npredicate P49(x: bool)\n\nmethod M() {\n}\n\n" }, { "test_ID": "480", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_triggers_loop-detection-looks-at-ranges-too.dfy", "ground_truth": "// RUN: %dafny /compile:0 /print:\"%t.print\" /dprint:\"%t.dprint\" /printTooltips \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// This file checks that loops between the range and the term of a quantifier\n// are properly detected.\n\npredicate P(x: int)\n\nmethod M(x: int) {\n // This will be flagged as a loop even without looking at the range\n assert true || forall x: int | P(x) :: P(x+1);\n // This requires checking the range for looping terms\n assert true || forall x: int | P(x+1) :: P(x);\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 /print:\"%t.print\" /dprint:\"%t.dprint\" /printTooltips \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// This file checks that loops between the range and the term of a quantifier\n// are properly detected.\n\npredicate P(x: int)\n\nmethod M(x: int) {\n // This will be flagged as a loop even without looking at the range\n // This requires checking the range for looping terms\n}\n\n" }, { "test_ID": "481", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_tutorial_maximum.dfy", "ground_truth": "// RUN: %dafny /compile:0 /print:\"%t.print\" /dprint:\"%t.dprint\" /printTooltips \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// This file shows how to specify and implement a function to compute the\n// largest element of a list. The function is fully specified by two\n// preconditions, as proved by the MaximumIsUnique lemma below.\n\nmethod Maximum(values: seq) returns (max: int)\n requires values != []\n ensures max in values\n ensures forall i | 0 <= i < |values| :: values[i] <= max\n{\n max := values[0];\n var idx := 0;\n while (idx < |values|)\n invariant max in values\n invariant idx <= |values|\n invariant forall j | 0 <= j < idx :: values[j] <= max\n {\n if (values[idx] > max) {\n max := values[idx];\n }\n idx := idx + 1;\n }\n}\n\nlemma MaximumIsUnique(values: seq, m1: int, m2: int)\n requires m1 in values && forall i | 0 <= i < |values| :: values[i] <= m1\n requires m2 in values && forall i | 0 <= i < |values| :: values[i] <= m2\n ensures m1 == m2 {\n // This lemma does not need a body: Dafny is able to prove it correct entirely automatically.\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 /print:\"%t.print\" /dprint:\"%t.dprint\" /printTooltips \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// This file shows how to specify and implement a function to compute the\n// largest element of a list. The function is fully specified by two\n// preconditions, as proved by the MaximumIsUnique lemma below.\n\nmethod Maximum(values: seq) returns (max: int)\n requires values != []\n ensures max in values\n ensures forall i | 0 <= i < |values| :: values[i] <= max\n{\n max := values[0];\n var idx := 0;\n while (idx < |values|)\n {\n if (values[idx] > max) {\n max := values[idx];\n }\n idx := idx + 1;\n }\n}\n\nlemma MaximumIsUnique(values: seq, m1: int, m2: int)\n requires m1 in values && forall i | 0 <= i < |values| :: values[i] <= m1\n requires m2 in values && forall i | 0 <= i < |values| :: values[i] <= m2\n ensures m1 == m2 {\n // This lemma does not need a body: Dafny is able to prove it correct entirely automatically.\n}\n\n" }, { "test_ID": "482", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_vacid0_Composite.dfy", "ground_truth": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nclass Composite {\n var left: Composite?\n var right: Composite?\n var parent: Composite?\n var val: int\n var sum: int\n\n function Valid(S: set): bool\n reads this, parent, left, right\n {\n this in S &&\n (parent != null ==> parent in S && (parent.left == this || parent.right == this)) &&\n (left != null ==> left in S && left.parent == this && left != right) &&\n (right != null ==> right in S && right.parent == this && left != right) &&\n sum == val + (if left == null then 0 else left.sum) + (if right == null then 0 else right.sum)\n }\n\n function Acyclic(S: set): bool\n reads S\n {\n this in S &&\n (parent != null ==> parent.Acyclic(S - {this}))\n }\n\n method Init(x: int)\n modifies this\n ensures Valid({this}) && Acyclic({this}) && val == x && parent == null\n {\n parent := null;\n left := null;\n right := null;\n val := x;\n sum := val;\n }\n\n method Update(x: int, ghost S: set)\n requires this in S && Acyclic(S)\n requires forall c :: c in S ==> c.Valid(S)\n modifies S\n ensures forall c :: c in S ==> c.Valid(S)\n ensures forall c :: c in S ==> c.left == old(c.left) && c.right == old(c.right) && c.parent == old(c.parent)\n ensures forall c :: c in S && c != this ==> c.val == old(c.val)\n ensures val == x\n {\n var delta := x - val;\n val := x;\n Adjust(delta, S, S);\n }\n\n method Add(ghost S: set, child: Composite, ghost U: set)\n requires this in S && Acyclic(S)\n requires forall c :: c in S ==> c.Valid(S)\n requires child in U\n requires forall c :: c in U ==> c.Valid(U)\n requires S !! U\n requires left == null || right == null\n requires child.parent == null\n // modifies only one of this.left and this.right, and child.parent, and various sum fields:\n modifies S, child\n ensures child.left == old(child.left) && child.right == old(child.right) && child.val == old(child.val)\n ensures forall c :: c in S && c != this ==> c.left == old(c.left) && c.right == old(c.right)\n ensures old(left) != null ==> left == old(left)\n ensures old(right) != null ==> right == old(right)\n ensures forall c :: c in S ==> c.parent == old(c.parent) && c.val == old(c.val)\n // sets child.parent to this:\n ensures child.parent == this\n // leaves everything in S+U valid\n 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].\n {\n if (left == null) {\n left := child;\n } else {\n right := child;\n }\n child.parent := this;\n Adjust(child.sum, S, S+U);\n }\n\n method Dislodge(ghost S: set)\n requires this in S && Acyclic(S)\n requires forall c :: c in S ==> c.Valid(S)\n modifies S\n ensures forall c :: c in S ==> c.Valid(S)\n ensures forall c :: c in S ==> c.val == old(c.val)\n ensures forall c :: c in S && c != this ==> c.parent == old(c.parent)\n ensures parent == null\n ensures forall c :: c in S ==> c.left == old(c.left) || (old(c.left) == this && c.left == null)\n ensures forall c :: c in S ==> c.right == old(c.right) || (old(c.right) == this && c.right == null)\n ensures Acyclic({this})\n {\n var p := parent;\n parent := null;\n if (p != null) {\n if (p.left == this) {\n p.left := null;\n } else {\n p.right := null;\n }\n var delta := -sum;\n p.Adjust(delta, S - {this}, S);\n }\n }\n\n /*private*/ method Adjust(delta: int, ghost U: set, ghost S: set)\n requires U <= S && Acyclic(U)\n // everything else is valid:\n requires forall c :: c in S && c != this ==> c.Valid(S)\n // this is almost valid:\n requires parent != null ==> parent in S && (parent.left == this || parent.right == this)\n requires left != null ==> left in S && left.parent == this && left != right\n requires right != null ==> right in S && right.parent == this && left != right\n // ... except that sum needs to be adjusted by delta:\n requires sum + delta == val + (if left == null then 0 else left.sum) + (if right == null then 0 else right.sum)\n // modifies sum fields in U:\n modifies U`sum\n // everything is valid, including this:\n ensures forall c :: c in S ==> c.Valid(S)\n {\n var p: Composite? := this;\n ghost var T := U;\n while (p != null)\n invariant T <= U\n invariant p == null || p.Acyclic(T)\n invariant forall c :: c in S && c != p ==> c.Valid(S)\n 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)\n 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)\n decreases T\n {\n p.sum := p.sum + delta;\n T := T - {p};\n p := p.parent;\n }\n }\n}\n\nmethod Main()\n{\n var c0 := new Composite.Init(57);\n\n var c1 := new Composite.Init(12);\n c0.Add({c0}, c1, {c1});\n\n var c2 := new Composite.Init(48);\n\n var c3 := new Composite.Init(48);\n c2.Add({c2}, c3, {c3});\n c0.Add({c0,c1}, c2, {c2,c3});\n\n ghost var S := {c0, c1, c2, c3};\n c1.Update(100, S);\n c2.Update(102, S);\n\n c2.Dislodge(S);\n c2.Update(496, S);\n c0.Update(0, S);\n}\n\nmethod Harness() {\n var a := new Composite.Init(5);\n var b := new Composite.Init(7);\n a.Add({a}, b, {b});\n assert a.sum == 12;\n\n b.Update(17, {a,b});\n assert a.sum == 22;\n\n var c := new Composite.Init(10);\n b.Add({a,b}, c, {c});\n b.Dislodge({a,b,c});\n assert b.sum == 27;\n}\n\n\n", "hints_removed": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nclass Composite {\n var left: Composite?\n var right: Composite?\n var parent: Composite?\n var val: int\n var sum: int\n\n function Valid(S: set): bool\n reads this, parent, left, right\n {\n this in S &&\n (parent != null ==> parent in S && (parent.left == this || parent.right == this)) &&\n (left != null ==> left in S && left.parent == this && left != right) &&\n (right != null ==> right in S && right.parent == this && left != right) &&\n sum == val + (if left == null then 0 else left.sum) + (if right == null then 0 else right.sum)\n }\n\n function Acyclic(S: set): bool\n reads S\n {\n this in S &&\n (parent != null ==> parent.Acyclic(S - {this}))\n }\n\n method Init(x: int)\n modifies this\n ensures Valid({this}) && Acyclic({this}) && val == x && parent == null\n {\n parent := null;\n left := null;\n right := null;\n val := x;\n sum := val;\n }\n\n method Update(x: int, ghost S: set)\n requires this in S && Acyclic(S)\n requires forall c :: c in S ==> c.Valid(S)\n modifies S\n ensures forall c :: c in S ==> c.Valid(S)\n ensures forall c :: c in S ==> c.left == old(c.left) && c.right == old(c.right) && c.parent == old(c.parent)\n ensures forall c :: c in S && c != this ==> c.val == old(c.val)\n ensures val == x\n {\n var delta := x - val;\n val := x;\n Adjust(delta, S, S);\n }\n\n method Add(ghost S: set, child: Composite, ghost U: set)\n requires this in S && Acyclic(S)\n requires forall c :: c in S ==> c.Valid(S)\n requires child in U\n requires forall c :: c in U ==> c.Valid(U)\n requires S !! U\n requires left == null || right == null\n requires child.parent == null\n // modifies only one of this.left and this.right, and child.parent, and various sum fields:\n modifies S, child\n ensures child.left == old(child.left) && child.right == old(child.right) && child.val == old(child.val)\n ensures forall c :: c in S && c != this ==> c.left == old(c.left) && c.right == old(c.right)\n ensures old(left) != null ==> left == old(left)\n ensures old(right) != null ==> right == old(right)\n ensures forall c :: c in S ==> c.parent == old(c.parent) && c.val == old(c.val)\n // sets child.parent to this:\n ensures child.parent == this\n // leaves everything in S+U valid\n 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].\n {\n if (left == null) {\n left := child;\n } else {\n right := child;\n }\n child.parent := this;\n Adjust(child.sum, S, S+U);\n }\n\n method Dislodge(ghost S: set)\n requires this in S && Acyclic(S)\n requires forall c :: c in S ==> c.Valid(S)\n modifies S\n ensures forall c :: c in S ==> c.Valid(S)\n ensures forall c :: c in S ==> c.val == old(c.val)\n ensures forall c :: c in S && c != this ==> c.parent == old(c.parent)\n ensures parent == null\n ensures forall c :: c in S ==> c.left == old(c.left) || (old(c.left) == this && c.left == null)\n ensures forall c :: c in S ==> c.right == old(c.right) || (old(c.right) == this && c.right == null)\n ensures Acyclic({this})\n {\n var p := parent;\n parent := null;\n if (p != null) {\n if (p.left == this) {\n p.left := null;\n } else {\n p.right := null;\n }\n var delta := -sum;\n p.Adjust(delta, S - {this}, S);\n }\n }\n\n /*private*/ method Adjust(delta: int, ghost U: set, ghost S: set)\n requires U <= S && Acyclic(U)\n // everything else is valid:\n requires forall c :: c in S && c != this ==> c.Valid(S)\n // this is almost valid:\n requires parent != null ==> parent in S && (parent.left == this || parent.right == this)\n requires left != null ==> left in S && left.parent == this && left != right\n requires right != null ==> right in S && right.parent == this && left != right\n // ... except that sum needs to be adjusted by delta:\n requires sum + delta == val + (if left == null then 0 else left.sum) + (if right == null then 0 else right.sum)\n // modifies sum fields in U:\n modifies U`sum\n // everything is valid, including this:\n ensures forall c :: c in S ==> c.Valid(S)\n {\n var p: Composite? := this;\n ghost var T := U;\n while (p != null)\n {\n p.sum := p.sum + delta;\n T := T - {p};\n p := p.parent;\n }\n }\n}\n\nmethod Main()\n{\n var c0 := new Composite.Init(57);\n\n var c1 := new Composite.Init(12);\n c0.Add({c0}, c1, {c1});\n\n var c2 := new Composite.Init(48);\n\n var c3 := new Composite.Init(48);\n c2.Add({c2}, c3, {c3});\n c0.Add({c0,c1}, c2, {c2,c3});\n\n ghost var S := {c0, c1, c2, c3};\n c1.Update(100, S);\n c2.Update(102, S);\n\n c2.Dislodge(S);\n c2.Update(496, S);\n c0.Update(0, S);\n}\n\nmethod Harness() {\n var a := new Composite.Init(5);\n var b := new Composite.Init(7);\n a.Add({a}, b, {b});\n\n b.Update(17, {a,b});\n\n var c := new Composite.Init(10);\n b.Add({a,b}, c, {c});\n b.Dislodge({a,b,c});\n}\n\n\n" }, { "test_ID": "483", "test_file": "dafny-language-server_tmp_tmpkir0kenl_Test_vstte2012_Two-Way-Sort.dfy", "ground_truth": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// This method is a slight generalization of the\n// code provided in the problem statement since it\n// is generic in the type of the array elements.\nmethod swap(a: array, i: int, j: int)\n requires 0 <= i < j < a.Length\n modifies a\n ensures a[i] == old(a[j])\n ensures a[j] == old(a[i])\n ensures forall m :: 0 <= m < a.Length && m != i && m != j ==> a[m] == old(a[m])\n ensures multiset(a[..]) == old(multiset(a[..]))\n{\n var t := a[i];\n a[i] := a[j];\n a[j] := t;\n}\n\n// This method is a direct translation of the pseudo\n// code given in the problem statement.\n// The first postcondition expresses that the resulting\n// array is sorted, that is, all occurrences of \"false\"\n// come before all occurrences of \"true\".\n// The second postcondition expresses that the post-state\n// array is a permutation of the pre-state array. To express\n// this, we use Dafny's built-in multisets. The built-in\n// function \"multiset\" takes an array and yields the\n// multiset of the array elements.\n// Note that Dafny guesses a suitable ranking function\n// for the termination proof of the while loop.\n// We use the loop guard from the given pseudo-code. However,\n// the program also verifies with the stronger guard \"i < j\"\n// (without changing any of the other specifications or\n// annotations).\nmethod two_way_sort(a: array)\n modifies a\n ensures forall m,n :: 0 <= m < n < a.Length ==> (!a[m] || a[n])\n ensures multiset(a[..]) == old(multiset(a[..]))\n{\n var i := 0;\n var j := a.Length - 1;\n while (i <= j)\n invariant 0 <= i <= j + 1 <= a.Length\n invariant forall m :: 0 <= m < i ==> !a[m]\n invariant forall n :: j < n < a.Length ==> a[n]\n invariant multiset(a[..]) == old(multiset(a[..]))\n {\n if (!a[i]) {\n i := i+1;\n } else if (a[j]) {\n j := j-1;\n } else {\n swap(a, i, j);\n i := i+1;\n j := j-1;\n }\n }\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 /dprint:\"%t.dprint\" \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\n// This method is a slight generalization of the\n// code provided in the problem statement since it\n// is generic in the type of the array elements.\nmethod swap(a: array, i: int, j: int)\n requires 0 <= i < j < a.Length\n modifies a\n ensures a[i] == old(a[j])\n ensures a[j] == old(a[i])\n ensures forall m :: 0 <= m < a.Length && m != i && m != j ==> a[m] == old(a[m])\n ensures multiset(a[..]) == old(multiset(a[..]))\n{\n var t := a[i];\n a[i] := a[j];\n a[j] := t;\n}\n\n// This method is a direct translation of the pseudo\n// code given in the problem statement.\n// The first postcondition expresses that the resulting\n// array is sorted, that is, all occurrences of \"false\"\n// come before all occurrences of \"true\".\n// The second postcondition expresses that the post-state\n// array is a permutation of the pre-state array. To express\n// this, we use Dafny's built-in multisets. The built-in\n// function \"multiset\" takes an array and yields the\n// multiset of the array elements.\n// Note that Dafny guesses a suitable ranking function\n// for the termination proof of the while loop.\n// We use the loop guard from the given pseudo-code. However,\n// the program also verifies with the stronger guard \"i < j\"\n// (without changing any of the other specifications or\n// annotations).\nmethod two_way_sort(a: array)\n modifies a\n ensures forall m,n :: 0 <= m < n < a.Length ==> (!a[m] || a[n])\n ensures multiset(a[..]) == old(multiset(a[..]))\n{\n var i := 0;\n var j := a.Length - 1;\n while (i <= j)\n {\n if (!a[i]) {\n i := i+1;\n } else if (a[j]) {\n j := j-1;\n } else {\n swap(a, i, j);\n i := i+1;\n j := j-1;\n }\n }\n}\n\n" }, { "test_ID": "484", "test_file": "dafny-learn_tmp_tmpn94ir40q_R01_assertions.dfy", "ground_truth": "method Abs(x: int) returns (y: int)\n ensures 0 <= y\n ensures x < 0 ==> y == -x\n ensures x >= 0 ==> y == x\n{\n if x < 0 {\n return -x;\n } else {\n return x;\n }\n}\n\nmethod TestingAbs()\n{\n var w := Abs(4);\n assert w >= 0;\n var v := Abs(3);\n assert 0 <= v;\n}\n\nmethod TestingAbs2()\n{\n var v := Abs(3); \n // property of v dependes on the post condition\n assert 0 <= v;\n assert v == 3;\n}\n\n\n\n// Exercise 1. Write a test method that calls your Max method from Exercise 0 and then asserts something about the result.\n// Use your code from Exercise 0\nmethod Max(a: int, b: int) returns (c: int)\n ensures c >= a\n ensures c >= b\n{\n c := a;\n if b > c {\n c := b;\n }\n}\nmethod TestingMax() {\n // Assert some things about Max. Does it operate as you expect?\n // If it does not, can you think of a way to fix it?\n var a := 3;\n var b := 2;\n var c := Max(a, b);\n assert c >= a;\n assert c >= b;\n}\n", "hints_removed": "method Abs(x: int) returns (y: int)\n ensures 0 <= y\n ensures x < 0 ==> y == -x\n ensures x >= 0 ==> y == x\n{\n if x < 0 {\n return -x;\n } else {\n return x;\n }\n}\n\nmethod TestingAbs()\n{\n var w := Abs(4);\n var v := Abs(3);\n}\n\nmethod TestingAbs2()\n{\n var v := Abs(3); \n // property of v dependes on the post condition\n}\n\n\n\n// Exercise 1. Write a test method that calls your Max method from Exercise 0 and then asserts something about the result.\n// Use your code from Exercise 0\nmethod Max(a: int, b: int) returns (c: int)\n ensures c >= a\n ensures c >= b\n{\n c := a;\n if b > c {\n c := b;\n }\n}\nmethod TestingMax() {\n // Assert some things about Max. Does it operate as you expect?\n // If it does not, can you think of a way to fix it?\n var a := 3;\n var b := 2;\n var c := Max(a, b);\n}\n" }, { "test_ID": "485", "test_file": "dafny-learn_tmp_tmpn94ir40q_R01_functions.dfy", "ground_truth": "function abs(x: int): int\n{\n if x < 0 then -x else x\n}\n\nmethod Testing_abs()\n{\n var v := abs(3);\n assert v == 3;\n}\n\n\n// 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.\n\nfunction max(a: int, b: int): int\n{\n // Fill in an expression here.\n if a > b then a else b\n}\nmethod Testing_max() {\n // Add assertions to check max here.\n assert max(3, 4) == 4;\n assert max(-1, -4) == -1;\n}\n\n\n// Exercise 6:\n\nmethod Abs(x: int) returns (y: int)\n ensures abs(x) == y\n{\n // Then change this body to also use abs.\n if x < 0 {\n return -x;\n } else {\n return x;\n }\n}\n\n\n// Ghost\nghost function Double(val:int) : int\n{\n 2 * val\n}\n\nmethod TestDouble(val: int) returns (val2:int)\n ensures val2 == Double(val)\n{\n val2 := 2 * val;\n}\n", "hints_removed": "function abs(x: int): int\n{\n if x < 0 then -x else x\n}\n\nmethod Testing_abs()\n{\n var v := abs(3);\n}\n\n\n// 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.\n\nfunction max(a: int, b: int): int\n{\n // Fill in an expression here.\n if a > b then a else b\n}\nmethod Testing_max() {\n // Add assertions to check max here.\n}\n\n\n// Exercise 6:\n\nmethod Abs(x: int) returns (y: int)\n ensures abs(x) == y\n{\n // Then change this body to also use abs.\n if x < 0 {\n return -x;\n } else {\n return x;\n }\n}\n\n\n// Ghost\nghost function Double(val:int) : int\n{\n 2 * val\n}\n\nmethod TestDouble(val: int) returns (val2:int)\n ensures val2 == Double(val)\n{\n val2 := 2 * val;\n}\n" }, { "test_ID": "486", "test_file": "dafny-mini-project_tmp_tmpjxr3wzqh_src_project2a.dfy", "ground_truth": "/*\n ===============================================\n DCC831 Formal Methods\n 2023.2\n\n Mini Project 2 - Part A\n\n Your name: Guilherme de Oliveira Silva\n ===============================================\n*/\n\n\nfunction rem(x: T, s: seq): seq\n decreases s\n ensures x !in rem(x, s)\n ensures forall i :: 0 <= i < |rem(x, s)| ==> rem(x, s)[i] in s\n ensures forall i :: 0 <= i < |s| && s[i] != x ==> s[i] in rem(x, s)\n{\n if |s| == 0 then []\n else if s[0] == x then rem(x, s[1..])\n else [s[0]] + rem(x, s[1..])\n}\n\n\n// The next three classes have a minimal class definition,\n// for simplicity\nclass Address\n{\n constructor () {}\n}\n\nclass Date\n{\n constructor () {}\n}\n\nclass MessageId\n{\n constructor () {}\n}\n\n//==========================================================\n// Message\n//==========================================================\nclass Message\n{\n var id: MessageId\n var content: string\n var date: Date\n var sender: Address\n var recipients: seq
\n\n constructor (s: Address)\n ensures fresh(id)\n ensures fresh(date)\n ensures content == \"\"\n ensures sender == s\n ensures recipients == []\n {\n id := new MessageId();\n date := new Date();\n this.content := \"\";\n this.sender := s;\n this.recipients := [];\n }\n\n method setContent(c: string)\n modifies this\n ensures content == c\n {\n this.content := c;\n }\n\n method setDate(d: Date)\n modifies this\n ensures date == d\n {\n this.date := d;\n }\n\n method addRecipient(p: nat, r: Address)\n modifies this\n requires p < |recipients|\n ensures |recipients| == |old(recipients)| + 1\n ensures recipients[p] == r\n ensures forall i :: 0 <= i < p ==> recipients[i] == old(recipients[i])\n ensures forall i :: p < i < |recipients| ==> recipients[i] == old(recipients[i-1])\n {\n this.recipients := this.recipients[..p] + [r] + this.recipients[p..];\n }\n}\n\n//==========================================================\n// Mailbox\n//==========================================================\n// Each Mailbox has a name, which is a string. Its main content is a set of messages.\nclass Mailbox {\n var messages: set\n var name: string\n\n // Creates an empty mailbox with name n\n constructor (n: string)\n ensures name == n\n ensures messages == {}\n {\n name := n;\n messages := {};\n }\n\n // Adds message m to the mailbox\n method add(m: Message)\n modifies this\n ensures m in messages\n ensures messages == old(messages) + {m}\n {\n messages := { m } + messages;\n }\n\n // Removes message m from mailbox. m must not be in the mailbox.\n method remove(m: Message)\n modifies this\n requires m in messages\n ensures m !in messages\n ensures messages == old(messages) - {m}\n {\n messages := messages - { m };\n }\n\n // Empties the mailbox messages\n method empty()\n modifies this\n ensures messages == {}\n {\n messages := {};\n }\n}\n\n//==========================================================\n// MailApp\n//==========================================================\nclass MailApp {\n // abstract field for user defined boxes\n ghost var userboxes: set\n\n // the inbox, drafts, trash and sent are both abstract and concrete\n var inbox: Mailbox\n var drafts: Mailbox\n var trash: Mailbox\n var sent: Mailbox\n\n // userboxList implements userboxes\n var userboxList: seq\n\n // Class invariant\n ghost predicate Valid()\n reads this\n {\n //----------------------------------------------------------\n // Abstract state invariants\n //----------------------------------------------------------\n // all predefined mailboxes (inbox, ..., sent) are distinct\n inbox != drafts &&\n inbox != trash &&\n inbox != sent &&\n drafts != trash &&\n drafts != sent &&\n\n // none of the predefined mailboxes are in the set of user-defined mailboxes\n inbox !in userboxList &&\n drafts !in userboxList &&\n trash !in userboxList &&\n sent !in userboxList &&\n\n //----------------------------------------------------------\n // Abstract-to-concrete state invariants\n //----------------------------------------------------------\n // userboxes is the set of mailboxes in userboxList\n forall i :: 0 <= i < |userboxList| ==> userboxList[i] in userboxes\n }\n\n constructor ()\n {\n inbox := new Mailbox(\"Inbox\");\n drafts := new Mailbox(\"Drafts\");\n trash := new Mailbox(\"Trash\");\n sent := new Mailbox(\"Sent\");\n userboxList := [];\n }\n\n // Deletes user-defined mailbox mb\n method deleteMailbox(mb: Mailbox)\n requires Valid()\n requires mb in userboxList\n // ensures mb !in userboxList\n {\n // userboxList := rem(mb, userboxList);\n }\n\n // Adds a new mailbox with name n to set of user-defined mailboxes\n // provided that no user-defined mailbox has name n already\n method newMailbox(n: string)\n modifies this\n requires Valid()\n requires !exists mb | mb in userboxList :: mb.name == n\n ensures exists mb | mb in userboxList :: mb.name == n\n {\n var mb := new Mailbox(n);\n userboxList := [mb] + userboxList;\n }\n\n // Adds a new message with sender s to the drafts mailbox\n method newMessage(s: Address)\n modifies this.drafts\n requires Valid()\n ensures exists m | m in drafts.messages :: m.sender == s\n {\n var m := new Message(s);\n drafts.add(m);\n }\n\n // Moves message m from mailbox mb1 to a different mailbox mb2\n method moveMessage (m: Message, mb1: Mailbox, mb2: Mailbox)\n modifies mb1, mb2\n requires Valid()\n requires m in mb1.messages\n requires m !in mb2.messages\n ensures m !in mb1.messages\n ensures m in mb2.messages\n {\n mb1.remove(m);\n mb2.add(m);\n }\n\n // Moves message m from mailbox mb to the trash mailbox provided\n // that mb is not the trash mailbox\n method deleteMessage (m: Message, mb: Mailbox)\n modifies m, mb, this.trash\n requires Valid()\n requires m in mb.messages\n requires m !in trash.messages\n {\n moveMessage(m, mb, trash);\n }\n\n // Moves message m from the drafts mailbox to the sent mailbox\n method sendMessage(m: Message)\n modifies this.drafts, this.sent\n requires Valid()\n requires m in drafts.messages\n requires m !in sent.messages\n {\n moveMessage(m, drafts, sent);\n }\n\n // Empties the trash mailbox\n method emptyTrash()\n modifies this.trash\n requires Valid()\n ensures trash.messages == {}\n {\n trash.empty();\n }\n}\n\n", "hints_removed": "/*\n ===============================================\n DCC831 Formal Methods\n 2023.2\n\n Mini Project 2 - Part A\n\n Your name: Guilherme de Oliveira Silva\n ===============================================\n*/\n\n\nfunction rem(x: T, s: seq): seq\n ensures x !in rem(x, s)\n ensures forall i :: 0 <= i < |rem(x, s)| ==> rem(x, s)[i] in s\n ensures forall i :: 0 <= i < |s| && s[i] != x ==> s[i] in rem(x, s)\n{\n if |s| == 0 then []\n else if s[0] == x then rem(x, s[1..])\n else [s[0]] + rem(x, s[1..])\n}\n\n\n// The next three classes have a minimal class definition,\n// for simplicity\nclass Address\n{\n constructor () {}\n}\n\nclass Date\n{\n constructor () {}\n}\n\nclass MessageId\n{\n constructor () {}\n}\n\n//==========================================================\n// Message\n//==========================================================\nclass Message\n{\n var id: MessageId\n var content: string\n var date: Date\n var sender: Address\n var recipients: seq
\n\n constructor (s: Address)\n ensures fresh(id)\n ensures fresh(date)\n ensures content == \"\"\n ensures sender == s\n ensures recipients == []\n {\n id := new MessageId();\n date := new Date();\n this.content := \"\";\n this.sender := s;\n this.recipients := [];\n }\n\n method setContent(c: string)\n modifies this\n ensures content == c\n {\n this.content := c;\n }\n\n method setDate(d: Date)\n modifies this\n ensures date == d\n {\n this.date := d;\n }\n\n method addRecipient(p: nat, r: Address)\n modifies this\n requires p < |recipients|\n ensures |recipients| == |old(recipients)| + 1\n ensures recipients[p] == r\n ensures forall i :: 0 <= i < p ==> recipients[i] == old(recipients[i])\n ensures forall i :: p < i < |recipients| ==> recipients[i] == old(recipients[i-1])\n {\n this.recipients := this.recipients[..p] + [r] + this.recipients[p..];\n }\n}\n\n//==========================================================\n// Mailbox\n//==========================================================\n// Each Mailbox has a name, which is a string. Its main content is a set of messages.\nclass Mailbox {\n var messages: set\n var name: string\n\n // Creates an empty mailbox with name n\n constructor (n: string)\n ensures name == n\n ensures messages == {}\n {\n name := n;\n messages := {};\n }\n\n // Adds message m to the mailbox\n method add(m: Message)\n modifies this\n ensures m in messages\n ensures messages == old(messages) + {m}\n {\n messages := { m } + messages;\n }\n\n // Removes message m from mailbox. m must not be in the mailbox.\n method remove(m: Message)\n modifies this\n requires m in messages\n ensures m !in messages\n ensures messages == old(messages) - {m}\n {\n messages := messages - { m };\n }\n\n // Empties the mailbox messages\n method empty()\n modifies this\n ensures messages == {}\n {\n messages := {};\n }\n}\n\n//==========================================================\n// MailApp\n//==========================================================\nclass MailApp {\n // abstract field for user defined boxes\n ghost var userboxes: set\n\n // the inbox, drafts, trash and sent are both abstract and concrete\n var inbox: Mailbox\n var drafts: Mailbox\n var trash: Mailbox\n var sent: Mailbox\n\n // userboxList implements userboxes\n var userboxList: seq\n\n // Class invariant\n ghost predicate Valid()\n reads this\n {\n //----------------------------------------------------------\n // Abstract state invariants\n //----------------------------------------------------------\n // all predefined mailboxes (inbox, ..., sent) are distinct\n inbox != drafts &&\n inbox != trash &&\n inbox != sent &&\n drafts != trash &&\n drafts != sent &&\n\n // none of the predefined mailboxes are in the set of user-defined mailboxes\n inbox !in userboxList &&\n drafts !in userboxList &&\n trash !in userboxList &&\n sent !in userboxList &&\n\n //----------------------------------------------------------\n // Abstract-to-concrete state invariants\n //----------------------------------------------------------\n // userboxes is the set of mailboxes in userboxList\n forall i :: 0 <= i < |userboxList| ==> userboxList[i] in userboxes\n }\n\n constructor ()\n {\n inbox := new Mailbox(\"Inbox\");\n drafts := new Mailbox(\"Drafts\");\n trash := new Mailbox(\"Trash\");\n sent := new Mailbox(\"Sent\");\n userboxList := [];\n }\n\n // Deletes user-defined mailbox mb\n method deleteMailbox(mb: Mailbox)\n requires Valid()\n requires mb in userboxList\n // ensures mb !in userboxList\n {\n // userboxList := rem(mb, userboxList);\n }\n\n // Adds a new mailbox with name n to set of user-defined mailboxes\n // provided that no user-defined mailbox has name n already\n method newMailbox(n: string)\n modifies this\n requires Valid()\n requires !exists mb | mb in userboxList :: mb.name == n\n ensures exists mb | mb in userboxList :: mb.name == n\n {\n var mb := new Mailbox(n);\n userboxList := [mb] + userboxList;\n }\n\n // Adds a new message with sender s to the drafts mailbox\n method newMessage(s: Address)\n modifies this.drafts\n requires Valid()\n ensures exists m | m in drafts.messages :: m.sender == s\n {\n var m := new Message(s);\n drafts.add(m);\n }\n\n // Moves message m from mailbox mb1 to a different mailbox mb2\n method moveMessage (m: Message, mb1: Mailbox, mb2: Mailbox)\n modifies mb1, mb2\n requires Valid()\n requires m in mb1.messages\n requires m !in mb2.messages\n ensures m !in mb1.messages\n ensures m in mb2.messages\n {\n mb1.remove(m);\n mb2.add(m);\n }\n\n // Moves message m from mailbox mb to the trash mailbox provided\n // that mb is not the trash mailbox\n method deleteMessage (m: Message, mb: Mailbox)\n modifies m, mb, this.trash\n requires Valid()\n requires m in mb.messages\n requires m !in trash.messages\n {\n moveMessage(m, mb, trash);\n }\n\n // Moves message m from the drafts mailbox to the sent mailbox\n method sendMessage(m: Message)\n modifies this.drafts, this.sent\n requires Valid()\n requires m in drafts.messages\n requires m !in sent.messages\n {\n moveMessage(m, drafts, sent);\n }\n\n // Empties the trash mailbox\n method emptyTrash()\n modifies this.trash\n requires Valid()\n ensures trash.messages == {}\n {\n trash.empty();\n }\n}\n\n" }, { "test_ID": "487", "test_file": "dafny-programs_tmp_tmpcwodh6qh_src_expt.dfy", "ground_truth": "function Expt(b: int, n: nat): int\n requires n >= 0\n{\n if n == 0 then 1 else b * Expt(b, n - 1)\n}\n\nmethod expt(b: int, n: nat) returns (res: int) \n ensures res == Expt(b, n)\n{\n var i := 1;\n res := 1;\n while i < n + 1 \n invariant 0 < i <= n + 1\n invariant res == Expt(b, i - 1)\n {\n res := res * b;\n i := i + 1;\n }\n}\n\n// source: https://www.dcc.fc.up.pt/~nam/web/resources/vfs20/DafnyQuickReference.pdf\nlemma {:induction a} distributive(x: int, a: nat, b: nat) \n ensures Expt(x, a) * Expt(x, b) == Expt(x, a + b)\n", "hints_removed": "function Expt(b: int, n: nat): int\n requires n >= 0\n{\n if n == 0 then 1 else b * Expt(b, n - 1)\n}\n\nmethod expt(b: int, n: nat) returns (res: int) \n ensures res == Expt(b, n)\n{\n var i := 1;\n res := 1;\n while i < n + 1 \n {\n res := res * b;\n i := i + 1;\n }\n}\n\n// source: https://www.dcc.fc.up.pt/~nam/web/resources/vfs20/DafnyQuickReference.pdf\nlemma {:induction a} distributive(x: int, a: nat, b: nat) \n ensures Expt(x, a) * Expt(x, b) == Expt(x, a + b)\n" }, { "test_ID": "488", "test_file": "dafny-programs_tmp_tmpcwodh6qh_src_factorial.dfy", "ground_truth": "function fact(n: nat): nat \n ensures fact(n) >= 1\n{\n if n == 0 then 1 else n * fact(n - 1)\n}\n\nmethod factorial(n: nat) returns (res: nat)\n ensures res == fact(n)\n{\n var i := 1;\n res := 1;\n while i < n + 1 \n invariant 0 < i <= n + 1\n invariant res == fact(i - 1) // result satisfies postcondition for every iteration, verification fails without this\n {\n res := i * res;\n i := i + 1;\n }\n}\n", "hints_removed": "function fact(n: nat): nat \n ensures fact(n) >= 1\n{\n if n == 0 then 1 else n * fact(n - 1)\n}\n\nmethod factorial(n: nat) returns (res: nat)\n ensures res == fact(n)\n{\n var i := 1;\n res := 1;\n while i < n + 1 \n {\n res := i * res;\n i := i + 1;\n }\n}\n" }, { "test_ID": "489", "test_file": "dafny-programs_tmp_tmpcwodh6qh_src_max.dfy", "ground_truth": "method Max(a: int, b: int) returns (c: int)\n ensures a >= b ==> c == a\n ensures b >= a ==> c == b\n{\n if a > b {\n return a;\n } else {\n return b;\n }\n}\n \nmethod MaxTest() {\n var low := 1;\n var high := 10;\n var v := Max(low, high);\n assert v == high; \n \n}\n\nfunction max(a: int, b: int): int\n{\n if a > b then a else b\n}\n\nmethod maxTest() {\n assert max(1, 10) == 10;\n}\n", "hints_removed": "method Max(a: int, b: int) returns (c: int)\n ensures a >= b ==> c == a\n ensures b >= a ==> c == b\n{\n if a > b {\n return a;\n } else {\n return b;\n }\n}\n \nmethod MaxTest() {\n var low := 1;\n var high := 10;\n var v := Max(low, high);\n \n}\n\nfunction max(a: int, b: int): int\n{\n if a > b then a else b\n}\n\nmethod maxTest() {\n}\n" }, { "test_ID": "490", "test_file": "dafny-programs_tmp_tmpcwodh6qh_src_ticketsystem.dfy", "ground_truth": "// Code taken from the following paper: http://leino.science/papers/krml260.pdf\n\n// Each philosopher's pseudocode:\n\n// repeat forever {\n// Thinking:\n\n// t: Ticket = ticket, ticket + 1 // request ticket to enter hungry state\n// Hungry:\n// //...\n\n// wait until serving = t; // Enter\n// Eating:\n// //...\n\n// serving := serving + 1; // Leaving\n// }\n\n// control state values; thinking, hungry, eating\n// introduce state for each process: use map from processes to values\n\ntype Process(==) // {type comes equipped with ability to compare its values with equality}\ndatatype CState = Thinking | Hungry | Eating\n\n// provides mutual exclusion\nclass TicketSystem {\n var ticket: int\n var serving: int\n const P: set\n\n var cs: map // cannot use state variable P as domain for maps => use Process => every conceivable process\n var t: map // ticket number for each philosopher\n\n // how to know some process p is in domain of map: introduce function which tells whether condition holds or not\n predicate Valid() // function which describes system invariant\n reads this // may depend on values in the class\n {\n P <= cs.Keys && P <= t.Keys && serving <= ticket && // ticket may be greater than serving but not the other way around\n (forall p :: p in P && cs[p] != Thinking ==> serving <= t[p] < ticket) && // any current ticket number is in the range of serving to ticket\n (forall p,q :: \n 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'\n ) && \n (forall p :: p in P && cs[p] == Eating ==> t[p] == serving) // if eating, the current ticket number must be the one being served\n }\n\n constructor (processes: set)\n ensures Valid() // postcondition\n {\n P := processes;\n ticket, serving := 0, 0;\n cs := map p | p in processes :: Thinking; // set initial state of every process to Thinking\n t := map p | p in processes :: 0;\n\n }\n\n // atomic events to formalize for each process: request, enter, leave\n // model each atomic event by a method\n\n // atomicity: read or write just once in body\n // method AtomicStep(p: Process)\n // requires Valid() && p in P && cs[p] == Thinking // Request(p) is only enabled when p is thinking\n // modifies this\n // ensures Valid()\n\n method Request(p: Process)\n requires Valid() && p in P && cs[p] == Thinking\n modifies this\n ensures Valid()\n {\n t, ticket := t[p := ticket], ticket + 1; // map update p to ticket, update ticket\n cs := cs[p := Hungry]; // map update p to Hungry state\n }\n\n method Enter(p: Process)\n requires Valid() && p in P && cs[p] == Hungry\n modifies this\n ensures Valid()\n {\n if t[p] == serving {\n cs := cs[p := Eating]; // map update p to eating state\n }\n }\n\n method Leave(p: Process)\n requires Valid() && p in P && cs[p] == Eating\n modifies this\n ensures Valid()\n {\n assert t[p] == serving;\n serving := serving + 1;\n cs := cs[p := Thinking];\n }\n\n // correctness: no two process are in eating state at same time\n // prove that invariant implies condition\n lemma MutualExclusion(p: Process, q: Process)\n requires Valid() && p in P && q in P // if system is in valid state and both p, q are processes\n requires cs[p] == Eating && cs[q] == Eating // both p, q are in Eating state\n ensures p == q // p and q are the same process \n}\n\n", "hints_removed": "// Code taken from the following paper: http://leino.science/papers/krml260.pdf\n\n// Each philosopher's pseudocode:\n\n// repeat forever {\n// Thinking:\n\n// t: Ticket = ticket, ticket + 1 // request ticket to enter hungry state\n// Hungry:\n// //...\n\n// wait until serving = t; // Enter\n// Eating:\n// //...\n\n// serving := serving + 1; // Leaving\n// }\n\n// control state values; thinking, hungry, eating\n// introduce state for each process: use map from processes to values\n\ntype Process(==) // {type comes equipped with ability to compare its values with equality}\ndatatype CState = Thinking | Hungry | Eating\n\n// provides mutual exclusion\nclass TicketSystem {\n var ticket: int\n var serving: int\n const P: set\n\n var cs: map // cannot use state variable P as domain for maps => use Process => every conceivable process\n var t: map // ticket number for each philosopher\n\n // how to know some process p is in domain of map: introduce function which tells whether condition holds or not\n predicate Valid() // function which describes system invariant\n reads this // may depend on values in the class\n {\n P <= cs.Keys && P <= t.Keys && serving <= ticket && // ticket may be greater than serving but not the other way around\n (forall p :: p in P && cs[p] != Thinking ==> serving <= t[p] < ticket) && // any current ticket number is in the range of serving to ticket\n (forall p,q :: \n 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'\n ) && \n (forall p :: p in P && cs[p] == Eating ==> t[p] == serving) // if eating, the current ticket number must be the one being served\n }\n\n constructor (processes: set)\n ensures Valid() // postcondition\n {\n P := processes;\n ticket, serving := 0, 0;\n cs := map p | p in processes :: Thinking; // set initial state of every process to Thinking\n t := map p | p in processes :: 0;\n\n }\n\n // atomic events to formalize for each process: request, enter, leave\n // model each atomic event by a method\n\n // atomicity: read or write just once in body\n // method AtomicStep(p: Process)\n // requires Valid() && p in P && cs[p] == Thinking // Request(p) is only enabled when p is thinking\n // modifies this\n // ensures Valid()\n\n method Request(p: Process)\n requires Valid() && p in P && cs[p] == Thinking\n modifies this\n ensures Valid()\n {\n t, ticket := t[p := ticket], ticket + 1; // map update p to ticket, update ticket\n cs := cs[p := Hungry]; // map update p to Hungry state\n }\n\n method Enter(p: Process)\n requires Valid() && p in P && cs[p] == Hungry\n modifies this\n ensures Valid()\n {\n if t[p] == serving {\n cs := cs[p := Eating]; // map update p to eating state\n }\n }\n\n method Leave(p: Process)\n requires Valid() && p in P && cs[p] == Eating\n modifies this\n ensures Valid()\n {\n serving := serving + 1;\n cs := cs[p := Thinking];\n }\n\n // correctness: no two process are in eating state at same time\n // prove that invariant implies condition\n lemma MutualExclusion(p: Process, q: Process)\n requires Valid() && p in P && q in P // if system is in valid state and both p, q are processes\n requires cs[p] == Eating && cs[q] == Eating // both p, q are in Eating state\n ensures p == q // p and q are the same process \n}\n\n" }, { "test_ID": "491", "test_file": "dafny-rope_tmp_tmpl4v_njmy_Rope.dfy", "ground_truth": "module Rope {\nclass Rope {\nghost var Contents: string;\nghost var Repr: set;\n\nvar data: string;\nvar weight: nat;\nvar left: Rope?;\nvar right: Rope?;\n\nghost predicate Valid() \n reads this, Repr\n ensures Valid() ==> this in Repr\n{\n this in Repr &&\n (left != null ==> \n left in Repr &&\n left.Repr < Repr && this !in left.Repr &&\n left.Valid() &&\n (forall child :: child in left.Repr ==> child.weight <= weight)) &&\n (right != null ==> \n right in Repr &&\n right.Repr < Repr && this !in right.Repr &&\n right.Valid()) &&\n (left == null && right == null ==>\n Repr == {this} &&\n Contents == data &&\n weight == |data| &&\n data != \"\") &&\n (left != null && right == null ==>\n Repr == {this} + left.Repr &&\n Contents == left.Contents &&\n weight == |left.Contents| &&\n data == \"\") &&\n (left == null && right != null ==>\n Repr == {this} + right.Repr &&\n Contents == right.Contents &&\n weight == 0 &&\n data == \"\") &&\n (left != null && right != null ==>\n Repr == {this} + left.Repr + right.Repr &&\n left.Repr !! right.Repr &&\n Contents == left.Contents + right.Contents &&\n weight == |left.Contents| &&\n data == \"\") \n}\n\nlemma contentSizeGtZero()\n requires Valid()\n ensures |Contents| > 0\n decreases Repr\n{}\n\nfunction getWeightsOfAllRightChildren(): nat\n reads right, Repr\n requires Valid()\n decreases Repr\n ensures right != null\n ==> getWeightsOfAllRightChildren() == |right.Contents|\n{\n if right == null then 0\n else right.weight + right.getWeightsOfAllRightChildren()\n} \n\nfunction length(): nat\n reads Repr\n requires Valid()\n ensures |Contents| == length()\n{\n this.weight + getWeightsOfAllRightChildren()\n}\n\n// constructor for creating a terminal node\nconstructor Terminal(x: string)\n requires x != \"\"\n ensures Valid() && fresh(Repr)\n && left == null && right == null\n && data == x\n{ \n data := x;\n weight := |x|;\n left := null;\n right := null;\n Contents := x;\n Repr := {this};\n} \n\npredicate isTerminal()\n reads this, this.left, this.right\n{ left == null && right == null }\n\nmethod report(i: nat, j: nat) returns (s: string)\n requires 0 <= i <= j <= |this.Contents|\n requires Valid()\n ensures s == this.Contents[i..j]\n decreases Repr\n{\n if i == j {\n s := \"\";\n } else {\n if this.left == null && this.right == null {\n s := data[i..j];\n } else {\n if (j <= this.weight) {\n var s' := this.left.report(i, j);\n s := s';\n } else if (this.weight <= i) {\n var s' := this.right.report(i - this.weight, j - this.weight);\n s := s';\n } else {\n // removing this assertion causes error\n assert i <= this.weight < j;\n var s1 := this.left.report(i, this.weight);\n var s2 := this.right.report(0, j - this.weight);\n s := s1 + s2;\n }\n }\n }\n}\n\nmethod toString() returns (s: string)\n requires Valid()\n ensures s == Contents\n{\n s := report(0, this.length());\n}\n\nmethod getCharAtIndex(index: nat) returns (c: char)\n requires Valid() && 0 <= index < |Contents|\n ensures c == Contents[index]\n{\n var nTemp := this;\n var i := index;\n while (!nTemp.isTerminal()) \n invariant nTemp != null;\n invariant nTemp.Valid()\n invariant 0 <= i < |nTemp.Contents| \n invariant nTemp.Contents[i] == Contents[index] \n decreases nTemp.Repr\n {\n if (i < nTemp.weight) {\n nTemp := nTemp.left;\n } else {\n i := i - nTemp.weight;\n nTemp := nTemp.right;\n }\n }\n // Have reached the terminal node with index i\n c := nTemp.data[i];\n}\n\nstatic method concat(n1: Rope?, n2: Rope?) returns (n: Rope?) \n requires (n1 != null) ==> n1.Valid()\n requires (n2 != null) ==> n2.Valid()\n requires (n1 != null && n2 != null) ==> (n1.Repr !! n2.Repr)\n\n ensures (n1 != null || n2 != null) <==> n != null && n.Valid()\n ensures (n1 == null && n2 == null) <==> n == null\n ensures (n1 == null && n2 != null)\n ==> n == n2 && n != null && n.Valid() && n.Contents == n2.Contents\n ensures (n1 != null && n2 == null)\n ==> n == n1 && n != null && n.Valid() && n.Contents == n1.Contents\n ensures (n1 != null && n2 != null)\n ==> n != null && n.Valid()\n && n.left == n1 && n.right == n2\n && n.Contents == n1.Contents + n2.Contents\n && fresh(n.Repr - n1.Repr - n2.Repr)\n{\n if (n1 == null) {\n n := n2;\n } else if (n2 == null) {\n n := n1;\n } else {\n n := new Rope.Terminal(\"placeholder\");\n n.left := n1;\n n.right := n2;\n n.data := \"\";\n\n var nTemp := n1;\n var w := 0;\n ghost var nodesTraversed : set := {};\n\n while (nTemp.right != null)\n invariant nTemp != null\n invariant nTemp.Valid()\n invariant forall node :: node in nodesTraversed ==> node.weight <= w\n invariant nodesTraversed == n1.Repr - nTemp.Repr\n invariant nTemp.right == null ==> w + nTemp.weight == |n1.Contents|\n invariant nTemp.right != null\n ==> w + nTemp.weight + |nTemp.right.Contents| == |n1.Contents| \n decreases nTemp.Repr\n {\n w := w + nTemp.weight;\n assert w >= 0;\n if (nTemp.left != null) {\n nodesTraversed := nodesTraversed + nTemp.left.Repr + {nTemp};\n } else {\n nodesTraversed := nodesTraversed + {nTemp};\n }\n nTemp := nTemp.right;\n }\n w := w + nTemp.weight;\n if (nTemp.left != null) {\n nodesTraversed := nodesTraversed + nTemp.left.Repr + {nTemp};\n } else {\n nodesTraversed := nodesTraversed + {nTemp};\n }\n n.weight := w;\n n.Contents := n1.Contents + n2.Contents;\n n.Repr := {n} + n1.Repr + n2.Repr;\n } \n} \n\n\n/**\n Dafny needs help to guess that in our definition, every rope must\n have non-empty Contents, otherwise it is represented by [null].\n\n The lemma contentSizeGtZero(n) is thus important to prove the\n postcondition of this method, in the two places where the lemma is\n invoked.\n*/\nstatic method split(n: Rope, index: nat) returns (n1: Rope?, n2: Rope?) \n requires n.Valid() && 0 <= index <= |n.Contents|\n ensures index == 0\n ==> n1 == null && n2 != null && n2.Valid()\n && n2.Contents == n.Contents && fresh(n2.Repr - n.Repr)\n ensures index == |n.Contents|\n ==> n2 == null && n1 != null && n1.Valid()\n && n1.Contents == n.Contents && fresh(n1.Repr - n.Repr)\n ensures 0 < index < |n.Contents|\n ==> n1 != null && n1.Valid() && n2 != null && n2.Valid()\n && n1.Contents == n.Contents[..index]\n && n2.Contents == n.Contents[index..]\n && n1.Repr !! n2.Repr\n && fresh(n1.Repr - n.Repr) && fresh(n2.Repr - n.Repr)\n decreases n.Repr\n{\n if (index == 0) {\n n1 := null;\n n2 := n;\n n.contentSizeGtZero();\n // assert index != |n.Contents|;\n } else if (index < n.weight) {\n if (n.left != null) {\n var s1, s2 := split(n.left, index);\n n1 := s1;\n n2 := concat(s2, n.right);\n } else {\n // terminal node\n assert n.isTerminal();\n if (index == 0) {\n n1 := null;\n n2 := n;\n } else {\n n1 := new Rope.Terminal(n.data[..index]);\n n2 := new Rope.Terminal(n.data[index..]);\n }\n }\n } else if (index > n.weight) {\n var s1, s2 := split(n.right, index - n.weight);\n n1 := concat(n.left, s1);\n n2 := s2;\n } else {\n // since [n.weight == index != 0], it means that [n] cannot be a\n // non-terminal node with [left == null].\n if (n.left != null && n.right == null) {\n n1 := n.left;\n n2 := null;\n } else if (n.left != null && n.right != null) {\n n.right.contentSizeGtZero();\n // assert index != |n.Contents|;\n n1 := n.left;\n n2 := n.right;\n } else {\n assert n.left == null && n.right == null;\n n1 := n;\n n2 := null;\n }\n }\n}\n\nstatic method insert(n1: Rope, n2: Rope, index: nat) returns (n: Rope)\n requires n1.Valid() && n2.Valid() && n1.Repr !! n2.Repr\n requires 0 <= index < |n1.Contents|\n ensures n.Valid()\n && n.Contents ==\n n1.Contents[..index] + n2.Contents + n1.Contents[index..]\n && fresh(n.Repr - n1.Repr - n2.Repr)\n{\n var n1BeforeIndex, n1AfterIndex := split(n1, index);\n var firstPart := concat(n1BeforeIndex, n2);\n n := concat(firstPart, n1AfterIndex);\n}\n\nstatic method delete(n: Rope, i: nat, j: nat) returns (m: Rope?)\n requires n.Valid()\n requires 0 <= i < j <= |n.Contents|\n ensures (i == 0 && j == |n.Contents|) <==> m == null\n ensures m != null ==>\n m.Valid() &&\n m.Contents == n.Contents[..i] + n.Contents[j..] &&\n fresh(m.Repr - n.Repr)\n{\n var l1, l2 := split(n, i);\n var r1, r2 := split(l2, j - i);\n m := concat(l1, r2);\n}\n\nstatic method substring(n: Rope, i: nat, j: nat) returns (m: Rope?)\n requires n.Valid()\n requires 0 <= i < j <= |n.Contents|\n ensures (i == j) <==> m == null\n ensures m != null ==>\n m.Valid() &&\n m.Contents == n.Contents[i..j] &&\n fresh(m.Repr - n.Repr)\n{\n var l1, l2 := split(n, i);\n var r1, r2 := split(l2, j - i);\n m := r1;\n}\n\n}\n// End of Rope Class\n}\n// End of Rope Module\n", "hints_removed": "module Rope {\nclass Rope {\nghost var Contents: string;\nghost var Repr: set;\n\nvar data: string;\nvar weight: nat;\nvar left: Rope?;\nvar right: Rope?;\n\nghost predicate Valid() \n reads this, Repr\n ensures Valid() ==> this in Repr\n{\n this in Repr &&\n (left != null ==> \n left in Repr &&\n left.Repr < Repr && this !in left.Repr &&\n left.Valid() &&\n (forall child :: child in left.Repr ==> child.weight <= weight)) &&\n (right != null ==> \n right in Repr &&\n right.Repr < Repr && this !in right.Repr &&\n right.Valid()) &&\n (left == null && right == null ==>\n Repr == {this} &&\n Contents == data &&\n weight == |data| &&\n data != \"\") &&\n (left != null && right == null ==>\n Repr == {this} + left.Repr &&\n Contents == left.Contents &&\n weight == |left.Contents| &&\n data == \"\") &&\n (left == null && right != null ==>\n Repr == {this} + right.Repr &&\n Contents == right.Contents &&\n weight == 0 &&\n data == \"\") &&\n (left != null && right != null ==>\n Repr == {this} + left.Repr + right.Repr &&\n left.Repr !! right.Repr &&\n Contents == left.Contents + right.Contents &&\n weight == |left.Contents| &&\n data == \"\") \n}\n\nlemma contentSizeGtZero()\n requires Valid()\n ensures |Contents| > 0\n{}\n\nfunction getWeightsOfAllRightChildren(): nat\n reads right, Repr\n requires Valid()\n ensures right != null\n ==> getWeightsOfAllRightChildren() == |right.Contents|\n{\n if right == null then 0\n else right.weight + right.getWeightsOfAllRightChildren()\n} \n\nfunction length(): nat\n reads Repr\n requires Valid()\n ensures |Contents| == length()\n{\n this.weight + getWeightsOfAllRightChildren()\n}\n\n// constructor for creating a terminal node\nconstructor Terminal(x: string)\n requires x != \"\"\n ensures Valid() && fresh(Repr)\n && left == null && right == null\n && data == x\n{ \n data := x;\n weight := |x|;\n left := null;\n right := null;\n Contents := x;\n Repr := {this};\n} \n\npredicate isTerminal()\n reads this, this.left, this.right\n{ left == null && right == null }\n\nmethod report(i: nat, j: nat) returns (s: string)\n requires 0 <= i <= j <= |this.Contents|\n requires Valid()\n ensures s == this.Contents[i..j]\n{\n if i == j {\n s := \"\";\n } else {\n if this.left == null && this.right == null {\n s := data[i..j];\n } else {\n if (j <= this.weight) {\n var s' := this.left.report(i, j);\n s := s';\n } else if (this.weight <= i) {\n var s' := this.right.report(i - this.weight, j - this.weight);\n s := s';\n } else {\n // removing this assertion causes error\n var s1 := this.left.report(i, this.weight);\n var s2 := this.right.report(0, j - this.weight);\n s := s1 + s2;\n }\n }\n }\n}\n\nmethod toString() returns (s: string)\n requires Valid()\n ensures s == Contents\n{\n s := report(0, this.length());\n}\n\nmethod getCharAtIndex(index: nat) returns (c: char)\n requires Valid() && 0 <= index < |Contents|\n ensures c == Contents[index]\n{\n var nTemp := this;\n var i := index;\n while (!nTemp.isTerminal()) \n {\n if (i < nTemp.weight) {\n nTemp := nTemp.left;\n } else {\n i := i - nTemp.weight;\n nTemp := nTemp.right;\n }\n }\n // Have reached the terminal node with index i\n c := nTemp.data[i];\n}\n\nstatic method concat(n1: Rope?, n2: Rope?) returns (n: Rope?) \n requires (n1 != null) ==> n1.Valid()\n requires (n2 != null) ==> n2.Valid()\n requires (n1 != null && n2 != null) ==> (n1.Repr !! n2.Repr)\n\n ensures (n1 != null || n2 != null) <==> n != null && n.Valid()\n ensures (n1 == null && n2 == null) <==> n == null\n ensures (n1 == null && n2 != null)\n ==> n == n2 && n != null && n.Valid() && n.Contents == n2.Contents\n ensures (n1 != null && n2 == null)\n ==> n == n1 && n != null && n.Valid() && n.Contents == n1.Contents\n ensures (n1 != null && n2 != null)\n ==> n != null && n.Valid()\n && n.left == n1 && n.right == n2\n && n.Contents == n1.Contents + n2.Contents\n && fresh(n.Repr - n1.Repr - n2.Repr)\n{\n if (n1 == null) {\n n := n2;\n } else if (n2 == null) {\n n := n1;\n } else {\n n := new Rope.Terminal(\"placeholder\");\n n.left := n1;\n n.right := n2;\n n.data := \"\";\n\n var nTemp := n1;\n var w := 0;\n ghost var nodesTraversed : set := {};\n\n while (nTemp.right != null)\n ==> w + nTemp.weight + |nTemp.right.Contents| == |n1.Contents| \n {\n w := w + nTemp.weight;\n if (nTemp.left != null) {\n nodesTraversed := nodesTraversed + nTemp.left.Repr + {nTemp};\n } else {\n nodesTraversed := nodesTraversed + {nTemp};\n }\n nTemp := nTemp.right;\n }\n w := w + nTemp.weight;\n if (nTemp.left != null) {\n nodesTraversed := nodesTraversed + nTemp.left.Repr + {nTemp};\n } else {\n nodesTraversed := nodesTraversed + {nTemp};\n }\n n.weight := w;\n n.Contents := n1.Contents + n2.Contents;\n n.Repr := {n} + n1.Repr + n2.Repr;\n } \n} \n\n\n/**\n Dafny needs help to guess that in our definition, every rope must\n have non-empty Contents, otherwise it is represented by [null].\n\n The lemma contentSizeGtZero(n) is thus important to prove the\n postcondition of this method, in the two places where the lemma is\n invoked.\n*/\nstatic method split(n: Rope, index: nat) returns (n1: Rope?, n2: Rope?) \n requires n.Valid() && 0 <= index <= |n.Contents|\n ensures index == 0\n ==> n1 == null && n2 != null && n2.Valid()\n && n2.Contents == n.Contents && fresh(n2.Repr - n.Repr)\n ensures index == |n.Contents|\n ==> n2 == null && n1 != null && n1.Valid()\n && n1.Contents == n.Contents && fresh(n1.Repr - n.Repr)\n ensures 0 < index < |n.Contents|\n ==> n1 != null && n1.Valid() && n2 != null && n2.Valid()\n && n1.Contents == n.Contents[..index]\n && n2.Contents == n.Contents[index..]\n && n1.Repr !! n2.Repr\n && fresh(n1.Repr - n.Repr) && fresh(n2.Repr - n.Repr)\n{\n if (index == 0) {\n n1 := null;\n n2 := n;\n n.contentSizeGtZero();\n // assert index != |n.Contents|;\n } else if (index < n.weight) {\n if (n.left != null) {\n var s1, s2 := split(n.left, index);\n n1 := s1;\n n2 := concat(s2, n.right);\n } else {\n // terminal node\n if (index == 0) {\n n1 := null;\n n2 := n;\n } else {\n n1 := new Rope.Terminal(n.data[..index]);\n n2 := new Rope.Terminal(n.data[index..]);\n }\n }\n } else if (index > n.weight) {\n var s1, s2 := split(n.right, index - n.weight);\n n1 := concat(n.left, s1);\n n2 := s2;\n } else {\n // since [n.weight == index != 0], it means that [n] cannot be a\n // non-terminal node with [left == null].\n if (n.left != null && n.right == null) {\n n1 := n.left;\n n2 := null;\n } else if (n.left != null && n.right != null) {\n n.right.contentSizeGtZero();\n // assert index != |n.Contents|;\n n1 := n.left;\n n2 := n.right;\n } else {\n n1 := n;\n n2 := null;\n }\n }\n}\n\nstatic method insert(n1: Rope, n2: Rope, index: nat) returns (n: Rope)\n requires n1.Valid() && n2.Valid() && n1.Repr !! n2.Repr\n requires 0 <= index < |n1.Contents|\n ensures n.Valid()\n && n.Contents ==\n n1.Contents[..index] + n2.Contents + n1.Contents[index..]\n && fresh(n.Repr - n1.Repr - n2.Repr)\n{\n var n1BeforeIndex, n1AfterIndex := split(n1, index);\n var firstPart := concat(n1BeforeIndex, n2);\n n := concat(firstPart, n1AfterIndex);\n}\n\nstatic method delete(n: Rope, i: nat, j: nat) returns (m: Rope?)\n requires n.Valid()\n requires 0 <= i < j <= |n.Contents|\n ensures (i == 0 && j == |n.Contents|) <==> m == null\n ensures m != null ==>\n m.Valid() &&\n m.Contents == n.Contents[..i] + n.Contents[j..] &&\n fresh(m.Repr - n.Repr)\n{\n var l1, l2 := split(n, i);\n var r1, r2 := split(l2, j - i);\n m := concat(l1, r2);\n}\n\nstatic method substring(n: Rope, i: nat, j: nat) returns (m: Rope?)\n requires n.Valid()\n requires 0 <= i < j <= |n.Contents|\n ensures (i == j) <==> m == null\n ensures m != null ==>\n m.Valid() &&\n m.Contents == n.Contents[i..j] &&\n fresh(m.Repr - n.Repr)\n{\n var l1, l2 := split(n, i);\n var r1, r2 := split(l2, j - i);\n m := r1;\n}\n\n}\n// End of Rope Class\n}\n// End of Rope Module\n" }, { "test_ID": "492", "test_file": "dafny-sandbox_tmp_tmp3tu2bu8a_Stlc.dfy", "ground_truth": "\ufeff// Proving type safety of a Simply Typed Lambda-Calculus in Dafny\n// adapted from Coq (http://www.cis.upenn.edu/~bcpierce/sf/Stlc.html)\n\n/// Utilities\n\n// ... handy for partial functions\ndatatype option = None | Some(get: A)\n\n/// -----\n/// Model\n/// -----\n\n/// Syntax\n\n// Types\ndatatype ty = TBase // (opaque base type)\n | TArrow(T1: ty, T2: ty) // T1 => T2\n/*BOOL?\n | TBool // (base type for booleans)\n?BOOL*/\n/*NAT?\n | TNat // (base type for naturals)\n?NAT*/\n/*REC?\n | TVar(id: int) | TRec(X: nat, T: ty)// (iso-recursive types)\n?REC*/\n\n// Terms\ndatatype tm = tvar(id: int) // x (variable)\n | tapp(f: tm, arg: tm) // t t (application)\n | tabs(x: int, T: ty, body: tm) // \\x:T.t (abstraction)\n/*BOOL?\n | ttrue | tfalse // true, false (boolean values)\n | tif(c: tm, a: tm, b: tm) // if t then t else t (if expression)\n?BOOL*/\n/*NAT?\n | tzero | tsucc(p: tm) | tprev(n: tm)// (naturals)\n/*BOOL?\n | teq(n1: tm, n2: tm) // (equality on naturals)\n?BOOL*/\n?NAT*/\n/*REC?\n | tfold(Tf: ty, tf: tm) | tunfold(tu: tm)// (iso-recursive terms)\n?REC*/\n\n/// Operational Semantics\n\n// Values\npredicate value(t: tm)\n{\n t.tabs?\n/*BOOL?\n || t.ttrue? || t.tfalse?\n?BOOL*/\n/*NAT?\n || peano(t)\n?NAT*/\n/*REC?\n || (t.tfold? && value(t.tf))\n?REC*/\n}\n\n/*NAT?\npredicate peano(t: tm)\n{\n t.tzero? || (t.tsucc? && peano(t.p))\n}\n?NAT*/\n\n// Free Variables and Substitution\n\nfunction fv(t: tm): set //of free variables of t\n{\n match t\n // interesting cases...\n case tvar(id) => {id}\n case tabs(x, T, body) => fv(body)-{x}//x is bound\n // congruent cases...\n case tapp(f, arg) => fv(f)+fv(arg)\n/*BOOL?\n case tif(c, a, b) => fv(a)+fv(b)+fv(c)\n case ttrue => {}\n case tfalse => {}\n?BOOL*/\n/*NAT?\n case tzero => {}\n case tsucc(p) => fv(p)\n case tprev(n) => fv(n)\n/*BOOL?\n case teq(n1, n2) => fv(n1)+fv(n2)\n?BOOL*/\n?NAT*/\n/*REC?\n case tfold(T, t1) => fv(t1)\n case tunfold(t1) => fv(t1)\n?REC*/\n}\n\nfunction subst(x: int, s: tm, t: tm): tm //[x -> s]t\n{\n match t\n // interesting cases...\n case tvar(x') => if x==x' then s else t\n // N.B. only capture-avoiding if s is closed...\n case tabs(x', T, t1) => tabs(x', T, if x==x' then t1 else subst(x, s, t1))\n // congruent cases...\n case tapp(t1, t2) => tapp(subst(x, s, t1), subst(x, s, t2))\n/*BOOL?\n case ttrue => ttrue\n case tfalse => tfalse\n case tif(t1, t2, t3) => tif(subst(x, s, t1), subst(x, s, t2), subst(x, s, t3))\n?BOOL*/\n/*NAT?\n case tzero => tzero\n case tsucc(p) => tsucc(subst(x, s, p))\n case tprev(n) => tprev(subst(x, s, n))\n/*BOOL?\n case teq(n1, n2) => teq(subst(x, s, n1), subst(x, s, n2))\n?BOOL*/\n?NAT*/\n/*REC?\n case tfold(T, t1) => tfold(T, subst(x, s, t1))\n case tunfold(t1) => tunfold(subst(x, s, t1))\n?REC*/\n}\n\n/*REC?\nfunction ty_fv(T: ty): set //of free type variables of T\n{\n match T\n case TVar(X) => {X}\n case TRec(X, T1) => ty_fv(T1)-{X}\n case TArrow(T1, T2) => ty_fv(T1)+ty_fv(T2)\n case TBase => {}\n/*BOOL?\n case TBool => {}\n?BOOL*/\n/*NAT?\n case TNat => {}\n?NAT*/\n}\n\nfunction tsubst(X: int, S: ty, T: ty): ty\n{\n match T\n case TVar(X') => if X==X' then S else T\n case TRec(X', T1) => TRec(X', if X==X' then T1 else tsubst(X, S, T1))\n case TArrow(T1, T2) => TArrow(tsubst(X, S, T1), tsubst(X, S, T2))\n case TBase => TBase\n/*BOOL?\n case TBool => TBool\n?BOOL*/\n/*NAT?\n case TNat => TNat\n?NAT*/\n}\n\npredicate ty_closed(T: ty)\n{\n forall x :: x !in ty_fv(T)\n}\n?REC*/\n\n// Reduction\nfunction step(t: tm): option\n{\n /* AppAbs */ if (t.tapp? && t.f.tabs? && value(t.arg)) then\n Some(subst(t.f.x, t.arg, t.f.body))\n /* App1 */ else if (t.tapp? && step(t.f).Some?) then\n Some(tapp(step(t.f).get, t.arg))\n /* App2 */ else if (t.tapp? && value(t.f) && step(t.arg).Some?) then\n Some(tapp(t.f, step(t.arg).get))\n/*BOOL?\n /* IfTrue */ else if (t.tif? && t.c == ttrue) then\n Some(t.a)\n /* IfFalse */ else if (t.tif? && t.c == tfalse) then\n Some(t.b)\n /* If */ else if (t.tif? && step(t.c).Some?) then\n Some(tif(step(t.c).get, t.a, t.b))\n?BOOL*/\n/*NAT?\n /* Prev0 */\n else if (t.tprev? && t.n.tzero?) then\n Some(tzero)\n /* PrevSucc */ else if (t.tprev? && peano(t.n) && t.n.tsucc?) then\n Some(t.n.p)\n /* Prev */ else if (t.tprev? && step(t.n).Some?) then\n Some(tprev(step(t.n).get))\n /* Succ */ else if (t.tsucc? && step(t.p).Some?) then\n Some(tsucc(step(t.p).get))\n/*BOOL?\n /* EqTrue0 */ else if (t.teq? && t.n1.tzero? && t.n2.tzero?) then\n Some(ttrue)\n /* EqFalse1 */ else if (t.teq? && t.n1.tsucc? && peano(t.n1) && t.n2.tzero?) then\n Some(tfalse)\n /* EqFalse2 */ else if (t.teq? && t.n1.tzero? && t.n2.tsucc? && peano(t.n2)) then\n Some(tfalse)\n /* EqRec */ else if (t.teq? && t.n1.tsucc? && t.n2.tsucc? && peano(t.n1) && peano(t.n2)) then\n Some(teq(t.n1.p, t.n2.p))\n /* Eq1 */ else if (t.teq? && step(t.n1).Some?) then\n Some(teq(step(t.n1).get, t.n2))\n /* Eq2 */ else if (t.teq? && peano(t.n1) && step(t.n2).Some?) then\n Some(teq(t.n1, step(t.n2).get))\n?BOOL*/\n?NAT*/\n/*REC?\n /* UnfoldFold */ else if (t.tunfold? && t.tu.tfold? && value(t.tu.tf)) then Some(t.tu.tf)\n /* Fold */ else if (t.tfold? && step(t.tf).Some?) then Some(tfold(t.Tf, step(t.tf).get))\n /* Unfold */ else if (t.tunfold? && step(t.tu).Some?) then Some(tunfold(step(t.tu).get))\n?REC*/\n else None\n}\n\n// Multistep reduction:\n// The term t reduces to the term t' in n or less number of steps.\npredicate reduces_to(t: tm, t': tm, n: nat)\n decreases n;\n{\n t == t' || (n > 0 && step(t).Some? && reduces_to(step(t).get, t', n-1))\n}\n\n// Examples\nlemma lemma_step_example1(n: nat)\n requires n > 0;\n // (\\x:B=>B.x) (\\x:B.x) reduces to (\\x:B.x)\n ensures reduces_to(tapp(tabs(0, TArrow(TBase, TBase), tvar(0)), tabs(0, TBase, tvar(0))),\n tabs(0, TBase, tvar(0)), n);\n{\n}\n\n\n/// Typing\n\n// A context is a partial map from variable names to types.\nfunction find(c: map, x: int): option\n{\n if (x in c) then Some(c[x]) else None\n}\nfunction extend(x: int, T: ty, c: map): map\n{\n c[x:=T]\n}\n\n// Typing Relation\nfunction has_type(c: map, t: tm): option\n decreases t;\n{\n match t\n /* Var */ case tvar(id) => find(c, id)\n /* Abs */ case tabs(x, T, body) =>\n var ty_body := has_type(extend(x, T, c), body);\n if (ty_body.Some?) then\n Some(TArrow(T, ty_body.get)) else None\n /* App */ case tapp(f, arg) =>\n var ty_f := has_type(c, f);\n var ty_arg := has_type(c, arg);\n if (ty_f.Some? && ty_arg.Some?) then\n if ty_f.get.TArrow? && ty_f.get.T1 == ty_arg.get then\n Some(ty_f.get.T2) else None else None\n/*BOOL?\n /* True */ case ttrue => Some(TBool)\n /* False */ case tfalse => Some(TBool)\n /* If */ case tif(cond, a, b) =>\n var ty_c := has_type(c, cond);\n var ty_a := has_type(c, a);\n var ty_b := has_type(c, b);\n if (ty_c.Some? && ty_a.Some? && ty_b.Some?) then\n if ty_c.get == TBool && ty_a.get == ty_b.get then\n ty_a\n else None else None\n?BOOL*/\n/*NAT?\n /* Zero */ case tzero => Some(TNat)\n /* Prev */ case tprev(n) =>\n var ty_n := has_type(c, n);\n if (ty_n.Some?) then\n if ty_n.get == TNat then\n Some(TNat) else None else None\n /* Succ */ case tsucc(p) =>\n var ty_p := has_type(c, p);\n if (ty_p.Some?) then\n if ty_p.get == TNat then\n Some(TNat) else None else None\n/*BOOL?\n /* Eq */ case teq(n1, n2) =>\n var ty_n1 := has_type(c, n1);\n var ty_n2 := has_type(c, n2);\n if (ty_n1.Some? && ty_n2.Some?) then\n if ty_n1.get == TNat && ty_n2.get == TNat then\n Some(TBool) else None else None\n?BOOL*/\n?NAT*/\n/*REC?\n /* Fold */ case tfold(U, t1) =>\n var ty_t1 := if (ty_closed(U)) then has_type(c, t1) else None;\n if (ty_t1.Some?) then\n if U.TRec? && ty_t1.get==tsubst(U.X, U, U.T) then\n Some(U) else None else None\n /* Unfold */ case tunfold(t1) =>\n var ty_t1 := has_type(c, t1);\n if ty_t1.Some? then\n var U := ty_t1.get;\n if U.TRec? then\n Some(tsubst(U.X, U, U.T)) else None else None\n?REC*/\n}\n\n// Examples\n\nlemma example_typing_1()\n ensures has_type(map[], tabs(0, TBase, tvar(0))) == Some(TArrow(TBase, TBase));\n{\n}\n\nlemma example_typing_2()\n ensures has_type(map[], tabs(0, TBase, tabs(1, TArrow(TBase, TBase), tapp(tvar(1), tapp(tvar(1), tvar(0)))))) ==\n Some(TArrow(TBase, TArrow(TArrow(TBase, TBase), TBase)));\n{\n var c := extend(1, TArrow(TBase, TBase), extend(0, TBase, map[]));\n assert find(c, 0) == Some(TBase);\n assert has_type(c, tvar(0)) == Some(TBase);\n assert has_type(c, tvar(1)) == Some(TArrow(TBase, TBase));\n assert has_type(c, tapp(tvar(1), tapp(tvar(1), tvar(0)))) == Some(TBase);\n}\n\nlemma nonexample_typing_1()\n ensures has_type(map[], tabs(0, TBase, tabs(1, TBase, tapp(tvar(0), tvar(1))))) == None;\n{\n var c := extend(1, TBase, extend(0, TBase, map[]));\n assert find(c, 0) == Some(TBase);\n assert has_type(c, tapp(tvar(0), tvar(1))) == None;\n}\n\nlemma nonexample_typing_3(S: ty, T: ty)\n ensures has_type(map[], tabs(0, S, tapp(tvar(0), tvar(0)))) != Some(T);\n{\n var c := extend(0, S, map[]);\n assert has_type(c, tapp(tvar(0), tvar(0))) == None;\n}\n\n/*BOOL?\nlemma example_typing_bool()\n ensures has_type(map[], tabs(0, TBase, tabs(1, TBase, tabs(2, TBool, tif(tvar(2), tvar(0), tvar(1)))))) ==\n Some(TArrow(TBase, TArrow(TBase, TArrow(TBool, TBase))));\n{\n var c0 := extend(0, TBase, map[]);\n var c1 := extend(1, TBase, c0);\n var c2 := extend(2, TBool, c1);\n assert has_type(c2, tvar(2)) == Some(TBool);\n assert has_type(c2, tvar(1)) == Some(TBase);\n assert has_type(c2, tvar(0)) == Some(TBase);\n assert has_type(c2, tif(tvar(2), tvar(0), tvar(1))) == Some(TBase);\n assert has_type(c1, tabs(2, TBool, tif(tvar(2), tvar(0), tvar(1)))) == Some(TArrow(TBool, TBase));\n assert has_type(c0, tabs(1, TBase, tabs(2, TBool, tif(tvar(2), tvar(0), tvar(1))))) == Some(TArrow(TBase, TArrow(TBool, TBase)));\n}\n?BOOL*/\n\n/*NAT?\nlemma example_typing_nat()\n ensures has_type(map[], tabs(0, TNat, tprev(tvar(0)))) == Some(TArrow(TNat, TNat));\n{\n var c := extend(0, TNat, map[]);\n assert has_type(c, tprev(tvar(0)))==Some(TNat);\n}\n?NAT*/\n\n/*REC?\n// TODO\nlemma example_typing_rec()\n // \u2205 \u0005|- fold\u00b5T. T\u2192\u03b1(\u03bbx : \u00b5T. T \u2192 \u03b1. (unfold x) x) : \u00b5T. T \u2192 \u03b1\n 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))))) ==\n Some(TRec(0, TArrow(TVar(0), TBase)));\n{\n var R := TRec(0, TArrow(TVar(0), TBase));\n var c := extend(0, R, map[]);\n //{x : \u00b5T. T \u2192 \u03b1} \u0005 x : \u00b5T. T \u2192 \u03b1\n assert has_type(c, tvar(0)) == Some(R);\n //{x : \u00b5T. T \u2192 \u03b1} \u0005 (unfold x):(\u00b5T. T \u2192 \u03b1) \u2192 \u03b1 {x : \u00b5T. T \u2192 \u03b1} \u0005 x : \u00b5T. T \u2192 \u03b1\n assert tsubst(R.X, R, R.T) == TArrow(R, TBase);\n assert has_type(c, tunfold(tvar(0))) == Some(TArrow(R, TBase));\n //{x : \u00b5T. T \u2192 \u03b1} \u0005 ( (unfold x) x)) : \u03b1\n assert has_type(c, tapp(tunfold(tvar(0)), tvar(0))) == Some(TBase);\n //\u2205 \u0005 (\u03bbx : \u00b5T. T \u2192 \u03b1. (unfold x) x)) :(\u00b5T. T \u2192 \u03b1) \u2192 \u03b1\n assert has_type(map[], tabs(0, R, tapp(tunfold(tvar(0)), tvar(0)))) == Some(TArrow(R, TBase));\n assert ty_fv(R)==ty_fv(TArrow(TVar(0),TBase))-{0}=={};\n assert ty_closed(R);\n 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?;\n}\n?REC*/\n\n/// -----------------------\n/// Type-Safety Properties\n/// -----------------------\n\n// Progress:\n// A well-typed term is either a value or it can step.\nlemma theorem_progress(t: tm)\n requires has_type(map[], t).Some?;\n ensures value(t) || step(t).Some?;\n{\n}\n\n// Towards preservation and the substitution lemma\n\n// If x is free in t and t is well-typed in some context,\n// then this context must contain x.\nlemma {:induction c, t} lemma_free_in_context(c: map, x: int, t: tm)\n requires x in fv(t);\n requires has_type(c, t).Some?;\n ensures find(c, x).Some?;\n decreases t;\n{\n}\n\n// A closed term does not contain any free variables.\n// N.B. We're only interested in proving type soundness of closed terms.\npredicate closed(t: tm)\n{\n forall x :: x !in fv(t)\n}\n\n// If a term can be well-typed in an empty context,\n// then it is closed.\nlemma corollary_typable_empty__closed(t: tm)\n requires has_type(map[], t).Some?;\n ensures closed(t);\n{\n forall (x:int) ensures x !in fv(t);\n {\n if (x in fv(t)) {\n lemma_free_in_context(map[], x, t);\n assert false;\n }\n }\n}\n\n// If a term t is well-typed in context c,\n// and context c' agrees with c on all free variables of t,\n// then the term t is well-typed in context c',\n// with the same type as in context c.\nlemma {:induction t} lemma_context_invariance(c: map, c': map, t: tm)\n requires has_type(c, t).Some?;\n requires forall x: int :: x in fv(t) ==> find(c, x) == find(c', x);\n ensures has_type(c, t) == has_type(c', t);\n decreases t;\n{\n if (t.tabs?) {\n assert fv(t.body) == fv(t) || fv(t.body) == fv(t) + {t.x};\n lemma_context_invariance(extend(t.x, t.T, c), extend(t.x, t.T, c'), t.body);\n }\n}\n\n// Substitution preserves typing:\n// If s has type S in an empty context,\n// and t has type T in a context extended with x having type S,\n// then [x -> s]t has type T as well.\nlemma lemma_substitution_preserves_typing(c: map, x: int, s: tm, t: tm)\n requires has_type(map[], s).Some?;\n requires has_type(extend(x, has_type(map[], s).get, c), t).Some?;\n ensures has_type(c, subst(x, s, t)) == has_type(extend(x, has_type(map[], s).get, c), t);\n decreases t;\n{\n var S := has_type(map[], s).get;\n var cs := extend(x, S, c);\n var T := has_type(cs, t).get;\n\n if (t.tvar?) {\n if (t.id==x) {\n assert T == S;\n corollary_typable_empty__closed(s);\n lemma_context_invariance(map[], c, s);\n }\n }\n if (t.tabs?) {\n if (t.x==x) {\n lemma_context_invariance(cs, c, t);\n } else {\n var cx := extend(t.x, t.T, c);\n var csx := extend(x, S, cx);\n var cxs := extend(t.x, t.T, cs);\n lemma_context_invariance(cxs, csx, t.body);\n lemma_substitution_preserves_typing(cx, x, s, t.body);\n }\n }\n}\n\n\n// Preservation:\n// A well-type term which steps preserves its type.\nlemma theorem_preservation(t: tm)\n requires has_type(map[], t).Some?;\n requires step(t).Some?;\n ensures has_type(map[], step(t).get) == has_type(map[], t);\n{\n if (t.tapp? && value(t.f) && value(t.arg)) {\n lemma_substitution_preserves_typing(map[], t.f.x, t.arg, t.f.body);\n }\n}\n\n// A normal form cannot step.\npredicate normal_form(t: tm)\n{\n step(t).None?\n}\n\n// A stuck term is a normal form that is not a value.\npredicate stuck(t: tm)\n{\n normal_form(t) && !value(t)\n}\n\n// Type soundness:\n// A well-typed term cannot be stuck.\nlemma corollary_soundness(t: tm, t': tm, T: ty, n: nat)\n requires has_type(map[], t) == Some(T);\n requires reduces_to(t, t', n);\n ensures !stuck(t');\n decreases n;\n{\n theorem_progress(t);\n if (t != t') {\n theorem_preservation(t);\n corollary_soundness(step(t).get, t', T, n-1);\n }\n}\n\n/// QED\n", "hints_removed": "\ufeff// Proving type safety of a Simply Typed Lambda-Calculus in Dafny\n// adapted from Coq (http://www.cis.upenn.edu/~bcpierce/sf/Stlc.html)\n\n/// Utilities\n\n// ... handy for partial functions\ndatatype option = None | Some(get: A)\n\n/// -----\n/// Model\n/// -----\n\n/// Syntax\n\n// Types\ndatatype ty = TBase // (opaque base type)\n | TArrow(T1: ty, T2: ty) // T1 => T2\n/*BOOL?\n | TBool // (base type for booleans)\n?BOOL*/\n/*NAT?\n | TNat // (base type for naturals)\n?NAT*/\n/*REC?\n | TVar(id: int) | TRec(X: nat, T: ty)// (iso-recursive types)\n?REC*/\n\n// Terms\ndatatype tm = tvar(id: int) // x (variable)\n | tapp(f: tm, arg: tm) // t t (application)\n | tabs(x: int, T: ty, body: tm) // \\x:T.t (abstraction)\n/*BOOL?\n | ttrue | tfalse // true, false (boolean values)\n | tif(c: tm, a: tm, b: tm) // if t then t else t (if expression)\n?BOOL*/\n/*NAT?\n | tzero | tsucc(p: tm) | tprev(n: tm)// (naturals)\n/*BOOL?\n | teq(n1: tm, n2: tm) // (equality on naturals)\n?BOOL*/\n?NAT*/\n/*REC?\n | tfold(Tf: ty, tf: tm) | tunfold(tu: tm)// (iso-recursive terms)\n?REC*/\n\n/// Operational Semantics\n\n// Values\npredicate value(t: tm)\n{\n t.tabs?\n/*BOOL?\n || t.ttrue? || t.tfalse?\n?BOOL*/\n/*NAT?\n || peano(t)\n?NAT*/\n/*REC?\n || (t.tfold? && value(t.tf))\n?REC*/\n}\n\n/*NAT?\npredicate peano(t: tm)\n{\n t.tzero? || (t.tsucc? && peano(t.p))\n}\n?NAT*/\n\n// Free Variables and Substitution\n\nfunction fv(t: tm): set //of free variables of t\n{\n match t\n // interesting cases...\n case tvar(id) => {id}\n case tabs(x, T, body) => fv(body)-{x}//x is bound\n // congruent cases...\n case tapp(f, arg) => fv(f)+fv(arg)\n/*BOOL?\n case tif(c, a, b) => fv(a)+fv(b)+fv(c)\n case ttrue => {}\n case tfalse => {}\n?BOOL*/\n/*NAT?\n case tzero => {}\n case tsucc(p) => fv(p)\n case tprev(n) => fv(n)\n/*BOOL?\n case teq(n1, n2) => fv(n1)+fv(n2)\n?BOOL*/\n?NAT*/\n/*REC?\n case tfold(T, t1) => fv(t1)\n case tunfold(t1) => fv(t1)\n?REC*/\n}\n\nfunction subst(x: int, s: tm, t: tm): tm //[x -> s]t\n{\n match t\n // interesting cases...\n case tvar(x') => if x==x' then s else t\n // N.B. only capture-avoiding if s is closed...\n case tabs(x', T, t1) => tabs(x', T, if x==x' then t1 else subst(x, s, t1))\n // congruent cases...\n case tapp(t1, t2) => tapp(subst(x, s, t1), subst(x, s, t2))\n/*BOOL?\n case ttrue => ttrue\n case tfalse => tfalse\n case tif(t1, t2, t3) => tif(subst(x, s, t1), subst(x, s, t2), subst(x, s, t3))\n?BOOL*/\n/*NAT?\n case tzero => tzero\n case tsucc(p) => tsucc(subst(x, s, p))\n case tprev(n) => tprev(subst(x, s, n))\n/*BOOL?\n case teq(n1, n2) => teq(subst(x, s, n1), subst(x, s, n2))\n?BOOL*/\n?NAT*/\n/*REC?\n case tfold(T, t1) => tfold(T, subst(x, s, t1))\n case tunfold(t1) => tunfold(subst(x, s, t1))\n?REC*/\n}\n\n/*REC?\nfunction ty_fv(T: ty): set //of free type variables of T\n{\n match T\n case TVar(X) => {X}\n case TRec(X, T1) => ty_fv(T1)-{X}\n case TArrow(T1, T2) => ty_fv(T1)+ty_fv(T2)\n case TBase => {}\n/*BOOL?\n case TBool => {}\n?BOOL*/\n/*NAT?\n case TNat => {}\n?NAT*/\n}\n\nfunction tsubst(X: int, S: ty, T: ty): ty\n{\n match T\n case TVar(X') => if X==X' then S else T\n case TRec(X', T1) => TRec(X', if X==X' then T1 else tsubst(X, S, T1))\n case TArrow(T1, T2) => TArrow(tsubst(X, S, T1), tsubst(X, S, T2))\n case TBase => TBase\n/*BOOL?\n case TBool => TBool\n?BOOL*/\n/*NAT?\n case TNat => TNat\n?NAT*/\n}\n\npredicate ty_closed(T: ty)\n{\n forall x :: x !in ty_fv(T)\n}\n?REC*/\n\n// Reduction\nfunction step(t: tm): option\n{\n /* AppAbs */ if (t.tapp? && t.f.tabs? && value(t.arg)) then\n Some(subst(t.f.x, t.arg, t.f.body))\n /* App1 */ else if (t.tapp? && step(t.f).Some?) then\n Some(tapp(step(t.f).get, t.arg))\n /* App2 */ else if (t.tapp? && value(t.f) && step(t.arg).Some?) then\n Some(tapp(t.f, step(t.arg).get))\n/*BOOL?\n /* IfTrue */ else if (t.tif? && t.c == ttrue) then\n Some(t.a)\n /* IfFalse */ else if (t.tif? && t.c == tfalse) then\n Some(t.b)\n /* If */ else if (t.tif? && step(t.c).Some?) then\n Some(tif(step(t.c).get, t.a, t.b))\n?BOOL*/\n/*NAT?\n /* Prev0 */\n else if (t.tprev? && t.n.tzero?) then\n Some(tzero)\n /* PrevSucc */ else if (t.tprev? && peano(t.n) && t.n.tsucc?) then\n Some(t.n.p)\n /* Prev */ else if (t.tprev? && step(t.n).Some?) then\n Some(tprev(step(t.n).get))\n /* Succ */ else if (t.tsucc? && step(t.p).Some?) then\n Some(tsucc(step(t.p).get))\n/*BOOL?\n /* EqTrue0 */ else if (t.teq? && t.n1.tzero? && t.n2.tzero?) then\n Some(ttrue)\n /* EqFalse1 */ else if (t.teq? && t.n1.tsucc? && peano(t.n1) && t.n2.tzero?) then\n Some(tfalse)\n /* EqFalse2 */ else if (t.teq? && t.n1.tzero? && t.n2.tsucc? && peano(t.n2)) then\n Some(tfalse)\n /* EqRec */ else if (t.teq? && t.n1.tsucc? && t.n2.tsucc? && peano(t.n1) && peano(t.n2)) then\n Some(teq(t.n1.p, t.n2.p))\n /* Eq1 */ else if (t.teq? && step(t.n1).Some?) then\n Some(teq(step(t.n1).get, t.n2))\n /* Eq2 */ else if (t.teq? && peano(t.n1) && step(t.n2).Some?) then\n Some(teq(t.n1, step(t.n2).get))\n?BOOL*/\n?NAT*/\n/*REC?\n /* UnfoldFold */ else if (t.tunfold? && t.tu.tfold? && value(t.tu.tf)) then Some(t.tu.tf)\n /* Fold */ else if (t.tfold? && step(t.tf).Some?) then Some(tfold(t.Tf, step(t.tf).get))\n /* Unfold */ else if (t.tunfold? && step(t.tu).Some?) then Some(tunfold(step(t.tu).get))\n?REC*/\n else None\n}\n\n// Multistep reduction:\n// The term t reduces to the term t' in n or less number of steps.\npredicate reduces_to(t: tm, t': tm, n: nat)\n{\n t == t' || (n > 0 && step(t).Some? && reduces_to(step(t).get, t', n-1))\n}\n\n// Examples\nlemma lemma_step_example1(n: nat)\n requires n > 0;\n // (\\x:B=>B.x) (\\x:B.x) reduces to (\\x:B.x)\n ensures reduces_to(tapp(tabs(0, TArrow(TBase, TBase), tvar(0)), tabs(0, TBase, tvar(0))),\n tabs(0, TBase, tvar(0)), n);\n{\n}\n\n\n/// Typing\n\n// A context is a partial map from variable names to types.\nfunction find(c: map, x: int): option\n{\n if (x in c) then Some(c[x]) else None\n}\nfunction extend(x: int, T: ty, c: map): map\n{\n c[x:=T]\n}\n\n// Typing Relation\nfunction has_type(c: map, t: tm): option\n{\n match t\n /* Var */ case tvar(id) => find(c, id)\n /* Abs */ case tabs(x, T, body) =>\n var ty_body := has_type(extend(x, T, c), body);\n if (ty_body.Some?) then\n Some(TArrow(T, ty_body.get)) else None\n /* App */ case tapp(f, arg) =>\n var ty_f := has_type(c, f);\n var ty_arg := has_type(c, arg);\n if (ty_f.Some? && ty_arg.Some?) then\n if ty_f.get.TArrow? && ty_f.get.T1 == ty_arg.get then\n Some(ty_f.get.T2) else None else None\n/*BOOL?\n /* True */ case ttrue => Some(TBool)\n /* False */ case tfalse => Some(TBool)\n /* If */ case tif(cond, a, b) =>\n var ty_c := has_type(c, cond);\n var ty_a := has_type(c, a);\n var ty_b := has_type(c, b);\n if (ty_c.Some? && ty_a.Some? && ty_b.Some?) then\n if ty_c.get == TBool && ty_a.get == ty_b.get then\n ty_a\n else None else None\n?BOOL*/\n/*NAT?\n /* Zero */ case tzero => Some(TNat)\n /* Prev */ case tprev(n) =>\n var ty_n := has_type(c, n);\n if (ty_n.Some?) then\n if ty_n.get == TNat then\n Some(TNat) else None else None\n /* Succ */ case tsucc(p) =>\n var ty_p := has_type(c, p);\n if (ty_p.Some?) then\n if ty_p.get == TNat then\n Some(TNat) else None else None\n/*BOOL?\n /* Eq */ case teq(n1, n2) =>\n var ty_n1 := has_type(c, n1);\n var ty_n2 := has_type(c, n2);\n if (ty_n1.Some? && ty_n2.Some?) then\n if ty_n1.get == TNat && ty_n2.get == TNat then\n Some(TBool) else None else None\n?BOOL*/\n?NAT*/\n/*REC?\n /* Fold */ case tfold(U, t1) =>\n var ty_t1 := if (ty_closed(U)) then has_type(c, t1) else None;\n if (ty_t1.Some?) then\n if U.TRec? && ty_t1.get==tsubst(U.X, U, U.T) then\n Some(U) else None else None\n /* Unfold */ case tunfold(t1) =>\n var ty_t1 := has_type(c, t1);\n if ty_t1.Some? then\n var U := ty_t1.get;\n if U.TRec? then\n Some(tsubst(U.X, U, U.T)) else None else None\n?REC*/\n}\n\n// Examples\n\nlemma example_typing_1()\n ensures has_type(map[], tabs(0, TBase, tvar(0))) == Some(TArrow(TBase, TBase));\n{\n}\n\nlemma example_typing_2()\n ensures has_type(map[], tabs(0, TBase, tabs(1, TArrow(TBase, TBase), tapp(tvar(1), tapp(tvar(1), tvar(0)))))) ==\n Some(TArrow(TBase, TArrow(TArrow(TBase, TBase), TBase)));\n{\n var c := extend(1, TArrow(TBase, TBase), extend(0, TBase, map[]));\n}\n\nlemma nonexample_typing_1()\n ensures has_type(map[], tabs(0, TBase, tabs(1, TBase, tapp(tvar(0), tvar(1))))) == None;\n{\n var c := extend(1, TBase, extend(0, TBase, map[]));\n}\n\nlemma nonexample_typing_3(S: ty, T: ty)\n ensures has_type(map[], tabs(0, S, tapp(tvar(0), tvar(0)))) != Some(T);\n{\n var c := extend(0, S, map[]);\n}\n\n/*BOOL?\nlemma example_typing_bool()\n ensures has_type(map[], tabs(0, TBase, tabs(1, TBase, tabs(2, TBool, tif(tvar(2), tvar(0), tvar(1)))))) ==\n Some(TArrow(TBase, TArrow(TBase, TArrow(TBool, TBase))));\n{\n var c0 := extend(0, TBase, map[]);\n var c1 := extend(1, TBase, c0);\n var c2 := extend(2, TBool, c1);\n}\n?BOOL*/\n\n/*NAT?\nlemma example_typing_nat()\n ensures has_type(map[], tabs(0, TNat, tprev(tvar(0)))) == Some(TArrow(TNat, TNat));\n{\n var c := extend(0, TNat, map[]);\n}\n?NAT*/\n\n/*REC?\n// TODO\nlemma example_typing_rec()\n // \u2205 \u0005|- fold\u00b5T. T\u2192\u03b1(\u03bbx : \u00b5T. T \u2192 \u03b1. (unfold x) x) : \u00b5T. T \u2192 \u03b1\n 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))))) ==\n Some(TRec(0, TArrow(TVar(0), TBase)));\n{\n var R := TRec(0, TArrow(TVar(0), TBase));\n var c := extend(0, R, map[]);\n //{x : \u00b5T. T \u2192 \u03b1} \u0005 x : \u00b5T. T \u2192 \u03b1\n //{x : \u00b5T. T \u2192 \u03b1} \u0005 (unfold x):(\u00b5T. T \u2192 \u03b1) \u2192 \u03b1 {x : \u00b5T. T \u2192 \u03b1} \u0005 x : \u00b5T. T \u2192 \u03b1\n //{x : \u00b5T. T \u2192 \u03b1} \u0005 ( (unfold x) x)) : \u03b1\n //\u2205 \u0005 (\u03bbx : \u00b5T. T \u2192 \u03b1. (unfold x) x)) :(\u00b5T. T \u2192 \u03b1) \u2192 \u03b1\n}\n?REC*/\n\n/// -----------------------\n/// Type-Safety Properties\n/// -----------------------\n\n// Progress:\n// A well-typed term is either a value or it can step.\nlemma theorem_progress(t: tm)\n requires has_type(map[], t).Some?;\n ensures value(t) || step(t).Some?;\n{\n}\n\n// Towards preservation and the substitution lemma\n\n// If x is free in t and t is well-typed in some context,\n// then this context must contain x.\nlemma {:induction c, t} lemma_free_in_context(c: map, x: int, t: tm)\n requires x in fv(t);\n requires has_type(c, t).Some?;\n ensures find(c, x).Some?;\n{\n}\n\n// A closed term does not contain any free variables.\n// N.B. We're only interested in proving type soundness of closed terms.\npredicate closed(t: tm)\n{\n forall x :: x !in fv(t)\n}\n\n// If a term can be well-typed in an empty context,\n// then it is closed.\nlemma corollary_typable_empty__closed(t: tm)\n requires has_type(map[], t).Some?;\n ensures closed(t);\n{\n forall (x:int) ensures x !in fv(t);\n {\n if (x in fv(t)) {\n lemma_free_in_context(map[], x, t);\n }\n }\n}\n\n// If a term t is well-typed in context c,\n// and context c' agrees with c on all free variables of t,\n// then the term t is well-typed in context c',\n// with the same type as in context c.\nlemma {:induction t} lemma_context_invariance(c: map, c': map, t: tm)\n requires has_type(c, t).Some?;\n requires forall x: int :: x in fv(t) ==> find(c, x) == find(c', x);\n ensures has_type(c, t) == has_type(c', t);\n{\n if (t.tabs?) {\n lemma_context_invariance(extend(t.x, t.T, c), extend(t.x, t.T, c'), t.body);\n }\n}\n\n// Substitution preserves typing:\n// If s has type S in an empty context,\n// and t has type T in a context extended with x having type S,\n// then [x -> s]t has type T as well.\nlemma lemma_substitution_preserves_typing(c: map, x: int, s: tm, t: tm)\n requires has_type(map[], s).Some?;\n requires has_type(extend(x, has_type(map[], s).get, c), t).Some?;\n ensures has_type(c, subst(x, s, t)) == has_type(extend(x, has_type(map[], s).get, c), t);\n{\n var S := has_type(map[], s).get;\n var cs := extend(x, S, c);\n var T := has_type(cs, t).get;\n\n if (t.tvar?) {\n if (t.id==x) {\n corollary_typable_empty__closed(s);\n lemma_context_invariance(map[], c, s);\n }\n }\n if (t.tabs?) {\n if (t.x==x) {\n lemma_context_invariance(cs, c, t);\n } else {\n var cx := extend(t.x, t.T, c);\n var csx := extend(x, S, cx);\n var cxs := extend(t.x, t.T, cs);\n lemma_context_invariance(cxs, csx, t.body);\n lemma_substitution_preserves_typing(cx, x, s, t.body);\n }\n }\n}\n\n\n// Preservation:\n// A well-type term which steps preserves its type.\nlemma theorem_preservation(t: tm)\n requires has_type(map[], t).Some?;\n requires step(t).Some?;\n ensures has_type(map[], step(t).get) == has_type(map[], t);\n{\n if (t.tapp? && value(t.f) && value(t.arg)) {\n lemma_substitution_preserves_typing(map[], t.f.x, t.arg, t.f.body);\n }\n}\n\n// A normal form cannot step.\npredicate normal_form(t: tm)\n{\n step(t).None?\n}\n\n// A stuck term is a normal form that is not a value.\npredicate stuck(t: tm)\n{\n normal_form(t) && !value(t)\n}\n\n// Type soundness:\n// A well-typed term cannot be stuck.\nlemma corollary_soundness(t: tm, t': tm, T: ty, n: nat)\n requires has_type(map[], t) == Some(T);\n requires reduces_to(t, t', n);\n ensures !stuck(t');\n{\n theorem_progress(t);\n if (t != t') {\n theorem_preservation(t);\n corollary_soundness(step(t).get, t', T, n-1);\n }\n}\n\n/// QED\n" }, { "test_ID": "493", "test_file": "dafny-synthesis_task_id_101.dfy", "ground_truth": "method KthElement(arr: array, k: int) returns (result: int)\n requires 1 <= k <= arr.Length\n ensures result == arr[k - 1]\n{\n result := arr[k - 1];\n}", "hints_removed": "method KthElement(arr: array, k: int) returns (result: int)\n requires 1 <= k <= arr.Length\n ensures result == arr[k - 1]\n{\n result := arr[k - 1];\n}" }, { "test_ID": "494", "test_file": "dafny-synthesis_task_id_105.dfy", "ground_truth": "function countTo( a:array, n:int ) : int\n requires a != null;\n requires 0 <= n && n <= a.Length;\n decreases n;\n reads a;\n{\n if (n == 0) then 0 else countTo(a, n-1) + (if a[n-1] then 1 else 0)\n}\n\nmethod CountTrue(a: array) returns (result: int)\n requires a != null\n ensures result == countTo(a, a.Length)\n{\n result := 0;\n for i := 0 to a.Length\n invariant 0 <= i <= a.Length\n invariant result == countTo(a, i)\n {\n if a[i] {\n result := result + 1;\n }\n }\n}", "hints_removed": "function countTo( a:array, n:int ) : int\n requires a != null;\n requires 0 <= n && n <= a.Length;\n reads a;\n{\n if (n == 0) then 0 else countTo(a, n-1) + (if a[n-1] then 1 else 0)\n}\n\nmethod CountTrue(a: array) returns (result: int)\n requires a != null\n ensures result == countTo(a, a.Length)\n{\n result := 0;\n for i := 0 to a.Length\n {\n if a[i] {\n result := result + 1;\n }\n }\n}" }, { "test_ID": "495", "test_file": "dafny-synthesis_task_id_106.dfy", "ground_truth": "method AppendArrayToSeq(s: seq, a: array) returns (r: seq)\n requires a != null\n ensures |r| == |s| + a.Length\n ensures forall i :: 0 <= i < |s| ==> r[i] == s[i]\n ensures forall i :: 0 <= i < a.Length ==> r[|s| + i] == a[i]\n{\n r := s;\n for i := 0 to a.Length\n invariant 0 <= i <= a.Length\n invariant |r| == |s| + i\n invariant forall j :: 0 <= j < |s| ==> r[j] == s[j]\n invariant forall j :: 0 <= j < i ==> r[|s| + j] == a[j]\n {\n r := r + [a[i]];\n }\n}", "hints_removed": "method AppendArrayToSeq(s: seq, a: array) returns (r: seq)\n requires a != null\n ensures |r| == |s| + a.Length\n ensures forall i :: 0 <= i < |s| ==> r[i] == s[i]\n ensures forall i :: 0 <= i < a.Length ==> r[|s| + i] == a[i]\n{\n r := s;\n for i := 0 to a.Length\n {\n r := r + [a[i]];\n }\n}" }, { "test_ID": "496", "test_file": "dafny-synthesis_task_id_113.dfy", "ground_truth": "predicate IsDigit(c: char)\n{\n 48 <= c as int <= 57\n}\n\nmethod IsInteger(s: string) returns (result: bool)\n ensures result <==> (|s| > 0) && (forall i :: 0 <= i < |s| ==> IsDigit(s[i]))\n{\n result := true;\n if |s| == 0 {\n result := false;\n } else {\n for i := 0 to |s|\n invariant 0 <= i <= |s|\n invariant result <==> (forall k :: 0 <= k < i ==> IsDigit(s[k]))\n {\n if !IsDigit(s[i]) {\n result := false;\n break;\n }\n }\n }\n}", "hints_removed": "predicate IsDigit(c: char)\n{\n 48 <= c as int <= 57\n}\n\nmethod IsInteger(s: string) returns (result: bool)\n ensures result <==> (|s| > 0) && (forall i :: 0 <= i < |s| ==> IsDigit(s[i]))\n{\n result := true;\n if |s| == 0 {\n result := false;\n } else {\n for i := 0 to |s|\n {\n if !IsDigit(s[i]) {\n result := false;\n break;\n }\n }\n }\n}" }, { "test_ID": "497", "test_file": "dafny-synthesis_task_id_126.dfy", "ground_truth": "method SumOfCommonDivisors(a: int, b: int) returns (sum: int)\n requires a > 0 && b > 0\n ensures sum >= 0\n ensures forall d :: 1 <= d <= a && 1 <= d <= b && a % d == 0 && b % d == 0 ==> sum >= d\n{\n sum := 0;\n var i := 1;\n while i <= a && i <= b\n invariant 1 <= i <= a + 1 && 1 <= i <= b + 1\n invariant sum >= 0\n invariant forall d :: 1 <= d < i && a % d == 0 && b % d == 0 ==> sum >= d\n {\n if a % i == 0 && b % i == 0 {\n sum := sum + i;\n }\n i := i + 1;\n }\n}", "hints_removed": "method SumOfCommonDivisors(a: int, b: int) returns (sum: int)\n requires a > 0 && b > 0\n ensures sum >= 0\n ensures forall d :: 1 <= d <= a && 1 <= d <= b && a % d == 0 && b % d == 0 ==> sum >= d\n{\n sum := 0;\n var i := 1;\n while i <= a && i <= b\n {\n if a % i == 0 && b % i == 0 {\n sum := sum + i;\n }\n i := i + 1;\n }\n}" }, { "test_ID": "498", "test_file": "dafny-synthesis_task_id_127.dfy", "ground_truth": "method Multiply(a: int, b: int) returns (result: int)\n ensures result == a * b\n{\n result := a * b;\n}", "hints_removed": "method Multiply(a: int, b: int) returns (result: int)\n ensures result == a * b\n{\n result := a * b;\n}" }, { "test_ID": "499", "test_file": "dafny-synthesis_task_id_133.dfy", "ground_truth": "function sumNegativesTo( a:array, n:int ) : int\n requires a != null;\n requires 0 <= n && n <= a.Length;\n decreases n;\n reads a;\n{\n if (n == 0) then 0 else if a[n-1] < 0 then sumNegativesTo(a, n-1) + a[n-1] else sumNegativesTo(a, n-1)\n}\n\nmethod SumOfNegatives(a: array) returns (result: int)\n ensures result == sumNegativesTo(a, a.Length)\n{\n result := 0;\n for i := 0 to a.Length\n invariant 0 <= i <= a.Length\n invariant result == sumNegativesTo(a, i)\n {\n if a[i] < 0 {\n result := result + a[i];\n }\n }\n}", "hints_removed": "function sumNegativesTo( a:array, n:int ) : int\n requires a != null;\n requires 0 <= n && n <= a.Length;\n reads a;\n{\n if (n == 0) then 0 else if a[n-1] < 0 then sumNegativesTo(a, n-1) + a[n-1] else sumNegativesTo(a, n-1)\n}\n\nmethod SumOfNegatives(a: array) returns (result: int)\n ensures result == sumNegativesTo(a, a.Length)\n{\n result := 0;\n for i := 0 to a.Length\n {\n if a[i] < 0 {\n result := result + a[i];\n }\n }\n}" }, { "test_ID": "500", "test_file": "dafny-synthesis_task_id_135.dfy", "ground_truth": "method NthHexagonalNumber(n: int) returns (hexNum: int)\n requires n >= 0\n ensures hexNum == n * ((2 * n) - 1)\n{\n hexNum := n * ((2 * n) - 1);\n}", "hints_removed": "method NthHexagonalNumber(n: int) returns (hexNum: int)\n requires n >= 0\n ensures hexNum == n * ((2 * n) - 1)\n{\n hexNum := n * ((2 * n) - 1);\n}" }, { "test_ID": "501", "test_file": "dafny-synthesis_task_id_139.dfy", "ground_truth": "method CircleCircumference(radius: real) returns (circumference: real)\n requires radius > 0.0\n ensures circumference == 2.0 * 3.14159265358979323846 * radius\n{\n circumference := 2.0 * 3.14159265358979323846 * radius;\n}", "hints_removed": "method CircleCircumference(radius: real) returns (circumference: real)\n requires radius > 0.0\n ensures circumference == 2.0 * 3.14159265358979323846 * radius\n{\n circumference := 2.0 * 3.14159265358979323846 * radius;\n}" }, { "test_ID": "502", "test_file": "dafny-synthesis_task_id_14.dfy", "ground_truth": "method TriangularPrismVolume(base: int, height: int, length: int) returns (volume: int)\n requires base > 0\n requires height > 0\n requires length > 0\n ensures volume == (base * height * length) / 2\n{\n volume := (base * height * length) / 2;\n}", "hints_removed": "method TriangularPrismVolume(base: int, height: int, length: int) returns (volume: int)\n requires base > 0\n requires height > 0\n requires length > 0\n ensures volume == (base * height * length) / 2\n{\n volume := (base * height * length) / 2;\n}" }, { "test_ID": "503", "test_file": "dafny-synthesis_task_id_142.dfy", "ground_truth": "method CountIdenticalPositions(a: seq, b: seq, c: seq) returns (count: int)\n requires |a| == |b| && |b| == |c|\n ensures count >= 0\n ensures count == | set i: int | 0 <= i < |a| && a[i] == b[i] && b[i] == c[i]|\n{\n var identical := set i: int | 0 <= i < |a| && a[i] == b[i] && b[i] == c[i];\n count := |identical|;\n}", "hints_removed": "method CountIdenticalPositions(a: seq, b: seq, c: seq) returns (count: int)\n requires |a| == |b| && |b| == |c|\n ensures count >= 0\n ensures count == | set i: int | 0 <= i < |a| && a[i] == b[i] && b[i] == c[i]|\n{\n var identical := set i: int | 0 <= i < |a| && a[i] == b[i] && b[i] == c[i];\n count := |identical|;\n}" }, { "test_ID": "504", "test_file": "dafny-synthesis_task_id_143.dfy", "ground_truth": "method CountArrays(arrays: seq>) returns (count: int)\n ensures count >= 0\n ensures count == |arrays|\n{\n count := |arrays|;\n}", "hints_removed": "method CountArrays(arrays: seq>) returns (count: int)\n ensures count >= 0\n ensures count == |arrays|\n{\n count := |arrays|;\n}" }, { "test_ID": "505", "test_file": "dafny-synthesis_task_id_145.dfy", "ground_truth": "method MaxDifference(a: array) returns (diff: int)\n requires a.Length > 1\n ensures forall i, j :: 0 <= i < a.Length && 0 <= j < a.Length ==> a[i] - a[j] <= diff\n{\n var minVal := a[0];\n var maxVal := a[0];\n\n for i := 1 to a.Length\n invariant 1 <= i <= a.Length\n invariant minVal <= maxVal\n invariant forall k :: 0 <= k < i ==> minVal <= a[k] && a[k] <= maxVal\n {\n if a[i] < minVal {\n minVal := a[i];\n } else if a[i] > maxVal {\n maxVal := a[i];\n }\n }\n diff := maxVal - minVal;\n}", "hints_removed": "method MaxDifference(a: array) returns (diff: int)\n requires a.Length > 1\n ensures forall i, j :: 0 <= i < a.Length && 0 <= j < a.Length ==> a[i] - a[j] <= diff\n{\n var minVal := a[0];\n var maxVal := a[0];\n\n for i := 1 to a.Length\n {\n if a[i] < minVal {\n minVal := a[i];\n } else if a[i] > maxVal {\n maxVal := a[i];\n }\n }\n diff := maxVal - minVal;\n}" }, { "test_ID": "506", "test_file": "dafny-synthesis_task_id_161.dfy", "ground_truth": "predicate InArray(a: array, x: int)\n reads a\n{\n exists i :: 0 <= i < a.Length && a[i] == x\n}\n\nmethod RemoveElements(a: array, b: array) returns (result: seq)\n // All elements in the output are in a and not in b\n ensures forall x :: x in result ==> InArray(a, x) && !InArray(b, x)\n // The elements in the output are all different\n ensures forall i, j :: 0 <= i < j < |result| ==> result[i] != result[j]\n{\n var res: seq := [];\n for i := 0 to a.Length\n invariant 0 <= i <= a.Length\n invariant forall x :: x in res ==> InArray(a, x) && !InArray(b, x)\n invariant forall i, j :: 0 <= i < j < |res| ==> res[i] != res[j]\n {\n if !InArray(b, a[i]) && a[i] !in res\n {\n res := res + [a[i]];\n }\n }\n\n result := res;\n}", "hints_removed": "predicate InArray(a: array, x: int)\n reads a\n{\n exists i :: 0 <= i < a.Length && a[i] == x\n}\n\nmethod RemoveElements(a: array, b: array) returns (result: seq)\n // All elements in the output are in a and not in b\n ensures forall x :: x in result ==> InArray(a, x) && !InArray(b, x)\n // The elements in the output are all different\n ensures forall i, j :: 0 <= i < j < |result| ==> result[i] != result[j]\n{\n var res: seq := [];\n for i := 0 to a.Length\n {\n if !InArray(b, a[i]) && a[i] !in res\n {\n res := res + [a[i]];\n }\n }\n\n result := res;\n}" }, { "test_ID": "507", "test_file": "dafny-synthesis_task_id_17.dfy", "ground_truth": "method SquarePerimeter(side: int) returns (perimeter: int)\n requires side > 0\n ensures perimeter == 4 * side\n{\n perimeter := 4 * side;\n}", "hints_removed": "method SquarePerimeter(side: int) returns (perimeter: int)\n requires side > 0\n ensures perimeter == 4 * side\n{\n perimeter := 4 * side;\n}" }, { "test_ID": "508", "test_file": "dafny-synthesis_task_id_170.dfy", "ground_truth": "function sumTo( a:array, start:int, end:int ) : int\n requires a != null;\n requires 0 <= start && start <= end && end <= a.Length;\n decreases end;\n reads a;\n {\n if (start == end) then 0 else sumTo(a, start, end-1) + a[end-1]\n }\n\n method SumInRange(a: array, start: int, end: int) returns (sum: int)\n requires a != null\n requires 0 <= start && start <= end && end <= a.Length\n ensures sum == sumTo(a, start, end)\n {\n sum := 0;\n for i := start to end\n invariant start <= i <= end\n invariant sum == sumTo(a, start, i)\n {\n sum := sum + a[i];\n }\n }", "hints_removed": "function sumTo( a:array, start:int, end:int ) : int\n requires a != null;\n requires 0 <= start && start <= end && end <= a.Length;\n reads a;\n {\n if (start == end) then 0 else sumTo(a, start, end-1) + a[end-1]\n }\n\n method SumInRange(a: array, start: int, end: int) returns (sum: int)\n requires a != null\n requires 0 <= start && start <= end && end <= a.Length\n ensures sum == sumTo(a, start, end)\n {\n sum := 0;\n for i := start to end\n {\n sum := sum + a[i];\n }\n }" }, { "test_ID": "509", "test_file": "dafny-synthesis_task_id_171.dfy", "ground_truth": "method PentagonPerimeter(side: int) returns (perimeter: int)\n requires side > 0\n ensures perimeter == 5 * side\n{\n perimeter := 5 * side;\n}", "hints_removed": "method PentagonPerimeter(side: int) returns (perimeter: int)\n requires side > 0\n ensures perimeter == 5 * side\n{\n perimeter := 5 * side;\n}" }, { "test_ID": "510", "test_file": "dafny-synthesis_task_id_18.dfy", "ground_truth": "method RemoveChars(s1: string, s2: string) returns (v: string)\n ensures |v| <= |s1|\n ensures forall i :: 0 <= i < |v| ==> (v[i] in s1) && !(v[i] in s2)\n ensures forall i :: 0 <= i < |s1| ==> (s1[i] in s2) || (s1[i] in v)\n{\n var v' : string := [];\n for i := 0 to |s1|\n invariant 0 <= i <= |s1|\n invariant |v'| <= i\n invariant forall k :: 0 <= k < |v'| ==> (v'[k] in s1) && !(v'[k] in s2)\n invariant forall k :: 0 <= k < i ==> (s1[k] in s2) || (s1[k] in v')\n {\n if !(s1[i] in s2)\n {\n v' := v' + [s1[i]];\n }\n }\n return v';\n}", "hints_removed": "method RemoveChars(s1: string, s2: string) returns (v: string)\n ensures |v| <= |s1|\n ensures forall i :: 0 <= i < |v| ==> (v[i] in s1) && !(v[i] in s2)\n ensures forall i :: 0 <= i < |s1| ==> (s1[i] in s2) || (s1[i] in v)\n{\n var v' : string := [];\n for i := 0 to |s1|\n {\n if !(s1[i] in s2)\n {\n v' := v' + [s1[i]];\n }\n }\n return v';\n}" }, { "test_ID": "511", "test_file": "dafny-synthesis_task_id_2.dfy", "ground_truth": "predicate InArray(a: array, x: int)\n reads a\n{\n exists i :: 0 <= i < a.Length && a[i] == x\n}\n\nmethod SharedElements(a: array, b: array) returns (result: seq)\n // All elements in the output are in both a and b\n ensures forall x :: x in result ==> (InArray(a, x) && InArray(b, x))\n // The elements in the output are all different\n ensures forall i, j :: 0 <= i < j < |result| ==> result[i] != result[j]\n{\n var res: seq := [];\n for i := 0 to a.Length\n invariant 0 <= i <= a.Length\n invariant forall x :: x in res ==> InArray(a, x) && InArray(b, x)\n invariant forall i, j :: 0 <= i < j < |res| ==> res[i] != res[j]\n {\n if InArray(b, a[i]) && a[i] !in res\n {\n res := res + [a[i]];\n }\n }\n result := res;\n}", "hints_removed": "predicate InArray(a: array, x: int)\n reads a\n{\n exists i :: 0 <= i < a.Length && a[i] == x\n}\n\nmethod SharedElements(a: array, b: array) returns (result: seq)\n // All elements in the output are in both a and b\n ensures forall x :: x in result ==> (InArray(a, x) && InArray(b, x))\n // The elements in the output are all different\n ensures forall i, j :: 0 <= i < j < |result| ==> result[i] != result[j]\n{\n var res: seq := [];\n for i := 0 to a.Length\n {\n if InArray(b, a[i]) && a[i] !in res\n {\n res := res + [a[i]];\n }\n }\n result := res;\n}" }, { "test_ID": "512", "test_file": "dafny-synthesis_task_id_227.dfy", "ground_truth": "method MinOfThree(a: int, b: int, c: int) returns (min: int)\n ensures min <= a && min <= b && min <= c\n ensures (min == a) || (min == b) || (min == c)\n{\n if (a <= b && a <= c) {\n min := a;\n } else if (b <= a && b <= c) {\n min := b;\n } else {\n min := c;\n }\n}", "hints_removed": "method MinOfThree(a: int, b: int, c: int) returns (min: int)\n ensures min <= a && min <= b && min <= c\n ensures (min == a) || (min == b) || (min == c)\n{\n if (a <= b && a <= c) {\n min := a;\n } else if (b <= a && b <= c) {\n min := b;\n } else {\n min := c;\n }\n}" }, { "test_ID": "513", "test_file": "dafny-synthesis_task_id_230.dfy", "ground_truth": "method ReplaceBlanksWithChar(s: string, ch: char) returns (v: string)\n ensures |v| == |s|\n ensures forall i :: 0 <= i < |s| ==> (s[i] == ' ' ==> v[i] == ch) && (s[i] != ' ' ==> v[i] == s[i])\n{\n var s' : string := [];\n for i := 0 to |s|\n invariant 0 <= i <= |s|\n invariant |s'| == i\n invariant forall k :: 0 <= k < i ==> (s[k] == ' ' ==> s'[k] == ch) && (s[k] != ' ' ==> s'[k] == s[k])\n {\n if s[i] == ' '\n {\n s' := s' + [ch];\n }\n else \n {\n s' := s' + [s[i]];\n }\n }\n return s';\n}", "hints_removed": "method ReplaceBlanksWithChar(s: string, ch: char) returns (v: string)\n ensures |v| == |s|\n ensures forall i :: 0 <= i < |s| ==> (s[i] == ' ' ==> v[i] == ch) && (s[i] != ' ' ==> v[i] == s[i])\n{\n var s' : string := [];\n for i := 0 to |s|\n {\n if s[i] == ' '\n {\n s' := s' + [ch];\n }\n else \n {\n s' := s' + [s[i]];\n }\n }\n return s';\n}" }, { "test_ID": "514", "test_file": "dafny-synthesis_task_id_233.dfy", "ground_truth": "method CylinderLateralSurfaceArea(radius: real, height: real) returns (area: real)\n requires radius > 0.0 && height > 0.0\n ensures area == 2.0 * (radius * height) * 3.14\n{\n area := 2.0 * (radius * height) * 3.14;\n}", "hints_removed": "method CylinderLateralSurfaceArea(radius: real, height: real) returns (area: real)\n requires radius > 0.0 && height > 0.0\n ensures area == 2.0 * (radius * height) * 3.14\n{\n area := 2.0 * (radius * height) * 3.14;\n}" }, { "test_ID": "515", "test_file": "dafny-synthesis_task_id_234.dfy", "ground_truth": "method CubeVolume(size: int) returns (volume: int)\n requires size > 0\n ensures volume == size * size * size\n{\n volume := size * size * size;\n}", "hints_removed": "method CubeVolume(size: int) returns (volume: int)\n requires size > 0\n ensures volume == size * size * size\n{\n volume := size * size * size;\n}" }, { "test_ID": "516", "test_file": "dafny-synthesis_task_id_238.dfy", "ground_truth": "method CountNonEmptySubstrings(s: string) returns (count: int)\n ensures count >= 0\n ensures count == (|s| * (|s| + 1)) / 2 // Formula for the number of non-empty substrings of a string\n{\n count := (|s| * (|s| + 1)) / 2;\n}", "hints_removed": "method CountNonEmptySubstrings(s: string) returns (count: int)\n ensures count >= 0\n ensures count == (|s| * (|s| + 1)) / 2 // Formula for the number of non-empty substrings of a string\n{\n count := (|s| * (|s| + 1)) / 2;\n}" }, { "test_ID": "517", "test_file": "dafny-synthesis_task_id_240.dfy", "ground_truth": "method ReplaceLastElement(first: seq, second: seq) returns (result: seq)\n requires |first| > 0\n ensures |result| == |first| - 1 + |second|\n ensures forall i :: 0 <= i < |first| - 1 ==> result[i] == first[i]\n ensures forall i :: |first| - 1 <= i < |result| ==> result[i] == second[i - |first| + 1]\n{\n result := first[0..|first| - 1] + second;\n}", "hints_removed": "method ReplaceLastElement(first: seq, second: seq) returns (result: seq)\n requires |first| > 0\n ensures |result| == |first| - 1 + |second|\n ensures forall i :: 0 <= i < |first| - 1 ==> result[i] == first[i]\n ensures forall i :: |first| - 1 <= i < |result| ==> result[i] == second[i - |first| + 1]\n{\n result := first[0..|first| - 1] + second;\n}" }, { "test_ID": "518", "test_file": "dafny-synthesis_task_id_242.dfy", "ground_truth": "method CountCharacters(s: string) returns (count: int)\n ensures count >= 0\n ensures count == |s|\n{\n count := |s|;\n}", "hints_removed": "method CountCharacters(s: string) returns (count: int)\n ensures count >= 0\n ensures count == |s|\n{\n count := |s|;\n}" }, { "test_ID": "519", "test_file": "dafny-synthesis_task_id_249.dfy", "ground_truth": "predicate InArray(a: array, x: int)\n reads a\n{\n exists i :: 0 <= i < a.Length && a[i] == x\n}\n\nmethod Intersection(a: array, b: array) returns (result: seq)\n // All elements in the output are in both a and b\n ensures forall x :: x in result ==> (InArray(a, x) && InArray(b, x))\n // The elements in the output are all different\n ensures forall i, j :: 0 <= i < j < |result| ==> result[i] != result[j]\n{\n var res: seq := [];\n for i := 0 to a.Length\n invariant 0 <= i <= a.Length\n invariant forall x :: x in res ==> (InArray(a, x) && InArray(b, x))\n invariant forall i, j :: 0 <= i < j < |res| ==> res[i] != res[j]\n {\n if InArray(b, a[i]) && a[i] !in res\n {\n res := res + [a[i]];\n }\n }\n\n result := res;\n}", "hints_removed": "predicate InArray(a: array, x: int)\n reads a\n{\n exists i :: 0 <= i < a.Length && a[i] == x\n}\n\nmethod Intersection(a: array, b: array) returns (result: seq)\n // All elements in the output are in both a and b\n ensures forall x :: x in result ==> (InArray(a, x) && InArray(b, x))\n // The elements in the output are all different\n ensures forall i, j :: 0 <= i < j < |result| ==> result[i] != result[j]\n{\n var res: seq := [];\n for i := 0 to a.Length\n {\n if InArray(b, a[i]) && a[i] !in res\n {\n res := res + [a[i]];\n }\n }\n\n result := res;\n}" }, { "test_ID": "520", "test_file": "dafny-synthesis_task_id_251.dfy", "ground_truth": "method InsertBeforeEach(s: seq, x: string) returns (v: seq)\n ensures |v| == 2 * |s|\n ensures forall i :: 0 <= i < |s| ==> v[2*i] == x && v[2*i + 1] == s[i]\n {\n v := [];\n for i := 0 to |s|\n invariant 0 <= i <= |s|\n invariant |v| == 2 * i\n invariant forall j :: 0 <= j < i ==> v[2*j] == x && v[2*j + 1] == s[j]\n {\n v := v + [x, s[i]];\n }\n }", "hints_removed": "method InsertBeforeEach(s: seq, x: string) returns (v: seq)\n ensures |v| == 2 * |s|\n ensures forall i :: 0 <= i < |s| ==> v[2*i] == x && v[2*i + 1] == s[i]\n {\n v := [];\n for i := 0 to |s|\n {\n v := v + [x, s[i]];\n }\n }" }, { "test_ID": "521", "test_file": "dafny-synthesis_task_id_257.dfy", "ground_truth": "method Swap(a: int, b: int) returns (result: seq)\n ensures |result| == 2\n ensures result[0] == b\n ensures result[1] == a\n{\n result := [b, a];\n}", "hints_removed": "method Swap(a: int, b: int) returns (result: seq)\n ensures |result| == 2\n ensures result[0] == b\n ensures result[1] == a\n{\n result := [b, a];\n}" }, { "test_ID": "522", "test_file": "dafny-synthesis_task_id_261.dfy", "ground_truth": "method ElementWiseDivision(a: seq, b: seq) returns (result: seq)\n requires |a| == |b|\n requires forall i :: 0 <= i < |b| ==> b[i] != 0\n ensures |result| == |a|\n ensures forall i :: 0 <= i < |result| ==> result[i] == a[i] / b[i]\n{\n result := [];\n var i := 0;\n while i < |a|\n invariant 0 <= i <= |a|\n invariant |result| == i\n invariant forall k :: 0 <= k < i ==> result[k] == a[k] / b[k]\n {\n result := result + [a[i] / b[i]];\n i := i + 1;\n }\n}", "hints_removed": "method ElementWiseDivision(a: seq, b: seq) returns (result: seq)\n requires |a| == |b|\n requires forall i :: 0 <= i < |b| ==> b[i] != 0\n ensures |result| == |a|\n ensures forall i :: 0 <= i < |result| ==> result[i] == a[i] / b[i]\n{\n result := [];\n var i := 0;\n while i < |a|\n {\n result := result + [a[i] / b[i]];\n i := i + 1;\n }\n}" }, { "test_ID": "523", "test_file": "dafny-synthesis_task_id_262.dfy", "ground_truth": "method SplitArray(arr: array, L: int) returns (firstPart: seq, secondPart: seq)\n requires 0 <= L <= arr.Length\n ensures |firstPart| == L\n ensures |secondPart| == arr.Length - L\n ensures firstPart + secondPart == arr[..]\n{\n firstPart := arr[..L];\n secondPart := arr[L..];\n}", "hints_removed": "method SplitArray(arr: array, L: int) returns (firstPart: seq, secondPart: seq)\n requires 0 <= L <= arr.Length\n ensures |firstPart| == L\n ensures |secondPart| == arr.Length - L\n ensures firstPart + secondPart == arr[..]\n{\n firstPart := arr[..L];\n secondPart := arr[L..];\n}" }, { "test_ID": "524", "test_file": "dafny-synthesis_task_id_264.dfy", "ground_truth": "method DogYears(humanYears: int) returns (dogYears: int)\n requires humanYears >= 0\n ensures dogYears == 7 * humanYears\n{\n dogYears := 7 * humanYears;\n}", "hints_removed": "method DogYears(humanYears: int) returns (dogYears: int)\n requires humanYears >= 0\n ensures dogYears == 7 * humanYears\n{\n dogYears := 7 * humanYears;\n}" }, { "test_ID": "525", "test_file": "dafny-synthesis_task_id_266.dfy", "ground_truth": "method LateralSurfaceArea(size: int) returns (area: int)\n requires size > 0\n ensures area == 4 * size * size\n{\n area := 4 * size * size;\n}", "hints_removed": "method LateralSurfaceArea(size: int) returns (area: int)\n requires size > 0\n ensures area == 4 * size * size\n{\n area := 4 * size * size;\n}" }, { "test_ID": "526", "test_file": "dafny-synthesis_task_id_267.dfy", "ground_truth": "method SumOfSquaresOfFirstNOddNumbers(n: int) returns (sum: int)\n requires n >= 0\n ensures sum == (n * (2 * n - 1) * (2 * n + 1)) / 3\n{\n sum := 0;\n var i := 1;\n for k:=0 to n\n invariant 0 <= k <= n\n invariant sum == k * (2 * k - 1) * (2 * k + 1) / 3\n invariant i == 2 * k + 1\n {\n sum := sum + i * i;\n i := i + 2;\n }\n}", "hints_removed": "method SumOfSquaresOfFirstNOddNumbers(n: int) returns (sum: int)\n requires n >= 0\n ensures sum == (n * (2 * n - 1) * (2 * n + 1)) / 3\n{\n sum := 0;\n var i := 1;\n for k:=0 to n\n {\n sum := sum + i * i;\n i := i + 2;\n }\n}" }, { "test_ID": "527", "test_file": "dafny-synthesis_task_id_268.dfy", "ground_truth": "method StarNumber(n: int) returns (star: int)\n requires n >= 0\n ensures star == 6 * n * (n - 1) + 1\n{\n star := 6 * n * (n - 1) + 1;\n}", "hints_removed": "method StarNumber(n: int) returns (star: int)\n requires n >= 0\n ensures star == 6 * n * (n - 1) + 1\n{\n star := 6 * n * (n - 1) + 1;\n}" }, { "test_ID": "528", "test_file": "dafny-synthesis_task_id_269.dfy", "ground_truth": "method AsciiValue(c: char) returns (ascii: int)\n ensures ascii == c as int\n{\n ascii := c as int;\n}", "hints_removed": "method AsciiValue(c: char) returns (ascii: int)\n ensures ascii == c as int\n{\n ascii := c as int;\n}" }, { "test_ID": "529", "test_file": "dafny-synthesis_task_id_273.dfy", "ground_truth": "method SubtractSequences(a: seq, b: seq) returns (result: seq)\n requires |a| == |b|\n ensures |result| == |a|\n ensures forall i :: 0 <= i < |result| ==> result[i] == a[i] - b[i]\n{\n result := [];\n var i := 0;\n while i < |a|\n invariant 0 <= i <= |a|\n invariant |result| == i\n invariant forall k :: 0 <= k < i ==> result[k] == a[k] - b[k]\n {\n result := result + [a[i] - b[i]];\n i := i + 1;\n }\n}", "hints_removed": "method SubtractSequences(a: seq, b: seq) returns (result: seq)\n requires |a| == |b|\n ensures |result| == |a|\n ensures forall i :: 0 <= i < |result| ==> result[i] == a[i] - b[i]\n{\n result := [];\n var i := 0;\n while i < |a|\n {\n result := result + [a[i] - b[i]];\n i := i + 1;\n }\n}" }, { "test_ID": "530", "test_file": "dafny-synthesis_task_id_276.dfy", "ground_truth": "method CylinderVolume(radius: real, height: real) returns (volume: real)\n requires radius > 0.0\n requires height > 0.0\n ensures volume == 3.14159265359 * radius * radius * height\n{\n volume := 3.14159265359 * radius * radius * height;\n}", "hints_removed": "method CylinderVolume(radius: real, height: real) returns (volume: real)\n requires radius > 0.0\n requires height > 0.0\n ensures volume == 3.14159265359 * radius * radius * height\n{\n volume := 3.14159265359 * radius * radius * height;\n}" }, { "test_ID": "531", "test_file": "dafny-synthesis_task_id_279.dfy", "ground_truth": "method NthDecagonalNumber(n: int) returns (decagonal: int)\n requires n >= 0\n ensures decagonal == 4 * n * n - 3 * n\n{\n decagonal := 4 * n * n - 3 * n;\n}", "hints_removed": "method NthDecagonalNumber(n: int) returns (decagonal: int)\n requires n >= 0\n ensures decagonal == 4 * n * n - 3 * n\n{\n decagonal := 4 * n * n - 3 * n;\n}" }, { "test_ID": "532", "test_file": "dafny-synthesis_task_id_282.dfy", "ground_truth": "method ElementWiseSubtraction(a: array, b: array) returns (result: array)\n requires a != null && b != null\n requires a.Length == b.Length\n ensures result != null\n ensures result.Length == a.Length\n ensures forall i :: 0 <= i < result.Length ==> result[i] == a[i] - b[i]\n{\n result := new int[a.Length];\n var i := 0;\n while i < a.Length\n invariant 0 <= i <= a.Length\n invariant result.Length == a.Length\n invariant forall k :: 0 <= k < i ==> result[k] == a[k] - b[k]\n {\n result[i] := a[i] - b[i];\n i := i + 1;\n }\n}", "hints_removed": "method ElementWiseSubtraction(a: array, b: array) returns (result: array)\n requires a != null && b != null\n requires a.Length == b.Length\n ensures result != null\n ensures result.Length == a.Length\n ensures forall i :: 0 <= i < result.Length ==> result[i] == a[i] - b[i]\n{\n result := new int[a.Length];\n var i := 0;\n while i < a.Length\n {\n result[i] := a[i] - b[i];\n i := i + 1;\n }\n}" }, { "test_ID": "533", "test_file": "dafny-synthesis_task_id_284.dfy", "ground_truth": "method AllElementsEqual(a: array, n: int) returns (result: bool)\n requires a != null\n ensures result ==> forall i :: 0 <= i < a.Length ==> a[i] == n\n ensures !result ==> exists i :: 0 <= i < a.Length && a[i] != n\n{\n result := true;\n for i := 0 to a.Length\n invariant 0 <= i <= a.Length\n invariant result ==> forall k :: 0 <= k < i ==> a[k] == n\n {\n if a[i] != n {\n result := false;\n break;\n }\n }\n}", "hints_removed": "method AllElementsEqual(a: array, n: int) returns (result: bool)\n requires a != null\n ensures result ==> forall i :: 0 <= i < a.Length ==> a[i] == n\n ensures !result ==> exists i :: 0 <= i < a.Length && a[i] != n\n{\n result := true;\n for i := 0 to a.Length\n {\n if a[i] != n {\n result := false;\n break;\n }\n }\n}" }, { "test_ID": "534", "test_file": "dafny-synthesis_task_id_290.dfy", "ground_truth": "method MaxLengthList(lists: seq>) returns (maxList: seq)\n requires |lists| > 0\n ensures forall l :: l in lists ==> |l| <= |maxList|\n ensures maxList in lists\n{\n maxList := lists[0];\n\n for i := 1 to |lists|\n invariant 1 <= i <= |lists|\n invariant forall l :: l in lists[..i] ==> |l| <= |maxList|\n invariant maxList in lists[..i]\n {\n if |lists[i]| > |maxList| {\n maxList := lists[i];\n }\n }\n}", "hints_removed": "method MaxLengthList(lists: seq>) returns (maxList: seq)\n requires |lists| > 0\n ensures forall l :: l in lists ==> |l| <= |maxList|\n ensures maxList in lists\n{\n maxList := lists[0];\n\n for i := 1 to |lists|\n {\n if |lists[i]| > |maxList| {\n maxList := lists[i];\n }\n }\n}" }, { "test_ID": "535", "test_file": "dafny-synthesis_task_id_292.dfy", "ground_truth": "method Quotient(a: int, b: int) returns (result: int)\n requires b != 0\n ensures result == a / b\n{\n result := a / b;\n}", "hints_removed": "method Quotient(a: int, b: int) returns (result: int)\n requires b != 0\n ensures result == a / b\n{\n result := a / b;\n}" }, { "test_ID": "536", "test_file": "dafny-synthesis_task_id_3.dfy", "ground_truth": "method IsNonPrime(n: int) returns (result: bool)\n requires n >= 2\n ensures result <==> (exists k :: 2 <= k < n && n % k == 0)\n{\n result := false;\n var i := 2;\n while i <= n/2\n invariant 2 <= i\n invariant result <==> (exists k :: 2 <= k < i && n % k == 0)\n {\n if n % i == 0\n {\n result := true;\n break;\n }\n i := i + 1;\n }\n}", "hints_removed": "method IsNonPrime(n: int) returns (result: bool)\n requires n >= 2\n ensures result <==> (exists k :: 2 <= k < n && n % k == 0)\n{\n result := false;\n var i := 2;\n while i <= n/2\n {\n if n % i == 0\n {\n result := true;\n break;\n }\n i := i + 1;\n }\n}" }, { "test_ID": "537", "test_file": "dafny-synthesis_task_id_304.dfy", "ground_truth": "method ElementAtIndexAfterRotation(l: seq, n: int, index: int) returns (element: int)\n requires n >= 0\n requires 0 <= index < |l|\n ensures element == l[(index - n + |l|) % |l|]\n{\n element := l[(index - n + |l|) % |l|];\n}", "hints_removed": "method ElementAtIndexAfterRotation(l: seq, n: int, index: int) returns (element: int)\n requires n >= 0\n requires 0 <= index < |l|\n ensures element == l[(index - n + |l|) % |l|]\n{\n element := l[(index - n + |l|) % |l|];\n}" }, { "test_ID": "538", "test_file": "dafny-synthesis_task_id_307.dfy", "ground_truth": "method DeepCopySeq(s: seq) returns (copy: seq)\n ensures |copy| == |s|\n ensures forall i :: 0 <= i < |s| ==> copy[i] == s[i]\n{\n var newSeq: seq := [];\n for i := 0 to |s|\n invariant 0 <= i <= |s|\n invariant |newSeq| == i\n invariant forall k :: 0 <= k < i ==> newSeq[k] == s[k]\n {\n newSeq := newSeq + [s[i]];\n }\n return newSeq;\n}", "hints_removed": "method DeepCopySeq(s: seq) returns (copy: seq)\n ensures |copy| == |s|\n ensures forall i :: 0 <= i < |s| ==> copy[i] == s[i]\n{\n var newSeq: seq := [];\n for i := 0 to |s|\n {\n newSeq := newSeq + [s[i]];\n }\n return newSeq;\n}" }, { "test_ID": "539", "test_file": "dafny-synthesis_task_id_309.dfy", "ground_truth": "method Max(a: int, b: int) returns (maxValue: int)\n ensures maxValue == a || maxValue == b\n ensures maxValue >= a && maxValue >= b\n{\n if a >= b {\n maxValue := a;\n } else {\n maxValue := b;\n }\n}", "hints_removed": "method Max(a: int, b: int) returns (maxValue: int)\n ensures maxValue == a || maxValue == b\n ensures maxValue >= a && maxValue >= b\n{\n if a >= b {\n maxValue := a;\n } else {\n maxValue := b;\n }\n}" }, { "test_ID": "540", "test_file": "dafny-synthesis_task_id_310.dfy", "ground_truth": "method ToCharArray(s: string) returns (a: array)\n ensures a.Length == |s|\n ensures forall i :: 0 <= i < |s| ==> a[i] == s[i]\n{\n a := new char[|s|];\n for i := 0 to |s|\n invariant 0 <= i <= |s|\n invariant a.Length == |s|\n invariant forall k :: 0 <= k < i ==> a[k] == s[k]\n {\n a[i] := s[i];\n }\n}", "hints_removed": "method ToCharArray(s: string) returns (a: array)\n ensures a.Length == |s|\n ensures forall i :: 0 <= i < |s| ==> a[i] == s[i]\n{\n a := new char[|s|];\n for i := 0 to |s|\n {\n a[i] := s[i];\n }\n}" }, { "test_ID": "541", "test_file": "dafny-synthesis_task_id_312.dfy", "ground_truth": "method ConeVolume(radius: real, height: real) returns (volume: real)\n requires radius > 0.0 && height > 0.0\n ensures volume == (1.0/3.0) * (3.14159265358979323846) * radius * radius * height\n{\n volume := (1.0/3.0) * (3.14159265358979323846) * radius * radius * height;\n}", "hints_removed": "method ConeVolume(radius: real, height: real) returns (volume: real)\n requires radius > 0.0 && height > 0.0\n ensures volume == (1.0/3.0) * (3.14159265358979323846) * radius * radius * height\n{\n volume := (1.0/3.0) * (3.14159265358979323846) * radius * radius * height;\n}" }, { "test_ID": "542", "test_file": "dafny-synthesis_task_id_396.dfy", "ground_truth": "method StartAndEndWithSameChar(s: string) returns (result: bool)\n requires |s| > 0\n ensures result <==> s[0] == s[|s| - 1]\n{\n result := s[0] == s[|s| - 1];\n}", "hints_removed": "method StartAndEndWithSameChar(s: string) returns (result: bool)\n requires |s| > 0\n ensures result <==> s[0] == s[|s| - 1]\n{\n result := s[0] == s[|s| - 1];\n}" }, { "test_ID": "543", "test_file": "dafny-synthesis_task_id_397.dfy", "ground_truth": "method MedianOfThree(a: int, b: int, c: int) returns (median: int)\n ensures median == a || median == b || median == c\n ensures (median >= a && median <= b) || (median >= b && median <= a) || (median >= a && median <= c) || (median >= c && median <= a) || (median >= b && median <= c) || (median >= c && median <= b)\n{\n if ((a <= b && b <= c) || (c <= b && b <= a)) {\n median := b;\n } else if ((b <= a && a <= c) || (c <= a && a <= b)) {\n median := a;\n } else {\n median := c;\n }\n}", "hints_removed": "method MedianOfThree(a: int, b: int, c: int) returns (median: int)\n ensures median == a || median == b || median == c\n ensures (median >= a && median <= b) || (median >= b && median <= a) || (median >= a && median <= c) || (median >= c && median <= a) || (median >= b && median <= c) || (median >= c && median <= b)\n{\n if ((a <= b && b <= c) || (c <= b && b <= a)) {\n median := b;\n } else if ((b <= a && a <= c) || (c <= a && a <= b)) {\n median := a;\n } else {\n median := c;\n }\n}" }, { "test_ID": "544", "test_file": "dafny-synthesis_task_id_399.dfy", "ground_truth": "method BitwiseXOR(a: seq, b: seq) returns (result: seq)\n requires |a| == |b|\n ensures |result| == |a|\n ensures forall i :: 0 <= i < |result| ==> result[i] == a[i] ^ b[i]\n{\n result := [];\n var i := 0;\n while i < |a|\n invariant 0 <= i <= |a|\n invariant |result| == i\n invariant forall k :: 0 <= k < i ==> result[k] == a[k] ^ b[k]\n {\n result := result + [a[i] ^ b[i]];\n i := i + 1;\n }\n}", "hints_removed": "method BitwiseXOR(a: seq, b: seq) returns (result: seq)\n requires |a| == |b|\n ensures |result| == |a|\n ensures forall i :: 0 <= i < |result| ==> result[i] == a[i] ^ b[i]\n{\n result := [];\n var i := 0;\n while i < |a|\n {\n result := result + [a[i] ^ b[i]];\n i := i + 1;\n }\n}" }, { "test_ID": "545", "test_file": "dafny-synthesis_task_id_401.dfy", "ground_truth": "method IndexWiseAddition(a: seq>, b: seq>) returns (result: seq>)\n requires |a| > 0 && |b| > 0\n requires |a| == |b|\n requires forall i :: 0 <= i < |a| ==> |a[i]| == |b[i]|\n ensures |result| == |a|\n ensures forall i :: 0 <= i < |result| ==> |result[i]| == |a[i]|\n ensures forall i :: 0 <= i < |result| ==> forall j :: 0 <= j < |result[i]| ==> result[i][j] == a[i][j] + b[i][j]\n{\n result := [];\n for i := 0 to |a|\n invariant 0 <= i <= |a|\n invariant |result| == i\n invariant forall k :: 0 <= k < i ==> |result[k]| == |a[k]|\n invariant forall k :: 0 <= k < i ==> forall j :: 0 <= j < |result[k]| ==> result[k][j] == a[k][j] + b[k][j]\n {\n var subResult := [];\n for j := 0 to |a[i]|\n invariant 0 <= j <= |a[i]|\n invariant |subResult| == j\n invariant forall k :: 0 <= k < j ==> subResult[k] == a[i][k] + b[i][k]\n {\n subResult := subResult + [a[i][j] + b[i][j]];\n }\n result := result + [subResult];\n }\n}", "hints_removed": "method IndexWiseAddition(a: seq>, b: seq>) returns (result: seq>)\n requires |a| > 0 && |b| > 0\n requires |a| == |b|\n requires forall i :: 0 <= i < |a| ==> |a[i]| == |b[i]|\n ensures |result| == |a|\n ensures forall i :: 0 <= i < |result| ==> |result[i]| == |a[i]|\n ensures forall i :: 0 <= i < |result| ==> forall j :: 0 <= j < |result[i]| ==> result[i][j] == a[i][j] + b[i][j]\n{\n result := [];\n for i := 0 to |a|\n {\n var subResult := [];\n for j := 0 to |a[i]|\n {\n subResult := subResult + [a[i][j] + b[i][j]];\n }\n result := result + [subResult];\n }\n}" }, { "test_ID": "546", "test_file": "dafny-synthesis_task_id_404.dfy", "ground_truth": "method Min(a: int, b: int) returns (minValue: int)\n ensures minValue == a || minValue == b\n ensures minValue <= a && minValue <= b\n{\n if a <= b {\n minValue := a;\n } else {\n minValue := b;\n }\n}", "hints_removed": "method Min(a: int, b: int) returns (minValue: int)\n ensures minValue == a || minValue == b\n ensures minValue <= a && minValue <= b\n{\n if a <= b {\n minValue := a;\n } else {\n minValue := b;\n }\n}" }, { "test_ID": "547", "test_file": "dafny-synthesis_task_id_406.dfy", "ground_truth": "method IsOdd(n: int) returns (result: bool)\n ensures result <==> n % 2 == 1\n{\n result := n % 2 == 1;\n}", "hints_removed": "method IsOdd(n: int) returns (result: bool)\n ensures result <==> n % 2 == 1\n{\n result := n % 2 == 1;\n}" }, { "test_ID": "548", "test_file": "dafny-synthesis_task_id_412.dfy", "ground_truth": "/**\n * Remove odd numbers from an array of numbers\n **/\n\npredicate IsEven(n: int)\n{\n n % 2 == 0\n}\n\nmethod RemoveOddNumbers(arr: array) returns (evenList: seq)\n // All numbers in the output are even and exist in the input \n ensures forall i :: 0 <= i < |evenList| ==> IsEven(evenList[i]) && evenList[i] in arr[..]\n // All even numbers in the input are in the output\n ensures forall i :: 0 <= i < arr.Length && IsEven(arr[i]) ==> arr[i] in evenList\n{\n evenList := [];\n for i := 0 to arr.Length\n invariant 0 <= i <= arr.Length\n invariant 0 <= |evenList| <= i\n invariant forall k :: 0 <= k < |evenList| ==> IsEven(evenList[k]) && evenList[k] in arr[..]\n invariant forall k :: 0 <= k < i && IsEven(arr[k]) ==> arr[k] in evenList\n {\n if IsEven(arr[i])\n {\n evenList := evenList + [arr[i]];\n }\n }\n}", "hints_removed": "/**\n * Remove odd numbers from an array of numbers\n **/\n\npredicate IsEven(n: int)\n{\n n % 2 == 0\n}\n\nmethod RemoveOddNumbers(arr: array) returns (evenList: seq)\n // All numbers in the output are even and exist in the input \n ensures forall i :: 0 <= i < |evenList| ==> IsEven(evenList[i]) && evenList[i] in arr[..]\n // All even numbers in the input are in the output\n ensures forall i :: 0 <= i < arr.Length && IsEven(arr[i]) ==> arr[i] in evenList\n{\n evenList := [];\n for i := 0 to arr.Length\n {\n if IsEven(arr[i])\n {\n evenList := evenList + [arr[i]];\n }\n }\n}" }, { "test_ID": "549", "test_file": "dafny-synthesis_task_id_414.dfy", "ground_truth": "method AnyValueExists(seq1: seq, seq2: seq) returns (result: bool)\n ensures result <==> (exists i :: 0 <= i < |seq1| && seq1[i] in seq2)\n{\n result := false;\n for i := 0 to |seq1|\n invariant 0 <= i <= |seq1|\n invariant result <==> (exists k :: 0 <= k < i && seq1[k] in seq2)\n {\n if seq1[i] in seq2 {\n result := true;\n break;\n }\n }\n}", "hints_removed": "method AnyValueExists(seq1: seq, seq2: seq) returns (result: bool)\n ensures result <==> (exists i :: 0 <= i < |seq1| && seq1[i] in seq2)\n{\n result := false;\n for i := 0 to |seq1|\n {\n if seq1[i] in seq2 {\n result := true;\n break;\n }\n }\n}" }, { "test_ID": "550", "test_file": "dafny-synthesis_task_id_424.dfy", "ground_truth": "method ExtractRearChars(l: seq) returns (r: seq)\n requires forall i :: 0 <= i < |l| ==> |l[i]| > 0\n ensures |r| == |l|\n ensures forall i :: 0 <= i < |l| ==> r[i] == l[i][|l[i]| - 1]\n{\n var rearChars: seq := [];\n for i := 0 to |l|\n invariant 0 <= i <= |l|\n invariant |rearChars| == i\n invariant forall k :: 0 <= k < i ==> rearChars[k] == l[k][|l[k]| - 1]\n {\n rearChars := rearChars + [l[i][|l[i]| - 1]];\n }\n return rearChars;\n}", "hints_removed": "method ExtractRearChars(l: seq) returns (r: seq)\n requires forall i :: 0 <= i < |l| ==> |l[i]| > 0\n ensures |r| == |l|\n ensures forall i :: 0 <= i < |l| ==> r[i] == l[i][|l[i]| - 1]\n{\n var rearChars: seq := [];\n for i := 0 to |l|\n {\n rearChars := rearChars + [l[i][|l[i]| - 1]];\n }\n return rearChars;\n}" }, { "test_ID": "551", "test_file": "dafny-synthesis_task_id_426.dfy", "ground_truth": "/**\n * Filter odd numbers from an array of numbers\n **/\n\npredicate IsOdd(n: int)\n{\n n % 2 != 0\n}\n\nmethod FilterOddNumbers(arr: array) returns (oddList: seq)\n // All numbers in the output are odd and exist in the input \n ensures forall i :: 0 <= i < |oddList| ==> IsOdd(oddList[i]) && oddList[i] in arr[..]\n // All odd numbers in the input are in the output\n ensures forall i :: 0 <= i < arr.Length && IsOdd(arr[i]) ==> arr[i] in oddList\n{\n oddList := [];\n for i := 0 to arr.Length\n invariant 0 <= i <= arr.Length\n invariant 0 <= |oddList| <= i\n invariant forall k :: 0 <= k < |oddList| ==> IsOdd(oddList[k]) && oddList[k] in arr[..]\n invariant forall k :: 0 <= k < i && IsOdd(arr[k]) ==> arr[k] in oddList\n {\n if IsOdd(arr[i])\n {\n oddList := oddList + [arr[i]];\n }\n }\n}", "hints_removed": "/**\n * Filter odd numbers from an array of numbers\n **/\n\npredicate IsOdd(n: int)\n{\n n % 2 != 0\n}\n\nmethod FilterOddNumbers(arr: array) returns (oddList: seq)\n // All numbers in the output are odd and exist in the input \n ensures forall i :: 0 <= i < |oddList| ==> IsOdd(oddList[i]) && oddList[i] in arr[..]\n // All odd numbers in the input are in the output\n ensures forall i :: 0 <= i < arr.Length && IsOdd(arr[i]) ==> arr[i] in oddList\n{\n oddList := [];\n for i := 0 to arr.Length\n {\n if IsOdd(arr[i])\n {\n oddList := oddList + [arr[i]];\n }\n }\n}" }, { "test_ID": "552", "test_file": "dafny-synthesis_task_id_430.dfy", "ground_truth": "method ParabolaDirectrix(a: real, h: real, k: real) returns (directrix: real)\n requires a != 0.0\n ensures directrix == k - 1.0 / (4.0 * a)\n{\n directrix := k - 1.0 / (4.0 * a);\n}", "hints_removed": "method ParabolaDirectrix(a: real, h: real, k: real) returns (directrix: real)\n requires a != 0.0\n ensures directrix == k - 1.0 / (4.0 * a)\n{\n directrix := k - 1.0 / (4.0 * a);\n}" }, { "test_ID": "553", "test_file": "dafny-synthesis_task_id_431.dfy", "ground_truth": "method HasCommonElement(a: array, b: array) returns (result: bool)\n requires a != null && b != null\n ensures result ==> exists i, j :: 0 <= i < a.Length && 0 <= j < b.Length && a[i] == b[j]\n ensures !result ==> forall i, j :: 0 <= i < a.Length && 0 <= j < b.Length ==> a[i] != b[j]\n{\n result := false;\n for i := 0 to a.Length\n invariant 0 <= i <= a.Length\n invariant !result ==> forall k, j :: 0 <= k < i && 0 <= j < b.Length ==> a[k] != b[j]\n {\n for j := 0 to b.Length\n invariant 0 <= j <= b.Length\n invariant !result ==> forall k :: 0 <= k < j ==> a[i] != b[k]\n {\n if a[i] == b[j] {\n result := true;\n return;\n }\n }\n }\n}", "hints_removed": "method HasCommonElement(a: array, b: array) returns (result: bool)\n requires a != null && b != null\n ensures result ==> exists i, j :: 0 <= i < a.Length && 0 <= j < b.Length && a[i] == b[j]\n ensures !result ==> forall i, j :: 0 <= i < a.Length && 0 <= j < b.Length ==> a[i] != b[j]\n{\n result := false;\n for i := 0 to a.Length\n {\n for j := 0 to b.Length\n {\n if a[i] == b[j] {\n result := true;\n return;\n }\n }\n }\n}" }, { "test_ID": "554", "test_file": "dafny-synthesis_task_id_432.dfy", "ground_truth": "method MedianLength(a: int, b: int) returns (median: int)\n requires a > 0 && b > 0\n ensures median == (a + b) / 2\n{\n median := (a + b) / 2;\n}", "hints_removed": "method MedianLength(a: int, b: int) returns (median: int)\n requires a > 0 && b > 0\n ensures median == (a + b) / 2\n{\n median := (a + b) / 2;\n}" }, { "test_ID": "555", "test_file": "dafny-synthesis_task_id_433.dfy", "ground_truth": "method IsGreater(n: int, a: array) returns (result: bool)\n requires a != null\n ensures result ==> forall i :: 0 <= i < a.Length ==> n > a[i]\n ensures !result ==> exists i :: 0 <= i < a.Length && n <= a[i]\n{\n result := true;\n var i := 0;\n while i < a.Length\n invariant 0 <= i <= a.Length\n invariant result ==> forall k :: 0 <= k < i ==> n > a[k]\n invariant !result ==> exists k :: 0 <= k < i && n <= a[k]\n {\n if n <= a[i] {\n result := false;\n break;\n }\n i := i + 1;\n }\n}", "hints_removed": "method IsGreater(n: int, a: array) returns (result: bool)\n requires a != null\n ensures result ==> forall i :: 0 <= i < a.Length ==> n > a[i]\n ensures !result ==> exists i :: 0 <= i < a.Length && n <= a[i]\n{\n result := true;\n var i := 0;\n while i < a.Length\n {\n if n <= a[i] {\n result := false;\n break;\n }\n i := i + 1;\n }\n}" }, { "test_ID": "556", "test_file": "dafny-synthesis_task_id_435.dfy", "ground_truth": "method LastDigit(n: int) returns (d: int)\n requires n >= 0\n ensures 0 <= d < 10\n ensures n % 10 == d\n{\n d := n % 10;\n}", "hints_removed": "method LastDigit(n: int) returns (d: int)\n requires n >= 0\n ensures 0 <= d < 10\n ensures n % 10 == d\n{\n d := n % 10;\n}" }, { "test_ID": "557", "test_file": "dafny-synthesis_task_id_436.dfy", "ground_truth": "/**\n * Find negative numbers from an array of numbers\n **/\n\npredicate IsNegative(n: int)\n{\n n < 0\n}\n\nmethod FindNegativeNumbers(arr: array) returns (negativeList: seq)\n // All numbers in the output are negative and exist in the input \n ensures forall i :: 0 <= i < |negativeList| ==> IsNegative(negativeList[i]) && negativeList[i] in arr[..]\n // All negative numbers in the input are in the output\n ensures forall i :: 0 <= i < arr.Length && IsNegative(arr[i]) ==> arr[i] in negativeList\n{\n negativeList := [];\n for i := 0 to arr.Length\n invariant 0 <= i <= arr.Length\n invariant 0 <= |negativeList| <= i\n invariant forall k :: 0 <= k < |negativeList| ==> IsNegative(negativeList[k]) && negativeList[k] in arr[..]\n invariant forall k :: 0 <= k < i && IsNegative(arr[k]) ==> arr[k] in negativeList\n {\n if IsNegative(arr[i])\n {\n negativeList := negativeList + [arr[i]];\n }\n }\n}", "hints_removed": "/**\n * Find negative numbers from an array of numbers\n **/\n\npredicate IsNegative(n: int)\n{\n n < 0\n}\n\nmethod FindNegativeNumbers(arr: array) returns (negativeList: seq)\n // All numbers in the output are negative and exist in the input \n ensures forall i :: 0 <= i < |negativeList| ==> IsNegative(negativeList[i]) && negativeList[i] in arr[..]\n // All negative numbers in the input are in the output\n ensures forall i :: 0 <= i < arr.Length && IsNegative(arr[i]) ==> arr[i] in negativeList\n{\n negativeList := [];\n for i := 0 to arr.Length\n {\n if IsNegative(arr[i])\n {\n negativeList := negativeList + [arr[i]];\n }\n }\n}" }, { "test_ID": "558", "test_file": "dafny-synthesis_task_id_441.dfy", "ground_truth": "method CubeSurfaceArea(size: int) returns (area: int)\n requires size > 0\n ensures area == 6 * size * size\n{\n area := 6 * size * size;\n}", "hints_removed": "method CubeSurfaceArea(size: int) returns (area: int)\n requires size > 0\n ensures area == 6 * size * size\n{\n area := 6 * size * size;\n}" }, { "test_ID": "559", "test_file": "dafny-synthesis_task_id_445.dfy", "ground_truth": "method MultiplyElements(a: seq, b: seq) returns (result: seq)\n requires |a| == |b|\n ensures |result| == |a|\n ensures forall i :: 0 <= i < |result| ==> result[i] == a[i] * b[i]\n{\n result := [];\n var i := 0;\n while i < |a|\n invariant 0 <= i <= |a|\n invariant |result| == i\n invariant forall k :: 0 <= k < i ==> result[k] == a[k] * b[k]\n {\n result := result + [a[i] * b[i]];\n i := i + 1;\n }\n}", "hints_removed": "method MultiplyElements(a: seq, b: seq) returns (result: seq)\n requires |a| == |b|\n ensures |result| == |a|\n ensures forall i :: 0 <= i < |result| ==> result[i] == a[i] * b[i]\n{\n result := [];\n var i := 0;\n while i < |a|\n {\n result := result + [a[i] * b[i]];\n i := i + 1;\n }\n}" }, { "test_ID": "560", "test_file": "dafny-synthesis_task_id_447.dfy", "ground_truth": "method CubeElements(a: array) returns (cubed: array)\n ensures cubed.Length == a.Length\n ensures forall i :: 0 <= i < a.Length ==> cubed[i] == a[i] * a[i] * a[i]\n{\n var cubedArray := new int[a.Length];\n for i := 0 to a.Length\n invariant 0 <= i <= a.Length\n invariant cubedArray.Length == a.Length\n invariant forall k :: 0 <= k < i ==> cubedArray[k] == a[k] * a[k] * a[k]\n {\n cubedArray[i] := a[i] * a[i] * a[i];\n }\n return cubedArray;\n}", "hints_removed": "method CubeElements(a: array) returns (cubed: array)\n ensures cubed.Length == a.Length\n ensures forall i :: 0 <= i < a.Length ==> cubed[i] == a[i] * a[i] * a[i]\n{\n var cubedArray := new int[a.Length];\n for i := 0 to a.Length\n {\n cubedArray[i] := a[i] * a[i] * a[i];\n }\n return cubedArray;\n}" }, { "test_ID": "561", "test_file": "dafny-synthesis_task_id_452.dfy", "ground_truth": "method CalculateLoss(costPrice: int, sellingPrice: int) returns (loss: int)\n requires costPrice >= 0 && sellingPrice >= 0\n ensures (costPrice > sellingPrice ==> loss == costPrice - sellingPrice) && (costPrice <= sellingPrice ==> loss == 0)\n{\n if (costPrice > sellingPrice) {\n loss := costPrice - sellingPrice;\n } else {\n loss := 0;\n }\n}", "hints_removed": "method CalculateLoss(costPrice: int, sellingPrice: int) returns (loss: int)\n requires costPrice >= 0 && sellingPrice >= 0\n ensures (costPrice > sellingPrice ==> loss == costPrice - sellingPrice) && (costPrice <= sellingPrice ==> loss == 0)\n{\n if (costPrice > sellingPrice) {\n loss := costPrice - sellingPrice;\n } else {\n loss := 0;\n }\n}" }, { "test_ID": "562", "test_file": "dafny-synthesis_task_id_454.dfy", "ground_truth": "method ContainsZ(s: string) returns (result: bool)\n ensures result <==> (exists i :: 0 <= i < |s| && (s[i] == 'z' || s[i] == 'Z'))\n{\n result := false;\n for i := 0 to |s|\n invariant 0 <= i <= |s|\n invariant result <==> (exists k :: 0 <= k < i && (s[k] == 'z' || s[k] == 'Z'))\n {\n if s[i] == 'z' || s[i] == 'Z' {\n result := true;\n break;\n }\n }\n}", "hints_removed": "method ContainsZ(s: string) returns (result: bool)\n ensures result <==> (exists i :: 0 <= i < |s| && (s[i] == 'z' || s[i] == 'Z'))\n{\n result := false;\n for i := 0 to |s|\n {\n if s[i] == 'z' || s[i] == 'Z' {\n result := true;\n break;\n }\n }\n}" }, { "test_ID": "563", "test_file": "dafny-synthesis_task_id_455.dfy", "ground_truth": "method MonthHas31Days(month: int) returns (result: bool)\n requires 1 <= month <= 12\n ensures result <==> month in {1, 3, 5, 7, 8, 10, 12}\n{\n result := month in {1, 3, 5, 7, 8, 10, 12};\n}", "hints_removed": "method MonthHas31Days(month: int) returns (result: bool)\n requires 1 <= month <= 12\n ensures result <==> month in {1, 3, 5, 7, 8, 10, 12}\n{\n result := month in {1, 3, 5, 7, 8, 10, 12};\n}" }, { "test_ID": "564", "test_file": "dafny-synthesis_task_id_457.dfy", "ground_truth": "method MinLengthSublist(s: seq>) returns (minSublist: seq)\n requires |s| > 0\n ensures minSublist in s\n ensures forall sublist :: sublist in s ==> |minSublist| <= |sublist|\n{\n minSublist := s[0];\n for i := 1 to |s|\n invariant 0 <= i <= |s|\n invariant minSublist in s[..i]\n invariant forall sublist :: sublist in s[..i] ==> |minSublist| <= |sublist|\n {\n if |s[i]| < |minSublist| {\n minSublist := s[i];\n }\n }\n}", "hints_removed": "method MinLengthSublist(s: seq>) returns (minSublist: seq)\n requires |s| > 0\n ensures minSublist in s\n ensures forall sublist :: sublist in s ==> |minSublist| <= |sublist|\n{\n minSublist := s[0];\n for i := 1 to |s|\n {\n if |s[i]| < |minSublist| {\n minSublist := s[i];\n }\n }\n}" }, { "test_ID": "565", "test_file": "dafny-synthesis_task_id_458.dfy", "ground_truth": "method RectangleArea(length: int, width: int) returns (area: int)\n requires length > 0\n requires width > 0\n ensures area == length * width\n{\n area := length * width;\n}", "hints_removed": "method RectangleArea(length: int, width: int) returns (area: int)\n requires length > 0\n requires width > 0\n ensures area == length * width\n{\n area := length * width;\n}" }, { "test_ID": "566", "test_file": "dafny-synthesis_task_id_460.dfy", "ground_truth": "method GetFirstElements(lst: seq>) returns (result: seq)\n requires forall i :: 0 <= i < |lst| ==> |lst[i]| > 0\n ensures |result| == |lst|\n ensures forall i :: 0 <= i < |result| ==> result[i] == lst[i][0]\n{\n result := [];\n for i := 0 to |lst|\n invariant 0 <= i <= |lst|\n invariant |result| == i\n invariant forall j :: 0 <= j < i ==> result[j] == lst[j][0]\n {\n result := result + [lst[i][0]];\n }\n}", "hints_removed": "method GetFirstElements(lst: seq>) returns (result: seq)\n requires forall i :: 0 <= i < |lst| ==> |lst[i]| > 0\n ensures |result| == |lst|\n ensures forall i :: 0 <= i < |result| ==> result[i] == lst[i][0]\n{\n result := [];\n for i := 0 to |lst|\n {\n result := result + [lst[i][0]];\n }\n}" }, { "test_ID": "567", "test_file": "dafny-synthesis_task_id_461.dfy", "ground_truth": "predicate IsUpperCase(c: char)\n{\n 65 <= c as int <= 90\n}\n\nmethod CountUppercase(s: string) returns (count: int)\n ensures count >= 0\n ensures count == | set i: int | 0 <= i < |s| && IsUpperCase(s[i])|\n{\n var uppercase := set i: int | 0 <= i < |s| && IsUpperCase(s[i]);\n count := |uppercase|;\n}", "hints_removed": "predicate IsUpperCase(c: char)\n{\n 65 <= c as int <= 90\n}\n\nmethod CountUppercase(s: string) returns (count: int)\n ensures count >= 0\n ensures count == | set i: int | 0 <= i < |s| && IsUpperCase(s[i])|\n{\n var uppercase := set i: int | 0 <= i < |s| && IsUpperCase(s[i]);\n count := |uppercase|;\n}" }, { "test_ID": "568", "test_file": "dafny-synthesis_task_id_470.dfy", "ground_truth": "method PairwiseAddition(a: array) returns (result: array)\n requires a != null\n requires a.Length % 2 == 0\n ensures result != null\n ensures result.Length == a.Length / 2\n ensures forall i :: 0 <= i < result.Length ==> result[i] == a[2*i] + a[2*i + 1]\n{\n result := new int[a.Length / 2];\n var i := 0;\n while i < a.Length / 2\n invariant 0 <= i <= a.Length / 2\n invariant result.Length == a.Length / 2\n invariant forall k :: 0 <= k < i ==> result[k] == a[2*k] + a[2*k + 1]\n {\n result[i] := a[2*i] + a[2*i + 1];\n i := i + 1;\n }\n}", "hints_removed": "method PairwiseAddition(a: array) returns (result: array)\n requires a != null\n requires a.Length % 2 == 0\n ensures result != null\n ensures result.Length == a.Length / 2\n ensures forall i :: 0 <= i < result.Length ==> result[i] == a[2*i] + a[2*i + 1]\n{\n result := new int[a.Length / 2];\n var i := 0;\n while i < a.Length / 2\n {\n result[i] := a[2*i] + a[2*i + 1];\n i := i + 1;\n }\n}" }, { "test_ID": "569", "test_file": "dafny-synthesis_task_id_472.dfy", "ground_truth": "method ContainsConsecutiveNumbers(a: array) returns (result: bool)\n requires a.Length>0\n ensures result <==> (exists i :: 0 <= i < a.Length - 1 && a[i] + 1 == a[i + 1])\n{\n result := false;\n for i := 0 to a.Length - 1\n invariant 0 <= i <= a.Length - 1\n invariant result <==> (exists k :: 0 <= k < i && a[k] + 1 == a[k + 1])\n {\n if a[i] + 1 == a[i + 1] {\n result := true;\n break;\n }\n }\n}", "hints_removed": "method ContainsConsecutiveNumbers(a: array) returns (result: bool)\n requires a.Length>0\n ensures result <==> (exists i :: 0 <= i < a.Length - 1 && a[i] + 1 == a[i + 1])\n{\n result := false;\n for i := 0 to a.Length - 1\n {\n if a[i] + 1 == a[i + 1] {\n result := true;\n break;\n }\n }\n}" }, { "test_ID": "570", "test_file": "dafny-synthesis_task_id_474.dfy", "ground_truth": "method ReplaceChars(s: string, oldChar: char, newChar: char) returns (v: string)\n ensures |v| == |s|\n ensures forall i :: 0 <= i < |s| ==> (s[i] == oldChar ==> v[i] == newChar) && (s[i] != oldChar ==> v[i] == s[i])\n{\n var s' : string := [];\n for i := 0 to |s|\n invariant 0 <= i <= |s|\n invariant |s'| == i\n invariant forall k :: 0 <= k < i ==> (s[k] == oldChar ==> s'[k] == newChar) && (s[k] != oldChar ==> s'[k] == s[k])\n {\n if s[i] == oldChar\n {\n s' := s' + [newChar];\n }\n else \n {\n s' := s' + [s[i]];\n }\n }\n return s';\n}", "hints_removed": "method ReplaceChars(s: string, oldChar: char, newChar: char) returns (v: string)\n ensures |v| == |s|\n ensures forall i :: 0 <= i < |s| ==> (s[i] == oldChar ==> v[i] == newChar) && (s[i] != oldChar ==> v[i] == s[i])\n{\n var s' : string := [];\n for i := 0 to |s|\n {\n if s[i] == oldChar\n {\n s' := s' + [newChar];\n }\n else \n {\n s' := s' + [s[i]];\n }\n }\n return s';\n}" }, { "test_ID": "571", "test_file": "dafny-synthesis_task_id_476.dfy", "ground_truth": "method SumMinMax(a: array) returns (sum: int)\n requires a.Length > 0\n ensures sum == Max(a[..]) + Min(a[..])\n{\n var minVal := a[0];\n var maxVal := a[0];\n\n for i := 1 to a.Length\n invariant 1 <= i <= a.Length\n invariant minVal <= maxVal\n invariant forall k :: 0 <= k < i ==> minVal <= a[k] && a[k] <= maxVal\n invariant minVal == Min(a[..i])\n invariant maxVal == Max(a[..i])\n {\n if a[i] < minVal {\n minVal := a[i];\n } else if a[i] > maxVal {\n maxVal := a[i];\n }\n assert a[..i+1][..i] == a[..i];\n }\n assert a[..a.Length] == a[..];\n sum := minVal + maxVal;\n}\n\n// The order of the recursion in these two functions\n// must match the order of the iteration in the algorithm above\nfunction Min(a: seq) : int\n requires |a| > 0\n{\n if |a| == 1 then a[0]\n else\n var minPrefix := Min(a[..|a|-1]);\n if a[|a|-1] <= minPrefix then a[|a|-1] else Min(a[..|a|-1])\n}\n\nfunction Max(a: seq) : int\n requires |a| > 0\n{\n if |a| == 1 then a[0]\n else\n var maxPrefix := Max(a[..|a|-1]);\n if a[|a|-1] >= maxPrefix then a[|a|-1] else Max(a[..|a|-1])\n}", "hints_removed": "method SumMinMax(a: array) returns (sum: int)\n requires a.Length > 0\n ensures sum == Max(a[..]) + Min(a[..])\n{\n var minVal := a[0];\n var maxVal := a[0];\n\n for i := 1 to a.Length\n {\n if a[i] < minVal {\n minVal := a[i];\n } else if a[i] > maxVal {\n maxVal := a[i];\n }\n }\n sum := minVal + maxVal;\n}\n\n// The order of the recursion in these two functions\n// must match the order of the iteration in the algorithm above\nfunction Min(a: seq) : int\n requires |a| > 0\n{\n if |a| == 1 then a[0]\n else\n var minPrefix := Min(a[..|a|-1]);\n if a[|a|-1] <= minPrefix then a[|a|-1] else Min(a[..|a|-1])\n}\n\nfunction Max(a: seq) : int\n requires |a| > 0\n{\n if |a| == 1 then a[0]\n else\n var maxPrefix := Max(a[..|a|-1]);\n if a[|a|-1] >= maxPrefix then a[|a|-1] else Max(a[..|a|-1])\n}" }, { "test_ID": "572", "test_file": "dafny-synthesis_task_id_477.dfy", "ground_truth": "predicate IsUpperCase(c : char)\n{\n 65 <= c as int <= 90\n}\n\npredicate IsUpperLowerPair(C : char, c : char)\n{\n (C as int) == (c as int) - 32\n}\n\nfunction Shift32(c : char) : char\n{\n ((c as int + 32) % 128) as char\n}\n\nmethod ToLowercase(s: string) returns (v: string)\n ensures |v| == |s|\n ensures forall i :: 0 <= i < |s| ==> if IsUpperCase(s[i]) then IsUpperLowerPair(s[i], v[i]) else v[i] == s[i]\n{\n var s' : string := [];\n for i := 0 to |s|\n invariant 0 <= i <= |s|\n invariant |s'| == i\n invariant forall k :: 0 <= k < i && IsUpperCase(s[k]) ==> IsUpperLowerPair(s[k], s'[k])\n invariant forall k :: 0 <= k < i && !IsUpperCase(s[k]) ==> s[k] == s'[k]\n {\n if IsUpperCase(s[i])\n {\n s' := s' + [Shift32(s[i])];\n }\n else \n {\n s' := s' + [s[i]];\n }\n }\n return s';\n}", "hints_removed": "predicate IsUpperCase(c : char)\n{\n 65 <= c as int <= 90\n}\n\npredicate IsUpperLowerPair(C : char, c : char)\n{\n (C as int) == (c as int) - 32\n}\n\nfunction Shift32(c : char) : char\n{\n ((c as int + 32) % 128) as char\n}\n\nmethod ToLowercase(s: string) returns (v: string)\n ensures |v| == |s|\n ensures forall i :: 0 <= i < |s| ==> if IsUpperCase(s[i]) then IsUpperLowerPair(s[i], v[i]) else v[i] == s[i]\n{\n var s' : string := [];\n for i := 0 to |s|\n {\n if IsUpperCase(s[i])\n {\n s' := s' + [Shift32(s[i])];\n }\n else \n {\n s' := s' + [s[i]];\n }\n }\n return s';\n}" }, { "test_ID": "573", "test_file": "dafny-synthesis_task_id_554.dfy", "ground_truth": "/**\n * Find odd numbers from an array of numbers\n **/\n\npredicate IsOdd(n: int)\n{\n n % 2 == 1\n}\n\nmethod FindOddNumbers(arr: array) returns (oddList: seq)\n // All numbers in the output are odd and exist in the input \n ensures forall i :: 0 <= i < |oddList| ==> IsOdd(oddList[i]) && oddList[i] in arr[..]\n // All odd numbers in the input are in the output\n ensures forall i :: 0 <= i < arr.Length && IsOdd(arr[i]) ==> arr[i] in oddList\n{\n oddList := [];\n for i := 0 to arr.Length\n invariant 0 <= i <= arr.Length\n invariant 0 <= |oddList| <= i\n invariant forall k :: 0 <= k < |oddList| ==> IsOdd(oddList[k]) && oddList[k] in arr[..]\n invariant forall k :: 0 <= k < i && IsOdd(arr[k]) ==> arr[k] in oddList\n {\n if IsOdd(arr[i])\n {\n oddList := oddList + [arr[i]];\n }\n }\n}", "hints_removed": "/**\n * Find odd numbers from an array of numbers\n **/\n\npredicate IsOdd(n: int)\n{\n n % 2 == 1\n}\n\nmethod FindOddNumbers(arr: array) returns (oddList: seq)\n // All numbers in the output are odd and exist in the input \n ensures forall i :: 0 <= i < |oddList| ==> IsOdd(oddList[i]) && oddList[i] in arr[..]\n // All odd numbers in the input are in the output\n ensures forall i :: 0 <= i < arr.Length && IsOdd(arr[i]) ==> arr[i] in oddList\n{\n oddList := [];\n for i := 0 to arr.Length\n {\n if IsOdd(arr[i])\n {\n oddList := oddList + [arr[i]];\n }\n }\n}" }, { "test_ID": "574", "test_file": "dafny-synthesis_task_id_555.dfy", "ground_truth": "method DifferenceSumCubesAndSumNumbers(n: int) returns (diff: int)\n requires n >= 0\n ensures diff == (n * n * (n + 1) * (n + 1)) / 4 - (n * (n + 1)) / 2\n{\n var sumCubes := 0;\n var sumNumbers := 0;\n for i := 1 to n + 1\n invariant 0 <= i <= n + 1\n invariant sumCubes == (i - 1) * (i - 1) * i * i / 4\n invariant sumNumbers == (i - 1) * i / 2\n {\n sumCubes := sumCubes + i * i * i;\n sumNumbers := sumNumbers + i;\n }\n diff := sumCubes - sumNumbers;\n}", "hints_removed": "method DifferenceSumCubesAndSumNumbers(n: int) returns (diff: int)\n requires n >= 0\n ensures diff == (n * n * (n + 1) * (n + 1)) / 4 - (n * (n + 1)) / 2\n{\n var sumCubes := 0;\n var sumNumbers := 0;\n for i := 1 to n + 1\n {\n sumCubes := sumCubes + i * i * i;\n sumNumbers := sumNumbers + i;\n }\n diff := sumCubes - sumNumbers;\n}" }, { "test_ID": "575", "test_file": "dafny-synthesis_task_id_557.dfy", "ground_truth": "predicate IsLowerCase(c : char)\n{\n 97 <= c as int <= 122\n}\n\npredicate IsUpperCase(c : char)\n{\n 65 <= c as int <= 90\n}\n\npredicate IsLowerUpperPair(c : char, C : char)\n{\n (c as int) == (C as int) + 32\n}\n\npredicate IsUpperLowerPair(C : char, c : char)\n{\n (C as int) == (c as int) - 32\n}\n\nfunction ShiftMinus32(c : char) : char\n{\n ((c as int - 32) % 128) as char\n}\n\nfunction Shift32(c : char) : char\n{\n ((c as int + 32) % 128) as char\n}\n\nmethod ToggleCase(s: string) returns (v: string)\n ensures |v| == |s|\n ensures forall i :: 0 <= i < |s| ==> if IsLowerCase(s[i]) then IsLowerUpperPair(s[i], v[i]) else if IsUpperCase(s[i]) then IsUpperLowerPair(s[i], v[i]) else v[i] == s[i]\n{\n var s' : string := [];\n for i := 0 to |s|\n invariant 0 <= i <= |s|\n invariant |s'| == i\n invariant forall k :: 0 <= k < i && IsLowerCase(s[k]) ==> IsLowerUpperPair(s[k], s'[k])\n invariant forall k :: 0 <= k < i && IsUpperCase(s[k]) ==> IsUpperLowerPair(s[k], s'[k])\n invariant forall k :: 0 <= k < i && !IsLowerCase(s[k]) && !IsUpperCase(s[k]) ==> s[k] == s'[k]\n {\n if IsLowerCase(s[i])\n {\n s' := s' + [ShiftMinus32(s[i])];\n }\n else if IsUpperCase(s[i])\n {\n s' := s' + [Shift32(s[i])];\n }\n else \n {\n s' := s' + [s[i]];\n }\n }\n return s';\n}", "hints_removed": "predicate IsLowerCase(c : char)\n{\n 97 <= c as int <= 122\n}\n\npredicate IsUpperCase(c : char)\n{\n 65 <= c as int <= 90\n}\n\npredicate IsLowerUpperPair(c : char, C : char)\n{\n (c as int) == (C as int) + 32\n}\n\npredicate IsUpperLowerPair(C : char, c : char)\n{\n (C as int) == (c as int) - 32\n}\n\nfunction ShiftMinus32(c : char) : char\n{\n ((c as int - 32) % 128) as char\n}\n\nfunction Shift32(c : char) : char\n{\n ((c as int + 32) % 128) as char\n}\n\nmethod ToggleCase(s: string) returns (v: string)\n ensures |v| == |s|\n ensures forall i :: 0 <= i < |s| ==> if IsLowerCase(s[i]) then IsLowerUpperPair(s[i], v[i]) else if IsUpperCase(s[i]) then IsUpperLowerPair(s[i], v[i]) else v[i] == s[i]\n{\n var s' : string := [];\n for i := 0 to |s|\n {\n if IsLowerCase(s[i])\n {\n s' := s' + [ShiftMinus32(s[i])];\n }\n else if IsUpperCase(s[i])\n {\n s' := s' + [Shift32(s[i])];\n }\n else \n {\n s' := s' + [s[i]];\n }\n }\n return s';\n}" }, { "test_ID": "576", "test_file": "dafny-synthesis_task_id_565.dfy", "ground_truth": "method SplitStringIntoChars(s: string) returns (v: seq)\n ensures |v| == |s|\n ensures forall i :: 0 <= i < |s| ==> v[i] == s[i]\n{\n v := [];\n for i := 0 to |s|\n invariant 0 <= i <= |s|\n invariant |v| == i\n invariant forall k :: 0 <= k < i ==> v[k] == s[k]\n {\n v := v + [s[i]];\n }\n}", "hints_removed": "method SplitStringIntoChars(s: string) returns (v: seq)\n ensures |v| == |s|\n ensures forall i :: 0 <= i < |s| ==> v[i] == s[i]\n{\n v := [];\n for i := 0 to |s|\n {\n v := v + [s[i]];\n }\n}" }, { "test_ID": "577", "test_file": "dafny-synthesis_task_id_566.dfy", "ground_truth": "method SumOfDigits(number: nat) returns (sum: nat)\n requires number >= 0\n ensures sum >= 0\n ensures sum == SumDigits(number)\n{\n sum := 0;\n var n: nat := number;\n\n // Let's find out the number of digits, which is the same as powers of ten for the given number\n ghost var ndigits := NumberOfDigits(number);\n X(number);\n assert Power10(ndigits) > number;\n\n ghost var PowersOfTen := seq(ndigits+1, i requires 0 <= i <= ndigits => Power10(i));\n ghost var pmax := Power10(ndigits);\n ghost var p := PowersOfTen[0];\n assert pmax == PowersOfTen[|PowersOfTen|-1];\n assert pmax > number;\n\n // Let's compute the values of n\n ghost var ValuesOfn := seq(ndigits+1, i requires 0 <= i <= ndigits => number / PowersOfTen[i]);\n assert forall j :: 0 < j <= ndigits ==> ValuesOfn[j] == ValuesOfn[j-1]/10;\n assert ValuesOfn[0] == number;\n //DivIsZero();\n assert ValuesOfn[|ValuesOfn|-1] == number/pmax == 0;\n\n assert ValuesOfn[0] == n;\n assert PowersOfTen[0] == p;\n ghost var i := 0;\n while n > 0\n // invariant 1 <= p <= pmax\n // invariant n in ValuesOfn\n invariant 0 <= i <= ndigits\n invariant ValuesOfn[i] == n\n invariant PowersOfTen[i] == p\n invariant sum >= 0\n invariant sum == SumDigits(number % p)\n {\n assert ValuesOfn[i] == n;\n var digit := n % 10;\n sum := sum + digit;\n n := n / 10;\n i := i + 1;\n // assert ValuesOfn[i] == ValuesOfn[i-1]/10;\n // assert ValuesOfn[i] == n;\n p := PowersOfTen[i]; //p * 10;\n assert n == 0 ==> p == pmax;\n }\n assert n == 0;\n // assert i == ndigits;\n assert p == pmax;\n NumberIdentity(number, p);\n assert number == number % p;\n}\n\n//lemma DivIsZero()\n// ensures forall num, den : nat :: den >= 1 && num < den ==> num/den == 0\n\nlemma X(x: nat)\n ensures Power10(NumberOfDigits(x)) > x\n{\n if x <= 9\n {\n assert NumberOfDigits(x) == 1;\n assert Power10(NumberOfDigits(x)) == 10;\n assert Power10(NumberOfDigits(x)) > x;\n }\n else // >= 10\n {\n assert NumberOfDigits(x) >= 2;\n X(x/10);\n assert NumberOfDigits(x) == NumberOfDigits(x/10) + 1;\n assert Power10(NumberOfDigits(x)) == Power10(NumberOfDigits(x/10)) * 10;\n assert Power10(NumberOfDigits(x)) > x;\n }\n}\n\nlemma NumberIdentity(number: nat, pmax: nat)\n requires pmax == Power10(NumberOfDigits(number))\n ensures number == number % pmax\n{\n if NumberOfDigits(number) == 1\n {\n assert 0 <= number <= 9;\n assert pmax == 10;\n assert number == number % pmax;\n }\n else // > 1\n {\n assert pmax == Power10(NumberOfDigits(number)) ==> pmax/10 == Power10(NumberOfDigits(number/10));\n NumberIdentity(number/10, pmax/10);\n assert number >= 10;\n assert pmax >= 100;\n assert number < pmax;\n assert forall n, m :: 0 < n < m <= pmax ==> n%m == n;\n assert number == number % pmax;\n }\n\n}\n\n\nlemma InIntValues(n: nat)\n ensures 0 in IntValues(n)\n ensures n in IntValues(n)\n ensures n/10 in IntValues(n)\n{}\n\n// ghost function ValuesOfn(number: nat, ndigits: nat) : (r: seq)\n// {\n// seq(ndigits+1, i requires 0 <= i <= ndigits => number / PowersOfTen[i])\n// }\n\nghost function IntValues(n: int) : (r: seq)\n requires n >= 0\n ensures 0 in r\n ensures n in r\n ensures n/10 in r\n // ensures forall p :: p in powersOfTen ==> n/p in r\n{\n if n == 0 then [0]\n else [n] + IntValues(n/10)\n}\n\nfunction Power10(n: nat): (r: nat)\n ensures r >= 1\n ensures n > 0 ==> r % 10 == 0\n{\n if (n == 0) then 1 else 10 * Power10(n-1)\n}\n\nfunction NumberToSeq(number: int) : seq\n requires number >= 0\n{\n if number == 0 then []\n else [number % 10] + NumberToSeq(number/10)\n}\n\nfunction Sum(digits: seq) : int\n{\n if |digits| == 0 then 0 else digits[0] + Sum(digits[1..])\n}\n\nfunction SumDigits(n: nat) : nat\n{\n var ndigits := NumberOfDigits(n);\n var p := Power10(ndigits-1);\n SumDigitsRecursive(n, p)\n}\n\nfunction SumDigitsRecursive(n: nat, p: nat) : (r: nat)\n{\n if n == 0 || p == 0 then 0\n else\n var leftMostDigit := n/p;\n var rest := n%p;\n leftMostDigit + SumDigitsRecursive(rest, p/10)\n\n}\n\nfunction NumberOfDigits(n: nat) : (r: nat)\n ensures r >= 1\n ensures r == 1 <==> 0 <= n <= 9\n{\n if 0 <= n <= 9 then 1 else 1+NumberOfDigits(n/10)\n}", "hints_removed": "method SumOfDigits(number: nat) returns (sum: nat)\n requires number >= 0\n ensures sum >= 0\n ensures sum == SumDigits(number)\n{\n sum := 0;\n var n: nat := number;\n\n // Let's find out the number of digits, which is the same as powers of ten for the given number\n ghost var ndigits := NumberOfDigits(number);\n X(number);\n\n ghost var PowersOfTen := seq(ndigits+1, i requires 0 <= i <= ndigits => Power10(i));\n ghost var pmax := Power10(ndigits);\n ghost var p := PowersOfTen[0];\n\n // Let's compute the values of n\n ghost var ValuesOfn := seq(ndigits+1, i requires 0 <= i <= ndigits => number / PowersOfTen[i]);\n //DivIsZero();\n\n ghost var i := 0;\n while n > 0\n {\n var digit := n % 10;\n sum := sum + digit;\n n := n / 10;\n i := i + 1;\n p := PowersOfTen[i]; //p * 10;\n }\n NumberIdentity(number, p);\n}\n\n//lemma DivIsZero()\n// ensures forall num, den : nat :: den >= 1 && num < den ==> num/den == 0\n\nlemma X(x: nat)\n ensures Power10(NumberOfDigits(x)) > x\n{\n if x <= 9\n {\n }\n else // >= 10\n {\n X(x/10);\n }\n}\n\nlemma NumberIdentity(number: nat, pmax: nat)\n requires pmax == Power10(NumberOfDigits(number))\n ensures number == number % pmax\n{\n if NumberOfDigits(number) == 1\n {\n }\n else // > 1\n {\n NumberIdentity(number/10, pmax/10);\n }\n\n}\n\n\nlemma InIntValues(n: nat)\n ensures 0 in IntValues(n)\n ensures n in IntValues(n)\n ensures n/10 in IntValues(n)\n{}\n\n// ghost function ValuesOfn(number: nat, ndigits: nat) : (r: seq)\n// {\n// seq(ndigits+1, i requires 0 <= i <= ndigits => number / PowersOfTen[i])\n// }\n\nghost function IntValues(n: int) : (r: seq)\n requires n >= 0\n ensures 0 in r\n ensures n in r\n ensures n/10 in r\n // ensures forall p :: p in powersOfTen ==> n/p in r\n{\n if n == 0 then [0]\n else [n] + IntValues(n/10)\n}\n\nfunction Power10(n: nat): (r: nat)\n ensures r >= 1\n ensures n > 0 ==> r % 10 == 0\n{\n if (n == 0) then 1 else 10 * Power10(n-1)\n}\n\nfunction NumberToSeq(number: int) : seq\n requires number >= 0\n{\n if number == 0 then []\n else [number % 10] + NumberToSeq(number/10)\n}\n\nfunction Sum(digits: seq) : int\n{\n if |digits| == 0 then 0 else digits[0] + Sum(digits[1..])\n}\n\nfunction SumDigits(n: nat) : nat\n{\n var ndigits := NumberOfDigits(n);\n var p := Power10(ndigits-1);\n SumDigitsRecursive(n, p)\n}\n\nfunction SumDigitsRecursive(n: nat, p: nat) : (r: nat)\n{\n if n == 0 || p == 0 then 0\n else\n var leftMostDigit := n/p;\n var rest := n%p;\n leftMostDigit + SumDigitsRecursive(rest, p/10)\n\n}\n\nfunction NumberOfDigits(n: nat) : (r: nat)\n ensures r >= 1\n ensures r == 1 <==> 0 <= n <= 9\n{\n if 0 <= n <= 9 then 1 else 1+NumberOfDigits(n/10)\n}" }, { "test_ID": "578", "test_file": "dafny-synthesis_task_id_567.dfy", "ground_truth": "method IsSorted(a: array) returns (sorted: bool)\n requires a.Length > 0\n ensures sorted <== forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j]\n ensures !sorted ==> exists i, j :: 0 <= i < j < a.Length && a[i] > a[j]\n{\n sorted := true;\n for i := 0 to a.Length - 1\n invariant 0 <= i < a.Length\n invariant sorted <== forall k, l :: 0 <= k < l < i ==> a[k] <= a[l]\n invariant !sorted ==> exists k :: 0 <= k < i && a[k] > a[k+1]\n {\n if a[i] > a[i + 1]\n {\n sorted := false;\n break;\n }\n }\n sorted := sorted;\n}", "hints_removed": "method IsSorted(a: array) returns (sorted: bool)\n requires a.Length > 0\n ensures sorted <== forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j]\n ensures !sorted ==> exists i, j :: 0 <= i < j < a.Length && a[i] > a[j]\n{\n sorted := true;\n for i := 0 to a.Length - 1\n {\n if a[i] > a[i + 1]\n {\n sorted := false;\n break;\n }\n }\n sorted := sorted;\n}" }, { "test_ID": "579", "test_file": "dafny-synthesis_task_id_572.dfy", "ground_truth": "method RemoveDuplicates(a: array) returns (result: seq)\n requires a != null\n ensures forall x :: x in result <==> exists i :: 0 <= i < a.Length && a[i] == x\n ensures forall i, j :: 0 <= i < j < |result| ==> result[i] != result[j]\n{\n var res: seq := [];\n for i := 0 to a.Length\n invariant 0 <= i <= a.Length\n invariant forall x :: x in res <==> exists k :: 0 <= k < i && a[k] == x\n invariant forall i, j :: 0 <= i < j < |res| ==> res[i] != res[j]\n {\n if a[i] !in res\n {\n res := res + [a[i]];\n }\n }\n result := res;\n}", "hints_removed": "method RemoveDuplicates(a: array) returns (result: seq)\n requires a != null\n ensures forall x :: x in result <==> exists i :: 0 <= i < a.Length && a[i] == x\n ensures forall i, j :: 0 <= i < j < |result| ==> result[i] != result[j]\n{\n var res: seq := [];\n for i := 0 to a.Length\n {\n if a[i] !in res\n {\n res := res + [a[i]];\n }\n }\n result := res;\n}" }, { "test_ID": "580", "test_file": "dafny-synthesis_task_id_573.dfy", "ground_truth": "method UniqueProduct (arr: array) returns (product: int)\n ensures product == SetProduct((set i | 0 <= i < arr.Length :: arr[i]))\n{\n var p := 1;\n var seen: set := {};\n \n for i := 0 to arr.Length\n invariant 0 <= i <= arr.Length\n invariant seen == (set k | 0 <= k < i :: arr[k])\n invariant p == SetProduct((set k | 0 <= k < i :: arr[k]))\n {\n if ! (arr[i] in seen) {\n seen := seen + { arr[i] };\n p := p * arr[i];\n SetProductLemma(seen, arr[i]);\n }\n }\n product := p;\n}\n\nghost function SetProduct(s : set) : int\n{\n if s == {} then 1\n else var x :| x in s; \n x * SetProduct(s - {x})\n}\n\n/* \n * This is necessary because, when we add one element, we need to make sure\n * that the product of the new set, as a whole, is the same as the product\n * of the old set times the new element.\n */\nlemma SetProductLemma(s: set , x: int) \n requires x in s\n ensures SetProduct(s - {x}) * x == SetProduct(s)\n{\n if s != {}\n {\n var y :| y in s && y * SetProduct(s - {y}) == SetProduct(s);\n if y == x {}\n else {\n calc {\n SetProduct(s);\n y * SetProduct(s - {y});\n { SetProductLemma(s - {y}, x); }\n y * x * SetProduct(s - {y} - {x});\n { assert s - {x} - {y} == s - {y} - {x};}\n y * x * SetProduct(s - {x} - {y});\n x * y * SetProduct(s - {x} - {y});\n { SetProductLemma(s - {x}, y); }\n x * SetProduct(s - {x});\n }\n }\n }\n}", "hints_removed": "method UniqueProduct (arr: array) returns (product: int)\n ensures product == SetProduct((set i | 0 <= i < arr.Length :: arr[i]))\n{\n var p := 1;\n var seen: set := {};\n \n for i := 0 to arr.Length\n {\n if ! (arr[i] in seen) {\n seen := seen + { arr[i] };\n p := p * arr[i];\n SetProductLemma(seen, arr[i]);\n }\n }\n product := p;\n}\n\nghost function SetProduct(s : set) : int\n{\n if s == {} then 1\n else var x :| x in s; \n x * SetProduct(s - {x})\n}\n\n/* \n * This is necessary because, when we add one element, we need to make sure\n * that the product of the new set, as a whole, is the same as the product\n * of the old set times the new element.\n */\nlemma SetProductLemma(s: set , x: int) \n requires x in s\n ensures SetProduct(s - {x}) * x == SetProduct(s)\n{\n if s != {}\n {\n var y :| y in s && y * SetProduct(s - {y}) == SetProduct(s);\n if y == x {}\n else {\n calc {\n SetProduct(s);\n y * SetProduct(s - {y});\n { SetProductLemma(s - {y}, x); }\n y * x * SetProduct(s - {y} - {x});\n y * x * SetProduct(s - {x} - {y});\n x * y * SetProduct(s - {x} - {y});\n { SetProductLemma(s - {x}, y); }\n x * SetProduct(s - {x});\n }\n }\n }\n}" }, { "test_ID": "581", "test_file": "dafny-synthesis_task_id_574.dfy", "ground_truth": "method CylinderSurfaceArea(radius: real, height: real) returns (area: real)\n requires radius > 0.0 && height > 0.0\n ensures area == 2.0 * 3.14159265358979323846 * radius * (radius + height)\n{\n area := 2.0 * 3.14159265358979323846 * radius * (radius + height);\n}", "hints_removed": "method CylinderSurfaceArea(radius: real, height: real) returns (area: real)\n requires radius > 0.0 && height > 0.0\n ensures area == 2.0 * 3.14159265358979323846 * radius * (radius + height)\n{\n area := 2.0 * 3.14159265358979323846 * radius * (radius + height);\n}" }, { "test_ID": "582", "test_file": "dafny-synthesis_task_id_576.dfy", "ground_truth": "method IsSublist(sub: seq, main: seq) returns (result: bool)\n ensures true <== (exists i :: 0 <= i <= |main| - |sub| && sub == main[i..i + |sub|])\n{\n if |sub| > |main| {\n return false;\n }\n\n for i := 0 to |main| - |sub| + 1\n invariant 0 <= i <= |main| - |sub| + 1\n invariant true <== (exists j :: 0 <= j < i && sub == main[j..j + |sub|])\n {\n if sub == main[i..i + |sub|] {\n result := true;\n }\n }\n result := false;\n}", "hints_removed": "method IsSublist(sub: seq, main: seq) returns (result: bool)\n ensures true <== (exists i :: 0 <= i <= |main| - |sub| && sub == main[i..i + |sub|])\n{\n if |sub| > |main| {\n return false;\n }\n\n for i := 0 to |main| - |sub| + 1\n {\n if sub == main[i..i + |sub|] {\n result := true;\n }\n }\n result := false;\n}" }, { "test_ID": "583", "test_file": "dafny-synthesis_task_id_577.dfy", "ground_truth": "function Factorial(n: int): int\n requires n >= 0\n ensures 0 <= Factorial(n)\n {\n if n == 0 then 1\n else n * Factorial(n-1)\n }\n\n method FactorialOfLastDigit(n: int) returns (fact: int)\n requires n >= 0\n ensures fact == Factorial(n % 10)\n {\n var lastDigit := n % 10;\n fact := Factorial(lastDigit);\n }", "hints_removed": "function Factorial(n: int): int\n requires n >= 0\n ensures 0 <= Factorial(n)\n {\n if n == 0 then 1\n else n * Factorial(n-1)\n }\n\n method FactorialOfLastDigit(n: int) returns (fact: int)\n requires n >= 0\n ensures fact == Factorial(n % 10)\n {\n var lastDigit := n % 10;\n fact := Factorial(lastDigit);\n }" }, { "test_ID": "584", "test_file": "dafny-synthesis_task_id_578.dfy", "ground_truth": "method Interleave(s1: seq, s2: seq, s3: seq) returns (r: seq)\n requires |s1| == |s2| && |s2| == |s3|\n ensures |r| == 3 * |s1|\n ensures forall i :: 0 <= i < |s1| ==> r[3*i] == s1[i] && r[3*i + 1] == s2[i] && r[3*i + 2] == s3[i]\n{\n r := [];\n for i := 0 to |s1|\n invariant 0 <= i <= |s1|\n invariant |r| == 3 * i\n invariant forall k :: 0 <= k < i ==> r[3*k] == s1[k] && r[3*k + 1] == s2[k] && r[3*k + 2] == s3[k]\n {\n r := r + [s1[i], s2[i], s3[i]];\n }\n}", "hints_removed": "method Interleave(s1: seq, s2: seq, s3: seq) returns (r: seq)\n requires |s1| == |s2| && |s2| == |s3|\n ensures |r| == 3 * |s1|\n ensures forall i :: 0 <= i < |s1| ==> r[3*i] == s1[i] && r[3*i + 1] == s2[i] && r[3*i + 2] == s3[i]\n{\n r := [];\n for i := 0 to |s1|\n {\n r := r + [s1[i], s2[i], s3[i]];\n }\n}" }, { "test_ID": "585", "test_file": "dafny-synthesis_task_id_579.dfy", "ground_truth": "predicate InArray(a: array, x: int)\n reads a\n{\n exists i :: 0 <= i < a.Length && a[i] == x\n}\n\nmethod DissimilarElements(a: array, b: array) returns (result: seq)\n // All elements in the output are either in a or b, but not in both or neither\n ensures forall x :: x in result ==> (InArray(a, x) != InArray(b, x))\n // The elements in the output are all different\n ensures forall i, j :: 0 <= i < j < |result| ==> result[i] != result[j]\n{\n var res: seq := [];\n for i := 0 to a.Length\n invariant 0 <= i <= a.Length\n invariant forall x :: x in res ==> InArray(a, x)\n invariant forall x :: x in res ==> InArray(a, x) != InArray(b, x) \n invariant forall i, j :: 0 <= i < j < |res| ==> res[i] != res[j]\n {\n if !InArray(b, a[i]) && a[i] !in res\n {\n res := res + [a[i]];\n }\n }\n\n ghost var partialSize := |res|;\n for i := 0 to b.Length\n invariant 0 <= i <= b.Length\n invariant forall k :: partialSize <= k < |res| ==> InArray(b, res[k])\n invariant forall k :: 0 <= k < |res| ==> InArray(a, res[k]) != InArray(b, res[k]) \n invariant forall i, j :: 0 <= i < j < |res| ==> res[i] != res[j]\n {\n if !InArray(a, b[i]) && b[i] !in res\n {\n res := res + [b[i]];\n }\n }\n\n result := res;\n}", "hints_removed": "predicate InArray(a: array, x: int)\n reads a\n{\n exists i :: 0 <= i < a.Length && a[i] == x\n}\n\nmethod DissimilarElements(a: array, b: array) returns (result: seq)\n // All elements in the output are either in a or b, but not in both or neither\n ensures forall x :: x in result ==> (InArray(a, x) != InArray(b, x))\n // The elements in the output are all different\n ensures forall i, j :: 0 <= i < j < |result| ==> result[i] != result[j]\n{\n var res: seq := [];\n for i := 0 to a.Length\n {\n if !InArray(b, a[i]) && a[i] !in res\n {\n res := res + [a[i]];\n }\n }\n\n ghost var partialSize := |res|;\n for i := 0 to b.Length\n {\n if !InArray(a, b[i]) && b[i] !in res\n {\n res := res + [b[i]];\n }\n }\n\n result := res;\n}" }, { "test_ID": "586", "test_file": "dafny-synthesis_task_id_58.dfy", "ground_truth": "method HasOppositeSign(a: int, b: int) returns (result: bool)\n ensures result <==> (a < 0 && b > 0) || (a > 0 && b < 0)\n{\n result := (a < 0 && b > 0) || (a > 0 && b < 0);\n}", "hints_removed": "method HasOppositeSign(a: int, b: int) returns (result: bool)\n ensures result <==> (a < 0 && b > 0) || (a > 0 && b < 0)\n{\n result := (a < 0 && b > 0) || (a > 0 && b < 0);\n}" }, { "test_ID": "587", "test_file": "dafny-synthesis_task_id_581.dfy", "ground_truth": "method SquarePyramidSurfaceArea(baseEdge: int, height: int) returns (area: int)\n requires baseEdge > 0\n requires height > 0\n ensures area == baseEdge * baseEdge + 2 * baseEdge * height\n{\n area := baseEdge * baseEdge + 2 * baseEdge * height;\n}", "hints_removed": "method SquarePyramidSurfaceArea(baseEdge: int, height: int) returns (area: int)\n requires baseEdge > 0\n requires height > 0\n ensures area == baseEdge * baseEdge + 2 * baseEdge * height\n{\n area := baseEdge * baseEdge + 2 * baseEdge * height;\n}" }, { "test_ID": "588", "test_file": "dafny-synthesis_task_id_586.dfy", "ground_truth": "method SplitAndAppend(l: seq, n: int) returns (r: seq)\n requires n >= 0 && n < |l|\n ensures |r| == |l|\n ensures forall i :: 0 <= i < |l| ==> r[i] == l[(i + n) % |l|]\n{\n var firstPart: seq := l[..n];\n var secondPart: seq := l[n..];\n r := secondPart + firstPart;\n}", "hints_removed": "method SplitAndAppend(l: seq, n: int) returns (r: seq)\n requires n >= 0 && n < |l|\n ensures |r| == |l|\n ensures forall i :: 0 <= i < |l| ==> r[i] == l[(i + n) % |l|]\n{\n var firstPart: seq := l[..n];\n var secondPart: seq := l[n..];\n r := secondPart + firstPart;\n}" }, { "test_ID": "589", "test_file": "dafny-synthesis_task_id_587.dfy", "ground_truth": "method ArrayToSeq(a: array) returns (s: seq)\n requires a != null\n ensures |s| == a.Length\n ensures forall i :: 0 <= i < a.Length ==> s[i] == a[i]\n{\n s := [];\n for i := 0 to a.Length\n invariant 0 <= i <= a.Length\n invariant |s| == i\n invariant forall j :: 0 <= j < i ==> s[j] == a[j]\n {\n s := s + [a[i]];\n }\n}", "hints_removed": "method ArrayToSeq(a: array) returns (s: seq)\n requires a != null\n ensures |s| == a.Length\n ensures forall i :: 0 <= i < a.Length ==> s[i] == a[i]\n{\n s := [];\n for i := 0 to a.Length\n {\n s := s + [a[i]];\n }\n}" }, { "test_ID": "590", "test_file": "dafny-synthesis_task_id_588.dfy", "ground_truth": "method DifferenceMinMax(a: array) returns (diff: int)\n requires a.Length > 0\n ensures diff == Max(a[..]) - Min(a[..])\n{\n var minVal := a[0];\n var maxVal := a[0];\n\n for i := 1 to a.Length\n invariant 1 <= i <= a.Length\n invariant minVal <= maxVal\n invariant forall k :: 0 <= k < i ==> minVal <= a[k] && a[k] <= maxVal\n invariant minVal == Min(a[..i])\n invariant maxVal == Max(a[..i])\n {\n if a[i] < minVal {\n minVal := a[i];\n } else if a[i] > maxVal {\n maxVal := a[i];\n }\n assert a[..i+1][..i] == a[..i];\n }\n assert a[..a.Length] == a[..];\n diff := maxVal - minVal;\n}\n\n// The order of the recursion in these two functions\n// must match the order of the iteration in the algorithm above\nfunction Min(a: seq) : int\n requires |a| > 0\n{\n if |a| == 1 then a[0]\n else\n var minPrefix := Min(a[..|a|-1]);\n if a[|a|-1] <= minPrefix then a[|a|-1] else Min(a[..|a|-1])\n}\n\nfunction Max(a: seq) : int\n requires |a| > 0\n{\n if |a| == 1 then a[0]\n else\n var maxPrefix := Max(a[..|a|-1]);\n if a[|a|-1] >= maxPrefix then a[|a|-1] else Max(a[..|a|-1])\n}\n\n", "hints_removed": "method DifferenceMinMax(a: array) returns (diff: int)\n requires a.Length > 0\n ensures diff == Max(a[..]) - Min(a[..])\n{\n var minVal := a[0];\n var maxVal := a[0];\n\n for i := 1 to a.Length\n {\n if a[i] < minVal {\n minVal := a[i];\n } else if a[i] > maxVal {\n maxVal := a[i];\n }\n }\n diff := maxVal - minVal;\n}\n\n// The order of the recursion in these two functions\n// must match the order of the iteration in the algorithm above\nfunction Min(a: seq) : int\n requires |a| > 0\n{\n if |a| == 1 then a[0]\n else\n var minPrefix := Min(a[..|a|-1]);\n if a[|a|-1] <= minPrefix then a[|a|-1] else Min(a[..|a|-1])\n}\n\nfunction Max(a: seq) : int\n requires |a| > 0\n{\n if |a| == 1 then a[0]\n else\n var maxPrefix := Max(a[..|a|-1]);\n if a[|a|-1] >= maxPrefix then a[|a|-1] else Max(a[..|a|-1])\n}\n\n" }, { "test_ID": "591", "test_file": "dafny-synthesis_task_id_59.dfy", "ground_truth": "method NthOctagonalNumber(n: int) returns (octagonalNumber: int)\n requires n >= 0\n ensures octagonalNumber == n * (3 * n - 2)\n{\n octagonalNumber := n * (3 * n - 2);\n}", "hints_removed": "method NthOctagonalNumber(n: int) returns (octagonalNumber: int)\n requires n >= 0\n ensures octagonalNumber == n * (3 * n - 2)\n{\n octagonalNumber := n * (3 * n - 2);\n}" }, { "test_ID": "592", "test_file": "dafny-synthesis_task_id_591.dfy", "ground_truth": "method SwapFirstAndLast(a: array)\n requires a != null && a.Length > 0\n modifies a\n ensures a[0] == old(a[a.Length - 1]) && a[a.Length - 1] == old(a[0])\n ensures forall k :: 1 <= k < a.Length - 1 ==> a[k] == old(a[k])\n{\n var temp := a[0];\n a[0] := a[a.Length - 1];\n a[a.Length - 1] := temp;\n}", "hints_removed": "method SwapFirstAndLast(a: array)\n requires a != null && a.Length > 0\n modifies a\n ensures a[0] == old(a[a.Length - 1]) && a[a.Length - 1] == old(a[0])\n ensures forall k :: 1 <= k < a.Length - 1 ==> a[k] == old(a[k])\n{\n var temp := a[0];\n a[0] := a[a.Length - 1];\n a[a.Length - 1] := temp;\n}" }, { "test_ID": "593", "test_file": "dafny-synthesis_task_id_594.dfy", "ground_truth": "predicate IsEven(n: int)\n{\n n % 2 == 0\n}\n\npredicate IsOdd(n: int)\n{\n n % 2 != 0\n}\n\nmethod FirstEvenOddDifference(a: array) returns (diff: int)\n requires a.Length >= 2\n requires exists i :: 0 <= i < a.Length && IsEven(a[i])\n requires exists i :: 0 <= i < a.Length && IsOdd(a[i])\n ensures exists i, j :: 0 <= i < a.Length && 0 <= j < a.Length && IsEven(a[i]) && IsOdd(a[j]) && diff == a[i] - a[j] && \n (forall k :: 0 <= k < i ==> IsOdd(a[k])) && (forall k :: 0 <= k < j ==> IsEven(a[k]))\n{\n var firstEven: int := -1;\n var firstOdd: int := -1;\n\n for i := 0 to a.Length\n invariant 0 <= i <= a.Length\n invariant (firstEven == -1 || (0 <= firstEven < i && IsEven(a[firstEven])))\n invariant (firstOdd == -1 || (0 <= firstOdd < i && IsOdd(a[firstOdd])))\n invariant firstEven == -1 ==> (forall k :: 0 <= k < i ==> !IsEven(a[k]))\n invariant firstOdd == -1 ==> (forall k :: 0 <= k < i ==> !IsOdd(a[k]))\n invariant firstEven != -1 ==> (forall k :: 0 <= k < firstEven ==> IsOdd(a[k]))\n invariant firstOdd != -1 ==> (forall k :: 0 <= k < firstOdd ==> IsEven(a[k]))\n {\n if firstEven == -1 && IsEven(a[i])\n {\n firstEven := i;\n }\n if firstOdd == -1 && IsOdd(a[i])\n {\n firstOdd := i;\n }\n if firstEven != -1 && firstOdd != -1\n {\n break;\n }\n }\n diff := a[firstEven] - a[firstOdd];\n}", "hints_removed": "predicate IsEven(n: int)\n{\n n % 2 == 0\n}\n\npredicate IsOdd(n: int)\n{\n n % 2 != 0\n}\n\nmethod FirstEvenOddDifference(a: array) returns (diff: int)\n requires a.Length >= 2\n requires exists i :: 0 <= i < a.Length && IsEven(a[i])\n requires exists i :: 0 <= i < a.Length && IsOdd(a[i])\n ensures exists i, j :: 0 <= i < a.Length && 0 <= j < a.Length && IsEven(a[i]) && IsOdd(a[j]) && diff == a[i] - a[j] && \n (forall k :: 0 <= k < i ==> IsOdd(a[k])) && (forall k :: 0 <= k < j ==> IsEven(a[k]))\n{\n var firstEven: int := -1;\n var firstOdd: int := -1;\n\n for i := 0 to a.Length\n {\n if firstEven == -1 && IsEven(a[i])\n {\n firstEven := i;\n }\n if firstOdd == -1 && IsOdd(a[i])\n {\n firstOdd := i;\n }\n if firstEven != -1 && firstOdd != -1\n {\n break;\n }\n }\n diff := a[firstEven] - a[firstOdd];\n}" }, { "test_ID": "594", "test_file": "dafny-synthesis_task_id_598.dfy", "ground_truth": "method IsArmstrong(n: int) returns (result: bool)\n requires 100 <= n < 1000\n ensures result <==> (n == ((n / 100) * (n / 100) * (n / 100) + ((n / 10) % 10) * ((n / 10) % 10) * ((n / 10) % 10) + (n % 10) * (n % 10) * (n % 10)))\n{\n var a := n / 100;\n var b := (n / 10) % 10;\n var c := n % 10;\n\n result := n == (a * a * a + b * b * b + c * c * c);\n}", "hints_removed": "method IsArmstrong(n: int) returns (result: bool)\n requires 100 <= n < 1000\n ensures result <==> (n == ((n / 100) * (n / 100) * (n / 100) + ((n / 10) % 10) * ((n / 10) % 10) * ((n / 10) % 10) + (n % 10) * (n % 10) * (n % 10)))\n{\n var a := n / 100;\n var b := (n / 10) % 10;\n var c := n % 10;\n\n result := n == (a * a * a + b * b * b + c * c * c);\n}" }, { "test_ID": "595", "test_file": "dafny-synthesis_task_id_599.dfy", "ground_truth": "method SumAndAverage(n: int) returns (sum: int, average: real)\n requires n > 0\n ensures sum == n * (n + 1) / 2\n ensures average == sum as real / n as real\n{\n sum := 0;\n for i := 1 to n + 1\n invariant 0 <= i <= n + 1\n invariant sum == (i - 1) * i / 2\n {\n sum := sum + i;\n }\n average := sum as real / n as real;\n}", "hints_removed": "method SumAndAverage(n: int) returns (sum: int, average: real)\n requires n > 0\n ensures sum == n * (n + 1) / 2\n ensures average == sum as real / n as real\n{\n sum := 0;\n for i := 1 to n + 1\n {\n sum := sum + i;\n }\n average := sum as real / n as real;\n}" }, { "test_ID": "596", "test_file": "dafny-synthesis_task_id_600.dfy", "ground_truth": "method IsEven(n: int) returns (result: bool)\n ensures result <==> n % 2 == 0\n{\n result := n % 2 == 0;\n}", "hints_removed": "method IsEven(n: int) returns (result: bool)\n ensures result <==> n % 2 == 0\n{\n result := n % 2 == 0;\n}" }, { "test_ID": "597", "test_file": "dafny-synthesis_task_id_602.dfy", "ground_truth": "method FindFirstRepeatedChar(s: string) returns (found: bool, c: char)\n ensures found ==> exists i, j :: 0 <= i < j < |s| && s[i] == s[j] && s[i] == c && (forall k, l :: 0 <= k < l < j && s[k] == s[l] ==> k >= i)\n ensures !found ==> (forall i, j :: 0 <= i < j < |s| ==> s[i] != s[j])\n{\n c := ' ';\n found := false;\n var inner_found := false;\n var i := 0;\n while i < |s| && !found\n invariant 0 <= i <= |s|\n invariant found == inner_found\n // Found: there exists number ii less or equal to i, that we looked above it and found it. And, btw, that didn't happen for any number less than ii\n invariant found ==> exists ii, jj :: 0 <= ii < i && ii < jj < |s| && s[ii] == s[jj] && s[ii] == c && (forall k, l :: 0 <= k < l < jj && s[k] == s[l] ==> k >= ii)\n // Not found: for every number up to i, we looked above it, and didn't find it\n invariant !found <==> (forall ii, jj :: 0 <= ii < i && ii < jj < |s| ==> s[ii] != s[jj])\n {\n var j := i + 1;\n while j < |s| && !inner_found\n invariant i < j <= |s|\n invariant inner_found ==> exists k :: i < k < |s| && s[i] == s[k] && s[i] == c\n invariant !inner_found <==> (forall k :: i < k < j ==> s[i] != s[k])\n {\n if s[i] == s[j] {\n inner_found := true;\n c := s[i];\n }\n j := j + 1;\n }\n found := inner_found;\n i := i + 1;\n }\n}", "hints_removed": "method FindFirstRepeatedChar(s: string) returns (found: bool, c: char)\n ensures found ==> exists i, j :: 0 <= i < j < |s| && s[i] == s[j] && s[i] == c && (forall k, l :: 0 <= k < l < j && s[k] == s[l] ==> k >= i)\n ensures !found ==> (forall i, j :: 0 <= i < j < |s| ==> s[i] != s[j])\n{\n c := ' ';\n found := false;\n var inner_found := false;\n var i := 0;\n while i < |s| && !found\n // Found: there exists number ii less or equal to i, that we looked above it and found it. And, btw, that didn't happen for any number less than ii\n // Not found: for every number up to i, we looked above it, and didn't find it\n {\n var j := i + 1;\n while j < |s| && !inner_found\n {\n if s[i] == s[j] {\n inner_found := true;\n c := s[i];\n }\n j := j + 1;\n }\n found := inner_found;\n i := i + 1;\n }\n}" }, { "test_ID": "598", "test_file": "dafny-synthesis_task_id_603.dfy", "ground_truth": "method LucidNumbers(n: int) returns (lucid: seq)\n requires n >= 0\n ensures forall i :: 0 <= i < |lucid| ==> lucid[i] % 3 == 0\n ensures forall i :: 0 <= i < |lucid| ==> lucid[i] <= n\n ensures forall i, j :: 0 <= i < j < |lucid| ==> lucid[i] < lucid[j]\n{\n lucid := [];\n var i := 0;\n while i <= n\n invariant 0 <= i <= n + 1\n invariant forall k :: 0 <= k < |lucid| ==> lucid[k] % 3 == 0\n invariant forall k :: 0 <= k < |lucid| ==> lucid[k] <= i - 1\n invariant forall k, l :: 0 <= k < l < |lucid| ==> lucid[k] < lucid[l]\n {\n if i % 3 == 0 {\n lucid := lucid + [i];\n }\n i := i + 1;\n }\n}", "hints_removed": "method LucidNumbers(n: int) returns (lucid: seq)\n requires n >= 0\n ensures forall i :: 0 <= i < |lucid| ==> lucid[i] % 3 == 0\n ensures forall i :: 0 <= i < |lucid| ==> lucid[i] <= n\n ensures forall i, j :: 0 <= i < j < |lucid| ==> lucid[i] < lucid[j]\n{\n lucid := [];\n var i := 0;\n while i <= n\n {\n if i % 3 == 0 {\n lucid := lucid + [i];\n }\n i := i + 1;\n }\n}" }, { "test_ID": "599", "test_file": "dafny-synthesis_task_id_605.dfy", "ground_truth": "method IsPrime(n: int) returns (result: bool)\n requires n >= 2\n ensures result <==> (forall k :: 2 <= k < n ==> n % k != 0)\n{\n result := true;\n var i := 2;\n while i <= n/2\n invariant 2 <= i\n invariant result <==> (forall k :: 2 <= k < i ==> n % k != 0)\n {\n if n % i == 0\n {\n result := false;\n break;\n }\n i := i + 1;\n }\n}", "hints_removed": "method IsPrime(n: int) returns (result: bool)\n requires n >= 2\n ensures result <==> (forall k :: 2 <= k < n ==> n % k != 0)\n{\n result := true;\n var i := 2;\n while i <= n/2\n {\n if n % i == 0\n {\n result := false;\n break;\n }\n i := i + 1;\n }\n}" }, { "test_ID": "600", "test_file": "dafny-synthesis_task_id_606.dfy", "ground_truth": "method DegreesToRadians(degrees: real) returns (radians: real)\n ensures radians == degrees * 3.14159265358979323846 / 180.0\n{\n radians := degrees * 3.14159265358979323846 / 180.0;\n}", "hints_removed": "method DegreesToRadians(degrees: real) returns (radians: real)\n ensures radians == degrees * 3.14159265358979323846 / 180.0\n{\n radians := degrees * 3.14159265358979323846 / 180.0;\n}" }, { "test_ID": "601", "test_file": "dafny-synthesis_task_id_61.dfy", "ground_truth": "predicate IsDigit(c: char)\n{\n 48 <= c as int <= 57\n}\n\nmethod CountSubstringsWithSumOfDigitsEqualToLength(s: string) returns (count: int)\n ensures count >= 0\n{\n count := 0;\n for i := 0 to |s|\n invariant 0 <= i <= |s|\n {\n var sum := 0;\n for j := i to |s|\n invariant i <= j <= |s|\n invariant sum >= 0\n invariant sum <= j - i\n {\n if j == |s| || !IsDigit(s[j]) {\n if sum == j - i {\n count := count + 1;\n }\n break;\n }\n sum := sum + (s[j] as int - 48);\n if sum > j - i + 1 {\n break;\n }\n }\n }\n \n}\n", "hints_removed": "predicate IsDigit(c: char)\n{\n 48 <= c as int <= 57\n}\n\nmethod CountSubstringsWithSumOfDigitsEqualToLength(s: string) returns (count: int)\n ensures count >= 0\n{\n count := 0;\n for i := 0 to |s|\n {\n var sum := 0;\n for j := i to |s|\n {\n if j == |s| || !IsDigit(s[j]) {\n if sum == j - i {\n count := count + 1;\n }\n break;\n }\n sum := sum + (s[j] as int - 48);\n if sum > j - i + 1 {\n break;\n }\n }\n }\n \n}\n" }, { "test_ID": "602", "test_file": "dafny-synthesis_task_id_610.dfy", "ground_truth": "method RemoveElement(s: array, k: int) returns (v: array)\n requires 0 <= k < s.Length\n ensures v.Length == s.Length - 1\n ensures forall i :: 0 <= i < k ==> v[i] == s[i]\n ensures forall i :: k <= i < v.Length ==> v[i] == s[i + 1]\n{\n v := new int[s.Length - 1];\n var i := 0;\n while i < k\n invariant 0 <= i <= k\n invariant forall j :: 0 <= j < i ==> v[j] == s[j]\n {\n v[i] := s[i];\n i := i + 1;\n }\n assert forall i :: 0 <= i < k ==> v[i] == s[i];\n while i < v.Length\n invariant k <= i <= v.Length\n invariant forall j :: k <= j < i ==> v[j] == s[j + 1]\n invariant forall i :: 0 <= i < k ==> v[i] == s[i]\n {\n v[i] := s[i + 1];\n i := i + 1;\n }\n}", "hints_removed": "method RemoveElement(s: array, k: int) returns (v: array)\n requires 0 <= k < s.Length\n ensures v.Length == s.Length - 1\n ensures forall i :: 0 <= i < k ==> v[i] == s[i]\n ensures forall i :: k <= i < v.Length ==> v[i] == s[i + 1]\n{\n v := new int[s.Length - 1];\n var i := 0;\n while i < k\n {\n v[i] := s[i];\n i := i + 1;\n }\n while i < v.Length\n {\n v[i] := s[i + 1];\n i := i + 1;\n }\n}" }, { "test_ID": "603", "test_file": "dafny-synthesis_task_id_616.dfy", "ground_truth": "method ElementWiseModulo(a: array, b: array) returns (result: array)\n requires a != null && b != null\n requires a.Length == b.Length\n requires forall i :: 0 <= i < b.Length ==> b[i] != 0\n ensures result != null\n ensures result.Length == a.Length\n ensures forall i :: 0 <= i < result.Length ==> result[i] == a[i] % b[i]\n{\n result := new int[a.Length];\n var i := 0;\n while i < a.Length\n invariant 0 <= i <= a.Length\n invariant result.Length == a.Length\n invariant forall k :: 0 <= k < i ==> result[k] == a[k] % b[k]\n {\n result[i] := a[i] % b[i];\n i := i + 1;\n }\n}", "hints_removed": "method ElementWiseModulo(a: array, b: array) returns (result: array)\n requires a != null && b != null\n requires a.Length == b.Length\n requires forall i :: 0 <= i < b.Length ==> b[i] != 0\n ensures result != null\n ensures result.Length == a.Length\n ensures forall i :: 0 <= i < result.Length ==> result[i] == a[i] % b[i]\n{\n result := new int[a.Length];\n var i := 0;\n while i < a.Length\n {\n result[i] := a[i] % b[i];\n i := i + 1;\n }\n}" }, { "test_ID": "604", "test_file": "dafny-synthesis_task_id_618.dfy", "ground_truth": "method ElementWiseDivide(a: seq, b: seq) returns (result: seq)\n requires |a| == |b|\n requires forall i :: 0 <= i < |b| ==> b[i] != 0\n ensures |result| == |a|\n ensures forall i :: 0 <= i < |result| ==> result[i] == a[i] / b[i]\n{\n result := [];\n for i := 0 to |a|\n invariant 0 <= i <= |a|\n invariant |result| == i\n invariant forall k :: 0 <= k < i ==> result[k] == a[k] / b[k]\n {\n result := result + [a[i] / b[i]];\n }\n}", "hints_removed": "method ElementWiseDivide(a: seq, b: seq) returns (result: seq)\n requires |a| == |b|\n requires forall i :: 0 <= i < |b| ==> b[i] != 0\n ensures |result| == |a|\n ensures forall i :: 0 <= i < |result| ==> result[i] == a[i] / b[i]\n{\n result := [];\n for i := 0 to |a|\n {\n result := result + [a[i] / b[i]];\n }\n}" }, { "test_ID": "605", "test_file": "dafny-synthesis_task_id_62.dfy", "ground_truth": "method FindSmallest(s: array) returns (min: int)\n requires s.Length > 0\n ensures forall i :: 0 <= i < s.Length ==> min <= s[i]\n ensures exists i :: 0 <= i < s.Length && min == s[i]\n{\n min := s[0];\n for i := 1 to s.Length\n invariant 0 <= i <= s.Length\n invariant forall k :: 0 <= k < i ==> min <= s[k]\n invariant exists k :: 0 <= k < i && min == s[k]\n {\n if s[i] < min\n {\n min := s[i];\n }\n }\n}", "hints_removed": "method FindSmallest(s: array) returns (min: int)\n requires s.Length > 0\n ensures forall i :: 0 <= i < s.Length ==> min <= s[i]\n ensures exists i :: 0 <= i < s.Length && min == s[i]\n{\n min := s[0];\n for i := 1 to s.Length\n {\n if s[i] < min\n {\n min := s[i];\n }\n }\n}" }, { "test_ID": "606", "test_file": "dafny-synthesis_task_id_622.dfy", "ground_truth": "method FindMedian(a: array, b: array) returns (median: int)\n requires a != null && b != null\n requires a.Length == b.Length\n requires a.Length > 0\n requires forall i :: 0 <= i < a.Length - 1 ==> a[i] <= a[i + 1]\n requires forall i :: 0 <= i < b.Length - 1 ==> b[i] <= b[i + 1]\n ensures median == if (a.Length % 2 == 0) then (a[a.Length / 2 - 1] + b[0]) / 2 else a[a.Length / 2]\n{\n if (a.Length % 2 == 0) {\n median := (a[a.Length / 2 - 1] + b[0]) / 2;\n } else {\n median := a[a.Length / 2];\n }\n}", "hints_removed": "method FindMedian(a: array, b: array) returns (median: int)\n requires a != null && b != null\n requires a.Length == b.Length\n requires a.Length > 0\n requires forall i :: 0 <= i < a.Length - 1 ==> a[i] <= a[i + 1]\n requires forall i :: 0 <= i < b.Length - 1 ==> b[i] <= b[i + 1]\n ensures median == if (a.Length % 2 == 0) then (a[a.Length / 2 - 1] + b[0]) / 2 else a[a.Length / 2]\n{\n if (a.Length % 2 == 0) {\n median := (a[a.Length / 2 - 1] + b[0]) / 2;\n } else {\n median := a[a.Length / 2];\n }\n}" }, { "test_ID": "607", "test_file": "dafny-synthesis_task_id_623.dfy", "ground_truth": "method PowerOfListElements(l: seq, n: int) returns (result: seq)\n requires n >= 0\n ensures |result| == |l|\n ensures forall i :: 0 <= i < |l| ==> result[i] == Power(l[i], n)\n{\n result := [];\n for i := 0 to |l|\n invariant 0 <= i <= |l|\n invariant |result| == i\n invariant forall k :: 0 <= k < i ==> result[k] == Power(l[k], n)\n {\n result := result + [Power(l[i], n)];\n }\n}\n\nfunction Power(base: int, exponent: int): int\n requires exponent >= 0\n{\n if exponent == 0 then 1\n else base * Power(base, exponent-1)\n}", "hints_removed": "method PowerOfListElements(l: seq, n: int) returns (result: seq)\n requires n >= 0\n ensures |result| == |l|\n ensures forall i :: 0 <= i < |l| ==> result[i] == Power(l[i], n)\n{\n result := [];\n for i := 0 to |l|\n {\n result := result + [Power(l[i], n)];\n }\n}\n\nfunction Power(base: int, exponent: int): int\n requires exponent >= 0\n{\n if exponent == 0 then 1\n else base * Power(base, exponent-1)\n}" }, { "test_ID": "608", "test_file": "dafny-synthesis_task_id_624.dfy", "ground_truth": "predicate IsLowerCase(c : char)\n{\n 97 <= c as int <= 122\n}\n\npredicate IsLowerUpperPair(c : char, C : char)\n{\n (c as int) == (C as int) + 32\n}\n\nfunction ShiftMinus32(c : char) : char\n{\n ((c as int - 32) % 128) as char\n}\n\nmethod ToUppercase(s: string) returns (v: string)\n ensures |v| == |s|\n ensures forall i :: 0 <= i < |s| ==> if IsLowerCase(s[i]) then IsLowerUpperPair(s[i], v[i]) else v[i] == s[i]\n{\n var s' : string := [];\n for i := 0 to |s|\n invariant 0 <= i <= |s|\n invariant |s'| == i\n invariant forall k :: 0 <= k < i && IsLowerCase(s[k]) ==> IsLowerUpperPair(s[k], s'[k])\n invariant forall k :: 0 <= k < i && !IsLowerCase(s[k]) ==> s[k] == s'[k]\n {\n if IsLowerCase(s[i])\n {\n s' := s' + [ShiftMinus32(s[i])];\n }\n else \n {\n s' := s' + [s[i]];\n }\n }\n return s';\n}\n", "hints_removed": "predicate IsLowerCase(c : char)\n{\n 97 <= c as int <= 122\n}\n\npredicate IsLowerUpperPair(c : char, C : char)\n{\n (c as int) == (C as int) + 32\n}\n\nfunction ShiftMinus32(c : char) : char\n{\n ((c as int - 32) % 128) as char\n}\n\nmethod ToUppercase(s: string) returns (v: string)\n ensures |v| == |s|\n ensures forall i :: 0 <= i < |s| ==> if IsLowerCase(s[i]) then IsLowerUpperPair(s[i], v[i]) else v[i] == s[i]\n{\n var s' : string := [];\n for i := 0 to |s|\n {\n if IsLowerCase(s[i])\n {\n s' := s' + [ShiftMinus32(s[i])];\n }\n else \n {\n s' := s' + [s[i]];\n }\n }\n return s';\n}\n" }, { "test_ID": "609", "test_file": "dafny-synthesis_task_id_625.dfy", "ground_truth": "method SwapFirstAndLast(a: array)\n requires a.Length > 0\n modifies a\n ensures a[0] == old(a[a.Length - 1])\n ensures a[a.Length - 1] == old(a[0])\n ensures forall k :: 1 <= k < a.Length - 1 ==> a[k] == old(a[k])\n{\n var tmp := a[0];\n a[0] := a[a.Length - 1];\n a[a.Length - 1] := tmp;\n}", "hints_removed": "method SwapFirstAndLast(a: array)\n requires a.Length > 0\n modifies a\n ensures a[0] == old(a[a.Length - 1])\n ensures a[a.Length - 1] == old(a[0])\n ensures forall k :: 1 <= k < a.Length - 1 ==> a[k] == old(a[k])\n{\n var tmp := a[0];\n a[0] := a[a.Length - 1];\n a[a.Length - 1] := tmp;\n}" }, { "test_ID": "610", "test_file": "dafny-synthesis_task_id_626.dfy", "ground_truth": "method AreaOfLargestTriangleInSemicircle(radius: int) returns (area: int)\n requires radius > 0\n ensures area == radius * radius\n{\n area := radius * radius;\n}", "hints_removed": "method AreaOfLargestTriangleInSemicircle(radius: int) returns (area: int)\n requires radius > 0\n ensures area == radius * radius\n{\n area := radius * radius;\n}" }, { "test_ID": "611", "test_file": "dafny-synthesis_task_id_627.dfy", "ground_truth": "method SmallestMissingNumber(s: seq) returns (v: int)\n requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j]\n requires forall i :: 0 <= i < |s| ==> s[i] >= 0\n ensures 0 <= v\n ensures v !in s\n ensures forall k :: 0 <= k < v ==> k in s\n{\n v := 0;\n for i := 0 to |s|\n invariant 0 <= i <= |s|\n invariant 0 <= v <= i\n invariant v !in s[..i]\n invariant forall k :: 0 <= k < v && s[k] != v ==> k in s[..i]\n {\n if s[i] > v\n {\n break;\n }\n else\n {\n if s[i] == v \n {\n v := v + 1;\n }\n }\n }\n assert forall k :: 0 <= k < v && s[k] != v ==> k in s;\n}", "hints_removed": "method SmallestMissingNumber(s: seq) returns (v: int)\n requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j]\n requires forall i :: 0 <= i < |s| ==> s[i] >= 0\n ensures 0 <= v\n ensures v !in s\n ensures forall k :: 0 <= k < v ==> k in s\n{\n v := 0;\n for i := 0 to |s|\n {\n if s[i] > v\n {\n break;\n }\n else\n {\n if s[i] == v \n {\n v := v + 1;\n }\n }\n }\n}" }, { "test_ID": "612", "test_file": "dafny-synthesis_task_id_629.dfy", "ground_truth": "predicate IsEven(n: int)\n{\n n % 2 == 0\n}\n\nmethod FindEvenNumbers(arr: array) returns (evenList: seq)\n // All numbers in the output are even and exist in the input \n ensures forall i :: 0 <= i < |evenList| ==> IsEven(evenList[i]) && evenList[i] in arr[..]\n // All even numbers in the input are in the output\n ensures forall i :: 0 <= i < arr.Length && IsEven(arr[i]) ==> arr[i] in evenList\n{\n evenList := [];\n for i := 0 to arr.Length\n invariant 0 <= i <= arr.Length\n invariant 0 <= |evenList| <= i\n invariant forall k :: 0 <= k < |evenList| ==> IsEven(evenList[k]) && evenList[k] in arr[..]\n invariant forall k :: 0 <= k < i && IsEven(arr[k]) ==> arr[k] in evenList\n {\n if IsEven(arr[i])\n {\n evenList := evenList + [arr[i]];\n }\n }\n}\n", "hints_removed": "predicate IsEven(n: int)\n{\n n % 2 == 0\n}\n\nmethod FindEvenNumbers(arr: array) returns (evenList: seq)\n // All numbers in the output are even and exist in the input \n ensures forall i :: 0 <= i < |evenList| ==> IsEven(evenList[i]) && evenList[i] in arr[..]\n // All even numbers in the input are in the output\n ensures forall i :: 0 <= i < arr.Length && IsEven(arr[i]) ==> arr[i] in evenList\n{\n evenList := [];\n for i := 0 to arr.Length\n {\n if IsEven(arr[i])\n {\n evenList := evenList + [arr[i]];\n }\n }\n}\n" }, { "test_ID": "613", "test_file": "dafny-synthesis_task_id_632.dfy", "ground_truth": "method MoveZeroesToEnd(arr: array)\n requires arr.Length >= 2\n modifies arr\n // Same size\n ensures arr.Length == old(arr.Length)\n // Zeros to the right of the first zero\n ensures forall i, j :: 0 <= i < j < arr.Length && arr[i] == 0 ==> arr[j] == 0\n // The final array is a permutation of the original one\n ensures multiset(arr[..]) == multiset(old(arr[..]))\n // Relative order of non-zero elements is preserved\n ensures forall n, m /* on old array */:: 0 <= n < m < arr.Length && old(arr[n]) != 0 && old(arr[m]) != 0 ==> \n exists k, l /* on new array */:: 0 <= k < l < arr.Length && arr[k] == old(arr[n]) && arr[l] == old(arr[m])\n //ensures IsOrderPreserved(arr[..], old(arr[..]))\n // Number of zeros is preserved\n{\n var i := 0;\n var j := 0;\n\n assert 0 <= i <= arr.Length;\n assert forall k :: 0 <= k < arr.Length ==> arr[k] == old(arr[k]);\n //assert(forall n, m :: 0 <= n < m < arr.Length ==> arr[n] == old(arr[n]) && arr[m] == old(arr[m]));\n while j < arr.Length\n invariant 0 <= i <= j <= arr.Length\n // Elements to the right of j are unchanged\n invariant forall k :: j <= k < arr.Length ==> old(arr[k]) == arr[k]\n // Everything to the left of i is non-zero\n invariant forall k :: 0 <= k < i ==> arr[k] != 0\n // Everything between i and j, but excluding j, is zero\n invariant forall k :: i <= k < j ==> arr[k] == 0\n // If there there are zeros, they are to the right of i\n invariant forall k :: 0 <= k < j && arr[k] == 0 ==> k >= i\n // No new numbers are added, up to j\n invariant forall k :: 0 <= k < j && arr[k] != old(arr[k]) ==> exists l :: 0 <= l < j && arr[k] == old(arr[l])\n // The new array up to j is always a permutation of the original one\n invariant multiset(arr[..]) == multiset(old(arr[..]))\n // Relative order of non-zero elements is always preserved\n //invariant IsOrderPreserved(arr[..], old(arr[..]))\n invariant forall n, m /* on old */:: 0 <= n < m < j && old(arr[n]) != 0 && old(arr[m]) != 0 ==> \n exists k, l /* on new */:: 0 <= k < l < i && arr[k] == old(arr[n]) && arr[l] == old(arr[m])\n {\n\n if arr[j] != 0\n {\n if i != j\n {\n assert(arr[j] != 0);\n swap(arr, i, j);\n assert(forall k :: 0 <= k <= j ==> exists l :: 0 <= l <= j && arr[k] == old(arr[l]));\n }\n i := i + 1;\n }\n j := j + 1;\n }\n assert j == arr.Length;\n}\n\nmethod swap(arr: array, i: int, j: int)\n requires arr.Length > 0\n requires 0 <= i < arr.Length && 0 <= j < arr.Length\n modifies arr\n ensures arr[i] == old(arr[j]) && arr[j] == old(arr[i])\n ensures forall k :: 0 <= k < arr.Length && k != i && k != j ==> arr[k] == old(arr[k])\n ensures multiset(arr[..]) == multiset(old(arr[..]))\n{\n var tmp := arr[i];\n arr[i] := arr[j];\n arr[j] := tmp;\n}\n\nfunction count(arr: seq, value: int) : (c: nat)\n ensures c <= |arr|\n{\n if |arr| == 0 then 0 else (if arr[0] == value then 1 else 0) + count(arr[1..], value)\n}\n\n", "hints_removed": "method MoveZeroesToEnd(arr: array)\n requires arr.Length >= 2\n modifies arr\n // Same size\n ensures arr.Length == old(arr.Length)\n // Zeros to the right of the first zero\n ensures forall i, j :: 0 <= i < j < arr.Length && arr[i] == 0 ==> arr[j] == 0\n // The final array is a permutation of the original one\n ensures multiset(arr[..]) == multiset(old(arr[..]))\n // Relative order of non-zero elements is preserved\n ensures forall n, m /* on old array */:: 0 <= n < m < arr.Length && old(arr[n]) != 0 && old(arr[m]) != 0 ==> \n exists k, l /* on new array */:: 0 <= k < l < arr.Length && arr[k] == old(arr[n]) && arr[l] == old(arr[m])\n //ensures IsOrderPreserved(arr[..], old(arr[..]))\n // Number of zeros is preserved\n{\n var i := 0;\n var j := 0;\n\n while j < arr.Length\n // Elements to the right of j are unchanged\n // Everything to the left of i is non-zero\n // Everything between i and j, but excluding j, is zero\n // If there there are zeros, they are to the right of i\n // No new numbers are added, up to j\n // The new array up to j is always a permutation of the original one\n // Relative order of non-zero elements is always preserved\n {\n\n if arr[j] != 0\n {\n if i != j\n {\n swap(arr, i, j);\n }\n i := i + 1;\n }\n j := j + 1;\n }\n}\n\nmethod swap(arr: array, i: int, j: int)\n requires arr.Length > 0\n requires 0 <= i < arr.Length && 0 <= j < arr.Length\n modifies arr\n ensures arr[i] == old(arr[j]) && arr[j] == old(arr[i])\n ensures forall k :: 0 <= k < arr.Length && k != i && k != j ==> arr[k] == old(arr[k])\n ensures multiset(arr[..]) == multiset(old(arr[..]))\n{\n var tmp := arr[i];\n arr[i] := arr[j];\n arr[j] := tmp;\n}\n\nfunction count(arr: seq, value: int) : (c: nat)\n ensures c <= |arr|\n{\n if |arr| == 0 then 0 else (if arr[0] == value then 1 else 0) + count(arr[1..], value)\n}\n\n" }, { "test_ID": "614", "test_file": "dafny-synthesis_task_id_637.dfy", "ground_truth": "method IsBreakEven(costPrice: int, sellingPrice: int) returns (result: bool)\n requires costPrice >= 0 && sellingPrice >= 0\n ensures result <==> costPrice == sellingPrice\n{\n result := costPrice == sellingPrice;\n}", "hints_removed": "method IsBreakEven(costPrice: int, sellingPrice: int) returns (result: bool)\n requires costPrice >= 0 && sellingPrice >= 0\n ensures result <==> costPrice == sellingPrice\n{\n result := costPrice == sellingPrice;\n}" }, { "test_ID": "615", "test_file": "dafny-synthesis_task_id_641.dfy", "ground_truth": "method NthNonagonalNumber(n: int) returns (number: int)\n requires n >= 0\n ensures number == n * (7 * n - 5) / 2\n{\n number := n * (7 * n - 5) / 2;\n}", "hints_removed": "method NthNonagonalNumber(n: int) returns (number: int)\n requires n >= 0\n ensures number == n * (7 * n - 5) / 2\n{\n number := n * (7 * n - 5) / 2;\n}" }, { "test_ID": "616", "test_file": "dafny-synthesis_task_id_644.dfy", "ground_truth": "method Reverse(a: array)\n\tmodifies a;\n\tensures forall k :: 0 <= k < a.Length ==> a[k] == old(a[(a.Length-1) - k]);\n{\n\tvar l := a.Length - 1;\n\tvar i := 0;\n\twhile (i < l-i)\n\t\tinvariant 0 <= i <= (l+1)/2;\n\t\tinvariant forall k :: 0 <= k < i || l-i < k <= l ==> a[k] == old(a[l-k]);\n\t\tinvariant forall k :: i <= k <= l-i ==> a[k] == old(a[k]);\n\t{\n\t\ta[i], a[l-i] := a[l-i], a[i];\n\t\ti := i + 1;\n\t}\n}\n\nmethod ReverseUptoK(s: array, k: int)\n modifies s\n requires 2 <= k <= s.Length\n ensures forall i :: 0 <= i < k ==> s[i] == old(s[k - 1 - i])\n ensures forall i :: k <= i < s.Length ==> s[i] == old(s[i])\n{\n\tvar l := k - 1;\n\tvar i := 0;\n\twhile (i < l-i)\n\t\tinvariant 0 <= i <= (l+1)/2;\n\t\tinvariant forall p :: 0 <= p < i || l-i < p <= l ==> s[p] == old(s[l-p]);\n\t\tinvariant forall p :: i <= p <= l-i ==> s[p] == old(s[p]);\n invariant forall p :: k <= p < s.Length ==> s[p] == old(s[p])\n\t{\n\t\ts[i], s[l-i] := s[l-i], s[i];\n\t\ti := i + 1;\n\t}\n\n}", "hints_removed": "method Reverse(a: array)\n\tmodifies a;\n\tensures forall k :: 0 <= k < a.Length ==> a[k] == old(a[(a.Length-1) - k]);\n{\n\tvar l := a.Length - 1;\n\tvar i := 0;\n\twhile (i < l-i)\n\t{\n\t\ta[i], a[l-i] := a[l-i], a[i];\n\t\ti := i + 1;\n\t}\n}\n\nmethod ReverseUptoK(s: array, k: int)\n modifies s\n requires 2 <= k <= s.Length\n ensures forall i :: 0 <= i < k ==> s[i] == old(s[k - 1 - i])\n ensures forall i :: k <= i < s.Length ==> s[i] == old(s[i])\n{\n\tvar l := k - 1;\n\tvar i := 0;\n\twhile (i < l-i)\n\t{\n\t\ts[i], s[l-i] := s[l-i], s[i];\n\t\ti := i + 1;\n\t}\n\n}" }, { "test_ID": "617", "test_file": "dafny-synthesis_task_id_69.dfy", "ground_truth": "method ContainsSequence(list: seq>, sub: seq) returns (result: bool)\n ensures result <==> (exists i :: 0 <= i < |list| && sub == list[i])\n{\n result := false;\n for i := 0 to |list|\n invariant 0 <= i <= |list|\n invariant result <==> (exists k :: 0 <= k < i && sub == list[k])\n {\n if sub == list[i] {\n result := true;\n break;\n }\n }\n}", "hints_removed": "method ContainsSequence(list: seq>, sub: seq) returns (result: bool)\n ensures result <==> (exists i :: 0 <= i < |list| && sub == list[i])\n{\n result := false;\n for i := 0 to |list|\n {\n if sub == list[i] {\n result := true;\n break;\n }\n }\n}" }, { "test_ID": "618", "test_file": "dafny-synthesis_task_id_70.dfy", "ground_truth": "method AllSequencesEqualLength(sequences: seq>) returns (result: bool)\n ensures result <==> forall i, j :: 0 <= i < |sequences| && 0 <= j < |sequences| ==> |sequences[i]| == |sequences[j]|\n{\n if |sequences| == 0 {\n return true;\n }\n\n var firstLength := |sequences[0]|;\n result := true;\n\n for i := 1 to |sequences|\n invariant 1 <= i <= |sequences|\n invariant result <==> forall k :: 0 <= k < i ==> |sequences[k]| == firstLength\n {\n if |sequences[i]| != firstLength {\n result := false;\n break;\n }\n }\n}", "hints_removed": "method AllSequencesEqualLength(sequences: seq>) returns (result: bool)\n ensures result <==> forall i, j :: 0 <= i < |sequences| && 0 <= j < |sequences| ==> |sequences[i]| == |sequences[j]|\n{\n if |sequences| == 0 {\n return true;\n }\n\n var firstLength := |sequences[0]|;\n result := true;\n\n for i := 1 to |sequences|\n {\n if |sequences[i]| != firstLength {\n result := false;\n break;\n }\n }\n}" }, { "test_ID": "619", "test_file": "dafny-synthesis_task_id_728.dfy", "ground_truth": "method AddLists(a: seq, b: seq) returns (result: seq)\n requires |a| == |b|\n ensures |result| == |a|\n ensures forall i :: 0 <= i < |result| ==> result[i] == a[i] + b[i]\n{\n result := [];\n for i := 0 to |a|\n invariant 0 <= i <= |a|\n invariant |result| == i\n invariant forall k :: 0 <= k < i ==> result[k] == a[k] + b[k]\n {\n result := result + [a[i] + b[i]];\n }\n}", "hints_removed": "method AddLists(a: seq, b: seq) returns (result: seq)\n requires |a| == |b|\n ensures |result| == |a|\n ensures forall i :: 0 <= i < |result| ==> result[i] == a[i] + b[i]\n{\n result := [];\n for i := 0 to |a|\n {\n result := result + [a[i] + b[i]];\n }\n}" }, { "test_ID": "620", "test_file": "dafny-synthesis_task_id_732.dfy", "ground_truth": "predicate IsSpaceCommaDot(c: char)\n{\n c == ' ' || c == ',' || c == '.'\n}\n\nmethod ReplaceWithColon(s: string) returns (v: string)\n ensures |v| == |s|\n ensures forall i :: 0 <= i < |s| ==> (IsSpaceCommaDot(s[i]) ==> v[i] == ':') && (!IsSpaceCommaDot(s[i]) ==> v[i] == s[i])\n{\n var s' : string := [];\n for i := 0 to |s|\n invariant 0 <= i <= |s|\n invariant |s'| == i\n invariant forall k :: 0 <= k < i ==> (IsSpaceCommaDot(s[k]) ==> s'[k] == ':') && (!IsSpaceCommaDot(s[k]) ==> s'[k] == s[k])\n {\n if IsSpaceCommaDot(s[i])\n {\n s' := s' + [':'];\n }\n else \n {\n s' := s' + [s[i]];\n }\n }\n return s';\n}", "hints_removed": "predicate IsSpaceCommaDot(c: char)\n{\n c == ' ' || c == ',' || c == '.'\n}\n\nmethod ReplaceWithColon(s: string) returns (v: string)\n ensures |v| == |s|\n ensures forall i :: 0 <= i < |s| ==> (IsSpaceCommaDot(s[i]) ==> v[i] == ':') && (!IsSpaceCommaDot(s[i]) ==> v[i] == s[i])\n{\n var s' : string := [];\n for i := 0 to |s|\n {\n if IsSpaceCommaDot(s[i])\n {\n s' := s' + [':'];\n }\n else \n {\n s' := s' + [s[i]];\n }\n }\n return s';\n}" }, { "test_ID": "621", "test_file": "dafny-synthesis_task_id_733.dfy", "ground_truth": "method FindFirstOccurrence(arr: array, target: int) returns (index: int)\n requires arr != null\n requires forall i, j :: 0 <= i < j < arr.Length ==> arr[i] <= arr[j]\n ensures 0 <= index < arr.Length ==> arr[index] == target\n ensures index == -1 ==> forall i :: 0 <= i < arr.Length ==> arr[i] != target\n ensures forall i :: 0 <= i < arr.Length ==> arr[i] == old(arr[i])\n{\n index := -1;\n for i := 0 to arr.Length\n invariant 0 <= i <= arr.Length\n invariant index == -1 ==> forall k :: 0 <= k < i ==> arr[k] != target\n invariant 0 <= index < i ==> arr[index] == target\n invariant forall k :: 0 <= k < arr.Length ==> arr[k] == old(arr[k])\n {\n if arr[i] == target\n {\n index := i;\n break;\n }\n if arr[i] > target\n {\n break;\n }\n }\n}", "hints_removed": "method FindFirstOccurrence(arr: array, target: int) returns (index: int)\n requires arr != null\n requires forall i, j :: 0 <= i < j < arr.Length ==> arr[i] <= arr[j]\n ensures 0 <= index < arr.Length ==> arr[index] == target\n ensures index == -1 ==> forall i :: 0 <= i < arr.Length ==> arr[i] != target\n ensures forall i :: 0 <= i < arr.Length ==> arr[i] == old(arr[i])\n{\n index := -1;\n for i := 0 to arr.Length\n {\n if arr[i] == target\n {\n index := i;\n break;\n }\n if arr[i] > target\n {\n break;\n }\n }\n}" }, { "test_ID": "622", "test_file": "dafny-synthesis_task_id_741.dfy", "ground_truth": "method AllCharactersSame(s: string) returns (result: bool)\n ensures result ==> forall i, j :: 0 <= i < |s| && 0 <= j < |s| ==> s[i] == s[j]\n ensures !result ==> (|s| > 1) && (exists i, j :: 0 <= i < |s| && 0 <= j < |s| && i != j && s[i] != s[j])\n{\n if |s| <= 1 {\n return true;\n }\n\n var firstChar := s[0];\n result := true;\n\n for i := 1 to |s|\n invariant 0 <= i <= |s|\n invariant result ==> forall k :: 0 <= k < i ==> s[k] == firstChar\n {\n if s[i] != firstChar {\n result := false;\n break;\n }\n }\n}", "hints_removed": "method AllCharactersSame(s: string) returns (result: bool)\n ensures result ==> forall i, j :: 0 <= i < |s| && 0 <= j < |s| ==> s[i] == s[j]\n ensures !result ==> (|s| > 1) && (exists i, j :: 0 <= i < |s| && 0 <= j < |s| && i != j && s[i] != s[j])\n{\n if |s| <= 1 {\n return true;\n }\n\n var firstChar := s[0];\n result := true;\n\n for i := 1 to |s|\n {\n if s[i] != firstChar {\n result := false;\n break;\n }\n }\n}" }, { "test_ID": "623", "test_file": "dafny-synthesis_task_id_743.dfy", "ground_truth": "method RotateRight(l: seq, n: int) returns (r: seq)\n requires n >= 0\n ensures |r| == |l|\n ensures forall i :: 0 <= i < |l| ==> r[i] == l[(i - n + |l|) % |l|]\n{\n var rotated: seq := [];\n for i := 0 to |l|\n invariant 0 <= i <= |l|\n invariant |rotated| == i\n invariant forall k :: 0 <= k < i ==> rotated[k] == l[(k - n + |l|) % |l|]\n {\n rotated := rotated + [l[(i - n + |l|) % |l|]];\n }\n return rotated;\n}", "hints_removed": "method RotateRight(l: seq, n: int) returns (r: seq)\n requires n >= 0\n ensures |r| == |l|\n ensures forall i :: 0 <= i < |l| ==> r[i] == l[(i - n + |l|) % |l|]\n{\n var rotated: seq := [];\n for i := 0 to |l|\n {\n rotated := rotated + [l[(i - n + |l|) % |l|]];\n }\n return rotated;\n}" }, { "test_ID": "624", "test_file": "dafny-synthesis_task_id_750.dfy", "ground_truth": "method AddTupleToList(l: seq<(int, int)>, t: (int, int)) returns (r: seq<(int, int)>)\n ensures |r| == |l| + 1\n ensures r[|r| - 1] == t\n ensures forall i :: 0 <= i < |l| ==> r[i] == l[i]\n{\n r := l + [t];\n}", "hints_removed": "method AddTupleToList(l: seq<(int, int)>, t: (int, int)) returns (r: seq<(int, int)>)\n ensures |r| == |l| + 1\n ensures r[|r| - 1] == t\n ensures forall i :: 0 <= i < |l| ==> r[i] == l[i]\n{\n r := l + [t];\n}" }, { "test_ID": "625", "test_file": "dafny-synthesis_task_id_751.dfy", "ground_truth": "method IsMinHeap(a: array) returns (result: bool)\n requires a != null\n ensures result ==> forall i :: 0 <= i < a.Length / 2 ==> a[i] <= a[2*i + 1] && (2*i + 2 == a.Length || a[i] <= a[2*i + 2])\n ensures !result ==> exists i :: 0 <= i < a.Length / 2 && (a[i] > a[2*i + 1] || (2*i + 2 != a.Length && a[i] > a[2*i + 2]))\n{\n result := true;\n for i := 0 to a.Length / 2\n invariant 0 <= i <= a.Length / 2\n invariant result ==> forall k :: 0 <= k < i ==> a[k] <= a[2*k + 1] && (2*k + 2 == a.Length || a[k] <= a[2*k + 2])\n {\n if a[i] > a[2*i + 1] || (2*i + 2 != a.Length && a[i] > a[2*i + 2]) {\n result := false;\n break;\n }\n }\n}", "hints_removed": "method IsMinHeap(a: array) returns (result: bool)\n requires a != null\n ensures result ==> forall i :: 0 <= i < a.Length / 2 ==> a[i] <= a[2*i + 1] && (2*i + 2 == a.Length || a[i] <= a[2*i + 2])\n ensures !result ==> exists i :: 0 <= i < a.Length / 2 && (a[i] > a[2*i + 1] || (2*i + 2 != a.Length && a[i] > a[2*i + 2]))\n{\n result := true;\n for i := 0 to a.Length / 2\n {\n if a[i] > a[2*i + 1] || (2*i + 2 != a.Length && a[i] > a[2*i + 2]) {\n result := false;\n break;\n }\n }\n}" }, { "test_ID": "626", "test_file": "dafny-synthesis_task_id_755.dfy", "ground_truth": "function MinPair(s: seq) : (r: int)\n requires |s| == 2\n ensures s[0] <= s[1] <==> r == s[0]\n ensures s[0] > s[1] ==> r == s[1] \n{\n if s[0] <= s[1] then s[0] else s[1]\n}\n\n\nfunction min(s: seq) : (r: int)\n requires |s| >= 2\n ensures forall i :: 0 <= i < |s| ==> r <= s[i]\n{\n if |s| == 2 then MinPair(s)\n else MinPair([s[0], min(s[1..])])\n}\n\n\nmethod SecondSmallest(s: array) returns (secondSmallest: int)\n requires s.Length >= 2\n // There must be at least 2 different values, a minimum and another one\n requires exists i, j :: 0 <= i < s.Length && 0 <= j < s.Length && i != j && s[i] == min(s[..]) && s[j] != s[i]\n ensures exists i, j :: 0 <= i < s.Length && 0 <= j < s.Length && i != j && s[i] == min(s[..]) && s[j] == secondSmallest \n ensures forall k :: 0 <= k < s.Length && s[k] != min(s[..]) ==> s[k] >= secondSmallest\n{\n var minIndex := 0;\n var secondMinIndex := 1;\n\n if s[1] < s[0] {\n minIndex := 1;\n secondMinIndex := 0;\n }\n\n for i := 2 to s.Length\n invariant 0 <= i <= s.Length\n invariant 0 <= minIndex < i\n invariant 0 <= secondMinIndex < i\n invariant minIndex != secondMinIndex\n invariant forall k :: 0 <= k < i ==> s[k] >= s[minIndex]\n invariant forall k :: 0 <= k < i && k != minIndex ==> s[k] >= s[secondMinIndex]\n {\n if s[i] < s[minIndex] {\n secondMinIndex := minIndex;\n minIndex := i;\n } else if s[i] < s[secondMinIndex] {\n secondMinIndex := i;\n }\n }\n\n secondSmallest := s[secondMinIndex];\n}\n", "hints_removed": "function MinPair(s: seq) : (r: int)\n requires |s| == 2\n ensures s[0] <= s[1] <==> r == s[0]\n ensures s[0] > s[1] ==> r == s[1] \n{\n if s[0] <= s[1] then s[0] else s[1]\n}\n\n\nfunction min(s: seq) : (r: int)\n requires |s| >= 2\n ensures forall i :: 0 <= i < |s| ==> r <= s[i]\n{\n if |s| == 2 then MinPair(s)\n else MinPair([s[0], min(s[1..])])\n}\n\n\nmethod SecondSmallest(s: array) returns (secondSmallest: int)\n requires s.Length >= 2\n // There must be at least 2 different values, a minimum and another one\n requires exists i, j :: 0 <= i < s.Length && 0 <= j < s.Length && i != j && s[i] == min(s[..]) && s[j] != s[i]\n ensures exists i, j :: 0 <= i < s.Length && 0 <= j < s.Length && i != j && s[i] == min(s[..]) && s[j] == secondSmallest \n ensures forall k :: 0 <= k < s.Length && s[k] != min(s[..]) ==> s[k] >= secondSmallest\n{\n var minIndex := 0;\n var secondMinIndex := 1;\n\n if s[1] < s[0] {\n minIndex := 1;\n secondMinIndex := 0;\n }\n\n for i := 2 to s.Length\n {\n if s[i] < s[minIndex] {\n secondMinIndex := minIndex;\n minIndex := i;\n } else if s[i] < s[secondMinIndex] {\n secondMinIndex := i;\n }\n }\n\n secondSmallest := s[secondMinIndex];\n}\n" }, { "test_ID": "627", "test_file": "dafny-synthesis_task_id_759.dfy", "ground_truth": "method IsDecimalWithTwoPrecision(s: string) returns (result: bool)\n ensures result ==> (exists i :: 0 <= i < |s| && s[i] == '.' && |s| - i - 1 == 2)\n ensures !result ==> !(exists i :: 0 <= i < |s| && s[i] == '.' && |s| - i - 1 == 2)\n{\n result := false;\n for i := 0 to |s|\n invariant 0 <= i <= |s|\n invariant result <==> (exists k :: 0 <= k < i && s[k] == '.' && |s| - k - 1 == 2)\n {\n if s[i] == '.' && |s| - i - 1 == 2 {\n result := true;\n break;\n }\n }\n}", "hints_removed": "method IsDecimalWithTwoPrecision(s: string) returns (result: bool)\n ensures result ==> (exists i :: 0 <= i < |s| && s[i] == '.' && |s| - i - 1 == 2)\n ensures !result ==> !(exists i :: 0 <= i < |s| && s[i] == '.' && |s| - i - 1 == 2)\n{\n result := false;\n for i := 0 to |s|\n {\n if s[i] == '.' && |s| - i - 1 == 2 {\n result := true;\n break;\n }\n }\n}" }, { "test_ID": "628", "test_file": "dafny-synthesis_task_id_760.dfy", "ground_truth": "method HasOnlyOneDistinctElement(a: array) returns (result: bool)\n requires a != null\n ensures result ==> forall i, j :: 0 <= i < a.Length && 0 <= j < a.Length ==> a[i] == a[j]\n ensures !result ==> exists i, j :: 0 <= i < a.Length && 0 <= j < a.Length && a[i] != a[j]\n{\n if a.Length == 0 {\n return true;\n }\n\n var firstElement := a[0];\n result := true;\n\n for i := 1 to a.Length\n invariant 1 <= i <= a.Length\n invariant result ==> forall k :: 0 <= k < i ==> a[k] == firstElement\n {\n if a[i] != firstElement {\n result := false;\n break;\n }\n }\n}", "hints_removed": "method HasOnlyOneDistinctElement(a: array) returns (result: bool)\n requires a != null\n ensures result ==> forall i, j :: 0 <= i < a.Length && 0 <= j < a.Length ==> a[i] == a[j]\n ensures !result ==> exists i, j :: 0 <= i < a.Length && 0 <= j < a.Length && a[i] != a[j]\n{\n if a.Length == 0 {\n return true;\n }\n\n var firstElement := a[0];\n result := true;\n\n for i := 1 to a.Length\n {\n if a[i] != firstElement {\n result := false;\n break;\n }\n }\n}" }, { "test_ID": "629", "test_file": "dafny-synthesis_task_id_762.dfy", "ground_truth": "method IsMonthWith30Days(month: int) returns (result: bool)\n requires 1 <= month <= 12\n ensures result <==> month == 4 || month == 6 || month == 9 || month == 11\n{\n result := month == 4 || month == 6 || month == 9 || month == 11;\n}", "hints_removed": "method IsMonthWith30Days(month: int) returns (result: bool)\n requires 1 <= month <= 12\n ensures result <==> month == 4 || month == 6 || month == 9 || month == 11\n{\n result := month == 4 || month == 6 || month == 9 || month == 11;\n}" }, { "test_ID": "630", "test_file": "dafny-synthesis_task_id_764.dfy", "ground_truth": "predicate IsDigit(c: char)\n{\n 48 <= c as int <= 57\n}\n\n\nmethod CountDigits(s: string) returns (count: int)\n ensures count >= 0\n ensures count == | set i: int | 0 <= i < |s| && IsDigit(s[i])|\n{\n var digits := set i: int | 0 <= i < |s| && IsDigit(s[i]);\n count := |digits|;\n}\n\n", "hints_removed": "predicate IsDigit(c: char)\n{\n 48 <= c as int <= 57\n}\n\n\nmethod CountDigits(s: string) returns (count: int)\n ensures count >= 0\n ensures count == | set i: int | 0 <= i < |s| && IsDigit(s[i])|\n{\n var digits := set i: int | 0 <= i < |s| && IsDigit(s[i]);\n count := |digits|;\n}\n\n" }, { "test_ID": "631", "test_file": "dafny-synthesis_task_id_769.dfy", "ground_truth": "method Difference(a: seq, b: seq) returns (diff: seq)\n ensures forall x :: x in diff <==> (x in a && x !in b)\n ensures forall i, j :: 0 <= i < j < |diff| ==> diff[i] != diff[j]\n{\n diff := [];\n for i := 0 to |a|\n invariant 0 <= i <= |a|\n invariant forall x :: x in diff <==> (x in a[..i] && x !in b)\n invariant forall i, j :: 0 <= i < j < |diff| ==> diff[i] != diff[j]\n {\n if a[i] !in b && a[i] !in diff\n {\n diff := diff + [a[i]];\n }\n }\n}", "hints_removed": "method Difference(a: seq, b: seq) returns (diff: seq)\n ensures forall x :: x in diff <==> (x in a && x !in b)\n ensures forall i, j :: 0 <= i < j < |diff| ==> diff[i] != diff[j]\n{\n diff := [];\n for i := 0 to |a|\n {\n if a[i] !in b && a[i] !in diff\n {\n diff := diff + [a[i]];\n }\n }\n}" }, { "test_ID": "632", "test_file": "dafny-synthesis_task_id_77.dfy", "ground_truth": "method IsDivisibleBy11(n: int) returns (result: bool)\n ensures result <==> n % 11 == 0\n{\n result := n % 11 == 0;\n}", "hints_removed": "method IsDivisibleBy11(n: int) returns (result: bool)\n ensures result <==> n % 11 == 0\n{\n result := n % 11 == 0;\n}" }, { "test_ID": "633", "test_file": "dafny-synthesis_task_id_770.dfy", "ground_truth": "method SumOfFourthPowerOfOddNumbers(n: int) returns (sum: int)\n requires n > 0\n ensures sum == n * (2 * n + 1) * (24 * n * n * n - 12 * n * n - 14 * n + 7) / 15\n{\n sum := 0;\n var i := 1;\n for k := 0 to n\n invariant 0 <= k <= n\n invariant i == 2 * k + 1\n invariant sum == k * (2 * k + 1) * (24 * k * k * k - 12 * k * k - 14 * k + 7) / 15\n {\n sum := sum + i * i * i * i;\n i := i + 2;\n }\n}", "hints_removed": "method SumOfFourthPowerOfOddNumbers(n: int) returns (sum: int)\n requires n > 0\n ensures sum == n * (2 * n + 1) * (24 * n * n * n - 12 * n * n - 14 * n + 7) / 15\n{\n sum := 0;\n var i := 1;\n for k := 0 to n\n {\n sum := sum + i * i * i * i;\n i := i + 2;\n }\n}" }, { "test_ID": "634", "test_file": "dafny-synthesis_task_id_775.dfy", "ground_truth": "predicate IsOdd(n: int)\n{\n n % 2 == 1\n}\n\nmethod IsOddAtIndexOdd(a: array) returns (result: bool)\n ensures result <==> forall i :: 0 <= i < a.Length ==> (IsOdd(i) ==> IsOdd(a[i]))\n{\n result := true;\n for i := 0 to a.Length\n invariant 0 <= i <= a.Length\n invariant result <==> forall k :: 0 <= k < i ==> (IsOdd(k) ==> IsOdd(a[k]))\n {\n if IsOdd(i) && !IsOdd(a[i])\n {\n result := false;\n break;\n }\n }\n}", "hints_removed": "predicate IsOdd(n: int)\n{\n n % 2 == 1\n}\n\nmethod IsOddAtIndexOdd(a: array) returns (result: bool)\n ensures result <==> forall i :: 0 <= i < a.Length ==> (IsOdd(i) ==> IsOdd(a[i]))\n{\n result := true;\n for i := 0 to a.Length\n {\n if IsOdd(i) && !IsOdd(a[i])\n {\n result := false;\n break;\n }\n }\n}" }, { "test_ID": "635", "test_file": "dafny-synthesis_task_id_776.dfy", "ground_truth": "predicate IsVowel(c: char)\n{\n c in {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}\n}\n\nmethod CountVowelNeighbors(s: string) returns (count: int)\n ensures count >= 0\n ensures count == | set i: int | 1 <= i < |s|-1 && IsVowel(s[i-1]) && IsVowel(s[i+1]) |\n{\n var vowels := set i: int | 1 <= i < |s|-1 && IsVowel(s[i-1]) && IsVowel(s[i+1]);\n count := |vowels|;\n}", "hints_removed": "predicate IsVowel(c: char)\n{\n c in {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}\n}\n\nmethod CountVowelNeighbors(s: string) returns (count: int)\n ensures count >= 0\n ensures count == | set i: int | 1 <= i < |s|-1 && IsVowel(s[i-1]) && IsVowel(s[i+1]) |\n{\n var vowels := set i: int | 1 <= i < |s|-1 && IsVowel(s[i-1]) && IsVowel(s[i+1]);\n count := |vowels|;\n}" }, { "test_ID": "636", "test_file": "dafny-synthesis_task_id_784.dfy", "ground_truth": "predicate IsEven(n: int)\n{\n n % 2 == 0\n}\n\npredicate IsOdd(n: int)\n{\n n % 2 != 0\n}\n\npredicate IsFirstEven(evenIndex: int, lst: seq)\n requires 0 <= evenIndex < |lst|\n requires IsEven(lst[evenIndex])\n{\n forall i :: 0 <= i < evenIndex ==> IsOdd(lst[i])\n}\n\npredicate IsFirstOdd(oddIndex: int, lst: seq)\n requires 0 <= oddIndex < |lst|\n requires IsOdd(lst[oddIndex])\n{\n forall i :: 0 <= i < oddIndex ==> IsEven(lst[i])\n}\n\n\nmethod FirstEvenOddIndices(lst : seq) returns (evenIndex: int, oddIndex : int)\n requires |lst| >= 2\n requires exists i :: 0 <= i < |lst| && IsEven(lst[i])\n requires exists i :: 0 <= i < |lst| && IsOdd(lst[i])\n ensures 0 <= evenIndex < |lst|\n ensures 0 <= oddIndex < |lst|\n // This is the postcondition that ensures that it's the first, not just any\n ensures IsEven(lst[evenIndex]) && IsFirstEven(evenIndex, lst)\n ensures IsOdd(lst[oddIndex]) && IsFirstOdd(oddIndex, lst)\n{\n for i := 0 to |lst|\n invariant 0 <= i <= |lst|\n invariant forall j :: 0 <= j < i ==> IsOdd(lst[j])\n {\n if IsEven(lst[i])\n {\n evenIndex := i;\n break;\n }\n }\n\n for i := 0 to |lst|\n invariant 0 <= i <= |lst|\n invariant forall j :: 0 <= j < i ==> IsEven(lst[j])\n {\n if IsOdd(lst[i])\n {\n oddIndex := i;\n break;\n }\n }\n}\n\nmethod ProductEvenOdd(lst: seq) returns (product : int)\n requires |lst| >= 2\n requires exists i :: 0 <= i < |lst| && IsEven(lst[i])\n requires exists i :: 0 <= i < |lst| && IsOdd(lst[i])\n ensures exists i, j :: 0 <= i < |lst| && IsEven(lst[i]) && IsFirstEven(i, lst) && \n 0 <= j < |lst| && IsOdd(lst[j]) && IsFirstOdd(j, lst) && product == lst[i] * lst[j]\n{\n var evenIndex, oddIndex := FirstEvenOddIndices(lst);\n product := lst[evenIndex] * lst[oddIndex];\n}", "hints_removed": "predicate IsEven(n: int)\n{\n n % 2 == 0\n}\n\npredicate IsOdd(n: int)\n{\n n % 2 != 0\n}\n\npredicate IsFirstEven(evenIndex: int, lst: seq)\n requires 0 <= evenIndex < |lst|\n requires IsEven(lst[evenIndex])\n{\n forall i :: 0 <= i < evenIndex ==> IsOdd(lst[i])\n}\n\npredicate IsFirstOdd(oddIndex: int, lst: seq)\n requires 0 <= oddIndex < |lst|\n requires IsOdd(lst[oddIndex])\n{\n forall i :: 0 <= i < oddIndex ==> IsEven(lst[i])\n}\n\n\nmethod FirstEvenOddIndices(lst : seq) returns (evenIndex: int, oddIndex : int)\n requires |lst| >= 2\n requires exists i :: 0 <= i < |lst| && IsEven(lst[i])\n requires exists i :: 0 <= i < |lst| && IsOdd(lst[i])\n ensures 0 <= evenIndex < |lst|\n ensures 0 <= oddIndex < |lst|\n // This is the postcondition that ensures that it's the first, not just any\n ensures IsEven(lst[evenIndex]) && IsFirstEven(evenIndex, lst)\n ensures IsOdd(lst[oddIndex]) && IsFirstOdd(oddIndex, lst)\n{\n for i := 0 to |lst|\n {\n if IsEven(lst[i])\n {\n evenIndex := i;\n break;\n }\n }\n\n for i := 0 to |lst|\n {\n if IsOdd(lst[i])\n {\n oddIndex := i;\n break;\n }\n }\n}\n\nmethod ProductEvenOdd(lst: seq) returns (product : int)\n requires |lst| >= 2\n requires exists i :: 0 <= i < |lst| && IsEven(lst[i])\n requires exists i :: 0 <= i < |lst| && IsOdd(lst[i])\n ensures exists i, j :: 0 <= i < |lst| && IsEven(lst[i]) && IsFirstEven(i, lst) && \n 0 <= j < |lst| && IsOdd(lst[j]) && IsFirstOdd(j, lst) && product == lst[i] * lst[j]\n{\n var evenIndex, oddIndex := FirstEvenOddIndices(lst);\n product := lst[evenIndex] * lst[oddIndex];\n}" }, { "test_ID": "637", "test_file": "dafny-synthesis_task_id_79.dfy", "ground_truth": "method IsLengthOdd(s: string) returns (result: bool)\n ensures result <==> |s| % 2 == 1\n{\n result := |s| % 2 == 1;\n}", "hints_removed": "method IsLengthOdd(s: string) returns (result: bool)\n ensures result <==> |s| % 2 == 1\n{\n result := |s| % 2 == 1;\n}" }, { "test_ID": "638", "test_file": "dafny-synthesis_task_id_790.dfy", "ground_truth": "predicate IsEven(n: int)\n{\n n % 2 == 0\n}\n\nmethod IsEvenAtIndexEven(lst: seq) returns (result: bool)\n ensures result <==> forall i :: 0 <= i < |lst| ==> (IsEven(i) ==> IsEven(lst[i]))\n{\n result := true;\n for i := 0 to |lst|\n invariant 0 <= i <= |lst|\n invariant result <==> forall k :: 0 <= k < i ==> (IsEven(k) ==> IsEven(lst[k]))\n {\n if IsEven(i) && !IsEven(lst[i])\n {\n result := false;\n break;\n }\n }\n}", "hints_removed": "predicate IsEven(n: int)\n{\n n % 2 == 0\n}\n\nmethod IsEvenAtIndexEven(lst: seq) returns (result: bool)\n ensures result <==> forall i :: 0 <= i < |lst| ==> (IsEven(i) ==> IsEven(lst[i]))\n{\n result := true;\n for i := 0 to |lst|\n {\n if IsEven(i) && !IsEven(lst[i])\n {\n result := false;\n break;\n }\n }\n}" }, { "test_ID": "639", "test_file": "dafny-synthesis_task_id_792.dfy", "ground_truth": "method CountLists(lists: seq>) returns (count: int)\n ensures count >= 0\n ensures count == |lists|\n{\n count := |lists|;\n}", "hints_removed": "method CountLists(lists: seq>) returns (count: int)\n ensures count >= 0\n ensures count == |lists|\n{\n count := |lists|;\n}" }, { "test_ID": "640", "test_file": "dafny-synthesis_task_id_793.dfy", "ground_truth": "method LastPosition(arr: array, elem: int) returns (pos: int)\n requires arr.Length > 0\n requires forall i, j :: 0 <= i < j < arr.Length ==> arr[i] <= arr[j]\n ensures pos == -1 || (0 <= pos < arr.Length && arr[pos] == elem && (pos <= arr.Length - 1 || arr[pos + 1] > elem))\n ensures forall i :: 0 <= i < arr.Length ==> arr[i] == old(arr[i])\n{\n pos := -1;\n for i := 0 to arr.Length - 1\n invariant 0 <= i <= arr.Length\n invariant pos == -1 || (0 <= pos < i && arr[pos] == elem && (pos == i - 1 || arr[pos + 1] > elem))\n invariant forall k :: 0 <= k < arr.Length ==> arr[k] == old(arr[k])\n {\n if arr[i] == elem\n {\n pos := i;\n }\n }\n}", "hints_removed": "method LastPosition(arr: array, elem: int) returns (pos: int)\n requires arr.Length > 0\n requires forall i, j :: 0 <= i < j < arr.Length ==> arr[i] <= arr[j]\n ensures pos == -1 || (0 <= pos < arr.Length && arr[pos] == elem && (pos <= arr.Length - 1 || arr[pos + 1] > elem))\n ensures forall i :: 0 <= i < arr.Length ==> arr[i] == old(arr[i])\n{\n pos := -1;\n for i := 0 to arr.Length - 1\n {\n if arr[i] == elem\n {\n pos := i;\n }\n }\n}" }, { "test_ID": "641", "test_file": "dafny-synthesis_task_id_798.dfy", "ground_truth": "function sumTo( a:array, n:int ) : int\n requires a != null;\n requires 0 <= n && n <= a.Length;\n decreases n;\n reads a;\n{\n if (n == 0) then 0 else sumTo(a, n-1) + a[n-1]\n}\n\nmethod ArraySum(a: array) returns (result: int)\n ensures result == sumTo(a, a.Length)\n{\n result := 0;\n for i := 0 to a.Length\n invariant 0 <= i <= a.Length\n invariant result == sumTo(a, i)\n {\n result := result + a[i];\n }\n}\n", "hints_removed": "function sumTo( a:array, n:int ) : int\n requires a != null;\n requires 0 <= n && n <= a.Length;\n reads a;\n{\n if (n == 0) then 0 else sumTo(a, n-1) + a[n-1]\n}\n\nmethod ArraySum(a: array) returns (result: int)\n ensures result == sumTo(a, a.Length)\n{\n result := 0;\n for i := 0 to a.Length\n {\n result := result + a[i];\n }\n}\n" }, { "test_ID": "642", "test_file": "dafny-synthesis_task_id_799.dfy", "ground_truth": "method RotateLeftBits(n: bv32, d: int) returns (result: bv32)\n requires 0 <= d < 32\n ensures result == ((n << d) | (n >> (32 - d)))\n{\n result := ((n << d) | (n >> (32 - d)));\n}", "hints_removed": "method RotateLeftBits(n: bv32, d: int) returns (result: bv32)\n requires 0 <= d < 32\n ensures result == ((n << d) | (n >> (32 - d)))\n{\n result := ((n << d) | (n >> (32 - d)));\n}" }, { "test_ID": "643", "test_file": "dafny-synthesis_task_id_8.dfy", "ground_truth": "method SquareElements(a: array) returns (squared: array)\n ensures squared.Length == a.Length\n ensures forall i :: 0 <= i < a.Length ==> squared[i] == a[i] * a[i]\n{\n squared := new int[a.Length];\n for i := 0 to a.Length\n invariant 0 <= i <= a.Length\n invariant squared.Length == a.Length\n invariant forall k :: 0 <= k < i ==> squared[k] == a[k] * a[k]\n {\n squared[i] := a[i] * a[i];\n }\n}", "hints_removed": "method SquareElements(a: array) returns (squared: array)\n ensures squared.Length == a.Length\n ensures forall i :: 0 <= i < a.Length ==> squared[i] == a[i] * a[i]\n{\n squared := new int[a.Length];\n for i := 0 to a.Length\n {\n squared[i] := a[i] * a[i];\n }\n}" }, { "test_ID": "644", "test_file": "dafny-synthesis_task_id_80.dfy", "ground_truth": "method TetrahedralNumber(n: int) returns (t: int)\n requires n >= 0\n ensures t == n * (n + 1) * (n + 2) / 6\n{\n t := n * (n + 1) * (n + 2) / 6;\n}", "hints_removed": "method TetrahedralNumber(n: int) returns (t: int)\n requires n >= 0\n ensures t == n * (n + 1) * (n + 2) / 6\n{\n t := n * (n + 1) * (n + 2) / 6;\n}" }, { "test_ID": "645", "test_file": "dafny-synthesis_task_id_801.dfy", "ground_truth": "method CountEqualNumbers(a: int, b: int, c: int) returns (count: int)\n ensures count >= 0 && count <= 3\n ensures (count == 3) <==> (a == b && b == c)\n ensures (count == 2) <==> ((a == b && b != c) || (a != b && b == c) || (a == c && b != c))\n ensures (count == 1) <==> (a != b && b != c && a != c)\n{\n count := 1;\n if (a == b) {\n count := count + 1;\n }\n if (a == c) {\n count := count + 1;\n }\n if (a != b && b == c) {\n count := count + 1;\n }\n}", "hints_removed": "method CountEqualNumbers(a: int, b: int, c: int) returns (count: int)\n ensures count >= 0 && count <= 3\n ensures (count == 3) <==> (a == b && b == c)\n ensures (count == 2) <==> ((a == b && b != c) || (a != b && b == c) || (a == c && b != c))\n ensures (count == 1) <==> (a != b && b != c && a != c)\n{\n count := 1;\n if (a == b) {\n count := count + 1;\n }\n if (a == c) {\n count := count + 1;\n }\n if (a != b && b == c) {\n count := count + 1;\n }\n}" }, { "test_ID": "646", "test_file": "dafny-synthesis_task_id_803.dfy", "ground_truth": "method IsPerfectSquare(n: int) returns (result: bool)\n requires n >= 0\n ensures result == true ==> (exists i: int :: 0 <= i <= n && i * i == n)\n ensures result == false ==> (forall a: int :: 0 < a*a < n ==> a*a != n)\n{\n var i := 0;\n while (i * i < n)\n invariant 0 <= i <= n\n invariant forall k :: 0 <= k < i ==> k * k < n\n {\n i := i + 1;\n }\n return i * i == n;\n}", "hints_removed": "method IsPerfectSquare(n: int) returns (result: bool)\n requires n >= 0\n ensures result == true ==> (exists i: int :: 0 <= i <= n && i * i == n)\n ensures result == false ==> (forall a: int :: 0 < a*a < n ==> a*a != n)\n{\n var i := 0;\n while (i * i < n)\n {\n i := i + 1;\n }\n return i * i == n;\n}" }, { "test_ID": "647", "test_file": "dafny-synthesis_task_id_804.dfy", "ground_truth": "predicate IsEven(n: int)\n{\n n % 2 == 0\n}\n\nmethod IsProductEven(a: array) returns (result: bool)\n ensures result <==> exists i :: 0 <= i < a.Length && IsEven(a[i])\n{\n result := false;\n for i := 0 to a.Length\n invariant 0 <= i <= a.Length\n invariant result <==> exists k :: 0 <= k < i && IsEven(a[k])\n {\n if IsEven(a[i])\n {\n result := true;\n break;\n }\n }\n}", "hints_removed": "predicate IsEven(n: int)\n{\n n % 2 == 0\n}\n\nmethod IsProductEven(a: array) returns (result: bool)\n ensures result <==> exists i :: 0 <= i < a.Length && IsEven(a[i])\n{\n result := false;\n for i := 0 to a.Length\n {\n if IsEven(a[i])\n {\n result := true;\n break;\n }\n }\n}" }, { "test_ID": "648", "test_file": "dafny-synthesis_task_id_807.dfy", "ground_truth": "predicate IsOdd(x: int)\n{\n x % 2 != 0\n}\n\nmethod FindFirstOdd(a: array) returns (found: bool, index: int)\n requires a != null\n ensures !found ==> forall i :: 0 <= i < a.Length ==> !IsOdd(a[i])\n ensures found ==> 0 <= index < a.Length && IsOdd(a[index]) && forall i :: 0 <= i < index ==> !IsOdd(a[i])\n{\n found := false;\n index := 0;\n while (index < a.Length)\n invariant 0 <= index <= a.Length\n invariant !found ==> forall i :: 0 <= i < index ==> !IsOdd(a[i])\n invariant found ==> IsOdd(a[index - 1]) && forall i :: 0 <= i < index - 1 ==> !IsOdd(a[i])\n {\n if IsOdd(a[index])\n {\n found := true;\n return;\n }\n index := index + 1;\n }\n}", "hints_removed": "predicate IsOdd(x: int)\n{\n x % 2 != 0\n}\n\nmethod FindFirstOdd(a: array) returns (found: bool, index: int)\n requires a != null\n ensures !found ==> forall i :: 0 <= i < a.Length ==> !IsOdd(a[i])\n ensures found ==> 0 <= index < a.Length && IsOdd(a[index]) && forall i :: 0 <= i < index ==> !IsOdd(a[i])\n{\n found := false;\n index := 0;\n while (index < a.Length)\n {\n if IsOdd(a[index])\n {\n found := true;\n return;\n }\n index := index + 1;\n }\n}" }, { "test_ID": "649", "test_file": "dafny-synthesis_task_id_808.dfy", "ground_truth": "method ContainsK(s: seq, k: int) returns (result: bool)\n ensures result <==> k in s\n{\n result := false;\n for i := 0 to |s|\n invariant 0 <= i <= |s|\n invariant result <==> (exists j :: 0 <= j < i && s[j] == k)\n {\n if s[i] == k {\n result := true;\n break;\n }\n }\n}", "hints_removed": "method ContainsK(s: seq, k: int) returns (result: bool)\n ensures result <==> k in s\n{\n result := false;\n for i := 0 to |s|\n {\n if s[i] == k {\n result := true;\n break;\n }\n }\n}" }, { "test_ID": "650", "test_file": "dafny-synthesis_task_id_809.dfy", "ground_truth": "method IsSmaller(a: seq, b: seq) returns (result: bool)\n requires |a| == |b|\n ensures result <==> forall i :: 0 <= i < |a| ==> a[i] > b[i]\n ensures !result <==> exists i :: 0 <= i < |a| && a[i] <= b[i]\n{\n result := true;\n for i := 0 to |a|\n invariant 0 <= i <= |a|\n invariant result <==> forall k :: 0 <= k < i ==> a[k] > b[k]\n invariant !result <==> exists k :: 0 <= k < i && a[k] <= b[k]\n {\n if a[i] <= b[i]\n {\n result := false;\n break;\n }\n }\n}", "hints_removed": "method IsSmaller(a: seq, b: seq) returns (result: bool)\n requires |a| == |b|\n ensures result <==> forall i :: 0 <= i < |a| ==> a[i] > b[i]\n ensures !result <==> exists i :: 0 <= i < |a| && a[i] <= b[i]\n{\n result := true;\n for i := 0 to |a|\n {\n if a[i] <= b[i]\n {\n result := false;\n break;\n }\n }\n}" }, { "test_ID": "651", "test_file": "dafny-synthesis_task_id_82.dfy", "ground_truth": "method SphereVolume(radius: real) returns (volume: real)\n requires radius > 0.0\n ensures volume == 4.0/3.0 * 3.1415926535 * radius * radius * radius\n{\n volume := 4.0/3.0 * 3.1415926535 * radius * radius * radius;\n}", "hints_removed": "method SphereVolume(radius: real) returns (volume: real)\n requires radius > 0.0\n ensures volume == 4.0/3.0 * 3.1415926535 * radius * radius * radius\n{\n volume := 4.0/3.0 * 3.1415926535 * radius * radius * radius;\n}" }, { "test_ID": "652", "test_file": "dafny-synthesis_task_id_85.dfy", "ground_truth": "method SphereSurfaceArea(radius: real) returns (area: real)\n requires radius > 0.0\n ensures area == 4.0 * 3.14159265358979323846 * radius * radius\n{\n area := 4.0 * 3.14159265358979323846 * radius * radius;\n}", "hints_removed": "method SphereSurfaceArea(radius: real) returns (area: real)\n requires radius > 0.0\n ensures area == 4.0 * 3.14159265358979323846 * radius * radius\n{\n area := 4.0 * 3.14159265358979323846 * radius * radius;\n}" }, { "test_ID": "653", "test_file": "dafny-synthesis_task_id_86.dfy", "ground_truth": "method CenteredHexagonalNumber(n: nat) returns (result: nat)\n requires n >= 0\n ensures result == 3 * n * (n - 1) + 1\n{\n result := 3 * n * (n - 1) + 1;\n}", "hints_removed": "method CenteredHexagonalNumber(n: nat) returns (result: nat)\n requires n >= 0\n ensures result == 3 * n * (n - 1) + 1\n{\n result := 3 * n * (n - 1) + 1;\n}" }, { "test_ID": "654", "test_file": "dafny-synthesis_task_id_89.dfy", "ground_truth": "method ClosestSmaller(n: int) returns (m: int)\n requires n > 0\n ensures m + 1 == n\n{\n m := n - 1;\n}", "hints_removed": "method ClosestSmaller(n: int) returns (m: int)\n requires n > 0\n ensures m + 1 == n\n{\n m := n - 1;\n}" }, { "test_ID": "655", "test_file": "dafny-synthesis_task_id_94.dfy", "ground_truth": "method MinSecondValueFirst(s: array>) returns (firstOfMinSecond: int)\n requires s.Length > 0\n requires forall i :: 0 <= i < s.Length ==> |s[i]| >= 2\n ensures exists i :: 0 <= i < s.Length && firstOfMinSecond == s[i][0] && \n (forall j :: 0 <= j < s.Length ==> s[i][1] <= s[j][1])\n{\n var minSecondIndex := 0;\n for i := 1 to s.Length\n invariant 0 <= i <= s.Length\n invariant 0 <= minSecondIndex < i\n invariant forall j :: 0 <= j < i ==> s[minSecondIndex][1] <= s[j][1]\n {\n if s[i][1] < s[minSecondIndex][1]\n {\n minSecondIndex := i;\n }\n }\n firstOfMinSecond := s[minSecondIndex][0];\n}", "hints_removed": "method MinSecondValueFirst(s: array>) returns (firstOfMinSecond: int)\n requires s.Length > 0\n requires forall i :: 0 <= i < s.Length ==> |s[i]| >= 2\n ensures exists i :: 0 <= i < s.Length && firstOfMinSecond == s[i][0] && \n (forall j :: 0 <= j < s.Length ==> s[i][1] <= s[j][1])\n{\n var minSecondIndex := 0;\n for i := 1 to s.Length\n {\n if s[i][1] < s[minSecondIndex][1]\n {\n minSecondIndex := i;\n }\n }\n firstOfMinSecond := s[minSecondIndex][0];\n}" }, { "test_ID": "656", "test_file": "dafny-synthesis_task_id_95.dfy", "ground_truth": "method SmallestListLength(s: seq>) returns (v: int)\n requires |s| > 0\n ensures forall i :: 0 <= i < |s| ==> v <= |s[i]|\n ensures exists i :: 0 <= i < |s| && v == |s[i]|\n{\n v := |s[0]|;\n for i := 1 to |s|\n invariant 0 <= i <= |s|\n invariant forall k :: 0 <= k < i ==> v <= |s[k]|\n invariant exists k :: 0 <= k < i && v == |s[k]|\n {\n if |s[i]| < v\n {\n v := |s[i]|;\n }\n }\n}", "hints_removed": "method SmallestListLength(s: seq>) returns (v: int)\n requires |s| > 0\n ensures forall i :: 0 <= i < |s| ==> v <= |s[i]|\n ensures exists i :: 0 <= i < |s| && v == |s[i]|\n{\n v := |s[0]|;\n for i := 1 to |s|\n {\n if |s[i]| < v\n {\n v := |s[i]|;\n }\n }\n}" }, { "test_ID": "657", "test_file": "dafny-training_tmp_tmp_n2kixni_session1_training1.dfy", "ground_truth": "/*\n * Copyright 2021 ConsenSys Software Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may \n * not use this file except in compliance with the License. You may obtain \n * a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software dis-\n * tributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT \n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the \n * License for the specific language governing permissions and limitations \n * under the License.\n */\n\n/**\n * Example 0.a.\n * Add pre-cond to specify x >= 0 and a post cond of your choice.\n * Counter-example generation.\n */\nmethod abs(x: int) returns (y: int)\n ensures true\n{\n if x < 0 {\n y := -x;\n } else {\n y := x;\n }\n}\n\n/** Call abs */\nmethod foo(x: int) \n requires x >= 0\n{\n var y := abs(x);\n // assert( y == x);\n}\n\n/**\n * Example 0.b.\n * The goal is to compute the maximum of x and y and return it in m.\n * The current version is buggy and returns 0 is x > y and 1 if x <= 1.\n * \n * Try to:\n * 1. write the post-condition that shows that max(x,y) (i.e. m) is larger than x and y.\n * 2. write a set of post-conditions that fully characterises max.\n * 3. fix the code and make sure it verifies.\n */\nmethod max(x: int, y: int) returns (m: int)\nrequires true;\nensures true;\n{\n var r : int;\n if x > y {\n r := 0;\n } else {\n r := 1;\n }\n m := r;\n // can use return r instead\n // return m;\n}\n\n/**\n * Example 1.\n * \n * Try to prove \n * 1. the final assert statement (uncomment it and you may need to strengthen pre condition).\n * 2. termination, propose a decrease clause (to replace *)\n */\nmethod ex1(n: int)\n requires true\n ensures true\n{\n var i := 0;\n while i < n\n invariant true\n // decreases * // do not check termination\n {\n i := i + 1;\n }\n /** This is the property to prove: */\n // assert i == n;\n}\n\n/**\n * Infinite loop.\n */\nmethod foo2() \n ensures false\n decreases *\n{\n while true \n decreases *\n {\n \n }\n assert false;\n}\n\n// Specify a post-condition and prove it.\n\n/**\n * Example 2.\n *\n * Find a key in an array.\n *\n * @param a The array.\n * @param key The key to find.\n * @returns An index i such a[i] == key if key in a and -1 otherwise.\n *\n * Try to:\n * 0. uncomment line index := index + 2 and check problems\n * 1. write the property defined by the @returns above\n * 2. prove this property (you may add loop invariants)\n *\n * @note The code below is flawed on purpose.\n * |a| is the length of a\n * to test whether an integer `k` is in `a`: k in a (true\n * iff exists 0 <= i < |a|, a[i] == k). \n * And: !(k in a) <==> k !in a\n * a[i..j] is the sub sequence a[i], ..., a[j - 1] \n * a[..j] is a[0..j] and a[i..] is a[i..|a|]\n * a[..] is same as a\n */\nmethod find(a: seq, key: int) returns (index: int)\n requires true\n ensures true\n{\n index := 0;\n while index < |a|\n invariant true \n {\n // index := index + 1;\n if a[index] == key { \n return 0;\n }\n index := index + 2;\n }\n index := -10;\n}\n\n// Prove more complicated invariants with quantifiers.\n\n/**\n * Palindrome checker.\n * Example 3.\n *\n * Check whether a sequence of letters is a palindrome.\n *\n * Try to:\n * 1. write the algorithm to determine whether a string is a palindrome\n * 2. write the ensures clauses that specify the palidrome properties\n * 3. verify algorithm. \n *\n * Notes: a[k] accesses element k of a for 0 <= k < |a|\n * a[i..j] is (a seq) with the first j elements minus the first i\n * a[0..|a|] is same as a. \n */\nmethod isPalindrome(a: seq) returns (b: bool) \n{\n return true;\n}\n\n/**\n * Whether a sequence of ints is sorted (ascending).\n * \n * @param a A sequence on integers.\n * @returns Whether the sequence is sorted.\n */\npredicate sorted(a: seq) \n{\n forall j, k::0 <= j < k < |a| ==> a[j] <= a[k]\n}\n\n/**\n * Example 4.\n *\n * Remove duplicates from a sorted sequence.\n *\n * Try to:\n * 1. write the code to compute b\n * 2. write the ensures clauses that specify the remove duplicates properties\n * 3. verify algorithm. \n *\n * Notes: a[k] accesses element k of a for 0 <= k < |a|\n * a[i..j] is (a seq) with the first j elements minus the first i\n * a[0.. |a| - 1] is same as a. \n */\nmethod unique(a: seq) returns (b: seq) \n requires sorted(a)\n ensures true\n{\n return a;\n}\n\n/**\n * Dafny compiles the Main method if it finds one in a file.\n */\nmethod Main() {\n\n // run find\n var r := find([], 1); \n print r, \"\\n\";\n\n r := find([0,3,5,7], 5); \n print r, \"\\n\";\n\n // run palindrome\n var s1 := ['a'];\n var r1 := isPalindrome(s1);\n print \"is [\", s1, \"]\", \" a isPalindrome? \", r1, \" \\n\";\n\n s1 := [];\n r1 := isPalindrome(s1);\n print \"is [\", s1, \"]\", \" a isPalindrome? \", r1, \" \\n\";\n\n s1 := ['a', 'b'];\n r1 := isPalindrome(s1);\n print \"is [\", s1, \"]\", \" a isPalindrome? \", r1, \" \\n\";\n\n s1 := ['a', 'b', 'a'];\n r1 := isPalindrome(s1);\n print \"is [\", s1, \"]\", \" a isPalindrome? \", r1, \" \\n\";\n\n // run unique\n var i := [0,1,3,3,5,5,7];\n var s := unique(i);\n print \"unique applied to \", i, \" is \", s, \"\\n\";\n \n}\n\n\n", "hints_removed": "/*\n * Copyright 2021 ConsenSys Software Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may \n * not use this file except in compliance with the License. You may obtain \n * a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software dis-\n * tributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT \n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the \n * License for the specific language governing permissions and limitations \n * under the License.\n */\n\n/**\n * Example 0.a.\n * Add pre-cond to specify x >= 0 and a post cond of your choice.\n * Counter-example generation.\n */\nmethod abs(x: int) returns (y: int)\n ensures true\n{\n if x < 0 {\n y := -x;\n } else {\n y := x;\n }\n}\n\n/** Call abs */\nmethod foo(x: int) \n requires x >= 0\n{\n var y := abs(x);\n // assert( y == x);\n}\n\n/**\n * Example 0.b.\n * The goal is to compute the maximum of x and y and return it in m.\n * The current version is buggy and returns 0 is x > y and 1 if x <= 1.\n * \n * Try to:\n * 1. write the post-condition that shows that max(x,y) (i.e. m) is larger than x and y.\n * 2. write a set of post-conditions that fully characterises max.\n * 3. fix the code and make sure it verifies.\n */\nmethod max(x: int, y: int) returns (m: int)\nrequires true;\nensures true;\n{\n var r : int;\n if x > y {\n r := 0;\n } else {\n r := 1;\n }\n m := r;\n // can use return r instead\n // return m;\n}\n\n/**\n * Example 1.\n * \n * Try to prove \n * 1. the final assert statement (uncomment it and you may need to strengthen pre condition).\n * 2. termination, propose a decrease clause (to replace *)\n */\nmethod ex1(n: int)\n requires true\n ensures true\n{\n var i := 0;\n while i < n\n // decreases * // do not check termination\n {\n i := i + 1;\n }\n /** This is the property to prove: */\n // assert i == n;\n}\n\n/**\n * Infinite loop.\n */\nmethod foo2() \n ensures false\n{\n while true \n {\n \n }\n}\n\n// Specify a post-condition and prove it.\n\n/**\n * Example 2.\n *\n * Find a key in an array.\n *\n * @param a The array.\n * @param key The key to find.\n * @returns An index i such a[i] == key if key in a and -1 otherwise.\n *\n * Try to:\n * 0. uncomment line index := index + 2 and check problems\n * 1. write the property defined by the @returns above\n * 2. prove this property (you may add loop invariants)\n *\n * @note The code below is flawed on purpose.\n * |a| is the length of a\n * to test whether an integer `k` is in `a`: k in a (true\n * iff exists 0 <= i < |a|, a[i] == k). \n * And: !(k in a) <==> k !in a\n * a[i..j] is the sub sequence a[i], ..., a[j - 1] \n * a[..j] is a[0..j] and a[i..] is a[i..|a|]\n * a[..] is same as a\n */\nmethod find(a: seq, key: int) returns (index: int)\n requires true\n ensures true\n{\n index := 0;\n while index < |a|\n {\n // index := index + 1;\n if a[index] == key { \n return 0;\n }\n index := index + 2;\n }\n index := -10;\n}\n\n// Prove more complicated invariants with quantifiers.\n\n/**\n * Palindrome checker.\n * Example 3.\n *\n * Check whether a sequence of letters is a palindrome.\n *\n * Try to:\n * 1. write the algorithm to determine whether a string is a palindrome\n * 2. write the ensures clauses that specify the palidrome properties\n * 3. verify algorithm. \n *\n * Notes: a[k] accesses element k of a for 0 <= k < |a|\n * a[i..j] is (a seq) with the first j elements minus the first i\n * a[0..|a|] is same as a. \n */\nmethod isPalindrome(a: seq) returns (b: bool) \n{\n return true;\n}\n\n/**\n * Whether a sequence of ints is sorted (ascending).\n * \n * @param a A sequence on integers.\n * @returns Whether the sequence is sorted.\n */\npredicate sorted(a: seq) \n{\n forall j, k::0 <= j < k < |a| ==> a[j] <= a[k]\n}\n\n/**\n * Example 4.\n *\n * Remove duplicates from a sorted sequence.\n *\n * Try to:\n * 1. write the code to compute b\n * 2. write the ensures clauses that specify the remove duplicates properties\n * 3. verify algorithm. \n *\n * Notes: a[k] accesses element k of a for 0 <= k < |a|\n * a[i..j] is (a seq) with the first j elements minus the first i\n * a[0.. |a| - 1] is same as a. \n */\nmethod unique(a: seq) returns (b: seq) \n requires sorted(a)\n ensures true\n{\n return a;\n}\n\n/**\n * Dafny compiles the Main method if it finds one in a file.\n */\nmethod Main() {\n\n // run find\n var r := find([], 1); \n print r, \"\\n\";\n\n r := find([0,3,5,7], 5); \n print r, \"\\n\";\n\n // run palindrome\n var s1 := ['a'];\n var r1 := isPalindrome(s1);\n print \"is [\", s1, \"]\", \" a isPalindrome? \", r1, \" \\n\";\n\n s1 := [];\n r1 := isPalindrome(s1);\n print \"is [\", s1, \"]\", \" a isPalindrome? \", r1, \" \\n\";\n\n s1 := ['a', 'b'];\n r1 := isPalindrome(s1);\n print \"is [\", s1, \"]\", \" a isPalindrome? \", r1, \" \\n\";\n\n s1 := ['a', 'b', 'a'];\n r1 := isPalindrome(s1);\n print \"is [\", s1, \"]\", \" a isPalindrome? \", r1, \" \\n\";\n\n // run unique\n var i := [0,1,3,3,5,5,7];\n var s := unique(i);\n print \"unique applied to \", i, \" is \", s, \"\\n\";\n \n}\n\n\n" }, { "test_ID": "658", "test_file": "dafny-workout_tmp_tmp0abkw6f8_starter_ex01.dfy", "ground_truth": "method Max(a: int, b: int) returns (c: int)\n\tensures c >= a && c >= b && (c == a || c == b)\n{\n\tif (a >= b)\n\t{\n\t\treturn a;\n\t} else {\n\t\treturn b;\n\t}\n}\n\nmethod Main()\n{\n\tprint \"Testing max...\\n\";\n\n\tvar max := Max(3, 4);\n\tassert max == 4;\n\n\tmax := Max(-3, 4);\n\tassert max == 4;\n\n\tmax := Max(-3, -4);\n\tassert max == -3;\n\n\tmax := Max(5555555, 5555);\n\tassert max == 5555555;\n}\n\n", "hints_removed": "method Max(a: int, b: int) returns (c: int)\n\tensures c >= a && c >= b && (c == a || c == b)\n{\n\tif (a >= b)\n\t{\n\t\treturn a;\n\t} else {\n\t\treturn b;\n\t}\n}\n\nmethod Main()\n{\n\tprint \"Testing max...\\n\";\n\n\tvar max := Max(3, 4);\n\n\tmax := Max(-3, 4);\n\n\tmax := Max(-3, -4);\n\n\tmax := Max(5555555, 5555);\n}\n\n" }, { "test_ID": "659", "test_file": "dafny-workout_tmp_tmp0abkw6f8_starter_ex02.dfy", "ground_truth": "method Abs(x: int) returns (y: int)\n\trequires x < 0\n\tensures 0 < y\n\tensures y == -x\n{\n\treturn -x;\n}\n\nmethod Main()\n{\n\tvar a := Abs(-3);\n\tassert a == 3;\n}\n\n", "hints_removed": "method Abs(x: int) returns (y: int)\n\trequires x < 0\n\tensures 0 < y\n\tensures y == -x\n{\n\treturn -x;\n}\n\nmethod Main()\n{\n\tvar a := Abs(-3);\n}\n\n" }, { "test_ID": "660", "test_file": "dafny-workout_tmp_tmp0abkw6f8_starter_ex03.dfy", "ground_truth": "method Abs(x: int) returns (y: int)\n\trequires x == -1\n\tensures 0 <= y\n\tensures 0 <= x ==> y == x\n\tensures x < 0 ==> y == -x\n{\n\treturn x + 2;\n}\n\nmethod Abs2(x: real) returns (y: real)\n\trequires x == -0.5\n\tensures 0.0 <= y\n\tensures 0.0 <= x ==> y == x\n\tensures x < 0.0 ==> y == -x\n{\n\treturn x + 1.0;\n}\n\nmethod Main()\n{\n\tvar a := Abs(-1);\n\tassert a == 1;\n\tvar a2 := Abs2(-0.5);\n\tassert a2 == 0.5;\n}\n\n", "hints_removed": "method Abs(x: int) returns (y: int)\n\trequires x == -1\n\tensures 0 <= y\n\tensures 0 <= x ==> y == x\n\tensures x < 0 ==> y == -x\n{\n\treturn x + 2;\n}\n\nmethod Abs2(x: real) returns (y: real)\n\trequires x == -0.5\n\tensures 0.0 <= y\n\tensures 0.0 <= x ==> y == x\n\tensures x < 0.0 ==> y == -x\n{\n\treturn x + 1.0;\n}\n\nmethod Main()\n{\n\tvar a := Abs(-1);\n\tvar a2 := Abs2(-0.5);\n}\n\n" }, { "test_ID": "661", "test_file": "dafny-workout_tmp_tmp0abkw6f8_starter_ex09.dfy", "ground_truth": "function fib(n: nat): nat\n{\n\tif n == 0 then 0 else\n\tif n == 1 then 1 else\n\t\tfib(n - 1) + fib(n - 2)\n}\n\nmethod ComputeFib(n: nat) returns (b: nat)\n\tensures b == fib(n)\n{\n\tvar i: int := 1;\n\tif 0 <= n < 2 { return n; }\n\tb := 1;\n\tvar c := 1;\n\t\n\twhile i < n\n\t\tdecreases n - i\n\t\tinvariant 0 < i <= n\n\t\tinvariant b == fib(i)\n\t\tinvariant c == fib(i+1)\n\t{\n\t\tb, c := c, b + c;\n\t\ti := i + 1;\n\t}\n}\n\nmethod Main()\n{\n\tvar ret := ComputeFib(5);\n\tassert ret == fib(5);\n}\n\n", "hints_removed": "function fib(n: nat): nat\n{\n\tif n == 0 then 0 else\n\tif n == 1 then 1 else\n\t\tfib(n - 1) + fib(n - 2)\n}\n\nmethod ComputeFib(n: nat) returns (b: nat)\n\tensures b == fib(n)\n{\n\tvar i: int := 1;\n\tif 0 <= n < 2 { return n; }\n\tb := 1;\n\tvar c := 1;\n\t\n\twhile i < n\n\t{\n\t\tb, c := c, b + c;\n\t\ti := i + 1;\n\t}\n}\n\nmethod Main()\n{\n\tvar ret := ComputeFib(5);\n}\n\n" }, { "test_ID": "662", "test_file": "dafny-workout_tmp_tmp0abkw6f8_starter_ex12.dfy", "ground_truth": "\nmethod FindMax(a: array) returns (max_idx: nat)\n\trequires a.Length > 0\n\tensures 0 <= max_idx < a.Length\n\tensures forall j :: 0 <= j < a.Length ==> a[max_idx] >= a[j]\n{\n\tmax_idx := 0;\n\tvar i: nat := 1;\n\twhile i < a.Length\n\t\tdecreases a.Length - i\n\t\tinvariant 1 <= i <= a.Length\n\t\tinvariant 0 <= max_idx < i\n\t\tinvariant forall j :: 0 <= j < i ==> a[max_idx] >= a[j]\n\t{\n\t\tif a[i] > a[max_idx]\n\t\t{\n\t\t\tmax_idx := i;\n\t\t}\n\t\ti := i + 1;\n\t}\n\treturn max_idx;\n}\n\nmethod Main()\n{\n\tvar arr: array := new int[][1, 1, 25, 7, 2, -2, 3, 3, 20];\n\tvar idx := FindMax(arr);\n\n\tassert forall i :: 0 <= i < arr.Length ==> arr[idx] >= arr[i];\n\t// apparently I can't assert definite values like\n\t// assert idx == 2\n\t// or assert arr[idx] == 25\n}\n\n", "hints_removed": "\nmethod FindMax(a: array) returns (max_idx: nat)\n\trequires a.Length > 0\n\tensures 0 <= max_idx < a.Length\n\tensures forall j :: 0 <= j < a.Length ==> a[max_idx] >= a[j]\n{\n\tmax_idx := 0;\n\tvar i: nat := 1;\n\twhile i < a.Length\n\t{\n\t\tif a[i] > a[max_idx]\n\t\t{\n\t\t\tmax_idx := i;\n\t\t}\n\t\ti := i + 1;\n\t}\n\treturn max_idx;\n}\n\nmethod Main()\n{\n\tvar arr: array := new int[][1, 1, 25, 7, 2, -2, 3, 3, 20];\n\tvar idx := FindMax(arr);\n\n\t// apparently I can't assert definite values like\n\t// assert idx == 2\n\t// or assert arr[idx] == 25\n}\n\n" }, { "test_ID": "663", "test_file": "dafny_examples_tmp_tmp8qotd4ez_leetcode_0001-two-sum.dfy", "ground_truth": "// If this invariant is added explicitly to the loop then the verfication never finishes.\n// It could be {:opaque} for a more controlled verification:\n// assert InMap([], m, target) by {\n// reveal InMap();\n// }\npredicate InMap(nums: seq, m: map, t: int) {\n forall j :: 0 <= j < |nums| ==> t - nums[j] in m\n}\n\nmethod TwoSum(nums: array, target: int) returns (r: (int, int))\n ensures 0 <= r.0 ==> 0 <= r.0 < r.1 < nums.Length && \n nums[r.0] + nums[r.1] == target &&\n forall i, j :: 0 <= i < j < r.1 ==> nums[i] + nums[j] != target\n ensures r.0 == -1 <==> forall i, j :: 0 <= i < j < nums.Length ==> nums[i] + nums[j] != target\n{\n var m: map := map[];\n var i := 0;\n while i < nums.Length\n invariant i <= nums.Length\n invariant forall k :: k in m ==> 0 <= m[k] < i\n invariant forall k :: k in m ==> nums[m[k]] + k == target\n invariant InMap(nums[..i], m, target)\n invariant forall u, v :: 0 <= u < v < i ==> nums[u] + nums[v] != target\n {\n if nums[i] in m {\n return (m[nums[i]], i);\n }\n m := m[target - nums[i] := i];\n i := i + 1;\n }\n return (-1, -1);\n}\n", "hints_removed": "// If this invariant is added explicitly to the loop then the verfication never finishes.\n// It could be {:opaque} for a more controlled verification:\n// assert InMap([], m, target) by {\n// reveal InMap();\n// }\npredicate InMap(nums: seq, m: map, t: int) {\n forall j :: 0 <= j < |nums| ==> t - nums[j] in m\n}\n\nmethod TwoSum(nums: array, target: int) returns (r: (int, int))\n ensures 0 <= r.0 ==> 0 <= r.0 < r.1 < nums.Length && \n nums[r.0] + nums[r.1] == target &&\n forall i, j :: 0 <= i < j < r.1 ==> nums[i] + nums[j] != target\n ensures r.0 == -1 <==> forall i, j :: 0 <= i < j < nums.Length ==> nums[i] + nums[j] != target\n{\n var m: map := map[];\n var i := 0;\n while i < nums.Length\n {\n if nums[i] in m {\n return (m[nums[i]], i);\n }\n m := m[target - nums[i] := i];\n i := i + 1;\n }\n return (-1, -1);\n}\n" }, { "test_ID": "664", "test_file": "dafny_examples_tmp_tmp8qotd4ez_leetcode_0027-remove-element.dfy", "ground_truth": "method RemoveElement(nums: array, val: int) returns (newLength: int)\n modifies nums\n ensures 0 <= newLength <= nums.Length\n ensures forall x :: x in nums[..newLength] ==> x != val\n ensures multiset(nums[..newLength]) == multiset(old(nums[..]))[val := 0]\n{\n var i := 0;\n var j := 0;\n while i < nums.Length\n invariant j <= i\n invariant i <= nums.Length\n invariant old(nums[i..]) == nums[i..];\n invariant multiset(nums[..j]) == multiset(old(nums[..i]))[val := 0]\n {\n if nums[i] != val {\n nums[j] := nums[i];\n j := j + 1;\n }\n i := i + 1;\n }\n assert old(nums[..i]) == old(nums[..]);\n return j;\n}\n\n", "hints_removed": "method RemoveElement(nums: array, val: int) returns (newLength: int)\n modifies nums\n ensures 0 <= newLength <= nums.Length\n ensures forall x :: x in nums[..newLength] ==> x != val\n ensures multiset(nums[..newLength]) == multiset(old(nums[..]))[val := 0]\n{\n var i := 0;\n var j := 0;\n while i < nums.Length\n {\n if nums[i] != val {\n nums[j] := nums[i];\n j := j + 1;\n }\n i := i + 1;\n }\n return j;\n}\n\n" }, { "test_ID": "665", "test_file": "dafny_examples_tmp_tmp8qotd4ez_leetcode_0069-sqrt.dfy", "ground_truth": "// Author: Shaobo He\n\npredicate sqrt(x: int, r: int) {\n r*r <= x && (r+1)*(r+1) > x\n}\n\nlemma uniqueSqrt(x: int, r1: int, r2: int)\nrequires x >= 0 && r1 >= 0 && r2 >= 0;\nensures sqrt(x, r1) && sqrt(x, r2) ==> r1 == r2\n{}\n\nmethod mySqrt(x: int) returns (res: int)\nrequires 0 <= x;\nensures sqrt(x, res);\n{\n var l, r := 0, x;\n while (l <= r)\n decreases r - l;\n invariant l >= 0;\n invariant r >= 0;\n invariant l*l <= x;\n invariant (r+1)*(r+1) > x;\n {\n var mid := (l + r) / 2;\n if (mid * mid <= x && (mid + 1) * (mid + 1) > x) {\n return mid;\n } else if (mid * mid <= x) {\n l := mid + 1;\n } else {\n r := mid - 1;\n }\n }\n}\n", "hints_removed": "// Author: Shaobo He\n\npredicate sqrt(x: int, r: int) {\n r*r <= x && (r+1)*(r+1) > x\n}\n\nlemma uniqueSqrt(x: int, r1: int, r2: int)\nrequires x >= 0 && r1 >= 0 && r2 >= 0;\nensures sqrt(x, r1) && sqrt(x, r2) ==> r1 == r2\n{}\n\nmethod mySqrt(x: int) returns (res: int)\nrequires 0 <= x;\nensures sqrt(x, res);\n{\n var l, r := 0, x;\n while (l <= r)\n {\n var mid := (l + r) / 2;\n if (mid * mid <= x && (mid + 1) * (mid + 1) > x) {\n return mid;\n } else if (mid * mid <= x) {\n l := mid + 1;\n } else {\n r := mid - 1;\n }\n }\n}\n" }, { "test_ID": "666", "test_file": "dafny_examples_tmp_tmp8qotd4ez_leetcode_0070-climbing-stairs.dfy", "ground_truth": "function Stairs(n: nat): nat {\n if n <= 1 then 1 else Stairs(n - 2) + Stairs(n - 1)\n}\n\n// A simple specification\nmethod ClimbStairs(n: nat) returns (r: nat)\n ensures r == Stairs(n)\n{\n var a, b := 1, 1;\n var i := 1;\n while i < n\n invariant i <= n || i == 1\n invariant a == Stairs(i - 1)\n invariant b == Stairs(i)\n {\n a, b := b, a + b;\n i := i + 1;\n }\n return b;\n}\n", "hints_removed": "function Stairs(n: nat): nat {\n if n <= 1 then 1 else Stairs(n - 2) + Stairs(n - 1)\n}\n\n// A simple specification\nmethod ClimbStairs(n: nat) returns (r: nat)\n ensures r == Stairs(n)\n{\n var a, b := 1, 1;\n var i := 1;\n while i < n\n {\n a, b := b, a + b;\n i := i + 1;\n }\n return b;\n}\n" }, { "test_ID": "667", "test_file": "dafny_examples_tmp_tmp8qotd4ez_leetcode_0277-find-the-celebrity.dfy", "ground_truth": "// Author: Shaobo He\n\npredicate knows(a: int, b: int)\n\npredicate isCelebrity(n : int, i : int)\nrequires n >= 0 && 0 <= i < n;\n{\n forall j :: 0 <= j < n && i != j ==> knows(j, i) && !knows(i, j)\n}\n\nlemma knowerCannotBeCelebrity(n: int, i: int)\nrequires n >= 0 && 0 <= i < n\nensures (exists j :: 0 <= j < n && j != i && knows(i, j)) ==> !isCelebrity(n, i)\n{}\n\nghost method isCelebrityP(n: int, i: int) returns (r : bool)\nrequires n >= 0 && 0 <= i < n;\nensures r <==> isCelebrity(n, i);\n{\n var j := 0;\n r := true;\n while j < n\n decreases n - j;\n invariant 0 <= j <= n;\n invariant r ==> forall k :: 0 <= k < j && k != i ==> knows(k, i) && !knows(i, k);\n {\n if j != i {\n if !knows(j, i) || knows(i, j) {\n return false;\n }\n }\n j := j + 1;\n }\n return r;\n} \n\nghost method findCelebrity(n : int) returns (r : int)\nrequires 2 <= n <= 100;\nensures 0 <= r < n ==> isCelebrity(n, r);\nensures r == -1 ==> forall i :: 0 <= i < n ==> !isCelebrity(n, i);\n{\n var candidate := 0;\n var i := 1;\n while i < n \n invariant 1 <= i <= n;\n invariant forall j :: 0 <= j < i && j != candidate ==> !isCelebrity(n, j);\n invariant 0 <= candidate < i;\n {\n if knows(candidate, i) {\n candidate := i;\n }\n i := i + 1;\n }\n //assert forall j :: 0 <= j < n && j != candidate ==> !isCelebrity(n, j);\n var isCelebrityC := isCelebrityP(n, candidate);\n if isCelebrityC {\n r := candidate;\n } else {\n r := -1;\n }\n}\n", "hints_removed": "// Author: Shaobo He\n\npredicate knows(a: int, b: int)\n\npredicate isCelebrity(n : int, i : int)\nrequires n >= 0 && 0 <= i < n;\n{\n forall j :: 0 <= j < n && i != j ==> knows(j, i) && !knows(i, j)\n}\n\nlemma knowerCannotBeCelebrity(n: int, i: int)\nrequires n >= 0 && 0 <= i < n\nensures (exists j :: 0 <= j < n && j != i && knows(i, j)) ==> !isCelebrity(n, i)\n{}\n\nghost method isCelebrityP(n: int, i: int) returns (r : bool)\nrequires n >= 0 && 0 <= i < n;\nensures r <==> isCelebrity(n, i);\n{\n var j := 0;\n r := true;\n while j < n\n {\n if j != i {\n if !knows(j, i) || knows(i, j) {\n return false;\n }\n }\n j := j + 1;\n }\n return r;\n} \n\nghost method findCelebrity(n : int) returns (r : int)\nrequires 2 <= n <= 100;\nensures 0 <= r < n ==> isCelebrity(n, r);\nensures r == -1 ==> forall i :: 0 <= i < n ==> !isCelebrity(n, i);\n{\n var candidate := 0;\n var i := 1;\n while i < n \n {\n if knows(candidate, i) {\n candidate := i;\n }\n i := i + 1;\n }\n //assert forall j :: 0 <= j < n && j != candidate ==> !isCelebrity(n, j);\n var isCelebrityC := isCelebrityP(n, candidate);\n if isCelebrityC {\n r := candidate;\n } else {\n r := -1;\n }\n}\n" }, { "test_ID": "668", "test_file": "dafny_examples_tmp_tmp8qotd4ez_lib_math_DivMod.dfy", "ground_truth": "module DivMod {\n\n function {:opaque} DivSub(a: int, b: int): int\n requires 0 <= a && 0 < b\n {\n if a < b then 0 else 1 + DivSub(a - b, b)\n }\n\n function {:opaque} ModSub(a: int, b: int): int\n requires 0 <= a && 0 < b\n {\n if a < b then a else ModSub(a - b, b)\n }\n\n lemma DivModAdd1(a: int, b: int)\n requires b != 0\n ensures (a + b) % b == a % b\n ensures (a + b) / b == a / b + 1\n {\n var c := (a + b) / b - (a / b) - 1;\n assert c * b + (a + b) % b - a % b == 0;\n }\n\n lemma DivModSub1(a: int, b: int)\n requires b != 0\n ensures (a - b) % b == a % b\n ensures (a - b) / b == a / b - 1\n {\n var c := (a - b) / b - (a / b) + 1;\n assert c * b + (a - b) % b - a % b == 0;\n }\n\n lemma ModEq(a: int, b: int)\n requires 0 <= a && 0 < b\n ensures a % b == ModSub(a, b)\n {\n reveal ModSub();\n if a >= b {\n DivModSub1(a, b);\n }\n }\n\n lemma DivEq(a: int, b: int)\n requires 0 <= a && 0 < b\n ensures a / b == DivSub(a, b)\n {\n reveal DivSub();\n if a >= b {\n DivModSub1(a, b);\n }\n }\n\n lemma DivModSpec'(a: int, b: int, q: int, r: int)\n requires 0 <= a && 0 < b\n requires 0 <= q && 0 <= r < b\n requires a == q * b + r\n ensures ModSub(a, b) == r\n ensures DivSub(a, b) == q\n {\n reveal ModSub();\n reveal DivSub();\n if q > 0 {\n DivModSpec'(a - b, b, q - 1, r);\n }\n }\n\n lemma DivModSpec(a: int, b: int, q: int, r: int)\n requires 0 <= a && 0 < b\n requires 0 <= q && 0 <= r < b\n requires a == q * b + r\n ensures a % b == r\n ensures a / b == q\n {\n ModEq(a, b);\n DivEq(a, b);\n DivModSpec'(a, b, q, r);\n }\n\n lemma DivMul(a: int, b: int)\n requires 0 <= a && 0 < b\n ensures a * b / b == a\n {\n DivModSpec(a * b, b, a, 0);\n }\n\n lemma DivModMulAdd(a: int, b: int, c: int)\n requires 0 <= a && 0 <= c < b && 0 < b\n ensures (a * b + c) / b == a\n ensures (a * b + c) % b == c\n {\n DivModSpec(a * b + c, b, a, c);\n }\n\n}\n", "hints_removed": "module DivMod {\n\n function {:opaque} DivSub(a: int, b: int): int\n requires 0 <= a && 0 < b\n {\n if a < b then 0 else 1 + DivSub(a - b, b)\n }\n\n function {:opaque} ModSub(a: int, b: int): int\n requires 0 <= a && 0 < b\n {\n if a < b then a else ModSub(a - b, b)\n }\n\n lemma DivModAdd1(a: int, b: int)\n requires b != 0\n ensures (a + b) % b == a % b\n ensures (a + b) / b == a / b + 1\n {\n var c := (a + b) / b - (a / b) - 1;\n }\n\n lemma DivModSub1(a: int, b: int)\n requires b != 0\n ensures (a - b) % b == a % b\n ensures (a - b) / b == a / b - 1\n {\n var c := (a - b) / b - (a / b) + 1;\n }\n\n lemma ModEq(a: int, b: int)\n requires 0 <= a && 0 < b\n ensures a % b == ModSub(a, b)\n {\n reveal ModSub();\n if a >= b {\n DivModSub1(a, b);\n }\n }\n\n lemma DivEq(a: int, b: int)\n requires 0 <= a && 0 < b\n ensures a / b == DivSub(a, b)\n {\n reveal DivSub();\n if a >= b {\n DivModSub1(a, b);\n }\n }\n\n lemma DivModSpec'(a: int, b: int, q: int, r: int)\n requires 0 <= a && 0 < b\n requires 0 <= q && 0 <= r < b\n requires a == q * b + r\n ensures ModSub(a, b) == r\n ensures DivSub(a, b) == q\n {\n reveal ModSub();\n reveal DivSub();\n if q > 0 {\n DivModSpec'(a - b, b, q - 1, r);\n }\n }\n\n lemma DivModSpec(a: int, b: int, q: int, r: int)\n requires 0 <= a && 0 < b\n requires 0 <= q && 0 <= r < b\n requires a == q * b + r\n ensures a % b == r\n ensures a / b == q\n {\n ModEq(a, b);\n DivEq(a, b);\n DivModSpec'(a, b, q, r);\n }\n\n lemma DivMul(a: int, b: int)\n requires 0 <= a && 0 < b\n ensures a * b / b == a\n {\n DivModSpec(a * b, b, a, 0);\n }\n\n lemma DivModMulAdd(a: int, b: int, c: int)\n requires 0 <= a && 0 <= c < b && 0 < b\n ensures (a * b + c) / b == a\n ensures (a * b + c) % b == c\n {\n DivModSpec(a * b + c, b, a, c);\n }\n\n}\n" }, { "test_ID": "669", "test_file": "dafny_examples_tmp_tmp8qotd4ez_test_shuffle.dfy", "ground_truth": "\nmethod random(a: int, b: int) returns (r: int)\n// requires a <= b\n ensures a <= b ==> a <= r <= b\n\nlemma eqMultiset_t(t: T, s1: seq, s2: seq)\n requires multiset(s1) == multiset(s2)\n ensures t in s1 <==> t in s2\n{\n calc <==> {\n t in s1;\n t in multiset(s1);\n // Not necessary:\n// t in multiset(s2);\n// t in s2;\n }\n/* \n if (t in s1) {\n assert t in multiset(s1);\n }\n else {\n assert t !in multiset(s1);\n }\n*/\n}\n\nlemma eqMultiset(s1: seq, s2: seq)\n requires multiset(s1) == multiset(s2)\n ensures forall t :: t in s1 <==> t in s2\n{\n forall t {\n eqMultiset_t(t, s1, s2);\n }\n}\n\nmethod swap(a: array, i: int, j: int)\n // requires a != null\n requires 0 <= i < a.Length && 0 <= j < a.Length\n modifies a\n ensures a[i] == old(a[j])\n ensures a[j] == old(a[i])\n ensures forall m :: 0 <= m < a.Length && m != i && m != j ==> a[m] == old(a[m])\n ensures multiset(a[..]) == old(multiset(a[..]))\n{\n var t := a[i];\n a[i] := a[j];\n a[j] := t;\n}\n \nmethod getAllShuffledDataEntries(m_dataEntries: array) returns (result: array)\n // requires m_dataEntries != null\n // ensures result != null\n ensures result.Length == m_dataEntries.Length\n ensures multiset(result[..]) == multiset(m_dataEntries[..])\n{\n result := new T[m_dataEntries.Length];\n forall i | 0 <= i < m_dataEntries.Length {\n result[i] := m_dataEntries[i];\n }\n\n assert result[..] == m_dataEntries[..];\n \n var k := result.Length - 1;\n while (k >= 0)\n invariant multiset(result[..]) == multiset(m_dataEntries[..])\n {\n var i := random(0, k);\n assert i >= 0 && i <= k;\n\n if (i != k) {\n swap(result, i, k);\n }\n \n k := k - 1;\n }\n}\n\nfunction set_of_seq(s: seq): set\n{\n set x: T | x in s :: x\n}\n\nlemma in_set_of_seq(x: T, s: seq)\n ensures x in s <==> x in set_of_seq(s)\n\nlemma subset_set_of_seq(s1: seq, s2: seq)\n requires set_of_seq(s1) <= set_of_seq(s2)\n ensures forall x :: x in s1 ==> x in s2\n \nmethod getRandomDataEntry(m_workList: array, avoidSet: seq) returns (e: T)\n requires m_workList.Length > 0\n// ensures set_of_seq(avoidSet) < set_of_seq(m_workList[..]) ==> e !in avoidSet\n// ensures avoidSet < m_workList[..] ==> e in m_workList[..]\n{\n var k := m_workList.Length - 1;\n\n while (k >= 0)\n {\n var i := random(0, k);\n assert i >= 0 && i <= k;\n\n e := m_workList[i];\n if (e !in avoidSet) {\n return e;\n }\n \n k := k - 1;\n }\n \n return m_workList[0];\n}\n\n", "hints_removed": "\nmethod random(a: int, b: int) returns (r: int)\n// requires a <= b\n ensures a <= b ==> a <= r <= b\n\nlemma eqMultiset_t(t: T, s1: seq, s2: seq)\n requires multiset(s1) == multiset(s2)\n ensures t in s1 <==> t in s2\n{\n calc <==> {\n t in s1;\n t in multiset(s1);\n // Not necessary:\n// t in multiset(s2);\n// t in s2;\n }\n/* \n if (t in s1) {\n }\n else {\n }\n*/\n}\n\nlemma eqMultiset(s1: seq, s2: seq)\n requires multiset(s1) == multiset(s2)\n ensures forall t :: t in s1 <==> t in s2\n{\n forall t {\n eqMultiset_t(t, s1, s2);\n }\n}\n\nmethod swap(a: array, i: int, j: int)\n // requires a != null\n requires 0 <= i < a.Length && 0 <= j < a.Length\n modifies a\n ensures a[i] == old(a[j])\n ensures a[j] == old(a[i])\n ensures forall m :: 0 <= m < a.Length && m != i && m != j ==> a[m] == old(a[m])\n ensures multiset(a[..]) == old(multiset(a[..]))\n{\n var t := a[i];\n a[i] := a[j];\n a[j] := t;\n}\n \nmethod getAllShuffledDataEntries(m_dataEntries: array) returns (result: array)\n // requires m_dataEntries != null\n // ensures result != null\n ensures result.Length == m_dataEntries.Length\n ensures multiset(result[..]) == multiset(m_dataEntries[..])\n{\n result := new T[m_dataEntries.Length];\n forall i | 0 <= i < m_dataEntries.Length {\n result[i] := m_dataEntries[i];\n }\n\n \n var k := result.Length - 1;\n while (k >= 0)\n {\n var i := random(0, k);\n\n if (i != k) {\n swap(result, i, k);\n }\n \n k := k - 1;\n }\n}\n\nfunction set_of_seq(s: seq): set\n{\n set x: T | x in s :: x\n}\n\nlemma in_set_of_seq(x: T, s: seq)\n ensures x in s <==> x in set_of_seq(s)\n\nlemma subset_set_of_seq(s1: seq, s2: seq)\n requires set_of_seq(s1) <= set_of_seq(s2)\n ensures forall x :: x in s1 ==> x in s2\n \nmethod getRandomDataEntry(m_workList: array, avoidSet: seq) returns (e: T)\n requires m_workList.Length > 0\n// ensures set_of_seq(avoidSet) < set_of_seq(m_workList[..]) ==> e !in avoidSet\n// ensures avoidSet < m_workList[..] ==> e in m_workList[..]\n{\n var k := m_workList.Length - 1;\n\n while (k >= 0)\n {\n var i := random(0, k);\n\n e := m_workList[i];\n if (e !in avoidSet) {\n return e;\n }\n \n k := k - 1;\n }\n \n return m_workList[0];\n}\n\n" }, { "test_ID": "670", "test_file": "dafny_experiments_tmp_tmpz29_3_3i_circuit.dfy", "ground_truth": "module Base\n{\n // We want to represent circuits.\n // A Circuit is composed of nodes.\n // Each node can have input ports and output ports.\n\n // The ports are represented just by the index of the node, and the index\n // of the port on the node.\n datatype INodePort = inodeport(node_id: nat, port_id: nat)\n datatype ONodePort = onodeport(node_id: nat, port_id: nat)\n\n // Currently the nodes can just be Xor, And or Identity gates.\n datatype Node =\n Xor |\n And |\n Ident\n\n // The number of input ports for each kind of node.\n function n_iports (node: Node): nat\n {\n match node {\n case Xor => 2\n case And => 2\n case Ident => 1\n } \n }\n\n // The number of output ports for each kind of node.\n function n_oports (node: Node): nat\n {\n match node {\n case Xor => 1\n case And => 1\n case Ident => 1\n } \n }\n\n // A circuit is represented by the nodes and the connections between the nodes.\n // Each output port can go to many input ports.\n // But each input port can only be connected to one output port.\n datatype Circuit = Circ(\n nodes: seq,\n backconns: map\n )\n\n // Just checking that the port and node indices mentioned in the connections are sane.\n predicate WellformedBackConns(c: Circuit)\n {\n forall inp :: inp in c.backconns ==>\n WellformedINP(c, inp) &&\n WellformedONP(c, c.backconns[inp])\n }\n\n predicate WellformedINP(c: Circuit, inp: INodePort)\n {\n (0 <= inp.node_id < |c.nodes|) && (inp.port_id < n_iports(c.nodes[inp.node_id]))\n }\n\n predicate WellformedONP(c: Circuit, onp: ONodePort)\n {\n (0 <= onp.node_id < |c.nodes|) && (onp.port_id < n_oports(c.nodes[onp.node_id]))\n}\n\n // All input ports in a circuit.\n function AllINPs(c: Circuit): set\n ensures forall inp :: inp in AllINPs(c) ==> WellformedINP(c, inp)\n {\n set node_id: nat, port_id: nat |\n 0 <= node_id < |c.nodes| && port_id < n_iports(c.nodes[node_id]) ::\n inodeport(node_id, port_id)\n }\n\n // All output ports in a circuit.\n function AllONPs(c: Circuit): set\n ensures forall onp :: onp in AllONPs(c) ==> WellformedONP(c, onp)\n {\n set node_id: nat, port_id: nat |\n 0 < node_id < |c.nodes| && port_id < n_oports(c.nodes[node_id]) ::\n onodeport(node_id, port_id)\n }\n\n ghost predicate Wellformed(c: Circuit)\n {\n WellformedBackConns(c)\n }\n}\n\nmodule Utils\n{\n // Updates both the keys and values of a map.\n function UpdateMap(A: map, f: T->T, g: U->U): (result: map)\n requires forall x: T, y: T :: x != y ==> f(x) != f(y)\n ensures forall x :: x in A <==> f(x) in result;\n ensures forall x :: x in A ==> g(A[x]) == result[f(x)];\n {\n map x | x in A :: f(x) := g(A[x])\n }\n\n // Combines two maps into a single map.\n function CombineMaps(a: map, b: map): map\n requires forall x :: x in a ==> x !in b\n requires forall x :: x in b ==> x !in a\n ensures\n var result := CombineMaps(a, b);\n (forall x :: x in a ==> a[x] == result[x]) &&\n (forall x :: x in b ==> b[x] == result[x]) &&\n (forall x :: x in result ==> (x in a) || (x in b))\n {\n map x | x in (a.Keys + b.Keys) :: if x in a then a[x] else b[x]\n }\n\n function sub(a: nat, b: nat): nat\n requires b <= a\n {\n a - b\n }\n\n}\n\nmodule BackwardConnections\n{\n import opened Base\n import opened Utils\n\n // This is used when we are trying to create a new circuit by combining two existing circuits.\n // This function takes care of combining the backwards connections.\n // Because the node_indices of the two circuits are just natural numbers when we combine the\n // two circuits we need to shift the node indices of the second circuit so that they don't clash.\n // We do this by adding `offset` to the node indices.\n function CombineBackconns(\n offset: nat,\n bc1: map, bc2: map): (result: map)\n requires\n forall inp :: inp in bc1 ==> inp.node_id < offset\n {\n var f:= (inp: INodePort) => inodeport(inp.node_id + offset, inp.port_id);\n var g := (onp: ONodePort) => onodeport(onp.node_id + offset, onp.port_id);\n var backconns2 := UpdateMap(bc2, f, g);\n CombineMaps(bc1, backconns2)\n }\n\n lemma CombineBackconnsHelper(\n offset: nat,\n bc1: map, bc2: map, result: map)\n requires\n forall inp :: inp in bc1 ==> inp.node_id < offset\n requires \n result == CombineBackconns(offset, bc1, bc2);\n ensures\n forall inp :: inp in bc1 ==> (\n inp in result &&\n result[inp] == bc1[inp])\n ensures\n forall inp :: inp in bc2 ==> (\n inodeport(inp.node_id+offset, inp.port_id) in result &&\n result[inodeport(inp.node_id+offset, inp.port_id)] == onodeport(bc2[inp].node_id+offset, bc2[inp].port_id))\n {\n var f:= (inp: INodePort) => inodeport(inp.node_id + offset, inp.port_id);\n var g := (onp: ONodePort) => onodeport(onp.node_id + offset, onp.port_id);\n var backconns2 := UpdateMap(bc2, f, g);\n assert forall inp :: inp in bc2 ==> inodeport(inp.node_id+offset, inp.port_id) in backconns2;\n assert backconns2 == UpdateMap(bc2, f, g);\n }\n\n lemma CombineBackconnsHelper2(\n offset: nat,\n bc1: map, bc2: map, result: map, inp: INodePort)\n requires\n forall inp :: inp in bc1 ==> inp.node_id < offset\n requires \n result == CombineBackconns(offset, bc1, bc2);\n requires inp in bc2\n ensures\n inodeport(inp.node_id+offset, inp.port_id) in result\n ensures\n result[inodeport(inp.node_id+offset, inp.port_id)] == onodeport(bc2[inp].node_id+offset, bc2[inp].port_id)\n {\n CombineBackconnsHelper(offset, bc1, bc2, result);\n }\n}\n\n\nmodule CombineCircuits {\n\n import opened Base\n import BackwardConnections\n import opened Utils\n\n // Combine two circuits into a new circuit.\n // This is a bit ugly because we have to offset the node indices of the\n // second circuit by |c1.nodes|.\n function CombineCircuits(c1: Circuit, c2: Circuit): (r: Circuit)\n requires Wellformed(c1)\n requires Wellformed(c2)\n {\n var new_nodes := c1.nodes + c2.nodes;\n var new_backconns := BackwardConnections.CombineBackconns(\n |c1.nodes|, c1.backconns, c2.backconns);\n Circ(new_nodes, new_backconns)\n }\n\n // Check that Circuit c2 contains a subcircuit that corresponds to c1 getting mapped with the\n // `node_map` function.\n predicate IsEquivalentCircuit(node_is_member: nat->bool, node_map: nat-->nat, c1: Circuit, c2: Circuit)\n requires forall inp :: inp in c1.backconns && node_is_member(inp.node_id) ==> node_is_member(c1.backconns[inp].node_id)\n requires forall n :: node_is_member(n) ==> node_map.requires(n)\n {\n forall inp :: inp in c1.backconns && node_is_member(inp.node_id) ==>\n inodeport(node_map(inp.node_id), inp.port_id) in c2.backconns &&\n var inp2 := inodeport(node_map(inp.node_id), inp.port_id);\n var onp := c1.backconns[inp];\n onodeport(node_map(onp.node_id), onp.port_id) == c2.backconns[inp2]\n }\n\n // Check that for every input port and output port in the combined Circuit, they can be assigned\n // to a port in one of the two source circuits.\n predicate CanBackAssign(c1: Circuit, c2: Circuit, r: Circuit, is_in_c1: nat->bool, is_in_c2: nat-> bool,\n map_r_to_c1: nat->nat, map_r_to_c2: nat-->nat)\n requires forall a :: is_in_c1(a) ==> map_r_to_c1.requires(a)\n requires forall a :: is_in_c2(a) ==> map_r_to_c2.requires(a)\n requires Wellformed(c1)\n requires Wellformed(c2)\n {\n (forall inp :: inp in AllINPs(r) ==>\n (is_in_c1(inp.node_id) || is_in_c2(inp.node_id)) &&\n if is_in_c1(inp.node_id) then\n WellformedINP(c1, inodeport(map_r_to_c1(inp.node_id), inp.port_id))\n else\n WellformedINP(c2, inodeport(map_r_to_c2(inp.node_id), inp.port_id))) &&\n (forall onp :: onp in AllONPs(r) ==>\n (is_in_c1(onp.node_id) || is_in_c2(onp.node_id)) &&\n if is_in_c1(onp.node_id) then\n WellformedONP(c1, onodeport(map_r_to_c1(onp.node_id), onp.port_id))\n else\n WellformedONP(c2, onodeport(map_r_to_c2(onp.node_id), onp.port_id))) &&\n true\n }\n\n lemma CombineCircuitsCorrectHelper(c1: Circuit, c2: Circuit, r: Circuit)\n requires Wellformed(c1)\n requires Wellformed(c2)\n requires r_is_result: r == CombineCircuits(c1, c2)\n {\n assert r.backconns == \n BackwardConnections.CombineBackconns(|c1.nodes|, c1.backconns, c2.backconns) by {\n reveal r_is_result;\n }\n }\n\n\n lemma CombineCircuitsCorrectC1(c1: Circuit, c2: Circuit, r: Circuit)\n requires Wellformed(c1)\n requires Wellformed(c2)\n requires r == CombineCircuits(c1, c2)\n ensures\n var offset := |c1.nodes|;\n // The original c1 has an image in r.\n IsEquivalentCircuit(a=>true, a=>a, c1, r) &&\n // This subset of r has an image in c1.\n IsEquivalentCircuit(a=>a < offset, a=>a, r, c1)\n {\n }\n\n lemma CombineCircuitsCorrect(c1: Circuit, c2: Circuit, r: Circuit)\n requires Wellformed(c1)\n requires Wellformed(c2)\n requires r_is_result: r == CombineCircuits(c1, c2)\n ensures\n var offset := |c1.nodes|;\n // The original c1 has an image in r.\n IsEquivalentCircuit(a=>true, a=>a, c1, r) &&\n // This subset of r has an image in c1.\n IsEquivalentCircuit(a=>a < offset, a=>a, r, c1) &&\n\n // The original c2 has an image in r.\n IsEquivalentCircuit(a=>true, a=>a+offset, c2, r) &&\n/*\n FIXME: These have been commented out for now\n otherwise it takes longer than 20s to solve.\n // All ports in r have equivalents in either c1 or c2.\n CanBackAssign(c1, c2, r, a=>a < offset, a=> a >= offset, a=>a, a requires a >= offset => sub(a, offset)) &&\n // This subset of r has an image in c2.\n IsEquivalentCircuit(a=>a >= offset, a requires a >= offset => sub(a, offset), r, c2) &&\n*/\n true\n { \n // Trying to prove:\n // The original c2 has an image in r.\n // IsEquivalentCircuit(a=>true, a=>a+offset, c2, r)\n\n var offset := |c1.nodes|;\n var node_is_member := a=>true;\n var node_map := a=>a+offset;\n calc {\n IsEquivalentCircuit(node_is_member, node_map, c2, r);\n // Substitute in the IsEquivalentCircuit function definition.\n forall inp :: inp in c2.backconns && node_is_member(inp.node_id) ==>\n inodeport(node_map(inp.node_id), inp.port_id) in r.backconns &&\n var inp2 := inodeport(node_map(inp.node_id), inp.port_id);\n var onp := c2.backconns[inp];\n onodeport(node_map(onp.node_id), onp.port_id) == r.backconns[inp2];\n // Substitute in the node_is_member and node_is_map definiions.\n // For some reason this cause the solver to take too long.\n forall inp :: inp in c2.backconns ==>\n inodeport(inp.node_id+offset, inp.port_id) in r.backconns &&\n var inp2 := inodeport(inp.node_id+offset, inp.port_id);\n var onp := c2.backconns[inp];\n onodeport(onp.node_id+offset, onp.port_id) == r.backconns[inp2];\n }\n assert basic_result: r.backconns == BackwardConnections.CombineBackconns(|c1.nodes|, c1.backconns, c2.backconns)\n by {\n reveal r_is_result;\n }\n\n forall inp | inp in c2.backconns\n {\n calc {\n inodeport(inp.node_id+offset, inp.port_id) in r.backconns &&\n var inp2 := inodeport(inp.node_id+offset, inp.port_id);\n var onp := c2.backconns[inp];\n onodeport(onp.node_id+offset, onp.port_id) == r.backconns[inp2];\n\n {reveal basic_result;}\n inodeport(inp.node_id+offset, inp.port_id) in \n BackwardConnections.CombineBackconns(|c1.nodes|, c1.backconns, c2.backconns) &&\n var inp2 := inodeport(inp.node_id+offset, inp.port_id);\n var onp := c2.backconns[inp];\n onodeport(onp.node_id+offset, onp.port_id) ==\n BackwardConnections.CombineBackconns(|c1.nodes|, c1.backconns, c2.backconns)[inp2];\n \n inodeport(inp.node_id+offset, inp.port_id) in \n BackwardConnections.CombineBackconns(|c1.nodes|, c1.backconns, c2.backconns) &&\n var inp2 := inodeport(inp.node_id+offset, inp.port_id);\n var onp := c2.backconns[inp];\n onodeport(onp.node_id+offset, onp.port_id) ==\n BackwardConnections.CombineBackconns(|c1.nodes|, c1.backconns, c2.backconns)[inp2];\n\n {\n var inp2 := inodeport(inp.node_id+offset, inp.port_id);\n BackwardConnections.CombineBackconnsHelper2(\n offset, c1.backconns, c2.backconns,\n BackwardConnections.CombineBackconns(|c1.nodes|, c1.backconns, c2.backconns),\n inp\n );\n assert \n BackwardConnections.CombineBackconns(|c1.nodes|, c1.backconns, c2.backconns)[inp2] ==\n onodeport(c2.backconns[inp].node_id+offset, c2.backconns[inp].port_id);\n assert \n inodeport(inp.node_id+offset, inp.port_id) in \n BackwardConnections.CombineBackconns(|c1.nodes|, c1.backconns, c2.backconns);\n }\n\n true;\n }\n }\n reveal r_is_result;\n CombineCircuitsCorrectC1(c1, c2, r);\n }\n}\n", "hints_removed": "module Base\n{\n // We want to represent circuits.\n // A Circuit is composed of nodes.\n // Each node can have input ports and output ports.\n\n // The ports are represented just by the index of the node, and the index\n // of the port on the node.\n datatype INodePort = inodeport(node_id: nat, port_id: nat)\n datatype ONodePort = onodeport(node_id: nat, port_id: nat)\n\n // Currently the nodes can just be Xor, And or Identity gates.\n datatype Node =\n Xor |\n And |\n Ident\n\n // The number of input ports for each kind of node.\n function n_iports (node: Node): nat\n {\n match node {\n case Xor => 2\n case And => 2\n case Ident => 1\n } \n }\n\n // The number of output ports for each kind of node.\n function n_oports (node: Node): nat\n {\n match node {\n case Xor => 1\n case And => 1\n case Ident => 1\n } \n }\n\n // A circuit is represented by the nodes and the connections between the nodes.\n // Each output port can go to many input ports.\n // But each input port can only be connected to one output port.\n datatype Circuit = Circ(\n nodes: seq,\n backconns: map\n )\n\n // Just checking that the port and node indices mentioned in the connections are sane.\n predicate WellformedBackConns(c: Circuit)\n {\n forall inp :: inp in c.backconns ==>\n WellformedINP(c, inp) &&\n WellformedONP(c, c.backconns[inp])\n }\n\n predicate WellformedINP(c: Circuit, inp: INodePort)\n {\n (0 <= inp.node_id < |c.nodes|) && (inp.port_id < n_iports(c.nodes[inp.node_id]))\n }\n\n predicate WellformedONP(c: Circuit, onp: ONodePort)\n {\n (0 <= onp.node_id < |c.nodes|) && (onp.port_id < n_oports(c.nodes[onp.node_id]))\n}\n\n // All input ports in a circuit.\n function AllINPs(c: Circuit): set\n ensures forall inp :: inp in AllINPs(c) ==> WellformedINP(c, inp)\n {\n set node_id: nat, port_id: nat |\n 0 <= node_id < |c.nodes| && port_id < n_iports(c.nodes[node_id]) ::\n inodeport(node_id, port_id)\n }\n\n // All output ports in a circuit.\n function AllONPs(c: Circuit): set\n ensures forall onp :: onp in AllONPs(c) ==> WellformedONP(c, onp)\n {\n set node_id: nat, port_id: nat |\n 0 < node_id < |c.nodes| && port_id < n_oports(c.nodes[node_id]) ::\n onodeport(node_id, port_id)\n }\n\n ghost predicate Wellformed(c: Circuit)\n {\n WellformedBackConns(c)\n }\n}\n\nmodule Utils\n{\n // Updates both the keys and values of a map.\n function UpdateMap(A: map, f: T->T, g: U->U): (result: map)\n requires forall x: T, y: T :: x != y ==> f(x) != f(y)\n ensures forall x :: x in A <==> f(x) in result;\n ensures forall x :: x in A ==> g(A[x]) == result[f(x)];\n {\n map x | x in A :: f(x) := g(A[x])\n }\n\n // Combines two maps into a single map.\n function CombineMaps(a: map, b: map): map\n requires forall x :: x in a ==> x !in b\n requires forall x :: x in b ==> x !in a\n ensures\n var result := CombineMaps(a, b);\n (forall x :: x in a ==> a[x] == result[x]) &&\n (forall x :: x in b ==> b[x] == result[x]) &&\n (forall x :: x in result ==> (x in a) || (x in b))\n {\n map x | x in (a.Keys + b.Keys) :: if x in a then a[x] else b[x]\n }\n\n function sub(a: nat, b: nat): nat\n requires b <= a\n {\n a - b\n }\n\n}\n\nmodule BackwardConnections\n{\n import opened Base\n import opened Utils\n\n // This is used when we are trying to create a new circuit by combining two existing circuits.\n // This function takes care of combining the backwards connections.\n // Because the node_indices of the two circuits are just natural numbers when we combine the\n // two circuits we need to shift the node indices of the second circuit so that they don't clash.\n // We do this by adding `offset` to the node indices.\n function CombineBackconns(\n offset: nat,\n bc1: map, bc2: map): (result: map)\n requires\n forall inp :: inp in bc1 ==> inp.node_id < offset\n {\n var f:= (inp: INodePort) => inodeport(inp.node_id + offset, inp.port_id);\n var g := (onp: ONodePort) => onodeport(onp.node_id + offset, onp.port_id);\n var backconns2 := UpdateMap(bc2, f, g);\n CombineMaps(bc1, backconns2)\n }\n\n lemma CombineBackconnsHelper(\n offset: nat,\n bc1: map, bc2: map, result: map)\n requires\n forall inp :: inp in bc1 ==> inp.node_id < offset\n requires \n result == CombineBackconns(offset, bc1, bc2);\n ensures\n forall inp :: inp in bc1 ==> (\n inp in result &&\n result[inp] == bc1[inp])\n ensures\n forall inp :: inp in bc2 ==> (\n inodeport(inp.node_id+offset, inp.port_id) in result &&\n result[inodeport(inp.node_id+offset, inp.port_id)] == onodeport(bc2[inp].node_id+offset, bc2[inp].port_id))\n {\n var f:= (inp: INodePort) => inodeport(inp.node_id + offset, inp.port_id);\n var g := (onp: ONodePort) => onodeport(onp.node_id + offset, onp.port_id);\n var backconns2 := UpdateMap(bc2, f, g);\n }\n\n lemma CombineBackconnsHelper2(\n offset: nat,\n bc1: map, bc2: map, result: map, inp: INodePort)\n requires\n forall inp :: inp in bc1 ==> inp.node_id < offset\n requires \n result == CombineBackconns(offset, bc1, bc2);\n requires inp in bc2\n ensures\n inodeport(inp.node_id+offset, inp.port_id) in result\n ensures\n result[inodeport(inp.node_id+offset, inp.port_id)] == onodeport(bc2[inp].node_id+offset, bc2[inp].port_id)\n {\n CombineBackconnsHelper(offset, bc1, bc2, result);\n }\n}\n\n\nmodule CombineCircuits {\n\n import opened Base\n import BackwardConnections\n import opened Utils\n\n // Combine two circuits into a new circuit.\n // This is a bit ugly because we have to offset the node indices of the\n // second circuit by |c1.nodes|.\n function CombineCircuits(c1: Circuit, c2: Circuit): (r: Circuit)\n requires Wellformed(c1)\n requires Wellformed(c2)\n {\n var new_nodes := c1.nodes + c2.nodes;\n var new_backconns := BackwardConnections.CombineBackconns(\n |c1.nodes|, c1.backconns, c2.backconns);\n Circ(new_nodes, new_backconns)\n }\n\n // Check that Circuit c2 contains a subcircuit that corresponds to c1 getting mapped with the\n // `node_map` function.\n predicate IsEquivalentCircuit(node_is_member: nat->bool, node_map: nat-->nat, c1: Circuit, c2: Circuit)\n requires forall inp :: inp in c1.backconns && node_is_member(inp.node_id) ==> node_is_member(c1.backconns[inp].node_id)\n requires forall n :: node_is_member(n) ==> node_map.requires(n)\n {\n forall inp :: inp in c1.backconns && node_is_member(inp.node_id) ==>\n inodeport(node_map(inp.node_id), inp.port_id) in c2.backconns &&\n var inp2 := inodeport(node_map(inp.node_id), inp.port_id);\n var onp := c1.backconns[inp];\n onodeport(node_map(onp.node_id), onp.port_id) == c2.backconns[inp2]\n }\n\n // Check that for every input port and output port in the combined Circuit, they can be assigned\n // to a port in one of the two source circuits.\n predicate CanBackAssign(c1: Circuit, c2: Circuit, r: Circuit, is_in_c1: nat->bool, is_in_c2: nat-> bool,\n map_r_to_c1: nat->nat, map_r_to_c2: nat-->nat)\n requires forall a :: is_in_c1(a) ==> map_r_to_c1.requires(a)\n requires forall a :: is_in_c2(a) ==> map_r_to_c2.requires(a)\n requires Wellformed(c1)\n requires Wellformed(c2)\n {\n (forall inp :: inp in AllINPs(r) ==>\n (is_in_c1(inp.node_id) || is_in_c2(inp.node_id)) &&\n if is_in_c1(inp.node_id) then\n WellformedINP(c1, inodeport(map_r_to_c1(inp.node_id), inp.port_id))\n else\n WellformedINP(c2, inodeport(map_r_to_c2(inp.node_id), inp.port_id))) &&\n (forall onp :: onp in AllONPs(r) ==>\n (is_in_c1(onp.node_id) || is_in_c2(onp.node_id)) &&\n if is_in_c1(onp.node_id) then\n WellformedONP(c1, onodeport(map_r_to_c1(onp.node_id), onp.port_id))\n else\n WellformedONP(c2, onodeport(map_r_to_c2(onp.node_id), onp.port_id))) &&\n true\n }\n\n lemma CombineCircuitsCorrectHelper(c1: Circuit, c2: Circuit, r: Circuit)\n requires Wellformed(c1)\n requires Wellformed(c2)\n requires r_is_result: r == CombineCircuits(c1, c2)\n {\n BackwardConnections.CombineBackconns(|c1.nodes|, c1.backconns, c2.backconns) by {\n reveal r_is_result;\n }\n }\n\n\n lemma CombineCircuitsCorrectC1(c1: Circuit, c2: Circuit, r: Circuit)\n requires Wellformed(c1)\n requires Wellformed(c2)\n requires r == CombineCircuits(c1, c2)\n ensures\n var offset := |c1.nodes|;\n // The original c1 has an image in r.\n IsEquivalentCircuit(a=>true, a=>a, c1, r) &&\n // This subset of r has an image in c1.\n IsEquivalentCircuit(a=>a < offset, a=>a, r, c1)\n {\n }\n\n lemma CombineCircuitsCorrect(c1: Circuit, c2: Circuit, r: Circuit)\n requires Wellformed(c1)\n requires Wellformed(c2)\n requires r_is_result: r == CombineCircuits(c1, c2)\n ensures\n var offset := |c1.nodes|;\n // The original c1 has an image in r.\n IsEquivalentCircuit(a=>true, a=>a, c1, r) &&\n // This subset of r has an image in c1.\n IsEquivalentCircuit(a=>a < offset, a=>a, r, c1) &&\n\n // The original c2 has an image in r.\n IsEquivalentCircuit(a=>true, a=>a+offset, c2, r) &&\n/*\n FIXME: These have been commented out for now\n otherwise it takes longer than 20s to solve.\n // All ports in r have equivalents in either c1 or c2.\n CanBackAssign(c1, c2, r, a=>a < offset, a=> a >= offset, a=>a, a requires a >= offset => sub(a, offset)) &&\n // This subset of r has an image in c2.\n IsEquivalentCircuit(a=>a >= offset, a requires a >= offset => sub(a, offset), r, c2) &&\n*/\n true\n { \n // Trying to prove:\n // The original c2 has an image in r.\n // IsEquivalentCircuit(a=>true, a=>a+offset, c2, r)\n\n var offset := |c1.nodes|;\n var node_is_member := a=>true;\n var node_map := a=>a+offset;\n calc {\n IsEquivalentCircuit(node_is_member, node_map, c2, r);\n // Substitute in the IsEquivalentCircuit function definition.\n forall inp :: inp in c2.backconns && node_is_member(inp.node_id) ==>\n inodeport(node_map(inp.node_id), inp.port_id) in r.backconns &&\n var inp2 := inodeport(node_map(inp.node_id), inp.port_id);\n var onp := c2.backconns[inp];\n onodeport(node_map(onp.node_id), onp.port_id) == r.backconns[inp2];\n // Substitute in the node_is_member and node_is_map definiions.\n // For some reason this cause the solver to take too long.\n forall inp :: inp in c2.backconns ==>\n inodeport(inp.node_id+offset, inp.port_id) in r.backconns &&\n var inp2 := inodeport(inp.node_id+offset, inp.port_id);\n var onp := c2.backconns[inp];\n onodeport(onp.node_id+offset, onp.port_id) == r.backconns[inp2];\n }\n by {\n reveal r_is_result;\n }\n\n forall inp | inp in c2.backconns\n {\n calc {\n inodeport(inp.node_id+offset, inp.port_id) in r.backconns &&\n var inp2 := inodeport(inp.node_id+offset, inp.port_id);\n var onp := c2.backconns[inp];\n onodeport(onp.node_id+offset, onp.port_id) == r.backconns[inp2];\n\n {reveal basic_result;}\n inodeport(inp.node_id+offset, inp.port_id) in \n BackwardConnections.CombineBackconns(|c1.nodes|, c1.backconns, c2.backconns) &&\n var inp2 := inodeport(inp.node_id+offset, inp.port_id);\n var onp := c2.backconns[inp];\n onodeport(onp.node_id+offset, onp.port_id) ==\n BackwardConnections.CombineBackconns(|c1.nodes|, c1.backconns, c2.backconns)[inp2];\n \n inodeport(inp.node_id+offset, inp.port_id) in \n BackwardConnections.CombineBackconns(|c1.nodes|, c1.backconns, c2.backconns) &&\n var inp2 := inodeport(inp.node_id+offset, inp.port_id);\n var onp := c2.backconns[inp];\n onodeport(onp.node_id+offset, onp.port_id) ==\n BackwardConnections.CombineBackconns(|c1.nodes|, c1.backconns, c2.backconns)[inp2];\n\n {\n var inp2 := inodeport(inp.node_id+offset, inp.port_id);\n BackwardConnections.CombineBackconnsHelper2(\n offset, c1.backconns, c2.backconns,\n BackwardConnections.CombineBackconns(|c1.nodes|, c1.backconns, c2.backconns),\n inp\n );\n BackwardConnections.CombineBackconns(|c1.nodes|, c1.backconns, c2.backconns)[inp2] ==\n onodeport(c2.backconns[inp].node_id+offset, c2.backconns[inp].port_id);\n inodeport(inp.node_id+offset, inp.port_id) in \n BackwardConnections.CombineBackconns(|c1.nodes|, c1.backconns, c2.backconns);\n }\n\n true;\n }\n }\n reveal r_is_result;\n CombineCircuitsCorrectC1(c1, c2, r);\n }\n}\n" }, { "test_ID": "671", "test_file": "dafny_misc_tmp_tmpg4vzlnm1_rosetta_code_factorial.dfy", "ground_truth": "// recursive definition of factorial\nfunction Factorial(n: nat): nat {\n if n == 0 then 1 else n * Factorial(n - 1)\n}\n\n// iterative implementation of factorial\nmethod IterativeFactorial(n: nat) returns (result: nat)\n ensures result == Factorial(n)\n{\n result := 1;\n var i := 1;\n while i <= n\n invariant i <= n + 1\n invariant result == Factorial(i - 1)\n {\n result := result * i;\n i := i + 1;\n }\n}\n\n", "hints_removed": "// recursive definition of factorial\nfunction Factorial(n: nat): nat {\n if n == 0 then 1 else n * Factorial(n - 1)\n}\n\n// iterative implementation of factorial\nmethod IterativeFactorial(n: nat) returns (result: nat)\n ensures result == Factorial(n)\n{\n result := 1;\n var i := 1;\n while i <= n\n {\n result := result * i;\n i := i + 1;\n }\n}\n\n" }, { "test_ID": "672", "test_file": "dafny_misc_tmp_tmpg4vzlnm1_rosetta_code_fibonacci_sequence.dfy", "ground_truth": "// definition of Fibonacci numbers\nfunction Fibonacci(n: nat): nat {\n match n {\n case 0 => 0\n case 1 => 1\n case _ => Fibonacci(n - 1) + Fibonacci(n - 2)\n }\n}\n\n// iterative calculation of Fibonacci numbers\nmethod FibonacciIterative(n: nat) returns (f: nat)\n ensures f == Fibonacci(n)\n{\n if n < 2 {\n return n;\n }\n\n var prev := 1;\n f := 1;\n var i := 2;\n\n while i < n\n invariant i <= n\n invariant prev == Fibonacci(i - 1)\n invariant f == Fibonacci(i)\n {\n prev, f := f, f + prev;\n i := i + 1;\n }\n}\n\n", "hints_removed": "// definition of Fibonacci numbers\nfunction Fibonacci(n: nat): nat {\n match n {\n case 0 => 0\n case 1 => 1\n case _ => Fibonacci(n - 1) + Fibonacci(n - 2)\n }\n}\n\n// iterative calculation of Fibonacci numbers\nmethod FibonacciIterative(n: nat) returns (f: nat)\n ensures f == Fibonacci(n)\n{\n if n < 2 {\n return n;\n }\n\n var prev := 1;\n f := 1;\n var i := 2;\n\n while i < n\n {\n prev, f := f, f + prev;\n i := i + 1;\n }\n}\n\n" }, { "test_ID": "673", "test_file": "dafny_projects_tmp_tmpjutqwjv4_tutorial_tutorial.dfy", "ground_truth": "// Working through https://dafny.org/dafny/OnlineTutorial/guide\n\nfunction fib(n: nat): nat\n{\n if n == 0 then 0\n else if n == 1 then 1\n else fib(n - 1) + fib(n - 2)\n}\nmethod ComputeFib(n: nat) returns (ret: nat)\n ensures ret == fib(n)\n{\n var a := 0;\n var b := 1;\n var i := 0;\n while i < n\n invariant 0 <= i <= n\n invariant a == fib(i)\n invariant b == fib(i+1)\n {\n a, b := b, a+b;\n i := i + 1;\n }\n assert i == n;\n\n return a;\n}\n\nmethod Find(a: array, key: int) returns (index: int)\n ensures 0 <= index ==> index < a.Length && a[index] == key\n ensures index < 0 ==> (forall k :: 0 <= k < a.Length ==> a[k] != key)\n{\n index := 0;\n while index < a.Length\n invariant 0 <= index <= a.Length\n invariant forall k :: 0 <= k < index ==> a[k] != key\n {\n if a[index] == key {\n return index;\n }\n index := index + 1;\n }\n\n return -1;\n}\n\npredicate sorted(a: array)\n reads a\n{\n forall n, m :: 0 <= n < m < a.Length ==> a[n] <= a[m]\n}\n\nmethod BinarySearch(a: array, value: int) returns (index: int)\n requires 0 <= a.Length && sorted(a)\n ensures 0 <= index ==> index < a.Length && a[index] == value\n ensures index < 0 ==> forall k :: 0 <= k < a.Length ==> a[k] != value\n{\n var low := 0;\n var high := a.Length - 1;\n while low < high\n invariant 0 <= low && high < a.Length\n invariant forall k :: 0 <= k < a.Length && (k < low || k > high) ==> a[k] != value\n {\n var mid : int := (low + high) / 2;\n assert 0 <= low <= mid < high < a.Length;\n if a[mid] < value {\n low := mid + 1;\n } else if a[mid] > value {\n high := mid - 1;\n } else {\n assert a[mid] == value;\n return mid;\n }\n }\n if low < a.Length && a[low] == value {\n return low;\n } else {\n return -1;\n }\n}\n\n\n// https://dafny.org/dafny/OnlineTutorial/ValueTypes\n\nfunction update(s: seq, i: int, v: int): seq\n requires 0 <= i < |s|\n ensures update(s, i, v) == s[i := v]\n{\n s[..i] + [v] + s[i+1..]\n}\n\n\n// https://dafny.org/dafny/OnlineTutorial/Lemmas\n\nlemma SkippingLemma(a: array, j: int)\n requires forall i :: 0 <= i < a.Length ==> 0 <= a[i]\n requires forall i :: 0 < i < a.Length ==> a[i-1]-1 <= a[i]\n requires 0 <= j < a.Length\n ensures forall i :: j <= i < j + a[j] && i < a.Length ==> a[i] != 0\n{\n var i := j;\n while i < j + a[j] && i < a.Length\n invariant i < a.Length ==> a[i] >= a[j] - (i-j)\n invariant forall k :: j <= k < i && k < a.Length ==> a[k] != 0\n {\n i := i + 1;\n }\n}\n\nmethod FindZero(a: array) returns (index: int)\n requires forall i :: 0 <= i < a.Length ==> 0 <= a[i]\n requires forall i :: 0 < i < a.Length ==> a[i-1]-1 <= a[i]\n ensures index < 0 ==> forall i :: 0 <= i < a.Length ==> a[i] != 0\n ensures 0 <= index ==> index < a.Length && a[index] == 0\n{\n index := 0;\n while index < a.Length\n invariant 0 <= index\n invariant forall k :: 0 <= k < index && k < a.Length ==> a[k] != 0\n {\n if a[index] == 0 { return; }\n SkippingLemma(a, index);\n index := index + a[index];\n }\n index := -1;\n}\n\n\nfunction count(a: seq): nat\n{\n if |a| == 0 then 0 else\n (if a[0] then 1 else 0) + count(a[1..])\n}\n\nlemma DistributiveLemma(a: seq, b: seq)\n ensures count(a + b) == count(a) + count(b)\n{\n if a == [] {\n assert a+b == b;\n } else {\n // Unnecessary! DistributiveLemma(a[1..], b);\n assert a + b == [a[0]] + (a[1..] + b);\n }\n}\n\n\nclass Node\n{\n var next: seq\n}\npredicate closed(graph: set)\n reads graph\n{\n forall i :: i in graph ==> forall k :: 0 <= k < |i.next| ==> i.next[k] in graph && i.next[k] != i\n}\npredicate path(p: seq, graph: set)\n requires closed(graph) && 0 < |p|\n reads graph\n{\n p[0] in graph &&\n (|p| > 1 ==> p[1] in p[0].next && // the first link is valid, if it exists\n path(p[1..], graph)) // and the rest of the sequence is a valid\n}\npredicate pathSpecific(p: seq, start: Node, end: Node, graph: set)\n requires closed(graph)\n reads graph\n{\n 0 < |p| && // path is nonempty\n start == p[0] && end == p[|p|-1] && // it starts and ends correctly\n path(p, graph) // and it is a valid path\n}\n\nlemma DisproofLemma(p: seq, subgraph: set,\n root: Node, goal: Node, graph: set)\n requires closed(subgraph) && closed(graph) && subgraph <= graph\n requires root in subgraph && goal in graph - subgraph\n ensures !pathSpecific(p, root, goal, graph)\n{\n if |p| >= 2 && p[0] == root && p[1] in p[0].next {\n DisproofLemma(p[1..], subgraph, p[1], goal, graph);\n }\n}\n\nlemma ClosedLemma(subgraph: set, root: Node, goal: Node, graph: set)\n requires closed(subgraph) && closed(graph) && subgraph <= graph\n requires root in subgraph && goal in graph - subgraph\n ensures !(exists p: seq :: pathSpecific(p, root, goal, graph))\n{\n forall p { DisproofLemma(p, subgraph, root, goal, graph); }\n}\n\n", "hints_removed": "// Working through https://dafny.org/dafny/OnlineTutorial/guide\n\nfunction fib(n: nat): nat\n{\n if n == 0 then 0\n else if n == 1 then 1\n else fib(n - 1) + fib(n - 2)\n}\nmethod ComputeFib(n: nat) returns (ret: nat)\n ensures ret == fib(n)\n{\n var a := 0;\n var b := 1;\n var i := 0;\n while i < n\n {\n a, b := b, a+b;\n i := i + 1;\n }\n\n return a;\n}\n\nmethod Find(a: array, key: int) returns (index: int)\n ensures 0 <= index ==> index < a.Length && a[index] == key\n ensures index < 0 ==> (forall k :: 0 <= k < a.Length ==> a[k] != key)\n{\n index := 0;\n while index < a.Length\n {\n if a[index] == key {\n return index;\n }\n index := index + 1;\n }\n\n return -1;\n}\n\npredicate sorted(a: array)\n reads a\n{\n forall n, m :: 0 <= n < m < a.Length ==> a[n] <= a[m]\n}\n\nmethod BinarySearch(a: array, value: int) returns (index: int)\n requires 0 <= a.Length && sorted(a)\n ensures 0 <= index ==> index < a.Length && a[index] == value\n ensures index < 0 ==> forall k :: 0 <= k < a.Length ==> a[k] != value\n{\n var low := 0;\n var high := a.Length - 1;\n while low < high\n {\n var mid : int := (low + high) / 2;\n if a[mid] < value {\n low := mid + 1;\n } else if a[mid] > value {\n high := mid - 1;\n } else {\n return mid;\n }\n }\n if low < a.Length && a[low] == value {\n return low;\n } else {\n return -1;\n }\n}\n\n\n// https://dafny.org/dafny/OnlineTutorial/ValueTypes\n\nfunction update(s: seq, i: int, v: int): seq\n requires 0 <= i < |s|\n ensures update(s, i, v) == s[i := v]\n{\n s[..i] + [v] + s[i+1..]\n}\n\n\n// https://dafny.org/dafny/OnlineTutorial/Lemmas\n\nlemma SkippingLemma(a: array, j: int)\n requires forall i :: 0 <= i < a.Length ==> 0 <= a[i]\n requires forall i :: 0 < i < a.Length ==> a[i-1]-1 <= a[i]\n requires 0 <= j < a.Length\n ensures forall i :: j <= i < j + a[j] && i < a.Length ==> a[i] != 0\n{\n var i := j;\n while i < j + a[j] && i < a.Length\n {\n i := i + 1;\n }\n}\n\nmethod FindZero(a: array) returns (index: int)\n requires forall i :: 0 <= i < a.Length ==> 0 <= a[i]\n requires forall i :: 0 < i < a.Length ==> a[i-1]-1 <= a[i]\n ensures index < 0 ==> forall i :: 0 <= i < a.Length ==> a[i] != 0\n ensures 0 <= index ==> index < a.Length && a[index] == 0\n{\n index := 0;\n while index < a.Length\n {\n if a[index] == 0 { return; }\n SkippingLemma(a, index);\n index := index + a[index];\n }\n index := -1;\n}\n\n\nfunction count(a: seq): nat\n{\n if |a| == 0 then 0 else\n (if a[0] then 1 else 0) + count(a[1..])\n}\n\nlemma DistributiveLemma(a: seq, b: seq)\n ensures count(a + b) == count(a) + count(b)\n{\n if a == [] {\n } else {\n // Unnecessary! DistributiveLemma(a[1..], b);\n }\n}\n\n\nclass Node\n{\n var next: seq\n}\npredicate closed(graph: set)\n reads graph\n{\n forall i :: i in graph ==> forall k :: 0 <= k < |i.next| ==> i.next[k] in graph && i.next[k] != i\n}\npredicate path(p: seq, graph: set)\n requires closed(graph) && 0 < |p|\n reads graph\n{\n p[0] in graph &&\n (|p| > 1 ==> p[1] in p[0].next && // the first link is valid, if it exists\n path(p[1..], graph)) // and the rest of the sequence is a valid\n}\npredicate pathSpecific(p: seq, start: Node, end: Node, graph: set)\n requires closed(graph)\n reads graph\n{\n 0 < |p| && // path is nonempty\n start == p[0] && end == p[|p|-1] && // it starts and ends correctly\n path(p, graph) // and it is a valid path\n}\n\nlemma DisproofLemma(p: seq, subgraph: set,\n root: Node, goal: Node, graph: set)\n requires closed(subgraph) && closed(graph) && subgraph <= graph\n requires root in subgraph && goal in graph - subgraph\n ensures !pathSpecific(p, root, goal, graph)\n{\n if |p| >= 2 && p[0] == root && p[1] in p[0].next {\n DisproofLemma(p[1..], subgraph, p[1], goal, graph);\n }\n}\n\nlemma ClosedLemma(subgraph: set, root: Node, goal: Node, graph: set)\n requires closed(subgraph) && closed(graph) && subgraph <= graph\n requires root in subgraph && goal in graph - subgraph\n ensures !(exists p: seq :: pathSpecific(p, root, goal, graph))\n{\n forall p { DisproofLemma(p, subgraph, root, goal, graph); }\n}\n\n" }, { "test_ID": "674", "test_file": "dafny_tmp_tmp2ewu6s7x_ListReverse.dfy", "ground_truth": "function reverse(xs: seq): seq\n{\n if xs == [] then [] else reverse(xs[1..]) + [xs[0]]\n}\n\nlemma ReverseAppendDistr(xs: seq, ys: seq)\nensures reverse(xs + ys) == reverse(ys) + reverse(xs)\n{\n if {\n case xs == [] =>\n calc {\n reverse([] + ys);\n calc {\n [] + ys;\n ys;\n }\n reverse(ys);\n reverse(ys) + reverse([]);\n }\n case xs != [] => {\n var zs := xs + ys;\n assert zs[1..] == xs[1..] + ys;\n }\n }\n}\n\nlemma ReverseInvolution(xxs: seq)\nensures reverse(reverse(xxs)) == xxs\n{\n if {\n case xxs == [] => {}\n case xxs != [] => calc {\n reverse(reverse(xxs));\n ==\n reverse(reverse(xxs[1..]) + [xxs[0]]);\n ==\n { ReverseAppendDistr(reverse(xxs[1..]), [xxs[0]]); }\n reverse([xxs[0]]) + reverse(reverse(xxs[1..]));\n ==\n { ReverseInvolution(xxs[1..]); }\n calc {\n reverse([xxs[0]]);\n ==\n [] + [xxs[0]];\n ==\n [xxs[0]];\n }\n [xxs[0]] + xxs[1..];\n ==\n xxs;\n }\n }\n}\n\n", "hints_removed": "function reverse(xs: seq): seq\n{\n if xs == [] then [] else reverse(xs[1..]) + [xs[0]]\n}\n\nlemma ReverseAppendDistr(xs: seq, ys: seq)\nensures reverse(xs + ys) == reverse(ys) + reverse(xs)\n{\n if {\n case xs == [] =>\n calc {\n reverse([] + ys);\n calc {\n [] + ys;\n ys;\n }\n reverse(ys);\n reverse(ys) + reverse([]);\n }\n case xs != [] => {\n var zs := xs + ys;\n }\n }\n}\n\nlemma ReverseInvolution(xxs: seq)\nensures reverse(reverse(xxs)) == xxs\n{\n if {\n case xxs == [] => {}\n case xxs != [] => calc {\n reverse(reverse(xxs));\n ==\n reverse(reverse(xxs[1..]) + [xxs[0]]);\n ==\n { ReverseAppendDistr(reverse(xxs[1..]), [xxs[0]]); }\n reverse([xxs[0]]) + reverse(reverse(xxs[1..]));\n ==\n { ReverseInvolution(xxs[1..]); }\n calc {\n reverse([xxs[0]]);\n ==\n [] + [xxs[0]];\n ==\n [xxs[0]];\n }\n [xxs[0]] + xxs[1..];\n ==\n xxs;\n }\n }\n}\n\n" }, { "test_ID": "675", "test_file": "dafny_tmp_tmp49a6ihvk_m4.dfy", "ground_truth": "datatype Color = Red | White | Blue\n\npredicate Below(c: Color, d: Color)\n{\n c == Red || c == d || d == Blue\n}\n\n\n\nmethod DutchFlag(a: array)\n modifies a\n ensures forall i, j :: 0 <= i < j < a.Length ==> Below(a[i], a[j])\n ensures multiset(a[..]) == multiset(old(a[..]))\n{\n var r,w,b := 0, 0, a.Length;\n while w < b\n invariant 0 <= r <= w <= b <= a.Length\n invariant forall i :: 0 <= i < r ==> a[i] == Red\n invariant forall i :: r <= i < w ==> a[i] == White\n invariant forall i :: b <= i < a.Length ==> a[i] == Blue\n invariant multiset(a[..]) == multiset(old(a[..]))\n {\n match a[w]\n case Red => \n a[r], a[w] := a[w], a[r];\n r, w := r + 1, w + 1;\n case White => \n w := w + 1;\n case Blue => \n a[b-1], a[w] := a[w], a[b-1];\n b := b - 1;\n }\n}\n", "hints_removed": "datatype Color = Red | White | Blue\n\npredicate Below(c: Color, d: Color)\n{\n c == Red || c == d || d == Blue\n}\n\n\n\nmethod DutchFlag(a: array)\n modifies a\n ensures forall i, j :: 0 <= i < j < a.Length ==> Below(a[i], a[j])\n ensures multiset(a[..]) == multiset(old(a[..]))\n{\n var r,w,b := 0, 0, a.Length;\n while w < b\n {\n match a[w]\n case Red => \n a[r], a[w] := a[w], a[r];\n r, w := r + 1, w + 1;\n case White => \n w := w + 1;\n case Blue => \n a[b-1], a[w] := a[w], a[b-1];\n b := b - 1;\n }\n}\n" }, { "test_ID": "676", "test_file": "dafny_tmp_tmp59p638nn_examples_GenericSelectionSort.dfy", "ground_truth": "\n\ntrait Comparable {\n function Lt(x: T, y: T): bool\n}\n\n trait Sorted extends Comparable {\n\n ghost predicate Ordered(a: array, left: nat, right: nat)\n reads a\n requires left <= right <= a.Length\n {\n forall i: nat :: 0 < left <= i < right ==> Lt(a[i-1],a[i]) || a[i-1] == a[i]\n }\n\n twostate predicate Preserved(a: array, left: nat, right: nat)\n reads a\n requires left <= right <= a.Length\n {\n multiset(a[left..right]) == multiset(old(a[left..right]))\n }\n\n twostate predicate Sorted(a: array)\n reads a\n {\n Ordered(a,0,a.Length) && Preserved(a,0,a.Length)\n }\n\n }\n\n// trait SelectionSort extends Comparable, Sorted {\n\n// method SelectionSort(a: array)\n// modifies a\n// ensures Sorted(a)\n// {\n// for i := 0 to a.Length\n// invariant Ordered(a,0,i)\n// invariant Preserved(a,0,a.Length)\n// {\n// var minValue := a[i];\n// var minPos := i;\n// for j := i + 1 to a.Length\n// invariant minPos < a.Length\n// invariant a[minPos] == minValue\n// {\n// if Lt(a[j], minValue) {\n// minValue := a[j];\n// minPos := j;\n// }\n// }\n// if i != minPos {\n// a[i], a[minPos] := minValue, a[i];\n// }\n// }\n// }\n\n// }\n\nclass Sort extends SelectionSort {\n const CMP: (T,T) -> bool\n\n constructor(cmp: (T,T) -> bool)\n ensures CMP == cmp\n ensures comparisonCount == 0\n {\n CMP := cmp;\n comparisonCount := 0;\n }\n\n function Lt(x: T, y: T): bool {\n CMP(x,y)\n }\n}\n\nghost function Sum(x: int): nat\n{\n if x <= 0 then 0 else x + Sum(x-1)\n}\n\ntrait Measurable extends Comparable {\n\n ghost var comparisonCount: nat\n\n method Ltm(x: T, y: T) returns (b: bool)\n modifies this`comparisonCount\n ensures b ==> Lt(x,y)\n ensures comparisonCount == old(comparisonCount) + 1\n {\n comparisonCount := comparisonCount + 1;\n b := Lt(x,y);\n }\n\n}\n\n trait SelectionSort extends Comparable, Measurable, Sorted {\n\n method SelectionSort(a: array)\n modifies a, this\n requires comparisonCount == 0\n ensures Sorted(a)\n ensures comparisonCount <= a.Length * a.Length\n {\n\n for i := 0 to a.Length\n invariant Ordered(a,0,i)\n invariant Preserved(a,0,a.Length)\n invariant comparisonCount == i * a.Length - Sum(i)\n {\n var minValue := a[i];\n var minPos := i;\n assert comparisonCount == i * a.Length - Sum(i) + (i + 1 - i) - 1;\n for j := i + 1 to a.Length\n invariant minPos < a.Length\n invariant a[minPos] == minValue\n invariant Preserved(a,0,a.Length)\n invariant comparisonCount == i * a.Length - Sum(i) + (j - i) - 1\n {\n label L:\n var cmp := Ltm(a[j], minValue);\n assert a[..] == old@L(a[..]);\n if cmp {\n minValue := a[j];\n minPos := j;\n }\n assert(i * a.Length - Sum(i) + (j - i) - 1) + 1 == i * a.Length - Sum(i) + ((j + 1) - i) - 1;\n }\n if i != minPos {\n a[i], a[minPos] := minValue, a[i];\n }\n assert comparisonCount == (i+1) * a.Length - Sum(i+1);\n }\n }\n\n}\n\nmethod Main()\n{\n var a: array := new int[3];\n a[0] := 2; a[1] := 4; a[2] := 1;\n var Sort := new Sort((x: int, y: int) => x < y);\n Sort.SelectionSort(a);\n print a[..];\n}\n", "hints_removed": "\n\ntrait Comparable {\n function Lt(x: T, y: T): bool\n}\n\n trait Sorted extends Comparable {\n\n ghost predicate Ordered(a: array, left: nat, right: nat)\n reads a\n requires left <= right <= a.Length\n {\n forall i: nat :: 0 < left <= i < right ==> Lt(a[i-1],a[i]) || a[i-1] == a[i]\n }\n\n twostate predicate Preserved(a: array, left: nat, right: nat)\n reads a\n requires left <= right <= a.Length\n {\n multiset(a[left..right]) == multiset(old(a[left..right]))\n }\n\n twostate predicate Sorted(a: array)\n reads a\n {\n Ordered(a,0,a.Length) && Preserved(a,0,a.Length)\n }\n\n }\n\n// trait SelectionSort extends Comparable, Sorted {\n\n// method SelectionSort(a: array)\n// modifies a\n// ensures Sorted(a)\n// {\n// for i := 0 to a.Length\n// invariant Ordered(a,0,i)\n// invariant Preserved(a,0,a.Length)\n// {\n// var minValue := a[i];\n// var minPos := i;\n// for j := i + 1 to a.Length\n// invariant minPos < a.Length\n// invariant a[minPos] == minValue\n// {\n// if Lt(a[j], minValue) {\n// minValue := a[j];\n// minPos := j;\n// }\n// }\n// if i != minPos {\n// a[i], a[minPos] := minValue, a[i];\n// }\n// }\n// }\n\n// }\n\nclass Sort extends SelectionSort {\n const CMP: (T,T) -> bool\n\n constructor(cmp: (T,T) -> bool)\n ensures CMP == cmp\n ensures comparisonCount == 0\n {\n CMP := cmp;\n comparisonCount := 0;\n }\n\n function Lt(x: T, y: T): bool {\n CMP(x,y)\n }\n}\n\nghost function Sum(x: int): nat\n{\n if x <= 0 then 0 else x + Sum(x-1)\n}\n\ntrait Measurable extends Comparable {\n\n ghost var comparisonCount: nat\n\n method Ltm(x: T, y: T) returns (b: bool)\n modifies this`comparisonCount\n ensures b ==> Lt(x,y)\n ensures comparisonCount == old(comparisonCount) + 1\n {\n comparisonCount := comparisonCount + 1;\n b := Lt(x,y);\n }\n\n}\n\n trait SelectionSort extends Comparable, Measurable, Sorted {\n\n method SelectionSort(a: array)\n modifies a, this\n requires comparisonCount == 0\n ensures Sorted(a)\n ensures comparisonCount <= a.Length * a.Length\n {\n\n for i := 0 to a.Length\n {\n var minValue := a[i];\n var minPos := i;\n for j := i + 1 to a.Length\n {\n label L:\n var cmp := Ltm(a[j], minValue);\n if cmp {\n minValue := a[j];\n minPos := j;\n }\n }\n if i != minPos {\n a[i], a[minPos] := minValue, a[i];\n }\n }\n }\n\n}\n\nmethod Main()\n{\n var a: array := new int[3];\n a[0] := 2; a[1] := 4; a[2] := 1;\n var Sort := new Sort((x: int, y: int) => x < y);\n Sort.SelectionSort(a);\n print a[..];\n}\n" }, { "test_ID": "677", "test_file": "dafny_tmp_tmp59p638nn_examples_SelectionSort.dfy", "ground_truth": "\ntwostate predicate Preserved(a: array, left: nat, right: nat)\n reads a\n requires left <= right <= a.Length\n{\n multiset(a[left..right]) == multiset(old(a[left..right]))\n}\n\nghost predicate Ordered(a: array, left: nat, right: nat)\n reads a\n requires left <= right <= a.Length\n{\n forall i: nat :: 0 < left <= i < right ==> a[i-1] <= a[i]\n}\n\ntwostate predicate Sorted(a: array)\n reads a\n{\n Ordered(a,0,a.Length) && Preserved(a,0,a.Length)\n}\n\nmethod SelectionnSort(a: array)\n modifies a\n ensures Sorted(a)\n{\n for i := 0 to a.Length\n invariant Ordered(a,0,i)\n invariant Preserved(a,0,a.Length)\n {\n var minValue := a[i];\n var minPos := i;\n for j := i + 1 to a.Length\n invariant minPos < a.Length\n invariant a[minPos] == minValue\n {\n if a[j] < minValue {\n minValue := a[j];\n minPos := j;\n }\n }\n if i != minPos {\n a[i], a[minPos] := minValue, a[i];\n }\n }\n}\n\n method SelectionSort(a: array)\n modifies a\n ensures Sorted(a)\n {\n for i := 0 to a.Length\n invariant Ordered(a,0,i)\n invariant Preserved(a,0,a.Length)\n {\n ghost var minValue := a[i];\n for j := i + 1 to a.Length\n invariant a[i] == minValue\n invariant Preserved(a,0,a.Length)\n {\n label L:\n // assert a[..] == a[0..a.Length];\n assert a[..] == old@L(a[..]);\n\n if a[j] < minValue {\n minValue := a[j];\n }\n if a[j] < a[i] {\n assert j != i;\n a[i], a[j] := a[j], a[i];\n // assert Preserved(a, 0, a.Length);\n }else{\n // assert Preserved(a, 0, a.Length);\n }\n }\n assert a[i] == minValue;\n }\n }\n", "hints_removed": "\ntwostate predicate Preserved(a: array, left: nat, right: nat)\n reads a\n requires left <= right <= a.Length\n{\n multiset(a[left..right]) == multiset(old(a[left..right]))\n}\n\nghost predicate Ordered(a: array, left: nat, right: nat)\n reads a\n requires left <= right <= a.Length\n{\n forall i: nat :: 0 < left <= i < right ==> a[i-1] <= a[i]\n}\n\ntwostate predicate Sorted(a: array)\n reads a\n{\n Ordered(a,0,a.Length) && Preserved(a,0,a.Length)\n}\n\nmethod SelectionnSort(a: array)\n modifies a\n ensures Sorted(a)\n{\n for i := 0 to a.Length\n {\n var minValue := a[i];\n var minPos := i;\n for j := i + 1 to a.Length\n {\n if a[j] < minValue {\n minValue := a[j];\n minPos := j;\n }\n }\n if i != minPos {\n a[i], a[minPos] := minValue, a[i];\n }\n }\n}\n\n method SelectionSort(a: array)\n modifies a\n ensures Sorted(a)\n {\n for i := 0 to a.Length\n {\n ghost var minValue := a[i];\n for j := i + 1 to a.Length\n {\n label L:\n // assert a[..] == a[0..a.Length];\n\n if a[j] < minValue {\n minValue := a[j];\n }\n if a[j] < a[i] {\n a[i], a[j] := a[j], a[i];\n // assert Preserved(a, 0, a.Length);\n }else{\n // assert Preserved(a, 0, a.Length);\n }\n }\n }\n }\n" }, { "test_ID": "678", "test_file": "dafny_tmp_tmp59p638nn_examples_derangement.dfy", "ground_truth": "\npredicate derangement(s: seq) {\n forall i :: 0 <= i < |s| ==> s[i] != i\n}\n\npredicate permutation(s: seq) {\n forall i :: 0 <= i < |s| ==> i in s\n}\n\nfunction multisetRange(n: nat): multiset {\n multiset(seq(n, i => i))\n}\n\npredicate distinct(s: seq) {\n forall x,y :: x != y && 0 <= x <= y < |s| ==> s[x] != s[y]\n}\n\nmethod test() {\n var tests := [2,0,1];\n var tests2 := [0,1,2];\n var t4 := seq(3, i => i);\n var test3 := multisetRange(3);\n assert t4 == tests2;\n assert 0 in t4;\n assert 0 in test3;\n assert multiset(tests) == multisetRange(3);\n assert derangement(tests);\n assert permutation(tests);\n assert permutation(tests2);\n // assert !derangement(tests2);\n}\n\nmethod {:timelimit 40} end(links: seq)\n requires |links| > 0\n requires permutation(links)\n requires derangement(links)\n requires distinct(links)\n{\n assume forall x :: x in links ==> 0 <= x < |links|;\n assume forall x :: x in links ==> multiset(links)[x] ==1;\n // assume multiset(links) == multisetRange(|links|);\n var qAct: nat := links[0];\n assert links[0] in links;\n var i : nat := 0;\n ghost var oldIndex := 0;\n ghost var indices: multiset := multiset{0};\n ghost var visited: multiset := multiset{};\n\n while qAct != 0\n invariant 0 <= oldIndex < |links|\n invariant qAct == links[oldIndex]\n invariant oldIndex in indices\n invariant qAct in links\n invariant indices == visited + multiset{0}\n invariant forall x :: x in visited ==> exists k :: 0 <= k < |links| && links[k] == x && k in indices\n invariant qAct !in visited\n invariant 0 <= qAct < |links|\n decreases multiset(links) - visited\n {\n ghost var oldVisit := visited;\n ghost var oldqAct := qAct;\n ghost var oldOldIndex := oldIndex;\n oldIndex := qAct;\n visited := visited + multiset{qAct};\n indices := indices + multiset{qAct};\n assert oldqAct in visited;\n assert forall x :: x in visited ==> exists k :: 0 <= k < |links| && links[k] == x && k in indices;// by {\n // forall x | x in visited \n // ensures exists k :: 0 <= k < |links| && links[k] == x && k in indices\n // {\n // if x == oldqAct {\n // // assert links[oldOldIndex] == oldqAct;\n // // assert exists k :: 0 <= k < |links| && links[k] == x && k in indices;\n // }else {\n // // assert x in oldVisit;\n // // assert exists k :: 0 <= k < |links| && links[k] == x && k in indices;\n // }\n // }\n //}\n qAct := links[qAct];\n i := i + 1;\n }\n}\n", "hints_removed": "\npredicate derangement(s: seq) {\n forall i :: 0 <= i < |s| ==> s[i] != i\n}\n\npredicate permutation(s: seq) {\n forall i :: 0 <= i < |s| ==> i in s\n}\n\nfunction multisetRange(n: nat): multiset {\n multiset(seq(n, i => i))\n}\n\npredicate distinct(s: seq) {\n forall x,y :: x != y && 0 <= x <= y < |s| ==> s[x] != s[y]\n}\n\nmethod test() {\n var tests := [2,0,1];\n var tests2 := [0,1,2];\n var t4 := seq(3, i => i);\n var test3 := multisetRange(3);\n // assert !derangement(tests2);\n}\n\nmethod {:timelimit 40} end(links: seq)\n requires |links| > 0\n requires permutation(links)\n requires derangement(links)\n requires distinct(links)\n{\n assume forall x :: x in links ==> 0 <= x < |links|;\n assume forall x :: x in links ==> multiset(links)[x] ==1;\n // assume multiset(links) == multisetRange(|links|);\n var qAct: nat := links[0];\n var i : nat := 0;\n ghost var oldIndex := 0;\n ghost var indices: multiset := multiset{0};\n ghost var visited: multiset := multiset{};\n\n while qAct != 0\n {\n ghost var oldVisit := visited;\n ghost var oldqAct := qAct;\n ghost var oldOldIndex := oldIndex;\n oldIndex := qAct;\n visited := visited + multiset{qAct};\n indices := indices + multiset{qAct};\n // forall x | x in visited \n // ensures exists k :: 0 <= k < |links| && links[k] == x && k in indices\n // {\n // if x == oldqAct {\n // // assert links[oldOldIndex] == oldqAct;\n // // assert exists k :: 0 <= k < |links| && links[k] == x && k in indices;\n // }else {\n // // assert x in oldVisit;\n // // assert exists k :: 0 <= k < |links| && links[k] == x && k in indices;\n // }\n // }\n //}\n qAct := links[qAct];\n i := i + 1;\n }\n}\n" }, { "test_ID": "679", "test_file": "dafny_tmp_tmp59p638nn_examples_minmax2.dfy", "ground_truth": "method DifferenceMinMax(a: array) returns (diff: int)\n requires a.Length > 0\n ensures diff == (Max(a[..]) - Min(a[..]))\n{\n var minVal := a[0];\n var maxVal := a[0];\n for i := 1 to a.Length\n invariant 1 <= i <= a.Length\n invariant minVal <= maxVal\n invariant forall k :: 0 <= k < i ==> minVal <= a[k] && a[k] <= maxVal\n invariant minVal == Min(a[..i])\n invariant maxVal == Max(a[..i])\n {\n if a[i] < minVal {\n minVal := a[i];\n } else if a[i] > maxVal {\n maxVal := a[i];\n }\n assert a[..i+1][..i] == a[..i];\n }\n assert a[..a.Length] == a[..];\n diff := maxVal - minVal;\n}\n\nfunction Min(a: seq) : (m: int)\n requires |a| > 0\n{\n if |a| == 1 then a[0]\n else\n var minPrefix := Min(a[..|a|-1]);\n if a[|a|-1] <= minPrefix then a[|a|-1] else minPrefix\n}\n\nfunction Max(a: seq) : (m: int)\n requires |a| > 0\n{\n if |a| == 1 then a[0]\n else\n var maxPrefix := Max(a[..|a|-1]);\n if a[|a|-1] >= maxPrefix then a[|a|-1] else maxPrefix\n}\n", "hints_removed": "method DifferenceMinMax(a: array) returns (diff: int)\n requires a.Length > 0\n ensures diff == (Max(a[..]) - Min(a[..]))\n{\n var minVal := a[0];\n var maxVal := a[0];\n for i := 1 to a.Length\n {\n if a[i] < minVal {\n minVal := a[i];\n } else if a[i] > maxVal {\n maxVal := a[i];\n }\n }\n diff := maxVal - minVal;\n}\n\nfunction Min(a: seq) : (m: int)\n requires |a| > 0\n{\n if |a| == 1 then a[0]\n else\n var minPrefix := Min(a[..|a|-1]);\n if a[|a|-1] <= minPrefix then a[|a|-1] else minPrefix\n}\n\nfunction Max(a: seq) : (m: int)\n requires |a| > 0\n{\n if |a| == 1 then a[0]\n else\n var maxPrefix := Max(a[..|a|-1]);\n if a[|a|-1] >= maxPrefix then a[|a|-1] else maxPrefix\n}\n" }, { "test_ID": "680", "test_file": "dafny_tmp_tmp59p638nn_examples_realExponent.dfy", "ground_truth": "\nghost function power(n: real, alpha: real): real\n requires n > 0.0 && alpha > 0.0\n ensures power(n, alpha) > 0.0\n\nghost function log(n: real, alpha: real): real\n requires n > 0.0 && alpha > 0.0\n ensures log(n, alpha) > 0.0\n\nlemma consistency(n: real, alpha: real)\n requires n > 0.0 && alpha > 0.0\n ensures log(power(n,alpha), alpha) == n\n ensures power(log(n, alpha), alpha) == n\n\nlemma logarithmSum(n: real, alpha: real, x: real, y: real)\n requires n > 0.0 && alpha > 0.0\n requires x > 0.0\n requires n == x * y\n ensures log(n,alpha) == log(x, alpha) + log(y, alpha)\n\nlemma powerLemma(n: real, alpha: real)\n requires n > 0.0 && alpha > 0.0\n ensures power(n, alpha) * alpha == power(n+1.0, alpha)\n\nlemma power1(alpha: real)\n requires alpha > 0.0\n ensures power(1.0, alpha) == alpha\n\nlemma test() {\n var pow3 := power(3.0,4.0);\n consistency(3.0,4.0);\n assert log(pow3, 4.0) == 3.0;\n var log6 := log(6.0,8.0);\n logarithmSum(6.0, 8.0, 2.0, 3.0);\n assert log6 == log(2.0,8.0)+log(3.0,8.0);\n}\n\nlemma test2() {\n var pow3 := power(3.0, 4.0);\n var power4 := power(4.0, 4.0);\n powerLemma(3.0, 4.0);\n assert pow3 * 4.0 == power4;\n}\n\nmethod pow(n: nat, alpha: real) returns (product: real)\n requires n > 0\n requires alpha > 0.0\n ensures product == power(n as real, alpha)\n{\n product := alpha;\n var i: nat := 1;\n power1(alpha);\n assert product == power(1.0, alpha);\n while i < n\n invariant i <= n\n invariant product == power(i as real, alpha)\n {\n powerLemma(i as real, alpha);\n product := product * alpha;\n i := i + 1;\n }\n assert i == n;\n assert product == power(n as real, alpha);\n}\n", "hints_removed": "\nghost function power(n: real, alpha: real): real\n requires n > 0.0 && alpha > 0.0\n ensures power(n, alpha) > 0.0\n\nghost function log(n: real, alpha: real): real\n requires n > 0.0 && alpha > 0.0\n ensures log(n, alpha) > 0.0\n\nlemma consistency(n: real, alpha: real)\n requires n > 0.0 && alpha > 0.0\n ensures log(power(n,alpha), alpha) == n\n ensures power(log(n, alpha), alpha) == n\n\nlemma logarithmSum(n: real, alpha: real, x: real, y: real)\n requires n > 0.0 && alpha > 0.0\n requires x > 0.0\n requires n == x * y\n ensures log(n,alpha) == log(x, alpha) + log(y, alpha)\n\nlemma powerLemma(n: real, alpha: real)\n requires n > 0.0 && alpha > 0.0\n ensures power(n, alpha) * alpha == power(n+1.0, alpha)\n\nlemma power1(alpha: real)\n requires alpha > 0.0\n ensures power(1.0, alpha) == alpha\n\nlemma test() {\n var pow3 := power(3.0,4.0);\n consistency(3.0,4.0);\n var log6 := log(6.0,8.0);\n logarithmSum(6.0, 8.0, 2.0, 3.0);\n}\n\nlemma test2() {\n var pow3 := power(3.0, 4.0);\n var power4 := power(4.0, 4.0);\n powerLemma(3.0, 4.0);\n}\n\nmethod pow(n: nat, alpha: real) returns (product: real)\n requires n > 0\n requires alpha > 0.0\n ensures product == power(n as real, alpha)\n{\n product := alpha;\n var i: nat := 1;\n power1(alpha);\n while i < n\n {\n powerLemma(i as real, alpha);\n product := product * alpha;\n i := i + 1;\n }\n}\n" }, { "test_ID": "681", "test_file": "eth2-dafny_tmp_tmpcrgexrgb_src_dafny_utils_SetHelpers.dfy", "ground_truth": "/*\n * Copyright 2021 ConsenSys Software Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may \n * not use this file except in compliance with the License. You may obtain \n * a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software dis-\n * tributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT \n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the \n * License for the specific language governing permissions and limitations \n * under the License.\n */\n\n/**\n * Provide some folk theorems on sets.\n */\nmodule SetHelpers {\n\n /**\n * If a set is included in another one, their intersection\n * is the smallest one.\n *\n * @param T A type.\n * @param x A finite set.\n * @param y A finite set.\n * @returns A proof that x <= y implies x * y == x.\n */\n lemma interSmallest(x : set, y : set) \n requires x <= y \n ensures x * y == x\n decreases y \n { // Thanks Dafny\n }\n\n /**\n * If x [= {0, ..., k - 1} and y [= {0, .., k - 1}\n * then x U y has at most k elements.\n *\n * @param T A type.\n * @param x A finite set.\n * @param y A finite set.\n * @param k k a natural number.\n * @returns A proof that if x [= {0, ..., k - 1} and y [= {0, .., k - 1}\n * then |x + y| <=k.\n */\n lemma unionCardBound(x : set, y : set, k : nat) \n requires forall e :: e in x ==> e < k\n requires forall e :: e in y ==> e < k\n ensures forall e :: e in x + y ==> e < k\n ensures |x + y| <= k \n {\n natSetCardBound(x + y, k);\n }\n\n /**\n * If x [= {0, ..., k - 1} then x has at most k elements.\n *\n * @param T A type.\n * @param x A finite set.\n * @param k k a natural number.\n * @returns A proof that if x [= {0, ..., k - 1} then |x| <= k.\n */\n lemma natSetCardBound(x : set, k : nat) \n requires forall e :: e in x ==> e < k\n ensures |x| <= k \n decreases k\n {\n if k == 0 {\n assert(x == { });\n } else {\n natSetCardBound(x - { k - 1}, k - 1);\n }\n }\n\n /** \n * If x contains all successive elements {0, ..., k-1} then x has k elements.\n *\n * @param T A type.\n * @param x A finite set.\n * @param k k a natural number.\n * @returns A proof that if x = {0, ..., k - 1} then |x| == k.\n */\n\n lemma {:induction k} successiveNatSetCardBound(x : set, k : nat) \n requires x == set x: nat | 0 <= x < k :: x\n ensures |x| == k\n {\n if k == 0 {\n // Thanks Dafny\n } else {\n successiveNatSetCardBound(x - {k - 1}, k - 1);\n }\n }\n \n /**\n * If a finite set x is included in a finite set y, then\n * card(x) <= card(y).\n *\n * @param T A type.\n * @param x A finite set.\n * @param y A finite set.\n * @returns A proof that x <= y implies card(x) <= card(y)\n * in other terms, card(_) is monotonic.\n */\n lemma cardIsMonotonic(x : set, y : set) \n requires x <= y \n ensures |x| <= |y|\n decreases y \n {\n if |y| == 0 {\n // Thanks Dafny\n } else {\n // |y| >= 1, get an element in y\n var e :| e in y;\n var y' := y - { e };\n // Split recursion according to whether e in x or not\n cardIsMonotonic(if e in x then x - {e} else x, y');\n }\n }\n\n /**\n * If two finite sets x and y are included in another one z and\n * have more than 2/3(|z|) elements, then their intersection has more\n * then |z|/3 elements.\n *\n * @param T A type.\n * @param x A finite set.\n * @param y A finite set.\n * @param z A finite set.\n * @returns A proof that if two finite sets x and y are included in \n * another one z and have more than 2/3(|z|) elements, then \n * their intersection has more then |z|/3 elements. \n */\n lemma pigeonHolePrinciple(x: set, y : set, z : set)\n requires x <= z \n requires y <= z\n requires |x| >= 2 * |z| / 3 + 1 // or equivalently 2 * |z| < 3 * |x| \n requires |y| >= 2 * |z| / 3 + 1 // or equivalently 2 * |z| < 3 * |y|\n ensures |x * y| >= |z| / 3 + 1 // or equivalently 3 * |x * y| < |z| \n {\n // Proof of alternative assumption\n assert(|x| >= 2 * |z| / 3 + 1 <==> 2 * |z| < 3 * |x|);\n assert(|y| >= 2 * |z| / 3 + 1 <==> 2 * |z| < 3 * |y|);\n // Proof by contradiction\n if |x * y| < |z| / 3 + 1 {\n // size of union is sum of sizes minus size of intersection.\n calc == {\n |x + y|;\n |x| + |y| - |x * y|;\n }\n cardIsMonotonic(x + y, z);\n } \n // proof of alternative conclusion\n assert(3 * |x * y| > |z| <==> |x * y| >= |z| / 3 + 1 );\n } \n\n}\n\n", "hints_removed": "/*\n * Copyright 2021 ConsenSys Software Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may \n * not use this file except in compliance with the License. You may obtain \n * a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software dis-\n * tributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT \n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the \n * License for the specific language governing permissions and limitations \n * under the License.\n */\n\n/**\n * Provide some folk theorems on sets.\n */\nmodule SetHelpers {\n\n /**\n * If a set is included in another one, their intersection\n * is the smallest one.\n *\n * @param T A type.\n * @param x A finite set.\n * @param y A finite set.\n * @returns A proof that x <= y implies x * y == x.\n */\n lemma interSmallest(x : set, y : set) \n requires x <= y \n ensures x * y == x\n { // Thanks Dafny\n }\n\n /**\n * If x [= {0, ..., k - 1} and y [= {0, .., k - 1}\n * then x U y has at most k elements.\n *\n * @param T A type.\n * @param x A finite set.\n * @param y A finite set.\n * @param k k a natural number.\n * @returns A proof that if x [= {0, ..., k - 1} and y [= {0, .., k - 1}\n * then |x + y| <=k.\n */\n lemma unionCardBound(x : set, y : set, k : nat) \n requires forall e :: e in x ==> e < k\n requires forall e :: e in y ==> e < k\n ensures forall e :: e in x + y ==> e < k\n ensures |x + y| <= k \n {\n natSetCardBound(x + y, k);\n }\n\n /**\n * If x [= {0, ..., k - 1} then x has at most k elements.\n *\n * @param T A type.\n * @param x A finite set.\n * @param k k a natural number.\n * @returns A proof that if x [= {0, ..., k - 1} then |x| <= k.\n */\n lemma natSetCardBound(x : set, k : nat) \n requires forall e :: e in x ==> e < k\n ensures |x| <= k \n {\n if k == 0 {\n } else {\n natSetCardBound(x - { k - 1}, k - 1);\n }\n }\n\n /** \n * If x contains all successive elements {0, ..., k-1} then x has k elements.\n *\n * @param T A type.\n * @param x A finite set.\n * @param k k a natural number.\n * @returns A proof that if x = {0, ..., k - 1} then |x| == k.\n */\n\n lemma {:induction k} successiveNatSetCardBound(x : set, k : nat) \n requires x == set x: nat | 0 <= x < k :: x\n ensures |x| == k\n {\n if k == 0 {\n // Thanks Dafny\n } else {\n successiveNatSetCardBound(x - {k - 1}, k - 1);\n }\n }\n \n /**\n * If a finite set x is included in a finite set y, then\n * card(x) <= card(y).\n *\n * @param T A type.\n * @param x A finite set.\n * @param y A finite set.\n * @returns A proof that x <= y implies card(x) <= card(y)\n * in other terms, card(_) is monotonic.\n */\n lemma cardIsMonotonic(x : set, y : set) \n requires x <= y \n ensures |x| <= |y|\n {\n if |y| == 0 {\n // Thanks Dafny\n } else {\n // |y| >= 1, get an element in y\n var e :| e in y;\n var y' := y - { e };\n // Split recursion according to whether e in x or not\n cardIsMonotonic(if e in x then x - {e} else x, y');\n }\n }\n\n /**\n * If two finite sets x and y are included in another one z and\n * have more than 2/3(|z|) elements, then their intersection has more\n * then |z|/3 elements.\n *\n * @param T A type.\n * @param x A finite set.\n * @param y A finite set.\n * @param z A finite set.\n * @returns A proof that if two finite sets x and y are included in \n * another one z and have more than 2/3(|z|) elements, then \n * their intersection has more then |z|/3 elements. \n */\n lemma pigeonHolePrinciple(x: set, y : set, z : set)\n requires x <= z \n requires y <= z\n requires |x| >= 2 * |z| / 3 + 1 // or equivalently 2 * |z| < 3 * |x| \n requires |y| >= 2 * |z| / 3 + 1 // or equivalently 2 * |z| < 3 * |y|\n ensures |x * y| >= |z| / 3 + 1 // or equivalently 3 * |x * y| < |z| \n {\n // Proof of alternative assumption\n // Proof by contradiction\n if |x * y| < |z| / 3 + 1 {\n // size of union is sum of sizes minus size of intersection.\n calc == {\n |x + y|;\n |x| + |y| - |x * y|;\n }\n cardIsMonotonic(x + y, z);\n } \n // proof of alternative conclusion\n } \n\n}\n\n" }, { "test_ID": "682", "test_file": "feup-mfes_tmp_tmp6_a1y5a5_examples_SelectionSort.dfy", "ground_truth": "/* \n* Formal verification of the selection sort algorithm with Dafny.\n* FEUP, MIEIC, MFES, 2020/21.\n*/\n\n// Checks if array 'a' is sorted between positions 'from' (inclusive) and 'to' (exclusive).\npredicate isSorted(a: array, from: nat, to: nat)\n requires 0 <= from <= to <= a.Length\n reads a\n{\n forall i, j :: from <= i < j < to ==> a[i] <= a[j] \n}\n\n// Sorts array 'a' using the selection sort algorithm.\nmethod selectionSort(a: array)\n modifies a\n ensures isSorted(a, 0, a.Length) \n ensures multiset(a[..]) == multiset(old(a[..]))\n{\n var i := 0; \n while i < a.Length - 1 \n invariant 0 <= i <= a.Length\n invariant isSorted(a, 0, i)\n invariant forall lhs, rhs :: 0 <= lhs < i <= rhs < a.Length ==> a[lhs] <= a[rhs] \n invariant multiset(a[..]) == multiset(old(a[..]))\n {\n var j := findMin(a, i, a.Length);\n a[i], a[j] := a[j], a[i];\n i := i + 1;\n }\n\n}\n\n// Finds the position of a miminum value in non-empty subarray 'a' between positions \n// 'from' (inclusive) and 'to' (exclusive)\nmethod findMin(a: array, from: nat, to: nat) returns(index: nat)\n requires 0 <= from < to <= a.Length\n ensures from <= index < to\n ensures forall k :: from <= k < to ==> a[k] >= a[index]\n{\n var i := from + 1;\n index := from; // position of min up to position i (excluded)\n while i < to\n decreases a.Length - i\n invariant from <= index < i <= to\n invariant forall k :: from <= k < i ==> a[k] >= a[index] \n {\n if a[i] < a[index] {\n index := i;\n }\n i := i + 1;\n }\n}\n\nmethod testSelectionSort() {\n var a := new real[5] [9.0, 4.0, 6.0, 3.0, 8.0];\n assert a[..] == [9.0, 4.0, 6.0, 3.0, 8.0]; // to help Dafny ...\n selectionSort(a);\n assert a[..] == [3.0, 4.0, 6.0, 8.0, 9.0];\n}\n\nmethod testFindMin() {\n var a := new real[5] [9.0, 5.0, 6.0, 4.0, 8.0];\n var m := findMin(a, 0, 5);\n assert a[3] == 4.0; // to help Dafny ... \n assert m == 3;\n}\n", "hints_removed": "/* \n* Formal verification of the selection sort algorithm with Dafny.\n* FEUP, MIEIC, MFES, 2020/21.\n*/\n\n// Checks if array 'a' is sorted between positions 'from' (inclusive) and 'to' (exclusive).\npredicate isSorted(a: array, from: nat, to: nat)\n requires 0 <= from <= to <= a.Length\n reads a\n{\n forall i, j :: from <= i < j < to ==> a[i] <= a[j] \n}\n\n// Sorts array 'a' using the selection sort algorithm.\nmethod selectionSort(a: array)\n modifies a\n ensures isSorted(a, 0, a.Length) \n ensures multiset(a[..]) == multiset(old(a[..]))\n{\n var i := 0; \n while i < a.Length - 1 \n {\n var j := findMin(a, i, a.Length);\n a[i], a[j] := a[j], a[i];\n i := i + 1;\n }\n\n}\n\n// Finds the position of a miminum value in non-empty subarray 'a' between positions \n// 'from' (inclusive) and 'to' (exclusive)\nmethod findMin(a: array, from: nat, to: nat) returns(index: nat)\n requires 0 <= from < to <= a.Length\n ensures from <= index < to\n ensures forall k :: from <= k < to ==> a[k] >= a[index]\n{\n var i := from + 1;\n index := from; // position of min up to position i (excluded)\n while i < to\n {\n if a[i] < a[index] {\n index := i;\n }\n i := i + 1;\n }\n}\n\nmethod testSelectionSort() {\n var a := new real[5] [9.0, 4.0, 6.0, 3.0, 8.0];\n selectionSort(a);\n}\n\nmethod testFindMin() {\n var a := new real[5] [9.0, 5.0, 6.0, 4.0, 8.0];\n var m := findMin(a, 0, 5);\n}\n" }, { "test_ID": "683", "test_file": "formal-methods-in-software-engineering_tmp_tmpe7fjnek6_Labs2_gr2.dfy", "ground_truth": "datatype Nat = Zero | Succ(Pred: Nat)\n\n/*\n\nNat: Zero, Succ(Zero), Succ(Succ(Zero)), ...\n\n*/\n\nlemma Disc(n: Nat)\nensures n.Succ? || n.Zero?\n{\n //\n}\n\nlemma LPred(n: Nat)\nensures Succ(n).Pred == n\n{\n //\n}\n\n// Succ(m') > m'\n\nfunction add(m: Nat, n: Nat) : Nat\ndecreases m\n{\n match m\n case Zero => n\n case Succ(m') => Succ(add(m', n))\n}\n\n// add(m, Zero) = m\n\nlemma AddZero(m: Nat)\nensures add(m, Zero) == m\n{\n //\n}\n\nlemma AddAssoc(m: Nat, n: Nat, p: Nat)\nensures add(m, add(n, p)) == add(add(m, n), p)\n{\n //\n}\n\nlemma AddComm(m: Nat, n: Nat)\nensures add(m, n) == add(n, m)\n{\n match m\n case Zero => AddZero(n);\n case Succ(m') => AddComm(m', n);\n}\n\npredicate lt(m: Nat, n: Nat)\n{\n (m.Zero? && n.Succ?) ||\n (m.Succ? && n.Succ? && lt(m.Pred, n.Pred))\n}\n\nlemma Test1(n:Nat)\nensures lt(n, Succ(Succ(n)))\n{\n //\n}\n\nlemma Test2(n: Nat)\nensures n < Succ(n)\n{\n //\n}\n\n/*\nlemma L1()\nensures exists x: Nat :: x == Zero.Pred \n{\n\n //\n}\n*/\n/*\nlemma L2(m: Nat, n: Nat)\nensures lt(m, n) == lt(n, m)\n{\n //\n}\n*/\nlemma LtTrans(m: Nat, n: Nat, p: Nat)\nrequires lt(m, n)\nrequires lt(n, p)\nensures lt(m, p)\n{\n //assert n.Succ?;\n //assert p.Pred.Succ?;\n /*\n match m \n case Zero => {\n match n\n case Zero => assert true;\n case Succ(n') => LtTrans(Zero, n', p);\n }\n case Succ(m') => LtTrans(m', n, p);\n */\n}\n\ndatatype List = Nil | Cons(head: T, tail: List)\n\nlemma Disc2(l: List, a: T)\nensures Cons(a, l).head == a && Cons(a, l).tail == l\n{\n //\n}\n\nfunction size(l: List): nat\n{\n match l\n case Nil => 0\n case Cons(x, l') => size(l') + 1\n}\n\nfunction app(l1: List, l2: List) : List\n{\n match l1\n case Nil => l2\n case Cons(x, l1') => Cons(x, app(l1', l2))\n}\n\nlemma LenApp(l1: List, l2: List)\nensures size(app(l1, l2)) == size(l1) + size(l2)\n{\n //\n}\n\n/*\n (1,(2,3)) -> ((3,2),1)\n (x, l') -> (rev(l'), x)\n*/\n\nfunction rev (l: List) : List\n{\n match l\n case Nil => Nil\n case Cons(x, l') => app(rev(l'), Cons(x, Nil))\n}\n\nlemma AppNil(l: List)\nensures app(l, Nil) == l\n{\n //\n}\n\n/*\nlemma RevApp(l1: List, l2: List)\nensures rev(app(l1, l2)) == app(rev(l2), rev(l1))\n{\n match l1\n case Nil => AppNil(rev(l2));\n case Cons(x, l1') => {\n // rev(Cons(x, app(l1', l2))) == app(rev(app(l1', l2)), Cons(x, Nil)))\n assert rev(Cons(x, app(l1', l2))) == app(rev(app(l1', l2)), Cons(x, Nil));\n RevApp(l1', l2);\n }\n}\n*/\nlemma LR1 (l: List, x: T)\nensures rev(app(l, Cons(x, Nil))) == Cons(x, rev(l))\n{\n //\n}\n\nlemma RevRev(l: List)\nensures rev(rev(l)) == l\n{\n match l\n case Nil => assert true;\n case Cons(x, l') => {\n assert rev(rev(l)) == rev(app(rev(l'), Cons(x, Nil)));\n LR1(rev(l'), x);\n }\n \n}\n\n\n/*\nHW1: Define over naturals (as an algebraic data type) the predicates odd(x) and even(x) \nand prove that the addition of two odd numbers is an even number.\nDeadline: Tuesday 12.10, 14:00\n*/\n\n", "hints_removed": "datatype Nat = Zero | Succ(Pred: Nat)\n\n/*\n\nNat: Zero, Succ(Zero), Succ(Succ(Zero)), ...\n\n*/\n\nlemma Disc(n: Nat)\nensures n.Succ? || n.Zero?\n{\n //\n}\n\nlemma LPred(n: Nat)\nensures Succ(n).Pred == n\n{\n //\n}\n\n// Succ(m') > m'\n\nfunction add(m: Nat, n: Nat) : Nat\n{\n match m\n case Zero => n\n case Succ(m') => Succ(add(m', n))\n}\n\n// add(m, Zero) = m\n\nlemma AddZero(m: Nat)\nensures add(m, Zero) == m\n{\n //\n}\n\nlemma AddAssoc(m: Nat, n: Nat, p: Nat)\nensures add(m, add(n, p)) == add(add(m, n), p)\n{\n //\n}\n\nlemma AddComm(m: Nat, n: Nat)\nensures add(m, n) == add(n, m)\n{\n match m\n case Zero => AddZero(n);\n case Succ(m') => AddComm(m', n);\n}\n\npredicate lt(m: Nat, n: Nat)\n{\n (m.Zero? && n.Succ?) ||\n (m.Succ? && n.Succ? && lt(m.Pred, n.Pred))\n}\n\nlemma Test1(n:Nat)\nensures lt(n, Succ(Succ(n)))\n{\n //\n}\n\nlemma Test2(n: Nat)\nensures n < Succ(n)\n{\n //\n}\n\n/*\nlemma L1()\nensures exists x: Nat :: x == Zero.Pred \n{\n\n //\n}\n*/\n/*\nlemma L2(m: Nat, n: Nat)\nensures lt(m, n) == lt(n, m)\n{\n //\n}\n*/\nlemma LtTrans(m: Nat, n: Nat, p: Nat)\nrequires lt(m, n)\nrequires lt(n, p)\nensures lt(m, p)\n{\n //assert n.Succ?;\n //assert p.Pred.Succ?;\n /*\n match m \n case Zero => {\n match n\n case Zero => assert true;\n case Succ(n') => LtTrans(Zero, n', p);\n }\n case Succ(m') => LtTrans(m', n, p);\n */\n}\n\ndatatype List = Nil | Cons(head: T, tail: List)\n\nlemma Disc2(l: List, a: T)\nensures Cons(a, l).head == a && Cons(a, l).tail == l\n{\n //\n}\n\nfunction size(l: List): nat\n{\n match l\n case Nil => 0\n case Cons(x, l') => size(l') + 1\n}\n\nfunction app(l1: List, l2: List) : List\n{\n match l1\n case Nil => l2\n case Cons(x, l1') => Cons(x, app(l1', l2))\n}\n\nlemma LenApp(l1: List, l2: List)\nensures size(app(l1, l2)) == size(l1) + size(l2)\n{\n //\n}\n\n/*\n (1,(2,3)) -> ((3,2),1)\n (x, l') -> (rev(l'), x)\n*/\n\nfunction rev (l: List) : List\n{\n match l\n case Nil => Nil\n case Cons(x, l') => app(rev(l'), Cons(x, Nil))\n}\n\nlemma AppNil(l: List)\nensures app(l, Nil) == l\n{\n //\n}\n\n/*\nlemma RevApp(l1: List, l2: List)\nensures rev(app(l1, l2)) == app(rev(l2), rev(l1))\n{\n match l1\n case Nil => AppNil(rev(l2));\n case Cons(x, l1') => {\n // rev(Cons(x, app(l1', l2))) == app(rev(app(l1', l2)), Cons(x, Nil)))\n RevApp(l1', l2);\n }\n}\n*/\nlemma LR1 (l: List, x: T)\nensures rev(app(l, Cons(x, Nil))) == Cons(x, rev(l))\n{\n //\n}\n\nlemma RevRev(l: List)\nensures rev(rev(l)) == l\n{\n match l\n case Nil => assert true;\n case Cons(x, l') => {\n LR1(rev(l'), x);\n }\n \n}\n\n\n/*\nHW1: Define over naturals (as an algebraic data type) the predicates odd(x) and even(x) \nand prove that the addition of two odd numbers is an even number.\nDeadline: Tuesday 12.10, 14:00\n*/\n\n" }, { "test_ID": "684", "test_file": "formal-methods-in-software-engineering_tmp_tmpe7fjnek6_Labs2_hw1.dfy", "ground_truth": "/*\nHW1: Define over naturals (as an algebraic data type) the predicates odd(x) and even(x) \nand prove that the addition of two odd numbers is an even number.\nDeadline: Tuesday 12.10, 14:00\n*/\n\ndatatype Nat = Zero | Succ(Pred: Nat)\n\nfunction add(m: Nat, n: Nat) : Nat\ndecreases m\n{\n match m\n case Zero => n\n case Succ(m') => Succ(add(m', n))\n}\n\npredicate Odd(m: Nat)\ndecreases m\n{\n match m\n case Zero => false\n case Succ(m') => Even(m')\n}\n\n\npredicate Even(m: Nat)\ndecreases m\n{\n match m\n case Zero => true\n case Succ(m') => Odd(m')\n}\n\n\nlemma SumMNIsEven(m: Nat, n: Nat)\nrequires Odd(m)\nrequires Odd(n)\nensures Even(add(m,n))\n{\n match m\n case Succ(Zero) => assert Even(add(Succ(Zero),n));\n case Succ(Succ(m')) => SumMNIsEven(m',n);\n}\n", "hints_removed": "/*\nHW1: Define over naturals (as an algebraic data type) the predicates odd(x) and even(x) \nand prove that the addition of two odd numbers is an even number.\nDeadline: Tuesday 12.10, 14:00\n*/\n\ndatatype Nat = Zero | Succ(Pred: Nat)\n\nfunction add(m: Nat, n: Nat) : Nat\n{\n match m\n case Zero => n\n case Succ(m') => Succ(add(m', n))\n}\n\npredicate Odd(m: Nat)\n{\n match m\n case Zero => false\n case Succ(m') => Even(m')\n}\n\n\npredicate Even(m: Nat)\n{\n match m\n case Zero => true\n case Succ(m') => Odd(m')\n}\n\n\nlemma SumMNIsEven(m: Nat, n: Nat)\nrequires Odd(m)\nrequires Odd(n)\nensures Even(add(m,n))\n{\n match m\n case Succ(Zero) => assert Even(add(Succ(Zero),n));\n case Succ(Succ(m')) => SumMNIsEven(m',n);\n}\n" }, { "test_ID": "685", "test_file": "formal-methods-in-software-engineering_tmp_tmpe7fjnek6_Labs4_gr2.dfy", "ground_truth": "/*\nDafny include 2 limbaje:\n * un limbaj pentru specificare \n MSFOL (ce am discutat p\u00e2n\u0103 acum)\n adnot\u0103ri care s\u0103 ajute \u00een procesul de verificare\n * un limbaj pentru scris programe\n*/\n\n// Exemplu de program\n\nmethod SqrSum(n: int) returns (s: int)\n{\n\tvar i,k : int;\n\ts := 0;\n\tk := 1;\n\ti := 1;\n\twhile (i <= n) \n decreases n - i\n {\n\t\ts := s + k;\n\t\tk := k + 2 * i + 1;\n\t\ti := i+1;\n\t}\n}\n\nmethod DivMod(a: int, b: int) returns (q: int, r: int)\ndecreases *\n{\n\t\tq := 0;\n\t\tr := a;\n\t\twhile (r >= b)\n\t\tdecreases *\n\t\t{\n\t\t\tr := r - b;\n\t\t\tq := q + 1;\n\t\t}\n\t\n}\n\n/*\n triple Hoare (| P |) S (| Q |) \n*/\n\n// varianta assume-assert\nmethod HoareTripleAssmAssrt()\n{\n\tvar i: int := *;\n\tvar k: int := *;\n\t// (| k == i*i |) k := k + 2 * i +1; (| k = (i+1)*(i+1) |)\n\tassume k == i*i; // P = precondition\n\tk := k + 2 * i + 1; // S\n\tassert k == (i+1)*(i+1); // Q = postcondition\n}\n\n// varianta requires-ensures\n\nmethod HoareTripleReqEns(i: int, k: int) returns (k': int)\n\t// (| k == i*i |) k := k + 2 * i +1; (| k = (i+1)*(i+1) |)\n\trequires k == i*i\n\tensures k' == (i+1)*(i+1)\n{\n\tk' := k + 2 * i + 1;\n}\n\n/*\nregula pentru while\n*/\n\n// varianta cu assert\n/*\nmethod WhileRule()\n{\n\t// var n: int := *; // havoc\n // assume n >= 0;\n\tvar n: int :| n >= 0; \n\tvar y := n;\n\tvar x := 0;\n \tassert (x + y) == n;\n\twhile (y >= 0)\n\t\tdecreases y\n\t{\n\t\tassert (x + y) == n; // fails\n\t\tx := x+1;\n\t\ty := y-1;\n\t\tassert (x + y) == n;\n\t}\n\tassert (y < 0) && (x + y) == n;\n}\n*/\n\n// varianta cu invariant\nmethod Invariant1()\n{\n\t// var n: int := *; // havoc\n\tvar n: int :| n >= 0; \n\tvar y := n;\n\tvar x := 0;\n\twhile (y >= 0)\n\t\tdecreases y\n\t\tinvariant (x + y) == n;\n\t{\n\t\tx := x+1;\n\t\ty := y-1;\n\t}\n\tassert (y < 0) && (x + y) == n;\n}\n\n//specificarea sumei de patrate\nfunction SqrSumRec(n: int) : int\n\trequires n >= 0\n{\n\tif (n == 0) then 0 else n*n + SqrSumRec(n-1)\n}\n/*\nmethod SqrSum1(n: int) returns (s: int)\n\trequires n >= 0\n\tensures s == SqrSumRec(n) // s = 0^2 + 1^2 + 2^2 + ... + n^2 == n(n+1)(2n+1)/6\n{\n\t// ???\n}\n*/\n\n// verificarea programului pentru suma de patrate\n\nmethod SqrSum1(n: int) returns (s: int)\n\trequires n >= 0\n\tensures s == SqrSumRec(n)\n{\n\tvar i,k : int;\n\ts := 0;\n\tk := 1;\n\ti := 1;\n\twhile (i <= n)\n decreases n - i\n invariant k == i*i\n // s: 0*0, 0*0 + 1*1, 0*0 + 1*1 + 2*2, ...\n // i: 1, 2, 3,\n invariant s == SqrSumRec(i-1)\n invariant i <= n+1\n\t{\n // k = i*i\n\t\ts := s + k;\n // k = i*i\n\t\tk := k + 2 * i + 1;\n // k = (i+1)*(i+1)\n\t\ti := i+1;\n // k = i*i\n\t}\n //s == SqrSumRec(i-1) && i <= n+1 && i > n\n // implies\n //s == SqrSumRec(n)\n}\n\n// SqrSumRec(n) = 0^2 + 1^2 + 2^2 + ... + n^2 == n(n+1)(2n+1)/6\nleast lemma L1(n: int)\n\trequires n >= 0\n ensures SqrSumRec(n) == n*(n+1)*(2*n + 1)/6\n{\n //OK\n}\n\n/*\nfunction SqrSumBy6(n: int) : int\n{\n\tn * (n + 1) * (2 * n + 1) \n}\n\ninductive lemma L(n: int) // it takes a while\n\tdecreases n\n\trequires n >= 0\n\tensures SqrSumBy6(n) == 6 * SqrSumRec(n)\n{\n\tif (n == 0) {}\n\telse {\n\t\tassert n > 0;\n\t\tL(n-1);\n\t\tassert SqrSumBy6(n-1) == n*(n-1)*(2*n - 1);\n\t\tassert SqrSumBy6(n-1) == 6*SqrSumRec(n-1);\n\t\tassert 6*SqrSumRec(n-1) == n*(n-1)*(2*n - 1);\n\t \tcalc == {\n\t\t\tn*((n-1)*(2*n - 1));\n\t\t\tn*(2*n*(n-1) - n + 1);\n\t\t\tn*(2*n*n - 3*n + 1);\n\t\t\tn*(2*n*n - 3*n + 1);\n\t\t}\n\t\tcalc == {\n\t\t\t2*n*n + n;\n\t\t\t(2*n + 1)*n;\n\t\t}\n\t\tcalc == {\n\t\t\t(2*n + 1)*n + (2*n + 1);\n\t\t\t(2*n + 1)*(n+1);\n\t\t}\n\t\tcalc == {\n\t\t\tn*((n-1)*(2*n - 1)) + 6*n*n;\n\t\t\tn*(2*n*(n-1) - n + 1) + 6*n*n;\n\t\t\tn*(2*n*(n-1) - n + 1) + 6*n*n;\n\t\t\tn*(2*n*n - 3*n + 1) + 6*n*n;\n\t\t\tn*(2*n*n - 3*n + 1 + 6*n);\n\t\t\tn*(2*n*n + 6*n - 3*n + 1);\n\t\t\tn*(2*n*n + 3*n + 1);\n\t\t\tn*(2*n*n + n + (2*n + 1));\n\t\t\tn*((2*n + 1)*n + (2*n + 1));\n\t\t \tn*((2*n + 1)*(n+1));\n\t\t}\n\t}\n}\n\n*/\n\nmethod DivMod1(a: int, b: int) returns (q: int, r: int)\nrequires b > 0 && a >= 0\nensures a == b*q + r && 0 <= r < b\n//decreases *\n{\n\t\tq := 0;\n\t\tr := a;\n\t\twhile (r >= b)\n invariant r >= 0\n invariant a == b*q + r\n\t\tdecreases r // variant == expresie descrescatoare si marginita inferior\n\t\t{\n\t\t\tr := r - b;\n\t\t\tq := q + 1;\n\t\t}\n //a == b*q + r && r <= 0 && r< b\n\t\n}\n\nmethod Main()\n\tdecreases *\n{\n\tvar v := SqrSum(5);\n\tprint \"SqrSum(5): \", v, \"\\n\";\n\n\tvar q, r := DivMod(5, 3);\n\tprint \"DivMod(5, 3): \", q, \", \", r, \"\\n\";\n\n}\n\n\n", "hints_removed": "/*\nDafny include 2 limbaje:\n * un limbaj pentru specificare \n MSFOL (ce am discutat p\u00e2n\u0103 acum)\n adnot\u0103ri care s\u0103 ajute \u00een procesul de verificare\n * un limbaj pentru scris programe\n*/\n\n// Exemplu de program\n\nmethod SqrSum(n: int) returns (s: int)\n{\n\tvar i,k : int;\n\ts := 0;\n\tk := 1;\n\ti := 1;\n\twhile (i <= n) \n {\n\t\ts := s + k;\n\t\tk := k + 2 * i + 1;\n\t\ti := i+1;\n\t}\n}\n\nmethod DivMod(a: int, b: int) returns (q: int, r: int)\n{\n\t\tq := 0;\n\t\tr := a;\n\t\twhile (r >= b)\n\t\t{\n\t\t\tr := r - b;\n\t\t\tq := q + 1;\n\t\t}\n\t\n}\n\n/*\n triple Hoare (| P |) S (| Q |) \n*/\n\n// varianta assume-assert\nmethod HoareTripleAssmAssrt()\n{\n\tvar i: int := *;\n\tvar k: int := *;\n\t// (| k == i*i |) k := k + 2 * i +1; (| k = (i+1)*(i+1) |)\n\tassume k == i*i; // P = precondition\n\tk := k + 2 * i + 1; // S\n}\n\n// varianta requires-ensures\n\nmethod HoareTripleReqEns(i: int, k: int) returns (k': int)\n\t// (| k == i*i |) k := k + 2 * i +1; (| k = (i+1)*(i+1) |)\n\trequires k == i*i\n\tensures k' == (i+1)*(i+1)\n{\n\tk' := k + 2 * i + 1;\n}\n\n/*\nregula pentru while\n*/\n\n// varianta cu assert\n/*\nmethod WhileRule()\n{\n\t// var n: int := *; // havoc\n // assume n >= 0;\n\tvar n: int :| n >= 0; \n\tvar y := n;\n\tvar x := 0;\n\twhile (y >= 0)\n\t{\n\t\tx := x+1;\n\t\ty := y-1;\n\t}\n}\n*/\n\n// varianta cu invariant\nmethod Invariant1()\n{\n\t// var n: int := *; // havoc\n\tvar n: int :| n >= 0; \n\tvar y := n;\n\tvar x := 0;\n\twhile (y >= 0)\n\t{\n\t\tx := x+1;\n\t\ty := y-1;\n\t}\n}\n\n//specificarea sumei de patrate\nfunction SqrSumRec(n: int) : int\n\trequires n >= 0\n{\n\tif (n == 0) then 0 else n*n + SqrSumRec(n-1)\n}\n/*\nmethod SqrSum1(n: int) returns (s: int)\n\trequires n >= 0\n\tensures s == SqrSumRec(n) // s = 0^2 + 1^2 + 2^2 + ... + n^2 == n(n+1)(2n+1)/6\n{\n\t// ???\n}\n*/\n\n// verificarea programului pentru suma de patrate\n\nmethod SqrSum1(n: int) returns (s: int)\n\trequires n >= 0\n\tensures s == SqrSumRec(n)\n{\n\tvar i,k : int;\n\ts := 0;\n\tk := 1;\n\ti := 1;\n\twhile (i <= n)\n // s: 0*0, 0*0 + 1*1, 0*0 + 1*1 + 2*2, ...\n // i: 1, 2, 3,\n\t{\n // k = i*i\n\t\ts := s + k;\n // k = i*i\n\t\tk := k + 2 * i + 1;\n // k = (i+1)*(i+1)\n\t\ti := i+1;\n // k = i*i\n\t}\n //s == SqrSumRec(i-1) && i <= n+1 && i > n\n // implies\n //s == SqrSumRec(n)\n}\n\n// SqrSumRec(n) = 0^2 + 1^2 + 2^2 + ... + n^2 == n(n+1)(2n+1)/6\nleast lemma L1(n: int)\n\trequires n >= 0\n ensures SqrSumRec(n) == n*(n+1)*(2*n + 1)/6\n{\n //OK\n}\n\n/*\nfunction SqrSumBy6(n: int) : int\n{\n\tn * (n + 1) * (2 * n + 1) \n}\n\ninductive lemma L(n: int) // it takes a while\n\trequires n >= 0\n\tensures SqrSumBy6(n) == 6 * SqrSumRec(n)\n{\n\tif (n == 0) {}\n\telse {\n\t\tL(n-1);\n\t \tcalc == {\n\t\t\tn*((n-1)*(2*n - 1));\n\t\t\tn*(2*n*(n-1) - n + 1);\n\t\t\tn*(2*n*n - 3*n + 1);\n\t\t\tn*(2*n*n - 3*n + 1);\n\t\t}\n\t\tcalc == {\n\t\t\t2*n*n + n;\n\t\t\t(2*n + 1)*n;\n\t\t}\n\t\tcalc == {\n\t\t\t(2*n + 1)*n + (2*n + 1);\n\t\t\t(2*n + 1)*(n+1);\n\t\t}\n\t\tcalc == {\n\t\t\tn*((n-1)*(2*n - 1)) + 6*n*n;\n\t\t\tn*(2*n*(n-1) - n + 1) + 6*n*n;\n\t\t\tn*(2*n*(n-1) - n + 1) + 6*n*n;\n\t\t\tn*(2*n*n - 3*n + 1) + 6*n*n;\n\t\t\tn*(2*n*n - 3*n + 1 + 6*n);\n\t\t\tn*(2*n*n + 6*n - 3*n + 1);\n\t\t\tn*(2*n*n + 3*n + 1);\n\t\t\tn*(2*n*n + n + (2*n + 1));\n\t\t\tn*((2*n + 1)*n + (2*n + 1));\n\t\t \tn*((2*n + 1)*(n+1));\n\t\t}\n\t}\n}\n\n*/\n\nmethod DivMod1(a: int, b: int) returns (q: int, r: int)\nrequires b > 0 && a >= 0\nensures a == b*q + r && 0 <= r < b\n//decreases *\n{\n\t\tq := 0;\n\t\tr := a;\n\t\twhile (r >= b)\n\t\t{\n\t\t\tr := r - b;\n\t\t\tq := q + 1;\n\t\t}\n //a == b*q + r && r <= 0 && r< b\n\t\n}\n\nmethod Main()\n{\n\tvar v := SqrSum(5);\n\tprint \"SqrSum(5): \", v, \"\\n\";\n\n\tvar q, r := DivMod(5, 3);\n\tprint \"DivMod(5, 3): \", q, \", \", r, \"\\n\";\n\n}\n\n\n" }, { "test_ID": "686", "test_file": "formal-verification_tmp_tmpoepcssay_strings3.dfy", "ground_truth": "predicate isPrefixPred(pre:string, str:string)\n{\n\t(|pre| <= |str|) && \n\tpre == str[..|pre|]\n}\n\npredicate isNotPrefixPred(pre:string, str:string)\n{\n\t(|pre| > |str|) || \n\tpre != str[..|pre|]\n}\n\nlemma PrefixNegationLemma(pre:string, str:string)\n\tensures isPrefixPred(pre,str) <==> !isNotPrefixPred(pre,str)\n\tensures !isPrefixPred(pre,str) <==> isNotPrefixPred(pre,str)\n{}\n\nmethod isPrefix(pre: string, str: string) returns (res:bool)\n\tensures !res <==> isNotPrefixPred(pre,str)\n\tensures res <==> isPrefixPred(pre,str)\n{\n\treturn |pre| <= |str| && forall i :: 0 <= i < |pre| ==> pre[i] == str[i];\n}\npredicate isSubstringPred(sub:string, str:string)\n{\n\t(exists i :: 0 <= i <= |str| && isPrefixPred(sub, str[i..]))\n}\n\npredicate isNotSubstringPred(sub:string, str:string)\n{\n\t(forall i :: 0 <= i <= |str| ==> isNotPrefixPred(sub,str[i..]))\n}\n\nlemma SubstringNegationLemma(sub:string, str:string)\n\tensures isSubstringPred(sub,str) <==> !isNotSubstringPred(sub,str)\n\tensures !isSubstringPred(sub,str) <==> isNotSubstringPred(sub,str)\n{}\n\nmethod isSubstring(sub: string, str: string) returns (res:bool)\n\tensures res <==> isSubstringPred(sub, str)\n\tensures res ==> isSubstringPred(sub, str)\n\t// ensures !res ==> !isSubstringPred(sub, str)\n\tensures isSubstringPred(sub, str) ==> res\n\tensures isSubstringPred(sub, str) ==> res\n\tensures !res <==> isNotSubstringPred(sub, str) // This postcondition follows from the above lemma.\n{\n\tif(|str| < |sub|)\n\t{\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\tvar i: nat := 0;\n\t \tres := false;\n\t\twhile (i <= |str|-|sub| && res == false)\n\t\tdecreases |str| - |sub| - i + (if !res then 1 else 0)\n\t\tinvariant 0 <= i <= |str|-|sub| + 1\n\t\tinvariant res ==> isSubstringPred(sub,str)\n\t\tinvariant forall j :: 0 <= j < i ==> isNotPrefixPred(sub, str[j..])\n\t\t{\n\t\t\tres := isPrefix(sub,str[i..]);\n\t\t\tif(!res)\n\t\t\t{\n\t\t\t\ti := i + 1;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\npredicate haveCommonKSubstringPred(k:nat, str1:string, str2:string)\n{\n\texists i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k && isSubstringPred(str1[i1..j1],str2)\n}\n\npredicate haveNotCommonKSubstringPred(k:nat, str1:string, str2:string)\n{\n\tforall i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k ==> isNotSubstringPred(str1[i1..j1],str2)\n}\n\nlemma commonKSubstringLemma(k:nat, str1:string, str2:string)\n\tensures haveCommonKSubstringPred(k,str1,str2) <==> !haveNotCommonKSubstringPred(k,str1,str2)\n\tensures !haveCommonKSubstringPred(k,str1,str2) <==> haveNotCommonKSubstringPred(k,str1,str2)\n{}\n\nmethod haveCommonKSubstring(k: nat, str1: string, str2: string) returns (found: bool)\n\tensures found <==> haveCommonKSubstringPred(k,str1,str2)\n\tensures !found <==> haveNotCommonKSubstringPred(k,str1,str2) // This postcondition follows from the above lemma.\n{\n\tif (k <= |str1| && k <= |str2|)\n\t{\n\t\tvar slice : string;\n\t\tfound := false;\n\t\tvar i: nat := 0;\n\n\t\twhile (i <= |str1| - k && found == false)\n\t\tdecreases |str1| - k - i + (if !found then 1 else 0)\n\t\tinvariant found ==> haveCommonKSubstringPred(k,str1,str2)\n\t\tinvariant forall x, y :: 0 <= x < i && found == false && y == x + k && y <= |str1| ==> isNotSubstringPred(str1[x..y], str2)\t\t\n\t\t{\n\t\t\tslice := str1[i..i+k];\n\t\t\tfound := isSubstring(slice, str2);\n\t\t\t\ti := i + 1;\n\t\t}\n\t} else {\n\t\treturn false;\n\t}\n \n}\n\nmethod maxCommonSubstringLength(str1: string, str2: string) returns (len:nat)\n\trequires (|str1| <= |str2|)\n\tensures (forall k :: len < k <= |str1| ==> !haveCommonKSubstringPred(k,str1,str2))\n\tensures haveCommonKSubstringPred(len,str1,str2)\n{\n\tassert isPrefixPred(str1[0..0],str2[0..]);\n\n\tlen := |str1|;\n\tvar hasCommon : bool := true;\n\twhile(len > 0)\n\t\tdecreases len\n\t\tinvariant forall i :: len < i <= |str1| ==> !haveCommonKSubstringPred(i,str1,str2)\n\t{\n\t\thasCommon := haveCommonKSubstring(len, str1, str2);\n\t\tif(hasCommon){\n\t\t\treturn len;\n\t\t}\n\t\tlen := len - 1;\n\t}\n\treturn len;\n}\n\n\n", "hints_removed": "predicate isPrefixPred(pre:string, str:string)\n{\n\t(|pre| <= |str|) && \n\tpre == str[..|pre|]\n}\n\npredicate isNotPrefixPred(pre:string, str:string)\n{\n\t(|pre| > |str|) || \n\tpre != str[..|pre|]\n}\n\nlemma PrefixNegationLemma(pre:string, str:string)\n\tensures isPrefixPred(pre,str) <==> !isNotPrefixPred(pre,str)\n\tensures !isPrefixPred(pre,str) <==> isNotPrefixPred(pre,str)\n{}\n\nmethod isPrefix(pre: string, str: string) returns (res:bool)\n\tensures !res <==> isNotPrefixPred(pre,str)\n\tensures res <==> isPrefixPred(pre,str)\n{\n\treturn |pre| <= |str| && forall i :: 0 <= i < |pre| ==> pre[i] == str[i];\n}\npredicate isSubstringPred(sub:string, str:string)\n{\n\t(exists i :: 0 <= i <= |str| && isPrefixPred(sub, str[i..]))\n}\n\npredicate isNotSubstringPred(sub:string, str:string)\n{\n\t(forall i :: 0 <= i <= |str| ==> isNotPrefixPred(sub,str[i..]))\n}\n\nlemma SubstringNegationLemma(sub:string, str:string)\n\tensures isSubstringPred(sub,str) <==> !isNotSubstringPred(sub,str)\n\tensures !isSubstringPred(sub,str) <==> isNotSubstringPred(sub,str)\n{}\n\nmethod isSubstring(sub: string, str: string) returns (res:bool)\n\tensures res <==> isSubstringPred(sub, str)\n\tensures res ==> isSubstringPred(sub, str)\n\t// ensures !res ==> !isSubstringPred(sub, str)\n\tensures isSubstringPred(sub, str) ==> res\n\tensures isSubstringPred(sub, str) ==> res\n\tensures !res <==> isNotSubstringPred(sub, str) // This postcondition follows from the above lemma.\n{\n\tif(|str| < |sub|)\n\t{\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\tvar i: nat := 0;\n\t \tres := false;\n\t\twhile (i <= |str|-|sub| && res == false)\n\t\t{\n\t\t\tres := isPrefix(sub,str[i..]);\n\t\t\tif(!res)\n\t\t\t{\n\t\t\t\ti := i + 1;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\npredicate haveCommonKSubstringPred(k:nat, str1:string, str2:string)\n{\n\texists i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k && isSubstringPred(str1[i1..j1],str2)\n}\n\npredicate haveNotCommonKSubstringPred(k:nat, str1:string, str2:string)\n{\n\tforall i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k ==> isNotSubstringPred(str1[i1..j1],str2)\n}\n\nlemma commonKSubstringLemma(k:nat, str1:string, str2:string)\n\tensures haveCommonKSubstringPred(k,str1,str2) <==> !haveNotCommonKSubstringPred(k,str1,str2)\n\tensures !haveCommonKSubstringPred(k,str1,str2) <==> haveNotCommonKSubstringPred(k,str1,str2)\n{}\n\nmethod haveCommonKSubstring(k: nat, str1: string, str2: string) returns (found: bool)\n\tensures found <==> haveCommonKSubstringPred(k,str1,str2)\n\tensures !found <==> haveNotCommonKSubstringPred(k,str1,str2) // This postcondition follows from the above lemma.\n{\n\tif (k <= |str1| && k <= |str2|)\n\t{\n\t\tvar slice : string;\n\t\tfound := false;\n\t\tvar i: nat := 0;\n\n\t\twhile (i <= |str1| - k && found == false)\n\t\t{\n\t\t\tslice := str1[i..i+k];\n\t\t\tfound := isSubstring(slice, str2);\n\t\t\t\ti := i + 1;\n\t\t}\n\t} else {\n\t\treturn false;\n\t}\n \n}\n\nmethod maxCommonSubstringLength(str1: string, str2: string) returns (len:nat)\n\trequires (|str1| <= |str2|)\n\tensures (forall k :: len < k <= |str1| ==> !haveCommonKSubstringPred(k,str1,str2))\n\tensures haveCommonKSubstringPred(len,str1,str2)\n{\n\n\tlen := |str1|;\n\tvar hasCommon : bool := true;\n\twhile(len > 0)\n\t{\n\t\thasCommon := haveCommonKSubstring(len, str1, str2);\n\t\tif(hasCommon){\n\t\t\treturn len;\n\t\t}\n\t\tlen := len - 1;\n\t}\n\treturn len;\n}\n\n\n" }, { "test_ID": "687", "test_file": "formal_verication_dafny_tmp_tmpwgl2qz28_Challenges_ex1.dfy", "ground_truth": "// ex3errors.dfy in Assignment 1\n// verify that an array of characters is a Palindrome\n/*\nA Palindrome is a word that is the same when written forwards and when written backwards. \nFor example, the word \u201drefer\u201d is a Palindrome.\nThe method PalVerify is supposed to verify whether a word is a Palindrome, \nwhere the word is represented as an array of characters. \nThe method was written by a novice software engineer, and contains many errors.\n\n i) Without changing the signature or the code in the while loop, \n fix the method so that it veriifes the code. Do not add any Dafny predicates or functions: \n keep the changes to a minimum.\n\n ii) Write a tester method (you may call it anything you like) that verifies that the \n testcases refer, z and the empty string are Palindromes, and xy and 123421 are not. \n The tester should not generate any output.\n*/\n\nmethod PalVerify(a: array) returns (yn: bool)\nensures yn == true ==> forall i :: 0 <= i < a.Length/2 ==> a[i] == a[a.Length - i -1]\nensures yn == false ==> exists i :: 0 <= i < a.Length/2 && a[i] != a[a.Length - i -1]\nensures forall j :: 0<=j a[j] == old(a[j]) \n{\n var i:int := 0;\n while i < a.Length/2\n invariant 0 <= i <= a.Length/2 && forall j:: 0<=j a[j] == a[a.Length-j-1]\n decreases a.Length/2 - i\n { \n if a[i] != a[a.Length-i-1] \n { \n return false; \n } \n i := i+1; \n } \n return true; \n} \n\nmethod TEST()\n{\n var a:array := new char[]['r','e','f','e','r'];\n var r:bool := PalVerify(a);\n assert r;\n\n var b:array := new char[]['z'];\n r := PalVerify(b);\n assert r;\n\n var c:array := new char[][];\n r := PalVerify(c);\n assert r;\n\n var d:array := new char[]['x', 'y'];\n assert d[0]=='x' && d[1]=='y';\n r := PalVerify(d);\n assert !r;\n\n var e:array := new char[]['1', '2', '3', '4', '2', '1'];\n assert e[0]=='1' && e[1]=='2' && e[2]=='3' && e[3]=='4' && e[4]=='2' && e[5]=='1';\n r := PalVerify(e);\n assert !r;\n}\n", "hints_removed": "// ex3errors.dfy in Assignment 1\n// verify that an array of characters is a Palindrome\n/*\nA Palindrome is a word that is the same when written forwards and when written backwards. \nFor example, the word \u201drefer\u201d is a Palindrome.\nThe method PalVerify is supposed to verify whether a word is a Palindrome, \nwhere the word is represented as an array of characters. \nThe method was written by a novice software engineer, and contains many errors.\n\n i) Without changing the signature or the code in the while loop, \n fix the method so that it veriifes the code. Do not add any Dafny predicates or functions: \n keep the changes to a minimum.\n\n ii) Write a tester method (you may call it anything you like) that verifies that the \n testcases refer, z and the empty string are Palindromes, and xy and 123421 are not. \n The tester should not generate any output.\n*/\n\nmethod PalVerify(a: array) returns (yn: bool)\nensures yn == true ==> forall i :: 0 <= i < a.Length/2 ==> a[i] == a[a.Length - i -1]\nensures yn == false ==> exists i :: 0 <= i < a.Length/2 && a[i] != a[a.Length - i -1]\nensures forall j :: 0<=j a[j] == old(a[j]) \n{\n var i:int := 0;\n while i < a.Length/2\n { \n if a[i] != a[a.Length-i-1] \n { \n return false; \n } \n i := i+1; \n } \n return true; \n} \n\nmethod TEST()\n{\n var a:array := new char[]['r','e','f','e','r'];\n var r:bool := PalVerify(a);\n\n var b:array := new char[]['z'];\n r := PalVerify(b);\n\n var c:array := new char[][];\n r := PalVerify(c);\n\n var d:array := new char[]['x', 'y'];\n r := PalVerify(d);\n\n var e:array := new char[]['1', '2', '3', '4', '2', '1'];\n r := PalVerify(e);\n}\n" }, { "test_ID": "688", "test_file": "formal_verication_dafny_tmp_tmpwgl2qz28_Challenges_ex2.dfy", "ground_truth": "/*\n i) Write a verified method with signature\n method Forbid42(x:int, y:int) returns (z: int)\n that returns x/(42 \u2212 y). The method is not defined for y = 42.\n\n ii) Write a verified method with signature\n method Allow42(x:int, y:int) returns (z: int, err:bool)\n If y is not equal to 42 then z = x/(42 \u2212 y), otherwise z = 0. \n The variable err is true if y == 42, otherwise it is false.\n\n iii) Test your two methods by writing a tester with the following testcases. \n You may call your tester anything you like.\n\n*/\n\nmethod Forbid42(x:int, y:int) returns (z:int)\nrequires y != 42;\nensures z == x/(42-y);\n{\n z:= x/(42-y);\n return z;\n} \n\nmethod Allow42(x:int, y:int) returns (z: int, err:bool) \nensures y != 42 ==> z == x/(42-y) && err == false;\nensures y == 42 ==> z == 0 && err == true;\n{\n if (y != 42){\n z:= x/(42-y);\n return z, false;\n } \n return 0, true;\n}\n\nmethod TEST1()\n{\n var c:int := Forbid42(0, 1);\n assert c == 0;\n\n c := Forbid42(10, 32);\n assert c == 1;\n\n c := Forbid42(-100, 38);\n assert c == -25;\n\n var d:int,z:bool := Allow42(0,42);\n assert d == 0 && z == true;\n\n d,z := Allow42(-10,42);\n assert d == 0 && z == true;\n\n d,z := Allow42(0,1);\n assert d == 0 && z == false;\n\n d,z := Allow42(10,32);\n assert d == 1 && z == false;\n\n d,z := Allow42(-100,38);\n assert d == -25 && z == false;\n}\n", "hints_removed": "/*\n i) Write a verified method with signature\n method Forbid42(x:int, y:int) returns (z: int)\n that returns x/(42 \u2212 y). The method is not defined for y = 42.\n\n ii) Write a verified method with signature\n method Allow42(x:int, y:int) returns (z: int, err:bool)\n If y is not equal to 42 then z = x/(42 \u2212 y), otherwise z = 0. \n The variable err is true if y == 42, otherwise it is false.\n\n iii) Test your two methods by writing a tester with the following testcases. \n You may call your tester anything you like.\n\n*/\n\nmethod Forbid42(x:int, y:int) returns (z:int)\nrequires y != 42;\nensures z == x/(42-y);\n{\n z:= x/(42-y);\n return z;\n} \n\nmethod Allow42(x:int, y:int) returns (z: int, err:bool) \nensures y != 42 ==> z == x/(42-y) && err == false;\nensures y == 42 ==> z == 0 && err == true;\n{\n if (y != 42){\n z:= x/(42-y);\n return z, false;\n } \n return 0, true;\n}\n\nmethod TEST1()\n{\n var c:int := Forbid42(0, 1);\n\n c := Forbid42(10, 32);\n\n c := Forbid42(-100, 38);\n\n var d:int,z:bool := Allow42(0,42);\n\n d,z := Allow42(-10,42);\n\n d,z := Allow42(0,1);\n\n d,z := Allow42(10,32);\n\n d,z := Allow42(-100,38);\n}\n" }, { "test_ID": "689", "test_file": "formal_verication_dafny_tmp_tmpwgl2qz28_Challenges_ex6.dfy", "ground_truth": "// see pdf 'ex6 & 7 documentation' for excercise question\n\nfunction bullspec(s:seq, u:seq): nat\nrequires 0 <= |u| == |s| && nomultiples(u)\n{reccbull(s, u, 0)}\n\nfunction cowspec(s:seq, u:seq): nat\nrequires 0 <= |u| == |s| && nomultiples(u)\n{recccow(s, u, 0)}\n\nfunction reccbull(s: seq, u:seq, i:int): nat\nrequires 0 <= i <= |s| == |u|\ndecreases |s| - i\n{\n if i ==|s| then 0\n else if s[i] == u[i] then reccbull(s, u, i + 1) + 1\n else reccbull(s, u, i + 1)\n}\n\nfunction recccow(s: seq, u:seq, i:int): nat\nrequires 0 <= i <= |s| == |u|\ndecreases |s| - i\n{\n if i == |s| then 0\n else if s[i] != u[i] && u[i] in s then recccow(s, u, i + 1) + 1\n else recccow(s, u, i + 1)\n}\n\npredicate nomultiples(u:seq) \n{forall j, k :: 0<=j u[j] != u[k]}\n\nmethod BullsCows (s:seq, u:seq) returns (b:nat, c:nat) \nrequires 0 < |u| == |s| <= 10\nrequires nomultiples(u) && nomultiples(s);\nensures b >= 0 && c >= 0\nensures b == bullspec(s, u)\nensures c == cowspec(s, u)\n{\n b, c := 0, 0;\n var i:int := |s|;\n\n while i > 0\n invariant 0 <= i <= |s| == |u|\n invariant b >= 0 && c >= 0\n invariant b == reccbull(s,u, i)\n invariant c == recccow(s, u, i)\n decreases i\n {\n i := i - 1;\n if s[i] != u[i] && u[i] in s {c:= c + 1;}\n else if s[i] == u[i] {b := b + 1;}\n }\n\n return b, c;\n}\n\nmethod TEST(){\n var sys:seq := [1,2,9,10];\n var usr:seq := [1,2,3,7];\n\n assert bullspec(sys, usr) == 2;\n assert cowspec(sys, usr) == 0;\n\n var b:nat, c:nat := BullsCows(sys, usr);\n assert b == 2 && c == 0;\n\n var sys1:seq := [1, 2, 3, 4];\n var usr2:seq := [4, 3, 2, 1];\n\n assert bullspec(sys1, usr2) == 0;\n assert cowspec(sys1, usr2) == 4;\n\n b, c := BullsCows(sys1, usr2);\n assert b == 0 && c == 4;\n\n var sys3:seq := [1, 2, 3, 4, 5, 6, 7];\n var usr3:seq := [1, 2, 3, 4, 5, 6, 7];\n\n assert bullspec(sys3, usr3) == 7;\n assert cowspec(sys3, usr3) == 0;\n\n b, c := BullsCows(sys3, usr3);\n assert b == 7 && c == 0;\n\n var sys4:seq := [1, 2, 3, 4, 5, 6, 7];\n var usr4:seq := [1, 2, 3, 7, 8, 6, 5];\n\n assert bullspec(sys4, usr4) == 4;\n assert cowspec(sys4, usr4) == 2;\n\n b, c := BullsCows(sys4, usr4);\n}\n", "hints_removed": "// see pdf 'ex6 & 7 documentation' for excercise question\n\nfunction bullspec(s:seq, u:seq): nat\nrequires 0 <= |u| == |s| && nomultiples(u)\n{reccbull(s, u, 0)}\n\nfunction cowspec(s:seq, u:seq): nat\nrequires 0 <= |u| == |s| && nomultiples(u)\n{recccow(s, u, 0)}\n\nfunction reccbull(s: seq, u:seq, i:int): nat\nrequires 0 <= i <= |s| == |u|\n{\n if i ==|s| then 0\n else if s[i] == u[i] then reccbull(s, u, i + 1) + 1\n else reccbull(s, u, i + 1)\n}\n\nfunction recccow(s: seq, u:seq, i:int): nat\nrequires 0 <= i <= |s| == |u|\n{\n if i == |s| then 0\n else if s[i] != u[i] && u[i] in s then recccow(s, u, i + 1) + 1\n else recccow(s, u, i + 1)\n}\n\npredicate nomultiples(u:seq) \n{forall j, k :: 0<=j u[j] != u[k]}\n\nmethod BullsCows (s:seq, u:seq) returns (b:nat, c:nat) \nrequires 0 < |u| == |s| <= 10\nrequires nomultiples(u) && nomultiples(s);\nensures b >= 0 && c >= 0\nensures b == bullspec(s, u)\nensures c == cowspec(s, u)\n{\n b, c := 0, 0;\n var i:int := |s|;\n\n while i > 0\n {\n i := i - 1;\n if s[i] != u[i] && u[i] in s {c:= c + 1;}\n else if s[i] == u[i] {b := b + 1;}\n }\n\n return b, c;\n}\n\nmethod TEST(){\n var sys:seq := [1,2,9,10];\n var usr:seq := [1,2,3,7];\n\n\n var b:nat, c:nat := BullsCows(sys, usr);\n\n var sys1:seq := [1, 2, 3, 4];\n var usr2:seq := [4, 3, 2, 1];\n\n\n b, c := BullsCows(sys1, usr2);\n\n var sys3:seq := [1, 2, 3, 4, 5, 6, 7];\n var usr3:seq := [1, 2, 3, 4, 5, 6, 7];\n\n\n b, c := BullsCows(sys3, usr3);\n\n var sys4:seq := [1, 2, 3, 4, 5, 6, 7];\n var usr4:seq := [1, 2, 3, 7, 8, 6, 5];\n\n\n b, c := BullsCows(sys4, usr4);\n}\n" }, { "test_ID": "690", "test_file": "formal_verication_dafny_tmp_tmpwgl2qz28_Challenges_ex7.dfy", "ground_truth": "// see pdf 'ex6 & 7 documentation' for excercise question\n\ndatatype Bases = A | C | G | T\n\n//swaps two sequence indexes\nmethod Exchanger(s: seq, x:nat, y:nat) returns (t: seq)\nrequires 0 < |s| && x < |s| && y < |s|\nensures |t| == |s|\nensures forall b:nat :: 0 <= b < |s| && b != x && b != y ==> t[b] == s[b]\nensures t[x] == s[y] && s[x] == t[y]\nensures multiset(s) == multiset(t)\n{\n t := s;\n t := t[ x := s[y]];\n t := t[ y := s[x] ];\n return t;\n}\n\n//idea from Rustan Leino video \"Basics of specification and verification: Lecture 3, the Dutch National Flag algorithm\"\n//modified for 4 elements\npredicate below(first: Bases, second: Bases)\n{\n first == second ||\n first == A || \n (first == C && (second == G || second == T)) || \n (first == G && second == T) ||\n second == T\n}\n\n//checks if a sequence is in base order\npredicate bordered(s:seq)\n{\n forall j, k :: 0 <= j < k < |s| ==> below(s[j], s[k])\n}\n\nmethod Sorter(bases: seq) returns (sobases:seq)\nrequires 0 < |bases|\nensures |sobases| == |bases|\nensures bordered(sobases)\nensures multiset(bases) == multiset(sobases);\n{\n\n sobases := bases;\n var c, next:nat := 0, 0;\n var g, t:nat := |bases|, |bases|;\n\n while next != g\n invariant 0 <= c <= next <= g <= t <= |bases|\n invariant |sobases| == |bases|\n invariant multiset(bases) == multiset(sobases);\n invariant forall i:nat :: 0 <= i < c ==> sobases[i] == A\n invariant forall i:nat :: c <= i < next ==> sobases[i] == C\n invariant forall i:nat :: g <= i < t ==> sobases[i] == G\n invariant forall i:nat :: t <= i < |bases| ==> sobases[i] == T\n {\n match(sobases[next]) {\n case C => next := next + 1;\n case A => sobases := Exchanger(sobases, next, c);\n c, next:= c + 1, next + 1;\n case G => g := g - 1;\n sobases := Exchanger(sobases, next, g);\n case T => g , t:= g - 1, t - 1;\n sobases := Exchanger(sobases, next, t);\n if (g != t) {sobases := Exchanger(sobases, next, g);}\n }\n }\n\n return sobases;\n}\n\nmethod Testerexchange() {\n var a:seq := [A, C, A, T]; \n var b:seq := Exchanger(a, 2, 3);\n assert b == [A, C, T, A];\n\n var c:seq := [A, C, A, T, A, T, C]; \n var d:seq := Exchanger(c, 5, 1); \n assert d == [A, T, A, T, A, C, C]; \n\n var e:seq := [A, C, A, T, A, T, C]; \n var f:seq := Exchanger(e, 1, 1); \n assert f == [A, C, A, T, A, T, C]; \n\n var g:seq := [A, C]; \n var h:seq := Exchanger(g, 0, 1); \n assert h == [C, A]; \n}\n\nmethod Testsort() {\n\n var a:seq := [G,A,T];\n assert a == [G,A,T];\n var b:seq := Sorter(a);\n assert bordered(b);\n assert multiset(b) == multiset(a);\n\n var c:seq := [G, A, T, T, A, C, G, C, T, A, C, G, T, T, G];\n assert c == [G, A, T, T, A, C, G, C, T, A, C, G, T, T, G];\n var d:seq := Sorter(c);\n assert bordered(d);\n assert multiset(c) == multiset(d);\n\n var e:seq := [A];\n assert e == [A];\n var f:seq := Sorter(e);\n assert bordered(b);\n assert multiset(e) == multiset(f);\n\n var g:seq := [A, C, G, T];\n assert g == [A, C, G, T];\n var h:seq := Sorter(g);\n assert bordered(b);\n assert multiset(g) == multiset(h);\n\n var i:seq := [A, T, C, T, T];\n assert i[0]==A && i[1]==T && i[2]==C && i[3]==T && i[4]==T;\n assert !bordered(i);\n}\n\n", "hints_removed": "// see pdf 'ex6 & 7 documentation' for excercise question\n\ndatatype Bases = A | C | G | T\n\n//swaps two sequence indexes\nmethod Exchanger(s: seq, x:nat, y:nat) returns (t: seq)\nrequires 0 < |s| && x < |s| && y < |s|\nensures |t| == |s|\nensures forall b:nat :: 0 <= b < |s| && b != x && b != y ==> t[b] == s[b]\nensures t[x] == s[y] && s[x] == t[y]\nensures multiset(s) == multiset(t)\n{\n t := s;\n t := t[ x := s[y]];\n t := t[ y := s[x] ];\n return t;\n}\n\n//idea from Rustan Leino video \"Basics of specification and verification: Lecture 3, the Dutch National Flag algorithm\"\n//modified for 4 elements\npredicate below(first: Bases, second: Bases)\n{\n first == second ||\n first == A || \n (first == C && (second == G || second == T)) || \n (first == G && second == T) ||\n second == T\n}\n\n//checks if a sequence is in base order\npredicate bordered(s:seq)\n{\n forall j, k :: 0 <= j < k < |s| ==> below(s[j], s[k])\n}\n\nmethod Sorter(bases: seq) returns (sobases:seq)\nrequires 0 < |bases|\nensures |sobases| == |bases|\nensures bordered(sobases)\nensures multiset(bases) == multiset(sobases);\n{\n\n sobases := bases;\n var c, next:nat := 0, 0;\n var g, t:nat := |bases|, |bases|;\n\n while next != g\n {\n match(sobases[next]) {\n case C => next := next + 1;\n case A => sobases := Exchanger(sobases, next, c);\n c, next:= c + 1, next + 1;\n case G => g := g - 1;\n sobases := Exchanger(sobases, next, g);\n case T => g , t:= g - 1, t - 1;\n sobases := Exchanger(sobases, next, t);\n if (g != t) {sobases := Exchanger(sobases, next, g);}\n }\n }\n\n return sobases;\n}\n\nmethod Testerexchange() {\n var a:seq := [A, C, A, T]; \n var b:seq := Exchanger(a, 2, 3);\n\n var c:seq := [A, C, A, T, A, T, C]; \n var d:seq := Exchanger(c, 5, 1); \n\n var e:seq := [A, C, A, T, A, T, C]; \n var f:seq := Exchanger(e, 1, 1); \n\n var g:seq := [A, C]; \n var h:seq := Exchanger(g, 0, 1); \n}\n\nmethod Testsort() {\n\n var a:seq := [G,A,T];\n var b:seq := Sorter(a);\n\n var c:seq := [G, A, T, T, A, C, G, C, T, A, C, G, T, T, G];\n var d:seq := Sorter(c);\n\n var e:seq := [A];\n var f:seq := Sorter(e);\n\n var g:seq := [A, C, G, T];\n var h:seq := Sorter(g);\n\n var i:seq := [A, T, C, T, T];\n}\n\n" }, { "test_ID": "691", "test_file": "fv2020-tms_tmp_tmpnp85b47l_modeling_concurrency_safety.dfy", "ground_truth": "/*\n * Model of the ticket system and correctness theorem\n * Parts 4 and 5 in the paper\n */\ntype Process(==) = int // Philosopher\n\ndatatype CState = Thinking | Hungry | Eating // Control states\n\n// A class can have state, with multiple fields, methods, a constructor, and declare functions and lemmas\nclass TicketSystem\n{\n var ticket: int // Ticket dispenser\n var serving: int // Serving display\n\n const P: set // Fixed set of processes\n\n // State for each process\n var cs: map // (Partial) Map from process to state\n var t: map // (Partial) Map from process to ticket number\n\n // Invariant of the system\n // Checks that P is a subset of the domain/keys of each map\n predicate Valid()\n reads this // Depends on the fields on the current class\n {\n && cs.Keys == t.Keys == P // Alt. P <= cs.Keys && P <= t.Keys\n && serving <= ticket\n && (forall p :: // ticket help is in range(serving, ticket)\n p in P && cs[p] != Thinking\n ==> serving <= t[p] < ticket\n )\n && (forall p, q :: // No other process can have the ticket number equals to serving\n p in P && q in P && p != q && cs[p] != Thinking && cs[q] != Thinking\n ==> t[p] != t[q]\n )\n && (forall p :: // We are serving the correct ticket number\n p in P && cs[p] == Eating\n ==> t[p] == serving\n )\n }\n\n // Initialize the ticket system\n constructor (processes: set)\n ensures Valid() // Postcondition\n ensures P == processes // Connection between processes and ts.P\n {\n P := processes;\n ticket, serving := 0, 0; // Alt. ticket := serving;\n // The two following use map comprehension\n cs := map p | p in processes :: Thinking; // The map from p, where p in processes, takes value Thinking\n t := map p | p in processes :: 0;\n }\n\n // The next three methods are our atomic events\n // A Philosopher is Thinking and gets Hungry\n method Request(p: Process)\n requires Valid() && p in P && cs[p] == Thinking // Control process precondition\n modifies this // Depends on the fields on the current class\n ensures Valid() // Postcondition\n {\n t, ticket := t[p := ticket], ticket + 1; // Philosopher gets current ticket, next ticket's number increases\n cs := cs[p := Hungry]; // Philosopher's state changes to Hungry\n }\n\n // A Philosopher is Hungry and enters the kitchen\n method Enter(p: Process)\n requires Valid() && p in P && cs[p] == Hungry // Control process precondition\n modifies this // Depends on the fields on the current class\n ensures Valid() // Postcondition\n {\n if t[p] == serving // The kitchen is available for this Philosopher\n {\n cs := cs[p := Eating]; // Philosopher's state changes to Eating\n }\n }\n\n // A Philosopher is done Eating and leaves the kitchen\n method Leave(p: Process)\n requires Valid() && p in P && cs[p] == Eating // Control process precondition\n modifies this // Depends on the fields on the current class\n ensures Valid() // Postcondition\n {\n //assert t[p] == serving; // Ticket held by p is equal to serving\n serving := serving + 1; // Kitchen is ready to serve the next ticket holder\n cs := cs[p := Thinking]; // Philosopher's state changes to Thinking\n }\n\n // Ensures that no two processes are in the same state\n lemma MutualExclusion(p: Process, q: Process)\n // Antecedents\n requires Valid() && p in P && q in P\n requires cs[p] == Eating && cs[q] == Eating\n // Conclusion/Proof goal\n ensures p == q\n {\n\n }\n}\n\n/*\n * Event scheduler\n * Part 6 in the paper\n * Part 6.1 for alternatives\n */\nmethod Run(processes: set)\n requires processes != {} // Cannot schedule no processes\n decreases * // Needed so that the loop omits termination checks\n{\n var ts := new TicketSystem(processes);\n var schedule := []; // Scheduling choices\n var trace := [(ts.ticket, ts.serving, ts.cs, ts.t)]; // Record sequence of states\n \n while true\n invariant ts.Valid()\n decreases * // Omits termination checks\n {\n var p :| p in ts.P; // p exists such that p is in ts.P\n match ts.cs[p] {\n case Thinking => ts.Request(p);\n case Hungry => ts.Enter(p);\n case Eating => ts.Leave(p);\n }\n schedule := schedule + [p];\n trace:=trace + [(ts.ticket, ts.serving, ts.cs, ts.t)];\n }\n}\n\n/*\n * Event scheduler with planified schedule\n * Part 6.2\n */\nmethod RunFromSchedule(processes: set, schedule: nat -> Process)\n requires processes != {}\n requires forall n :: schedule(n) in processes\n decreases *\n{\n var ts := new TicketSystem(processes);\n var n := 0;\n \n while true\n invariant ts.Valid()\n decreases * // Omits termination checks\n {\n var p := schedule(n);\n match ts.cs[p] {\n case Thinking => ts.Request(p);\n case Hungry => ts.Enter(p);\n case Eating => ts.Leave(p);\n }\n n := n + 1;\n }\n}\n\n", "hints_removed": "/*\n * Model of the ticket system and correctness theorem\n * Parts 4 and 5 in the paper\n */\ntype Process(==) = int // Philosopher\n\ndatatype CState = Thinking | Hungry | Eating // Control states\n\n// A class can have state, with multiple fields, methods, a constructor, and declare functions and lemmas\nclass TicketSystem\n{\n var ticket: int // Ticket dispenser\n var serving: int // Serving display\n\n const P: set // Fixed set of processes\n\n // State for each process\n var cs: map // (Partial) Map from process to state\n var t: map // (Partial) Map from process to ticket number\n\n // Invariant of the system\n // Checks that P is a subset of the domain/keys of each map\n predicate Valid()\n reads this // Depends on the fields on the current class\n {\n && cs.Keys == t.Keys == P // Alt. P <= cs.Keys && P <= t.Keys\n && serving <= ticket\n && (forall p :: // ticket help is in range(serving, ticket)\n p in P && cs[p] != Thinking\n ==> serving <= t[p] < ticket\n )\n && (forall p, q :: // No other process can have the ticket number equals to serving\n p in P && q in P && p != q && cs[p] != Thinking && cs[q] != Thinking\n ==> t[p] != t[q]\n )\n && (forall p :: // We are serving the correct ticket number\n p in P && cs[p] == Eating\n ==> t[p] == serving\n )\n }\n\n // Initialize the ticket system\n constructor (processes: set)\n ensures Valid() // Postcondition\n ensures P == processes // Connection between processes and ts.P\n {\n P := processes;\n ticket, serving := 0, 0; // Alt. ticket := serving;\n // The two following use map comprehension\n cs := map p | p in processes :: Thinking; // The map from p, where p in processes, takes value Thinking\n t := map p | p in processes :: 0;\n }\n\n // The next three methods are our atomic events\n // A Philosopher is Thinking and gets Hungry\n method Request(p: Process)\n requires Valid() && p in P && cs[p] == Thinking // Control process precondition\n modifies this // Depends on the fields on the current class\n ensures Valid() // Postcondition\n {\n t, ticket := t[p := ticket], ticket + 1; // Philosopher gets current ticket, next ticket's number increases\n cs := cs[p := Hungry]; // Philosopher's state changes to Hungry\n }\n\n // A Philosopher is Hungry and enters the kitchen\n method Enter(p: Process)\n requires Valid() && p in P && cs[p] == Hungry // Control process precondition\n modifies this // Depends on the fields on the current class\n ensures Valid() // Postcondition\n {\n if t[p] == serving // The kitchen is available for this Philosopher\n {\n cs := cs[p := Eating]; // Philosopher's state changes to Eating\n }\n }\n\n // A Philosopher is done Eating and leaves the kitchen\n method Leave(p: Process)\n requires Valid() && p in P && cs[p] == Eating // Control process precondition\n modifies this // Depends on the fields on the current class\n ensures Valid() // Postcondition\n {\n //assert t[p] == serving; // Ticket held by p is equal to serving\n serving := serving + 1; // Kitchen is ready to serve the next ticket holder\n cs := cs[p := Thinking]; // Philosopher's state changes to Thinking\n }\n\n // Ensures that no two processes are in the same state\n lemma MutualExclusion(p: Process, q: Process)\n // Antecedents\n requires Valid() && p in P && q in P\n requires cs[p] == Eating && cs[q] == Eating\n // Conclusion/Proof goal\n ensures p == q\n {\n\n }\n}\n\n/*\n * Event scheduler\n * Part 6 in the paper\n * Part 6.1 for alternatives\n */\nmethod Run(processes: set)\n requires processes != {} // Cannot schedule no processes\n{\n var ts := new TicketSystem(processes);\n var schedule := []; // Scheduling choices\n var trace := [(ts.ticket, ts.serving, ts.cs, ts.t)]; // Record sequence of states\n \n while true\n {\n var p :| p in ts.P; // p exists such that p is in ts.P\n match ts.cs[p] {\n case Thinking => ts.Request(p);\n case Hungry => ts.Enter(p);\n case Eating => ts.Leave(p);\n }\n schedule := schedule + [p];\n trace:=trace + [(ts.ticket, ts.serving, ts.cs, ts.t)];\n }\n}\n\n/*\n * Event scheduler with planified schedule\n * Part 6.2\n */\nmethod RunFromSchedule(processes: set, schedule: nat -> Process)\n requires processes != {}\n requires forall n :: schedule(n) in processes\n{\n var ts := new TicketSystem(processes);\n var n := 0;\n \n while true\n {\n var p := schedule(n);\n match ts.cs[p] {\n case Thinking => ts.Request(p);\n case Hungry => ts.Enter(p);\n case Eating => ts.Leave(p);\n }\n n := n + 1;\n }\n}\n\n" }, { "test_ID": "692", "test_file": "fv2020-tms_tmp_tmpnp85b47l_simple_tm.dfy", "ground_truth": "module ModelingTM {\n type ProcessId = nat\n type MemoryObject = nat\n type TimeStamp = nat\n\n class Operation {\n const isWrite: bool\n const memObject: MemoryObject\n }\n\n class Transaction {\n const ops: seq\n }\n\n // Process state : transaction progress and process memory.\n class ProcessState {\n // currentTx : id of tx being processed. txs.size() means done.\n const currentTx: nat\n // currentOp :\n // - tx.ops.size() represents tryCommit operation.\n // - -1 represents abort operation\n // - values in between represent read and write operations\n const currentOp: int\n // sub-operations of the operation, see the step function\n const currentSubOp: nat\n\n // Set of read objects with original observed timestamp.\n const readSet: map\n // Set of written objects.\n const writeSet: set\n\n constructor () {\n currentTx := 0;\n currentOp := 0;\n currentSubOp := 0;\n readSet := map[];\n writeSet := {};\n }\n\n constructor nextSubOp(that: ProcessState)\n ensures this.currentTx == that.currentTx\n ensures this.currentOp == that.currentOp\n ensures this.currentSubOp == that.currentSubOp + 1\n ensures this.readSet == that.readSet\n ensures this.writeSet == that.writeSet\n {\n currentTx := that.currentTx;\n currentOp := that.currentOp;\n currentSubOp := that.currentSubOp + 1;\n readSet := that.readSet;\n writeSet := that.writeSet;\n }\n\n constructor nextOp(that: ProcessState)\n ensures this.currentTx == that.currentTx\n ensures this.currentOp == that.currentOp + 1\n ensures this.currentSubOp == 0\n ensures this.readSet == that.readSet\n ensures this.writeSet == that.writeSet\n {\n currentTx := that.currentTx;\n currentOp := that.currentOp + 1;\n currentSubOp := 0;\n readSet := that.readSet;\n writeSet := that.writeSet;\n }\n\n constructor abortTx(that: ProcessState)\n ensures this.currentTx == that.currentTx\n ensures this.currentOp == -1\n ensures this.currentSubOp == 0\n ensures this.readSet == that.readSet\n ensures this.writeSet == that.writeSet\n {\n currentTx := that.currentTx;\n currentOp := -1;\n currentSubOp := 0;\n readSet := that.readSet;\n writeSet := that.writeSet;\n }\n\n constructor restartTx(that: ProcessState)\n ensures this.currentTx == that.currentTx\n ensures this.currentOp == 0\n ensures this.currentSubOp == 0\n ensures this.readSet == map[]\n ensures this.writeSet == {}\n {\n currentTx := that.currentTx;\n currentOp := 0;\n currentSubOp := 0;\n readSet := map[];\n writeSet := {};\n }\n\n constructor nextTx(that: ProcessState)\n ensures this.currentTx == that.currentTx + 1\n ensures this.currentOp == 0\n ensures this.currentSubOp == 0\n ensures this.readSet == map[]\n ensures this.writeSet == {}\n {\n currentTx := that.currentTx + 1;\n currentOp := 0;\n currentSubOp := 0;\n readSet := map[];\n writeSet := {};\n }\n\n constructor addToReadSet(that: ProcessState, obj: MemoryObject, ts: TimeStamp)\n ensures currentTx == that.currentTx\n ensures currentOp == that.currentOp\n ensures currentSubOp == that.currentSubOp\n ensures readSet.Keys == that.readSet.Keys + {obj}\n && readSet[obj] == ts\n && forall o :: o in readSet && o != obj ==> readSet[o] == that.readSet[o]\n ensures writeSet == that.writeSet\n {\n currentTx := that.currentTx;\n currentOp := that.currentOp;\n currentSubOp := that.currentSubOp;\n readSet := that.readSet[obj := ts];\n writeSet := that.writeSet;\n }\n\n constructor addToWriteSet(that: ProcessState, obj: MemoryObject)\n ensures this.currentTx == that.currentTx\n ensures this.currentOp == that.currentOp\n ensures this.currentSubOp == that.currentSubOp\n ensures this.readSet == that.readSet\n ensures this.writeSet == that.writeSet + {obj}\n {\n currentTx := that.currentTx;\n currentOp := that.currentOp;\n currentSubOp := that.currentSubOp;\n readSet := that.readSet;\n writeSet := that.writeSet + {obj};\n }\n }\n\n class TMSystem {\n // Ordered list of transaction that each process should process\n const txQueues : map>\n // State and memory of processes\n const procStates : map\n // Dirty objects. (Replaces the object value in a real representation. Used for safety proof)\n const dirtyObjs: set\n // Object lock.\n const lockedObjs: set\n // Object timestamp. (Incremented at the end of any write transaction)\n const objTimeStamps: map\n\n constructor (q: map>) {\n txQueues := q;\n procStates := map[];\n dirtyObjs := {};\n lockedObjs := {};\n objTimeStamps := map[];\n }\n\n constructor initTimestamp(that: TMSystem, obj: MemoryObject)\n ensures txQueues == that.txQueues\n ensures procStates == that.procStates\n ensures dirtyObjs == that.dirtyObjs\n ensures lockedObjs == that.lockedObjs\n ensures objTimeStamps.Keys == that.objTimeStamps.Keys + {obj}\n && objTimeStamps[obj] == 0\n && forall o :: o in objTimeStamps && o != obj ==> objTimeStamps[o] == that.objTimeStamps[o]\n {\n txQueues := that.txQueues;\n procStates := that.procStates;\n dirtyObjs := that.dirtyObjs;\n lockedObjs := that.lockedObjs;\n objTimeStamps := that.objTimeStamps[obj := 0];\n }\n \n constructor updateState(that: TMSystem, pid: ProcessId, state: ProcessState)\n ensures txQueues == that.txQueues\n ensures procStates.Keys == that.procStates.Keys + {pid}\n && procStates[pid] == state\n && forall p :: p in procStates && p != pid ==> procStates[p] == that.procStates[p]\n ensures dirtyObjs == that.dirtyObjs\n ensures lockedObjs == that.lockedObjs\n ensures objTimeStamps == that.objTimeStamps\n {\n txQueues := that.txQueues;\n procStates := that.procStates[pid := state];\n dirtyObjs := that.dirtyObjs;\n lockedObjs := that.lockedObjs;\n objTimeStamps := that.objTimeStamps;\n }\n \n constructor markDirty(that: TMSystem, obj: MemoryObject)\n ensures txQueues == that.txQueues\n ensures procStates == that.procStates\n ensures dirtyObjs == that.dirtyObjs + {obj}\n ensures lockedObjs == that.lockedObjs\n ensures objTimeStamps == that.objTimeStamps\n {\n txQueues := that.txQueues;\n procStates := that.procStates;\n dirtyObjs := that.dirtyObjs + {obj};\n lockedObjs := that.lockedObjs;\n objTimeStamps := that.objTimeStamps;\n }\n \n constructor clearDirty(that: TMSystem, writeSet: set)\n ensures txQueues == that.txQueues\n ensures procStates == that.procStates\n ensures dirtyObjs == that.dirtyObjs - writeSet\n ensures lockedObjs == that.lockedObjs\n ensures objTimeStamps == that.objTimeStamps\n {\n txQueues := that.txQueues;\n procStates := that.procStates;\n dirtyObjs := that.dirtyObjs - writeSet;\n lockedObjs := that.lockedObjs;\n objTimeStamps := that.objTimeStamps;\n }\n\n constructor acquireLock(that: TMSystem, o: MemoryObject)\n ensures txQueues == that.txQueues\n ensures procStates == that.procStates\n ensures dirtyObjs == that.dirtyObjs\n ensures lockedObjs == that.lockedObjs + {o}\n ensures objTimeStamps == that.objTimeStamps\n {\n txQueues := that.txQueues;\n procStates := that.procStates;\n dirtyObjs := that.dirtyObjs;\n lockedObjs := that.lockedObjs + {o};\n objTimeStamps := that.objTimeStamps;\n }\n\n constructor releaseLocks(that: TMSystem, objs: set)\n ensures txQueues == that.txQueues\n ensures procStates == that.procStates\n ensures dirtyObjs == that.dirtyObjs\n ensures lockedObjs == that.lockedObjs - objs\n ensures objTimeStamps == that.objTimeStamps\n {\n txQueues := that.txQueues;\n procStates := that.procStates;\n dirtyObjs := that.dirtyObjs;\n lockedObjs := that.lockedObjs - objs;\n objTimeStamps := that.objTimeStamps;\n }\n \n constructor updateTimestamps(that: TMSystem, objs: set)\n ensures txQueues == that.txQueues\n ensures procStates == that.procStates\n ensures dirtyObjs == that.dirtyObjs\n ensures lockedObjs == that.lockedObjs\n ensures objTimeStamps.Keys == that.objTimeStamps.Keys\n && forall o :: o in that.objTimeStamps ==>\n if(o in objs) then objTimeStamps[o] != that.objTimeStamps[o] else objTimeStamps[o] == that.objTimeStamps[o]\n {\n txQueues := that.txQueues;\n procStates := that.procStates;\n dirtyObjs := that.dirtyObjs;\n lockedObjs := that.lockedObjs;\n objTimeStamps := map o | o in that.objTimeStamps ::\n if(o in objs) then (that.objTimeStamps[o] + 1) else that.objTimeStamps[o];\n }\n\n predicate stateValid(pid: ProcessId, state: ProcessState)\n requires pid in procStates && state == procStates[pid]\n {\n && pid in txQueues\n && state.currentTx <= |txQueues[pid]|\n && if state.currentTx == |txQueues[pid]| then (\n // Queue finished\n && state.currentOp == 0\n && state.currentSubOp == 0\n && |state.readSet| == 0\n && |state.writeSet| == 0\n ) else if state.currentTx < |txQueues[pid]| then (\n // Queue unfinished\n && exists tx :: (\n && tx == txQueues[pid][state.currentTx]\n && state.currentOp <= |tx.ops|\n && state.currentOp >= -1\n && if (state.currentOp >= 0 && state.currentOp < |tx.ops|) then (\n // Read/Write operations have at most two subOps\n state.currentSubOp < 2\n ) else if state.currentOp == |tx.ops| then (\n // tryCommit has 4 subOps\n state.currentSubOp < 4\n ) else if state.currentOp == -1 then (\n // abort has 3 subOps\n state.currentSubOp < 3\n ) else false\n )\n && state.readSet.Keys <= objTimeStamps.Keys\n && state.writeSet <= lockedObjs\n ) else false\n }\n\n predicate validSystem()\n {\n && procStates.Keys <= txQueues.Keys\n && dirtyObjs <= objTimeStamps.Keys\n && lockedObjs <= objTimeStamps.Keys\n && forall p, s :: p in procStates && s == procStates[p] ==> stateValid(p, s)\n }\n }\n \n\n method Step(input: TMSystem, pid: ProcessId) returns (system: TMSystem)\n requires pid in input.txQueues\n requires pid in input.procStates\n requires input.validSystem()\n ensures system.validSystem()\n {\n system := input;\n var state: ProcessState := system.procStates[pid];\n assert(system.stateValid(pid, state)); // Given by input.validSystem()\n var txs := system.txQueues[pid];\n\n if (state.currentTx >= |txs|) {\n // Nothing left to do.\n return;\n }\n var tx := txs[state.currentTx];\n \n if (state.currentOp == |tx.ops|) {\n // tryCommit\n if(state.currentSubOp == 0) {\n // Check locks\n if !(forall o :: o in state.readSet ==> o in state.writeSet || o !in system.lockedObjs) {\n // Write detected (locked), aborting.\n state := new ProcessState.abortTx(state);\n system := new TMSystem.updateState(system, pid, state);\n assume(system.validSystem()); // TODO : Remove assumption.\n return;\n }\n // Continue to next sub-op.\n state := new ProcessState.nextSubOp(state);\n } else if (state.currentSubOp == 1) {\n // Validate timestamps\n if !(forall o :: o in state.readSet ==> state.readSet[o] == system.objTimeStamps[o]) {\n // Write detected (timestamp changed), aborting.\n state := new ProcessState.abortTx(state);\n system := new TMSystem.updateState(system, pid, state);\n assume(system.validSystem()); // TODO : Remove assumption.\n return;\n }\n // Can (and will) commit !\n // The writeset can now be read safely by others so we can remove the dirty mark.\n system := new TMSystem.clearDirty(system, state.writeSet);\n // Continue to next sub-op.\n state := new ProcessState.nextSubOp(state);\n } else if (state.currentSubOp == 2) {\n // Update timestamps\n system := new TMSystem.updateTimestamps(system, state.writeSet);\n // Continue to next sub-op.\n state := new ProcessState.nextSubOp(state);\n } else if (state.currentSubOp == 3) {\n // Release locks\n system := new TMSystem.releaseLocks(system, state.writeSet);\n // Commited. Continue to next transaction.\n state := new ProcessState.nextTx(state);\n } else {\n assert(false);\n }\n } else if (state.currentOp == -1) {\n // Abort\n if(state.currentSubOp == 0) {\n assert(state.currentTx < |system.txQueues[pid]|);\n // Restore written values (equivalent to removing dirty marks here).\n system := new TMSystem.clearDirty(system, state.writeSet);\n // Continue to next sub-op.\n state := new ProcessState.nextSubOp(state);\n } else if (state.currentSubOp == 1) {\n // Update timestamps\n system := new TMSystem.updateTimestamps(system, state.writeSet);\n // Continue to next sub-op.\n state := new ProcessState.nextSubOp(state);\n } else if (state.currentSubOp == 2) {\n // Release locks\n system := new TMSystem.releaseLocks(system, state.writeSet);\n // Restart transaction.\n state := new ProcessState.restartTx(state);\n } else {\n assert(false);\n }\n } else if (state.currentOp >= 0 && state.currentOp < |tx.ops|) {\n // Read/Write op\n var op := tx.ops[state.currentOp];\n var o := op.memObject;\n \n // Init object timestamp if not present\n if(o !in system.objTimeStamps) {\n system := new TMSystem.initTimestamp(system, o);\n }\n assert(o in system.objTimeStamps);\n\n if(op.isWrite) {\n // Write\n if(state.currentSubOp == 0) {\n if(!(op.memObject in state.writeSet)) {\n // trylock\n if(o in system.lockedObjs) {\n // Failed locking, aborting.\n state := new ProcessState.abortTx(state);\n } else {\n // Aquire lock. Continue to next sub-op.\n system := new TMSystem.acquireLock(system, o);\n state := new ProcessState.addToWriteSet(state, o);\n state := new ProcessState.nextSubOp(state);\n }\n } else {\n // Already in writeset, continue to next subOp.\n state := new ProcessState.nextSubOp(state);\n }\n } else if (state.currentSubOp == 1) {\n // Do the write (equivalent to marking as dirty). Continue to next op.\n system := new TMSystem.markDirty(system, o);\n state := new ProcessState.nextOp(state);\n } else {\n assert(false);\n }\n } else {\n // Read operation\n if(state.currentSubOp == 0) {\n if(o in state.writeSet || o in state.readSet) {\n // Already in writeSet or readSet, fast-skip to next op.\n state := new ProcessState.nextOp(state);\n } else {\n // Read timestamp and add to readSet. Continue to next sub-op.\n state := new ProcessState.addToReadSet(state, o, system.objTimeStamps[o]);\n state := new ProcessState.nextSubOp(state);\n }\n } else if (state.currentSubOp == 1) {\n if(o in system.lockedObjs) {\n // Object is locked, aborting.\n state := new ProcessState.abortTx(state);\n } else {\n // All good. Continue to next op.\n state := new ProcessState.nextOp(state);\n }\n } else {\n assert(false);\n }\n }\n } else {\n assert(false);\n }\n // Save the new state.\n system := new TMSystem.updateState(system, pid, state);\n assume(system.validSystem()); // TODO : Remove assumption.\n }\n}\n\n", "hints_removed": "module ModelingTM {\n type ProcessId = nat\n type MemoryObject = nat\n type TimeStamp = nat\n\n class Operation {\n const isWrite: bool\n const memObject: MemoryObject\n }\n\n class Transaction {\n const ops: seq\n }\n\n // Process state : transaction progress and process memory.\n class ProcessState {\n // currentTx : id of tx being processed. txs.size() means done.\n const currentTx: nat\n // currentOp :\n // - tx.ops.size() represents tryCommit operation.\n // - -1 represents abort operation\n // - values in between represent read and write operations\n const currentOp: int\n // sub-operations of the operation, see the step function\n const currentSubOp: nat\n\n // Set of read objects with original observed timestamp.\n const readSet: map\n // Set of written objects.\n const writeSet: set\n\n constructor () {\n currentTx := 0;\n currentOp := 0;\n currentSubOp := 0;\n readSet := map[];\n writeSet := {};\n }\n\n constructor nextSubOp(that: ProcessState)\n ensures this.currentTx == that.currentTx\n ensures this.currentOp == that.currentOp\n ensures this.currentSubOp == that.currentSubOp + 1\n ensures this.readSet == that.readSet\n ensures this.writeSet == that.writeSet\n {\n currentTx := that.currentTx;\n currentOp := that.currentOp;\n currentSubOp := that.currentSubOp + 1;\n readSet := that.readSet;\n writeSet := that.writeSet;\n }\n\n constructor nextOp(that: ProcessState)\n ensures this.currentTx == that.currentTx\n ensures this.currentOp == that.currentOp + 1\n ensures this.currentSubOp == 0\n ensures this.readSet == that.readSet\n ensures this.writeSet == that.writeSet\n {\n currentTx := that.currentTx;\n currentOp := that.currentOp + 1;\n currentSubOp := 0;\n readSet := that.readSet;\n writeSet := that.writeSet;\n }\n\n constructor abortTx(that: ProcessState)\n ensures this.currentTx == that.currentTx\n ensures this.currentOp == -1\n ensures this.currentSubOp == 0\n ensures this.readSet == that.readSet\n ensures this.writeSet == that.writeSet\n {\n currentTx := that.currentTx;\n currentOp := -1;\n currentSubOp := 0;\n readSet := that.readSet;\n writeSet := that.writeSet;\n }\n\n constructor restartTx(that: ProcessState)\n ensures this.currentTx == that.currentTx\n ensures this.currentOp == 0\n ensures this.currentSubOp == 0\n ensures this.readSet == map[]\n ensures this.writeSet == {}\n {\n currentTx := that.currentTx;\n currentOp := 0;\n currentSubOp := 0;\n readSet := map[];\n writeSet := {};\n }\n\n constructor nextTx(that: ProcessState)\n ensures this.currentTx == that.currentTx + 1\n ensures this.currentOp == 0\n ensures this.currentSubOp == 0\n ensures this.readSet == map[]\n ensures this.writeSet == {}\n {\n currentTx := that.currentTx + 1;\n currentOp := 0;\n currentSubOp := 0;\n readSet := map[];\n writeSet := {};\n }\n\n constructor addToReadSet(that: ProcessState, obj: MemoryObject, ts: TimeStamp)\n ensures currentTx == that.currentTx\n ensures currentOp == that.currentOp\n ensures currentSubOp == that.currentSubOp\n ensures readSet.Keys == that.readSet.Keys + {obj}\n && readSet[obj] == ts\n && forall o :: o in readSet && o != obj ==> readSet[o] == that.readSet[o]\n ensures writeSet == that.writeSet\n {\n currentTx := that.currentTx;\n currentOp := that.currentOp;\n currentSubOp := that.currentSubOp;\n readSet := that.readSet[obj := ts];\n writeSet := that.writeSet;\n }\n\n constructor addToWriteSet(that: ProcessState, obj: MemoryObject)\n ensures this.currentTx == that.currentTx\n ensures this.currentOp == that.currentOp\n ensures this.currentSubOp == that.currentSubOp\n ensures this.readSet == that.readSet\n ensures this.writeSet == that.writeSet + {obj}\n {\n currentTx := that.currentTx;\n currentOp := that.currentOp;\n currentSubOp := that.currentSubOp;\n readSet := that.readSet;\n writeSet := that.writeSet + {obj};\n }\n }\n\n class TMSystem {\n // Ordered list of transaction that each process should process\n const txQueues : map>\n // State and memory of processes\n const procStates : map\n // Dirty objects. (Replaces the object value in a real representation. Used for safety proof)\n const dirtyObjs: set\n // Object lock.\n const lockedObjs: set\n // Object timestamp. (Incremented at the end of any write transaction)\n const objTimeStamps: map\n\n constructor (q: map>) {\n txQueues := q;\n procStates := map[];\n dirtyObjs := {};\n lockedObjs := {};\n objTimeStamps := map[];\n }\n\n constructor initTimestamp(that: TMSystem, obj: MemoryObject)\n ensures txQueues == that.txQueues\n ensures procStates == that.procStates\n ensures dirtyObjs == that.dirtyObjs\n ensures lockedObjs == that.lockedObjs\n ensures objTimeStamps.Keys == that.objTimeStamps.Keys + {obj}\n && objTimeStamps[obj] == 0\n && forall o :: o in objTimeStamps && o != obj ==> objTimeStamps[o] == that.objTimeStamps[o]\n {\n txQueues := that.txQueues;\n procStates := that.procStates;\n dirtyObjs := that.dirtyObjs;\n lockedObjs := that.lockedObjs;\n objTimeStamps := that.objTimeStamps[obj := 0];\n }\n \n constructor updateState(that: TMSystem, pid: ProcessId, state: ProcessState)\n ensures txQueues == that.txQueues\n ensures procStates.Keys == that.procStates.Keys + {pid}\n && procStates[pid] == state\n && forall p :: p in procStates && p != pid ==> procStates[p] == that.procStates[p]\n ensures dirtyObjs == that.dirtyObjs\n ensures lockedObjs == that.lockedObjs\n ensures objTimeStamps == that.objTimeStamps\n {\n txQueues := that.txQueues;\n procStates := that.procStates[pid := state];\n dirtyObjs := that.dirtyObjs;\n lockedObjs := that.lockedObjs;\n objTimeStamps := that.objTimeStamps;\n }\n \n constructor markDirty(that: TMSystem, obj: MemoryObject)\n ensures txQueues == that.txQueues\n ensures procStates == that.procStates\n ensures dirtyObjs == that.dirtyObjs + {obj}\n ensures lockedObjs == that.lockedObjs\n ensures objTimeStamps == that.objTimeStamps\n {\n txQueues := that.txQueues;\n procStates := that.procStates;\n dirtyObjs := that.dirtyObjs + {obj};\n lockedObjs := that.lockedObjs;\n objTimeStamps := that.objTimeStamps;\n }\n \n constructor clearDirty(that: TMSystem, writeSet: set)\n ensures txQueues == that.txQueues\n ensures procStates == that.procStates\n ensures dirtyObjs == that.dirtyObjs - writeSet\n ensures lockedObjs == that.lockedObjs\n ensures objTimeStamps == that.objTimeStamps\n {\n txQueues := that.txQueues;\n procStates := that.procStates;\n dirtyObjs := that.dirtyObjs - writeSet;\n lockedObjs := that.lockedObjs;\n objTimeStamps := that.objTimeStamps;\n }\n\n constructor acquireLock(that: TMSystem, o: MemoryObject)\n ensures txQueues == that.txQueues\n ensures procStates == that.procStates\n ensures dirtyObjs == that.dirtyObjs\n ensures lockedObjs == that.lockedObjs + {o}\n ensures objTimeStamps == that.objTimeStamps\n {\n txQueues := that.txQueues;\n procStates := that.procStates;\n dirtyObjs := that.dirtyObjs;\n lockedObjs := that.lockedObjs + {o};\n objTimeStamps := that.objTimeStamps;\n }\n\n constructor releaseLocks(that: TMSystem, objs: set)\n ensures txQueues == that.txQueues\n ensures procStates == that.procStates\n ensures dirtyObjs == that.dirtyObjs\n ensures lockedObjs == that.lockedObjs - objs\n ensures objTimeStamps == that.objTimeStamps\n {\n txQueues := that.txQueues;\n procStates := that.procStates;\n dirtyObjs := that.dirtyObjs;\n lockedObjs := that.lockedObjs - objs;\n objTimeStamps := that.objTimeStamps;\n }\n \n constructor updateTimestamps(that: TMSystem, objs: set)\n ensures txQueues == that.txQueues\n ensures procStates == that.procStates\n ensures dirtyObjs == that.dirtyObjs\n ensures lockedObjs == that.lockedObjs\n ensures objTimeStamps.Keys == that.objTimeStamps.Keys\n && forall o :: o in that.objTimeStamps ==>\n if(o in objs) then objTimeStamps[o] != that.objTimeStamps[o] else objTimeStamps[o] == that.objTimeStamps[o]\n {\n txQueues := that.txQueues;\n procStates := that.procStates;\n dirtyObjs := that.dirtyObjs;\n lockedObjs := that.lockedObjs;\n objTimeStamps := map o | o in that.objTimeStamps ::\n if(o in objs) then (that.objTimeStamps[o] + 1) else that.objTimeStamps[o];\n }\n\n predicate stateValid(pid: ProcessId, state: ProcessState)\n requires pid in procStates && state == procStates[pid]\n {\n && pid in txQueues\n && state.currentTx <= |txQueues[pid]|\n && if state.currentTx == |txQueues[pid]| then (\n // Queue finished\n && state.currentOp == 0\n && state.currentSubOp == 0\n && |state.readSet| == 0\n && |state.writeSet| == 0\n ) else if state.currentTx < |txQueues[pid]| then (\n // Queue unfinished\n && exists tx :: (\n && tx == txQueues[pid][state.currentTx]\n && state.currentOp <= |tx.ops|\n && state.currentOp >= -1\n && if (state.currentOp >= 0 && state.currentOp < |tx.ops|) then (\n // Read/Write operations have at most two subOps\n state.currentSubOp < 2\n ) else if state.currentOp == |tx.ops| then (\n // tryCommit has 4 subOps\n state.currentSubOp < 4\n ) else if state.currentOp == -1 then (\n // abort has 3 subOps\n state.currentSubOp < 3\n ) else false\n )\n && state.readSet.Keys <= objTimeStamps.Keys\n && state.writeSet <= lockedObjs\n ) else false\n }\n\n predicate validSystem()\n {\n && procStates.Keys <= txQueues.Keys\n && dirtyObjs <= objTimeStamps.Keys\n && lockedObjs <= objTimeStamps.Keys\n && forall p, s :: p in procStates && s == procStates[p] ==> stateValid(p, s)\n }\n }\n \n\n method Step(input: TMSystem, pid: ProcessId) returns (system: TMSystem)\n requires pid in input.txQueues\n requires pid in input.procStates\n requires input.validSystem()\n ensures system.validSystem()\n {\n system := input;\n var state: ProcessState := system.procStates[pid];\n var txs := system.txQueues[pid];\n\n if (state.currentTx >= |txs|) {\n // Nothing left to do.\n return;\n }\n var tx := txs[state.currentTx];\n \n if (state.currentOp == |tx.ops|) {\n // tryCommit\n if(state.currentSubOp == 0) {\n // Check locks\n if !(forall o :: o in state.readSet ==> o in state.writeSet || o !in system.lockedObjs) {\n // Write detected (locked), aborting.\n state := new ProcessState.abortTx(state);\n system := new TMSystem.updateState(system, pid, state);\n assume(system.validSystem()); // TODO : Remove assumption.\n return;\n }\n // Continue to next sub-op.\n state := new ProcessState.nextSubOp(state);\n } else if (state.currentSubOp == 1) {\n // Validate timestamps\n if !(forall o :: o in state.readSet ==> state.readSet[o] == system.objTimeStamps[o]) {\n // Write detected (timestamp changed), aborting.\n state := new ProcessState.abortTx(state);\n system := new TMSystem.updateState(system, pid, state);\n assume(system.validSystem()); // TODO : Remove assumption.\n return;\n }\n // Can (and will) commit !\n // The writeset can now be read safely by others so we can remove the dirty mark.\n system := new TMSystem.clearDirty(system, state.writeSet);\n // Continue to next sub-op.\n state := new ProcessState.nextSubOp(state);\n } else if (state.currentSubOp == 2) {\n // Update timestamps\n system := new TMSystem.updateTimestamps(system, state.writeSet);\n // Continue to next sub-op.\n state := new ProcessState.nextSubOp(state);\n } else if (state.currentSubOp == 3) {\n // Release locks\n system := new TMSystem.releaseLocks(system, state.writeSet);\n // Commited. Continue to next transaction.\n state := new ProcessState.nextTx(state);\n } else {\n }\n } else if (state.currentOp == -1) {\n // Abort\n if(state.currentSubOp == 0) {\n // Restore written values (equivalent to removing dirty marks here).\n system := new TMSystem.clearDirty(system, state.writeSet);\n // Continue to next sub-op.\n state := new ProcessState.nextSubOp(state);\n } else if (state.currentSubOp == 1) {\n // Update timestamps\n system := new TMSystem.updateTimestamps(system, state.writeSet);\n // Continue to next sub-op.\n state := new ProcessState.nextSubOp(state);\n } else if (state.currentSubOp == 2) {\n // Release locks\n system := new TMSystem.releaseLocks(system, state.writeSet);\n // Restart transaction.\n state := new ProcessState.restartTx(state);\n } else {\n }\n } else if (state.currentOp >= 0 && state.currentOp < |tx.ops|) {\n // Read/Write op\n var op := tx.ops[state.currentOp];\n var o := op.memObject;\n \n // Init object timestamp if not present\n if(o !in system.objTimeStamps) {\n system := new TMSystem.initTimestamp(system, o);\n }\n\n if(op.isWrite) {\n // Write\n if(state.currentSubOp == 0) {\n if(!(op.memObject in state.writeSet)) {\n // trylock\n if(o in system.lockedObjs) {\n // Failed locking, aborting.\n state := new ProcessState.abortTx(state);\n } else {\n // Aquire lock. Continue to next sub-op.\n system := new TMSystem.acquireLock(system, o);\n state := new ProcessState.addToWriteSet(state, o);\n state := new ProcessState.nextSubOp(state);\n }\n } else {\n // Already in writeset, continue to next subOp.\n state := new ProcessState.nextSubOp(state);\n }\n } else if (state.currentSubOp == 1) {\n // Do the write (equivalent to marking as dirty). Continue to next op.\n system := new TMSystem.markDirty(system, o);\n state := new ProcessState.nextOp(state);\n } else {\n }\n } else {\n // Read operation\n if(state.currentSubOp == 0) {\n if(o in state.writeSet || o in state.readSet) {\n // Already in writeSet or readSet, fast-skip to next op.\n state := new ProcessState.nextOp(state);\n } else {\n // Read timestamp and add to readSet. Continue to next sub-op.\n state := new ProcessState.addToReadSet(state, o, system.objTimeStamps[o]);\n state := new ProcessState.nextSubOp(state);\n }\n } else if (state.currentSubOp == 1) {\n if(o in system.lockedObjs) {\n // Object is locked, aborting.\n state := new ProcessState.abortTx(state);\n } else {\n // All good. Continue to next op.\n state := new ProcessState.nextOp(state);\n }\n } else {\n }\n }\n } else {\n }\n // Save the new state.\n system := new TMSystem.updateState(system, pid, state);\n assume(system.validSystem()); // TODO : Remove assumption.\n }\n}\n\n" }, { "test_ID": "693", "test_file": "groupTheory_tmp_tmppmmxvu8h_assignment1.dfy", "ground_truth": "/*\nStudent name: Mark Valman\nId: 342439593\n*/\n\n/* Question/Exercise 1 of 4 */\nlemma Q1_logical_equivalence_as_a_conjunction_of_two_implications__PROOF_BY_TRUTH_TABLE__in_a_comment(L: bool, R: bool)\n\tensures (L <==> R) <==> (L ==> R) && (!L ==> !R)\n{\n\t/*\n\t\tThis lemma states that logical equivalence (L <==> R) can be proved in two steps:\n\t\t(1) that L implies R, and that (2) the negation of L implies the negation of R.\n\t\t\n\t\tAs can be seen here (by the curly braces \"{\" on line 4 and \"}\" below this comment), Dafny accepts this claim we no problem.\n\n\t\tYour goal in this exercise is to use the truth tables we've learned for conjunction and negation in lecture01.dfy,\n\t\tfor logical implication in lecture02.dfy, and for logical equivalence (bi-directional implication) in lecture03.dfy,\n\t\tto prove correctness of this claim (such that the final column will have T on each line).\n\t\t\n\t\tSee as an example for this kind of exercise the truth table in lines 13-21 of tutorial03.dfy;\n\t\tthere, however, the stated property was not correct (as we ended with the truth value T only on 6 of the 8 lines)\n\n\t\tYOUR_SOLUTION_SHOULD_BE_WRITTEN_HERE (inside this comment, to the human reader, not to Dafny):\n\n\t\tL\tR\t!L\t!R\t\"L ==> R\"\t\"!L ==> !R\"\t\"(L ==> R) && (!L ==> !R)\"\t\"(L <==> R)\"\t\"(L <==> R) <==> (L ==> R) && (!L ==> !R)\"\n\t\tF\tF\tT\tT\tT\t\t\tT\t\t\tT\t\t\t\t\t\t\tT\t\t\t\tT\n\t\tF\tT\tT\tF\tT\t\t\tF\t\t\tF\t\t\t\t\t\t\tF\t\t\t\tT\n\t\tT\tF\tF\tT\tF\t\t\tT\t\t\tF\t\t\t\t\t\t\tF\t\t\t\tT\n\t\tT\tT\tF\tF\tT\t\t\tT\t\t\tT\t\t\t\t\t\t\tT\t\t\t\tT\n\n\t*/\n} \n\n\n/* Question/Exercise 2 of 4 */\nlemma Q2_DistributivityOfSetUnionOverSetIntersection(A: set, B: set, C: set)\n\tensures A+(B*C) == (A+B)*(A+C)\n/*\n\tIn this exercise you are expected to write a *full* proof for the lemma;\n\tas an example, see the proof of \"DistributivityOfSetIntersectionOverSetUnion\"\n\tstarting on line 167 of lecture04.dfy and continuing on lines 3-44 of tutorial04.dfy;\n\tnote that the proof must be fully justified for the human reader,\n\twith labels to assertions and the relevant reveal statements where needed,\n\tas can be seen in the \"Distributivity2a\" lemma from the tutorial\n\t(in contrast to the lemma \"Distributivity1a\" from the lecture, where we did not add labels);\n\tin case of syntax errors, you solution will NOT be checked.\n\n\tYOUR_SOLUTION_SHOULD_BE_WRITTEN_BELOW_THIS_LINE, between curly braces \"{\" and \"}\" */\n\n\t\t{\n\t\tvar L,R:= A+(B*C),(A+B)*(A+C);\n\t\tforall x| x in L ensures x in R\n\t\t{\n\t\t\tassert 1: x in A+(B*C);\n\t\t\tassert 2: x in A||(x in B && x in C) by {reveal 1; }\n\t\t\tif x in A\n\t\t\t{\n\t\t\t\tassert 3: x in A+(B*C) by {reveal 1; } \n\t\t\t\tassert 4: (x in A || x in B ) && (x in A || x in C) by {reveal 3;}\n\t\t\t\tassert 5: x in (A+B)*(A+C) by {reveal 4;}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tassert 6: x in (B*C);\n\t\t\t\tassert 7: (x in A || x in B ) && (x in A || x in C) by {reveal 6,3;}\n\t\t\t\tassert 8: x in (A+B)*(A+C) by {reveal 7; }\n\t\t\t\tassert 9: x in R by {reveal 8;}\t\t\n\t\t\t}\t\n\t\t}\n\t\tforall x| x in R ensures x in L\n\t\t{\n\t\t\t\tassert 9: x in (A+B)*(A+C);\n\t\t\t\tassert 10: (x in A|| x in B)&& (x in A|| x in C) by {reveal 9; }\n\t\t\t\tassert 11: x in A || (x in B && x in C) by {reveal 10; }\n\t\t\t\tassert 12: x in A + (B*C) by {reveal 11; }\n\t\t\t\tassert 13: x in L by {reveal 12; }\n\n\n\t\t}\n\t\t\n\t}\n\n\n\n\n\n\n\n/* Question/Exercise 3 of 4 */\nlemma Q3_SetUnionIsAssociative(A: iset, B: iset, C: iset)\n\tensures (A + B) + C == A + (B + C)\n\t/*\n\twhen taking the union of three (possibly-infinite) sets, the order of the operations does not matter;\n\tthis property is known as associativity;\n\tthis is the same in the addition of integers:\n\t\n\tassert forall x:int, y: int, z: int :: x+(y+z) == (x+y)+z;\n\n\t(whereas for sutraction it does not hold: assert 10-(4-1) == 10-3 == 7 != 5 == 6-1 == (10-4)-1;)\n\t\n\tAs in exercise 2 above, you are expected to provide a *full* proof, in Dafny, with no errors.\n\n\tYOUR_SOLUTION_SHOULD_BE_WRITTEN_BELOW_THIS_LINE, between curly braces \"{\" and \"}\" */\n\n\t{\n\t\tvar L,R := (A + B) + C, A + (B + C);\n\t\tforall x | x in L ensures x in R\n\t\t{\n\t\t\tassert 1: x in (A + B) + C;\n\t\t\tassert 2: (x in A || x in B) || x in C by {reveal 1; }\n\t\t\tassert 3: x in A || (x in B || x in C) by {reveal 2; }\n\t\t\tassert 4: x in A + (B + C) by {reveal 3; }\n\t\t\tassert 5: x in R by {reveal 4; }\n\n\t\t}\n\t\n\t\t\tforall x | x in R ensures x in L\n\t\t{\n\t\t\tassert 6: x in A + (B + C);\n\t\t\tassert 7: x in A || (x in B || x in C ) by {reveal 6; }\n\t\t\tassert 8: (x in A|| x in B) || x in C by {reveal 7; }\n\t\t\tassert 9: x in (A + B) + C by {reveal 8; }\n\t\t\tassert 10: x in L by {reveal 9; }\n\t\t}\n\t}\n\n\n/* Question/Exercise 4 of 4 */\n/*\n\tRecall from \"SquareOfIntegersIsNotMonotonic\" in lecture05.dfy how a lemma that returns results\n\tcan be used to disprove a claim by providing evidence for its negation;\n\tsimilarly, your goal here is to choose values for A,B,C and demonstrate (using assertions or the \"calc\" construct)\n\thow when performing the set difference operation twice, the order of operations DOES matter!\n\n\tYOUR_SOLUTION_SHOULD_BE_WRITTEN_BELOW_THIS_LINE, between curly braces \"{\" and \"}\" */\n\t\nlemma preparation_for_Q4_SetDifferenceIs_NOT_Associative()\n\tensures !forall A: set, B: set, C: set :: (A - B) - C == A - (B - C)\n{\n\tassert exists A: set, B: set, C: set :: (A - B) - C != A - (B - C) by {\n\t\tvar A, B, C := Q4_Evidence_That_SetDifferenceIs_NOT_Associative();\n\t\tassert (A - B) - C != A - (B - C);\n\t}\n}\n\nlemma Q4_Evidence_That_SetDifferenceIs_NOT_Associative() returns (A: set, B: set, C: set)\n\tensures (A - B) - C != A - (B - C)\n\t{\n\t\tA:= {6,3,7};\n\t\tB:= {1,6};\n\t\tC:= {3,2,5};\n\t\tassert (A - B) - C != A - (B - C);\n calc\n {\n\t(A - B) - C != A - (B - C);\n\t==\n\t({6,3,7} - {1,6}) - {3,2,5} != {6,3,7} - ({1,6} - {3,2,5});\n\t==\n\t( {7} != {3,7} );\n\t==\n\ttrue;\n\n }\n\t}\n", "hints_removed": "/*\nStudent name: Mark Valman\nId: 342439593\n*/\n\n/* Question/Exercise 1 of 4 */\nlemma Q1_logical_equivalence_as_a_conjunction_of_two_implications__PROOF_BY_TRUTH_TABLE__in_a_comment(L: bool, R: bool)\n\tensures (L <==> R) <==> (L ==> R) && (!L ==> !R)\n{\n\t/*\n\t\tThis lemma states that logical equivalence (L <==> R) can be proved in two steps:\n\t\t(1) that L implies R, and that (2) the negation of L implies the negation of R.\n\t\t\n\t\tAs can be seen here (by the curly braces \"{\" on line 4 and \"}\" below this comment), Dafny accepts this claim we no problem.\n\n\t\tYour goal in this exercise is to use the truth tables we've learned for conjunction and negation in lecture01.dfy,\n\t\tfor logical implication in lecture02.dfy, and for logical equivalence (bi-directional implication) in lecture03.dfy,\n\t\tto prove correctness of this claim (such that the final column will have T on each line).\n\t\t\n\t\tSee as an example for this kind of exercise the truth table in lines 13-21 of tutorial03.dfy;\n\t\tthere, however, the stated property was not correct (as we ended with the truth value T only on 6 of the 8 lines)\n\n\t\tYOUR_SOLUTION_SHOULD_BE_WRITTEN_HERE (inside this comment, to the human reader, not to Dafny):\n\n\t\tL\tR\t!L\t!R\t\"L ==> R\"\t\"!L ==> !R\"\t\"(L ==> R) && (!L ==> !R)\"\t\"(L <==> R)\"\t\"(L <==> R) <==> (L ==> R) && (!L ==> !R)\"\n\t\tF\tF\tT\tT\tT\t\t\tT\t\t\tT\t\t\t\t\t\t\tT\t\t\t\tT\n\t\tF\tT\tT\tF\tT\t\t\tF\t\t\tF\t\t\t\t\t\t\tF\t\t\t\tT\n\t\tT\tF\tF\tT\tF\t\t\tT\t\t\tF\t\t\t\t\t\t\tF\t\t\t\tT\n\t\tT\tT\tF\tF\tT\t\t\tT\t\t\tT\t\t\t\t\t\t\tT\t\t\t\tT\n\n\t*/\n} \n\n\n/* Question/Exercise 2 of 4 */\nlemma Q2_DistributivityOfSetUnionOverSetIntersection(A: set, B: set, C: set)\n\tensures A+(B*C) == (A+B)*(A+C)\n/*\n\tIn this exercise you are expected to write a *full* proof for the lemma;\n\tas an example, see the proof of \"DistributivityOfSetIntersectionOverSetUnion\"\n\tstarting on line 167 of lecture04.dfy and continuing on lines 3-44 of tutorial04.dfy;\n\tnote that the proof must be fully justified for the human reader,\n\twith labels to assertions and the relevant reveal statements where needed,\n\tas can be seen in the \"Distributivity2a\" lemma from the tutorial\n\t(in contrast to the lemma \"Distributivity1a\" from the lecture, where we did not add labels);\n\tin case of syntax errors, you solution will NOT be checked.\n\n\tYOUR_SOLUTION_SHOULD_BE_WRITTEN_BELOW_THIS_LINE, between curly braces \"{\" and \"}\" */\n\n\t\t{\n\t\tvar L,R:= A+(B*C),(A+B)*(A+C);\n\t\tforall x| x in L ensures x in R\n\t\t{\n\t\t\tif x in A\n\t\t\t{\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t}\t\n\t\t}\n\t\tforall x| x in R ensures x in L\n\t\t{\n\n\n\t\t}\n\t\t\n\t}\n\n\n\n\n\n\n\n/* Question/Exercise 3 of 4 */\nlemma Q3_SetUnionIsAssociative(A: iset, B: iset, C: iset)\n\tensures (A + B) + C == A + (B + C)\n\t/*\n\twhen taking the union of three (possibly-infinite) sets, the order of the operations does not matter;\n\tthis property is known as associativity;\n\tthis is the same in the addition of integers:\n\t\n\n\t(whereas for sutraction it does not hold: assert 10-(4-1) == 10-3 == 7 != 5 == 6-1 == (10-4)-1;)\n\t\n\tAs in exercise 2 above, you are expected to provide a *full* proof, in Dafny, with no errors.\n\n\tYOUR_SOLUTION_SHOULD_BE_WRITTEN_BELOW_THIS_LINE, between curly braces \"{\" and \"}\" */\n\n\t{\n\t\tvar L,R := (A + B) + C, A + (B + C);\n\t\tforall x | x in L ensures x in R\n\t\t{\n\n\t\t}\n\t\n\t\t\tforall x | x in R ensures x in L\n\t\t{\n\t\t}\n\t}\n\n\n/* Question/Exercise 4 of 4 */\n/*\n\tRecall from \"SquareOfIntegersIsNotMonotonic\" in lecture05.dfy how a lemma that returns results\n\tcan be used to disprove a claim by providing evidence for its negation;\n\tsimilarly, your goal here is to choose values for A,B,C and demonstrate (using assertions or the \"calc\" construct)\n\thow when performing the set difference operation twice, the order of operations DOES matter!\n\n\tYOUR_SOLUTION_SHOULD_BE_WRITTEN_BELOW_THIS_LINE, between curly braces \"{\" and \"}\" */\n\t\nlemma preparation_for_Q4_SetDifferenceIs_NOT_Associative()\n\tensures !forall A: set, B: set, C: set :: (A - B) - C == A - (B - C)\n{\n\t\tvar A, B, C := Q4_Evidence_That_SetDifferenceIs_NOT_Associative();\n\t}\n}\n\nlemma Q4_Evidence_That_SetDifferenceIs_NOT_Associative() returns (A: set, B: set, C: set)\n\tensures (A - B) - C != A - (B - C)\n\t{\n\t\tA:= {6,3,7};\n\t\tB:= {1,6};\n\t\tC:= {3,2,5};\n calc\n {\n\t(A - B) - C != A - (B - C);\n\t==\n\t({6,3,7} - {1,6}) - {3,2,5} != {6,3,7} - ({1,6} - {3,2,5});\n\t==\n\t( {7} != {3,7} );\n\t==\n\ttrue;\n\n }\n\t}\n" }, { "test_ID": "694", "test_file": "groupTheory_tmp_tmppmmxvu8h_tutorial2.dfy", "ground_truth": "ghost method M1()\n{\n\tassert 1 != 3;\n\n//\tassert 1 == 2;\n\tassume 1 == 2;\n\tassert 1 == 2;\n}\n\nlemma IntersectionIsSubsetOfBoth(A: set, B: set, C: set)\n\trequires C == A*B\n\tensures C <= A && C <= B\n{}\n\nlemma BothSetsAreSubsetsOfTheirUnion(A: set, B: set, C: set)\n\trequires C == A+B\n\tensures A <= C && B <= C\n{}\n\nconst s0 := {3,8,1}\n//var s2 := {4,5}\n\nlemma M2()\n{\n\tvar s1 := {2,4,6,8};\n\tassert |s1| == 4;\n\t//s0 := {4,1,2};\n\ts1 := {};\n\tassert |s1| == 0;\n\tassert s1 <= s0;\n}\n\nlemma TheEmptySetIsASubsetOfAnySet(A: set, B: set)\n\trequires A == {}\n\tensures A <= B // same as writing: B >= A\n{}\n\nlemma AnySetIsASubsetOfItself(A: set)\n\tensures A <= A\n{}\n\nlemma TheIntersectionOfTwoSetsIsASubsetOfTheirUnion(A: set, B: set, C: set, D: set)\n\trequires C == A*B && D == A+B\n\tensures C <= D\n{\n\tassert C <= A by { assert C == A*B; IntersectionIsSubsetOfBoth(A, B, C); }\n\tassert A <= D by { assert D == A+B; BothSetsAreSubsetsOfTheirUnion(A, B, D); }\n}\n\n", "hints_removed": "ghost method M1()\n{\n\n//\tassert 1 == 2;\n\tassume 1 == 2;\n}\n\nlemma IntersectionIsSubsetOfBoth(A: set, B: set, C: set)\n\trequires C == A*B\n\tensures C <= A && C <= B\n{}\n\nlemma BothSetsAreSubsetsOfTheirUnion(A: set, B: set, C: set)\n\trequires C == A+B\n\tensures A <= C && B <= C\n{}\n\nconst s0 := {3,8,1}\n//var s2 := {4,5}\n\nlemma M2()\n{\n\tvar s1 := {2,4,6,8};\n\t//s0 := {4,1,2};\n\ts1 := {};\n}\n\nlemma TheEmptySetIsASubsetOfAnySet(A: set, B: set)\n\trequires A == {}\n\tensures A <= B // same as writing: B >= A\n{}\n\nlemma AnySetIsASubsetOfItself(A: set)\n\tensures A <= A\n{}\n\nlemma TheIntersectionOfTwoSetsIsASubsetOfTheirUnion(A: set, B: set, C: set, D: set)\n\trequires C == A*B && D == A+B\n\tensures C <= D\n{\n}\n\n" }, { "test_ID": "695", "test_file": "groupTheory_tmp_tmppmmxvu8h_yair_yair2.dfy", "ground_truth": "\n///////////////////////////\n// Lemma to prove Transitive\n// Got A n in B // same as the next line\n\t//forall n :: if n in A then n in B else true // same as \"A <= B\"\n}\n// lemma - \u05de\u05e9\u05e4\u05d8\n// subsetIsTransitive - lemma name.\n// (A: set, B: set, C: set) - parameters using in lemma.\n// \"A\" - parameter name, \": set \" - parameter type (set = group).\nlemma subsetIsTransitive(A: set, B: set, C: set)\n // requires - \u05d4\u05e0\u05ea\u05d5\u05df/\u05d4\u05d3\u05e8\u05d9\u05e9\u05d4 \u05e9\u05dc \u05d4\u05d8\u05e2\u05e0\u05d4 \n // \"Pre1\" - label,require \u05d4\u05ea\u05d5\u05d9\u05ea \u05e9\u05dc \n // \"IsSubset\" - function name. \"(A, B)\" function parameters\n requires Pre1 : IsSubset(A, B)\n requires Pre2 : IsSubset(B, C)\n // ensures - \u05f4\u05de\u05d1\u05d8\u05d9\u05d7 \u05dc\u05d9\u05f4- \u05e6\u05e8\u05d9\u05da \u05dc\u05d4\u05d5\u05db\u05d9\u05d7\n ensures IsSubset(A, C)\n// Start of ensure - \u05ea\u05d7\u05d9\u05dc\u05ea \u05d4\u05d4\u05d5\u05db\u05d7\u05d4\n{\n // forall - \u05dc\u05db\u05dc X\n // \"x in A\" - \u05db\u05da \u05e9x \u05e9\u05d9\u05d9\u05da \u05dc A,\n // ensures x in C - \u05de\u05d1\u05d8\u05d9\u05d7 \u05e9X \u05e9\u05d9\u05d9\u05da \u05dcC\n forall x | x in A ensures x in C {\n // assert - \u05d8\u05e2\u05e0\u05d4 + label \"3\"\n assert 3: x in A;\n // can't just tell x n in B // same as the next line\n\t//forall n :: if n in A then n in B else true // same as \"A <= B\"\n}\n// lemma - \u05de\u05e9\u05e4\u05d8\n// subsetIsTransitive - lemma name.\n// (A: set, B: set, C: set) - parameters using in lemma.\n// \"A\" - parameter name, \": set \" - parameter type (set = group).\nlemma subsetIsTransitive(A: set, B: set, C: set)\n // requires - \u05d4\u05e0\u05ea\u05d5\u05df/\u05d4\u05d3\u05e8\u05d9\u05e9\u05d4 \u05e9\u05dc \u05d4\u05d8\u05e2\u05e0\u05d4 \n // \"Pre1\" - label,require \u05d4\u05ea\u05d5\u05d9\u05ea \u05e9\u05dc \n // \"IsSubset\" - function name. \"(A, B)\" function parameters\n requires Pre1 : IsSubset(A, B)\n requires Pre2 : IsSubset(B, C)\n // ensures - \u05f4\u05de\u05d1\u05d8\u05d9\u05d7 \u05dc\u05d9\u05f4- \u05e6\u05e8\u05d9\u05da \u05dc\u05d4\u05d5\u05db\u05d9\u05d7\n ensures IsSubset(A, C)\n// Start of ensure - \u05ea\u05d7\u05d9\u05dc\u05ea \u05d4\u05d4\u05d5\u05db\u05d7\u05d4\n{\n // forall - \u05dc\u05db\u05dc X\n // \"x in A\" - \u05db\u05da \u05e9x \u05e9\u05d9\u05d9\u05da \u05dc A,\n // ensures x in C - \u05de\u05d1\u05d8\u05d9\u05d7 \u05e9X \u05e9\u05d9\u05d9\u05da \u05dcC\n forall x | x in A ensures x in C {\n // assert - \u05d8\u05e2\u05e0\u05d4 + label \"3\"\n // can't just tell x,\n// it: LinearMutableMap.Iterator,\n// m0: LinearMutableMap.LinearHashMap)\n// : (m' : LinearMutableMap.LinearHashMap)\n// requires LinearMutableMap.Inv(m)\n// requires LinearMutableMap.WFIter(m, it)\n// requires LinearMutableMap.Inv(m0)\n// requires m0.contents.Keys == it.s\n// ensures LinearMutableMap.Inv(m')\n// decreases it.decreaser\n// {\n// if it.next.Done? then\n// m0\n// else (\n// LinearMutableMap.LemmaIterIndexLtCount(m, it);\n// LinearMutableMap.CountBound(m);\n// SyncReqs2to1Iterate(\n// m,\n// LinearMutableMap.IterInc(m, it),\n// LinearMutableMap.Insert(m0, it.next.key,\n// (if it.next.value == JC.State2 then JC.State1 else it.next.value))\n// )\n// )\n// }\n\n// function {:opaque} SyncReqs2to1(m: LinearMutableMap.LinearHashMap)\n// : (m' : LinearMutableMap.LinearHashMap)\n// requires LinearMutableMap.Inv(m)\n// ensures LinearMutableMap.Inv(m')\n// {\n// SyncReqs2to1Iterate(m,\n// LinearMutableMap.IterStart(m),\n// LinearMutableMap.Constructor(128))\n// }\n\n// lemma SyncReqs2to1Correct(m: LinearMutableMap.LinearHashMap)\n// requires LinearMutableMap.Inv(m)\n// ensures SyncReqs2to1(m).contents == JC.syncReqs2to1(m.contents)\n// {\n// reveal_SyncReqs2to1();\n// var it := LinearMutableMap.IterStart(m);\n// var m0 := LinearMutableMap.Constructor(128);\n// while !it.next.Done?\n// invariant LinearMutableMap.Inv(m)\n// invariant LinearMutableMap.WFIter(m, it)\n// invariant LinearMutableMap.Inv(m0)\n// invariant m0.contents.Keys == it.s\n// invariant forall id | id in it.s ::\n// m0.contents[id] == (if m.contents[id] == JC.State2 then JC.State1 else m.contents[id])\n// invariant SyncReqs2to1(m) == SyncReqs2to1Iterate(m, it, m0)\n// decreases it.decreaser\n// {\n// LinearMutableMap.LemmaIterIndexLtCount(m, it);\n// LinearMutableMap.CountBound(m);\n// m0 := LinearMutableMap.Insert(m0, it.next.key,\n// (if it.next.value == JC.State2 then JC.State1 else it.next.value));\n// it := LinearMutableMap.IterInc(m, it);\n// }\n// }\n\n// function SyncReqs3to2Iterate(\n// m: LinearMutableMap.LinearHashMap,\n// it: LinearMutableMap.Iterator,\n// m0: LinearMutableMap.LinearHashMap)\n// : (m' : LinearMutableMap.LinearHashMap)\n// requires LinearMutableMap.Inv(m)\n// requires LinearMutableMap.WFIter(m, it)\n// requires LinearMutableMap.Inv(m0)\n// requires m0.contents.Keys == it.s\n// ensures LinearMutableMap.Inv(m')\n// decreases it.decreaser\n// {\n// if it.next.Done? then\n// m0\n// else (\n// LinearMutableMap.LemmaIterIndexLtCount(m, it);\n// LinearMutableMap.CountBound(m);\n// SyncReqs3to2Iterate(\n// m,\n// LinearMutableMap.IterInc(m, it),\n// LinearMutableMap.Insert(m0, it.next.key,\n// (if it.next.value == JC.State3 then JC.State2 else it.next.value))\n// )\n// )\n// }\n\n// function {:opaque} SyncReqs3to2(m: LinearMutableMap.LinearHashMap)\n// : (m' : LinearMutableMap.LinearHashMap)\n// requires LinearMutableMap.Inv(m)\n// ensures LinearMutableMap.Inv(m')\n// {\n// SyncReqs3to2Iterate(m,\n// LinearMutableMap.IterStart(m),\n// LinearMutableMap.Constructor(128))\n// }\n\n// lemma SyncReqs3to2Correct(m: LinearMutableMap.LinearHashMap)\n// requires LinearMutableMap.Inv(m)\n// ensures SyncReqs3to2(m).contents == JC.syncReqs3to2(m.contents)\n// {\n// reveal_SyncReqs3to2();\n// var it := LinearMutableMap.IterStart(m);\n// var m0 := LinearMutableMap.Constructor(128);\n// while !it.next.Done?\n// invariant LinearMutableMap.Inv(m)\n// invariant LinearMutableMap.WFIter(m, it)\n// invariant LinearMutableMap.Inv(m0)\n// invariant m0.contents.Keys == it.s\n// invariant forall id | id in it.s ::\n// m0.contents[id] == (if m.contents[id] == JC.State3 then JC.State2 else m.contents[id])\n// invariant SyncReqs3to2(m) == SyncReqs3to2Iterate(m, it, m0)\n// decreases it.decreaser\n// {\n// LinearMutableMap.LemmaIterIndexLtCount(m, it);\n// LinearMutableMap.CountBound(m);\n// m0 := LinearMutableMap.Insert(m0, it.next.key,\n// (if it.next.value == JC.State3 then JC.State2 else it.next.value));\n// it := LinearMutableMap.IterInc(m, it);\n// }\n// }\n\n // function {:opaque} WriteOutJournal(cm: CM, io: IO)\n // : (res : (CM, IO))\n // requires io.IOInit?\n // requires CommitterModel.WF(cm)\n // requires JournalistModel.I(cm.journalist).inMemoryJournalFrozen != []\n // || JournalistModel.I(cm.journalist).inMemoryJournal != []\n // {\n // var writtenJournalLen :=\n // JournalistModel.getWrittenJournalLen(cm.journalist);\n\n // var doingFrozen :=\n // JournalistModel.hasFrozenJournal(cm.journalist);\n\n // var (journalist', j) :=\n // if doingFrozen then\n // JournalistModel.packageFrozenJournal(cm.journalist)\n // else\n // JournalistModel.packageInMemoryJournal(cm.journalist);\n\n // var start := start_pos_add(\n // cm.superblock.journalStart,\n // writtenJournalLen);\n\n // var len := |j| as uint64 / 4096;\n\n // var contiguous := start + len <= NumJournalBlocks();\n\n // var io' := if contiguous then\n // IOReqWrite(io.id, D.ReqWrite(JournalPoint(start), j))\n // else (\n // var cut := (NumJournalBlocks() - start) * 4096;\n // IOReqWrite2(io.id, io.id2,\n // D.ReqWrite(JournalPoint(start), j[..cut]),\n // D.ReqWrite(JournalPoint(0), j[cut..]))\n // );\n\n // var outstandingJournalWrites' := if contiguous\n // then cm.outstandingJournalWrites + {io.id}\n // else cm.outstandingJournalWrites + {io.id, io.id2};\n\n // var frozenJournalPosition' := if doingFrozen\n // then JournalistModel.getWrittenJournalLen(journalist')\n // else cm.frozenJournalPosition;\n\n // var syncReqs' := if doingFrozen\n // then cm.syncReqs\n // else SyncReqs3to2(cm.syncReqs);\n\n // var cm' := cm\n // .(outstandingJournalWrites := outstandingJournalWrites')\n // .(journalist := journalist')\n // .(frozenJournalPosition := frozenJournalPosition')\n // .(syncReqs := syncReqs');\n\n // (cm', io')\n // }\n\n // lemma WriteOutJournalCorrect(cm: CM, io: IO)\n // requires WriteOutJournal.requires(cm, io)\n // requires cm.superblockWrite.None?\n // ensures var (cm', io') := WriteOutJournal(cm, io);\n // && CommitterModel.WF(cm')\n // && ValidDiskOp(diskOp(io'))\n // && IDiskOp(diskOp(io')).bdop.NoDiskOp?\n // && JC.Next(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io')).jdop,\n // JournalInternalOp)\n // {\n // var (cm', io') := WriteOutJournal(cm, io);\n // reveal_WriteOutJournal();\n\n // var writtenJournalLen :=\n // JournalistModel.getWrittenJournalLen(cm.journalist);\n\n // var doingFrozen :=\n // JournalistModel.hasFrozenJournal(cm.journalist);\n\n // var (journalist', j) :=\n // if doingFrozen then\n // JournalistModel.packageFrozenJournal(cm.journalist)\n // else\n // JournalistModel.packageInMemoryJournal(cm.journalist);\n\n // var start := start_pos_add(\n // cm.superblock.journalStart,\n // writtenJournalLen);\n\n // var jr := JournalRangeOfByteSeq(j).value;\n // var len := |j| as uint64 / 4096;\n // var contiguous := start + len <= NumJournalBlocks();\n\n // assert |jr| == len as int;\n\n // if contiguous {\n // assert LocOfReqWrite(diskOp(io').reqWrite)\n // == JournalRangeLocation(start, len);\n // assert ValidDiskOp(diskOp(io'));\n // } else {\n // assert LocOfReqWrite(diskOp(io').reqWrite1)\n // == JournalRangeLocation(start, NumJournalBlocks() - start);\n // assert LocOfReqWrite(diskOp(io').reqWrite2)\n // == JournalRangeLocation(0, len - (NumJournalBlocks() - start));\n // JournalBytesSplit(j, len as int,\n // NumJournalBlocks() as int - start as int);\n // assert ValidDiskOp(diskOp(io'));\n // }\n\n // SyncReqs3to2Correct(cm.syncReqs);\n\n // assert JC.WriteBackJournalReq(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io')).jdop,\n // JournalInternalOp,\n // jr);\n // assert JC.NextStep(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io')).jdop,\n // JournalInternalOp,\n // JC.WriteBackJournalReqStep(jr));\n // }\n\n // predicate writeOutSuperblockAdvanceLog(cm: CM, io: IO,\n // cm': CM, io': IO)\n // requires io.IOInit?\n // requires CommitterModel.WF(cm)\n // {\n // var writtenJournalLen :=\n // JournalistModel.getWrittenJournalLen(cm.journalist);\n // var newSuperblock := SectorType.Superblock(\n // JC.IncrementSuperblockCounter(cm.superblock.counter),\n // cm.superblock.journalStart,\n // writtenJournalLen,\n // cm.superblock.indirectionTableLoc\n // );\n\n // var loc := if cm.whichSuperblock == 0 then Superblock2Location() else Superblock1Location();\n\n // && cm'.superblockWrite.Some?\n // && var id := cm'.superblockWrite.value;\n\n // && RequestWrite(io, loc, SSM.SectorSuperblock(newSuperblock),\n // id, io')\n // && cm' == cm\n // .(newSuperblock := Some(newSuperblock))\n // .(superblockWrite := Some(id))\n // .(commitStatus := JC.CommitAdvanceLog)\n // }\n\n // lemma writeOutSuperblockAdvanceLogCorrect(cm: CM, io: IO,\n // cm': CM, io': IO)\n // requires io.IOInit?\n // requires CommitterModel.WF(cm)\n // requires writeOutSuperblockAdvanceLog(cm, io, cm', io')\n // requires cm.status == StatusReady\n // requires cm.commitStatus.CommitNone?\n // requires cm.outstandingJournalWrites == {}\n // requires JournalistModel.I(cm.journalist).inMemoryJournalFrozen == []\n // ensures CommitterModel.WF(cm')\n // ensures ValidDiskOp(diskOp(io'))\n // ensures IDiskOp(diskOp(io')).bdop.NoDiskOp?\n // ensures JC.Next(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io')).jdop,\n // JournalInternalOp)\n // {\n // var writtenJournalLen :=\n // JournalistModel.getWrittenJournalLen(cm.journalist);\n // var newSuperblock := SectorType.Superblock(\n // JC.IncrementSuperblockCounter(cm.superblock.counter),\n // cm.superblock.journalStart,\n // writtenJournalLen,\n // cm.superblock.indirectionTableLoc\n // );\n // assert JC.WFSuperblock(newSuperblock);\n\n // var loc := if cm.whichSuperblock == 0 then Superblock2Location() else Superblock1Location();\n\n // var id := cm'.superblockWrite.value;\n\n // RequestWriteCorrect(io, loc, SSM.SectorSuperblock(newSuperblock),\n // id, io');\n\n // assert ValidDiskOp(diskOp(io'));\n\n // assert JC.WriteBackSuperblockReq_AdvanceLog(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io')).jdop,\n // JournalInternalOp);\n // assert JC.NextStep(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io')).jdop,\n // JournalInternalOp,\n // JC.WriteBackSuperblockReq_AdvanceLog_Step);\n // }\n\n // predicate {:opaque} writeOutSuperblockAdvanceLocation(cm: CM, io: IO,\n // cm': CM, io': IO)\n // requires io.IOInit?\n // requires CommitterModel.Inv(cm)\n // requires cm.status == StatusReady\n // requires cm.frozenLoc.Some?\n // {\n // var writtenJournalLen :=\n // JournalistModel.getWrittenJournalLen(cm.journalist);\n // var newSuperblock := SectorType.Superblock(\n // JC.IncrementSuperblockCounter(cm.superblock.counter),\n // start_pos_add(\n // cm.superblock.journalStart,\n // cm.frozenJournalPosition),\n // writtenJournalLen - cm.frozenJournalPosition,\n // cm.frozenLoc.value\n // );\n\n // var loc := if cm.whichSuperblock == 0 then Superblock2Location() else Superblock1Location();\n\n // && cm'.superblockWrite.Some?\n // && var id := cm'.superblockWrite.value;\n\n // && RequestWrite(io, loc, SSM.SectorSuperblock(newSuperblock),\n // id, io')\n // && cm' == cm\n // .(newSuperblock := Some(newSuperblock))\n // .(superblockWrite := Some(id))\n // .(commitStatus := JC.CommitAdvanceLocation)\n // }\n\n // lemma writeOutSuperblockAdvanceLocationCorrect(cm: CM, io: IO,\n // cm': CM, io': IO)\n // requires io.IOInit?\n // requires CommitterModel.Inv(cm)\n // requires cm.status == StatusReady\n // requires cm.frozenLoc.Some?\n // requires cm.commitStatus.CommitNone?\n // requires cm.outstandingJournalWrites == {}\n // requires writeOutSuperblockAdvanceLocation(cm, io, cm', io')\n // requires JournalistModel.I(cm.journalist).inMemoryJournalFrozen == []\n // ensures CommitterModel.WF(cm')\n // ensures ValidDiskOp(diskOp(io'))\n // ensures IDiskOp(diskOp(io')).bdop.NoDiskOp?\n // ensures JC.Next(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io')).jdop,\n // JournalInternalOp)\n // {\n // reveal_writeOutSuperblockAdvanceLocation();\n\n // var writtenJournalLen :=\n // JournalistModel.getWrittenJournalLen(cm.journalist);\n // var newSuperblock := SectorType.Superblock(\n // JC.IncrementSuperblockCounter(cm.superblock.counter),\n // start_pos_add(\n // cm.superblock.journalStart,\n // cm.frozenJournalPosition) as uint64,\n // (writtenJournalLen - cm.frozenJournalPosition) as uint64,\n // cm.frozenLoc.value\n // );\n // assert JC.WFSuperblock(newSuperblock);\n\n // var loc := if cm.whichSuperblock == 0 then Superblock2Location() else Superblock1Location();\n\n // var id := cm'.superblockWrite.value;\n\n // RequestWriteCorrect(io, loc, SSM.SectorSuperblock(newSuperblock),\n // id, io');\n\n // assert ValidDiskOp(diskOp(io'));\n\n // assert JC.WriteBackSuperblockReq_AdvanceLocation(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io')).jdop,\n // JournalInternalOp);\n // assert JC.NextStep(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io')).jdop,\n // JournalInternalOp,\n // JC.WriteBackSuperblockReq_AdvanceLocation_Step);\n // }\n\n // function {:opaque} freeze(cm: CM) : (cm': CM)\n // requires CommitterModel.WF(cm)\n // {\n // var writtenJournalLen :=\n // JournalistModel.getWrittenJournalLen(cm.journalist);\n // cm.(frozenLoc := None)\n // .(journalist := JournalistModel.freeze(cm.journalist))\n // .(frozenJournalPosition := writtenJournalLen)\n // .(isFrozen := true)\n // .(syncReqs := SyncReqs3to2(cm.syncReqs))\n // }\n\n // lemma freezeCorrect(cm: CM)\n // requires CommitterModel.WF(cm)\n // requires cm.superblockWrite.None?\n\n // // Mostly we'll probably just do this with cm.frozenLoc == None\n // // but more generally we can do it whenever we have:\n // requires cm.status == StatusReady\n // requires cm.frozenLoc != Some(cm.superblock.indirectionTableLoc)\n // requires JournalistModel.I(cm.journalist).replayJournal == []\n\n // ensures var cm' := freeze(cm);\n // && CommitterModel.WF(cm')\n // && JC.Next(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // FreezeOp)\n // {\n // reveal_freeze();\n // var cm' := freeze(cm);\n // SyncReqs3to2Correct(cm.syncReqs);\n\n // assert JC.Freeze(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // FreezeOp);\n // assert JC.NextStep(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // FreezeOp,\n // JC.FreezeStep);\n // }\n\n // function {:opaque} receiveFrozenLoc(\n // cm: CM, loc: Location) : (cm': CM)\n // {\n // cm.(frozenLoc := Some(loc))\n // }\n\n // lemma receiveFrozenLocCorrect(cm: CM, loc: Location)\n // requires CommitterModel.WF(cm)\n // requires cm.status == StatusReady\n // requires cm.isFrozen\n // requires !cm.frozenLoc.Some?\n // requires ValidIndirectionTableLocation(loc)\n\n // ensures var cm' := receiveFrozenLoc(cm, loc);\n // && CommitterModel.WF(cm')\n // && JC.Next(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // SendFrozenLocOp(loc))\n // {\n // reveal_receiveFrozenLoc();\n // var cm' := receiveFrozenLoc(cm, loc);\n // assert JC.ReceiveFrozenLoc(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // SendFrozenLocOp(loc));\n // assert JC.NextStep(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // SendFrozenLocOp(loc),\n // JC.ReceiveFrozenLocStep);\n // }\n\n // // == pushSync ==\n\n // function {:opaque} freeId(syncReqs: LinearMutableMap.LinearHashMap) : (id: uint64)\n // requires LinearMutableMap.Inv(syncReqs)\n // ensures id != 0 ==> id !in syncReqs.contents\n // {\n // var maxId := LinearMutableMap.MaxKey(syncReqs);\n // if maxId == 0xffff_ffff_ffff_ffff then (\n // 0\n // ) else (\n // maxId + 1\n // )\n // }\n\n // function pushSync(cm: CM) : (CM, uint64)\n // requires CommitterModel.WF(cm)\n // {\n // var id := freeId(cm.syncReqs);\n // if id == 0 || cm.syncReqs.count as int >= 0x1_0000_0000_0000_0000 / 8 then (\n // (cm, 0)\n // ) else (\n // var cm' := cm.(syncReqs := LinearMutableMap.Insert(cm.syncReqs, id, JC.State3));\n // (cm', id)\n // )\n // }\n\n // lemma pushSyncCorrect(cm: CM)\n // requires CommitterModel.WF(cm)\n\n // ensures var (cm', id) := pushSync(cm);\n // && CommitterModel.WF(cm')\n // && JC.Next(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // if id == 0 then JournalInternalOp else PushSyncOp(id as int))\n // {\n // var (cm', id) := pushSync(cm);\n // if id == 0 || cm.syncReqs.count as int >= 0x1_0000_0000_0000_0000 / 8 {\n // assert JC.NoOp(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // JournalInternalOp);\n // assert JC.NextStep(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // JournalInternalOp,\n // JC.NoOpStep);\n // } else {\n // assert JC.PushSyncReq(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // PushSyncOp(id as int), id);\n // assert JC.NextStep(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // PushSyncOp(id as int),\n // JC.PushSyncReqStep(id));\n // }\n // }\n\n // // == popSync ==\n\n // function {:opaque} popSync(cm: CM, id: uint64) : (cm' : CM)\n // requires CommitterModel.WF(cm)\n // {\n // cm.(syncReqs := LinearMutableMap.Remove(cm.syncReqs, id))\n // }\n\n // lemma popSyncCorrect(cm: CM, id: uint64)\n // requires CommitterModel.WF(cm)\n // requires id in cm.syncReqs.contents\n // requires cm.syncReqs.contents[id] == JC.State1\n // ensures var cm' := popSync(cm, id);\n // && CommitterModel.WF(cm')\n // && JC.Next(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // PopSyncOp(id as int))\n // {\n // var cm' := popSync(cm, id);\n // reveal_popSync();\n // assert JC.PopSyncReq(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // PopSyncOp(id as int), id);\n // assert JC.NextStep(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // PopSyncOp(id as int),\n // JC.PopSyncReqStep(id));\n // }\n\n // // == AdvanceLog ==\n\n // predicate {:opaque} tryAdvanceLog(cm: CM, io: IO,\n // cm': CM, io': IO)\n // requires CommitterModel.WF(cm)\n // requires io.IOInit?\n // {\n // var hasFrozen := JournalistModel.hasFrozenJournal(cm.journalist);\n // var hasInMem := JournalistModel.hasInMemoryJournal(cm.journalist);\n // if cm.superblockWrite.None? then (\n // if hasFrozen || hasInMem then (\n // (cm', io') == WriteOutJournal(cm, io)\n // ) else if cm.outstandingJournalWrites == {} then (\n // writeOutSuperblockAdvanceLog(cm, io, cm', io')\n // ) else (\n // && cm' == cm\n // && io' == io\n // )\n // ) else (\n // && cm' == cm\n // && io' == io\n // )\n // }\n\n // lemma tryAdvanceLogCorrect(cm: CM, io: IO,\n // cm': CM, io': IO)\n // requires CommitterModel.Inv(cm)\n // requires io.IOInit?\n // requires cm.status.StatusReady?\n // requires tryAdvanceLog(cm, io, cm', io')\n // ensures CommitterModel.WF(cm')\n // ensures ValidDiskOp(diskOp(io'))\n // ensures IDiskOp(diskOp(io')).bdop.NoDiskOp?\n // ensures JC.Next(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io')).jdop,\n // JournalInternalOp)\n // {\n // reveal_tryAdvanceLog();\n // var hasFrozen := JournalistModel.hasFrozenJournal(cm.journalist);\n // var hasInMem := JournalistModel.hasInMemoryJournal(cm.journalist);\n // if cm.superblockWrite.None? {\n // if hasFrozen || hasInMem {\n // WriteOutJournalCorrect(cm, io);\n // } else if (cm.outstandingJournalWrites == {}) {\n // writeOutSuperblockAdvanceLogCorrect(cm, io, cm', io');\n // } else {\n // assert JC.NoOp( CommitterModel.I(cm), CommitterModel.I(cm'), JournalDisk.NoDiskOp, JournalInternalOp);\n // assert JC.NextStep( CommitterModel.I(cm), CommitterModel.I(cm'), JournalDisk.NoDiskOp, JournalInternalOp, JC.NoOpStep);\n // }\n // } else {\n // assert JC.NoOp( CommitterModel.I(cm), CommitterModel.I(cm'), JournalDisk.NoDiskOp, JournalInternalOp);\n // assert JC.NextStep( CommitterModel.I(cm), CommitterModel.I(cm'), JournalDisk.NoDiskOp, JournalInternalOp, JC.NoOpStep);\n // }\n // }\n\n // predicate {:opaque} tryAdvanceLocation(cm: CM, io: IO,\n // cm': CM, io': IO)\n // requires CommitterModel.Inv(cm)\n // requires io.IOInit?\n // requires cm.status == StatusReady\n // requires cm.frozenLoc.Some?\n // {\n // var hasFrozen := JournalistModel.hasFrozenJournal(cm.journalist);\n // var hasInMem := JournalistModel.hasInMemoryJournal(cm.journalist);\n // if cm.superblockWrite.None? then (\n // if hasFrozen || hasInMem then (\n // (cm', io') == WriteOutJournal(cm, io)\n // ) else if cm.outstandingJournalWrites == {} then (\n // writeOutSuperblockAdvanceLocation(cm, io, cm', io')\n // ) else (\n // && cm' == cm\n // && io' == io\n // )\n // ) else (\n // && cm' == cm\n // && io' == io\n // )\n // }\n\n // lemma tryAdvanceLocationCorrect(cm: CM, io: IO,\n // cm': CM, io': IO)\n // requires CommitterModel.Inv(cm)\n // requires io.IOInit?\n // requires cm.status.StatusReady?\n // requires cm.frozenLoc.Some?\n // requires tryAdvanceLocation(cm, io, cm', io')\n // ensures CommitterModel.WF(cm')\n // ensures ValidDiskOp(diskOp(io'))\n // ensures IDiskOp(diskOp(io')).bdop.NoDiskOp?\n // ensures JC.Next(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io')).jdop,\n // JournalInternalOp)\n // {\n // reveal_tryAdvanceLocation();\n // var hasFrozen := JournalistModel.hasFrozenJournal(cm.journalist);\n // var hasInMem := JournalistModel.hasInMemoryJournal(cm.journalist);\n // if cm.superblockWrite.None? {\n // if hasFrozen || hasInMem {\n // WriteOutJournalCorrect(cm, io);\n // } else if (cm.outstandingJournalWrites == {}) {\n // writeOutSuperblockAdvanceLocationCorrect(cm, io, cm', io');\n // } else {\n // assert JC.NoOp( CommitterModel.I(cm), CommitterModel.I(cm'), JournalDisk.NoDiskOp, JournalInternalOp);\n // assert JC.NextStep( CommitterModel.I(cm), CommitterModel.I(cm'), JournalDisk.NoDiskOp, JournalInternalOp, JC.NoOpStep);\n // }\n // } else {\n // assert JC.NoOp( CommitterModel.I(cm), CommitterModel.I(cm'), JournalDisk.NoDiskOp, JournalInternalOp);\n // assert JC.NextStep( CommitterModel.I(cm), CommitterModel.I(cm'), JournalDisk.NoDiskOp, JournalInternalOp, JC.NoOpStep);\n // }\n // }\n\n // function {:opaque} writeBackSuperblockResp(\n // cm: CommitterModel.CM) : CommitterModel.CM\n // requires CommitterModel.Inv(cm)\n // {\n // if cm.status.StatusReady? &&\n // cm.commitStatus.CommitAdvanceLocation? then (\n // cm.(superblockWrite := None)\n // .(superblock := cm.newSuperblock.value)\n // .(newSuperblock := None)\n // .(whichSuperblock := if cm.whichSuperblock == 0 then 1 else 0)\n // .(syncReqs := SyncReqs2to1(cm.syncReqs))\n // .(journalist :=\n // JournalistModel.updateWrittenJournalLen(\n // cm.journalist,\n // JournalistModel.getWrittenJournalLen(cm.journalist)\n // - cm.frozenJournalPosition\n // )\n // )\n // .(frozenJournalPosition := 0)\n // .(frozenLoc := None)\n // .(isFrozen := false)\n // .(commitStatus := JC.CommitNone)\n // )\n // else if cm.status.StatusReady? &&\n // cm.commitStatus.CommitAdvanceLog? then (\n // cm.(superblockWrite := None)\n // .(superblock := cm.newSuperblock.value)\n // .(newSuperblock := None)\n // .(whichSuperblock := if cm.whichSuperblock == 0 then 1 else 0)\n // .(syncReqs := SyncReqs2to1(cm.syncReqs))\n // .(commitStatus := JC.CommitNone)\n // )\n // else (\n // cm\n // )\n // }\n\n // lemma writeBackSuperblockRespCorrect(\n // cm: CommitterModel.CM, io: IO)\n // requires CommitterModel.Inv(cm)\n // requires ValidDiskOp(diskOp(io))\n // requires IDiskOp(diskOp(io)).jdop.RespWriteSuperblockOp?\n // requires Some(io.id) == cm.superblockWrite\n // ensures var cm' := writeBackSuperblockResp(cm);\n // && CommitterModel.WF(cm')\n // && JC.Next(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io)).jdop,\n // if cm.status.StatusReady? && cm.commitStatus.CommitAdvanceLocation? then CleanUpOp else JournalInternalOp\n // )\n // {\n // reveal_writeBackSuperblockResp();\n // var cm' := writeBackSuperblockResp(cm);\n // SyncReqs2to1Correct(cm.syncReqs);\n // if cm.status.StatusReady? &&\n // cm.commitStatus.CommitAdvanceLocation? {\n // assert JC.WriteBackSuperblockResp(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io)).jdop,\n // CleanUpOp);\n // assert JC.NextStep(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io)).jdop,\n // CleanUpOp,\n // JC.WriteBackSuperblockRespStep);\n // }\n // else if cm.status.StatusReady? &&\n // cm.commitStatus.CommitAdvanceLog? {\n // assert JC.WriteBackSuperblockResp(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io)).jdop,\n // JournalInternalOp);\n // assert JC.NextStep(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io)).jdop,\n // JournalInternalOp,\n // JC.WriteBackSuperblockRespStep);\n // }\n // else {\n // assert JC.NoOp(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io)).jdop,\n // JournalInternalOp);\n // assert JC.NextStep(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io)).jdop,\n // JournalInternalOp,\n // JC.NoOpStep);\n // }\n // }\n// }\n\n", "hints_removed": "// include \"IOModel.i.dfy\"\n// include \"../lib/DataStructures/LinearMutableMap.i.dfy\"\n\n// module CommitterCommitModel {\n// import opened NativeTypes\n// import opened Options\n\n// import opened DiskLayout\n// import opened InterpretationDiskOps\n// import opened ViewOp\n// import JC = JournalCache\n// import opened Journal\n// import opened JournalBytes\n// import opened DiskOpModel\n// import SectorType\n\n// import LinearMutableMap\n// // import opened StateModel\n// import opened IOModel\n\n// function SyncReqs2to1Iterate(\n// m: LinearMutableMap.LinearHashMap,\n// it: LinearMutableMap.Iterator,\n// m0: LinearMutableMap.LinearHashMap)\n// : (m' : LinearMutableMap.LinearHashMap)\n// requires LinearMutableMap.Inv(m)\n// requires LinearMutableMap.WFIter(m, it)\n// requires LinearMutableMap.Inv(m0)\n// requires m0.contents.Keys == it.s\n// ensures LinearMutableMap.Inv(m')\n// decreases it.decreaser\n// {\n// if it.next.Done? then\n// m0\n// else (\n// LinearMutableMap.LemmaIterIndexLtCount(m, it);\n// LinearMutableMap.CountBound(m);\n// SyncReqs2to1Iterate(\n// m,\n// LinearMutableMap.IterInc(m, it),\n// LinearMutableMap.Insert(m0, it.next.key,\n// (if it.next.value == JC.State2 then JC.State1 else it.next.value))\n// )\n// )\n// }\n\n// function {:opaque} SyncReqs2to1(m: LinearMutableMap.LinearHashMap)\n// : (m' : LinearMutableMap.LinearHashMap)\n// requires LinearMutableMap.Inv(m)\n// ensures LinearMutableMap.Inv(m')\n// {\n// SyncReqs2to1Iterate(m,\n// LinearMutableMap.IterStart(m),\n// LinearMutableMap.Constructor(128))\n// }\n\n// lemma SyncReqs2to1Correct(m: LinearMutableMap.LinearHashMap)\n// requires LinearMutableMap.Inv(m)\n// ensures SyncReqs2to1(m).contents == JC.syncReqs2to1(m.contents)\n// {\n// reveal_SyncReqs2to1();\n// var it := LinearMutableMap.IterStart(m);\n// var m0 := LinearMutableMap.Constructor(128);\n// while !it.next.Done?\n// invariant LinearMutableMap.Inv(m)\n// invariant LinearMutableMap.WFIter(m, it)\n// invariant LinearMutableMap.Inv(m0)\n// invariant m0.contents.Keys == it.s\n// invariant forall id | id in it.s ::\n// m0.contents[id] == (if m.contents[id] == JC.State2 then JC.State1 else m.contents[id])\n// invariant SyncReqs2to1(m) == SyncReqs2to1Iterate(m, it, m0)\n// decreases it.decreaser\n// {\n// LinearMutableMap.LemmaIterIndexLtCount(m, it);\n// LinearMutableMap.CountBound(m);\n// m0 := LinearMutableMap.Insert(m0, it.next.key,\n// (if it.next.value == JC.State2 then JC.State1 else it.next.value));\n// it := LinearMutableMap.IterInc(m, it);\n// }\n// }\n\n// function SyncReqs3to2Iterate(\n// m: LinearMutableMap.LinearHashMap,\n// it: LinearMutableMap.Iterator,\n// m0: LinearMutableMap.LinearHashMap)\n// : (m' : LinearMutableMap.LinearHashMap)\n// requires LinearMutableMap.Inv(m)\n// requires LinearMutableMap.WFIter(m, it)\n// requires LinearMutableMap.Inv(m0)\n// requires m0.contents.Keys == it.s\n// ensures LinearMutableMap.Inv(m')\n// decreases it.decreaser\n// {\n// if it.next.Done? then\n// m0\n// else (\n// LinearMutableMap.LemmaIterIndexLtCount(m, it);\n// LinearMutableMap.CountBound(m);\n// SyncReqs3to2Iterate(\n// m,\n// LinearMutableMap.IterInc(m, it),\n// LinearMutableMap.Insert(m0, it.next.key,\n// (if it.next.value == JC.State3 then JC.State2 else it.next.value))\n// )\n// )\n// }\n\n// function {:opaque} SyncReqs3to2(m: LinearMutableMap.LinearHashMap)\n// : (m' : LinearMutableMap.LinearHashMap)\n// requires LinearMutableMap.Inv(m)\n// ensures LinearMutableMap.Inv(m')\n// {\n// SyncReqs3to2Iterate(m,\n// LinearMutableMap.IterStart(m),\n// LinearMutableMap.Constructor(128))\n// }\n\n// lemma SyncReqs3to2Correct(m: LinearMutableMap.LinearHashMap)\n// requires LinearMutableMap.Inv(m)\n// ensures SyncReqs3to2(m).contents == JC.syncReqs3to2(m.contents)\n// {\n// reveal_SyncReqs3to2();\n// var it := LinearMutableMap.IterStart(m);\n// var m0 := LinearMutableMap.Constructor(128);\n// while !it.next.Done?\n// invariant LinearMutableMap.Inv(m)\n// invariant LinearMutableMap.WFIter(m, it)\n// invariant LinearMutableMap.Inv(m0)\n// invariant m0.contents.Keys == it.s\n// invariant forall id | id in it.s ::\n// m0.contents[id] == (if m.contents[id] == JC.State3 then JC.State2 else m.contents[id])\n// invariant SyncReqs3to2(m) == SyncReqs3to2Iterate(m, it, m0)\n// decreases it.decreaser\n// {\n// LinearMutableMap.LemmaIterIndexLtCount(m, it);\n// LinearMutableMap.CountBound(m);\n// m0 := LinearMutableMap.Insert(m0, it.next.key,\n// (if it.next.value == JC.State3 then JC.State2 else it.next.value));\n// it := LinearMutableMap.IterInc(m, it);\n// }\n// }\n\n // function {:opaque} WriteOutJournal(cm: CM, io: IO)\n // : (res : (CM, IO))\n // requires io.IOInit?\n // requires CommitterModel.WF(cm)\n // requires JournalistModel.I(cm.journalist).inMemoryJournalFrozen != []\n // || JournalistModel.I(cm.journalist).inMemoryJournal != []\n // {\n // var writtenJournalLen :=\n // JournalistModel.getWrittenJournalLen(cm.journalist);\n\n // var doingFrozen :=\n // JournalistModel.hasFrozenJournal(cm.journalist);\n\n // var (journalist', j) :=\n // if doingFrozen then\n // JournalistModel.packageFrozenJournal(cm.journalist)\n // else\n // JournalistModel.packageInMemoryJournal(cm.journalist);\n\n // var start := start_pos_add(\n // cm.superblock.journalStart,\n // writtenJournalLen);\n\n // var len := |j| as uint64 / 4096;\n\n // var contiguous := start + len <= NumJournalBlocks();\n\n // var io' := if contiguous then\n // IOReqWrite(io.id, D.ReqWrite(JournalPoint(start), j))\n // else (\n // var cut := (NumJournalBlocks() - start) * 4096;\n // IOReqWrite2(io.id, io.id2,\n // D.ReqWrite(JournalPoint(start), j[..cut]),\n // D.ReqWrite(JournalPoint(0), j[cut..]))\n // );\n\n // var outstandingJournalWrites' := if contiguous\n // then cm.outstandingJournalWrites + {io.id}\n // else cm.outstandingJournalWrites + {io.id, io.id2};\n\n // var frozenJournalPosition' := if doingFrozen\n // then JournalistModel.getWrittenJournalLen(journalist')\n // else cm.frozenJournalPosition;\n\n // var syncReqs' := if doingFrozen\n // then cm.syncReqs\n // else SyncReqs3to2(cm.syncReqs);\n\n // var cm' := cm\n // .(outstandingJournalWrites := outstandingJournalWrites')\n // .(journalist := journalist')\n // .(frozenJournalPosition := frozenJournalPosition')\n // .(syncReqs := syncReqs');\n\n // (cm', io')\n // }\n\n // lemma WriteOutJournalCorrect(cm: CM, io: IO)\n // requires WriteOutJournal.requires(cm, io)\n // requires cm.superblockWrite.None?\n // ensures var (cm', io') := WriteOutJournal(cm, io);\n // && CommitterModel.WF(cm')\n // && ValidDiskOp(diskOp(io'))\n // && IDiskOp(diskOp(io')).bdop.NoDiskOp?\n // && JC.Next(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io')).jdop,\n // JournalInternalOp)\n // {\n // var (cm', io') := WriteOutJournal(cm, io);\n // reveal_WriteOutJournal();\n\n // var writtenJournalLen :=\n // JournalistModel.getWrittenJournalLen(cm.journalist);\n\n // var doingFrozen :=\n // JournalistModel.hasFrozenJournal(cm.journalist);\n\n // var (journalist', j) :=\n // if doingFrozen then\n // JournalistModel.packageFrozenJournal(cm.journalist)\n // else\n // JournalistModel.packageInMemoryJournal(cm.journalist);\n\n // var start := start_pos_add(\n // cm.superblock.journalStart,\n // writtenJournalLen);\n\n // var jr := JournalRangeOfByteSeq(j).value;\n // var len := |j| as uint64 / 4096;\n // var contiguous := start + len <= NumJournalBlocks();\n\n // assert |jr| == len as int;\n\n // if contiguous {\n // assert LocOfReqWrite(diskOp(io').reqWrite)\n // == JournalRangeLocation(start, len);\n // assert ValidDiskOp(diskOp(io'));\n // } else {\n // assert LocOfReqWrite(diskOp(io').reqWrite1)\n // == JournalRangeLocation(start, NumJournalBlocks() - start);\n // assert LocOfReqWrite(diskOp(io').reqWrite2)\n // == JournalRangeLocation(0, len - (NumJournalBlocks() - start));\n // JournalBytesSplit(j, len as int,\n // NumJournalBlocks() as int - start as int);\n // assert ValidDiskOp(diskOp(io'));\n // }\n\n // SyncReqs3to2Correct(cm.syncReqs);\n\n // assert JC.WriteBackJournalReq(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io')).jdop,\n // JournalInternalOp,\n // jr);\n // assert JC.NextStep(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io')).jdop,\n // JournalInternalOp,\n // JC.WriteBackJournalReqStep(jr));\n // }\n\n // predicate writeOutSuperblockAdvanceLog(cm: CM, io: IO,\n // cm': CM, io': IO)\n // requires io.IOInit?\n // requires CommitterModel.WF(cm)\n // {\n // var writtenJournalLen :=\n // JournalistModel.getWrittenJournalLen(cm.journalist);\n // var newSuperblock := SectorType.Superblock(\n // JC.IncrementSuperblockCounter(cm.superblock.counter),\n // cm.superblock.journalStart,\n // writtenJournalLen,\n // cm.superblock.indirectionTableLoc\n // );\n\n // var loc := if cm.whichSuperblock == 0 then Superblock2Location() else Superblock1Location();\n\n // && cm'.superblockWrite.Some?\n // && var id := cm'.superblockWrite.value;\n\n // && RequestWrite(io, loc, SSM.SectorSuperblock(newSuperblock),\n // id, io')\n // && cm' == cm\n // .(newSuperblock := Some(newSuperblock))\n // .(superblockWrite := Some(id))\n // .(commitStatus := JC.CommitAdvanceLog)\n // }\n\n // lemma writeOutSuperblockAdvanceLogCorrect(cm: CM, io: IO,\n // cm': CM, io': IO)\n // requires io.IOInit?\n // requires CommitterModel.WF(cm)\n // requires writeOutSuperblockAdvanceLog(cm, io, cm', io')\n // requires cm.status == StatusReady\n // requires cm.commitStatus.CommitNone?\n // requires cm.outstandingJournalWrites == {}\n // requires JournalistModel.I(cm.journalist).inMemoryJournalFrozen == []\n // ensures CommitterModel.WF(cm')\n // ensures ValidDiskOp(diskOp(io'))\n // ensures IDiskOp(diskOp(io')).bdop.NoDiskOp?\n // ensures JC.Next(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io')).jdop,\n // JournalInternalOp)\n // {\n // var writtenJournalLen :=\n // JournalistModel.getWrittenJournalLen(cm.journalist);\n // var newSuperblock := SectorType.Superblock(\n // JC.IncrementSuperblockCounter(cm.superblock.counter),\n // cm.superblock.journalStart,\n // writtenJournalLen,\n // cm.superblock.indirectionTableLoc\n // );\n // assert JC.WFSuperblock(newSuperblock);\n\n // var loc := if cm.whichSuperblock == 0 then Superblock2Location() else Superblock1Location();\n\n // var id := cm'.superblockWrite.value;\n\n // RequestWriteCorrect(io, loc, SSM.SectorSuperblock(newSuperblock),\n // id, io');\n\n // assert ValidDiskOp(diskOp(io'));\n\n // assert JC.WriteBackSuperblockReq_AdvanceLog(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io')).jdop,\n // JournalInternalOp);\n // assert JC.NextStep(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io')).jdop,\n // JournalInternalOp,\n // JC.WriteBackSuperblockReq_AdvanceLog_Step);\n // }\n\n // predicate {:opaque} writeOutSuperblockAdvanceLocation(cm: CM, io: IO,\n // cm': CM, io': IO)\n // requires io.IOInit?\n // requires CommitterModel.Inv(cm)\n // requires cm.status == StatusReady\n // requires cm.frozenLoc.Some?\n // {\n // var writtenJournalLen :=\n // JournalistModel.getWrittenJournalLen(cm.journalist);\n // var newSuperblock := SectorType.Superblock(\n // JC.IncrementSuperblockCounter(cm.superblock.counter),\n // start_pos_add(\n // cm.superblock.journalStart,\n // cm.frozenJournalPosition),\n // writtenJournalLen - cm.frozenJournalPosition,\n // cm.frozenLoc.value\n // );\n\n // var loc := if cm.whichSuperblock == 0 then Superblock2Location() else Superblock1Location();\n\n // && cm'.superblockWrite.Some?\n // && var id := cm'.superblockWrite.value;\n\n // && RequestWrite(io, loc, SSM.SectorSuperblock(newSuperblock),\n // id, io')\n // && cm' == cm\n // .(newSuperblock := Some(newSuperblock))\n // .(superblockWrite := Some(id))\n // .(commitStatus := JC.CommitAdvanceLocation)\n // }\n\n // lemma writeOutSuperblockAdvanceLocationCorrect(cm: CM, io: IO,\n // cm': CM, io': IO)\n // requires io.IOInit?\n // requires CommitterModel.Inv(cm)\n // requires cm.status == StatusReady\n // requires cm.frozenLoc.Some?\n // requires cm.commitStatus.CommitNone?\n // requires cm.outstandingJournalWrites == {}\n // requires writeOutSuperblockAdvanceLocation(cm, io, cm', io')\n // requires JournalistModel.I(cm.journalist).inMemoryJournalFrozen == []\n // ensures CommitterModel.WF(cm')\n // ensures ValidDiskOp(diskOp(io'))\n // ensures IDiskOp(diskOp(io')).bdop.NoDiskOp?\n // ensures JC.Next(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io')).jdop,\n // JournalInternalOp)\n // {\n // reveal_writeOutSuperblockAdvanceLocation();\n\n // var writtenJournalLen :=\n // JournalistModel.getWrittenJournalLen(cm.journalist);\n // var newSuperblock := SectorType.Superblock(\n // JC.IncrementSuperblockCounter(cm.superblock.counter),\n // start_pos_add(\n // cm.superblock.journalStart,\n // cm.frozenJournalPosition) as uint64,\n // (writtenJournalLen - cm.frozenJournalPosition) as uint64,\n // cm.frozenLoc.value\n // );\n // assert JC.WFSuperblock(newSuperblock);\n\n // var loc := if cm.whichSuperblock == 0 then Superblock2Location() else Superblock1Location();\n\n // var id := cm'.superblockWrite.value;\n\n // RequestWriteCorrect(io, loc, SSM.SectorSuperblock(newSuperblock),\n // id, io');\n\n // assert ValidDiskOp(diskOp(io'));\n\n // assert JC.WriteBackSuperblockReq_AdvanceLocation(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io')).jdop,\n // JournalInternalOp);\n // assert JC.NextStep(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io')).jdop,\n // JournalInternalOp,\n // JC.WriteBackSuperblockReq_AdvanceLocation_Step);\n // }\n\n // function {:opaque} freeze(cm: CM) : (cm': CM)\n // requires CommitterModel.WF(cm)\n // {\n // var writtenJournalLen :=\n // JournalistModel.getWrittenJournalLen(cm.journalist);\n // cm.(frozenLoc := None)\n // .(journalist := JournalistModel.freeze(cm.journalist))\n // .(frozenJournalPosition := writtenJournalLen)\n // .(isFrozen := true)\n // .(syncReqs := SyncReqs3to2(cm.syncReqs))\n // }\n\n // lemma freezeCorrect(cm: CM)\n // requires CommitterModel.WF(cm)\n // requires cm.superblockWrite.None?\n\n // // Mostly we'll probably just do this with cm.frozenLoc == None\n // // but more generally we can do it whenever we have:\n // requires cm.status == StatusReady\n // requires cm.frozenLoc != Some(cm.superblock.indirectionTableLoc)\n // requires JournalistModel.I(cm.journalist).replayJournal == []\n\n // ensures var cm' := freeze(cm);\n // && CommitterModel.WF(cm')\n // && JC.Next(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // FreezeOp)\n // {\n // reveal_freeze();\n // var cm' := freeze(cm);\n // SyncReqs3to2Correct(cm.syncReqs);\n\n // assert JC.Freeze(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // FreezeOp);\n // assert JC.NextStep(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // FreezeOp,\n // JC.FreezeStep);\n // }\n\n // function {:opaque} receiveFrozenLoc(\n // cm: CM, loc: Location) : (cm': CM)\n // {\n // cm.(frozenLoc := Some(loc))\n // }\n\n // lemma receiveFrozenLocCorrect(cm: CM, loc: Location)\n // requires CommitterModel.WF(cm)\n // requires cm.status == StatusReady\n // requires cm.isFrozen\n // requires !cm.frozenLoc.Some?\n // requires ValidIndirectionTableLocation(loc)\n\n // ensures var cm' := receiveFrozenLoc(cm, loc);\n // && CommitterModel.WF(cm')\n // && JC.Next(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // SendFrozenLocOp(loc))\n // {\n // reveal_receiveFrozenLoc();\n // var cm' := receiveFrozenLoc(cm, loc);\n // assert JC.ReceiveFrozenLoc(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // SendFrozenLocOp(loc));\n // assert JC.NextStep(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // SendFrozenLocOp(loc),\n // JC.ReceiveFrozenLocStep);\n // }\n\n // // == pushSync ==\n\n // function {:opaque} freeId(syncReqs: LinearMutableMap.LinearHashMap) : (id: uint64)\n // requires LinearMutableMap.Inv(syncReqs)\n // ensures id != 0 ==> id !in syncReqs.contents\n // {\n // var maxId := LinearMutableMap.MaxKey(syncReqs);\n // if maxId == 0xffff_ffff_ffff_ffff then (\n // 0\n // ) else (\n // maxId + 1\n // )\n // }\n\n // function pushSync(cm: CM) : (CM, uint64)\n // requires CommitterModel.WF(cm)\n // {\n // var id := freeId(cm.syncReqs);\n // if id == 0 || cm.syncReqs.count as int >= 0x1_0000_0000_0000_0000 / 8 then (\n // (cm, 0)\n // ) else (\n // var cm' := cm.(syncReqs := LinearMutableMap.Insert(cm.syncReqs, id, JC.State3));\n // (cm', id)\n // )\n // }\n\n // lemma pushSyncCorrect(cm: CM)\n // requires CommitterModel.WF(cm)\n\n // ensures var (cm', id) := pushSync(cm);\n // && CommitterModel.WF(cm')\n // && JC.Next(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // if id == 0 then JournalInternalOp else PushSyncOp(id as int))\n // {\n // var (cm', id) := pushSync(cm);\n // if id == 0 || cm.syncReqs.count as int >= 0x1_0000_0000_0000_0000 / 8 {\n // assert JC.NoOp(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // JournalInternalOp);\n // assert JC.NextStep(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // JournalInternalOp,\n // JC.NoOpStep);\n // } else {\n // assert JC.PushSyncReq(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // PushSyncOp(id as int), id);\n // assert JC.NextStep(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // PushSyncOp(id as int),\n // JC.PushSyncReqStep(id));\n // }\n // }\n\n // // == popSync ==\n\n // function {:opaque} popSync(cm: CM, id: uint64) : (cm' : CM)\n // requires CommitterModel.WF(cm)\n // {\n // cm.(syncReqs := LinearMutableMap.Remove(cm.syncReqs, id))\n // }\n\n // lemma popSyncCorrect(cm: CM, id: uint64)\n // requires CommitterModel.WF(cm)\n // requires id in cm.syncReqs.contents\n // requires cm.syncReqs.contents[id] == JC.State1\n // ensures var cm' := popSync(cm, id);\n // && CommitterModel.WF(cm')\n // && JC.Next(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // PopSyncOp(id as int))\n // {\n // var cm' := popSync(cm, id);\n // reveal_popSync();\n // assert JC.PopSyncReq(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // PopSyncOp(id as int), id);\n // assert JC.NextStep(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // JournalDisk.NoDiskOp,\n // PopSyncOp(id as int),\n // JC.PopSyncReqStep(id));\n // }\n\n // // == AdvanceLog ==\n\n // predicate {:opaque} tryAdvanceLog(cm: CM, io: IO,\n // cm': CM, io': IO)\n // requires CommitterModel.WF(cm)\n // requires io.IOInit?\n // {\n // var hasFrozen := JournalistModel.hasFrozenJournal(cm.journalist);\n // var hasInMem := JournalistModel.hasInMemoryJournal(cm.journalist);\n // if cm.superblockWrite.None? then (\n // if hasFrozen || hasInMem then (\n // (cm', io') == WriteOutJournal(cm, io)\n // ) else if cm.outstandingJournalWrites == {} then (\n // writeOutSuperblockAdvanceLog(cm, io, cm', io')\n // ) else (\n // && cm' == cm\n // && io' == io\n // )\n // ) else (\n // && cm' == cm\n // && io' == io\n // )\n // }\n\n // lemma tryAdvanceLogCorrect(cm: CM, io: IO,\n // cm': CM, io': IO)\n // requires CommitterModel.Inv(cm)\n // requires io.IOInit?\n // requires cm.status.StatusReady?\n // requires tryAdvanceLog(cm, io, cm', io')\n // ensures CommitterModel.WF(cm')\n // ensures ValidDiskOp(diskOp(io'))\n // ensures IDiskOp(diskOp(io')).bdop.NoDiskOp?\n // ensures JC.Next(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io')).jdop,\n // JournalInternalOp)\n // {\n // reveal_tryAdvanceLog();\n // var hasFrozen := JournalistModel.hasFrozenJournal(cm.journalist);\n // var hasInMem := JournalistModel.hasInMemoryJournal(cm.journalist);\n // if cm.superblockWrite.None? {\n // if hasFrozen || hasInMem {\n // WriteOutJournalCorrect(cm, io);\n // } else if (cm.outstandingJournalWrites == {}) {\n // writeOutSuperblockAdvanceLogCorrect(cm, io, cm', io');\n // } else {\n // assert JC.NoOp( CommitterModel.I(cm), CommitterModel.I(cm'), JournalDisk.NoDiskOp, JournalInternalOp);\n // assert JC.NextStep( CommitterModel.I(cm), CommitterModel.I(cm'), JournalDisk.NoDiskOp, JournalInternalOp, JC.NoOpStep);\n // }\n // } else {\n // assert JC.NoOp( CommitterModel.I(cm), CommitterModel.I(cm'), JournalDisk.NoDiskOp, JournalInternalOp);\n // assert JC.NextStep( CommitterModel.I(cm), CommitterModel.I(cm'), JournalDisk.NoDiskOp, JournalInternalOp, JC.NoOpStep);\n // }\n // }\n\n // predicate {:opaque} tryAdvanceLocation(cm: CM, io: IO,\n // cm': CM, io': IO)\n // requires CommitterModel.Inv(cm)\n // requires io.IOInit?\n // requires cm.status == StatusReady\n // requires cm.frozenLoc.Some?\n // {\n // var hasFrozen := JournalistModel.hasFrozenJournal(cm.journalist);\n // var hasInMem := JournalistModel.hasInMemoryJournal(cm.journalist);\n // if cm.superblockWrite.None? then (\n // if hasFrozen || hasInMem then (\n // (cm', io') == WriteOutJournal(cm, io)\n // ) else if cm.outstandingJournalWrites == {} then (\n // writeOutSuperblockAdvanceLocation(cm, io, cm', io')\n // ) else (\n // && cm' == cm\n // && io' == io\n // )\n // ) else (\n // && cm' == cm\n // && io' == io\n // )\n // }\n\n // lemma tryAdvanceLocationCorrect(cm: CM, io: IO,\n // cm': CM, io': IO)\n // requires CommitterModel.Inv(cm)\n // requires io.IOInit?\n // requires cm.status.StatusReady?\n // requires cm.frozenLoc.Some?\n // requires tryAdvanceLocation(cm, io, cm', io')\n // ensures CommitterModel.WF(cm')\n // ensures ValidDiskOp(diskOp(io'))\n // ensures IDiskOp(diskOp(io')).bdop.NoDiskOp?\n // ensures JC.Next(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io')).jdop,\n // JournalInternalOp)\n // {\n // reveal_tryAdvanceLocation();\n // var hasFrozen := JournalistModel.hasFrozenJournal(cm.journalist);\n // var hasInMem := JournalistModel.hasInMemoryJournal(cm.journalist);\n // if cm.superblockWrite.None? {\n // if hasFrozen || hasInMem {\n // WriteOutJournalCorrect(cm, io);\n // } else if (cm.outstandingJournalWrites == {}) {\n // writeOutSuperblockAdvanceLocationCorrect(cm, io, cm', io');\n // } else {\n // assert JC.NoOp( CommitterModel.I(cm), CommitterModel.I(cm'), JournalDisk.NoDiskOp, JournalInternalOp);\n // assert JC.NextStep( CommitterModel.I(cm), CommitterModel.I(cm'), JournalDisk.NoDiskOp, JournalInternalOp, JC.NoOpStep);\n // }\n // } else {\n // assert JC.NoOp( CommitterModel.I(cm), CommitterModel.I(cm'), JournalDisk.NoDiskOp, JournalInternalOp);\n // assert JC.NextStep( CommitterModel.I(cm), CommitterModel.I(cm'), JournalDisk.NoDiskOp, JournalInternalOp, JC.NoOpStep);\n // }\n // }\n\n // function {:opaque} writeBackSuperblockResp(\n // cm: CommitterModel.CM) : CommitterModel.CM\n // requires CommitterModel.Inv(cm)\n // {\n // if cm.status.StatusReady? &&\n // cm.commitStatus.CommitAdvanceLocation? then (\n // cm.(superblockWrite := None)\n // .(superblock := cm.newSuperblock.value)\n // .(newSuperblock := None)\n // .(whichSuperblock := if cm.whichSuperblock == 0 then 1 else 0)\n // .(syncReqs := SyncReqs2to1(cm.syncReqs))\n // .(journalist :=\n // JournalistModel.updateWrittenJournalLen(\n // cm.journalist,\n // JournalistModel.getWrittenJournalLen(cm.journalist)\n // - cm.frozenJournalPosition\n // )\n // )\n // .(frozenJournalPosition := 0)\n // .(frozenLoc := None)\n // .(isFrozen := false)\n // .(commitStatus := JC.CommitNone)\n // )\n // else if cm.status.StatusReady? &&\n // cm.commitStatus.CommitAdvanceLog? then (\n // cm.(superblockWrite := None)\n // .(superblock := cm.newSuperblock.value)\n // .(newSuperblock := None)\n // .(whichSuperblock := if cm.whichSuperblock == 0 then 1 else 0)\n // .(syncReqs := SyncReqs2to1(cm.syncReqs))\n // .(commitStatus := JC.CommitNone)\n // )\n // else (\n // cm\n // )\n // }\n\n // lemma writeBackSuperblockRespCorrect(\n // cm: CommitterModel.CM, io: IO)\n // requires CommitterModel.Inv(cm)\n // requires ValidDiskOp(diskOp(io))\n // requires IDiskOp(diskOp(io)).jdop.RespWriteSuperblockOp?\n // requires Some(io.id) == cm.superblockWrite\n // ensures var cm' := writeBackSuperblockResp(cm);\n // && CommitterModel.WF(cm')\n // && JC.Next(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io)).jdop,\n // if cm.status.StatusReady? && cm.commitStatus.CommitAdvanceLocation? then CleanUpOp else JournalInternalOp\n // )\n // {\n // reveal_writeBackSuperblockResp();\n // var cm' := writeBackSuperblockResp(cm);\n // SyncReqs2to1Correct(cm.syncReqs);\n // if cm.status.StatusReady? &&\n // cm.commitStatus.CommitAdvanceLocation? {\n // assert JC.WriteBackSuperblockResp(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io)).jdop,\n // CleanUpOp);\n // assert JC.NextStep(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io)).jdop,\n // CleanUpOp,\n // JC.WriteBackSuperblockRespStep);\n // }\n // else if cm.status.StatusReady? &&\n // cm.commitStatus.CommitAdvanceLog? {\n // assert JC.WriteBackSuperblockResp(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io)).jdop,\n // JournalInternalOp);\n // assert JC.NextStep(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io)).jdop,\n // JournalInternalOp,\n // JC.WriteBackSuperblockRespStep);\n // }\n // else {\n // assert JC.NoOp(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io)).jdop,\n // JournalInternalOp);\n // assert JC.NextStep(\n // CommitterModel.I(cm),\n // CommitterModel.I(cm'),\n // IDiskOp(diskOp(io)).jdop,\n // JournalInternalOp,\n // JC.NoOpStep);\n // }\n // }\n// }\n\n" }, { "test_ID": "697", "test_file": "iron-sync_tmp_tmps49o3tyz_concurrency_docs_code_ShardedStateMachine.dfy", "ground_truth": "// General form of a ShardedStateMachine\n// To instantiate one, fill in the 'Shard' type, the 'glue' function\n// provide the 'Next' predicate and the invariant 'Inv',\n// and then meet various proof obligations in the form of lemmas.\n\nabstract module ShardedStateMachine {\n /*\n * A ShardedStateMachine contains a 'Shard' type that represents\n * a shard of the state machine.\n */\n\n type Shard\n\n predicate valid_shard(a: Shard)\n\n /*\n * There must be some notion that lets us put two shards together.\n */\n\n function glue(a: Shard, b: Shard) : Shard\n\n /*\n * The 'glue' operation must respect monoidal laws.\n */\n\n lemma glue_commutative(a: Shard, b: Shard)\n ensures glue(a, b) == glue(b, a)\n\n lemma glue_associative(a: Shard, b: Shard, c: Shard)\n ensures glue(glue(a, b), c) == glue(a, glue(b, c))\n\n function unit() : Shard\n ensures valid_shard(unit())\n\n lemma glue_unit(a: Shard)\n ensures glue(a, unit()) == a\n\n /*\n * The invariant is meant to be a predicate over a 'whole' shard,\n * that is, all the pieces glued together at once.\n */\n\n predicate Inv(s: Shard)\n\n /*\n * 'Next' predicate of our state machine.\n */\n\n predicate Next(shard: Shard, shard': Shard)\n\n lemma NextPreservesValid(s: Shard, s': Shard)\n requires valid_shard(s)\n requires Next(s, s')\n ensures valid_shard(s')\n\n lemma NextAdditive(s: Shard, s': Shard, t: Shard)\n requires Next(s, s')\n requires valid_shard(glue(s, t))\n requires Next(glue(s, t), glue(s', t))\n\n /*\n * The operation must preserve the state machine invariant.\n */\n\n lemma NextPreservesInv(s: Shard, s': Shard)\n requires Inv(s)\n requires Next(s, s')\n ensures Inv(s')\n}\n\n", "hints_removed": "// General form of a ShardedStateMachine\n// To instantiate one, fill in the 'Shard' type, the 'glue' function\n// provide the 'Next' predicate and the invariant 'Inv',\n// and then meet various proof obligations in the form of lemmas.\n\nabstract module ShardedStateMachine {\n /*\n * A ShardedStateMachine contains a 'Shard' type that represents\n * a shard of the state machine.\n */\n\n type Shard\n\n predicate valid_shard(a: Shard)\n\n /*\n * There must be some notion that lets us put two shards together.\n */\n\n function glue(a: Shard, b: Shard) : Shard\n\n /*\n * The 'glue' operation must respect monoidal laws.\n */\n\n lemma glue_commutative(a: Shard, b: Shard)\n ensures glue(a, b) == glue(b, a)\n\n lemma glue_associative(a: Shard, b: Shard, c: Shard)\n ensures glue(glue(a, b), c) == glue(a, glue(b, c))\n\n function unit() : Shard\n ensures valid_shard(unit())\n\n lemma glue_unit(a: Shard)\n ensures glue(a, unit()) == a\n\n /*\n * The invariant is meant to be a predicate over a 'whole' shard,\n * that is, all the pieces glued together at once.\n */\n\n predicate Inv(s: Shard)\n\n /*\n * 'Next' predicate of our state machine.\n */\n\n predicate Next(shard: Shard, shard': Shard)\n\n lemma NextPreservesValid(s: Shard, s': Shard)\n requires valid_shard(s)\n requires Next(s, s')\n ensures valid_shard(s')\n\n lemma NextAdditive(s: Shard, s': Shard, t: Shard)\n requires Next(s, s')\n requires valid_shard(glue(s, t))\n requires Next(glue(s, t), glue(s', t))\n\n /*\n * The operation must preserve the state machine invariant.\n */\n\n lemma NextPreservesInv(s: Shard, s': Shard)\n requires Inv(s)\n requires Next(s, s')\n ensures Inv(s')\n}\n\n" }, { "test_ID": "698", "test_file": "iron-sync_tmp_tmps49o3tyz_lib_Base_MapRemove.dfy", "ground_truth": "// Defines a MapRemove1 operation for removing a key from a\n// the built-in map type, and declares a trusted, compilable\n// version.\n//\n// TODO On principle, it'd be nice to remove our dependence\n// on compiling the built-in map entirely, and just\n// replace them with our own hash tables. There are only\n// a few minor usages left.\n\nmodule {:extern} MapRemove_s {\n function {:opaque} MapRemove1(m:map, k:K) : (m':map)\n ensures forall j :: j in m && j != k ==> j in m'\n ensures forall j :: j in m' ==> j in m && j != k\n ensures forall j :: j in m' ==> m'[j] == m[j]\n ensures |m'.Keys| <= |m.Keys|\n ensures k in m ==> |m'| == |m| - 1\n ensures k !in m ==> |m'| == |m|\n {\n var m' := map j | j in m && j != k :: m[j];\n assert m'.Keys == m.Keys - {k};\n m'\n }\n\n method {:extern \"MapRemove__s_Compile\", \"ComputeMapRemove1\"}\n ComputeMapRemove1(m: map, k:K) \n returns (m' : map)\n ensures m' == MapRemove1(m, k)\n}\n\n", "hints_removed": "// Defines a MapRemove1 operation for removing a key from a\n// the built-in map type, and declares a trusted, compilable\n// version.\n//\n// TODO On principle, it'd be nice to remove our dependence\n// on compiling the built-in map entirely, and just\n// replace them with our own hash tables. There are only\n// a few minor usages left.\n\nmodule {:extern} MapRemove_s {\n function {:opaque} MapRemove1(m:map, k:K) : (m':map)\n ensures forall j :: j in m && j != k ==> j in m'\n ensures forall j :: j in m' ==> j in m && j != k\n ensures forall j :: j in m' ==> m'[j] == m[j]\n ensures |m'.Keys| <= |m.Keys|\n ensures k in m ==> |m'| == |m| - 1\n ensures k !in m ==> |m'| == |m|\n {\n var m' := map j | j in m && j != k :: m[j];\n m'\n }\n\n method {:extern \"MapRemove__s_Compile\", \"ComputeMapRemove1\"}\n ComputeMapRemove1(m: map, k:K) \n returns (m' : map)\n ensures m' == MapRemove1(m, k)\n}\n\n" }, { "test_ID": "699", "test_file": "ironsync-osdi2023_tmp_tmpx80antoe_lib_Marshalling_Math.dfy", "ground_truth": "// Based on IronFleet's math library.\n// I pulled out only the functions we need for the marshalling code,\n// and in a few cases rewrote the proof from scratch to avoid pulling in\n// a lot of dependencies.\n\nmodule Math {\n function {:opaque} power2(exp: nat) : nat\n ensures power2(exp) > 0;\n {\n if (exp==0) then\n 1\n else\n 2*power2(exp-1)\n }\n\n lemma lemma_2toX()\n ensures power2(8) == 256;\n ensures power2(16) == 65536;\n ensures power2(19) == 524288;\n ensures power2(24) == 16777216;\n ensures power2(32) == 4294967296;\n ensures power2(60) == 1152921504606846976;\n ensures power2(64) == 18446744073709551616;\n {\n reveal_power2();\n }\n\n lemma lemma_power2_adds(e1:nat, e2:nat)\n decreases e2;\n ensures power2(e1 + e2) == power2(e1) * power2(e2);\n {\n reveal_power2();\n if (e2 == 0) {\n } else {\n lemma_power2_adds(e1, e2-1);\n }\n }\n\n lemma lemma_2toX32()\n ensures power2(0) == 0x1;\n ensures power2(1) == 0x2;\n ensures power2(2) == 0x4;\n ensures power2(3) == 0x8;\n ensures power2(4) == 0x10;\n ensures power2(5) == 0x20;\n ensures power2(6) == 0x40;\n ensures power2(7) == 0x80;\n ensures power2(8) == 0x100;\n ensures power2(9) == 0x200;\n ensures power2(10) == 0x400;\n ensures power2(11) == 0x800;\n ensures power2(12) == 0x1000;\n ensures power2(13) == 0x2000;\n ensures power2(14) == 0x4000;\n ensures power2(15) == 0x8000;\n ensures power2(16) == 0x10000;\n ensures power2(17) == 0x20000;\n ensures power2(18) == 0x40000;\n ensures power2(19) == 0x80000;\n ensures power2(20) == 0x100000;\n ensures power2(21) == 0x200000;\n ensures power2(22) == 0x400000;\n ensures power2(23) == 0x800000;\n ensures power2(24) == 0x1000000;\n ensures power2(25) == 0x2000000;\n ensures power2(26) == 0x4000000;\n ensures power2(27) == 0x8000000;\n ensures power2(28) == 0x10000000;\n ensures power2(29) == 0x20000000;\n ensures power2(30) == 0x40000000;\n ensures power2(31) == 0x80000000;\n ensures power2(32) == 0x100000000;\n {\n reveal_power2();\n }\n\n lemma bounded_mul_eq_0(x: int, m: int)\n requires -m < m*x < m\n ensures x == 0\n {\n }\n\n // This is often used as part of the axiomatic definition of division\n // in a lot of formalizations of mathematics. Oddly, it isn't built-in to dafny\n // and we have to prove it in sort of a roundabout way.\n lemma lemma_div_ind(x: int, d: int)\n requires d > 0\n ensures x / d + 1 == (x + d) / d\n {\n assert d * (x / d + 1)\n == (x/d)*d + d\n == x - (x % d) + d;\n\n assert d * ((x + d) / d)\n == (x + d) - ((x + d) % d);\n\n assert 0 <= x % d < d;\n assert 0 <= (x + d) % d < d;\n\n assert d * (x / d + 1) - d * ((x + d) / d)\n == ((x + d) % d) - (x % d);\n\n assert -d < d * (x / d + 1) - d * ((x + d) / d) < d;\n assert -d < d * ((x / d + 1) - ((x + d) / d)) < d;\n bounded_mul_eq_0((x / d + 1) - ((x + d) / d), d);\n }\n\n lemma lemma_add_mul_div(a: int, b: int, d: int)\n requires d > 0\n ensures (a + b*d) / d == a/d + b\n decreases if b > 0 then b else -b\n {\n if (b == 0) {\n } else if (b > 0) {\n lemma_add_mul_div(a, b-1, d);\n lemma_div_ind(a + (b-1)*d, d);\n } else {\n lemma_add_mul_div(a, b+1, d);\n lemma_div_ind(a + b*d, d);\n }\n }\n\n lemma lemma_div_multiples_vanish_fancy(x:int, b:int, d:int)\n requires 0 0 then x else -x\n {\n if (x == 0) {\n } else if (x > 0) {\n lemma_div_multiples_vanish_fancy(x-1, b, d);\n lemma_div_ind(d*(x-1) + b, d);\n } else {\n lemma_div_multiples_vanish_fancy(x+1, b, d);\n lemma_div_ind(d*x + b, d);\n }\n }\n\n lemma lemma_div_by_multiple(b:int, d:int)\n requires 0 < d;\n ensures (b*d) / d == b;\n { \n lemma_div_multiples_vanish_fancy(b, 0, d);\n }\n\n lemma lemma_mod_multiples_basic(x:int, m:int)\n requires m > 0;\n ensures (x * m) % m == 0;\n {\n assert (x*m)%m == x*m - ((x*m)/m)*m;\n lemma_div_by_multiple(x, m);\n assert (x*m)/m == x;\n assert x*m - ((x*m)/m)*m == x*m - x*m\n == 0;\n }\n\n lemma lemma_div_by_multiple_is_strongly_ordered(x:int, y:int, m:int, z:int)\n requires x < y;\n requires y == m * z;\n requires z > 0;\n ensures x / z < y / z;\n {\n lemma_mod_multiples_basic(m, z);\n if (x / z <= m-1) {\n } else {\n lemma_div_by_multiple_is_strongly_ordered(x, y-z, m-1, z);\n }\n }\n\n lemma lemma_power2_div_is_sub(x:int, y:int)\n requires 0 <= x <= y;\n ensures power2(y - x) == power2(y) / power2(x)\n >= 0;\n {\n calc {\n power2(y) / power2(x);\n { lemma_power2_adds(y-x, x); }\n (power2(y-x)*power2(x)) / power2(x);\n { lemma_div_by_multiple(power2(y-x), power2(x)); }\n power2(y-x);\n }\n }\n\n lemma lemma_div_denominator(x:int,c:nat,d:nat)\n requires 0 <= x;\n requires 0 0;\n {\n if (exp==0) then\n 1\n else\n 2*power2(exp-1)\n }\n\n lemma lemma_2toX()\n ensures power2(8) == 256;\n ensures power2(16) == 65536;\n ensures power2(19) == 524288;\n ensures power2(24) == 16777216;\n ensures power2(32) == 4294967296;\n ensures power2(60) == 1152921504606846976;\n ensures power2(64) == 18446744073709551616;\n {\n reveal_power2();\n }\n\n lemma lemma_power2_adds(e1:nat, e2:nat)\n ensures power2(e1 + e2) == power2(e1) * power2(e2);\n {\n reveal_power2();\n if (e2 == 0) {\n } else {\n lemma_power2_adds(e1, e2-1);\n }\n }\n\n lemma lemma_2toX32()\n ensures power2(0) == 0x1;\n ensures power2(1) == 0x2;\n ensures power2(2) == 0x4;\n ensures power2(3) == 0x8;\n ensures power2(4) == 0x10;\n ensures power2(5) == 0x20;\n ensures power2(6) == 0x40;\n ensures power2(7) == 0x80;\n ensures power2(8) == 0x100;\n ensures power2(9) == 0x200;\n ensures power2(10) == 0x400;\n ensures power2(11) == 0x800;\n ensures power2(12) == 0x1000;\n ensures power2(13) == 0x2000;\n ensures power2(14) == 0x4000;\n ensures power2(15) == 0x8000;\n ensures power2(16) == 0x10000;\n ensures power2(17) == 0x20000;\n ensures power2(18) == 0x40000;\n ensures power2(19) == 0x80000;\n ensures power2(20) == 0x100000;\n ensures power2(21) == 0x200000;\n ensures power2(22) == 0x400000;\n ensures power2(23) == 0x800000;\n ensures power2(24) == 0x1000000;\n ensures power2(25) == 0x2000000;\n ensures power2(26) == 0x4000000;\n ensures power2(27) == 0x8000000;\n ensures power2(28) == 0x10000000;\n ensures power2(29) == 0x20000000;\n ensures power2(30) == 0x40000000;\n ensures power2(31) == 0x80000000;\n ensures power2(32) == 0x100000000;\n {\n reveal_power2();\n }\n\n lemma bounded_mul_eq_0(x: int, m: int)\n requires -m < m*x < m\n ensures x == 0\n {\n }\n\n // This is often used as part of the axiomatic definition of division\n // in a lot of formalizations of mathematics. Oddly, it isn't built-in to dafny\n // and we have to prove it in sort of a roundabout way.\n lemma lemma_div_ind(x: int, d: int)\n requires d > 0\n ensures x / d + 1 == (x + d) / d\n {\n == (x/d)*d + d\n == x - (x % d) + d;\n\n == (x + d) - ((x + d) % d);\n\n\n == ((x + d) % d) - (x % d);\n\n bounded_mul_eq_0((x / d + 1) - ((x + d) / d), d);\n }\n\n lemma lemma_add_mul_div(a: int, b: int, d: int)\n requires d > 0\n ensures (a + b*d) / d == a/d + b\n {\n if (b == 0) {\n } else if (b > 0) {\n lemma_add_mul_div(a, b-1, d);\n lemma_div_ind(a + (b-1)*d, d);\n } else {\n lemma_add_mul_div(a, b+1, d);\n lemma_div_ind(a + b*d, d);\n }\n }\n\n lemma lemma_div_multiples_vanish_fancy(x:int, b:int, d:int)\n requires 0 0) {\n lemma_div_multiples_vanish_fancy(x-1, b, d);\n lemma_div_ind(d*(x-1) + b, d);\n } else {\n lemma_div_multiples_vanish_fancy(x+1, b, d);\n lemma_div_ind(d*x + b, d);\n }\n }\n\n lemma lemma_div_by_multiple(b:int, d:int)\n requires 0 < d;\n ensures (b*d) / d == b;\n { \n lemma_div_multiples_vanish_fancy(b, 0, d);\n }\n\n lemma lemma_mod_multiples_basic(x:int, m:int)\n requires m > 0;\n ensures (x * m) % m == 0;\n {\n lemma_div_by_multiple(x, m);\n == 0;\n }\n\n lemma lemma_div_by_multiple_is_strongly_ordered(x:int, y:int, m:int, z:int)\n requires x < y;\n requires y == m * z;\n requires z > 0;\n ensures x / z < y / z;\n {\n lemma_mod_multiples_basic(m, z);\n if (x / z <= m-1) {\n } else {\n lemma_div_by_multiple_is_strongly_ordered(x, y-z, m-1, z);\n }\n }\n\n lemma lemma_power2_div_is_sub(x:int, y:int)\n requires 0 <= x <= y;\n ensures power2(y - x) == power2(y) / power2(x)\n >= 0;\n {\n calc {\n power2(y) / power2(x);\n { lemma_power2_adds(y-x, x); }\n (power2(y-x)*power2(x)) / power2(x);\n { lemma_div_by_multiple(power2(y-x), power2(x)); }\n power2(y-x);\n }\n }\n\n lemma lemma_div_denominator(x:int,c:nat,d:nat)\n requires 0 <= x;\n requires 0 0;\n decreases if x < 0 then (m - x) else x;\n{\n if x < 0 then\n mod(m + x, m)\n else if x < m then\n x\n else\n mod(x - m, m)\n}\n*/\n\nfunction div(x:int, d:int) : int\n requires d != 0;\n{\n x/d\n}\n\nfunction mod(x:int, d:int) : int\n requires d != 0;\n{\n x%d\n}\n\nfunction div_recursive(x:int, d:int) : int\n requires d != 0;\n{ INTERNAL_div_recursive(x,d) }\n\nfunction mod_recursive(x:int, d:int) : int\n requires d > 0;\n{ INTERNAL_mod_recursive(x,d) }\n\nfunction mod_boogie(x:int, y:int) : int\n requires y != 0;\n{ x % y } //- INTERNAL_mod_boogie(x,y) }\n\nfunction div_boogie(x:int, y:int) : int\n requires y != 0;\n{ x / y } //-{ INTERNAL_div_boogie(x,y) }\n\nfunction my_div_recursive(x:int, d:int) : int\n requires d != 0;\n{\n if d > 0 then\n my_div_pos(x, d)\n else\n -1 * my_div_pos(x, -1*d)\n}\n\nfunction my_div_pos(x:int, d:int) : int\n requires d > 0;\n decreases if x < 0 then (d - x) else x;\n{\n if x < 0 then\n -1 + my_div_pos(x+d, d)\n else if x < d then\n 0\n else\n 1 + my_div_pos(x-d, d)\n}\n\nfunction my_mod_recursive(x:int, m:int) : int\n requires m > 0;\n decreases if x < 0 then (m - x) else x;\n{\n if x < 0 then\n my_mod_recursive(m + x, m)\n else if x < m then\n x\n else\n my_mod_recursive(x - m, m)\n}\n\n\n//- Kept for legacy reasons:\n//-static function INTERNAL_mod_boogie(x:int, m:int) : int { x % y }\nfunction INTERNAL_mod_recursive(x:int, m:int) : int \n requires m > 0;\n{ my_mod_recursive(x, m) }\n\n//-static function INTERNAL_div_boogie(x:int, m:int) : int { x / m }\nfunction INTERNAL_div_recursive(x:int, d:int) : int \n requires d != 0;\n{ my_div_recursive(x, d) }\n\n\n/*\nghost method mod_test()\n{\n assert -3 % 5 == 2;\n assert 10 % -5 == 0;\n assert 1 % -5 == 1;\n assert -3 / 5 == -1;\n}\n*/\n\n} \n\n", "hints_removed": "//- Specs/implements mathematical div and mod, not the C version.\n//- This may produce \"surprising\" results for negative values\n//- For example, -3 div 5 is -1 and -3 mod 5 is 2.\n//- Note this is consistent: -3 * -1 + 2 == 5\n\nmodule Math__div_def_i {\n/*\nfunction mod(x:int, m:int) : int\n requires m > 0;\n{\n if x < 0 then\n mod(m + x, m)\n else if x < m then\n x\n else\n mod(x - m, m)\n}\n*/\n\nfunction div(x:int, d:int) : int\n requires d != 0;\n{\n x/d\n}\n\nfunction mod(x:int, d:int) : int\n requires d != 0;\n{\n x%d\n}\n\nfunction div_recursive(x:int, d:int) : int\n requires d != 0;\n{ INTERNAL_div_recursive(x,d) }\n\nfunction mod_recursive(x:int, d:int) : int\n requires d > 0;\n{ INTERNAL_mod_recursive(x,d) }\n\nfunction mod_boogie(x:int, y:int) : int\n requires y != 0;\n{ x % y } //- INTERNAL_mod_boogie(x,y) }\n\nfunction div_boogie(x:int, y:int) : int\n requires y != 0;\n{ x / y } //-{ INTERNAL_div_boogie(x,y) }\n\nfunction my_div_recursive(x:int, d:int) : int\n requires d != 0;\n{\n if d > 0 then\n my_div_pos(x, d)\n else\n -1 * my_div_pos(x, -1*d)\n}\n\nfunction my_div_pos(x:int, d:int) : int\n requires d > 0;\n{\n if x < 0 then\n -1 + my_div_pos(x+d, d)\n else if x < d then\n 0\n else\n 1 + my_div_pos(x-d, d)\n}\n\nfunction my_mod_recursive(x:int, m:int) : int\n requires m > 0;\n{\n if x < 0 then\n my_mod_recursive(m + x, m)\n else if x < m then\n x\n else\n my_mod_recursive(x - m, m)\n}\n\n\n//- Kept for legacy reasons:\n//-static function INTERNAL_mod_boogie(x:int, m:int) : int { x % y }\nfunction INTERNAL_mod_recursive(x:int, m:int) : int \n requires m > 0;\n{ my_mod_recursive(x, m) }\n\n//-static function INTERNAL_div_boogie(x:int, m:int) : int { x / m }\nfunction INTERNAL_div_recursive(x:int, d:int) : int \n requires d != 0;\n{ my_div_recursive(x, d) }\n\n\n/*\nghost method mod_test()\n{\n}\n*/\n\n} \n\n" }, { "test_ID": "701", "test_file": "ironsync-osdi2023_tmp_tmpx80antoe_linear-dafny_Test_c++_arrays.dfy", "ground_truth": "// RUN: %dafny /compile:3 /spillTargetCode:2 /compileTarget:cpp \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nnewtype uint32 = i:int | 0 <= i < 0x100000000\n\nmethod returnANullArray() returns (a: array?)\n ensures a == null\n{\n a := null;\n}\n\nmethod returnANonNullArray() returns (a: array?)\n ensures a != null\n ensures a.Length == 5\n{\n a := new uint32[5];\n a[0] := 1;\n a[1] := 2;\n a[2] := 3;\n a[3] := 4;\n a[4] := 5;\n}\n\nmethod LinearSearch(a: array, len:uint32, key: uint32) returns (n: uint32)\n requires a.Length == len as int\n ensures 0 <= n <= len\n ensures n == len || a[n] == key\n{\n n := 0;\n while n < len\n invariant n <= len\n {\n if a[n] == key {\n return;\n }\n n := n + 1;\n }\n}\n\nmethod PrintArray(a:array?, len:uint32)\n requires a != null ==> len as int == a.Length\n{\n if (a == null) {\n print \"It's null\\n\";\n } else {\n var i:uint32 := 0;\n while i < len {\n print a[i], \" \";\n i := i + 1;\n }\n print \"\\n\";\n }\n}\n\ndatatype ArrayDatatype = AD(ar: array)\n\nmethod Main() {\n var a := new uint32[23];\n var i := 0;\n while i < 23 {\n a[i] := i;\n i := i + 1;\n }\n PrintArray(a, 23);\n var n := LinearSearch(a, 23, 17);\n print n, \"\\n\";\n var s : seq := a[..];\n print s, \"\\n\";\n s := a[2..16];\n print s, \"\\n\";\n s := a[20..];\n print s, \"\\n\";\n s := a[..8];\n print s, \"\\n\";\n\n // Conversion to sequence should copy elements (sequences are immutable!)\n a[0] := 42;\n print s, \"\\n\";\n\n PrintArray(null, 0);\n\n print \"Null array:\\n\";\n var a1 := returnANullArray();\n PrintArray(a1, 5);\n\n print \"Non-Null array:\\n\";\n var a2 := returnANonNullArray();\n PrintArray(a2, 5);\n\n print \"Array in datatype:\\n\";\n var someAr := new uint32[3];\n someAr[0] := 1;\n someAr[1] := 3;\n someAr[2] := 9;\n var ad := AD(someAr);\n PrintArray(ad.ar, 3);\n}\n\n\n\n", "hints_removed": "// RUN: %dafny /compile:3 /spillTargetCode:2 /compileTarget:cpp \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nnewtype uint32 = i:int | 0 <= i < 0x100000000\n\nmethod returnANullArray() returns (a: array?)\n ensures a == null\n{\n a := null;\n}\n\nmethod returnANonNullArray() returns (a: array?)\n ensures a != null\n ensures a.Length == 5\n{\n a := new uint32[5];\n a[0] := 1;\n a[1] := 2;\n a[2] := 3;\n a[3] := 4;\n a[4] := 5;\n}\n\nmethod LinearSearch(a: array, len:uint32, key: uint32) returns (n: uint32)\n requires a.Length == len as int\n ensures 0 <= n <= len\n ensures n == len || a[n] == key\n{\n n := 0;\n while n < len\n {\n if a[n] == key {\n return;\n }\n n := n + 1;\n }\n}\n\nmethod PrintArray(a:array?, len:uint32)\n requires a != null ==> len as int == a.Length\n{\n if (a == null) {\n print \"It's null\\n\";\n } else {\n var i:uint32 := 0;\n while i < len {\n print a[i], \" \";\n i := i + 1;\n }\n print \"\\n\";\n }\n}\n\ndatatype ArrayDatatype = AD(ar: array)\n\nmethod Main() {\n var a := new uint32[23];\n var i := 0;\n while i < 23 {\n a[i] := i;\n i := i + 1;\n }\n PrintArray(a, 23);\n var n := LinearSearch(a, 23, 17);\n print n, \"\\n\";\n var s : seq := a[..];\n print s, \"\\n\";\n s := a[2..16];\n print s, \"\\n\";\n s := a[20..];\n print s, \"\\n\";\n s := a[..8];\n print s, \"\\n\";\n\n // Conversion to sequence should copy elements (sequences are immutable!)\n a[0] := 42;\n print s, \"\\n\";\n\n PrintArray(null, 0);\n\n print \"Null array:\\n\";\n var a1 := returnANullArray();\n PrintArray(a1, 5);\n\n print \"Non-Null array:\\n\";\n var a2 := returnANonNullArray();\n PrintArray(a2, 5);\n\n print \"Array in datatype:\\n\";\n var someAr := new uint32[3];\n someAr[0] := 1;\n someAr[1] := 3;\n someAr[2] := 9;\n var ad := AD(someAr);\n PrintArray(ad.ar, 3);\n}\n\n\n\n" }, { "test_ID": "702", "test_file": "ironsync-osdi2023_tmp_tmpx80antoe_linear-dafny_Test_c++_maps.dfy", "ground_truth": "// RUN: %dafny /compile:3 /spillTargetCode:2 /compileTarget:cpp \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nnewtype uint32 = i:int | 0 <= i < 0x100000000\n\nmethod Test(name:string, b:bool)\n requires b\n{\n if b {\n print name, \": This is expected\\n\";\n } else {\n print name, \": This is *** UNEXPECTED *** !!!!\\n\";\n }\n}\n\ndatatype map_holder = map_holder(m:map)\n\nmethod Basic() {\n var f:map_holder;\n var s:map := map[1 := 0, 2 := 1, 3 := 2, 4 := 3];\n var t:map := map[1 := 0, 2 := 1, 3 := 2, 4 := 3];\n\n Test(\"Identity\", s == s);\n Test(\"ValuesIdentity\", s == t);\n Test(\"KeyMembership\", 1 in s);\n Test(\"Value1\", s[1] == 0);\n Test(\"Value2\", t[2] == 1);\n\n var u := s[1 := 42];\n Test(\"Update Inequality\", s != u);\n Test(\"Update Immutable 1\", s == s);\n Test(\"Update Immutable 2\", s[1] == 0);\n Test(\"Update Result\", u[1] == 42);\n Test(\"Update Others\", u[2] == 1);\n\n var s_keys := s.Keys;\n var t_keys := t.Keys;\n Test(\"Keys equal\", s_keys == t_keys);\n Test(\"Keys membership 1\", 1 in s_keys);\n Test(\"Keys membership 2\", 2 in s_keys);\n Test(\"Keys membership 3\", 3 in s_keys);\n Test(\"Keys membership 4\", 4 in s_keys);\n}\n\n\nmethod Main() {\n Basic();\n TestMapMergeSubtraction();\n}\n\nmethod TestMapMergeSubtraction() {\n TestMapMerge();\n TestMapSubtraction();\n TestNullsAmongKeys();\n TestNullsAmongValues();\n}\n\nmethod TestMapMerge() {\n var a := map[\"ronald\" := 66 as uint32, \"jack\" := 70, \"bk\" := 8];\n var b := map[\"wendy\" := 52, \"bk\" := 67];\n var ages := a + b;\n assert ages[\"jack\"] == 70;\n assert ages[\"bk\"] == 67;\n assert \"sanders\" !in ages;\n print |a|, \" \", |b|, \" \", |ages|, \"\\n\"; // 3 2 4\n print ages[\"jack\"], \" \", ages[\"wendy\"], \" \", ages[\"ronald\"], \"\\n\"; // 70 52 66\n print a[\"bk\"], \" \", b[\"bk\"], \" \", ages[\"bk\"], \"\\n\"; // 8 67 67\n}\n\nmethod TestMapSubtraction() {\n var ages := map[\"ronald\" := 66 as uint32, \"jack\" := 70, \"bk\" := 67, \"wendy\" := 52];\n var d := ages - {};\n var e := ages - {\"jack\", \"sanders\"};\n print |ages|, \" \", |d|, \" \", |e|, \"\\n\"; // 4 4 3\n print \"ronald\" in d, \" \", \"sanders\" in d, \" \", \"jack\" in d, \" \", \"sibylla\" in d, \"\\n\"; // true false true false\n print \"ronald\" in e, \" \", \"sanders\" in e, \" \", \"jack\" in e, \" \", \"sibylla\" in e, \"\\n\"; // true false false false\n}\n\nclass MyClass {\n const name: string\n constructor (name: string) {\n this.name := name;\n }\n}\n\nmethod TestNullsAmongKeys() {\n var a := new MyClass(\"ronald\");\n var b := new MyClass(\"wendy\");\n var c: MyClass? := null;\n var d := new MyClass(\"jack\");\n var e := new MyClass(\"sibylla\");\n\n var m := map[a := 0 as uint32, b := 1, c := 2, d := 3];\n var n := map[a := 0, b := 10, c := 20, e := 4];\n var o := map[b := 199, a := 198];\n\n var o' := map[b := 199, c := 55, a := 198];\n var o'' := map[b := 199, c := 56, a := 198];\n var o3 := map[c := 3, d := 16];\n var x0, x1, x2 := o == o', o' == o'', o' == o';\n print x0, \" \" , x1, \" \", x2, \"\\n\"; // false false true\n\n var p := m + n;\n var q := n + o;\n var r := o + m;\n var s := o3 + o;\n var y0, y1, y2, y3 := p == n + m, q == o + n, r == m + o, s == o + o3;\n print y0, \" \" , y1, \" \", y2, \" \", y3, \"\\n\"; // false false false true\n\n print p[a], \" \", p[c], \" \", p[e], \"\\n\"; // 0 20 4\n print q[a], \" \", q[c], \" \", q[e], \"\\n\"; // 198 20 4\n print r[a], \" \", r[c], \" \", e in r, \"\\n\"; // 0 2 false\n\n p, q, r := GenericMap(m, n, o, a, e);\n print p[a], \" \", p[c], \" \", p[e], \"\\n\"; // 0 20 4\n print q[a], \" \", q[c], \" \", q[e], \"\\n\"; // 198 20 4\n print r[a], \" \", r[c], \" \", e in r, \"\\n\"; // 0 2 false\n}\n\nmethod GenericMap(m: map, n: map, o: map, a: K, b: K)\n returns (p: map, q: map, r: map)\n requires a in m.Keys && a in n.Keys\n requires b !in m.Keys && b !in o.Keys\n ensures p == m + n && q == n + o && r == o + m\n{\n p := m + n;\n q := n + o;\n r := o + m;\n print a in m.Keys, \" \", a in n.Keys, \" \", a in p, \" \", b in r, \"\\n\"; // true true true false\n\n assert p.Keys == m.Keys + n.Keys;\n assert q.Keys == o.Keys + n.Keys;\n assert r.Keys == m.Keys + o.Keys;\n}\n\nmethod TestNullsAmongValues() {\n var a := new MyClass(\"ronald\");\n var b := new MyClass(\"wendy\");\n var d := new MyClass(\"jack\");\n var e := new MyClass(\"sibylla\");\n\n var m: map := map[0 := a, 1 := b, 2 := null, 3 := null];\n var n: map := map[0 := d, 10 := b, 20 := null, 4 := e];\n var o: map := map[199 := null, 198 := a];\n\n var o': map := map[199 := b, 55 := null, 198 := a];\n var o'': map := map[199 := b, 56 := null, 198 := a];\n var o3: map := map[3 := null, 16 := d];\n var x0, x1, x2 := o == o', o' == o'', o' == o';\n print x0, \" \" , x1, \" \", x2, \"\\n\"; // false false true\n\n var p := m + n;\n var q := n + o;\n var r := o + m;\n var s := o3 + o;\n var y0, y1, y2, y3 := p == n + m, q == o + n, r == m + o, s == o + o3;\n print y0, \" \" , y1, \" \", y2, \" \", y3, \"\\n\"; // false true true true\n\n print p[0].name, \" \", p[1].name, \" \", p[20], \"\\n\"; // jack wendy null\n print q[0].name, \" \", q[199], \" \", q[20], \"\\n\"; // jack null null\n print r[0].name, \" \", r[198].name, \" \", 20 in r, \"\\n\"; // ronald ronald false\n\n p, q, r := GenericMap(m, n, o, 0, 321);\n print p[0].name, \" \", p[1].name, \" \", p[20], \"\\n\"; // jack wendy null\n print q[0].name, \" \", q[199], \" \", q[20], \"\\n\"; // jack null null\n print r[0].name, \" \", r[198].name, \" \", 20 in r, \"\\n\"; // ronald ronald false\n}\n\n", "hints_removed": "// RUN: %dafny /compile:3 /spillTargetCode:2 /compileTarget:cpp \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nnewtype uint32 = i:int | 0 <= i < 0x100000000\n\nmethod Test(name:string, b:bool)\n requires b\n{\n if b {\n print name, \": This is expected\\n\";\n } else {\n print name, \": This is *** UNEXPECTED *** !!!!\\n\";\n }\n}\n\ndatatype map_holder = map_holder(m:map)\n\nmethod Basic() {\n var f:map_holder;\n var s:map := map[1 := 0, 2 := 1, 3 := 2, 4 := 3];\n var t:map := map[1 := 0, 2 := 1, 3 := 2, 4 := 3];\n\n Test(\"Identity\", s == s);\n Test(\"ValuesIdentity\", s == t);\n Test(\"KeyMembership\", 1 in s);\n Test(\"Value1\", s[1] == 0);\n Test(\"Value2\", t[2] == 1);\n\n var u := s[1 := 42];\n Test(\"Update Inequality\", s != u);\n Test(\"Update Immutable 1\", s == s);\n Test(\"Update Immutable 2\", s[1] == 0);\n Test(\"Update Result\", u[1] == 42);\n Test(\"Update Others\", u[2] == 1);\n\n var s_keys := s.Keys;\n var t_keys := t.Keys;\n Test(\"Keys equal\", s_keys == t_keys);\n Test(\"Keys membership 1\", 1 in s_keys);\n Test(\"Keys membership 2\", 2 in s_keys);\n Test(\"Keys membership 3\", 3 in s_keys);\n Test(\"Keys membership 4\", 4 in s_keys);\n}\n\n\nmethod Main() {\n Basic();\n TestMapMergeSubtraction();\n}\n\nmethod TestMapMergeSubtraction() {\n TestMapMerge();\n TestMapSubtraction();\n TestNullsAmongKeys();\n TestNullsAmongValues();\n}\n\nmethod TestMapMerge() {\n var a := map[\"ronald\" := 66 as uint32, \"jack\" := 70, \"bk\" := 8];\n var b := map[\"wendy\" := 52, \"bk\" := 67];\n var ages := a + b;\n print |a|, \" \", |b|, \" \", |ages|, \"\\n\"; // 3 2 4\n print ages[\"jack\"], \" \", ages[\"wendy\"], \" \", ages[\"ronald\"], \"\\n\"; // 70 52 66\n print a[\"bk\"], \" \", b[\"bk\"], \" \", ages[\"bk\"], \"\\n\"; // 8 67 67\n}\n\nmethod TestMapSubtraction() {\n var ages := map[\"ronald\" := 66 as uint32, \"jack\" := 70, \"bk\" := 67, \"wendy\" := 52];\n var d := ages - {};\n var e := ages - {\"jack\", \"sanders\"};\n print |ages|, \" \", |d|, \" \", |e|, \"\\n\"; // 4 4 3\n print \"ronald\" in d, \" \", \"sanders\" in d, \" \", \"jack\" in d, \" \", \"sibylla\" in d, \"\\n\"; // true false true false\n print \"ronald\" in e, \" \", \"sanders\" in e, \" \", \"jack\" in e, \" \", \"sibylla\" in e, \"\\n\"; // true false false false\n}\n\nclass MyClass {\n const name: string\n constructor (name: string) {\n this.name := name;\n }\n}\n\nmethod TestNullsAmongKeys() {\n var a := new MyClass(\"ronald\");\n var b := new MyClass(\"wendy\");\n var c: MyClass? := null;\n var d := new MyClass(\"jack\");\n var e := new MyClass(\"sibylla\");\n\n var m := map[a := 0 as uint32, b := 1, c := 2, d := 3];\n var n := map[a := 0, b := 10, c := 20, e := 4];\n var o := map[b := 199, a := 198];\n\n var o' := map[b := 199, c := 55, a := 198];\n var o'' := map[b := 199, c := 56, a := 198];\n var o3 := map[c := 3, d := 16];\n var x0, x1, x2 := o == o', o' == o'', o' == o';\n print x0, \" \" , x1, \" \", x2, \"\\n\"; // false false true\n\n var p := m + n;\n var q := n + o;\n var r := o + m;\n var s := o3 + o;\n var y0, y1, y2, y3 := p == n + m, q == o + n, r == m + o, s == o + o3;\n print y0, \" \" , y1, \" \", y2, \" \", y3, \"\\n\"; // false false false true\n\n print p[a], \" \", p[c], \" \", p[e], \"\\n\"; // 0 20 4\n print q[a], \" \", q[c], \" \", q[e], \"\\n\"; // 198 20 4\n print r[a], \" \", r[c], \" \", e in r, \"\\n\"; // 0 2 false\n\n p, q, r := GenericMap(m, n, o, a, e);\n print p[a], \" \", p[c], \" \", p[e], \"\\n\"; // 0 20 4\n print q[a], \" \", q[c], \" \", q[e], \"\\n\"; // 198 20 4\n print r[a], \" \", r[c], \" \", e in r, \"\\n\"; // 0 2 false\n}\n\nmethod GenericMap(m: map, n: map, o: map, a: K, b: K)\n returns (p: map, q: map, r: map)\n requires a in m.Keys && a in n.Keys\n requires b !in m.Keys && b !in o.Keys\n ensures p == m + n && q == n + o && r == o + m\n{\n p := m + n;\n q := n + o;\n r := o + m;\n print a in m.Keys, \" \", a in n.Keys, \" \", a in p, \" \", b in r, \"\\n\"; // true true true false\n\n}\n\nmethod TestNullsAmongValues() {\n var a := new MyClass(\"ronald\");\n var b := new MyClass(\"wendy\");\n var d := new MyClass(\"jack\");\n var e := new MyClass(\"sibylla\");\n\n var m: map := map[0 := a, 1 := b, 2 := null, 3 := null];\n var n: map := map[0 := d, 10 := b, 20 := null, 4 := e];\n var o: map := map[199 := null, 198 := a];\n\n var o': map := map[199 := b, 55 := null, 198 := a];\n var o'': map := map[199 := b, 56 := null, 198 := a];\n var o3: map := map[3 := null, 16 := d];\n var x0, x1, x2 := o == o', o' == o'', o' == o';\n print x0, \" \" , x1, \" \", x2, \"\\n\"; // false false true\n\n var p := m + n;\n var q := n + o;\n var r := o + m;\n var s := o3 + o;\n var y0, y1, y2, y3 := p == n + m, q == o + n, r == m + o, s == o + o3;\n print y0, \" \" , y1, \" \", y2, \" \", y3, \"\\n\"; // false true true true\n\n print p[0].name, \" \", p[1].name, \" \", p[20], \"\\n\"; // jack wendy null\n print q[0].name, \" \", q[199], \" \", q[20], \"\\n\"; // jack null null\n print r[0].name, \" \", r[198].name, \" \", 20 in r, \"\\n\"; // ronald ronald false\n\n p, q, r := GenericMap(m, n, o, 0, 321);\n print p[0].name, \" \", p[1].name, \" \", p[20], \"\\n\"; // jack wendy null\n print q[0].name, \" \", q[199], \" \", q[20], \"\\n\"; // jack null null\n print r[0].name, \" \", r[198].name, \" \", 20 in r, \"\\n\"; // ronald ronald false\n}\n\n" }, { "test_ID": "703", "test_file": "ironsync-osdi2023_tmp_tmpx80antoe_linear-dafny_Test_c++_sets.dfy", "ground_truth": "// RUN: %dafny /compile:3 /spillTargetCode:2 /compileTarget:cpp \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nnewtype uint32 = i:int | 0 <= i < 0x100000000\n\ndatatype Example0 = Example0(u:uint32, b:bool)\n\nmethod Test0(e0:Example0)\n{\n var s := { e0 };\n}\n\ndatatype Example1 = Ex1a(u:uint32) | Ex1b(b:bool)\nmethod Test1(t0:Example1)\n{\n var t := { t0 };\n}\n\nmethod Test(name:string, b:bool)\n requires b\n{\n if b {\n print name, \": This is expected\\n\";\n } else {\n print name, \": This is *** UNEXPECTED *** !!!!\\n\";\n }\n}\n\nmethod Basic() {\n var s:set := {1, 2, 3, 4};\n var t:set := {1, 2, 3, 4};\n\n Test(\"Identity\", s == s);\n Test(\"ValuesIdentity\", s == t);\n Test(\"DiffIdentity\", s - {1} == t - {1});\n Test(\"DiffIdentitySelf\", s - {2} != s - {1});\n Test(\"ProperSubsetIdentity\", !(s < s));\n Test(\"ProperSubset\", !(s < t));\n Test(\"SelfSubset\", s <= s);\n Test(\"OtherSubset\", t <= s && s <= t);\n Test(\"UnionIdentity\", s + s == s);\n Test(\"Membership\", 1 in s);\n Test(\"NonMembership1\", !(5 in s));\n Test(\"NonMembership2\", !(1 in (s - {1})));\n}\n\nmethod SetSeq() {\n var m1:seq := [1];\n var m2:seq := [1, 2];\n var m3:seq := [1, 2, 3];\n var m4:seq := [1, 2, 3, 4];\n var n1:seq := [1];\n var n2:seq := [1, 2];\n var n3:seq := [1, 2, 3];\n\n var s1:set> := { m1, m2, m3 };\n var s2:set> := s1 - { m1 };\n\n Test(\"SeqMembership1\", m1 in s1);\n Test(\"SeqMembership2\", m2 in s1);\n Test(\"SeqMembership3\", m3 in s1);\n Test(\"SeqNonMembership1\", !(m1 in s2));\n Test(\"SeqNonMembership2\", !(m4 in s1));\n Test(\"SeqNonMembership3\", !(m4 in s2));\n\n Test(\"SeqMembershipValue1\", n1 in s1);\n Test(\"SeqMembershipValue2\", n2 in s1);\n Test(\"SeqMembershipValue3\", n3 in s1);\n}\n\nmethod SetComprehension(s:set)\n requires forall i :: 0 <= i < 10 ==> i in s\n requires |s| == 10\n{\n var t:set := set y:uint32 | y in s;\n Test(\"SetComprehensionInEquality\", t == s);\n Test(\"SetComprehensionInMembership\", 0 in t);\n}\n\nmethod LetSuchThat() {\n var s:set := { 0, 1, 2, 3 };\n var e:uint32 :| e in s;\n\n //print e, \"\\n\";\n Test(\"LetSuchThatMembership\", e in s);\n Test(\"LetSuchThatValue\", e == 0 || e == 1 || e == 2 || e == 3);\n}\n\nmethod Contains() {\n var m1:seq := [1];\n var m2:seq := [1, 2];\n var m3:seq := [1, 2, 3];\n var m3identical:seq := [1, 2, 3];\n var mm := [m1, m3, m1];\n\n if m1 in mm {\n print \"Membership 1: This is expected\\n\";\n } else {\n print \"Membership 1: This is unexpected\\n\";\n assert false;\n }\n if m2 in mm {\n print \"Membership 2: This is unexpected\\n\";\n assert false;\n } else {\n print \"Membership 2: This is expected\\n\";\n }\n if m3 in mm {\n print \"Membership 3: This is expected\\n\";\n } else {\n print \"Membership 3: This is unexpected\\n\";\n assert false;\n }\n if m3identical in mm {\n print \"Membership 3 value equality: This is expected\\n\";\n } else {\n print \"Membership 3 value equality: This is unexpected\\n\";\n assert false;\n }\n}\n\nmethod Main() {\n Basic();\n SetSeq();\n var s := { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n SetComprehension(s);\n LetSuchThat();\n}\n\n", "hints_removed": "// RUN: %dafny /compile:3 /spillTargetCode:2 /compileTarget:cpp \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nnewtype uint32 = i:int | 0 <= i < 0x100000000\n\ndatatype Example0 = Example0(u:uint32, b:bool)\n\nmethod Test0(e0:Example0)\n{\n var s := { e0 };\n}\n\ndatatype Example1 = Ex1a(u:uint32) | Ex1b(b:bool)\nmethod Test1(t0:Example1)\n{\n var t := { t0 };\n}\n\nmethod Test(name:string, b:bool)\n requires b\n{\n if b {\n print name, \": This is expected\\n\";\n } else {\n print name, \": This is *** UNEXPECTED *** !!!!\\n\";\n }\n}\n\nmethod Basic() {\n var s:set := {1, 2, 3, 4};\n var t:set := {1, 2, 3, 4};\n\n Test(\"Identity\", s == s);\n Test(\"ValuesIdentity\", s == t);\n Test(\"DiffIdentity\", s - {1} == t - {1});\n Test(\"DiffIdentitySelf\", s - {2} != s - {1});\n Test(\"ProperSubsetIdentity\", !(s < s));\n Test(\"ProperSubset\", !(s < t));\n Test(\"SelfSubset\", s <= s);\n Test(\"OtherSubset\", t <= s && s <= t);\n Test(\"UnionIdentity\", s + s == s);\n Test(\"Membership\", 1 in s);\n Test(\"NonMembership1\", !(5 in s));\n Test(\"NonMembership2\", !(1 in (s - {1})));\n}\n\nmethod SetSeq() {\n var m1:seq := [1];\n var m2:seq := [1, 2];\n var m3:seq := [1, 2, 3];\n var m4:seq := [1, 2, 3, 4];\n var n1:seq := [1];\n var n2:seq := [1, 2];\n var n3:seq := [1, 2, 3];\n\n var s1:set> := { m1, m2, m3 };\n var s2:set> := s1 - { m1 };\n\n Test(\"SeqMembership1\", m1 in s1);\n Test(\"SeqMembership2\", m2 in s1);\n Test(\"SeqMembership3\", m3 in s1);\n Test(\"SeqNonMembership1\", !(m1 in s2));\n Test(\"SeqNonMembership2\", !(m4 in s1));\n Test(\"SeqNonMembership3\", !(m4 in s2));\n\n Test(\"SeqMembershipValue1\", n1 in s1);\n Test(\"SeqMembershipValue2\", n2 in s1);\n Test(\"SeqMembershipValue3\", n3 in s1);\n}\n\nmethod SetComprehension(s:set)\n requires forall i :: 0 <= i < 10 ==> i in s\n requires |s| == 10\n{\n var t:set := set y:uint32 | y in s;\n Test(\"SetComprehensionInEquality\", t == s);\n Test(\"SetComprehensionInMembership\", 0 in t);\n}\n\nmethod LetSuchThat() {\n var s:set := { 0, 1, 2, 3 };\n var e:uint32 :| e in s;\n\n //print e, \"\\n\";\n Test(\"LetSuchThatMembership\", e in s);\n Test(\"LetSuchThatValue\", e == 0 || e == 1 || e == 2 || e == 3);\n}\n\nmethod Contains() {\n var m1:seq := [1];\n var m2:seq := [1, 2];\n var m3:seq := [1, 2, 3];\n var m3identical:seq := [1, 2, 3];\n var mm := [m1, m3, m1];\n\n if m1 in mm {\n print \"Membership 1: This is expected\\n\";\n } else {\n print \"Membership 1: This is unexpected\\n\";\n }\n if m2 in mm {\n print \"Membership 2: This is unexpected\\n\";\n } else {\n print \"Membership 2: This is expected\\n\";\n }\n if m3 in mm {\n print \"Membership 3: This is expected\\n\";\n } else {\n print \"Membership 3: This is unexpected\\n\";\n }\n if m3identical in mm {\n print \"Membership 3 value equality: This is expected\\n\";\n } else {\n print \"Membership 3 value equality: This is unexpected\\n\";\n }\n}\n\nmethod Main() {\n Basic();\n SetSeq();\n var s := { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n SetComprehension(s);\n LetSuchThat();\n}\n\n" }, { "test_ID": "704", "test_file": "ironsync-osdi2023_tmp_tmpx80antoe_linear-dafny_Test_git-issues_git-issue-1158.dfy", "ground_truth": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\ntype Id(==)\n\nfunction F(s: set): int\n\nlemma Test(x: Id)\n{\n var X := {x};\n var a := map i | i <= X :: F(i);\n var b := map[{} := F({}), X := F(X)];\n\n assert a.Keys == b.Keys by { // spurious error reported here\n forall i\n ensures i in a.Keys <==> i in b.Keys\n {\n calc {\n i in a.Keys;\n ==\n i <= X;\n == { assert i <= X <==> i == {} || i == X; }\n i in b.Keys;\n }\n }\n }\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\ntype Id(==)\n\nfunction F(s: set): int\n\nlemma Test(x: Id)\n{\n var X := {x};\n var a := map i | i <= X :: F(i);\n var b := map[{} := F({}), X := F(X)];\n\n forall i\n ensures i in a.Keys <==> i in b.Keys\n {\n calc {\n i in a.Keys;\n ==\n i <= X;\n == { assert i <= X <==> i == {} || i == X; }\n i in b.Keys;\n }\n }\n }\n}\n\n" }, { "test_ID": "705", "test_file": "ironsync-osdi2023_tmp_tmpx80antoe_linear-dafny_Test_git-issues_git-issue-283.dfy", "ground_truth": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %dafny /noVerify /compile:4 /compileTarget:cs \"%s\" >> \"%t\"\n// RUN: %dafny /noVerify /compile:4 /compileTarget:js \"%s\" >> \"%t\"\n// RUN: %dafny /noVerify /compile:4 /compileTarget:go \"%s\" >> \"%t\"\n// RUN: %dafny /noVerify /compile:4 /compileTarget:java \"%s\" >> \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\ndatatype Result =\n | Success(value: T)\n | Failure(error: string)\n\ndatatype C = C1 | C2(x: int)\n\ntrait Foo\n{\n method FooMethod1(r: Result<()>)\n ensures\n match r {\n case Success(()) => true // OK\n case Failure(e) => true\n }\n {\n var x: int := 0;\n match r {\n case Success(()) => x := 1;\n case Failure(e) => x := 2;\n }\n assert x > 0;\n expect x == 1;\n }\n method FooMethod2(r: Result)\n ensures\n match r {\n case Success(C1()) => true // OK\n case Success(C2(x)) => true // OK\n case Failure(e) => true\n }\n {\n var x: int := 0;\n match r {\n case Success(C1()) => x := 1;\n case Success(C2(_)) => x := 2;\n case Failure(e) => x := 3;\n }\n assert x > 0;\n expect x == 1;\n }\n method FooMethod2q(r: Result)\n ensures\n match r {\n case Success(C1()) => true // OK\n case Success(C2(x)) => true // OK\n case Failure(e) => true\n }\n {\n var x: int := 0;\n match r {\n case Success(C1()) => x := 1;\n case Success(C2(x)) => x := 2; // x is local variable\n case Failure(e) => x := 3;\n }\n assert x == 0 || x == 1 || x == 3;\n expect x == 0 || x == 1 || x == 3;\n }\n method FooMethod2r(r: Result)\n ensures\n match r {\n case Success(C1()) => true // OK\n case Success(C2(x)) => true // OK\n case Failure(e) => true\n }\n {\n var x: real := 0.0;\n match r {\n case Success(C1()) => x := 1.0;\n case Success(C2(x)) => x := 2; // x is local variable\n case Failure(e) => x := 3.0;\n }\n assert x == 0.0 || x == 1.0 || x == 3.0;\n expect x == 0.0 || x == 1.0 || x == 3.0;\n }\n method FooMethod3(r: Result)\n ensures\n match r {\n case Success(C1) => true // OK\n case Success(C2(x)) => true // OK\n case Failure(e) => true\n }\n {\n var x: int := 0;\n match r {\n case Success(C1) => x := 1;\n case Success(C2(_)) => x := 2; // BUG - problem if _ is x\n case Failure(e) => x := 3;\n }\n assert x > 0;\n expect x == 1;\n }\n method FooMethod4(r: Result)\n ensures\n match r {\n case Success(C2) => true // OK -- C2 is a variable\n case Failure(e) => true\n }\n {\n var x: int := 0;\n match r {\n case Success(C2) => x := 1;\n case Failure(e) => x := 2;\n }\n assert x > 0;\n expect x == 1;\n }\n method FooMethod5(r: Result)\n ensures\n match r {\n case Success(C1) => true // OK -- C1 is a variable\n case Failure(e) => true\n }\n {\n var x: int := 0;\n match r {\n case Success(C1) => x := 1;\n case Failure(e) => x := 2;\n }\n assert x > 0;\n expect x == 1;\n }\n}\n\nclass CL extends Foo {}\n\nmethod Main() {\n var t := new CL;\n m(t);\n}\n\nmethod m(t: Foo) {\n t.FooMethod1(Result.Success(()));\n t.FooMethod2(Result.Success(C1));\n t.FooMethod2q(Result.Success(C1));\n t.FooMethod2r(Result.Success(C1));\n t.FooMethod3(Result.Success(C1));\n t.FooMethod4(Result.Success(C1));\n t.FooMethod5(Result.Success(\"\"));\n print \"Done\\n\";\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %dafny /noVerify /compile:4 /compileTarget:cs \"%s\" >> \"%t\"\n// RUN: %dafny /noVerify /compile:4 /compileTarget:js \"%s\" >> \"%t\"\n// RUN: %dafny /noVerify /compile:4 /compileTarget:go \"%s\" >> \"%t\"\n// RUN: %dafny /noVerify /compile:4 /compileTarget:java \"%s\" >> \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\ndatatype Result =\n | Success(value: T)\n | Failure(error: string)\n\ndatatype C = C1 | C2(x: int)\n\ntrait Foo\n{\n method FooMethod1(r: Result<()>)\n ensures\n match r {\n case Success(()) => true // OK\n case Failure(e) => true\n }\n {\n var x: int := 0;\n match r {\n case Success(()) => x := 1;\n case Failure(e) => x := 2;\n }\n expect x == 1;\n }\n method FooMethod2(r: Result)\n ensures\n match r {\n case Success(C1()) => true // OK\n case Success(C2(x)) => true // OK\n case Failure(e) => true\n }\n {\n var x: int := 0;\n match r {\n case Success(C1()) => x := 1;\n case Success(C2(_)) => x := 2;\n case Failure(e) => x := 3;\n }\n expect x == 1;\n }\n method FooMethod2q(r: Result)\n ensures\n match r {\n case Success(C1()) => true // OK\n case Success(C2(x)) => true // OK\n case Failure(e) => true\n }\n {\n var x: int := 0;\n match r {\n case Success(C1()) => x := 1;\n case Success(C2(x)) => x := 2; // x is local variable\n case Failure(e) => x := 3;\n }\n expect x == 0 || x == 1 || x == 3;\n }\n method FooMethod2r(r: Result)\n ensures\n match r {\n case Success(C1()) => true // OK\n case Success(C2(x)) => true // OK\n case Failure(e) => true\n }\n {\n var x: real := 0.0;\n match r {\n case Success(C1()) => x := 1.0;\n case Success(C2(x)) => x := 2; // x is local variable\n case Failure(e) => x := 3.0;\n }\n expect x == 0.0 || x == 1.0 || x == 3.0;\n }\n method FooMethod3(r: Result)\n ensures\n match r {\n case Success(C1) => true // OK\n case Success(C2(x)) => true // OK\n case Failure(e) => true\n }\n {\n var x: int := 0;\n match r {\n case Success(C1) => x := 1;\n case Success(C2(_)) => x := 2; // BUG - problem if _ is x\n case Failure(e) => x := 3;\n }\n expect x == 1;\n }\n method FooMethod4(r: Result)\n ensures\n match r {\n case Success(C2) => true // OK -- C2 is a variable\n case Failure(e) => true\n }\n {\n var x: int := 0;\n match r {\n case Success(C2) => x := 1;\n case Failure(e) => x := 2;\n }\n expect x == 1;\n }\n method FooMethod5(r: Result)\n ensures\n match r {\n case Success(C1) => true // OK -- C1 is a variable\n case Failure(e) => true\n }\n {\n var x: int := 0;\n match r {\n case Success(C1) => x := 1;\n case Failure(e) => x := 2;\n }\n expect x == 1;\n }\n}\n\nclass CL extends Foo {}\n\nmethod Main() {\n var t := new CL;\n m(t);\n}\n\nmethod m(t: Foo) {\n t.FooMethod1(Result.Success(()));\n t.FooMethod2(Result.Success(C1));\n t.FooMethod2q(Result.Success(C1));\n t.FooMethod2r(Result.Success(C1));\n t.FooMethod3(Result.Success(C1));\n t.FooMethod4(Result.Success(C1));\n t.FooMethod5(Result.Success(\"\"));\n print \"Done\\n\";\n}\n\n" }, { "test_ID": "706", "test_file": "ironsync-osdi2023_tmp_tmpx80antoe_linear-dafny_Test_git-issues_git-issue-506.dfy", "ground_truth": "// RUN: %dafny /compile:4 /compileTarget:cs \"%s\" > \"%t\"\n// RUN: %dafny /compile:4 /compileTarget:js \"%s\" >> \"%t\"\n// RUN: %dafny /compile:4 /compileTarget:go \"%s\" >> \"%t\"\n// RUN: %dafny /compile:4 /compileTarget:java \"%s\" >> \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nmethod Main() {\n\n var a := new int[10];\n var index := 6;\n a[8] := 1;\n a[index], index := 3, index+1;\n assert a[6] == 3;\n assert index == 7;\n print index, \" \", a[6], a[7], a[8], \"\\n\"; // Should be: \"7 301\"\n index, a[index] := index+1, 9;\n assert index == 8;\n assert a[7] == 9;\n assert a[8] == 1; // Assertion is OK\n expect a[8] == 1; // This failed before the bug fix\n print index, \" \", a[6], a[7], a[8], \"\\n\"; // Should be \"8 391\" not \"8 309\"\n\n a[index+1], index := 7, 6;\n assert a[9] == 7 && index == 6;\n expect a[9] == 7 && index == 6;\n\n var o := new F(2);\n var oo := o;\n print o.f, \" \", oo.f, \"\\n\";\n assert o.f == 2;\n assert oo.f == 2;\n var ooo := new F(4);\n o.f, o := 5, ooo;\n print o.f, \" \", oo.f, \"\\n\";\n assert o.f == 4;\n assert oo.f == 5;\n var oooo := new F(6);\n o, o.f := oooo, 7;\n assert o.f == 6;\n assert ooo.f == 7;\n expect ooo.f == 7; // This failed before the bug fix\n print o.f, \" \", ooo.f, \"\\n\";\n\n var aa := new int[9,9];\n var j := 4;\n var k := 5;\n aa[j,k] := 8;\n j, k, aa[j,k] := 2, 3, 7;\n print j, \" \", k, \" \", aa[4,5], \" \", aa[2,3], \"\\n\"; // Should be 2 3 7 0\n assert aa[4,5] == 7;\n expect aa[4,5] == 7; // This failed before the bug fix\n j, aa[j,k], k := 5, 6, 1;\n assert j == 5 && aa[2,3] == 6 && k == 1;\n expect j == 5 && aa[2,3] == 6 && k == 1; // This failed before the bug fix\n aa[j,k], k, j := 5, 6, 1;\n assert j == 1 && aa[5,1] == 5 && k == 6;\n expect j == 1 && aa[5,1] == 5 && k == 6;\n}\n\nclass F {\n var f: int;\n constructor (f: int) ensures this.f == f { this.f := f; }\n}\n\n", "hints_removed": "// RUN: %dafny /compile:4 /compileTarget:cs \"%s\" > \"%t\"\n// RUN: %dafny /compile:4 /compileTarget:js \"%s\" >> \"%t\"\n// RUN: %dafny /compile:4 /compileTarget:go \"%s\" >> \"%t\"\n// RUN: %dafny /compile:4 /compileTarget:java \"%s\" >> \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nmethod Main() {\n\n var a := new int[10];\n var index := 6;\n a[8] := 1;\n a[index], index := 3, index+1;\n print index, \" \", a[6], a[7], a[8], \"\\n\"; // Should be: \"7 301\"\n index, a[index] := index+1, 9;\n expect a[8] == 1; // This failed before the bug fix\n print index, \" \", a[6], a[7], a[8], \"\\n\"; // Should be \"8 391\" not \"8 309\"\n\n a[index+1], index := 7, 6;\n expect a[9] == 7 && index == 6;\n\n var o := new F(2);\n var oo := o;\n print o.f, \" \", oo.f, \"\\n\";\n var ooo := new F(4);\n o.f, o := 5, ooo;\n print o.f, \" \", oo.f, \"\\n\";\n var oooo := new F(6);\n o, o.f := oooo, 7;\n expect ooo.f == 7; // This failed before the bug fix\n print o.f, \" \", ooo.f, \"\\n\";\n\n var aa := new int[9,9];\n var j := 4;\n var k := 5;\n aa[j,k] := 8;\n j, k, aa[j,k] := 2, 3, 7;\n print j, \" \", k, \" \", aa[4,5], \" \", aa[2,3], \"\\n\"; // Should be 2 3 7 0\n expect aa[4,5] == 7; // This failed before the bug fix\n j, aa[j,k], k := 5, 6, 1;\n expect j == 5 && aa[2,3] == 6 && k == 1; // This failed before the bug fix\n aa[j,k], k, j := 5, 6, 1;\n expect j == 1 && aa[5,1] == 5 && k == 6;\n}\n\nclass F {\n var f: int;\n constructor (f: int) ensures this.f == f { this.f := f; }\n}\n\n" }, { "test_ID": "707", "test_file": "ironsync-osdi2023_tmp_tmpx80antoe_linear-dafny_Test_git-issues_git-issue-975.dfy", "ground_truth": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nfunction f():nat\n ensures f() == 0\n{ // no problem for methods\n var x := 0; // no problem without this\n assert true by {}\n 0\n}\n\n", "hints_removed": "// RUN: %dafny /compile:0 \"%s\" > \"%t\"\n// RUN: %diff \"%s.expect\" \"%t\"\n\nfunction f():nat\n ensures f() == 0\n{ // no problem for methods\n var x := 0; // no problem without this\n 0\n}\n\n" }, { "test_ID": "708", "test_file": "ironsync-osdi2023_tmp_tmpx80antoe_linear-dafny_docs_DafnyRef_examples_Example-Old.dfy", "ground_truth": "class A {\n\n var value: int\n\n method m(i: int)\n requires i == 6\n requires value == 42\n modifies this\n {\n var j: int := 17;\n value := 43;\n label L:\n j := 18;\n value := 44;\n label M:\n assert old(i) == 6; // i is local, but can't be changed anyway\n assert old(j) == 18; // j is local and not affected by old\n assert old@L(j) == 18; // j is local and not affected by old\n assert old(value) == 42;\n assert old@L(value) == 43;\n assert old@M(value) == 44 && this.value == 44;\n // value is this.value; 'this' is the same\n // same reference in current and pre state but the\n // values stored in the heap as its fields are different;\n // '.value' evaluates to 42 in the pre-state, 43 at L,\n // and 44 in the current state\n }\n}\n\n", "hints_removed": "class A {\n\n var value: int\n\n method m(i: int)\n requires i == 6\n requires value == 42\n modifies this\n {\n var j: int := 17;\n value := 43;\n label L:\n j := 18;\n value := 44;\n label M:\n // value is this.value; 'this' is the same\n // same reference in current and pre state but the\n // values stored in the heap as its fields are different;\n // '.value' evaluates to 42 in the pre-state, 43 at L,\n // and 44 in the current state\n }\n}\n\n" }, { "test_ID": "709", "test_file": "ironsync-osdi2023_tmp_tmpx80antoe_linear-dafny_docs_DafnyRef_examples_Example-Old2.dfy", "ground_truth": "class A {\n var value: int\n constructor ()\n ensures value == 10\n {\n value := 10;\n }\n}\n\nclass B {\n var a: A\n constructor () { a := new A(); }\n\n method m()\n requires a.value == 11\n modifies this, this.a\n {\n label L:\n a.value := 12;\n label M:\n a := new A(); // Line X\n label N:\n a.value := 20;\n label P:\n\n assert old(a.value) == 11;\n assert old(a).value == 12; // this.a is from pre-state,\n // but .value in current state\n assert old@L(a.value) == 11;\n assert old@L(a).value == 12; // same as above\n assert old@M(a.value) == 12; // .value in M state is 12\n assert old@M(a).value == 12;\n assert old@N(a.value) == 10; // this.a in N is the heap\n // reference at Line X\n assert old@N(a).value == 20; // .value in current state is 20\n assert old@P(a.value) == 20;\n assert old@P(a).value == 20;\n }\n}\n\n", "hints_removed": "class A {\n var value: int\n constructor ()\n ensures value == 10\n {\n value := 10;\n }\n}\n\nclass B {\n var a: A\n constructor () { a := new A(); }\n\n method m()\n requires a.value == 11\n modifies this, this.a\n {\n label L:\n a.value := 12;\n label M:\n a := new A(); // Line X\n label N:\n a.value := 20;\n label P:\n\n // but .value in current state\n // reference at Line X\n }\n}\n\n" }, { "test_ID": "710", "test_file": "ironsync-osdi2023_tmp_tmpx80antoe_linear-dafny_docs_DafnyRef_examples_Example-Old3.dfy", "ground_truth": "class A {\n var z1: array\n var z2: array\n\n method mm()\n requires z1.Length > 10 && z1[0] == 7\n requires z2.Length > 10 && z2[0] == 17\n modifies z2\n {\n var a: array := z1;\n assert a[0] == 7;\n a := z2;\n assert a[0] == 17;\n assert old(a[0]) == 17; // a is local with value z2\n z2[0] := 27;\n assert old(a[0]) == 17; // a is local, with current value of\n // z2; in pre-state z2[0] == 17\n assert old(a)[0] == 27; // a is local, with current value of\n // z2; z2[0] is currently 27\n }\n}\n\n", "hints_removed": "class A {\n var z1: array\n var z2: array\n\n method mm()\n requires z1.Length > 10 && z1[0] == 7\n requires z2.Length > 10 && z2[0] == 17\n modifies z2\n {\n var a: array := z1;\n a := z2;\n z2[0] := 27;\n // z2; in pre-state z2[0] == 17\n // z2; z2[0] is currently 27\n }\n}\n\n" }, { "test_ID": "711", "test_file": "laboratory_tmp_tmps8ws6mu2_dafny-tutorial_exercise12.dfy", "ground_truth": "method FindMax(a: array) returns (i: int)\n // Annotate this method with pre- and postconditions\n // that ensure it behaves as described.\n requires 0 < a.Length\n ensures 0 <= i < a.Length\n ensures forall k: int :: 0 <= k < a.Length ==> a[k] <= a[i]\n{\n // Fill in the body that calculates the INDEX of the maximum.\n var j := 0;\n var max := a[0];\n i := 1;\n while i < a.Length\n invariant 1 <= i <= a.Length\n invariant forall k: int :: 0 <= k < i ==> max >= a[k]\n invariant 0 <= j < a.Length\n invariant a[j] == max\n decreases a.Length - i\n {\n if max < a[i] {\n max := a[i];\n j := i;\n }\n i := i + 1;\n }\n\n i := j;\n}\n", "hints_removed": "method FindMax(a: array) returns (i: int)\n // Annotate this method with pre- and postconditions\n // that ensure it behaves as described.\n requires 0 < a.Length\n ensures 0 <= i < a.Length\n ensures forall k: int :: 0 <= k < a.Length ==> a[k] <= a[i]\n{\n // Fill in the body that calculates the INDEX of the maximum.\n var j := 0;\n var max := a[0];\n i := 1;\n while i < a.Length\n {\n if max < a[i] {\n max := a[i];\n j := i;\n }\n i := i + 1;\n }\n\n i := j;\n}\n" }, { "test_ID": "712", "test_file": "laboratory_tmp_tmps8ws6mu2_dafny-tutorial_exercise9.dfy", "ground_truth": "function fib(n: nat): nat\n{\n if n == 0 then 0 else\n if n == 1 then 1 else\n fib(n - 1) + fib(n - 2)\n}\n\nmethod ComputeFib(n: nat) returns (b: nat)\n ensures b == fib(n) // Do not change this postcondition\n{\n // Change the method body to instead use c as described.\n // You will need to change both the initialization and the loop.\n var i: int := 0;\n b := 0;\n var c := 1;\n while i < n\n invariant 0 <= i <= n\n invariant b == fib(i)\n invariant c == fib(i + 1)\n {\n b, c := c, c + b;\n i := i + 1;\n }\n}\n", "hints_removed": "function fib(n: nat): nat\n{\n if n == 0 then 0 else\n if n == 1 then 1 else\n fib(n - 1) + fib(n - 2)\n}\n\nmethod ComputeFib(n: nat) returns (b: nat)\n ensures b == fib(n) // Do not change this postcondition\n{\n // Change the method body to instead use c as described.\n // You will need to change both the initialization and the loop.\n var i: int := 0;\n b := 0;\n var c := 1;\n while i < n\n {\n b, c := c, c + b;\n i := i + 1;\n }\n}\n" }, { "test_ID": "713", "test_file": "lets-prove-blocking-queue_tmp_tmptd_aws1k_dafny_prod-cons.dfy", "ground_truth": "/**\n * A proof in Dafny of the non blocking property of a queue.\n * @author Franck Cassez.\n *\n * @note: based off Modelling Concurrency in Dafny, K.R.M. Leino\n * @link{http://leino.science/papers/krml260.pdf}\n */\nmodule ProdCons {\n\n // A type for process id that supports equality (i.e. p == q is defined).\n type Process(==) \n\n // A type for the elemets in the buffer.\n type T\n\n /**\n * The producer/consumer problem.\n * The set of processes is actuall irrelevant (included here because part of the \n * original problem statement ...)\n */\n class ProdCons { \n\n /**\n * Set of processes in the system.\n */\n const P: set\n\n /**\n * The maximal size of the buffer.\n */\n var maxBufferSize : nat \n\n /**\n * The buffer.\n */\n var buffer : seq \n\n /**\n * Invariant.\n *\n * Buffer should always less than maxBufferSize elements,\n * Set of processes is not empty\n * \n */\n predicate valid() \n reads this\n {\n maxBufferSize > 0 && P != {} &&\n 0 <= |buffer| <= maxBufferSize \n }\n \n /**\n * Initialise set of processes and buffer and maxBufferSize\n */\n constructor (processes: set, m: nat ) \n requires processes != {} // Non empty set of processes.\n requires m >= 1 // Buffer as at least one cell.\n ensures valid() // After initilisation the invariant is true\n { \n P := processes;\n buffer := [];\n maxBufferSize := m;\n }\n\n /**\n * Enabledness of a put operation.\n * If enabled any process can perform a put.\n */\n predicate putEnabled(p : Process) \n reads this\n {\n |buffer| < maxBufferSize\n }\n\n /** Event: a process puts an element in the queue. */\n method put(p: Process, t : T) \n requires valid() \n requires putEnabled(p) // |buffer| < maxBufferSize\n modifies this \n { \n buffer := buffer + [t] ;\n }\n\n /**\n * Enabledness of a get operation. \n * If enabled, any process can perform a get.\n */\n predicate getEnabled(p : Process) \n reads this\n {\n |buffer| >= 1\n }\n\n /** Event: a process gets an element from the queue. */\n method get(p: Process) \n requires getEnabled(p)\n requires valid() // Invariant is inductive\n ensures |buffer| == |old(buffer)| - 1 // this invariant is not needed and can be omitted\n modifies this \n { \n // remove the first element of buffer.\n // note: Dafny implcitly proves that the tail operation can be performed\n // as a consequence of |buffer| >= 1 (getEnabled()). \n // To see this, comment out the\n // requires and an error shows up.\n buffer := buffer[1..];\n }\n \n /** Correctness theorem: no deadlock. \n * From any valid state, at least one process is enabled.\n */\n lemma noDeadlock() \n requires valid() \n ensures exists p :: p in P && (getEnabled(p) || putEnabled(p))\n\n // as processes are irrelevant, this could be simplified\n // into isBufferNotFull() or isBufferNotEmpty()\n { \n // Dafny automatically proves this. so we can leave the\n // body of this lemma empty.\n // But for the sake of clarity, here is the proof.\n\n // P is not empty so there is a process p in P\n // Reads as: select a p of type Process such that p in P\n var p: Process :| p in P ;\n // Now we have a p.\n // We are going to use the fact that valid() must hold as it is a pre-condition\n if ( |buffer| > 0 ) {\n assert (getEnabled(p));\n }\n else {\n // You may comment out the following asserts and Dafny\n // can figure out the proof from the constraints that are\n // true in this case.\n // Becas=use |buffer| == 0 and maxBufferSize >= 1, we can do a put\n assert(|buffer| == 0);\n assert (|buffer| < maxBufferSize); \n assert(putEnabled(p));\n }\n }\n }\n}\n\n\n\n\n\n", "hints_removed": "/**\n * A proof in Dafny of the non blocking property of a queue.\n * @author Franck Cassez.\n *\n * @note: based off Modelling Concurrency in Dafny, K.R.M. Leino\n * @link{http://leino.science/papers/krml260.pdf}\n */\nmodule ProdCons {\n\n // A type for process id that supports equality (i.e. p == q is defined).\n type Process(==) \n\n // A type for the elemets in the buffer.\n type T\n\n /**\n * The producer/consumer problem.\n * The set of processes is actuall irrelevant (included here because part of the \n * original problem statement ...)\n */\n class ProdCons { \n\n /**\n * Set of processes in the system.\n */\n const P: set\n\n /**\n * The maximal size of the buffer.\n */\n var maxBufferSize : nat \n\n /**\n * The buffer.\n */\n var buffer : seq \n\n /**\n * Invariant.\n *\n * Buffer should always less than maxBufferSize elements,\n * Set of processes is not empty\n * \n */\n predicate valid() \n reads this\n {\n maxBufferSize > 0 && P != {} &&\n 0 <= |buffer| <= maxBufferSize \n }\n \n /**\n * Initialise set of processes and buffer and maxBufferSize\n */\n constructor (processes: set, m: nat ) \n requires processes != {} // Non empty set of processes.\n requires m >= 1 // Buffer as at least one cell.\n ensures valid() // After initilisation the invariant is true\n { \n P := processes;\n buffer := [];\n maxBufferSize := m;\n }\n\n /**\n * Enabledness of a put operation.\n * If enabled any process can perform a put.\n */\n predicate putEnabled(p : Process) \n reads this\n {\n |buffer| < maxBufferSize\n }\n\n /** Event: a process puts an element in the queue. */\n method put(p: Process, t : T) \n requires valid() \n requires putEnabled(p) // |buffer| < maxBufferSize\n modifies this \n { \n buffer := buffer + [t] ;\n }\n\n /**\n * Enabledness of a get operation. \n * If enabled, any process can perform a get.\n */\n predicate getEnabled(p : Process) \n reads this\n {\n |buffer| >= 1\n }\n\n /** Event: a process gets an element from the queue. */\n method get(p: Process) \n requires getEnabled(p)\n requires valid() // Invariant is inductive\n ensures |buffer| == |old(buffer)| - 1 // this invariant is not needed and can be omitted\n modifies this \n { \n // remove the first element of buffer.\n // note: Dafny implcitly proves that the tail operation can be performed\n // as a consequence of |buffer| >= 1 (getEnabled()). \n // To see this, comment out the\n // requires and an error shows up.\n buffer := buffer[1..];\n }\n \n /** Correctness theorem: no deadlock. \n * From any valid state, at least one process is enabled.\n */\n lemma noDeadlock() \n requires valid() \n ensures exists p :: p in P && (getEnabled(p) || putEnabled(p))\n\n // as processes are irrelevant, this could be simplified\n // into isBufferNotFull() or isBufferNotEmpty()\n { \n // Dafny automatically proves this. so we can leave the\n // body of this lemma empty.\n // But for the sake of clarity, here is the proof.\n\n // P is not empty so there is a process p in P\n // Reads as: select a p of type Process such that p in P\n var p: Process :| p in P ;\n // Now we have a p.\n // We are going to use the fact that valid() must hold as it is a pre-condition\n if ( |buffer| > 0 ) {\n }\n else {\n // You may comment out the following asserts and Dafny\n // can figure out the proof from the constraints that are\n // true in this case.\n // Becas=use |buffer| == 0 and maxBufferSize >= 1, we can do a put\n }\n }\n }\n}\n\n\n\n\n\n" }, { "test_ID": "714", "test_file": "libraries_tmp_tmp9gegwhqj_examples_MutableMap_MutableMapDafny.dfy", "ground_truth": "/*******************************************************************************\n* Copyright by the contributors to the Dafny Project\n* SPDX-License-Identifier: MIT\n*******************************************************************************/\n\n// RUN: %verify \"%s\"\n \n/**\n * Implements mutable maps in Dafny to guard against inconsistent specifications.\n * Only exists to verify feasability; not meant for actual usage.\n */\nmodule {:options \"-functionSyntax:4\"} MutableMapDafny {\n /**\n * NOTE: Only here because of #2500; once resolved import \"MutableMapTrait.dfy\".\n */\n trait {:termination false} MutableMapTrait {\n function content(): map\n reads this\n\n method Put(k: K, v: V)\n modifies this\n ensures this.content() == old(this.content())[k := v] \n ensures k in old(this.content()).Keys ==> this.content().Values + {old(this.content())[k]} == old(this.content()).Values + {v}\n ensures k !in old(this.content()).Keys ==> this.content().Values == old(this.content()).Values + {v}\n\n function Keys(): (keys: set)\n reads this\n ensures keys == this.content().Keys\n\n predicate HasKey(k: K)\n reads this\n ensures HasKey(k) <==> k in this.content().Keys\n\n function Values(): (values: set)\n reads this\n ensures values == this.content().Values\n\n function Items(): (items: set<(K,V)>)\n reads this\n ensures items == this.content().Items\n ensures items == set k | k in this.content().Keys :: (k, this.content()[k])\n\n function Select(k: K): (v: V)\n reads this\n requires this.HasKey(k)\n ensures v in this.content().Values\n ensures this.content()[k] == v\n\n method Remove(k: K)\n modifies this\n ensures this.content() == old(this.content()) - {k}\n ensures k in old(this.content()).Keys ==> this.content().Values + {old(this.content())[k]} == old(this.content()).Values\n \n function Size(): (size: int)\n reads this\n ensures size == |this.content().Items|\n }\n\n class MutableMapDafny extends MutableMapTrait {\n var m: map\n\n function content(): map \n reads this\n {\n m\n }\n\n constructor ()\n ensures this.content() == map[]\n {\n m := map[];\n }\n\n method Put(k: K, v: V)\n modifies this\n ensures this.content() == old(this.content())[k := v] \n ensures k in old(this.content()).Keys ==> this.content().Values + {old(this.content())[k]} == old(this.content()).Values + {v}\n ensures k !in old(this.content()).Keys ==> this.content().Values == old(this.content()).Values + {v}\n {\n m := m[k := v];\n if k in old(m).Keys {\n forall v' | v' in old(m).Values + {v} ensures v' in m.Values + {old(m)[k]} {\n if v' == v || v' == old(m)[k] {\n assert m[k] == v;\n } else {\n assert m.Keys == old(m).Keys + {k};\n }\n }\n }\n if k !in old(m).Keys {\n forall v' | v' in old(m).Values + {v} ensures v' in m.Values {\n if v' == v {\n assert m[k] == v;\n assert m[k] == v';\n assert v' in m.Values;\n } else {\n assert m.Keys == old(m).Keys + {k};\n }\n }\n }\n }\n\n function Keys(): (keys: set)\n reads this\n ensures keys == this.content().Keys\n {\n m.Keys\n }\n\n predicate HasKey(k: K)\n reads this\n ensures HasKey(k) <==> k in this.content().Keys\n {\n k in m.Keys\n }\n\n function Values(): (values: set)\n reads this\n ensures values == this.content().Values\n {\n m.Values\n }\n\n function Items(): (items: set<(K,V)>)\n reads this\n ensures items == this.content().Items\n ensures items == set k | k in this.content().Keys :: (k, this.content()[k])\n {\n var items := set k | k in m.Keys :: (k, m[k]);\n assert items == m.Items by {\n forall k | k in m.Keys ensures (k, m[k]) in m.Items {\n assert (k, m[k]) in m.Items;\n }\n assert items <= m.Items;\n forall x | x in m.Items ensures x in items {\n assert (x.0, m[x.0]) in items;\n }\n assert m.Items <= items;\n }\n items\n }\n\n function Select(k: K): (v: V)\n reads this\n requires this.HasKey(k)\n ensures v in this.content().Values\n ensures this.content()[k] == v\n {\n m[k]\n }\n\n method Remove(k: K)\n modifies this\n ensures this.content() == old(this.content()) - {k}\n ensures k in old(this.content()).Keys ==> this.content().Values + {old(this.content())[k]} == old(this.content()).Values\n {\n m := map k' | k' in m.Keys && k' != k :: m[k'];\n if k in old(m).Keys {\n var v := old(m)[k];\n forall v' | v' in old(m).Values ensures v' in m.Values + {v} {\n if v' == v {\n } else {\n assert exists k' | k' in m.Keys :: old(m)[k'] == v';\n }\n }\n }\n }\n\n function Size(): (size: int)\n reads this\n ensures size == |this.content().Items|\n {\n |m|\n }\n }\n}\n", "hints_removed": "/*******************************************************************************\n* Copyright by the contributors to the Dafny Project\n* SPDX-License-Identifier: MIT\n*******************************************************************************/\n\n// RUN: %verify \"%s\"\n \n/**\n * Implements mutable maps in Dafny to guard against inconsistent specifications.\n * Only exists to verify feasability; not meant for actual usage.\n */\nmodule {:options \"-functionSyntax:4\"} MutableMapDafny {\n /**\n * NOTE: Only here because of #2500; once resolved import \"MutableMapTrait.dfy\".\n */\n trait {:termination false} MutableMapTrait {\n function content(): map\n reads this\n\n method Put(k: K, v: V)\n modifies this\n ensures this.content() == old(this.content())[k := v] \n ensures k in old(this.content()).Keys ==> this.content().Values + {old(this.content())[k]} == old(this.content()).Values + {v}\n ensures k !in old(this.content()).Keys ==> this.content().Values == old(this.content()).Values + {v}\n\n function Keys(): (keys: set)\n reads this\n ensures keys == this.content().Keys\n\n predicate HasKey(k: K)\n reads this\n ensures HasKey(k) <==> k in this.content().Keys\n\n function Values(): (values: set)\n reads this\n ensures values == this.content().Values\n\n function Items(): (items: set<(K,V)>)\n reads this\n ensures items == this.content().Items\n ensures items == set k | k in this.content().Keys :: (k, this.content()[k])\n\n function Select(k: K): (v: V)\n reads this\n requires this.HasKey(k)\n ensures v in this.content().Values\n ensures this.content()[k] == v\n\n method Remove(k: K)\n modifies this\n ensures this.content() == old(this.content()) - {k}\n ensures k in old(this.content()).Keys ==> this.content().Values + {old(this.content())[k]} == old(this.content()).Values\n \n function Size(): (size: int)\n reads this\n ensures size == |this.content().Items|\n }\n\n class MutableMapDafny extends MutableMapTrait {\n var m: map\n\n function content(): map \n reads this\n {\n m\n }\n\n constructor ()\n ensures this.content() == map[]\n {\n m := map[];\n }\n\n method Put(k: K, v: V)\n modifies this\n ensures this.content() == old(this.content())[k := v] \n ensures k in old(this.content()).Keys ==> this.content().Values + {old(this.content())[k]} == old(this.content()).Values + {v}\n ensures k !in old(this.content()).Keys ==> this.content().Values == old(this.content()).Values + {v}\n {\n m := m[k := v];\n if k in old(m).Keys {\n forall v' | v' in old(m).Values + {v} ensures v' in m.Values + {old(m)[k]} {\n if v' == v || v' == old(m)[k] {\n } else {\n }\n }\n }\n if k !in old(m).Keys {\n forall v' | v' in old(m).Values + {v} ensures v' in m.Values {\n if v' == v {\n } else {\n }\n }\n }\n }\n\n function Keys(): (keys: set)\n reads this\n ensures keys == this.content().Keys\n {\n m.Keys\n }\n\n predicate HasKey(k: K)\n reads this\n ensures HasKey(k) <==> k in this.content().Keys\n {\n k in m.Keys\n }\n\n function Values(): (values: set)\n reads this\n ensures values == this.content().Values\n {\n m.Values\n }\n\n function Items(): (items: set<(K,V)>)\n reads this\n ensures items == this.content().Items\n ensures items == set k | k in this.content().Keys :: (k, this.content()[k])\n {\n var items := set k | k in m.Keys :: (k, m[k]);\n forall k | k in m.Keys ensures (k, m[k]) in m.Items {\n }\n forall x | x in m.Items ensures x in items {\n }\n }\n items\n }\n\n function Select(k: K): (v: V)\n reads this\n requires this.HasKey(k)\n ensures v in this.content().Values\n ensures this.content()[k] == v\n {\n m[k]\n }\n\n method Remove(k: K)\n modifies this\n ensures this.content() == old(this.content()) - {k}\n ensures k in old(this.content()).Keys ==> this.content().Values + {old(this.content())[k]} == old(this.content()).Values\n {\n m := map k' | k' in m.Keys && k' != k :: m[k'];\n if k in old(m).Keys {\n var v := old(m)[k];\n forall v' | v' in old(m).Values ensures v' in m.Values + {v} {\n if v' == v {\n } else {\n }\n }\n }\n }\n\n function Size(): (size: int)\n reads this\n ensures size == |this.content().Items|\n {\n |m|\n }\n }\n}\n" }, { "test_ID": "715", "test_file": "llm-verified-eval_tmp_tmpd2deqn_i_dafny_0.dfy", "ground_truth": "function abs(x: real): real\n{\n if x < 0.0 then -x else x\n}\n\nmethod has_close_elements(numbers: seq, threshold: real) returns (result: bool)\n ensures result <==> exists i, j ::\n 0 <= i < |numbers| &&\n 0 <= j < |numbers| &&\n i != j &&\n abs(numbers[i] - numbers[j]) < threshold\n ensures result ==> |numbers| > 1\n{\n result := false;\n\n assert (forall i0 :: (0 <= i0 < 0 ==>\n forall j0 :: (0 <= j0 < |numbers| ==>\n abs(numbers[i0] - numbers[j0]) >= threshold)));\n\n for i := 0 to |numbers|\n invariant (forall i0 :: (0 <= i0 < i ==>\n forall j0 :: (0 <= j0 < |numbers| ==>\n (i0 != j0 ==>\n abs(numbers[i0] - numbers[j0]) >= threshold))))\n {\n for j := 0 to |numbers|\n invariant (forall i0 :: (0 <= i0 <= i ==>\n forall j0 :: (0 <= j0 < j ==>\n (i0 != j0 ==>\n abs(numbers[i0] - numbers[j0]) >= threshold))))\n {\n if i != j && abs(numbers[i] - numbers[j]) < threshold {\n assert abs(numbers[i] - numbers[j]) < threshold;\n result := true;\n return;\n }\n\n }\n }\n}\n\n", "hints_removed": "function abs(x: real): real\n{\n if x < 0.0 then -x else x\n}\n\nmethod has_close_elements(numbers: seq, threshold: real) returns (result: bool)\n ensures result <==> exists i, j ::\n 0 <= i < |numbers| &&\n 0 <= j < |numbers| &&\n i != j &&\n abs(numbers[i] - numbers[j]) < threshold\n ensures result ==> |numbers| > 1\n{\n result := false;\n\n forall j0 :: (0 <= j0 < |numbers| ==>\n abs(numbers[i0] - numbers[j0]) >= threshold)));\n\n for i := 0 to |numbers|\n forall j0 :: (0 <= j0 < |numbers| ==>\n (i0 != j0 ==>\n abs(numbers[i0] - numbers[j0]) >= threshold))))\n {\n for j := 0 to |numbers|\n forall j0 :: (0 <= j0 < j ==>\n (i0 != j0 ==>\n abs(numbers[i0] - numbers[j0]) >= threshold))))\n {\n if i != j && abs(numbers[i] - numbers[j]) < threshold {\n result := true;\n return;\n }\n\n }\n }\n}\n\n" }, { "test_ID": "716", "test_file": "llm-verified-eval_tmp_tmpd2deqn_i_dafny_160.dfy", "ground_truth": "function pow(base: int, exponent: int): int\n requires exponent >= 0\n decreases exponent\n{\n if exponent == 0 then 1\n else if exponent % 2 == 0 then pow(base * base, exponent / 2)\n else base * pow(base, exponent - 1)\n}\n\nmethod do_algebra(operators: seq, operands: seq) returns (result: int)\n requires operators != [] && operands != [] && |operators| + 1 == |operands|\n requires forall i :: 0 <= i < |operands| ==> operands[i] >= 0\n{\n result := operands[0];\n var i := 0;\n while i < |operators|\n invariant 0 <= i <= |operators|\n decreases |operators| - i\n {\n var op := operators[i];\n i := i + 1;\n match op\n {\n case '+' =>\n result := result + operands[i];\n case '-' =>\n result := result - operands[i];\n case '*' =>\n result := result * operands[i];\n case '/' => \n if operands[i] != 0 {\n result := result / operands[i];\n }\n case '^' => \n result := pow(result, operands[i]);\n case _ =>\n }\n }\n}\n\n", "hints_removed": "function pow(base: int, exponent: int): int\n requires exponent >= 0\n{\n if exponent == 0 then 1\n else if exponent % 2 == 0 then pow(base * base, exponent / 2)\n else base * pow(base, exponent - 1)\n}\n\nmethod do_algebra(operators: seq, operands: seq) returns (result: int)\n requires operators != [] && operands != [] && |operators| + 1 == |operands|\n requires forall i :: 0 <= i < |operands| ==> operands[i] >= 0\n{\n result := operands[0];\n var i := 0;\n while i < |operators|\n {\n var op := operators[i];\n i := i + 1;\n match op\n {\n case '+' =>\n result := result + operands[i];\n case '-' =>\n result := result - operands[i];\n case '*' =>\n result := result * operands[i];\n case '/' => \n if operands[i] != 0 {\n result := result / operands[i];\n }\n case '^' => \n result := pow(result, operands[i]);\n case _ =>\n }\n }\n}\n\n" }, { "test_ID": "717", "test_file": "llm-verified-eval_tmp_tmpd2deqn_i_dafny_161.dfy", "ground_truth": "function IsLetter(c: char): bool \n{\n (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') \n}\n\nfunction NoLetters(s: string, n: nat): bool \n requires n <= |s|\n{\n forall c :: 0 <= c < n ==> !IsLetter(s[c])\n}\n\nfunction ToggleCase(c: char): char\n{\n if c >= 'a' && c <= 'z' \n then \n (c - 'a' + 'A')\n else if c >= 'A' && c <= 'Z' \n then \n (c - 'A' + 'a')\n else \n c\n}\nfunction isReverse(s: string, s_prime: string): bool{\n (|s| == |s_prime|) &&\n (forall si :: 0 <= si < |s|/2 ==> s_prime[|s| - si - 1] == s[si])\n}\n\nmethod Reverse(original: seq) returns (reversed: seq)\n ensures |reversed| == |original| \n ensures forall i :: 0 <= i < |original| ==> reversed[i] == original[|original| - 1 - i] \n{\n reversed := []; \n var i := |original|;\n while i > 0\n decreases i\n invariant 0 <= i <= |original|\n invariant |reversed| == |original| - i\n invariant forall j :: 0 <= j < |original|-i ==>\n reversed[j] == original[|original| - 1 - j]\n {\n i := i - 1;\n reversed := reversed + [original[i]]; \n }\n}\n\n\nmethod solve(s: string) returns (result: string)\n ensures |result| == |s| \n ensures !NoLetters(s, |s|) ==> forall i :: 0 <= i < |s| && IsLetter(s[i]) ==> result[i] == ToggleCase(s[i])\n ensures !NoLetters(s, |s|) ==> forall i :: 0 <= i < |s| && !IsLetter(s[i]) ==> result[i] == s[i] \n ensures NoLetters(s, |s|) ==> isReverse(result, s) \n{\n var flg : bool := false;\n result := \"\";\n for i := 0 to |s|\n invariant |result| == i\n invariant flg <==> !NoLetters(s, i)\n invariant forall j :: 0 <= j < i ==> result[j] == ToggleCase(s[j])\n {\n if IsLetter(s[i])\n {\n result := result + [ToggleCase(s[i])];\n flg := true;\n } else {\n result := result + [s[i]];\n }\n }\n if !flg\n {\n result := Reverse(s);\n }\n}\n\n", "hints_removed": "function IsLetter(c: char): bool \n{\n (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') \n}\n\nfunction NoLetters(s: string, n: nat): bool \n requires n <= |s|\n{\n forall c :: 0 <= c < n ==> !IsLetter(s[c])\n}\n\nfunction ToggleCase(c: char): char\n{\n if c >= 'a' && c <= 'z' \n then \n (c - 'a' + 'A')\n else if c >= 'A' && c <= 'Z' \n then \n (c - 'A' + 'a')\n else \n c\n}\nfunction isReverse(s: string, s_prime: string): bool{\n (|s| == |s_prime|) &&\n (forall si :: 0 <= si < |s|/2 ==> s_prime[|s| - si - 1] == s[si])\n}\n\nmethod Reverse(original: seq) returns (reversed: seq)\n ensures |reversed| == |original| \n ensures forall i :: 0 <= i < |original| ==> reversed[i] == original[|original| - 1 - i] \n{\n reversed := []; \n var i := |original|;\n while i > 0\n reversed[j] == original[|original| - 1 - j]\n {\n i := i - 1;\n reversed := reversed + [original[i]]; \n }\n}\n\n\nmethod solve(s: string) returns (result: string)\n ensures |result| == |s| \n ensures !NoLetters(s, |s|) ==> forall i :: 0 <= i < |s| && IsLetter(s[i]) ==> result[i] == ToggleCase(s[i])\n ensures !NoLetters(s, |s|) ==> forall i :: 0 <= i < |s| && !IsLetter(s[i]) ==> result[i] == s[i] \n ensures NoLetters(s, |s|) ==> isReverse(result, s) \n{\n var flg : bool := false;\n result := \"\";\n for i := 0 to |s|\n {\n if IsLetter(s[i])\n {\n result := result + [ToggleCase(s[i])];\n flg := true;\n } else {\n result := result + [s[i]];\n }\n }\n if !flg\n {\n result := Reverse(s);\n }\n}\n\n" }, { "test_ID": "718", "test_file": "llm-verified-eval_tmp_tmpd2deqn_i_dafny_3.dfy", "ground_truth": "function sum(s: seq, n: nat): int\n requires n <= |s|\n{\n if |s| == 0 || n == 0 then\n 0\n else\n s[0] + sum(s[1..], n-1)\n}\n\nlemma sum_plus(s: seq, i: nat)\n requires i < |s|\n ensures sum(s, i) + s[i] == sum(s, i+1)\n{\n}\n\nmethod below_zero(ops: seq) returns (result: bool)\n ensures result <==> exists n: nat :: n <= |ops| && sum(ops, n) < 0\n{\n result := false;\n var t := 0;\n for i := 0 to |ops|\n invariant t == sum(ops, i)\n invariant forall n: nat :: n <= i ==> sum(ops, n) >= 0\n {\n t := t + ops[i];\n sum_plus(ops, i);\n if t < 0 {\n result := true;\n return;\n }\n }\n}\n", "hints_removed": "function sum(s: seq, n: nat): int\n requires n <= |s|\n{\n if |s| == 0 || n == 0 then\n 0\n else\n s[0] + sum(s[1..], n-1)\n}\n\nlemma sum_plus(s: seq, i: nat)\n requires i < |s|\n ensures sum(s, i) + s[i] == sum(s, i+1)\n{\n}\n\nmethod below_zero(ops: seq) returns (result: bool)\n ensures result <==> exists n: nat :: n <= |ops| && sum(ops, n) < 0\n{\n result := false;\n var t := 0;\n for i := 0 to |ops|\n {\n t := t + ops[i];\n sum_plus(ops, i);\n if t < 0 {\n result := true;\n return;\n }\n }\n}\n" }, { "test_ID": "719", "test_file": "llm-verified-eval_tmp_tmpd2deqn_i_dafny_5.dfy", "ground_truth": "method intersperse(numbers: seq, delimiter: int) returns (interspersed: seq)\n ensures |interspersed| == if |numbers| > 0 then 2 * |numbers| - 1 else 0\n ensures forall i :: 0 <= i < |interspersed| ==> i % 2 == 0 ==> \n interspersed[i] == numbers[i / 2]\n ensures forall i :: 0 <= i < |interspersed| ==> i % 2 == 1 ==>\n interspersed[i] == delimiter\n{\n interspersed := [];\n for i := 0 to |numbers|\n invariant |interspersed| == if i > 0 then 2 * i - 1 else 0\n invariant forall i0 :: 0 <= i0 < |interspersed| ==> i0 % 2 == 0 ==> \n interspersed[i0] == numbers[i0 / 2]\n invariant forall i0 :: 0 <= i0 < |interspersed| ==> i0 % 2 == 1 ==>\n interspersed[i0] == delimiter\n {\n if i > 0 {\n interspersed := interspersed + [delimiter];\n }\n interspersed := interspersed + [numbers[i]];\n }\n}\n\n", "hints_removed": "method intersperse(numbers: seq, delimiter: int) returns (interspersed: seq)\n ensures |interspersed| == if |numbers| > 0 then 2 * |numbers| - 1 else 0\n ensures forall i :: 0 <= i < |interspersed| ==> i % 2 == 0 ==> \n interspersed[i] == numbers[i / 2]\n ensures forall i :: 0 <= i < |interspersed| ==> i % 2 == 1 ==>\n interspersed[i] == delimiter\n{\n interspersed := [];\n for i := 0 to |numbers|\n interspersed[i0] == numbers[i0 / 2]\n interspersed[i0] == delimiter\n {\n if i > 0 {\n interspersed := interspersed + [delimiter];\n }\n interspersed := interspersed + [numbers[i]];\n }\n}\n\n" }, { "test_ID": "720", "test_file": "llm-verified-eval_tmp_tmpd2deqn_i_dafny_9.dfy", "ground_truth": "function isMax(m: int, numbers: seq): bool\n{\n m in numbers &&\n forall i :: 0 <= i < |numbers| ==> numbers[i] <= m\n\n}\n\nmethod max(numbers: seq) returns (result: int)\nrequires numbers != []\nensures isMax(result, numbers)\n{\n result := numbers[0];\n for i := 1 to |numbers|\n invariant isMax(result, numbers[0..i])\n {\n if numbers[i] > result {\n result := numbers[i];\n }\n }\n}\n\nmethod rolling_max(numbers: seq) returns (result: seq)\nrequires numbers != []\nensures |result| == |numbers|\nensures forall i :: 0 < i < |result| ==> isMax(result[i], numbers[0..(i+1)])\n{\n var m := numbers[0];\n result := [m];\n for i := 1 to |numbers|\n invariant |result| == i\n invariant m == result[i-1]\n invariant forall j :: 0 <= j < i ==> isMax(result[j], numbers[0..(j+1)])\n {\n if numbers[i] > m {\n m := numbers[i];\n }\n result := result + [m];\n }\n}\n\n", "hints_removed": "function isMax(m: int, numbers: seq): bool\n{\n m in numbers &&\n forall i :: 0 <= i < |numbers| ==> numbers[i] <= m\n\n}\n\nmethod max(numbers: seq) returns (result: int)\nrequires numbers != []\nensures isMax(result, numbers)\n{\n result := numbers[0];\n for i := 1 to |numbers|\n {\n if numbers[i] > result {\n result := numbers[i];\n }\n }\n}\n\nmethod rolling_max(numbers: seq) returns (result: seq)\nrequires numbers != []\nensures |result| == |numbers|\nensures forall i :: 0 < i < |result| ==> isMax(result[i], numbers[0..(i+1)])\n{\n var m := numbers[0];\n result := [m];\n for i := 1 to |numbers|\n {\n if numbers[i] > m {\n m := numbers[i];\n }\n result := result + [m];\n }\n}\n\n" }, { "test_ID": "721", "test_file": "metodosFormais_tmp_tmp4q2kmya4_T1-MetodosFormais_examples_ex1.dfy", "ground_truth": "/*\nBuscar\nr = 0\nenquanto(r<|a|){\n se (a[r] == x) retorne r\n r = r+1\n}\nretorne -1\n*/\n\nmethod buscar(a:array, x:int) returns (r:int)\nensures r < 0 ==> forall i :: 0 <= i a[i] != x\nensures 0 <= r < a.Length ==> a[r] == x\n{\n r := 0;\n while r < a.Length\n decreases a.Length - r\n invariant 0 <= r <= a.Length\n invariant forall i :: 0 <= i < r ==> a[i] != x\n {\n if a[r] == x\n {\n return r;\n }\n r := r + 1;\n }\n return -1;\n\n}\n", "hints_removed": "/*\nBuscar\nr = 0\nenquanto(r<|a|){\n se (a[r] == x) retorne r\n r = r+1\n}\nretorne -1\n*/\n\nmethod buscar(a:array, x:int) returns (r:int)\nensures r < 0 ==> forall i :: 0 <= i a[i] != x\nensures 0 <= r < a.Length ==> a[r] == x\n{\n r := 0;\n while r < a.Length\n {\n if a[r] == x\n {\n return r;\n }\n r := r + 1;\n }\n return -1;\n\n}\n" }, { "test_ID": "722", "test_file": "metodosFormais_tmp_tmp4q2kmya4_T1-MetodosFormais_examples_somatoriov2.dfy", "ground_truth": "function somaAteAberto(a:array, i:nat):nat\nrequires i <= a.Length\nreads a\n{\n if i ==0\n then 0\n else a[i-1] + somaAteAberto(a,i-1)\n}\n\nmethod somatorio(a:array) returns (s:nat)\nensures s == somaAteAberto(a, a.Length)\n{\n s := 0;\n for i:= 0 to a.Length\n invariant s == somaAteAberto(a,i)\n {\n s := s + a[i];\n }\n} \n", "hints_removed": "function somaAteAberto(a:array, i:nat):nat\nrequires i <= a.Length\nreads a\n{\n if i ==0\n then 0\n else a[i-1] + somaAteAberto(a,i-1)\n}\n\nmethod somatorio(a:array) returns (s:nat)\nensures s == somaAteAberto(a, a.Length)\n{\n s := 0;\n for i:= 0 to a.Length\n {\n s := s + a[i];\n }\n} \n" }, { "test_ID": "723", "test_file": "nitwit_tmp_tmplm098gxz_nit.dfy", "ground_truth": "// Liam Wynn, 3/13/2021, CS 510p\n\n/*\n In this program, I'm hoping to define\n N's complement: a generalized form of 2's complement.\n\n I ran across this idea back in ECE 341, when I asked\n the professor about a crackpot theoretical \"ternary machine\".\n Looking into it, I came across a general form of 2's complement.\n\n Suppose I had the following 4 nit word in base base 3:\n\n 1 2 0 1 (3)\n\n Now, in two's complement, you \"flip\" the bits and add 1. In\n n's complement, you flip the bits by subtracting the current\n nit value from the largest possible nit value. Since our base\n is 3, our highest possible nit value is 2:\n\n 1 0 2 1 (3)\n\n Note how the 1's don't change (2 - 1 = 1), but the \"flipping\"\n is demonstrated in the 2 and 0. flip(2) in base 3 = 0, and flip(0)\n in base 3 = 2.\n\n Now let's increment our flipped word:\n\n 1 0 2 2 (3)\n\n Now, if this is truly the n's complement of 1 2 0 1 (3), their\n sum should be 0:\n\n 1 1 1\n 1 2 0 1\n + 1 0 2 2\n ---------\n 1 0 0 0 0 (3)\n\n Now, since our word size if 4 nits, the last nit gets dropped\n giving us 0 0 0 0!\n\n So basically I want to write a Dafny program that does the above\n but verified. I don't know how far I will get, but I essentially\n want to write an increment, addition, and flip procedures such\n that:\n\n sum(v, increment(flip(v)) = 0, where v is a 4 nit value in\n a given base n.\n\n*/\n\n/*\n In this program, we deal with bases that are explicitly greater\n than or equal to 2. Without this fact, virtually all of our\n postconditions will not be provable. We will run into issues\n of dividing by 0 and what not.\n*/\npredicate valid_base(b : nat) {\n b >= 2\n}\n\n/*\n Now we are in a position to define a nit formally. We say\n a natural number n is a \"nit\" of some base b if 0 <= n < b.\n 0 and 1 are 2-nits (\"bits\") since 0 <= 0 < 2 and 0 <= 1 < 2.\n*/\npredicate nitness(b : nat, n : nat)\n requires (valid_base(b))\n{\n 0 <= n < b\n}\n\n/*\n We define incrementing a nit (given its base). When you add two digits\n together, you \"carry the one\" if the sum is >= 10.\n\n 1\n 7\n + 3\n ---\n 10\n\n Addition simply takes two collections of things and merges them together.\n Expressing the resulting collection in base 10 requires this strange\n notion of \"carrying the one\". What it means is: the sum of 7 and 3\n is one set of ten items, and nothing left over\". Or if I did 6 + 7,\n that is \"one set of 10, and a set of 3\".\n\n The same notion applies in other bases. 1 + 1 in base 2 is \"one set\n of 2 and 0 sets of ones\".\n\n We can express \"carrying\" by using division. Division by a base\n tells us how many sets of that base we have. So 19 in base 10 is\n \"1 set of 10, and 9 left over\". So modding tells us what's left\n over and division tells us how much to carry (how many sets of the\n base we have).\n*/\nmethod nit_increment(b : nat, n : nat) returns (sum : nat, carry : nat)\n // Note: apparently, you need to explicitly put this here\n // even though we've got it in the nitness predicate\n requires (valid_base(b))\n requires (nitness(b, n))\n ensures (nitness(b, sum))\n ensures (nitness(b, carry))\n{\n sum := (n + 1) % b;\n carry := (n + 1) / b;\n}\n\n/*\n Okay next we are going to define the flip operation. In binary,\n flip(0) = 1 and flip(1) = 0. We can generalize it to any base\n by defining it as so:\n\n let q be the max possible value of a given base. This\n is b - 1. Given some nit n of b, the flip(n) is q - n.\n\n For base 2, q = b - 1 = 2 - 1 = 1. flip(0) = 1 - 0 = 1,\n and flip(1) = 1 - 1 = 0.\n\n For base 3, q = 3 - 1 = 2. flip(0) = 2 - 0 = 2,\n flip(1) = 2 - 1 = 1, and flip(2) = 2 - 2 = 0.\n\n To begin with, we define a predicate is_max_nit which\n is true if some natural q == b - 1.\n*/\npredicate is_max_nit(b : nat, q : nat) {\n q == b - 1\n}\n\n/*\n Next we define a meta-operator (on a base b) that\n returns the max nit. To make Dafny (and our inner\n mathmatician) happy, we need to require that b is\n a valid base, and explicitly say max_nit(b) is\n a nit of b, and that max_nit(b) is_max_nit(b).\n I found these made the actual flip operation provable.\n*/\nmethod max_nit(b: nat) returns (nmax : nat)\n requires (valid_base(b))\n ensures (nitness(b, nmax))\n ensures (is_max_nit(b, nmax))\n{\n nmax := b - 1;\n}\n\n/*\n Now we define the flip operation proper. For this to work,\n we need is_max_nit and a kind of silly proof to make Dafny\n happy.\n*/\nmethod nit_flip(b: nat, n : nat) returns (nf : nat)\n requires (valid_base(b))\n requires (nitness(b, n))\n ensures (nitness (b, nf))\n{\n var mn : nat := max_nit(b);\n\n // I found I could not just assert that\n // 0 <= n <= mn. I had to do this long\n // series of asserts to prove it.\n assert 0 < n < b ==> n <= b - 1;\n assert 0 == n ==> n <= b - 1;\n assert n <= b - 1;\n assert mn == b - 1;\n assert 0 <= n <= mn;\n\n // But from all the above, Dafny can figure\n // out that nitness(b, mn - n) holds.\n nf := mn - n;\n}\n\n/*\n We will now take a detour back to addition. We want to define\n a general version of nit_increment that allows you to add any two nits\n*/\nmethod nit_add(b : nat, x : nat, y : nat) returns (z : nat, carry : nat)\n requires (valid_base(b))\n requires (nitness(b, x))\n requires (nitness(b, y))\n ensures (nitness(b, z))\n ensures (nitness(b, carry))\n // This is a useful fact for doing general form addition.\n ensures (carry == 0 || carry == 1)\n{\n z := (x + y) % b;\n carry := (x + y) / b;\n\n // The last postcondition is a little too bold,\n // so here is a proof of its correctness\n assert x + y < b + b;\n assert (x + y) / b < (b + b) / b;\n assert (x + y) / b < 2;\n assert carry < 2;\n assert carry == 0 || carry == 1;\n}\n\n/*\n It will come in handy to define a version of nit_add that takes\n an additional argument c. Suppose I wanted to do base 2 addition\n as follows:\n\n 1 1\n 0 1\n +----\n\n Doing one step would give us:\n\n 1\n 1 1\n 0 1\n +----\n 0\n\n This will allow us to do the above step nicely.\n*/\nmethod nit_add_three(b : nat, c : nat, x : nat, y : nat) returns (z : nat, carry : nat)\n requires (valid_base(b))\n requires (c == 0 || c == 1)\n requires (nitness(b, x))\n requires (nitness(b, y))\n ensures (nitness(b, z))\n ensures (nitness(b, carry))\n ensures (carry == 0 || carry == 1)\n{\n if(c == 0) {\n z, carry := nit_add(b, x, y);\n } else {\n z := (x + y + 1) % b;\n carry := (x + y + 1) / b;\n\n // Gigantic proof to show that (x + y + 1) / b will either == 1\n // (meaning we need 1 set of b to contain x + y + 1)\n // or (x + y + 1) == 0 (meaning we don't need a set of b to contian x + y + 1).\n assert 0 <= b - 1;\n\n assert 0 <= x < b;\n assert 0 == x || 0 < x;\n assert 0 < x ==> x <= b - 1;\n assert 0 <= x <= b - 1;\n\n assert 0 <= y < b;\n assert 0 == y || 0 < y;\n assert 0 <= b - 1;\n assert 0 < y ==> y <= b - 1;\n assert 0 <= y <= b - 1;\n\n assert x + y <= (b - 1) + (b - 1);\n assert x + y <= 2 * b - 2;\n assert x + y + 1 <= 2 * b - 2 + 1;\n assert x + y + 1 <= 2 * b - 1;\n assert 2 * b - 1 < 2 * b;\n assert x + y + 1 < 2 * b;\n assert (x + y + 1) / b < 2;\n assert (x + y + 1) / b == 0 || (x + y + 1) / b == 1;\n }\n}\n\n/*\n Whereas in binary computers, where we've the byte,\n we will define a general version called a \"nyte\". A \"nyte\"\n would be a collection of eight nits. However, for\n simplicity's sake, we deal in half-nytes. A nibble is a\n half-byte, so in our program we will call it a bibble.\n\n So, a bibble given some valid_base b is a collection\n of four nits.\n*/\npredicate bibble(b : nat, a : seq)\n{\n valid_base(b) && \n |a| == 4 && \n forall n :: n in a ==> nitness(b, n)\n}\n\n/*\n As with nits, we will define addition, increment, and flip operations.\n*/\nmethod bibble_add(b : nat, p : seq, q : seq) returns (r : seq)\n requires (valid_base(b))\n requires (bibble(b, p))\n requires (bibble(b, q))\n ensures (bibble(b, r))\n{\n var z3, c3 := nit_add(b, p[3], q[3]);\n var z2, c2 := nit_add_three(b, c3, p[2], q[2]);\n var z1, c1 := nit_add_three(b, c2, p[1], q[1]);\n var z0, c0 := nit_add_three(b, c1, p[0], q[0]);\n\n r := [z0, z1, z2, z3];\n}\n\nmethod bibble_increment(b : nat, p : seq) returns (r : seq)\n requires (valid_base(b))\n requires (bibble(b, p))\n ensures (bibble(b, r))\n{\n var q : seq := [0, 0, 0, 1];\n assert bibble(b, q);\n r := bibble_add(b, p, q);\n}\n\nmethod bibble_flip(b : nat, p : seq) returns (fp : seq)\n requires (valid_base(b))\n requires (bibble(b, p))\n ensures (bibble(b, fp))\n{\n var n0 := nit_flip(b, p[0]);\n var n1 := nit_flip(b, p[1]);\n var n2 := nit_flip(b, p[2]);\n var n3 := nit_flip(b, p[3]);\n\n fp := [n0, n1, n2, n3];\n}\n\n/*\n The last part of the program: n's complement! It's the same as two's complement:\n we flip all the nits and add 1.\n*/\nmethod n_complement(b : nat, p : seq) returns (com : seq)\n requires (valid_base(b))\n requires (bibble(b, p))\n ensures (bibble(b, com))\n{\n var fp := bibble_flip(b, p);\n var fpi := bibble_increment(b, fp);\n com := fpi;\n}\n\nmethod Main() {\n var b := 3;\n var bibble1 := [2, 1, 0, 2];\n var complement := n_complement(b, bibble1);\n var bibble_sum := bibble_add(b, bibble1, complement);\n\n print bibble1, \" + \", complement, \" = \", bibble_sum, \" (should be [0, 0, 0, 0])\\n\";\n}\n\n", "hints_removed": "// Liam Wynn, 3/13/2021, CS 510p\n\n/*\n In this program, I'm hoping to define\n N's complement: a generalized form of 2's complement.\n\n I ran across this idea back in ECE 341, when I asked\n the professor about a crackpot theoretical \"ternary machine\".\n Looking into it, I came across a general form of 2's complement.\n\n Suppose I had the following 4 nit word in base base 3:\n\n 1 2 0 1 (3)\n\n Now, in two's complement, you \"flip\" the bits and add 1. In\n n's complement, you flip the bits by subtracting the current\n nit value from the largest possible nit value. Since our base\n is 3, our highest possible nit value is 2:\n\n 1 0 2 1 (3)\n\n Note how the 1's don't change (2 - 1 = 1), but the \"flipping\"\n is demonstrated in the 2 and 0. flip(2) in base 3 = 0, and flip(0)\n in base 3 = 2.\n\n Now let's increment our flipped word:\n\n 1 0 2 2 (3)\n\n Now, if this is truly the n's complement of 1 2 0 1 (3), their\n sum should be 0:\n\n 1 1 1\n 1 2 0 1\n + 1 0 2 2\n ---------\n 1 0 0 0 0 (3)\n\n Now, since our word size if 4 nits, the last nit gets dropped\n giving us 0 0 0 0!\n\n So basically I want to write a Dafny program that does the above\n but verified. I don't know how far I will get, but I essentially\n want to write an increment, addition, and flip procedures such\n that:\n\n sum(v, increment(flip(v)) = 0, where v is a 4 nit value in\n a given base n.\n\n*/\n\n/*\n In this program, we deal with bases that are explicitly greater\n than or equal to 2. Without this fact, virtually all of our\n postconditions will not be provable. We will run into issues\n of dividing by 0 and what not.\n*/\npredicate valid_base(b : nat) {\n b >= 2\n}\n\n/*\n Now we are in a position to define a nit formally. We say\n a natural number n is a \"nit\" of some base b if 0 <= n < b.\n 0 and 1 are 2-nits (\"bits\") since 0 <= 0 < 2 and 0 <= 1 < 2.\n*/\npredicate nitness(b : nat, n : nat)\n requires (valid_base(b))\n{\n 0 <= n < b\n}\n\n/*\n We define incrementing a nit (given its base). When you add two digits\n together, you \"carry the one\" if the sum is >= 10.\n\n 1\n 7\n + 3\n ---\n 10\n\n Addition simply takes two collections of things and merges them together.\n Expressing the resulting collection in base 10 requires this strange\n notion of \"carrying the one\". What it means is: the sum of 7 and 3\n is one set of ten items, and nothing left over\". Or if I did 6 + 7,\n that is \"one set of 10, and a set of 3\".\n\n The same notion applies in other bases. 1 + 1 in base 2 is \"one set\n of 2 and 0 sets of ones\".\n\n We can express \"carrying\" by using division. Division by a base\n tells us how many sets of that base we have. So 19 in base 10 is\n \"1 set of 10, and 9 left over\". So modding tells us what's left\n over and division tells us how much to carry (how many sets of the\n base we have).\n*/\nmethod nit_increment(b : nat, n : nat) returns (sum : nat, carry : nat)\n // Note: apparently, you need to explicitly put this here\n // even though we've got it in the nitness predicate\n requires (valid_base(b))\n requires (nitness(b, n))\n ensures (nitness(b, sum))\n ensures (nitness(b, carry))\n{\n sum := (n + 1) % b;\n carry := (n + 1) / b;\n}\n\n/*\n Okay next we are going to define the flip operation. In binary,\n flip(0) = 1 and flip(1) = 0. We can generalize it to any base\n by defining it as so:\n\n let q be the max possible value of a given base. This\n is b - 1. Given some nit n of b, the flip(n) is q - n.\n\n For base 2, q = b - 1 = 2 - 1 = 1. flip(0) = 1 - 0 = 1,\n and flip(1) = 1 - 1 = 0.\n\n For base 3, q = 3 - 1 = 2. flip(0) = 2 - 0 = 2,\n flip(1) = 2 - 1 = 1, and flip(2) = 2 - 2 = 0.\n\n To begin with, we define a predicate is_max_nit which\n is true if some natural q == b - 1.\n*/\npredicate is_max_nit(b : nat, q : nat) {\n q == b - 1\n}\n\n/*\n Next we define a meta-operator (on a base b) that\n returns the max nit. To make Dafny (and our inner\n mathmatician) happy, we need to require that b is\n a valid base, and explicitly say max_nit(b) is\n a nit of b, and that max_nit(b) is_max_nit(b).\n I found these made the actual flip operation provable.\n*/\nmethod max_nit(b: nat) returns (nmax : nat)\n requires (valid_base(b))\n ensures (nitness(b, nmax))\n ensures (is_max_nit(b, nmax))\n{\n nmax := b - 1;\n}\n\n/*\n Now we define the flip operation proper. For this to work,\n we need is_max_nit and a kind of silly proof to make Dafny\n happy.\n*/\nmethod nit_flip(b: nat, n : nat) returns (nf : nat)\n requires (valid_base(b))\n requires (nitness(b, n))\n ensures (nitness (b, nf))\n{\n var mn : nat := max_nit(b);\n\n // I found I could not just assert that\n // 0 <= n <= mn. I had to do this long\n // series of asserts to prove it.\n\n // But from all the above, Dafny can figure\n // out that nitness(b, mn - n) holds.\n nf := mn - n;\n}\n\n/*\n We will now take a detour back to addition. We want to define\n a general version of nit_increment that allows you to add any two nits\n*/\nmethod nit_add(b : nat, x : nat, y : nat) returns (z : nat, carry : nat)\n requires (valid_base(b))\n requires (nitness(b, x))\n requires (nitness(b, y))\n ensures (nitness(b, z))\n ensures (nitness(b, carry))\n // This is a useful fact for doing general form addition.\n ensures (carry == 0 || carry == 1)\n{\n z := (x + y) % b;\n carry := (x + y) / b;\n\n // The last postcondition is a little too bold,\n // so here is a proof of its correctness\n}\n\n/*\n It will come in handy to define a version of nit_add that takes\n an additional argument c. Suppose I wanted to do base 2 addition\n as follows:\n\n 1 1\n 0 1\n +----\n\n Doing one step would give us:\n\n 1\n 1 1\n 0 1\n +----\n 0\n\n This will allow us to do the above step nicely.\n*/\nmethod nit_add_three(b : nat, c : nat, x : nat, y : nat) returns (z : nat, carry : nat)\n requires (valid_base(b))\n requires (c == 0 || c == 1)\n requires (nitness(b, x))\n requires (nitness(b, y))\n ensures (nitness(b, z))\n ensures (nitness(b, carry))\n ensures (carry == 0 || carry == 1)\n{\n if(c == 0) {\n z, carry := nit_add(b, x, y);\n } else {\n z := (x + y + 1) % b;\n carry := (x + y + 1) / b;\n\n // Gigantic proof to show that (x + y + 1) / b will either == 1\n // (meaning we need 1 set of b to contain x + y + 1)\n // or (x + y + 1) == 0 (meaning we don't need a set of b to contian x + y + 1).\n\n\n\n }\n}\n\n/*\n Whereas in binary computers, where we've the byte,\n we will define a general version called a \"nyte\". A \"nyte\"\n would be a collection of eight nits. However, for\n simplicity's sake, we deal in half-nytes. A nibble is a\n half-byte, so in our program we will call it a bibble.\n\n So, a bibble given some valid_base b is a collection\n of four nits.\n*/\npredicate bibble(b : nat, a : seq)\n{\n valid_base(b) && \n |a| == 4 && \n forall n :: n in a ==> nitness(b, n)\n}\n\n/*\n As with nits, we will define addition, increment, and flip operations.\n*/\nmethod bibble_add(b : nat, p : seq, q : seq) returns (r : seq)\n requires (valid_base(b))\n requires (bibble(b, p))\n requires (bibble(b, q))\n ensures (bibble(b, r))\n{\n var z3, c3 := nit_add(b, p[3], q[3]);\n var z2, c2 := nit_add_three(b, c3, p[2], q[2]);\n var z1, c1 := nit_add_three(b, c2, p[1], q[1]);\n var z0, c0 := nit_add_three(b, c1, p[0], q[0]);\n\n r := [z0, z1, z2, z3];\n}\n\nmethod bibble_increment(b : nat, p : seq) returns (r : seq)\n requires (valid_base(b))\n requires (bibble(b, p))\n ensures (bibble(b, r))\n{\n var q : seq := [0, 0, 0, 1];\n r := bibble_add(b, p, q);\n}\n\nmethod bibble_flip(b : nat, p : seq) returns (fp : seq)\n requires (valid_base(b))\n requires (bibble(b, p))\n ensures (bibble(b, fp))\n{\n var n0 := nit_flip(b, p[0]);\n var n1 := nit_flip(b, p[1]);\n var n2 := nit_flip(b, p[2]);\n var n3 := nit_flip(b, p[3]);\n\n fp := [n0, n1, n2, n3];\n}\n\n/*\n The last part of the program: n's complement! It's the same as two's complement:\n we flip all the nits and add 1.\n*/\nmethod n_complement(b : nat, p : seq) returns (com : seq)\n requires (valid_base(b))\n requires (bibble(b, p))\n ensures (bibble(b, com))\n{\n var fp := bibble_flip(b, p);\n var fpi := bibble_increment(b, fp);\n com := fpi;\n}\n\nmethod Main() {\n var b := 3;\n var bibble1 := [2, 1, 0, 2];\n var complement := n_complement(b, bibble1);\n var bibble_sum := bibble_add(b, bibble1, complement);\n\n print bibble1, \" + \", complement, \" = \", bibble_sum, \" (should be [0, 0, 0, 0])\\n\";\n}\n\n" }, { "test_ID": "724", "test_file": "paxos_proof_tmp_tmpxpmiksmt_triggers.dfy", "ground_truth": "// predicate P(x:int)\n\n// predicate Q(x:int)\n\n\nlemma M(a: seq, m: map)\n requires 2 <= |a|\n requires false in m && true in m\n{\n assume forall i {:trigger a[i]} :: 0 <= i < |a|-1 ==> a[i] <= a[i+1];\n var x :| 0 <= x <= |a|-2;\n assert a[x] <= a[x+1];\n}\n", "hints_removed": "// predicate P(x:int)\n\n// predicate Q(x:int)\n\n\nlemma M(a: seq, m: map)\n requires 2 <= |a|\n requires false in m && true in m\n{\n assume forall i {:trigger a[i]} :: 0 <= i < |a|-1 ==> a[i] <= a[i+1];\n var x :| 0 <= x <= |a|-2;\n}\n" }, { "test_ID": "725", "test_file": "protocol-verification-fa2023_tmp_tmpw6hy3mjp_demos_ch01_fast_exp.dfy", "ground_truth": "function exp(b: nat, n: nat): nat {\n if n == 0 then 1\n else b * exp(b, n-1)\n}\n\nlemma exp_sum(b: nat, n1: nat, n2: nat)\n ensures exp(b, n1 + n2) == exp(b, n1) * exp(b, n2)\n{\n if n1 == 0 {\n return;\n }\n exp_sum(b, n1-1, n2);\n}\n\n// this \"auto\" version of exp_sum is convenient when we want to let Z3 figure\n// out how to use exp_sum rather than providing all the arguments ourselves\nlemma exp_sum_auto(b: nat)\n ensures forall n1: nat, n2: nat :: exp(b, n1 + n2) == exp(b, n1) * exp(b, n2)\n{\n forall n1: nat, n2: nat\n ensures exp(b, n1 + n2) == exp(b, n1) * exp(b, n2) {\n exp_sum(b, n1, n2);\n }\n}\n\n/* A key aspect of this proof is that each iteration handles one bit of the\n * input. The best way I found to express its loop invariants is to compute and\n * refer to this sequence of bits, even if the code never materializes it. */\n\nfunction bits(n: nat): seq\n decreases n\n{\n if n == 0 then []\n else [if (n % 2 == 0) then false else true] + bits(n/2)\n}\n\nfunction from_bits(s: seq): nat {\n if s == [] then 0\n else (if s[0] then 1 else 0) + 2 * from_bits(s[1..])\n}\n\nlemma bits_from_bits(n: nat)\n ensures from_bits(bits(n)) == n\n{\n}\n\nlemma from_bits_append(s: seq, b: bool)\n ensures from_bits(s + [b]) == from_bits(s) + exp(2, |s|) * (if b then 1 else 0)\n{\n if s == [] {\n return;\n }\n assert s == [s[0]] + s[1..];\n from_bits_append(s[1..], b);\n // from recursive call\n assert from_bits(s[1..] + [b]) == from_bits(s[1..]) + exp(2, |s|-1) * (if b then 1 else 0);\n exp_sum(2, |s|-1, 1);\n assert (s + [b])[1..] == s[1..] + [b]; // observe\n assert from_bits(s + [b]) == (if s[0] then 1 else 0) + 2 * from_bits(s[1..] + [b]);\n}\n\nmethod fast_exp(b: nat, n: nat) returns (r: nat)\n ensures r == exp(b, n)\n{\n // a is the exponent so far (see the invariant for the details)\n var a := 1;\n // c is b^(2^i) where i is the iteration number (see the invariant)\n var c := b;\n // we shadow n with a mutable variable since the loop modifies it at each\n // iteration (it essentially tracks the remaining work, as expressed more\n // precisely in the invariants)\n var n := n;\n // we will need to refer to the original value of n, which is shadowed, so to\n // do that we store it in a ghost variable\n ghost var n0 := n;\n // to state the invariants we track the iteration count (but it's not used for\n // the implementation, which only relies on n)\n ghost var i: nat := 0;\n bits_from_bits(n);\n while n > 0\n decreases n\n invariant n <= n0\n invariant i <= |bits(n0)|\n // c is used to accumulate the exponent for the current bit\n invariant c == exp(b, exp(2, i))\n invariant bits(n) == bits(n0)[i..]\n // n is the remaining work\n invariant n == from_bits(bits(n0)[i..])\n // a has the exponent using the bits of n0 through i\n invariant a == exp(b, from_bits(bits(n0)[..i]))\n {\n ghost var n_loop_top := n;\n if n % 2 == 1 {\n assert bits(n)[0] == true;\n // a accumulates bits(n0)[i..]. In this branch we drop a 1 bit from n and\n // need to multiply in 2^i multiplications for that bit, which we get from\n // c\n a := a * c;\n exp_sum(b, n0-n, i);\n n := n / 2;\n assert a == exp(b, from_bits(bits(n0)[..i]) + exp(2, i)) by {\n exp_sum_auto(b);\n }\n assert bits(n0)[..i+1] == bits(n0)[..i] + [bits(n0)[i]];\n from_bits_append(bits(n0)[..i], bits(n0)[i]);\n assert a == exp(b, from_bits(bits(n0)[..i+1]));\n } else {\n assert bits(n)[0] == false;\n n := n / 2;\n assert bits(n0)[..i+1] == bits(n0)[..i] + [bits(n0)[i]];\n from_bits_append(bits(n0)[..i], bits(n0)[i]);\n // the new bit is a 0 so we don't need to change a to restore the\n // invariant, we can just advance i\n assert a == exp(b, from_bits(bits(n0)[..i+1]));\n }\n assert n == n_loop_top/2;\n c := c * c;\n // the invariant for c is relatively easy to maintain\n assert c == exp(b, exp(2, i+1)) by {\n exp_sum_auto(b);\n }\n i := i + 1;\n }\n // we need to prove that i covers all of bits(n0)\n assert bits(n0)[..i] == bits(n0);\n return a;\n}\n\n", "hints_removed": "function exp(b: nat, n: nat): nat {\n if n == 0 then 1\n else b * exp(b, n-1)\n}\n\nlemma exp_sum(b: nat, n1: nat, n2: nat)\n ensures exp(b, n1 + n2) == exp(b, n1) * exp(b, n2)\n{\n if n1 == 0 {\n return;\n }\n exp_sum(b, n1-1, n2);\n}\n\n// this \"auto\" version of exp_sum is convenient when we want to let Z3 figure\n// out how to use exp_sum rather than providing all the arguments ourselves\nlemma exp_sum_auto(b: nat)\n ensures forall n1: nat, n2: nat :: exp(b, n1 + n2) == exp(b, n1) * exp(b, n2)\n{\n forall n1: nat, n2: nat\n ensures exp(b, n1 + n2) == exp(b, n1) * exp(b, n2) {\n exp_sum(b, n1, n2);\n }\n}\n\n/* A key aspect of this proof is that each iteration handles one bit of the\n * input. The best way I found to express its loop invariants is to compute and\n * refer to this sequence of bits, even if the code never materializes it. */\n\nfunction bits(n: nat): seq\n{\n if n == 0 then []\n else [if (n % 2 == 0) then false else true] + bits(n/2)\n}\n\nfunction from_bits(s: seq): nat {\n if s == [] then 0\n else (if s[0] then 1 else 0) + 2 * from_bits(s[1..])\n}\n\nlemma bits_from_bits(n: nat)\n ensures from_bits(bits(n)) == n\n{\n}\n\nlemma from_bits_append(s: seq, b: bool)\n ensures from_bits(s + [b]) == from_bits(s) + exp(2, |s|) * (if b then 1 else 0)\n{\n if s == [] {\n return;\n }\n from_bits_append(s[1..], b);\n // from recursive call\n exp_sum(2, |s|-1, 1);\n}\n\nmethod fast_exp(b: nat, n: nat) returns (r: nat)\n ensures r == exp(b, n)\n{\n // a is the exponent so far (see the invariant for the details)\n var a := 1;\n // c is b^(2^i) where i is the iteration number (see the invariant)\n var c := b;\n // we shadow n with a mutable variable since the loop modifies it at each\n // iteration (it essentially tracks the remaining work, as expressed more\n // precisely in the invariants)\n var n := n;\n // we will need to refer to the original value of n, which is shadowed, so to\n // do that we store it in a ghost variable\n ghost var n0 := n;\n // to state the invariants we track the iteration count (but it's not used for\n // the implementation, which only relies on n)\n ghost var i: nat := 0;\n bits_from_bits(n);\n while n > 0\n // c is used to accumulate the exponent for the current bit\n // n is the remaining work\n // a has the exponent using the bits of n0 through i\n {\n ghost var n_loop_top := n;\n if n % 2 == 1 {\n // a accumulates bits(n0)[i..]. In this branch we drop a 1 bit from n and\n // need to multiply in 2^i multiplications for that bit, which we get from\n // c\n a := a * c;\n exp_sum(b, n0-n, i);\n n := n / 2;\n exp_sum_auto(b);\n }\n from_bits_append(bits(n0)[..i], bits(n0)[i]);\n } else {\n n := n / 2;\n from_bits_append(bits(n0)[..i], bits(n0)[i]);\n // the new bit is a 0 so we don't need to change a to restore the\n // invariant, we can just advance i\n }\n c := c * c;\n // the invariant for c is relatively easy to maintain\n exp_sum_auto(b);\n }\n i := i + 1;\n }\n // we need to prove that i covers all of bits(n0)\n return a;\n}\n\n" }, { "test_ID": "726", "test_file": "protocol-verification-fa2023_tmp_tmpw6hy3mjp_demos_ch03_nim_v3.dfy", "ground_truth": "// Nim version 3: fix the bug and demonstrate a behavior.\n//\n// In this version, we've fixed the bug by actually flipping whose turn it is in\n// each transition.\n\ndatatype Player = P1 | P2\n{\n function Other(): Player {\n if this == P1 then P2 else P1\n }\n}\ndatatype Variables = Variables(piles: seq, turn: Player)\n\nghost predicate Init(v: Variables) {\n && |v.piles| == 3\n && v.turn.P1? // syntax\n}\n\ndatatype Step =\n | TurnStep(take: nat, p: nat)\n | NoOpStep()\n\nghost predicate Turn(v: Variables, v': Variables, step: Step)\n requires step.TurnStep?\n{\n var p := step.p;\n var take := step.take;\n && p < |v.piles|\n && take <= v.piles[p]\n && v' == v.(piles := v.piles[p := v.piles[p] - take]).(turn := v.turn.Other())\n}\n\n// nearly boilerplate (just gather up all transitions)\nghost predicate NextStep(v: Variables, v': Variables, step: Step) {\n match step {\n case TurnStep(_, _) => Turn(v, v', step)\n case NoOpStep() => v' == v // we don't really need to define predicate NoOp\n }\n}\n\n// boilerplate\nlemma NextStepDeterministicGivenStep(v: Variables, v': Variables, v'': Variables, step: Step)\n requires NextStep(v, v', step)\n requires NextStep(v, v'', step)\n ensures v' == v''\n{\n}\n\n// boilerplate\nghost predicate Next(v: Variables, v': Variables) {\n exists step :: NextStep(v, v', step)\n}\n\n// We'll frequently prove a lemma of this form to show some example of the state\n// machine transitioning. You'll prove determinism to avoid accidentally having\n// transitions do things they shouldn't. Proofs will show that your state\n// machine doesn't do anything bad (note this would also catch unintentional\n// non-determinism, but it can be more painful to debug such issues at this\n// stage). These example behaviors will prevent bugs where your state machine\n// just doesn't do anything, especially because of overly restrictive\n// preconditions.\nlemma ExampleBehavior() returns (b: seq)\n ensures |b| >= 3 // for this example, we just demonstrate there is some execution with three states\n ensures Init(b[0])\n ensures forall i:nat | i + 1 < |b| :: Next(b[i], b[i+1])\n{\n // the syntax here constructs a Variables with named fields.\n var state0 := Variables(piles := [3, 5, 7], turn := P1);\n b := [\n state0,\n Variables(piles := [3, 1, 7], turn := P2),\n Variables(piles := [3, 1, 0], turn := P1)\n ];\n // note that we need these assertions because we need to prove Next, which is\n // defined with `exists step :: ...` - Dafny needs help to see which value of\n // `step` will prove this.\n assert NextStep(b[0], b[1], TurnStep(take := 4, p := 1));\n assert NextStep(b[1], b[2], TurnStep(take := 7, p := 2));\n}\n\n", "hints_removed": "// Nim version 3: fix the bug and demonstrate a behavior.\n//\n// In this version, we've fixed the bug by actually flipping whose turn it is in\n// each transition.\n\ndatatype Player = P1 | P2\n{\n function Other(): Player {\n if this == P1 then P2 else P1\n }\n}\ndatatype Variables = Variables(piles: seq, turn: Player)\n\nghost predicate Init(v: Variables) {\n && |v.piles| == 3\n && v.turn.P1? // syntax\n}\n\ndatatype Step =\n | TurnStep(take: nat, p: nat)\n | NoOpStep()\n\nghost predicate Turn(v: Variables, v': Variables, step: Step)\n requires step.TurnStep?\n{\n var p := step.p;\n var take := step.take;\n && p < |v.piles|\n && take <= v.piles[p]\n && v' == v.(piles := v.piles[p := v.piles[p] - take]).(turn := v.turn.Other())\n}\n\n// nearly boilerplate (just gather up all transitions)\nghost predicate NextStep(v: Variables, v': Variables, step: Step) {\n match step {\n case TurnStep(_, _) => Turn(v, v', step)\n case NoOpStep() => v' == v // we don't really need to define predicate NoOp\n }\n}\n\n// boilerplate\nlemma NextStepDeterministicGivenStep(v: Variables, v': Variables, v'': Variables, step: Step)\n requires NextStep(v, v', step)\n requires NextStep(v, v'', step)\n ensures v' == v''\n{\n}\n\n// boilerplate\nghost predicate Next(v: Variables, v': Variables) {\n exists step :: NextStep(v, v', step)\n}\n\n// We'll frequently prove a lemma of this form to show some example of the state\n// machine transitioning. You'll prove determinism to avoid accidentally having\n// transitions do things they shouldn't. Proofs will show that your state\n// machine doesn't do anything bad (note this would also catch unintentional\n// non-determinism, but it can be more painful to debug such issues at this\n// stage). These example behaviors will prevent bugs where your state machine\n// just doesn't do anything, especially because of overly restrictive\n// preconditions.\nlemma ExampleBehavior() returns (b: seq)\n ensures |b| >= 3 // for this example, we just demonstrate there is some execution with three states\n ensures Init(b[0])\n ensures forall i:nat | i + 1 < |b| :: Next(b[i], b[i+1])\n{\n // the syntax here constructs a Variables with named fields.\n var state0 := Variables(piles := [3, 5, 7], turn := P1);\n b := [\n state0,\n Variables(piles := [3, 1, 7], turn := P2),\n Variables(piles := [3, 1, 0], turn := P1)\n ];\n // note that we need these assertions because we need to prove Next, which is\n // defined with `exists step :: ...` - Dafny needs help to see which value of\n // `step` will prove this.\n}\n\n" }, { "test_ID": "727", "test_file": "protocol-verification-fa2023_tmp_tmpw6hy3mjp_demos_ch04_inductive_chain.dfy", "ground_truth": "module Ex {\n // This simple example illustrates what the process of looking for an\n // inductive invariant might look like.\n\n datatype Variables = Variables(p1: bool, p2: bool, p3: bool, p4: bool)\n\n ghost predicate Init(v: Variables) {\n && !v.p1\n && !v.p2\n && !v.p3\n && !v.p4\n }\n\n // The state machine starts out with all four booleans false, and it \"turns\n // on\" p1, p2, p3, and p4 in order. The safety property says p4 ==> p1;\n // proving this requires a stronger inductive invariant.\n\n datatype Step =\n | Step1\n | Step2\n | Step3\n | Step4\n | Noop\n\n ghost predicate NextStep(v: Variables, v': Variables, step: Step)\n {\n match step {\n // ordinarily we'd have a predicate for each step, but in this simple\n // example it's easier to see everything written in one place\n case Step1 =>\n !v.p1 && v' == v.(p1 := true)\n case Step2 =>\n v.p1 && v' == v.(p2 := true)\n case Step3 =>\n v.p2 && v' == v.(p3 := true)\n case Step4 =>\n v.p3 && v' == v.(p4 := true)\n case Noop => v' == v\n }\n }\n\n ghost predicate Next(v: Variables, v': Variables)\n {\n exists step: Step :: NextStep(v, v', step)\n }\n\n ghost predicate Safety(v: Variables)\n {\n v.p4 ==> v.p1\n }\n\n ghost predicate Inv(v: Variables)\n {\n // SOLUTION\n // This is one approach: prove implications that go all the way back to the\n // beginning, trying to slowly work our way up to something inductive.\n && Safety(v)\n && (v.p3 ==> v.p1)\n && (v.p2 ==> v.p1)\n // END\n }\n\n lemma InvInductive(v: Variables, v': Variables)\n requires Inv(v) && Next(v, v')\n ensures Inv(v')\n {\n // SOLUTION\n // This :| syntax is called \"assign-such-that\". Think of it as telling Dafny\n // to assign step a value such that NextStep(v, v', step) (the predicate on\n // the RHS) holds. What Dafny will do is first prove there exists such a\n // step, then bind an arbitrary value to step where NextStep(v, v', step)\n // holds for the remainder of the proof.\n var step :| NextStep(v, v', step);\n assert NextStep(v, v', step); // by definition of :|\n // END\n match step {\n case Step1 => { return; }\n case Step2 => { return; }\n case Step3 => { return; }\n case Step4 => {\n // SOLUTION\n return;\n // END\n }\n case Noop => { return; }\n }\n }\n\n lemma InvSafe(v: Variables)\n ensures Inv(v) ==> Safety(v)\n {\n return;\n }\n\n // This is the main inductive proof of Safety, but we moved all the difficult\n // reasoning to the lemmas above.\n lemma SafetyHolds(v: Variables, v': Variables)\n ensures Init(v) ==> Inv(v)\n ensures Inv(v) && Next(v, v') ==> Inv(v')\n ensures Inv(v) ==> Safety(v)\n {\n if Inv(v) && Next(v, v') {\n InvInductive(v, v');\n }\n InvSafe(v);\n }\n\n // SOLUTION\n // Instead of worrying about Safety, we can approach invariants by starting\n // with properties that should hold in all reachable states. The advantage of\n // this approach is that we can \"checkpoint\" our work of writing an invariant\n // that characterizes reachable states. The disadvantage is that we might\n // prove properties that don't help with safety and waste time.\n //\n // Recall that an invariant may have a counterexample to induction (CTI): a\n // way to start in a state satisfying the invariant and transition out of it.\n // If the invariant really holds, then a CTI simply reflects an unreachable\n // state, one that we should try to eliminate by strengthening the invariant.\n // If we find a \"self-inductive\" property Inv that satisfies Init(v) ==>\n // Inv(v) and Inv(v) && Next(v, v') ==> Inv(v'), then we can extend it without\n // fear of breaking inductiveness: in proving Inv(v) && Inv2(v) && Next(v, v')\n // ==> Inv(v') && Inv2(v'), notice that we can immediately prove Inv(v').\n // However, we've also made progress: in proving Inv2(v'), we get to know\n // Inv(v). This may rule out some CTIs, and eventually will be enough to prove\n // Inv2 is inductive.\n //\n // Notice that the above discussion involved identifying a self-inductive\n // invariant without trying to prove a safety property. This is one way to go\n // about proving safety: start by proving \"easy\" properties that hold in\n // reachable states. This will reduce the burden of getting CTIs (or failed\n // proofs). However, don't spend all your time proving properties about\n // reachable states: there will likely be properties that really are\n // invariants, but (a) the proof is complicated and (b) they don't help you\n // prove safety.\n\n predicate Inv2(v: Variables) {\n // each of these conjuncts is individually \"self-inductive\", but all of them\n // are needed together to actually prove safety\n && (v.p2 ==> v.p1)\n && (v.p3 ==> v.p2)\n && (v.p4 ==> v.p3)\n }\n\n lemma Inv2Holds(v: Variables, v': Variables)\n ensures Init(v) ==> Inv2(v)\n ensures Inv2(v) && Next(v, v') ==> Inv2(v')\n {\n assert Init(v) ==> Inv2(v);\n if Inv2(v) && Next(v, v') {\n var step :| NextStep(v, v', step);\n match step {\n case Step1 => { return; }\n case Step2 => { return; }\n case Step3 => { return; }\n case Step4 => { return; }\n case Noop => { return; }\n }\n }\n }\n // END\n}\n\n", "hints_removed": "module Ex {\n // This simple example illustrates what the process of looking for an\n // inductive invariant might look like.\n\n datatype Variables = Variables(p1: bool, p2: bool, p3: bool, p4: bool)\n\n ghost predicate Init(v: Variables) {\n && !v.p1\n && !v.p2\n && !v.p3\n && !v.p4\n }\n\n // The state machine starts out with all four booleans false, and it \"turns\n // on\" p1, p2, p3, and p4 in order. The safety property says p4 ==> p1;\n // proving this requires a stronger inductive invariant.\n\n datatype Step =\n | Step1\n | Step2\n | Step3\n | Step4\n | Noop\n\n ghost predicate NextStep(v: Variables, v': Variables, step: Step)\n {\n match step {\n // ordinarily we'd have a predicate for each step, but in this simple\n // example it's easier to see everything written in one place\n case Step1 =>\n !v.p1 && v' == v.(p1 := true)\n case Step2 =>\n v.p1 && v' == v.(p2 := true)\n case Step3 =>\n v.p2 && v' == v.(p3 := true)\n case Step4 =>\n v.p3 && v' == v.(p4 := true)\n case Noop => v' == v\n }\n }\n\n ghost predicate Next(v: Variables, v': Variables)\n {\n exists step: Step :: NextStep(v, v', step)\n }\n\n ghost predicate Safety(v: Variables)\n {\n v.p4 ==> v.p1\n }\n\n ghost predicate Inv(v: Variables)\n {\n // SOLUTION\n // This is one approach: prove implications that go all the way back to the\n // beginning, trying to slowly work our way up to something inductive.\n && Safety(v)\n && (v.p3 ==> v.p1)\n && (v.p2 ==> v.p1)\n // END\n }\n\n lemma InvInductive(v: Variables, v': Variables)\n requires Inv(v) && Next(v, v')\n ensures Inv(v')\n {\n // SOLUTION\n // This :| syntax is called \"assign-such-that\". Think of it as telling Dafny\n // to assign step a value such that NextStep(v, v', step) (the predicate on\n // the RHS) holds. What Dafny will do is first prove there exists such a\n // step, then bind an arbitrary value to step where NextStep(v, v', step)\n // holds for the remainder of the proof.\n var step :| NextStep(v, v', step);\n // END\n match step {\n case Step1 => { return; }\n case Step2 => { return; }\n case Step3 => { return; }\n case Step4 => {\n // SOLUTION\n return;\n // END\n }\n case Noop => { return; }\n }\n }\n\n lemma InvSafe(v: Variables)\n ensures Inv(v) ==> Safety(v)\n {\n return;\n }\n\n // This is the main inductive proof of Safety, but we moved all the difficult\n // reasoning to the lemmas above.\n lemma SafetyHolds(v: Variables, v': Variables)\n ensures Init(v) ==> Inv(v)\n ensures Inv(v) && Next(v, v') ==> Inv(v')\n ensures Inv(v) ==> Safety(v)\n {\n if Inv(v) && Next(v, v') {\n InvInductive(v, v');\n }\n InvSafe(v);\n }\n\n // SOLUTION\n // Instead of worrying about Safety, we can approach invariants by starting\n // with properties that should hold in all reachable states. The advantage of\n // this approach is that we can \"checkpoint\" our work of writing an invariant\n // that characterizes reachable states. The disadvantage is that we might\n // prove properties that don't help with safety and waste time.\n //\n // Recall that an invariant may have a counterexample to induction (CTI): a\n // way to start in a state satisfying the invariant and transition out of it.\n // If the invariant really holds, then a CTI simply reflects an unreachable\n // state, one that we should try to eliminate by strengthening the invariant.\n // If we find a \"self-inductive\" property Inv that satisfies Init(v) ==>\n // Inv(v) and Inv(v) && Next(v, v') ==> Inv(v'), then we can extend it without\n // fear of breaking inductiveness: in proving Inv(v) && Inv2(v) && Next(v, v')\n // ==> Inv(v') && Inv2(v'), notice that we can immediately prove Inv(v').\n // However, we've also made progress: in proving Inv2(v'), we get to know\n // Inv(v). This may rule out some CTIs, and eventually will be enough to prove\n // Inv2 is inductive.\n //\n // Notice that the above discussion involved identifying a self-inductive\n // invariant without trying to prove a safety property. This is one way to go\n // about proving safety: start by proving \"easy\" properties that hold in\n // reachable states. This will reduce the burden of getting CTIs (or failed\n // proofs). However, don't spend all your time proving properties about\n // reachable states: there will likely be properties that really are\n // invariants, but (a) the proof is complicated and (b) they don't help you\n // prove safety.\n\n predicate Inv2(v: Variables) {\n // each of these conjuncts is individually \"self-inductive\", but all of them\n // are needed together to actually prove safety\n && (v.p2 ==> v.p1)\n && (v.p3 ==> v.p2)\n && (v.p4 ==> v.p3)\n }\n\n lemma Inv2Holds(v: Variables, v': Variables)\n ensures Init(v) ==> Inv2(v)\n ensures Inv2(v) && Next(v, v') ==> Inv2(v')\n {\n if Inv2(v) && Next(v, v') {\n var step :| NextStep(v, v', step);\n match step {\n case Step1 => { return; }\n case Step2 => { return; }\n case Step3 => { return; }\n case Step4 => { return; }\n case Noop => { return; }\n }\n }\n }\n // END\n}\n\n" }, { "test_ID": "728", "test_file": "protocol-verification-fa2023_tmp_tmpw6hy3mjp_demos_ch04_invariant_proof.dfy", "ground_truth": "/* These three declarations are _abstract_ - we declare a state machine, but\n * don't actually give a definition. Dafny will assume nothing about them, so our\n * proofs below will be true for an abitrary state machine. */\n\ntype Variables\npredicate Init(v: Variables)\npredicate Next(v: Variables, v': Variables)\n\n/* We'll also consider an abstract Safety predicate over states and a\n * user-supplied invariant to help prove the safety property. */\n\npredicate Safety(v: Variables)\npredicate Inv(v: Variables)\n\n// We're going to reason about infinite executions, called behaviors here.\ntype Behavior = nat -> Variables\n\n/* Now we want to prove the lemma below called SafetyAlwaysHolds. Take a look at\n * its theorem statement. To prove this lemma, we need a helper lemma for two\n * reasons: first, (because of Dafny) we need to have access to a variable for i\n * to perform induction on it, and second, (more fundamentally) we need to\n * _strengthen the induction hypothesis_ and prove `Inv(e(i))` rather than just\n * `Safety(e(i))`. */\n\n// This is the key induction.\nlemma InvHoldsTo(e: nat -> Variables, i: nat)\n requires Inv(e(0))\n requires forall i:nat :: Next(e(i), e(i+1))\n requires forall v, v' :: Inv(v) && Next(v, v') ==> Inv(v')\n ensures Inv(e(i))\n{\n if i == 0 {\n return;\n }\n InvHoldsTo(e, i-1);\n // this is the inductive hypothesis\n assert Inv(e(i-1));\n // the requirements let us take the invariant from one step to the next (so in\n // particular from e(i-1) to e(i)).\n assert forall i:nat :: Inv(e(i)) ==> Inv(e(i+1));\n}\n\nghost predicate IsBehavior(e: Behavior) {\n && Init(e(0))\n && forall i:nat :: Next(e(i), e(i+1))\n}\n\nlemma SafetyAlwaysHolds(e: Behavior)\n // In the labs, we'll prove these three conditions. Note that these properties\n // only require one or two states, not reasoning about sequences of states.\n requires forall v :: Init(v) ==> Inv(v)\n requires forall v, v' :: Inv(v) && Next(v, v') ==> Inv(v')\n requires forall v :: Inv(v) ==> Safety(v)\n // What we get generically from those three conditions is that the safety\n // property holds for all reachable states - every state of every behavior of\n // the state machine.\n ensures IsBehavior(e) ==> forall i :: Safety(e(i))\n{\n if IsBehavior(e) {\n assert Inv(e(0));\n forall i:nat\n ensures Safety(e(i)) {\n InvHoldsTo(e, i);\n }\n }\n}\n\n", "hints_removed": "/* These three declarations are _abstract_ - we declare a state machine, but\n * don't actually give a definition. Dafny will assume nothing about them, so our\n * proofs below will be true for an abitrary state machine. */\n\ntype Variables\npredicate Init(v: Variables)\npredicate Next(v: Variables, v': Variables)\n\n/* We'll also consider an abstract Safety predicate over states and a\n * user-supplied invariant to help prove the safety property. */\n\npredicate Safety(v: Variables)\npredicate Inv(v: Variables)\n\n// We're going to reason about infinite executions, called behaviors here.\ntype Behavior = nat -> Variables\n\n/* Now we want to prove the lemma below called SafetyAlwaysHolds. Take a look at\n * its theorem statement. To prove this lemma, we need a helper lemma for two\n * reasons: first, (because of Dafny) we need to have access to a variable for i\n * to perform induction on it, and second, (more fundamentally) we need to\n * _strengthen the induction hypothesis_ and prove `Inv(e(i))` rather than just\n * `Safety(e(i))`. */\n\n// This is the key induction.\nlemma InvHoldsTo(e: nat -> Variables, i: nat)\n requires Inv(e(0))\n requires forall i:nat :: Next(e(i), e(i+1))\n requires forall v, v' :: Inv(v) && Next(v, v') ==> Inv(v')\n ensures Inv(e(i))\n{\n if i == 0 {\n return;\n }\n InvHoldsTo(e, i-1);\n // this is the inductive hypothesis\n // the requirements let us take the invariant from one step to the next (so in\n // particular from e(i-1) to e(i)).\n}\n\nghost predicate IsBehavior(e: Behavior) {\n && Init(e(0))\n && forall i:nat :: Next(e(i), e(i+1))\n}\n\nlemma SafetyAlwaysHolds(e: Behavior)\n // In the labs, we'll prove these three conditions. Note that these properties\n // only require one or two states, not reasoning about sequences of states.\n requires forall v :: Init(v) ==> Inv(v)\n requires forall v, v' :: Inv(v) && Next(v, v') ==> Inv(v')\n requires forall v :: Inv(v) ==> Safety(v)\n // What we get generically from those three conditions is that the safety\n // property holds for all reachable states - every state of every behavior of\n // the state machine.\n ensures IsBehavior(e) ==> forall i :: Safety(e(i))\n{\n if IsBehavior(e) {\n forall i:nat\n ensures Safety(e(i)) {\n InvHoldsTo(e, i);\n }\n }\n}\n\n" }, { "test_ID": "729", "test_file": "protocol-verification-fa2023_tmp_tmpw6hy3mjp_demos_ch04_leader_election.dfy", "ground_truth": "// We'll define \"Between\" to capture how the ring wraps around.\n// SOLUTION\nghost predicate Between(start: nat, i: nat, end: nat)\n{\n if start < end then start < i < end\n else i < end || start < i\n}\n\nlemma BetweenTests()\n{\n assert Between(3, 4, 5);\n assert !Between(3, 2, 4);\n\n // when start >= end, behavior is a bit tricker\n // before end\n assert Between(5, 2, 3);\n // after start\n assert Between(5, 6, 3);\n // not in this range\n assert !Between(5, 4, 3);\n\n assert forall i, k | Between(i, k, i) :: i != k;\n}\n// END\n\n// ids gives each node's (unique) identifier (address)\n//\n// highest_heard[i] is the highest other identifier the node at index i has\n// heard about (or -1 if it has heard about nobody - note that -1 is not a valid identifier).\ndatatype Variables = Variables(ids: seq, highest_heard: seq) {\n\n ghost predicate ValidIdx(i: int) {\n 0<=i<|ids|\n }\n\n ghost predicate UniqueIds() {\n forall i, j | ValidIdx(i) && ValidIdx(j) ::\n ids[i]==ids[j] ==> i == j\n }\n\n ghost predicate WF()\n {\n && 0 < |ids|\n && |ids| == |highest_heard|\n }\n\n // We'll define an important predicate for the inductive invariant.\n // SOLUTION\n // `end` thinks `start` is the highest\n ghost predicate IsChord(start: nat, end: nat)\n {\n && ValidIdx(start) && ValidIdx(end)\n && WF()\n && highest_heard[end] == ids[start]\n }\n // END\n}\n\nghost predicate Init(v: Variables)\n{\n && v.UniqueIds()\n && v.WF()\n // Everyone begins having heard about nobody, not even themselves.\n && (forall i | v.ValidIdx(i) :: v.highest_heard[i] == -1)\n}\n\nghost function max(a: int, b: int) : int {\n if a > b then a else b\n}\n\nghost function NextIdx(v: Variables, idx: nat) : nat\n requires v.WF()\n requires v.ValidIdx(idx)\n{\n // for demo we started with a definition using modulo (%), but this non-linear\n // arithmetic is less friendly to Dafny's automation\n // SOLUTION\n if idx == |v.ids| - 1 then 0 else idx + 1\n // END\n}\n\n// The destination of a transmission is determined by the ring topology\ndatatype Step = TransmissionStep(src: nat)\n\n// This is an atomic step where src tells its neighbor (dst, computed here) the\n// highest src has seen _and_ dst updates its local state to reflect receiving\n// this message.\nghost predicate Transmission(v: Variables, v': Variables, step: Step)\n requires step.TransmissionStep?\n{\n var src := step.src;\n && v.WF()\n && v.ValidIdx(src)\n && v'.ids == v.ids\n\n // Neighbor address in ring.\n && var dst := NextIdx(v, src);\n\n // src sends the max of its highest_heard value and its own id.\n && var message := max(v.highest_heard[src], v.ids[src]);\n\n // dst only overwrites its highest_heard if the message is higher.\n && var dst_new_max := max(v.highest_heard[dst], message);\n\n // demo has a bug here\n // SOLUTION\n && v'.highest_heard == v.highest_heard[dst := dst_new_max]\n // END\n}\n\nghost predicate NextStep(v: Variables, v': Variables, step: Step)\n{\n match step {\n case TransmissionStep(_) => Transmission(v, v', step)\n }\n}\n\nlemma NextStepDeterministicGivenStep(v: Variables, step: Step, v'1: Variables, v'2: Variables)\n requires NextStep(v, v'1, step)\n requires NextStep(v, v'2, step)\n ensures v'1 == v'2\n{}\n\nghost predicate Next(v: Variables, v': Variables)\n{\n exists step :: NextStep(v, v', step)\n}\n\n//////////////////////////////////////////////////////////////////////////////\n// Spec (proof goal)\n//////////////////////////////////////////////////////////////////////////////\n\nghost predicate IsLeader(v: Variables, i: int)\n requires v.WF()\n{\n && v.ValidIdx(i)\n && v.highest_heard[i] == v.ids[i]\n}\n\nghost predicate Safety(v: Variables)\n requires v.WF()\n{\n forall i, j | IsLeader(v, i) && IsLeader(v, j) :: i == j\n}\n\n//////////////////////////////////////////////////////////////////////////////\n// Proof\n//////////////////////////////////////////////////////////////////////////////\n\n// SOLUTION\nghost predicate ChordHeardDominated(v: Variables, start: nat, end: nat)\n requires v.IsChord(start, end)\n requires v.WF()\n{\n forall i | v.ValidIdx(i) && Between(start, i, end) ::\n v.highest_heard[i] > v.ids[i]\n}\n\n// We make this opaque so Dafny does not use it automatically; instead we'll use\n// the lemma UseChordDominated when needed. In many proofs opaqueness is a way\n// to improve performance, since it prevents the automation from doing too much\n// work; in this proof it's only so we can make clear in the proof when this\n// invariant is being used.\nghost predicate {:opaque} OnChordHeardDominatesId(v: Variables)\n requires v.WF()\n{\n forall start: nat, end: nat | v.IsChord(start, end) ::\n ChordHeardDominated(v, start, end)\n}\n\nlemma UseChordDominated(v: Variables, start: nat, end: nat)\n requires v.WF()\n requires OnChordHeardDominatesId(v)\n requires v.IsChord(start, end )\n ensures ChordHeardDominated(v, start, end)\n{\n reveal OnChordHeardDominatesId();\n}\n// END\n\n\nghost predicate Inv(v: Variables)\n{\n && v.WF()\n // The solution will need more conjuncts\n // SOLUTION\n && v.UniqueIds()\n && OnChordHeardDominatesId(v)\n // Safety is not needed - we can prove it holds from the other invariants\n // END\n}\n\nlemma InitImpliesInv(v: Variables)\n requires Init(v)\n ensures Inv(v)\n{\n // SOLUTION\n forall start: nat, end: nat | v.IsChord(start, end)\n ensures false {\n }\n assert OnChordHeardDominatesId(v) by {\n reveal OnChordHeardDominatesId();\n }\n // END\n}\n\nlemma NextPreservesInv(v: Variables, v': Variables)\n requires Inv(v)\n requires Next(v, v')\n ensures Inv(v')\n{\n var step :| NextStep(v, v', step);\n // SOLUTION\n var src := step.src;\n var dst := NextIdx(v, src);\n var message := max(v.highest_heard[src], v.ids[src]);\n var dst_new_max := max(v.highest_heard[dst], message);\n assert v'.UniqueIds();\n\n forall start: nat, end: nat | v'.IsChord(start, end)\n ensures ChordHeardDominated(v', start, end)\n {\n if dst == end {\n // the destination ignored the message anyway (because it already knew of a high enough node)\n if dst_new_max == v.highest_heard[dst] {\n assert v' == v;\n UseChordDominated(v, start, end);\n assert ChordHeardDominated(v', start, end);\n } else if v'.highest_heard[dst] == v.ids[src] {\n // the new chord is empty, irrespective of the old state\n assert start == src;\n assert forall k | v.ValidIdx(k) :: !Between(start, k, end);\n assert ChordHeardDominated(v', start, end);\n } else if v'.highest_heard[end] == v.highest_heard[src] {\n // extended a chord\n assert v.IsChord(start, src); // trigger\n UseChordDominated(v, start, src);\n assert ChordHeardDominated(v', start, end);\n }\n assert ChordHeardDominated(v', start, end);\n } else {\n assert v.IsChord(start, end);\n UseChordDominated(v, start, end);\n assert ChordHeardDominated(v', start, end);\n }\n }\n assert OnChordHeardDominatesId(v') by {\n reveal OnChordHeardDominatesId();\n }\n // END\n}\n\nlemma InvImpliesSafety(v: Variables)\n requires Inv(v)\n ensures Safety(v)\n{\n // the solution gives a long proof here to try to explain what's going on, but\n // only a little proof is strictly needed for Dafny\n // SOLUTION\n forall i: nat, j: nat | IsLeader(v, i) && IsLeader(v, j)\n ensures i == j\n {\n assert forall k | v.ValidIdx(k) && Between(i, k, i) :: i != k;\n assert v.highest_heard[j] == v.ids[j]; // it's a leader\n // do this proof by contradiction\n if i != j {\n assert v.IsChord(i, i); // observe\n assert Between(i, j, i);\n UseChordDominated(v, i, i);\n // here we have the contradiction already, because i and j can't dominate\n // each others ids\n assert false;\n }\n }\n // END\n}\n\n", "hints_removed": "// We'll define \"Between\" to capture how the ring wraps around.\n// SOLUTION\nghost predicate Between(start: nat, i: nat, end: nat)\n{\n if start < end then start < i < end\n else i < end || start < i\n}\n\nlemma BetweenTests()\n{\n\n // when start >= end, behavior is a bit tricker\n // before end\n // after start\n // not in this range\n\n}\n// END\n\n// ids gives each node's (unique) identifier (address)\n//\n// highest_heard[i] is the highest other identifier the node at index i has\n// heard about (or -1 if it has heard about nobody - note that -1 is not a valid identifier).\ndatatype Variables = Variables(ids: seq, highest_heard: seq) {\n\n ghost predicate ValidIdx(i: int) {\n 0<=i<|ids|\n }\n\n ghost predicate UniqueIds() {\n forall i, j | ValidIdx(i) && ValidIdx(j) ::\n ids[i]==ids[j] ==> i == j\n }\n\n ghost predicate WF()\n {\n && 0 < |ids|\n && |ids| == |highest_heard|\n }\n\n // We'll define an important predicate for the inductive invariant.\n // SOLUTION\n // `end` thinks `start` is the highest\n ghost predicate IsChord(start: nat, end: nat)\n {\n && ValidIdx(start) && ValidIdx(end)\n && WF()\n && highest_heard[end] == ids[start]\n }\n // END\n}\n\nghost predicate Init(v: Variables)\n{\n && v.UniqueIds()\n && v.WF()\n // Everyone begins having heard about nobody, not even themselves.\n && (forall i | v.ValidIdx(i) :: v.highest_heard[i] == -1)\n}\n\nghost function max(a: int, b: int) : int {\n if a > b then a else b\n}\n\nghost function NextIdx(v: Variables, idx: nat) : nat\n requires v.WF()\n requires v.ValidIdx(idx)\n{\n // for demo we started with a definition using modulo (%), but this non-linear\n // arithmetic is less friendly to Dafny's automation\n // SOLUTION\n if idx == |v.ids| - 1 then 0 else idx + 1\n // END\n}\n\n// The destination of a transmission is determined by the ring topology\ndatatype Step = TransmissionStep(src: nat)\n\n// This is an atomic step where src tells its neighbor (dst, computed here) the\n// highest src has seen _and_ dst updates its local state to reflect receiving\n// this message.\nghost predicate Transmission(v: Variables, v': Variables, step: Step)\n requires step.TransmissionStep?\n{\n var src := step.src;\n && v.WF()\n && v.ValidIdx(src)\n && v'.ids == v.ids\n\n // Neighbor address in ring.\n && var dst := NextIdx(v, src);\n\n // src sends the max of its highest_heard value and its own id.\n && var message := max(v.highest_heard[src], v.ids[src]);\n\n // dst only overwrites its highest_heard if the message is higher.\n && var dst_new_max := max(v.highest_heard[dst], message);\n\n // demo has a bug here\n // SOLUTION\n && v'.highest_heard == v.highest_heard[dst := dst_new_max]\n // END\n}\n\nghost predicate NextStep(v: Variables, v': Variables, step: Step)\n{\n match step {\n case TransmissionStep(_) => Transmission(v, v', step)\n }\n}\n\nlemma NextStepDeterministicGivenStep(v: Variables, step: Step, v'1: Variables, v'2: Variables)\n requires NextStep(v, v'1, step)\n requires NextStep(v, v'2, step)\n ensures v'1 == v'2\n{}\n\nghost predicate Next(v: Variables, v': Variables)\n{\n exists step :: NextStep(v, v', step)\n}\n\n//////////////////////////////////////////////////////////////////////////////\n// Spec (proof goal)\n//////////////////////////////////////////////////////////////////////////////\n\nghost predicate IsLeader(v: Variables, i: int)\n requires v.WF()\n{\n && v.ValidIdx(i)\n && v.highest_heard[i] == v.ids[i]\n}\n\nghost predicate Safety(v: Variables)\n requires v.WF()\n{\n forall i, j | IsLeader(v, i) && IsLeader(v, j) :: i == j\n}\n\n//////////////////////////////////////////////////////////////////////////////\n// Proof\n//////////////////////////////////////////////////////////////////////////////\n\n// SOLUTION\nghost predicate ChordHeardDominated(v: Variables, start: nat, end: nat)\n requires v.IsChord(start, end)\n requires v.WF()\n{\n forall i | v.ValidIdx(i) && Between(start, i, end) ::\n v.highest_heard[i] > v.ids[i]\n}\n\n// We make this opaque so Dafny does not use it automatically; instead we'll use\n// the lemma UseChordDominated when needed. In many proofs opaqueness is a way\n// to improve performance, since it prevents the automation from doing too much\n// work; in this proof it's only so we can make clear in the proof when this\n// invariant is being used.\nghost predicate {:opaque} OnChordHeardDominatesId(v: Variables)\n requires v.WF()\n{\n forall start: nat, end: nat | v.IsChord(start, end) ::\n ChordHeardDominated(v, start, end)\n}\n\nlemma UseChordDominated(v: Variables, start: nat, end: nat)\n requires v.WF()\n requires OnChordHeardDominatesId(v)\n requires v.IsChord(start, end )\n ensures ChordHeardDominated(v, start, end)\n{\n reveal OnChordHeardDominatesId();\n}\n// END\n\n\nghost predicate Inv(v: Variables)\n{\n && v.WF()\n // The solution will need more conjuncts\n // SOLUTION\n && v.UniqueIds()\n && OnChordHeardDominatesId(v)\n // Safety is not needed - we can prove it holds from the other invariants\n // END\n}\n\nlemma InitImpliesInv(v: Variables)\n requires Init(v)\n ensures Inv(v)\n{\n // SOLUTION\n forall start: nat, end: nat | v.IsChord(start, end)\n ensures false {\n }\n reveal OnChordHeardDominatesId();\n }\n // END\n}\n\nlemma NextPreservesInv(v: Variables, v': Variables)\n requires Inv(v)\n requires Next(v, v')\n ensures Inv(v')\n{\n var step :| NextStep(v, v', step);\n // SOLUTION\n var src := step.src;\n var dst := NextIdx(v, src);\n var message := max(v.highest_heard[src], v.ids[src]);\n var dst_new_max := max(v.highest_heard[dst], message);\n\n forall start: nat, end: nat | v'.IsChord(start, end)\n ensures ChordHeardDominated(v', start, end)\n {\n if dst == end {\n // the destination ignored the message anyway (because it already knew of a high enough node)\n if dst_new_max == v.highest_heard[dst] {\n UseChordDominated(v, start, end);\n } else if v'.highest_heard[dst] == v.ids[src] {\n // the new chord is empty, irrespective of the old state\n } else if v'.highest_heard[end] == v.highest_heard[src] {\n // extended a chord\n UseChordDominated(v, start, src);\n }\n } else {\n UseChordDominated(v, start, end);\n }\n }\n reveal OnChordHeardDominatesId();\n }\n // END\n}\n\nlemma InvImpliesSafety(v: Variables)\n requires Inv(v)\n ensures Safety(v)\n{\n // the solution gives a long proof here to try to explain what's going on, but\n // only a little proof is strictly needed for Dafny\n // SOLUTION\n forall i: nat, j: nat | IsLeader(v, i) && IsLeader(v, j)\n ensures i == j\n {\n // do this proof by contradiction\n if i != j {\n UseChordDominated(v, i, i);\n // here we have the contradiction already, because i and j can't dominate\n // each others ids\n }\n }\n // END\n}\n\n" }, { "test_ID": "730", "test_file": "protocol-verification-fa2023_tmp_tmpw6hy3mjp_demos_ch04_toy_consensus.dfy", "ground_truth": "// Ported from ivy/examples/ivy/toy_consensus.ivy.\n\n// Ivy only supports first-order logic, which is limited (perhaps in surprising\n// ways). In this model of consensus, we use some tricks to model quorums in\n// first-order logic without getting into the arithmetic of why sets of n/2+1\n// nodes intersect.\n\ntype Node(==)\ntype Quorum(==)\ntype Choice(==)\n\nghost predicate Member(n: Node, q: Quorum)\n\n// axiom: any two quorums intersect in at least one node\n// SOLUTION\n// note we give this without proof: this is in general dangerous! However, here\n// we believe it is possible to have Node and Quorum types with this property.\n//\n// The way we might realize that is to have Node be a finite type (one value for\n// each node in the system) and Quorum to capture any subset with strictly more\n// than half the nodes. Such a setup guarantees that any two quorums intersect.\n// END\nlemma {:axiom} QuorumIntersect(q1: Quorum, q2: Quorum) returns (n: Node)\n ensures Member(n, q1) && Member(n, q2)\n\ndatatype Variables = Variables(\n votes: map>,\n // this is one reason why this is \"toy\" consensus: the decision is a global\n // variable rather than being decided at each node individually\n decision: set\n)\n{\n ghost predicate WF()\n {\n && (forall n:Node :: n in votes)\n }\n}\n\ndatatype Step =\n | CastVoteStep(n: Node, c: Choice)\n | DecideStep(c: Choice, q: Quorum)\n\nghost predicate CastVote(v: Variables, v': Variables, step: Step)\n requires v.WF()\n requires step.CastVoteStep?\n{\n var n := step.n;\n && (v.votes[n] == {})\n // learn to read these \"functional updates\" of maps/sequences:\n // this is like v.votes[n] += {step.c} if that was supported\n && (v' == v.(votes := v.votes[n := v.votes[n] + {step.c}]))\n}\n\nghost predicate Decide(v: Variables, v': Variables, step: Step)\n requires v.WF()\n requires step.DecideStep?\n{\n // if all nodes of a quorum have voted for a value, then that value can be a\n // decision\n && (forall n: Node | Member(n, step.q) :: step.c in v.votes[n])\n && v' == v.(decision := v.decision + {step.c})\n}\n\nghost predicate NextStep(v: Variables, v': Variables, step: Step)\n{\n && v.WF()\n && match step {\n case CastVoteStep(_, _) => CastVote(v, v', step)\n case DecideStep(_, _) => Decide(v, v', step)\n }\n}\n\nlemma NextStepDeterministicGivenStep(v: Variables, step: Step, v'1: Variables, v'2: Variables)\n requires NextStep(v, v'1, step)\n requires NextStep(v, v'2, step)\n ensures v'1 == v'2\n{\n}\n\nghost predicate Next(v: Variables, v': Variables)\n{\n exists step :: NextStep(v, v', step)\n}\n\nghost predicate Init(v: Variables) {\n && v.WF()\n && (forall n :: v.votes[n] == {})\n && v.decision == {}\n}\n\nghost predicate Safety(v: Variables) {\n forall c1, c2 :: c1 in v.decision && c2 in v.decision ==> c1 == c2\n}\n\n// SOLUTION\nghost predicate ChoiceQuorum(v: Variables, q: Quorum, c: Choice)\n requires v.WF()\n{\n forall n :: Member(n, q) ==> c in v.votes[n]\n}\n\nghost predicate Inv(v: Variables) {\n && v.WF()\n && Safety(v)\n && (forall n, v1, v2 :: v1 in v.votes[n] && v2 in v.votes[n] ==> v1 == v2)\n && (forall c :: c in v.decision ==> exists q:Quorum :: ChoiceQuorum(v, q, c))\n}\n// END\n\nlemma InitImpliesInv(v: Variables)\n requires Init(v)\n ensures Inv(v)\n{}\n\nlemma InvInductive(v: Variables, v': Variables)\n requires Inv(v)\n requires Next(v, v')\n ensures Inv(v')\n{\n var step :| NextStep(v, v', step);\n // SOLUTION\n match step {\n case CastVoteStep(n, c) => {\n forall c | c in v'.decision\n ensures exists q:Quorum :: ChoiceQuorum(v', q, c)\n {\n var q :| ChoiceQuorum(v, q, c);\n assert ChoiceQuorum(v', q, c);\n }\n return;\n }\n case DecideStep(c, q) => {\n forall c | c in v'.decision\n ensures exists q:Quorum :: ChoiceQuorum(v', q, c)\n {\n var q0 :| ChoiceQuorum(v, q0, c);\n assert ChoiceQuorum(v', q0, c);\n }\n forall c1, c2 | c1 in v'.decision && c2 in v'.decision\n ensures c1 == c2\n {\n var q1 :| ChoiceQuorum(v, q1, c1);\n var q2 :| ChoiceQuorum(v, q2, c2);\n var n := QuorumIntersect(q1, q2);\n }\n assert Safety(v');\n return;\n }\n }\n // END\n}\n\nlemma SafetyHolds(v: Variables, v': Variables)\n ensures Init(v) ==> Inv(v)\n ensures Inv(v) && Next(v, v') ==> Inv(v')\n ensures Inv(v) ==> Safety(v)\n{\n if Inv(v) && Next(v, v') {\n InvInductive(v, v');\n }\n}\n\n", "hints_removed": "// Ported from ivy/examples/ivy/toy_consensus.ivy.\n\n// Ivy only supports first-order logic, which is limited (perhaps in surprising\n// ways). In this model of consensus, we use some tricks to model quorums in\n// first-order logic without getting into the arithmetic of why sets of n/2+1\n// nodes intersect.\n\ntype Node(==)\ntype Quorum(==)\ntype Choice(==)\n\nghost predicate Member(n: Node, q: Quorum)\n\n// axiom: any two quorums intersect in at least one node\n// SOLUTION\n// note we give this without proof: this is in general dangerous! However, here\n// we believe it is possible to have Node and Quorum types with this property.\n//\n// The way we might realize that is to have Node be a finite type (one value for\n// each node in the system) and Quorum to capture any subset with strictly more\n// than half the nodes. Such a setup guarantees that any two quorums intersect.\n// END\nlemma {:axiom} QuorumIntersect(q1: Quorum, q2: Quorum) returns (n: Node)\n ensures Member(n, q1) && Member(n, q2)\n\ndatatype Variables = Variables(\n votes: map>,\n // this is one reason why this is \"toy\" consensus: the decision is a global\n // variable rather than being decided at each node individually\n decision: set\n)\n{\n ghost predicate WF()\n {\n && (forall n:Node :: n in votes)\n }\n}\n\ndatatype Step =\n | CastVoteStep(n: Node, c: Choice)\n | DecideStep(c: Choice, q: Quorum)\n\nghost predicate CastVote(v: Variables, v': Variables, step: Step)\n requires v.WF()\n requires step.CastVoteStep?\n{\n var n := step.n;\n && (v.votes[n] == {})\n // learn to read these \"functional updates\" of maps/sequences:\n // this is like v.votes[n] += {step.c} if that was supported\n && (v' == v.(votes := v.votes[n := v.votes[n] + {step.c}]))\n}\n\nghost predicate Decide(v: Variables, v': Variables, step: Step)\n requires v.WF()\n requires step.DecideStep?\n{\n // if all nodes of a quorum have voted for a value, then that value can be a\n // decision\n && (forall n: Node | Member(n, step.q) :: step.c in v.votes[n])\n && v' == v.(decision := v.decision + {step.c})\n}\n\nghost predicate NextStep(v: Variables, v': Variables, step: Step)\n{\n && v.WF()\n && match step {\n case CastVoteStep(_, _) => CastVote(v, v', step)\n case DecideStep(_, _) => Decide(v, v', step)\n }\n}\n\nlemma NextStepDeterministicGivenStep(v: Variables, step: Step, v'1: Variables, v'2: Variables)\n requires NextStep(v, v'1, step)\n requires NextStep(v, v'2, step)\n ensures v'1 == v'2\n{\n}\n\nghost predicate Next(v: Variables, v': Variables)\n{\n exists step :: NextStep(v, v', step)\n}\n\nghost predicate Init(v: Variables) {\n && v.WF()\n && (forall n :: v.votes[n] == {})\n && v.decision == {}\n}\n\nghost predicate Safety(v: Variables) {\n forall c1, c2 :: c1 in v.decision && c2 in v.decision ==> c1 == c2\n}\n\n// SOLUTION\nghost predicate ChoiceQuorum(v: Variables, q: Quorum, c: Choice)\n requires v.WF()\n{\n forall n :: Member(n, q) ==> c in v.votes[n]\n}\n\nghost predicate Inv(v: Variables) {\n && v.WF()\n && Safety(v)\n && (forall n, v1, v2 :: v1 in v.votes[n] && v2 in v.votes[n] ==> v1 == v2)\n && (forall c :: c in v.decision ==> exists q:Quorum :: ChoiceQuorum(v, q, c))\n}\n// END\n\nlemma InitImpliesInv(v: Variables)\n requires Init(v)\n ensures Inv(v)\n{}\n\nlemma InvInductive(v: Variables, v': Variables)\n requires Inv(v)\n requires Next(v, v')\n ensures Inv(v')\n{\n var step :| NextStep(v, v', step);\n // SOLUTION\n match step {\n case CastVoteStep(n, c) => {\n forall c | c in v'.decision\n ensures exists q:Quorum :: ChoiceQuorum(v', q, c)\n {\n var q :| ChoiceQuorum(v, q, c);\n }\n return;\n }\n case DecideStep(c, q) => {\n forall c | c in v'.decision\n ensures exists q:Quorum :: ChoiceQuorum(v', q, c)\n {\n var q0 :| ChoiceQuorum(v, q0, c);\n }\n forall c1, c2 | c1 in v'.decision && c2 in v'.decision\n ensures c1 == c2\n {\n var q1 :| ChoiceQuorum(v, q1, c1);\n var q2 :| ChoiceQuorum(v, q2, c2);\n var n := QuorumIntersect(q1, q2);\n }\n return;\n }\n }\n // END\n}\n\nlemma SafetyHolds(v: Variables, v': Variables)\n ensures Init(v) ==> Inv(v)\n ensures Inv(v) && Next(v, v') ==> Inv(v')\n ensures Inv(v) ==> Safety(v)\n{\n if Inv(v) && Next(v, v') {\n InvInductive(v, v');\n }\n}\n\n" }, { "test_ID": "731", "test_file": "protocol-verification-fa2023_tmp_tmpw6hy3mjp_demos_ch06_refinement_proof.dfy", "ground_truth": "// Analogous to ch04/invariant_proof.dfy, we show what the conditions on a\n// refinement (an abstraction function, invariant, an initial condition, and an\n// inductive property)\n\nmodule Types {\n type Event(==, 0, !new)\n}\n\nimport opened Types\n\nmodule Code {\n import opened Types\n type Variables(==, 0, !new)\n ghost predicate Init(v: Variables)\n ghost predicate Next(v: Variables, v': Variables, ev: Event)\n\n ghost predicate IsBehavior(tr: nat -> Event) {\n exists ss: nat -> Variables ::\n && Init(ss(0))\n && forall n: nat :: Next(ss(n), ss(n + 1), tr(n))\n }\n}\n\nmodule Spec {\n import opened Types\n type Variables(==, 0, !new)\n ghost predicate Init(v: Variables)\n ghost predicate Next(v: Variables, v': Variables, ev: Event)\n\n ghost predicate IsBehavior(tr: nat -> Event) {\n exists ss: nat -> Variables ::\n && Init(ss(0))\n && forall n: nat :: Next(ss(n), ss(n + 1), tr(n))\n }\n}\n\n// The proof of refinement is based on supplying these two pieces of data. Note\n// that they don't appear in the final statement of Refinement; they're only the\n// evidence that shows how to demonstrate refinement one step at a time.\n\nghost predicate Inv(v: Code.Variables)\nghost function Abstraction(v: Code.Variables): Spec.Variables\n\n// These two properties of the abstraction are sometimes called a \"forward\n// simulation\", to distinguish them from refinement which is the property we're\n// trying to achieve. (There is also an analogous \"backward simulation\" that\n// works in the reverse direction of execution and is more complicated - we\n// won't need it).\n\nlemma {:axiom} AbstractionInit(v: Code.Variables)\n requires Code.Init(v)\n ensures Inv(v)\n ensures Spec.Init(Abstraction(v))\n\nlemma {:axiom} AbstractionInductive(v: Code.Variables, v': Code.Variables, ev: Event)\n requires Inv(v)\n requires Code.Next(v, v', ev)\n ensures Inv(v')\n ensures Spec.Next(Abstraction(v), Abstraction(v'), ev)\n\n// InvAt is a helper lemma to show the invariant always holds using Dafny\n// induction.\nlemma InvAt(tr: nat -> Event, ss: nat -> Code.Variables, i: nat)\n requires Code.Init(ss(0))\n requires forall k:nat :: Code.Next(ss(k), ss(k + 1), tr(k))\n ensures Inv(ss(i))\n{\n if i == 0 {\n AbstractionInit(ss(0));\n } else {\n InvAt(tr, ss, i - 1);\n AbstractionInductive(ss(i - 1), ss(i), tr(i - 1));\n }\n}\n\n// RefinementTo is a helper lemma to prove refinement inductively (for a\n// specific sequence of states).\nlemma RefinementTo(tr: nat -> Event, ss: nat -> Code.Variables, i: nat)\n requires forall n: nat :: Code.Next(ss(n), ss(n + 1), tr(n))\n requires forall n: nat :: Inv(ss(n))\n ensures\n var ss' := (j: nat) => Abstraction(ss(j));\n && forall n: nat | n < i :: Spec.Next(ss'(n), ss'(n + 1), tr(n))\n{\n if i == 0 {\n return;\n } else {\n var ss' := (j: nat) => Abstraction(ss(j));\n RefinementTo(tr, ss, i - 1);\n AbstractionInductive(ss(i - 1), ss(i), tr(i - 1));\n }\n}\n\n// Refinement is the key property we use the abstraction and forward simulation\n// to prove.\nlemma Refinement(tr: nat -> Event)\n requires Code.IsBehavior(tr)\n ensures Spec.IsBehavior(tr)\n{\n var ss: nat -> Code.Variables :|\n && Code.Init(ss(0))\n && forall n: nat :: Code.Next(ss(n), ss(n + 1), tr(n));\n forall i: nat\n ensures Inv(ss(i)) {\n InvAt(tr, ss, i);\n }\n\n var ss': nat -> Spec.Variables :=\n (i: nat) => Abstraction(ss(i));\n assert Spec.Init(ss'(0)) by {\n AbstractionInit(ss(0));\n }\n forall n: nat\n ensures Spec.Next(ss'(n), ss'(n + 1), tr(n))\n {\n RefinementTo(tr, ss, n+1);\n }\n}\n\n", "hints_removed": "// Analogous to ch04/invariant_proof.dfy, we show what the conditions on a\n// refinement (an abstraction function, invariant, an initial condition, and an\n// inductive property)\n\nmodule Types {\n type Event(==, 0, !new)\n}\n\nimport opened Types\n\nmodule Code {\n import opened Types\n type Variables(==, 0, !new)\n ghost predicate Init(v: Variables)\n ghost predicate Next(v: Variables, v': Variables, ev: Event)\n\n ghost predicate IsBehavior(tr: nat -> Event) {\n exists ss: nat -> Variables ::\n && Init(ss(0))\n && forall n: nat :: Next(ss(n), ss(n + 1), tr(n))\n }\n}\n\nmodule Spec {\n import opened Types\n type Variables(==, 0, !new)\n ghost predicate Init(v: Variables)\n ghost predicate Next(v: Variables, v': Variables, ev: Event)\n\n ghost predicate IsBehavior(tr: nat -> Event) {\n exists ss: nat -> Variables ::\n && Init(ss(0))\n && forall n: nat :: Next(ss(n), ss(n + 1), tr(n))\n }\n}\n\n// The proof of refinement is based on supplying these two pieces of data. Note\n// that they don't appear in the final statement of Refinement; they're only the\n// evidence that shows how to demonstrate refinement one step at a time.\n\nghost predicate Inv(v: Code.Variables)\nghost function Abstraction(v: Code.Variables): Spec.Variables\n\n// These two properties of the abstraction are sometimes called a \"forward\n// simulation\", to distinguish them from refinement which is the property we're\n// trying to achieve. (There is also an analogous \"backward simulation\" that\n// works in the reverse direction of execution and is more complicated - we\n// won't need it).\n\nlemma {:axiom} AbstractionInit(v: Code.Variables)\n requires Code.Init(v)\n ensures Inv(v)\n ensures Spec.Init(Abstraction(v))\n\nlemma {:axiom} AbstractionInductive(v: Code.Variables, v': Code.Variables, ev: Event)\n requires Inv(v)\n requires Code.Next(v, v', ev)\n ensures Inv(v')\n ensures Spec.Next(Abstraction(v), Abstraction(v'), ev)\n\n// InvAt is a helper lemma to show the invariant always holds using Dafny\n// induction.\nlemma InvAt(tr: nat -> Event, ss: nat -> Code.Variables, i: nat)\n requires Code.Init(ss(0))\n requires forall k:nat :: Code.Next(ss(k), ss(k + 1), tr(k))\n ensures Inv(ss(i))\n{\n if i == 0 {\n AbstractionInit(ss(0));\n } else {\n InvAt(tr, ss, i - 1);\n AbstractionInductive(ss(i - 1), ss(i), tr(i - 1));\n }\n}\n\n// RefinementTo is a helper lemma to prove refinement inductively (for a\n// specific sequence of states).\nlemma RefinementTo(tr: nat -> Event, ss: nat -> Code.Variables, i: nat)\n requires forall n: nat :: Code.Next(ss(n), ss(n + 1), tr(n))\n requires forall n: nat :: Inv(ss(n))\n ensures\n var ss' := (j: nat) => Abstraction(ss(j));\n && forall n: nat | n < i :: Spec.Next(ss'(n), ss'(n + 1), tr(n))\n{\n if i == 0 {\n return;\n } else {\n var ss' := (j: nat) => Abstraction(ss(j));\n RefinementTo(tr, ss, i - 1);\n AbstractionInductive(ss(i - 1), ss(i), tr(i - 1));\n }\n}\n\n// Refinement is the key property we use the abstraction and forward simulation\n// to prove.\nlemma Refinement(tr: nat -> Event)\n requires Code.IsBehavior(tr)\n ensures Spec.IsBehavior(tr)\n{\n var ss: nat -> Code.Variables :|\n && Code.Init(ss(0))\n && forall n: nat :: Code.Next(ss(n), ss(n + 1), tr(n));\n forall i: nat\n ensures Inv(ss(i)) {\n InvAt(tr, ss, i);\n }\n\n var ss': nat -> Spec.Variables :=\n (i: nat) => Abstraction(ss(i));\n AbstractionInit(ss(0));\n }\n forall n: nat\n ensures Spec.Next(ss'(n), ss'(n + 1), tr(n))\n {\n RefinementTo(tr, ss, n+1);\n }\n}\n\n" }, { "test_ID": "732", "test_file": "protocol-verification-fa2023_tmp_tmpw6hy3mjp_demos_dafny-internals_02-triggers_triggers2.dfy", "ground_truth": "function f(x: int): int\n\nfunction ff(x: int): int\n\nlemma {:axiom} ff_eq()\n ensures forall x {:trigger ff(x)} :: ff(x) == f(f(x))\n\nlemma {:axiom} ff_eq2()\n ensures forall x {:trigger f(f(x))} :: ff(x) == f(f(x))\n\nlemma {:axiom} ff_eq_bad()\n // dafny ignores this trigger because it's an obvious loop\n ensures forall x {:trigger {f(x)}} :: ff(x) == f(f(x))\n\nlemma use_ff(x: int)\n{\n ff_eq();\n assert f(ff(x)) == ff(f(x));\n}\n\nlemma use_ff2(x: int)\n{\n ff_eq2();\n assert f(f(x)) == ff(x);\n assert f(ff(x)) == ff(f(x));\n}\n\n", "hints_removed": "function f(x: int): int\n\nfunction ff(x: int): int\n\nlemma {:axiom} ff_eq()\n ensures forall x {:trigger ff(x)} :: ff(x) == f(f(x))\n\nlemma {:axiom} ff_eq2()\n ensures forall x {:trigger f(f(x))} :: ff(x) == f(f(x))\n\nlemma {:axiom} ff_eq_bad()\n // dafny ignores this trigger because it's an obvious loop\n ensures forall x {:trigger {f(x)}} :: ff(x) == f(f(x))\n\nlemma use_ff(x: int)\n{\n ff_eq();\n}\n\nlemma use_ff2(x: int)\n{\n ff_eq2();\n}\n\n" }, { "test_ID": "733", "test_file": "protocol-verification-fa2023_tmp_tmpw6hy3mjp_demos_dafny-internals_03-encoding_lemma_call.dfy", "ground_truth": "function f(x: int): int\n\nlemma {:axiom} f_positive(x: int)\n requires x >= 0\n ensures f(x) >= 0\n\nlemma f_2_pos()\n ensures f(2) >= 0\n{\n f_positive(2);\n}\n\nlemma f_1_1_pos()\n ensures f(1 + 1) >= 0\n{\n f_2_pos();\n assert 1 + 1 == 2;\n}\n\n", "hints_removed": "function f(x: int): int\n\nlemma {:axiom} f_positive(x: int)\n requires x >= 0\n ensures f(x) >= 0\n\nlemma f_2_pos()\n ensures f(2) >= 0\n{\n f_positive(2);\n}\n\nlemma f_1_1_pos()\n ensures f(1 + 1) >= 0\n{\n f_2_pos();\n}\n\n" }, { "test_ID": "734", "test_file": "protocol-verification-fa2023_tmp_tmpw6hy3mjp_demos_dafny-internals_03-encoding_pair.dfy", "ground_truth": "// based on https://ethz.ch/content/dam/ethz/special-interest/infk/chair-program-method/pm/documents/Education/Courses/SS2019/Program%20Verification/05-EncodingToSMT.pdf\n\nmodule DafnyVersion {\n datatype Pair = Pair(x: int, y: int)\n\n function pair_x(p: Pair): int {\n p.x\n }\n\n function pair_y(p: Pair): int {\n p.y\n }\n\n lemma UsePair() {\n assert Pair(1, 2) != Pair(2, 1);\n var p := Pair(1, 2);\n assert pair_x(p) + pair_y(p) == 3;\n\n assert forall p1, p2 :: pair_x(p1) == pair_x(p2) && pair_y(p1) == pair_y(p2) ==> p1 == p2;\n }\n}\n\n// Dafny encodes pairs to SMT by emitting the SMT equivalent of the following.\nmodule Encoding {\n\n // We define the new type as a new \"sort\" in SMT. This will create a new type\n // but not give any way to construct or use it.\n type Pair(==)\n\n // Then we define _uninterpreted functions_ for all the operations on the\n // type. These are all the implicit operations on a DafnyVersion.Pair:\n function pair(x: int, y: int): Pair\n function pair_x(p: Pair): int\n function pair_y(p: Pair): int\n\n // Finally (and this is the interesting bit) we define _axioms_ that assume\n // the uninterpreted functions have the expected properties. Getting the\n // axioms right is a bit of an art in that we want sound and minimal axioms,\n // ones that are efficient for the solver, and we want to fully characterize\n // pairs so that proofs go through.\n lemma {:axiom} x_defn()\n ensures forall x, y :: pair_x(pair(x, y)) == x\n lemma {:axiom} y_defn()\n ensures forall x, y :: pair_y(pair(x, y)) == y\n lemma {:axiom} bijection()\n ensures forall p:Pair :: pair(pair_x(p), pair_y(p)) == p\n\n lemma UseEncoding() {\n\n x_defn();\n y_defn();\n bijection();\n\n assert pair(1, 2) != pair(2, 1) by {\n x_defn();\n }\n\n assert pair_y(pair(1, 2)) == 2 by {\n y_defn();\n }\n\n assert forall p1, p2 |\n pair_x(p1) == pair_x(p2) && pair_y(p1) == pair_y(p2)\n :: p1 == p2 by {\n bijection();\n }\n }\n\n // Exercises to think about:\n // How exactly are the axioms being used in each proof above?\n // What happens if we remove the bijection axiom?\n // Can you think of other properties wee would expect?\n // Are we missing any axioms? How would you know? (hard)\n}\n\n", "hints_removed": "// based on https://ethz.ch/content/dam/ethz/special-interest/infk/chair-program-method/pm/documents/Education/Courses/SS2019/Program%20Verification/05-EncodingToSMT.pdf\n\nmodule DafnyVersion {\n datatype Pair = Pair(x: int, y: int)\n\n function pair_x(p: Pair): int {\n p.x\n }\n\n function pair_y(p: Pair): int {\n p.y\n }\n\n lemma UsePair() {\n var p := Pair(1, 2);\n\n }\n}\n\n// Dafny encodes pairs to SMT by emitting the SMT equivalent of the following.\nmodule Encoding {\n\n // We define the new type as a new \"sort\" in SMT. This will create a new type\n // but not give any way to construct or use it.\n type Pair(==)\n\n // Then we define _uninterpreted functions_ for all the operations on the\n // type. These are all the implicit operations on a DafnyVersion.Pair:\n function pair(x: int, y: int): Pair\n function pair_x(p: Pair): int\n function pair_y(p: Pair): int\n\n // Finally (and this is the interesting bit) we define _axioms_ that assume\n // the uninterpreted functions have the expected properties. Getting the\n // axioms right is a bit of an art in that we want sound and minimal axioms,\n // ones that are efficient for the solver, and we want to fully characterize\n // pairs so that proofs go through.\n lemma {:axiom} x_defn()\n ensures forall x, y :: pair_x(pair(x, y)) == x\n lemma {:axiom} y_defn()\n ensures forall x, y :: pair_y(pair(x, y)) == y\n lemma {:axiom} bijection()\n ensures forall p:Pair :: pair(pair_x(p), pair_y(p)) == p\n\n lemma UseEncoding() {\n\n x_defn();\n y_defn();\n bijection();\n\n x_defn();\n }\n\n y_defn();\n }\n\n pair_x(p1) == pair_x(p2) && pair_y(p1) == pair_y(p2)\n :: p1 == p2 by {\n bijection();\n }\n }\n\n // Exercises to think about:\n // How exactly are the axioms being used in each proof above?\n // What happens if we remove the bijection axiom?\n // Can you think of other properties wee would expect?\n // Are we missing any axioms? How would you know? (hard)\n}\n\n" }, { "test_ID": "735", "test_file": "protocol-verification-fa2023_tmp_tmpw6hy3mjp_exercises_chapter04-invariants_ch03exercise03.dfy", "ground_truth": "\n// Model a lock service that consists of a single server and an\n// arbitrary number of clients.\n//\n// The state of the system includes the server's state (whether the server\n// knows that some client holds the lock, and if so which one)\n// and the clients' states (for each client, whether that client knows\n// it holds the lock).\n//\n// The system should begin with the server holding the lock.\n// An acquire step atomically transfers the lock from the server to some client.\n// (Note that we're not modeling the network yet -- the lock disappears from\n// the server and appears at a client in a single atomic transition.)\n// A release step atomically transfers the lock from the client back to the server.\n//\n// The safety property is that no two clients ever hold the lock\n// simultaneously.\n\n// SOLUTION\ndatatype ServerGrant = Unlocked | Client(id: nat)\ndatatype ClientRecord = Released | Acquired\ndatatype Variables = Variables(\n clientCount: nat, /* constant */\n server: ServerGrant, clients: seq\n) {\n ghost predicate ValidIdx(idx: int) {\n 0 <= idx < this.clientCount\n }\n ghost predicate WellFormed() {\n |clients| == this.clientCount\n }\n}\n// END\n\n\nghost predicate Init(v:Variables) {\n && v.WellFormed()\n // SOLUTION\n && v.server.Unlocked?\n && |v.clients| == v.clientCount\n && forall i | 0 <= i < |v.clients| :: v.clients[i].Released?\n // END\n}\n// SOLUTION\nghost predicate Acquire(v:Variables, v':Variables, id:int) {\n && v.WellFormed()\n && v'.WellFormed()\n && v.ValidIdx(id)\n\n && v.server.Unlocked?\n\n && v'.server == Client(id)\n && v'.clients == v.clients[id := Acquired]\n && v'.clientCount == v.clientCount\n}\n\nghost predicate Release(v:Variables, v':Variables, id:int) {\n && v.WellFormed()\n && v'.WellFormed()\n && v.ValidIdx(id)\n\n && v.clients[id].Acquired?\n\n && v'.server.Unlocked?\n && v'.clients == v.clients[id := Released]\n && v'.clientCount == v.clientCount\n}\n// END\n// Jay-Normal-Form: pack all the nondeterminism into a single object\n// that gets there-exist-ed once.\ndatatype Step =\n // SOLUTION\n | AcquireStep(id: int)\n | ReleaseStep(id: int)\n // END\n\nghost predicate NextStep(v:Variables, v':Variables, step: Step) {\n match step\n // SOLUTION\n case AcquireStep(id) => Acquire(v, v', id)\n case ReleaseStep(id) => Release(v, v', id)\n // END\n}\n\nlemma NextStepDeterministicGivenStep(v:Variables, v':Variables, step: Step)\n requires NextStep(v, v', step)\n ensures forall v'' | NextStep(v, v'', step) :: v' == v''\n{}\n\nghost predicate Next(v:Variables, v':Variables) {\n exists step :: NextStep(v, v', step)\n}\n\n// A good definition of safety for the lock server is that no two clients\n// may hold the lock simultaneously. This predicate should capture that\n// idea in terms of the Variables you have defined.\nghost predicate Safety(v:Variables) {\n // SOLUTION\n // HAND-GRADE: The examiner must read the definition of Variables and confirm\n // that this predicate captures the semantics in the comment at the top of the\n // predicate.\n\n forall i,j |\n && 0 <= i < |v.clients|\n && 0 <= j < |v.clients|\n && v.clients[i].Acquired?\n && v.clients[j].Acquired?\n :: i == j\n // END\n}\n\n\n// This predicate should be true if and only if the client with index `clientIndex`\n// has the lock acquired.\n// Since you defined the Variables state, you must define this predicate in\n// those terms.\nghost predicate ClientHoldsLock(v: Variables, clientIndex: nat)\n requires v.WellFormed()\n{\n // SOLUTION\n && v.server == Client(clientIndex)\n // END\n}\n\n// Show a behavior that the system can release a lock from clientA and deliver\n// it to clientB.\nlemma PseudoLiveness(clientA:nat, clientB:nat) returns (behavior:seq)\n requires clientA == 2\n requires clientB == 0\n ensures 2 <= |behavior| // precondition for index operators below\n ensures Init(behavior[0])\n ensures forall i | 0 <= i < |behavior|-1 :: Next(behavior[i], behavior[i+1]) // Behavior satisfies your state machine\n ensures forall i | 0 <= i < |behavior| :: Safety(behavior[i]) // Behavior always satisfies the Safety predicate\n ensures behavior[|behavior|-1].WellFormed() // precondition for calling ClientHoldsLock\n ensures ClientHoldsLock(behavior[1], clientA) // first clientA acquires lock\n ensures ClientHoldsLock(behavior[|behavior|-1], clientB) // eventually clientB acquires lock\n{\n // SOLUTION\n var state0 := Variables(clientCount := 3, server := Unlocked, clients := [Released, Released, Released]);\n var state1 := Variables(clientCount := 3, server := Client(clientA), clients := [Released, Released, Acquired]);\n var state2 := Variables(clientCount := 3, server := Unlocked, clients := [Released, Released, Released]);\n var state3 := Variables(clientCount := 3, server := Client(clientB), clients := [Acquired, Released, Released]);\n assert NextStep(state0, state1, AcquireStep(clientA));\n assert Release(state1, state2, 2);\n assert NextStep(state1, state2, ReleaseStep(clientA)); // witness\n assert NextStep(state2, state3, AcquireStep(clientB)); // witness\n behavior := [state0, state1, state2, state3];\n // END\n}\n\n", "hints_removed": "\n// Model a lock service that consists of a single server and an\n// arbitrary number of clients.\n//\n// The state of the system includes the server's state (whether the server\n// knows that some client holds the lock, and if so which one)\n// and the clients' states (for each client, whether that client knows\n// it holds the lock).\n//\n// The system should begin with the server holding the lock.\n// An acquire step atomically transfers the lock from the server to some client.\n// (Note that we're not modeling the network yet -- the lock disappears from\n// the server and appears at a client in a single atomic transition.)\n// A release step atomically transfers the lock from the client back to the server.\n//\n// The safety property is that no two clients ever hold the lock\n// simultaneously.\n\n// SOLUTION\ndatatype ServerGrant = Unlocked | Client(id: nat)\ndatatype ClientRecord = Released | Acquired\ndatatype Variables = Variables(\n clientCount: nat, /* constant */\n server: ServerGrant, clients: seq\n) {\n ghost predicate ValidIdx(idx: int) {\n 0 <= idx < this.clientCount\n }\n ghost predicate WellFormed() {\n |clients| == this.clientCount\n }\n}\n// END\n\n\nghost predicate Init(v:Variables) {\n && v.WellFormed()\n // SOLUTION\n && v.server.Unlocked?\n && |v.clients| == v.clientCount\n && forall i | 0 <= i < |v.clients| :: v.clients[i].Released?\n // END\n}\n// SOLUTION\nghost predicate Acquire(v:Variables, v':Variables, id:int) {\n && v.WellFormed()\n && v'.WellFormed()\n && v.ValidIdx(id)\n\n && v.server.Unlocked?\n\n && v'.server == Client(id)\n && v'.clients == v.clients[id := Acquired]\n && v'.clientCount == v.clientCount\n}\n\nghost predicate Release(v:Variables, v':Variables, id:int) {\n && v.WellFormed()\n && v'.WellFormed()\n && v.ValidIdx(id)\n\n && v.clients[id].Acquired?\n\n && v'.server.Unlocked?\n && v'.clients == v.clients[id := Released]\n && v'.clientCount == v.clientCount\n}\n// END\n// Jay-Normal-Form: pack all the nondeterminism into a single object\n// that gets there-exist-ed once.\ndatatype Step =\n // SOLUTION\n | AcquireStep(id: int)\n | ReleaseStep(id: int)\n // END\n\nghost predicate NextStep(v:Variables, v':Variables, step: Step) {\n match step\n // SOLUTION\n case AcquireStep(id) => Acquire(v, v', id)\n case ReleaseStep(id) => Release(v, v', id)\n // END\n}\n\nlemma NextStepDeterministicGivenStep(v:Variables, v':Variables, step: Step)\n requires NextStep(v, v', step)\n ensures forall v'' | NextStep(v, v'', step) :: v' == v''\n{}\n\nghost predicate Next(v:Variables, v':Variables) {\n exists step :: NextStep(v, v', step)\n}\n\n// A good definition of safety for the lock server is that no two clients\n// may hold the lock simultaneously. This predicate should capture that\n// idea in terms of the Variables you have defined.\nghost predicate Safety(v:Variables) {\n // SOLUTION\n // HAND-GRADE: The examiner must read the definition of Variables and confirm\n // that this predicate captures the semantics in the comment at the top of the\n // predicate.\n\n forall i,j |\n && 0 <= i < |v.clients|\n && 0 <= j < |v.clients|\n && v.clients[i].Acquired?\n && v.clients[j].Acquired?\n :: i == j\n // END\n}\n\n\n// This predicate should be true if and only if the client with index `clientIndex`\n// has the lock acquired.\n// Since you defined the Variables state, you must define this predicate in\n// those terms.\nghost predicate ClientHoldsLock(v: Variables, clientIndex: nat)\n requires v.WellFormed()\n{\n // SOLUTION\n && v.server == Client(clientIndex)\n // END\n}\n\n// Show a behavior that the system can release a lock from clientA and deliver\n// it to clientB.\nlemma PseudoLiveness(clientA:nat, clientB:nat) returns (behavior:seq)\n requires clientA == 2\n requires clientB == 0\n ensures 2 <= |behavior| // precondition for index operators below\n ensures Init(behavior[0])\n ensures forall i | 0 <= i < |behavior|-1 :: Next(behavior[i], behavior[i+1]) // Behavior satisfies your state machine\n ensures forall i | 0 <= i < |behavior| :: Safety(behavior[i]) // Behavior always satisfies the Safety predicate\n ensures behavior[|behavior|-1].WellFormed() // precondition for calling ClientHoldsLock\n ensures ClientHoldsLock(behavior[1], clientA) // first clientA acquires lock\n ensures ClientHoldsLock(behavior[|behavior|-1], clientB) // eventually clientB acquires lock\n{\n // SOLUTION\n var state0 := Variables(clientCount := 3, server := Unlocked, clients := [Released, Released, Released]);\n var state1 := Variables(clientCount := 3, server := Client(clientA), clients := [Released, Released, Acquired]);\n var state2 := Variables(clientCount := 3, server := Unlocked, clients := [Released, Released, Released]);\n var state3 := Variables(clientCount := 3, server := Client(clientB), clients := [Acquired, Released, Released]);\n behavior := [state0, state1, state2, state3];\n // END\n}\n\n" }, { "test_ID": "736", "test_file": "pucrs-metodos-formais-t1_tmp_tmp7gvq3cw4_fila.dfy", "ground_truth": " /*\n OK fila de tamanho ilimitado com arrays circulares\n OK representa\u00e7\u00e3o ghost: cole\u00e7\u00e3o de elementos da fila e qualquer outra informa\u00e7\u00e3o necess\u00e1ria\n OK predicate: invariante da representa\u00e7\u00e3o abstrata associada \u00e0 cole\u00e7\u00e3o do tipo fila\n\n Opera\u00e7\u00f5es\n - OK construtor inicia fila fazia\n - OK adicionar novo elemento na fila -> enfileira()\n - OK remover um elemento da fila e retornar seu valor caso a fila contenha elementos -> desenfileira()\n - OK verificar se um elemento pertence a fila -> contem()\n - OK retornar numero de elementos da fila -> tamanho()\n - OK verificar se a fila \u00e9 vazia ou n\u00e3o -> estaVazia()\n - OK concatenar duas filas retornando uma nova fila sem alterar nenhuma das outras -> concat()\n\n OK criar m\u00e9todo main testando a implementa\u00e7\u00e3o \n OK transformar uso de naturais para inteiros\n*/\n\nclass {:autocontracts} Fila\n {\n var a: array;\n var cauda: nat;\n const defaultSize: nat;\n\n ghost var Conteudo: seq;\n\n // invariante\n ghost predicate Valid() {\n defaultSize > 0\n && a.Length >= defaultSize\n && 0 <= cauda <= a.Length\n && Conteudo == a[0..cauda]\n }\n\n // inicia fila com 3 elementos\n constructor ()\n ensures Conteudo == []\n ensures defaultSize == 3\n ensures a.Length == 3\n ensures fresh(a)\n {\n defaultSize := 3;\n a := new int[3];\n cauda := 0;\n Conteudo := [];\n }\n\n function tamanho():nat\n ensures tamanho() == |Conteudo|\n {\n cauda\n }\n\n function estaVazia(): bool\n ensures estaVazia() <==> |Conteudo| == 0\n {\n cauda == 0\n }\n\n method enfileira(e:int)\n ensures Conteudo == old(Conteudo) + [e]\n {\n\n if (cauda == a.Length) {\n var novoArray := new int[cauda + defaultSize];\n var i := 0;\n\n forall i | 0 <= i < a.Length\n {\n novoArray[i] := a[i];\n }\n a := novoArray;\n }\n\n a[cauda] := e;\n cauda := cauda + 1;\n Conteudo := Conteudo + [e];\n }\n\n method desenfileira() returns (e:int)\n requires |Conteudo| > 0\n ensures e == old(Conteudo)[0]\n ensures Conteudo == old(Conteudo)[1..]\n {\n e := a[0];\n cauda := cauda - 1;\n forall i | 0 <= i < cauda\n {\n a[i] := a[i+1];\n }\n Conteudo := a[0..cauda];\n }\n\n method contem(e: int) returns (r:bool)\n ensures r <==> exists i :: 0 <= i < cauda && e == a[i]\n {\n var i := 0;\n r:= false;\n\n while i < cauda\n invariant 0 <= i <= cauda\n invariant forall j: nat :: j < i ==> a[j] != e\n {\n if (a[i] == e) {\n r:= true;\n return;\n }\n\n i := i + 1;\n }\n\n return r;\n }\n\n method concat(f2: Fila) returns (r: Fila)\n requires Valid()\n requires f2.Valid()\n ensures r.Conteudo == Conteudo + f2.Conteudo\n {\n r := new Fila();\n\n var i:= 0;\n\n while i < cauda\n invariant 0 <= i <= cauda\n invariant 0 <= i <= r.cauda\n invariant r.cauda <= r.a.Length\n invariant fresh(r.Repr)\n invariant r.Valid()\n invariant r.Conteudo == Conteudo[0..i]\n {\n var valor := a[i];\n r.enfileira(valor);\n i := i + 1;\n }\n\n var j := 0;\n while j < f2.cauda\n invariant 0 <= j <= f2.cauda\n invariant 0 <= j <= r.cauda\n invariant r.cauda <= r.a.Length\n invariant fresh(r.Repr)\n invariant r.Valid()\n invariant r.Conteudo == Conteudo + f2.Conteudo[0..j]\n {\n var valor := f2.a[j];\n r.enfileira(valor);\n j := j + 1;\n }\n }\n}\n\nmethod Main()\n{\n var fila := new Fila();\n\n // enfileira deve alocar mais espa\u00e7o\n fila.enfileira(1);\n fila.enfileira(2);\n fila.enfileira(3);\n fila.enfileira(4);\n assert fila.Conteudo == [1, 2, 3, 4];\n\n // tamanho\n var q := fila.tamanho();\n assert q == 4;\n\n // desenfileira\n var e := fila.desenfileira();\n assert e == 1;\n assert fila.Conteudo == [2, 3, 4];\n assert fila.tamanho() == 3;\n\n // contem\n assert fila.Conteudo == [2, 3, 4];\n var r := fila.contem(1);\n assert r == false;\n assert fila.a[0] == 2;\n var r2 := fila.contem(2);\n assert r2 == true;\n\n // estaVazia\n var vazia := fila.estaVazia();\n assert vazia == false;\n var outraFila := new Fila();\n vazia := outraFila.estaVazia();\n assert vazia == true;\n\n // concat\n assert fila.Conteudo == [2, 3, 4];\n outraFila.enfileira(5);\n outraFila.enfileira(6);\n outraFila.enfileira(7);\n assert outraFila.Conteudo == [5, 6, 7];\n var concatenada := fila.concat(outraFila);\n assert concatenada.Conteudo == [2,3,4,5,6,7];\n}\n", "hints_removed": " /*\n OK fila de tamanho ilimitado com arrays circulares\n OK representa\u00e7\u00e3o ghost: cole\u00e7\u00e3o de elementos da fila e qualquer outra informa\u00e7\u00e3o necess\u00e1ria\n OK predicate: invariante da representa\u00e7\u00e3o abstrata associada \u00e0 cole\u00e7\u00e3o do tipo fila\n\n Opera\u00e7\u00f5es\n - OK construtor inicia fila fazia\n - OK adicionar novo elemento na fila -> enfileira()\n - OK remover um elemento da fila e retornar seu valor caso a fila contenha elementos -> desenfileira()\n - OK verificar se um elemento pertence a fila -> contem()\n - OK retornar numero de elementos da fila -> tamanho()\n - OK verificar se a fila \u00e9 vazia ou n\u00e3o -> estaVazia()\n - OK concatenar duas filas retornando uma nova fila sem alterar nenhuma das outras -> concat()\n\n OK criar m\u00e9todo main testando a implementa\u00e7\u00e3o \n OK transformar uso de naturais para inteiros\n*/\n\nclass {:autocontracts} Fila\n {\n var a: array;\n var cauda: nat;\n const defaultSize: nat;\n\n ghost var Conteudo: seq;\n\n // invariante\n ghost predicate Valid() {\n defaultSize > 0\n && a.Length >= defaultSize\n && 0 <= cauda <= a.Length\n && Conteudo == a[0..cauda]\n }\n\n // inicia fila com 3 elementos\n constructor ()\n ensures Conteudo == []\n ensures defaultSize == 3\n ensures a.Length == 3\n ensures fresh(a)\n {\n defaultSize := 3;\n a := new int[3];\n cauda := 0;\n Conteudo := [];\n }\n\n function tamanho():nat\n ensures tamanho() == |Conteudo|\n {\n cauda\n }\n\n function estaVazia(): bool\n ensures estaVazia() <==> |Conteudo| == 0\n {\n cauda == 0\n }\n\n method enfileira(e:int)\n ensures Conteudo == old(Conteudo) + [e]\n {\n\n if (cauda == a.Length) {\n var novoArray := new int[cauda + defaultSize];\n var i := 0;\n\n forall i | 0 <= i < a.Length\n {\n novoArray[i] := a[i];\n }\n a := novoArray;\n }\n\n a[cauda] := e;\n cauda := cauda + 1;\n Conteudo := Conteudo + [e];\n }\n\n method desenfileira() returns (e:int)\n requires |Conteudo| > 0\n ensures e == old(Conteudo)[0]\n ensures Conteudo == old(Conteudo)[1..]\n {\n e := a[0];\n cauda := cauda - 1;\n forall i | 0 <= i < cauda\n {\n a[i] := a[i+1];\n }\n Conteudo := a[0..cauda];\n }\n\n method contem(e: int) returns (r:bool)\n ensures r <==> exists i :: 0 <= i < cauda && e == a[i]\n {\n var i := 0;\n r:= false;\n\n while i < cauda\n {\n if (a[i] == e) {\n r:= true;\n return;\n }\n\n i := i + 1;\n }\n\n return r;\n }\n\n method concat(f2: Fila) returns (r: Fila)\n requires Valid()\n requires f2.Valid()\n ensures r.Conteudo == Conteudo + f2.Conteudo\n {\n r := new Fila();\n\n var i:= 0;\n\n while i < cauda\n {\n var valor := a[i];\n r.enfileira(valor);\n i := i + 1;\n }\n\n var j := 0;\n while j < f2.cauda\n {\n var valor := f2.a[j];\n r.enfileira(valor);\n j := j + 1;\n }\n }\n}\n\nmethod Main()\n{\n var fila := new Fila();\n\n // enfileira deve alocar mais espa\u00e7o\n fila.enfileira(1);\n fila.enfileira(2);\n fila.enfileira(3);\n fila.enfileira(4);\n\n // tamanho\n var q := fila.tamanho();\n\n // desenfileira\n var e := fila.desenfileira();\n\n // contem\n var r := fila.contem(1);\n var r2 := fila.contem(2);\n\n // estaVazia\n var vazia := fila.estaVazia();\n var outraFila := new Fila();\n vazia := outraFila.estaVazia();\n\n // concat\n outraFila.enfileira(5);\n outraFila.enfileira(6);\n outraFila.enfileira(7);\n var concatenada := fila.concat(outraFila);\n}\n" }, { "test_ID": "737", "test_file": "repo-8967-Ironclad_tmp_tmp4q25en_1_ironclad-apps_src_Dafny_Libraries_Util_seqs_simple.dfy", "ground_truth": "static lemma lemma_vacuous_statement_about_a_sequence(intseq:seq, j:int)\n requires 0<=j<|intseq|;\n ensures intseq[0..j]==intseq[..j];\n{\n}\n\nstatic lemma lemma_painful_statement_about_a_sequence(intseq:seq)\n ensures intseq==intseq[..|intseq|];\n{\n}\n\nstatic lemma lemma_obvious_statement_about_a_sequence(boolseq:seq, j:int)\n requires 0<=j<|boolseq|-1;\n ensures boolseq[1..][j] == boolseq[j+1];\n{\n}\n\nstatic lemma lemma_obvious_statement_about_a_sequence_int(intseq:seq, j:int)\n requires 0<=j<|intseq|-1;\n ensures intseq[1..][j] == intseq[j+1];\n{\n}\n\nstatic lemma lemma_straightforward_statement_about_a_sequence(intseq:seq, j:int)\n requires 0<=j<|intseq|;\n ensures intseq[..j] + intseq[j..] == intseq;\n{\n}\n\nstatic lemma lemma_sequence_reduction(s:seq, b:nat)\n requires 0, b:seq, c:seq)\n ensures (a+b)+c == a+(b+c);\n{\n}\n\n\nstatic lemma lemma_subseq_concatenation(s: seq, left: int, middle: int, right: int)\n requires 0 <= left <= middle <= right <= |s|;\n ensures s[left..right] == s[left..middle] + s[middle..right];\n{\n}\n\nstatic lemma lemma_seq_equality(a:seq, b:seq, len:int)\n requires |a| == |b| == len;\n requires forall i {:trigger a[i]}{:trigger b[i]} :: 0 <= i < len ==> a[i] == b[i];\n ensures a == b;\n{\n assert forall i :: 0 <= i < len ==> a[i] == b[i];\n}\n\nstatic lemma lemma_seq_suffix(s: seq, prefix_length: int, index: int)\n requires 0 <= prefix_length <= index < |s|;\n ensures s[index] == s[prefix_length..][index - prefix_length];\n{\n}\n\n", "hints_removed": "static lemma lemma_vacuous_statement_about_a_sequence(intseq:seq, j:int)\n requires 0<=j<|intseq|;\n ensures intseq[0..j]==intseq[..j];\n{\n}\n\nstatic lemma lemma_painful_statement_about_a_sequence(intseq:seq)\n ensures intseq==intseq[..|intseq|];\n{\n}\n\nstatic lemma lemma_obvious_statement_about_a_sequence(boolseq:seq, j:int)\n requires 0<=j<|boolseq|-1;\n ensures boolseq[1..][j] == boolseq[j+1];\n{\n}\n\nstatic lemma lemma_obvious_statement_about_a_sequence_int(intseq:seq, j:int)\n requires 0<=j<|intseq|-1;\n ensures intseq[1..][j] == intseq[j+1];\n{\n}\n\nstatic lemma lemma_straightforward_statement_about_a_sequence(intseq:seq, j:int)\n requires 0<=j<|intseq|;\n ensures intseq[..j] + intseq[j..] == intseq;\n{\n}\n\nstatic lemma lemma_sequence_reduction(s:seq, b:nat)\n requires 0, b:seq, c:seq)\n ensures (a+b)+c == a+(b+c);\n{\n}\n\n\nstatic lemma lemma_subseq_concatenation(s: seq, left: int, middle: int, right: int)\n requires 0 <= left <= middle <= right <= |s|;\n ensures s[left..right] == s[left..middle] + s[middle..right];\n{\n}\n\nstatic lemma lemma_seq_equality(a:seq, b:seq, len:int)\n requires |a| == |b| == len;\n requires forall i {:trigger a[i]}{:trigger b[i]} :: 0 <= i < len ==> a[i] == b[i];\n ensures a == b;\n{\n}\n\nstatic lemma lemma_seq_suffix(s: seq, prefix_length: int, index: int)\n requires 0 <= prefix_length <= index < |s|;\n ensures s[index] == s[prefix_length..][index - prefix_length];\n{\n}\n\n" }, { "test_ID": "738", "test_file": "sat_dfy_tmp_tmpfcyj8am9_dfy_Seq.dfy", "ground_truth": "module Seq {\n function seq_sum(s: seq) : (sum: int)\n {\n if s == [] then\n 0\n else\n var x := s[0];\n var remaining := s[1..];\n x + seq_sum(remaining)\n }\n\n lemma SeqPartsSameSum(s: seq, s1: seq, s2: seq)\n requires s == s1 + s2\n ensures seq_sum(s) == seq_sum(s1) + seq_sum(s2)\n {\n if s == [] {\n assert s1 == [];\n assert s2 == [];\n } else if s1 == [] {\n assert s2 == s;\n } else {\n var x := s1[0];\n var s1' := s1[1..];\n assert s == [x] + s1' + s2;\n SeqPartsSameSum(s[1..], s1[1..], s2);\n }\n }\n\n lemma DifferentPermutationSameSum(s1: seq, s2: seq)\n requires multiset(s1) == multiset(s2)\n ensures seq_sum(s1) == seq_sum(s2)\n {\n if s1 == [] {\n assert s2 == [];\n } else {\n var x :| x in s1;\n assert x in s1;\n assert multiset(s1)[x] > 0;\n assert multiset(s2)[x] > 0;\n assert x in s2;\n var i1, i2 :| 0 <= i1 < |s1| && 0 <= i2 < |s2| && s1[i1] == s2[i2] && s1[i1] == x;\n\n var remaining1 := s1[..i1] + s1[i1+1..];\n assert s1 == s1[..i1] + s1[i1..];\n assert s1 == s1[..i1] + [x] + s1[i1+1..];\n assert seq_sum(s1) == seq_sum(s1[..i1] + [x] + s1[i1+1..]);\n SeqPartsSameSum(s1[..i1+1], s1[..i1], [x]);\n SeqPartsSameSum(s1, s1[..i1+1], s1[i1+1..]);\n assert seq_sum(s1) == seq_sum(s1[..i1]) + x + seq_sum(s1[i1+1..]);\n SeqPartsSameSum(remaining1, s1[..i1], s1[i1+1..]);\n assert multiset(s1) == multiset(remaining1 + [x]);\n assert seq_sum(s1) == seq_sum(remaining1) + x;\n assert multiset(s1) == multiset(remaining1) + multiset([x]);\n assert multiset(s1) - multiset([x]) == multiset(remaining1);\n\n var remaining2 := s2[..i2] + s2[i2+1..];\n assert s2 == s2[..i2] + s2[i2..];\n assert s2 == s2[..i2] + [x] + s2[i2+1..];\n assert seq_sum(s2) == seq_sum(s2[..i2] + [x] + s2[i2+1..]);\n SeqPartsSameSum(s2[..i2+1], s2[..i2], [x]);\n SeqPartsSameSum(s2, s2[..i2+1], s2[i2+1..]);\n assert seq_sum(s2) == seq_sum(s2[..i2]) + x + seq_sum(s2[i2+1..]);\n SeqPartsSameSum(remaining2, s2[..i2], s2[i2+1..]);\n assert multiset(s2) == multiset(remaining2 + [x]);\n assert seq_sum(s2) == seq_sum(remaining2) + x;\n assert multiset(s2) == multiset(remaining2) + multiset([x]);\n assert multiset(s2) - multiset([x]) == multiset(remaining2);\n\n DifferentPermutationSameSum(remaining1, remaining2);\n assert seq_sum(remaining1) == seq_sum(remaining2);\n assert seq_sum(s1) == seq_sum(s2);\n }\n }\n\n}\n", "hints_removed": "module Seq {\n function seq_sum(s: seq) : (sum: int)\n {\n if s == [] then\n 0\n else\n var x := s[0];\n var remaining := s[1..];\n x + seq_sum(remaining)\n }\n\n lemma SeqPartsSameSum(s: seq, s1: seq, s2: seq)\n requires s == s1 + s2\n ensures seq_sum(s) == seq_sum(s1) + seq_sum(s2)\n {\n if s == [] {\n } else if s1 == [] {\n } else {\n var x := s1[0];\n var s1' := s1[1..];\n SeqPartsSameSum(s[1..], s1[1..], s2);\n }\n }\n\n lemma DifferentPermutationSameSum(s1: seq, s2: seq)\n requires multiset(s1) == multiset(s2)\n ensures seq_sum(s1) == seq_sum(s2)\n {\n if s1 == [] {\n } else {\n var x :| x in s1;\n var i1, i2 :| 0 <= i1 < |s1| && 0 <= i2 < |s2| && s1[i1] == s2[i2] && s1[i1] == x;\n\n var remaining1 := s1[..i1] + s1[i1+1..];\n SeqPartsSameSum(s1[..i1+1], s1[..i1], [x]);\n SeqPartsSameSum(s1, s1[..i1+1], s1[i1+1..]);\n SeqPartsSameSum(remaining1, s1[..i1], s1[i1+1..]);\n\n var remaining2 := s2[..i2] + s2[i2+1..];\n SeqPartsSameSum(s2[..i2+1], s2[..i2], [x]);\n SeqPartsSameSum(s2, s2[..i2+1], s2[i2+1..]);\n SeqPartsSameSum(remaining2, s2[..i2], s2[i2+1..]);\n\n DifferentPermutationSameSum(remaining1, remaining2);\n }\n }\n\n}\n" }, { "test_ID": "739", "test_file": "se2011_tmp_tmp71eb82zt_ass1_ex4.dfy", "ground_truth": "method Eval(x:int) returns (r:int)\t\t// do not change\nrequires x >= 0\nensures r == x*x\n{ \t\t\t\t\t\t\t\t\t\t// do not change\nvar y:int := x; \t\t\t\t\t\t// do not change\nvar z:int := 0; \t\t\t\t\t\t// do not change\nwhile y>0 \t\t\t\t\t\t\t\t// do not change\ninvariant 0 <= y <= x && z == x*(x-y)\ndecreases y\n{ \t\t\t\t\t\t\t\t\t\t// do not change\nz := z + x; \t\t\t\t\t\t\t// do not change\ny := y - 1; \t\t\t\t\t\t\t// do not change\n} \t\t\t\t\t\t\t\t\t\t// do not change\nreturn z; \t\t\t\t\t\t\t\t// do not change\n} \t\t\t\t\t\t\t\t\t\t// do not change\n\n", "hints_removed": "method Eval(x:int) returns (r:int)\t\t// do not change\nrequires x >= 0\nensures r == x*x\n{ \t\t\t\t\t\t\t\t\t\t// do not change\nvar y:int := x; \t\t\t\t\t\t// do not change\nvar z:int := 0; \t\t\t\t\t\t// do not change\nwhile y>0 \t\t\t\t\t\t\t\t// do not change\n{ \t\t\t\t\t\t\t\t\t\t// do not change\nz := z + x; \t\t\t\t\t\t\t// do not change\ny := y - 1; \t\t\t\t\t\t\t// do not change\n} \t\t\t\t\t\t\t\t\t\t// do not change\nreturn z; \t\t\t\t\t\t\t\t// do not change\n} \t\t\t\t\t\t\t\t\t\t// do not change\n\n" }, { "test_ID": "740", "test_file": "se2011_tmp_tmp71eb82zt_ass1_ex6.dfy", "ground_truth": "method Ceiling7(n:nat) returns (k:nat)\nrequires n >= 0\nensures k == n-(n%7)\n{\n\tk := n-(n%7);\n}\n\nmethod test7() {\n\tvar k: nat;\n\tk := Ceiling7(43);\n\tassert k == 42; \n\tk := Ceiling7(6);\n\tassert k == 0; \n\tk := Ceiling7(1000);\n\tassert k == 994; \n\tk := Ceiling7(7);\n\tassert k == 7; \n\tk := Ceiling7(70);\n\tassert k == 70; \n}\n\n", "hints_removed": "method Ceiling7(n:nat) returns (k:nat)\nrequires n >= 0\nensures k == n-(n%7)\n{\n\tk := n-(n%7);\n}\n\nmethod test7() {\n\tvar k: nat;\n\tk := Ceiling7(43);\n\tk := Ceiling7(6);\n\tk := Ceiling7(1000);\n\tk := Ceiling7(7);\n\tk := Ceiling7(70);\n}\n\n" }, { "test_ID": "741", "test_file": "se2011_tmp_tmp71eb82zt_ass2_ex2.dfy", "ground_truth": "// ex2\n\n// this was me playing around to try and get an ensures for the method \n/*predicate method check(a: array, seclar:int)\nrequires a.Length > 0\nreads a\n{ ensures exists i :: 0 <= i < a.Length && forall j :: (0 <= j < a.Length && j != i) ==> (a[i] >= a[j]) && (seclar <= a[i]) && ( if a[j] != a[i] then seclar >= a[j] else seclar <= a[j]) } */\n\nmethod SecondLargest(a:array) returns (seclar:int)\nrequires a.Length > 0\n//ensures exists i :: 0 <= i < a.Length && forall j :: (0 <= j < a.Length && j != i) ==> (a[i] >= a[j]) && (seclar <= a[i]) && ( if a[j] != a[i] then seclar >= a[j] else seclar <= a[j])\n{\n\t// if length = 1, return first element\n\tif a.Length == 1\n\t{ seclar := a[0]; }\n\telse \n\t{\n\t\tvar l, s, i: int := 0, 0, 0;\n\n\t\t// set initial largest and second largest\n\t\tif a[1] > a[0]\n\t\t{ l := a[1]; s := a[0]; }\n\t\telse \n\t\t{ l := a[0]; s := a[1]; }\n\n\t\twhile i < a.Length\n\t\tinvariant 0 <= i <= a.Length\n\t\tinvariant forall j :: (0 <= j < i) ==> l >= a[j]\n\t\tinvariant s <= l\n\t\t{\n\t\t\tif a[i] > l\t\t\t\t\t\t// check if curr is greater then largest and set l and s\n\t\t\t{ s := l; l := a[i]; }\n\t\t\tif a[i] > s && a[i] < l\t\t\t// check if curr is greater than s and set s\n\t\t\t{ s := a[i]; }\n\t\t\tif s == l && s > a[i]\t\t\t// check s is not the same as l\n\t\t\t{ s := a[i]; }\n\t\t\ti := i+1;\n\t\t}\n\t\tseclar := s;\n\t}\n}\n\nmethod Main()\n{\n\tvar a: array := new int[][1];\n\tassert a[0] == 1;\n\tvar x:int := SecondLargest(a);\n//\tassert x == 1;\n\n\tvar b: array := new int[][9,1];\n\tassert b[0] == 9 && b[1] == 1;\n\tx := SecondLargest(b);\n//\tassert x == 1;\n\t\n\tvar c: array := new int[][1,9];\n\tassert c[0] == 1 && c[1] == 9;\n\tx := SecondLargest(c);\n//\tassert x == 1;\n\n\tvar d: array := new int[][2,42,-4,123,42];\n\tassert d[0] == 2 && d[1] == 42 && d[2] == -4 && d[3] == 123 && d[4] == 42;\n\tx := SecondLargest(d);\n//\tassert x == 42;\n\n\tvar e: array := new int[][1,9,8];\n\tassert e[0] == 1 && e[1] == 9 && e[2] == 8;\n\tx := SecondLargest(e);\n//\tassert x == 8;\n}\n\n", "hints_removed": "// ex2\n\n// this was me playing around to try and get an ensures for the method \n/*predicate method check(a: array, seclar:int)\nrequires a.Length > 0\nreads a\n{ ensures exists i :: 0 <= i < a.Length && forall j :: (0 <= j < a.Length && j != i) ==> (a[i] >= a[j]) && (seclar <= a[i]) && ( if a[j] != a[i] then seclar >= a[j] else seclar <= a[j]) } */\n\nmethod SecondLargest(a:array) returns (seclar:int)\nrequires a.Length > 0\n//ensures exists i :: 0 <= i < a.Length && forall j :: (0 <= j < a.Length && j != i) ==> (a[i] >= a[j]) && (seclar <= a[i]) && ( if a[j] != a[i] then seclar >= a[j] else seclar <= a[j])\n{\n\t// if length = 1, return first element\n\tif a.Length == 1\n\t{ seclar := a[0]; }\n\telse \n\t{\n\t\tvar l, s, i: int := 0, 0, 0;\n\n\t\t// set initial largest and second largest\n\t\tif a[1] > a[0]\n\t\t{ l := a[1]; s := a[0]; }\n\t\telse \n\t\t{ l := a[0]; s := a[1]; }\n\n\t\twhile i < a.Length\n\t\t{\n\t\t\tif a[i] > l\t\t\t\t\t\t// check if curr is greater then largest and set l and s\n\t\t\t{ s := l; l := a[i]; }\n\t\t\tif a[i] > s && a[i] < l\t\t\t// check if curr is greater than s and set s\n\t\t\t{ s := a[i]; }\n\t\t\tif s == l && s > a[i]\t\t\t// check s is not the same as l\n\t\t\t{ s := a[i]; }\n\t\t\ti := i+1;\n\t\t}\n\t\tseclar := s;\n\t}\n}\n\nmethod Main()\n{\n\tvar a: array := new int[][1];\n\tvar x:int := SecondLargest(a);\n//\tassert x == 1;\n\n\tvar b: array := new int[][9,1];\n\tx := SecondLargest(b);\n//\tassert x == 1;\n\t\n\tvar c: array := new int[][1,9];\n\tx := SecondLargest(c);\n//\tassert x == 1;\n\n\tvar d: array := new int[][2,42,-4,123,42];\n\tx := SecondLargest(d);\n//\tassert x == 42;\n\n\tvar e: array := new int[][1,9,8];\n\tx := SecondLargest(e);\n//\tassert x == 8;\n}\n\n" }, { "test_ID": "742", "test_file": "software-specification-p1_tmp_tmpz9x6mpxb_BoilerPlate_Ex1.dfy", "ground_truth": "datatype Tree = Leaf(V) | SingleNode(V, Tree) | DoubleNode(V, Tree, Tree)\n\ndatatype Code = CLf(V) | CSNd(V) | CDNd(V)\n\nfunction serialise(t : Tree) : seq> \n decreases t \n{\n match t {\n case Leaf(v) => [ CLf(v) ]\n case SingleNode(v, t) => serialise(t) + [ CSNd(v) ]\n case DoubleNode(v, t1, t2) => serialise(t2) + serialise(t1) + [ CDNd(v) ]\n }\n}\n\n// Ex 1\nfunction deserialiseAux(codes: seq>, trees: seq>): seq>\n requires |codes| > 0 || |trees| > 0\n ensures |deserialiseAux(codes, trees)| >= 0\n decreases codes\n{\n if |codes| == 0 then trees\n else\n match codes[0] {\n case CLf(v) => deserialiseAux(codes[1..], trees + [Leaf(v)])\n case CSNd(v) => if (|trees| >= 1) then deserialiseAux(codes[1..], trees[..|trees|-1] + [SingleNode(v, trees[|trees|-1])]) else trees\n case CDNd(v) => if (|trees| >= 2) then deserialiseAux(codes[1..], trees[..|trees|-2] + [DoubleNode(v, trees[|trees|-1], trees[|trees|-2])]) else trees\n }\n}\n\nfunction deserialise(s:seq>):seq>\n requires |s| > 0\n{\n deserialiseAux(s, [])\n}\n\n// Ex 2\nmethod testSerializeWithASingleLeaf()\n{\n var tree := Leaf(42);\n var result := serialise(tree);\n assert result == [CLf(42)];\n}\n\nmethod testSerializeNullValues()\n{\n var tree := Leaf(null);\n var result := serialise(tree);\n assert result == [CLf(null)];\n}\n\nmethod testSerializeWithAllElements()\n{\n var tree: Tree := DoubleNode(9, Leaf(6), DoubleNode(2, Leaf(5), SingleNode(4, Leaf(3))));\n var codes := serialise(tree);\n assert |codes| == 6;\n var expectedCodes := [CLf(3), CSNd(4), CLf(5), CDNd(2), CLf(6), CDNd(9)];\n assert codes == expectedCodes;\n}\n\n// Ex 3 \n\nmethod testDeseraliseWithASingleLeaf() {\n var codes: seq> := [CLf(9)];\n var trees := deserialise(codes);\n assert |trees| == 1;\n var expectedTree := Leaf(9);\n assert trees[0] == expectedTree;\n}\n\nmethod testDeserializeWithASingleNode()\n{\n var codes: seq> := [CLf(3), CSNd(9), CLf(5)];\n var trees := deserialise(codes);\n assert |trees| == 2;\n var expectedTree1 := SingleNode(9, Leaf(3));\n var expectedTree2 := Leaf(5);\n assert trees[0] == expectedTree1;\n assert trees[1] == expectedTree2;\n}\n\nmethod testDeserialiseWithAllElements()\n{\n var codes: seq> := [CLf(3), CSNd(4), CLf(5), CDNd(2), CLf(6), CDNd(9)];\n var trees := deserialise(codes);\n assert |trees| == 1; \n var expectedTree := DoubleNode(9, Leaf(6), DoubleNode(2, Leaf(5), SingleNode(4, Leaf(3))));\n assert trees[0] == expectedTree;\n}\n\n// Ex 4 \nlemma SerialiseLemma(t: Tree)\n ensures deserialise(serialise(t)) == [t]\n{\n assert serialise(t) + [] == serialise(t);\n\n calc{\n deserialise(serialise(t));\n ==\n deserialise(serialise(t) + []);\n ==\n deserialiseAux(serialise(t) + [], []);\n == { DeserialisetAfterSerialiseLemma(t, [], []); }\n deserialiseAux([],[] + [t]);\n ==\n deserialiseAux([],[t]);\n == \n [t];\n }\n}\n\n\nlemma DeserialisetAfterSerialiseLemma (t : Tree, cds : seq>, ts : seq>) \n ensures deserialiseAux(serialise(t) + cds, ts) == deserialiseAux(cds, ts + [t])\n {\n match t{\n case Leaf(x) =>\n calc{\n deserialiseAux(serialise(t) + cds, ts);\n ==\n deserialiseAux([CLf(x)] + cds, ts);\n == \n deserialiseAux(cds, ts + [Leaf(x)]);\n == \n deserialiseAux(cds, ts + [t]);\n }\n case SingleNode(x,t1) =>\n assert serialise(t1) + [ CSNd(x) ] + cds == serialise(t1) + ([ CSNd(x) ] + cds);\n calc{\n deserialiseAux(serialise(t) + cds, ts);\n ==\n deserialiseAux( serialise(t1) + [CSNd(x)] + cds ,ts); \n ==\n deserialiseAux((serialise(t1) + [CSNd(x)] + cds),ts);\n == { DeserialisetAfterSerialiseLemma(t1 , [ CSNd(x) ], ts); }\n deserialiseAux(serialise(t1)+ [CSNd(x)] + cds, ts );\n ==\n deserialiseAux( ([CSNd(x)] + cds), ts + [ t1 ]);\n == \n deserialiseAux(cds, ts + [SingleNode(x,t1)]);\n == \n deserialiseAux(cds, ts + [t]); \n }\n case DoubleNode(x,t1,t2) =>\n assert serialise(t2) + serialise(t1) + [ CDNd(x) ] + cds == serialise(t2) + (serialise(t1) + [ CDNd(x) ] + cds);\n assert serialise(t1) + [CDNd(x)] + cds == serialise(t1) + ([CDNd(x)] + cds); \n assert (ts + [ t2 ]) + [ t1 ] == ts + [t2,t1];\n calc{\n deserialiseAux(serialise(t) + cds, ts);\n ==\n deserialiseAux(serialise(t2) + serialise(t1) + [CDNd(x)] + cds ,ts); \n ==\n deserialiseAux(serialise(t2) + (serialise(t1) + [CDNd(x)] + cds),ts);\n == { DeserialisetAfterSerialiseLemma(t2, serialise(t1) + [ CDNd(x) ], ts); }\n deserialiseAux(serialise(t1)+ [CDNd(x)] + cds, ts + [ t2 ]);\n ==\n deserialiseAux(serialise(t1) + ([CDNd(x)] + cds), ts + [ t2 ]);\n == { DeserialisetAfterSerialiseLemma(t1, [ CDNd(x) ] + cds, ts + [ t2 ]); }\n deserialiseAux([ CDNd(x) ] + cds, (ts + [ t2 ]) + [t1]);\n ==\n deserialiseAux([ CDNd(x) ] + cds, ts + [t2, t1]);\n == \n deserialiseAux([CDNd(x)] + cds, ts + [t2 , t1]);\n == \n deserialiseAux(cds, ts + [DoubleNode(x,t1,t2)]); \n == \n deserialiseAux(cds, ts + [t]);\n }\n }\n }\n\n", "hints_removed": "datatype Tree = Leaf(V) | SingleNode(V, Tree) | DoubleNode(V, Tree, Tree)\n\ndatatype Code = CLf(V) | CSNd(V) | CDNd(V)\n\nfunction serialise(t : Tree) : seq> \n{\n match t {\n case Leaf(v) => [ CLf(v) ]\n case SingleNode(v, t) => serialise(t) + [ CSNd(v) ]\n case DoubleNode(v, t1, t2) => serialise(t2) + serialise(t1) + [ CDNd(v) ]\n }\n}\n\n// Ex 1\nfunction deserialiseAux(codes: seq>, trees: seq>): seq>\n requires |codes| > 0 || |trees| > 0\n ensures |deserialiseAux(codes, trees)| >= 0\n{\n if |codes| == 0 then trees\n else\n match codes[0] {\n case CLf(v) => deserialiseAux(codes[1..], trees + [Leaf(v)])\n case CSNd(v) => if (|trees| >= 1) then deserialiseAux(codes[1..], trees[..|trees|-1] + [SingleNode(v, trees[|trees|-1])]) else trees\n case CDNd(v) => if (|trees| >= 2) then deserialiseAux(codes[1..], trees[..|trees|-2] + [DoubleNode(v, trees[|trees|-1], trees[|trees|-2])]) else trees\n }\n}\n\nfunction deserialise(s:seq>):seq>\n requires |s| > 0\n{\n deserialiseAux(s, [])\n}\n\n// Ex 2\nmethod testSerializeWithASingleLeaf()\n{\n var tree := Leaf(42);\n var result := serialise(tree);\n}\n\nmethod testSerializeNullValues()\n{\n var tree := Leaf(null);\n var result := serialise(tree);\n}\n\nmethod testSerializeWithAllElements()\n{\n var tree: Tree := DoubleNode(9, Leaf(6), DoubleNode(2, Leaf(5), SingleNode(4, Leaf(3))));\n var codes := serialise(tree);\n var expectedCodes := [CLf(3), CSNd(4), CLf(5), CDNd(2), CLf(6), CDNd(9)];\n}\n\n// Ex 3 \n\nmethod testDeseraliseWithASingleLeaf() {\n var codes: seq> := [CLf(9)];\n var trees := deserialise(codes);\n var expectedTree := Leaf(9);\n}\n\nmethod testDeserializeWithASingleNode()\n{\n var codes: seq> := [CLf(3), CSNd(9), CLf(5)];\n var trees := deserialise(codes);\n var expectedTree1 := SingleNode(9, Leaf(3));\n var expectedTree2 := Leaf(5);\n}\n\nmethod testDeserialiseWithAllElements()\n{\n var codes: seq> := [CLf(3), CSNd(4), CLf(5), CDNd(2), CLf(6), CDNd(9)];\n var trees := deserialise(codes);\n var expectedTree := DoubleNode(9, Leaf(6), DoubleNode(2, Leaf(5), SingleNode(4, Leaf(3))));\n}\n\n// Ex 4 \nlemma SerialiseLemma(t: Tree)\n ensures deserialise(serialise(t)) == [t]\n{\n\n calc{\n deserialise(serialise(t));\n ==\n deserialise(serialise(t) + []);\n ==\n deserialiseAux(serialise(t) + [], []);\n == { DeserialisetAfterSerialiseLemma(t, [], []); }\n deserialiseAux([],[] + [t]);\n ==\n deserialiseAux([],[t]);\n == \n [t];\n }\n}\n\n\nlemma DeserialisetAfterSerialiseLemma (t : Tree, cds : seq>, ts : seq>) \n ensures deserialiseAux(serialise(t) + cds, ts) == deserialiseAux(cds, ts + [t])\n {\n match t{\n case Leaf(x) =>\n calc{\n deserialiseAux(serialise(t) + cds, ts);\n ==\n deserialiseAux([CLf(x)] + cds, ts);\n == \n deserialiseAux(cds, ts + [Leaf(x)]);\n == \n deserialiseAux(cds, ts + [t]);\n }\n case SingleNode(x,t1) =>\n calc{\n deserialiseAux(serialise(t) + cds, ts);\n ==\n deserialiseAux( serialise(t1) + [CSNd(x)] + cds ,ts); \n ==\n deserialiseAux((serialise(t1) + [CSNd(x)] + cds),ts);\n == { DeserialisetAfterSerialiseLemma(t1 , [ CSNd(x) ], ts); }\n deserialiseAux(serialise(t1)+ [CSNd(x)] + cds, ts );\n ==\n deserialiseAux( ([CSNd(x)] + cds), ts + [ t1 ]);\n == \n deserialiseAux(cds, ts + [SingleNode(x,t1)]);\n == \n deserialiseAux(cds, ts + [t]); \n }\n case DoubleNode(x,t1,t2) =>\n calc{\n deserialiseAux(serialise(t) + cds, ts);\n ==\n deserialiseAux(serialise(t2) + serialise(t1) + [CDNd(x)] + cds ,ts); \n ==\n deserialiseAux(serialise(t2) + (serialise(t1) + [CDNd(x)] + cds),ts);\n == { DeserialisetAfterSerialiseLemma(t2, serialise(t1) + [ CDNd(x) ], ts); }\n deserialiseAux(serialise(t1)+ [CDNd(x)] + cds, ts + [ t2 ]);\n ==\n deserialiseAux(serialise(t1) + ([CDNd(x)] + cds), ts + [ t2 ]);\n == { DeserialisetAfterSerialiseLemma(t1, [ CDNd(x) ] + cds, ts + [ t2 ]); }\n deserialiseAux([ CDNd(x) ] + cds, (ts + [ t2 ]) + [t1]);\n ==\n deserialiseAux([ CDNd(x) ] + cds, ts + [t2, t1]);\n == \n deserialiseAux([CDNd(x)] + cds, ts + [t2 , t1]);\n == \n deserialiseAux(cds, ts + [DoubleNode(x,t1,t2)]); \n == \n deserialiseAux(cds, ts + [t]);\n }\n }\n }\n\n" }, { "test_ID": "743", "test_file": "software_analysis_tmp_tmpmt6bo9sf_ss.dfy", "ground_truth": "method find_min_index(a : array, s: int, e: int) returns (min_i: int)\nrequires a.Length > 0\nrequires 0 <= s < a.Length\nrequires e <= a.Length\nrequires e > s\n\nensures min_i >= s \nensures min_i < e \nensures forall k: int :: s <= k < e ==> a[min_i] <= a[k]\n{\n min_i := s;\n var i : int := s; \n\n while i < e \n decreases e - i // loop variant\n invariant s <= i <= e\n invariant s <= min_i < e\n // unnecessary invariant\n // invariant i < e ==> min_i <= i \n invariant forall k: int :: s <= k < i ==> a[min_i] <= a[k]\n {\n if a[i] <= a[min_i] {\n min_i := i;\n }\n i := i + 1;\n }\n\n}\n\n\n\npredicate is_sorted(ss: seq)\n{\n forall i, j: int:: 0 <= i <= j < |ss| ==> ss[i] <= ss[j]\n}\n\npredicate is_permutation(a:seq, b:seq)\ndecreases |a|\ndecreases |b|\n{\n |a| == |b| && \n ((|a| == 0 && |b| == 0) || \n exists i,j : int :: 0<=i<|a| && 0<=j<|b| && a[i] == b[j] && is_permutation(a[0..i] + if i < |a| then a[i+1..] else [], b[0..j] + if j < |b| then b[j+1..] else []))\n}\n\n\n// predicate is_permutation(a:seq, b:seq)\n// decreases |a|\n// decreases |b|\n// {\n// |a| == |b| && ((|a| == 0 && |b| == 0) || exists i,j : int :: 0<=i<|a| && 0<=j<|b| && a[i] == b[j] && is_permutation(a[0..i] + a[i+1..], b[0..j] + b[j+1..]))\n// }\n\npredicate is_permutation2(a:seq, b:seq)\n{\n multiset(a) == multiset(b)\n}\n\n\n\nmethod selection_sort(ns: array) \nrequires ns.Length >= 0\nensures is_sorted(ns[..])\nensures is_permutation2(old(ns[..]), ns[..])\nmodifies ns\n{\n var i: int := 0;\n var l: int := ns.Length;\n while i < l\n decreases l - i\n invariant 0 <= i <= l\n invariant is_permutation2(old(ns[..]), ns[..])\n invariant forall k, kk: int :: 0 <= k < i && i <= kk < ns.Length ==> ns[k] <= ns[kk] // left els must be lesser than right ones\n invariant is_sorted(ns[..i])\n {\n var min_i: int := find_min_index(ns, i, ns.Length);\n ns[i], ns[min_i] := ns[min_i], ns[i];\n i := i + 1;\n }\n\n}\n", "hints_removed": "method find_min_index(a : array, s: int, e: int) returns (min_i: int)\nrequires a.Length > 0\nrequires 0 <= s < a.Length\nrequires e <= a.Length\nrequires e > s\n\nensures min_i >= s \nensures min_i < e \nensures forall k: int :: s <= k < e ==> a[min_i] <= a[k]\n{\n min_i := s;\n var i : int := s; \n\n while i < e \n // unnecessary invariant\n // invariant i < e ==> min_i <= i \n {\n if a[i] <= a[min_i] {\n min_i := i;\n }\n i := i + 1;\n }\n\n}\n\n\n\npredicate is_sorted(ss: seq)\n{\n forall i, j: int:: 0 <= i <= j < |ss| ==> ss[i] <= ss[j]\n}\n\npredicate is_permutation(a:seq, b:seq)\n{\n |a| == |b| && \n ((|a| == 0 && |b| == 0) || \n exists i,j : int :: 0<=i<|a| && 0<=j<|b| && a[i] == b[j] && is_permutation(a[0..i] + if i < |a| then a[i+1..] else [], b[0..j] + if j < |b| then b[j+1..] else []))\n}\n\n\n// predicate is_permutation(a:seq, b:seq)\n// decreases |a|\n// decreases |b|\n// {\n// |a| == |b| && ((|a| == 0 && |b| == 0) || exists i,j : int :: 0<=i<|a| && 0<=j<|b| && a[i] == b[j] && is_permutation(a[0..i] + a[i+1..], b[0..j] + b[j+1..]))\n// }\n\npredicate is_permutation2(a:seq, b:seq)\n{\n multiset(a) == multiset(b)\n}\n\n\n\nmethod selection_sort(ns: array) \nrequires ns.Length >= 0\nensures is_sorted(ns[..])\nensures is_permutation2(old(ns[..]), ns[..])\nmodifies ns\n{\n var i: int := 0;\n var l: int := ns.Length;\n while i < l\n {\n var min_i: int := find_min_index(ns, i, ns.Length);\n ns[i], ns[min_i] := ns[min_i], ns[i];\n i := i + 1;\n }\n\n}\n" }, { "test_ID": "744", "test_file": "specTesting_tmp_tmpueam35lx_examples_binary_search_binary_search_specs.dfy", "ground_truth": "lemma BinarySearch(intSeq:seq, key:int) returns (r:int)\n // original\n requires forall i,j | 0 <= i <= j < |intSeq| :: intSeq[i] <= intSeq[j]\n ensures r >= 0 ==> r < |intSeq| && intSeq[r] == key\n ensures r < 0 ==> forall i:nat | i < |intSeq| :: intSeq[i] != key\n{ \n var lo:nat := 0;\n var hi:nat := |intSeq|;\n while lo < hi\n invariant 0 <= lo <= hi <= |intSeq|\n invariant forall i:nat | 0 <= i < lo :: intSeq[i] < key\n invariant forall i:nat | hi <= i < |intSeq| :: intSeq[i] > key\n {\n var mid := (lo + hi) / 2;\n if (intSeq[mid] < key) {\n lo := mid + 1;\n } else if (intSeq[mid] > key) {\n hi := mid;\n } else {\n return mid;\n }\n }\n return -1;\n}\n\npredicate BinarySearchTransition(intSeq:seq, key:int, r:int)\n requires (forall i,j | 0 <= i <= j < |intSeq| :: intSeq[i] <= intSeq[j])\n{\n && (r >= 0 ==> r < |intSeq| && intSeq[r] == key)\n && (r < 0 ==> forall i:nat | i < |intSeq| :: intSeq[i] != key)\n}\n\nlemma BinarySearchDeterministic(intSeq:seq, key:int) returns (r:int)\n requires forall i,j | 0 <= i <= j < |intSeq| :: intSeq[i] <= intSeq[j]\n ensures r >= 0 ==> r < |intSeq| && intSeq[r] == key\n ensures r < 0 ==> forall i:nat | i < |intSeq| :: intSeq[i] != key\n\n // make it deterministic\n ensures r < 0 ==> r == -1 // return -1 if not found\n ensures r >= 0 ==> forall i:nat | i < r :: intSeq[i] < key // multiple matches return the first result\n\n{ \n var lo:nat := 0;\n var hi:nat := |intSeq|;\n while lo < hi\n invariant 0 <= lo <= hi <= |intSeq|\n invariant forall i:nat | 0 <= i < lo :: intSeq[i] < key\n invariant (forall i:nat | hi <= i < |intSeq| :: intSeq[i] > key)\n || (forall i:nat | hi <= i < |intSeq| :: intSeq[i] >= key && exists i:nat | lo <= i < hi :: intSeq[i] == key)\n {\n var mid := (lo + hi) / 2;\n if (intSeq[mid] < key) {\n lo := mid + 1;\n } else if (intSeq[mid] > key) {\n hi := mid;\n } else {\n assert intSeq[mid] == key;\n var inner_mid := (lo + mid) / 2;\n if (intSeq[inner_mid] < key) {\n lo := inner_mid + 1;\n } else if (hi != inner_mid + 1) {\n hi := inner_mid + 1;\n } else {\n if (intSeq[lo] == key) {\n return lo;\n } else {\n lo := lo + 1;\n }\n }\n }\n }\n return -1;\n}\n\npredicate BinarySearchDeterministicTransition(intSeq:seq, key:int, r:int)\n requires (forall i,j | 0 <= i <= j < |intSeq| :: intSeq[i] <= intSeq[j])\n{\n && (r >= 0 ==> r < |intSeq| && intSeq[r] == key)\n && (r < 0 ==> forall i:nat | i < |intSeq| :: intSeq[i] != key)\n\n // make it deterministic\n && (r < 0 ==> r == -1) // return -1 if not found\n && (r >= 0 ==> forall i:nat | i < r :: intSeq[i] < key)\n}\n\nlemma BinarySearchWrong1(intSeq:seq, key:int) returns (r:int)\n // first element\n requires forall i,j | 0 <= i <= j < |intSeq| :: intSeq[i] <= intSeq[j]\n ensures r >= 0 ==> r < |intSeq| && intSeq[r] == key\n ensures r < 0 ==> forall i:nat | 0 < i < |intSeq| :: intSeq[i] != key // i >= 0\n\n // make it deterministic\n ensures r < 0 ==> r == -1 // return -1 if not found\n ensures r >= 0 ==> forall i:nat | i < r :: intSeq[i] < key // multiple matches return the first result\n\npredicate BinarySearchWrong1Transition(intSeq:seq, key:int, r:int)\n requires forall i,j | 0 <= i <= j < |intSeq| :: intSeq[i] <= intSeq[j]\n{\n && (r >= 0 ==> r < |intSeq| && intSeq[r] == key)\n && (r < 0 ==> forall i:nat | 0 < i < |intSeq| :: intSeq[i] != key) // i >= 0\n\n // make it deterministic\n && (r < 0 ==> r == -1) // return -1 if not found\n && (r >= 0 ==> forall i:nat | i < r :: intSeq[i] < key)\n}\n\nlemma BinarySearchWrong2(intSeq:seq, key:int) returns (r:int)\n // last element\n requires forall i,j | 0 <= i <= j < |intSeq| :: intSeq[i] <= intSeq[j]\n ensures r >= 0 ==> r < |intSeq| && intSeq[r] == key\n ensures r < 0 ==> forall i:nat | 0 <= i < |intSeq| - 1 :: intSeq[i] != key // i < |intSeq|\n\n // make it deterministic\n ensures r < 0 ==> r == -1 // return -1 if not found\n ensures r >= 0 ==> forall i:nat | i < r :: intSeq[i] < key // multiple matches return the first result\n\npredicate BinarySearchWrong2Transition(intSeq:seq, key:int, r:int)\n requires forall i,j | 0 <= i <= j < |intSeq| :: intSeq[i] <= intSeq[j]\n{\n && (r >= 0 ==> r < |intSeq| && intSeq[r] == key)\n && (r < 0 ==> forall i:nat | 0 <= i < |intSeq| - 1 :: intSeq[i] != key) // i < |intSeq|\n\n // make it deterministic\n && (r < 0 ==> r == -1) // return -1 if not found\n && (r >= 0 ==> forall i:nat | i < r :: intSeq[i] < key)\n}\n\nlemma BinarySearchWrong3(intSeq:seq, key:int) returns (r:int)\n // weaker spec\n requires forall i,j | 0 <= i <= j < |intSeq| :: intSeq[i] <= intSeq[j]\n ensures r < 0 || (r < |intSeq| && intSeq[r] == key) // post condition not correctly formed\n{\n return -1;\n}\n\npredicate BinarySearchWrong3Transition(intSeq:seq, key:int, r:int)\n requires forall i,j | 0 <= i <= j < |intSeq| :: intSeq[i] <= intSeq[j]\n{\n r < 0 || (r < |intSeq| && intSeq[r] == key)\n}\n\nlemma BinarySearchWrong4(intSeq:seq, key:int) returns (r:int)\n // non-realistic\n requires forall i,j | 0 <= i <= j < |intSeq| :: intSeq[i] <= intSeq[j]\n ensures 0 <= r < |intSeq| && intSeq[r] == key\n\npredicate BinarySearchWrong4Transition(intSeq:seq, key:int, r:int)\n requires forall i,j | 0 <= i <= j < |intSeq| :: intSeq[i] <= intSeq[j]\n{\n 0 <= r < |intSeq| && intSeq[r] == key\n}\n\n", "hints_removed": "lemma BinarySearch(intSeq:seq, key:int) returns (r:int)\n // original\n requires forall i,j | 0 <= i <= j < |intSeq| :: intSeq[i] <= intSeq[j]\n ensures r >= 0 ==> r < |intSeq| && intSeq[r] == key\n ensures r < 0 ==> forall i:nat | i < |intSeq| :: intSeq[i] != key\n{ \n var lo:nat := 0;\n var hi:nat := |intSeq|;\n while lo < hi\n {\n var mid := (lo + hi) / 2;\n if (intSeq[mid] < key) {\n lo := mid + 1;\n } else if (intSeq[mid] > key) {\n hi := mid;\n } else {\n return mid;\n }\n }\n return -1;\n}\n\npredicate BinarySearchTransition(intSeq:seq, key:int, r:int)\n requires (forall i,j | 0 <= i <= j < |intSeq| :: intSeq[i] <= intSeq[j])\n{\n && (r >= 0 ==> r < |intSeq| && intSeq[r] == key)\n && (r < 0 ==> forall i:nat | i < |intSeq| :: intSeq[i] != key)\n}\n\nlemma BinarySearchDeterministic(intSeq:seq, key:int) returns (r:int)\n requires forall i,j | 0 <= i <= j < |intSeq| :: intSeq[i] <= intSeq[j]\n ensures r >= 0 ==> r < |intSeq| && intSeq[r] == key\n ensures r < 0 ==> forall i:nat | i < |intSeq| :: intSeq[i] != key\n\n // make it deterministic\n ensures r < 0 ==> r == -1 // return -1 if not found\n ensures r >= 0 ==> forall i:nat | i < r :: intSeq[i] < key // multiple matches return the first result\n\n{ \n var lo:nat := 0;\n var hi:nat := |intSeq|;\n while lo < hi\n || (forall i:nat | hi <= i < |intSeq| :: intSeq[i] >= key && exists i:nat | lo <= i < hi :: intSeq[i] == key)\n {\n var mid := (lo + hi) / 2;\n if (intSeq[mid] < key) {\n lo := mid + 1;\n } else if (intSeq[mid] > key) {\n hi := mid;\n } else {\n var inner_mid := (lo + mid) / 2;\n if (intSeq[inner_mid] < key) {\n lo := inner_mid + 1;\n } else if (hi != inner_mid + 1) {\n hi := inner_mid + 1;\n } else {\n if (intSeq[lo] == key) {\n return lo;\n } else {\n lo := lo + 1;\n }\n }\n }\n }\n return -1;\n}\n\npredicate BinarySearchDeterministicTransition(intSeq:seq, key:int, r:int)\n requires (forall i,j | 0 <= i <= j < |intSeq| :: intSeq[i] <= intSeq[j])\n{\n && (r >= 0 ==> r < |intSeq| && intSeq[r] == key)\n && (r < 0 ==> forall i:nat | i < |intSeq| :: intSeq[i] != key)\n\n // make it deterministic\n && (r < 0 ==> r == -1) // return -1 if not found\n && (r >= 0 ==> forall i:nat | i < r :: intSeq[i] < key)\n}\n\nlemma BinarySearchWrong1(intSeq:seq, key:int) returns (r:int)\n // first element\n requires forall i,j | 0 <= i <= j < |intSeq| :: intSeq[i] <= intSeq[j]\n ensures r >= 0 ==> r < |intSeq| && intSeq[r] == key\n ensures r < 0 ==> forall i:nat | 0 < i < |intSeq| :: intSeq[i] != key // i >= 0\n\n // make it deterministic\n ensures r < 0 ==> r == -1 // return -1 if not found\n ensures r >= 0 ==> forall i:nat | i < r :: intSeq[i] < key // multiple matches return the first result\n\npredicate BinarySearchWrong1Transition(intSeq:seq, key:int, r:int)\n requires forall i,j | 0 <= i <= j < |intSeq| :: intSeq[i] <= intSeq[j]\n{\n && (r >= 0 ==> r < |intSeq| && intSeq[r] == key)\n && (r < 0 ==> forall i:nat | 0 < i < |intSeq| :: intSeq[i] != key) // i >= 0\n\n // make it deterministic\n && (r < 0 ==> r == -1) // return -1 if not found\n && (r >= 0 ==> forall i:nat | i < r :: intSeq[i] < key)\n}\n\nlemma BinarySearchWrong2(intSeq:seq, key:int) returns (r:int)\n // last element\n requires forall i,j | 0 <= i <= j < |intSeq| :: intSeq[i] <= intSeq[j]\n ensures r >= 0 ==> r < |intSeq| && intSeq[r] == key\n ensures r < 0 ==> forall i:nat | 0 <= i < |intSeq| - 1 :: intSeq[i] != key // i < |intSeq|\n\n // make it deterministic\n ensures r < 0 ==> r == -1 // return -1 if not found\n ensures r >= 0 ==> forall i:nat | i < r :: intSeq[i] < key // multiple matches return the first result\n\npredicate BinarySearchWrong2Transition(intSeq:seq, key:int, r:int)\n requires forall i,j | 0 <= i <= j < |intSeq| :: intSeq[i] <= intSeq[j]\n{\n && (r >= 0 ==> r < |intSeq| && intSeq[r] == key)\n && (r < 0 ==> forall i:nat | 0 <= i < |intSeq| - 1 :: intSeq[i] != key) // i < |intSeq|\n\n // make it deterministic\n && (r < 0 ==> r == -1) // return -1 if not found\n && (r >= 0 ==> forall i:nat | i < r :: intSeq[i] < key)\n}\n\nlemma BinarySearchWrong3(intSeq:seq, key:int) returns (r:int)\n // weaker spec\n requires forall i,j | 0 <= i <= j < |intSeq| :: intSeq[i] <= intSeq[j]\n ensures r < 0 || (r < |intSeq| && intSeq[r] == key) // post condition not correctly formed\n{\n return -1;\n}\n\npredicate BinarySearchWrong3Transition(intSeq:seq, key:int, r:int)\n requires forall i,j | 0 <= i <= j < |intSeq| :: intSeq[i] <= intSeq[j]\n{\n r < 0 || (r < |intSeq| && intSeq[r] == key)\n}\n\nlemma BinarySearchWrong4(intSeq:seq, key:int) returns (r:int)\n // non-realistic\n requires forall i,j | 0 <= i <= j < |intSeq| :: intSeq[i] <= intSeq[j]\n ensures 0 <= r < |intSeq| && intSeq[r] == key\n\npredicate BinarySearchWrong4Transition(intSeq:seq, key:int, r:int)\n requires forall i,j | 0 <= i <= j < |intSeq| :: intSeq[i] <= intSeq[j]\n{\n 0 <= r < |intSeq| && intSeq[r] == key\n}\n\n" }, { "test_ID": "745", "test_file": "specTesting_tmp_tmpueam35lx_examples_increment_decrement_spec.dfy", "ground_truth": "module OneSpec {\n datatype Variables = Variables(value: int)\n\n predicate Init(v: Variables)\n {\n v.value == 0\n }\n\n predicate IncrementOp(v: Variables, v': Variables)\n {\n && v'.value == v.value + 1\n }\n\n predicate DecrementOp(v: Variables, v': Variables)\n {\n && v'.value == v.value - 1\n }\n\n datatype Step = \n | IncrementStep()\n | DecrementStep()\n\n predicate NextStep(v: Variables, v': Variables, step: Step)\n {\n match step\n case IncrementStep() => IncrementOp(v, v')\n case DecrementStep() => DecrementOp(v, v')\n }\n\n predicate Next(v: Variables, v': Variables)\n {\n exists step :: NextStep(v, v', step)\n }\n}\n\nmodule OneProtocol {\n datatype Variables = Variables(value: int)\n\n predicate Init(v: Variables)\n {\n v.value == 0\n }\n\n predicate IncrementOp(v: Variables, v': Variables)\n {\n && v'.value == v.value - 1\n }\n\n predicate DecrementOp(v: Variables, v': Variables)\n {\n && v'.value == v.value + 1\n }\n\n datatype Step = \n | IncrementStep()\n | DecrementStep()\n\n predicate NextStep(v: Variables, v': Variables, step: Step)\n {\n match step \n case IncrementStep() => IncrementOp(v, v')\n case DecrementStep() => DecrementOp(v, v')\n }\n\n predicate Next(v: Variables, v': Variables)\n {\n exists step :: NextStep(v, v', step)\n }\n}\n\nmodule RefinementProof {\n import OneSpec\n import opened OneProtocol\n\n function Abstraction(v: Variables) : OneSpec.Variables {\n OneSpec.Variables(v.value)\n }\n\n lemma RefinementInit(v: Variables)\n requires Init(v)\n ensures OneSpec.Init(Abstraction(v))\n {\n\n }\n\n lemma RefinementNext(v: Variables, v': Variables)\n requires Next(v, v')\n ensures OneSpec.Next(Abstraction(v), Abstraction(v'))\n {\n var step :| NextStep(v, v', step);\n match step {\n case IncrementStep() => {\n assert OneSpec.NextStep(Abstraction(v), Abstraction(v'), OneSpec.DecrementStep());\n }\n case DecrementStep() => {\n assert OneSpec.NextStep(Abstraction(v), Abstraction(v'), OneSpec.IncrementStep());\n }\n }\n }\n}\n", "hints_removed": "module OneSpec {\n datatype Variables = Variables(value: int)\n\n predicate Init(v: Variables)\n {\n v.value == 0\n }\n\n predicate IncrementOp(v: Variables, v': Variables)\n {\n && v'.value == v.value + 1\n }\n\n predicate DecrementOp(v: Variables, v': Variables)\n {\n && v'.value == v.value - 1\n }\n\n datatype Step = \n | IncrementStep()\n | DecrementStep()\n\n predicate NextStep(v: Variables, v': Variables, step: Step)\n {\n match step\n case IncrementStep() => IncrementOp(v, v')\n case DecrementStep() => DecrementOp(v, v')\n }\n\n predicate Next(v: Variables, v': Variables)\n {\n exists step :: NextStep(v, v', step)\n }\n}\n\nmodule OneProtocol {\n datatype Variables = Variables(value: int)\n\n predicate Init(v: Variables)\n {\n v.value == 0\n }\n\n predicate IncrementOp(v: Variables, v': Variables)\n {\n && v'.value == v.value - 1\n }\n\n predicate DecrementOp(v: Variables, v': Variables)\n {\n && v'.value == v.value + 1\n }\n\n datatype Step = \n | IncrementStep()\n | DecrementStep()\n\n predicate NextStep(v: Variables, v': Variables, step: Step)\n {\n match step \n case IncrementStep() => IncrementOp(v, v')\n case DecrementStep() => DecrementOp(v, v')\n }\n\n predicate Next(v: Variables, v': Variables)\n {\n exists step :: NextStep(v, v', step)\n }\n}\n\nmodule RefinementProof {\n import OneSpec\n import opened OneProtocol\n\n function Abstraction(v: Variables) : OneSpec.Variables {\n OneSpec.Variables(v.value)\n }\n\n lemma RefinementInit(v: Variables)\n requires Init(v)\n ensures OneSpec.Init(Abstraction(v))\n {\n\n }\n\n lemma RefinementNext(v: Variables, v': Variables)\n requires Next(v, v')\n ensures OneSpec.Next(Abstraction(v), Abstraction(v'))\n {\n var step :| NextStep(v, v', step);\n match step {\n case IncrementStep() => {\n }\n case DecrementStep() => {\n }\n }\n }\n}\n" }, { "test_ID": "746", "test_file": "specTesting_tmp_tmpueam35lx_examples_max_max.dfy", "ground_truth": "lemma max(a:int, b:int) returns (m:int)\n ensures m >= a\n ensures m >= b\n ensures m == a || m == b\n{\n if (a > b) {\n m := a;\n } else {\n m := b;\n }\n}\n\npredicate post_max(a:int, b:int, m:int)\n{\n && m >= a\n && m >= b\n && (m == a || m == b)\n}\n\n// to check if it is functioning: postcondition not too accommodating\n// the case it will refuse\nlemma post_max_point_1(a:int, b:int, m:int)\n requires a > b\n requires m != a\n ensures !post_max(a, b, m)\n{}\n\n// an equivalent way of doing so\nlemma post_max_point_1'(a:int, b:int, m:int)\n requires a > b\n requires post_max(a, b, m)\n ensures m == a\n{}\n\nlemma post_max_point_2(a:int, b:int, m:int)\n requires a == b\n requires m != a || m != b\n ensures !post_max(a, b, m)\n{}\n\nlemma post_max_point_3(a:int, b:int, m:int)\n requires a < b\n requires m != b\n ensures !post_max(a, b, m)\n{}\n\nlemma post_max_vertical_1(a:int, b:int, m:int)\n requires m != a && m != b\n ensures !post_max(a, b, m)\n{}\n\nlemma post_max_vertical_1'(a:int, b:int, m:int)\n requires post_max(a, b, m)\n ensures m == a || m == b\n{}\n\n// to check if it is implementable\nlemma post_max_realistic_1(a:int, b:int, m:int)\n requires a > b\n requires m == a\n ensures post_max(a, b, m)\n{}\n\nlemma post_max_realistic_2(a:int, b:int, m:int)\n requires a < b\n requires m == b\n ensures post_max(a, b, m)\n{}\n\nlemma post_max_realistic_3(a:int, b:int, m:int)\n requires a == b\n requires m == a\n ensures post_max(a, b, m)\n{}\n\n\n// this form is more natural\nlemma max_deterministic(a:int, b:int, m:int, m':int)\n // should include preconditions if applicable\n requires post_max(a, b, m)\n requires post_max(a, b, m')\n ensures m == m'\n{}\n\nlemma max_deterministic'(a:int, b:int, m:int, m':int)\n requires m != m'\n ensures !post_max(a, b, m) || !post_max(a, b, m')\n{}\n\n\n\nlemma lemmaInvTheProposerOfAnyValidBlockInAnHonestBlockchailnIsInTheSetOfValidatorsHelper6Helper(\n s: seq,\n b: int,\n i: nat\n )\n requires |s| > i \n requires b == s[i]\n ensures s[..i] + [b] == s[..i+1]\n { }\n\nlemma multisetEquality(m1:multiset, m2:multiset, m3:multiset, m4:multiset)\n requires m1 > m2 + m3\n requires m1 == m2 + m4\n ensures m3 < m4\n{\n assert m3 < m1 - m2;\n}\n\n", "hints_removed": "lemma max(a:int, b:int) returns (m:int)\n ensures m >= a\n ensures m >= b\n ensures m == a || m == b\n{\n if (a > b) {\n m := a;\n } else {\n m := b;\n }\n}\n\npredicate post_max(a:int, b:int, m:int)\n{\n && m >= a\n && m >= b\n && (m == a || m == b)\n}\n\n// to check if it is functioning: postcondition not too accommodating\n// the case it will refuse\nlemma post_max_point_1(a:int, b:int, m:int)\n requires a > b\n requires m != a\n ensures !post_max(a, b, m)\n{}\n\n// an equivalent way of doing so\nlemma post_max_point_1'(a:int, b:int, m:int)\n requires a > b\n requires post_max(a, b, m)\n ensures m == a\n{}\n\nlemma post_max_point_2(a:int, b:int, m:int)\n requires a == b\n requires m != a || m != b\n ensures !post_max(a, b, m)\n{}\n\nlemma post_max_point_3(a:int, b:int, m:int)\n requires a < b\n requires m != b\n ensures !post_max(a, b, m)\n{}\n\nlemma post_max_vertical_1(a:int, b:int, m:int)\n requires m != a && m != b\n ensures !post_max(a, b, m)\n{}\n\nlemma post_max_vertical_1'(a:int, b:int, m:int)\n requires post_max(a, b, m)\n ensures m == a || m == b\n{}\n\n// to check if it is implementable\nlemma post_max_realistic_1(a:int, b:int, m:int)\n requires a > b\n requires m == a\n ensures post_max(a, b, m)\n{}\n\nlemma post_max_realistic_2(a:int, b:int, m:int)\n requires a < b\n requires m == b\n ensures post_max(a, b, m)\n{}\n\nlemma post_max_realistic_3(a:int, b:int, m:int)\n requires a == b\n requires m == a\n ensures post_max(a, b, m)\n{}\n\n\n// this form is more natural\nlemma max_deterministic(a:int, b:int, m:int, m':int)\n // should include preconditions if applicable\n requires post_max(a, b, m)\n requires post_max(a, b, m')\n ensures m == m'\n{}\n\nlemma max_deterministic'(a:int, b:int, m:int, m':int)\n requires m != m'\n ensures !post_max(a, b, m) || !post_max(a, b, m')\n{}\n\n\n\nlemma lemmaInvTheProposerOfAnyValidBlockInAnHonestBlockchailnIsInTheSetOfValidatorsHelper6Helper(\n s: seq,\n b: int,\n i: nat\n )\n requires |s| > i \n requires b == s[i]\n ensures s[..i] + [b] == s[..i+1]\n { }\n\nlemma multisetEquality(m1:multiset, m2:multiset, m3:multiset, m4:multiset)\n requires m1 > m2 + m3\n requires m1 == m2 + m4\n ensures m3 < m4\n{\n}\n\n" }, { "test_ID": "747", "test_file": "specTesting_tmp_tmpueam35lx_examples_sort_sort.dfy", "ground_truth": "method quickSort(intSeq:array)\n modifies intSeq\n ensures forall i:nat, j:nat | 0 <= i <= j < intSeq.Length :: intSeq[i] <= intSeq[j]\n // ensures multiset(intSeq[..]) == multiset(old(intSeq[..]))\n\n\nlemma sort(prevSeq:seq) returns (curSeq:seq)\n ensures (forall i:nat, j:nat | 0 <= i <= j < |curSeq| :: curSeq[i] <= curSeq[j])\n ensures multiset(prevSeq) == multiset(curSeq)\n\npredicate post_sort(prevSeq:seq, curSeq:seq)\n{\n && (forall i:nat, j:nat | 0 <= i <= j < |curSeq| :: curSeq[i] <= curSeq[j])\n && multiset(prevSeq) == multiset(curSeq)\n}\n\nlemma multisetAdditivity(m1:multiset, m2:multiset, m3:multiset, m4:multiset)\n requires m1 == m2 + m3\n requires m1 == m2 + m4\n ensures m3 == m4\n {\n assert m3 == m1 - m2;\n assert m4 == m1 - m2;\n }\n\n\nlemma twoSortedSequencesWithSameElementsAreEqual(s1:seq, s2:seq)\n requires (forall i:nat, j:nat | 0 <= i <= j < |s1| :: s1[i] <= s1[j])\n requires (forall i:nat, j:nat | 0 <= i <= j < |s2| :: s2[i] <= s2[j])\n requires multiset(s1) == multiset(s2)\n requires |s1| == |s2|\n ensures s1 == s2\n{\n if (|s1| != 0) {\n if s1[|s1|-1] == s2[|s2|-1] {\n assert multiset(s1[..|s1|-1]) == multiset(s2[..|s2|-1]) by {\n assert s1 == s1[..|s1|-1] + [s1[|s1|-1]];\n assert multiset(s1) == multiset(s1[..|s1|-1]) + multiset([s1[|s1|-1]]);\n\n assert s2 == s2[..|s1|-1] + [s2[|s1|-1]];\n assert multiset(s2) == multiset(s2[..|s1|-1]) + multiset([s2[|s1|-1]]);\n\n assert multiset([s1[|s1|-1]]) == multiset([s2[|s1|-1]]);\n\n multisetAdditivity(multiset(s1), multiset([s1[|s1|-1]]), multiset(s1[..|s1|-1]), multiset(s2[..|s1|-1]));\n }\n twoSortedSequencesWithSameElementsAreEqual(s1[..|s1|-1], s2[..|s2|-1]);\n } else if s1[|s1|-1] < s2[|s2|-1] {\n assert s2[|s2|-1] !in multiset(s1);\n assert false;\n } else {\n assert s1[|s1|-1] !in multiset(s2);\n assert false;\n }\n }\n}\n\nlemma sort_determinisitc(prevSeq:seq, curSeq:seq, curSeq':seq)\n requires post_sort(prevSeq, curSeq)\n requires post_sort(prevSeq, curSeq')\n ensures curSeq == curSeq'\n{\n \n if (|curSeq| != |curSeq'|) {\n assert |multiset(curSeq)| != |multiset(curSeq')|;\n } else {\n twoSortedSequencesWithSameElementsAreEqual(curSeq, curSeq');\n }\n}\n\nlemma sort_determinisitc1(prevSeq:seq, curSeq:seq, curSeq':seq)\n requires prevSeq == [5,4,3,2,1]\n requires post_sort(prevSeq, curSeq)\n requires post_sort(prevSeq, curSeq')\n ensures curSeq == curSeq'\n{\n}\n \n\n\n\n\n", "hints_removed": "method quickSort(intSeq:array)\n modifies intSeq\n ensures forall i:nat, j:nat | 0 <= i <= j < intSeq.Length :: intSeq[i] <= intSeq[j]\n // ensures multiset(intSeq[..]) == multiset(old(intSeq[..]))\n\n\nlemma sort(prevSeq:seq) returns (curSeq:seq)\n ensures (forall i:nat, j:nat | 0 <= i <= j < |curSeq| :: curSeq[i] <= curSeq[j])\n ensures multiset(prevSeq) == multiset(curSeq)\n\npredicate post_sort(prevSeq:seq, curSeq:seq)\n{\n && (forall i:nat, j:nat | 0 <= i <= j < |curSeq| :: curSeq[i] <= curSeq[j])\n && multiset(prevSeq) == multiset(curSeq)\n}\n\nlemma multisetAdditivity(m1:multiset, m2:multiset, m3:multiset, m4:multiset)\n requires m1 == m2 + m3\n requires m1 == m2 + m4\n ensures m3 == m4\n {\n }\n\n\nlemma twoSortedSequencesWithSameElementsAreEqual(s1:seq, s2:seq)\n requires (forall i:nat, j:nat | 0 <= i <= j < |s1| :: s1[i] <= s1[j])\n requires (forall i:nat, j:nat | 0 <= i <= j < |s2| :: s2[i] <= s2[j])\n requires multiset(s1) == multiset(s2)\n requires |s1| == |s2|\n ensures s1 == s2\n{\n if (|s1| != 0) {\n if s1[|s1|-1] == s2[|s2|-1] {\n\n\n\n multisetAdditivity(multiset(s1), multiset([s1[|s1|-1]]), multiset(s1[..|s1|-1]), multiset(s2[..|s1|-1]));\n }\n twoSortedSequencesWithSameElementsAreEqual(s1[..|s1|-1], s2[..|s2|-1]);\n } else if s1[|s1|-1] < s2[|s2|-1] {\n } else {\n }\n }\n}\n\nlemma sort_determinisitc(prevSeq:seq, curSeq:seq, curSeq':seq)\n requires post_sort(prevSeq, curSeq)\n requires post_sort(prevSeq, curSeq')\n ensures curSeq == curSeq'\n{\n \n if (|curSeq| != |curSeq'|) {\n } else {\n twoSortedSequencesWithSameElementsAreEqual(curSeq, curSeq');\n }\n}\n\nlemma sort_determinisitc1(prevSeq:seq, curSeq:seq, curSeq':seq)\n requires prevSeq == [5,4,3,2,1]\n requires post_sort(prevSeq, curSeq)\n requires post_sort(prevSeq, curSeq')\n ensures curSeq == curSeq'\n{\n}\n \n\n\n\n\n" }, { "test_ID": "748", "test_file": "stunning-palm-tree_tmp_tmpr84c2iwh_ch1.dfy", "ground_truth": "// Ex 1.3\nmethod Triple (x: int) returns (r: int)\n ensures r == 3*x {\n var y := 2*x;\n r := y + x;\n assert r == 3*x;\n}\n\nmethod Caller() {\n var t := Triple(18);\n assert t < 100;\n}\n\n// Ex 1.6\nmethod MinUnderSpec (x: int, y: int) returns (r: int)\n ensures r <= x && r <= y {\n if x <= y {\n r := x - 1;\n } else {\n r := y - 1;\n }\n}\n\nmethod Min (x: int, y: int) returns (r: int)\n ensures r <= x && r <= y\n ensures r == x || r == y {\n if x <= y {\n r := x;\n } else {\n r := y;\n }\n}\n\n// Ex 1.7\nmethod MaxSum (x: int, y: int) returns (s:int, m: int)\n ensures s == x + y\n ensures x <= m && y <= m\n ensures m == x || m == y\n// look ma, no implementation!\n\nmethod MaxSumCaller() {\n var s, m := MaxSum(1928, 1);\n assert s == 1929;\n assert m == 1928;\n}\n\n// Ex 1.8\nmethod ReconstructFromMaxSum (s: int, m: int ) returns (x: int, y: int)\n // requires (0 < s && s / 2 < m && m < s)\n requires s - m <= m\n ensures s == x + y\n ensures (m == y || m == x) && x <= m && y <= m\n{\n x := m;\n y := s - m;\n}\n\nmethod TestMaxSum(x: int, y: int)\n // requires x > 0 && y > 0 && x != y\n{\n var s, m := MaxSum(x, y);\n var xx, yy := ReconstructFromMaxSum(s, m);\n assert (xx == x && yy == y) || (xx == y && yy == x);\n}\n\n// Ex 1.9\nfunction Average (a: int, b: int): int {\n (a + b) / 2\n}\n\nmethod Triple'(x: int) returns (r: int)\n // spec 1: ensures Average(r, 3*x) == 3*x\n ensures Average(2*r, 6*x) == 6*x\n{\n // r := x + x + x + 1; // does not meet spec of Triple, but does spec 1\n r := x + x + x;\n}\n", "hints_removed": "// Ex 1.3\nmethod Triple (x: int) returns (r: int)\n ensures r == 3*x {\n var y := 2*x;\n r := y + x;\n}\n\nmethod Caller() {\n var t := Triple(18);\n}\n\n// Ex 1.6\nmethod MinUnderSpec (x: int, y: int) returns (r: int)\n ensures r <= x && r <= y {\n if x <= y {\n r := x - 1;\n } else {\n r := y - 1;\n }\n}\n\nmethod Min (x: int, y: int) returns (r: int)\n ensures r <= x && r <= y\n ensures r == x || r == y {\n if x <= y {\n r := x;\n } else {\n r := y;\n }\n}\n\n// Ex 1.7\nmethod MaxSum (x: int, y: int) returns (s:int, m: int)\n ensures s == x + y\n ensures x <= m && y <= m\n ensures m == x || m == y\n// look ma, no implementation!\n\nmethod MaxSumCaller() {\n var s, m := MaxSum(1928, 1);\n}\n\n// Ex 1.8\nmethod ReconstructFromMaxSum (s: int, m: int ) returns (x: int, y: int)\n // requires (0 < s && s / 2 < m && m < s)\n requires s - m <= m\n ensures s == x + y\n ensures (m == y || m == x) && x <= m && y <= m\n{\n x := m;\n y := s - m;\n}\n\nmethod TestMaxSum(x: int, y: int)\n // requires x > 0 && y > 0 && x != y\n{\n var s, m := MaxSum(x, y);\n var xx, yy := ReconstructFromMaxSum(s, m);\n}\n\n// Ex 1.9\nfunction Average (a: int, b: int): int {\n (a + b) / 2\n}\n\nmethod Triple'(x: int) returns (r: int)\n // spec 1: ensures Average(r, 3*x) == 3*x\n ensures Average(2*r, 6*x) == 6*x\n{\n // r := x + x + x + 1; // does not meet spec of Triple, but does spec 1\n r := x + x + x;\n}\n" }, { "test_ID": "749", "test_file": "stunning-palm-tree_tmp_tmpr84c2iwh_ch10.dfy", "ground_truth": "// Ch. 10: Datatype Invariants\n\nmodule PQueue {\n export\n // Impl\n provides PQueue\n provides Empty, IsEmpty, Insert, RemoveMin\n // Spec\n provides Valid, Elements, EmptyCorrect, IsEmptyCorrect\n provides InsertCorrect, RemoveMinCorrect\n reveals IsMin\n\n // Implementation\n type PQueue = BraunTree\n datatype BraunTree =\n | Leaf\n | Node(x: int, left: BraunTree, right: BraunTree)\n\n function Empty(): PQueue {\n Leaf\n }\n\n predicate IsEmpty(pq: PQueue) {\n pq == Leaf\n }\n\n function Insert(pq: PQueue, y: int): PQueue {\n match pq\n case Leaf => Node(y, Leaf, Leaf)\n case Node(x, left, right) =>\n if y < x then\n Node(y, Insert(right ,x), left)\n else\n Node(x, Insert(right, y), left)\n }\n\n function RemoveMin(pq: PQueue): (int, PQueue)\n requires Valid(pq) && !IsEmpty(pq)\n {\n var Node(x, left, right) := pq;\n (x, DeleteMin(pq))\n }\n \n function DeleteMin(pq: PQueue): PQueue\n requires IsBalanced(pq) && !IsEmpty(pq)\n {\n // Ex. 10.4: by the IsBalanced property, pq.left is always as large or one node larger\n // than pq.right. Thus pq.left.Leaf? ==> pq.right.leaf?\n if pq.right.Leaf? then\n pq.left\n else if pq.left.x <= pq.right.x then\n Node(pq.left.x, pq.right, DeleteMin(pq.left))\n else\n Node(pq.right.x, ReplaceRoot(pq.right, pq.left.x), DeleteMin(pq.left))\n }\n\n function ReplaceRoot(pq: PQueue, r: int): PQueue\n requires !IsEmpty(pq)\n {\n // left is empty or r is smaller than either sub-root\n if pq.left.Leaf? ||\n (r <= pq.left.x && (pq.right.Leaf? || r <= pq.right.x))\n then\n // simply replace the root\n Node(r, pq.left, pq.right)\n // right is empty, left has one element\n else if pq.right.Leaf? then\n Node(pq.left.x, Node(r, Leaf, Leaf), Leaf)\n // both left/right are non-empty and `r` needs to be inserted deeper in the sub-trees\n else if pq.left.x < pq.right.x then\n // promote left root\n Node(pq.left.x, ReplaceRoot(pq.left, r), pq.right)\n else\n // promote right root\n Node(pq.right.x, pq.left, ReplaceRoot(pq.right, r))\n }\n\n //////////////////////////////////////////////////////////////\n // Specification exposed to callers\n //////////////////////////////////////////////////////////////\n\n ghost function Elements(pq: PQueue): multiset {\n match pq\n case Leaf => multiset{}\n case Node(x, left, right) =>\n multiset{x} + Elements(left) + Elements(right)\n }\n\n ghost predicate Valid(pq: PQueue) {\n IsBinaryHeap(pq) && IsBalanced(pq)\n }\n \n //////////////////////////////////////////////////////////////\n // Lemmas\n //////////////////////////////////////////////////////////////\n\n ghost predicate IsBinaryHeap(pq: PQueue) {\n match pq\n case Leaf => true\n case Node(x, left, right) =>\n IsBinaryHeap(left) && IsBinaryHeap(right) &&\n (left.Leaf? || x <= left.x) &&\n (right.Leaf? || x <= right.x)\n }\n\n ghost predicate IsBalanced(pq: PQueue) {\n match pq\n case Leaf => true\n case Node(_, left, right) =>\n IsBalanced(left) && IsBalanced(right) &&\n var L, R := |Elements(left)|, |Elements(right)|;\n L == R || L == R + 1\n }\n\n // Ex. 10.2\n lemma {:induction false} BinaryHeapStoresMin(pq: PQueue, y: int)\n requires IsBinaryHeap(pq) && y in Elements(pq)\n ensures pq.x <= y\n {\n if pq.Node? {\n assert y in Elements(pq) ==> (y == pq.x\n || y in Elements(pq.left) \n || y in Elements(pq.right));\n if y == pq.x {\n assert pq.x <= y;\n } else if y in Elements(pq.left) {\n assert pq.x <= pq.left.x;\n BinaryHeapStoresMin(pq.left, y);\n assert pq.x <= y;\n } else if y in Elements(pq.right) {\n assert pq.x <= pq.right.x;\n BinaryHeapStoresMin(pq.right, y);\n assert pq.x <= y;\n }\n }\n }\n\n lemma EmptyCorrect()\n ensures Valid(Empty()) && Elements(Empty()) == multiset{}\n { // unfold Empty()\n }\n \n lemma IsEmptyCorrect(pq: PQueue)\n requires Valid(pq)\n ensures IsEmpty(pq) <==> Elements(pq) == multiset{}\n {\n if Elements(pq) == multiset{} {\n assert pq.Leaf?;\n }\n }\n \n lemma InsertCorrect(pq: PQueue, y: int)\n requires Valid(pq)\n ensures var pq' := Insert(pq, y);\n Valid(pq') && Elements(Insert(pq, y)) == Elements(pq) + multiset{y}\n {}\n\n lemma RemoveMinCorrect(pq: PQueue)\n requires Valid(pq)\n requires !IsEmpty(pq)\n ensures var (y, pq') := RemoveMin(pq);\n Elements(pq) == Elements(pq') + multiset{y} &&\n IsMin(y, Elements(pq)) &&\n Valid(pq')\n {\n DeleteMinCorrect(pq);\n }\n \n lemma {:induction false} {:rlimit 1000} {:vcs_split_on_every_assert} DeleteMinCorrect(pq: PQueue)\n requires Valid(pq) && !IsEmpty(pq)\n ensures var pq' := DeleteMin(pq);\n Valid(pq') &&\n Elements(pq') + multiset{pq.x} == Elements(pq) &&\n |Elements(pq')| == |Elements(pq)| - 1\n {\n if pq.left.Leaf? || pq.right.Leaf? {}\n else if pq.left.x <= pq.right.x {\n DeleteMinCorrect(pq.left);\n } else {\n var left, right := ReplaceRoot(pq.right, pq.left.x), DeleteMin(pq.left);\n var pq' := Node(pq.right.x, left, right);\n assert pq' == DeleteMin(pq);\n \n // Elements post-condition\n calc {\n Elements(pq') + multiset{pq.x};\n == // defn Elements\n (multiset{pq.right.x} + Elements(left) + Elements(right)) + multiset{pq.x};\n == // multiset left assoc\n ((multiset{pq.right.x} + Elements(left)) + Elements(right)) + multiset{pq.x};\n == { ReplaceRootCorrect(pq.right, pq.left.x);\n assert multiset{pq.right.x} + Elements(left) == Elements(pq.right) + multiset{pq.left.x}; }\n ((Elements(pq.right) + multiset{pq.left.x}) + Elements(right)) + multiset{pq.x};\n == // defn right\n ((Elements(pq.right) + multiset{pq.left.x}) + Elements(DeleteMin(pq.left))) + multiset{pq.x};\n == // multiset right assoc\n (Elements(pq.right) + (multiset{pq.left.x} + Elements(DeleteMin(pq.left)))) + multiset{pq.x};\n == { DeleteMinCorrect(pq.left);\n assert multiset{pq.left.x} + Elements(DeleteMin(pq.left)) == Elements(pq.left); }\n (Elements(pq.right) + (Elements(pq.left))) + multiset{pq.x};\n ==\n multiset{pq.x} + Elements(pq.right) + (Elements(pq.left));\n ==\n Elements(pq);\n }\n \n // Validity\n // Prove IsBinaryHeap(pq')\n // IsBinaryHeap(left) && IsBinaryHeap(right) &&\n DeleteMinCorrect(pq.left);\n assert Valid(right);\n ReplaceRootCorrect(pq.right, pq.left.x);\n assert Valid(left);\n \n // (left.Leaf? || x <= left.x) &&\n assert pq.left.x in Elements(left);\n assert pq.right.x <= pq.left.x;\n BinaryHeapStoresMin(pq.left, pq.left.x);\n BinaryHeapStoresMin(pq.right, pq.right.x);\n assert pq.right.x <= left.x;\n // (right.Leaf? || x <= right.x)\n assert right.Leaf? || pq.right.x <= right.x;\n assert IsBinaryHeap(pq');\n }\n }\n\n lemma {:induction false} {:rlimit 1000} {:vcs_split_on_every_assert} ReplaceRootCorrect(pq: PQueue, r: int)\n requires Valid(pq) && !IsEmpty(pq)\n ensures var pq' := ReplaceRoot(pq, r);\n Valid(pq') &&\n r in Elements(pq') &&\n |Elements(pq')| == |Elements(pq)| &&\n Elements(pq) + multiset{r} == Elements(pq') + multiset{pq.x}\n {\n var pq' := ReplaceRoot(pq, r);\n // Element post-condition\n var left, right := pq'.left, pq'.right;\n if pq.left.Leaf? ||\n (r <= pq.left.x && (pq.right.Leaf? || r <= pq.right.x))\n {\n // simply replace the root\n assert Valid(pq');\n assert |Elements(pq')| == |Elements(pq)|;\n }\n else if pq.right.Leaf? {\n // both left/right are non-empty and `r` needs to be inserted deeper in the sub-trees\n }\n else if pq.left.x < pq.right.x {\n // promote left root\n assert pq.left.Node? && pq.right.Node?;\n assert pq.left.x < r || pq.right.x < r;\n assert pq' == Node(pq.left.x, ReplaceRoot(pq.left, r), pq.right);\n ReplaceRootCorrect(pq.left, r);\n assert Valid(pq');\n calc {\n Elements(pq') + multiset{pq.x};\n ==\n (multiset{pq.left.x} + Elements(ReplaceRoot(pq.left, r)) + Elements(pq.right)) + multiset{pq.x};\n == { ReplaceRootCorrect(pq.left, r); }\n (Elements(pq.left) + multiset{r}) + Elements(pq.right) + multiset{pq.x};\n ==\n Elements(pq) + multiset{r};\n }\n }\n else {\n // promote right root\n assert pq' == Node(pq.right.x, pq.left, ReplaceRoot(pq.right, r));\n ReplaceRootCorrect(pq.right, r);\n assert Valid(pq');\n calc {\n Elements(pq') + multiset{pq.x};\n == // defn\n (multiset{pq.right.x} + Elements(pq.left) + Elements(ReplaceRoot(pq.right, r))) + multiset{pq.x};\n == // assoc\n (Elements(pq.left) + (Elements(ReplaceRoot(pq.right, r)) + multiset{pq.right.x})) + multiset{pq.x};\n == { ReplaceRootCorrect(pq.right, r); }\n (Elements(pq.left) + multiset{r} + Elements(pq.right)) + multiset{pq.x};\n ==\n Elements(pq) + multiset{r};\n }\n }\n }\n\n ghost predicate IsMin(y: int, s: multiset) {\n y in s && forall x :: x in s ==> y <= x\n }\n\n}\n\n// Ex 10.0, 10.1\nmodule PQueueClient {\n import PQ = PQueue\n\n method Client() {\n var pq := PQ.Empty();\n PQ.EmptyCorrect();\n assert PQ.Elements(pq) == multiset{};\n assert PQ.Valid(pq);\n PQ.InsertCorrect(pq, 1);\n var pq1 := PQ.Insert(pq, 1);\n assert 1 in PQ.Elements(pq1);\n\n PQ.InsertCorrect(pq1, 2);\n var pq2 := PQ.Insert(pq1, 2);\n assert 2 in PQ.Elements(pq2);\n\n PQ.IsEmptyCorrect(pq2);\n PQ.RemoveMinCorrect(pq2);\n var (m, pq3) := PQ.RemoveMin(pq2); \n\n PQ.IsEmptyCorrect(pq3);\n PQ.RemoveMinCorrect(pq3);\n var (n, pq4) := PQ.RemoveMin(pq3); \n\n PQ.IsEmptyCorrect(pq4);\n assert PQ.IsEmpty(pq4);\n\n assert m <= n;\n }\n}\n", "hints_removed": "// Ch. 10: Datatype Invariants\n\nmodule PQueue {\n export\n // Impl\n provides PQueue\n provides Empty, IsEmpty, Insert, RemoveMin\n // Spec\n provides Valid, Elements, EmptyCorrect, IsEmptyCorrect\n provides InsertCorrect, RemoveMinCorrect\n reveals IsMin\n\n // Implementation\n type PQueue = BraunTree\n datatype BraunTree =\n | Leaf\n | Node(x: int, left: BraunTree, right: BraunTree)\n\n function Empty(): PQueue {\n Leaf\n }\n\n predicate IsEmpty(pq: PQueue) {\n pq == Leaf\n }\n\n function Insert(pq: PQueue, y: int): PQueue {\n match pq\n case Leaf => Node(y, Leaf, Leaf)\n case Node(x, left, right) =>\n if y < x then\n Node(y, Insert(right ,x), left)\n else\n Node(x, Insert(right, y), left)\n }\n\n function RemoveMin(pq: PQueue): (int, PQueue)\n requires Valid(pq) && !IsEmpty(pq)\n {\n var Node(x, left, right) := pq;\n (x, DeleteMin(pq))\n }\n \n function DeleteMin(pq: PQueue): PQueue\n requires IsBalanced(pq) && !IsEmpty(pq)\n {\n // Ex. 10.4: by the IsBalanced property, pq.left is always as large or one node larger\n // than pq.right. Thus pq.left.Leaf? ==> pq.right.leaf?\n if pq.right.Leaf? then\n pq.left\n else if pq.left.x <= pq.right.x then\n Node(pq.left.x, pq.right, DeleteMin(pq.left))\n else\n Node(pq.right.x, ReplaceRoot(pq.right, pq.left.x), DeleteMin(pq.left))\n }\n\n function ReplaceRoot(pq: PQueue, r: int): PQueue\n requires !IsEmpty(pq)\n {\n // left is empty or r is smaller than either sub-root\n if pq.left.Leaf? ||\n (r <= pq.left.x && (pq.right.Leaf? || r <= pq.right.x))\n then\n // simply replace the root\n Node(r, pq.left, pq.right)\n // right is empty, left has one element\n else if pq.right.Leaf? then\n Node(pq.left.x, Node(r, Leaf, Leaf), Leaf)\n // both left/right are non-empty and `r` needs to be inserted deeper in the sub-trees\n else if pq.left.x < pq.right.x then\n // promote left root\n Node(pq.left.x, ReplaceRoot(pq.left, r), pq.right)\n else\n // promote right root\n Node(pq.right.x, pq.left, ReplaceRoot(pq.right, r))\n }\n\n //////////////////////////////////////////////////////////////\n // Specification exposed to callers\n //////////////////////////////////////////////////////////////\n\n ghost function Elements(pq: PQueue): multiset {\n match pq\n case Leaf => multiset{}\n case Node(x, left, right) =>\n multiset{x} + Elements(left) + Elements(right)\n }\n\n ghost predicate Valid(pq: PQueue) {\n IsBinaryHeap(pq) && IsBalanced(pq)\n }\n \n //////////////////////////////////////////////////////////////\n // Lemmas\n //////////////////////////////////////////////////////////////\n\n ghost predicate IsBinaryHeap(pq: PQueue) {\n match pq\n case Leaf => true\n case Node(x, left, right) =>\n IsBinaryHeap(left) && IsBinaryHeap(right) &&\n (left.Leaf? || x <= left.x) &&\n (right.Leaf? || x <= right.x)\n }\n\n ghost predicate IsBalanced(pq: PQueue) {\n match pq\n case Leaf => true\n case Node(_, left, right) =>\n IsBalanced(left) && IsBalanced(right) &&\n var L, R := |Elements(left)|, |Elements(right)|;\n L == R || L == R + 1\n }\n\n // Ex. 10.2\n lemma {:induction false} BinaryHeapStoresMin(pq: PQueue, y: int)\n requires IsBinaryHeap(pq) && y in Elements(pq)\n ensures pq.x <= y\n {\n if pq.Node? {\n || y in Elements(pq.left) \n || y in Elements(pq.right));\n if y == pq.x {\n } else if y in Elements(pq.left) {\n BinaryHeapStoresMin(pq.left, y);\n } else if y in Elements(pq.right) {\n BinaryHeapStoresMin(pq.right, y);\n }\n }\n }\n\n lemma EmptyCorrect()\n ensures Valid(Empty()) && Elements(Empty()) == multiset{}\n { // unfold Empty()\n }\n \n lemma IsEmptyCorrect(pq: PQueue)\n requires Valid(pq)\n ensures IsEmpty(pq) <==> Elements(pq) == multiset{}\n {\n if Elements(pq) == multiset{} {\n }\n }\n \n lemma InsertCorrect(pq: PQueue, y: int)\n requires Valid(pq)\n ensures var pq' := Insert(pq, y);\n Valid(pq') && Elements(Insert(pq, y)) == Elements(pq) + multiset{y}\n {}\n\n lemma RemoveMinCorrect(pq: PQueue)\n requires Valid(pq)\n requires !IsEmpty(pq)\n ensures var (y, pq') := RemoveMin(pq);\n Elements(pq) == Elements(pq') + multiset{y} &&\n IsMin(y, Elements(pq)) &&\n Valid(pq')\n {\n DeleteMinCorrect(pq);\n }\n \n lemma {:induction false} {:rlimit 1000} {:vcs_split_on_every_assert} DeleteMinCorrect(pq: PQueue)\n requires Valid(pq) && !IsEmpty(pq)\n ensures var pq' := DeleteMin(pq);\n Valid(pq') &&\n Elements(pq') + multiset{pq.x} == Elements(pq) &&\n |Elements(pq')| == |Elements(pq)| - 1\n {\n if pq.left.Leaf? || pq.right.Leaf? {}\n else if pq.left.x <= pq.right.x {\n DeleteMinCorrect(pq.left);\n } else {\n var left, right := ReplaceRoot(pq.right, pq.left.x), DeleteMin(pq.left);\n var pq' := Node(pq.right.x, left, right);\n \n // Elements post-condition\n calc {\n Elements(pq') + multiset{pq.x};\n == // defn Elements\n (multiset{pq.right.x} + Elements(left) + Elements(right)) + multiset{pq.x};\n == // multiset left assoc\n ((multiset{pq.right.x} + Elements(left)) + Elements(right)) + multiset{pq.x};\n == { ReplaceRootCorrect(pq.right, pq.left.x);\n ((Elements(pq.right) + multiset{pq.left.x}) + Elements(right)) + multiset{pq.x};\n == // defn right\n ((Elements(pq.right) + multiset{pq.left.x}) + Elements(DeleteMin(pq.left))) + multiset{pq.x};\n == // multiset right assoc\n (Elements(pq.right) + (multiset{pq.left.x} + Elements(DeleteMin(pq.left)))) + multiset{pq.x};\n == { DeleteMinCorrect(pq.left);\n (Elements(pq.right) + (Elements(pq.left))) + multiset{pq.x};\n ==\n multiset{pq.x} + Elements(pq.right) + (Elements(pq.left));\n ==\n Elements(pq);\n }\n \n // Validity\n // Prove IsBinaryHeap(pq')\n // IsBinaryHeap(left) && IsBinaryHeap(right) &&\n DeleteMinCorrect(pq.left);\n ReplaceRootCorrect(pq.right, pq.left.x);\n \n // (left.Leaf? || x <= left.x) &&\n BinaryHeapStoresMin(pq.left, pq.left.x);\n BinaryHeapStoresMin(pq.right, pq.right.x);\n // (right.Leaf? || x <= right.x)\n }\n }\n\n lemma {:induction false} {:rlimit 1000} {:vcs_split_on_every_assert} ReplaceRootCorrect(pq: PQueue, r: int)\n requires Valid(pq) && !IsEmpty(pq)\n ensures var pq' := ReplaceRoot(pq, r);\n Valid(pq') &&\n r in Elements(pq') &&\n |Elements(pq')| == |Elements(pq)| &&\n Elements(pq) + multiset{r} == Elements(pq') + multiset{pq.x}\n {\n var pq' := ReplaceRoot(pq, r);\n // Element post-condition\n var left, right := pq'.left, pq'.right;\n if pq.left.Leaf? ||\n (r <= pq.left.x && (pq.right.Leaf? || r <= pq.right.x))\n {\n // simply replace the root\n }\n else if pq.right.Leaf? {\n // both left/right are non-empty and `r` needs to be inserted deeper in the sub-trees\n }\n else if pq.left.x < pq.right.x {\n // promote left root\n ReplaceRootCorrect(pq.left, r);\n calc {\n Elements(pq') + multiset{pq.x};\n ==\n (multiset{pq.left.x} + Elements(ReplaceRoot(pq.left, r)) + Elements(pq.right)) + multiset{pq.x};\n == { ReplaceRootCorrect(pq.left, r); }\n (Elements(pq.left) + multiset{r}) + Elements(pq.right) + multiset{pq.x};\n ==\n Elements(pq) + multiset{r};\n }\n }\n else {\n // promote right root\n ReplaceRootCorrect(pq.right, r);\n calc {\n Elements(pq') + multiset{pq.x};\n == // defn\n (multiset{pq.right.x} + Elements(pq.left) + Elements(ReplaceRoot(pq.right, r))) + multiset{pq.x};\n == // assoc\n (Elements(pq.left) + (Elements(ReplaceRoot(pq.right, r)) + multiset{pq.right.x})) + multiset{pq.x};\n == { ReplaceRootCorrect(pq.right, r); }\n (Elements(pq.left) + multiset{r} + Elements(pq.right)) + multiset{pq.x};\n ==\n Elements(pq) + multiset{r};\n }\n }\n }\n\n ghost predicate IsMin(y: int, s: multiset) {\n y in s && forall x :: x in s ==> y <= x\n }\n\n}\n\n// Ex 10.0, 10.1\nmodule PQueueClient {\n import PQ = PQueue\n\n method Client() {\n var pq := PQ.Empty();\n PQ.EmptyCorrect();\n PQ.InsertCorrect(pq, 1);\n var pq1 := PQ.Insert(pq, 1);\n\n PQ.InsertCorrect(pq1, 2);\n var pq2 := PQ.Insert(pq1, 2);\n\n PQ.IsEmptyCorrect(pq2);\n PQ.RemoveMinCorrect(pq2);\n var (m, pq3) := PQ.RemoveMin(pq2); \n\n PQ.IsEmptyCorrect(pq3);\n PQ.RemoveMinCorrect(pq3);\n var (n, pq4) := PQ.RemoveMin(pq3); \n\n PQ.IsEmptyCorrect(pq4);\n\n }\n}\n" }, { "test_ID": "750", "test_file": "stunning-palm-tree_tmp_tmpr84c2iwh_ch5.dfy", "ground_truth": "function More(x: int): int {\n if x <= 0 then 1 else More(x - 2) + 3\n}\n\nlemma {:induction false} Increasing(x: int)\n ensures x < More(x)\n{\n if x <= 0 {}\n else {\n // x < More(x) <=> x < More(x - 2) + 3\n // <=> x - 3 < More(x - 2)\n // Increasing(x - 2) ==> x - 2 < More(x - 2)\n // ==> x - 3 < x - 2 < More(x - 2)\n Increasing(x - 2);\n }\n}\n\nmethod ExampleLemmaUse(a: int) {\n var b := More(a);\n Increasing(a);\n var c := More(b);\n Increasing(b);\n assert 2 <= c - a;\n}\n\n// Ex 5.0\nmethod ExampleLemmaUse50(a: int) {\n Increasing(a);\n var b := More(a);\n var c := More(b);\n if a < 1000 {\n Increasing(b);\n assert 2 <= c - a;\n }\n assert a < 200 ==> 2 <= c - a;\n}\n\n// Ex 5.1\nmethod ExampleLemmaUse51(a: int) {\n Increasing(a);\n var b := More(a);\n Increasing(b);\n b := More(b);\n if a < 1000 {\n // Increasing(More(a));\n assert 2 <= b - a;\n }\n assert a < 200 ==> 2 <= b - a;\n}\n\n// Ex 5.6\nfunction Ack(m: nat, n: nat): nat {\n if m == 0 then\n n + 1\n else if n == 0 then\n Ack(m - 1, 1)\n else\n Ack(m - 1, Ack(m, n - 1))\n}\n\nlemma {:induction false} Ack1n(m: nat, n: nat)\n requires m == 1\n ensures Ack(m, n) == n + 2\n{\n if n == 0 {\n calc {\n Ack(m, n);\n ==\n Ack(m - 1, 1);\n ==\n Ack(0, 1);\n ==\n 1 + 1;\n ==\n 2;\n ==\n n + 2;\n }\n }\n else {\n calc {\n Ack(m, n);\n == // defn\n Ack(m - 1, Ack(m, n - 1));\n == // subs m := 1\n Ack(0, Ack(1, n - 1));\n == { Ack1n(1, n - 1); }\n Ack(0, (n - 1) + 2);\n == // arith\n Ack(0, n + 1);\n == // arith\n (n + 1) + 1;\n == // arith\n n + 2;\n }\n }\n}\n\n// Ex 5.5\nfunction Reduce(m: nat, x: int): int {\n if m == 0 then x else Reduce(m / 2, x + 1) - m\n}\n\nlemma {:induction false} ReduceUpperBound(m: nat, x: int)\n ensures Reduce(m, x) <= x\n{\n if m == 0 { // trivial\n assert Reduce(0, x) == x;\n }\n else {\n calc {\n Reduce(m, x);\n == // defn\n Reduce(m / 2, x + 1) - m;\n <= { ReduceUpperBound(m/2, x+1); }\n Reduce(m / 2, x + 1) - m + x + 1 - Reduce(m / 2, x + 1);\n == // arith\n x - m + 1;\n <= { assert m >= 1; }\n x;\n }\n }\n}\n\n// 5.5.1\nlemma {:induction false} ReduceLowerBound(m: nat, x: int)\n ensures x - 2 * m <= Reduce(m, x)\n{\n if m == 0 { // trivial\n assert x - 2 * 0 <= x == Reduce(0, x);\n }\n else {\n calc {\n Reduce(m, x);\n == // defn\n Reduce(m / 2, x + 1) - m;\n >= { ReduceLowerBound(m/2, x+1);\n assert x + 1 - m <= Reduce(m / 2, x + 1); }\n x + 1 - 2 * m;\n > // arith\n x - 2 * m;\n }\n }\n}\n\n\n// ------------------------------------------------------------------------------\n// ----- Expr Eval --------------------------------------------------------------\n// ------------------------------------------------------------------------------\n\n// 5.8.0\n\ndatatype Expr = Const(nat)\n | Var(string)\n | Node(op: Op, args: List)\n\ndatatype Op = Mul | Add\ndatatype List = Nil | Cons(head: T, tail: List)\n\nfunction Eval(e: Expr, env: map): nat\n{\n match e {\n case Const(c) => c\n case Var(s) => if s in env then env[s] else 0\n case Node(op, args) => EvalList(op, args, env)\n }\n}\n\n// intro'd in 5.8.1\nfunction Unit(op: Op): nat {\n match op case Add => 0 case Mul => 1\n}\n\nfunction EvalList(op: Op, args: List, env: map): nat\n decreases args, op, env\n{\n match args {\n case Nil => Unit(op)\n case Cons(e, tail) =>\n var v0, v1 := Eval(e, env), EvalList(op, tail, env);\n match op\n case Add => v0 + v1\n case Mul => v0 * v1\n }\n}\n\nfunction Substitute(e: Expr, n: string, c: nat): Expr\n{\n match e\n case Const(_) => e\n case Var(s) => if s == n then Const(c) else e\n case Node(op, args) => Node(op, SubstituteList(args, n, c))\n}\n\nfunction SubstituteList(es: List, n: string, c: nat): List\n{\n match es\n case Nil => Nil\n case Cons(head, tail) => Cons(Substitute(head, n, c), SubstituteList(tail, n, c))\n}\n\nlemma {:induction false} EvalSubstituteCorrect(e: Expr, n: string, c: nat, env: map)\n ensures Eval(Substitute(e, n, c), env) == Eval(e, env[n := c])\n{\n match e\n case Const(_) => {}\n case Var(s) => {\n calc {\n Eval(Substitute(e, n, c), env);\n Eval(if s == n then Const(c) else e, env);\n if s == n then Eval(Const(c), env) else Eval(e, env);\n if s == n then c else Eval(e, env);\n if s == n then c else Eval(e, env[n := c]);\n if s == n then Eval(e, env[n := c]) else Eval(e, env[n := c]);\n Eval(e, env[n := c]);\n }\n }\n case Node(op, args) => {\n EvalSubstituteListCorrect(op, args, n, c, env);\n }\n}\n\nlemma {:induction false} EvalSubstituteListCorrect(op: Op, args: List, n: string, c: nat, env: map)\n ensures EvalList(op, SubstituteList(args, n, c), env) == EvalList(op, args, env[n := c])\n decreases args, op, n, c, env\n{\n match args\n case Nil => {}\n case Cons(head, tail) => {\n // Ex 5.15\n calc {\n EvalList(op, SubstituteList(args, n, c), env);\n == // defn SubstituteList\n EvalList(op, Cons(Substitute(head, n, c), SubstituteList(tail, n, c)), env);\n == // unfold defn EvalList\n EvalList(op, Cons(Substitute(head, n, c), SubstituteList(tail, n, c)), env);\n ==\n (match op\n case Add => Eval(Substitute(head, n, c), env) + EvalList(op, SubstituteList(tail, n, c), env)\n case Mul => Eval(Substitute(head, n, c), env) * EvalList(op, SubstituteList(tail, n, c), env));\n == { EvalSubstituteCorrect(head, n, c, env); }\n (match op\n case Add => Eval(head, env[n := c]) + EvalList(op, SubstituteList(tail, n, c), env)\n case Mul => Eval(head, env[n := c]) * EvalList(op, SubstituteList(tail, n, c), env));\n == { EvalSubstituteListCorrect(op, tail, n, c, env); }\n (match op\n case Add => Eval(head, env[n := c]) + EvalList(op, tail, env[n := c])\n case Mul => Eval(head, env[n := c]) * EvalList(op, tail, env[n := c]));\n == // fold defn Eval/EvalList\n EvalList(op, args, env[n := c]);\n }\n }\n}\n\n// Ex 5.16\nlemma EvalEnv(e: Expr, n: string, env: map)\n requires n in env.Keys\n ensures Eval(e, env) == Eval(Substitute(e, n, env[n]), env)\n{\n match e\n case Const(_) => {}\n case Var(s) => {}\n case Node(op, args) => {\n match args\n case Nil => {}\n case Cons(head, tail) => { EvalEnv(head, n, env); EvalEnvList(op, tail, n, env); }\n }\n}\n\nlemma EvalEnvList(op: Op, es: List, n: string, env: map)\n decreases es, op, n, env\n requires n in env.Keys\n ensures EvalList(op, es, env) == EvalList(op, SubstituteList(es, n, env[n]), env)\n{\n match es\n case Nil => {}\n case Cons(head, tail) => { EvalEnv(head, n, env); EvalEnvList(op, tail, n, env); }\n}\n\n// Ex 5.17\nlemma EvalEnvDefault(e: Expr, n: string, env: map)\n requires n !in env.Keys\n ensures Eval(e, env) == Eval(Substitute(e, n, 0), env)\n{\n match e\n case Const(_) => {}\n case Var(s) => {}\n case Node(op, args) => {\n calc {\n Eval(Substitute(e, n, 0), env);\n EvalList(op, SubstituteList(args, n, 0), env);\n == { EvalEnvDefaultList(op, args, n, env); }\n EvalList(op, args, env);\n Eval(e, env);\n }\n }\n}\n\nlemma EvalEnvDefaultList(op: Op, args: List, n: string, env: map)\n decreases args, op, n, env\n requires n !in env.Keys\n ensures EvalList(op, args, env) == EvalList(op, SubstituteList(args, n, 0), env)\n{\n match args\n case Nil => {}\n case Cons(head, tail) => { EvalEnvDefault(head, n, env); EvalEnvDefaultList(op, tail, n, env); }\n}\n\n// Ex 5.18\nlemma SubstituteIdempotent(e: Expr, n: string, c: nat)\n ensures Substitute(Substitute(e, n, c), n, c) == Substitute(e, n, c)\n{\n match e\n case Const(_) => {}\n case Var(_) => {}\n case Node(op, args) => { SubstituteListIdempotent(args, n, c); }\n}\n\nlemma SubstituteListIdempotent(args: List, n: string, c: nat)\n ensures SubstituteList(SubstituteList(args, n, c), n, c) == SubstituteList(args, n, c)\n{\n match args\n case Nil => {}\n case Cons(head, tail) => { SubstituteIdempotent(head, n, c); SubstituteListIdempotent(tail, n, c); }\n}\n\n// 5.8.1\n// Optimization is correct\n\nfunction Optimize(e: Expr): Expr\n // intrinsic\n // ensures forall env: map :: Eval(Optimize(e), env) == Eval(e, env)\n{\n if e.Node? then\n var args := OptimizeAndFilter(e.args, Unit(e.op));\n Shorten(e.op, args)\n else\n e\n}\n\nlemma OptimizeCorrect(e: Expr, env: map)\n ensures Eval(Optimize(e), env) == Eval(e, env)\n{\n if e.Node? {\n OptimizeAndFilterCorrect(e.args, e.op, env); \n ShortenCorrect(OptimizeAndFilter(e.args, Unit(e.op)), e.op, env); \n // calc {\n // Eval(Optimize(e), env);\n // == // defn Optimize\n // Eval(Shorten(e.op, OptimizeAndFilter(e.args, Unit(e.op))), env);\n // == { ShortenCorrect(OptimizeAndFilter(e.args, Unit(e.op)), e.op, env); }\n // Eval(Node(e.op, OptimizeAndFilter(e.args, Unit(e.op))), env);\n // == { OptimizeAndFilterCorrect(e.args, e.op, env); }\n // Eval(e, env);\n // }\n }\n}\n\nfunction OptimizeAndFilter(args: List, u: nat): List\n // intrinsic\n // ensures forall op: Op, env: map :: u == Unit(op) ==> Eval(Node(op, OptimizeAndFilter(args, u)), env) == Eval(Node(op, args), env)\n{\n match args\n case Nil => Nil\n case Cons(head, tail) =>\n var hd, tl := Optimize(head), OptimizeAndFilter(tail, u);\n if hd == Const(u) then tl else Cons(hd, tl)\n}\n\nlemma OptimizeAndFilterCorrect(args: List, op: Op, env: map)\n ensures Eval(Node(op, OptimizeAndFilter(args, Unit(op))), env) == Eval(Node(op, args), env)\n{\n match args\n case Nil => {}\n case Cons(head, tail) => {\n OptimizeCorrect(head, env);\n OptimizeAndFilterCorrect(tail, op, env);\n // var hd, tl := Optimize(head), OptimizeAndFilter(tail, Unit(op));\n // var u := Unit(op);\n // if hd == Const(u) {\n // calc {\n // Eval(Node(op, OptimizeAndFilter(args, u)), env);\n // ==\n // EvalList(op, OptimizeAndFilter(args, u), env);\n // == { assert OptimizeAndFilter(args, u) == tl; }\n // EvalList(op, tl, env);\n // ==\n // Eval(Node(op, tl), env);\n // == { EvalListUnitHead(hd, tl, op, env); }\n // Eval(Node(op, Cons(hd, tl)), env);\n // == { OptimizeCorrect(head, env); OptimizeAndFilterCorrect(tail, op, env); }\n // Eval(Node(op, args), env);\n // }\n // } else {\n // calc {\n // Eval(Node(op, OptimizeAndFilter(args, u)), env);\n // ==\n // EvalList(op, OptimizeAndFilter(args, u), env);\n // == { assert OptimizeAndFilter(args, u) == Cons(hd, tl); }\n // EvalList(op, Cons(hd, tl), env);\n // ==\n // Eval(Node(op, Cons(hd, tl)), env);\n // == { OptimizeCorrect(head, env); OptimizeAndFilterCorrect(tail, op, env); }\n // Eval(Node(op, args), env);\n // }\n // }\n }\n}\n\nlemma EvalListUnitHead(head: Expr, tail: List, op: Op, env: map)\n ensures Eval(head, env) == Unit(op) ==> EvalList(op, Cons(head, tail), env) == EvalList(op, tail, env)\n{\n // Note: verifier can prove the whole lemma with empty body!\n var ehead, etail := Eval(head, env), EvalList(op, tail, env);\n if ehead == Unit(op) {\n match op\n case Add => {\n calc {\n EvalList(op, Cons(head, tail), env);\n == // defn EvalList\n ehead + etail;\n == // { assert ehead == Unit(Add); assert Unit(Add) == 0; }\n etail;\n }\n }\n case Mul => {\n calc {\n EvalList(op, Cons(head, tail), env);\n == // defn EvalList\n ehead * etail;\n == // { assert ehead == 1; }\n etail;\n }\n }\n }\n}\n\nfunction Shorten(op: Op, args: List): Expr {\n match args\n case Nil => Const(Unit(op))\n // shorten the singleton list\n case Cons(head, Nil) => head\n // reduce units from the head\n case _ => Node(op, args)\n}\n\nlemma ShortenCorrect(args: List, op: Op, env: map)\n ensures Eval(Shorten(op, args), env) == Eval(Node(op, args), env)\n{\n match args\n case Nil => {}\n case Cons(head, Nil) => {\n calc {\n Eval(Node(op, args), env);\n EvalList(op, Cons(head, Nil), env);\n Eval(head, env);\n /* Eval(Shorten(op, Cons(head, Nil)), env); */\n /* Eval(Shorten(op, args), env); */\n }\n }\n case _ => {}\n}\n", "hints_removed": "function More(x: int): int {\n if x <= 0 then 1 else More(x - 2) + 3\n}\n\nlemma {:induction false} Increasing(x: int)\n ensures x < More(x)\n{\n if x <= 0 {}\n else {\n // x < More(x) <=> x < More(x - 2) + 3\n // <=> x - 3 < More(x - 2)\n // Increasing(x - 2) ==> x - 2 < More(x - 2)\n // ==> x - 3 < x - 2 < More(x - 2)\n Increasing(x - 2);\n }\n}\n\nmethod ExampleLemmaUse(a: int) {\n var b := More(a);\n Increasing(a);\n var c := More(b);\n Increasing(b);\n}\n\n// Ex 5.0\nmethod ExampleLemmaUse50(a: int) {\n Increasing(a);\n var b := More(a);\n var c := More(b);\n if a < 1000 {\n Increasing(b);\n }\n}\n\n// Ex 5.1\nmethod ExampleLemmaUse51(a: int) {\n Increasing(a);\n var b := More(a);\n Increasing(b);\n b := More(b);\n if a < 1000 {\n // Increasing(More(a));\n }\n}\n\n// Ex 5.6\nfunction Ack(m: nat, n: nat): nat {\n if m == 0 then\n n + 1\n else if n == 0 then\n Ack(m - 1, 1)\n else\n Ack(m - 1, Ack(m, n - 1))\n}\n\nlemma {:induction false} Ack1n(m: nat, n: nat)\n requires m == 1\n ensures Ack(m, n) == n + 2\n{\n if n == 0 {\n calc {\n Ack(m, n);\n ==\n Ack(m - 1, 1);\n ==\n Ack(0, 1);\n ==\n 1 + 1;\n ==\n 2;\n ==\n n + 2;\n }\n }\n else {\n calc {\n Ack(m, n);\n == // defn\n Ack(m - 1, Ack(m, n - 1));\n == // subs m := 1\n Ack(0, Ack(1, n - 1));\n == { Ack1n(1, n - 1); }\n Ack(0, (n - 1) + 2);\n == // arith\n Ack(0, n + 1);\n == // arith\n (n + 1) + 1;\n == // arith\n n + 2;\n }\n }\n}\n\n// Ex 5.5\nfunction Reduce(m: nat, x: int): int {\n if m == 0 then x else Reduce(m / 2, x + 1) - m\n}\n\nlemma {:induction false} ReduceUpperBound(m: nat, x: int)\n ensures Reduce(m, x) <= x\n{\n if m == 0 { // trivial\n }\n else {\n calc {\n Reduce(m, x);\n == // defn\n Reduce(m / 2, x + 1) - m;\n <= { ReduceUpperBound(m/2, x+1); }\n Reduce(m / 2, x + 1) - m + x + 1 - Reduce(m / 2, x + 1);\n == // arith\n x - m + 1;\n <= { assert m >= 1; }\n x;\n }\n }\n}\n\n// 5.5.1\nlemma {:induction false} ReduceLowerBound(m: nat, x: int)\n ensures x - 2 * m <= Reduce(m, x)\n{\n if m == 0 { // trivial\n }\n else {\n calc {\n Reduce(m, x);\n == // defn\n Reduce(m / 2, x + 1) - m;\n >= { ReduceLowerBound(m/2, x+1);\n x + 1 - 2 * m;\n > // arith\n x - 2 * m;\n }\n }\n}\n\n\n// ------------------------------------------------------------------------------\n// ----- Expr Eval --------------------------------------------------------------\n// ------------------------------------------------------------------------------\n\n// 5.8.0\n\ndatatype Expr = Const(nat)\n | Var(string)\n | Node(op: Op, args: List)\n\ndatatype Op = Mul | Add\ndatatype List = Nil | Cons(head: T, tail: List)\n\nfunction Eval(e: Expr, env: map): nat\n{\n match e {\n case Const(c) => c\n case Var(s) => if s in env then env[s] else 0\n case Node(op, args) => EvalList(op, args, env)\n }\n}\n\n// intro'd in 5.8.1\nfunction Unit(op: Op): nat {\n match op case Add => 0 case Mul => 1\n}\n\nfunction EvalList(op: Op, args: List, env: map): nat\n{\n match args {\n case Nil => Unit(op)\n case Cons(e, tail) =>\n var v0, v1 := Eval(e, env), EvalList(op, tail, env);\n match op\n case Add => v0 + v1\n case Mul => v0 * v1\n }\n}\n\nfunction Substitute(e: Expr, n: string, c: nat): Expr\n{\n match e\n case Const(_) => e\n case Var(s) => if s == n then Const(c) else e\n case Node(op, args) => Node(op, SubstituteList(args, n, c))\n}\n\nfunction SubstituteList(es: List, n: string, c: nat): List\n{\n match es\n case Nil => Nil\n case Cons(head, tail) => Cons(Substitute(head, n, c), SubstituteList(tail, n, c))\n}\n\nlemma {:induction false} EvalSubstituteCorrect(e: Expr, n: string, c: nat, env: map)\n ensures Eval(Substitute(e, n, c), env) == Eval(e, env[n := c])\n{\n match e\n case Const(_) => {}\n case Var(s) => {\n calc {\n Eval(Substitute(e, n, c), env);\n Eval(if s == n then Const(c) else e, env);\n if s == n then Eval(Const(c), env) else Eval(e, env);\n if s == n then c else Eval(e, env);\n if s == n then c else Eval(e, env[n := c]);\n if s == n then Eval(e, env[n := c]) else Eval(e, env[n := c]);\n Eval(e, env[n := c]);\n }\n }\n case Node(op, args) => {\n EvalSubstituteListCorrect(op, args, n, c, env);\n }\n}\n\nlemma {:induction false} EvalSubstituteListCorrect(op: Op, args: List, n: string, c: nat, env: map)\n ensures EvalList(op, SubstituteList(args, n, c), env) == EvalList(op, args, env[n := c])\n{\n match args\n case Nil => {}\n case Cons(head, tail) => {\n // Ex 5.15\n calc {\n EvalList(op, SubstituteList(args, n, c), env);\n == // defn SubstituteList\n EvalList(op, Cons(Substitute(head, n, c), SubstituteList(tail, n, c)), env);\n == // unfold defn EvalList\n EvalList(op, Cons(Substitute(head, n, c), SubstituteList(tail, n, c)), env);\n ==\n (match op\n case Add => Eval(Substitute(head, n, c), env) + EvalList(op, SubstituteList(tail, n, c), env)\n case Mul => Eval(Substitute(head, n, c), env) * EvalList(op, SubstituteList(tail, n, c), env));\n == { EvalSubstituteCorrect(head, n, c, env); }\n (match op\n case Add => Eval(head, env[n := c]) + EvalList(op, SubstituteList(tail, n, c), env)\n case Mul => Eval(head, env[n := c]) * EvalList(op, SubstituteList(tail, n, c), env));\n == { EvalSubstituteListCorrect(op, tail, n, c, env); }\n (match op\n case Add => Eval(head, env[n := c]) + EvalList(op, tail, env[n := c])\n case Mul => Eval(head, env[n := c]) * EvalList(op, tail, env[n := c]));\n == // fold defn Eval/EvalList\n EvalList(op, args, env[n := c]);\n }\n }\n}\n\n// Ex 5.16\nlemma EvalEnv(e: Expr, n: string, env: map)\n requires n in env.Keys\n ensures Eval(e, env) == Eval(Substitute(e, n, env[n]), env)\n{\n match e\n case Const(_) => {}\n case Var(s) => {}\n case Node(op, args) => {\n match args\n case Nil => {}\n case Cons(head, tail) => { EvalEnv(head, n, env); EvalEnvList(op, tail, n, env); }\n }\n}\n\nlemma EvalEnvList(op: Op, es: List, n: string, env: map)\n requires n in env.Keys\n ensures EvalList(op, es, env) == EvalList(op, SubstituteList(es, n, env[n]), env)\n{\n match es\n case Nil => {}\n case Cons(head, tail) => { EvalEnv(head, n, env); EvalEnvList(op, tail, n, env); }\n}\n\n// Ex 5.17\nlemma EvalEnvDefault(e: Expr, n: string, env: map)\n requires n !in env.Keys\n ensures Eval(e, env) == Eval(Substitute(e, n, 0), env)\n{\n match e\n case Const(_) => {}\n case Var(s) => {}\n case Node(op, args) => {\n calc {\n Eval(Substitute(e, n, 0), env);\n EvalList(op, SubstituteList(args, n, 0), env);\n == { EvalEnvDefaultList(op, args, n, env); }\n EvalList(op, args, env);\n Eval(e, env);\n }\n }\n}\n\nlemma EvalEnvDefaultList(op: Op, args: List, n: string, env: map)\n requires n !in env.Keys\n ensures EvalList(op, args, env) == EvalList(op, SubstituteList(args, n, 0), env)\n{\n match args\n case Nil => {}\n case Cons(head, tail) => { EvalEnvDefault(head, n, env); EvalEnvDefaultList(op, tail, n, env); }\n}\n\n// Ex 5.18\nlemma SubstituteIdempotent(e: Expr, n: string, c: nat)\n ensures Substitute(Substitute(e, n, c), n, c) == Substitute(e, n, c)\n{\n match e\n case Const(_) => {}\n case Var(_) => {}\n case Node(op, args) => { SubstituteListIdempotent(args, n, c); }\n}\n\nlemma SubstituteListIdempotent(args: List, n: string, c: nat)\n ensures SubstituteList(SubstituteList(args, n, c), n, c) == SubstituteList(args, n, c)\n{\n match args\n case Nil => {}\n case Cons(head, tail) => { SubstituteIdempotent(head, n, c); SubstituteListIdempotent(tail, n, c); }\n}\n\n// 5.8.1\n// Optimization is correct\n\nfunction Optimize(e: Expr): Expr\n // intrinsic\n // ensures forall env: map :: Eval(Optimize(e), env) == Eval(e, env)\n{\n if e.Node? then\n var args := OptimizeAndFilter(e.args, Unit(e.op));\n Shorten(e.op, args)\n else\n e\n}\n\nlemma OptimizeCorrect(e: Expr, env: map)\n ensures Eval(Optimize(e), env) == Eval(e, env)\n{\n if e.Node? {\n OptimizeAndFilterCorrect(e.args, e.op, env); \n ShortenCorrect(OptimizeAndFilter(e.args, Unit(e.op)), e.op, env); \n // calc {\n // Eval(Optimize(e), env);\n // == // defn Optimize\n // Eval(Shorten(e.op, OptimizeAndFilter(e.args, Unit(e.op))), env);\n // == { ShortenCorrect(OptimizeAndFilter(e.args, Unit(e.op)), e.op, env); }\n // Eval(Node(e.op, OptimizeAndFilter(e.args, Unit(e.op))), env);\n // == { OptimizeAndFilterCorrect(e.args, e.op, env); }\n // Eval(e, env);\n // }\n }\n}\n\nfunction OptimizeAndFilter(args: List, u: nat): List\n // intrinsic\n // ensures forall op: Op, env: map :: u == Unit(op) ==> Eval(Node(op, OptimizeAndFilter(args, u)), env) == Eval(Node(op, args), env)\n{\n match args\n case Nil => Nil\n case Cons(head, tail) =>\n var hd, tl := Optimize(head), OptimizeAndFilter(tail, u);\n if hd == Const(u) then tl else Cons(hd, tl)\n}\n\nlemma OptimizeAndFilterCorrect(args: List, op: Op, env: map)\n ensures Eval(Node(op, OptimizeAndFilter(args, Unit(op))), env) == Eval(Node(op, args), env)\n{\n match args\n case Nil => {}\n case Cons(head, tail) => {\n OptimizeCorrect(head, env);\n OptimizeAndFilterCorrect(tail, op, env);\n // var hd, tl := Optimize(head), OptimizeAndFilter(tail, Unit(op));\n // var u := Unit(op);\n // if hd == Const(u) {\n // calc {\n // Eval(Node(op, OptimizeAndFilter(args, u)), env);\n // ==\n // EvalList(op, OptimizeAndFilter(args, u), env);\n // == { assert OptimizeAndFilter(args, u) == tl; }\n // EvalList(op, tl, env);\n // ==\n // Eval(Node(op, tl), env);\n // == { EvalListUnitHead(hd, tl, op, env); }\n // Eval(Node(op, Cons(hd, tl)), env);\n // == { OptimizeCorrect(head, env); OptimizeAndFilterCorrect(tail, op, env); }\n // Eval(Node(op, args), env);\n // }\n // } else {\n // calc {\n // Eval(Node(op, OptimizeAndFilter(args, u)), env);\n // ==\n // EvalList(op, OptimizeAndFilter(args, u), env);\n // == { assert OptimizeAndFilter(args, u) == Cons(hd, tl); }\n // EvalList(op, Cons(hd, tl), env);\n // ==\n // Eval(Node(op, Cons(hd, tl)), env);\n // == { OptimizeCorrect(head, env); OptimizeAndFilterCorrect(tail, op, env); }\n // Eval(Node(op, args), env);\n // }\n // }\n }\n}\n\nlemma EvalListUnitHead(head: Expr, tail: List, op: Op, env: map)\n ensures Eval(head, env) == Unit(op) ==> EvalList(op, Cons(head, tail), env) == EvalList(op, tail, env)\n{\n // Note: verifier can prove the whole lemma with empty body!\n var ehead, etail := Eval(head, env), EvalList(op, tail, env);\n if ehead == Unit(op) {\n match op\n case Add => {\n calc {\n EvalList(op, Cons(head, tail), env);\n == // defn EvalList\n ehead + etail;\n == // { assert ehead == Unit(Add); assert Unit(Add) == 0; }\n etail;\n }\n }\n case Mul => {\n calc {\n EvalList(op, Cons(head, tail), env);\n == // defn EvalList\n ehead * etail;\n == // { assert ehead == 1; }\n etail;\n }\n }\n }\n}\n\nfunction Shorten(op: Op, args: List): Expr {\n match args\n case Nil => Const(Unit(op))\n // shorten the singleton list\n case Cons(head, Nil) => head\n // reduce units from the head\n case _ => Node(op, args)\n}\n\nlemma ShortenCorrect(args: List, op: Op, env: map)\n ensures Eval(Shorten(op, args), env) == Eval(Node(op, args), env)\n{\n match args\n case Nil => {}\n case Cons(head, Nil) => {\n calc {\n Eval(Node(op, args), env);\n EvalList(op, Cons(head, Nil), env);\n Eval(head, env);\n /* Eval(Shorten(op, Cons(head, Nil)), env); */\n /* Eval(Shorten(op, args), env); */\n }\n }\n case _ => {}\n}\n" }, { "test_ID": "751", "test_file": "stunning-palm-tree_tmp_tmpr84c2iwh_ch8.dfy", "ground_truth": "// Ch. 8: Sorting\n\ndatatype List = Nil | Cons(head: T, tail: List)\n\nfunction Length(xs: List): int\n ensures Length(xs) >= 0\n{\n match xs\n case Nil => 0\n case Cons(_, tl) => 1 + Length(tl)\n}\n\nfunction At(xs: List, i: nat): T\n requires i < Length(xs)\n{\n if i == 0 then xs.head else At(xs.tail, i - 1)\n}\n\nghost predicate Ordered(xs: List) {\n match xs\n case Nil => true\n case Cons(_, Nil) => true\n case Cons(hd0, Cons(hd1, _)) => (hd0 <= hd1) && Ordered(xs.tail)\n}\n\nlemma AllOrdered(xs: List, i: nat, j: nat)\n requires Ordered(xs) && i <= j < Length(xs)\n ensures At(xs, i) <= At(xs, j)\n{\n if i != 0 {\n AllOrdered(xs.tail, i - 1, j - 1);\n } else if i == j {\n assert i == 0 && j == 0;\n } else {\n assert i == 0 && i < j;\n assert xs.head <= xs.tail.head;\n AllOrdered(xs.tail, 0, j - 1);\n }\n}\n\n// Ex. 8.0 generalize fron int to T by: T(==)\nghost function Count(xs: List, p: T): int\n ensures Count(xs, p) >= 0\n{\n match xs\n case Nil => 0\n case Cons(hd, tl) => (if hd == p then 1 else 0) + Count(tl, p)\n}\n\nghost function Project(xs: List, p: T): List {\n match xs\n case Nil => Nil\n case Cons(hd, tl) => if hd == p then Cons(hd, Project(tl, p)) else Project(tl, p)\n}\n\n// Ex 8.1\nlemma {:induction false} CountProject(xs: List, ys: List, p: T)\n requires Project(xs, p) == Project(ys, p)\n ensures Count(xs, p) == Count(ys, p)\n{\n match xs\n case Nil => {\n match ys\n case Nil => {}\n case Cons(yhd, ytl) => {\n assert Count(xs, p) == 0;\n assert Project(xs, p) == Nil;\n assert Project(ys, p) == Nil;\n assert yhd != p;\n CountProject(xs, ytl, p);\n }\n }\n case Cons(xhd, xtl) => {\n match ys\n case Nil => {\n assert Count(ys, p) == 0;\n CountProject(xtl, ys, p);\n }\n case Cons(yhd, ytl) => {\n if xhd == p && yhd == p {\n assert Count(xs, p) == 1 + Count(xtl, p);\n assert Count(ys, p) == 1 + Count(ytl, p);\n assert Project(xtl, p) == Project(ytl, p);\n CountProject(xtl, ytl, p);\n } else if xhd != p && yhd == p {\n assert Count(xs, p) == Count(xtl, p);\n assert Count(ys, p) == 1 + Count(ytl, p);\n CountProject(xtl, ys, p);\n } else if xhd == p && yhd != p {\n assert Count(ys, p) == Count(ytl, p);\n assert Count(xs, p) == 1 + Count(xtl, p);\n CountProject(xs, ytl, p);\n } else {\n CountProject(xtl, ytl, p);\n }\n }\n }\n}\n\nfunction InsertionSort(xs: List): List\n{\n match xs\n case Nil => Nil\n case Cons(x, rest) => Insert(x, InsertionSort(rest))\n}\n\nfunction Insert(x: int, xs: List): List\n{\n match xs\n case Nil => Cons(x, Nil)\n case Cons(hd, tl) => if x < hd then Cons(x, xs) else Cons(hd, Insert(x, tl))\n}\n\nlemma InsertionSortOrdered(xs: List)\n ensures Ordered(InsertionSort(xs))\n{\n match xs\n case Nil =>\n case Cons(hd, tl) => {\n InsertionSortOrdered(tl);\n InsertOrdered(hd, InsertionSort(tl));\n }\n}\n\nlemma InsertOrdered(y: int, xs: List)\n requires Ordered(xs)\n ensures Ordered(Insert(y, xs))\n{\n match xs\n case Nil =>\n case Cons(hd, tl) => {\n if y < hd {\n assert Ordered(Cons(y, xs)); \n } else {\n InsertOrdered(y, tl);\n assert Ordered(Cons(hd, Insert(y, tl))); \n }\n }\n}\n\nlemma InsertionSortSameElements(xs: List, p: int)\n ensures Project(xs, p) == Project(InsertionSort(xs), p)\n{\n match xs\n case Nil =>\n case Cons(hd, tl) => {\n InsertSameElements(hd, InsertionSort(tl), p);\n }\n}\n\nlemma InsertSameElements(y: int, xs: List, p: int)\n ensures Project(Cons(y, xs), p) == Project(Insert(y, xs), p)\n{}\n", "hints_removed": "// Ch. 8: Sorting\n\ndatatype List = Nil | Cons(head: T, tail: List)\n\nfunction Length(xs: List): int\n ensures Length(xs) >= 0\n{\n match xs\n case Nil => 0\n case Cons(_, tl) => 1 + Length(tl)\n}\n\nfunction At(xs: List, i: nat): T\n requires i < Length(xs)\n{\n if i == 0 then xs.head else At(xs.tail, i - 1)\n}\n\nghost predicate Ordered(xs: List) {\n match xs\n case Nil => true\n case Cons(_, Nil) => true\n case Cons(hd0, Cons(hd1, _)) => (hd0 <= hd1) && Ordered(xs.tail)\n}\n\nlemma AllOrdered(xs: List, i: nat, j: nat)\n requires Ordered(xs) && i <= j < Length(xs)\n ensures At(xs, i) <= At(xs, j)\n{\n if i != 0 {\n AllOrdered(xs.tail, i - 1, j - 1);\n } else if i == j {\n } else {\n AllOrdered(xs.tail, 0, j - 1);\n }\n}\n\n// Ex. 8.0 generalize fron int to T by: T(==)\nghost function Count(xs: List, p: T): int\n ensures Count(xs, p) >= 0\n{\n match xs\n case Nil => 0\n case Cons(hd, tl) => (if hd == p then 1 else 0) + Count(tl, p)\n}\n\nghost function Project(xs: List, p: T): List {\n match xs\n case Nil => Nil\n case Cons(hd, tl) => if hd == p then Cons(hd, Project(tl, p)) else Project(tl, p)\n}\n\n// Ex 8.1\nlemma {:induction false} CountProject(xs: List, ys: List, p: T)\n requires Project(xs, p) == Project(ys, p)\n ensures Count(xs, p) == Count(ys, p)\n{\n match xs\n case Nil => {\n match ys\n case Nil => {}\n case Cons(yhd, ytl) => {\n CountProject(xs, ytl, p);\n }\n }\n case Cons(xhd, xtl) => {\n match ys\n case Nil => {\n CountProject(xtl, ys, p);\n }\n case Cons(yhd, ytl) => {\n if xhd == p && yhd == p {\n CountProject(xtl, ytl, p);\n } else if xhd != p && yhd == p {\n CountProject(xtl, ys, p);\n } else if xhd == p && yhd != p {\n CountProject(xs, ytl, p);\n } else {\n CountProject(xtl, ytl, p);\n }\n }\n }\n}\n\nfunction InsertionSort(xs: List): List\n{\n match xs\n case Nil => Nil\n case Cons(x, rest) => Insert(x, InsertionSort(rest))\n}\n\nfunction Insert(x: int, xs: List): List\n{\n match xs\n case Nil => Cons(x, Nil)\n case Cons(hd, tl) => if x < hd then Cons(x, xs) else Cons(hd, Insert(x, tl))\n}\n\nlemma InsertionSortOrdered(xs: List)\n ensures Ordered(InsertionSort(xs))\n{\n match xs\n case Nil =>\n case Cons(hd, tl) => {\n InsertionSortOrdered(tl);\n InsertOrdered(hd, InsertionSort(tl));\n }\n}\n\nlemma InsertOrdered(y: int, xs: List)\n requires Ordered(xs)\n ensures Ordered(Insert(y, xs))\n{\n match xs\n case Nil =>\n case Cons(hd, tl) => {\n if y < hd {\n } else {\n InsertOrdered(y, tl);\n }\n }\n}\n\nlemma InsertionSortSameElements(xs: List, p: int)\n ensures Project(xs, p) == Project(InsertionSort(xs), p)\n{\n match xs\n case Nil =>\n case Cons(hd, tl) => {\n InsertSameElements(hd, InsertionSort(tl), p);\n }\n}\n\nlemma InsertSameElements(y: int, xs: List, p: int)\n ensures Project(Cons(y, xs), p) == Project(Insert(y, xs), p)\n{}\n" }, { "test_ID": "752", "test_file": "summer-school-2020_tmp_tmpn8nf7zf0_chapter01_solutions_exercise04_solution.dfy", "ground_truth": "// Predicates\n\n// A common thing you'll want is a function with a boolean result.\nfunction AtLeastTwiceAsBigFunction(a:int, b:int) : bool\n{\n a >= 2*b\n}\n\n// It's so fantastically common that there's a shorthand for it: `predicate`.\npredicate AtLeastTwiceAsBigPredicate(a:int, b:int)\n{\n a >= 2*b\n}\n\nfunction Double(a:int) : int\n{\n 2 * a\n}\n\nlemma TheseTwoPredicatesAreEquivalent(x:int, y:int)\n{\n assert AtLeastTwiceAsBigFunction(x, y) == AtLeastTwiceAsBigPredicate(x, y);\n}\n\n// Add a precondition to make this lemma verify.\nlemma FourTimesIsPrettyBig(x:int)\n requires x>=0\n{\n assert AtLeastTwiceAsBigPredicate(Double(Double(x)), x);\n}\n\n", "hints_removed": "// Predicates\n\n// A common thing you'll want is a function with a boolean result.\nfunction AtLeastTwiceAsBigFunction(a:int, b:int) : bool\n{\n a >= 2*b\n}\n\n// It's so fantastically common that there's a shorthand for it: `predicate`.\npredicate AtLeastTwiceAsBigPredicate(a:int, b:int)\n{\n a >= 2*b\n}\n\nfunction Double(a:int) : int\n{\n 2 * a\n}\n\nlemma TheseTwoPredicatesAreEquivalent(x:int, y:int)\n{\n}\n\n// Add a precondition to make this lemma verify.\nlemma FourTimesIsPrettyBig(x:int)\n requires x>=0\n{\n}\n\n" }, { "test_ID": "753", "test_file": "summer-school-2020_tmp_tmpn8nf7zf0_chapter01_solutions_exercise11_solution.dfy", "ground_truth": "// Algebraic datatypes in their full glory. The include statement.\n\n// A struct is a product:\n// There are 3 HAlign instances, and 3 VAlign instances;\n// so there are 9 TextAlign instances (all combinations).\n// Note that it's okay to omit the parens for zero-element constructors.\ndatatype HAlign = Left | Center | Right\ndatatype VAlign = Top | Middle | Bottom\ndatatype TextAlign = TextAlign(hAlign:HAlign, vAlign:VAlign)\n\n// If you squint, you'll believe that unions are like\n// sums. There's one \"Top\", one \"Middle\", and one \"Bottom\"\n// element, so there are three things that are of type VAlign.\n\n// There are two instances of GraphicsAlign\ndatatype GraphicsAlign = Square | Round\n\n// So if we make another tagged-union (sum) of TextAlign or GraphicsAlign,\n// it has how many instances?\n// (That's the exercise, to answer that question. No Dafny required.)\ndatatype PageElement = Text(t:TextAlign) | Graphics(g:GraphicsAlign)\n\n// The answer is 11:\n// There are 9 TextAligns.\n// There are 2 GraphicsAligns.\n// So there are 11 PageElements.\n\n// Here's a *proof* for the HAlign type (to keep it simple):\nlemma NumPageElements()\n ensures exists eltSet:set :: |eltSet| == 3 // bound is tight\n ensures forall eltSet:set :: |eltSet| <= 3 // upper bound\n{\n var maxSet := { Left, Center, Right };\n\n // Prove the bound is tight.\n assert |maxSet| == 3;\n\n // Prove upper bound.\n forall eltSet:set\n ensures |eltSet| <= 3\n {\n // Prove eltSet <= maxSet\n forall elt | elt in eltSet ensures elt in maxSet {\n if elt.Left? { } // hint at a case analysis\n }\n\n // Cardinality relation should have been obvious to Dafny;\n // see comment on lemma below.\n subsetCardinality(eltSet, maxSet);\n }\n}\n\n// Dafny seems to be missing a heuristic to trigger this cardinality relation!\n// So I proved it. This should get fixed in dafny, or at least tucked into a\n// library! How embarrassing.\nlemma subsetCardinality(a:set, b:set)\n requires a <= b\n ensures |a| <= |b|\n{\n if a == {} {\n assert |a| <= |b|;\n } else {\n var e :| e in a;\n if e in b {\n subsetCardinality(a - {e}, b - {e});\n assert |a| <= |b|;\n } else {\n subsetCardinality(a - {e}, b);\n assert |a| <= |b|;\n }\n }\n}\n\n", "hints_removed": "// Algebraic datatypes in their full glory. The include statement.\n\n// A struct is a product:\n// There are 3 HAlign instances, and 3 VAlign instances;\n// so there are 9 TextAlign instances (all combinations).\n// Note that it's okay to omit the parens for zero-element constructors.\ndatatype HAlign = Left | Center | Right\ndatatype VAlign = Top | Middle | Bottom\ndatatype TextAlign = TextAlign(hAlign:HAlign, vAlign:VAlign)\n\n// If you squint, you'll believe that unions are like\n// sums. There's one \"Top\", one \"Middle\", and one \"Bottom\"\n// element, so there are three things that are of type VAlign.\n\n// There are two instances of GraphicsAlign\ndatatype GraphicsAlign = Square | Round\n\n// So if we make another tagged-union (sum) of TextAlign or GraphicsAlign,\n// it has how many instances?\n// (That's the exercise, to answer that question. No Dafny required.)\ndatatype PageElement = Text(t:TextAlign) | Graphics(g:GraphicsAlign)\n\n// The answer is 11:\n// There are 9 TextAligns.\n// There are 2 GraphicsAligns.\n// So there are 11 PageElements.\n\n// Here's a *proof* for the HAlign type (to keep it simple):\nlemma NumPageElements()\n ensures exists eltSet:set :: |eltSet| == 3 // bound is tight\n ensures forall eltSet:set :: |eltSet| <= 3 // upper bound\n{\n var maxSet := { Left, Center, Right };\n\n // Prove the bound is tight.\n\n // Prove upper bound.\n forall eltSet:set\n ensures |eltSet| <= 3\n {\n // Prove eltSet <= maxSet\n forall elt | elt in eltSet ensures elt in maxSet {\n if elt.Left? { } // hint at a case analysis\n }\n\n // Cardinality relation should have been obvious to Dafny;\n // see comment on lemma below.\n subsetCardinality(eltSet, maxSet);\n }\n}\n\n// Dafny seems to be missing a heuristic to trigger this cardinality relation!\n// So I proved it. This should get fixed in dafny, or at least tucked into a\n// library! How embarrassing.\nlemma subsetCardinality(a:set, b:set)\n requires a <= b\n ensures |a| <= |b|\n{\n if a == {} {\n } else {\n var e :| e in a;\n if e in b {\n subsetCardinality(a - {e}, b - {e});\n } else {\n subsetCardinality(a - {e}, b);\n }\n }\n}\n\n" }, { "test_ID": "754", "test_file": "summer-school-2020_tmp_tmpn8nf7zf0_chapter02_solutions_exercise01_solution.dfy", "ground_truth": "predicate divides(f:nat, i:nat)\n requires 1<=f\n{\n i % f == 0\n}\n\npredicate IsPrime(i:nat)\n{\n && 1 < i\n && forall f :: 1 < f < i ==> !divides(f, i)\n}\n\nmethod Main()\n{\n assert !IsPrime(0);\n assert !IsPrime(1);\n assert IsPrime(2);\n assert IsPrime(3);\n assert divides(2, 6);\n assert !IsPrime(6);\n assert IsPrime(7);\n assert divides(3, 9);\n assert !IsPrime(9);\n}\n\n", "hints_removed": "predicate divides(f:nat, i:nat)\n requires 1<=f\n{\n i % f == 0\n}\n\npredicate IsPrime(i:nat)\n{\n && 1 < i\n && forall f :: 1 < f < i ==> !divides(f, i)\n}\n\nmethod Main()\n{\n}\n\n" }, { "test_ID": "755", "test_file": "summer-school-2020_tmp_tmpn8nf7zf0_chapter02_solutions_exercise02_solution.dfy", "ground_truth": "predicate divides(f:nat, i:nat)\n requires 1<=f\n{\n i % f == 0\n}\n\npredicate IsPrime(i:nat)\n{\n && 1 !divides(f, i) )\n}\n\n// Convincing the proof to go through requires adding\n// a loop invariant and a triggering assert.\nmethod test_prime(i:nat) returns (result:bool)\n requires 1 !divides(g, i)\n {\n if i % f == 0 {\n // This assert is needed to witness that !IsPrime.\n // !IsPrime is !forall !divides, which rewrites to exists divides.\n // Dafny rarely triggers its way to a guess for an exists (apparently\n // it's tough for Z3), but mention a witness and Z3's happy.\n assert divides(f, i);\n return false;\n }\n f := f + 1;\n }\n return true;\n}\n\nmethod Main()\n{\n var a := test_prime(3);\n assert a;\n var b := test_prime(4);\n assert divides(2, 4);\n assert !b;\n var c := test_prime(5);\n assert c;\n}\n\n", "hints_removed": "predicate divides(f:nat, i:nat)\n requires 1<=f\n{\n i % f == 0\n}\n\npredicate IsPrime(i:nat)\n{\n && 1 !divides(f, i) )\n}\n\n// Convincing the proof to go through requires adding\n// a loop invariant and a triggering assert.\nmethod test_prime(i:nat) returns (result:bool)\n requires 1)\n{\n forall i :: 0 <= i < |s|-1 ==> s[i] <= s[i+1]\n}\n\npredicate SortSpec(input:seq, output:seq)\n{\n && IsSorted(output)\n && multiset(output) == multiset(input)\n}\n\n//lemma SequenceConcat(s:seq, pivot:int)\n// requires 0<=pivot<|s|\n// ensures s[..pivot] + s[pivot..] == s\n//{\n//}\n\nmethod merge_sort(input:seq) returns (output:seq)\n ensures SortSpec(input, output)\n{\n if |input| <= 1 {\n output := input;\n } else {\n var pivotIndex := |input| / 2;\n var left := input[..pivotIndex];\n var right := input[pivotIndex..];\n var leftSorted := left;\n leftSorted := merge_sort(left);\n var rightSorted := right;\n rightSorted := merge_sort(right);\n output := merge(leftSorted, rightSorted);\n assert left + right == input; // derived via calc\n// calc {\n// multiset(output);\n// multiset(leftSorted + rightSorted);\n// multiset(leftSorted) + multiset(rightSorted);\n// multiset(left) + multiset(right);\n// multiset(left + right);\n// { assert left + right == input; }\n// multiset(input);\n// }\n }\n}\n\nmethod merge(a:seq, b:seq) returns (output:seq)\n requires IsSorted(a)\n requires IsSorted(b)\n// ensures IsSorted(output)\n ensures SortSpec(a+b, output)\n //decreases |a|+|b|\n{\n var ai := 0;\n var bi := 0;\n output := [];\n while ai < |a| || bi < |b|\n invariant 0 <= ai <= |a|\n invariant 0 <= bi <= |b|\n invariant 0 < |output| && ai < |a| ==> output[|output|-1] <= a[ai]\n invariant 0 < |output| && bi < |b| ==> output[|output|-1] <= b[bi]\n invariant forall i :: 0 <= i < |output|-1 ==> output[i] <= output[i+1]\n invariant multiset(output) == multiset(a[..ai]) + multiset(b[..bi])\n decreases |a|-ai + |b|-bi\n {\n ghost var outputo := output;\n ghost var ao := ai;\n ghost var bo := bi;\n if ai == |a| || (bi < |b| && a[ai] > b[bi]) {\n output := output + [b[bi]];\n bi := bi + 1;\n assert b[bo..bi] == [b[bo]]; // discovered by calc\n } else {\n output := output + [a[ai]];\n ai := ai + 1;\n assert a[ao..ai] == [a[ao]]; // discovered by calc\n }\n assert a[..ai] == a[..ao] + a[ao..ai]; // discovered by calc\n assert b[..bi] == b[..bo] + b[bo..bi]; // discovered by calc\n// calc {\n// multiset(a[..ai]) + multiset(b[..bi]);\n// multiset(a[..ao] + a[ao..ai]) + multiset(b[..bo] + b[bo..bi]);\n// multiset(a[..ao]) + multiset(a[ao..ai]) + multiset(b[..bo]) + multiset(b[bo..bi]);\n// multiset(a[..ao]) + multiset(b[..bo]) + multiset(a[ao..ai]) + multiset(b[bo..bi]);\n// multiset(outputo) + multiset(a[ao..ai]) + multiset(b[bo..bi]);\n// multiset(output);\n// }\n }\n assert a == a[..ai]; // derived by calc\n assert b == b[..bi];\n// calc {\n// multiset(output);\n// multiset(a[..ai]) + multiset(b[..bi]);\n// multiset(a) + multiset(b);\n// multiset(a + b);\n// }\n}\n\nmethod fast_sort(input:seq) returns (output:seq)\n// ensures SortSpec(input, output)\n{\n output := [1, 2, 3];\n}\n\n", "hints_removed": "predicate IsSorted(s:seq)\n{\n forall i :: 0 <= i < |s|-1 ==> s[i] <= s[i+1]\n}\n\npredicate SortSpec(input:seq, output:seq)\n{\n && IsSorted(output)\n && multiset(output) == multiset(input)\n}\n\n//lemma SequenceConcat(s:seq, pivot:int)\n// requires 0<=pivot<|s|\n// ensures s[..pivot] + s[pivot..] == s\n//{\n//}\n\nmethod merge_sort(input:seq) returns (output:seq)\n ensures SortSpec(input, output)\n{\n if |input| <= 1 {\n output := input;\n } else {\n var pivotIndex := |input| / 2;\n var left := input[..pivotIndex];\n var right := input[pivotIndex..];\n var leftSorted := left;\n leftSorted := merge_sort(left);\n var rightSorted := right;\n rightSorted := merge_sort(right);\n output := merge(leftSorted, rightSorted);\n// calc {\n// multiset(output);\n// multiset(leftSorted + rightSorted);\n// multiset(leftSorted) + multiset(rightSorted);\n// multiset(left) + multiset(right);\n// multiset(left + right);\n// { assert left + right == input; }\n// multiset(input);\n// }\n }\n}\n\nmethod merge(a:seq, b:seq) returns (output:seq)\n requires IsSorted(a)\n requires IsSorted(b)\n// ensures IsSorted(output)\n ensures SortSpec(a+b, output)\n //decreases |a|+|b|\n{\n var ai := 0;\n var bi := 0;\n output := [];\n while ai < |a| || bi < |b|\n {\n ghost var outputo := output;\n ghost var ao := ai;\n ghost var bo := bi;\n if ai == |a| || (bi < |b| && a[ai] > b[bi]) {\n output := output + [b[bi]];\n bi := bi + 1;\n } else {\n output := output + [a[ai]];\n ai := ai + 1;\n }\n// calc {\n// multiset(a[..ai]) + multiset(b[..bi]);\n// multiset(a[..ao] + a[ao..ai]) + multiset(b[..bo] + b[bo..bi]);\n// multiset(a[..ao]) + multiset(a[ao..ai]) + multiset(b[..bo]) + multiset(b[bo..bi]);\n// multiset(a[..ao]) + multiset(b[..bo]) + multiset(a[ao..ai]) + multiset(b[bo..bi]);\n// multiset(outputo) + multiset(a[ao..ai]) + multiset(b[bo..bi]);\n// multiset(output);\n// }\n }\n// calc {\n// multiset(output);\n// multiset(a[..ai]) + multiset(b[..bi]);\n// multiset(a) + multiset(b);\n// multiset(a + b);\n// }\n}\n\nmethod fast_sort(input:seq) returns (output:seq)\n// ensures SortSpec(input, output)\n{\n output := [1, 2, 3];\n}\n\n" }, { "test_ID": "757", "test_file": "t1_MF_tmp_tmpi_sqie4j_exemplos_classes_parte1_contadorV1b.dfy", "ground_truth": "class Contador\n{\n var valor: int;\n\n //construtor an\u00f4nimo\n constructor ()\n ensures valor == 0\n {\n valor := 0;\n }\n\n //construtor com nome\n constructor Init(v:int)\n ensures valor == v\n {\n valor := v;\n }\n\n method Incrementa()\n modifies this\n ensures valor == old(valor) + 1\n {\n valor := valor + 1;\n }\n\n method Decrementa()\n modifies this\n ensures valor == old(valor) - 1\n {\n valor := valor -1 ;\n }\n\n method GetValor() returns (v:int)\n ensures v == valor\n {\n return valor;\n }\n}\n\nmethod Main()\n{\n var c := new Contador(); //cria um novo objeto no heap via construtor an\u00f4nimo\n var c2 := new Contador.Init(10); //cria um novo objeto no heap via construtor nomeado\n var v := c.GetValor();\n assert v == 0;\n var v2 := c2.GetValor();\n assert v2 == 10;\n c.Incrementa();\n v := c.GetValor();\n assert v == 1;\n c.Decrementa();\n v := c.GetValor();\n assert v == 0;\n\n}\n", "hints_removed": "class Contador\n{\n var valor: int;\n\n //construtor an\u00f4nimo\n constructor ()\n ensures valor == 0\n {\n valor := 0;\n }\n\n //construtor com nome\n constructor Init(v:int)\n ensures valor == v\n {\n valor := v;\n }\n\n method Incrementa()\n modifies this\n ensures valor == old(valor) + 1\n {\n valor := valor + 1;\n }\n\n method Decrementa()\n modifies this\n ensures valor == old(valor) - 1\n {\n valor := valor -1 ;\n }\n\n method GetValor() returns (v:int)\n ensures v == valor\n {\n return valor;\n }\n}\n\nmethod Main()\n{\n var c := new Contador(); //cria um novo objeto no heap via construtor an\u00f4nimo\n var c2 := new Contador.Init(10); //cria um novo objeto no heap via construtor nomeado\n var v := c.GetValor();\n var v2 := c2.GetValor();\n c.Incrementa();\n v := c.GetValor();\n c.Decrementa();\n v := c.GetValor();\n\n}\n" }, { "test_ID": "758", "test_file": "t1_MF_tmp_tmpi_sqie4j_exemplos_colecoes_arrays_ex4.dfy", "ground_truth": "function SomaAte(a:array, i:nat):nat\n requires 0 <= i <= a.Length\n reads a\n{\n if i == 0\n then 0\n else a[i-1] + SomaAte(a,i-1)\n}\n\nmethod Somatorio(a:array) returns (s:nat)\n ensures s == SomaAte(a,a.Length)\n{\n var i := 0;\n s := 0;\n while i < a.Length\n invariant 0 <= i && i <= a.Length\n invariant s == SomaAte(a,i)\n {\n s := s + a[i];\n i := i + 1;\n }\n}\n", "hints_removed": "function SomaAte(a:array, i:nat):nat\n requires 0 <= i <= a.Length\n reads a\n{\n if i == 0\n then 0\n else a[i-1] + SomaAte(a,i-1)\n}\n\nmethod Somatorio(a:array) returns (s:nat)\n ensures s == SomaAte(a,a.Length)\n{\n var i := 0;\n s := 0;\n while i < a.Length\n {\n s := s + a[i];\n i := i + 1;\n }\n}\n" }, { "test_ID": "759", "test_file": "t1_MF_tmp_tmpi_sqie4j_exemplos_colecoes_arrays_ex5.dfy", "ground_truth": "method Busca(a:array, x:T) returns (r:int)\n ensures 0 <= r ==> r < a.Length && a[r] == x\n ensures r < 0 ==> forall i :: 0 <= i < a.Length ==> a[i] != x\n{\n r :=0;\n while r < a.Length\n invariant 0 <= r <= a.Length\n invariant forall i :: 0 <= i < r ==> a[i] != x\n {\n if a[r]==x\n {\n return;\n }\n r := r + 1;\n }\n r := -1;\n}\n", "hints_removed": "method Busca(a:array, x:T) returns (r:int)\n ensures 0 <= r ==> r < a.Length && a[r] == x\n ensures r < 0 ==> forall i :: 0 <= i < a.Length ==> a[i] != x\n{\n r :=0;\n while r < a.Length\n {\n if a[r]==x\n {\n return;\n }\n r := r + 1;\n }\n r := -1;\n}\n" }, { "test_ID": "760", "test_file": "t1_MF_tmp_tmpi_sqie4j_exemplos_colecoes_conjuntos_ex5.dfy", "ground_truth": "function to_seq(a: array, i: int) : (res: seq)\nrequires 0 <= i <= a.Length\nensures res == a[i..]\nreads a\ndecreases a.Length-i\n{\n if i == a.Length\n then []\n else [a[i]] + to_seq(a, i + 1)\n}\n\nmethod Main() {\n var a: array := new int[2];\n a[0] := 2;\n a[1] := 3;\n\n var ms: multiset := multiset(a[..]);\n assert a[..] == to_seq(a, 0); //dica para o Dafny\n assert ms[2] == 1;\n}\n", "hints_removed": "function to_seq(a: array, i: int) : (res: seq)\nrequires 0 <= i <= a.Length\nensures res == a[i..]\nreads a\n{\n if i == a.Length\n then []\n else [a[i]] + to_seq(a, i + 1)\n}\n\nmethod Main() {\n var a: array := new int[2];\n a[0] := 2;\n a[1] := 3;\n\n var ms: multiset := multiset(a[..]);\n}\n" }, { "test_ID": "761", "test_file": "t1_MF_tmp_tmpi_sqie4j_exemplos_colecoes_sequences_ex3.dfy", "ground_truth": "// line cont\u00e9m uma string de tamanho l\n// remover p caracteres a partir da posi\u00e7\u00e3o at\nmethod Delete(line:array, l:nat, at:nat, p:nat)\n requires l <= line.Length\n requires at+p <= l\n modifies line\n ensures line[..at] == old(line[..at])\n ensures line[at..l-p] == old(line[at+p..l])\n{\n var i:nat := 0;\n while i < l-(at+p)\n invariant i <= l-(at+p)\n invariant at+p+i >= at+i \n invariant line[..at] == old(line[..at])\n invariant line[at..at+i] == old(line[at+p..at+p+i])\n invariant line[at+i..l] == old(line[at+i..l]) // futuro \u00e9 intoc\u00e1vel\n { \n line[at+i] := line[at+p+i];\n i := i+1;\n }\n}\n", "hints_removed": "// line cont\u00e9m uma string de tamanho l\n// remover p caracteres a partir da posi\u00e7\u00e3o at\nmethod Delete(line:array, l:nat, at:nat, p:nat)\n requires l <= line.Length\n requires at+p <= l\n modifies line\n ensures line[..at] == old(line[..at])\n ensures line[at..l-p] == old(line[at+p..l])\n{\n var i:nat := 0;\n while i < l-(at+p)\n { \n line[at+i] := line[at+p+i];\n i := i+1;\n }\n}\n" }, { "test_ID": "762", "test_file": "t1_MF_tmp_tmpi_sqie4j_exemplos_introducao_ex4.dfy", "ground_truth": "function Fat(n: nat): nat\n{\n if n == 0 then 1 else n * Fat(n-1)\n}\n\nmethod Fatorial(n:nat) returns (r:nat)\n ensures r == Fat(n)\n{\n r := 1;\n var i := 0;\n while i < n\n invariant 0 <= i <= n\n invariant r == Fat(i)\n {\n i := i + 1;\n r := r * i;\n }\n}\n", "hints_removed": "function Fat(n: nat): nat\n{\n if n == 0 then 1 else n * Fat(n-1)\n}\n\nmethod Fatorial(n:nat) returns (r:nat)\n ensures r == Fat(n)\n{\n r := 1;\n var i := 0;\n while i < n\n {\n i := i + 1;\n r := r * i;\n }\n}\n" }, { "test_ID": "763", "test_file": "tangent-finder_tmp_tmpgyzf44ve_circles.dfy", "ground_truth": "method Tangent(r: array, x: array) returns (b: bool)\n requires forall i, j :: 0 <= i <= j < x.Length ==> x[i] <= x[j] // values in x will be in ascending order or empty\n requires forall i, j :: (0 <= i < r.Length && 0 <= j < x.Length) ==> (r[i] >= 0 && x[j] >= 0) // x and r will contain no negative values\n ensures !b ==> forall i, j :: 0 <= i< r.Length && 0 <= j < x.Length ==> r[i] != x[j] \n ensures b ==> exists i, j :: 0 <= i< r.Length && 0 <= j < x.Length && r[i] == x[j]\n{\n var tempB, tangentMissing, k, l := false, false, 0, 0;\n while k != r.Length && !tempB\n invariant 0 <= k <= r.Length\n invariant tempB ==> exists i, j :: 0 <= i < r.Length && 0 <= j < x.Length && r[i] == x[j]\n invariant !tempB ==> forall i, j :: (0 <= i r[i] != x[j]\n decreases r.Length - k\n {\n l:= 0;\n tangentMissing := false;\n while l != x.Length && !tangentMissing\n invariant 0 <= l <= x.Length\n invariant tempB ==> exists i, j :: 0 <= i < r.Length && 0 <= j < x.Length && r[i] == x[j]\n invariant !tempB ==> forall i :: 0 <= i< l ==> r[k] != x[i]\n invariant tangentMissing ==> forall i :: (l <= i < x.Length) ==> r[k] != x[i]\n decreases x.Length - l, !tempB, !tangentMissing\n {\n\n if r[k] == x[l] {\n tempB := true;\n }\n if (r[k] < x[l]) {\n tangentMissing := true;\n }\n l := l + 1;\n }\n k := k + 1;\n }\n b := tempB;\n}\n", "hints_removed": "method Tangent(r: array, x: array) returns (b: bool)\n requires forall i, j :: 0 <= i <= j < x.Length ==> x[i] <= x[j] // values in x will be in ascending order or empty\n requires forall i, j :: (0 <= i < r.Length && 0 <= j < x.Length) ==> (r[i] >= 0 && x[j] >= 0) // x and r will contain no negative values\n ensures !b ==> forall i, j :: 0 <= i< r.Length && 0 <= j < x.Length ==> r[i] != x[j] \n ensures b ==> exists i, j :: 0 <= i< r.Length && 0 <= j < x.Length && r[i] == x[j]\n{\n var tempB, tangentMissing, k, l := false, false, 0, 0;\n while k != r.Length && !tempB\n {\n l:= 0;\n tangentMissing := false;\n while l != x.Length && !tangentMissing\n {\n\n if r[k] == x[l] {\n tempB := true;\n }\n if (r[k] < x[l]) {\n tangentMissing := true;\n }\n l := l + 1;\n }\n k := k + 1;\n }\n b := tempB;\n}\n" }, { "test_ID": "764", "test_file": "test-generation-examples_tmp_tmptwyqofrp_IntegerSet_dafny_IntegerSet.dfy", "ground_truth": "module IntegerSet {\n\n class Set {\n\n var elements: seq;\n\n constructor Set0() \n ensures this.elements == []\n ensures |this.elements| == 0\n {\n this.elements := [];\n }\n\n constructor Set(elements: seq)\n requires forall i, j | 0 <= i < |elements| && 0 <= j < |elements| && j != i :: elements[i] != elements[j]\n ensures this.elements == elements\n ensures forall i, j | 0 <= i < |this.elements| && 0 <= j < |this.elements| && j != i:: this.elements[i] != this.elements[j]\n {\n this.elements := elements;\n }\n\n method size() returns (size : int)\n ensures size == |elements|\n {\n size := |elements|;\n }\n\n method addElement(element : int)\n modifies this`elements\n requires forall i, j | 0 <= i < |elements| && 0 <= j < |elements| && j != i :: elements[i] != elements[j]\n ensures element in old(elements) ==> elements == old(elements)\n ensures element !in old(elements) ==> |elements| == |old(elements)| + 1 && element in elements && forall i : int :: i in old(elements) ==> i in elements\n ensures forall i, j | 0 <= i < |elements| && 0 <= j < |elements| && j != i :: elements[i] != elements[j]\n {\n if (element !in elements) {\n elements := elements + [element];\n }\n }\n\n method removeElement(element : int)\n modifies this`elements\n requires forall i, j | 0 <= i < |elements| && 0 <= j < |elements| && j != i :: elements[i] != elements[j]\n ensures element in old(elements) ==> |elements| == |old(elements)| - 1 && (forall i : int :: i in old(elements) && i != element <==> i in elements) && element !in elements\n ensures element !in old(elements) ==> elements == old(elements)\n ensures forall i, j | 0 <= i < |elements| && 0 <= j < |elements| && j != i :: elements[i] != elements[j]\n {\n if (element in elements) {\n var i := 0;\n\n while (0 <= i < |elements|)\n decreases |elements| - i\n invariant 0 <= i < |elements|\n invariant forall j : int :: 0 <= j < i < |elements| ==> elements[j] != element\n {\n if (elements[i] == element) {\n if (i < |elements| - 1 && i != -1) {\n elements := elements[..i] + elements[i+1..];\n } \n else if (i == |elements| - 1) {\n elements := elements[..i];\n }\n break;\n }\n i := i + 1;\n }\n }\n }\n\n method contains(element : int) returns (contains : bool)\n ensures contains == (element in elements)\n ensures elements == old(elements)\n {\n contains := false;\n if (element in elements) {\n contains := true;\n }\n }\n\n //for computing the length of the intersection of 2 sets\n function intersect_length(s1 : seq, s2 : seq, count : int, start : int, stop : int) : int \n requires 0 <= start <= stop\n requires stop <= |s1|\n decreases stop - start\n {\n if start == stop then count else (if s1[start] in s2 then intersect_length(s1, s2, count + 1, start + 1, stop) else intersect_length(s1, s2, count, start + 1, stop))\n }\n\n //for computing the length of the union of 2 sets\n //pass in the length of s2 as the initial count\n function union_length(s1 : seq, s2 : seq, count : int, i : int, stop : int) : int \n requires 0 <= i <= stop\n requires stop <= |s1|\n decreases stop - i\n {\n if i == stop then count else (if s1[i] !in s2 then union_length(s1, s2, count + 1, i + 1, stop) else union_length(s1, s2, count, i + 1, stop))\n }\n\n method intersect(s : Set) returns (intersection : Set)\n requires forall i, j | 0 <= i < |s.elements| && 0 <= j < |s.elements| && i != j :: s.elements[i] != s.elements[j]\n requires forall i, j | 0 <= i < |this.elements| && 0 <= j < |this.elements| && i != j :: this.elements[i] != this.elements[j]\n ensures forall i : int :: i in intersection.elements <==> i in s.elements && i in this.elements \n ensures forall i : int :: i !in intersection.elements <==> i !in s.elements || i !in this.elements\n ensures forall j, k | 0 <= j < |intersection.elements| && 0 <= k < |intersection.elements| && j != k :: intersection.elements[j] != intersection.elements[k]\n ensures fresh(intersection)\n {\n intersection := new Set.Set0();\n var inter: seq := [];\n\n var i := 0;\n while (0 <= i < |this.elements|)\n decreases |this.elements| - i\n invariant 0 <= i < |this.elements| || i == 0\n invariant forall j, k | 0 <= j < |inter| && 0 <= k < |inter| && j != k :: inter[j] != inter[k]\n invariant forall j :: 0 <= j < i < |this.elements| ==> (this.elements[j] in inter <==> this.elements[j] in s.elements)\n invariant forall j :: 0 <= j < |inter| ==> inter[j] in this.elements && inter[j] in s.elements\n invariant |inter| <= i <= |this.elements|\n {\n \n var old_len := |inter|;\n if (this.elements[i] in s.elements && this.elements[i] !in inter) {\n inter := inter + [this.elements[i]];\n }\n if (i == |this.elements| - 1) {\n assert(old_len + 1 == |inter| || old_len == |inter|);\n break;\n }\n assert(old_len + 1 == |inter| || old_len == |inter|);\n i := i + 1;\n }\n intersection.elements := inter;\n }\n\n method union(s : Set) returns (union : Set)\n requires forall i, j | 0 <= i < |s.elements| && 0 <= j < |s.elements| && i != j :: s.elements[i] != s.elements[j]\n requires forall i, j | 0 <= i < |this.elements| && 0 <= j < |this.elements| && i != j :: this.elements[i] != this.elements[j]\n ensures forall i : int :: i in s.elements || i in this.elements <==> i in union.elements\n ensures forall i : int :: i !in s.elements && i !in this.elements <==> i !in union.elements\n ensures forall j, k | 0 <= j < |union.elements| && 0 <= k < |union.elements| && j != k :: union.elements[j] != union.elements[k]\n ensures fresh(union)\n {\n var elems := s.elements;\n union := new Set.Set0();\n\n var i := 0;\n while (0 <= i < |this.elements|)\n decreases |this.elements| - i\n invariant 0 <= i < |this.elements| || i == 0\n invariant forall j : int :: 0 <= j < |s.elements| ==> s.elements[j] in elems\n invariant forall j : int :: 0 <= j < i < |this.elements| ==> (this.elements[j] in elems <==> (this.elements[j] in s.elements || this.elements[j] in this.elements))\n invariant forall j :: 0 <= j < |elems| ==> elems[j] in this.elements || elems[j] in s.elements\n invariant forall j, k :: 0 <= j < |elems| && 0 <= k < |elems| && j != k ==> elems[j] != elems[k]\n {\n if (this.elements[i] !in elems) {\n elems := elems + [this.elements[i]];\n }\n if (i == |this.elements| - 1) {\n break;\n }\n i := i + 1;\n }\n\n union.elements := elems;\n }\n }\n}\n", "hints_removed": "module IntegerSet {\n\n class Set {\n\n var elements: seq;\n\n constructor Set0() \n ensures this.elements == []\n ensures |this.elements| == 0\n {\n this.elements := [];\n }\n\n constructor Set(elements: seq)\n requires forall i, j | 0 <= i < |elements| && 0 <= j < |elements| && j != i :: elements[i] != elements[j]\n ensures this.elements == elements\n ensures forall i, j | 0 <= i < |this.elements| && 0 <= j < |this.elements| && j != i:: this.elements[i] != this.elements[j]\n {\n this.elements := elements;\n }\n\n method size() returns (size : int)\n ensures size == |elements|\n {\n size := |elements|;\n }\n\n method addElement(element : int)\n modifies this`elements\n requires forall i, j | 0 <= i < |elements| && 0 <= j < |elements| && j != i :: elements[i] != elements[j]\n ensures element in old(elements) ==> elements == old(elements)\n ensures element !in old(elements) ==> |elements| == |old(elements)| + 1 && element in elements && forall i : int :: i in old(elements) ==> i in elements\n ensures forall i, j | 0 <= i < |elements| && 0 <= j < |elements| && j != i :: elements[i] != elements[j]\n {\n if (element !in elements) {\n elements := elements + [element];\n }\n }\n\n method removeElement(element : int)\n modifies this`elements\n requires forall i, j | 0 <= i < |elements| && 0 <= j < |elements| && j != i :: elements[i] != elements[j]\n ensures element in old(elements) ==> |elements| == |old(elements)| - 1 && (forall i : int :: i in old(elements) && i != element <==> i in elements) && element !in elements\n ensures element !in old(elements) ==> elements == old(elements)\n ensures forall i, j | 0 <= i < |elements| && 0 <= j < |elements| && j != i :: elements[i] != elements[j]\n {\n if (element in elements) {\n var i := 0;\n\n while (0 <= i < |elements|)\n {\n if (elements[i] == element) {\n if (i < |elements| - 1 && i != -1) {\n elements := elements[..i] + elements[i+1..];\n } \n else if (i == |elements| - 1) {\n elements := elements[..i];\n }\n break;\n }\n i := i + 1;\n }\n }\n }\n\n method contains(element : int) returns (contains : bool)\n ensures contains == (element in elements)\n ensures elements == old(elements)\n {\n contains := false;\n if (element in elements) {\n contains := true;\n }\n }\n\n //for computing the length of the intersection of 2 sets\n function intersect_length(s1 : seq, s2 : seq, count : int, start : int, stop : int) : int \n requires 0 <= start <= stop\n requires stop <= |s1|\n {\n if start == stop then count else (if s1[start] in s2 then intersect_length(s1, s2, count + 1, start + 1, stop) else intersect_length(s1, s2, count, start + 1, stop))\n }\n\n //for computing the length of the union of 2 sets\n //pass in the length of s2 as the initial count\n function union_length(s1 : seq, s2 : seq, count : int, i : int, stop : int) : int \n requires 0 <= i <= stop\n requires stop <= |s1|\n {\n if i == stop then count else (if s1[i] !in s2 then union_length(s1, s2, count + 1, i + 1, stop) else union_length(s1, s2, count, i + 1, stop))\n }\n\n method intersect(s : Set) returns (intersection : Set)\n requires forall i, j | 0 <= i < |s.elements| && 0 <= j < |s.elements| && i != j :: s.elements[i] != s.elements[j]\n requires forall i, j | 0 <= i < |this.elements| && 0 <= j < |this.elements| && i != j :: this.elements[i] != this.elements[j]\n ensures forall i : int :: i in intersection.elements <==> i in s.elements && i in this.elements \n ensures forall i : int :: i !in intersection.elements <==> i !in s.elements || i !in this.elements\n ensures forall j, k | 0 <= j < |intersection.elements| && 0 <= k < |intersection.elements| && j != k :: intersection.elements[j] != intersection.elements[k]\n ensures fresh(intersection)\n {\n intersection := new Set.Set0();\n var inter: seq := [];\n\n var i := 0;\n while (0 <= i < |this.elements|)\n {\n \n var old_len := |inter|;\n if (this.elements[i] in s.elements && this.elements[i] !in inter) {\n inter := inter + [this.elements[i]];\n }\n if (i == |this.elements| - 1) {\n break;\n }\n i := i + 1;\n }\n intersection.elements := inter;\n }\n\n method union(s : Set) returns (union : Set)\n requires forall i, j | 0 <= i < |s.elements| && 0 <= j < |s.elements| && i != j :: s.elements[i] != s.elements[j]\n requires forall i, j | 0 <= i < |this.elements| && 0 <= j < |this.elements| && i != j :: this.elements[i] != this.elements[j]\n ensures forall i : int :: i in s.elements || i in this.elements <==> i in union.elements\n ensures forall i : int :: i !in s.elements && i !in this.elements <==> i !in union.elements\n ensures forall j, k | 0 <= j < |union.elements| && 0 <= k < |union.elements| && j != k :: union.elements[j] != union.elements[k]\n ensures fresh(union)\n {\n var elems := s.elements;\n union := new Set.Set0();\n\n var i := 0;\n while (0 <= i < |this.elements|)\n {\n if (this.elements[i] !in elems) {\n elems := elems + [this.elements[i]];\n }\n if (i == |this.elements| - 1) {\n break;\n }\n i := i + 1;\n }\n\n union.elements := elems;\n }\n }\n}\n" }, { "test_ID": "765", "test_file": "test-generation-examples_tmp_tmptwyqofrp_IntegerSet_dafny_Utils.dfy", "ground_truth": "module Utils {\n class Assertions {\n static method {:extern} assertEquals(expected : T, actual : T)\n requires expected == actual\n\n static method {:extern} expectEquals(expected : T, actual : T)\n ensures expected == actual\n\n static method {:extern} assertTrue(condition : bool)\n requires condition\n\n static method {:extern} expectTrue(condition : bool)\n ensures condition\n \n static method {:extern} assertFalse(condition : bool)\n requires !condition\n\n static method {:extern} expectFalse(condition : bool)\n ensures !condition\n }\n}\n", "hints_removed": "module Utils {\n class Assertions {\n static method {:extern} assertEquals(expected : T, actual : T)\n requires expected == actual\n\n static method {:extern} expectEquals(expected : T, actual : T)\n ensures expected == actual\n\n static method {:extern} assertTrue(condition : bool)\n requires condition\n\n static method {:extern} expectTrue(condition : bool)\n ensures condition\n \n static method {:extern} assertFalse(condition : bool)\n requires !condition\n\n static method {:extern} expectFalse(condition : bool)\n ensures !condition\n }\n}\n" }, { "test_ID": "766", "test_file": "test-generation-examples_tmp_tmptwyqofrp_ParamTests_dafny_Utils.dfy", "ground_truth": "module Utils {\n\n export \n reveals Assertions\n provides Assertions.assertEquals\n\n class Assertions {\n static method {:axiom} assertEquals(left : T, right : T)\n requires left == right\n /* \npublic static void assertEquals(T a, T b) {\n Xunit.Assert.Equal(a, b);\n}\n */\n\n /*\nstatic public void assertEquals(dafny.TypeDescriptor typeDescriptor, T left, T right) {\n org.junit.jupiter.api.Assertions.assertEquals(left, right);\n}\n */\n\n static method {:axiom} assertTrue(value : bool)\n requires value\n\n static method {:axiom} assertFalse(value : bool)\n requires !value\n }\n}\n", "hints_removed": "module Utils {\n\n export \n reveals Assertions\n provides Assertions.assertEquals\n\n class Assertions {\n static method {:axiom} assertEquals(left : T, right : T)\n requires left == right\n /* \npublic static void assertEquals(T a, T b) {\n Xunit.Assert.Equal(a, b);\n}\n */\n\n /*\nstatic public void assertEquals(dafny.TypeDescriptor typeDescriptor, T left, T right) {\n org.junit.jupiter.api.Assertions.assertEquals(left, right);\n}\n */\n\n static method {:axiom} assertTrue(value : bool)\n requires value\n\n static method {:axiom} assertFalse(value : bool)\n requires !value\n }\n}\n" }, { "test_ID": "767", "test_file": "test-generation-examples_tmp_tmptwyqofrp_RussianMultiplication_dafny_RussianMultiplication.dfy", "ground_truth": "module RussianMultiplication {\n \n export provides mult\n\n method mult(n0 : int, m0 : int) returns (res : int)\n ensures res == (n0 * m0);\n {\n var n, m : int;\n res := 0;\n if (n0 >= 0) {\n n,m := n0, m0;\n } \n else {\n n,m := -n0, -m0;\n }\n while (0 < n)\n invariant (m * n + res) == (m0 * n0);\n decreases n; \n { \n res := res + m; \n n := n - 1; \n }\n }\n}\n", "hints_removed": "module RussianMultiplication {\n \n export provides mult\n\n method mult(n0 : int, m0 : int) returns (res : int)\n ensures res == (n0 * m0);\n {\n var n, m : int;\n res := 0;\n if (n0 >= 0) {\n n,m := n0, m0;\n } \n else {\n n,m := -n0, -m0;\n }\n while (0 < n)\n { \n res := res + m; \n n := n - 1; \n }\n }\n}\n" }, { "test_ID": "768", "test_file": "type-definition_tmp_tmp71kdzz3p_final.dfy", "ground_truth": "// -------------------------------------------------------------\n// 1. Implementing type inference\n// -------------------------------------------------------------\n\n// Syntax:\n//\n// \u03c4 := Int | Bool | \u03c41->\u03c42\n// e ::= x | \u03bbx : \u03c4.e | true| false| e1 e2 | if e then e1 else e2\n// v ::= true | false | \u03bbx : \u03c4.e\n// E ::= [\u00b7] | E e | v E | if E then e1 else e2\ntype VarName = string\n\ntype TypeVar = Type -> Type\n\ndatatype Type = Int | Bool | TypeVar\n\ndatatype Exp =\n | Var(x: VarName)\n | Lam(x: VarName, t: Type, e: Exp)\n | App(e1: Exp, e2:Exp)\n | True()\n | False()\n | Cond(e0: Exp, e1: Exp, e2: Exp)\n\ndatatype Value =\n | TrueB()\n | FalseB()\n | Lam(x: VarName, t: Type, e: Exp)\n\ndatatype Eva = \n | E()\n | EExp(E : Eva, e : Exp)\n | EVar(v : Value, E : Eva)\n | ECond(E:Eva, e1 : Exp, e2 : Exp)\n\nfunction FV(e: Exp): set {\n match(e) {\n case Var(x) => {x}\n case Lam(x, t, e) => FV(e) - {x} //\u4e0d\u786e\u5b9a\n case App(e1,e2) => FV(e1) + FV(e2)\n case True() => {}\n case False() => {}\n case Cond(e0, e1, e2) => FV(e0) + FV(e1) + FV(e2)\n }\n}\n// Typing rules system\n// -------------------------------------------------------------\n// Typing rules system\ntype Env = map\n\npredicate hasType(gamma: Env, e: Exp, t: Type)\n{\n match e {\n\n case Var(x) => x in gamma && t == gamma[x]\n case Lam(x, t, e) => hasType(gamma, e, t)//\u9519\u7684\n case App(e1,e2) => hasType(gamma, e1, t) && hasType(gamma, e2, t)\n case True() => t == Bool\n case False() => t == Bool\n case Cond(e0, e1, e2) => hasType(gamma, e0, Bool) && hasType(gamma, e1, t) && hasType(gamma, e2, t)\n } \n}\n\n// -----------------------------------------------------------------\n// 2. Extending While with tuples\n// -----------------------------------------------------------------\n\n\n/*lemma {:induction false} extendGamma(gamma: Env, e: Exp, t: Type, x1: VarName, t1: Type)\n requires hasType(gamma, e, t)\n requires x1 !in FV(e)\n ensures hasType(gamma[x1 := t1], e, t)\n{\n match e {\n case Var(x) => {\n assert x in FV(e);\n assert x != x1;\n assert gamma[x1 := t1][x] == gamma[x];\n assert hasType(gamma[x1 := t1], e, t);\n }\n case True() => {\n assert t == Bool;\n }\n case False() => {\n assert t == Bool;\n }\n //case Lam(x, t, e)\n case App(e1, e2) =>{\n calc{\n hasType(gamma, e, t);\n ==>\n hasType(gamma, e1, TypeVar) && hasType(gamma, e2, t);\n ==> { extendGamma(gamma, e1, TypeVar, x1, t2); }\n hasType(gamma[x1 := t1], e1, TypeVar) && hasType(gamma, e2, t);\n ==> { extendGamma(gamma, e1, t, x1, t1); }\n hasType(gamma[x1 := t1], e0, Bool) && hasType(gamma[x1 := t1], e1, t) && hasType(gamma, e2, t);\n ==> { extendGamma(gamma, e2, t, x1, t1); }\n hasType(gamma[x1 := t1], e0, Bool) && hasType(gamma[x1 := t1], e1, t) && hasType(gamma[x1 := t1], e2, t);\n ==> \n hasType(gamma[x1 := t1], e, t);\n }\n }\n case Cond(e0, e1, e2) => {\n calc {\n hasType(gamma, e, t);\n ==>\n hasType(gamma, e0, Bool) && hasType(gamma, e1, t) && hasType(gamma, e2, t);\n ==> { extendGamma(gamma, e0, Bool, x1, t1); }\n hasType(gamma[x1 := t1], e0, Bool) && hasType(gamma, e1, t) && hasType(gamma, e2, t);\n ==> { extendGamma(gamma, e1, t, x1, t1); }\n hasType(gamma[x1 := t1], e0, Bool) && hasType(gamma[x1 := t1], e1, t) && hasType(gamma, e2, t);\n ==> { extendGamma(gamma, e2, t, x1, t1); }\n hasType(gamma[x1 := t1], e0, Bool) && hasType(gamma[x1 := t1], e1, t) && hasType(gamma[x1 := t1], e2, t);\n ==> \n hasType(gamma[x1 := t1], e, t);\n } \n }\n }\n} \n", "hints_removed": "// -------------------------------------------------------------\n// 1. Implementing type inference\n// -------------------------------------------------------------\n\n// Syntax:\n//\n// \u03c4 := Int | Bool | \u03c41->\u03c42\n// e ::= x | \u03bbx : \u03c4.e | true| false| e1 e2 | if e then e1 else e2\n// v ::= true | false | \u03bbx : \u03c4.e\n// E ::= [\u00b7] | E e | v E | if E then e1 else e2\ntype VarName = string\n\ntype TypeVar = Type -> Type\n\ndatatype Type = Int | Bool | TypeVar\n\ndatatype Exp =\n | Var(x: VarName)\n | Lam(x: VarName, t: Type, e: Exp)\n | App(e1: Exp, e2:Exp)\n | True()\n | False()\n | Cond(e0: Exp, e1: Exp, e2: Exp)\n\ndatatype Value =\n | TrueB()\n | FalseB()\n | Lam(x: VarName, t: Type, e: Exp)\n\ndatatype Eva = \n | E()\n | EExp(E : Eva, e : Exp)\n | EVar(v : Value, E : Eva)\n | ECond(E:Eva, e1 : Exp, e2 : Exp)\n\nfunction FV(e: Exp): set {\n match(e) {\n case Var(x) => {x}\n case Lam(x, t, e) => FV(e) - {x} //\u4e0d\u786e\u5b9a\n case App(e1,e2) => FV(e1) + FV(e2)\n case True() => {}\n case False() => {}\n case Cond(e0, e1, e2) => FV(e0) + FV(e1) + FV(e2)\n }\n}\n// Typing rules system\n// -------------------------------------------------------------\n// Typing rules system\ntype Env = map\n\npredicate hasType(gamma: Env, e: Exp, t: Type)\n{\n match e {\n\n case Var(x) => x in gamma && t == gamma[x]\n case Lam(x, t, e) => hasType(gamma, e, t)//\u9519\u7684\n case App(e1,e2) => hasType(gamma, e1, t) && hasType(gamma, e2, t)\n case True() => t == Bool\n case False() => t == Bool\n case Cond(e0, e1, e2) => hasType(gamma, e0, Bool) && hasType(gamma, e1, t) && hasType(gamma, e2, t)\n } \n}\n\n// -----------------------------------------------------------------\n// 2. Extending While with tuples\n// -----------------------------------------------------------------\n\n\n/*lemma {:induction false} extendGamma(gamma: Env, e: Exp, t: Type, x1: VarName, t1: Type)\n requires hasType(gamma, e, t)\n requires x1 !in FV(e)\n ensures hasType(gamma[x1 := t1], e, t)\n{\n match e {\n case Var(x) => {\n }\n case True() => {\n }\n case False() => {\n }\n //case Lam(x, t, e)\n case App(e1, e2) =>{\n calc{\n hasType(gamma, e, t);\n ==>\n hasType(gamma, e1, TypeVar) && hasType(gamma, e2, t);\n ==> { extendGamma(gamma, e1, TypeVar, x1, t2); }\n hasType(gamma[x1 := t1], e1, TypeVar) && hasType(gamma, e2, t);\n ==> { extendGamma(gamma, e1, t, x1, t1); }\n hasType(gamma[x1 := t1], e0, Bool) && hasType(gamma[x1 := t1], e1, t) && hasType(gamma, e2, t);\n ==> { extendGamma(gamma, e2, t, x1, t1); }\n hasType(gamma[x1 := t1], e0, Bool) && hasType(gamma[x1 := t1], e1, t) && hasType(gamma[x1 := t1], e2, t);\n ==> \n hasType(gamma[x1 := t1], e, t);\n }\n }\n case Cond(e0, e1, e2) => {\n calc {\n hasType(gamma, e, t);\n ==>\n hasType(gamma, e0, Bool) && hasType(gamma, e1, t) && hasType(gamma, e2, t);\n ==> { extendGamma(gamma, e0, Bool, x1, t1); }\n hasType(gamma[x1 := t1], e0, Bool) && hasType(gamma, e1, t) && hasType(gamma, e2, t);\n ==> { extendGamma(gamma, e1, t, x1, t1); }\n hasType(gamma[x1 := t1], e0, Bool) && hasType(gamma[x1 := t1], e1, t) && hasType(gamma, e2, t);\n ==> { extendGamma(gamma, e2, t, x1, t1); }\n hasType(gamma[x1 := t1], e0, Bool) && hasType(gamma[x1 := t1], e1, t) && hasType(gamma[x1 := t1], e2, t);\n ==> \n hasType(gamma[x1 := t1], e, t);\n } \n }\n }\n} \n" }, { "test_ID": "769", "test_file": "veri-sparse_tmp_tmp15fywna6_dafny_concurrent_poc_6.dfy", "ground_truth": "class Process {\n var row: nat;\n var curColumn: nat;\n var opsLeft: nat;\n\n constructor (init_row: nat, initOpsLeft: nat) \n ensures row == init_row\n ensures opsLeft == initOpsLeft\n ensures curColumn == 0\n {\n row := init_row;\n curColumn := 0;\n opsLeft := initOpsLeft;\n }\n}\n\nfunction sum(s : seq) : nat\n ensures sum(s) == 0 ==> forall i :: 0 <= i < |s| ==> s[i] == 0\n{\n if s == [] then 0 else s[0] + sum(s[1..])\n}\n\nlemma sum0(s : seq)\n ensures sum(s) == 0 ==> forall i :: 0 <= i < |s| ==> s[i] == 0\n {\n if s == [] {\n } else {\n sum0(s[1..]);\n }\n }\n\nlemma sum_const(s : seq, x : nat)\n ensures (forall i :: 0 <= i < |s| ==> s[i] == x) ==> sum(s) == |s| * x \n {\n }\n\nlemma sum_eq(s1 : seq, s2 : seq)\n requires |s1| == |s2|\n requires forall i :: 0 <= i < |s1| ==> s1[i] == s2[i]\n ensures sum(s1) == sum(s2)\n {\n\n }\n\nlemma sum_exept(s1 : seq, s2 : seq, x : nat, j : nat)\nrequires |s1| == |s2|\nrequires j < |s1|\nrequires forall i :: 0 <= i < |s1| ==> i != j ==> s1[i] == s2[i]\nrequires s1[j] == s2[j] + x\nensures sum(s1) == sum(s2) + x\n{\n if s1 == [] {\n assert(j >= |s1|);\n } else {\n if j == 0 {\n assert (sum(s1) == s1[0] + sum(s1[1..]));\n assert (sum(s2) == s2[0] + sum(s2[1..]));\n sum_eq(s1[1..], s2[1..]);\n assert sum(s1[1..]) == sum(s2[1..]);\n } else {\n sum_exept(s1[1..], s2[1..], x, j - 1);\n }\n }\n}\n\n\nfunction calcRow(M : array2, x : seq, row: nat, start_index: nat) : (product: int)\n reads M\n requires M.Length1 == |x|\n requires row < M.Length0\n requires start_index <= M.Length1\n decreases M.Length1 - start_index\n{\n if start_index == M.Length1 then\n 0\n else\n M[row, start_index] * x[start_index] + calcRow(M, x, row, start_index+1)\n}\n\nclass MatrixVectorMultiplier\n{ \n\n ghost predicate Valid(M: array2, x: seq, y: array, P: set, leftOvers : array)\n reads this, y, P, M, leftOvers\n {\n M.Length0 == y.Length &&\n M.Length1 == |x| &&\n |P| == y.Length &&\n |P| == leftOvers.Length &&\n\n (forall p, q :: p in P && q in P && p != q ==> p.row != q.row) &&\n (forall p, q :: p in P && q in P ==> p != q) &&\n (forall p :: p in P ==> 0 <= p.row < |P|) &&\n (forall p :: p in P ==> 0 <= p.curColumn <= M.Length1) &&\n (forall p :: p in P ==> 0 <= p.opsLeft <= M.Length1) && \n (forall p :: p in P ==> y[p.row] + calcRow(M, x, p.row, p.curColumn) == calcRow(M, x, p.row, 0)) &&\n (forall p :: p in P ==> leftOvers[p.row] == p.opsLeft) &&\n (forall p :: p in P ==> p.opsLeft == M.Length1 - p.curColumn) &&\n (sum(leftOvers[..]) > 0 ==> exists p :: p in P && p.opsLeft > 0)\n }\n\n\n constructor (processes: set, M_: array2, x_: seq, y_: array, leftOvers : array)\n // Idea here is that we already have a set of processes such that each one is assigned one row.\n // Daphny makes it a ginormous pain in the ass to actually create such a set, so we just assume\n // we already have one.\n\n //this states that the number of rows and processes are the same, and that there is one process\n //for every row, and that no two processes are the same, nor do any two processes share the same\n //row\n requires (forall i :: 0 <= i < leftOvers.Length ==> leftOvers[i] == M_.Length1)\n requires |processes| == leftOvers.Length \n requires |processes| == M_.Length0\n requires (forall p, q :: p in processes && q in processes && p != q ==> p.row != q.row)\n requires (forall p, q :: p in processes && q in processes ==> p != q)\n requires (forall p :: p in processes ==> 0 <= p.row < M_.Length0)\n\n //initializes process start\n requires (forall p :: p in processes ==> 0 == p.curColumn)\n requires (forall p :: p in processes ==> p.opsLeft == M_.Length1)\n\n requires (forall i :: 0 <= i < y_.Length ==> y_[i] == 0)\n requires y_.Length == M_.Length0\n\n requires |x_| == M_.Length1\n requires M_.Length0 > 0\n requires |x_| > 0\n ensures (forall i :: 0 <= i < leftOvers.Length ==> leftOvers[i] == M_.Length1)\n ensures Valid(M_, x_, y_, processes, leftOvers)\n {\n \n }\n\n method processNext(M: array2, x: seq, y: array, P : set, leftOvers : array)\n requires Valid(M, x, y, P, leftOvers)\n requires exists p :: (p in P && p.opsLeft > 0)\n requires sum(leftOvers[..]) > 0\n modifies this, y, P, leftOvers\n requires (forall p, q :: p in P && q in P && p != q ==> p.row != q.row)\n\n ensures Valid(M, x, y, P, leftOvers)\n ensures sum(leftOvers[..]) == sum(old(leftOvers[..])) - 1\n {\n var p :| p in P && p.opsLeft > 0;\n y[p.row] := y[p.row] + M[p.row, p.curColumn] * x[p.curColumn];\n p.opsLeft := p.opsLeft - 1;\n p.curColumn := p.curColumn + 1;\n leftOvers[p.row] := leftOvers[p.row] - 1;\n assert (forall i :: 0 <= i < leftOvers.Length ==> i != p.row ==> leftOvers[i] == old(leftOvers[i]));\n assert (leftOvers[p.row] + 1 == old(leftOvers[p.row]));\n assert((forall p :: p in P ==> leftOvers[p.row] == p.opsLeft));\n sum_exept(old(leftOvers[..]), leftOvers[..], 1, p.row);\n }\n\n\n}\n\nmethod Run(processes: set, M: array2, x: array) returns (y: array)\n requires |processes| == M.Length0\n requires (forall p, q :: p in processes && q in processes && p != q ==> p.row != q.row)\n requires (forall p, q :: p in processes && q in processes ==> p != q)\n requires (forall p :: p in processes ==> 0 <= p.row < M.Length0)\n\n requires (forall p :: p in processes ==> 0 == p.curColumn)\n requires (forall p :: p in processes ==> p.opsLeft == M.Length1)\n\n requires x.Length > 0\n requires M.Length0 > 0\n requires M.Length1 == x.Length\n ensures M.Length0 == y.Length\n modifies processes, M, x\n{\n var i := 0;\n y := new int[M.Length0](i => 0);\n\n var leftOvers := new nat[M.Length0](i => M.Length1);\n\n var mv := new MatrixVectorMultiplier(processes, M, x[..], y, leftOvers);\n while sum(leftOvers[..]) > 0 && exists p :: (p in processes && p.opsLeft > 0)\n invariant mv.Valid(M, x[..], y, processes, leftOvers)\n invariant (forall p :: p in processes ==> y[p.row] + calcRow(M, x[..], p.row, p.curColumn) == calcRow(M, x[..], p.row, 0))\n invariant sum(leftOvers[..]) >= 0\n invariant (forall p, q :: p in processes && q in processes && p != q ==> p.row != q.row)\n decreases sum(leftOvers[..])\n {\n mv.processNext(M, x[..], y, processes, leftOvers);\n }\n assert(sum(leftOvers[..]) == 0);\n assert(forall i :: 0 <= i < y.Length ==> y[i] == calcRow(M, x[..], i, 0));\n\n\n}\n\n\n// lemma lemma_newProcessNotInSet(process: Process, processes: set)\n// requires (forall p :: p in processes ==> p.row != process.row)\n// ensures process !in processes\n// {\n// }\n\n// lemma diffRowMeansDiffProcess(p1: Process, p2: Process)\n// requires p1.row != p2.row\n// ensures p1 != p2\n// {\n// }\n\n\n// method createSetProcesses(numRows: nat, numColumns: nat) returns (processes: set)\n// ensures |processes| == numRows\n// ensures (forall p, q :: p in processes && q in processes ==> p != q)\n// ensures (forall p, q :: p in processes && q in processes && p != q ==> p.row != q.row)\n// ensures (forall p :: p in processes ==> 0 <= p.row < numRows)\n// ensures (forall p :: p in processes ==> 0 == p.curColumn)\n// ensures (forall p :: p in processes ==> p.opsLeft == numColumns)\n// {\n// processes := {};\n// assert (forall p, q :: p in processes && q in processes ==> p != q);\n// assert (forall p, q :: p in processes && q in processes && p != q ==> p.row != q.row);\n// var i := 0;\n// while i < numRows\n// invariant i == |processes|\n// invariant 0 <= i <= numRows\n// invariant (forall p, q :: p in processes && q in processes && p != q ==> p.row != q.row)\n// invariant (forall p, q :: p in processes && q in processes ==> p != q)\n// {\n// var process := new Process(i, numColumns);\n// processes := processes + {process};\n// i := i + 1;\n// }\n// }\n\n// method Main()\n// {\n// var M: array2 := new int[3, 3];\n\n// M[0,0] := 1;\n// M[0,1] := 2;\n// M[0,2] := 3;\n\n// M[1,0] := 1;\n// M[1,1] := 2;\n// M[1,2] := 3;\n\n// M[2,0] := 1;\n// M[2,1] := 20;\n// M[2,2] := 3;\n\n// var x := new int[3];\n// x[0] := 1;\n// x[1] := -3;\n// x[2] := 3;\n\n// var p0: Process := new Process(0, 3);\n// var p1: Process := new Process(1, 3);\n// var p2: Process := new Process(2, 3);\n// var processes := {p0, p1, p2};\n\n// assert (p0 != p1 && p1 != p2 && p0 != p2);\n// assert (forall p :: p in processes ==> p == p0 || p == p1 || p == p2);\n// assert (exists p :: p in processes && p == p0);\n// assert (exists p :: p in processes && p == p1);\n// assert (exists p :: p in processes && p == p2);\n// assert (forall p, q :: p in processes && q in processes ==> p.row != q.row);\n// assert (forall p, q :: p in processes && q in processes ==> p != q);\n\n// var y := Run(processes, M, x);\n\n// for i := 0 to 3 {\n// print \"output: \", y[i], \"\\n\";\n// }\n// }\n\n", "hints_removed": "class Process {\n var row: nat;\n var curColumn: nat;\n var opsLeft: nat;\n\n constructor (init_row: nat, initOpsLeft: nat) \n ensures row == init_row\n ensures opsLeft == initOpsLeft\n ensures curColumn == 0\n {\n row := init_row;\n curColumn := 0;\n opsLeft := initOpsLeft;\n }\n}\n\nfunction sum(s : seq) : nat\n ensures sum(s) == 0 ==> forall i :: 0 <= i < |s| ==> s[i] == 0\n{\n if s == [] then 0 else s[0] + sum(s[1..])\n}\n\nlemma sum0(s : seq)\n ensures sum(s) == 0 ==> forall i :: 0 <= i < |s| ==> s[i] == 0\n {\n if s == [] {\n } else {\n sum0(s[1..]);\n }\n }\n\nlemma sum_const(s : seq, x : nat)\n ensures (forall i :: 0 <= i < |s| ==> s[i] == x) ==> sum(s) == |s| * x \n {\n }\n\nlemma sum_eq(s1 : seq, s2 : seq)\n requires |s1| == |s2|\n requires forall i :: 0 <= i < |s1| ==> s1[i] == s2[i]\n ensures sum(s1) == sum(s2)\n {\n\n }\n\nlemma sum_exept(s1 : seq, s2 : seq, x : nat, j : nat)\nrequires |s1| == |s2|\nrequires j < |s1|\nrequires forall i :: 0 <= i < |s1| ==> i != j ==> s1[i] == s2[i]\nrequires s1[j] == s2[j] + x\nensures sum(s1) == sum(s2) + x\n{\n if s1 == [] {\n } else {\n if j == 0 {\n sum_eq(s1[1..], s2[1..]);\n } else {\n sum_exept(s1[1..], s2[1..], x, j - 1);\n }\n }\n}\n\n\nfunction calcRow(M : array2, x : seq, row: nat, start_index: nat) : (product: int)\n reads M\n requires M.Length1 == |x|\n requires row < M.Length0\n requires start_index <= M.Length1\n{\n if start_index == M.Length1 then\n 0\n else\n M[row, start_index] * x[start_index] + calcRow(M, x, row, start_index+1)\n}\n\nclass MatrixVectorMultiplier\n{ \n\n ghost predicate Valid(M: array2, x: seq, y: array, P: set, leftOvers : array)\n reads this, y, P, M, leftOvers\n {\n M.Length0 == y.Length &&\n M.Length1 == |x| &&\n |P| == y.Length &&\n |P| == leftOvers.Length &&\n\n (forall p, q :: p in P && q in P && p != q ==> p.row != q.row) &&\n (forall p, q :: p in P && q in P ==> p != q) &&\n (forall p :: p in P ==> 0 <= p.row < |P|) &&\n (forall p :: p in P ==> 0 <= p.curColumn <= M.Length1) &&\n (forall p :: p in P ==> 0 <= p.opsLeft <= M.Length1) && \n (forall p :: p in P ==> y[p.row] + calcRow(M, x, p.row, p.curColumn) == calcRow(M, x, p.row, 0)) &&\n (forall p :: p in P ==> leftOvers[p.row] == p.opsLeft) &&\n (forall p :: p in P ==> p.opsLeft == M.Length1 - p.curColumn) &&\n (sum(leftOvers[..]) > 0 ==> exists p :: p in P && p.opsLeft > 0)\n }\n\n\n constructor (processes: set, M_: array2, x_: seq, y_: array, leftOvers : array)\n // Idea here is that we already have a set of processes such that each one is assigned one row.\n // Daphny makes it a ginormous pain in the ass to actually create such a set, so we just assume\n // we already have one.\n\n //this states that the number of rows and processes are the same, and that there is one process\n //for every row, and that no two processes are the same, nor do any two processes share the same\n //row\n requires (forall i :: 0 <= i < leftOvers.Length ==> leftOvers[i] == M_.Length1)\n requires |processes| == leftOvers.Length \n requires |processes| == M_.Length0\n requires (forall p, q :: p in processes && q in processes && p != q ==> p.row != q.row)\n requires (forall p, q :: p in processes && q in processes ==> p != q)\n requires (forall p :: p in processes ==> 0 <= p.row < M_.Length0)\n\n //initializes process start\n requires (forall p :: p in processes ==> 0 == p.curColumn)\n requires (forall p :: p in processes ==> p.opsLeft == M_.Length1)\n\n requires (forall i :: 0 <= i < y_.Length ==> y_[i] == 0)\n requires y_.Length == M_.Length0\n\n requires |x_| == M_.Length1\n requires M_.Length0 > 0\n requires |x_| > 0\n ensures (forall i :: 0 <= i < leftOvers.Length ==> leftOvers[i] == M_.Length1)\n ensures Valid(M_, x_, y_, processes, leftOvers)\n {\n \n }\n\n method processNext(M: array2, x: seq, y: array, P : set, leftOvers : array)\n requires Valid(M, x, y, P, leftOvers)\n requires exists p :: (p in P && p.opsLeft > 0)\n requires sum(leftOvers[..]) > 0\n modifies this, y, P, leftOvers\n requires (forall p, q :: p in P && q in P && p != q ==> p.row != q.row)\n\n ensures Valid(M, x, y, P, leftOvers)\n ensures sum(leftOvers[..]) == sum(old(leftOvers[..])) - 1\n {\n var p :| p in P && p.opsLeft > 0;\n y[p.row] := y[p.row] + M[p.row, p.curColumn] * x[p.curColumn];\n p.opsLeft := p.opsLeft - 1;\n p.curColumn := p.curColumn + 1;\n leftOvers[p.row] := leftOvers[p.row] - 1;\n sum_exept(old(leftOvers[..]), leftOvers[..], 1, p.row);\n }\n\n\n}\n\nmethod Run(processes: set, M: array2, x: array) returns (y: array)\n requires |processes| == M.Length0\n requires (forall p, q :: p in processes && q in processes && p != q ==> p.row != q.row)\n requires (forall p, q :: p in processes && q in processes ==> p != q)\n requires (forall p :: p in processes ==> 0 <= p.row < M.Length0)\n\n requires (forall p :: p in processes ==> 0 == p.curColumn)\n requires (forall p :: p in processes ==> p.opsLeft == M.Length1)\n\n requires x.Length > 0\n requires M.Length0 > 0\n requires M.Length1 == x.Length\n ensures M.Length0 == y.Length\n modifies processes, M, x\n{\n var i := 0;\n y := new int[M.Length0](i => 0);\n\n var leftOvers := new nat[M.Length0](i => M.Length1);\n\n var mv := new MatrixVectorMultiplier(processes, M, x[..], y, leftOvers);\n while sum(leftOvers[..]) > 0 && exists p :: (p in processes && p.opsLeft > 0)\n {\n mv.processNext(M, x[..], y, processes, leftOvers);\n }\n\n\n}\n\n\n// lemma lemma_newProcessNotInSet(process: Process, processes: set)\n// requires (forall p :: p in processes ==> p.row != process.row)\n// ensures process !in processes\n// {\n// }\n\n// lemma diffRowMeansDiffProcess(p1: Process, p2: Process)\n// requires p1.row != p2.row\n// ensures p1 != p2\n// {\n// }\n\n\n// method createSetProcesses(numRows: nat, numColumns: nat) returns (processes: set)\n// ensures |processes| == numRows\n// ensures (forall p, q :: p in processes && q in processes ==> p != q)\n// ensures (forall p, q :: p in processes && q in processes && p != q ==> p.row != q.row)\n// ensures (forall p :: p in processes ==> 0 <= p.row < numRows)\n// ensures (forall p :: p in processes ==> 0 == p.curColumn)\n// ensures (forall p :: p in processes ==> p.opsLeft == numColumns)\n// {\n// processes := {};\n// assert (forall p, q :: p in processes && q in processes ==> p != q);\n// assert (forall p, q :: p in processes && q in processes && p != q ==> p.row != q.row);\n// var i := 0;\n// while i < numRows\n// invariant i == |processes|\n// invariant 0 <= i <= numRows\n// invariant (forall p, q :: p in processes && q in processes && p != q ==> p.row != q.row)\n// invariant (forall p, q :: p in processes && q in processes ==> p != q)\n// {\n// var process := new Process(i, numColumns);\n// processes := processes + {process};\n// i := i + 1;\n// }\n// }\n\n// method Main()\n// {\n// var M: array2 := new int[3, 3];\n\n// M[0,0] := 1;\n// M[0,1] := 2;\n// M[0,2] := 3;\n\n// M[1,0] := 1;\n// M[1,1] := 2;\n// M[1,2] := 3;\n\n// M[2,0] := 1;\n// M[2,1] := 20;\n// M[2,2] := 3;\n\n// var x := new int[3];\n// x[0] := 1;\n// x[1] := -3;\n// x[2] := 3;\n\n// var p0: Process := new Process(0, 3);\n// var p1: Process := new Process(1, 3);\n// var p2: Process := new Process(2, 3);\n// var processes := {p0, p1, p2};\n\n// assert (p0 != p1 && p1 != p2 && p0 != p2);\n// assert (forall p :: p in processes ==> p == p0 || p == p1 || p == p2);\n// assert (exists p :: p in processes && p == p0);\n// assert (exists p :: p in processes && p == p1);\n// assert (exists p :: p in processes && p == p2);\n// assert (forall p, q :: p in processes && q in processes ==> p.row != q.row);\n// assert (forall p, q :: p in processes && q in processes ==> p != q);\n\n// var y := Run(processes, M, x);\n\n// for i := 0 to 3 {\n// print \"output: \", y[i], \"\\n\";\n// }\n// }\n\n" }, { "test_ID": "770", "test_file": "veri-sparse_tmp_tmp15fywna6_dafny_dspmspv.dfy", "ground_truth": "function sum(X_val : array, X_crd : array,\n v_val : array, v_crd : array, kX : nat, kV : nat, pX_end : nat, pV_end : nat) : (s : int) \n reads X_val, X_crd\n requires X_val.Length == X_crd.Length\n requires pX_end <= X_crd.Length\n requires 0 <= kX <= X_crd.Length\n\n reads v_crd, v_val\n requires v_val.Length == v_crd.Length\n requires pV_end <= v_crd.Length\n requires 0 <= kV <= v_crd.Length\n\n decreases pX_end + pV_end - (kX + kV)\n {\n if pV_end <= kV || pX_end <= kX then \n 0\n else if X_crd[kX] == v_crd[kV] then \n sum(X_val, X_crd, v_val, v_crd, kX + 1, kV + 1, pX_end, pV_end) + v_val[kV] * X_val[kX]\n else if X_crd[kX] < v_crd[kV] then \n sum(X_val, X_crd, v_val, v_crd, kX + 1, kV, pX_end, pV_end)\n else sum(X_val, X_crd, v_val, v_crd, kX, kV + 1, pX_end, pV_end)\n }\n\nfunction min(x : nat, y : nat) : nat {\n if x <= y then x else y\n}\n\npredicate notin(y: nat, x : array) \n reads x\n{\n forall i :: 0 <= i < x.Length ==> y != x[i]\n}\n\npredicate notin_seq(y: nat, x : seq) \n{\n forall i :: 0 <= i < |x| ==> y != x[i]\n}\n\nfunction index_seq(x : nat, y: seq) : (i : nat)\n ensures i >= |y| ==> notin_seq(x, y)\n ensures i < |y| ==> y[i] == x\n{\n if |y| == 0 then 0 \n else \n if y[0] == x then 0 \n else 1 + index_seq(x, y[1..])\n}\n\nfunction index(x : nat, y: array) : (i : nat)\n reads y\n ensures i >= y.Length ==> notin(x, y)\n ensures i < y.Length ==> y[i] == x\n{\n index_seq(x, y[.. ])\n}\n\nmethod DSpMSpV(X_val : array, X_crd : array, X_pos : array,\n X_crd1 : array, X_len: nat,\n v_val : array, v_crd : array) returns (y : array)\n // X requirements \n requires X_pos.Length >= 1\n requires X_val.Length == X_crd.Length\n requires forall i, j :: 0 <= i < j < X_pos.Length ==> X_pos[i] <= X_pos[j];\n requires forall i :: 0 <= i < X_pos.Length ==> 0 <= X_pos[i] <= X_val.Length\n\n requires X_len >= X_crd1.Length\n requires forall i :: 0 <= i < X_crd1.Length ==> X_crd1[i] < X_len\n\n requires X_crd1.Length < X_pos.Length\n requires forall i, j :: 0 <= i < j < X_crd1.Length ==> X_crd1[i] < X_crd1[j]\n\n // v requirements \n requires v_val.Length == v_crd.Length\n\n ensures y.Length == X_len\n ensures forall i :: 0 <= i < y.Length ==> \n y[i] == \n if index(i, X_crd1) < X_crd1.Length then \n sum(X_val, X_crd, v_val, v_crd, X_pos[index(i, X_crd1)], 0, X_pos[index(i, X_crd1)+1], v_val.Length)\n else 0\n {\n var N : nat := X_len;\n y := new int[N](i => 0);\n\n var n : nat := 0;\n var kX , pX_end : nat;\n var kV : nat;\n var pV_end : nat := v_val.Length;\n var kX0, kV0 : nat;\n var k : nat;\n var pX_end1 := X_crd1.Length;\n \n\n while n < pX_end1\n invariant n <= X_crd1.Length\n invariant forall i :: 0 <= i < n ==> y[X_crd1[i]] == sum(X_val, X_crd, v_val, v_crd, X_pos[i], 0, X_pos[i+1], pV_end)\n invariant forall i :: n <= i < X_crd1.Length ==> y[X_crd1[i]] == 0\n invariant forall i :: 0 <= i < y.Length ==> notin(i, X_crd1) ==> y[i] == 0\n {\n kX := X_pos[n];\n pX_end := X_pos[n + 1];\n kV := 0;\n\n while (kX < pX_end && kV < pV_end) \n invariant X_pos[n] <= kX <= pX_end\n invariant 0 <= kV <= pV_end\n invariant forall i :: n < i < X_crd1.Length ==> y[X_crd1[i]] == 0\n invariant forall i :: 0 <= i < y.Length ==> notin(i, X_crd1) ==> y[i] == 0\n invariant forall i :: 0 <= i < n ==> y[X_crd1[i]] == sum(X_val, X_crd, v_val, v_crd, X_pos[i], 0, X_pos[i+1], pV_end)\n invariant y[X_crd1[n]] + sum(X_val, X_crd, v_val, v_crd, kX, kV, pX_end, pV_end) == sum(X_val, X_crd, v_val, v_crd, X_pos[n], 0, X_pos[n+1], pV_end)\n decreases pX_end + pV_end - (kX + kV)\n {\n kX0 := X_crd[kX];\n kV0 := v_crd[kV];\n k := min(kV0, kX0);\n if (kX0 == k && kV0 == k) {\n y[X_crd1[n]] := y[X_crd1[n]] + X_val[kX] * v_val[kV];\n kX := kX + 1;\n kV := kV + 1;\n } else if (kX0 == k) {\n kX := kX + 1;\n } else if (kV0 == k) {\n kV := kV + 1;\n }\n }\n n := n + 1;\n }\n }\n\nmethod Main() {\n var X_val := new int[4](i => 1);\n var X_crd := new nat[4](i => if i <= 3 then (3 - i) * 2 else 0);\n var X_pos := new nat[5](i => i);\n var X_crd1 := new nat[4](i => i * 2);\n var X_pos1 := new nat[2](i => i * 8);\n var X_len := 8;\n\n var v_val := new int[4](i => 30 + i);\n var v_crd := new nat[4](i => i * 2);\n var v_pos := new nat[2](i => if i == 0 then 0 else 4);\n\n var y := DSpMSpV(\n X_val,\n X_crd,\n X_pos,\n X_crd1,\n X_len,\n v_val,\n v_crd\n );\n\n var i := 0;\n while i < 8 { print y[i]; print \"; \"; i := i + 1; }\n}\n\n", "hints_removed": "function sum(X_val : array, X_crd : array,\n v_val : array, v_crd : array, kX : nat, kV : nat, pX_end : nat, pV_end : nat) : (s : int) \n reads X_val, X_crd\n requires X_val.Length == X_crd.Length\n requires pX_end <= X_crd.Length\n requires 0 <= kX <= X_crd.Length\n\n reads v_crd, v_val\n requires v_val.Length == v_crd.Length\n requires pV_end <= v_crd.Length\n requires 0 <= kV <= v_crd.Length\n\n {\n if pV_end <= kV || pX_end <= kX then \n 0\n else if X_crd[kX] == v_crd[kV] then \n sum(X_val, X_crd, v_val, v_crd, kX + 1, kV + 1, pX_end, pV_end) + v_val[kV] * X_val[kX]\n else if X_crd[kX] < v_crd[kV] then \n sum(X_val, X_crd, v_val, v_crd, kX + 1, kV, pX_end, pV_end)\n else sum(X_val, X_crd, v_val, v_crd, kX, kV + 1, pX_end, pV_end)\n }\n\nfunction min(x : nat, y : nat) : nat {\n if x <= y then x else y\n}\n\npredicate notin(y: nat, x : array) \n reads x\n{\n forall i :: 0 <= i < x.Length ==> y != x[i]\n}\n\npredicate notin_seq(y: nat, x : seq) \n{\n forall i :: 0 <= i < |x| ==> y != x[i]\n}\n\nfunction index_seq(x : nat, y: seq) : (i : nat)\n ensures i >= |y| ==> notin_seq(x, y)\n ensures i < |y| ==> y[i] == x\n{\n if |y| == 0 then 0 \n else \n if y[0] == x then 0 \n else 1 + index_seq(x, y[1..])\n}\n\nfunction index(x : nat, y: array) : (i : nat)\n reads y\n ensures i >= y.Length ==> notin(x, y)\n ensures i < y.Length ==> y[i] == x\n{\n index_seq(x, y[.. ])\n}\n\nmethod DSpMSpV(X_val : array, X_crd : array, X_pos : array,\n X_crd1 : array, X_len: nat,\n v_val : array, v_crd : array) returns (y : array)\n // X requirements \n requires X_pos.Length >= 1\n requires X_val.Length == X_crd.Length\n requires forall i, j :: 0 <= i < j < X_pos.Length ==> X_pos[i] <= X_pos[j];\n requires forall i :: 0 <= i < X_pos.Length ==> 0 <= X_pos[i] <= X_val.Length\n\n requires X_len >= X_crd1.Length\n requires forall i :: 0 <= i < X_crd1.Length ==> X_crd1[i] < X_len\n\n requires X_crd1.Length < X_pos.Length\n requires forall i, j :: 0 <= i < j < X_crd1.Length ==> X_crd1[i] < X_crd1[j]\n\n // v requirements \n requires v_val.Length == v_crd.Length\n\n ensures y.Length == X_len\n ensures forall i :: 0 <= i < y.Length ==> \n y[i] == \n if index(i, X_crd1) < X_crd1.Length then \n sum(X_val, X_crd, v_val, v_crd, X_pos[index(i, X_crd1)], 0, X_pos[index(i, X_crd1)+1], v_val.Length)\n else 0\n {\n var N : nat := X_len;\n y := new int[N](i => 0);\n\n var n : nat := 0;\n var kX , pX_end : nat;\n var kV : nat;\n var pV_end : nat := v_val.Length;\n var kX0, kV0 : nat;\n var k : nat;\n var pX_end1 := X_crd1.Length;\n \n\n while n < pX_end1\n {\n kX := X_pos[n];\n pX_end := X_pos[n + 1];\n kV := 0;\n\n while (kX < pX_end && kV < pV_end) \n {\n kX0 := X_crd[kX];\n kV0 := v_crd[kV];\n k := min(kV0, kX0);\n if (kX0 == k && kV0 == k) {\n y[X_crd1[n]] := y[X_crd1[n]] + X_val[kX] * v_val[kV];\n kX := kX + 1;\n kV := kV + 1;\n } else if (kX0 == k) {\n kX := kX + 1;\n } else if (kV0 == k) {\n kV := kV + 1;\n }\n }\n n := n + 1;\n }\n }\n\nmethod Main() {\n var X_val := new int[4](i => 1);\n var X_crd := new nat[4](i => if i <= 3 then (3 - i) * 2 else 0);\n var X_pos := new nat[5](i => i);\n var X_crd1 := new nat[4](i => i * 2);\n var X_pos1 := new nat[2](i => i * 8);\n var X_len := 8;\n\n var v_val := new int[4](i => 30 + i);\n var v_crd := new nat[4](i => i * 2);\n var v_pos := new nat[2](i => if i == 0 then 0 else 4);\n\n var y := DSpMSpV(\n X_val,\n X_crd,\n X_pos,\n X_crd1,\n X_len,\n v_val,\n v_crd\n );\n\n var i := 0;\n while i < 8 { print y[i]; print \"; \"; i := i + 1; }\n}\n\n" }, { "test_ID": "771", "test_file": "veri-sparse_tmp_tmp15fywna6_dafny_spmv.dfy", "ground_truth": "function sum(X_val: array, X_crd: array, v : array, b : int, k : int) : (s : int)\n reads X_val, X_crd, v\n requires X_val.Length >= b >= 0\n requires k <= X_val.Length\n requires X_val.Length == X_crd.Length\n requires forall i :: 0 <= i < X_crd.Length ==> 0 <= X_crd[i] < v.Length\n decreases k - b\n {\n if k <= b then \n 0\n else sum(X_val, X_crd, v, b + 1, k) + X_val[b] * v[X_crd[b]]\n }\n\n\nmethod SpMV(X_val: array, X_crd: array, X_pos: array, v : array) returns (y : array)\n requires X_crd.Length >= 1 \n requires X_crd.Length == X_val.Length;\n requires forall i, j :: 0 <= i < j < X_pos.Length ==> X_pos[i] <= X_pos[j];\n requires forall i :: 0 <= i < X_crd.Length ==> X_crd[i] < v.Length\n requires forall i :: 0 <= i < X_pos.Length ==> X_pos[i] <= X_val.Length\n requires X_pos.Length >= 1\n ensures y.Length + 1 == X_pos.Length\n ensures forall i :: 0 <= i < y.Length ==> y[i] == sum(X_val, X_crd, v, X_pos[i], X_pos[i + 1])\n {\n var N: nat := X_pos.Length - 1;\n y := new int[N](i => 0);\n var n: nat := 0;\n while n < N\n invariant n <= y.Length\n invariant forall i :: 0 <= i < n ==> y[i] == sum(X_val, X_crd, v, X_pos[i], X_pos[i + 1])\n invariant forall i :: n <= i < y.Length ==> y[i] == 0\n { \n var k: nat := X_pos[n];\n while k < X_pos[n + 1]\n invariant k <= X_pos[n + 1]\n invariant forall i :: n < i < y.Length ==> y[i] == 0\n invariant forall i :: 0 <= i < n ==> y[i] == sum(X_val, X_crd, v, X_pos[i], X_pos[i + 1])\n invariant y[n] + sum(X_val, X_crd, v, k, X_pos[n+1]) == sum(X_val, X_crd, v, X_pos[n], X_pos[n+1]) \n {\n y[n] := y[n] + X_val[k] * v[X_crd[k]];\n k := k + 1;\n }\n n := n + 1;\n }\n }\n\n\n// 0 0 0 0 0 0 1 0\n// 0 0 0 0 0 0 0 0\n// 0 0 0 0 1 0 0 0\n// 0 0 0 0 0 0 0 0\n// 0 0 1 0 0 0 0 0\n// 0 0 0 0 0 0 0 0\n// 1 0 0 0 0 0 0 0\n// 0 0 0 0 0 0 0 0\n\nmethod Main() {\n var X_val := new int[4](i => 1);\n var X_crd := new nat[4](i => if i <= 3 then (3 - i) * 2 else 0);\n var X_pos := new nat[9];\n X_pos[0] := 0;\n X_pos[1] := 1;\n X_pos[2] := 1;\n X_pos[3] := 2;\n X_pos[4] := 2;\n X_pos[5] := 3;\n X_pos[6] := 3;\n X_pos[7] := 4;\n X_pos[8] := 4;\n\n var v := new int[8];\n\n v[0] := 30;\n v[1] := 0;\n v[2] := 31;\n v[3] := 0;\n v[4] := 32;\n v[5] := 0;\n v[6] := 33;\n v[7] := 0;\n\n var y := SpMV(\n X_val,\n X_crd,\n X_pos,\n v\n );\n\n var i := 0;\n while i < 8 { print y[i]; print \"; \"; i := i + 1; }\n}\n", "hints_removed": "function sum(X_val: array, X_crd: array, v : array, b : int, k : int) : (s : int)\n reads X_val, X_crd, v\n requires X_val.Length >= b >= 0\n requires k <= X_val.Length\n requires X_val.Length == X_crd.Length\n requires forall i :: 0 <= i < X_crd.Length ==> 0 <= X_crd[i] < v.Length\n {\n if k <= b then \n 0\n else sum(X_val, X_crd, v, b + 1, k) + X_val[b] * v[X_crd[b]]\n }\n\n\nmethod SpMV(X_val: array, X_crd: array, X_pos: array, v : array) returns (y : array)\n requires X_crd.Length >= 1 \n requires X_crd.Length == X_val.Length;\n requires forall i, j :: 0 <= i < j < X_pos.Length ==> X_pos[i] <= X_pos[j];\n requires forall i :: 0 <= i < X_crd.Length ==> X_crd[i] < v.Length\n requires forall i :: 0 <= i < X_pos.Length ==> X_pos[i] <= X_val.Length\n requires X_pos.Length >= 1\n ensures y.Length + 1 == X_pos.Length\n ensures forall i :: 0 <= i < y.Length ==> y[i] == sum(X_val, X_crd, v, X_pos[i], X_pos[i + 1])\n {\n var N: nat := X_pos.Length - 1;\n y := new int[N](i => 0);\n var n: nat := 0;\n while n < N\n { \n var k: nat := X_pos[n];\n while k < X_pos[n + 1]\n {\n y[n] := y[n] + X_val[k] * v[X_crd[k]];\n k := k + 1;\n }\n n := n + 1;\n }\n }\n\n\n// 0 0 0 0 0 0 1 0\n// 0 0 0 0 0 0 0 0\n// 0 0 0 0 1 0 0 0\n// 0 0 0 0 0 0 0 0\n// 0 0 1 0 0 0 0 0\n// 0 0 0 0 0 0 0 0\n// 1 0 0 0 0 0 0 0\n// 0 0 0 0 0 0 0 0\n\nmethod Main() {\n var X_val := new int[4](i => 1);\n var X_crd := new nat[4](i => if i <= 3 then (3 - i) * 2 else 0);\n var X_pos := new nat[9];\n X_pos[0] := 0;\n X_pos[1] := 1;\n X_pos[2] := 1;\n X_pos[3] := 2;\n X_pos[4] := 2;\n X_pos[5] := 3;\n X_pos[6] := 3;\n X_pos[7] := 4;\n X_pos[8] := 4;\n\n var v := new int[8];\n\n v[0] := 30;\n v[1] := 0;\n v[2] := 31;\n v[3] := 0;\n v[4] := 32;\n v[5] := 0;\n v[6] := 33;\n v[7] := 0;\n\n var y := SpMV(\n X_val,\n X_crd,\n X_pos,\n v\n );\n\n var i := 0;\n while i < 8 { print y[i]; print \"; \"; i := i + 1; }\n}\n" }, { "test_ID": "772", "test_file": "veri-titan_tmp_tmpbg2iy0kf_spec_crypto_fntt512.dfy", "ground_truth": "// include \"ct_std2rev_model.dfy\"\n\n// abstract module ntt_impl {\n// import opened Seq\n// import opened Power\n// import opened Power2\n// import opened DivMod\n// import opened Mul\n\n// import opened pows_of_2\n// import opened ntt_index\n// import opened ntt_512_params\n// import opened mq_polys\n// import opened poly_view\n// import opened nth_root\n// import opened forward_ntt\n\n// method j_loop(a: elems, p: elems, t: pow2_t, d: pow2_t, j: nat, u: nat, ghost view: loop_view)\n// returns (a': elems)\n// requires u == j * (2 * d.full);\n// requires view.j_loop_inv(a, d, j);\n// requires t == view.lsize();\n// requires p == rev_mixed_powers_mont_table();\n// requires j < view.lsize().full;\n// ensures view.j_loop_inv(a', d, j + 1);\n// {\n// view.s_loop_inv_pre_lemma(a, d, j);\n\n// assert (2 * j) * d.full == j * (2 * d.full) by {\n// LemmaMulProperties();\n// }\n\n// rev_mixed_powers_mont_table_lemma(t, d, j);\n// var w := p[t.full + j];\n// // modmul(x_value(2 * j, d), R);\n\n// var s := u;\n// a' := a;\n\n// ghost var bi := 0;\n\n// while (s < u + d.full)\n// invariant view.s_loop_inv(a', d, j, s-u);\n// {\n// var a :elems := a';\n// var bi := s-u;\n\n// var _ := view.higher_points_view_index_lemma(a, d, j, bi);\n\n// var e := a[s];\n// var o := a[s + d.full];\n\n// var x := montmul(o, w);\n// a' := a[s+d.full := mqsub(e, x)];\n// a' := a'[s := mqadd(e, x)];\n// s := s + 1;\n\n// view.s_loop_inv_peri_lemma(a, a', d, j, bi);\n// }\n\n// assert s == u + d.full;\n// view.s_loop_inv_post_lemma(a', d, j, d.full);\n// }\n\n// method t_loop(a: elems, p: elems, t: pow2_t, d: pow2_t, ghost coeffs: elems)\n// returns (a': elems)\n// requires 0 <= d.exp < N.exp;\n// requires t_loop_inv(a, pow2_double(d), coeffs);\n// requires p == rev_mixed_powers_mont_table();\n// requires t == block_size(pow2_double(d));\n// ensures t_loop_inv(a', d, coeffs);\n// {\n// ghost var view := build_loop_view(coeffs, d);\n// view.j_loop_inv_pre_lemma(a, d);\n\n// var j := 0;\n// var u: nat := 0;\n// a' := a;\n\n// while (j < t.full)\n// invariant t == view.lsize();\n// invariant u == j * (2 * d.full);\n// invariant view.j_loop_inv(a', d, j);\n// {\n// a' := j_loop(a', p, t, d, j, u, view);\n\n// calc == {\n// u + 2 * d.full;\n// j * (2 * d.full) + 2 * d.full;\n// {\n// LemmaMulProperties();\n// }\n// (j + 1) * (2 * d.full);\n// }\n\n// j := j + 1;\n// u := u + 2 * d.full;\n// }\n\n// view.j_loop_inv_post_lemma(a', d, j);\n// }\n\n// method mulntt_ct(a: elems, p: elems)\n// returns (a': elems)\n// requires N == pow2_t_cons(512, 9);\n// requires p == rev_mixed_powers_mont_table();\n// ensures points_eval_inv(a', a, x_value, pow2(0));\n// {\n// var d := pow2(9);\n\n// assert d == N by {\n// Nth_root_lemma();\n// }\n\n// var t := pow2(0);\n\n// ghost var coeffs := a;\n// t_loop_inv_pre_lemma(a);\n\n// a' := a;\n\n// while (t.exp < 9)\n// invariant 0 <= d.exp <= N.exp;\n// invariant t == block_size(d);\n// invariant t_loop_inv(a', d, coeffs);\n// {\n// d := pow2_half(d);\n// a' := t_loop(a', p, t, d, coeffs);\n// t := pow2_double(t);\n// }\n \n// t_loop_inv_post_lemma(a', d, coeffs);\n// }\n// }\n", "hints_removed": "// include \"ct_std2rev_model.dfy\"\n\n// abstract module ntt_impl {\n// import opened Seq\n// import opened Power\n// import opened Power2\n// import opened DivMod\n// import opened Mul\n\n// import opened pows_of_2\n// import opened ntt_index\n// import opened ntt_512_params\n// import opened mq_polys\n// import opened poly_view\n// import opened nth_root\n// import opened forward_ntt\n\n// method j_loop(a: elems, p: elems, t: pow2_t, d: pow2_t, j: nat, u: nat, ghost view: loop_view)\n// returns (a': elems)\n// requires u == j * (2 * d.full);\n// requires view.j_loop_inv(a, d, j);\n// requires t == view.lsize();\n// requires p == rev_mixed_powers_mont_table();\n// requires j < view.lsize().full;\n// ensures view.j_loop_inv(a', d, j + 1);\n// {\n// view.s_loop_inv_pre_lemma(a, d, j);\n\n// assert (2 * j) * d.full == j * (2 * d.full) by {\n// LemmaMulProperties();\n// }\n\n// rev_mixed_powers_mont_table_lemma(t, d, j);\n// var w := p[t.full + j];\n// // modmul(x_value(2 * j, d), R);\n\n// var s := u;\n// a' := a;\n\n// ghost var bi := 0;\n\n// while (s < u + d.full)\n// invariant view.s_loop_inv(a', d, j, s-u);\n// {\n// var a :elems := a';\n// var bi := s-u;\n\n// var _ := view.higher_points_view_index_lemma(a, d, j, bi);\n\n// var e := a[s];\n// var o := a[s + d.full];\n\n// var x := montmul(o, w);\n// a' := a[s+d.full := mqsub(e, x)];\n// a' := a'[s := mqadd(e, x)];\n// s := s + 1;\n\n// view.s_loop_inv_peri_lemma(a, a', d, j, bi);\n// }\n\n// assert s == u + d.full;\n// view.s_loop_inv_post_lemma(a', d, j, d.full);\n// }\n\n// method t_loop(a: elems, p: elems, t: pow2_t, d: pow2_t, ghost coeffs: elems)\n// returns (a': elems)\n// requires 0 <= d.exp < N.exp;\n// requires t_loop_inv(a, pow2_double(d), coeffs);\n// requires p == rev_mixed_powers_mont_table();\n// requires t == block_size(pow2_double(d));\n// ensures t_loop_inv(a', d, coeffs);\n// {\n// ghost var view := build_loop_view(coeffs, d);\n// view.j_loop_inv_pre_lemma(a, d);\n\n// var j := 0;\n// var u: nat := 0;\n// a' := a;\n\n// while (j < t.full)\n// invariant t == view.lsize();\n// invariant u == j * (2 * d.full);\n// invariant view.j_loop_inv(a', d, j);\n// {\n// a' := j_loop(a', p, t, d, j, u, view);\n\n// calc == {\n// u + 2 * d.full;\n// j * (2 * d.full) + 2 * d.full;\n// {\n// LemmaMulProperties();\n// }\n// (j + 1) * (2 * d.full);\n// }\n\n// j := j + 1;\n// u := u + 2 * d.full;\n// }\n\n// view.j_loop_inv_post_lemma(a', d, j);\n// }\n\n// method mulntt_ct(a: elems, p: elems)\n// returns (a': elems)\n// requires N == pow2_t_cons(512, 9);\n// requires p == rev_mixed_powers_mont_table();\n// ensures points_eval_inv(a', a, x_value, pow2(0));\n// {\n// var d := pow2(9);\n\n// assert d == N by {\n// Nth_root_lemma();\n// }\n\n// var t := pow2(0);\n\n// ghost var coeffs := a;\n// t_loop_inv_pre_lemma(a);\n\n// a' := a;\n\n// while (t.exp < 9)\n// invariant 0 <= d.exp <= N.exp;\n// invariant t == block_size(d);\n// invariant t_loop_inv(a', d, coeffs);\n// {\n// d := pow2_half(d);\n// a' := t_loop(a', p, t, d, coeffs);\n// t := pow2_double(t);\n// }\n \n// t_loop_inv_post_lemma(a', d, coeffs);\n// }\n// }\n" }, { "test_ID": "773", "test_file": "veribetrkv-osdi2020_tmp_tmpra431m8q_docker-hdd_src_veribetrkv-linear_lib_Base_SetBijectivity.dfy", "ground_truth": "module SetBijectivity {\n lemma BijectivityImpliesEqualCardinality(setA: set, setB: set, relation: iset<(A, B)>)\n requires forall a :: a in setA ==> exists b :: b in setB && (a, b) in relation\n requires forall a1, a2, b :: a1 in setA && a2 in setA && b in setB && (a1, b) in relation && (a2, b) in relation ==> a1 == a2\n requires forall b :: b in setB ==> exists a :: a in setA && (a, b) in relation\n requires forall a, b1, b2 :: b1 in setB && b2 in setB && a in setA && (a, b1) in relation && (a, b2) in relation ==> b1 == b2\n ensures |setA| == |setB|\n {\n if |setA| == 0 {\n } else {\n var a :| a in setA;\n var b :| b in setB && (a, b) in relation;\n var setA' := setA - {a};\n var setB' := setB - {b};\n BijectivityImpliesEqualCardinality(setA', setB', relation);\n }\n }\n\n lemma CrossProductCardinality(setA: set, setB: set, cp: set<(A,B)>)\n requires cp == (set a, b | a in setA && b in setB :: (a,b))\n ensures |cp| == |setA| * |setB|;\n {\n if |setA| == 0 {\n assert setA == {};\n assert cp == {};\n } else {\n var x :| x in setA;\n var setA' := setA - {x};\n var cp' := (set a, b | a in setA' && b in setB :: (a,b));\n var line := (set a, b | a == x && b in setB :: (a,b));\n\n assert |line| == |setB| by {\n var relation := iset p : ((A, B), B) | p.0.1 == p.1;\n forall b | b in setB\n ensures exists p :: p in line && (p, b) in relation\n {\n var p := (x, b);\n assert p in line && (p, b) in relation;\n }\n BijectivityImpliesEqualCardinality(line, setB, relation);\n }\n\n CrossProductCardinality(setA', setB, cp');\n assert cp == cp' + line;\n assert cp' !! line;\n assert |cp'| == |setA'| * |setB|;\n assert |setA'| == |setA| - 1;\n assert |cp|\n == |cp' + line|\n == |cp'| + |line|\n == (|setA| - 1) * |setB| + |setB|\n == |setA| * |setB|;\n }\n }\n}\n\n", "hints_removed": "module SetBijectivity {\n lemma BijectivityImpliesEqualCardinality(setA: set, setB: set, relation: iset<(A, B)>)\n requires forall a :: a in setA ==> exists b :: b in setB && (a, b) in relation\n requires forall a1, a2, b :: a1 in setA && a2 in setA && b in setB && (a1, b) in relation && (a2, b) in relation ==> a1 == a2\n requires forall b :: b in setB ==> exists a :: a in setA && (a, b) in relation\n requires forall a, b1, b2 :: b1 in setB && b2 in setB && a in setA && (a, b1) in relation && (a, b2) in relation ==> b1 == b2\n ensures |setA| == |setB|\n {\n if |setA| == 0 {\n } else {\n var a :| a in setA;\n var b :| b in setB && (a, b) in relation;\n var setA' := setA - {a};\n var setB' := setB - {b};\n BijectivityImpliesEqualCardinality(setA', setB', relation);\n }\n }\n\n lemma CrossProductCardinality(setA: set, setB: set, cp: set<(A,B)>)\n requires cp == (set a, b | a in setA && b in setB :: (a,b))\n ensures |cp| == |setA| * |setB|;\n {\n if |setA| == 0 {\n } else {\n var x :| x in setA;\n var setA' := setA - {x};\n var cp' := (set a, b | a in setA' && b in setB :: (a,b));\n var line := (set a, b | a == x && b in setB :: (a,b));\n\n var relation := iset p : ((A, B), B) | p.0.1 == p.1;\n forall b | b in setB\n ensures exists p :: p in line && (p, b) in relation\n {\n var p := (x, b);\n }\n BijectivityImpliesEqualCardinality(line, setB, relation);\n }\n\n CrossProductCardinality(setA', setB, cp');\n == |cp' + line|\n == |cp'| + |line|\n == (|setA| - 1) * |setB| + |setB|\n == |setA| * |setB|;\n }\n }\n}\n\n" }, { "test_ID": "774", "test_file": "veribetrkv-osdi2020_tmp_tmpra431m8q_docker-hdd_src_veribetrkv-linear_lib_Base_Sets.dfy", "ground_truth": "module Sets {\n\n lemma {:opaque} ProperSubsetImpliesSmallerCardinality(a: set, b: set)\n requires a < b\n ensures |a| < |b|\n {\n assert |b| == |a| + |b-a|;\n }\n\n lemma {:opaque} SetInclusionImpliesSmallerCardinality(a: set, b: set)\n requires a <= b\n ensures |a| <= |b|\n {\n assert b == a + (b - a);\n }\n\n lemma {:opaque} SetInclusionImpliesStrictlySmallerCardinality(a: set, b: set)\n requires a < b\n ensures |a| < |b|\n {\n assert b == a + (b - a);\n }\n\n lemma {:opaque} SetInclusionAndEqualCardinalityImpliesSetEquality(a: set, b: set)\n requires a <= b\n requires |a| == |b|\n ensures a == b\n {\n assert b == a + (b - a);\n }\n\n function SetRange(n: int) : set\n {\n set i | 0 <= i < n\n }\n\n lemma CardinalitySetRange(n: int)\n requires n >= 0\n ensures |SetRange(n)| == n\n {\n if n == 0 {\n } else {\n CardinalitySetRange(n-1);\n assert SetRange(n)\n == SetRange(n-1) + {n-1};\n }\n }\n}\n\n", "hints_removed": "module Sets {\n\n lemma {:opaque} ProperSubsetImpliesSmallerCardinality(a: set, b: set)\n requires a < b\n ensures |a| < |b|\n {\n }\n\n lemma {:opaque} SetInclusionImpliesSmallerCardinality(a: set, b: set)\n requires a <= b\n ensures |a| <= |b|\n {\n }\n\n lemma {:opaque} SetInclusionImpliesStrictlySmallerCardinality(a: set, b: set)\n requires a < b\n ensures |a| < |b|\n {\n }\n\n lemma {:opaque} SetInclusionAndEqualCardinalityImpliesSetEquality(a: set, b: set)\n requires a <= b\n requires |a| == |b|\n ensures a == b\n {\n }\n\n function SetRange(n: int) : set\n {\n set i | 0 <= i < n\n }\n\n lemma CardinalitySetRange(n: int)\n requires n >= 0\n ensures |SetRange(n)| == n\n {\n if n == 0 {\n } else {\n CardinalitySetRange(n-1);\n == SetRange(n-1) + {n-1};\n }\n }\n}\n\n" }, { "test_ID": "775", "test_file": "verification-class_tmp_tmpz9ik148s_2022_chapter05-distributed-state-machines_exercises_UtilitiesLibrary.dfy", "ground_truth": "module UtilitiesLibrary {\n function DropLast(theSeq: seq) : seq\n requires 0 < |theSeq|\n {\n theSeq[..|theSeq|-1]\n }\n\n function Last(theSeq: seq) : T\n requires 0 < |theSeq|\n {\n theSeq[|theSeq|-1]\n }\n\n function UnionSeqOfSets(theSets: seq>) : set\n {\n if |theSets| == 0 then {} else\n UnionSeqOfSets(DropLast(theSets)) + Last(theSets)\n }\n\n // As you can see, Dafny's recursion heuristics easily complete the recursion\n // induction proofs, so these two statements could easily be ensures of\n // UnionSeqOfSets. However, the quantifiers combine with native map axioms\n // to be a bit trigger-happy, so we've pulled them into independent lemmas\n // you can invoke only when needed.\n // Suggestion: hide calls to this lemma in a an\n // assert P by { SetsAreSubsetsOfUnion(...) }\n // construct so you can get your conclusion without \"polluting\" the rest of the\n // lemma proof context with this enthusiastic forall.\n lemma SetsAreSubsetsOfUnion(theSets: seq>)\n ensures forall idx | 0<=idx<|theSets| :: theSets[idx] <= UnionSeqOfSets(theSets)\n {\n }\n\n lemma EachUnionMemberBelongsToASet(theSets: seq>)\n ensures forall member | member in UnionSeqOfSets(theSets) ::\n exists idx :: 0<=idx<|theSets| && member in theSets[idx]\n {\n }\n\n // Convenience function for learning a particular index (invoking Hilbert's\n // Choose on the exists in EachUnionMemberBelongsToASet).\n lemma GetIndexForMember(theSets: seq>, member: T) returns (idx:int)\n requires member in UnionSeqOfSets(theSets)\n ensures 0<=idx<|theSets|\n ensures member in theSets[idx]\n {\n EachUnionMemberBelongsToASet(theSets);\n var chosenIdx :| 0<=chosenIdx<|theSets| && member in theSets[chosenIdx];\n idx := chosenIdx;\n }\n\n datatype Option = Some(value:T) | None\n\n function {:opaque} MapRemoveOne(m:map, key:K) : (m':map)\n ensures forall k :: k in m && k != key ==> k in m'\n ensures forall k :: k in m' ==> k in m && k != key\n ensures forall j :: j in m' ==> m'[j] == m[j]\n ensures |m'.Keys| <= |m.Keys|\n ensures |m'| <= |m|\n {\n var m':= map j | j in m && j != key :: m[j];\n assert m'.Keys == m.Keys - {key};\n m'\n }\n\n ////////////// Library code for exercises 12 and 14 /////////////////////\n\n // This is tagged union, a \"sum\" datatype.\n datatype Direction = North() | East() | South() | West()\n\n function TurnRight(direction:Direction) : Direction\n {\n // This function introduces two new bis of syntax.\n // First, the if-else expression: if then T else T\n // Second, the element.Ctor? built-in predicate, which tests whether\n // the datatype `element` was built by `Ctor`.\n if direction.North?\n then East\n else if direction.East?\n then South\n else if direction.South?\n then West\n else // By elimination, West!\n North\n }\n\n lemma Rotation()\n {\n assert TurnRight(North) == East;\n }\n\n function TurnLeft(direction:Direction) : Direction\n {\n // Another nice way to take apart a datatype element is with match-case\n // construct. Each case argument is a constructor; each body must be of the\n // same type, which is the type of the entire `match` expression.\n match direction {\n case North => West\n case West => South\n case South => East // Try changing \"East\" to 7.\n case East => North\n }\n }\n\n ////////////// Library code for exercises 13 and 14 /////////////////////\n\n // This whole product-sum idea gets clearer when we use both powers\n // (struct/product, union/sum) at the same time.\n\n datatype Meat = Salami | Ham\n datatype Cheese = Provolone | Swiss | Cheddar | Jack\n datatype Veggie = Olive | Onion | Pepper\n datatype Order =\n Sandwich(meat:Meat, cheese:Cheese)\n | Pizza(meat:Meat, veggie:Veggie)\n | Appetizer(cheese:Cheese)\n\n // There are 2 Meats, 4 Cheeses, and 3 Veggies.\n // Thus there are 8 Sandwiches, 6 Pizzas, and 4 Appetizers.\n // Thus there are 8+6+4 = 18 Orders.\n // This is why they're called \"algebraic\" datatypes.\n\n}\n\n", "hints_removed": "module UtilitiesLibrary {\n function DropLast(theSeq: seq) : seq\n requires 0 < |theSeq|\n {\n theSeq[..|theSeq|-1]\n }\n\n function Last(theSeq: seq) : T\n requires 0 < |theSeq|\n {\n theSeq[|theSeq|-1]\n }\n\n function UnionSeqOfSets(theSets: seq>) : set\n {\n if |theSets| == 0 then {} else\n UnionSeqOfSets(DropLast(theSets)) + Last(theSets)\n }\n\n // As you can see, Dafny's recursion heuristics easily complete the recursion\n // induction proofs, so these two statements could easily be ensures of\n // UnionSeqOfSets. However, the quantifiers combine with native map axioms\n // to be a bit trigger-happy, so we've pulled them into independent lemmas\n // you can invoke only when needed.\n // Suggestion: hide calls to this lemma in a an\n // assert P by { SetsAreSubsetsOfUnion(...) }\n // construct so you can get your conclusion without \"polluting\" the rest of the\n // lemma proof context with this enthusiastic forall.\n lemma SetsAreSubsetsOfUnion(theSets: seq>)\n ensures forall idx | 0<=idx<|theSets| :: theSets[idx] <= UnionSeqOfSets(theSets)\n {\n }\n\n lemma EachUnionMemberBelongsToASet(theSets: seq>)\n ensures forall member | member in UnionSeqOfSets(theSets) ::\n exists idx :: 0<=idx<|theSets| && member in theSets[idx]\n {\n }\n\n // Convenience function for learning a particular index (invoking Hilbert's\n // Choose on the exists in EachUnionMemberBelongsToASet).\n lemma GetIndexForMember(theSets: seq>, member: T) returns (idx:int)\n requires member in UnionSeqOfSets(theSets)\n ensures 0<=idx<|theSets|\n ensures member in theSets[idx]\n {\n EachUnionMemberBelongsToASet(theSets);\n var chosenIdx :| 0<=chosenIdx<|theSets| && member in theSets[chosenIdx];\n idx := chosenIdx;\n }\n\n datatype Option = Some(value:T) | None\n\n function {:opaque} MapRemoveOne(m:map, key:K) : (m':map)\n ensures forall k :: k in m && k != key ==> k in m'\n ensures forall k :: k in m' ==> k in m && k != key\n ensures forall j :: j in m' ==> m'[j] == m[j]\n ensures |m'.Keys| <= |m.Keys|\n ensures |m'| <= |m|\n {\n var m':= map j | j in m && j != key :: m[j];\n m'\n }\n\n ////////////// Library code for exercises 12 and 14 /////////////////////\n\n // This is tagged union, a \"sum\" datatype.\n datatype Direction = North() | East() | South() | West()\n\n function TurnRight(direction:Direction) : Direction\n {\n // This function introduces two new bis of syntax.\n // First, the if-else expression: if then T else T\n // Second, the element.Ctor? built-in predicate, which tests whether\n // the datatype `element` was built by `Ctor`.\n if direction.North?\n then East\n else if direction.East?\n then South\n else if direction.South?\n then West\n else // By elimination, West!\n North\n }\n\n lemma Rotation()\n {\n }\n\n function TurnLeft(direction:Direction) : Direction\n {\n // Another nice way to take apart a datatype element is with match-case\n // construct. Each case argument is a constructor; each body must be of the\n // same type, which is the type of the entire `match` expression.\n match direction {\n case North => West\n case West => South\n case South => East // Try changing \"East\" to 7.\n case East => North\n }\n }\n\n ////////////// Library code for exercises 13 and 14 /////////////////////\n\n // This whole product-sum idea gets clearer when we use both powers\n // (struct/product, union/sum) at the same time.\n\n datatype Meat = Salami | Ham\n datatype Cheese = Provolone | Swiss | Cheddar | Jack\n datatype Veggie = Olive | Onion | Pepper\n datatype Order =\n Sandwich(meat:Meat, cheese:Cheese)\n | Pizza(meat:Meat, veggie:Veggie)\n | Appetizer(cheese:Cheese)\n\n // There are 2 Meats, 4 Cheeses, and 3 Veggies.\n // Thus there are 8 Sandwiches, 6 Pizzas, and 4 Appetizers.\n // Thus there are 8+6+4 = 18 Orders.\n // This is why they're called \"algebraic\" datatypes.\n\n}\n\n" }, { "test_ID": "776", "test_file": "verified-isort_tmp_tmp7hhb8ei__dafny_isort.dfy", "ground_truth": "// Dafny is designed to be familiar to those programming in an OOP language like\n// Java, so, we have plain old ordinary mutable arrays rather than the functional\n// list data structures that we saw in Coq. This means that unlike our Coq\n// and Python examples, we can sort our array in-place and avoid needing a whole\n// bunch of intermediary allocations.\n\n// Just as before, we need a way of defining what it means for an array of nats\n// to be sorted:\npredicate sorted(a: seq)\n{\n true // TODO\n}\n\nmethod Isort(a: array)\n modifies a\n ensures sorted(a[..])\n{\n if a.Length == 0 {\n return;\n }\n\n // Here is the thing that we have to get Dafny to understand:\n //\n // We are going to iterate from left to right in the input array. As we\n // progress, everything to the left of the current element is going to be\n // in sorted order, so that when we finish iterating through the array all\n // elements are going to be in their correct order.\n //\n // Let's look at some iteration of that main loop, where we're neither at the\n // beginning nor at the end of the process:\n // \n // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\n // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n // a | \u2713 | \u2713 | \u2713 | \u2713 | \u2713 | = | | | | | | | | | | |\n // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n // \\------------------/^\n // These elements are |\n // in sorted order n == 5: this element will be placed in its right place\n // by the end of the current loop iteration...\n //\n\n // In particular, there is some j on [0..n) such that:\n //\n // 1. j on [1..n) when a[j-1] <= a[n] and a[j] > a[n];\n // 2. j == 0 when a[0] > a[n].\n //\n // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\n // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n // a | <=| <=| <=| > | > | = | | | | | | | | | | |\n // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n // \\----------/^\\-----/\n // <= a[n] | > a[n]\n // |\n // +--- k == 3: This is the index of where a[5] should go!\n\n // So, we'll shift all the elements on [j, n) over by one, so they're now \n // located on [j+1, n+1), and then place the old value of a[n] into a[j].\n //\n // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\n // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n // a | <=| <=| <=| = | > | > | | | | | | | | | | |\n // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n // \\----------/ \\-----/\n // <= a[n] > a[n]\n //\n // And now we have one more element in the correct place! We are now ready\n // to begin the next iteration of the loop.\n\n var n := 1;\n while n < a.Length\n {\n\n var curr := a[n];\n\n // 1. Find our pivot position k, the location where we should insert the\n // current value.\n var k := n;\n while k > 0 && a[k-1] > curr\n {\n k := k-1;\n }\n\n a[n] := a[n-1]; // Hack to help the verifier with invariant sorted(a[k..n+1])\n\n // 2. Shift all elements between k and n to the right by one.\n var j := n-1;\n while j >= k\n {\n a[j+1] := a[j];\n j := j-1;\n }\n\n // 3. Put curr in its place!\n a[k] := curr;\n n := n + 1;\n }\n}\n\n", "hints_removed": "// Dafny is designed to be familiar to those programming in an OOP language like\n// Java, so, we have plain old ordinary mutable arrays rather than the functional\n// list data structures that we saw in Coq. This means that unlike our Coq\n// and Python examples, we can sort our array in-place and avoid needing a whole\n// bunch of intermediary allocations.\n\n// Just as before, we need a way of defining what it means for an array of nats\n// to be sorted:\npredicate sorted(a: seq)\n{\n true // TODO\n}\n\nmethod Isort(a: array)\n modifies a\n ensures sorted(a[..])\n{\n if a.Length == 0 {\n return;\n }\n\n // Here is the thing that we have to get Dafny to understand:\n //\n // We are going to iterate from left to right in the input array. As we\n // progress, everything to the left of the current element is going to be\n // in sorted order, so that when we finish iterating through the array all\n // elements are going to be in their correct order.\n //\n // Let's look at some iteration of that main loop, where we're neither at the\n // beginning nor at the end of the process:\n // \n // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\n // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n // a | \u2713 | \u2713 | \u2713 | \u2713 | \u2713 | = | | | | | | | | | | |\n // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n // \\------------------/^\n // These elements are |\n // in sorted order n == 5: this element will be placed in its right place\n // by the end of the current loop iteration...\n //\n\n // In particular, there is some j on [0..n) such that:\n //\n // 1. j on [1..n) when a[j-1] <= a[n] and a[j] > a[n];\n // 2. j == 0 when a[0] > a[n].\n //\n // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\n // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n // a | <=| <=| <=| > | > | = | | | | | | | | | | |\n // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n // \\----------/^\\-----/\n // <= a[n] | > a[n]\n // |\n // +--- k == 3: This is the index of where a[5] should go!\n\n // So, we'll shift all the elements on [j, n) over by one, so they're now \n // located on [j+1, n+1), and then place the old value of a[n] into a[j].\n //\n // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\n // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n // a | <=| <=| <=| = | > | > | | | | | | | | | | |\n // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n // \\----------/ \\-----/\n // <= a[n] > a[n]\n //\n // And now we have one more element in the correct place! We are now ready\n // to begin the next iteration of the loop.\n\n var n := 1;\n while n < a.Length\n {\n\n var curr := a[n];\n\n // 1. Find our pivot position k, the location where we should insert the\n // current value.\n var k := n;\n while k > 0 && a[k-1] > curr\n {\n k := k-1;\n }\n\n a[n] := a[n-1]; // Hack to help the verifier with invariant sorted(a[k..n+1])\n\n // 2. Shift all elements between k and n to the right by one.\n var j := n-1;\n while j >= k\n {\n a[j+1] := a[j];\n j := j-1;\n }\n\n // 3. Put curr in its place!\n a[k] := curr;\n n := n + 1;\n }\n}\n\n" }, { "test_ID": "777", "test_file": "verified-using-dafny_tmp_tmp7jatpjyn_longestZero.dfy", "ground_truth": "function getSize(i: int, j:int) : int\n{\n j - i + 1 \n}\n\n// For a given integer array, let's find the longest subesquence of 0s.\n// sz: size, pos: position. a[pos..(pos+sz)] will be all zeros\nmethod longestZero(a: array) returns (sz:int, pos:int) \n requires 1 <= a.Length\n ensures 0 <= sz <= a.Length\n ensures 0 <= pos < a.Length\n ensures pos + sz <= a.Length\n ensures forall i:int :: pos <= i < pos + sz ==> a[i] == 0\n ensures forall i,j :: (0 <= i < j < a.Length && getSize(i, j) > sz) ==> exists k :: i <= k <= j && a[k] != 0\n{\n var b := new int[a.Length]; // if b[i] == n, then a[i], a[i-1], ... a[i-n+1] will be all zeros and (i-n ==0 or a[i-n] !=0)\n if a[0] == 0\n {b[0] := 1;}\n else\n {b[0] := 0;}\n\n var idx:int := 0;\n while idx < a.Length - 1 // idx <- 0 to a.Length - 2\n invariant 0 <= idx <= a.Length - 1\n invariant forall i:int :: 0 <= i <= idx ==> 0 <= b[i] <= a.Length\n invariant forall i:int :: 0 <= i <= idx ==> -1 <= i - b[i]\n invariant forall i:int :: 0 <= i <= idx ==> (forall j:int :: i-b[i] < j <= i ==> a[j] == 0) \n invariant forall i:int :: 0 <= i <= idx ==> ( 0 <= i - b[i] ==> a[i - b[i]] != 0 )\n {\n if a[idx + 1] == 0\n { b[idx + 1] := b[idx] + 1; }\n else\n { b[idx + 1] := 0;}\n\n idx := idx + 1;\n }\n\n\n idx := 1;\n sz := b[0];\n pos := 0;\n // Let's find maximum of array b. That is the desired sz.\n while idx < a.Length\n invariant 1 <= idx <= b.Length\n\n invariant 0 <= sz <= a.Length\n invariant 0 <= pos < a.Length\n invariant pos + sz <= a.Length\n\n invariant forall i:int :: 0 <= i < idx ==> b[i] <= sz\n invariant forall i:int :: pos <= i < pos + sz ==> a[i] == 0\n invariant forall i, j:int :: (0 <= i < j < idx && getSize(i,j) > sz) ==> a[j-b[j]] != 0\n {\n // find max\n if b[idx] > sz \n { \n sz := b[idx]; \n pos := idx - b[idx] + 1;\n }\n idx := idx + 1;\n }\n}\n\n\n\nmethod Main()\n{\n var a := new int[10];\n forall i | 0 <= i < a.Length\n { a[i] := 0;}\n \n a[3] := 1;\n var sz, pos := longestZero(a);\n print a[..], \"\\n\";\n print a[pos..(sz+pos)], \"\\n\";\n}\n\n\n\n", "hints_removed": "function getSize(i: int, j:int) : int\n{\n j - i + 1 \n}\n\n// For a given integer array, let's find the longest subesquence of 0s.\n// sz: size, pos: position. a[pos..(pos+sz)] will be all zeros\nmethod longestZero(a: array) returns (sz:int, pos:int) \n requires 1 <= a.Length\n ensures 0 <= sz <= a.Length\n ensures 0 <= pos < a.Length\n ensures pos + sz <= a.Length\n ensures forall i:int :: pos <= i < pos + sz ==> a[i] == 0\n ensures forall i,j :: (0 <= i < j < a.Length && getSize(i, j) > sz) ==> exists k :: i <= k <= j && a[k] != 0\n{\n var b := new int[a.Length]; // if b[i] == n, then a[i], a[i-1], ... a[i-n+1] will be all zeros and (i-n ==0 or a[i-n] !=0)\n if a[0] == 0\n {b[0] := 1;}\n else\n {b[0] := 0;}\n\n var idx:int := 0;\n while idx < a.Length - 1 // idx <- 0 to a.Length - 2\n {\n if a[idx + 1] == 0\n { b[idx + 1] := b[idx] + 1; }\n else\n { b[idx + 1] := 0;}\n\n idx := idx + 1;\n }\n\n\n idx := 1;\n sz := b[0];\n pos := 0;\n // Let's find maximum of array b. That is the desired sz.\n while idx < a.Length\n\n\n {\n // find max\n if b[idx] > sz \n { \n sz := b[idx]; \n pos := idx - b[idx] + 1;\n }\n idx := idx + 1;\n }\n}\n\n\n\nmethod Main()\n{\n var a := new int[10];\n forall i | 0 <= i < a.Length\n { a[i] := 0;}\n \n a[3] := 1;\n var sz, pos := longestZero(a);\n print a[..], \"\\n\";\n print a[pos..(sz+pos)], \"\\n\";\n}\n\n\n\n" }, { "test_ID": "778", "test_file": "vfag_tmp_tmpc29dxm1j_Verificacion_torneo.dfy", "ground_truth": "method torneo(Valores : array?, i : int, j : int, k : int) returns (pos_padre : int, pos_madre : int)\n requires Valores != null && Valores.Length >= 20 && Valores.Length < 50 && i >= 0 && j >= 0 && k >= 0 \n requires i < Valores.Length && j < Valores.Length && k < Valores.Length && i != j && j != k && k != i \n ensures exists p, q, r | p in {i, j, k} && q in {i, j, k} && r in {i, j, k} && p != q && q != r && p != r :: Valores[p] >= Valores[q] >= Valores[r] && pos_padre == p && pos_madre == q // Q\n\n{\n \n assert (Valores[i] < Valores[j] && ((Valores[j] < Valores[k] && exists r | r in {i, j, k} && k != j && j != r && k != r :: Valores[k] >= Valores[j] >= Valores[r]) || (Valores[j] >= Valores[k] && ((Valores[i] < Valores[k] && exists r | r in {i, j, k} && j != k && k != r && j != r :: Valores[j] >= Valores[k] >= Valores[r]) || (Valores[i] >= Valores[k] && exists r | r in {i, j, k} && j != i && i != r && j != r :: Valores[j] >= Valores[i] >= Valores[r]))))) || (Valores[i] >= Valores[j] && ((Valores[j] >= Valores[k] && exists r | r in {i, j, k} && i != j && j != r && i != r :: Valores[i] >= Valores[j] >= Valores[r]) || (Valores[j] < Valores[k] && ((Valores[i] < Valores[k] && exists r | r in {i, j, k} && k != i && i != r && k != r :: Valores[k] >= Valores[i] >= Valores[r]) || (Valores[i] >= Valores[k] && exists r | r in {i, j, k} && i != k && k != r && i != r :: Valores[i] >= Valores[k] >= Valores[r]))))) ; // R : pmd(if..., Q)\n\n if Valores[i] < Valores[j] {\n\n assert (Valores[j] < Valores[k] && exists r | r in {i, j, k} && k != j && j != r && k != r :: Valores[k] >= Valores[j] >= Valores[r]) || (Valores[j] >= Valores[k] && ((Valores[i] < Valores[k] && exists r | r in {i, j, k} && j != k && k != r && j != r :: Valores[j] >= Valores[k] >= Valores[r]) || (Valores[i] >= Valores[k] && exists r | r in {i, j, k} && j != i && i != r && j != r :: Valores[j] >= Valores[i] >= Valores[r]))) ; // R1 : pmd(if..., Q)\n \n if Valores[j] < Valores[k] {\n\n assert exists r | r in {i, j, k} && k != j && j != r && k != r :: Valores[k] >= Valores[j] >= Valores[r] ; // R11 : pmd(pos_padre := k, R12)\n\n pos_padre := k ;\n \n assert exists p, r | p in {i, j, k} && r in {i, j, k} && p != j && j != r && p != r :: Valores[p] >= Valores[j] >= Valores[r] && pos_padre == p ; // R12 : pmd(pos_madre := j, Q) \n\n pos_madre := j ;\n\n assert exists p, q, r | p in {i, j, k} && q in {i, j, k} && r in {i, j, k} && p != q && q != r && p != r :: Valores[p] >= Valores[q] >= Valores[r] && pos_padre == p && pos_madre == q ; // Q\n\n } else {\n\n assert (Valores[i] < Valores[k] && exists r | r in {i, j, k} && j != k && k != r && j != r :: Valores[j] >= Valores[k] >= Valores[r]) || (Valores[i] >= Valores[k] && exists r | r in {i, j, k} && j != i && i != r && j != r :: Valores[j] >= Valores[i] >= Valores[r]) ; // R2 : pmd(if..., Q)\n \n if Valores[i] < Valores[k] {\n\n assert exists r | r in {i, j, k} && j != k && k != r && j != r :: Valores[j] >= Valores[k] >= Valores[r] ; // R13 : pmd(pos_padre := j, R14)\n\n pos_padre := j ;\n\n assert exists p, r | p in {i, j, k} && r in {i, j, k} && p != k && k != r && p != r :: Valores[p] >= Valores[k] >= Valores[r] && pos_padre == p ; // R14 : pmd(pos_madre := k, Q) \n\n pos_madre := k ;\n\n assert exists p, q, r | p in {i, j, k} && q in {i, j, k} && r in {i, j, k} && p != q && q != r && p != r :: Valores[p] >= Valores[q] >= Valores[r] && pos_padre == p && pos_madre == q ; // Q\n\n } else {\n\n assert exists r | r in {i, j, k} && j != i && i != r && j != r :: Valores[j] >= Valores[i] >= Valores[r] ; // R15 : pmd(pos_padre := j, R16)\n\n pos_padre := j ;\n\n assert exists p, r | p in {i, j, k} && r in {i, j, k} && p != i && i != r && p != r :: Valores[p] >= Valores[i] >= Valores[r] && pos_padre == p ; // R16 : pmd(pos_madre := i, Q) \n\n pos_madre := i ;\n\n assert exists p, q, r | p in {i, j, k} && q in {i, j, k} && r in {i, j, k} && p != q && q != r && p != r :: Valores[p] >= Valores[q] >= Valores[r] && pos_padre == p && pos_madre == q ; // Q\n\n }\n\n }\n\n } else {\n\n assert (Valores[j] >= Valores[k] && exists r | r in {i, j, k} && i != j && j != r && i != r :: Valores[i] >= Valores[j] >= Valores[r]) || (Valores[j] < Valores[k] && ((Valores[i] < Valores[k] && exists r | r in {i, j, k} && k != i && i != r && k != r :: Valores[k] >= Valores[i] >= Valores[r]) || (Valores[i] >= Valores[k] && exists r | r in {i, j, k} && i != k && k != r && i != r :: Valores[i] >= Valores[k] >= Valores[r]))) ; // R3 : pmd(if..., Q)\n\n if Valores[j] >= Valores[k] {\n \n assert exists r | r in {i, j, k} && i != j && j != r && i != r :: Valores[i] >= Valores[j] >= Valores[r] ; // R17 : pmd(pos_padre := i, R18) \n\n pos_padre := i ;\n\n assert exists p, r | p in {i, j, k} && r in {i, j, k} && p != j && j != r && p != r :: Valores[p] >= Valores[j] >= Valores[r] && pos_padre == p ; // R18 : pmd(pos_madre := j, Q) \n\n pos_madre := j ;\n\n assert exists p, q, r | p in {i, j, k} && q in {i, j, k} && r in {i, j, k} && p != q && q != r && p != r :: Valores[p] >= Valores[q] >= Valores[r] && pos_padre == p && pos_madre == q ; // Q\n\n } else {\n\n assert (Valores[i] < Valores[k] && exists r | r in {i, j, k} && k != i && i != r && k != r :: Valores[k] >= Valores[i] >= Valores[r]) || (Valores[i] >= Valores[k] && exists r | r in {i, j, k} && i != k && k != r && i != r :: Valores[i] >= Valores[k] >= Valores[r]) ; // R4 : pmd(if..., Q)\n\n if Valores[i] < Valores[k] {\n\n assert exists r | r in {i, j, k} && k != i && i != r && k != r :: Valores[k] >= Valores[i] >= Valores[r] ; // R19 : pmd(pos_padre := k, R110) \n\n pos_padre := k ;\n\n assert exists p, r | p in {i, j, k} && r in {i, j, k} && p != i && i != r && p != r :: Valores[p] >= Valores[i] >= Valores[r] && pos_padre == p ; // R110 : pmd(pos_madre := i, Q) \n\n pos_madre := i ;\n\n assert exists p, q, r | p in {i, j, k} && q in {i, j, k} && r in {i, j, k} && p != q && q != r && p != r :: Valores[p] >= Valores[q] >= Valores[r] && pos_padre == p && pos_madre == q ; // Q\n\n } else {\n\n assert exists r | r in {i, j, k} && i != k && k != r && i != r :: Valores[i] >= Valores[k] >= Valores[r] ; // R111 : pmd(pos_padre := i, R112) \n\n pos_padre := i ;\n\n assert exists p, r | p in {i, j, k} && r in {i, j, k} && p != k && k != r && p != r :: Valores[p] >= Valores[k] >= Valores[r] && pos_padre == p ; // R112 : pmd(pos_madre := k, Q) \n\n pos_madre := k ;\n\n assert exists p, q, r | p in {i, j, k} && q in {i, j, k} && r in {i, j, k} && p != q && q != r && p != r :: Valores[p] >= Valores[q] >= Valores[r] && pos_padre == p && pos_madre == q ; // Q\n \n }\n\n assert exists p, q, r | p in {i, j, k} && q in {i, j, k} && r in {i, j, k} && p != q && q != r && p != r :: Valores[p] >= Valores[q] >= Valores[r] && pos_padre == p && pos_madre == q ; // Q\n \n }\n\n assert exists p, q, r | p in {i, j, k} && q in {i, j, k} && r in {i, j, k} && p != q && q != r && p != r :: Valores[p] >= Valores[q] >= Valores[r] && pos_padre == p && pos_madre == q ; // Q\n \n }\n\n assert exists p, q, r | p in {i, j, k} && q in {i, j, k} && r in {i, j, k} && p != q && q != r && p != r :: Valores[p] >= Valores[q] >= Valores[r] && pos_padre == p && pos_madre == q ; // Q\n\n}\n", "hints_removed": "method torneo(Valores : array?, i : int, j : int, k : int) returns (pos_padre : int, pos_madre : int)\n requires Valores != null && Valores.Length >= 20 && Valores.Length < 50 && i >= 0 && j >= 0 && k >= 0 \n requires i < Valores.Length && j < Valores.Length && k < Valores.Length && i != j && j != k && k != i \n ensures exists p, q, r | p in {i, j, k} && q in {i, j, k} && r in {i, j, k} && p != q && q != r && p != r :: Valores[p] >= Valores[q] >= Valores[r] && pos_padre == p && pos_madre == q // Q\n\n{\n \n\n if Valores[i] < Valores[j] {\n\n \n if Valores[j] < Valores[k] {\n\n\n pos_padre := k ;\n \n\n pos_madre := j ;\n\n\n } else {\n\n \n if Valores[i] < Valores[k] {\n\n\n pos_padre := j ;\n\n\n pos_madre := k ;\n\n\n } else {\n\n\n pos_padre := j ;\n\n\n pos_madre := i ;\n\n\n }\n\n }\n\n } else {\n\n\n if Valores[j] >= Valores[k] {\n \n\n pos_padre := i ;\n\n\n pos_madre := j ;\n\n\n } else {\n\n\n if Valores[i] < Valores[k] {\n\n\n pos_padre := k ;\n\n\n pos_madre := i ;\n\n\n } else {\n\n\n pos_padre := i ;\n\n\n pos_madre := k ;\n\n \n }\n\n \n }\n\n \n }\n\n\n}\n" }, { "test_ID": "779", "test_file": "vfag_tmp_tmpc29dxm1j_mergesort.dfy", "ground_truth": "method ordenar_mergesort(V : array?)\n\n requires V != null\n \n modifies V\n\n{\n \n mergesort(V, 0, V.Length - 1) ;\n \n}\n\n\n\nmethod mergesort(V : array?, c : int, f : int) \n\n requires V != null\n requires c >= 0 && f <= V.Length\n \n decreases f - c\n\n modifies V\n\n{\n \n if c < f {\n \n var m : int ;\n\tm := c + (f - c) / 2 ;\n \n mergesort(V, c, m) ;\n mergesort(V, m + 1, f) ;\n\n mezclar(V, c, m, f) ;\n \n }\n \n}\n\n\n\nmethod mezclar(V: array?, c : int, m : int, f : int)\n\n requires V != null\n requires c <= m <= f\n requires 0 <= c <= V.Length\n requires 0 <= m <= V.Length\n requires 0 <= f <= V.Length\n\n modifies V\n\n{\n\n var V1 : array? ;\n var j : nat ;\n\n V1 := new int[m - c + 1] ;\n j := 0 ;\n \n while j < V1.Length && c + j < V.Length\n \n invariant 0 <= j <= V1.Length\n invariant 0 <= c + j <= V.Length\n \n decreases V1.Length - j\n \n {\n\n V1[j] := V[c + j] ;\n j := j + 1 ;\n \n }\n\n\n var V2 : array? ;\n var k : nat ;\n\n V2 := new int[f - m] ; \n k := 0 ;\n \n while k < V2.Length && m + k + 1 < V.Length\n \n invariant 0 <= k <= V2.Length\n invariant 0 <= m + k <= V.Length\n \n decreases V2.Length - k\n \n {\n \n V2[k] := V[m + k + 1] ;\n k := k + 1 ;\n \n }\n\n\n var i : nat ;\n\n i := 0 ;\n j := 0 ;\n k := 0 ;\n \n while i < f - c + 1 && \n j <= V1.Length && \n k <= V2.Length && \n c + i < V.Length\n \n invariant 0 <= i <= f - c + 1\n \n decreases f - c - i\n \n {\n \n if j >= V1.Length && k >= V2.Length {\n \n break ;\n \n }\n \n else if j >= V1.Length {\n \n V[c + i] := V2[k] ;\n k := k + 1 ;\n \n }\n \n else if k >= V2.Length {\n \n V[c + i] := V1[j] ;\n j := j + 1 ;\n \n }\n \n else {\n \n if V1[j] <= V2[k] {\n \n V[c + i] := V1[j] ;\n j := j + 1 ;\n \n }\n \n else if V1[j] > V2[k] {\n \n V[c + i] := V2[k] ;\n k := k + 1 ;\n \n }\n \n }\n \n i := i + 1 ;\n \n }\n \n}\n", "hints_removed": "method ordenar_mergesort(V : array?)\n\n requires V != null\n \n modifies V\n\n{\n \n mergesort(V, 0, V.Length - 1) ;\n \n}\n\n\n\nmethod mergesort(V : array?, c : int, f : int) \n\n requires V != null\n requires c >= 0 && f <= V.Length\n \n\n modifies V\n\n{\n \n if c < f {\n \n var m : int ;\n\tm := c + (f - c) / 2 ;\n \n mergesort(V, c, m) ;\n mergesort(V, m + 1, f) ;\n\n mezclar(V, c, m, f) ;\n \n }\n \n}\n\n\n\nmethod mezclar(V: array?, c : int, m : int, f : int)\n\n requires V != null\n requires c <= m <= f\n requires 0 <= c <= V.Length\n requires 0 <= m <= V.Length\n requires 0 <= f <= V.Length\n\n modifies V\n\n{\n\n var V1 : array? ;\n var j : nat ;\n\n V1 := new int[m - c + 1] ;\n j := 0 ;\n \n while j < V1.Length && c + j < V.Length\n \n \n \n {\n\n V1[j] := V[c + j] ;\n j := j + 1 ;\n \n }\n\n\n var V2 : array? ;\n var k : nat ;\n\n V2 := new int[f - m] ; \n k := 0 ;\n \n while k < V2.Length && m + k + 1 < V.Length\n \n \n \n {\n \n V2[k] := V[m + k + 1] ;\n k := k + 1 ;\n \n }\n\n\n var i : nat ;\n\n i := 0 ;\n j := 0 ;\n k := 0 ;\n \n while i < f - c + 1 && \n j <= V1.Length && \n k <= V2.Length && \n c + i < V.Length\n \n \n \n {\n \n if j >= V1.Length && k >= V2.Length {\n \n break ;\n \n }\n \n else if j >= V1.Length {\n \n V[c + i] := V2[k] ;\n k := k + 1 ;\n \n }\n \n else if k >= V2.Length {\n \n V[c + i] := V1[j] ;\n j := j + 1 ;\n \n }\n \n else {\n \n if V1[j] <= V2[k] {\n \n V[c + i] := V1[j] ;\n j := j + 1 ;\n \n }\n \n else if V1[j] > V2[k] {\n \n V[c + i] := V2[k] ;\n k := k + 1 ;\n \n }\n \n }\n \n i := i + 1 ;\n \n }\n \n}\n" }, { "test_ID": "780", "test_file": "vfag_tmp_tmpc29dxm1j_sumar_componentes.dfy", "ground_truth": "method suma_componentes(V : array?) returns (suma : int)\n\n requires V != null\n ensures suma == suma_aux(V, 0)\t// x = V[0] + V[1] + ... + V[N - 1]\n \n{\n \n var n : int ;\n\n assert V != null ;\t\t\t\t\t\t // P\n\n assert 0 <= V.Length <= V.Length && 0 == suma_aux(V, V.Length) ; // P ==> pmd(n := V.Length ; x := 0, I) \n\n \tn := V.Length ; // n := N\n \tsuma := 0 ;\n\n assert 0 <= n <= V.Length && suma == suma_aux(V, n) ;\t\t // I\n \n while n != 0\n \n invariant 0 <= n <= V.Length && suma == suma_aux(V, n)\t// I\n decreases n\t\t\t\t\t\t\t// C\n \n {\n\n assert 0 <= n <= V.Length && suma == suma_aux(V, n) && n != 0 ; \t// I /\\ B ==> R\n\n assert 0 <= n - 1 <= V.Length ;\n assert suma + V[n - 1] == suma_aux(V, n - 1) ; \t\t\t// R : pmd(x := x + V[n - 1], R1)\n\n \tsuma := suma + V[n - 1] ;\n\n assert 0 <= n - 1 <= V.Length && suma == suma_aux(V, n - 1) ; \t// R1 : pmd(n := n - 1, I)\n\n \tn := n - 1 ;\n\n assert 0 <= n <= V.Length && suma == suma_aux(V, n) ; \t\t// I\n\n }\n\n assert 0 <= n <= V.Length && suma == suma_aux(V, n) && n == 0 ; \t// I /\\ \u00acB ==> Q \t\n\n assert suma == suma_aux(V, 0)\t;\t\t\t\t\t// Q \n \n}\n\n\n\nfunction suma_aux(V : array?, n : int) : int\n\n // suma_aux(V, n) = V[n] + V[n + 1] + ... + V[N - 1]\n\n requires V != null\t\t\t// P_0\n requires 0 <= n <= V.Length\t\t// Q_0\n \n decreases V.Length - n\t\t// C_0\n \n reads V\n \n{\n \n if (n == V.Length) then 0 \t\t\t\t\t// Caso base: n = N\n else V[n] + suma_aux(V, n + 1)\t\t// Caso recursivo: n < N\n \n}\n", "hints_removed": "method suma_componentes(V : array?) returns (suma : int)\n\n requires V != null\n ensures suma == suma_aux(V, 0)\t// x = V[0] + V[1] + ... + V[N - 1]\n \n{\n \n var n : int ;\n\n\n\n \tn := V.Length ; // n := N\n \tsuma := 0 ;\n\n \n while n != 0\n \n \n {\n\n\n\n \tsuma := suma + V[n - 1] ;\n\n\n \tn := n - 1 ;\n\n\n }\n\n\n \n}\n\n\n\nfunction suma_aux(V : array?, n : int) : int\n\n // suma_aux(V, n) = V[n] + V[n + 1] + ... + V[N - 1]\n\n requires V != null\t\t\t// P_0\n requires 0 <= n <= V.Length\t\t// Q_0\n \n \n reads V\n \n{\n \n if (n == V.Length) then 0 \t\t\t\t\t// Caso base: n = N\n else V[n] + suma_aux(V, n + 1)\t\t// Caso recursivo: n < N\n \n}\n" }, { "test_ID": "781", "test_file": "vmware-verification-2023_tmp_tmpoou5u54i_demos_leader_election.dfy", "ground_truth": "// Each node's identifier (address)\ndatatype Constants = Constants(ids: seq) {\n predicate ValidIdx(i: int) {\n 0<=i<|ids|\n }\n\n ghost predicate UniqueIds() {\n (forall i, j | ValidIdx(i) && ValidIdx(j) && ids[i]==ids[j] :: i == j)\n }\n\n ghost predicate WF() {\n && 0 < |ids|\n && UniqueIds()\n }\n}\n\n// The highest other identifier this node has heard about.\ndatatype Variables = Variables(highest_heard: seq) {\n ghost predicate WF(c: Constants)\n {\n && c.WF()\n && |highest_heard| == |c.ids|\n }\n}\n\nghost predicate Init(c: Constants, v: Variables)\n{\n && v.WF(c)\n && c.UniqueIds()\n // Everyone begins having heard about nobody, not even themselves.\n && (forall i | c.ValidIdx(i) :: v.highest_heard[i] == -1)\n}\n\nfunction max(a: int, b: int) : int {\n if a > b then a else b\n}\n\nfunction NextIdx(c: Constants, idx: nat) : nat\n requires c.WF()\n requires c.ValidIdx(idx)\n{\n if idx + 1 == |c.ids| then 0 else idx + 1\n}\n\nghost predicate Transmission(c: Constants, v: Variables, v': Variables, srcidx: nat)\n{\n && v.WF(c)\n && v'.WF(c)\n && c.ValidIdx(srcidx)\n\n // Neighbor address in ring.\n && var dstidx := NextIdx(c, srcidx);\n\n // srcidx sends the max of its highest_heard value and its own id.\n && var message := max(v.highest_heard[srcidx], c.ids[srcidx]);\n\n // dstidx only overwrites its highest_heard if the message is higher.\n && var dst_new_max := max(v.highest_heard[dstidx], message);\n // XXX Manos: How could this have been a bug!? How could a srcidx, having sent message X, ever send message Y < X!?\n\n && v' == v.(highest_heard := v.highest_heard[dstidx := dst_new_max])\n}\n\ndatatype Step = TransmissionStep(srcidx: nat)\n\nghost predicate NextStep(c: Constants, v: Variables, v': Variables, step: Step)\n{\n match step {\n case TransmissionStep(srcidx) => Transmission(c, v, v', srcidx)\n }\n}\n\nghost predicate Next(c: Constants, v: Variables, v': Variables)\n{\n exists step :: NextStep(c, v, v', step)\n}\n\n//////////////////////////////////////////////////////////////////////////////\n// Spec (proof goal)\n//////////////////////////////////////////////////////////////////////////////\n\nghost predicate IsLeader(c: Constants, v: Variables, i: int)\n requires v.WF(c)\n{\n && c.ValidIdx(i)\n && v.highest_heard[i] == c.ids[i]\n}\n\nghost predicate Safety(c: Constants, v: Variables)\n requires v.WF(c)\n{\n forall i, j | IsLeader(c, v, i) && IsLeader(c, v, j) :: i == j\n}\n\n//////////////////////////////////////////////////////////////////////////////\n// Proof\n//////////////////////////////////////////////////////////////////////////////\n\nghost predicate IsChord(c: Constants, v: Variables, start: int, end: int)\n{\n && v.WF(c)\n && c.ValidIdx(start)\n && c.ValidIdx(end)\n && c.ids[start] == v.highest_heard[end]\n}\n\nghost predicate Between(start: int, node: int, end: int)\n{\n if start < end\n then start < node < end // not wrapped\n else node < end || start < node // wrapped\n}\n\nghost predicate OnChordHeardDominatesId(c: Constants, v: Variables, start: int, end: int)\n requires v.WF(c)\n{\n forall node | Between(start, node, end) && c.ValidIdx(node)\n :: v.highest_heard[node] > c.ids[node]\n}\n\nghost predicate OnChordHeardDominatesIdInv(c: Constants, v: Variables)\n{\n && v.WF(c)\n && (forall start, end\n | IsChord(c, v, start, end)\n :: OnChordHeardDominatesId(c, v, start, end)\n )\n}\n\nghost predicate Inv(c: Constants, v: Variables)\n{\n && v.WF(c)\n && OnChordHeardDominatesIdInv(c, v)\n && Safety(c, v)\n}\n\nlemma InitImpliesInv(c: Constants, v: Variables)\n requires Init(c, v)\n ensures Inv(c, v)\n{\n}\n\nlemma NextPreservesInv(c: Constants, v: Variables, v': Variables)\n requires Inv(c, v)\n requires Next(c, v, v')\n ensures Inv(c, v')\n{\n var step :| NextStep(c, v, v', step);\n var srcidx := step.srcidx;\n var dstidx := NextIdx(c, srcidx);\n var message := max(v.highest_heard[srcidx], c.ids[srcidx]);\n var dst_new_max := max(v.highest_heard[dstidx], message);\n\n forall start, end\n | IsChord(c, v', start, end)\n ensures OnChordHeardDominatesId(c, v', start, end)\n {\n forall node | Between(start, node, end) && c.ValidIdx(node)\n ensures v'.highest_heard[node] > c.ids[node]\n {\n if dstidx == end {\n // maybe this chord just sprung into existence\n if v'.highest_heard[end] == v.highest_heard[end] {\n // no change --\n assert v' == v; // trigger\n } else if v'.highest_heard[end] == c.ids[srcidx] {\n assert false; // proof by contridiction\n } else if v'.highest_heard[end] == v.highest_heard[srcidx] {\n assert IsChord(c, v, start, srcidx); // trigger\n }\n } else {\n // this chord was already here\n assert IsChord(c, v, start, end); // trigger\n }\n }\n }\n assert OnChordHeardDominatesIdInv(c, v');\n\n forall i, j | IsLeader(c, v', i) && IsLeader(c, v', j) ensures i == j {\n assert IsChord(c, v', i, i); // trigger\n assert IsChord(c, v', j, j); // trigger\n }\n assert Safety(c, v');\n}\n\nlemma InvImpliesSafety(c: Constants, v: Variables)\n requires Inv(c, v)\n ensures Safety(c, v)\n{\n}\n\n", "hints_removed": "// Each node's identifier (address)\ndatatype Constants = Constants(ids: seq) {\n predicate ValidIdx(i: int) {\n 0<=i<|ids|\n }\n\n ghost predicate UniqueIds() {\n (forall i, j | ValidIdx(i) && ValidIdx(j) && ids[i]==ids[j] :: i == j)\n }\n\n ghost predicate WF() {\n && 0 < |ids|\n && UniqueIds()\n }\n}\n\n// The highest other identifier this node has heard about.\ndatatype Variables = Variables(highest_heard: seq) {\n ghost predicate WF(c: Constants)\n {\n && c.WF()\n && |highest_heard| == |c.ids|\n }\n}\n\nghost predicate Init(c: Constants, v: Variables)\n{\n && v.WF(c)\n && c.UniqueIds()\n // Everyone begins having heard about nobody, not even themselves.\n && (forall i | c.ValidIdx(i) :: v.highest_heard[i] == -1)\n}\n\nfunction max(a: int, b: int) : int {\n if a > b then a else b\n}\n\nfunction NextIdx(c: Constants, idx: nat) : nat\n requires c.WF()\n requires c.ValidIdx(idx)\n{\n if idx + 1 == |c.ids| then 0 else idx + 1\n}\n\nghost predicate Transmission(c: Constants, v: Variables, v': Variables, srcidx: nat)\n{\n && v.WF(c)\n && v'.WF(c)\n && c.ValidIdx(srcidx)\n\n // Neighbor address in ring.\n && var dstidx := NextIdx(c, srcidx);\n\n // srcidx sends the max of its highest_heard value and its own id.\n && var message := max(v.highest_heard[srcidx], c.ids[srcidx]);\n\n // dstidx only overwrites its highest_heard if the message is higher.\n && var dst_new_max := max(v.highest_heard[dstidx], message);\n // XXX Manos: How could this have been a bug!? How could a srcidx, having sent message X, ever send message Y < X!?\n\n && v' == v.(highest_heard := v.highest_heard[dstidx := dst_new_max])\n}\n\ndatatype Step = TransmissionStep(srcidx: nat)\n\nghost predicate NextStep(c: Constants, v: Variables, v': Variables, step: Step)\n{\n match step {\n case TransmissionStep(srcidx) => Transmission(c, v, v', srcidx)\n }\n}\n\nghost predicate Next(c: Constants, v: Variables, v': Variables)\n{\n exists step :: NextStep(c, v, v', step)\n}\n\n//////////////////////////////////////////////////////////////////////////////\n// Spec (proof goal)\n//////////////////////////////////////////////////////////////////////////////\n\nghost predicate IsLeader(c: Constants, v: Variables, i: int)\n requires v.WF(c)\n{\n && c.ValidIdx(i)\n && v.highest_heard[i] == c.ids[i]\n}\n\nghost predicate Safety(c: Constants, v: Variables)\n requires v.WF(c)\n{\n forall i, j | IsLeader(c, v, i) && IsLeader(c, v, j) :: i == j\n}\n\n//////////////////////////////////////////////////////////////////////////////\n// Proof\n//////////////////////////////////////////////////////////////////////////////\n\nghost predicate IsChord(c: Constants, v: Variables, start: int, end: int)\n{\n && v.WF(c)\n && c.ValidIdx(start)\n && c.ValidIdx(end)\n && c.ids[start] == v.highest_heard[end]\n}\n\nghost predicate Between(start: int, node: int, end: int)\n{\n if start < end\n then start < node < end // not wrapped\n else node < end || start < node // wrapped\n}\n\nghost predicate OnChordHeardDominatesId(c: Constants, v: Variables, start: int, end: int)\n requires v.WF(c)\n{\n forall node | Between(start, node, end) && c.ValidIdx(node)\n :: v.highest_heard[node] > c.ids[node]\n}\n\nghost predicate OnChordHeardDominatesIdInv(c: Constants, v: Variables)\n{\n && v.WF(c)\n && (forall start, end\n | IsChord(c, v, start, end)\n :: OnChordHeardDominatesId(c, v, start, end)\n )\n}\n\nghost predicate Inv(c: Constants, v: Variables)\n{\n && v.WF(c)\n && OnChordHeardDominatesIdInv(c, v)\n && Safety(c, v)\n}\n\nlemma InitImpliesInv(c: Constants, v: Variables)\n requires Init(c, v)\n ensures Inv(c, v)\n{\n}\n\nlemma NextPreservesInv(c: Constants, v: Variables, v': Variables)\n requires Inv(c, v)\n requires Next(c, v, v')\n ensures Inv(c, v')\n{\n var step :| NextStep(c, v, v', step);\n var srcidx := step.srcidx;\n var dstidx := NextIdx(c, srcidx);\n var message := max(v.highest_heard[srcidx], c.ids[srcidx]);\n var dst_new_max := max(v.highest_heard[dstidx], message);\n\n forall start, end\n | IsChord(c, v', start, end)\n ensures OnChordHeardDominatesId(c, v', start, end)\n {\n forall node | Between(start, node, end) && c.ValidIdx(node)\n ensures v'.highest_heard[node] > c.ids[node]\n {\n if dstidx == end {\n // maybe this chord just sprung into existence\n if v'.highest_heard[end] == v.highest_heard[end] {\n // no change --\n } else if v'.highest_heard[end] == c.ids[srcidx] {\n } else if v'.highest_heard[end] == v.highest_heard[srcidx] {\n }\n } else {\n // this chord was already here\n }\n }\n }\n\n forall i, j | IsLeader(c, v', i) && IsLeader(c, v', j) ensures i == j {\n }\n}\n\nlemma InvImpliesSafety(c: Constants, v: Variables)\n requires Inv(c, v)\n ensures Safety(c, v)\n{\n}\n\n" } ]