diff --git a/Source/Core/DynamicStack.cs b/Source/Core/DynamicStack.cs new file mode 100644 index 000000000..9db58a4ca --- /dev/null +++ b/Source/Core/DynamicStack.cs @@ -0,0 +1,227 @@ +using System.ComponentModel.Design.Serialization; +using System.Diagnostics; + +namespace Microsoft.Boogie; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; + +[AsyncMethodBuilder(typeof(DynamicStackBuilder))] +public class DynamicStack { + + public static DynamicStack FromResult(TResult result) { + return new DynamicStack { + Result = result + }; + } + public void Run() { + DynamicStackBuilder.Builder.Value!.Run(); + } + + public DynamicStackBuilder GetAwaiter() { + return DynamicStackBuilder.Builder.Value; + } +} + +public class DynamicStackBuilder : INotifyCompletion { + public static readonly ThreadLocal Builder = new(() => new DynamicStackBuilder()); + private static readonly DynamicStack TheOne = new(); + + public static DynamicStackBuilder Create() { + return Builder.Value; + } + + private readonly Stack todos = new(); + + public void Run() { + while (todos.Any()) { + var machine = todos.Pop(); + machine.MoveNext(); + } + } + + public void Start(ref TStateMachine stateMachine) + where TStateMachine : IAsyncStateMachine { + // Called on await, push recursive call + todos.Push(stateMachine); + } + + public void SetException(Exception exception) { + throw exception; + } + + public void SetResult() { + } + + public void SetStateMachine(IAsyncStateMachine stateMachine) { + } + + public void AwaitOnCompleted( + ref TAwaiter awaiter, ref TStateMachine stateMachine) + where TAwaiter : INotifyCompletion + where TStateMachine : IAsyncStateMachine { + // Place recursive call on top of continuation + var recursiveCall = todos.Pop(); + todos.Push(stateMachine); + todos.Push(recursiveCall); + } + + public void AwaitUnsafeOnCompleted( + ref TAwaiter awaiter, ref TStateMachine stateMachine) + where TAwaiter : ICriticalNotifyCompletion + where TStateMachine : IAsyncStateMachine { + // Place recursive call on top of continuation + var recursiveCall = todos.Pop(); + todos.Push(stateMachine); + todos.Push(recursiveCall); + } + + public DynamicStack Task => TheOne; + + public bool IsCompleted => false; + + public void GetResult() { + } + + public void OnCompleted(System.Action continuation) { + throw new NotImplementedException(); + } +} + +public static class DynamicStackExtensions { + public static async DynamicStack> ToDynamicStackList(this IEnumerable> items) { + var result = new List(); + foreach (var item in items) { + result.Add(await item); + } + return result; + } +} + +/// +/// Equivalent to Task +/// +[AsyncMethodBuilder(typeof(DynamicStackBuilder<>))] +public class DynamicStack : INotifyCompletion { + private TResult result; + private bool completed = false; + + internal DynamicStack() { + } + + public TResult Result { + get { + if (!IsCompleted) { + Run(); + } + return result; + } + internal set { + result = value; + completed = true; + } + } + + public void Run() { + DynamicStackBuilder.Builder.Value!.Run(); + } + + public DynamicStack GetAwaiter() { + return this; + } + + public void OnCompleted(Action continuation) { + // Never called because AwaitOnCompleted doesn't call it. + } + + public bool IsCompleted => completed; + + public TResult GetResult() { + return result; + } +} + +/// +/// Combines both the builder and the awaiter pattern, described here: +/// https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-7.0/task-types +/// +public class DynamicStackBuilder { + public static readonly ThreadLocal> Builder = new(() => new DynamicStackBuilder()); + private ConditionalWeakTable> results = new (); + private DynamicStack dynamicStack; + + public static DynamicStackBuilder Create() { + return Builder.Value; + } + + private readonly Stack todos = new(); + + public void Run() { + while (todos.Any()) { + var machine = todos.Pop(); + results.TryGetValue(machine, out dynamicStack); + machine.MoveNext(); + } + } + + [DebuggerStepThrough] + public void Start(ref TStateMachine stateMachine) + where TStateMachine : IAsyncStateMachine { + // Push recursive call + dynamicStack = new DynamicStack(); + results.Add(stateMachine, dynamicStack); + todos.Push(stateMachine); + } + + public void SetStateMachine(IAsyncStateMachine stateMachine) { + } + + public void SetException(Exception exception) { + throw exception; + } + + public DynamicStack Task => dynamicStack; + + public void SetResult(TResult result) { + dynamicStack.Result = result; + // dynamicStack = new DynamicStack() { + // Result = result + // }; + //dynamicStack.Result = result; + } + + public void SetResult(DynamicStack result) { + dynamicStack = new DynamicStack() { + Result = result.Result + }; + // dynamicStack = result; + // TODO maybe not correct? + } + + public void AwaitOnCompleted( + ref TAwaiter awaiter, ref TStateMachine stateMachine) + where TAwaiter : INotifyCompletion + where TStateMachine : IAsyncStateMachine { + // Place recursive call on top of continuation + if (todos.Any()) { + var recursiveCall = todos.Pop(); + todos.Push(stateMachine); + todos.Push(recursiveCall); + } else { + todos.Push(stateMachine); + } + } + + public void AwaitUnsafeOnCompleted( + ref TAwaiter awaiter, ref TStateMachine stateMachine) + where TAwaiter : ICriticalNotifyCompletion + where TStateMachine : IAsyncStateMachine { + // Place recursive call on top of continuation + var recursiveCall = todos.Pop(); + todos.Push(stateMachine); + todos.Push(recursiveCall); + } +} \ No newline at end of file diff --git a/Source/Provers/SMTLib/FunctionDependencyCollector.cs b/Source/Provers/SMTLib/FunctionDependencyCollector.cs index eea6991d5..30aa7ac07 100644 --- a/Source/Provers/SMTLib/FunctionDependencyCollector.cs +++ b/Source/Provers/SMTLib/FunctionDependencyCollector.cs @@ -20,7 +20,7 @@ public List Collect(VCExpr expr) return functionList; } - public override bool Visit(VCExprNAry node, bool arg) + public override DynamicStack Visit(VCExprNAry node, bool arg) { VCExprBoogieFunctionOp op = node.Op as VCExprBoogieFunctionOp; if (op != null) diff --git a/Source/Provers/SMTLib/SMTLibLineariser.cs b/Source/Provers/SMTLib/SMTLibLineariser.cs index 0985109ee..1485cfb6c 100644 --- a/Source/Provers/SMTLib/SMTLibLineariser.cs +++ b/Source/Provers/SMTLib/SMTLibLineariser.cs @@ -324,7 +324,7 @@ public bool Visit(VCExprLiteral node, LineariserOptions options) ///////////////////////////////////////////////////////////////////////////////////// - public bool Visit(VCExprNAry node, LineariserOptions options) + public DynamicStack Visit(VCExprNAry node, LineariserOptions options) { VCExprOp op = node.Op; Contract.Assert(op != null); @@ -379,7 +379,7 @@ public bool Visit(VCExprNAry node, LineariserOptions options) } } - return true; + return DynamicStack.FromResult(true); } if (OptimizationRequests != null @@ -389,13 +389,13 @@ public bool Visit(VCExprNAry node, LineariserOptions options) OptimizationRequests.Add(string.Format("({0} {1})", optOp, ToString(node[0], Namer, LibOptions, solverOptions, NamedAssumes))); Linearise(node[1], options); - return true; + return DynamicStack.FromResult(true); } if (node.Op is VCExprSoftOp) { Linearise(node[1], options); - return true; + return DynamicStack.FromResult(true); } if (node.Op.Equals(VCExpressionGenerator.NamedAssumeOp) || node.Op.Equals(VCExpressionGenerator.NamedAssertOp)) @@ -403,7 +403,7 @@ public bool Visit(VCExprNAry node, LineariserOptions options) var exprVar = node[0] as VCExprVar; NamedAssumes.Add(exprVar); Linearise(node[1], options); - return true; + return DynamicStack.FromResult(true); } return node.Accept(OpLineariser, options); @@ -419,7 +419,7 @@ public bool Visit(VCExprVar node, LineariserOptions options) ///////////////////////////////////////////////////////////////////////////////////// - public bool Visit(VCExprQuantifier node, LineariserOptions options) + public DynamicStack Visit(VCExprQuantifier node, LineariserOptions options) { Contract.Assert(node.TypeParameters.Count == 0); @@ -485,7 +485,7 @@ public bool Visit(VCExprQuantifier node, LineariserOptions options) wr.Write(")"); - return true; + return DynamicStack.FromResult(true); } finally { @@ -568,7 +568,7 @@ private void WriteTriggers(List!*/> triggers, LineariserOptions o ///////////////////////////////////////////////////////////////////////////////////// - public bool Visit(VCExprLet node, LineariserOptions options) + public DynamicStack Visit(VCExprLet node, LineariserOptions options) { Namer.PushScope(); try @@ -588,7 +588,7 @@ public bool Visit(VCExprLet node, LineariserOptions options) wr.Write(")"); } - return true; + return DynamicStack.FromResult(true); } finally { @@ -652,10 +652,10 @@ private void WriteApplication(string opName, VCExprNAry /*!>!*/ call, Lineariser /////////////////////////////////////////////////////////////////////////////////// - public bool VisitNotOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitNotOp(VCExprNAry node, LineariserOptions options) { WriteApplication("not", node, options); // arguments can be both terms and formulas - return true; + return DynamicStack.FromResult(true); } private bool PrintEq(VCExprNAry node, LineariserOptions options) @@ -668,46 +668,46 @@ private bool PrintEq(VCExprNAry node, LineariserOptions options) return true; } - public bool VisitEqOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitEqOp(VCExprNAry node, LineariserOptions options) { - return PrintEq(node, options); + return DynamicStack.FromResult(PrintEq(node, options)); } - public bool VisitNeqOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitNeqOp(VCExprNAry node, LineariserOptions options) { //Contract.Requires(node != null); //Contract.Requires(options != null); wr.Write("(not "); PrintEq(node, options); wr.Write(")"); - return true; + return DynamicStack.FromResult(true); } - public bool VisitAndOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitAndOp(VCExprNAry node, LineariserOptions options) { WriteApplication("and", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitOrOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitOrOp(VCExprNAry node, LineariserOptions options) { WriteApplication("or", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitImpliesOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitImpliesOp(VCExprNAry node, LineariserOptions options) { WriteApplication("=>", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitIfThenElseOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitIfThenElseOp(VCExprNAry node, LineariserOptions options) { WriteApplication("ite", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitCustomOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitCustomOp(VCExprNAry node, LineariserOptions options) { VCExprCustomOp op = (VCExprCustomOp) node.Op; if (!ExprLineariser.solverOptions.UseTickleBool && op.Name == "tickleBool") @@ -719,10 +719,10 @@ public bool VisitCustomOp(VCExprNAry node, LineariserOptions options) WriteApplication(op.Name, node, options); } - return true; + return DynamicStack.FromResult(true); } - public bool VisitDistinctOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitDistinctOp(VCExprNAry node, LineariserOptions options) { //Contract.Requires(node != null); //Contract.Requires(options != null); @@ -767,10 +767,10 @@ public bool VisitDistinctOp(VCExprNAry node, LineariserOptions options) } } - return true; + return DynamicStack.FromResult(true); } - public bool VisitFieldAccessOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitFieldAccessOp(VCExprNAry node, LineariserOptions options) { var op = (VCExprFieldAccessOp)node.Op; var constructor = op.DatatypeTypeCtorDecl.Constructors[op.ConstructorIndex]; @@ -778,20 +778,20 @@ public bool VisitFieldAccessOp(VCExprNAry node, LineariserOptions options) var name = v.Name + "#" + constructor.Name; name = ExprLineariser.Namer.GetQuotedName(v, name); WriteApplication(name, node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitIsConstructorOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitIsConstructorOp(VCExprNAry node, LineariserOptions options) { var op = (VCExprIsConstructorOp)node.Op; var constructor = op.DatatypeTypeCtorDecl.Constructors[op.ConstructorIndex]; var constructorName = ExprLineariser.Namer.GetQuotedName(constructor, constructor.Name); var name = "is-" + constructorName; WriteApplication(name, node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitSelectOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitSelectOp(VCExprNAry node, LineariserOptions options) { var name = ExprLineariser.SelectOpName(node); name = ExprLineariser.Namer.GetQuotedName(name, name); @@ -801,10 +801,10 @@ public bool VisitSelectOp(VCExprNAry node, LineariserOptions options) } WriteApplication(name, node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitStoreOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitStoreOp(VCExprNAry node, LineariserOptions options) { var name = ExprLineariser.StoreOpName(node); name = ExprLineariser.Namer.GetQuotedName(name, name); @@ -814,74 +814,74 @@ public bool VisitStoreOp(VCExprNAry node, LineariserOptions options) } WriteApplication(name, node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitFloatAddOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitFloatAddOp(VCExprNAry node, LineariserOptions options) { WriteApplication("fp.add RNE", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitFloatSubOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitFloatSubOp(VCExprNAry node, LineariserOptions options) { WriteApplication("fp.sub RNE", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitFloatMulOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitFloatMulOp(VCExprNAry node, LineariserOptions options) { WriteApplication("fp.mul RNE", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitFloatDivOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitFloatDivOp(VCExprNAry node, LineariserOptions options) { WriteApplication("fp.div RNE", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitFloatLeqOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitFloatLeqOp(VCExprNAry node, LineariserOptions options) { WriteApplication("fp.leq", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitFloatLtOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitFloatLtOp(VCExprNAry node, LineariserOptions options) { WriteApplication("fp.lt", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitFloatGeqOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitFloatGeqOp(VCExprNAry node, LineariserOptions options) { WriteApplication("fp.geq", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitFloatGtOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitFloatGtOp(VCExprNAry node, LineariserOptions options) { WriteApplication("fp.gt", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitFloatEqOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitFloatEqOp(VCExprNAry node, LineariserOptions options) { WriteApplication("fp.eq", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitFloatNeqOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitFloatNeqOp(VCExprNAry node, LineariserOptions options) { wr.Write("(not "); VisitFloatEqOp(node, options); wr.Write(")"); - return true; + return DynamicStack.FromResult(true); } static char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; - public bool VisitBvOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitBvOp(VCExprNAry node, LineariserOptions options) { var lit = (VCExprIntLit) node[0]; var bytes = lit.Val.ToByteArray(); @@ -906,115 +906,115 @@ public bool VisitBvOp(VCExprNAry node, LineariserOptions options) } } - return true; + return DynamicStack.FromResult(true); } - public bool VisitBvExtractOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitBvExtractOp(VCExprNAry node, LineariserOptions options) { var op = (VCExprBvExtractOp) node.Op; wr.Write("((_ extract {0} {1}) ", op.End - 1, op.Start); ExprLineariser.Linearise(node[0], options); wr.Write(")"); - return true; + return DynamicStack.FromResult(true); } - public bool VisitBvConcatOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitBvConcatOp(VCExprNAry node, LineariserOptions options) { WriteApplication("concat", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitAddOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitAddOp(VCExprNAry node, LineariserOptions options) { WriteApplication("+", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitSubOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitSubOp(VCExprNAry node, LineariserOptions options) { WriteApplication("-", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitMulOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitMulOp(VCExprNAry node, LineariserOptions options) { WriteApplication("*", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitDivOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitDivOp(VCExprNAry node, LineariserOptions options) { WriteApplication("div", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitModOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitModOp(VCExprNAry node, LineariserOptions options) { WriteApplication("mod", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitRealDivOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitRealDivOp(VCExprNAry node, LineariserOptions options) { WriteApplication("/", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitPowOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitPowOp(VCExprNAry node, LineariserOptions options) { WriteApplication("real_pow", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitLtOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitLtOp(VCExprNAry node, LineariserOptions options) { WriteApplication("<", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitLeOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitLeOp(VCExprNAry node, LineariserOptions options) { WriteApplication("<=", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitGtOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitGtOp(VCExprNAry node, LineariserOptions options) { WriteApplication(">", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitGeOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitGeOp(VCExprNAry node, LineariserOptions options) { WriteApplication(">=", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitSubtypeOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitSubtypeOp(VCExprNAry node, LineariserOptions options) { WriteApplication("UOrdering2", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitSubtype3Op(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitSubtype3Op(VCExprNAry node, LineariserOptions options) { WriteApplication("UOrdering3", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitToIntOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitToIntOp(VCExprNAry node, LineariserOptions options) { WriteApplication("to_int", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitToRealOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitToRealOp(VCExprNAry node, LineariserOptions options) { WriteApplication("to_real", node, options); - return true; + return DynamicStack.FromResult(true); } - public bool VisitBoogieFunctionOp(VCExprNAry node, LineariserOptions options) + public DynamicStack VisitBoogieFunctionOp(VCExprNAry node, LineariserOptions options) { VCExprBoogieFunctionOp op = (VCExprBoogieFunctionOp) node.Op; Contract.Assert(op != null); @@ -1038,7 +1038,7 @@ public bool VisitBoogieFunctionOp(VCExprNAry node, LineariserOptions options) WriteApplication(printedName, node, options); - return true; + return DynamicStack.FromResult(true); } private static Type ResultType(Type type) diff --git a/Source/Provers/SMTLib/TypeDeclCollector.cs b/Source/Provers/SMTLib/TypeDeclCollector.cs index 6f034db03..76bc25e2c 100644 --- a/Source/Provers/SMTLib/TypeDeclCollector.cs +++ b/Source/Provers/SMTLib/TypeDeclCollector.cs @@ -195,7 +195,7 @@ public void AddKnownVariable(VCExprVar variable) KnownVariables.Add(variable); } - public override bool Visit(VCExprNAry node, bool arg) + public override DynamicStack Visit(VCExprNAry node, bool arg) { Contract.Requires(node != null); @@ -287,7 +287,7 @@ public override bool Visit(VCExprVar node, bool arg) return base.Visit(node, arg); } - public override bool Visit(VCExprQuantifier node, bool arg) + public override DynamicStack Visit(VCExprQuantifier node, bool arg) { Contract.Requires(node != null); foreach (VCExprVar v in node.BoundVars) diff --git a/Source/UnitTests/CoreTests/DynamicStackReturnValueTest.cs b/Source/UnitTests/CoreTests/DynamicStackReturnValueTest.cs new file mode 100644 index 000000000..64d64a45f --- /dev/null +++ b/Source/UnitTests/CoreTests/DynamicStackReturnValueTest.cs @@ -0,0 +1,67 @@ +using Microsoft.Boogie; +using NUnit.Framework; + +namespace CoreTests; + +[TestFixture()] +public class DynamicStackReturnValueTest { + + [Test] + public void SmallStackRecursiveTest() { + var value = Recursive(10).Result; + Assert.AreEqual(10, value); + } + + [Test] + public void SmallStackTest() { + var iterations = 2; + var dynamicStack = MutuallyRecursiveAB(iterations); + dynamicStack.Run(); + Assert.AreEqual(iterations, dynamicStack.Result); + } + + [Test] + public void LargeStackTest() { + var iterations = 100_000; + var dynamicStack = MutuallyRecursiveAB(iterations); + dynamicStack.Run(); + Assert.AreEqual(iterations, dynamicStack.Result); + } + + private async DynamicStack MutuallyRecursiveAB(int iterations) { + var result = 1; + if (iterations > 1) { + result += await MutuallyRecursiveBA(iterations - 1); + } + + Assert.AreEqual(3, await FromResultTest()); + + var value = await Recursive(10); + Assert.AreEqual(10, value); + + return result; + } + + private async DynamicStack MutuallyRecursiveBA(int iterations) { + var result = 1; + if (iterations > 1) { + result += await MutuallyRecursiveAB(iterations - 1); + } + return result; + } + + private async DynamicStack Recursive(int iterations) { + var result = 1; + if (iterations > 1) { + var recValue = await Recursive(iterations - 1); + result += recValue; + } + return result; + } + + + private DynamicStack FromResultTest() { + return DynamicStack.FromResult(3); + } + +} \ No newline at end of file diff --git a/Source/UnitTests/CoreTests/DynamicStackReturnValueTest1.cs b/Source/UnitTests/CoreTests/DynamicStackReturnValueTest1.cs new file mode 100644 index 000000000..5a4616337 --- /dev/null +++ b/Source/UnitTests/CoreTests/DynamicStackReturnValueTest1.cs @@ -0,0 +1,29 @@ +using Microsoft.Boogie; +using NUnit.Framework; + +namespace CoreTests; + +[TestFixture()] +public class DynamicStackReturnValueTest1 { + + [Test] + public void SmallStackRecursiveTest() { + var value = Recursive(10).Result; + Assert.AreEqual(10, value); + } + + private async DynamicStack Recursive(int iterations) { + var result = 1; + if (iterations > 1) { + var recValue = await Recursive(iterations - 1); + result += recValue; + } + return result; + } + + + private DynamicStack FromResultTest() { + return DynamicStack.FromResult(3); + } + +} \ No newline at end of file diff --git a/Source/UnitTests/CoreTests/DynamicStackTest.cs b/Source/UnitTests/CoreTests/DynamicStackTest.cs new file mode 100644 index 000000000..66d23e4f7 --- /dev/null +++ b/Source/UnitTests/CoreTests/DynamicStackTest.cs @@ -0,0 +1,31 @@ +using System; +using Microsoft.Boogie; +using NUnit.Framework; + +namespace CoreTests; + +[TestFixture()] +public class DynamicStackTest { + + [Test] + public void SmallStackTest() { + MutuallyRecursiveA(2).Run(); + } + + [Test] + public void LargeStackTest() { + MutuallyRecursiveA(100_000).Run(); + } + + private async DynamicStack MutuallyRecursiveA(int iterations) { + if (iterations > 0) { + await MutuallyRecursiveB(iterations - 1); + } + } + + private async DynamicStack MutuallyRecursiveB(int iterations) { + if (iterations > 0) { + await MutuallyRecursiveA(iterations - 1); + } + } +} \ No newline at end of file diff --git a/Source/UnitTests/CoreTests/Simulated.cs b/Source/UnitTests/CoreTests/Simulated.cs new file mode 100644 index 000000000..2f826b443 --- /dev/null +++ b/Source/UnitTests/CoreTests/Simulated.cs @@ -0,0 +1,95 @@ +using System; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using Microsoft.Boogie; +using NUnit.Framework; + +namespace CoreTests; + +[TestFixture] + public class DynamicStackReturnValueTest2 + { + [Test] + public void SmallStackRecursiveTest() + { + Assert.AreEqual(2, Recursive(2).Result); + } + + [DebuggerStepThrough] + private DynamicStack Recursive(int iterations) + { + StateMachine stateMachine = new StateMachine(); + stateMachine.builder = DynamicStackBuilder.Create(); + stateMachine.__this = this; + stateMachine.iterations = iterations; + stateMachine.state = -1; + stateMachine.builder.Start(ref stateMachine); + return stateMachine.builder.Task; + } + + [CompilerGenerated] + private sealed class StateMachine : IAsyncStateMachine + { + public int state; + public DynamicStackBuilder builder; + public int iterations; + public DynamicStackReturnValueTest2 __this; + private int result5__1; + private int recValue5__2; + private int s__3; + private object u__1; + + void IAsyncStateMachine.MoveNext() + { + int num1 = this.state; + int result51; + try + { + DynamicStack awaiter; + int num2; + if (num1 != 0) + { + this.result5__1 = 1; + if (this.iterations > 1) + { + awaiter = this.__this.Recursive(this.iterations - 1).GetAwaiter(); + if (!awaiter.IsCompleted) + { + this.state = num2 = 0; + this.u__1 = (object) awaiter; + StateMachine stateMachine = this; + this.builder.AwaitOnCompleted, StateMachine>(ref awaiter, ref stateMachine); + return; + } + } + else + goto label_7; + } + else + { + awaiter = (DynamicStack) this.u__1; + this.u__1 = (object) null; + this.state = num2 = -1; + } + this.s__3 = awaiter.GetResult(); + this.recValue5__2 = this.s__3; + this.result5__1 += this.recValue5__2; +label_7: + result51 = this.result5__1; + } + catch (Exception ex) + { + this.state = -2; + this.builder.SetException(ex); + return; + } + this.state = -2; + this.builder.SetResult(result51); + } + + [DebuggerHidden] + void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) + { + } + } + } \ No newline at end of file diff --git a/Source/VCExpr/BigLiteralAbstracter.cs b/Source/VCExpr/BigLiteralAbstracter.cs index 5c1d4797e..9ae1c6855 100644 --- a/Source/VCExpr/BigLiteralAbstracter.cs +++ b/Source/VCExpr/BigLiteralAbstracter.cs @@ -7,13 +7,10 @@ // constants. This is necessary for Simplify, which cannot deal with // literals larger than 32 bits. -namespace Microsoft.Boogie.VCExprAST -{ - public class BigLiteralAbstracter : MutatingVCExprVisitor, ICloneable - { +namespace Microsoft.Boogie.VCExprAST { + public class BigLiteralAbstracter : MutatingVCExprVisitor, ICloneable { public BigLiteralAbstracter(VCExpressionGenerator gen) - : base(gen) - { + : base(gen) { Contract.Requires(gen != null); DummyVar = gen.Variable("x", Type.Int); IncAxioms = new List(); @@ -21,16 +18,14 @@ public BigLiteralAbstracter(VCExpressionGenerator gen) } private BigLiteralAbstracter(BigLiteralAbstracter abstracter) - : base(abstracter.Gen) - { + : base(abstracter.Gen) { Contract.Requires(abstracter != null); DummyVar = abstracter.DummyVar; IncAxioms = new List(abstracter.IncAxioms); Literals = new List>(abstracter.Literals); } - public Object Clone() - { + public Object Clone() { Contract.Ensures(Contract.Result() != null); return new BigLiteralAbstracter(this); @@ -44,8 +39,7 @@ public Object Clone() private static readonly BigNum ConstantDistanceTPO = BigNum.FromLong(200001); private static readonly BigNum ConstantDistancePO = BigNum.FromLong(100001); - public VCExpr Abstract(VCExpr expr) - { + public VCExpr Abstract(VCExpr expr) { Contract.Requires(expr != null); Contract.Ensures(Contract.Result() != null); @@ -59,21 +53,18 @@ private readonly List /*!*/ IncAxioms; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(cce.NonNullElements(IncAxioms)); } - private void AddAxiom(VCExpr /*!*/ axiom) - { + private void AddAxiom(VCExpr /*!*/ axiom) { Contract.Requires(axiom != null); IncAxioms.Add(axiom); } // Return all axioms that were added since the last time NewAxioms // was called - public VCExpr GetNewAxioms() - { + public VCExpr GetNewAxioms() { Contract.Ensures(Contract.Result() != null); VCExpr res = Gen.NAry(VCExpressionGenerator.AndOp, IncAxioms); IncAxioms.Clear(); @@ -89,18 +80,15 @@ public VCExpr GetNewAxioms() Literals; [ContractInvariantMethod] - void ObjectInvariat() - { + void ObjectInvariat() { Contract.Invariant(Literals != null); Contract.Invariant(Contract.ForAll(Literals, i => i.Value != null)); } - private class EntryComparerC : IComparer> - { + private class EntryComparerC : IComparer> { public int Compare(KeyValuePair a, - KeyValuePair b) - { + KeyValuePair b) { //Contract.Requires(a.Value!=null); //Contract.Requires(b.Value!=null); return a.Key.CompareTo(b.Key); @@ -114,8 +102,7 @@ private readonly VCExprVar /*!*/ DummyVar; [ContractInvariantMethod] - void ObjectInvarint() - { + void ObjectInvarint() { Contract.Invariant(DummyVar != null); } @@ -124,30 +111,24 @@ void ObjectInvarint() // Construct an expression to represent the given (large) integer // literal. Constants are defined and axiomatised if necessary - private VCExpr Represent(BigNum lit) - { + private VCExpr Represent(BigNum lit) { Contract.Requires((NegConstantDistance > lit || lit > ConstantDistance)); Contract.Ensures(Contract.Result() != null); - if (lit.IsNegative) - { + if (lit.IsNegative) { return Gen.Function(VCExpressionGenerator.SubIOp, Gen.Integer(BigNum.ZERO), RepresentPos(lit.Neg)); - } - else - { + } else { return RepresentPos(lit); } } - private VCExpr RepresentPos(BigNum lit) - { + private VCExpr RepresentPos(BigNum lit) { Contract.Requires((lit > ConstantDistance)); Contract.Ensures(Contract.Result() != null); int index = GetIndexFor(lit); - if (index >= 0) - { + if (index >= 0) { // precise match return Literals[index].Value; } @@ -158,30 +139,25 @@ private VCExpr RepresentPos(BigNum lit) VCExpr res = null; BigNum resDistance = ConstantDistancePO; - if (index > 0) - { + if (index > 0) { BigNum dist = lit - Literals[index - 1].Key; - if (dist < resDistance) - { + if (dist < resDistance) { resDistance = dist; res = Gen.Function(VCExpressionGenerator.AddIOp, Literals[index - 1].Value, Gen.Integer(dist)); } } - if (index < Literals.Count) - { + if (index < Literals.Count) { BigNum dist = Literals[index].Key - lit; - if (dist < resDistance) - { + if (dist < resDistance) { resDistance = dist; res = Gen.Function(VCExpressionGenerator.SubIOp, Literals[index].Value, Gen.Integer(dist)); } } - if (res != null) - { + if (res != null) { return res; } @@ -189,8 +165,7 @@ private VCExpr RepresentPos(BigNum lit) return AddConstantFor(lit); } - private VCExpr AddConstantFor(BigNum lit) - { + private VCExpr AddConstantFor(BigNum lit) { Contract.Requires((lit > ConstantDistance)); Contract.Ensures(Contract.Result() != null); @@ -202,18 +177,14 @@ private VCExpr AddConstantFor(BigNum lit) Literals.Insert(index, new KeyValuePair(lit, res)); // relate the new constant to the predecessor and successor - if (index > 0) - { + if (index > 0) { DefineRelationship(Literals[index - 1].Value, Literals[index - 1].Key, res, lit); - } - else - { + } else { DefineRelationship(Gen.Integer(BigNum.ZERO), BigNum.ZERO, res, lit); } - if (index < Literals.Count - 1) - { + if (index < Literals.Count - 1) { DefineRelationship(res, lit, Literals[index + 1].Value, Literals[index + 1].Key); } @@ -222,29 +193,24 @@ private VCExpr AddConstantFor(BigNum lit) } private void DefineRelationship(VCExpr /*!*/ aExpr, BigNum aValue, - VCExpr /*!*/ bExpr, BigNum bValue) - { + VCExpr /*!*/ bExpr, BigNum bValue) { Contract.Requires(aValue < bValue); Contract.Requires(aExpr != null); Contract.Requires(bExpr != null); BigNum dist = bValue - aValue; VCExpr distExpr = Gen.Function(VCExpressionGenerator.SubIOp, bExpr, aExpr); - if (dist <= ConstantDistanceTPO) - { + if (dist <= ConstantDistanceTPO) { // constants that are sufficiently close to each other are put // into a precise relationship AddAxiom(Gen.Eq(distExpr, Gen.Integer(dist))); - } - else - { + } else { AddAxiom(Gen.Function(VCExpressionGenerator.GtOp, distExpr, Gen.Integer(ConstantDistanceTPO))); } } - private int GetIndexFor(BigNum lit) - { + private int GetIndexFor(BigNum lit) { return Literals.BinarySearch( new KeyValuePair(lit, DummyVar), EntryComparer); @@ -252,15 +218,12 @@ private int GetIndexFor(BigNum lit) //////////////////////////////////////////////////////////////////////////// - public override VCExpr Visit(VCExprLiteral node, bool arg) - { + public override VCExpr Visit(VCExprLiteral node, bool arg) { Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); VCExprIntLit intLit = node as VCExprIntLit; - if (intLit != null) - { - if (NegConstantDistance > intLit.Val || intLit.Val > ConstantDistance) - { + if (intLit != null) { + if (NegConstantDistance > intLit.Val || intLit.Val > ConstantDistance) { return Represent(intLit.Val); } } diff --git a/Source/VCExpr/Boogie2VCExpr.cs b/Source/VCExpr/Boogie2VCExpr.cs index a4596afe0..c0593b032 100644 --- a/Source/VCExpr/Boogie2VCExpr.cs +++ b/Source/VCExpr/Boogie2VCExpr.cs @@ -7,8 +7,7 @@ // A translator from Boogie AST to VCExpr AST. -namespace Microsoft.Boogie.VCExprAST -{ +namespace Microsoft.Boogie.VCExprAST { using Microsoft.Boogie; // TODO: in future we might use that for defining symbols for Boogie's conditional compilation @@ -27,9 +26,7 @@ public bool IsAnyProverCommandSupported(string kinds) if (kinds.IndexOf(',') < 0) { return IsProverCommandSupported(kinds); - } - else - { + } else { return kinds.Split(',', ' ').Any(k => IsProverCommandSupported(k)); } } @@ -43,48 +40,41 @@ public VCGenerationOptions(CoreOptions options, List supportedProverComm public delegate VCExpr CodeExprConverter(CodeExpr codeExpr, List bindings, bool isPositiveContext, Dictionary> debugInfos); - public class Boogie2VCExprTranslator : ReadOnlyVisitor, ICloneable - { + public class Boogie2VCExprTranslator : ReadOnlyVisitor, ICloneable { // Stack on which the various Visit-methods put the result of the translation private readonly Stack /*!*/ SubExpressions = new Stack(); [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(cce.NonNullElements(SubExpressions)); Contract.Invariant(Gen != null); } - private void Push(VCExpr expr) - { + private void Push(VCExpr expr) { Contract.Requires(expr != null); SubExpressions.Push(expr); } - private VCExpr Pop() - { + private VCExpr Pop() { Contract.Ensures(Contract.Result() != null); return SubExpressions.Pop(); } - public VCExpr Translate(Expr expr) - { + public VCExpr Translate(Expr expr) { Contract.Requires(expr != null); Contract.Ensures(Contract.Result() != null); this.Visit(expr); return Pop(); } - public List /*!*/ Translate(IList exprs) - { + public List /*!*/ Translate(IList exprs) { Contract.Requires(exprs != null); Contract.Ensures(cce.NonNullElements(Contract.Result>())); List /*!*/ res = new List(); - foreach (Expr e in exprs) - { + foreach (Expr e in exprs) { res.Add(Translate(cce.NonNull(e))); } @@ -97,8 +87,7 @@ internal readonly VCExpressionGenerator /*!*/ Gen; public Boogie2VCExprTranslator(VCExpressionGenerator gen, - VCGenerationOptions genOptions) - { + VCGenerationOptions genOptions) { Contract.Requires(gen != null); Contract.Requires(genOptions != null); this.Gen = gen; @@ -108,33 +97,28 @@ public Boogie2VCExprTranslator(VCExpressionGenerator gen, Formals = new VariableMapping(); } - private Boogie2VCExprTranslator(Boogie2VCExprTranslator tl) - { + private Boogie2VCExprTranslator(Boogie2VCExprTranslator tl) { Contract.Requires(tl != null); this.Gen = tl.Gen; this.GenerationOptions = tl.GenerationOptions; UnboundVariables = - (VariableMapping) tl.UnboundVariables.Clone(); + (VariableMapping)tl.UnboundVariables.Clone(); BoundVariables = new VariableMapping(); Formals = new VariableMapping(); } - public object Clone() - { + public object Clone() { Contract.Ensures(Contract.Result() != null); return new Boogie2VCExprTranslator(this); } private IAppliableTranslator IAppTranslatorAttr = null; - private IAppliableTranslator IAppTranslator - { - get - { + private IAppliableTranslator IAppTranslator { + get { Contract.Ensures(Contract.Result() != null); - if (IAppTranslatorAttr == null) - { + if (IAppTranslatorAttr == null) { IAppTranslatorAttr = new IAppliableTranslator(this); } @@ -145,20 +129,17 @@ private IAppliableTranslator IAppTranslator /////////////////////////////////////////////////////////////////////////////// // Class for handling occurring variables - private class VariableMapping : ICloneable - { + private class VariableMapping : ICloneable { private readonly List /*!*/> /*!*/ Mapping; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(Mapping != null && Contract.ForAll(Mapping, i => cce.NonNullDictionaryAndValues(i))); } - public VariableMapping() - { + public VariableMapping() { List /*!*/> /*!*/ mapping = new List /*!*/>(); @@ -166,14 +147,12 @@ public VariableMapping() this.Mapping = mapping; } - private VariableMapping(VariableMapping vm) - { + private VariableMapping(VariableMapping vm) { Contract.Requires(vm != null); List /*!*/> /*!*/ mapping = new List /*!*/>(); - foreach (Dictionary /*!*/ d in vm.Mapping) - { + foreach (Dictionary /*!*/ d in vm.Mapping) { Contract.Assert(cce.NonNullDictionaryAndValues(d)); mapping.Add(new Dictionary(d)); } @@ -181,33 +160,28 @@ private VariableMapping(VariableMapping vm) this.Mapping = mapping; } - public object Clone() - { + public object Clone() { Contract.Ensures(Contract.Result() != null); return new VariableMapping(this); } - public void PushScope() - { + public void PushScope() { Mapping.Add(new Dictionary()); } - public void PopScope() - { + public void PopScope() { Contract.Assume(Mapping.Count > 0); Mapping.RemoveAt(Mapping.Count - 1); } - public void Bind(VarKind boogieVar, VCExprVar /*!*/ vcExprVar) - { + public void Bind(VarKind boogieVar, VCExprVar /*!*/ vcExprVar) { Contract.Requires(vcExprVar != null); Contract.Requires(boogieVar != null); Contract.Requires(!Contains(boogieVar)); Mapping[Mapping.Count - 1].Add(boogieVar, vcExprVar); } - public VCExprVar Lookup(VarKind boogieVar) - { + public VCExprVar Lookup(VarKind boogieVar) { Contract.Requires(boogieVar != null); Contract.Ensures(Contract.Result() != null); VCExprVar res = LookupHelp(boogieVar); @@ -216,28 +190,23 @@ public VCExprVar Lookup(VarKind boogieVar) } [Pure] - public bool Contains(VarKind boogieVar) - { + public bool Contains(VarKind boogieVar) { Contract.Requires(boogieVar != null); return LookupHelp(boogieVar) != null; } - public bool TryGetValue(VarKind boogieVar, out VCExprVar res) - { + public bool TryGetValue(VarKind boogieVar, out VCExprVar res) { Contract.Requires(boogieVar != null); res = LookupHelp(boogieVar); return res != null; } [Pure] - private VCExprVar LookupHelp(VarKind boogieVar) - { + private VCExprVar LookupHelp(VarKind boogieVar) { Contract.Requires(boogieVar != null); - foreach (Dictionary /*!*/ d in Mapping) - { + foreach (Dictionary /*!*/ d in Mapping) { //Contract.Assert(cce.NonNullElements(d)); - if (d.TryGetValue(boogieVar, out var res)) - { + if (d.TryGetValue(boogieVar, out var res)) { Contract.Assert(res != null); return res; } @@ -260,87 +229,69 @@ private readonly VariableMapping /*!*/ Formals; [ContractInvariantMethod] - void ObjectInvairant() - { + void ObjectInvairant() { Contract.Invariant(UnboundVariables != null); Contract.Invariant(BoundVariables != null); Contract.Invariant(Formals != null); } - internal void PushBoundVariableScope() - { + internal void PushBoundVariableScope() { BoundVariables.PushScope(); } - internal void PopBoundVariableScope() - { + internal void PopBoundVariableScope() { BoundVariables.PopScope(); } - internal void PushFormalsScope() - { + internal void PushFormalsScope() { Formals.PushScope(); } - internal void PopFormalsScope() - { + internal void PopFormalsScope() { Formals.PopScope(); } - public VCExprVar BindVariable(Variable boogieVar) - { + public VCExprVar BindVariable(Variable boogieVar) { Contract.Requires(boogieVar != null); Contract.Ensures(Contract.Result() != null); - if (boogieVar is BoundVariable) - { + if (boogieVar is BoundVariable) { VCExprVar /*!*/ newVar = Gen.Variable(boogieVar.Name, boogieVar.TypedIdent.Type); - BoundVariables.Bind((BoundVariable) boogieVar, newVar); + BoundVariables.Bind((BoundVariable)boogieVar, newVar); return newVar; - } - else if (boogieVar is Formal) - { + } else if (boogieVar is Formal) { VCExprVar /*!*/ newVar = Gen.Variable(boogieVar.Name, boogieVar.TypedIdent.Type); - Formals.Bind((Formal) boogieVar, newVar); + Formals.Bind((Formal)boogieVar, newVar); return newVar; - } - else - { + } else { // only bound variables and formals are declared explicitly Contract.Assert(false); throw new cce.UnreachableException(); } } - public VCExprVar LookupVariable(Variable boogieVar) - { + public VCExprVar LookupVariable(Variable boogieVar) { Contract.Requires(boogieVar != null); Contract.Ensures(Contract.Result() != null); BoundVariable bv = boogieVar as BoundVariable; - if (bv != null) - { + if (bv != null) { return BoundVariables.Lookup(bv); } Formal fml = boogieVar as Formal; - if (fml != null && Formals.TryGetValue(fml, out var res)) - { + if (fml != null && Formals.TryGetValue(fml, out var res)) { return cce.NonNull(res); } // global variables, local variables, incarnations, etc. are // bound the first time they occur - if (!UnboundVariables.TryGetValue(boogieVar, out res)) - { - if (boogieVar is Constant) - { + if (!UnboundVariables.TryGetValue(boogieVar, out res)) { + if (boogieVar is Constant) { res = new VCExprConstant(boogieVar.Name, boogieVar.TypedIdent.Type); - } - else - { + } else { res = new VCExprVar(boogieVar.Name, boogieVar.TypedIdent.Type); } @@ -357,18 +308,15 @@ public VCExprVar LookupVariable(Variable boogieVar) /// /// /// - public VCExprVar TryLookupVariable(Variable boogieVar) - { + public VCExprVar TryLookupVariable(Variable boogieVar) { Contract.Requires(boogieVar != null); Formal fml = boogieVar as Formal; - if (fml != null && Formals.TryGetValue(fml, out var res)) - { + if (fml != null && Formals.TryGetValue(fml, out var res)) { return cce.NonNull(res); } - if (UnboundVariables.TryGetValue(boogieVar, out res)) - { + if (UnboundVariables.TryGetValue(boogieVar, out res)) { return cce.NonNull(res); } @@ -381,63 +329,42 @@ internal readonly VCGenerationOptions /*!*/ GenerationOptions; [ContractInvariantMethod] - void ObjectInvarian() - { + void ObjectInvarian() { Contract.Invariant(GenerationOptions != null); } /////////////////////////////////////////////////////////////////////////////////// - public override Expr VisitLiteralExpr(LiteralExpr node) - { + public override Expr VisitLiteralExpr(LiteralExpr node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Push(TranslateLiteralExpr(node)); return node; } - private VCExpr TranslateLiteralExpr(LiteralExpr node) - { + private VCExpr TranslateLiteralExpr(LiteralExpr node) { Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); - if (node.Val is bool) - { - bool b = (bool) node.Val; - if (b) - { + if (node.Val is bool) { + bool b = (bool)node.Val; + if (b) { return VCExpressionGenerator.True; - } - else - { + } else { return VCExpressionGenerator.False; } - } - else if (node.Val is BigNum) - { + } else if (node.Val is BigNum) { return Gen.Integer(node.asBigNum); - } - else if (node.Val is BigDec) - { + } else if (node.Val is BigDec) { return Gen.Real(node.asBigDec); - } - else if (node.Val is BigFloat) - { + } else if (node.Val is BigFloat) { return Gen.Float(node.asBigFloat); - } - else if (node.Val is RoundingMode) - { + } else if (node.Val is RoundingMode) { return Gen.RMode(node.asRoundingMode); - } - else if (node.Val is String) - { + } else if (node.Val is String) { return Gen.String(node.asString); - } - else if (node.Val is BvConst) - { - return Gen.Bitvector((BvConst) node.Val); - } - else - { + } else if (node.Val is BvConst) { + return Gen.Bitvector((BvConst)node.Val); + } else { System.Diagnostics.Debug.Assert(false, "unknown kind of literal " + node.tok.ToString()); Contract.Assert(false); throw new cce.UnreachableException(); @@ -446,8 +373,7 @@ private VCExpr TranslateLiteralExpr(LiteralExpr node) /////////////////////////////////////////////////////////////////////////////////// - public override Expr VisitIdentifierExpr(IdentifierExpr node) - { + public override Expr VisitIdentifierExpr(IdentifierExpr node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assume(node.Decl != null); // the expression has to be resolved @@ -461,8 +387,7 @@ public override Expr VisitIdentifierExpr(IdentifierExpr node) // value of a variable x is always just "x". (The first update to it in a method // causes it to become "x0". So we just remove old expressions with a visitor // before transforming it into a VCExpr. - public override Expr VisitOldExpr(OldExpr node) - { + public override Expr VisitOldExpr(OldExpr node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); @@ -471,8 +396,7 @@ public override Expr VisitOldExpr(OldExpr node) /////////////////////////////////////////////////////////////////////////////////// - public override Expr VisitNAryExpr(NAryExpr node) - { + public override Expr VisitNAryExpr(NAryExpr node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Push(TranslateNAryExpr(node)); @@ -481,30 +405,23 @@ public override Expr VisitNAryExpr(NAryExpr node) public bool isPositiveContext = true; - private VCExpr TranslateNAryExpr(NAryExpr node) - { + private VCExpr TranslateNAryExpr(NAryExpr node) { Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); - if (node.Fun is FieldUpdate fieldUpdate) - { + if (node.Fun is FieldUpdate fieldUpdate) { return TranslateNAryExpr(fieldUpdate.Update(Token.NoToken, node.Args[0], node.Args[1])); } - + bool flipContextForArg0 = false; - if (node.Fun is UnaryOperator) - { - UnaryOperator oper = (UnaryOperator) node.Fun; - if (oper.Op == UnaryOperator.Opcode.Not) - { + if (node.Fun is UnaryOperator) { + UnaryOperator oper = (UnaryOperator)node.Fun; + if (oper.Op == UnaryOperator.Opcode.Not) { flipContextForArg0 = true; } - } - else if (node.Fun is BinaryOperator) - { - BinaryOperator oper = (BinaryOperator) node.Fun; - if (oper.Op == BinaryOperator.Opcode.Imp) - { + } else if (node.Fun is BinaryOperator) { + BinaryOperator oper = (BinaryOperator)node.Fun; + if (oper.Op == BinaryOperator.Opcode.Imp) { flipContextForArg0 = true; } } @@ -513,22 +430,18 @@ private VCExpr TranslateNAryExpr(NAryExpr node) List /*!*/ vcs = new List(n); - for (int i = 0; i < n; i++) - { - if (i == 0 && flipContextForArg0) - { + for (int i = 0; i < n; i++) { + if (i == 0 && flipContextForArg0) { isPositiveContext = !isPositiveContext; } vcs.Add(Translate(cce.NonNull(node.Args)[i])); - if (i == 0 && flipContextForArg0) - { + if (i == 0 && flipContextForArg0) { isPositiveContext = !isPositiveContext; } } - if (node.Type == null) - { + if (node.Type == null) { System.Console.WriteLine("*** type is null for {0}", node); Contract.Assert(false); throw new cce.UnreachableException(); @@ -543,25 +456,21 @@ private static List /*!*/ EMPTY_TYPE_LIST = new List(); [ContractInvariantMethod] - void ObjectInvirant() - { + void ObjectInvirant() { Contract.Invariant(EMPTY_TYPE_LIST != null); } - private List /*!*/ ToList(TypeParamInstantiation insts) - { + private List /*!*/ ToList(TypeParamInstantiation insts) { Contract.Requires(insts != null); Contract.Ensures(cce.NonNullElements(Contract.Result>())); - if (insts.FormalTypeParams.Count == 0) - { + if (insts.FormalTypeParams.Count == 0) { return EMPTY_TYPE_LIST; } List /*!*/ typeArgs = new List(); - foreach (TypeVariable /*!*/ var in insts.FormalTypeParams) - { + foreach (TypeVariable /*!*/ var in insts.FormalTypeParams) { Contract.Assert(var != null); typeArgs.Add(insts[var]); } @@ -571,38 +480,33 @@ void ObjectInvirant() /////////////////////////////////////////////////////////////////////////////////// - public override QuantifierExpr VisitQuantifierExpr(QuantifierExpr node) - { + public override QuantifierExpr VisitQuantifierExpr(QuantifierExpr node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Push(TranslateQuantifierExpr(node)); return node; } - public override Expr VisitExistsExpr(ExistsExpr node) - { + public override Expr VisitExistsExpr(ExistsExpr node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); - node = (ExistsExpr) this.VisitQuantifierExpr(node); + node = (ExistsExpr)this.VisitQuantifierExpr(node); return node; } - public override Expr VisitForallExpr(ForallExpr node) - { + public override Expr VisitForallExpr(ForallExpr node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); - node = (ForallExpr) this.VisitQuantifierExpr(node); + node = (ForallExpr)this.VisitQuantifierExpr(node); return node; } - private VCExpr TranslateQuantifierExpr(QuantifierExpr node) - { + private VCExpr TranslateQuantifierExpr(QuantifierExpr node) { Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); List /*!*/ typeParams = new List(); - foreach (TypeVariable /*!*/ v in node.TypeParameters) - { + foreach (TypeVariable /*!*/ v in node.TypeParameters) { Contract.Assert(v != null); typeParams.Add(v); } @@ -611,13 +515,11 @@ private VCExpr TranslateQuantifierExpr(QuantifierExpr node) List /*!*/ boundVars = new List(); - foreach (Variable /*!*/ v in node.Dummies) - { + foreach (Variable /*!*/ v in node.Dummies) { boundVars.Add(BindVariable(v)); } - try - { + try { List /*!*/ triggers = TranslateTriggers(node.Triggers); VCExpr /*!*/ @@ -626,36 +528,28 @@ private VCExpr TranslateQuantifierExpr(QuantifierExpr node) info = GenerateQuantifierInfo(node, boundVars); Quantifier quan; - if (node is ForallExpr) - { + if (node is ForallExpr) { quan = Quantifier.ALL; - } - else if (node is ExistsExpr) - { + } else if (node is ExistsExpr) { quan = Quantifier.EX; - } - else - { + } else { Contract.Assert(false); throw new cce.UnreachableException(); } return Gen.Quantify(quan, typeParams, boundVars, triggers, info, body); } - finally - { + finally { PopBoundVariableScope(); } } - private List /*!*/ TranslateTriggers(Trigger node) - { + private List /*!*/ TranslateTriggers(Trigger node) { Contract.Ensures(cce.NonNullElements(Contract.Result>())); List /*!*/ res = new List(); Trigger curTrigger = node; - while (curTrigger != null) - { + while (curTrigger != null) { res.Add(Gen.Trigger(curTrigger.Pos, Translate(curTrigger.Tr))); curTrigger = curTrigger.Next; } @@ -663,8 +557,7 @@ private VCExpr TranslateQuantifierExpr(QuantifierExpr node) return res; } - private VCQuantifierInfo GenerateQuantifierInfo(QuantifierExpr node, List boundVars) - { + private VCQuantifierInfo GenerateQuantifierInfo(QuantifierExpr node, List boundVars) { Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); return new VCQuantifierInfo( @@ -676,33 +569,26 @@ private VCQuantifierInfo GenerateQuantifierInfo(QuantifierExpr node, List vars = node.Dummies; QKeyValue attributes = node.Attributes; // Check for a 'qid, name' pair in attributes string qid = QKeyValue.FindStringAttribute(attributes, "qid"); - if (qid == null && vars.Count != 0) - { + if (qid == null && vars.Count != 0) { // generate default name (line:column position in .bpl file) Variable v = vars[0]; Contract.Assert(v != null); StringBuilder buf = new StringBuilder(20); string filename = v.tok.filename; - if (filename == null) - { + if (filename == null) { filename = "unknown"; } - for (int i = 0; i < filename.Length; ++i) - { - if (filename[i] == '/' || filename[i] == '\\') - { + for (int i = 0; i < filename.Length; ++i) { + if (filename[i] == '/' || filename[i] == '\\') { buf.Length = 0; } - if (char.IsLetterOrDigit(filename[i])) - { - if (buf.Length == 0 && char.IsDigit(filename[i])) - { + if (char.IsLetterOrDigit(filename[i])) { + if (buf.Length == 0 && char.IsDigit(filename[i])) { // Z3 does not like QID's to start with a digit, so we prepend another character buf.Append('_'); } @@ -715,20 +601,17 @@ private string GetQid(QuantifierExpr node) return qid; } - public override Expr VisitLetExpr(LetExpr node) - { + public override Expr VisitLetExpr(LetExpr node) { Contract.Ensures(Contract.Result() != null); var rhss = new List(); - foreach (var e in node.Rhss) - { + foreach (var e in node.Rhss) { rhss.Add(Translate(e)); } PushBoundVariableScope(); var boundVars = new List(); - foreach (var v in node.Dummies) - { + foreach (var v in node.Dummies) { boundVars.Add(BindVariable(v)); } @@ -737,8 +620,7 @@ public override Expr VisitLetExpr(LetExpr node) Contract.Assert(boundVars.Count == rhss.Count); var bindings = new List(); - for (var i = 0; i < boundVars.Count; i++) - { + for (var i = 0; i < boundVars.Count; i++) { var b = new VCExprLetBinding(boundVars[i], rhss[i]); bindings.Add(b); } @@ -750,16 +632,14 @@ public override Expr VisitLetExpr(LetExpr node) /////////////////////////////////////////////////////////////////////////////////// - public override Expr VisitBvExtractExpr(BvExtractExpr node) - { + public override Expr VisitBvExtractExpr(BvExtractExpr node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Push(TranslateBvExtractExpr(node)); return node; } - private VCExpr TranslateBvExtractExpr(BvExtractExpr node) - { + private VCExpr TranslateBvExtractExpr(BvExtractExpr node) { Contract.Requires(node != null); Contract.Requires((node.Start <= node.End)); Contract.Ensures(Contract.Result() != null); @@ -770,16 +650,14 @@ private VCExpr TranslateBvExtractExpr(BvExtractExpr node) /////////////////////////////////////////////////////////////////////////////////// - public override Expr VisitBvConcatExpr(BvConcatExpr node) - { + public override Expr VisitBvConcatExpr(BvConcatExpr node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Push(TranslateBvConcatExpr(node)); return node; } - private VCExpr TranslateBvConcatExpr(BvConcatExpr node) - { + private VCExpr TranslateBvConcatExpr(BvConcatExpr node) { Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); VCExpr /*!*/ @@ -792,70 +670,61 @@ private VCExpr TranslateBvConcatExpr(BvConcatExpr node) /////////////////////////////////////////////////////////////////////////////////// // all the other cases should never happen - public override Cmd VisitAssertCmd(AssertCmd node) - { + public override Cmd VisitAssertCmd(AssertCmd node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Cmd VisitAssignCmd(AssignCmd node) - { + public override Cmd VisitAssignCmd(AssignCmd node) { Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Cmd VisitUnpackCmd(UnpackCmd node) - { + public override Cmd VisitUnpackCmd(UnpackCmd node) { Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - - public override Cmd VisitAssumeCmd(AssumeCmd node) - { + + public override Cmd VisitAssumeCmd(AssumeCmd node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override AtomicRE VisitAtomicRE(AtomicRE node) - { + public override AtomicRE VisitAtomicRE(AtomicRE node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Axiom VisitAxiom(Axiom node) - { + public override Axiom VisitAxiom(Axiom node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Type VisitBasicType(BasicType node) - { + public override Type VisitBasicType(BasicType node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Type VisitBvType(BvType node) - { + public override Type VisitBvType(BvType node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Block VisitBlock(Block node) - { + public override Block VisitBlock(Block node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); @@ -864,377 +733,330 @@ public override Block VisitBlock(Block node) public CodeExprConverter codeExprConverter = null; - public void SetCodeExprConverter(CodeExprConverter f) - { + public void SetCodeExprConverter(CodeExprConverter f) { this.codeExprConverter = f; } - public override Expr VisitCodeExpr(CodeExpr codeExpr) - { + public override Expr VisitCodeExpr(CodeExpr codeExpr) { //Contract.Requires(codeExpr != null); Contract.Ensures(Contract.Result() != null); Contract.Assume(codeExprConverter != null); - + List bindings = new List(); VCExpr e = codeExprConverter(codeExpr, bindings, isPositiveContext, new()); Push(e); return codeExpr; } - public override List VisitBlockSeq(List blockSeq) - { + public override List VisitBlockSeq(List blockSeq) { //Contract.Requires(blockSeq != null); Contract.Ensures(Contract.Result>() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override List /*!*/ VisitBlockList(List /*!*/ blocks) - { + public override List /*!*/ VisitBlockList(List /*!*/ blocks) { //Contract.Requires(cce.NonNullElements(blocks)); Contract.Ensures(cce.NonNullElements(Contract.Result>())); Contract.Assert(false); throw new cce.UnreachableException(); } - public override BoundVariable VisitBoundVariable(BoundVariable node) - { + public override BoundVariable VisitBoundVariable(BoundVariable node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Cmd VisitCallCmd(CallCmd node) - { + public override Cmd VisitCallCmd(CallCmd node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Cmd VisitParCallCmd(ParCallCmd node) - { + public override Cmd VisitParCallCmd(ParCallCmd node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override List VisitCmdSeq(List cmdSeq) - { + public override List VisitCmdSeq(List cmdSeq) { //Contract.Requires(cmdSeq != null); Contract.Ensures(Contract.Result>() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Choice VisitChoice(Choice node) - { + public override Choice VisitChoice(Choice node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Cmd VisitCommentCmd(CommentCmd node) - { + public override Cmd VisitCommentCmd(CommentCmd node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Constant VisitConstant(Constant node) - { + public override Constant VisitConstant(Constant node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override CtorType VisitCtorType(CtorType node) - { + public override CtorType VisitCtorType(CtorType node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Declaration VisitDeclaration(Declaration node) - { + public override Declaration VisitDeclaration(Declaration node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override List /*!*/ VisitDeclarationList(List /*!*/ declarationList) - { + public override List /*!*/ VisitDeclarationList(List /*!*/ declarationList) { //Contract.Requires(cce.NonNullElements(declarationList)); Contract.Ensures(cce.NonNullElements(Contract.Result>())); Contract.Assert(false); throw new cce.UnreachableException(); } - public override DeclWithFormals VisitDeclWithFormals(DeclWithFormals node) - { + public override DeclWithFormals VisitDeclWithFormals(DeclWithFormals node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Requires VisitRequires(Requires @requires) - { + public override Requires VisitRequires(Requires @requires) { //Contract.Requires(@requires != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override List VisitRequiresSeq(List requiresSeq) - { + public override List VisitRequiresSeq(List requiresSeq) { //Contract.Requires(requiresSeq != null); Contract.Ensures(Contract.Result>() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Ensures VisitEnsures(Ensures @ensures) - { + public override Ensures VisitEnsures(Ensures @ensures) { //Contract.Requires(@ensures != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override List VisitEnsuresSeq(List ensuresSeq) - { + public override List VisitEnsuresSeq(List ensuresSeq) { //Contract.Requires(ensuresSeq != null); Contract.Ensures(Contract.Result>() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Formal VisitFormal(Formal node) - { + public override Formal VisitFormal(Formal node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Function VisitFunction(Function node) - { + public override Function VisitFunction(Function node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override GlobalVariable VisitGlobalVariable(GlobalVariable node) - { + public override GlobalVariable VisitGlobalVariable(GlobalVariable node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override GotoCmd VisitGotoCmd(GotoCmd node) - { + public override GotoCmd VisitGotoCmd(GotoCmd node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Cmd VisitHavocCmd(HavocCmd node) - { + public override Cmd VisitHavocCmd(HavocCmd node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Implementation VisitImplementation(Implementation node) - { + public override Implementation VisitImplementation(Implementation node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override LocalVariable VisitLocalVariable(LocalVariable node) - { + public override LocalVariable VisitLocalVariable(LocalVariable node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override AssignLhs VisitMapAssignLhs(MapAssignLhs node) - { + public override AssignLhs VisitMapAssignLhs(MapAssignLhs node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Type VisitMapType(MapType node) - { + public override Type VisitMapType(MapType node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Procedure VisitProcedure(Procedure node) - { + public override Procedure VisitProcedure(Procedure node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Program VisitProgram(Program node) - { + public override Program VisitProgram(Program node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Cmd VisitRE(RE node) - { + public override Cmd VisitRE(RE node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override List VisitRESeq(List reSeq) - { + public override List VisitRESeq(List reSeq) { //Contract.Requires(reSeq != null); Contract.Ensures(Contract.Result>() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override ReturnCmd VisitReturnCmd(ReturnCmd node) - { + public override ReturnCmd VisitReturnCmd(ReturnCmd node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override ReturnExprCmd VisitReturnExprCmd(ReturnExprCmd node) - { + public override ReturnExprCmd VisitReturnExprCmd(ReturnExprCmd node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Sequential VisitSequential(Sequential node) - { + public override Sequential VisitSequential(Sequential node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override AssignLhs VisitSimpleAssignLhs(SimpleAssignLhs node) - { + public override AssignLhs VisitSimpleAssignLhs(SimpleAssignLhs node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Cmd VisitStateCmd(StateCmd node) - { + public override Cmd VisitStateCmd(StateCmd node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override TransferCmd VisitTransferCmd(TransferCmd node) - { + public override TransferCmd VisitTransferCmd(TransferCmd node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Trigger VisitTrigger(Trigger node) - { + public override Trigger VisitTrigger(Trigger node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Type VisitType(Type node) - { + public override Type VisitType(Type node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override TypedIdent VisitTypedIdent(TypedIdent node) - { + public override TypedIdent VisitTypedIdent(TypedIdent node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Type VisitTypeSynonymAnnotation(TypeSynonymAnnotation node) - { + public override Type VisitTypeSynonymAnnotation(TypeSynonymAnnotation node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Type VisitTypeVariable(TypeVariable node) - { + public override Type VisitTypeVariable(TypeVariable node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Variable VisitVariable(Variable node) - { + public override Variable VisitVariable(Variable node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override List VisitVariableSeq(List variableSeq) - { + public override List VisitVariableSeq(List variableSeq) { //Contract.Requires(variableSeq != null); Contract.Ensures(Contract.Result>() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Cmd VisitAssertEnsuresCmd(AssertEnsuresCmd node) - { + public override Cmd VisitAssertEnsuresCmd(AssertEnsuresCmd node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public override Cmd VisitAssertRequiresCmd(AssertRequiresCmd node) - { + public override Cmd VisitAssertRequiresCmd(AssertRequiresCmd node) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(false); @@ -1245,40 +1067,33 @@ public override Cmd VisitAssertRequiresCmd(AssertRequiresCmd node) ///////////////////////////////////////////////////////////////////////////////// - public class IAppliableTranslator : IAppliableVisitor - { + public class IAppliableTranslator : IAppliableVisitor { private readonly Boogie2VCExprTranslator /*!*/ BaseTranslator; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(BaseTranslator != null); } - private VCExpressionGenerator /*!*/ Gen - { - get - { + private VCExpressionGenerator /*!*/ Gen { + get { Contract.Ensures(Contract.Result() != null); return BaseTranslator.Gen; } } - private VCGenerationOptions GenerationOptions - { - get - { + private VCGenerationOptions GenerationOptions { + get { Contract.Ensures(Contract.Result() != null); return BaseTranslator.GenerationOptions; } } - public IAppliableTranslator(Boogie2VCExprTranslator baseTranslator) - { + public IAppliableTranslator(Boogie2VCExprTranslator baseTranslator) { Contract.Requires(baseTranslator != null); this.BaseTranslator = baseTranslator; } @@ -1292,15 +1107,13 @@ private List /*!*/ typeArgs = new List(); [ContractInvariantMethod] - void ObjectInvarianet() - { + void ObjectInvarianet() { Contract.Invariant(args != null); Contract.Invariant(typeArgs != null); } - public VCExpr Translate(IAppliable app, Type ty, List /*!*/ args, List /*!*/ typeArgs) - { + public VCExpr Translate(IAppliable app, Type ty, List /*!*/ args, List /*!*/ typeArgs) { Contract.Requires(ty != null); Contract.Requires(app != null); Contract.Requires(cce.NonNullElements(typeArgs)); @@ -1323,21 +1136,16 @@ public VCExpr Translate(IAppliable app, Type ty, List /*!*/ args, /////////////////////////////////////////////////////////////////////////////// - public VCExpr Visit(UnaryOperator unaryOperator) - { + public VCExpr Visit(UnaryOperator unaryOperator) { //Contract.Requires(unaryOperator != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(unaryOperator.Op == UnaryOperator.Opcode.Neg || unaryOperator.Op == UnaryOperator.Opcode.Not); Contract.Assert(this.args.Count == 1); - if (unaryOperator.Op == UnaryOperator.Opcode.Neg) - { + if (unaryOperator.Op == UnaryOperator.Opcode.Neg) { VCExpr e = cce.NonNull(this.args[0]); - if (cce.NonNull(e.Type).IsInt) - { + if (cce.NonNull(e.Type).IsInt) { return Gen.Function(VCExpressionGenerator.SubIOp, Gen.Integer(BigNum.ZERO), e); - } - else - { + } else { // if (cce.NonNull(e.Type).IsReal) { return Gen.Function(VCExpressionGenerator.SubROp, Gen.Real(BigDec.ZERO), e); } @@ -1345,22 +1153,18 @@ public VCExpr Visit(UnaryOperator unaryOperator) //else {//is float //return Gen.Function(VCExpressionGenerator.SubFOp, Gen.Float(BigFloat.ZERO(8, 23)), e); //} - } - else - { + } else { return Gen.Not(this.args); } } - public VCExpr Visit(BinaryOperator binaryOperator) - { + public VCExpr Visit(BinaryOperator binaryOperator) { //Contract.Requires(binaryOperator != null); Contract.Ensures(Contract.Result() != null); return TranslateBinaryOperator(binaryOperator, this.args); } - public VCExpr Visit(FunctionCall functionCall) - { + public VCExpr Visit(FunctionCall functionCall) { //Contract.Requires(functionCall != null); Contract.Ensures(Contract.Result() != null); return TranslateFunctionCall(functionCall, this.args, this.typeArgs); @@ -1384,21 +1188,18 @@ public VCExpr Visit(MapStore mapStore) return Gen.Store(this.args, this.typeArgs); } - public VCExpr Visit(TypeCoercion typeCoercion) - { + public VCExpr Visit(TypeCoercion typeCoercion) { //Contract.Requires(typeCoercion != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(this.args.Count == 1); return this.args[0]; } - public VCExpr Visit(ArithmeticCoercion arithCoercion) - { + public VCExpr Visit(ArithmeticCoercion arithCoercion) { //Contract.Requires(arithCoercion != null); Contract.Ensures(Contract.Result() != null); Contract.Assert(this.args.Count == 1); - switch (arithCoercion.Coercion) - { + switch (arithCoercion.Coercion) { case ArithmeticCoercion.CoercionType.ToInt: return Gen.Function(VCExpressionGenerator.ToIntOp, this.args); case ArithmeticCoercion.CoercionType.ToReal: @@ -1409,20 +1210,17 @@ public VCExpr Visit(ArithmeticCoercion arithCoercion) } } - public VCExpr Visit(IfThenElse ite) - { + public VCExpr Visit(IfThenElse ite) { //Contract.Requires(ite != null); Contract.Ensures(Contract.Result() != null); return Gen.Function(VCExpressionGenerator.IfThenElseOp, this.args); } - - public VCExpr Visit(FieldAccess fieldAccess) - { + + public VCExpr Visit(FieldAccess fieldAccess) { var accessor = fieldAccess.Accessors[0]; var expr = Gen.Function(new VCExprFieldAccessOp(fieldAccess.DatatypeTypeCtorDecl, accessor), this.args); - for (int i = 1; i < fieldAccess.Accessors.Count; i++) - { + for (int i = 1; i < fieldAccess.Accessors.Count; i++) { accessor = fieldAccess.Accessors[i]; var condExpr = Gen.Function(new VCExprIsConstructorOp(fieldAccess.DatatypeTypeCtorDecl, accessor.ConstructorIndex), this.args); @@ -1434,68 +1232,49 @@ public VCExpr Visit(FieldAccess fieldAccess) return expr; } - public VCExpr Visit(FieldUpdate fieldUpdate) - { + public VCExpr Visit(FieldUpdate fieldUpdate) { throw new cce.UnreachableException(); } - - public VCExpr Visit(IsConstructor isConstructor) - { + + public VCExpr Visit(IsConstructor isConstructor) { return Gen.Function(new VCExprIsConstructorOp(isConstructor.DatatypeTypeCtorDecl, isConstructor.ConstructorIndex), this.args); } - - + + /////////////////////////////////////////////////////////////////////////////// - private VCExpr TranslateBinaryOperator(BinaryOperator app, List /*!*/ args) - { + private VCExpr TranslateBinaryOperator(BinaryOperator app, List /*!*/ args) { Contract.Requires(app != null); Contract.Requires(cce.NonNullElements(args)); Contract.Ensures(Contract.Result() != null); Contract.Assert(args.Count == 2); Type t = cce.NonNull(cce.NonNull(args[0]).Type); - switch (app.Op) - { + switch (app.Op) { case BinaryOperator.Opcode.Add: - if (t.IsInt) - { + if (t.IsInt) { return Gen.Function(VCExpressionGenerator.AddIOp, args); - } - else if (t.IsReal) - { + } else if (t.IsReal) { return Gen.Function(VCExpressionGenerator.AddROp, args); - } - else - { + } else { //t is float return Gen.Function(Gen.BinaryFloatOp(t.FloatSignificand, t.FloatExponent, "+"), args); } case BinaryOperator.Opcode.Sub: - if (t.IsInt) - { + if (t.IsInt) { return Gen.Function(VCExpressionGenerator.SubIOp, args); - } - else if (t.IsReal) - { + } else if (t.IsReal) { return Gen.Function(VCExpressionGenerator.SubROp, args); - } - else - { + } else { //t is float return Gen.Function(Gen.BinaryFloatOp(t.FloatSignificand, t.FloatExponent, "-"), args); } case BinaryOperator.Opcode.Mul: - if (t.IsInt) - { + if (t.IsInt) { return Gen.Function(VCExpressionGenerator.MulIOp, args); - } - else if (t.IsReal) - { + } else if (t.IsReal) { return Gen.Function(VCExpressionGenerator.MulROp, args); - } - else - { + } else { //t is float return Gen.Function(Gen.BinaryFloatOp(t.FloatSignificand, t.FloatExponent, "*"), args); } @@ -1504,20 +1283,17 @@ private VCExpr TranslateBinaryOperator(BinaryOperator app, List /* case BinaryOperator.Opcode.Mod: return Gen.Function(VCExpressionGenerator.ModOp, args); case BinaryOperator.Opcode.RealDiv: - if (t.IsFloat) - { + if (t.IsFloat) { return Gen.Function(Gen.BinaryFloatOp(t.FloatSignificand, t.FloatExponent, "/"), args); } VCExpr arg0 = cce.NonNull(args[0]); VCExpr arg1 = cce.NonNull(args[1]); - if (cce.NonNull(arg0.Type).IsInt) - { + if (cce.NonNull(arg0.Type).IsInt) { arg0 = Gen.Function(VCExpressionGenerator.ToRealOp, arg0); } - if (cce.NonNull(arg1.Type).IsInt) - { + if (cce.NonNull(arg1.Type).IsInt) { arg1 = Gen.Function(VCExpressionGenerator.ToRealOp, arg1); } @@ -1527,43 +1303,37 @@ private VCExpr TranslateBinaryOperator(BinaryOperator app, List /* case BinaryOperator.Opcode.Eq: case BinaryOperator.Opcode.Iff: // we don't distinguish between equality and equivalence at this point - if (t.IsFloat) - { + if (t.IsFloat) { return Gen.Function(Gen.BinaryFloatOp(t.FloatSignificand, t.FloatExponent, "=="), args); } return Gen.Function(VCExpressionGenerator.EqOp, args); case BinaryOperator.Opcode.Neq: - if (t.IsFloat) - { + if (t.IsFloat) { return Gen.Function(Gen.BinaryFloatOp(t.FloatSignificand, t.FloatExponent, "!="), args); } return Gen.Function(VCExpressionGenerator.NeqOp, args); case BinaryOperator.Opcode.Lt: - if (t.IsFloat) - { + if (t.IsFloat) { return Gen.Function(Gen.BinaryFloatOp(t.FloatSignificand, t.FloatExponent, "<"), args); } return Gen.Function(VCExpressionGenerator.LtOp, args); case BinaryOperator.Opcode.Le: - if (t.IsFloat) - { + if (t.IsFloat) { return Gen.Function(Gen.BinaryFloatOp(t.FloatSignificand, t.FloatExponent, "<="), args); } return Gen.Function(VCExpressionGenerator.LeOp, args); case BinaryOperator.Opcode.Ge: - if (t.IsFloat) - { + if (t.IsFloat) { return Gen.Function(Gen.BinaryFloatOp(t.FloatSignificand, t.FloatExponent, ">="), args); } return Gen.Function(VCExpressionGenerator.GeOp, args); case BinaryOperator.Opcode.Gt: - if (t.IsFloat) - { + if (t.IsFloat) { return Gen.Function(Gen.BinaryFloatOp(t.FloatSignificand, t.FloatExponent, ">"), args); } @@ -1583,8 +1353,7 @@ private VCExpr TranslateBinaryOperator(BinaryOperator app, List /* /////////////////////////////////////////////////////////////////////////////// private VCExpr /*!*/ - TranslateFunctionCall(FunctionCall app, List /*!*/ args, List /*!*/ typeArgs) - { + TranslateFunctionCall(FunctionCall app, List /*!*/ args, List /*!*/ typeArgs) { Contract.Requires(cce.NonNullElements(args)); Contract.Requires(cce.NonNullElements(typeArgs)); Contract.Requires(app != null); @@ -1592,8 +1361,7 @@ private VCExpr /*!*/ Contract.Ensures(Contract.Result() != null); // resolution must have happened VCExpr res = ApplyExpansion(app, args, typeArgs); - if (res != null) - { + if (res != null) { return res; } @@ -1602,18 +1370,15 @@ private VCExpr /*!*/ return Gen.Function(functionOp, args, typeArgs); } - private VCExpr ApplyExpansion(FunctionCall app, List /*!*/ args, List /*!*/ typeArgs) - { + private VCExpr ApplyExpansion(FunctionCall app, List /*!*/ args, List /*!*/ typeArgs) { Contract.Requires(app != null); Contract.Requires(cce.NonNullElements(args)); Contract.Requires(cce.NonNullElements(typeArgs)); Contract.Assert(app.Func != null); // resolution must have happened - lock (app.Func) - { + lock (app.Func) { var exp = app.Func.Body; - if (exp == null) - { + if (exp == null) { return null; } @@ -1621,24 +1386,21 @@ private VCExpr ApplyExpansion(FunctionCall app, List /*!*/ args, L translatedBody; VCExprSubstitution /*!*/ subst = new VCExprSubstitution(); - try - { + try { BaseTranslator.PushFormalsScope(); BaseTranslator.PushBoundVariableScope(); // first bind the formals to VCExpr variables, which are later // substituted with the actual parameters var inParams = app.Func.InParams; - for (int i = 0; i < inParams.Count; ++i) - { + for (int i = 0; i < inParams.Count; ++i) { subst[BaseTranslator.BindVariable(inParams[i])] = args[i]; } // recursively translate the body of the expansion translatedBody = BaseTranslator.Translate(exp); } - finally - { + finally { BaseTranslator.PopFormalsScope(); BaseTranslator.PopBoundVariableScope(); } @@ -1646,8 +1408,7 @@ private VCExpr ApplyExpansion(FunctionCall app, List /*!*/ args, L // substitute the formals with the actual parameters in the body var tparms = app.Func.TypeParameters; Contract.Assert(typeArgs.Count == tparms.Count); - for (int i = 0; i < typeArgs.Count; ++i) - { + for (int i = 0; i < typeArgs.Count; ++i) { subst[tparms[i]] = typeArgs[i]; } diff --git a/Source/VCExpr/Clustering.cs b/Source/VCExpr/Clustering.cs index 33677850c..caeba454b 100644 --- a/Source/VCExpr/Clustering.cs +++ b/Source/VCExpr/Clustering.cs @@ -6,24 +6,20 @@ // Code for managing and clustering sets of terms; this is used to // compress the input given to the theorem prover -namespace Microsoft.Boogie.Clustering -{ - public class SubtermCollector : BoundVarTraversingVCExprVisitor - { +namespace Microsoft.Boogie.Clustering { + public class SubtermCollector : BoundVarTraversingVCExprVisitor { private readonly VCExpressionGenerator /*!*/ Gen; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(Gen != null); Contract.Invariant(cce.NonNullDictionaryAndValues(GlobalVariables)); Contract.Invariant(cce.NonNullDictionaryAndValues(SubtermClusters)); } - public SubtermCollector(VCExpressionGenerator gen) - { + public SubtermCollector(VCExpressionGenerator gen) { Contract.Requires(gen != null); Gen = gen; } @@ -35,11 +31,9 @@ public SubtermCollector(VCExpressionGenerator gen) private readonly IDictionary SubtermClusters = new Dictionary(); - public void UnifyClusters() - { + public void UnifyClusters() { foreach (KeyValuePair pair - in SubtermClusters) - { + in SubtermClusters) { Contract.Assert(cce.NonNullElements(pair)); pair.Value.UnifyClusters(); } @@ -47,39 +41,32 @@ public void UnifyClusters() //////////////////////////////////////////////////////////////////////////// - protected override bool StandardResult(VCExpr node, bool arg) - { + protected override bool StandardResult(VCExpr node, bool arg) { //Contract.Requires(node != null); return false; // by default, do not collect terms containing node } - public override bool Visit(VCExprLiteral node, bool arg) - { + public override bool Visit(VCExprLiteral node, bool arg) { Contract.Requires(node != null); return true; } - public override bool Visit(VCExprNAry node, bool arg) - { + public override async DynamicStack Visit(VCExprNAry node, bool arg) { Contract.Requires(node != null); VCExprBoogieFunctionOp op = node.Op as VCExprBoogieFunctionOp; - if (op == null) - { - base.Visit(node, arg); + if (op == null) { + await base.Visit(node, arg); return false; } bool res = true; - foreach (VCExpr subexpr in node.Arguments) - { + foreach (VCExpr subexpr in node.Arguments) { Contract.Assert(subexpr != null); - res &= this.Traverse(subexpr, arg); + res &= await Traverse(subexpr, arg); } - if (res) - { - if (!SubtermClusters.TryGetValue(op, out var clusters)) - { + if (res) { + if (!SubtermClusters.TryGetValue(op, out var clusters)) { clusters = new TermClustersSameHead(op, GlobalVariables, Gen); SubtermClusters.Add(op, clusters); } @@ -90,11 +77,9 @@ public override bool Visit(VCExprNAry node, bool arg) return res; } - public override bool Visit(VCExprVar node, bool arg) - { + public override bool Visit(VCExprVar node, bool arg) { Contract.Requires(node != null); - if (!BoundTermVars.ContainsKey(node)) - { + if (!BoundTermVars.ContainsKey(node)) { GlobalVariables[node] = node; } @@ -102,14 +87,12 @@ public override bool Visit(VCExprVar node, bool arg) } [Pure] - public override string ToString() - { + public override string ToString() { Contract.Ensures(Contract.Result() != null); string /*!*/ res = ""; foreach (KeyValuePair pair - in SubtermClusters) - { + in SubtermClusters) { Contract.Assert(cce.NonNullElements(pair)); res = res + pair.Value + "\n"; } @@ -122,11 +105,9 @@ public override string ToString() // Class for managing and clustering a set of terms that all start // with the same function symbol - internal class TermClustersSameHead - { + internal class TermClustersSameHead { [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(Op != null); Contract.Invariant(Gen != null); Contract.Invariant(cce.NonNullDictionaryAndValues(GlobalVariables)); @@ -143,8 +124,7 @@ private readonly VCExpressionGenerator /*!*/ Gen; public TermClustersSameHead(VCExprOp op, IDictionary /*!*/ globalVars, - VCExpressionGenerator /*!*/ gen) - { + VCExpressionGenerator /*!*/ gen) { Contract.Requires(cce.NonNullDictionaryAndValues(globalVars)); Contract.Requires(gen != null); Contract.Requires(op != null); @@ -156,29 +136,25 @@ public TermClustersSameHead(VCExprOp op, IDictionary /*!*/ Clusters = new List(); - private struct Cluster - { + private struct Cluster { public readonly VCExprNAry /*!*/ Generator; public readonly int Size; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(Generator != null); } - public Cluster(VCExprNAry generator, int size) - { + public Cluster(VCExprNAry generator, int size) { Contract.Requires(generator != null); Generator = generator; Size = size; } } - private int Distance(Cluster a, Cluster b) - { + private int Distance(Cluster a, Cluster b) { AntiUnificationVisitor /*!*/ visitor = new AntiUnificationVisitor(Gen); visitor.AntiUnify(a.Generator, b.Generator); @@ -187,16 +163,14 @@ private int Distance(Cluster a, Cluster b) return (a.Size - 1) * reprSizeA + (b.Size - 1) * reprSizeB; } - private bool EqualUpToRenaming(Cluster a, Cluster b) - { + private bool EqualUpToRenaming(Cluster a, Cluster b) { AntiUnificationVisitor /*!*/ visitor = new AntiUnificationVisitor(Gen); visitor.AntiUnify(a.Generator, b.Generator); return visitor.RepresentationIsRenaming(GlobalVariables); } - private Cluster Merge(Cluster a, Cluster b) - { + private Cluster Merge(Cluster a, Cluster b) { AntiUnificationVisitor /*!*/ visitor = new AntiUnificationVisitor(Gen); VCExpr /*!*/ @@ -209,17 +183,14 @@ private Cluster Merge(Cluster a, Cluster b) //////////////////////////////////////////////////////////////////////////// - public void AddExpr(VCExprNAry expr) - { + public void AddExpr(VCExprNAry expr) { Contract.Requires(expr != null); Contract.Requires(Op.Equals(expr.Op)); Cluster c = new Cluster(expr, 1); - for (int i = 0; i < Clusters.Count; ++i) - { + for (int i = 0; i < Clusters.Count; ++i) { Cluster d = Clusters[i]; - if (EqualUpToRenaming(c, d)) - { + if (EqualUpToRenaming(c, d)) { Clusters[i] = new Cluster(d.Generator, d.Size + 1); return; } @@ -230,8 +201,7 @@ public void AddExpr(VCExprNAry expr) //////////////////////////////////////////////////////////////////////////// - private struct ClusteringMatrix - { + private struct ClusteringMatrix { private readonly VCExpressionGenerator /*!*/ Gen; @@ -248,8 +218,7 @@ public readonly bool[] /*!*/ Distances; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(Gen != null); Contract.Invariant(cce.NonNullDictionaryAndValues(GlobalVariables)); Contract.Invariant(Clusters != null); @@ -258,21 +227,19 @@ void ObjectInvariant() } - public struct Distance - { + public struct Distance { public readonly int Dist; public readonly VCExprNAry /*!*/ Generator; public Distance(Cluster a, Cluster b, IDictionary /*!*/ globalVars, - VCExpressionGenerator gen) - { + VCExpressionGenerator gen) { Contract.Requires(gen != null); Contract.Requires(cce.NonNullDictionaryAndValues(globalVars)); AntiUnificationVisitor /*!*/ visitor = new AntiUnificationVisitor(gen); - Generator = (VCExprNAry) visitor.AntiUnify(a.Generator, b.Generator); + Generator = (VCExprNAry)visitor.AntiUnify(a.Generator, b.Generator); visitor.RepresentationSize(globalVars, out var reprSizeA, out var reprSizeB); Dist = (a.Size - 1) * reprSizeA + (b.Size - 1) * reprSizeB; @@ -280,8 +247,7 @@ public Distance(Cluster a, Cluster b, IDictionary clusters, IDictionary /*!*/ globalVars, - VCExpressionGenerator gen) - { + VCExpressionGenerator gen) { Contract.Requires(gen != null); Contract.Requires(clusters != null); Contract.Requires(cce.NonNullDictionaryAndValues(globalVars)); @@ -294,32 +260,26 @@ public ClusteringMatrix(List clusters, IDictionary maxDist) - { + if (minDist > maxDist) { return; } @@ -327,14 +287,11 @@ public void UnifyClusters(int maxDist) } } - public void ResultingClusters(List clusters) - { + public void ResultingClusters(List clusters) { Contract.Requires(clusters != null); clusters.Clear(); - for (int i = 0; i < Clusters.Count; ++i) - { - if (RemainingClusters[i]) - { + for (int i = 0; i < Clusters.Count; ++i) { + if (RemainingClusters[i]) { clusters.Add(Clusters[i]); } } @@ -342,43 +299,32 @@ public void ResultingClusters(List clusters) ////////////////////////////////////////////////////////////////////////// - private void Update(int i) - { - for (int j = 0; j < i; ++j) - { - if (RemainingClusters[j]) - { + private void Update(int i) { + for (int j = 0; j < i; ++j) { + if (RemainingClusters[j]) { Distances[i, j] = new Distance(Clusters[i], Clusters[j], GlobalVariables, Gen); } } - for (int j = i + 1; j < Clusters.Count; ++j) - { - if (RemainingClusters[j]) - { + for (int j = i + 1; j < Clusters.Count; ++j) { + if (RemainingClusters[j]) { Distances[j, i] = new Distance(Clusters[j], Clusters[i], GlobalVariables, Gen); } } } - private int FindMinDistance(out int c0, out int c1) - { + private int FindMinDistance(out int c0, out int c1) { int minDist = int.MaxValue; c0 = -1; c1 = -1; - for (int i = 0; i < Clusters.Count; ++i) - { - if (RemainingClusters[i]) - { - for (int j = 0; j < i; ++j) - { - if (RemainingClusters[j]) - { - if (Distances[i, j].Dist < minDist) - { + for (int i = 0; i < Clusters.Count; ++i) { + if (RemainingClusters[i]) { + for (int j = 0; j < i; ++j) { + if (RemainingClusters[j]) { + if (Distances[i, j].Dist < minDist) { minDist = Distances[i, j].Dist; c0 = i; c1 = j; @@ -392,8 +338,7 @@ private int FindMinDistance(out int c0, out int c1) return minDist; } - private void MergeClusters(int i, int j) - { + private void MergeClusters(int i, int j) { Contract.Requires(j >= 0 && i > j && RemainingClusters[i] && RemainingClusters[j]); Clusters[i] = new Cluster(Distances[i, j].Generator, Clusters[i].Size + Clusters[j].Size); @@ -404,8 +349,7 @@ private void MergeClusters(int i, int j) //////////////////////////////////////////////////////////////////////////// - public void UnifyClusters() - { + public void UnifyClusters() { ClusteringMatrix matrix = new ClusteringMatrix(Clusters, GlobalVariables, Gen); matrix.UnifyClusters(50); @@ -413,13 +357,11 @@ public void UnifyClusters() } [Pure] - public override string ToString() - { + public override string ToString() { Contract.Ensures(Contract.Result() != null); string /*!*/ res = ""; - foreach (Cluster c in Clusters) - { + foreach (Cluster c in Clusters) { res = res + c.Generator + "\t" + c.Size + "\n"; } @@ -429,21 +371,18 @@ public override string ToString() ////////////////////////////////////////////////////////////////////////////// - internal class AntiUnificationVisitor : TraversingVCExprVisitor - { + internal class AntiUnificationVisitor : TraversingVCExprVisitor { private readonly VCExpressionGenerator /*!*/ Gen; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(Gen != null); Contract.Invariant(cce.NonNullDictionaryAndValues(Representation)); } - public AntiUnificationVisitor(VCExpressionGenerator gen) - { + public AntiUnificationVisitor(VCExpressionGenerator gen) { Contract.Requires(gen != null); Gen = gen; } @@ -455,20 +394,17 @@ public AntiUnificationVisitor(VCExpressionGenerator gen) new Dictionary(); - private struct ExprPair - { + private struct ExprPair { public readonly VCExpr /*!*/ Expr0, Expr1; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(Expr0 != null); Contract.Invariant(Expr1 != null); } - public ExprPair(VCExpr expr0, VCExpr expr1) - { + public ExprPair(VCExpr expr0, VCExpr expr1) { Contract.Requires(expr1 != null); Contract.Requires(expr0 != null); Expr0 = expr0; @@ -477,11 +413,9 @@ public ExprPair(VCExpr expr0, VCExpr expr1) [Pure] [Reads(ReadsAttribute.Reads.Nothing)] - public override bool Equals(object that) - { - if (that is ExprPair) - { - ExprPair thatPair = (ExprPair) that; + public override bool Equals(object that) { + if (that is ExprPair) { + ExprPair thatPair = (ExprPair)that; return this.Expr0.Equals(thatPair.Expr0) && this.Expr1.Equals(thatPair.Expr1); } @@ -490,25 +424,21 @@ public override bool Equals(object that) } [Pure] - public override int GetHashCode() - { + public override int GetHashCode() { return Expr0.GetHashCode() + Expr1.GetHashCode() * 13; } } - public void Reset() - { + public void Reset() { Representation.Clear(); } - public bool RepresentationIsRenaming(IDictionary /*!*/ globalVars) - { + public bool RepresentationIsRenaming(IDictionary /*!*/ globalVars) { Contract.Requires(cce.NonNullDictionaryAndValues(globalVars)); if (!Representation.Any(pair => pair.Key.Expr0 is VCExprVar && pair.Key.Expr1 is VCExprVar && - !globalVars.ContainsKey(cce.NonNull((VCExprVar) pair.Key.Expr0)) && - !globalVars.ContainsKey(cce.NonNull((VCExprVar /*!*/) pair.Key.Expr1)))) - { + !globalVars.ContainsKey(cce.NonNull((VCExprVar)pair.Key.Expr0)) && + !globalVars.ContainsKey(cce.NonNull((VCExprVar /*!*/)pair.Key.Expr1)))) { return false; } // check that all substituted variables are distinct @@ -520,16 +450,14 @@ pair.Key.Expr0 is VCExprVar && pair.Key.Expr1 is VCExprVar && } public void RepresentationSize(IDictionary /*!*/ globalVars, out int expr0Size, - out int expr1Size) - { + out int expr1Size) { Contract.Requires(cce.NonNullDictionaryAndValues(globalVars)); ReprSizeComputingVisitor /*!*/ size0Visitor = new ReprSizeComputingVisitor(); ReprSizeComputingVisitor /*!*/ size1Visitor = new ReprSizeComputingVisitor(); - foreach (KeyValuePair pair in Representation) - { + foreach (KeyValuePair pair in Representation) { Contract.Assert(pair.Value != null); size0Visitor.ComputeSize(pair.Key.Expr0, globalVars); size1Visitor.ComputeSize(pair.Key.Expr1, globalVars); @@ -539,27 +467,24 @@ public void RepresentationSize(IDictionary /*! expr1Size = size1Visitor.Size; } - public VCExpr AntiUnify(VCExpr s, VCExpr t) - { + public VCExpr AntiUnify(VCExpr s, VCExpr t) { Contract.Requires(t != null); Contract.Requires(s != null); Contract.Requires((s.Type.Equals(t.Type))); Contract.Ensures(Contract.Result() != null); - return Traverse(s, t); + return Traverse(s, t).Result; } //////////////////////////////////////////////////////////////////////////// - private VCExprVar AbstractWithVariable(VCExpr s, VCExpr t) - { + private VCExprVar AbstractWithVariable(VCExpr s, VCExpr t) { Contract.Requires(t != null); Contract.Requires(s != null); Contract.Requires((s.Type.Equals(t.Type))); Contract.Ensures(Contract.Result() != null); ExprPair pair = new ExprPair(s, t); - if (!Representation.TryGetValue(pair, out var repr)) - { + if (!Representation.TryGetValue(pair, out var repr)) { repr = Gen.Variable("abs" + Representation.Count, s.Type); Representation.Add(pair, repr); } @@ -569,36 +494,31 @@ private VCExprVar AbstractWithVariable(VCExpr s, VCExpr t) //////////////////////////////////////////////////////////////////////////// - public override VCExpr Visit(VCExprLiteral node, VCExpr that) - { + public override VCExpr Visit(VCExprLiteral node, VCExpr that) { Contract.Requires(that != null); Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); - if (node.Equals(that)) - { + if (node.Equals(that)) { return node; } return AbstractWithVariable(node, that); } - public override VCExpr Visit(VCExprNAry node, VCExpr that) - { + public override async DynamicStack Visit(VCExprNAry node, VCExpr that) { Contract.Requires(that != null); Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); VCExprNAry thatNAry = that as VCExprNAry; - if (thatNAry != null && node.Op.Equals(thatNAry.Op)) - { + if (thatNAry != null && node.Op.Equals(thatNAry.Op)) { // type parameters should already have been eliminated at this // stage Contract.Assert(node.TypeParamArity == 0 && thatNAry.TypeParamArity == 0 && node.Arity == thatNAry.Arity); List /*!*/ unifiedArgs = new List(); - for (int i = 0; i < node.Arity; ++i) - { - unifiedArgs.Add(Traverse(node[i], thatNAry[i])); + for (int i = 0; i < node.Arity; ++i) { + unifiedArgs.Add(await Traverse(node[i], thatNAry[i])); } return Gen.Function(node.Op, unifiedArgs); @@ -607,21 +527,18 @@ public override VCExpr Visit(VCExprNAry node, VCExpr that) return AbstractWithVariable(node, that); } - public override VCExpr Visit(VCExprVar node, VCExpr that) - { + public override VCExpr Visit(VCExprVar node, VCExpr that) { Contract.Requires(that != null); Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); - if (node.Equals(that)) - { + if (node.Equals(that)) { return node; } return AbstractWithVariable(node, that); } - protected override VCExpr StandardResult(VCExpr node, VCExpr that) - { + protected override VCExpr StandardResult(VCExpr node, VCExpr that) { //Contract.Requires(that != null); //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); @@ -635,24 +552,20 @@ protected override VCExpr StandardResult(VCExpr node, VCExpr that) internal class ReprSizeComputingVisitor : TraversingVCExprVisitor /*!*/> - { + IDictionary /*!*/> { public int Size = 0; - public void ComputeSize(VCExpr expr, IDictionary /*!*/ globalVars) - { + public void ComputeSize(VCExpr expr, IDictionary /*!*/ globalVars) { Contract.Requires(expr != null); Contract.Requires(cce.NonNullDictionaryAndValues(globalVars)); Traverse(expr, globalVars); } - protected override bool StandardResult(VCExpr node, IDictionary /*!*/ globalVars) - { + protected override bool StandardResult(VCExpr node, IDictionary /*!*/ globalVars) { //Contract.Requires(node != null); //Contract.Requires(cce.NonNullElements(globalVars)); VCExprVar nodeAsVar = node as VCExprVar; - if (nodeAsVar == null || globalVars.ContainsKey(nodeAsVar)) - { + if (nodeAsVar == null || globalVars.ContainsKey(nodeAsVar)) { Size = Size + 1; } diff --git a/Source/VCExpr/KeepOriginalNamer.cs b/Source/VCExpr/KeepOriginalNamer.cs index 821f38b54..15054cac8 100644 --- a/Source/VCExpr/KeepOriginalNamer.cs +++ b/Source/VCExpr/KeepOriginalNamer.cs @@ -1,31 +1,25 @@ using System; using System.Diagnostics.Contracts; -namespace Microsoft.Boogie.VCExprAST -{ - public class KeepOriginalNamer : ScopedNamer - { +namespace Microsoft.Boogie.VCExprAST { + public class KeepOriginalNamer : ScopedNamer { - public KeepOriginalNamer() - { + public KeepOriginalNamer() { } - public KeepOriginalNamer(ScopedNamer namer) : base(namer) - { + public KeepOriginalNamer(ScopedNamer namer) : base(namer) { } public static KeepOriginalNamer Create(ScopedNamer namer = null) { return namer != null ? new KeepOriginalNamer(namer) : new KeepOriginalNamer(); } - - public override UniqueNamer Clone() - { + + public override UniqueNamer Clone() { Contract.Ensures(Contract.Result() != null); return new KeepOriginalNamer(this); } - protected override string GetModifiedName(string uniqueInherentName) - { + protected override string GetModifiedName(string uniqueInherentName) { return uniqueInherentName; } } diff --git a/Source/VCExpr/LetBindingSorter.cs b/Source/VCExpr/LetBindingSorter.cs index c4824020f..866ffe611 100644 --- a/Source/VCExpr/LetBindingSorter.cs +++ b/Source/VCExpr/LetBindingSorter.cs @@ -5,14 +5,11 @@ // Sort the bindings in a let-expression so that terms bound earlier do // not contain variables bound later -namespace Microsoft.Boogie.VCExprAST -{ +namespace Microsoft.Boogie.VCExprAST { // (argument is not used) - public class LetBindingSorter : MutatingVCExprVisitor - { + public class LetBindingSorter : MutatingVCExprVisitor { [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(FreeVarCollector != null); } @@ -20,8 +17,7 @@ private readonly FreeVariableCollector /*!*/ FreeVarCollector = new FreeVariableCollector(); - private List /*!*/ FreeVarsIn(VCExpr expr) - { + private List /*!*/ FreeVarsIn(VCExpr expr) { Contract.Requires(expr != null); Contract.Ensures(cce.NonNullElements(Contract.Result>())); FreeVarCollector.Collect(expr); @@ -31,21 +27,18 @@ private readonly FreeVariableCollector /*!*/ return freeVars; } - public LetBindingSorter(VCExpressionGenerator gen) : base(gen) - { + public LetBindingSorter(VCExpressionGenerator gen) : base(gen) { Contract.Requires(gen != null); } - public override VCExpr Visit(VCExprLet node, bool arg) - { + public override DynamicStack Visit(VCExprLet node, bool arg) { Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); IDictionary boundVars = new Dictionary(); // recurse and collect the free variables in bound terms and formulae - foreach (VCExprLetBinding /*!*/ binding in node) - { + foreach (VCExprLetBinding /*!*/ binding in node) { Contract.Assert(binding != null); VCExpr /*!*/ newE = Mutate(binding.E, arg); @@ -55,17 +48,14 @@ public override VCExpr Visit(VCExprLet node, bool arg) } // generate the occurrence edges - foreach (KeyValuePair pair in boundVars) - { + foreach (KeyValuePair pair in boundVars) { Contract.Assert(cce.NonNullElements(pair)); Binding /*!*/ b = pair.Value; Contract.Assert(b != null); - foreach (VCExprVar /*!*/ v in b.FreeVars) - { + foreach (VCExprVar /*!*/ v in b.FreeVars) { Contract.Assert(v != null); - if (boundVars.TryGetValue(v, out var b2)) - { + if (boundVars.TryGetValue(v, out var b2)) { cce.NonNull(b2).Occurrences.Add(b); b.InvOccurrencesNum = b.InvOccurrencesNum + 1; } @@ -74,36 +64,30 @@ public override VCExpr Visit(VCExprLet node, bool arg) // topological sort Stack rootBindings = new Stack(); - foreach (KeyValuePair pair in boundVars) - { + foreach (KeyValuePair pair in boundVars) { Contract.Assert(cce.NonNullElements(pair)); - if (pair.Value.InvOccurrencesNum == 0) - { + if (pair.Value.InvOccurrencesNum == 0) { rootBindings.Push(pair.Value); } } List /*!*/ sortedBindings = new List(); - while (rootBindings.Count > 0) - { + while (rootBindings.Count > 0) { Binding /*!*/ b = rootBindings.Pop(); Contract.Assert(b != null); sortedBindings.Add(b); - foreach (Binding /*!*/ b2 in b.Occurrences) - { + foreach (Binding /*!*/ b2 in b.Occurrences) { Contract.Assert(b2 != null); b2.InvOccurrencesNum = b2.InvOccurrencesNum - 1; - if (b2.InvOccurrencesNum == 0) - { + if (b2.InvOccurrencesNum == 0) { rootBindings.Push(b2); } } } - if (boundVars.Any(pair => pair.Value.InvOccurrencesNum > 0)) - { + if (boundVars.Any(pair => pair.Value.InvOccurrencesNum > 0)) { System.Diagnostics.Debug.Fail("Cyclic let-bindings"); } @@ -116,30 +100,22 @@ public override VCExpr Visit(VCExprLet node, bool arg) IDictionary /*!*/ usedVars = new Dictionary(); - foreach (VCExprVar /*!*/ v in FreeVarsIn(newBody)) - { + foreach (VCExprVar /*!*/ v in FreeVarsIn(newBody)) { Contract.Assert(v != null); - if (!usedVars.ContainsKey(v)) - { + if (!usedVars.ContainsKey(v)) { usedVars.Add(v, v); } } - for (int i = sortedBindings.Count - 1; i >= 0; --i) - { - if (usedVars.ContainsKey(sortedBindings[i].V)) - { - foreach (VCExprVar /*!*/ v in sortedBindings[i].FreeVars) - { + for (int i = sortedBindings.Count - 1; i >= 0; --i) { + if (usedVars.ContainsKey(sortedBindings[i].V)) { + foreach (VCExprVar /*!*/ v in sortedBindings[i].FreeVars) { Contract.Assert(v != null); - if (!usedVars.ContainsKey(v)) - { + if (!usedVars.ContainsKey(v)) { usedVars.Add(v, v); } } - } - else - { + } else { sortedBindings.RemoveAt(i); } } @@ -147,16 +123,14 @@ public override VCExpr Visit(VCExprLet node, bool arg) // assemble the resulting let-expression List /*!*/ newBindings = new List(); - foreach (Binding b in sortedBindings) - { + foreach (Binding b in sortedBindings) { newBindings.Add(Gen.LetBinding(b.V, b.E)); } - return Gen.Let(newBindings, newBody); + return DynamicStack.FromResult(Gen.Let(newBindings, newBody)); } - private class Binding - { + private class Binding { public readonly VCExprVar /*!*/ V; @@ -167,8 +141,7 @@ public readonly List /*!*/ FreeVars; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(V != null); Contract.Invariant(E != null); Contract.Invariant(cce.NonNullElements(FreeVars)); @@ -186,8 +159,7 @@ public readonly List /*!*/ // (incoming edges) public int InvOccurrencesNum; - public Binding(VCExprVar v, VCExpr e, List /*!*/ freeVars) - { + public Binding(VCExprVar v, VCExpr e, List /*!*/ freeVars) { Contract.Requires(e != null); Contract.Requires(v != null); Contract.Requires(cce.NonNullElements(freeVars)); diff --git a/Source/VCExpr/MutatingVCExprVisitor.cs b/Source/VCExpr/MutatingVCExprVisitor.cs index 38ab0f7c9..cb5cfc69f 100644 --- a/Source/VCExpr/MutatingVCExprVisitor.cs +++ b/Source/VCExpr/MutatingVCExprVisitor.cs @@ -4,76 +4,62 @@ namespace Microsoft.Boogie.VCExprAST; -public abstract class MutatingVCExprVisitor - : IVCExprVisitor -{ +public abstract class MutatingVCExprVisitor : IVCExprVisitor { protected readonly VCExpressionGenerator /*!*/ Gen; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(Gen != null); } - - public MutatingVCExprVisitor(VCExpressionGenerator gen) - { + + public MutatingVCExprVisitor(VCExpressionGenerator gen) { Contract.Requires(gen != null); this.Gen = gen; } - public VCExpr Mutate(VCExpr expr, Arg arg) - { + public VCExpr Mutate(VCExpr expr, Arg arg) { Contract.Requires(expr != null); Contract.Ensures(Contract.Result() != null); - return expr.Accept(this, arg); + return expr.Accept(this, arg).Result; } - public List /*!*/ MutateSeq(IEnumerable /*!*/ exprs, Arg arg) - { + public async DynamicStack> /*!*/ MutateSeq(IEnumerable /*!*/ exprs, Arg arg) { Contract.Requires(cce.NonNullElements(exprs)); Contract.Ensures(cce.NonNullElements(Contract.Result>())); - List /*!*/ - res = new List(); - foreach (VCExpr /*!*/ expr in exprs) - { + List /*!*/ res = new List(); + foreach (VCExpr /*!*/ expr in exprs) { Contract.Assert(expr != null); - res.Add(expr.Accept(this, arg)); + res.Add(await expr.Accept(this, arg)); } return res; } - private List /*!*/ MutateList(List /*!*/ exprs, Arg arg) - { + private async DynamicStack> /*!*/ MutateList(List /*!*/ exprs, Arg arg) { Contract.Requires(cce.NonNullElements(exprs)); Contract.Ensures(cce.NonNullElements(Contract.Result>())); bool changed = false; List /*!*/ res = new List(); - foreach (VCExpr /*!*/ expr in exprs) - { + foreach (VCExpr /*!*/ expr in exprs) { Contract.Assert(expr != null); - VCExpr /*!*/ - newExpr = expr.Accept(this, arg); - if (!Object.ReferenceEquals(expr, newExpr)) - { + var /*!*/ newExpr = await expr.Accept(this, arg); + if (!ReferenceEquals(expr, newExpr)) { changed = true; } res.Add(newExpr); } - if (!changed) - { + if (!changed) { return exprs; } return res; } - public virtual VCExpr Visit(VCExprLiteral node, Arg arg) - { + public virtual VCExpr Visit(VCExprLiteral node, Arg arg) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); return node; @@ -81,194 +67,81 @@ public virtual VCExpr Visit(VCExprLiteral node, Arg arg) //////////////////////////////////////////////////////////////////////////// - // Special element used to mark the positions in the todo-stack where - // results have to be popped from the result-stack. - private static readonly VCExpr /*!*/ - CombineResultsMarker = new VCExprLiteral(Type.Bool); - - // The todo-stack contains records of the shape - // - // arg0 - // arg1 - // arg2 - // ... - // CombineResultsMarker - // f(arg0, arg1, arg2, ...) (the original expression) - - private readonly Stack /*!*/ - NAryExprTodoStack = new Stack(); - - private readonly Stack /*!*/ - NAryExprResultStack = new Stack(); - - [ContractInvariantMethod] - void ObjectInvarianta() - { - Contract.Invariant(cce.NonNullElements(NAryExprResultStack)); - Contract.Invariant(cce.NonNullElements(NAryExprTodoStack)); - } - - - private void PushTodo(VCExprNAry exprTodo) - { - Contract.Requires(exprTodo != null); - NAryExprTodoStack.Push(exprTodo); - NAryExprTodoStack.Push(CombineResultsMarker); - for (int i = exprTodo.Arity - 1; i >= 0; --i) - { - NAryExprTodoStack.Push(exprTodo[i]); - } - } - - public virtual bool AvoidVisit(VCExprNAry node, Arg arg) - { - return true; - } - - public virtual VCExpr Visit(VCExprNAry node, Arg arg) - { + public virtual async DynamicStack Visit(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); - int initialStackSize = NAryExprTodoStack.Count; - int initialResultStackSize = NAryExprResultStack.Count; - - PushTodo(node); - - while (NAryExprTodoStack.Count > initialStackSize) - { - VCExpr /*!*/ - subExpr = NAryExprTodoStack.Pop(); - Contract.Assert(subExpr != null); - - if (Object.ReferenceEquals(subExpr, CombineResultsMarker)) - { - // assemble a result - VCExprNAry /*!*/ - originalExpr = (VCExprNAry) NAryExprTodoStack.Pop(); - Contract.Assert(originalExpr != null); - VCExprOp /*!*/ - op = originalExpr.Op; - bool changed = false; - List /*!*/ - newSubExprs = new List(); - - for (int i = op.Arity - 1; i >= 0; --i) - { - VCExpr /*!*/ - nextSubExpr = NAryExprResultStack.Pop(); - Contract.Assert(nextSubExpr != null); - if (!Object.ReferenceEquals(nextSubExpr, originalExpr[i])) - { - changed = true; - } - - newSubExprs.Insert(0, nextSubExpr); - } - - NAryExprResultStack.Push(UpdateModifiedNode(originalExpr, newSubExprs, changed, arg)); - // - } - else - { - // - VCExprNAry narySubExpr = subExpr as VCExprNAry; - if (narySubExpr != null && this.AvoidVisit(narySubExpr, arg) && - // as in VCExprNAryUniformOpEnumerator, all expressions with - // type parameters are allowed to be inspected more closely - narySubExpr.TypeParamArity == 0) - { - PushTodo(narySubExpr); - } - else - { - NAryExprResultStack.Push(subExpr.Accept(this, arg)); - } - - // + + bool changed = false; + var children = new List(); + for (int i = node.Arity - 1; i >= 0; --i) { + var child = await node[i].Accept(this, arg); + if (!Object.ReferenceEquals(child, node[i])) { + changed = true; } + children.Insert(0, child); } - Contract.Assert(NAryExprTodoStack.Count == initialStackSize && - NAryExprResultStack.Count == initialResultStackSize + 1); - return NAryExprResultStack.Pop(); + return UpdateModifiedNode(node, children, changed, arg); } protected virtual VCExpr /*!*/ UpdateModifiedNode(VCExprNAry /*!*/ originalNode, List /*!*/ newSubExprs, // has any of the subexpressions changed? bool changed, - Arg arg) - { + Arg arg) { Contract.Requires(cce.NonNullElements(newSubExprs)); Contract.Ensures(Contract.Result() != null); - if (changed) - { + if (changed) { return Gen.Function(originalNode.Op, newSubExprs, originalNode.TypeArguments); - } - else - { + } else { return originalNode; } } //////////////////////////////////////////////////////////////////////////// - public virtual VCExpr Visit(VCExprVar node, Arg arg) - { + public virtual VCExpr Visit(VCExprVar node, Arg arg) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); return node; } - protected List /*!*/ MutateTriggers(List /*!*/ triggers, Arg arg) - { + protected async DynamicStack> /*!*/ MutateTriggers(List /*!*/ triggers, Arg arg) { Contract.Requires(cce.NonNullElements(triggers)); Contract.Ensures(cce.NonNullElements(Contract.Result>())); - List /*!*/ - newTriggers = new List(); + List /*!*/ newTriggers = new List(); bool changed = false; - foreach (VCTrigger /*!*/ trigger in triggers) - { + foreach (VCTrigger /*!*/ trigger in triggers) { Contract.Assert(trigger != null); - List /*!*/ - exprs = trigger.Exprs; - List /*!*/ - newExprs = MutateList(exprs, arg); + List /*!*/ exprs = trigger.Exprs; + List /*!*/ newExprs = await MutateList(exprs, arg); - if (Object.ReferenceEquals(exprs, newExprs)) - { + if (Object.ReferenceEquals(exprs, newExprs)) { newTriggers.Add(trigger); - } - else - { + } else { newTriggers.Add(Gen.Trigger(trigger.Pos, newExprs)); changed = true; } } - if (!changed) - { + if (!changed) { return triggers; } return newTriggers; } - public virtual VCExpr Visit(VCExprQuantifier node, Arg arg) - { + public virtual async DynamicStack Visit(VCExprQuantifier node, Arg arg) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); bool changed = false; - VCExpr /*!*/ - body = node.Body; + VCExpr /*!*/ body = node.Body; Contract.Assert(body != null); - VCExpr /*!*/ - newbody = body.Accept(this, arg); + VCExpr /*!*/ newbody = await body.Accept(this, arg); Contract.Assert(newbody != null); - if (!Object.ReferenceEquals(body, newbody)) - { + if (!ReferenceEquals(body, newbody)) { changed = true; } @@ -276,16 +149,13 @@ public virtual VCExpr Visit(VCExprQuantifier node, Arg arg) List /*!*/ triggers = node.Triggers; Contract.Assert(cce.NonNullElements(triggers)); - List /*!*/ - newTriggers = MutateTriggers(triggers, arg); + List /*!*/ newTriggers = await MutateTriggers(triggers, arg); Contract.Assert(cce.NonNullElements(newTriggers)); - if (!Object.ReferenceEquals(triggers, newTriggers)) - { + if (!ReferenceEquals(triggers, newTriggers)) { changed = true; } - if (!changed) - { + if (!changed) { return node; } @@ -293,45 +163,32 @@ public virtual VCExpr Visit(VCExprQuantifier node, Arg arg) newTriggers, node.Info, newbody); } - public virtual VCExpr Visit(VCExprLet node, Arg arg) - { + public virtual async DynamicStack Visit(VCExprLet node, Arg arg) { //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); bool changed = false; - VCExpr /*!*/ - body = node.Body; - VCExpr /*!*/ - newbody = body.Accept(this, arg); - if (!Object.ReferenceEquals(body, newbody)) - { + VCExpr /*!*/ body = node.Body; + VCExpr /*!*/ newbody = await body.Accept(this, arg); + if (!ReferenceEquals(body, newbody)) { changed = true; } - List /*!*/ - newbindings = new List(); - for (int i = 0; i < node.Length; ++i) - { - VCExprLetBinding /*!*/ - binding = node[i]; + List /*!*/ newbindings = new List(); + for (int i = 0; i < node.Length; ++i) { + VCExprLetBinding /*!*/ binding = node[i]; Contract.Assert(binding != null); - VCExpr /*!*/ - e = binding.E; - VCExpr /*!*/ - newE = e.Accept(this, arg); - if (Object.ReferenceEquals(e, newE)) - { + VCExpr /*!*/ e = binding.E; + var /*!*/ newE = await e.Accept(this, arg); + if (ReferenceEquals(e, newE)) { newbindings.Add(binding); - } - else - { + } else { changed = true; newbindings.Add(Gen.LetBinding(binding.V, newE)); } } - if (!changed) - { + if (!changed) { return node; } diff --git a/Source/VCExpr/NormalizeNamer.cs b/Source/VCExpr/NormalizeNamer.cs index b371210ba..9d5a0c73b 100644 --- a/Source/VCExpr/NormalizeNamer.cs +++ b/Source/VCExpr/NormalizeNamer.cs @@ -6,21 +6,18 @@ public NormalizeNamer() : base() { } - public NormalizeNamer(ScopedNamer namer) : base(namer) - { + public NormalizeNamer(ScopedNamer namer) : base(namer) { } public static NormalizeNamer Create(ScopedNamer namer = null) { return namer != null ? new NormalizeNamer(namer) : new NormalizeNamer(); } - protected override string GetModifiedName(string uniqueInherentName) - { + protected override string GetModifiedName(string uniqueInherentName) { return "$generated"; } - public override UniqueNamer Clone() - { + public override UniqueNamer Clone() { return new NormalizeNamer(this); } } diff --git a/Source/VCExpr/OpTypeEraserPremisses.cs b/Source/VCExpr/OpTypeEraserPremisses.cs index 4fcd187af..37db28650 100644 --- a/Source/VCExpr/OpTypeEraserPremisses.cs +++ b/Source/VCExpr/OpTypeEraserPremisses.cs @@ -4,22 +4,19 @@ namespace Microsoft.Boogie.TypeErasure; -public class OpTypeEraserPremisses : OpTypeEraser -{ +public class OpTypeEraserPremisses : OpTypeEraser { private TypeAxiomBuilderPremisses /*!*/ AxBuilderPremisses; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(AxBuilderPremisses != null); } public OpTypeEraserPremisses(TypeEraserPremisses eraser, TypeAxiomBuilderPremisses axBuilder, VCExpressionGenerator gen) - : base(eraser, axBuilder, gen) - { + : base(eraser, axBuilder, gen) { Contract.Requires(gen != null); Contract.Requires(axBuilder != null); Contract.Requires(eraser != null); @@ -27,8 +24,7 @@ public OpTypeEraserPremisses(TypeEraserPremisses eraser, TypeAxiomBuilderPremiss } private VCExpr HandleFunctionOp(Function newFun, List /*!*/ typeArgs /*!*/, - IEnumerable /*!*/ oldArgs, VariableBindings bindings) - { + IEnumerable /*!*/ oldArgs, VariableBindings bindings) { Contract.Requires(bindings != null); Contract.Requires(newFun != null); Contract.Requires(cce.NonNullElements(typeArgs /*!*/)); @@ -42,15 +38,13 @@ private VCExpr HandleFunctionOp(Function newFun, List /*!*/ typeArgs newArgs = new List(typeArgs.Count); // translate the explicit type arguments - foreach (Type /*!*/ t in typeArgs) - { + foreach (Type /*!*/ t in typeArgs) { Contract.Assert(t != null); newArgs.Add(AxBuilder.Type2Term(t, bindings.TypeVariableBindings)); } // recursively translate the value arguments - foreach (VCExpr /*!*/ arg in oldArgs) - { + foreach (VCExpr /*!*/ arg in oldArgs) { Contract.Assert(arg != null); Type /*!*/ newType = cce.NonNull(newFun.InParams[newArgs.Count]).TypedIdent.Type; @@ -61,9 +55,8 @@ private VCExpr HandleFunctionOp(Function newFun, List /*!*/ typeArgs return Gen.Function(newFun, newArgs); } - public override VCExpr /*!*/ VisitSelectOp(VCExprNAry /*!*/ node, - VariableBindings /*!*/ bindings) - { + public override DynamicStack /*!*/ VisitSelectOp(VCExprNAry node, /*!*/ + VariableBindings bindings /*!*/) { Contract.Requires(node != null); Contract.Requires(bindings != null); Contract.Ensures(Contract.Result() != null); @@ -84,16 +77,14 @@ private VCExpr HandleFunctionOp(Function newFun, List /*!*/ typeArgs List /*!*/ typeArgs = new List(explicitTypeParams.Count); - foreach (int i in explicitTypeParams) - { + foreach (int i in explicitTypeParams) { typeArgs.Add(node.TypeArguments[i]); } - return HandleFunctionOp(select, typeArgs, node.Arguments, bindings); + return DynamicStack.FromResult(HandleFunctionOp(select, typeArgs, node.Arguments, bindings)); } - public override VCExpr VisitStoreOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitStoreOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires(bindings != null); Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); @@ -101,43 +92,37 @@ public override VCExpr VisitStoreOp(VCExprNAry node, VariableBindings bindings) store = AxBuilder.MapTypeAbstracter.Store(node[0].Type.AsMap, out var instantiations); Contract.Assert(store != null); - return HandleFunctionOp(store, + return DynamicStack.FromResult(HandleFunctionOp(store, // the store function never has explicit // type parameters new List(), - node.Arguments, bindings); + node.Arguments, bindings)); } - public override VCExpr VisitBoogieFunctionOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitBoogieFunctionOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires(bindings != null); Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); Function /*!*/ - oriFun = ((VCExprBoogieFunctionOp) node.Op).Func; + oriFun = ((VCExprBoogieFunctionOp)node.Op).Func; Contract.Assert(oriFun != null); UntypedFunction untypedFun = AxBuilderPremisses.Typed2Untyped(oriFun); Contract.Assert(untypedFun.Fun.InParams.Count == untypedFun.ExplicitTypeParams.Count + node.Arity); - List /*!*/ - typeArgs = - ExtractTypeArgs(node, - oriFun.TypeParameters, untypedFun.ExplicitTypeParams); - return HandleFunctionOp(untypedFun.Fun, typeArgs, node.Arguments, bindings); + List /*!*/ typeArgs = ExtractTypeArgs(node, oriFun.TypeParameters, untypedFun.ExplicitTypeParams); + return DynamicStack.FromResult(HandleFunctionOp(untypedFun.Fun, typeArgs, node.Arguments, bindings)); } private List /*!*/ ExtractTypeArgs(VCExprNAry node, List allTypeParams, - List /*!*/ explicitTypeParams) - { + List /*!*/ explicitTypeParams) { Contract.Requires(allTypeParams != null); Contract.Requires(node != null); Contract.Requires(cce.NonNullElements(explicitTypeParams)); Contract.Ensures(cce.NonNullElements(Contract.Result>())); List /*!*/ res = new List(explicitTypeParams.Count); - foreach (TypeVariable /*!*/ var in explicitTypeParams) - { + foreach (TypeVariable /*!*/ var in explicitTypeParams) { Contract.Assert(var != null); // this lookup could be optimised res.Add(node.TypeArguments[allTypeParams.IndexOf(var)]); diff --git a/Source/VCExpr/QuantifierInstantiationEngine.cs b/Source/VCExpr/QuantifierInstantiationEngine.cs index 04bee25d9..5d94e1966 100644 --- a/Source/VCExpr/QuantifierInstantiationEngine.cs +++ b/Source/VCExpr/QuantifierInstantiationEngine.cs @@ -3,11 +3,10 @@ using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; +using System.Threading.Tasks; -namespace Microsoft.Boogie.VCExprAST -{ - public class QuantifierInstantiationEngine - { +namespace Microsoft.Boogie.VCExprAST { + public class QuantifierInstantiationEngine { /* * The algorithm implemented by QuantifierInstantiationEngine is a fixpoint. There are three phases. * @@ -27,18 +26,16 @@ public class QuantifierInstantiationEngine * - Add instances of the axioms for lambdas as assume statements in the starting block of impl. */ - private class QuantifierInstantiationInfo - { + private class QuantifierInstantiationInfo { public HashSet relevantLabels; public Dictionary, VCExpr> instances; - public QuantifierInstantiationInfo(Dictionary> boundVariableToLabels) - { + public QuantifierInstantiationInfo(Dictionary> boundVariableToLabels) { this.relevantLabels = boundVariableToLabels.Values.SelectMany(x => x).ToHashSet(); this.instances = new Dictionary, VCExpr>(new ListComparer()); } } - + private Dictionary quantifierBinding; private Dictionary lambdaDefinition; private Dictionary quantifierInstantiationInfo; @@ -53,18 +50,15 @@ public QuantifierInstantiationInfo(Dictionary> boundV private Boogie2VCExprTranslator exprTranslator; internal static ConcurrentDictionary> labelToTypes = new(); // pool name may map to multiple types - public static VCExpr Instantiate(Implementation impl, VCExpressionGenerator vcExprGen, Boogie2VCExprTranslator exprTranslator, VCExpr vcExpr) - { - if (!InstantiationSourceChecker.HasInstantiationSources(impl)) - { + public static VCExpr Instantiate(Implementation impl, VCExpressionGenerator vcExprGen, Boogie2VCExprTranslator exprTranslator, VCExpr vcExpr) { + if (!InstantiationSourceChecker.HasInstantiationSources(impl)) { return vcExpr; } var qiEngine = new QuantifierInstantiationEngine(vcExprGen, exprTranslator); return qiEngine.Execute(impl, vcExpr); } - private QuantifierInstantiationEngine(VCExpressionGenerator vcExprGen, Boogie2VCExprTranslator exprTranslator) - { + private QuantifierInstantiationEngine(VCExpressionGenerator vcExprGen, Boogie2VCExprTranslator exprTranslator) { this.quantifierBinding = new Dictionary(); this.lambdaDefinition = new Dictionary(); this.quantifierInstantiationInfo = new Dictionary(); @@ -78,31 +72,22 @@ private QuantifierInstantiationEngine(VCExpressionGenerator vcExprGen, Boogie2VC this.vcExprGen = vcExprGen; this.exprTranslator = exprTranslator; } - - public static void SubstituteIncarnationInInstantiationSources(Cmd cmd, Substitution incarnationSubst) - { + + public static void SubstituteIncarnationInInstantiationSources(Cmd cmd, Substitution incarnationSubst) { QKeyValue iter = null; - if (cmd is AssignCmd assignCmd) - { + if (cmd is AssignCmd assignCmd) { iter = assignCmd.Attributes; - } - else if (cmd is PredicateCmd predicateCmd) - { + } else if (cmd is PredicateCmd predicateCmd) { iter = predicateCmd.Attributes; } - while (iter != null) - { - if (iter.Key == "add_to_pool" && iter.Params.Count > 1) - { + while (iter != null) { + if (iter.Key == "add_to_pool" && iter.Params.Count > 1) { var label = iter.Params[0] as string; - if (label != null) - { - var newParams = new List {label}; - for (int i = 1; i < iter.Params.Count; i++) - { + if (label != null) { + var newParams = new List { label }; + for (int i = 1; i < iter.Params.Count; i++) { var instance = iter.Params[i] as Expr; - if (instance != null) - { + if (instance != null) { instance = Substituter.Apply(incarnationSubst, instance); newParams.Add(instance); } @@ -115,16 +100,13 @@ public static void SubstituteIncarnationInInstantiationSources(Cmd cmd, Substitu } } - public VCExpr BindQuantifier(VCExprQuantifier node) - { - if (node.TypeParameters.Count > 0) - { + public VCExpr BindQuantifier(VCExprQuantifier node) { + if (node.TypeParameters.Count > 0) { return node; } var boundVariableToLabels = node.Info.instantiationLabels; if (boundVariableToLabels.Count < node.BoundVars.Count || - boundVariableToLabels.Any(kv => kv.Value.Count == 0)) - { + boundVariableToLabels.Any(kv => kv.Value.Count == 0)) { return node; } var v = new VCExprVar($"{quantifierBindingNamePrefix}{quantifierBinding.Count}", Type.Bool); @@ -133,36 +115,29 @@ public VCExpr BindQuantifier(VCExprQuantifier node) return v; } - public void AddTerm(string label, VCExpr term) - { - if (!labelToInstances.ContainsKey(label)) - { + public void AddTerm(string label, VCExpr term) { + if (!labelToInstances.ContainsKey(label)) { labelToInstances[label] = new HashSet(); } labelToInstances[label].Add(term); } - public bool IsQuantifierBinding(VCExprVar vcExprVar) - { + public bool IsQuantifierBinding(VCExprVar vcExprVar) { return this.quantifierBinding.ContainsKey(vcExprVar); } - public VCExprVar FreshSkolemConstant(VCExprVar variable) - { + public VCExprVar FreshSkolemConstant(VCExprVar variable) { var skolemConstant = new VCExprVar($"{skolemConstantNamePrefix}{skolemConstants.Count}", variable.Type); skolemConstants.Add(skolemConstant); return skolemConstant; } - public bool BindLambdaFunction(Function lambdaFunction) - { - if (lambdaDefinition.ContainsKey(lambdaFunction)) - { + public bool BindLambdaFunction(Function lambdaFunction) { + if (lambdaDefinition.ContainsKey(lambdaFunction)) { return true; } var lambdaDefinitionExpr = lambdaFunction.DefinitionAxiom.Expr as QuantifierExpr; - if (lambdaDefinitionExpr.TypeParameters.Count > 0) - { + if (lambdaDefinitionExpr.TypeParameters.Count > 0) { return false; } var translatedExpr = exprTranslator.Translate(lambdaDefinitionExpr) as VCExprQuantifier; @@ -170,8 +145,7 @@ public bool BindLambdaFunction(Function lambdaFunction) var numParametersInLambdaDefinition = lambdaDefinitionExpr.Dummies.Count - lambdaFunction.InParams.Count; if (boundVariableToLabels.Count < numParametersInLambdaDefinition || Enumerable.Range(lambdaFunction.InParams.Count, numParametersInLambdaDefinition) - .Any(i => boundVariableToLabels[translatedExpr.BoundVars[i]].Count == 0)) - { + .Any(i => boundVariableToLabels[translatedExpr.BoundVars[i]].Count == 0)) { return false; } lambdaDefinition[lambdaFunction] = translatedExpr; @@ -225,15 +199,11 @@ public static Dictionary> FindInstantiationSources(ICarr if (iter.Key == "add_to_pool" && iter.Params.Count > 1) { var label = iter.Params[0] as string; - if (label != null) - { - for (int i = 1; i < iter.Params.Count; i++) - { + if (label != null) { + for (int i = 1; i < iter.Params.Count; i++) { var instance = iter.Params[i] as Expr; - if (instance != null) - { - if (!freshInstances.ContainsKey(label)) - { + if (instance != null) { + if (!freshInstances.ContainsKey(label)) { freshInstances[label] = new HashSet(); } freshInstances[label].Add(exprTranslator.Translate(instance)); @@ -277,8 +247,7 @@ private VCExpr Execute(Implementation impl, VCExpr vcExpr) AddDictionary(FindInstantiationSources(predicateCmd, exprTranslator), labelToInstances); })); vcExpr = Skolemizer.Skolemize(this, Polarity.Negative, vcExpr); - while (labelToInstances.Count > 0 || lambdaToInstances.Count > 0) - { + while (labelToInstances.Count > 0 || lambdaToInstances.Count > 0) { /* * Each iteration of this loop * (1) moves the contents of labelToInstances into accLabelToInstances @@ -297,31 +266,26 @@ private VCExpr Execute(Implementation impl, VCExpr vcExpr) lambdaToInstances = new Dictionary>>(); var visitedQuantifierBindings = new HashSet(); - while (visitedQuantifierBindings.Count < quantifierBinding.Count) - { + while (visitedQuantifierBindings.Count < quantifierBinding.Count) { /* * quantifierBinding may be modified in each iteration of the following loop. * Therefore, take a snapshot of quantifierBinding.Keys to start the loop. */ - foreach (var v in quantifierBinding.Keys) - { - if (visitedQuantifierBindings.Contains(v)) - { + foreach (var v in quantifierBinding.Keys) { + if (visitedQuantifierBindings.Contains(v)) { continue; } visitedQuantifierBindings.Add(v); var quantifierExpr = quantifierBinding[v]; var quantifierInfo = quantifierInstantiationInfo[quantifierExpr]; - if (quantifierInfo.relevantLabels.Overlaps(accLabelToInstances.Keys)) - { + if (quantifierInfo.relevantLabels.Overlaps(accLabelToInstances.Keys)) { InstantiateQuantifier(quantifierExpr); } } } var visitedLambdaFunctions = new HashSet(); - while (visitedLambdaFunctions.Count < lambdaDefinition.Count) - { + while (visitedLambdaFunctions.Count < lambdaDefinition.Count) { /* * lambdaDefinition may be modified in each iteration of the following loop. * Therefore, take a snapshot of lambdaDefinition.Keys to start the loop. @@ -349,17 +313,14 @@ private VCExpr Execute(Implementation impl, VCExpr vcExpr) quantifierInstantiationInfo[quantifierExpr].instances.Values.ToList()).ToList()); return vcExprGen.Implies(lambdaAxioms, LetConvert(vcExpr)); } - - private VCExpr LetConvert(VCExpr vcExpr) - { + + private VCExpr LetConvert(VCExpr vcExpr) { var bindings = BindingCollector.CollectBindings(this, vcExpr).ToList(); - if (bindings.Count == 0) - { + if (bindings.Count == 0) { return vcExpr; } var rhss = new List(); - foreach (var binding in bindings) - { + foreach (var binding in bindings) { rhss.Add(new VCExprLetBinding(binding, LetConvert(this.AugmentWithInstances(quantifierBinding[binding])))); } return vcExprGen.Let(rhss, vcExpr); @@ -398,8 +359,7 @@ private VCExpr AugmentWithInstances(VCExprQuantifier quantifierExpr) } } - private void InstantiateLambdaDefinition(Function lambdaFunction) - { + private void InstantiateLambdaDefinition(Function lambdaFunction) { var quantifierExpr = lambdaDefinition[lambdaFunction]; var boundVariableToLabels = quantifierExpr.Info.instantiationLabels; var boundVariableToExprs = boundVariableToLabels.Keys.ToDictionary( @@ -408,14 +368,12 @@ private void InstantiateLambdaDefinition(Function lambdaFunction) boundVariableToLabels[boundVariable] .SelectMany(label => accLabelToInstances.ContainsKey(label) ? accLabelToInstances[label] : new HashSet()).ToHashSet()); - foreach (var instance in accLambdaToInstances[lambdaFunction]) - { + foreach (var instance in accLambdaToInstances[lambdaFunction]) { ConstructInstances(quantifierExpr, boundVariableToExprs, lambdaFunction.InParams.Count, instance); } } - private void InstantiateQuantifier(VCExprQuantifier quantifierExpr) - { + private void InstantiateQuantifier(VCExprQuantifier quantifierExpr) { var boundVariableToLabels = quantifierExpr.Info.instantiationLabels; var boundVariableToExprs = boundVariableToLabels.Keys.ToDictionary( boundVariable => boundVariable, @@ -427,27 +385,22 @@ private void InstantiateQuantifier(VCExprQuantifier quantifierExpr) } private void ConstructInstances(VCExprQuantifier quantifierExpr, - Dictionary> boundVariableToExprs, int n, List instance) - { - if (quantifierExpr.BoundVars.Count == n) - { + Dictionary> boundVariableToExprs, int n, List instance) { + if (quantifierExpr.BoundVars.Count == n) { InstantiateQuantifierAtInstance(quantifierExpr, instance); return; } var boundVariable = quantifierExpr.BoundVars[n]; - foreach (var expr in boundVariableToExprs[boundVariable]) - { + foreach (var expr in boundVariableToExprs[boundVariable]) { instance.Add(expr); ConstructInstances(quantifierExpr, boundVariableToExprs, n + 1, instance); instance.RemoveAt(n); } } - private void InstantiateQuantifierAtInstance(VCExprQuantifier quantifierExpr, List instance) - { + private void InstantiateQuantifierAtInstance(VCExprQuantifier quantifierExpr, List instance) { var quantifierInstantiationInfo = this.quantifierInstantiationInfo[quantifierExpr]; - if (quantifierInstantiationInfo.instances.ContainsKey(instance)) - { + if (quantifierInstantiationInfo.instances.ContainsKey(instance)) { return; } @@ -472,15 +425,13 @@ quantifierInstantiationInfo.instances[new List(instance)] = } } - enum Polarity - { + enum Polarity { Positive, Negative, Unknown, } - - class QuantifierCollector : BoundVarTraversingVCExprVisitor, Polarity> - { + + class QuantifierCollector : BoundVarTraversingVCExprVisitor, Polarity> { /* * This method collects quantifiers embedded in vcExpr. * If polarity == Polarity.Negative, a quantifier F embedded in expr is collected @@ -488,17 +439,14 @@ class QuantifierCollector : BoundVarTraversingVCExprVisitor CollectQuantifiers(VCExpr vcExpr, Polarity polarity) - { + public static HashSet CollectQuantifiers(VCExpr vcExpr, Polarity polarity) { var visitor = new QuantifierCollector(); visitor.Traverse(vcExpr, polarity); return visitor.quantifiers; } - public static Polarity Flip(Polarity polarity) - { - switch (polarity) - { + public static Polarity Flip(Polarity polarity) { + switch (polarity) { case Polarity.Positive: return Polarity.Negative; case Polarity.Negative: @@ -511,133 +459,105 @@ public static Polarity Flip(Polarity polarity) } private HashSet quantifiers = new HashSet(); - - private static Polarity Join(Polarity first, Polarity second) - { - if (first == second) - { + + private static Polarity Join(Polarity first, Polarity second) { + if (first == second) { return first; } return Polarity.Unknown; } - private static Dictionary Join(IEnumerable> elems) - { + private static Dictionary Join(IEnumerable> elems) { var result = new Dictionary(); - foreach (var elem in elems) - { - foreach (var x in elem.Keys) - { - if (result.ContainsKey(x)) - { + foreach (var elem in elems) { + foreach (var x in elem.Keys) { + if (result.ContainsKey(x)) { result[x] = Join(result[x], elem[x]); - } - else - { + } else { result[x] = elem[x]; } } } return result; } - - private static Dictionary Join(params Dictionary[] elems) - { + + private static Dictionary Join(params Dictionary[] elems) { return Join(elems.Select(x => x)); } - - public override Dictionary Visit(VCExprNAry node, Polarity arg) - { - if (arg != Polarity.Unknown) - { - if (node.Op.Equals(VCExpressionGenerator.NotOp)) - { - return node[0].Accept(this, Flip(arg)); + + public override async DynamicStack> Visit(VCExprNAry node, Polarity arg) { + if (arg != Polarity.Unknown) { + if (node.Op.Equals(VCExpressionGenerator.NotOp)) { + return await node[0].Accept(this, Flip(arg)); } - if (node.Op.Equals(VCExpressionGenerator.AndOp) || node.Op.Equals(VCExpressionGenerator.OrOp)) - { - return Join(node[0].Accept(this, arg), node[1].Accept(this, arg)); + if (node.Op.Equals(VCExpressionGenerator.AndOp) || node.Op.Equals(VCExpressionGenerator.OrOp)) { + return Join(await node[0].Accept(this, arg), await node[1].Accept(this, arg)); } - if (node.Op.Equals(VCExpressionGenerator.ImpliesOp)) - { - return Join(node[0].Accept(this, Flip(arg)), node[1].Accept(this, arg)); + if (node.Op.Equals(VCExpressionGenerator.ImpliesOp)) { + return Join(await node[0].Accept(this, Flip(arg)), await node[1].Accept(this, arg)); } } - return Join(node.UniformArguments.Select(x => x.Accept(this, Polarity.Unknown))); + return Join(await node.UniformArguments.Select(x => x.Accept(this, Polarity.Unknown)).ToDynamicStackList()); } - public override Dictionary Visit(VCExprVar node, Polarity arg) - { - return new Dictionary {{node, arg}}; + public override Dictionary Visit(VCExprVar node, Polarity arg) { + return new Dictionary { { node, arg } }; } - protected override Dictionary VisitAfterBinding(VCExprLet node, Polarity arg) - { - var result = node.Body.Accept(this, arg); - for (int i = node.Length - 1; i >= 0; i--) - { - if (result.ContainsKey(node[i].V)) - { - result = Join(result, node[i].E.Accept(this, result[node[i].V])); + protected override async DynamicStack> VisitAfterBinding(VCExprLet node, Polarity arg) { + var result = await node.Body.Accept(this, arg); + for (int i = node.Length - 1; i >= 0; i--) { + if (result.ContainsKey(node[i].V)) { + result = Join(result, await node[i].E.Accept(this, result[node[i].V])); } } - foreach (var x in node.BoundVars) - { + foreach (var x in node.BoundVars) { result.Remove(x); } return result; } - protected override Dictionary VisitAfterBinding(VCExprQuantifier node, Polarity arg) - { - var result = node.Body.Accept(this, arg); - foreach (var x in node.BoundVars) - { + protected override async DynamicStack> VisitAfterBinding(VCExprQuantifier node, + Polarity arg) { + var result = await node.Body.Accept(this, arg); + foreach (var x in node.BoundVars) { result.Remove(x); } return result; } - public override Dictionary Visit(VCExprQuantifier node, Polarity arg) - { - var result = base.Visit(node, arg); - if (arg != Polarity.Unknown && !result.Keys.Intersect(BoundTermVars.Keys).Any()) - { - if ((arg == Polarity.Positive) == (node.Quan == Quantifier.EX)) - { + public override async DynamicStack> Visit(VCExprQuantifier node, Polarity arg) { + var result = await base.Visit(node, arg); + if (arg != Polarity.Unknown && !result.Keys.Intersect(BoundTermVars.Keys).Any()) { + if ((arg == Polarity.Positive) == (node.Quan == Quantifier.EX)) { quantifiers.Add(node); } } return result; } - protected override Dictionary StandardResult(VCExpr node, Polarity arg) - { + protected override Dictionary StandardResult(VCExpr node, Polarity arg) { return null; } - public override Dictionary Visit(VCExprLiteral node, Polarity arg) - { + public override Dictionary Visit(VCExprLiteral node, Polarity arg) { return new Dictionary(); } } - - class Skolemizer : MutatingVCExprVisitor - { + + class Skolemizer : MutatingVCExprVisitor { /* * The method Skolemize performs best-effort skolemization of the input expression expr. * Factorization is performed on the resulting expression. */ - public static VCExpr Skolemize(QuantifierInstantiationEngine qiEngine, Polarity polarity, VCExpr vcExpr) - { + public static VCExpr Skolemize(QuantifierInstantiationEngine qiEngine, Polarity polarity, VCExpr vcExpr) { var skolemizer = new Skolemizer(qiEngine, polarity, vcExpr); var skolemizedExpr = skolemizer.Mutate(vcExpr, true); LambdaInstanceCollector.CollectInstances(qiEngine, vcExpr); return Factorizer.Factorize(qiEngine, skolemizedExpr); } - private Skolemizer(QuantifierInstantiationEngine qiEngine, Polarity polarity, VCExpr vcExpr) : base(qiEngine.vcExprGen) - { + private Skolemizer(QuantifierInstantiationEngine qiEngine, Polarity polarity, VCExpr vcExpr) : base(qiEngine.vcExprGen) { this.qiEngine = qiEngine; this.quantifiers = QuantifierCollector.CollectQuantifiers(vcExpr, polarity); this.bound = new Dictionary(); @@ -647,36 +567,33 @@ private Skolemizer(QuantifierInstantiationEngine qiEngine, Polarity polarity, VC private HashSet quantifiers; private Dictionary bound; - public override VCExpr Visit(VCExprVar node, bool arg) - { - if (bound.ContainsKey(node)) - { + public override VCExpr Visit(VCExprVar node, bool arg) { + if (bound.ContainsKey(node)) { return bound[node]; } return base.Visit(node, arg); } - public override VCExpr Visit(VCExprQuantifier node, bool arg) - { - if (node.TypeParameters.Count == 0 && quantifiers.Contains(node)) - { + public override DynamicStack Visit(VCExprQuantifier node, bool arg) { + if (node.TypeParameters.Count == 0 && quantifiers.Contains(node)) { return PerformSkolemization(node, arg); } return base.Visit(node, arg); } - private VCExpr PerformSkolemization(VCExprQuantifier node, bool arg) - { - var oldToNew = node.BoundVars.ToDictionary(v => v, v => (VCExpr) qiEngine.FreshSkolemConstant(v)); - foreach (var x in node.BoundVars) - { + private async DynamicStack PerformSkolemization(VCExprQuantifier node, bool arg) { + var oldToNew = node.BoundVars.ToDictionary(v => v, v => (VCExpr)qiEngine.FreshSkolemConstant(v)); + foreach (var x in node.BoundVars) { bound.Add(x, oldToNew[x]); } - var retExpr = (VCExprQuantifier) base.Visit(node, arg); - retExpr.Info.instantiationExprs.ForEach(kv => + var retExpr = (VCExprQuantifier) await base.Visit(node, arg); + foreach(var kv in retExpr.Info.instantiationExprs) { - CollectionExtensions.ForEach(kv.Value, expr => { qiEngine.AddTerm(kv.Key, expr.Accept(this, arg)); }); - }); + foreach (var expr in (IEnumerable)kv.Value) + { + qiEngine.AddTerm(kv.Key, await expr.Accept(this, arg)); + } + } foreach (var x in node.BoundVars) { bound.Remove(x); @@ -684,44 +601,37 @@ private VCExpr PerformSkolemization(VCExprQuantifier node, bool arg) return retExpr.Body; } } - - class Factorizer : MutatingVCExprVisitor - { + + class Factorizer : MutatingVCExprVisitor { /* * The method Factorize factors out quantified expressions in expr replacing them with a bound variable. * The binding between the bound variable and the quantifier replaced by it is registered in qiEngine. */ - + private QuantifierInstantiationEngine qiEngine; - public static VCExpr Factorize(QuantifierInstantiationEngine qiEngine, VCExpr vcExpr) - { + public static VCExpr Factorize(QuantifierInstantiationEngine qiEngine, VCExpr vcExpr) { var factorizer = new Factorizer(qiEngine); return factorizer.Mutate(vcExpr, true); } - private Factorizer(QuantifierInstantiationEngine qiEngine) : base(qiEngine.vcExprGen) - { + private Factorizer(QuantifierInstantiationEngine qiEngine) : base(qiEngine.vcExprGen) { this.qiEngine = qiEngine; } - public override VCExpr Visit(VCExprQuantifier node, bool arg) - { - return qiEngine.BindQuantifier(node); + public override DynamicStack Visit(VCExprQuantifier node, bool arg) { + return DynamicStack.FromResult(qiEngine.BindQuantifier(node)); } } - - class BindingCollector : TraversingVCExprVisitor - { - public static HashSet CollectBindings(QuantifierInstantiationEngine qiEngine, VCExpr vcExpr) - { + + class BindingCollector : TraversingVCExprVisitor { + public static HashSet CollectBindings(QuantifierInstantiationEngine qiEngine, VCExpr vcExpr) { var bindingCollector = new BindingCollector(qiEngine); bindingCollector.Traverse(vcExpr, true); return bindingCollector.bindings; } - private BindingCollector(QuantifierInstantiationEngine qiEngine) - { + private BindingCollector(QuantifierInstantiationEngine qiEngine) { this.qiEngine = qiEngine; this.bindings = new HashSet(); } @@ -729,33 +639,26 @@ private BindingCollector(QuantifierInstantiationEngine qiEngine) private QuantifierInstantiationEngine qiEngine; private HashSet bindings; - protected override bool StandardResult(VCExpr node, bool arg) - { + protected override bool StandardResult(VCExpr node, bool arg) { return true; } - public override bool Visit(VCExprVar node, bool arg) - { - if (qiEngine.IsQuantifierBinding(node)) - { + public override bool Visit(VCExprVar node, bool arg) { + if (qiEngine.IsQuantifierBinding(node)) { bindings.Add(node); } return base.Visit(node, arg); } } - - class LambdaInstanceCollector : BoundVarTraversingVCExprVisitor - { - public static void CollectInstances(QuantifierInstantiationEngine qiEngine, VCExpr vcExpr) - { + + class LambdaInstanceCollector : BoundVarTraversingVCExprVisitor { + public static void CollectInstances(QuantifierInstantiationEngine qiEngine, VCExpr vcExpr) { var lambdaInstanceCollector = new LambdaInstanceCollector(qiEngine); lambdaInstanceCollector.Traverse(vcExpr, true); var lambdaFunctionToInstances = new Dictionary>>(); - foreach (var instance in lambdaInstanceCollector.instances) - { + foreach (var instance in lambdaInstanceCollector.instances) { var function = (instance.Op as VCExprBoogieFunctionOp).Func; - if (!lambdaFunctionToInstances.ContainsKey(function)) - { + if (!lambdaFunctionToInstances.ContainsKey(function)) { lambdaFunctionToInstances[function] = new HashSet>(new ListComparer()); } lambdaFunctionToInstances[function].Add(instance.UniformArguments.ToList()); @@ -763,8 +666,7 @@ public static void CollectInstances(QuantifierInstantiationEngine qiEngine, VCEx qiEngine.AddLambdaInstances(lambdaFunctionToInstances); } - private LambdaInstanceCollector(QuantifierInstantiationEngine qiEngine) - { + private LambdaInstanceCollector(QuantifierInstantiationEngine qiEngine) { this.qiEngine = qiEngine; this.instances = new HashSet(); this.instancesOnStack = new Stack>>(); @@ -776,31 +678,25 @@ private LambdaInstanceCollector(QuantifierInstantiationEngine qiEngine) private Stack>> instancesOnStack; private Stack> letBoundVarsOnStack; - protected override bool StandardResult(VCExpr node, bool arg) - { + protected override bool StandardResult(VCExpr node, bool arg) { return true; } - private VCExprNAry Substitute(VCExprNAry vcExpr) - { - foreach (var letBoundVars in letBoundVarsOnStack) - { + private VCExprNAry Substitute(VCExprNAry vcExpr) { + foreach (var letBoundVars in letBoundVarsOnStack) { var subst = new VCExprSubstitution( letBoundVars.ToDictionary(x => x, x => BoundTermVars[x]), new Dictionary()); var substituter = new SubstitutingVCExprVisitor(qiEngine.vcExprGen); - vcExpr = (VCExprNAry) substituter.Mutate(vcExpr, subst); + vcExpr = (VCExprNAry)substituter.Mutate(vcExpr, subst); } return vcExpr; } - - public override bool Visit(VCExprNAry node, bool arg) - { - if (node.Op is VCExprBoogieFunctionOp functionOp) - { + + public override async DynamicStack Visit(VCExprNAry node, bool arg) { + if (node.Op is VCExprBoogieFunctionOp functionOp) { var function = functionOp.Func; - if (function.OriginalLambdaExprAsString != null && qiEngine.BindLambdaFunction(function)) - { + if (function.OriginalLambdaExprAsString != null && qiEngine.BindLambdaFunction(function)) { // substitute all let-bound variables in the lambda expr var substExpr = Substitute(node); instances.Add(substExpr); @@ -809,43 +705,36 @@ public override bool Visit(VCExprNAry node, bool arg) // then this term is ineligible and should be removed instancesOnStack.Push(new Tuple>(substExpr, BoundTermVars.Keys.Where(x => BoundTermVars[x] == null).ToHashSet())); - var retVal = base.Visit(node, arg); + var retVal = await base.Visit(node, arg); instancesOnStack.Pop(); return retVal; } } - return base.Visit(node, arg); + return await base.Visit(node, arg); } - public override bool Visit(VCExprVar node, bool arg) - { + public override bool Visit(VCExprVar node, bool arg) { // check each lambda term going down the stack and remove ineligible terms if any // once an eligible term is found, all terms below it must be eligible as well - foreach (var pair in instancesOnStack) - { - if (pair.Item2.Contains(node)) - { + foreach (var pair in instancesOnStack) { + if (pair.Item2.Contains(node)) { instances.Remove(pair.Item1); - } - else - { + } else { break; } } return base.Visit(node, arg); } - - public override bool Visit(VCExprLet node, bool arg) - { + + public override DynamicStack Visit(VCExprLet node, bool arg) { letBoundVarsOnStack.Push(node.BoundVars); var retVal = base.Visit(node, arg); letBoundVarsOnStack.Pop(); return retVal; } } - - class InstantiationSourceChecker : ReadOnlyVisitor - { + + class InstantiationSourceChecker : ReadOnlyVisitor { private bool hasInstances; private void FindInstantiationSources(ICarriesAttributes o) @@ -871,16 +760,14 @@ private void FindInstantiationSources(ICarriesAttributes o) iter = iter.Next; } } - - public static bool HasInstantiationSources(Implementation impl) - { + + public static bool HasInstantiationSources(Implementation impl) { var instanceChecker = new InstantiationSourceChecker(); instanceChecker.VisitImplementation(impl); return instanceChecker.hasInstances; } - private InstantiationSourceChecker() - { + private InstantiationSourceChecker() { this.hasInstances = false; } diff --git a/Source/VCExpr/RandomiseNamer.cs b/Source/VCExpr/RandomiseNamer.cs index 6fe1ad021..24811fc03 100644 --- a/Source/VCExpr/RandomiseNamer.cs +++ b/Source/VCExpr/RandomiseNamer.cs @@ -2,41 +2,34 @@ namespace Microsoft.Boogie.VCExprAST; -public class RandomiseNamer : ScopedNamer -{ +public class RandomiseNamer : ScopedNamer { private Random random; - public RandomiseNamer(Random random) - { + public RandomiseNamer(Random random) { this.random = random; } - public RandomiseNamer(ScopedNamer namer, Random random) : base(namer) - { + public RandomiseNamer(ScopedNamer namer, Random random) : base(namer) { this.random = random; } public static RandomiseNamer Create(Random random, ScopedNamer namer = null) { return namer != null ? new RandomiseNamer(namer, random) : new RandomiseNamer(random); } - - private RandomiseNamer(RandomiseNamer namer) : base(namer) - { + + private RandomiseNamer(RandomiseNamer namer) : base(namer) { random = namer.random; } - public void SetRandom(Random random) - { + public void SetRandom(Random random) { this.random = random; } - - public override UniqueNamer Clone() - { + + public override UniqueNamer Clone() { return new RandomiseNamer(this); } - protected override string GetModifiedName(string uniqueInherentName) - { + protected override string GetModifiedName(string uniqueInherentName) { return $"random{random.Next()}"; } } \ No newline at end of file diff --git a/Source/VCExpr/ScopedNamer.cs b/Source/VCExpr/ScopedNamer.cs index 00d28fead..f9c325952 100644 --- a/Source/VCExpr/ScopedNamer.cs +++ b/Source/VCExpr/ScopedNamer.cs @@ -2,21 +2,19 @@ using System.Collections.Generic; using System.Diagnostics.Contracts; -namespace Microsoft.Boogie.VCExprAST -{ +namespace Microsoft.Boogie.VCExprAST { /** * Visitor that establishes unique variable (or constant) names in a VCExpr. * This is done by adding a counter as suffix if name clashes occur * TODO: also handle type variables here */ - public abstract class ScopedNamer : UniqueNamer - { + public abstract class ScopedNamer : UniqueNamer { private static ISet boogieDeterminedNames = new HashSet() { }; public static void AddBoogieDeterminedName(string name) { boogieDeterminedNames.Add(name); } - + public string Spacer = "@@"; protected IDictionary /*!*/ GlobalNames; @@ -27,27 +25,24 @@ public static void AddBoogieDeterminedName(string name) { protected IDictionary /*!*/ CurrentCounters; protected IDictionary /*!*/ GlobalPlusLocalNames; - protected Dictionary globalNewToOldName = new (); + protected Dictionary globalNewToOldName = new(); - protected ScopedNamer() - { + protected ScopedNamer() { GlobalNames = new Dictionary(); LocalNames = new() { new Dictionary() }; UsedNames = new HashSet(); CurrentCounters = new Dictionary(); GlobalPlusLocalNames = new Dictionary(); } - - protected ScopedNamer(ScopedNamer namer) - { + + protected ScopedNamer(ScopedNamer namer) { Contract.Requires(namer != null); Spacer = namer.Spacer; GlobalNames = new Dictionary(namer.GlobalNames); LocalNames = new List>(); - foreach (IDictionary /*!*/ d in namer.LocalNames) - { + foreach (IDictionary /*!*/ d in namer.LocalNames) { LocalNames.Add(new Dictionary(d)); } @@ -58,67 +53,55 @@ protected ScopedNamer(ScopedNamer namer) } [ContractInvariantMethod] - private void GlobalNamesInvariantMethod() - { + private void GlobalNamesInvariantMethod() { Contract.Invariant(cce.NonNullDictionaryAndValues(GlobalNames)); } [ContractInvariantMethod] - private void LocalNamesInvariantMethod() - { + private void LocalNamesInvariantMethod() { Contract.Invariant(Contract.ForAll(LocalNames, i => i != null && cce.NonNullDictionaryAndValues(i))); } [ContractInvariantMethod] - private void UsedNamesInvariantMethod() - { + private void UsedNamesInvariantMethod() { Contract.Invariant(cce.NonNull(UsedNames)); } [ContractInvariantMethod] - private void CurrentCountersInvariantMethod() - { + private void CurrentCountersInvariantMethod() { Contract.Invariant(CurrentCounters != null); } [ContractInvariantMethod] - private void GlobalPlusLocalNamesInvariantMethod() - { + private void GlobalPlusLocalNamesInvariantMethod() { Contract.Invariant(cce.NonNullDictionaryAndValues(GlobalPlusLocalNames)); } - public void PushScope() - { + public void PushScope() { LocalNames.Add(new Dictionary()); } public abstract UniqueNamer Clone(); - public void PopScope() - { + public void PopScope() { LocalNames.RemoveAt(LocalNames.Count - 1); } - protected string NextFreeName(Object thing, string baseName) - { + protected string NextFreeName(Object thing, string baseName) { Contract.Requires(baseName != null); Contract.Requires(thing != null); Contract.Ensures(Contract.Result() != null); string /*!*/ candidate; - if (CurrentCounters.TryGetValue(baseName, out var counter)) - { + if (CurrentCounters.TryGetValue(baseName, out var counter)) { candidate = baseName + Spacer + counter; counter = counter + 1; - } - else - { + } else { candidate = baseName; counter = 0; } - while (UsedNames.Contains(candidate)) - { + while (UsedNames.Contains(candidate)) { candidate = baseName + Spacer + counter; counter = counter + 1; } @@ -130,17 +113,13 @@ protected string NextFreeName(Object thing, string baseName) } [Pure] - public string this[Object /*!*/ thingie] - { - get - { + public string this[Object /*!*/ thingie] { + get { Contract.Requires(thingie != null); string res; - for (int i = LocalNames.Count - 1; i >= 0; --i) - { - if (LocalNames[i].TryGetValue(thingie, out res)) - { + for (int i = LocalNames.Count - 1; i >= 0; --i) { + if (LocalNames[i].TryGetValue(thingie, out res)) { return res; } } @@ -150,46 +129,36 @@ public string this[Object /*!*/ thingie] } } - public string Lookup(Object thingie) - { + public string Lookup(Object thingie) { Contract.Requires(thingie != null); Contract.Ensures(Contract.Result() != null); - if (GlobalPlusLocalNames.TryGetValue(thingie, out var name)) - { + if (GlobalPlusLocalNames.TryGetValue(thingie, out var name)) { return name; } return Spacer + "undefined" + Spacer + thingie.GetHashCode() + Spacer; } - public virtual string GetName(object thing, string inherentName) - { + public virtual string GetName(object thing, string inherentName) { Contract.Requires(inherentName != null); Contract.Requires(thing != null); Contract.Ensures(Contract.Result() != null); string result = this[thing]; - if (result != null) - { + if (result != null) { return result; } var uniqueInherentName = NextFreeName(thing, inherentName); - if (thing is NamedDeclaration namedDeclaration && !namedDeclaration.MayRename) - { + if (thing is NamedDeclaration namedDeclaration && !namedDeclaration.MayRename) { result = uniqueInherentName; - } - else if (boogieDeterminedNames.Contains(inherentName)) - { + } else if (boogieDeterminedNames.Contains(inherentName)) { result = uniqueInherentName; - } - else { + } else { var modifiedName = GetModifiedName(uniqueInherentName); if (modifiedName != uniqueInherentName) { result = NextFreeName(thing, modifiedName); globalNewToOldName.Add(result, uniqueInherentName); - } - else - { + } else { result = uniqueInherentName; } } @@ -201,8 +170,7 @@ public virtual string GetName(object thing, string inherentName) protected abstract string GetModifiedName(string uniqueInherentName); - public virtual string GetLocalName(Object thing, string inherentName) - { + public virtual string GetLocalName(Object thing, string inherentName) { Contract.Requires(inherentName != null); Contract.Requires(thing != null); Contract.Ensures(Contract.Result() != null); @@ -215,8 +183,7 @@ public virtual string GetLocalName(Object thing, string inherentName) return res; } - public virtual string GetOriginalName(string newName) - { + public virtual string GetOriginalName(string newName) { return globalNewToOldName.GetValueOrDefault(newName, newName); } } diff --git a/Source/VCExpr/TypeErasure/TypeEraserPremisses.cs b/Source/VCExpr/TypeEraserPremisses.cs similarity index 77% rename from Source/VCExpr/TypeErasure/TypeEraserPremisses.cs rename to Source/VCExpr/TypeEraserPremisses.cs index c1957bd47..f8a5ca410 100644 --- a/Source/VCExpr/TypeErasure/TypeEraserPremisses.cs +++ b/Source/VCExpr/TypeEraserPremisses.cs @@ -5,27 +5,22 @@ namespace Microsoft.Boogie.TypeErasure; -public class TypeEraserPremisses : TypeEraser -{ +public class TypeEraserPremisses : TypeEraser { private readonly TypeAxiomBuilderPremisses /*!*/ AxBuilderPremisses; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(AxBuilderPremisses != null); } private OpTypeEraser OpEraserAttr = null; - protected override OpTypeEraser /*!*/ OpEraser - { - get - { + protected override OpTypeEraser /*!*/ OpEraser { + get { Contract.Ensures(Contract.Result() != null); - if (OpEraserAttr == null) - { + if (OpEraserAttr == null) { OpEraserAttr = new OpTypeEraserPremisses(this, AxBuilderPremisses, Gen); } @@ -34,8 +29,7 @@ protected override OpTypeEraser /*!*/ OpEraser } public TypeEraserPremisses(TypeAxiomBuilderPremisses axBuilder, VCExpressionGenerator gen) - : base(axBuilder, gen) - { + : base(axBuilder, gen) { Contract.Requires(gen != null); Contract.Requires(axBuilder != null); @@ -44,8 +38,7 @@ public TypeEraserPremisses(TypeAxiomBuilderPremisses axBuilder, VCExpressionGene //////////////////////////////////////////////////////////////////////////// - public override VCExpr Visit(VCExprQuantifier node, VariableBindings oldBindings) - { + public override async DynamicStack Visit(VCExprQuantifier node, VariableBindings oldBindings) { Contract.Requires(oldBindings != null); Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); @@ -57,12 +50,9 @@ public override VCExpr Visit(VCExprQuantifier node, VariableBindings oldBindings // in the types of such variables) FreeVariableCollector coll = new FreeVariableCollector(); coll.Collect(node.Body); - foreach (VCTrigger trigger in node.Triggers) - { - if (trigger.Pos) - { - foreach (VCExpr /*!*/ e in trigger.Exprs) - { + foreach (VCTrigger trigger in node.Triggers) { + if (trigger.Pos) { + foreach (VCExpr /*!*/ e in trigger.Exprs) { Contract.Assert(e != null); coll.Collect(e); @@ -71,10 +61,8 @@ public override VCExpr Visit(VCExprQuantifier node, VariableBindings oldBindings } List occurringVars = new List(node.BoundVars.Count); - foreach (VCExprVar var in node.BoundVars) - { - if (coll.FreeTermVars.Contains(var)) - { + foreach (VCExprVar var in node.BoundVars) { + if (coll.FreeTermVars.Contains(var)) { occurringVars.Add(var); } } @@ -83,28 +71,22 @@ public override VCExpr Visit(VCExprQuantifier node, VariableBindings oldBindings // bound term variables are replaced with bound term variables typed in // a simpler way - List /*!*/ - newBoundVars = - BoundVarsAfterErasure(occurringVars, bindings); + List /*!*/ newBoundVars = BoundVarsAfterErasure(occurringVars, bindings); Contract.Assert(cce.NonNullElements(newBoundVars)); - VCExpr /*!*/ - newNode = HandleQuantifier(node, occurringVars, + VCExpr /*!*/ newNode = await HandleQuantifier(node, occurringVars, newBoundVars, bindings); Contract.Assert(newNode != null); - if (!(newNode is VCExprQuantifier) || !IsUniversalQuantifier(node)) - { + if (!(newNode is VCExprQuantifier) || !IsUniversalQuantifier(node)) { return newNode; } - if (!RedoQuantifier(node, (VCExprQuantifier) newNode, occurringVars, oldBindings, - out var bindings2, out newBoundVars)) - { + if (!RedoQuantifier(node, (VCExprQuantifier)newNode, occurringVars, oldBindings, + out var bindings2, out newBoundVars)) { return newNode; } - return HandleQuantifier(node, occurringVars, - newBoundVars, bindings2); + return await HandleQuantifier(node, occurringVars, newBoundVars, bindings2); } private VCExpr /*!*/ GenTypePremisses(List /*!*/ oldBoundVars, @@ -112,8 +94,7 @@ public override VCExpr Visit(VCExprQuantifier node, VariableBindings oldBindings IDictionary /*!*/ typeVarTranslation, List /*!*/ typeVarBindings, - out List /*!*/ triggers) - { + out List /*!*/ triggers) { Contract.Requires(cce.NonNullElements(oldBoundVars)); Contract.Requires(cce.NonNullElements(newBoundVars)); Contract.Requires(cce.NonNullDictionaryAndValues(typeVarTranslation)); @@ -125,8 +106,7 @@ public override VCExpr Visit(VCExprQuantifier node, VariableBindings oldBindings // whether type premisses are trivial VCExprSubstitution /*!*/ typeParamSubstitution = new VCExprSubstitution(); - foreach (VCExprLetBinding /*!*/ binding in typeVarBindings) - { + foreach (VCExprLetBinding /*!*/ binding in typeVarBindings) { Contract.Assert(binding != null); typeParamSubstitution[binding.V] = binding.E; } @@ -139,8 +119,7 @@ public override VCExpr Visit(VCExprQuantifier node, VariableBindings oldBindings typePremisses = new List(newBoundVars.Count); triggers = new List(newBoundVars.Count); - for (int i = 0; i < newBoundVars.Count; ++i) - { + for (int i = 0; i < newBoundVars.Count; ++i) { VCExprVar /*!*/ oldVar = oldBoundVars[i]; Contract.Assert(oldVar != null); @@ -154,8 +133,7 @@ public override VCExpr Visit(VCExprQuantifier node, VariableBindings oldBindings typeVarTranslation); Contract.Assert(typePremiss != null); if (!IsTriviallyTrue(substituter.Mutate(typePremiss, - typeParamSubstitution))) - { + typeParamSubstitution))) { typePremisses.Add(typePremiss); // generate a negative trigger for the variable occurrence // in the type premiss @@ -172,22 +150,18 @@ public override VCExpr Visit(VCExprQuantifier node, VariableBindings oldBindings // these optimisations should maybe be moved into a separate // visitor (peep-hole optimisations) - private bool IsTriviallyTrue(VCExpr expr) - { + private bool IsTriviallyTrue(VCExpr expr) { Contract.Requires(expr != null); - if (expr.Equals(VCExpressionGenerator.True)) - { + if (expr.Equals(VCExpressionGenerator.True)) { return true; } - if (expr is VCExprNAry) - { + if (expr is VCExprNAry) { VCExprNAry /*!*/ - naryExpr = (VCExprNAry) expr; + naryExpr = (VCExprNAry)expr; Contract.Assert(naryExpr != null); if (naryExpr.Op.Equals(VCExpressionGenerator.EqOp) && - naryExpr[0].Equals(naryExpr[1])) - { + naryExpr[0].Equals(naryExpr[1])) { return true; } } @@ -195,9 +169,8 @@ private bool IsTriviallyTrue(VCExpr expr) return false; } - private VCExpr HandleQuantifier(VCExprQuantifier node, List /*!*/ occurringVars /*!*/, - List /*!*/ newBoundVars, VariableBindings bindings) - { + private async DynamicStack HandleQuantifier(VCExprQuantifier node, List /*!*/ occurringVars /*!*/, + List /*!*/ newBoundVars, VariableBindings bindings) { Contract.Requires(bindings != null); Contract.Requires(node != null); Contract.Requires(cce.NonNullElements(occurringVars /*!*/)); @@ -210,14 +183,11 @@ private VCExpr HandleQuantifier(VCExprQuantifier node, List /*! // Check whether some of the type parameters could not be // determined from the bound variable types. In this case, we // quantify explicitly over these variables - if (typeVarBindings.Count < node.TypeParameters.Count) - { - foreach (TypeVariable /*!*/ var in node.TypeParameters) - { + if (typeVarBindings.Count < node.TypeParameters.Count) { + foreach (TypeVariable /*!*/ var in node.TypeParameters) { Contract.Assert(var != null); - if (typeVarBindings.All(b => !b.V.Equals(bindings.TypeVariableBindings[var]))) - { - newBoundVars.Add((VCExprVar) bindings.TypeVariableBindings[var]); + if (typeVarBindings.All(b => !b.V.Equals(bindings.TypeVariableBindings[var]))) { + newBoundVars.Add((VCExprVar)bindings.TypeVariableBindings[var]); } } } @@ -230,10 +200,8 @@ private VCExpr HandleQuantifier(VCExprQuantifier node, List /*! newVarsWithTypeSpecs = new List(); if (!IsUniversalQuantifier(node) || AxBuilderPremisses.Options.TypeEncodingMethod - == CoreOptions.TypeEncoding.Predicates) - { - foreach (VCExprVar /*!*/ oldVar in occurringVars) - { + == CoreOptions.TypeEncoding.Predicates) { + foreach (VCExprVar /*!*/ oldVar in occurringVars) { Contract.Assert(oldVar != null); varsWithTypeSpecs.Add(oldVar); newVarsWithTypeSpecs.Add(bindings.VCExprVarBindings[oldVar]); @@ -249,7 +217,7 @@ private VCExpr HandleQuantifier(VCExprQuantifier node, List /*! Contract.Assert(cce.NonNullElements(furtherTriggers)); Contract.Assert(typePremisses != null); List /*!*/ - newTriggers = new List(MutateTriggers(node.Triggers, bindings)); + newTriggers = new List(await MutateTriggers(node.Triggers, bindings)); Contract.Assert(cce.NonNullElements(newTriggers)); newTriggers.AddRange(furtherTriggers); newTriggers = AddLets2Triggers(newTriggers, typeVarBindings); @@ -271,11 +239,9 @@ private VCExpr HandleQuantifier(VCExprQuantifier node, List /*! return bodyWithPremisses; } - foreach (VCExprVar /*!*/ v in newBoundVars) - { + foreach (VCExprVar /*!*/ v in newBoundVars) { Contract.Assert(v != null); - if (v.Type == AxBuilderPremisses.U) - { + if (v.Type == AxBuilderPremisses.U) { newTriggers.Add(Gen.Trigger(false, AxBuilderPremisses.Cast(v, Type.Int))); newTriggers.Add(Gen.Trigger(false, AxBuilderPremisses.Cast(v, Type.Bool))); } @@ -289,43 +255,34 @@ private VCExpr HandleQuantifier(VCExprQuantifier node, List /*! // parameters to the triggers (otherwise, the triggers will // contain unbound/dangling variables for such parameters) private List /*!*/ AddLets2Triggers(List /*!*/ triggers /*!*/, - List /*!*/ typeVarBindings) - { + List /*!*/ typeVarBindings) { Contract.Requires(cce.NonNullElements(triggers /*!*/)); Contract.Requires(cce.NonNullElements(typeVarBindings)); Contract.Ensures(cce.NonNullElements(Contract.Result>())); List /*!*/ triggersWithLets = new List(triggers.Count); - foreach (VCTrigger /*!*/ t in triggers) - { + foreach (VCTrigger /*!*/ t in triggers) { Contract.Assert(t != null); List /*!*/ exprsWithLets = new List(t.Exprs.Count); bool changed = false; - foreach (VCExpr /*!*/ e in t.Exprs) - { + foreach (VCExpr /*!*/ e in t.Exprs) { Contract.Assert(e != null); HashSet freeVars = FreeVariableCollector.FreeTermVariables(e); Contract.Assert(freeVars != null && cce.NonNullElements(freeVars)); - if (typeVarBindings.Any(b => freeVars.Contains(b.V))) - { + if (typeVarBindings.Any(b => freeVars.Contains(b.V))) { exprsWithLets.Add(Gen.Let(typeVarBindings, e)); changed = true; - } - else - { + } else { exprsWithLets.Add(e); } } - if (changed) - { + if (changed) { triggersWithLets.Add(Gen.Trigger(t.Pos, exprsWithLets)); - } - else - { + } else { triggersWithLets.Add(t); } } diff --git a/Source/VCExpr/TypeErasure/HelperFuns.cs b/Source/VCExpr/TypeErasure/HelperFuns.cs index 179162989..f949b79be 100644 --- a/Source/VCExpr/TypeErasure/HelperFuns.cs +++ b/Source/VCExpr/TypeErasure/HelperFuns.cs @@ -4,10 +4,11 @@ namespace Microsoft.Boogie.TypeErasure; -public class HelperFuns -{ - public static Function BoogieFunction(string name, List /*!*/ typeParams, params Type[] types) - { +// some functionality that is needed in many places (and that should +// really be provided by the Spec# container classes; maybe one +// could integrate the functions in a nicer way?) +public class HelperFuns { + public static Function BoogieFunction(string name, List /*!*/ typeParams, params Type[] types) { Contract.Requires(types != null); Contract.Requires(name != null); Contract.Requires(cce.NonNullElements(typeParams)); @@ -16,8 +17,7 @@ public static Function BoogieFunction(string name, List /*!* Contract.Ensures(Contract.Result() != null); List args = new List(); - for (int i = 0; i < types.Length - 1; ++i) - { + for (int i = 0; i < types.Length - 1; ++i) { args.Add(new Formal(Token.NoToken, new TypedIdent(Token.NoToken, "arg" + i, cce.NonNull(types[i])), true)); @@ -30,8 +30,7 @@ public static Function BoogieFunction(string name, List /*!* return new Function(Token.NoToken, name, new List(typeParams), args, result); } - public static Function BoogieFunction(string name, params Type[] types) - { + public static Function BoogieFunction(string name, params Type[] types) { Contract.Requires(types != null); Contract.Requires(name != null); Contract.Ensures(Contract.Result() != null); @@ -39,30 +38,26 @@ public static Function BoogieFunction(string name, params Type[] types) } // boogie function where all arguments and the result have the same type U - public static Function UniformBoogieFunction(string name, int arity, Type U) - { + public static Function UniformBoogieFunction(string name, int arity, Type U) { Contract.Requires(U != null); Contract.Requires(name != null); Contract.Ensures(Contract.Result() != null); Type[] /*!*/ types = new Type[arity + 1]; - for (int i = 0; i < arity + 1; ++i) - { + for (int i = 0; i < arity + 1; ++i) { types[i] = U; } return BoogieFunction(name, types); } - public static List /*!*/ GenVarsForInParams(Function fun, VCExpressionGenerator gen) - { + public static List /*!*/ GenVarsForInParams(Function fun, VCExpressionGenerator gen) { Contract.Requires(gen != null); Contract.Requires(fun != null); Contract.Ensures(cce.NonNullElements(Contract.Result>())); List /*!*/ arguments = new List(fun.InParams.Count); - foreach (Formal /*!*/ f in fun.InParams) - { + foreach (Formal /*!*/ f in fun.InParams) { Contract.Assert(f != null); VCExprVar /*!*/ var = gen.Variable(f.Name, f.TypedIdent.Type); @@ -72,30 +67,26 @@ public static Function UniformBoogieFunction(string name, int arity, Type U) return arguments; } - public static List /*!*/ ToList(params T[] args) where T : class - { + public static List /*!*/ ToList(params T[] args) where T : class { Contract.Requires(cce.NonNullElements(args)); Contract.Ensures(cce.NonNullElements(Contract.Result>())); return new List(args); } - public static List /*!*/ ToVCExprList(List /*!*/ list) - { + public static List /*!*/ ToVCExprList(List /*!*/ list) { Contract.Requires(cce.NonNullElements(list)); Contract.Ensures(cce.NonNullElements(Contract.Result>())); return new List(list); } - public static List /*!*/ VarVector(string baseName, int num, Type type, VCExpressionGenerator gen) - { + public static List /*!*/ VarVector(string baseName, int num, Type type, VCExpressionGenerator gen) { Contract.Requires(gen != null); Contract.Requires(type != null); Contract.Requires(baseName != null); Contract.Ensures(cce.NonNullElements(Contract.Result>())); List /*!*/ res = new List(num); - for (int i = 0; i < num; ++i) - { + for (int i = 0; i < num; ++i) { res.Add(gen.Variable(baseName + i, type)); } @@ -103,16 +94,14 @@ public static Function UniformBoogieFunction(string name, int arity, Type U) } public static List /*!*/ - VarVector(string baseName, List /*!*/ types, VCExpressionGenerator gen) - { + VarVector(string baseName, List /*!*/ types, VCExpressionGenerator gen) { Contract.Requires(gen != null); Contract.Requires(baseName != null); Contract.Requires(cce.NonNullElements(types)); Contract.Ensures(cce.NonNullElements(Contract.Result>())); List /*!*/ res = new List(types.Count); - for (int i = 0; i < types.Count; ++i) - { + for (int i = 0; i < types.Count; ++i) { res.Add(gen.Variable(baseName + i, types[i])); } diff --git a/Source/VCExpr/TypeErasure/MapTypeAbstractionBuilder.cs b/Source/VCExpr/TypeErasure/MapTypeAbstractionBuilder.cs index 96f70e643..125a407fb 100644 --- a/Source/VCExpr/TypeErasure/MapTypeAbstractionBuilder.cs +++ b/Source/VCExpr/TypeErasure/MapTypeAbstractionBuilder.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; @@ -5,8 +6,7 @@ namespace Microsoft.Boogie.TypeErasure; [ContractClass(typeof(MapTypeAbstractionBuilderContracts))] -internal abstract class MapTypeAbstractionBuilder -{ +internal abstract class MapTypeAbstractionBuilder { protected readonly TypeAxiomBuilder /*!*/ AxBuilder; @@ -14,15 +14,13 @@ protected readonly VCExpressionGenerator /*!*/ Gen; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(AxBuilder != null); Contract.Invariant(Gen != null); } - internal MapTypeAbstractionBuilder(TypeAxiomBuilder axBuilder, VCExpressionGenerator gen) - { + internal MapTypeAbstractionBuilder(TypeAxiomBuilder axBuilder, VCExpressionGenerator gen) { Contract.Requires(gen != null); Contract.Requires(axBuilder != null); this.AxBuilder = axBuilder; @@ -33,8 +31,7 @@ internal MapTypeAbstractionBuilder(TypeAxiomBuilder axBuilder, VCExpressionGener // constructor for cloning internal MapTypeAbstractionBuilder(TypeAxiomBuilder axBuilder, VCExpressionGenerator gen, - MapTypeAbstractionBuilder builder) - { + MapTypeAbstractionBuilder builder) { Contract.Requires(builder != null); Contract.Requires(gen != null); Contract.Requires(axBuilder != null); @@ -55,17 +52,14 @@ private readonly List /*!*/ AbstractionVariables; [ContractInvariantMethod] - void AbstractionVariablesInvariantMethod() - { + void AbstractionVariablesInvariantMethod() { Contract.Invariant(cce.NonNullElements(AbstractionVariables)); } - private TypeVariable AbstractionVariable(int num) - { + private TypeVariable AbstractionVariable(int num) { Contract.Requires((num >= 0)); Contract.Ensures(Contract.Result() != null); - while (AbstractionVariables.Count <= num) - { + while (AbstractionVariables.Count <= num) { AbstractionVariables.Add(new TypeVariable(Token.NoToken, "aVar" + AbstractionVariables.Count)); } @@ -79,8 +73,7 @@ private TypeVariable AbstractionVariable(int num) // possibly contain free type variables. For each such class, a separate type // constructor and separate select/store functions are introduced. - protected struct MapTypeClassRepresentation - { + protected struct MapTypeClassRepresentation { public readonly TypeCtorDecl /*!*/ RepresentingType; @@ -91,16 +84,14 @@ public readonly Function /*!*/ Store; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(RepresentingType != null); Contract.Invariant(Select != null); Contract.Invariant(Store != null); } - public MapTypeClassRepresentation(TypeCtorDecl representingType, Function select, Function store) - { + public MapTypeClassRepresentation(TypeCtorDecl representingType, Function select, Function store) { Contract.Requires(store != null); Contract.Requires(select != null); Contract.Requires(representingType != null); @@ -114,16 +105,13 @@ public MapTypeClassRepresentation(TypeCtorDecl representingType, Function select ClassRepresentations; [ContractInvariantMethod] - void ClassRepresentationsInvariantMethod() - { + void ClassRepresentationsInvariantMethod() { Contract.Invariant(ClassRepresentations != null); } - protected MapTypeClassRepresentation GetClassRepresentation(MapType abstractedType) - { + protected MapTypeClassRepresentation GetClassRepresentation(MapType abstractedType) { Contract.Requires(abstractedType != null); - if (!ClassRepresentations.TryGetValue(abstractedType, out var res)) - { + if (!ClassRepresentations.TryGetValue(abstractedType, out var res)) { int num = ClassRepresentations.Count; TypeCtorDecl /*!*/ synonym = @@ -145,16 +133,14 @@ protected abstract void GenSelectStoreFunctions(MapType /*!*/ abstractedType, Ty /////////////////////////////////////////////////////////////////////////// - public Function Select(MapType rawType, out List instantiations) - { + public Function Select(MapType rawType, out List instantiations) { Contract.Requires((rawType != null)); Contract.Ensures(Contract.ValueAtReturn(out instantiations) != null); Contract.Ensures(Contract.Result() != null); return AbstractAndGetRepresentation(rawType, out instantiations).Select; } - public Function Store(MapType rawType, out List instantiations) - { + public Function Store(MapType rawType, out List instantiations) { Contract.Requires((rawType != null)); Contract.Ensures(Contract.ValueAtReturn(out instantiations) != null); Contract.Ensures(Contract.Result() != null); @@ -162,8 +148,7 @@ public Function Store(MapType rawType, out List instantiations) } private MapTypeClassRepresentation - AbstractAndGetRepresentation(MapType rawType, out List instantiations) - { + AbstractAndGetRepresentation(MapType rawType, out List instantiations) { Contract.Requires((rawType != null)); Contract.Ensures(Contract.ValueAtReturn(out instantiations) != null); instantiations = new List(); @@ -172,8 +157,7 @@ private MapTypeClassRepresentation return GetClassRepresentation(abstraction); } - public CtorType AbstractMapType(MapType rawType) - { + public CtorType AbstractMapType(MapType rawType) { Contract.Requires(rawType != null); Contract.Ensures(Contract.Result() != null); List /*!*/ @@ -187,15 +171,13 @@ public CtorType AbstractMapType(MapType rawType) } // TODO: cache the result of this operation - protected MapType ThinOutMapType(MapType rawType, List instantiations) - { + protected MapType ThinOutMapType(MapType rawType, List instantiations) { Contract.Requires(instantiations != null); Contract.Requires(rawType != null); Contract.Ensures(Contract.Result() != null); List /*!*/ newArguments = new List(); - foreach (Type /*!*/ subtype in rawType.Arguments.ToList()) - { + foreach (Type /*!*/ subtype in rawType.Arguments.ToList()) { Contract.Assert(subtype != null); newArguments.Add(ThinOutType(subtype, rawType.TypeParameters, instantiations)); @@ -208,15 +190,13 @@ protected MapType ThinOutMapType(MapType rawType, List instantiations) } // the instantiations of inserted type variables, the order corresponds to the order in which "AbstractionVariable(int)" delivers variables - private Type /*!*/ ThinOutType(Type rawType, List boundTypeParams, List instantiations) - { + private Type /*!*/ ThinOutType(Type rawType, List boundTypeParams, List instantiations) { Contract.Requires(instantiations != null); Contract.Requires(boundTypeParams != null); Contract.Requires(rawType != null); Contract.Ensures(Contract.Result() != null); - if (rawType.FreeVariables.All(var => !boundTypeParams.Contains(var))) - { + if (rawType.FreeVariables.All(var => !boundTypeParams.Contains(var))) { // Bingo! // if the type does not contain any bound variables, we can simply // replace it with a type variable @@ -227,8 +207,7 @@ protected MapType ThinOutMapType(MapType rawType, List instantiations) return abstractionVar; } - if (rawType.IsVariable) - { + if (rawType.IsVariable) { // // then the variable has to be bound, we cannot do anything TypeVariable /*!*/ @@ -236,26 +215,21 @@ protected MapType ThinOutMapType(MapType rawType, List instantiations) Contract.Assume(boundTypeParams.Contains(rawVar)); return rawVar; // - } - else if (rawType.IsMap) - { + } else if (rawType.IsMap) { // // recursively abstract this map type and continue abstracting CtorType /*!*/ abstraction = AbstractMapType(rawType.AsMap); return ThinOutType(abstraction, boundTypeParams, instantiations); // - } - else if (rawType.IsCtor) - { + } else if (rawType.IsCtor) { // // traverse the subtypes CtorType /*!*/ rawCtorType = rawType.AsCtor; List /*!*/ newArguments = new List(); - foreach (Type /*!*/ subtype in rawCtorType.Arguments.ToList()) - { + foreach (Type /*!*/ subtype in rawCtorType.Arguments.ToList()) { Contract.Assert(subtype != null); newArguments.Add(ThinOutType(subtype, boundTypeParams, instantiations)); @@ -263,11 +237,63 @@ protected MapType ThinOutMapType(MapType rawType, List instantiations) return new CtorType(Token.NoToken, rawCtorType.Decl, newArguments); // - } - else - { + } else { System.Diagnostics.Debug.Fail("Don't know how to handle this type: " + rawType); return rawType; // compiler appeasement policy } } +} + +internal struct TypeCtorRepr { + // function that represents the application of the type constructor + // to smaller types + public readonly Function /*!*/ + Ctor; + + // left-inverse functions that extract the subtypes of a compound type + public readonly List /*!*/ + Dtors; + + [ContractInvariantMethod] + void ObjectInvariant() { + Contract.Invariant(Ctor != null); + Contract.Invariant(cce.NonNullElements(Dtors)); + } + + + public TypeCtorRepr(Function ctor, List /*!*/ dtors) { + Contract.Requires(ctor != null); + Contract.Requires(cce.NonNullElements(dtors)); + Contract.Requires(ctor.InParams.Count == dtors.Count); + this.Ctor = ctor; + this.Dtors = dtors; + } +} + +////////////////////////////////////////////////////////////////////////////// +// Class for computing most general abstractions of map types. An abstraction +// of a map type t is a maptype t' in which closed proper subtypes have been replaced +// with type variables. E.g., an abstraction of [C a, int]a would be [C a, b]a. +// We subsequently consider most general abstractions as ordinary parametrised types, +// i.e., "[C a, b]a" would be considered as a type "M b" with polymorphically typed +// access functions +// +// select(M b, C a, b) returns (a) +// store(M b, C a, b, a) returns (M b) + +[ContractClassFor(typeof(MapTypeAbstractionBuilder))] +internal abstract class MapTypeAbstractionBuilderContracts : MapTypeAbstractionBuilder { + public MapTypeAbstractionBuilderContracts() + : base(null, null) { + } + + protected override void GenSelectStoreFunctions(MapType abstractedType, TypeCtorDecl synonymDecl, + out Function select, out Function store) { + Contract.Requires(abstractedType != null); + Contract.Requires(synonymDecl != null); + Contract.Ensures(Contract.ValueAtReturn(out select) != null); + Contract.Ensures(Contract.ValueAtReturn(out store) != null); + + throw new NotImplementedException(); + } } \ No newline at end of file diff --git a/Source/VCExpr/TypeErasure/OpTypeEraser.cs b/Source/VCExpr/TypeErasure/OpTypeEraser.cs index 98d10ccef..f3b3d5dd9 100644 --- a/Source/VCExpr/TypeErasure/OpTypeEraser.cs +++ b/Source/VCExpr/TypeErasure/OpTypeEraser.cs @@ -5,8 +5,7 @@ namespace Microsoft.Boogie.TypeErasure; -public abstract class OpTypeEraser : StandardVCExprOpVisitor -{ +public abstract class OpTypeEraser : StandardVCExprOpVisitor { protected readonly TypeAxiomBuilderIntBoolU /*!*/ AxBuilder; @@ -17,8 +16,7 @@ protected readonly VCExpressionGenerator /*!*/ Gen; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(AxBuilder != null); Contract.Invariant(Eraser != null); Contract.Invariant(Gen != null); @@ -26,8 +24,7 @@ void ObjectInvariant() public OpTypeEraser(TypeEraser /*!*/ eraser, TypeAxiomBuilderIntBoolU /*!*/ axBuilder, - VCExpressionGenerator /*!*/ gen) - { + VCExpressionGenerator /*!*/ gen) { Contract.Requires(eraser != null); Contract.Requires(axBuilder != null); Contract.Requires(gen != null); @@ -36,8 +33,7 @@ public OpTypeEraser(TypeEraser /*!*/ eraser, TypeAxiomBuilderIntBoolU /*!*/ axBu this.Gen = gen; } - protected override VCExpr StandardResult(VCExprNAry node, VariableBindings bindings) - { + protected override DynamicStack StandardResult(VCExprNAry node, VariableBindings bindings) { //Contract.Requires(bindings != null); //Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); @@ -46,82 +42,68 @@ protected override VCExpr StandardResult(VCExprNAry node, VariableBindings bindi throw new cce.UnreachableException(); // to please the compiler } - private List /*!*/ MutateSeq(VCExprNAry node, VariableBindings bindings, int newPolarity) - { + private async DynamicStack> /*!*/ MutateSeq(VCExprNAry node, VariableBindings bindings, int newPolarity) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(cce.NonNullElements(Contract.Result>())); int oldPolarity = Eraser.Polarity; Eraser.Polarity = newPolarity; - List /*!*/ - newArgs = Eraser.MutateSeq(node.Arguments, bindings); + List /*!*/ newArgs = await Eraser.MutateSeq(node.Arguments, bindings); Eraser.Polarity = oldPolarity; return newArgs; } - private VCExpr CastArguments(VCExprNAry node, Type argType, VariableBindings bindings, int newPolarity) - { + private async DynamicStack CastArguments(VCExprNAry node, Type argType, VariableBindings bindings, int newPolarity) { Contract.Requires(bindings != null); Contract.Requires(argType != null); Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); - return Gen.Function(node.Op, - AxBuilder.CastSeq(MutateSeq(node, bindings, newPolarity), - argType)); + return Gen.Function(node.Op, AxBuilder.CastSeq(await MutateSeq(node, bindings, newPolarity), argType)); } // Cast the arguments of the node to their old type if necessary and possible; otherwise use // their new type (int, real, bool, or U) - private VCExpr CastArgumentsToOldType(VCExprNAry node, VariableBindings bindings, int newPolarity) - { + private async DynamicStack CastArgumentsToOldType(VCExprNAry node, VariableBindings bindings, int newPolarity) { Contract.Requires(bindings != null); Contract.Requires(node != null); Contract.Requires((node.Arity > 0)); Contract.Ensures(Contract.Result() != null); - List /*!*/ - newArgs = MutateSeq(node, bindings, newPolarity); + List /*!*/ newArgs = await MutateSeq(node, bindings, newPolarity); Type /*!*/ oldType = node[0].Type; if (AxBuilder.UnchangedType(oldType) && - node.Arguments.Skip(1).All(e => e.Type.Equals(oldType))) - { + node.Arguments.Skip(1).All(e => e.Type.Equals(oldType))) { return Gen.Function(node.Op, AxBuilder.CastSeq(newArgs, oldType)); - } - else - { + } else { return Gen.Function(node.Op, AxBuilder.CastSeq(newArgs, AxBuilder.U)); } } /////////////////////////////////////////////////////////////////////////// - public override VCExpr VisitNotOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitNotOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArguments(node, Type.Bool, bindings, -Eraser.Polarity); } - public override VCExpr VisitEqOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitEqOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArgumentsToOldType(node, bindings, 0); } - public override VCExpr VisitNeqOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitNeqOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArgumentsToOldType(node, bindings, 0); } - public override VCExpr VisitImpliesOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitImpliesOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); @@ -132,28 +114,24 @@ public override VCExpr VisitImpliesOp(VCExprNAry node, VariableBindings bindings newArgs.Add(Eraser.Mutate(node[0], bindings)); Eraser.Polarity = -Eraser.Polarity; newArgs.Add(Eraser.Mutate(node[1], bindings)); - return Gen.Function(node.Op, AxBuilder.CastSeq(newArgs, Type.Bool)); + return DynamicStack.FromResult(Gen.Function(node.Op, AxBuilder.CastSeq(newArgs, Type.Bool))); } - public override VCExpr VisitDistinctOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitDistinctOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArgumentsToOldType(node, bindings, 0); } - public override VCExpr VisitIfThenElseOp(VCExprNAry node, VariableBindings bindings) - { + public override async DynamicStack VisitIfThenElseOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); - List /*!*/ - newArgs = MutateSeq(node, bindings, 0); + List /*!*/ newArgs = await MutateSeq(node, bindings, 0); newArgs[0] = AxBuilder.Cast(newArgs[0], Type.Bool); Type t = node.Type; - if (!AxBuilder.UnchangedType(t)) - { + if (!AxBuilder.UnchangedType(t)) { t = AxBuilder.U; } @@ -162,59 +140,51 @@ public override VCExpr VisitIfThenElseOp(VCExprNAry node, VariableBindings bindi return Gen.Function(node.Op, newArgs); } - public override VCExpr /*!*/ VisitCustomOp(VCExprNAry /*!*/ node, VariableBindings /*!*/ bindings) - { + public override async DynamicStack /*!*/ VisitCustomOp(VCExprNAry node /*!*/, VariableBindings bindings /*!*/) { Contract.Requires(node != null); Contract.Requires(bindings != null); Contract.Ensures(Contract.Result() != null); - List /*!*/ - newArgs = MutateSeq(node, bindings, 0); + List /*!*/ newArgs = await MutateSeq(node, bindings, 0); return Gen.Function(node.Op, newArgs); } - public override VCExpr VisitAddOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitAddOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArguments(node, node.Type, bindings, 0); } - public override VCExpr VisitSubOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitSubOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArguments(node, node.Type, bindings, 0); } - public override VCExpr VisitMulOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitMulOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArguments(node, node.Type, bindings, 0); } - public override VCExpr VisitDivOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitDivOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArguments(node, Type.Int, bindings, 0); } - public override VCExpr VisitModOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitModOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArguments(node, Type.Int, bindings, 0); } - public override VCExpr VisitRealDivOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitRealDivOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); @@ -228,173 +198,151 @@ public override VCExpr VisitRealDivOp(VCExprNAry node, VariableBindings bindings Contract.Ensures(Contract.Result() != null); return CastArguments(node, Type.Float, bindings, 0); }*/ - public override VCExpr VisitPowOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitPowOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArguments(node, Type.Real, bindings, 0); } - public override VCExpr VisitLtOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitLtOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArgumentsToOldType(node, bindings, 0); } - public override VCExpr VisitLeOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitLeOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArgumentsToOldType(node, bindings, 0); } - public override VCExpr VisitGtOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitGtOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArgumentsToOldType(node, bindings, 0); } - public override VCExpr VisitGeOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitGeOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArgumentsToOldType(node, bindings, 0); } - public override VCExpr VisitSubtypeOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitSubtypeOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArguments(node, AxBuilder.U, bindings, 0); } - public override VCExpr VisitToIntOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitToIntOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArgumentsToOldType(node, bindings, 0); } - public override VCExpr VisitToRealOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitToRealOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArgumentsToOldType(node, bindings, 0); } - public override VCExpr VisitFloatAddOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitFloatAddOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArgumentsToOldType(node, bindings, 0); } - public override VCExpr VisitFloatSubOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitFloatSubOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArgumentsToOldType(node, bindings, 0); } - public override VCExpr VisitFloatMulOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitFloatMulOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArgumentsToOldType(node, bindings, 0); } - public override VCExpr VisitFloatDivOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitFloatDivOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArgumentsToOldType(node, bindings, 0); } - public override VCExpr VisitFloatLeqOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitFloatLeqOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArgumentsToOldType(node, bindings, 0); } - public override VCExpr VisitFloatLtOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitFloatLtOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArgumentsToOldType(node, bindings, 0); } - public override VCExpr VisitFloatGeqOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitFloatGeqOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArgumentsToOldType(node, bindings, 0); } - public override VCExpr VisitFloatGtOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitFloatGtOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArgumentsToOldType(node, bindings, 0); } - public override VCExpr VisitFloatEqOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitFloatEqOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArgumentsToOldType(node, bindings, 0); } - public override VCExpr VisitFloatNeqOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitFloatNeqOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArgumentsToOldType(node, bindings, 0); } - public override VCExpr VisitBvOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitBvOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); return CastArgumentsToOldType(node, bindings, 0); } - public override VCExpr VisitBvExtractOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitBvExtractOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires(bindings != null); Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); return CastArgumentsToOldType(node, bindings, 0); } - public override VCExpr VisitBvConcatOp(VCExprNAry node, VariableBindings bindings) - { + public override async DynamicStack VisitBvConcatOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); - List /*!*/ - newArgs = MutateSeq(node, bindings, 0); + List /*!*/ newArgs = await MutateSeq(node, bindings, 0); // each argument is cast to its old type Contract.Assert(newArgs.Count == node.Arity && newArgs.Count == 2); diff --git a/Source/VCExpr/TypeErasure/TypeAxiomBuilder.cs b/Source/VCExpr/TypeErasure/TypeAxiomBuilder.cs index 8a96a9d9c..459e2cd1b 100644 --- a/Source/VCExpr/TypeErasure/TypeAxiomBuilder.cs +++ b/Source/VCExpr/TypeErasure/TypeAxiomBuilder.cs @@ -6,15 +6,19 @@ namespace Microsoft.Boogie.TypeErasure; +// The class responsible for creating and keeping track of all +// axioms related to the type system. This abstract class is made +// concrete in two subclasses, one for type erasure with type +// premisses in quantifiers (the semantic approach), and one for +// type erasure with explicit type arguments of polymorphic +// functions (the syntactic approach). [ContractClass(typeof(TypeAxiomBuilderContracts))] -public abstract class TypeAxiomBuilder : ICloneable -{ +public abstract class TypeAxiomBuilder : ICloneable { protected readonly VCExpressionGenerator /*!*/ Gen; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(Gen != null); Contract.Invariant(Ctor != null); } @@ -30,8 +34,7 @@ private readonly List /*!*/ AllTypeAxioms; [ContractInvariantMethod] - void AllTypeAxiomsInvariantMethod() - { + void AllTypeAxiomsInvariantMethod() { Contract.Invariant(cce.NonNullElements(AllTypeAxioms)); } @@ -40,13 +43,11 @@ private readonly List /*!*/ IncTypeAxioms; [ContractInvariantMethod] - void IncTypeAxiomsInvariantMethod() - { + void IncTypeAxiomsInvariantMethod() { Contract.Invariant(cce.NonNullElements(IncTypeAxioms)); } - internal void AddTypeAxiom(VCExpr axiom) - { + internal void AddTypeAxiom(VCExpr axiom) { Contract.Requires(axiom != null); AllTypeAxioms.Add(axiom); IncTypeAxioms.Add(axiom); @@ -54,8 +55,7 @@ internal void AddTypeAxiom(VCExpr axiom) // Return all axioms that were added since the last time NewAxioms // was called - public VCExpr GetNewAxioms() - { + public VCExpr GetNewAxioms() { Contract.Ensures(Contract.Result() != null); VCExpr /*!*/ res = Gen.NAry(VCExpressionGenerator.AndOp, IncTypeAxioms); @@ -69,8 +69,7 @@ private readonly Function /*!*/ private BigNum CurrentCtorNum; - private VCExpr GenCtorAssignment(VCExpr typeRepr) - { + private VCExpr GenCtorAssignment(VCExpr typeRepr) { Contract.Requires(typeRepr != null); Contract.Ensures(Contract.Result() != null); @@ -80,8 +79,7 @@ private VCExpr GenCtorAssignment(VCExpr typeRepr) return res; } - private VCExpr GenCtorAssignment(Function typeRepr) - { + private VCExpr GenCtorAssignment(Function typeRepr) { Contract.Requires(typeRepr != null); Contract.Ensures(Contract.Result() != null); @@ -92,8 +90,7 @@ private VCExpr GenCtorAssignment(Function typeRepr) GenCtorAssignment(Gen.Function(typeRepr, HelperFuns.ToVCExprList(quantifiedVars))); - if (typeRepr.InParams.Count == 0) - { + if (typeRepr.InParams.Count == 0) { return eq; } @@ -102,8 +99,7 @@ private VCExpr GenCtorAssignment(Function typeRepr) } // generate an axiom (forall x0, x1, ... :: invFun(fun(x0, x1, ...) == xi) - protected VCExpr GenLeftInverseAxiom(Function fun, Function invFun, int dtorNum) - { + protected VCExpr GenLeftInverseAxiom(Function fun, Function invFun, int dtorNum) { Contract.Requires(invFun != null); Contract.Requires(fun != null); Contract.Ensures(Contract.Result() != null); @@ -130,8 +126,7 @@ protected VCExpr GenLeftInverseAxiom(Function fun, Function invFun, int dtorNum) // the type of everything that is not int, bool, or a type [ContractInvariantMethod] - void ObjectInvariant2() - { + void ObjectInvariant2() { Contract.Invariant(UDecl != null); Contract.Invariant(TDecl != null); Contract.Invariant(U != null); @@ -163,18 +158,15 @@ public readonly Type /*!*/ BasicTypeReprs; [ContractInvariantMethod] - void BasicTypeReprsInvariantMethod() - { + void BasicTypeReprsInvariantMethod() { Contract.Invariant(cce.NonNullDictionaryAndValues(BasicTypeReprs)); } - private VCExpr GetBasicTypeRepr(Type type) - { + private VCExpr GetBasicTypeRepr(Type type) { Contract.Requires(type != null); Contract.Requires(type.IsBasic || type.IsBv || type.IsFloat); Contract.Ensures(Contract.Result() != null); - if (!BasicTypeReprs.TryGetValue(type, out var res)) - { + if (!BasicTypeReprs.TryGetValue(type, out var res)) { res = Gen.Function(HelperFuns.BoogieFunction(type.ToString() + "Type", T)); AddTypeAxiom(GenCtorAssignment(res)); BasicTypeReprs.Add(type, res); @@ -187,16 +179,13 @@ private VCExpr GetBasicTypeRepr(Type type) TypeCtorReprs; [ContractInvariantMethod] - void TypeCtorReprsInvariantMethod() - { + void TypeCtorReprsInvariantMethod() { Contract.Invariant(TypeCtorReprs != null); } - internal TypeCtorRepr GetTypeCtorReprStruct(TypeCtorDecl decl) - { + internal TypeCtorRepr GetTypeCtorReprStruct(TypeCtorDecl decl) { Contract.Requires(decl != null); - if (!TypeCtorReprs.TryGetValue(decl, out var reprSet)) - { + if (!TypeCtorReprs.TryGetValue(decl, out var reprSet)) { Function /*!*/ ctor = HelperFuns.UniformBoogieFunction(decl.Name + "Type", decl.Arity, T); Contract.Assert(ctor != null); @@ -204,8 +193,7 @@ internal TypeCtorRepr GetTypeCtorReprStruct(TypeCtorDecl decl) List /*!*/ dtors = new List(decl.Arity); - for (int i = 0; i < decl.Arity; ++i) - { + for (int i = 0; i < decl.Arity; ++i) { Function /*!*/ dtor = HelperFuns.UniformBoogieFunction(decl.Name + "TypeInv" + i, 1, T); dtors.Add(dtor); @@ -219,15 +207,13 @@ internal TypeCtorRepr GetTypeCtorReprStruct(TypeCtorDecl decl) return reprSet; } - public Function GetTypeCtorRepr(TypeCtorDecl decl) - { + public Function GetTypeCtorRepr(TypeCtorDecl decl) { Contract.Requires(decl != null); Contract.Ensures(Contract.Result() != null); return GetTypeCtorReprStruct(decl).Ctor; } - public Function GetTypeDtor(TypeCtorDecl decl, int num) - { + public Function GetTypeDtor(TypeCtorDecl decl, int num) { Contract.Requires(decl != null); Contract.Ensures(Contract.Result() != null); return GetTypeCtorReprStruct(decl).Dtors[num]; @@ -238,17 +224,14 @@ public Function GetTypeDtor(TypeCtorDecl decl, int num) TypeVariableMapping; [ContractInvariantMethod] - void TypeVariableMappingInvariantMethod() - { + void TypeVariableMappingInvariantMethod() { Contract.Invariant(cce.NonNullDictionaryAndValues(TypeVariableMapping)); } - public VCExprVar Typed2Untyped(TypeVariable var) - { + public VCExprVar Typed2Untyped(TypeVariable var) { Contract.Requires(var != null); Contract.Ensures(Contract.Result() != null); - if (!TypeVariableMapping.TryGetValue(var, out var res)) - { + if (!TypeVariableMapping.TryGetValue(var, out var res)) { res = new VCExprVar(var.Name, T); TypeVariableMapping.Add(var, res); } @@ -265,19 +248,16 @@ public VCExprVar Typed2Untyped(TypeVariable var) Typed2UntypedVariables; [ContractInvariantMethod] - void Typed2UntypedVariablesInvariantMethod() - { + void Typed2UntypedVariablesInvariantMethod() { Contract.Invariant(cce.NonNullDictionaryAndValues(Typed2UntypedVariables)); } // This method must only be used for free (unbound) variables - public VCExprVar Typed2Untyped(VCExprVar var) - { + public VCExprVar Typed2Untyped(VCExprVar var) { Contract.Requires(var != null); Contract.Ensures(Contract.Result() != null); VCExprVar res = TryTyped2Untyped(var); - if (res == null) - { + if (res == null) { res = Gen.Variable(var.Name, TypeAfterErasure(var.Type)); Typed2UntypedVariables.Add(var, res); AddVarTypeAxiom(res, var.Type); @@ -293,15 +273,11 @@ public VCExprVar Typed2Untyped(VCExprVar var) /// /// /// - public VCExprVar TryTyped2Untyped(VCExprVar var) - { + public VCExprVar TryTyped2Untyped(VCExprVar var) { Contract.Requires(var != null); - if (Typed2UntypedVariables.TryGetValue(var, out var res)) - { + if (Typed2UntypedVariables.TryGetValue(var, out var res)) { return res; - } - else - { + } else { return null; } } @@ -311,40 +287,32 @@ public VCExprVar TryTyped2Untyped(VCExprVar var) /////////////////////////////////////////////////////////////////////////// // Translation function from types to their term representation - public VCExpr Type2Term(Type type, IDictionary /*!*/ varMapping) - { + public VCExpr Type2Term(Type type, IDictionary /*!*/ varMapping) { Contract.Requires(type != null); Contract.Requires(cce.NonNullDictionaryAndValues(varMapping)); Contract.Ensures(Contract.Result() != null); // - if (type.IsBasic || type.IsBv || type.IsFloat) - { + if (type.IsBasic || type.IsBv || type.IsFloat) { // return GetBasicTypeRepr(type); // - } - else if (type.IsCtor) - { + } else if (type.IsCtor) { // CtorType ctype = type.AsCtor; Function /*!*/ repr = GetTypeCtorRepr(ctype.Decl); List /*!*/ args = new List(ctype.Arguments.Count); - foreach (Type /*!*/ t in ctype.Arguments.ToArray()) - { + foreach (Type /*!*/ t in ctype.Arguments.ToArray()) { Contract.Assert(t != null); args.Add(Type2Term(t, varMapping)); } return Gen.Function(repr, args); // - } - else if (type.IsVariable) - { + } else if (type.IsVariable) { // - if (!varMapping.TryGetValue(type.AsVariable, out var res)) - { + if (!varMapping.TryGetValue(type.AsVariable, out var res)) { // then the variable is free and we bind it at this point to a term // variable res = Typed2Untyped(type.AsVariable); @@ -352,15 +320,11 @@ public VCExpr Type2Term(Type type, IDictionary return cce.NonNull(res); // - } - else if (type.IsMap) - { + } else if (type.IsMap) { // return Type2Term(MapTypeAbstracter.AbstractMapType(type.AsMap), varMapping); // - } - else - { + } else { System.Diagnostics.Debug.Fail("Don't know how to handle this type: " + type); Contract.Assert(false); throw new cce.UnreachableException(); // please the compiler @@ -369,8 +333,7 @@ public VCExpr Type2Term(Type type, IDictionary //////////////////////////////////////////////////////////////////////////// - public TypeAxiomBuilder(VCExpressionGenerator gen) - { + public TypeAxiomBuilder(VCExpressionGenerator gen) { Contract.Requires(gen != null); this.Gen = gen; AllTypeAxioms = new List(); @@ -398,16 +361,14 @@ public TypeAxiomBuilder(VCExpressionGenerator gen) Ctor = HelperFuns.BoogieFunction("Ctor", t, Type.Int); } - public virtual void Setup(List usedTypes) - { + public virtual void Setup(List usedTypes) { foreach (var ty in usedTypes) { GetBasicTypeRepr(ty); } } // constructor to allow cloning - internal TypeAxiomBuilder(TypeAxiomBuilder builder) - { + internal TypeAxiomBuilder(TypeAxiomBuilder builder) { Contract.Requires(builder != null); Gen = builder.Gen; AllTypeAxioms = new List(builder.AllTypeAxioms); @@ -432,6 +393,291 @@ internal TypeAxiomBuilder(TypeAxiomBuilder builder) } public abstract Object /*!*/ Clone(); - + public abstract VCExpr Cast(VCExpr expr, Type toType); +} + +// Subclass of the TypeAxiomBuilder that provides all functionality +// to deal with native sorts of a theorem prover (that are the only +// types left after erasing all other types). Currently, these are: +// +// U ... sort of all individuals/objects/values +// T ... sort of all types +// int ... integers +// bool ... booleans + +[ContractClass(typeof(TypeAxiomBuilderIntBoolUContracts))] +public abstract class TypeAxiomBuilderIntBoolU : TypeAxiomBuilder { + public TypeAxiomBuilderIntBoolU(VCExpressionGenerator gen) + : base(gen) { + Contract.Requires(gen != null); + + TypeCasts = new Dictionary(); + } + + // constructor to allow cloning + internal TypeAxiomBuilderIntBoolU(TypeAxiomBuilderIntBoolU builder) + : base(builder) { + Contract.Requires(builder != null); + + TypeCasts = new Dictionary(builder.TypeCasts); + } + + public override void Setup(List usedTypes) { + base.Setup(usedTypes); + + foreach (var ty in usedTypes) { + GetTypeCasts(ty); + } + } + + // generate inverse axioms for casts (castToU(castFromU(x)) = x, under certain premisses) + protected abstract VCExpr /*!*/ GenReverseCastAxiom(Function /*!*/ castToU, Function /*!*/ castFromU); + + protected VCExpr GenReverseCastEq(Function castToU, Function castFromU, out VCExprVar var, + out List /*!*/ triggers) { + Contract.Requires((castFromU != null)); + Contract.Requires((castToU != null)); + Contract.Ensures((cce.NonNullElements(Contract.ValueAtReturn(out triggers)))); + Contract.Ensures(Contract.ValueAtReturn(out var) != null); + Contract.Ensures(Contract.Result() != null); + var = Gen.Variable("x", U); + + VCExpr inner = Gen.Function(castFromU, var); + VCExpr lhs = Gen.Function(castToU, inner); + triggers = HelperFuns.ToList(Gen.Trigger(true, HelperFuns.ToList(inner))); + + return Gen.Eq(lhs, var); + } + + protected abstract VCExpr /*!*/ GenCastTypeAxioms(Function /*!*/ castToU, Function /*!*/ castFromU); + + /////////////////////////////////////////////////////////////////////////// + // storage of type casts for types that are supposed to be left over in the + // VCs (like int, bool, bitvectors) + + private readonly IDictionary /*!*/ + TypeCasts; + + [ContractInvariantMethod] + void TypeCastsInvariantMethod() { + Contract.Invariant(TypeCasts != null); + } + + private TypeCastSet GetTypeCasts(Type type) { + Contract.Requires(type != null); + if (!TypeCasts.TryGetValue(type, out var res)) { + Function /*!*/ + castToU = HelperFuns.BoogieFunction(type.ToString() + "_2_U", type, U); + Function /*!*/ + castFromU = HelperFuns.BoogieFunction("U_2_" + type.ToString(), U, type); + + AddTypeAxiom(GenLeftInverseAxiom(castToU, castFromU, 0)); + AddTypeAxiom(GenReverseCastAxiom(castToU, castFromU)); + AddTypeAxiom(GenCastTypeAxioms(castToU, castFromU)); + + res = new TypeCastSet(castToU, castFromU); + TypeCasts.Add(type, res); + } + + return res; + } + + [Pure] + public Function CastTo(Type type) { + Contract.Requires(type != null); + Contract.Requires(UnchangedType(type)); + Contract.Ensures(Contract.Result() != null); + return GetTypeCasts(type).CastFromU; + } + + public Function CastFrom(Type type) { + Contract.Requires(type != null); + Contract.Requires((UnchangedType(type))); + Contract.Ensures(Contract.Result() != null); + return GetTypeCasts(type).CastToU; + } + + private struct TypeCastSet { + public readonly Function /*!*/ + CastToU; + + public readonly Function /*!*/ + CastFromU; + + [ContractInvariantMethod] + void ObjectInvariant() { + Contract.Invariant(CastToU != null); + Contract.Invariant(CastFromU != null); + } + + + public TypeCastSet(Function castToU, Function castFromU) { + Contract.Requires(castFromU != null); + Contract.Requires(castToU != null); + CastToU = castToU; + CastFromU = castFromU; + } + } + + public bool IsCast(Function fun) { + Contract.Requires(fun != null); + if (fun.InParams.Count != 1) { + return false; + } + + Type /*!*/ + inType = cce.NonNull(fun.InParams[0]).TypedIdent.Type; + if (inType.Equals(U)) { + Type /*!*/ + outType = cce.NonNull(fun.OutParams[0]).TypedIdent.Type; + if (!TypeCasts.ContainsKey(outType)) { + return false; + } + + return fun.Equals(CastTo(outType)); + } else { + if (!TypeCasts.ContainsKey(inType)) { + return false; + } + + Type /*!*/ + outType = cce.NonNull(fun.OutParams[0]).TypedIdent.Type; + if (!outType.Equals(U)) { + return false; + } + + return fun.Equals(CastFrom(inType)); + } + } + + //////////////////////////////////////////////////////////////////////////// + + // the only types that we allow in "untyped" expressions are U, + // Type.Int, Type.Real, Type.Bool, and Type.RMode + + public override Type TypeAfterErasure(Type type) { + //Contract.Requires(type != null); + Contract.Ensures(Contract.Result() != null); + if (UnchangedType(type)) { + // these types are kept + return type; + } else { + // all other types are replaced by U + return U; + } + } + + [Pure] + public override bool UnchangedType(Type type) { + //Contract.Requires(type != null); + return type.IsInt || type.IsReal || type.IsBool || type.IsBv || type.IsFloat || type.IsRMode || type.IsString || + type.IsRegEx; + } + + public override VCExpr Cast(VCExpr expr, Type toType) { + Contract.Requires(toType != null); + Contract.Requires(expr != null); + Contract.Requires((expr.Type.Equals(U) || UnchangedType(expr.Type))); + Contract.Requires((toType.Equals(U) || UnchangedType(toType))); + Contract.Ensures(Contract.Result() != null); + if (expr.Type.Equals(toType)) { + return expr; + } + + if (toType.Equals(U)) { + return Gen.Function(CastFrom(expr.Type), expr); + } else { + Contract.Assert(expr.Type.Equals(U)); + return Gen.Function(CastTo(toType), expr); + } + } + + public List /*!*/ CastSeq(List /*!*/ exprs, Type toType) { + Contract.Requires(toType != null); + Contract.Requires(cce.NonNullElements(exprs)); + Contract.Ensures(cce.NonNullElements(Contract.Result>())); + List /*!*/ + res = new List(exprs.Count); + foreach (VCExpr /*!*/ expr in exprs) { + Contract.Assert(expr != null); + res.Add(Cast(expr, toType)); + } + + return res; + } +} + +[ContractClassFor(typeof(TypeAxiomBuilderIntBoolU))] +public abstract class TypeAxiomBuilderIntBoolUContracts : TypeAxiomBuilderIntBoolU { + public TypeAxiomBuilderIntBoolUContracts() + : base((TypeAxiomBuilderIntBoolU)null) { + } + + protected override VCExpr GenReverseCastAxiom(Function castToU, Function castFromU) { + Contract.Requires(castToU != null); + Contract.Requires(castFromU != null); + Contract.Ensures(Contract.Result() != null); + + throw new NotImplementedException(); + } + + protected override VCExpr GenCastTypeAxioms(Function castToU, Function castFromU) { + Contract.Requires(castFromU != null); + Contract.Requires(castToU != null); + Contract.Ensures(Contract.Result() != null); + + throw new NotImplementedException(); + } + + internal override MapTypeAbstractionBuilder MapTypeAbstracter { + get { throw new NotImplementedException(); } + } + + protected override void AddVarTypeAxiom(VCExprVar var, Type originalType) { + throw new NotImplementedException(); + } + + public override object Clone() { + throw new NotImplementedException(); + } +} + + +[ContractClassFor(typeof(TypeAxiomBuilder))] +public abstract class TypeAxiomBuilderContracts : TypeAxiomBuilder { + public TypeAxiomBuilderContracts() + : base((VCExpressionGenerator)null) { + } + + internal override MapTypeAbstractionBuilder MapTypeAbstracter { + get { + Contract.Ensures(Contract.Result() != null); + throw new NotImplementedException(); + } + } + + public override Type TypeAfterErasure(Type type) { + Contract.Requires(type != null); + Contract.Ensures(Contract.Result() != null); + + throw new NotImplementedException(); + } + + public override bool UnchangedType(Type type) { + Contract.Requires(type != null); + throw new NotImplementedException(); + } + + protected override void AddVarTypeAxiom(VCExprVar var, Type originalType) { + Contract.Requires(var != null); + Contract.Requires(originalType != null); + throw new NotImplementedException(); + } + + public override object Clone() { + Contract.Ensures(Contract.Result() != null); + + throw new NotImplementedException(); + } } \ No newline at end of file diff --git a/Source/VCExpr/TypeErasure/TypeEraser.cs b/Source/VCExpr/TypeErasure/TypeEraser.cs index b5818305b..99775188e 100644 --- a/Source/VCExpr/TypeErasure/TypeEraser.cs +++ b/Source/VCExpr/TypeErasure/TypeEraser.cs @@ -1,18 +1,21 @@ using System.Collections.Generic; using System.Diagnostics.Contracts; +using System.Threading; +using System.Threading.Tasks; using Microsoft.Boogie.VCExprAST; namespace Microsoft.Boogie.TypeErasure; +// The central class for turning types VCExprs into untyped +// VCExprs. This class makes use of the type axiom builder to manage +// the available types and symbols. [ContractClass(typeof(TypeEraserContracts))] -public abstract class TypeEraser : MutatingVCExprVisitor -{ +public abstract class TypeEraser : MutatingVCExprVisitor { protected readonly TypeAxiomBuilderIntBoolU /*!*/ AxBuilder; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(AxBuilder != null); } @@ -22,15 +25,13 @@ void ObjectInvariant() //////////////////////////////////////////////////////////////////////////// public TypeEraser(TypeAxiomBuilderIntBoolU axBuilder, VCExpressionGenerator gen) - : base(gen) - { + : base(gen) { Contract.Requires(gen != null); Contract.Requires(axBuilder != null); AxBuilder = axBuilder; } - public VCExpr Erase(VCExpr expr, int polarity) - { + public VCExpr Erase(VCExpr expr, int polarity) { Contract.Requires(expr != null); Contract.Requires((polarity >= -1 && polarity <= 1)); Contract.Ensures(Contract.Result() != null); @@ -42,8 +43,7 @@ public VCExpr Erase(VCExpr expr, int polarity) //////////////////////////////////////////////////////////////////////////// - public override VCExpr Visit(VCExprLiteral node, VariableBindings bindings) - { + public override VCExpr Visit(VCExprLiteral node, VariableBindings bindings) { Contract.Requires(bindings != null); Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); @@ -54,21 +54,14 @@ public override VCExpr Visit(VCExprLiteral node, VariableBindings bindings) //////////////////////////////////////////////////////////////////////////// - public override bool AvoidVisit(VCExprNAry node, VariableBindings arg) - { - return node.Op.Equals(VCExpressionGenerator.AndOp) || - node.Op.Equals(VCExpressionGenerator.OrOp); - } - public override VCExpr Visit(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack Visit(VCExprNAry node, VariableBindings bindings) { Contract.Requires(bindings != null); Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); VCExprOp /*!*/ op = node.Op; - if (op == VCExpressionGenerator.AndOp || op == VCExpressionGenerator.OrOp) - { + if (op == VCExpressionGenerator.AndOp || op == VCExpressionGenerator.OrOp) { // more efficient on large conjunctions/disjunctions return base.Visit(node, bindings); } @@ -79,8 +72,7 @@ public override VCExpr Visit(VCExprNAry node, VariableBindings bindings) // this method is called by MutatingVCExprVisitor.Visit(VCExprNAry, ...) protected override VCExpr /*!*/ UpdateModifiedNode(VCExprNAry /*!*/ originalNode, - List /*!*/ newSubExprs, bool changed, VariableBindings /*!*/ bindings) - { + List /*!*/ newSubExprs, bool changed, VariableBindings /*!*/ bindings) { //Contract.Requires(originalNode != null); //Contract.Requires(cce.NonNullElements(newSubExprs)); //Contract.Requires(bindings != null); @@ -93,13 +85,11 @@ public override VCExpr Visit(VCExprNAry node, VariableBindings bindings) //////////////////////////////////////////////////////////////////////////// - public override VCExpr Visit(VCExprVar node, VariableBindings bindings) - { + public override VCExpr Visit(VCExprVar node, VariableBindings bindings) { Contract.Requires(bindings != null); Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); - if (!bindings.VCExprVarBindings.TryGetValue(node, out var res)) - { + if (!bindings.VCExprVarBindings.TryGetValue(node, out var res)) { return AxBuilder.Typed2Untyped(node); } @@ -108,8 +98,7 @@ public override VCExpr Visit(VCExprVar node, VariableBindings bindings) //////////////////////////////////////////////////////////////////////////// - protected bool IsUniversalQuantifier(VCExprQuantifier node) - { + protected bool IsUniversalQuantifier(VCExprQuantifier node) { Contract.Requires(node != null); return Polarity == 1 && node.Quan == Quantifier.EX || Polarity == -1 && node.Quan == Quantifier.ALL; @@ -118,16 +107,14 @@ protected bool IsUniversalQuantifier(VCExprQuantifier node) protected List /*!*/ BoundVarsAfterErasure(List /*!*/ oldBoundVars, // the mapping between old and new variables // is added to this bindings-object - VariableBindings /*!*/ bindings) - { + VariableBindings /*!*/ bindings) { Contract.Requires(bindings != null); Contract.Requires(cce.NonNullElements(oldBoundVars)); Contract.Ensures(cce.NonNullElements(Contract.Result>())); List /*!*/ newBoundVars = new List(oldBoundVars.Count); - foreach (VCExprVar /*!*/ var in oldBoundVars) - { + foreach (VCExprVar /*!*/ var in oldBoundVars) { Type /*!*/ newType = AxBuilder.TypeAfterErasure(var.Type); VCExprVar /*!*/ @@ -151,8 +138,7 @@ protected bool RedoQuantifier(VCExprQuantifier /*!*/ node, List /*!*/ occurringVars, VariableBindings /*!*/ oldBindings, out VariableBindings /*!*/ newBindings, - out List /*!*/ newBoundVars) - { + out List /*!*/ newBoundVars) { Contract.Requires(node != null); Contract.Requires(newNode != null); Contract.Requires(cce.NonNullElements(occurringVars)); @@ -161,8 +147,7 @@ protected bool RedoQuantifier(VCExprQuantifier /*!*/ node, Contract.Ensures(cce.NonNullElements(Contract.ValueAtReturn(out newBoundVars))); List castVariables = VariableCastCollector.FindCastVariables(node, newNode, AxBuilder); - if (castVariables.Count == 0) - { + if (castVariables.Count == 0) { newBindings = oldBindings; // to make the compiler happy newBoundVars = newNode.BoundVars; // to make the compiler happy return false; @@ -172,8 +157,7 @@ protected bool RedoQuantifier(VCExprQuantifier /*!*/ node, newBindings = oldBindings.Clone(); newBoundVars = new List(node.BoundVars.Count); - foreach (VCExprVar /*!*/ var in node.BoundVars) - { + foreach (VCExprVar /*!*/ var in node.BoundVars) { Contract.Assert(var != null); Type /*!*/ newType = @@ -193,8 +177,7 @@ protected bool RedoQuantifier(VCExprQuantifier /*!*/ node, //////////////////////////////////////////////////////////////////////////// - public override VCExpr Visit(VCExprLet node, VariableBindings bindings) - { + public override DynamicStack Visit(VCExprLet node, VariableBindings bindings) { Contract.Requires(bindings != null); Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); @@ -203,8 +186,7 @@ public override VCExpr Visit(VCExprLet node, VariableBindings bindings) List /*!*/ newBoundVars = new List(node.BoundVars.Count); - foreach (VCExprVar /*!*/ var in node.BoundVars) - { + foreach (VCExprVar /*!*/ var in node.BoundVars) { Type /*!*/ newType = AxBuilder.TypeAfterErasure(var.Type); VCExprVar /*!*/ @@ -215,8 +197,7 @@ public override VCExpr Visit(VCExprLet node, VariableBindings bindings) List /*!*/ newbindings = new List(node.Length); - for (int i = 0; i < node.Length; ++i) - { + for (int i = 0; i < node.Length; ++i) { VCExprLetBinding /*!*/ binding = node[i]; Contract.Assert(binding != null); @@ -232,6 +213,6 @@ public override VCExpr Visit(VCExprLet node, VariableBindings bindings) VCExpr /*!*/ newbody = Mutate(node.Body, newVarBindings); - return Gen.Let(newbindings, newbody); + return DynamicStack.FromResult(Gen.Let(newbindings, newbody)); } } \ No newline at end of file diff --git a/Source/VCExpr/TypeErasure/TypeEraserContracts.cs b/Source/VCExpr/TypeErasure/TypeEraserContracts.cs index b1441e931..91a08bfa6 100644 --- a/Source/VCExpr/TypeErasure/TypeEraserContracts.cs +++ b/Source/VCExpr/TypeErasure/TypeEraserContracts.cs @@ -4,17 +4,13 @@ namespace Microsoft.Boogie.TypeErasure; [ContractClassFor(typeof(TypeEraser))] -public abstract class TypeEraserContracts : TypeEraser -{ +public abstract class TypeEraserContracts : TypeEraser { public TypeEraserContracts() - : base(null, null) - { + : base(null, null) { } - protected override OpTypeEraser OpEraser - { - get - { + protected override OpTypeEraser OpEraser { + get { Contract.Ensures(Contract.Result() != null); throw new NotImplementedException(); } diff --git a/Source/VCExpr/TypeErasure/TypeErasure.cs b/Source/VCExpr/TypeErasure/TypeErasure.cs deleted file mode 100644 index e9f7a9128..000000000 --- a/Source/VCExpr/TypeErasure/TypeErasure.cs +++ /dev/null @@ -1,433 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using Microsoft.Boogie.VCExprAST; - -// different classes for erasing complex types in VCExprs, replacing them -// with axioms that can be handled by theorem provers and SMT solvers - -namespace Microsoft.Boogie.TypeErasure -{ - // some functionality that is needed in many places (and that should - // really be provided by the Spec# container classes; maybe one - // could integrate the functions in a nicer way?) - - ////////////////////////////////////////////////////////////////////////////// - - internal struct TypeCtorRepr - { - // function that represents the application of the type constructor - // to smaller types - public readonly Function /*!*/ - Ctor; - - // left-inverse functions that extract the subtypes of a compound type - public readonly List /*!*/ - Dtors; - - [ContractInvariantMethod] - void ObjectInvariant() - { - Contract.Invariant(Ctor != null); - Contract.Invariant(cce.NonNullElements(Dtors)); - } - - - public TypeCtorRepr(Function ctor, List /*!*/ dtors) - { - Contract.Requires(ctor != null); - Contract.Requires(cce.NonNullElements(dtors)); - Contract.Requires(ctor.InParams.Count == dtors.Count); - this.Ctor = ctor; - this.Dtors = dtors; - } - } - - ////////////////////////////////////////////////////////////////////////////// - - // The class responsible for creating and keeping track of all - // axioms related to the type system. This abstract class is made - // concrete in two subclasses, one for type erasure with type - // premisses in quantifiers (the semantic approach), and one for - // type erasure with explicit type arguments of polymorphic - // functions (the syntactic approach). - - [ContractClassFor(typeof(TypeAxiomBuilder))] - public abstract class TypeAxiomBuilderContracts : TypeAxiomBuilder - { - public TypeAxiomBuilderContracts() - : base((VCExpressionGenerator) null) - { - } - - internal override MapTypeAbstractionBuilder MapTypeAbstracter - { - get - { - Contract.Ensures(Contract.Result() != null); - throw new NotImplementedException(); - } - } - - public override Type TypeAfterErasure(Type type) - { - Contract.Requires(type != null); - Contract.Ensures(Contract.Result() != null); - - throw new NotImplementedException(); - } - - public override bool UnchangedType(Type type) - { - Contract.Requires(type != null); - throw new NotImplementedException(); - } - - protected override void AddVarTypeAxiom(VCExprVar var, Type originalType) - { - Contract.Requires(var != null); - Contract.Requires(originalType != null); - throw new NotImplementedException(); - } - - public override object Clone() - { - Contract.Ensures(Contract.Result() != null); - - throw new NotImplementedException(); - } - } - - ////////////////////////////////////////////////////////////////////////////// - - // Subclass of the TypeAxiomBuilder that provides all functionality - // to deal with native sorts of a theorem prover (that are the only - // types left after erasing all other types). Currently, these are: - // - // U ... sort of all individuals/objects/values - // T ... sort of all types - // int ... integers - // bool ... booleans - - [ContractClass(typeof(TypeAxiomBuilderIntBoolUContracts))] - public abstract class TypeAxiomBuilderIntBoolU : TypeAxiomBuilder - { - public TypeAxiomBuilderIntBoolU(VCExpressionGenerator gen) - : base(gen) - { - Contract.Requires(gen != null); - - TypeCasts = new Dictionary(); - } - - // constructor to allow cloning - internal TypeAxiomBuilderIntBoolU(TypeAxiomBuilderIntBoolU builder) - : base(builder) - { - Contract.Requires(builder != null); - - TypeCasts = new Dictionary(builder.TypeCasts); - } - - public override void Setup(List usedTypes) - { - base.Setup(usedTypes); - - foreach (var ty in usedTypes) { - GetTypeCasts(ty); - } - } - - // generate inverse axioms for casts (castToU(castFromU(x)) = x, under certain premisses) - protected abstract VCExpr /*!*/ GenReverseCastAxiom(Function /*!*/ castToU, Function /*!*/ castFromU); - - protected VCExpr GenReverseCastEq(Function castToU, Function castFromU, out VCExprVar var, - out List /*!*/ triggers) - { - Contract.Requires((castFromU != null)); - Contract.Requires((castToU != null)); - Contract.Ensures((cce.NonNullElements(Contract.ValueAtReturn(out triggers)))); - Contract.Ensures(Contract.ValueAtReturn(out var) != null); - Contract.Ensures(Contract.Result() != null); - var = Gen.Variable("x", U); - - VCExpr inner = Gen.Function(castFromU, var); - VCExpr lhs = Gen.Function(castToU, inner); - triggers = HelperFuns.ToList(Gen.Trigger(true, HelperFuns.ToList(inner))); - - return Gen.Eq(lhs, var); - } - - protected abstract VCExpr /*!*/ GenCastTypeAxioms(Function /*!*/ castToU, Function /*!*/ castFromU); - - /////////////////////////////////////////////////////////////////////////// - // storage of type casts for types that are supposed to be left over in the - // VCs (like int, bool, bitvectors) - - private readonly IDictionary /*!*/ - TypeCasts; - - [ContractInvariantMethod] - void TypeCastsInvariantMethod() - { - Contract.Invariant(TypeCasts != null); - } - - private TypeCastSet GetTypeCasts(Type type) - { - Contract.Requires(type != null); - if (!TypeCasts.TryGetValue(type, out var res)) - { - Function /*!*/ - castToU = HelperFuns.BoogieFunction(type.ToString() + "_2_U", type, U); - Function /*!*/ - castFromU = HelperFuns.BoogieFunction("U_2_" + type.ToString(), U, type); - - AddTypeAxiom(GenLeftInverseAxiom(castToU, castFromU, 0)); - AddTypeAxiom(GenReverseCastAxiom(castToU, castFromU)); - AddTypeAxiom(GenCastTypeAxioms(castToU, castFromU)); - - res = new TypeCastSet(castToU, castFromU); - TypeCasts.Add(type, res); - } - - return res; - } - - [Pure] - public Function CastTo(Type type) - { - Contract.Requires(type != null); - Contract.Requires(UnchangedType(type)); - Contract.Ensures(Contract.Result() != null); - return GetTypeCasts(type).CastFromU; - } - - public Function CastFrom(Type type) - { - Contract.Requires(type != null); - Contract.Requires((UnchangedType(type))); - Contract.Ensures(Contract.Result() != null); - return GetTypeCasts(type).CastToU; - } - - private struct TypeCastSet - { - public readonly Function /*!*/ - CastToU; - - public readonly Function /*!*/ - CastFromU; - - [ContractInvariantMethod] - void ObjectInvariant() - { - Contract.Invariant(CastToU != null); - Contract.Invariant(CastFromU != null); - } - - - public TypeCastSet(Function castToU, Function castFromU) - { - Contract.Requires(castFromU != null); - Contract.Requires(castToU != null); - CastToU = castToU; - CastFromU = castFromU; - } - } - - public bool IsCast(Function fun) - { - Contract.Requires(fun != null); - if (fun.InParams.Count != 1) - { - return false; - } - - Type /*!*/ - inType = cce.NonNull(fun.InParams[0]).TypedIdent.Type; - if (inType.Equals(U)) - { - Type /*!*/ - outType = cce.NonNull(fun.OutParams[0]).TypedIdent.Type; - if (!TypeCasts.ContainsKey(outType)) - { - return false; - } - - return fun.Equals(CastTo(outType)); - } - else - { - if (!TypeCasts.ContainsKey(inType)) - { - return false; - } - - Type /*!*/ - outType = cce.NonNull(fun.OutParams[0]).TypedIdent.Type; - if (!outType.Equals(U)) - { - return false; - } - - return fun.Equals(CastFrom(inType)); - } - } - - //////////////////////////////////////////////////////////////////////////// - - // the only types that we allow in "untyped" expressions are U, - // Type.Int, Type.Real, Type.Bool, and Type.RMode - - public override Type TypeAfterErasure(Type type) - { - //Contract.Requires(type != null); - Contract.Ensures(Contract.Result() != null); - if (UnchangedType(type)) - { - // these types are kept - return type; - } - else - { - // all other types are replaced by U - return U; - } - } - - [Pure] - public override bool UnchangedType(Type type) - { - //Contract.Requires(type != null); - return type.IsInt || type.IsReal || type.IsBool || type.IsBv || type.IsFloat || type.IsRMode || type.IsString || - type.IsRegEx; - } - - public override VCExpr Cast(VCExpr expr, Type toType) - { - Contract.Requires(toType != null); - Contract.Requires(expr != null); - Contract.Requires((expr.Type.Equals(U) || UnchangedType(expr.Type))); - Contract.Requires((toType.Equals(U) || UnchangedType(toType))); - Contract.Ensures(Contract.Result() != null); - if (expr.Type.Equals(toType)) - { - return expr; - } - - if (toType.Equals(U)) - { - return Gen.Function(CastFrom(expr.Type), expr); - } - else - { - Contract.Assert(expr.Type.Equals(U)); - return Gen.Function(CastTo(toType), expr); - } - } - - public List /*!*/ CastSeq(List /*!*/ exprs, Type toType) - { - Contract.Requires(toType != null); - Contract.Requires(cce.NonNullElements(exprs)); - Contract.Ensures(cce.NonNullElements(Contract.Result>())); - List /*!*/ - res = new List(exprs.Count); - foreach (VCExpr /*!*/ expr in exprs) - { - Contract.Assert(expr != null); - res.Add(Cast(expr, toType)); - } - - return res; - } - } - - [ContractClassFor(typeof(TypeAxiomBuilderIntBoolU))] - public abstract class TypeAxiomBuilderIntBoolUContracts : TypeAxiomBuilderIntBoolU - { - public TypeAxiomBuilderIntBoolUContracts() - : base((TypeAxiomBuilderIntBoolU) null) - { - } - - protected override VCExpr GenReverseCastAxiom(Function castToU, Function castFromU) - { - Contract.Requires(castToU != null); - Contract.Requires(castFromU != null); - Contract.Ensures(Contract.Result() != null); - - throw new NotImplementedException(); - } - - protected override VCExpr GenCastTypeAxioms(Function castToU, Function castFromU) - { - Contract.Requires(castFromU != null); - Contract.Requires(castToU != null); - Contract.Ensures(Contract.Result() != null); - - throw new NotImplementedException(); - } - - internal override MapTypeAbstractionBuilder MapTypeAbstracter - { - get { throw new NotImplementedException(); } - } - - protected override void AddVarTypeAxiom(VCExprVar var, Type originalType) - { - throw new NotImplementedException(); - } - - public override object Clone() - { - throw new NotImplementedException(); - } - } - - ////////////////////////////////////////////////////////////////////////////// - // Class for computing most general abstractions of map types. An abstraction - // of a map type t is a maptype t' in which closed proper subtypes have been replaced - // with type variables. E.g., an abstraction of [C a, int]a would be [C a, b]a. - // We subsequently consider most general abstractions as ordinary parametrised types, - // i.e., "[C a, b]a" would be considered as a type "M b" with polymorphically typed - // access functions - // - // select(M b, C a, b) returns (a) - // store(M b, C a, b, a) returns (M b) - - [ContractClassFor(typeof(MapTypeAbstractionBuilder))] - internal abstract class MapTypeAbstractionBuilderContracts : MapTypeAbstractionBuilder - { - public MapTypeAbstractionBuilderContracts() - : base(null, null) - { - } - - protected override void GenSelectStoreFunctions(MapType abstractedType, TypeCtorDecl synonymDecl, - out Function select, out Function store) - { - Contract.Requires(abstractedType != null); - Contract.Requires(synonymDecl != null); - Contract.Ensures(Contract.ValueAtReturn(out select) != null); - Contract.Ensures(Contract.ValueAtReturn(out store) != null); - - throw new NotImplementedException(); - } - } - - - ////////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////////// - - // The central class for turning types VCExprs into untyped - // VCExprs. This class makes use of the type axiom builder to manage - // the available types and symbols. - - - ////////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////////// -} \ No newline at end of file diff --git a/Source/VCExpr/TypeErasure/TypeErasureArguments.cs b/Source/VCExpr/TypeErasure/TypeErasureArguments.cs index ebbd4958c..5e34450b2 100644 --- a/Source/VCExpr/TypeErasure/TypeErasureArguments.cs +++ b/Source/VCExpr/TypeErasure/TypeErasureArguments.cs @@ -7,14 +7,11 @@ // Erasure of types using explicit type parameters for functions -namespace Microsoft.Boogie.TypeErasure -{ - public class TypeAxiomBuilderArguments : TypeAxiomBuilderIntBoolU - { +namespace Microsoft.Boogie.TypeErasure { + public class TypeAxiomBuilderArguments : TypeAxiomBuilderIntBoolU { private CoreOptions options; public TypeAxiomBuilderArguments(VCExpressionGenerator gen, CoreOptions options) - : base(gen) - { + : base(gen) { Contract.Requires(gen != null); this.options = options; @@ -24,8 +21,7 @@ public TypeAxiomBuilderArguments(VCExpressionGenerator gen, CoreOptions options) // constructor to allow cloning [NotDelayed] internal TypeAxiomBuilderArguments(TypeAxiomBuilderArguments builder) - : base(builder) - { + : base(builder) { Contract.Requires(builder != null); this.options = builder.options; Typed2UntypedFunctions = @@ -39,8 +35,7 @@ internal TypeAxiomBuilderArguments(TypeAxiomBuilderArguments builder) builder.MapTypeAbstracterAttr, options); } - public override Object Clone() - { + public override Object Clone() { Contract.Ensures(Contract.Result() != null); return new TypeAxiomBuilderArguments(this); } @@ -51,8 +46,7 @@ public override Object Clone() // (this makes use of the assumption that only well-typed terms are generated // by the SMT-solver, i.e., that U2Int is only applied to terms that actually // are of type int) - protected override VCExpr GenReverseCastAxiom(Function castToU, Function castFromU) - { + protected override VCExpr GenReverseCastAxiom(Function castToU, Function castFromU) { //Contract.Requires(castFromU != null); //Contract.Requires(castToU != null); Contract.Ensures(Contract.Result() != null); @@ -61,8 +55,7 @@ protected override VCExpr GenReverseCastAxiom(Function castToU, Function castFro return Gen.Forall(HelperFuns.ToList(var), triggers, "cast:" + castFromU.Name, 1, eq); } - protected override VCExpr GenCastTypeAxioms(Function castToU, Function castFromU) - { + protected override VCExpr GenCastTypeAxioms(Function castToU, Function castFromU) { //Contract.Requires(castFromU != null); //Contract.Requires(castToU != null); Contract.Ensures(Contract.Result() != null); @@ -72,14 +65,11 @@ protected override VCExpr GenCastTypeAxioms(Function castToU, Function castFromU private MapTypeAbstractionBuilderArguments MapTypeAbstracterAttr = null; - internal override MapTypeAbstractionBuilder /*!*/ MapTypeAbstracter - { - get - { + internal override MapTypeAbstractionBuilder /*!*/ MapTypeAbstracter { + get { Contract.Ensures(Contract.Result() != null); - if (MapTypeAbstracterAttr == null) - { + if (MapTypeAbstracterAttr == null) { MapTypeAbstracterAttr = new MapTypeAbstractionBuilderArguments(this, Gen, options); } @@ -87,8 +77,7 @@ internal override MapTypeAbstractionBuilder /*!*/ MapTypeAbstracter } } - protected override void AddVarTypeAxiom(VCExprVar var, Type originalType) - { + protected override void AddVarTypeAxiom(VCExprVar var, Type originalType) { //Contract.Requires(originalType != null); //Contract.Requires(var != null); // no axioms are needed for variable or function types @@ -102,42 +91,34 @@ protected override void AddVarTypeAxiom(VCExprVar var, Type originalType) Typed2UntypedFunctions; [ContractInvariantMethod] - void Typed2UntypedFunctionsInvariantMethod() - { + void Typed2UntypedFunctionsInvariantMethod() { Contract.Invariant(cce.NonNullDictionaryAndValues(Typed2UntypedFunctions)); } - public Function Typed2Untyped(Function fun) - { + public Function Typed2Untyped(Function fun) { Contract.Requires(fun != null); Contract.Ensures(Contract.Result() != null); - if (!Typed2UntypedFunctions.TryGetValue(fun, out var res)) - { + if (!Typed2UntypedFunctions.TryGetValue(fun, out var res)) { Contract.Assert(fun.OutParams.Count == 1); // if all of the parameters are int or bool, the function does // not have to be changed if (fun.InParams.All(param => UnchangedType(cce.NonNull(param).TypedIdent.Type)) && - UnchangedType(cce.NonNull(fun.OutParams[0]).TypedIdent.Type)) - { + UnchangedType(cce.NonNull(fun.OutParams[0]).TypedIdent.Type)) { res = fun; - } - else - { + } else { Type[] /*!*/ types = new Type[fun.TypeParameters.Count + fun.InParams.Count + 1]; int i = 0; // the first arguments are the explicit type parameters - for (int j = 0; j < fun.TypeParameters.Count; ++j) - { + for (int j = 0; j < fun.TypeParameters.Count; ++j) { types[i] = T; i = i + 1; } // followed by the actual parameters - foreach (Variable /*!*/ x in fun.InParams) - { + foreach (Variable /*!*/ x in fun.InParams) { Contract.Assert(x != null); types[i] = TypeAfterErasure(x.TypedIdent.Type); i = i + 1; @@ -158,22 +139,19 @@ public Function Typed2Untyped(Function fun) ////////////////////////////////////////////////////////////////////////////// - internal class MapTypeAbstractionBuilderArguments : MapTypeAbstractionBuilder - { + internal class MapTypeAbstractionBuilderArguments : MapTypeAbstractionBuilder { private CoreOptions options; private readonly TypeAxiomBuilderArguments /*!*/ AxBuilderArguments; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(AxBuilderArguments != null); } internal MapTypeAbstractionBuilderArguments(TypeAxiomBuilderArguments axBuilder, VCExpressionGenerator gen, CoreOptions options) - : base(axBuilder, gen) - { + : base(axBuilder, gen) { Contract.Requires(gen != null); Contract.Requires(axBuilder != null); @@ -184,8 +162,7 @@ internal MapTypeAbstractionBuilderArguments(TypeAxiomBuilderArguments axBuilder, // constructor for cloning internal MapTypeAbstractionBuilderArguments(TypeAxiomBuilderArguments axBuilder, VCExpressionGenerator gen, MapTypeAbstractionBuilderArguments builder, CoreOptions options) - : base(axBuilder, gen, builder) - { + : base(axBuilder, gen, builder) { Contract.Requires(builder != null); Contract.Requires(gen != null); Contract.Requires(axBuilder != null); @@ -196,10 +173,9 @@ internal MapTypeAbstractionBuilderArguments(TypeAxiomBuilderArguments axBuilder, //////////////////////////////////////////////////////////////////////////// protected override void GenSelectStoreFunctions(MapType abstractedType, TypeCtorDecl synonym, - out Function /*!*/ select, out Function /*!*/ store) - { + out Function /*!*/ select, out Function /*!*/ store) { //Contract.Requires(synonym != null); -//Contract.Requires(abstractedType != null); + //Contract.Requires(abstractedType != null); Contract.Ensures(Contract.ValueAtReturn(out select) != null); Contract.Ensures(Contract.ValueAtReturn(out store) != null); Contract.Assert(synonym.Name != null); @@ -217,8 +193,7 @@ protected override void GenSelectStoreFunctions(MapType abstractedType, TypeCtor int i = 0; // Fill in the free variables and type parameters - for (; i < typeParamNum; i++) - { + for (; i < typeParamNum; i++) { selectTypes[i] = AxBuilder.T; storeTypes[i] = AxBuilder.T; } @@ -228,8 +203,7 @@ protected override void GenSelectStoreFunctions(MapType abstractedType, TypeCtor storeTypes[i] = AxBuilder.U; i++; // Fill in the index types - foreach (Type /*!*/ type in abstractedType.Arguments) - { + foreach (Type /*!*/ type in abstractedType.Arguments) { Contract.Assert(type != null); selectTypes[i] = AxBuilder.U; storeTypes[i] = AxBuilder.U; @@ -258,8 +232,7 @@ protected override void GenSelectStoreFunctions(MapType abstractedType, TypeCtor // The normal axioms of the theory of arrays (right now without extensionality) private VCExpr Select(Function select, List /*!*/ types, VCExpr map, - List /*!*/ indexes) - { + List /*!*/ indexes) { Contract.Requires(map != null); Contract.Requires(select != null); Contract.Requires(cce.NonNullElements(indexes)); @@ -274,8 +247,7 @@ private VCExpr Select(Function select, List /*!*/ types, VCExpr } private VCExpr Store(Function store, List /*!*/ types, VCExpr map, - List /*!*/ indexes, VCExpr val) - { + List /*!*/ indexes, VCExpr val) { Contract.Requires(val != null); Contract.Requires(map != null); Contract.Requires(store != null); @@ -296,8 +268,7 @@ private VCExpr Store(Function store, List /*!*/ types, VCExpr m int mapTypeParamNum, // free type variables in the map // type (abstraction) - int mapAbstractionVarNum) - { + int mapAbstractionVarNum) { Contract.Requires(select != null); Contract.Requires(store != null); Contract.Ensures(Contract.Result() != null); @@ -309,8 +280,7 @@ private VCExpr Store(Function store, List /*!*/ types, VCExpr m AxBuilder.T, Gen); List indexTypes = new List(); - for (int i = mapTypeParamNum + mapAbstractionVarNum + 1; i < select.InParams.Count; i++) - { + for (int i = mapTypeParamNum + mapAbstractionVarNum + 1; i < select.InParams.Count; i++) { indexTypes.Add(cce.NonNull(select.InParams[i]).TypedIdent.Type); } @@ -352,8 +322,7 @@ private VCExpr Store(Function store, List /*!*/ types, VCExpr m int mapTypeParamNum, // free type variables in the map // type (abstraction) - int mapAbstractionVarNum) - { + int mapAbstractionVarNum) { Contract.Requires(select != null); Contract.Requires(store != null); Contract.Ensures(Contract.Result() != null); @@ -379,8 +348,7 @@ private VCExpr Store(Function store, List /*!*/ types, VCExpr m types1.AddRange(freeTypeVars); List indexTypes = new List(); - for (int i = mapTypeParamNum + mapAbstractionVarNum + 1; i < select.InParams.Count; i++) - { + for (int i = mapTypeParamNum + mapAbstractionVarNum + 1; i < select.InParams.Count; i++) { indexTypes.Add(cce.NonNull(select.InParams[i]).TypedIdent.Type); } @@ -431,21 +399,18 @@ private VCExpr Store(Function store, List /*!*/ types, VCExpr m List /*!*/ indexEqs = new List(); - for (int i = 0; i < mapTypeParamNum; ++i) - { + for (int i = 0; i < mapTypeParamNum; ++i) { indexEqs.Add(Gen.Eq(boundTypeVars0[i], boundTypeVars1[i])); } - for (int i = 0; i < arity; ++i) - { + for (int i = 0; i < arity; ++i) { indexEqs.Add(Gen.Eq(indexes0[i], indexes1[i])); } VCExpr /*!*/ axiom = VCExpressionGenerator.True; int n = 0; - foreach (VCExpr /*!*/ indexesEq in indexEqs) - { + foreach (VCExpr /*!*/ indexesEq in indexEqs) { Contract.Assert(indexesEq != null); VCExpr /*!*/ matrix = Gen.Or(indexesEq, selectEq); @@ -463,28 +428,23 @@ private VCExpr Store(Function store, List /*!*/ types, VCExpr m ////////////////////////////////////////////////////////////////////////////// - public class TypeEraserArguments : TypeEraser - { + public class TypeEraserArguments : TypeEraser { private readonly TypeAxiomBuilderArguments /*!*/ AxBuilderArguments; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(AxBuilderArguments != null); } private OpTypeEraser OpEraserAttr = null; - protected override OpTypeEraser /*!*/ OpEraser - { - get - { + protected override OpTypeEraser /*!*/ OpEraser { + get { Contract.Ensures(Contract.Result() != null); - if (OpEraserAttr == null) - { + if (OpEraserAttr == null) { OpEraserAttr = new OpTypeEraserArguments(this, AxBuilderArguments, Gen); } @@ -492,8 +452,7 @@ protected override OpTypeEraser /*!*/ OpEraser } } - public TypeEraserArguments(TypeAxiomBuilderArguments axBuilder, VCExpressionGenerator gen) : base(axBuilder, gen) - { + public TypeEraserArguments(TypeAxiomBuilderArguments axBuilder, VCExpressionGenerator gen) : base(axBuilder, gen) { Contract.Requires(gen != null); Contract.Requires(axBuilder != null); @@ -502,8 +461,7 @@ public TypeEraserArguments(TypeAxiomBuilderArguments axBuilder, VCExpressionGene //////////////////////////////////////////////////////////////////////////// - public override VCExpr Visit(VCExprQuantifier node, VariableBindings oldBindings) - { + public override async DynamicStack Visit(VCExprQuantifier node, VariableBindings oldBindings) { Contract.Requires(oldBindings != null); Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); @@ -518,33 +476,28 @@ public override VCExpr Visit(VCExprQuantifier node, VariableBindings oldBindings // type variables are replaced with ordinary quantified variables GenBoundVarsForTypeParams(node.TypeParameters, newBoundVars, bindings); - VCExpr /*!*/ - newNode = HandleQuantifier(node, newBoundVars, bindings); + VCExpr /*!*/ newNode = await HandleQuantifier(node, newBoundVars, bindings); Contract.Assert(newNode != null); - if (!(newNode is VCExprQuantifier) || !IsUniversalQuantifier(node)) - { + if (!(newNode is VCExprQuantifier) || !IsUniversalQuantifier(node)) { return newNode; } - if (!RedoQuantifier(node, (VCExprQuantifier) newNode, node.BoundVars, oldBindings, - out var bindings2, out newBoundVars)) - { + if (!RedoQuantifier(node, (VCExprQuantifier)newNode, node.BoundVars, oldBindings, + out var bindings2, out newBoundVars)) { return newNode; } GenBoundVarsForTypeParams(node.TypeParameters, newBoundVars, bindings2); - return HandleQuantifier(node, newBoundVars, bindings2); + return await HandleQuantifier(node, newBoundVars, bindings2); } private void GenBoundVarsForTypeParams(List /*!*/ typeParams, - List /*!*/ newBoundVars, VariableBindings bindings) - { + List /*!*/ newBoundVars, VariableBindings bindings) { Contract.Requires(bindings != null); Contract.Requires(cce.NonNullElements(typeParams)); Contract.Requires(cce.NonNullElements(newBoundVars)); - foreach (TypeVariable /*!*/ tvar in typeParams) - { + foreach (TypeVariable /*!*/ tvar in typeParams) { Contract.Assert(tvar != null); VCExprVar /*!*/ var = Gen.Variable(tvar.Name, AxBuilder.T); @@ -554,15 +507,14 @@ private void GenBoundVarsForTypeParams(List /*!*/ typeParams } } - private VCExpr HandleQuantifier(VCExprQuantifier node, List /*!*/ newBoundVars, - VariableBindings bindings) - { + private async DynamicStack HandleQuantifier(VCExprQuantifier node, List /*!*/ newBoundVars, + VariableBindings bindings) { Contract.Requires(bindings != null); Contract.Requires(node != null); Contract.Requires(cce.NonNullElements(newBoundVars)); Contract.Ensures(Contract.Result() != null); List /*!*/ - newTriggers = MutateTriggers(node.Triggers, bindings); + newTriggers = await MutateTriggers(node.Triggers, bindings); Contract.Assert(cce.NonNullElements(newTriggers)); VCExpr /*!*/ newBody = Mutate(node.Body, bindings); @@ -581,21 +533,18 @@ private VCExpr HandleQuantifier(VCExprQuantifier node, List /*! ////////////////////////////////////////////////////////////////////////////// - public class OpTypeEraserArguments : OpTypeEraser - { + public class OpTypeEraserArguments : OpTypeEraser { protected readonly TypeAxiomBuilderArguments /*!*/ AxBuilderArguments; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(AxBuilderArguments != null); } public OpTypeEraserArguments(TypeEraserArguments eraser, TypeAxiomBuilderArguments axBuilder, - VCExpressionGenerator gen) : base(eraser, axBuilder, gen) - { + VCExpressionGenerator gen) : base(eraser, axBuilder, gen) { Contract.Requires(gen != null); Contract.Requires(axBuilder != null); Contract.Requires(eraser != null); @@ -605,8 +554,7 @@ public OpTypeEraserArguments(TypeEraserArguments eraser, TypeAxiomBuilderArgumen //////////////////////////////////////////////////////////////////////////// private VCExpr AssembleOpExpression(OpTypesPair opTypes, IEnumerable /*!*/ oldArgs, - VariableBindings bindings) - { + VariableBindings bindings) { Contract.Requires(bindings != null); Contract.Requires(cce.NonNullElements(oldArgs)); Contract.Ensures(Contract.Result() != null); @@ -617,19 +565,17 @@ private VCExpr AssembleOpExpression(OpTypesPair opTypes, IEnumerable /*!*/ newArgs = new List(); // explicit type parameters - foreach (Type /*!*/ t in opTypes.Types) - { + foreach (Type /*!*/ t in opTypes.Types) { Contract.Assert(newArgs != null); newArgs.Add(AxBuilder.Type2Term(t, bindings.TypeVariableBindings)); } // and the actual value parameters Function /*!*/ - newFun = ((VCExprBoogieFunctionOp) opTypes.Op).Func; + newFun = ((VCExprBoogieFunctionOp)opTypes.Op).Func; // ^ we only allow this operator at this point int i = opTypes.Types.Count; - foreach (VCExpr /*!*/ arg in oldArgs) - { + foreach (VCExpr /*!*/ arg in oldArgs) { Contract.Assert(arg != null); newArgs.Add(AxBuilder.Cast(Eraser.Mutate(arg, bindings), cce.NonNull(newFun.InParams[i]).TypedIdent.Type)); @@ -642,13 +588,11 @@ private VCExpr AssembleOpExpression(OpTypesPair opTypes, IEnumerable /*!*/ originalTypes = new List(); - foreach (VCExpr /*!*/ expr in node.Arguments) - { + foreach (VCExpr /*!*/ expr in node.Arguments) { Contract.Assert(expr != null); originalTypes.Add(expr.Type); } @@ -657,14 +601,12 @@ private OpTypesPair OriginalOpTypes(VCExprNAry node) return new OpTypesPair(node.Op, originalTypes); } - private VCExpr EqualTypes(Type t0, Type t1, VariableBindings bindings) - { + private VCExpr EqualTypes(Type t0, Type t1, VariableBindings bindings) { Contract.Requires(bindings != null); Contract.Requires(t1 != null); Contract.Requires(t0 != null); Contract.Ensures(Contract.Result() != null); - if (t0.Equals(t1)) - { + if (t0.Equals(t1)) { return VCExpressionGenerator.True; } @@ -679,39 +621,35 @@ private VCExpr EqualTypes(Type t0, Type t1, VariableBindings bindings) /////////////////////////////////////////////////////////////////////////// - public override VCExpr VisitEqOp(VCExprNAry node, VariableBindings bindings) - { + public override async DynamicStack VisitEqOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); // we also have to state that the types are equal, because the // translation does not contain any information about the // relationship between values and types - return Gen.AndSimp(base.VisitEqOp(node, bindings), + return Gen.AndSimp(await base.VisitEqOp(node, bindings), EqualTypes(node[0].Type, node[1].Type, bindings)); } - public override VCExpr VisitNeqOp(VCExprNAry node, VariableBindings bindings) - { + public override async DynamicStack VisitNeqOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); // we also have to state that the types are (un)equal, because the // translation does not contain any information about the // relationship between values and types - return Gen.OrSimp(base.VisitNeqOp(node, bindings), + return Gen.OrSimp(await base.VisitNeqOp(node, bindings), Gen.Not(EqualTypes(node[0].Type, node[1].Type, bindings))); } - public override VCExpr VisitSelectOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitSelectOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); OpTypesPair originalOpTypes = OriginalOpTypes(node); - if (!NewOpCache.TryGetValue(originalOpTypes, out var newOpTypes)) - { + if (!NewOpCache.TryGetValue(originalOpTypes, out var newOpTypes)) { MapType /*!*/ rawType = node[0].Type.AsMap; Contract.Assert(rawType != null); @@ -723,18 +661,16 @@ public override VCExpr VisitSelectOp(VCExprNAry node, VariableBindings bindings) NewOpCache.Add(originalOpTypes, newOpTypes); } - return AssembleOpExpression(newOpTypes, node.Arguments, bindings); + return DynamicStack.FromResult(AssembleOpExpression(newOpTypes, node.Arguments, bindings)); } - public override VCExpr VisitStoreOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitStoreOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); OpTypesPair originalOpTypes = OriginalOpTypes(node); - if (!NewOpCache.TryGetValue(originalOpTypes, out var newOpTypes)) - { + if (!NewOpCache.TryGetValue(originalOpTypes, out var newOpTypes)) { MapType /*!*/ rawType = node[0].Type.AsMap; Function /*!*/ @@ -745,28 +681,25 @@ public override VCExpr VisitStoreOp(VCExprNAry node, VariableBindings bindings) NewOpCache.Add(originalOpTypes, newOpTypes); } - return AssembleOpExpression(newOpTypes, node.Arguments, bindings); + return DynamicStack.FromResult(AssembleOpExpression(newOpTypes, node.Arguments, bindings)); } private OpTypesPair TypesPairForSelectStore(VCExprNAry /*!*/ node, Function /*!*/ untypedOp, // instantiation of the abstract map type parameters - List /*!*/ abstractionInstantiation) - { + List /*!*/ abstractionInstantiation) { Contract.Requires(node != null); Contract.Requires(untypedOp != null); Contract.Requires(abstractionInstantiation != null); List /*!*/ inferredTypeArgs = new List(); - foreach (Type /*!*/ t in node.TypeArguments) - { + foreach (Type /*!*/ t in node.TypeArguments) { Contract.Assert(t != null); -// inferredTypeArgs.Add(AxBuilder.MapTypeAbstracter.AbstractMapTypeRecursively(t)); + // inferredTypeArgs.Add(AxBuilder.MapTypeAbstracter.AbstractMapTypeRecursively(t)); inferredTypeArgs.Add(t); } - foreach (Type /*!*/ t in abstractionInstantiation) - { + foreach (Type /*!*/ t in abstractionInstantiation) { Contract.Assert(t != null); inferredTypeArgs.Add(t); } @@ -777,24 +710,21 @@ private OpTypesPair TypesPairForSelectStore(VCExprNAry /*!*/ node, Function /*!* /////////////////////////////////////////////////////////////////////////// - public override VCExpr VisitBoogieFunctionOp(VCExprNAry node, VariableBindings bindings) - { + public override DynamicStack VisitBoogieFunctionOp(VCExprNAry node, VariableBindings bindings) { Contract.Requires((bindings != null)); Contract.Requires((node != null)); Contract.Ensures(Contract.Result() != null); OpTypesPair originalOpTypes = OriginalOpTypes(node); - if (!NewOpCache.TryGetValue(originalOpTypes, out var newOpTypes)) - { + if (!NewOpCache.TryGetValue(originalOpTypes, out var newOpTypes)) { Function /*!*/ - oriFun = ((VCExprBoogieFunctionOp) node.Op).Func; + oriFun = ((VCExprBoogieFunctionOp)node.Op).Func; Contract.Assert(oriFun != null); List /*!*/ inferredTypeArgs = new List(); - foreach (Type /*!*/ t in node.TypeArguments) - { + foreach (Type /*!*/ t in node.TypeArguments) { Contract.Assert(t != null); -// inferredTypeArgs.Add(AxBuilder.MapTypeAbstracter.AbstractMapTypeRecursively(t)); + // inferredTypeArgs.Add(AxBuilder.MapTypeAbstracter.AbstractMapTypeRecursively(t)); inferredTypeArgs.Add(t); } @@ -805,7 +735,7 @@ public override VCExpr VisitBoogieFunctionOp(VCExprNAry node, VariableBindings b NewOpCache.Add(originalOpTypes, newOpTypes); } - return AssembleOpExpression(newOpTypes, node.Arguments, bindings); + return DynamicStack.FromResult(AssembleOpExpression(newOpTypes, node.Arguments, bindings)); } /////////////////////////////////////////////////////////////////////////// @@ -819,8 +749,7 @@ private readonly IDictionary /*!*/ NewOpCache = new Dictionary(); - private struct OpTypesPair - { + private struct OpTypesPair { public readonly VCExprOp /*!*/ Op; @@ -828,15 +757,13 @@ public readonly List /*!*/ Types; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(Op != null); Contract.Invariant(cce.NonNullElements(Types)); } - public OpTypesPair(VCExprOp op, List /*!*/ types) - { + public OpTypesPair(VCExprOp op, List /*!*/ types) { Contract.Requires(op != null); Contract.Requires(cce.NonNullElements(types)); this.Op = op; @@ -846,11 +773,9 @@ public OpTypesPair(VCExprOp op, List /*!*/ types) [Pure] [Reads(ReadsAttribute.Reads.Nothing)] - public override bool Equals(object that) - { - if (that is OpTypesPair) - { - OpTypesPair thatPair = (OpTypesPair) that; + public override bool Equals(object that) { + if (that is OpTypesPair) { + OpTypesPair thatPair = (OpTypesPair)that; return this.Op.Equals(thatPair.Op) && HFNS.SameElements(this.Types, thatPair.Types); } @@ -861,8 +786,7 @@ public override bool Equals(object that) private readonly int HashCode; [Pure] - public override int GetHashCode() - { + public override int GetHashCode() { return HashCode; } } diff --git a/Source/VCExpr/TypeErasure/TypeErasurePremisses.cs b/Source/VCExpr/TypeErasure/TypeErasurePremisses.cs index 9e2f75dcb..967007f5a 100644 --- a/Source/VCExpr/TypeErasure/TypeErasurePremisses.cs +++ b/Source/VCExpr/TypeErasure/TypeErasurePremisses.cs @@ -6,8 +6,7 @@ // Erasure of types using premisses (forall x :: type(x)=T ==> p(x)) -namespace Microsoft.Boogie.TypeErasure -{ +namespace Microsoft.Boogie.TypeErasure { // When using type premisses, we can distinguish two kinds of type // parameters of a function or map: parameters that occur in the // formal argument types of the function are "implicit" because they @@ -21,8 +20,7 @@ namespace Microsoft.Boogie.TypeErasure // type parameters (in the same order as they occur in the signature // of the original function). - internal struct UntypedFunction - { + internal struct UntypedFunction { public readonly Function /*!*/ Fun; @@ -35,8 +33,7 @@ public readonly List /*!*/ ExplicitTypeParams; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(Fun != null); Contract.Invariant(cce.NonNullElements(ImplicitTypeParams)); Contract.Invariant(cce.NonNullElements(ExplicitTypeParams)); @@ -45,8 +42,7 @@ void ObjectInvariant() public UntypedFunction(Function /*!*/ fun, List /*!*/ implicitTypeParams, - List /*!*/ explicitTypeParams) - { + List /*!*/ explicitTypeParams) { Contract.Requires(fun != null); Contract.Requires(cce.NonNullElements(implicitTypeParams)); Contract.Requires(cce.NonNullElements(explicitTypeParams)); @@ -56,8 +52,7 @@ public UntypedFunction(Function /*!*/ fun, } } - public class TypeAxiomBuilderPremisses : TypeAxiomBuilderIntBoolU - { + public class TypeAxiomBuilderPremisses : TypeAxiomBuilderIntBoolU { private const string TypeName = "type"; static TypeAxiomBuilderPremisses() { ScopedNamer.AddBoogieDeterminedName(TypeName); @@ -65,8 +60,7 @@ static TypeAxiomBuilderPremisses() { public CoreOptions Options { get; } public TypeAxiomBuilderPremisses(VCExpressionGenerator gen, CoreOptions options) - : base(gen) - { + : base(gen) { Contract.Requires(gen != null); this.Options = options; @@ -78,8 +72,7 @@ public TypeAxiomBuilderPremisses(VCExpressionGenerator gen, CoreOptions options) // constructor to allow cloning [NotDelayed] internal TypeAxiomBuilderPremisses(TypeAxiomBuilderPremisses builder) - : base(builder) - { + : base(builder) { Contract.Requires(builder != null); this.Options = builder.Options; TypeFunction = builder.TypeFunction; @@ -92,14 +85,12 @@ internal TypeAxiomBuilderPremisses(TypeAxiomBuilderPremisses builder) : new MapTypeAbstractionBuilderPremisses(this, builder.Gen, builder.MapTypeAbstracterAttr); } - public override Object Clone() - { + public override Object Clone() { Contract.Ensures(Contract.Result() != null); return new TypeAxiomBuilderPremisses(this); } - public override void Setup(List usedTypes) - { + public override void Setup(List usedTypes) { TypeFunction = HelperFuns.BoogieFunction(TypeName, U, T); base.Setup(usedTypes); } @@ -108,8 +99,7 @@ public override void Setup(List usedTypes) // generate axioms of the kind "forall x:U. {Int2U(U2Int(x))} // type(x)=int ==> Int2U(U2Int(x))==x" - protected override VCExpr GenReverseCastAxiom(Function castToU, Function castFromU) - { + protected override VCExpr GenReverseCastAxiom(Function castToU, Function castFromU) { //Contract.Requires(castFromU != null); //Contract.Requires(castToU != null); Contract.Ensures(Contract.Result() != null); @@ -129,8 +119,7 @@ protected override VCExpr GenReverseCastAxiom(Function castToU, Function castFro return Gen.Forall(HelperFuns.ToList(var), triggers, "cast:" + castFromU.Name, 1, matrix); } - protected override VCExpr GenCastTypeAxioms(Function castToU, Function castFromU) - { + protected override VCExpr GenCastTypeAxioms(Function castToU, Function castFromU) { //Contract.Requires(castFromU != null); //Contract.Requires(castToU != null); Contract.Ensures(Contract.Result() != null); @@ -142,14 +131,11 @@ protected override VCExpr GenCastTypeAxioms(Function castToU, Function castFromU private MapTypeAbstractionBuilderPremisses MapTypeAbstracterAttr; - internal override MapTypeAbstractionBuilder /*!*/ MapTypeAbstracter - { - get - { + internal override MapTypeAbstractionBuilder /*!*/ MapTypeAbstracter { + get { Contract.Ensures(Contract.Result() != null); - if (MapTypeAbstracterAttr == null) - { + if (MapTypeAbstracterAttr == null) { MapTypeAbstracterAttr = new MapTypeAbstractionBuilderPremisses(this, Gen); } @@ -157,13 +143,11 @@ internal override MapTypeAbstractionBuilder /*!*/ MapTypeAbstracter } } - internal MapTypeAbstractionBuilderPremisses /*!*/ MapTypeAbstracterPremisses - { - get - { + internal MapTypeAbstractionBuilderPremisses /*!*/ MapTypeAbstracterPremisses { + get { Contract.Ensures(Contract.Result() != null); - return (MapTypeAbstractionBuilderPremisses) MapTypeAbstracter; + return (MapTypeAbstractionBuilderPremisses)MapTypeAbstracter; } } @@ -175,14 +159,12 @@ private Function /*!*/ TypeFunction; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(TypeFunction != null); } - public VCExpr TypeOf(VCExpr expr) - { + public VCExpr TypeOf(VCExpr expr) { Contract.Requires(expr != null); Contract.Ensures(Contract.Result() != null); return Gen.Function(TypeFunction, expr); @@ -198,8 +180,7 @@ public List /*!*/ // VariableBindings to which the translation // TypeVariable -> VCExprVar is added VariableBindings /*!*/ bindings, - bool addTypeVarsToBindings) - { + bool addTypeVarsToBindings) { Contract.Requires(typeParams != null); Contract.Requires(cce.NonNullElements(oldBoundVars)); Contract.Requires(bindings != null); @@ -208,10 +189,8 @@ public List /*!*/ // type variables are replaced with ordinary variables that are bound using a // let-expression - if (addTypeVarsToBindings) - { - foreach (TypeVariable /*!*/ tvar in typeParams) - { + if (addTypeVarsToBindings) { + foreach (TypeVariable /*!*/ tvar in typeParams) { Contract.Assert(tvar != null); bindings.TypeVariableBindings.Add(tvar, Gen.Variable(tvar.Name, T)); } @@ -222,12 +201,10 @@ public List /*!*/ UtypedVars = new List(oldBoundVars.Count); List /*!*/ originalTypes = new List(oldBoundVars.Count); - foreach (VCExprVar var in oldBoundVars) - { + foreach (VCExprVar var in oldBoundVars) { VCExprVar /*!*/ newVar = bindings.VCExprVarBindings[var]; - if (newVar.Type.Equals(U)) - { + if (newVar.Type.Equals(U)) { UtypedVars.Add(newVar); originalTypes.Add(var.Type); } @@ -242,8 +219,7 @@ public List /*!*/ public VCExpr /*!*/ AddTypePremisses(List /*!*/ typeVarBindings, VCExpr /*!*/ typePremisses, bool universal, - VCExpr /*!*/ body) - { + VCExpr /*!*/ body) { Contract.Requires(cce.NonNullElements(typeVarBindings)); Contract.Requires(typePremisses != null); Contract.Requires(body != null); @@ -251,12 +227,9 @@ public List /*!*/ VCExpr /*!*/ bodyWithPremisses; - if (universal) - { + if (universal) { bodyWithPremisses = Gen.ImpliesSimp(typePremisses, body); - } - else - { + } else { bodyWithPremisses = Gen.AndSimp(typePremisses, body); } @@ -272,8 +245,7 @@ public List /*!*/ public List /*!*/ BestTypeVarExtractors(List /*!*/ vars, List /*!*/ types, List /*!*/ concreteTypeSources, - VariableBindings /*!*/ bindings) - { + VariableBindings /*!*/ bindings) { Contract.Requires(cce.NonNullElements(vars)); Contract.Requires(cce.NonNullElements(types)); Contract.Requires(cce.NonNullElements(concreteTypeSources)); @@ -282,14 +254,12 @@ public List /*!*/ List /*!*/ typeParamBindings = new List(); - foreach (TypeVariable /*!*/ var in vars) - { + foreach (TypeVariable /*!*/ var in vars) { Contract.Assert(var != null); VCExpr extractor = BestTypeVarExtractor(var, types, concreteTypeSources); - if (extractor != null) - { + if (extractor != null) { typeParamBindings.Add( - Gen.LetBinding((VCExprVar) bindings.TypeVariableBindings[var], + Gen.LetBinding((VCExprVar)bindings.TypeVariableBindings[var], extractor)); } } @@ -298,25 +268,21 @@ public List /*!*/ } private VCExpr BestTypeVarExtractor(TypeVariable /*!*/ var, List /*!*/ types, - List /*!*/ concreteTypeSources) - { + List /*!*/ concreteTypeSources) { Contract.Requires(var != null); Contract.Requires(cce.NonNullElements(types)); Contract.Requires(cce.NonNullElements(concreteTypeSources)); List allExtractors = TypeVarExtractors(var, types, concreteTypeSources); Contract.Assert(cce.NonNullElements(allExtractors)); - if (allExtractors.Count == 0) - { + if (allExtractors.Count == 0) { return null; } VCExpr bestExtractor = allExtractors[0]; int bestExtractorSize = SizeComputingVisitor.ComputeSize(bestExtractor); - for (int i = 1; i < allExtractors.Count; ++i) - { + for (int i = 1; i < allExtractors.Count; ++i) { int newSize = SizeComputingVisitor.ComputeSize(allExtractors[i]); - if (newSize < bestExtractorSize) - { + if (newSize < bestExtractorSize) { bestExtractor = allExtractors[i]; bestExtractorSize = newSize; } @@ -326,8 +292,7 @@ private VCExpr BestTypeVarExtractor(TypeVariable /*!*/ var, List /*! } private List /*!*/ TypeVarExtractors(TypeVariable /*!*/ var, List /*!*/ types, - List /*!*/ concreteTypeSources) - { + List /*!*/ concreteTypeSources) { Contract.Requires(var != null); Contract.Requires(cce.NonNullElements(types)); Contract.Requires(cce.NonNullElements(concreteTypeSources)); @@ -335,8 +300,7 @@ private VCExpr BestTypeVarExtractor(TypeVariable /*!*/ var, List /*! Contract.Ensures(cce.NonNullElements(Contract.Result>())); List /*!*/ res = new List(); - for (int i = 0; i < types.Count; ++i) - { + for (int i = 0; i < types.Count; ++i) { TypeVarExtractors(var, types[i], TypeOf(concreteTypeSources[i]), res); } @@ -344,48 +308,35 @@ private VCExpr BestTypeVarExtractor(TypeVariable /*!*/ var, List /*! } private void TypeVarExtractors(TypeVariable var, Type completeType, VCExpr innerTerm, - List /*!*/ extractors) - { + List /*!*/ extractors) { Contract.Requires(innerTerm != null); Contract.Requires(completeType != null); Contract.Requires(var != null); Contract.Requires(cce.NonNullElements(extractors)); - if (completeType.IsVariable) - { - if (var.Equals(completeType)) - { + if (completeType.IsVariable) { + if (var.Equals(completeType)) { extractors.Add(innerTerm); } // else nothing - } - else if (completeType.IsBasic) - { + } else if (completeType.IsBasic) { // nothing - } - else if (completeType.IsCtor) - { + } else if (completeType.IsCtor) { CtorType /*!*/ ctorType = completeType.AsCtor; - if (ctorType.Arguments.Count > 0) - { + if (ctorType.Arguments.Count > 0) { // otherwise there are no chances of extracting any // instantiations from this type TypeCtorRepr repr = GetTypeCtorReprStruct(ctorType.Decl); - for (int i = 0; i < ctorType.Arguments.Count; ++i) - { + for (int i = 0; i < ctorType.Arguments.Count; ++i) { VCExpr /*!*/ newInnerTerm = Gen.Function(repr.Dtors[i], innerTerm); Contract.Assert(newInnerTerm != null); TypeVarExtractors(var, ctorType.Arguments[i], newInnerTerm, extractors); } } - } - else if (completeType.IsMap) - { + } else if (completeType.IsMap) { TypeVarExtractors(var, MapTypeAbstracter.AbstractMapType(completeType.AsMap), innerTerm, extractors); - } - else - { + } else { System.Diagnostics.Debug.Fail("Don't know how to handle this type: " + completeType); } } @@ -398,8 +349,7 @@ private void TypeVarExtractors(TypeVariable var, Type completeType, VCExpr inner Typed2UntypedFunctions; [ContractInvariantMethod] - void Typed2UntypedFunctionsInvariantMethod() - { + void Typed2UntypedFunctionsInvariantMethod() { Contract.Invariant(Typed2UntypedFunctions != null); } @@ -407,16 +357,14 @@ void Typed2UntypedFunctionsInvariantMethod() internal static void SeparateTypeParams(List /*!*/ valueArgumentTypes, List /*!*/ allTypeParams, out List /*!*/ implicitParams, - out List /*!*/ explicitParams) - { + out List /*!*/ explicitParams) { Contract.Requires(cce.NonNullElements(valueArgumentTypes)); Contract.Requires(allTypeParams != null); Contract.Ensures(cce.NonNullElements(Contract.ValueAtReturn(out implicitParams))); Contract.Ensures(cce.NonNullElements(Contract.ValueAtReturn(out explicitParams))); List /*!*/ varsInInParamTypes = new List(); - foreach (Type /*!*/ t in valueArgumentTypes) - { + foreach (Type /*!*/ t in valueArgumentTypes) { Contract.Assert(t != null); varsInInParamTypes.AppendWithoutDups(t.FreeVariables); } @@ -424,15 +372,11 @@ internal static void SeparateTypeParams(List /*!*/ valueArgumentType implicitParams = new List(allTypeParams.Count); explicitParams = new List(allTypeParams.Count); - foreach (TypeVariable /*!*/ var in allTypeParams) - { + foreach (TypeVariable /*!*/ var in allTypeParams) { Contract.Assert(var != null); - if (varsInInParamTypes.Contains(var)) - { + if (varsInInParamTypes.Contains(var)) { implicitParams.Add(var); - } - else - { + } else { explicitParams.Add(var); } } @@ -441,27 +385,21 @@ internal static void SeparateTypeParams(List /*!*/ valueArgumentType explicitParams.TrimExcess(); } - internal UntypedFunction Typed2Untyped(Function fun) - { + internal UntypedFunction Typed2Untyped(Function fun) { Contract.Requires(fun != null); - if (!Typed2UntypedFunctions.TryGetValue(fun, out var res)) - { + if (!Typed2UntypedFunctions.TryGetValue(fun, out var res)) { Contract.Assert(fun.OutParams.Count == 1); // if all of the parameters are int or bool, the function does // not have to be changed if (fun.InParams.All(param => UnchangedType(cce.NonNull(param).TypedIdent.Type)) && UnchangedType(cce.NonNull(fun.OutParams[0]).TypedIdent.Type) && - fun.TypeParameters.Count == 0) - { + fun.TypeParameters.Count == 0) { res = new UntypedFunction(fun, new List(), new List()); - } - else - { + } else { List /*!*/ argTypes = new List(); - foreach (Variable /*!*/ v in fun.InParams) - { + foreach (Variable /*!*/ v in fun.InParams) { Contract.Assert(v != null); argTypes.Add(v.TypedIdent.Type); } @@ -471,14 +409,12 @@ internal UntypedFunction Typed2Untyped(Function fun) Type[] /*!*/ types = new Type[explicitParams.Count + fun.InParams.Count + 1]; int i = 0; - for (int j = 0; j < explicitParams.Count; ++j) - { + for (int j = 0; j < explicitParams.Count; ++j) { types[i] = T; i = i + 1; } - for (int j = 0; j < fun.InParams.Count; ++i, ++j) - { + for (int j = 0; j < fun.InParams.Count; ++i, ++j) { types[i] = TypeAfterErasure(cce.NonNull(fun.InParams[j]).TypedIdent.Type); } @@ -489,8 +425,7 @@ internal UntypedFunction Typed2Untyped(Function fun) Contract.Assert(untypedFun != null); untypedFun.Attributes = fun.Attributes; res = new UntypedFunction(untypedFun, implicitParams, explicitParams); - if (U.Equals(types[types.Length - 1])) - { + if (U.Equals(types[types.Length - 1])) { AddTypeAxiom(GenFunctionAxiom(res, fun)); } } @@ -501,14 +436,12 @@ internal UntypedFunction Typed2Untyped(Function fun) return res; } - private VCExpr GenFunctionAxiom(UntypedFunction fun, Function originalFun) - { + private VCExpr GenFunctionAxiom(UntypedFunction fun, Function originalFun) { Contract.Requires(originalFun != null); Contract.Ensures(Contract.Result() != null); List /*!*/ originalInTypes = new List(originalFun.InParams.Count); - foreach (Formal /*!*/ f in originalFun.InParams) - { + foreach (Formal /*!*/ f in originalFun.InParams) { originalInTypes.Add(f.TypedIdent.Type); } @@ -521,8 +454,7 @@ private VCExpr GenFunctionAxiom(UntypedFunction fun, Function originalFun) List /*!*/ implicitTypeParams, List /*!*/ explicitTypeParams, List /*!*/ originalInTypes, - Type /*!*/ originalResultType) - { + Type /*!*/ originalResultType) { Contract.Requires(cce.NonNullElements(implicitTypeParams)); Contract.Requires(fun != null); Contract.Requires(cce.NonNullElements(explicitTypeParams)); @@ -534,8 +466,7 @@ private VCExpr GenFunctionAxiom(UntypedFunction fun, Function originalFun) List /*!*/ typedInputVars = new List(originalInTypes.Count); int i = 0; - foreach (Type /*!*/ t in originalInTypes) - { + foreach (Type /*!*/ t in originalInTypes) { Contract.Assert(t != null); typedInputVars.Add(Gen.Variable("arg" + i, t)); i = i + 1; @@ -548,8 +479,7 @@ private VCExpr GenFunctionAxiom(UntypedFunction fun, Function originalFun) // with universally quantified type variables List /*!*/ boundVars = new List(explicitTypeParams.Count + typedInputVars.Count); - foreach (TypeVariable /*!*/ var in explicitTypeParams) - { + foreach (TypeVariable /*!*/ var in explicitTypeParams) { Contract.Assert(var != null); VCExprVar /*!*/ newVar = Gen.Variable(var.Name, T); @@ -559,8 +489,7 @@ private VCExpr GenFunctionAxiom(UntypedFunction fun, Function originalFun) // bound term variables are replaced with bound term variables typed in // a simpler way - foreach (VCExprVar /*!*/ var in typedInputVars) - { + foreach (VCExprVar /*!*/ var in typedInputVars) { Contract.Assert(var != null); Type /*!*/ newType = TypeAfterErasure(var.Type); @@ -594,22 +523,18 @@ private VCExpr GenFunctionAxiom(UntypedFunction fun, Function originalFun) VCExpr conclusionWithPremisses = AddTypePremisses(typeVarBindings, typePremisses, true, conclusion); - if (boundVars.Count > 0) - { + if (boundVars.Count > 0) { List triggers = HelperFuns.ToList(Gen.Trigger(true, HelperFuns.ToList(funApp))); Contract.Assert(cce.NonNullElements(triggers)); return Gen.Forall(boundVars, triggers, "funType:" + fun.Name, 1, conclusionWithPremisses); - } - else - { + } else { return conclusionWithPremisses; } } //////////////////////////////////////////////////////////////////////////// - protected override void AddVarTypeAxiom(VCExprVar var, Type originalType) - { + protected override void AddVarTypeAxiom(VCExprVar var, Type originalType) { //Contract.Requires(originalType != null); //Contract.Requires(var != null); AddTypeAxiom(GenVarTypeAxiom(var, originalType, @@ -618,15 +543,13 @@ protected override void AddVarTypeAxiom(VCExprVar var, Type originalType) } public VCExpr GenVarTypeAxiom(VCExprVar var, Type originalType, - IDictionary /*!*/ varMapping) - { + IDictionary /*!*/ varMapping) { Contract.Requires(var != null); Contract.Requires(originalType != null); Contract.Requires(cce.NonNullDictionaryAndValues(varMapping)); Contract.Ensures(Contract.Result() != null); - if (!var.Type.Equals(originalType)) - { + if (!var.Type.Equals(originalType)) { VCExpr /*!*/ typeRepr = Type2Term(originalType, varMapping); return Gen.Eq(TypeOf(var), typeRepr); @@ -638,20 +561,17 @@ public VCExpr GenVarTypeAxiom(VCExprVar var, Type originalType, ///////////////////////////////////////////////////////////////////////////// - internal class MapTypeAbstractionBuilderPremisses : MapTypeAbstractionBuilder - { + internal class MapTypeAbstractionBuilderPremisses : MapTypeAbstractionBuilder { private readonly TypeAxiomBuilderPremisses /*!*/ AxBuilderPremisses; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(AxBuilderPremisses != null); } internal MapTypeAbstractionBuilderPremisses(TypeAxiomBuilderPremisses axBuilder, VCExpressionGenerator gen) - : base(axBuilder, gen) - { + : base(axBuilder, gen) { Contract.Requires(gen != null); Contract.Requires(axBuilder != null); @@ -661,8 +581,7 @@ internal MapTypeAbstractionBuilderPremisses(TypeAxiomBuilderPremisses axBuilder, // constructor for cloning internal MapTypeAbstractionBuilderPremisses(TypeAxiomBuilderPremisses axBuilder, VCExpressionGenerator gen, MapTypeAbstractionBuilderPremisses builder) - : base(axBuilder, gen, builder) - { + : base(axBuilder, gen, builder) { Contract.Requires(builder != null); Contract.Requires(gen != null); Contract.Requires(axBuilder != null); @@ -678,20 +597,17 @@ internal MapTypeAbstractionBuilderPremisses(TypeAxiomBuilderPremisses axBuilder, // map). These parameters are given as a list of indexes sorted in // ascending order; the index i refers to the i'th bound variable // in a type [...]... - public List /*!*/ ExplicitSelectTypeParams(MapType type) - { + public List /*!*/ ExplicitSelectTypeParams(MapType type) { Contract.Requires(type != null); Contract.Ensures(Contract.Result>() != null); - if (!explicitSelectTypeParamsCache.TryGetValue(type, out var res)) - { + if (!explicitSelectTypeParamsCache.TryGetValue(type, out var res)) { TypeAxiomBuilderPremisses.SeparateTypeParams(type.Arguments.ToList(), type.TypeParameters, out var implicitParams, out var explicitParams); res = new List(explicitParams.Count); - foreach (TypeVariable /*!*/ var in explicitParams) - { + foreach (TypeVariable /*!*/ var in explicitParams) { Contract.Assert(var != null); res.Add(type.TypeParameters.IndexOf(var)); } @@ -707,8 +623,7 @@ internal MapTypeAbstractionBuilderPremisses(TypeAxiomBuilderPremisses axBuilder, new Dictionary /*!*/>(); [ContractInvariantMethod] - void ObjectInvarant() - { + void ObjectInvarant() { Contract.Invariant(cce.NonNullDictionaryAndValues(explicitSelectTypeParamsCache)); } @@ -716,8 +631,7 @@ void ObjectInvarant() //////////////////////////////////////////////////////////////////////////// protected override void GenSelectStoreFunctions(MapType abstractedType, TypeCtorDecl synonym, - out Function /*!*/ select, out Function /*!*/ store) - { + out Function /*!*/ select, out Function /*!*/ store) { //Contract.Requires(synonym != null); //Contract.Requires(abstractedType != null); Contract.Ensures(Contract.ValueAtReturn(out select) != null); @@ -748,8 +662,7 @@ protected override void GenSelectStoreFunctions(MapType abstractedType, TypeCtor protected void GenTypeAxiomParams(MapType /*!*/ abstractedType, TypeCtorDecl /*!*/ synonymDecl, out Type /*!*/ mapTypeSynonym, out List /*!*/ typeParams, - out List /*!*/ originalIndexTypes) - { + out List /*!*/ originalIndexTypes) { Contract.Requires(abstractedType != null); Contract.Requires(synonymDecl != null); Contract.Ensures(Contract.ValueAtReturn(out mapTypeSynonym) != null); @@ -762,8 +675,7 @@ protected void GenTypeAxiomParams(MapType /*!*/ abstractedType, TypeCtorDecl /*! originalIndexTypes = new List(abstractedType.Arguments.Count + 1); List /*!*/ mapTypeParams = new List(); - foreach (TypeVariable /*!*/ var in abstractedType.FreeVariables) - { + foreach (TypeVariable /*!*/ var in abstractedType.FreeVariables) { Contract.Assert(var != null); mapTypeParams.Add(var); } @@ -779,8 +691,7 @@ protected void GenTypeAxiomParams(MapType /*!*/ abstractedType, TypeCtorDecl /*! List /*!*/ originalInTypes, Type /*!*/ originalResult, string /*!*/ name, - out List /*!*/ implicitTypeParams, out List /*!*/ explicitTypeParams) - { + out List /*!*/ implicitTypeParams, out List /*!*/ explicitTypeParams) { Contract.Requires(cce.NonNullElements(originalTypeParams)); Contract.Requires(cce.NonNullElements(originalInTypes)); Contract.Requires(originalResult != null); @@ -800,13 +711,11 @@ protected void GenTypeAxiomParams(MapType /*!*/ abstractedType, TypeCtorDecl /*! Type[] /*!*/ ioTypes = new Type[explicitTypeParams.Count + originalInTypes.Count + 1]; int i = 0; - for (; i < explicitTypeParams.Count; ++i) - { + for (; i < explicitTypeParams.Count; ++i) { ioTypes[i] = AxBuilder.T; } - foreach (Type /*!*/ type in originalInTypes) - { + foreach (Type /*!*/ type in originalInTypes) { Contract.Assert(type != null); ioTypes[i] = AxBuilder.U; i++; @@ -818,8 +727,7 @@ protected void GenTypeAxiomParams(MapType /*!*/ abstractedType, TypeCtorDecl /*! res = HelperFuns.BoogieFunction(name, ioTypes); Contract.Assert(res != null); - if (AxBuilder.U.Equals(ioTypes[i])) - { + if (AxBuilder.U.Equals(ioTypes[i])) { AxBuilder.AddTypeAxiom( AxBuilderPremisses.GenFunctionAxiom(res, implicitTypeParams, explicitTypeParams, @@ -839,8 +747,7 @@ protected void GenTypeAxiomParams(MapType /*!*/ abstractedType, TypeCtorDecl /*! // of type T) List /*!*/ typeParams, VCExpr /*!*/ map, - List /*!*/ indexes) - { + List /*!*/ indexes) { Contract.Requires(select != null); Contract.Requires(cce.NonNullElements(typeParams)); Contract.Requires(map != null); @@ -855,8 +762,7 @@ protected void GenTypeAxiomParams(MapType /*!*/ abstractedType, TypeCtorDecl /*! return Gen.Function(select, selectArgs); } - private VCExpr Store(Function store, VCExpr map, List /*!*/ indexes, VCExpr val) - { + private VCExpr Store(Function store, VCExpr map, List /*!*/ indexes, VCExpr val) { Contract.Requires(val != null); Contract.Requires(map != null); Contract.Requires(store != null); @@ -879,8 +785,7 @@ private VCExpr Store(Function store, VCExpr map, List /*!*/ ind /// private VCExpr GenMapAxiom0(Function select, Function store, Type mapResult, List /*!*/ implicitTypeParamsSelect, List /*!*/ explicitTypeParamsSelect, - List /*!*/ originalInTypes) - { + List /*!*/ originalInTypes) { Contract.Requires(mapResult != null); Contract.Requires(store != null); Contract.Requires(select != null); @@ -903,8 +808,7 @@ private VCExpr GenMapAxiom0(Function select, Function store, Type mapResult, // bound variables: indexes List origIndexTypes = new List(arity); List indexTypes = new List(arity); - for (int i = 1; i < store.InParams.Count - 1; i++) - { + for (int i = 1; i < store.InParams.Count - 1; i++) { origIndexTypes.Add(originalInTypes[i]); indexTypes.Add(cce.NonNull(store.InParams[i]).TypedIdent.Type); } @@ -917,8 +821,7 @@ private VCExpr GenMapAxiom0(Function select, Function store, Type mapResult, Contract.Assert(typedArgs.Count == indexes.Count); inParams.AddRange(typedArgs); quantifiedVars.AddRange(indexes); - for (int i = 0; i < arity; i++) - { + for (int i = 0; i < arity; i++) { bindings.VCExprVarBindings.Add(typedArgs[i], indexes[i]); } @@ -929,15 +832,13 @@ private VCExpr GenMapAxiom0(Function select, Function store, Type mapResult, bindings.VCExprVarBindings.Add(typedVal, val); // add all type parameters into bindings - foreach (TypeVariable tp in implicitTypeParamsSelect) - { + foreach (TypeVariable tp in implicitTypeParamsSelect) { VCExprVar tVar = Gen.Variable(tp.Name, AxBuilderPremisses.T); bindings.TypeVariableBindings.Add(tp, tVar); } List typeParams = new List(explicitTypeParamsSelect.Count); - foreach (TypeVariable tp in explicitTypeParamsSelect) - { + foreach (TypeVariable tp in explicitTypeParamsSelect) { VCExprVar tVar = Gen.Variable(tp.Name, AxBuilderPremisses.T); bindings.TypeVariableBindings.Add(tp, tVar); // ... and record these explicit type-parameter arguments in typeParams @@ -975,12 +876,9 @@ private VCExpr GenMapAxiom0(Function select, Function store, Type mapResult, AxBuilderPremisses.Type2Term(mapResult, bindings.TypeVariableBindings)); Contract.Assert(ante != null); VCExpr body; - if (!AxBuilder.U.Equals(cce.NonNull(select.OutParams[0]).TypedIdent.Type)) - { + if (!AxBuilder.U.Equals(cce.NonNull(select.OutParams[0]).TypedIdent.Type)) { body = Gen.Let(letBindings_Explicit, eq); - } - else - { + } else { body = Gen.Let(letBindings_Implicit, Gen.Let(letBindings_Explicit, Gen.ImpliesSimp(ante, eq))); } @@ -988,8 +886,7 @@ private VCExpr GenMapAxiom0(Function select, Function store, Type mapResult, } private VCExpr GenMapAxiom1(Function select, Function store, Type mapResult, - List /*!*/ explicitSelectParams) - { + List /*!*/ explicitSelectParams) { Contract.Requires(mapResult != null); Contract.Requires(store != null); Contract.Requires(select != null); @@ -998,8 +895,7 @@ private VCExpr GenMapAxiom1(Function select, Function store, Type mapResult, int arity = store.InParams.Count - 2; List indexTypes = new List(); - for (int i = 1; i < store.InParams.Count - 1; i++) - { + for (int i = 1; i < store.InParams.Count - 1; i++) { indexTypes.Add(cce.NonNull(store.InParams[i]).TypedIdent.Type); } @@ -1039,11 +935,10 @@ private VCExpr GenMapAxiom1(Function select, Function store, Type mapResult, typeParams = new List(explicitSelectParams.Count); List /*!*/ typeParamsExpr = new List(explicitSelectParams.Count); - foreach (TypeVariable /*!*/ var in explicitSelectParams) - { + foreach (TypeVariable /*!*/ var in explicitSelectParams) { Contract.Assert(var != null); VCExprVar /*!*/ - newVar = (VCExprVar) bindings.TypeVariableBindings[var]; + newVar = (VCExprVar)bindings.TypeVariableBindings[var]; Contract.Assert(newVar != null); typeParams.Add(newVar); typeParamsExpr.Add(newVar); @@ -1081,8 +976,7 @@ private VCExpr GenMapAxiom1(Function select, Function store, Type mapResult, // first non-interference criterium: the queried location is // different from the assigned location - for (int i = 0; i < arity; ++i) - { + for (int i = 0; i < arity; ++i) { VCExpr /*!*/ indexesEq = Gen.Eq(indexes0[i], indexes1[i]); VCExpr /*!*/ @@ -1099,8 +993,7 @@ private VCExpr GenMapAxiom1(Function select, Function store, Type mapResult, // different from the assigned type VCExpr /*!*/ typesEq = VCExpressionGenerator.True; - foreach (VCExprLetBinding /*!*/ b in letBindings) - { + foreach (VCExprLetBinding /*!*/ b in letBindings) { Contract.Assert(b != null); typesEq = Gen.AndSimp(typesEq, Gen.Eq(b.V, b.E)); } diff --git a/Source/VCExpr/TypeErasure/VariableBindings.cs b/Source/VCExpr/TypeErasure/VariableBindings.cs index 7085846c0..2b8abac8a 100644 --- a/Source/VCExpr/TypeErasure/VariableBindings.cs +++ b/Source/VCExpr/TypeErasure/VariableBindings.cs @@ -4,8 +4,7 @@ namespace Microsoft.Boogie.TypeErasure; -public class VariableBindings -{ +public class VariableBindings { public readonly IDictionary /*!*/ VCExprVarBindings; @@ -13,16 +12,14 @@ public class VariableBindings TypeVariableBindings; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(cce.NonNullDictionaryAndValues(VCExprVarBindings)); Contract.Invariant(cce.NonNullDictionaryAndValues(TypeVariableBindings)); } public VariableBindings(IDictionary /*!*/ vcExprVarBindings, - IDictionary /*!*/ typeVariableBindings) - { + IDictionary /*!*/ typeVariableBindings) { Contract.Requires(cce.NonNullDictionaryAndValues(vcExprVarBindings)); Contract.Requires(cce.NonNullDictionaryAndValues(typeVariableBindings)); this.VCExprVarBindings = vcExprVarBindings; @@ -31,18 +28,15 @@ public VariableBindings(IDictionary /*!*/ vcEx public VariableBindings() : this(new Dictionary(), - new Dictionary()) - { + new Dictionary()) { } - public VariableBindings Clone() - { + public VariableBindings Clone() { Contract.Ensures(Contract.Result() != null); IDictionary /*!*/ newVCExprVarBindings = new Dictionary(); - foreach (KeyValuePair pair in VCExprVarBindings) - { + foreach (KeyValuePair pair in VCExprVarBindings) { Contract.Assert(cce.NonNullElements(pair)); newVCExprVarBindings.Add(pair); } @@ -50,8 +44,7 @@ public VariableBindings Clone() IDictionary /*!*/ newTypeVariableBindings = new Dictionary(); - foreach (KeyValuePair pair in TypeVariableBindings) - { + foreach (KeyValuePair pair in TypeVariableBindings) { Contract.Assert(cce.NonNullElements(pair)); newTypeVariableBindings.Add(pair); } diff --git a/Source/VCExpr/TypeErasure/VariableCastCollector.cs b/Source/VCExpr/TypeErasure/VariableCastCollector.cs index 860a509f6..67a15aa58 100644 --- a/Source/VCExpr/TypeErasure/VariableCastCollector.cs +++ b/Source/VCExpr/TypeErasure/VariableCastCollector.cs @@ -9,8 +9,7 @@ namespace Microsoft.Boogie.TypeErasure; /// Collect all variables x occurring in expressions of the form Int2U(x) or Bool2U(x), and /// collect all variables x occurring outside such forms. /// -internal class VariableCastCollector : TraversingVCExprVisitor -{ +internal class VariableCastCollector : TraversingVCExprVisitor { /// /// Determine those bound variables in "oldNode" all of whose relevant uses /// have to be cast in potential triggers in "newNode". It is assume that @@ -18,8 +17,7 @@ internal class VariableCastCollector : TraversingVCExprVisitor /// variables of "newNode". /// public static List /*!*/ FindCastVariables(VCExprQuantifier oldNode, VCExprQuantifier newNode, - TypeAxiomBuilderIntBoolU axBuilder) - { + TypeAxiomBuilderIntBoolU axBuilder) { Contract.Requires((axBuilder != null)); Contract.Requires((newNode != null)); Contract.Requires((oldNode != null)); @@ -27,36 +25,28 @@ internal class VariableCastCollector : TraversingVCExprVisitor VariableCastCollector /*!*/ collector = new VariableCastCollector(axBuilder); Contract.Assert(collector != null); - if (newNode.Triggers.Any(trigger => trigger.Pos)) - { + if (newNode.Triggers.Any(trigger => trigger.Pos)) { // look in the given triggers - foreach (VCTrigger /*!*/ trigger in newNode.Triggers) - { + foreach (VCTrigger /*!*/ trigger in newNode.Triggers) { Contract.Assert(trigger != null); - if (trigger.Pos) - { - foreach (VCExpr /*!*/ expr in trigger.Exprs) - { + if (trigger.Pos) { + foreach (VCExpr /*!*/ expr in trigger.Exprs) { Contract.Assert(expr != null); collector.Traverse(expr, true); } } } - } - else - { + } else { // look in the body of the quantifier collector.Traverse(newNode.Body, true); } List /*!*/ castVariables = new List(collector.varsInCasts.Count); - foreach (VCExprVar /*!*/ castVar in collector.varsInCasts) - { + foreach (VCExprVar /*!*/ castVar in collector.varsInCasts) { Contract.Assert(castVar != null); int i = newNode.BoundVars.IndexOf(castVar); - if (0 <= i && i < oldNode.BoundVars.Count && !collector.varsOutsideCasts.ContainsKey(castVar)) - { + if (0 <= i && i < oldNode.BoundVars.Count && !collector.varsOutsideCasts.ContainsKey(castVar)) { castVariables.Add(oldNode.BoundVars[i]); } } @@ -64,8 +54,7 @@ internal class VariableCastCollector : TraversingVCExprVisitor return castVariables; } - public VariableCastCollector(TypeAxiomBuilderIntBoolU axBuilder) - { + public VariableCastCollector(TypeAxiomBuilderIntBoolU axBuilder) { Contract.Requires(axBuilder != null); this.AxBuilder = axBuilder; } @@ -77,8 +66,7 @@ readonly List /*!*/ varsOutsideCasts = new Dictionary(); [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(cce.NonNullElements(varsInCasts)); Contract.Invariant(varsOutsideCasts != null && Contract.ForAll(varsOutsideCasts, voc => voc.Key != null)); Contract.Invariant(AxBuilder != null); @@ -88,35 +76,27 @@ void ObjectInvariant() readonly TypeAxiomBuilderIntBoolU /*!*/ AxBuilder; - protected override bool StandardResult(VCExpr node, bool arg) - { + protected override bool StandardResult(VCExpr node, bool arg) { //Contract.Requires(node != null); return true; // not used } - public override bool Visit(VCExprNAry node, bool arg) - { + public override DynamicStack Visit(VCExprNAry node, bool arg) { Contract.Requires(node != null); - if (node.Op is VCExprBoogieFunctionOp) - { - Function func = ((VCExprBoogieFunctionOp) node.Op).Func; + if (node.Op is VCExprBoogieFunctionOp) { + Function func = ((VCExprBoogieFunctionOp)node.Op).Func; Contract.Assert(func != null); - if ((AxBuilder.IsCast(func)) && node[0] is VCExprVar) - { - VCExprVar castVar = (VCExprVar) node[0]; - if (!varsInCasts.Contains(castVar)) - { + if ((AxBuilder.IsCast(func)) && node[0] is VCExprVar) { + VCExprVar castVar = (VCExprVar)node[0]; + if (!varsInCasts.Contains(castVar)) { varsInCasts.Add(castVar); } - return true; + return DynamicStack.FromResult(true); } - } - else if (node.Op is VCExprNAryOp) - { + } else if (node.Op is VCExprNAryOp) { VCExpressionGenerator.SingletonOp op = VCExpressionGenerator.SingletonOpDict[node.Op]; - switch (op) - { + switch (op) { // the following operators cannot be used in triggers, so disregard any uses of variables as direct arguments case VCExpressionGenerator.SingletonOp.NotOp: case VCExpressionGenerator.SingletonOp.EqOp: @@ -128,16 +108,14 @@ public override bool Visit(VCExprNAry node, bool arg) case VCExpressionGenerator.SingletonOp.LeOp: case VCExpressionGenerator.SingletonOp.GtOp: case VCExpressionGenerator.SingletonOp.GeOp: - foreach (VCExpr n in node.Arguments) - { - if (!(n is VCExprVar)) - { + foreach (VCExpr n in node.Arguments) { + if (!(n is VCExprVar)) { // don't recurse on VCExprVar argument n.Accept(this, arg); } } - return true; + return DynamicStack.FromResult(true); default: break; } @@ -146,11 +124,9 @@ public override bool Visit(VCExprNAry node, bool arg) return base.Visit(node, arg); } - public override bool Visit(VCExprVar node, bool arg) - { + public override bool Visit(VCExprVar node, bool arg) { Contract.Requires(node != null); - if (!varsOutsideCasts.ContainsKey(node)) - { + if (!varsOutsideCasts.ContainsKey(node)) { varsOutsideCasts.Add(node, null); } diff --git a/Source/VCExpr/UniqueNamer.cs b/Source/VCExpr/UniqueNamer.cs index 23acbd78d..adfda5fbe 100644 --- a/Source/VCExpr/UniqueNamer.cs +++ b/Source/VCExpr/UniqueNamer.cs @@ -1,9 +1,7 @@ using System; -namespace Microsoft.Boogie.VCExprAST -{ - public interface UniqueNamer - { +namespace Microsoft.Boogie.VCExprAST { + public interface UniqueNamer { string Lookup(Object thingie); string GetName(Object thing, string name); diff --git a/Source/VCExpr/VCExprAST.cs b/Source/VCExpr/VCExprAST.cs index a8f68dcbe..95fd689ed 100644 --- a/Source/VCExpr/VCExprAST.cs +++ b/Source/VCExpr/VCExprAST.cs @@ -9,100 +9,79 @@ // The language can be seen as a simple polymorphically typed first-order logic, // very similar to the expression language of Boogie -namespace Microsoft.Boogie.VCExprAST -{ - public class HelperFuns - { - public static bool SameElements(IEnumerable a, IEnumerable b) - { +namespace Microsoft.Boogie.VCExprAST { + public class HelperFuns { + public static bool SameElements(IEnumerable a, IEnumerable b) { Contract.Requires(b != null); Contract.Requires(a != null); IEnumerator ia = a.GetEnumerator(); IEnumerator ib = b.GetEnumerator(); - while (true) - { - if (ia.MoveNext()) - { - if (ib.MoveNext()) - { - if (!cce.NonNull(ia.Current).Equals(ib.Current)) - { + while (true) { + if (ia.MoveNext()) { + if (ib.MoveNext()) { + if (!cce.NonNull(ia.Current).Equals(ib.Current)) { return false; } - } - else - { + } else { return false; } - } - else - { + } else { return !ib.MoveNext(); } } } - public static int PolyHash(int init, int factor, IEnumerable a) - { + public static int PolyHash(int init, int factor, IEnumerable a) { Contract.Requires(a != null); int res = init; - foreach (object x in a) - { + foreach (object x in a) { res = res * factor + (cce.NonNull(x)).GetHashCode(); } return res; } - public static List ToList(IEnumerable l) - { + public static List ToList(IEnumerable l) { Contract.Requires(l != null); Contract.Ensures(Contract.Result>() != null); List /*!*/ res = new List(); - foreach (T x in l) - { + foreach (T x in l) { res.Add(x); } return res; } - public static List ToTypeSeq(VCExpr[] exprs, int startIndex) - { + public static List ToTypeSeq(VCExpr[] exprs, int startIndex) { Contract.Requires(exprs != null); Contract.Requires((Contract.ForAll(0, exprs.Length, i => exprs[i] != null))); Contract.Ensures(Contract.Result>() != null); List /*!*/ res = new List(); - for (int i = startIndex; i < exprs.Length; ++i) - { + for (int i = startIndex; i < exprs.Length; ++i) { res.Add(cce.NonNull(exprs[i]).Type); } return res; } - public static List /*!*/ ToNonNullList(params T[] args) where T : class - { + public static List /*!*/ ToNonNullList(params T[] args) where T : class { Contract.Requires(args != null); List /*!*/ res = new List(args.Length); - foreach (T t in args) - { + foreach (T t in args) { res.Add(cce.NonNull(t)); } return res; } - public static IDictionary Clone(IDictionary dict) - { + public static IDictionary Clone(IDictionary dict) { Contract.Requires(dict != null); Contract.Ensures(Contract.Result>() != null); IDictionary res = new Dictionary(dict.Count); - foreach (KeyValuePair pair in dict) - { + foreach (KeyValuePair pair in dict) { res.Add(pair); } @@ -111,34 +90,28 @@ public static IDictionary Clone(IDictionary dict) } [ContractClassFor(typeof(VCExpr))] - public abstract class VCExprContracts : VCExpr - { - public override Type Type - { - get - { + public abstract class VCExprContracts : VCExpr { + public override Type Type { + get { Contract.Ensures(Contract.Result() != null); throw new NotImplementedException(); } } - public override Result Accept(IVCExprVisitor visitor, Arg arg) - { + public override DynamicStack Accept(IVCExprVisitor visitor, Arg arg) { Contract.Requires(visitor != null); throw new NotImplementedException(); } } [ContractClass(typeof(VCExprContracts))] - public abstract class VCExpr - { + public abstract class VCExpr { public abstract Type Type { get; } - public abstract Result Accept(IVCExprVisitor visitor, Arg arg); + public abstract DynamicStack Accept(IVCExprVisitor visitor, Arg arg); [Pure] - public override string ToString() - { + public override string ToString() { Contract.Ensures(Contract.Result() != null); StringWriter sw = new StringWriter(); VCExprPrinter printer = new VCExprPrinter(PrintOptions.Default); @@ -150,200 +123,165 @@ public override string ToString() ///////////////////////////////////////////////////////////////////////////////// // Literal expressions - public class VCExprLiteral : VCExpr - { + public class VCExprLiteral : VCExpr { private readonly Type LitType; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(LitType != null); } - public override Type Type - { + public override Type Type { get { return LitType; } } - internal VCExprLiteral(Type type) - { + internal VCExprLiteral(Type type) { Contract.Requires(type != null); this.LitType = type; } - public override Result Accept(IVCExprVisitor visitor, Arg arg) - { + public override DynamicStack Accept(IVCExprVisitor visitor, Arg arg) { //Contract.Requires(visitor != null); - return visitor.Visit(this, arg); + return DynamicStack.FromResult(visitor.Visit(this, arg)); } } - public class VCExprIntLit : VCExprLiteral - { + public class VCExprIntLit : VCExprLiteral { public readonly BigNum Val; internal VCExprIntLit(BigNum val) - : base(Type.Int) - { + : base(Type.Int) { this.Val = val; } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] - public override bool Equals(object that) - { - if (Object.ReferenceEquals(this, that)) - { + public override bool Equals(object that) { + if (Object.ReferenceEquals(this, that)) { return true; } - if (that is VCExprIntLit) - { - return Val == ((VCExprIntLit) that).Val; + if (that is VCExprIntLit) { + return Val == ((VCExprIntLit)that).Val; } return false; } [Pure] - public override int GetHashCode() - { + public override int GetHashCode() { return Val.GetHashCode() * 72321; } } - public class VCExprRealLit : VCExprLiteral - { + public class VCExprRealLit : VCExprLiteral { public readonly BigDec Val; internal VCExprRealLit(BigDec val) - : base(Type.Real) - { + : base(Type.Real) { this.Val = val; } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] - public override bool Equals(object that) - { - if (Object.ReferenceEquals(this, that)) - { + public override bool Equals(object that) { + if (Object.ReferenceEquals(this, that)) { return true; } - if (that is VCExprRealLit) - { - return Val == ((VCExprRealLit) that).Val; + if (that is VCExprRealLit) { + return Val == ((VCExprRealLit)that).Val; } return false; } [Pure] - public override int GetHashCode() - { + public override int GetHashCode() { return Val.GetHashCode() * 72321; } } - public class VCExprFloatLit : VCExprLiteral - { + public class VCExprFloatLit : VCExprLiteral { public readonly BigFloat Val; internal VCExprFloatLit(BigFloat val) - : base(Type.GetFloatType(val.SignificandSize, val.ExponentSize)) - { + : base(Type.GetFloatType(val.SignificandSize, val.ExponentSize)) { this.Val = val; } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] - public override bool Equals(object that) - { - if (Object.ReferenceEquals(this, that)) - { + public override bool Equals(object that) { + if (Object.ReferenceEquals(this, that)) { return true; } - if (that is VCExprFloatLit) - { - return Val == ((VCExprFloatLit) that).Val; + if (that is VCExprFloatLit) { + return Val == ((VCExprFloatLit)that).Val; } return false; } [Pure] - public override int GetHashCode() - { + public override int GetHashCode() { return Val.GetHashCode() * 72321; } } - public class VCExprRModeLit : VCExprLiteral - { + public class VCExprRModeLit : VCExprLiteral { public readonly RoundingMode Val; internal VCExprRModeLit(RoundingMode val) - : base(Type.RMode) - { + : base(Type.RMode) { this.Val = val; } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] - public override bool Equals(object that) - { - if (Object.ReferenceEquals(this, that)) - { + public override bool Equals(object that) { + if (Object.ReferenceEquals(this, that)) { return true; } - if (that is VCExprRModeLit) - { - return Val == ((VCExprRModeLit) that).Val; + if (that is VCExprRModeLit) { + return Val == ((VCExprRModeLit)that).Val; } return false; } [Pure] - public override int GetHashCode() - { + public override int GetHashCode() { return Val.GetHashCode() * 72321; } } - public class VCExprStringLit : VCExprLiteral - { + public class VCExprStringLit : VCExprLiteral { public readonly String Val; internal VCExprStringLit(String val) - : base(Type.RMode) - { + : base(Type.RMode) { this.Val = val; } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] - public override bool Equals(object that) - { - if (Object.ReferenceEquals(this, that)) - { + public override bool Equals(object that) { + if (Object.ReferenceEquals(this, that)) { return true; } - if (that is VCExprStringLit) - { - return Val == ((VCExprStringLit) that).Val; + if (that is VCExprStringLit) { + return Val == ((VCExprStringLit)that).Val; } return false; } [Pure] - public override int GetHashCode() - { + public override int GetHashCode() { return Val.GetHashCode() * 72321; } } @@ -351,17 +289,13 @@ public override int GetHashCode() ///////////////////////////////////////////////////////////////////////////////// // Operator expressions with fixed arity [ContractClassFor(typeof(VCExprNAry))] - public abstract class VCExprNAryContracts : VCExprNAry - { + public abstract class VCExprNAryContracts : VCExprNAry { public VCExprNAryContracts() - : base(null) - { + : base(null) { } - public override VCExpr this[int index] - { - get - { + public override VCExpr this[int index] { + get { Contract.Ensures(Contract.Result() != null); throw new NotImplementedException(); } @@ -369,49 +303,40 @@ public override VCExpr this[int index] } [ContractClass(typeof(VCExprNAryContracts))] - public abstract class VCExprNAry : VCExpr - { - public override string ToString() - { + public abstract class VCExprNAry : VCExpr { + public override string ToString() { return $"${Op}(${String.Join(", ", Arguments)})"; } [Pure] [GlobalAccess(false)] [Escapes(true, false)] - public IEnumerable Arguments - { - get - { - for (int i = 0; i < Arity; ++i) - { + public IEnumerable Arguments { + get { + for (int i = 0; i < Arity; ++i) { yield return this[i]; } } } - + public readonly VCExprOp Op; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(Op != null); Contract.Invariant(cce.NonNullElements(EMPTY_TYPE_LIST)); Contract.Invariant(cce.NonNullElements(EMPTY_VCEXPR_LIST)); } - public int Arity - { + public int Arity { get { return Op.Arity; } } - public int TypeParamArity - { + public int TypeParamArity { get { return Op.TypeParamArity; } } - public int Length - { + public int Length { get { return Arity; } } @@ -423,54 +348,42 @@ public int Length [Pure] [Reads(ReadsAttribute.Reads.Nothing)] - public override bool Equals(object that) - { - if (Object.ReferenceEquals(this, that)) - { + public override bool Equals(object that) { + if (Object.ReferenceEquals(this, that)) { return true; } - if (that is VCExprNAry) - { + if (that is VCExprNAry) { // we compare the subterms iteratively (not recursively) // to avoid stack overflows VCExprNAryEnumerator enum0 = new VCExprNAryEnumerator(this); - VCExprNAryEnumerator enum1 = new VCExprNAryEnumerator((VCExprNAry) that); + VCExprNAryEnumerator enum1 = new VCExprNAryEnumerator((VCExprNAry)that); - while (true) - { + while (true) { bool next0 = enum0.MoveNext(); bool next1 = enum1.MoveNext(); - if (next0 != next1) - { + if (next0 != next1) { return false; } - if (!next0) - { + if (!next0) { return true; } VCExprNAry nextExprNAry0 = enum0.Current as VCExprNAry; VCExprNAry nextExprNAry1 = enum1.Current as VCExprNAry; - if ((nextExprNAry0 == null) != (nextExprNAry1 == null)) - { + if ((nextExprNAry0 == null) != (nextExprNAry1 == null)) { return false; } - if (nextExprNAry0 != null && nextExprNAry1 != null) - { - if (!nextExprNAry0.Op.Equals(nextExprNAry1.Op)) - { + if (nextExprNAry0 != null && nextExprNAry1 != null) { + if (!nextExprNAry0.Op.Equals(nextExprNAry1.Op)) { return false; } - } - else - { - if (!cce.NonNull(enum0.Current).Equals(enum1.Current)) - { + } else { + if (!cce.NonNull(enum0.Current).Equals(enum1.Current)) { return false; } } @@ -481,25 +394,21 @@ public override bool Equals(object that) } [Pure] - public override int GetHashCode() - { + public override int GetHashCode() { return HelperFuns.PolyHash(Op.GetHashCode() * 123 + Arity * 61521, 3, this.Arguments); } - internal VCExprNAry(VCExprOp op) - { + internal VCExprNAry(VCExprOp op) { Contract.Requires(op != null); this.Op = op; } - public override Result Accept(IVCExprVisitor visitor, Arg arg) - { + public override DynamicStack Accept(IVCExprVisitor visitor, Arg arg) { //Contract.Requires(visitor != null); return visitor.Visit(this, arg); } - public Result Accept(IVCExprOpVisitor visitor, Arg arg) - { + public DynamicStack Accept(IVCExprOpVisitor visitor, Arg arg) { Contract.Requires(visitor != null); return Op.Accept(this, visitor, arg); } @@ -510,17 +419,13 @@ internal static readonly List /*!*/ internal static readonly List /*!*/ EMPTY_VCEXPR_LIST = new List(); - public IEnumerable UniformArguments - { - get - { + public IEnumerable UniformArguments { + get { var enumerator = new VCExprNAryUniformOpEnumerator(this); - while (enumerator.MoveNext()) - { + while (enumerator.MoveNext()) { VCExprNAry naryExpr = enumerator.Current as VCExprNAry; - if (naryExpr == null || !naryExpr.Op.Equals(this.Op)) - { - yield return (VCExpr) enumerator.Current; + if (naryExpr == null || !naryExpr.Op.Equals(this.Op)) { + yield return (VCExpr)enumerator.Current; } } } @@ -529,29 +434,23 @@ public IEnumerable UniformArguments // We give specialised implementations for nullary, unary and binary expressions - internal class VCExprNullary : VCExprNAry - { + internal class VCExprNullary : VCExprNAry { private readonly Type ExprType; [ContractInvariantMethod] - void loneinvariant() - { + void loneinvariant() { Contract.Invariant(ExprType != null); } - public override Type Type - { - get - { + public override Type Type { + get { Contract.Ensures(Contract.Result() != null); return ExprType; } } - public override VCExpr this[int index] - { - get - { + public override VCExpr this[int index] { + get { Contract.Ensures(Contract.Result() != null); Contract.Assert(false); @@ -560,29 +459,24 @@ public override VCExpr this[int index] } // the type arguments - public override List /*!*/ TypeArguments - { - get - { + public override List /*!*/ TypeArguments { + get { Contract.Ensures(cce.NonNullElements(Contract.Result>())); return EMPTY_TYPE_LIST; } } internal VCExprNullary(VCExprOp op) - : base(op) - { + : base(op) { Contract.Requires(op != null); Contract.Requires(op.Arity == 0 && op.TypeParamArity == 0); this.ExprType = op.InferType(EMPTY_VCEXPR_LIST, EMPTY_TYPE_LIST); } } - internal class VCExprUnary : VCExprNAry - { + internal class VCExprUnary : VCExprNAry { [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(Argument != null); Contract.Invariant(ExprType != null); } @@ -593,19 +487,15 @@ private readonly VCExpr /*!*/ private readonly Type /*!*/ ExprType; - public override Type /*!*/ Type - { - get - { + public override Type /*!*/ Type { + get { Contract.Ensures(Contract.Result() != null); return ExprType; } } - public override VCExpr /*!*/ this[int index] - { - get - { + public override VCExpr /*!*/ this[int index] { + get { Contract.Ensures(Contract.Result() != null); Contract.Assume(index == 0); @@ -614,18 +504,15 @@ public override VCExpr /*!*/ this[int index] } // the type arguments - public override List /*!*/ TypeArguments - { - get - { + public override List /*!*/ TypeArguments { + get { Contract.Ensures(cce.NonNullElements(Contract.Result>())); return EMPTY_TYPE_LIST; } } internal VCExprUnary(VCExprOp op, List arguments) - : base(op) - { + : base(op) { Contract.Requires(op != null); Contract.Requires(cce.NonNullElements(arguments)); Contract.Requires(op.Arity == 1 && op.TypeParamArity == 0 && arguments.Count == 1); @@ -636,8 +523,7 @@ internal VCExprUnary(VCExprOp op, List arguments) } internal VCExprUnary(VCExprOp op, VCExpr argument) - : base(op) - { + : base(op) { Contract.Requires(argument != null); Contract.Requires(op != null); Contract.Requires(op.Arity == 1 && op.TypeParamArity == 0); @@ -650,11 +536,9 @@ internal VCExprUnary(VCExprOp op, VCExpr argument) } } - internal class VCExprBinary : VCExprNAry - { + internal class VCExprBinary : VCExprNAry { [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(Argument0 != null); Contract.Invariant(Argument1 != null); Contract.Invariant(ExprType != null); @@ -664,49 +548,40 @@ void ObjectInvariant() private readonly VCExpr Argument1; private readonly Type ExprType; - public override Type Type - { - get - { + public override Type Type { + get { Contract.Ensures(Contract.Result() != null); return ExprType; } } - public override VCExpr this[int index] - { - get - { + public override VCExpr this[int index] { + get { Contract.Ensures(Contract.Result() != null); - switch (index) - { + switch (index) { case 0: return Argument0; case 1: return Argument1; - default: - { - Contract.Assert(false); - throw new cce.UnreachableException(); - } + default: { + Contract.Assert(false); + throw new cce.UnreachableException(); + } } } } // the type arguments - public override List /*!*/ TypeArguments - { - get - { + public override List /*!*/ TypeArguments { + get { Contract.Ensures(cce.NonNullElements(Contract.Result>())); return EMPTY_TYPE_LIST; } } internal VCExprBinary(VCExprOp op, List arguments) - : base(op) - { + : base(op) { Contract.Requires(op != null); Contract.Requires(cce.NonNullElements(arguments)); Contract.Requires(op.Arity == 2 && op.TypeParamArity == 0 && arguments.Count == 2); @@ -717,8 +592,7 @@ internal VCExprBinary(VCExprOp op, List arguments) } internal VCExprBinary(VCExprOp op, VCExpr argument0, VCExpr argument1) - : base(op) - { + : base(op) { Contract.Requires(argument1 != null); Contract.Requires(argument0 != null); Contract.Requires(op != null); @@ -733,16 +607,14 @@ internal VCExprBinary(VCExprOp op, VCExpr argument0, VCExpr argument1) } } - internal class VCExprMultiAry : VCExprNAry - { + internal class VCExprMultiAry : VCExprNAry { private readonly List /*!*/ arguments; private readonly List /*!*/ TypeArgumentsAttr; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(cce.NonNullElements(arguments)); Contract.Invariant(cce.NonNullElements(TypeArgumentsAttr)); Contract.Invariant(ExprType != null); @@ -752,19 +624,15 @@ void ObjectInvariant() private readonly Type /*!*/ ExprType; - public override Type /*!*/ Type - { - get - { + public override Type /*!*/ Type { + get { Contract.Ensures(Contract.Result() != null); return ExprType; } } - public override VCExpr /*!*/ this[int index] - { - get - { + public override VCExpr /*!*/ this[int index] { + get { Contract.Ensures(Contract.Result() != null); Contract.Assume(index >= 0 && index < Arity); @@ -773,18 +641,15 @@ public override VCExpr /*!*/ this[int index] } // the type arguments - public override List /*!*/ TypeArguments - { - get - { + public override List /*!*/ TypeArguments { + get { Contract.Ensures(cce.NonNullElements(Contract.Result>())); return TypeArgumentsAttr; } } internal VCExprMultiAry(VCExprOp op, List arguments) - : base(op) - { + : base(op) { Contract.Requires(op != null); Contract.Requires(cce.NonNullElements(arguments)); this.arguments = arguments; @@ -793,8 +658,7 @@ internal VCExprMultiAry(VCExprOp op, List arguments) } internal VCExprMultiAry(VCExprOp op, List arguments, List /*!*/ typeArguments) - : base(op) - { + : base(op) { Contract.Requires(op != null); Contract.Requires(cce.NonNullElements(typeArguments)); Contract.Requires(cce.NonNullElements(arguments)); @@ -810,8 +674,7 @@ internal VCExprMultiAry(VCExprOp op, List arguments, List /* ///////////////////////////////////////////////////////////////////////////////// // The various operators available [ContractClass(typeof(VCExprOpContracts))] - public abstract class VCExprOp - { + public abstract class VCExprOp { // the number of value parameters public abstract int Arity { get; } @@ -820,14 +683,12 @@ public abstract class VCExprOp public abstract Type /*!*/ InferType(List /*!*/ args, List /*!*/ typeArgs); - public virtual Result Accept(VCExprNAry expr, IVCExprOpVisitor visitor, Arg arg) - { + public virtual DynamicStack Accept(VCExprNAry expr, IVCExprOpVisitor visitor, + Arg arg) { Contract.Requires(visitor != null); Contract.Requires(expr != null); - if (VCExpressionGenerator.SingletonOpDict.TryGetValue(this, out var op)) - { - switch (op) - { + if (VCExpressionGenerator.SingletonOpDict.TryGetValue(this, out var op)) { + switch (op) { case VCExpressionGenerator.SingletonOp.NotOp: return visitor.VisitNotOp(expr, arg); case VCExpressionGenerator.SingletonOp.EqOp: @@ -876,9 +737,7 @@ public virtual Result Accept(VCExprNAry expr, IVCExprOpVisitor(VCExprNAry expr, IVCExprOpVisitor args, List typeArgs) - { + abstract class VCExprOpContracts : VCExprOp { + public override Type InferType(List args, List typeArgs) { Contract.Requires(cce.NonNullElements(args)); Contract.Requires(cce.NonNullElements(typeArgs)); Contract.Ensures(Contract.Result() != null); @@ -898,205 +755,169 @@ public override Type InferType(List args, List typeArgs) } } - public class VCExprNAryOp : VCExprOp - { + public class VCExprNAryOp : VCExprOp { private readonly Type OpType; private readonly int OpArity; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(OpType != null); } - public override int Arity - { + public override int Arity { get { return OpArity; } } - public override int TypeParamArity - { + public override int TypeParamArity { get { return 0; } } - public override Type InferType(List args, List /*!*/ typeArgs) - { + public override Type InferType(List args, List /*!*/ typeArgs) { //Contract.Requires(cce.NonNullElements(typeArgs)); //Contract.Requires(cce.NonNullElements(args)); Contract.Ensures(Contract.Result() != null); return OpType; } - internal VCExprNAryOp(int arity, Type type) - { + internal VCExprNAryOp(int arity, Type type) { Contract.Requires(type != null); this.OpArity = arity; this.OpType = type; } } - public class VCExprDistinctOp : VCExprNAryOp - { + public class VCExprDistinctOp : VCExprNAryOp { internal VCExprDistinctOp(int arity) - : base(arity, Type.Bool) - { + : base(arity, Type.Bool) { } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] - public override bool Equals(object that) - { - if (Object.ReferenceEquals(this, that)) - { + public override bool Equals(object that) { + if (Object.ReferenceEquals(this, that)) { return true; } - if (that is VCExprDistinctOp) - { - return Arity == ((VCExprDistinctOp) that).Arity; + if (that is VCExprDistinctOp) { + return Arity == ((VCExprDistinctOp)that).Arity; } return false; } [Pure] - public override int GetHashCode() - { + public override int GetHashCode() { return Arity * 917632481; } - public override Result Accept( - VCExprNAry expr, + public override DynamicStack Accept(VCExprNAry expr, IVCExprOpVisitor visitor, - Arg arg) - { + Arg arg) { //Contract.Requires(visitor != null); //Contract.Requires(expr != null); return visitor.VisitDistinctOp(expr, arg); } } - public class VCExprFieldAccessOp : VCExprOp - { + public class VCExprFieldAccessOp : VCExprOp { public DatatypeTypeCtorDecl DatatypeTypeCtorDecl; private DatatypeAccessor DatatypeAccessor; - + public int ConstructorIndex => DatatypeAccessor.ConstructorIndex; - + public int FieldIndex => DatatypeAccessor.FieldIndex; - + public override int Arity => 1; - + public override int TypeParamArity => 0; // datatypes work only with monomorphization - - public override Type InferType(List args, List typeArgs) - { + + public override Type InferType(List args, List typeArgs) { Contract.Assert(typeArgs.Count == 0); return DatatypeTypeCtorDecl.Constructors[ConstructorIndex].InParams[FieldIndex].TypedIdent.Type; } - - public override bool Equals(object that) - { - if (Object.ReferenceEquals(this, that)) - { + + public override bool Equals(object that) { + if (Object.ReferenceEquals(this, that)) { return true; } - if (that is VCExprFieldAccessOp thatOp) - { + if (that is VCExprFieldAccessOp thatOp) { return DatatypeTypeCtorDecl.Equals(thatOp.DatatypeTypeCtorDecl) && ConstructorIndex == thatOp.ConstructorIndex && FieldIndex == thatOp.FieldIndex; } return false; } - - public override int GetHashCode() - { + + public override int GetHashCode() { return Arity * 1212481; } - internal VCExprFieldAccessOp(DatatypeTypeCtorDecl datatypeTypeCtorDecl, DatatypeAccessor datatypeAccessor) - { + internal VCExprFieldAccessOp(DatatypeTypeCtorDecl datatypeTypeCtorDecl, DatatypeAccessor datatypeAccessor) { DatatypeTypeCtorDecl = datatypeTypeCtorDecl; DatatypeAccessor = datatypeAccessor; } - public override Result Accept( - VCExprNAry expr, + public override DynamicStack Accept(VCExprNAry expr, IVCExprOpVisitor visitor, - Arg arg) - { + Arg arg) { return visitor.VisitFieldAccessOp(expr, arg); } } - - public class VCExprIsConstructorOp : VCExprOp - { + + public class VCExprIsConstructorOp : VCExprOp { public DatatypeTypeCtorDecl DatatypeTypeCtorDecl; - + public int ConstructorIndex; - + public override int Arity => 1; - + public override int TypeParamArity => 0; // datatypes work only with monomorphization - - public override Type InferType(List args, List typeArgs) - { + + public override Type InferType(List args, List typeArgs) { Contract.Assert(typeArgs.Count == 0); return Type.Bool; } - - public override bool Equals(object that) - { - if (Object.ReferenceEquals(this, that)) - { + + public override bool Equals(object that) { + if (Object.ReferenceEquals(this, that)) { return true; } - if (that is VCExprIsConstructorOp thatOp) - { + if (that is VCExprIsConstructorOp thatOp) { return DatatypeTypeCtorDecl.Equals(thatOp.DatatypeTypeCtorDecl) && ConstructorIndex == thatOp.ConstructorIndex; } return false; } - - public override int GetHashCode() - { + + public override int GetHashCode() { return Arity * 1212481; } - internal VCExprIsConstructorOp(DatatypeTypeCtorDecl datatypeTypeCtorDecl, int constructorIndex) - { + internal VCExprIsConstructorOp(DatatypeTypeCtorDecl datatypeTypeCtorDecl, int constructorIndex) { DatatypeTypeCtorDecl = datatypeTypeCtorDecl; ConstructorIndex = constructorIndex; } - public override Result Accept( - VCExprNAry expr, + public override DynamicStack Accept(VCExprNAry expr, IVCExprOpVisitor visitor, - Arg arg) - { + Arg arg) { return visitor.VisitIsConstructorOp(expr, arg); } } - - public class VCExprSelectOp : VCExprOp - { + + public class VCExprSelectOp : VCExprOp { private readonly int MapArity; private readonly int MapTypeParamArity; - public override int Arity - { + public override int Arity { get { return MapArity + 1; } } - public override int TypeParamArity - { + public override int TypeParamArity { get { return MapTypeParamArity; } } - public override Type InferType(List args, List /*!*/ typeArgs) - { + public override Type InferType(List args, List /*!*/ typeArgs) { //Contract.Requires(cce.NonNullElements(typeArgs)); //Contract.Requires(cce.NonNullElements(args)); Contract.Ensures(Contract.Result() != null); @@ -1105,8 +926,7 @@ public override Type InferType(List args, List /*!*/ typeArg Contract.Assert(TypeParamArity == mapType.TypeParameters.Count); IDictionary /*!*/ subst = new Dictionary(); - for (int i = 0; i < TypeParamArity; ++i) - { + for (int i = 0; i < TypeParamArity; ++i) { subst.Add(mapType.TypeParameters[i], typeArgs[i]); } @@ -1115,65 +935,54 @@ public override Type InferType(List args, List /*!*/ typeArg [Pure] [Reads(ReadsAttribute.Reads.Nothing)] - public override bool Equals(object that) - { - if (Object.ReferenceEquals(this, that)) - { + public override bool Equals(object that) { + if (Object.ReferenceEquals(this, that)) { return true; } - if (that is VCExprSelectOp) - { - return Arity == ((VCExprSelectOp) that).Arity && - TypeParamArity == ((VCExprSelectOp) that).TypeParamArity; + if (that is VCExprSelectOp) { + return Arity == ((VCExprSelectOp)that).Arity && + TypeParamArity == ((VCExprSelectOp)that).TypeParamArity; } return false; } [Pure] - public override int GetHashCode() - { + public override int GetHashCode() { return Arity * 1212481 + TypeParamArity * 298741; } - internal VCExprSelectOp(int arity, int typeParamArity) - { + internal VCExprSelectOp(int arity, int typeParamArity) { Contract.Requires(0 <= arity && 0 <= typeParamArity); this.MapArity = arity; this.MapTypeParamArity = typeParamArity; } - public override Result Accept( - VCExprNAry expr, + public override DynamicStack Accept(VCExprNAry expr, IVCExprOpVisitor visitor, - Arg arg) - { + Arg arg) { //Contract.Requires(visitor != null); //Contract.Requires(expr != null); return visitor.VisitSelectOp(expr, arg); } } - public class VCExprStoreOp : VCExprOp - { + public class VCExprStoreOp : VCExprOp { private readonly int MapArity; private readonly int MapTypeParamArity; - public override int Arity - { + public override int Arity { get { return MapArity + 2; } } // stores never need explicit type parameters, because also the // rhs is a value argument - public override int TypeParamArity - { + public override int TypeParamArity { get { return MapTypeParamArity; } } - public override Type InferType(List args, List /*!*/ typeArgs) - { + public override Type InferType(List args, List /*!*/ typeArgs) { //Contract.Requires(cce.NonNullElements(typeArgs)); //Contract.Requires(cce.NonNullElements(args)); Contract.Ensures(Contract.Result() != null); @@ -1182,59 +991,48 @@ public override Type InferType(List args, List /*!*/ typeArg [Pure] [Reads(ReadsAttribute.Reads.Nothing)] - public override bool Equals(object that) - { - if (Object.ReferenceEquals(this, that)) - { + public override bool Equals(object that) { + if (Object.ReferenceEquals(this, that)) { return true; } - if (that is VCExprStoreOp) - { - return Arity == ((VCExprStoreOp) that).Arity; + if (that is VCExprStoreOp) { + return Arity == ((VCExprStoreOp)that).Arity; } return false; } [Pure] - public override int GetHashCode() - { + public override int GetHashCode() { return Arity * 91361821; } - internal VCExprStoreOp(int arity, int typeParamArity) - { + internal VCExprStoreOp(int arity, int typeParamArity) { Contract.Requires(0 <= arity && 0 <= typeParamArity); this.MapArity = arity; this.MapTypeParamArity = typeParamArity; } - public override Result Accept( - VCExprNAry expr, + public override DynamicStack Accept(VCExprNAry expr, IVCExprOpVisitor visitor, - Arg arg) - { + Arg arg) { //Contract.Requires(visitor != null); //Contract.Requires(expr != null); return visitor.VisitStoreOp(expr, arg); } } - public class VCExprIfThenElseOp : VCExprOp - { - public override int Arity - { + public class VCExprIfThenElseOp : VCExprOp { + public override int Arity { get { return 3; } } - public override int TypeParamArity - { + public override int TypeParamArity { get { return 0; } } - public override Type InferType(List args, List /*!*/ typeArgs) - { + public override Type InferType(List args, List /*!*/ typeArgs) { //Contract.Requires(cce.NonNullElements(typeArgs)); //Contract.Requires(cce.NonNullElements(args)); Contract.Ensures(Contract.Result() != null); @@ -1243,15 +1041,12 @@ public override Type InferType(List args, List /*!*/ typeArg [Pure] [Reads(ReadsAttribute.Reads.Nothing)] - public override bool Equals(object that) - { - if (Object.ReferenceEquals(this, that)) - { + public override bool Equals(object that) { + if (Object.ReferenceEquals(this, that)) { return true; } - if (that is VCExprIfThenElseOp) - { + if (that is VCExprIfThenElseOp) { return true; } @@ -1259,38 +1054,31 @@ public override bool Equals(object that) } [Pure] - public override int GetHashCode() - { + public override int GetHashCode() { return 1; } - internal VCExprIfThenElseOp() - { + internal VCExprIfThenElseOp() { } - public override Result Accept( - VCExprNAry expr, + public override DynamicStack Accept(VCExprNAry expr, IVCExprOpVisitor visitor, - Arg arg) - { + Arg arg) { //Contract.Requires(visitor != null); //Contract.Requires(expr != null); return visitor.VisitIfThenElseOp(expr, arg); } } - public class VCExprSoftOp : VCExprCustomOp - { + public class VCExprSoftOp : VCExprCustomOp { public readonly int Weight; - public VCExprSoftOp(int weight) : base("soft##dummy", 2, Microsoft.Boogie.Type.Bool) - { + public VCExprSoftOp(int weight) : base("soft##dummy", 2, Microsoft.Boogie.Type.Bool) { Weight = weight; } } - public class VCExprCustomOp : VCExprOp - { + public class VCExprCustomOp : VCExprOp { public readonly string /*!*/ Name; @@ -1300,14 +1088,12 @@ public readonly Type /*!*/ Type; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(Name != null); Contract.Invariant(Type != null); } - public VCExprCustomOp(string /*!*/ name, int arity, Type /*!*/ type) - { + public VCExprCustomOp(string /*!*/ name, int arity, Type /*!*/ type) { Contract.Requires(name != null); Contract.Requires(type != null); this.Name = name; @@ -1317,16 +1103,13 @@ public VCExprCustomOp(string /*!*/ name, int arity, Type /*!*/ type) [Pure] [Reads(ReadsAttribute.Reads.Nothing)] - public override bool Equals(object that) - { - if (Object.ReferenceEquals(this, that)) - { + public override bool Equals(object that) { + if (Object.ReferenceEquals(this, that)) { return true; } VCExprCustomOp t = that as VCExprCustomOp; - if (t == null) - { + if (t == null) { return false; } @@ -1335,37 +1118,31 @@ public override bool Equals(object that) [Pure] [Reads(ReadsAttribute.Reads.Nothing)] - public override int GetHashCode() - { + public override int GetHashCode() { int h = Name.GetHashCode(); h = 7823 * h + arity; h = 7823 * h + Type.GetHashCode(); return h; } - public override int Arity - { + public override int Arity { get { return arity; } } - public override int TypeParamArity - { + public override int TypeParamArity { get { return 0; } } - public override Type /*!*/ InferType(List /*!*/ args, List /*!*/ typeArgs) - { + public override Type /*!*/ InferType(List /*!*/ args, List /*!*/ typeArgs) { //Contract.Requires((cce.NonNullElements(args))); //Contract.Requires((cce.NonNullElements(typeArgs))); Contract.Ensures(Contract.Result() != null); return Type; } - public override Result Accept( - VCExprNAry /*!*/ expr, - IVCExprOpVisitor /*!*/ visitor, - Arg arg) - { + public override DynamicStack Accept(VCExprNAry expr, /*!*/ + IVCExprOpVisitor visitor, /*!*/ + Arg arg) { //Contract.Requires(expr != null); //Contract.Requires(visitor != null); return visitor.VisitCustomOp(expr, arg); @@ -1375,29 +1152,24 @@ public override Result Accept( ///////////////////////////////////////////////////////////////////////////////// // Float operators - public class VCExprBinaryFloatOp : VCExprOp - { + public class VCExprBinaryFloatOp : VCExprOp { public readonly int Significand; public readonly int Exponent; private string op; - public override int Arity - { + public override int Arity { get { return 2; } } - public override int TypeParamArity - { + public override int TypeParamArity { get { return 2; } } - public override Type InferType(List args, List /*!*/ typeArgs) - { + public override Type InferType(List args, List /*!*/ typeArgs) { //Contract.Requires(cce.NonNullElements(typeArgs)); //Contract.Requires(cce.NonNullElements(args)); Contract.Ensures(Contract.Result() != null); - switch (op) - { + switch (op) { case ("+"): case ("-"): case ("*"): @@ -1418,44 +1190,36 @@ public override Type InferType(List args, List /*!*/ typeArg [Pure] [Reads(ReadsAttribute.Reads.Nothing)] - public override bool Equals(object that) - { - if (Object.ReferenceEquals(this, that)) - { + public override bool Equals(object that) { + if (Object.ReferenceEquals(this, that)) { return true; } - if (that is VCExprBinaryFloatOp) - { - return this.Exponent == ((VCExprBinaryFloatOp) that).Exponent && - this.Significand == ((VCExprBinaryFloatOp) that).Significand; + if (that is VCExprBinaryFloatOp) { + return this.Exponent == ((VCExprBinaryFloatOp)that).Exponent && + this.Significand == ((VCExprBinaryFloatOp)that).Significand; } return false; } [Pure] - public override int GetHashCode() - { + public override int GetHashCode() { return Exponent * 81748912 + Significand * 67867979; } - internal VCExprBinaryFloatOp(int sig, int exp, string op) - { + internal VCExprBinaryFloatOp(int sig, int exp, string op) { this.Exponent = exp; this.Significand = sig; this.op = op; } - public override Result Accept( - VCExprNAry expr, + public override DynamicStack Accept(VCExprNAry expr, IVCExprOpVisitor visitor, - Arg arg) - { + Arg arg) { //Contract.Requires(visitor != null); //Contract.Requires(expr != null); - switch (op) - { + switch (op) { case ("+"): return visitor.VisitFloatAddOp(expr, arg); case ("-"): @@ -1486,22 +1250,18 @@ public override Result Accept( ///////////////////////////////////////////////////////////////////////////////// // Bitvector operators - public class VCExprBvOp : VCExprOp - { + public class VCExprBvOp : VCExprOp { public readonly int Bits; - public override int Arity - { + public override int Arity { get { return 1; } } - public override int TypeParamArity - { + public override int TypeParamArity { get { return 0; } } - public override Type InferType(List args, List /*!*/ typeArgs) - { + public override Type InferType(List args, List /*!*/ typeArgs) { //Contract.Requires(cce.NonNullElements(typeArgs)); //Contract.Requires(cce.NonNullElements(args)); Contract.Ensures(Contract.Result() != null); @@ -1510,61 +1270,50 @@ public override Type InferType(List args, List /*!*/ typeArg [Pure] [Reads(ReadsAttribute.Reads.Nothing)] - public override bool Equals(object that) - { - if (Object.ReferenceEquals(this, that)) - { + public override bool Equals(object that) { + if (Object.ReferenceEquals(this, that)) { return true; } - if (that is VCExprBvOp) - { - return this.Bits == ((VCExprBvOp) that).Bits; + if (that is VCExprBvOp) { + return this.Bits == ((VCExprBvOp)that).Bits; } return false; } [Pure] - public override int GetHashCode() - { + public override int GetHashCode() { return Bits * 81748912; } - internal VCExprBvOp(int bits) - { + internal VCExprBvOp(int bits) { this.Bits = bits; } - public override Result Accept( - VCExprNAry expr, + public override DynamicStack Accept(VCExprNAry expr, IVCExprOpVisitor visitor, - Arg arg) - { + Arg arg) { //Contract.Requires(visitor != null); //Contract.Requires(expr != null); return visitor.VisitBvOp(expr, arg); } } - public class VCExprBvExtractOp : VCExprOp - { + public class VCExprBvExtractOp : VCExprOp { public readonly int Start; public readonly int End; public readonly int Total; // the number of bits from which the End-Start bits are extracted - public override int Arity - { + public override int Arity { get { return 1; } } - public override int TypeParamArity - { + public override int TypeParamArity { get { return 0; } } - public override Type InferType(List args, List /*!*/ typeArgs) - { + public override Type InferType(List args, List /*!*/ typeArgs) { //Contract.Requires(cce.NonNullElements(typeArgs)); //Contract.Requires(cce.NonNullElements(args)); Contract.Ensures(Contract.Result() != null); @@ -1573,17 +1322,14 @@ public override Type InferType(List args, List /*!*/ typeArg [Pure] [Reads(ReadsAttribute.Reads.Nothing)] - public override bool Equals(object that) - { - if (Object.ReferenceEquals(this, that)) - { + public override bool Equals(object that) { + if (Object.ReferenceEquals(this, that)) { return true; } - if (that is VCExprBvExtractOp) - { + if (that is VCExprBvExtractOp) { VCExprBvExtractOp /*!*/ - thatExtract = (VCExprBvExtractOp) that; + thatExtract = (VCExprBvExtractOp)that; return this.Start == thatExtract.Start && this.End == thatExtract.End && this.Total == thatExtract.Total; } @@ -1591,47 +1337,39 @@ public override bool Equals(object that) } [Pure] - public override int GetHashCode() - { + public override int GetHashCode() { return Start * 81912 + End * 978132 + Total * 571289; } - internal VCExprBvExtractOp(int start, int end, int total) - { + internal VCExprBvExtractOp(int start, int end, int total) { Contract.Requires(0 <= start && start <= end && end <= total); this.Start = start; this.End = end; this.Total = total; } - public override Result Accept( - VCExprNAry expr, + public override DynamicStack Accept(VCExprNAry expr, IVCExprOpVisitor visitor, - Arg arg) - { + Arg arg) { //Contract.Requires(visitor != null); //Contract.Requires(expr != null); return visitor.VisitBvExtractOp(expr, arg); } } - public class VCExprBvConcatOp : VCExprOp - { + public class VCExprBvConcatOp : VCExprOp { public readonly int LeftSize; public readonly int RightSize; - public override int Arity - { + public override int Arity { get { return 2; } } - public override int TypeParamArity - { + public override int TypeParamArity { get { return 0; } } - public override Type InferType(List args, List /*!*/ typeArgs) - { + public override Type InferType(List args, List /*!*/ typeArgs) { //Contract.Requires(cce.NonNullElements(typeArgs)); //Contract.Requires(cce.NonNullElements(args)); Contract.Ensures(Contract.Result() != null); @@ -1640,16 +1378,13 @@ public override Type InferType(List args, List /*!*/ typeArg [Pure] [Reads(ReadsAttribute.Reads.Nothing)] - public override bool Equals(object that) - { - if (Object.ReferenceEquals(this, that)) - { + public override bool Equals(object that) { + if (Object.ReferenceEquals(this, that)) { return true; } - if (that is VCExprBvConcatOp) - { - VCExprBvConcatOp thatConcat = (VCExprBvConcatOp) that; + if (that is VCExprBvConcatOp) { + VCExprBvConcatOp thatConcat = (VCExprBvConcatOp)that; return this.LeftSize == thatConcat.LeftSize && this.RightSize == thatConcat.RightSize; } @@ -1657,23 +1392,19 @@ public override bool Equals(object that) } [Pure] - public override int GetHashCode() - { + public override int GetHashCode() { return LeftSize * 81912 + RightSize * 978132; } - internal VCExprBvConcatOp(int leftSize, int rightSize) - { + internal VCExprBvConcatOp(int leftSize, int rightSize) { Contract.Requires(0 <= leftSize && 0 <= rightSize); this.LeftSize = leftSize; this.RightSize = rightSize; } - public override Result Accept( - VCExprNAry expr, + public override DynamicStack Accept(VCExprNAry expr, IVCExprOpVisitor visitor, - Arg arg) - { + Arg arg) { //Contract.Requires(visitor != null); //Contract.Requires(expr != null); return visitor.VisitBvConcatOp(expr, arg); @@ -1683,42 +1414,35 @@ public override Result Accept( ///////////////////////////////////////////////////////////////////////////////// // References to user-defined Boogie functions - public class VCExprBoogieFunctionOp : VCExprOp - { + public class VCExprBoogieFunctionOp : VCExprOp { public readonly Function Func; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(Func != null); } - public override int Arity - { + public override int Arity { get { return Func.InParams.Count; } } - public override int TypeParamArity - { + public override int TypeParamArity { get { return Func.TypeParameters.Count; } } - public override Type InferType(List args, List /*!*/ typeArgs) - { + public override Type InferType(List args, List /*!*/ typeArgs) { //Contract.Requires(cce.NonNullElements(typeArgs)); //Contract.Requires(cce.NonNullElements(args)); Contract.Ensures(Contract.Result() != null); Contract.Assert(TypeParamArity == Func.TypeParameters.Count); - if (TypeParamArity == 0) - { + if (TypeParamArity == 0) { return cce.NonNull(Func.OutParams[0]).TypedIdent.Type; } IDictionary /*!*/ subst = new Dictionary(TypeParamArity); - for (int i = 0; i < TypeParamArity; ++i) - { + for (int i = 0; i < TypeParamArity; ++i) { subst.Add(Func.TypeParameters[i], typeArgs[i]); } @@ -1727,40 +1451,33 @@ public override Type InferType(List args, List /*!*/ typeArg [Pure] [Reads(ReadsAttribute.Reads.Nothing)] - public override bool Equals(object that) - { - if (Object.ReferenceEquals(this, that)) - { + public override bool Equals(object that) { + if (Object.ReferenceEquals(this, that)) { return true; } - if (that is VCExprBoogieFunctionOp) - { - return this.Func.Equals(((VCExprBoogieFunctionOp) that).Func); + if (that is VCExprBoogieFunctionOp) { + return this.Func.Equals(((VCExprBoogieFunctionOp)that).Func); } return false; } [Pure] - public override int GetHashCode() - { + public override int GetHashCode() { return Func.GetHashCode() + 18731; } // we require that the result type of the expression is specified, because we // do not want to perform full type inference at this point - internal VCExprBoogieFunctionOp(Function func) - { + internal VCExprBoogieFunctionOp(Function func) { Contract.Requires(func != null); this.Func = func; } - public override Result Accept( - VCExprNAry expr, + public override DynamicStack Accept(VCExprNAry expr, IVCExprOpVisitor visitor, - Arg arg) - { + Arg arg) { //Contract.Requires(visitor != null); //Contract.Requires(expr != null); return visitor.VisitBoogieFunctionOp(expr, arg); @@ -1785,8 +1502,7 @@ public class VCExprVar : VCExpr // the name of the variable. Note that the name is not used for comparison, // i.e., there can be two distinct variables with the same name [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(Name != null); Contract.Invariant(VarType != null); } @@ -1830,29 +1546,25 @@ private string KindPrefix(VCExprVarKind kind) }; } - public override Result Accept(IVCExprVisitor visitor, Arg arg) - { + public override DynamicStack Accept(IVCExprVisitor visitor, Arg arg) { //Contract.Requires(visitor != null); - return visitor.Visit(this, arg); + return DynamicStack.FromResult(visitor.Visit(this, arg)); } - + // For VCExprVar, equality is based on reference comparison. // Two different heap-allocated variables with the same name // are considered semantically-different variables. // Name clashes are handled in NameClashResolver.cs. } - public class VCExprConstant : VCExprVar - { - internal VCExprConstant(string name, Type type) : base(name, type) - { + public class VCExprConstant : VCExprVar { + internal VCExprConstant(string name, Type type) : base(name, type) { Contract.Requires(type != null); Contract.Requires(name != null); } } - public abstract class VCExprBinder : VCExpr - { + public abstract class VCExprBinder : VCExpr { public readonly VCExpr /*!*/ Body; @@ -1863,26 +1575,22 @@ public readonly List /*!*/ BoundVars; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(Body != null); Contract.Invariant(cce.NonNullElements(TypeParameters)); Contract.Invariant(cce.NonNullElements(BoundVars)); } - public override Type /*!*/ Type - { - get - { + public override Type /*!*/ Type { + get { Contract.Ensures(Contract.Result() != null); return Body.Type; } } - internal VCExprBinder(List /*!*/ typeParams, List /*!*/ boundVars, VCExpr body) - { + internal VCExprBinder(List /*!*/ typeParams, List /*!*/ boundVars, VCExpr body) { Contract.Requires(body != null); Contract.Requires(cce.NonNullElements(boundVars)); Contract.Requires(cce.NonNullElements(typeParams)); @@ -1893,33 +1601,28 @@ internal VCExprBinder(List /*!*/ typeParams, List /*!*/ Exprs; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(Exprs != null); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] - public override bool Equals(object that) - { - if (Object.ReferenceEquals(this, that)) - { + public override bool Equals(object that) { + if (Object.ReferenceEquals(this, that)) { return true; } - if (that is VCTrigger) - { + if (that is VCTrigger) { VCTrigger /*!*/ - thatTrigger = (VCTrigger) that; + thatTrigger = (VCTrigger)that; return this.Pos == thatTrigger.Pos && HelperFuns.SameElements(this.Exprs, thatTrigger.Exprs); } @@ -1928,22 +1631,19 @@ public override bool Equals(object that) } [Pure] - public override int GetHashCode() - { + public override int GetHashCode() { return (Pos ? 913821 : 871334) + HelperFuns.PolyHash(123, 7, this.Exprs); } - public VCTrigger(bool pos, List exprs) - { + public VCTrigger(bool pos, List exprs) { Contract.Requires(cce.NonNullElements(exprs)); this.Pos = pos; this.Exprs = exprs; } } - public class VCQuantifierInfo - { + public class VCQuantifierInfo { public readonly string qid; public readonly int uniqueId; public readonly int weight; @@ -1958,9 +1658,8 @@ public class VCQuantifierInfo // each expression in instantiationExprs[L] is added to the pool of // expressions for label L. public readonly Dictionary> instantiationExprs; - - public VCQuantifierInfo(string qid, int uniqueId) - { + + public VCQuantifierInfo(string qid, int uniqueId) { this.qid = qid; this.uniqueId = uniqueId; this.weight = 1; @@ -1968,8 +1667,7 @@ public VCQuantifierInfo(string qid, int uniqueId) this.instantiationExprs = new Dictionary>(); } - public VCQuantifierInfo(string qid, int uniqueId, int weight) - { + public VCQuantifierInfo(string qid, int uniqueId, int weight) { this.qid = qid; this.uniqueId = uniqueId; this.weight = weight; @@ -1978,8 +1676,7 @@ public VCQuantifierInfo(string qid, int uniqueId, int weight) } public VCQuantifierInfo(string qid, int uniqueId, int weight, - Dictionary> instantiationLabels, Dictionary> instantiationExprs) - { + Dictionary> instantiationLabels, Dictionary> instantiationExprs) { this.qid = qid; this.uniqueId = uniqueId; this.weight = weight; @@ -1988,19 +1685,16 @@ public VCQuantifierInfo(string qid, int uniqueId, int weight, } } - public enum Quantifier - { + public enum Quantifier { ALL, EX } - public class VCExprQuantifier : VCExprBinder - { + public class VCExprQuantifier : VCExprBinder { public readonly Quantifier Quan; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(Info != null); Contract.Invariant(cce.NonNullElements(Triggers)); } @@ -2009,21 +1703,18 @@ public readonly List /*!*/ Triggers; public readonly VCQuantifierInfo Info; - + // Equality is /not/ modulo bound renaming at this point [Pure] [Reads(ReadsAttribute.Reads.Nothing)] - public override bool Equals(object that) - { - if (Object.ReferenceEquals(this, that)) - { + public override bool Equals(object that) { + if (Object.ReferenceEquals(this, that)) { return true; } - if (that is VCExprQuantifier) - { + if (that is VCExprQuantifier) { VCExprQuantifier /*!*/ - thatQuan = (VCExprQuantifier) that; + thatQuan = (VCExprQuantifier)that; return this.Quan == thatQuan.Quan && HelperFuns.SameElements(this.Triggers, thatQuan.Triggers) && HelperFuns.SameElements(this.TypeParameters, thatQuan.TypeParameters) && @@ -2035,8 +1726,7 @@ public override bool Equals(object that) } [Pure] - public override int GetHashCode() - { + public override int GetHashCode() { return Quan.GetHashCode() + HelperFuns.PolyHash(973219, 7, TypeParameters) + HelperFuns.PolyHash(998431, 9, BoundVars) + @@ -2045,8 +1735,7 @@ public override int GetHashCode() internal VCExprQuantifier(Quantifier kind, List /*!*/ typeParams, List /*!*/ boundVars, List /*!*/ triggers, VCQuantifierInfo info, VCExpr body) - : base(typeParams, boundVars, body) - { + : base(typeParams, boundVars, body) { Contract.Requires(body != null); Contract.Requires(info != null); Contract.Requires(cce.NonNullElements(triggers)); @@ -2058,8 +1747,7 @@ internal VCExprQuantifier(Quantifier kind, List /*!*/ typePa this.Info = info; } - public override Result Accept(IVCExprVisitor visitor, Arg arg) - { + public override DynamicStack Accept(IVCExprVisitor visitor, Arg arg) { //Contract.Requires(visitor != null); return visitor.Visit(this, arg); } @@ -2068,14 +1756,12 @@ public override Result Accept(IVCExprVisitor visitor, ///////////////////////////////////////////////////////////////////////////////// // Let-Bindings - public class VCExprLetBinding - { + public class VCExprLetBinding { public readonly VCExprVar V; public readonly VCExpr E; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(V != null); Contract.Invariant(E != null); } @@ -2083,17 +1769,14 @@ void ObjectInvariant() [Pure] [Reads(ReadsAttribute.Reads.Nothing)] - public override bool Equals(object that) - { - if (Object.ReferenceEquals(this, that)) - { + public override bool Equals(object that) { + if (Object.ReferenceEquals(this, that)) { return true; } - if (that is VCExprLetBinding) - { + if (that is VCExprLetBinding) { VCExprLetBinding /*!*/ - thatB = (VCExprLetBinding) that; + thatB = (VCExprLetBinding)that; return this.V.Equals(thatB.V) && this.E.Equals(thatB.E); } @@ -2101,13 +1784,11 @@ public override bool Equals(object that) } [Pure] - public override int GetHashCode() - { + public override int GetHashCode() { return V.GetHashCode() * 71261 + E.GetHashCode(); } - internal VCExprLetBinding(VCExprVar v, VCExpr e) - { + internal VCExprLetBinding(VCExprVar v, VCExpr e) { Contract.Requires(e != null); Contract.Requires(v != null); this.V = v; @@ -2116,27 +1797,22 @@ internal VCExprLetBinding(VCExprVar v, VCExpr e) } } - public class VCExprLet : VCExprBinder, IEnumerable - { + public class VCExprLet : VCExprBinder, IEnumerable { private readonly List /*!*/ Bindings; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(cce.NonNullElements(Bindings)); } - public int Length - { + public int Length { get { return Bindings.Count; } } - public VCExprLetBinding this[int index] - { - get - { + public VCExprLetBinding this[int index] { + get { Contract.Ensures(Contract.Result() != null); return Bindings[index]; } @@ -2144,35 +1820,30 @@ public VCExprLetBinding this[int index] [Pure] [Reads(ReadsAttribute.Reads.Nothing)] - public override bool Equals(object that) - { - if (Object.ReferenceEquals(this, that)) - { + public override bool Equals(object that) { + if (Object.ReferenceEquals(this, that)) { return true; } - if (that is VCExprLet) - { + if (that is VCExprLet) { VCExprLet /*!*/ - thatLet = (VCExprLet) that; + thatLet = (VCExprLet)that; return this.Body.Equals(thatLet.Body) && - HelperFuns.SameElements(this, (VCExprLet) that); + HelperFuns.SameElements(this, (VCExprLet)that); } return false; } [Pure] - public override int GetHashCode() - { + public override int GetHashCode() { return HelperFuns.PolyHash(Body.GetHashCode(), 9, Bindings); } [Pure] [GlobalAccess(false)] [Escapes(true, false)] - public IEnumerator /*!*/ GetEnumerator() - { + public IEnumerator /*!*/ GetEnumerator() { Contract.Ensures(cce.NonNullElements(Contract.Result>())); return Bindings.GetEnumerator(); } @@ -2180,19 +1851,16 @@ public override int GetHashCode() [Pure] [GlobalAccess(false)] [Escapes(true, false)] - IEnumerator System.Collections.IEnumerable.GetEnumerator() - { + IEnumerator System.Collections.IEnumerable.GetEnumerator() { Contract.Ensures(Contract.Result() != null); return Bindings.GetEnumerator(); } - private static List /*!*/ toSeq(List /*!*/ bindings) - { + private static List /*!*/ toSeq(List /*!*/ bindings) { Contract.Requires(cce.NonNullElements(bindings)); Contract.Ensures(cce.NonNullElements(Contract.Result>())); List res = new List(); - foreach (VCExprLetBinding /*!*/ b in bindings) - { + foreach (VCExprLetBinding /*!*/ b in bindings) { res.Add(b.V); } @@ -2200,15 +1868,13 @@ IEnumerator System.Collections.IEnumerable.GetEnumerator() } internal VCExprLet(List /*!*/ bindings, VCExpr /*!*/ body) - : base(new List(), toSeq(bindings), body) - { + : base(new List(), toSeq(bindings), body) { Contract.Requires(cce.NonNullElements(bindings)); Contract.Requires(body != null); this.Bindings = bindings; } - public override Result Accept(IVCExprVisitor visitor, Arg arg) - { + public override DynamicStack Accept(IVCExprVisitor visitor, Arg arg) { //Contract.Requires(visitor != null); return visitor.Visit(this, arg); } diff --git a/Source/VCExpr/VCExprASTPrinter.cs b/Source/VCExpr/VCExprASTPrinter.cs index 1bf7ba56c..8019997fa 100644 --- a/Source/VCExpr/VCExprASTPrinter.cs +++ b/Source/VCExpr/VCExprASTPrinter.cs @@ -5,26 +5,20 @@ // A simple visitor for turning a VCExpr into a human-readable string // (S-expr syntax) -namespace Microsoft.Boogie.VCExprAST -{ - public class VCExprPrinter : IVCExprVisitor - { +namespace Microsoft.Boogie.VCExprAST { + public class VCExprPrinter : IVCExprVisitor { private VCExprOpPrinter OpPrinterVar = null; public PrintOptions Options { get; } - public VCExprPrinter(PrintOptions options) - { + public VCExprPrinter(PrintOptions options) { Options = options; } - private VCExprOpPrinter /*!*/ OpPrinter - { - get - { + private VCExprOpPrinter /*!*/ OpPrinter { + get { Contract.Ensures(Contract.Result() != null); - if (OpPrinterVar == null) - { + if (OpPrinterVar == null) { OpPrinterVar = new VCExprOpPrinter(this); } @@ -32,35 +26,24 @@ private VCExprOpPrinter /*!*/ OpPrinter } } - public void Print(VCExpr expr, TextWriter wr) - { + public void Print(VCExpr expr, TextWriter wr) { Contract.Requires(wr != null); Contract.Requires(expr != null); expr.Accept(this, wr); } - public bool Visit(VCExprLiteral node, TextWriter wr) - { + public bool Visit(VCExprLiteral node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); - if (node == VCExpressionGenerator.True) - { + if (node == VCExpressionGenerator.True) { wr.Write("true"); - } - else if (node == VCExpressionGenerator.False) - { + } else if (node == VCExpressionGenerator.False) { wr.Write("false"); - } - else if (node is VCExprIntLit) - { - wr.Write(((VCExprIntLit) node).Val); - } - else if (node is VCExprStringLit stringLit) - { + } else if (node is VCExprIntLit) { + wr.Write(((VCExprIntLit)node).Val); + } else if (node is VCExprStringLit stringLit) { wr.Write(stringLit.Val); - } - else - { + } else { Contract.Assert(false); throw new cce.UnreachableException(); } @@ -68,8 +51,7 @@ public bool Visit(VCExprLiteral node, TextWriter wr) return true; } - public bool Visit(VCExprNAry node, TextWriter wr) - { + public DynamicStack Visit(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); VCExprOp /*!*/ @@ -77,8 +59,7 @@ public bool Visit(VCExprNAry node, TextWriter wr) Contract.Assert(op != null); if (op.Equals(VCExpressionGenerator.AndOp) || - op.Equals(VCExpressionGenerator.OrOp)) - { + op.Equals(VCExpressionGenerator.OrOp)) { // handle these operators without recursion wr.Write("({0}", @@ -86,34 +67,30 @@ public bool Visit(VCExprNAry node, TextWriter wr) IEnumerator /*!*/ enumerator = new VCExprNAryUniformOpEnumerator(node); Contract.Assert(enumerator != null); - while (enumerator.MoveNext()) - { + while (enumerator.MoveNext()) { VCExprNAry naryExpr = enumerator.Current as VCExprNAry; - if (naryExpr == null || !naryExpr.Op.Equals(op)) - { + if (naryExpr == null || !naryExpr.Op.Equals(op)) { wr.Write(" "); - Print(cce.NonNull((VCExpr /*!*/) enumerator.Current), wr); + Print(cce.NonNull((VCExpr /*!*/)enumerator.Current), wr); } } wr.Write(")"); - return true; + return DynamicStack.FromResult(true); } return node.Accept(OpPrinter, wr); } - public bool Visit(VCExprVar node, TextWriter wr) - { + public bool Visit(VCExprVar node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); wr.Write(node.Name); return true; } - public bool Visit(VCExprQuantifier node, TextWriter wr) - { + public DynamicStack Visit(VCExprQuantifier node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); string /*!*/ @@ -122,13 +99,11 @@ public bool Visit(VCExprQuantifier node, TextWriter wr) wr.Write("({0} ", quan); - if (node.TypeParameters.Count > 0) - { + if (node.TypeParameters.Count > 0) { wr.Write("<"); string /*!*/ sep = ""; - foreach (TypeVariable /*!*/ v in node.TypeParameters) - { + foreach (TypeVariable /*!*/ v in node.TypeParameters) { Contract.Assert(v != null); wr.Write(sep); sep = ", "; @@ -138,12 +113,10 @@ public bool Visit(VCExprQuantifier node, TextWriter wr) wr.Write("> "); } - if (node.BoundVars.Count > 0) - { + if (node.BoundVars.Count > 0) { string /*!*/ sep = ""; - foreach (VCExprVar /*!*/ v in node.BoundVars) - { + foreach (VCExprVar /*!*/ v in node.BoundVars) { Contract.Assert(v != null); wr.Write(sep); sep = ", "; @@ -155,20 +128,17 @@ public bool Visit(VCExprQuantifier node, TextWriter wr) wr.Write(":: "); - if (node.Triggers.Count > 0) - { + if (node.Triggers.Count > 0) { wr.Write("{0} ", "{"); string /*!*/ sep = ""; - foreach (VCTrigger /*!*/ t in node.Triggers) - { + foreach (VCTrigger /*!*/ t in node.Triggers) { Contract.Assert(t != null); wr.Write(sep); sep = ", "; string /*!*/ sep2 = ""; - foreach (VCExpr /*!*/ e in t.Exprs) - { + foreach (VCExpr /*!*/ e in t.Exprs) { Contract.Assert(e != null); wr.Write(sep2); sep2 = "+"; @@ -181,19 +151,17 @@ public bool Visit(VCExprQuantifier node, TextWriter wr) Print(node.Body, wr); wr.Write(")"); - return true; + return DynamicStack.FromResult(true); } - public bool Visit(VCExprLet node, TextWriter wr) - { + public DynamicStack Visit(VCExprLet node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); wr.Write("(Let "); string /*!*/ sep = ""; - foreach (VCExprLetBinding /*!*/ b in node) - { + foreach (VCExprLetBinding /*!*/ b in node) { Contract.Assert(b != null); wr.Write(sep); sep = ", "; @@ -206,349 +174,299 @@ public bool Visit(VCExprLet node, TextWriter wr) Print(node.Body, wr); wr.Write(")"); - return true; + return DynamicStack.FromResult(true); } } - public class VCExprOpPrinter : IVCExprOpVisitor - { + public class VCExprOpPrinter : IVCExprOpVisitor { private VCExprPrinter /*!*/ ExprPrinter; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(ExprPrinter != null); } - public VCExprOpPrinter(VCExprPrinter exprPrinter) - { + public VCExprOpPrinter(VCExprPrinter exprPrinter) { Contract.Requires(exprPrinter != null); this.ExprPrinter = exprPrinter; } - private bool PrintNAry(string op, VCExprNAry node, TextWriter wr) - { + private DynamicStack PrintNAry(string op, VCExprNAry node, TextWriter wr) { Contract.Requires(wr != null); Contract.Requires(node != null); Contract.Requires(op != null); wr.Write("({0}", op); - foreach (VCExpr /*!*/ arg in node.Arguments) - { + foreach (VCExpr /*!*/ arg in node.Arguments) { Contract.Assert(arg != null); wr.Write(" "); ExprPrinter.Print(arg, wr); } wr.Write(")"); - return true; + return DynamicStack.FromResult(true); } - public bool VisitNotOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitNotOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("!", node, wr); } - public bool VisitEqOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitEqOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("==", node, wr); } - public bool VisitNeqOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitNeqOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("!=", node, wr); } - public bool VisitAndOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitAndOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public bool VisitOrOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitOrOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); Contract.Assert(false); throw new cce.UnreachableException(); } - public bool VisitImpliesOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitImpliesOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("Implies", node, wr); } - public bool VisitDistinctOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitDistinctOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("Distinct", node, wr); } - public bool VisitFieldAccessOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitFieldAccessOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("FieldAccess", node, wr); } - - public bool VisitIsConstructorOp(VCExprNAry node, TextWriter wr) - { + + public DynamicStack VisitIsConstructorOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("IsConstructor", node, wr); } - - public bool VisitSelectOp(VCExprNAry node, TextWriter wr) - { + + public DynamicStack VisitSelectOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("Select", node, wr); } - public bool VisitStoreOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitStoreOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("Store", node, wr); } - public bool VisitFloatAddOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitFloatAddOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("fp.add", node, wr); } - public bool VisitFloatSubOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitFloatSubOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("fp.sub", node, wr); } - public bool VisitFloatMulOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitFloatMulOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("fp.mul", node, wr); } - public bool VisitFloatDivOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitFloatDivOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("fp.div", node, wr); } - public bool VisitFloatLeqOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitFloatLeqOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("fp.leq", node, wr); } - public bool VisitFloatLtOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitFloatLtOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("fp.lt", node, wr); } - public bool VisitFloatGeqOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitFloatGeqOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("fp.geq", node, wr); } - public bool VisitFloatGtOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitFloatGtOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("fp.gt", node, wr); } - public bool VisitFloatEqOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitFloatEqOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("fp.eq", node, wr); } - public bool VisitFloatNeqOp(VCExprNAry node, TextWriter wr) - { + public async DynamicStack VisitFloatNeqOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); - bool toReturn = PrintNAry("not (fp.eq", node, wr); + bool toReturn = await PrintNAry("not (fp.eq", node, wr); wr.Write(")"); // A bit hacky, but it works return toReturn; } - public bool VisitBvOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitBvOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("Bv", node, wr); } - public bool VisitBvExtractOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitBvExtractOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("BvExtract", node, wr); } - public bool VisitBvConcatOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitBvConcatOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("BvConcat", node, wr); } - public bool VisitIfThenElseOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitIfThenElseOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("if-then-else", node, wr); } - public bool VisitCustomOp(VCExprNAry /*!*/ node, TextWriter /*!*/ wr) - { + public DynamicStack VisitCustomOp(VCExprNAry node /*!*/, TextWriter wr /*!*/) { //Contract.Requires(node!=null); //Contract.Requires(wr != null); - VCExprCustomOp op = (VCExprCustomOp) node.Op; + VCExprCustomOp op = (VCExprCustomOp)node.Op; return PrintNAry(op.Name, node, wr); } - public bool VisitAddOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitAddOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); - if (ExprPrinter.Options.ReflectAdd) - { + if (ExprPrinter.Options.ReflectAdd) { return PrintNAry("Reflect$Add", node, wr); - } - else - { + } else { return PrintNAry("+", node, wr); } } - public bool VisitSubOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitSubOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("-", node, wr); } - public bool VisitMulOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitMulOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("*", node, wr); } - public bool VisitDivOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitDivOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("div", node, wr); } - public bool VisitModOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitModOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("mod", node, wr); } - public bool VisitRealDivOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitRealDivOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("/", node, wr); } - public bool VisitPowOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitPowOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("**", node, wr); } - public bool VisitLtOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitLtOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("<", node, wr); } - public bool VisitLeOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitLeOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("<=", node, wr); } - public bool VisitGtOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitGtOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry(">", node, wr); } - public bool VisitGeOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitGeOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry(">=", node, wr); } - public bool VisitSubtypeOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitSubtypeOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("<:", node, wr); } - public bool VisitSubtype3Op(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitSubtype3Op(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("<::", node, wr); } - public bool VisitToIntOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitToIntOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("int", node, wr); } - public bool VisitToRealOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitToRealOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); return PrintNAry("real", node, wr); } - public bool VisitBoogieFunctionOp(VCExprNAry node, TextWriter wr) - { + public DynamicStack VisitBoogieFunctionOp(VCExprNAry node, TextWriter wr) { //Contract.Requires(wr != null); //Contract.Requires(node != null); VCExprBoogieFunctionOp /*!*/ - op = (VCExprBoogieFunctionOp) node.Op; + op = (VCExprBoogieFunctionOp)node.Op; Contract.Assert(op != null); return PrintNAry(op.Func.Name, node, wr); } diff --git a/Source/VCExpr/VCExprASTVisitors.cs b/Source/VCExpr/VCExprASTVisitors.cs index eece56645..78d281036 100644 --- a/Source/VCExpr/VCExprASTVisitors.cs +++ b/Source/VCExpr/VCExprASTVisitors.cs @@ -3,52 +3,45 @@ using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; +using System.Threading.Tasks; // Some visitor skeletons for the VCExpression AST -namespace Microsoft.Boogie.VCExprAST -{ +namespace Microsoft.Boogie.VCExprAST { [ContractClass(typeof(IVCExprVisitorContracts<,>))] - public interface IVCExprVisitor - { + public interface IVCExprVisitor { Result Visit(VCExprLiteral /*!*/ node, Arg arg); - Result Visit(VCExprNAry /*!*/ node, Arg arg); + DynamicStack Visit(VCExprNAry node /*!*/, Arg arg); Result Visit(VCExprVar /*!*/ node, Arg arg); - Result Visit(VCExprQuantifier /*!*/ node, Arg arg); - Result Visit(VCExprLet /*!*/ node, Arg arg); + DynamicStack Visit(VCExprQuantifier node /*!*/, Arg arg); + DynamicStack Visit(VCExprLet node /*!*/, Arg arg); } [ContractClassFor(typeof(IVCExprVisitor<,>))] - public abstract class IVCExprVisitorContracts : IVCExprVisitor - { + public abstract class IVCExprVisitorContracts : IVCExprVisitor { #region IVCExprVisitor Members - public Result Visit(VCExprLiteral node, Arg arg) - { + public Result Visit(VCExprLiteral node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result Visit(VCExprNAry node, Arg arg) - { + public DynamicStack Visit(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result Visit(VCExprVar node, Arg arg) - { + public Result Visit(VCExprVar node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result Visit(VCExprQuantifier node, Arg arg) - { + public DynamicStack Visit(VCExprQuantifier node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result Visit(VCExprLet node, Arg arg) - { + public DynamicStack Visit(VCExprLet node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } @@ -57,287 +50,246 @@ public Result Visit(VCExprLet node, Arg arg) } [ContractClass(typeof(IVCExprOpVisitorContracts<,>))] - public interface IVCExprOpVisitor - { - Result VisitNotOp(VCExprNAry node, Arg arg); - Result VisitEqOp(VCExprNAry node, Arg arg); - Result VisitNeqOp(VCExprNAry node, Arg arg); - Result VisitAndOp(VCExprNAry node, Arg arg); - Result VisitOrOp(VCExprNAry node, Arg arg); - Result VisitImpliesOp(VCExprNAry node, Arg arg); - Result VisitDistinctOp(VCExprNAry node, Arg arg); - Result VisitFieldAccessOp(VCExprNAry node, Arg arg); - Result VisitIsConstructorOp(VCExprNAry node, Arg arg); - Result VisitSelectOp(VCExprNAry node, Arg arg); - Result VisitStoreOp(VCExprNAry node, Arg arg); - Result VisitFloatAddOp(VCExprNAry node, Arg arg); - Result VisitFloatSubOp(VCExprNAry node, Arg arg); - Result VisitFloatMulOp(VCExprNAry node, Arg arg); - Result VisitFloatDivOp(VCExprNAry node, Arg arg); - Result VisitFloatLeqOp(VCExprNAry node, Arg arg); - Result VisitFloatLtOp(VCExprNAry node, Arg arg); - Result VisitFloatGeqOp(VCExprNAry node, Arg arg); - Result VisitFloatGtOp(VCExprNAry node, Arg arg); - Result VisitFloatEqOp(VCExprNAry node, Arg arg); - Result VisitFloatNeqOp(VCExprNAry node, Arg arg); - Result VisitBvOp(VCExprNAry node, Arg arg); - Result VisitBvExtractOp(VCExprNAry node, Arg arg); - Result VisitBvConcatOp(VCExprNAry node, Arg arg); - Result VisitAddOp(VCExprNAry node, Arg arg); - Result VisitSubOp(VCExprNAry node, Arg arg); - Result VisitMulOp(VCExprNAry node, Arg arg); - Result VisitDivOp(VCExprNAry node, Arg arg); - Result VisitModOp(VCExprNAry node, Arg arg); - Result VisitRealDivOp(VCExprNAry node, Arg arg); - Result VisitPowOp(VCExprNAry node, Arg arg); - Result VisitLtOp(VCExprNAry node, Arg arg); - Result VisitLeOp(VCExprNAry node, Arg arg); - Result VisitGtOp(VCExprNAry node, Arg arg); - Result VisitGeOp(VCExprNAry node, Arg arg); - Result VisitSubtypeOp(VCExprNAry node, Arg arg); - Result VisitSubtype3Op(VCExprNAry node, Arg arg); - Result VisitToIntOp(VCExprNAry node, Arg arg); - Result VisitToRealOp(VCExprNAry node, Arg arg); - Result VisitBoogieFunctionOp(VCExprNAry node, Arg arg); - Result VisitIfThenElseOp(VCExprNAry node, Arg arg); - Result VisitCustomOp(VCExprNAry node, Arg arg); + public interface IVCExprOpVisitor { + DynamicStack VisitNotOp(VCExprNAry node, Arg arg); + DynamicStack VisitEqOp(VCExprNAry node, Arg arg); + DynamicStack VisitNeqOp(VCExprNAry node, Arg arg); + DynamicStack VisitAndOp(VCExprNAry node, Arg arg); + DynamicStack VisitOrOp(VCExprNAry node, Arg arg); + DynamicStack VisitImpliesOp(VCExprNAry node, Arg arg); + DynamicStack VisitDistinctOp(VCExprNAry node, Arg arg); + DynamicStack VisitFieldAccessOp(VCExprNAry node, Arg arg); + DynamicStack VisitIsConstructorOp(VCExprNAry node, Arg arg); + DynamicStack VisitSelectOp(VCExprNAry node, Arg arg); + DynamicStack VisitStoreOp(VCExprNAry node, Arg arg); + DynamicStack VisitFloatAddOp(VCExprNAry node, Arg arg); + DynamicStack VisitFloatSubOp(VCExprNAry node, Arg arg); + DynamicStack VisitFloatMulOp(VCExprNAry node, Arg arg); + DynamicStack VisitFloatDivOp(VCExprNAry node, Arg arg); + DynamicStack VisitFloatLeqOp(VCExprNAry node, Arg arg); + DynamicStack VisitFloatLtOp(VCExprNAry node, Arg arg); + DynamicStack VisitFloatGeqOp(VCExprNAry node, Arg arg); + DynamicStack VisitFloatGtOp(VCExprNAry node, Arg arg); + DynamicStack VisitFloatEqOp(VCExprNAry node, Arg arg); + DynamicStack VisitFloatNeqOp(VCExprNAry node, Arg arg); + DynamicStack VisitBvOp(VCExprNAry node, Arg arg); + DynamicStack VisitBvExtractOp(VCExprNAry node, Arg arg); + DynamicStack VisitBvConcatOp(VCExprNAry node, Arg arg); + DynamicStack VisitAddOp(VCExprNAry node, Arg arg); + DynamicStack VisitSubOp(VCExprNAry node, Arg arg); + DynamicStack VisitMulOp(VCExprNAry node, Arg arg); + DynamicStack VisitDivOp(VCExprNAry node, Arg arg); + DynamicStack VisitModOp(VCExprNAry node, Arg arg); + DynamicStack VisitRealDivOp(VCExprNAry node, Arg arg); + DynamicStack VisitPowOp(VCExprNAry node, Arg arg); + DynamicStack VisitLtOp(VCExprNAry node, Arg arg); + DynamicStack VisitLeOp(VCExprNAry node, Arg arg); + DynamicStack VisitGtOp(VCExprNAry node, Arg arg); + DynamicStack VisitGeOp(VCExprNAry node, Arg arg); + DynamicStack VisitSubtypeOp(VCExprNAry node, Arg arg); + DynamicStack VisitSubtype3Op(VCExprNAry node, Arg arg); + DynamicStack VisitToIntOp(VCExprNAry node, Arg arg); + DynamicStack VisitToRealOp(VCExprNAry node, Arg arg); + DynamicStack VisitBoogieFunctionOp(VCExprNAry node, Arg arg); + DynamicStack VisitIfThenElseOp(VCExprNAry node, Arg arg); + DynamicStack VisitCustomOp(VCExprNAry node, Arg arg); } [ContractClassFor(typeof(IVCExprOpVisitor<,>))] - public abstract class IVCExprOpVisitorContracts : IVCExprOpVisitor - { + public abstract class IVCExprOpVisitorContracts : IVCExprOpVisitor { #region IVCExprOpVisitor Members - public Result VisitNotOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitNotOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitEqOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitEqOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitNeqOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitNeqOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitAndOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitAndOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitOrOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitOrOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitImpliesOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitImpliesOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitDistinctOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitDistinctOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitFieldAccessOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitFieldAccessOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - - public Result VisitIsConstructorOp(VCExprNAry node, Arg arg) - { + + public DynamicStack VisitIsConstructorOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - - public Result VisitSelectOp(VCExprNAry node, Arg arg) - { + + public DynamicStack VisitSelectOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitStoreOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitStoreOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitFloatAddOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitFloatAddOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitFloatSubOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitFloatSubOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitFloatMulOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitFloatMulOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitFloatDivOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitFloatDivOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitFloatLeqOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitFloatLeqOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitFloatLtOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitFloatLtOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitFloatGeqOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitFloatGeqOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitFloatGtOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitFloatGtOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitFloatEqOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitFloatEqOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitFloatNeqOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitFloatNeqOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitBvOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitBvOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitBvExtractOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitBvExtractOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitBvConcatOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitBvConcatOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitAddOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitAddOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitSubOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitSubOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitMulOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitMulOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitDivOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitDivOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitModOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitModOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitRealDivOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitRealDivOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitPowOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitPowOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitLtOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitLtOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitLeOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitLeOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitGtOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitGtOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitGeOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitGeOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitSubtypeOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitSubtypeOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitSubtype3Op(VCExprNAry node, Arg arg) - { + public DynamicStack VisitSubtype3Op(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitToIntOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitToIntOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitToRealOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitToRealOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } @@ -348,20 +300,17 @@ public Result VisitToFloat(VCExprNAry node, Arg arg) //TODO: modify later throw new NotImplementedException(); } - public Result VisitBoogieFunctionOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitBoogieFunctionOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitIfThenElseOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitIfThenElseOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } - public Result VisitCustomOp(VCExprNAry node, Arg arg) - { + public DynamicStack VisitCustomOp(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } @@ -381,32 +330,27 @@ public Result VisitCustomOp(VCExprNAry node, Arg arg) [ContractClass(typeof(TraversingVCExprVisitorContracts<,>))] public abstract class TraversingVCExprVisitor - : IVCExprVisitor - { + : IVCExprVisitor { protected abstract Result StandardResult(VCExpr /*!*/ node, Arg arg); - public Result Traverse(VCExpr node, Arg arg) - { + public DynamicStack Traverse(VCExpr node, Arg arg) { Contract.Requires(node != null); return node.Accept(this, arg); } - public virtual Result Visit(VCExprLiteral node, Arg arg) - { + public virtual Result Visit(VCExprLiteral node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result Visit(VCExprNAry node, Arg arg) - { + public virtual DynamicStack Visit(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); Result res = StandardResult(node, arg); - + if (node.TypeParamArity == 0 && (node.Op == VCExpressionGenerator.AndOp || node.Op == VCExpressionGenerator.OrOp || - node.Op == VCExpressionGenerator.ImpliesOp)) - { + node.Op == VCExpressionGenerator.ImpliesOp)) { Contract.Assert(node.Op != null); VCExprOp op = node.Op; HashSet ops = new HashSet(); @@ -414,77 +358,62 @@ public virtual Result Visit(VCExprNAry node, Arg arg) ops.Add(VCExpressionGenerator.OrOp); ops.Add(VCExpressionGenerator.ImpliesOp); IEnumerator enumerator = new VCExprNAryMultiUniformOpEnumerator(node, ops); - while (enumerator.MoveNext()) - { - VCExpr expr = cce.NonNull((VCExpr) enumerator.Current); + while (enumerator.MoveNext()) { + VCExpr expr = cce.NonNull((VCExpr)enumerator.Current); VCExprNAry naryExpr = expr as VCExprNAry; - if (naryExpr == null || !ops.Contains(naryExpr.Op)) - { + if (naryExpr == null || !ops.Contains(naryExpr.Op)) { expr.Accept(this, arg); - } - else - { + } else { StandardResult(expr, arg); } } - } - else - { - foreach (VCExpr e in node.Arguments) - { + } else { + foreach (VCExpr e in node.Arguments) { Contract.Assert(e != null); e.Accept(this, arg); } } - return res; + return DynamicStack.FromResult(res); } - public virtual Result Visit(VCExprVar node, Arg arg) - { + public virtual Result Visit(VCExprVar node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result Visit(VCExprQuantifier node, Arg arg) - { + public virtual DynamicStack Visit(VCExprQuantifier node, Arg arg) { //Contract.Requires(node != null); Result res = StandardResult(node, arg); - foreach (VCTrigger /*!*/ trigger in node.Triggers) - { + foreach (VCTrigger /*!*/ trigger in node.Triggers) { Contract.Assert(trigger != null); - foreach (VCExpr /*!*/ expr in trigger.Exprs) - { + foreach (VCExpr /*!*/ expr in trigger.Exprs) { Contract.Assert(expr != null); expr.Accept(this, arg); } } node.Body.Accept(this, arg); - return res; + return DynamicStack.FromResult(res); } - public virtual Result Visit(VCExprLet node, Arg arg) - { + public virtual DynamicStack Visit(VCExprLet node, Arg arg) { //Contract.Requires(node != null); Result res = StandardResult(node, arg); // visit the bound expressions first - foreach (VCExprLetBinding /*!*/ binding in node) - { + foreach (VCExprLetBinding /*!*/ binding in node) { Contract.Assert(binding != null); binding.E.Accept(this, arg); } node.Body.Accept(this, arg); - return res; + return DynamicStack.FromResult(res); } } [ContractClassFor(typeof(TraversingVCExprVisitor<,>))] - public abstract class TraversingVCExprVisitorContracts : TraversingVCExprVisitor - { - protected override Result StandardResult(VCExpr node, Arg arg) - { + public abstract class TraversingVCExprVisitorContracts : TraversingVCExprVisitor { + protected override Result StandardResult(VCExpr node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } @@ -494,8 +423,7 @@ protected override Result StandardResult(VCExpr node, Arg arg) // used to avoid handling such VCExpr recursively, which can easily // lead to stack overflows - public class VCExprNAryEnumerator : IEnumerator - { + public class VCExprNAryEnumerator : IEnumerator { private readonly VCExprNAry /*!*/ CompleteExpr; @@ -505,14 +433,12 @@ private readonly Stack /*!*/ ExprTodo = new Stack(); [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(CompleteExpr != null); Contract.Invariant(cce.NonNullElements(ExprTodo)); } - public VCExprNAryEnumerator(VCExprNAry completeExpr) - { + public VCExprNAryEnumerator(VCExprNAry completeExpr) { Contract.Requires(completeExpr != null); this.CompleteExpr = completeExpr; Stack /*!*/ @@ -524,27 +450,22 @@ public VCExprNAryEnumerator(VCExprNAry completeExpr) // Method using which a subclass can decide whether the // subexpressions of an expression should be enumerated as well // The default is to enumerate all nodes - protected virtual bool Descend(VCExprNAry expr) - { + protected virtual bool Descend(VCExprNAry expr) { Contract.Requires(expr != null); return true; } //////////////////////////////////////////////////////////////////////////// - public bool MoveNext() - { - if (ExprTodo.Count == 0) - { + public bool MoveNext() { + if (ExprTodo.Count == 0) { return false; } CurrentExpr = ExprTodo.Pop(); VCExprNAry currentNAry = CurrentExpr as VCExprNAry; - if (currentNAry != null && Descend(currentNAry)) - { - for (int i = currentNAry.Arity - 1; i >= 0; --i) - { + if (currentNAry != null && Descend(currentNAry)) { + for (int i = currentNAry.Arity - 1; i >= 0; --i) { ExprTodo.Push(currentNAry[i]); } } @@ -552,13 +473,11 @@ public bool MoveNext() return true; } - public object Current - { + public object Current { get { return cce.NonNull(CurrentExpr); } } - public void Reset() - { + public void Reset() { ExprTodo.Clear(); CurrentExpr = null; ExprTodo.Push(CompleteExpr); @@ -568,27 +487,23 @@ public void Reset() ////////////////////////////////////////////////////////////////////////////// - public class VCExprNAryUniformOpEnumerator : VCExprNAryEnumerator - { + public class VCExprNAryUniformOpEnumerator : VCExprNAryEnumerator { private readonly VCExprOp /*!*/ Op; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(Op != null); } public VCExprNAryUniformOpEnumerator(VCExprNAry completeExpr) - : base(completeExpr) - { + : base(completeExpr) { Contract.Requires(completeExpr != null); this.Op = completeExpr.Op; } - protected override bool Descend(VCExprNAry expr) - { + protected override bool Descend(VCExprNAry expr) { //Contract.Requires(expr != null); return expr.Op.Equals(Op) && // we never skip nodes with type parameters @@ -597,26 +512,22 @@ protected override bool Descend(VCExprNAry expr) } } - public class VCExprNAryMultiUniformOpEnumerator : VCExprNAryEnumerator - { + public class VCExprNAryMultiUniformOpEnumerator : VCExprNAryEnumerator { private readonly HashSet Ops; [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(Ops != null); } public VCExprNAryMultiUniformOpEnumerator(VCExprNAry completeExpr, HashSet ops) - : base(completeExpr) - { + : base(completeExpr) { Contract.Requires(completeExpr != null); this.Ops = ops; } - protected override bool Descend(VCExprNAry expr) - { + protected override bool Descend(VCExprNAry expr) { return Ops.Contains(expr.Op) && expr.TypeParamArity == 0; } } @@ -625,8 +536,7 @@ protected override bool Descend(VCExprNAry expr) // Visitor that knows about the variables bound at each location in a VCExpr public abstract class BoundVarTraversingVCExprVisitor - : TraversingVCExprVisitor - { + : TraversingVCExprVisitor { private readonly IDictionary BoundTermVarsMap = new Dictionary(); private readonly ISet BoundTypeVarsSet = new HashSet(); @@ -635,34 +545,27 @@ public abstract class BoundVarTraversingVCExprVisitor protected ICollection BoundTypeVars => BoundTypeVarsSet; - public override Result Visit(VCExprQuantifier node, Arg arg) - { + public override async DynamicStack Visit(VCExprQuantifier node, Arg arg) { // we temporarily add bound (term and type) variables to the // corresponding lists - foreach (VCExprVar v in node.BoundVars) - { + foreach (VCExprVar v in node.BoundVars) { BoundTermVarsMap.Add(v, null); } - foreach (TypeVariable v in node.TypeParameters) - { + foreach (TypeVariable v in node.TypeParameters) { BoundTypeVarsSet.Add(v); } Result res; - try - { - res = VisitAfterBinding(node, arg); + try { + res = await VisitAfterBinding(node, arg); } - finally - { - foreach (VCExprVar v in node.BoundVars) - { + finally { + foreach (VCExprVar v in node.BoundVars) { BoundTermVarsMap.Remove(v); } - foreach (TypeVariable v in node.TypeParameters) - { + foreach (TypeVariable v in node.TypeParameters) { BoundTypeVarsSet.Remove(v); } } @@ -670,24 +573,19 @@ public override Result Visit(VCExprQuantifier node, Arg arg) return res; } - public override Result Visit(VCExprLet node, Arg arg) - { + public override async DynamicStack Visit(VCExprLet node, Arg arg) { // we temporarily add bound term variables to the // corresponding lists - foreach (var binding in node) - { + foreach (var binding in node) { BoundTermVarsMap.Add(binding.V, binding.E); } Result res; - try - { - res = VisitAfterBinding(node, arg); + try { + res = await VisitAfterBinding(node, arg); } - finally - { - foreach (VCExprVar v in node.BoundVars) - { + finally { + foreach (VCExprVar v in node.BoundVars) { BoundTermVarsMap.Remove(v); } } @@ -701,25 +599,21 @@ public override Result Visit(VCExprLet node, Arg arg) // (when overriding the normal visit-methods, the node will be visited // before the binding happens) - protected virtual Result VisitAfterBinding(VCExprQuantifier node, Arg arg) - { + protected virtual DynamicStack VisitAfterBinding(VCExprQuantifier node, Arg arg) { Contract.Requires(node != null); return base.Visit(node, arg); } - protected virtual Result VisitAfterBinding(VCExprLet node, Arg arg) - { + protected virtual DynamicStack VisitAfterBinding(VCExprLet node, Arg arg) { Contract.Requires(node != null); return base.Visit(node, arg); } } - public class SizeComputingVisitor : TraversingVCExprVisitor - { + public class SizeComputingVisitor : TraversingVCExprVisitor { private int Size = 0; - public static int ComputeSize(VCExpr expr) - { + public static int ComputeSize(VCExpr expr) { Contract.Requires(expr != null); SizeComputingVisitor /*!*/ visitor = new SizeComputingVisitor(); @@ -727,8 +621,7 @@ public static int ComputeSize(VCExpr expr) return visitor.Size; } - protected override bool StandardResult(VCExpr node, bool arg) - { + protected override bool StandardResult(VCExpr node, bool arg) { //Contract.Requires(node != null); Size = Size + 1; return true; @@ -742,29 +635,25 @@ protected override bool StandardResult(VCExpr node, bool arg) // parameters of VCExprNAry. // the result and argument (of type bool) are not used currently - public class FreeVariableCollector : BoundVarTraversingVCExprVisitor - { + public class FreeVariableCollector : BoundVarTraversingVCExprVisitor { public readonly HashSet FreeTermVars = new HashSet(); public readonly List FreeTypeVars = new List(); [ContractInvariantMethod] - void ObjectInvariant() - { + void ObjectInvariant() { Contract.Invariant(FreeTermVars != null && Contract.ForAll(FreeTermVars, entry => entry != null)); Contract.Invariant(cce.NonNullElements(FreeTypeVars)); } // not used - protected override bool StandardResult(VCExpr node, bool arg) - { + protected override bool StandardResult(VCExpr node, bool arg) { //Contract.Requires(node != null); return true; } - public static HashSet FreeTermVariables(VCExpr node) - { + public static HashSet FreeTermVariables(VCExpr node) { Contract.Requires(node != null); Contract.Ensures(Contract.Result>() != null); Contract.Ensures(Contract.ForAll(Contract.Result>(), ftv => ftv.Key != null)); @@ -773,8 +662,7 @@ public static HashSet FreeTermVariables(VCExpr node) return collector.FreeTermVars; } - public static List FreeTypeVariables(VCExpr node) - { + public static List FreeTypeVariables(VCExpr node) { Contract.Requires(node != null); Contract.Ensures(cce.NonNullElements(Contract.Result>())); FreeVariableCollector collector = new FreeVariableCollector(); @@ -782,54 +670,44 @@ public static List FreeTypeVariables(VCExpr node) return collector.FreeTypeVars; } - public void Reset() - { + public void Reset() { FreeTermVars.Clear(); FreeTypeVars.Clear(); } - public void Collect(VCExpr node) - { + public void Collect(VCExpr node) { Contract.Requires(node != null); Traverse(node, true); } - public void Collect(Type type) - { + public void Collect(Type type) { Contract.Requires(type != null); AddTypeVariables(type.FreeVariables.ToList()); } ///////////////////////////////////////////////////////////////////////// - private void CollectTypeVariables(IEnumerable /*!*/ boundVars) - { + private void CollectTypeVariables(IEnumerable /*!*/ boundVars) { Contract.Requires(cce.NonNullElements(boundVars)); - foreach (VCExprVar /*!*/ var in boundVars) - { + foreach (VCExprVar /*!*/ var in boundVars) { Contract.Assert(var != null); Collect(var.Type); } } - private void AddTypeVariables(IEnumerable /*!*/ typeVars) - { + private void AddTypeVariables(IEnumerable /*!*/ typeVars) { Contract.Requires(cce.NonNullElements(typeVars)); - foreach (TypeVariable /*!*/ tvar in typeVars) - { + foreach (TypeVariable /*!*/ tvar in typeVars) { Contract.Assert(tvar != null); - if (!BoundTypeVars.Contains(tvar) && !FreeTypeVars.Contains(tvar)) - { + if (!BoundTypeVars.Contains(tvar) && !FreeTypeVars.Contains(tvar)) { FreeTypeVars.Add(tvar); } } } - public override bool Visit(VCExprVar node, bool arg) - { + public override bool Visit(VCExprVar node, bool arg) { Contract.Requires(node != null); - if (!BoundTermVars.ContainsKey(node) && !FreeTermVars.Contains(node)) - { + if (!BoundTermVars.ContainsKey(node) && !FreeTermVars.Contains(node)) { FreeTermVars.Add(node); Collect(node.Type); } @@ -837,11 +715,9 @@ public override bool Visit(VCExprVar node, bool arg) return true; } - public override bool Visit(VCExprNAry node, bool arg) - { + public override DynamicStack Visit(VCExprNAry node, bool arg) { Contract.Requires(node != null); - foreach (Type /*!*/ t in node.TypeArguments) - { + foreach (Type /*!*/ t in node.TypeArguments) { Contract.Assert(t != null); Collect(t); } @@ -849,15 +725,13 @@ public override bool Visit(VCExprNAry node, bool arg) return base.Visit(node, arg); } - protected override bool VisitAfterBinding(VCExprQuantifier node, bool arg) - { + protected override DynamicStack VisitAfterBinding(VCExprQuantifier node, bool arg) { //Contract.Requires(node != null); CollectTypeVariables(node.BoundVars); return base.VisitAfterBinding(node, arg); } - protected override bool VisitAfterBinding(VCExprLet node, bool arg) - { + protected override DynamicStack VisitAfterBinding(VCExprLet node, bool arg) { //Contract.Requires(node != null); CollectTypeVariables(node.BoundVars); return base.VisitAfterBinding(node, arg); @@ -877,14 +751,12 @@ protected override bool VisitAfterBinding(VCExprLet node, bool arg) // Substitutions and a visitor for applying substitutions. A substitution can // substitute both type variables and term variables - public class VCExprSubstitution - { + public class VCExprSubstitution { private readonly List /*!*/> /*!*/ TermSubsts; [ContractInvariantMethod] - void TermSubstsInvariantMethod() - { + void TermSubstsInvariantMethod() { Contract.Invariant(TermSubsts != null && Contract.ForAll(TermSubsts, i => cce.NonNullDictionaryAndValues(i))); } @@ -892,14 +764,12 @@ void TermSubstsInvariantMethod() TypeSubsts; [ContractInvariantMethod] - void TypeSubstsInvariantMethod() - { + void TypeSubstsInvariantMethod() { Contract.Invariant(TermSubsts != null && Contract.ForAll(TypeSubsts, i => cce.NonNullDictionaryAndValues(i))); } public VCExprSubstitution(IDictionary /*!*/ termSubst, - IDictionary /*!*/ typeSubst) - { + IDictionary /*!*/ typeSubst) { Contract.Requires(cce.NonNullDictionaryAndValues(termSubst)); Contract.Requires(cce.NonNullDictionaryAndValues(typeSubst)); List /*!*/> /*!*/ @@ -915,31 +785,24 @@ public VCExprSubstitution(IDictionary /*!*/ termS } public VCExprSubstitution() - : this(new Dictionary(), new Dictionary()) - { + : this(new Dictionary(), new Dictionary()) { } - public void PushScope() - { + public void PushScope() { TermSubsts.Add(new Dictionary()); TypeSubsts.Add(new Dictionary()); } - public void PopScope() - { + public void PopScope() { TermSubsts.RemoveAt(TermSubsts.Count - 1); TypeSubsts.RemoveAt(TypeSubsts.Count - 1); } - public VCExpr this[VCExprVar /*!*/ var] - { - get - { + public VCExpr this[VCExprVar /*!*/ var] { + get { Contract.Requires(var != null); - for (int i = TermSubsts.Count - 1; i >= 0; --i) - { - if (TermSubsts[i].TryGetValue(var, out var res)) - { + for (int i = TermSubsts.Count - 1; i >= 0; --i) { + if (TermSubsts[i].TryGetValue(var, out var res)) { return res; } } @@ -949,15 +812,11 @@ public VCExpr this[VCExprVar /*!*/ var] set { TermSubsts[TermSubsts.Count - 1][var] = cce.NonNull(value); } } - public Type this[TypeVariable /*!*/ var] - { - get - { + public Type this[TypeVariable /*!*/ var] { + get { Contract.Requires(var != null); - for (int i = TypeSubsts.Count - 1; i >= 0; --i) - { - if (TypeSubsts[i].TryGetValue(var, out var res)) - { + for (int i = TypeSubsts.Count - 1; i >= 0; --i) { + if (TypeSubsts[i].TryGetValue(var, out var res)) { return res; } } @@ -967,39 +826,31 @@ public Type this[TypeVariable /*!*/ var] set { TypeSubsts[TypeSubsts.Count - 1][var] = cce.NonNull(value); } } - public bool ContainsKey(VCExprVar var) - { + public bool ContainsKey(VCExprVar var) { Contract.Requires(var != null); return this[var] != null; } - public bool ContainsKey(TypeVariable var) - { + public bool ContainsKey(TypeVariable var) { Contract.Requires(var != null); return this[var] != null; } - public bool TermSubstIsEmpty - { + public bool TermSubstIsEmpty { get { return TermSubsts.All(dict => !dict.Any()); } } - public bool TypeSubstIsEmpty - { + public bool TypeSubstIsEmpty { get { return TypeSubsts.All(dict => !dict.Any()); } } - public IDictionary /*!*/ ToTypeSubst - { - get - { + public IDictionary /*!*/ ToTypeSubst { + get { Contract.Ensures(cce.NonNullDictionaryAndValues(Contract.Result>())); IDictionary /*!*/ res = new Dictionary(); - foreach (IDictionary /*!*/ dict in TypeSubsts) - { - foreach (KeyValuePair pair in dict) - { + foreach (IDictionary /*!*/ dict in TypeSubsts) { + foreach (KeyValuePair pair in dict) { Contract.Assert(cce.NonNullElements(pair)); // later ones overwrite earlier ones res[pair.Key] = pair.Value; @@ -1011,21 +862,16 @@ public bool TypeSubstIsEmpty } // the variables that are not mapped to themselves - public IEnumerable /*!*/ TermDomain - { - get - { + public IEnumerable /*!*/ TermDomain { + get { Contract.Ensures(cce.NonNullElements(Contract.Result>())); HashSet /*!*/ domain = new HashSet(); - foreach (IDictionary /*!*/ dict in TermSubsts) - { + foreach (IDictionary /*!*/ dict in TermSubsts) { Contract.Assert(dict != null); - foreach (VCExprVar /*!*/ var in dict.Keys) - { + foreach (VCExprVar /*!*/ var in dict.Keys) { Contract.Assert(var != null); - if (!var.Equals(this[var])) - { + if (!var.Equals(this[var])) { domain.Add(var); } } @@ -1036,21 +882,16 @@ public IEnumerable /*!*/ TermDomain } // the variables that are not mapped to themselves - public IEnumerable /*!*/ TypeDomain - { - get - { + public IEnumerable /*!*/ TypeDomain { + get { Contract.Ensures(cce.NonNullElements(Contract.Result>())); HashSet /*!*/ domain = new HashSet(); - foreach (IDictionary /*!*/ dict in TypeSubsts) - { + foreach (IDictionary /*!*/ dict in TypeSubsts) { Contract.Assert(dict != null); - foreach (TypeVariable /*!*/ var in dict.Keys) - { + foreach (TypeVariable /*!*/ var in dict.Keys) { Contract.Assert(var != null); - if (!var.Equals(this[var])) - { + if (!var.Equals(this[var])) { domain.Add(var); } } @@ -1060,21 +901,17 @@ public IEnumerable /*!*/ TypeDomain } } - public FreeVariableCollector /*!*/ Codomains - { - get - { + public FreeVariableCollector /*!*/ Codomains { + get { Contract.Ensures(Contract.Result() != null); FreeVariableCollector /*!*/ coll = new FreeVariableCollector(); - foreach (VCExprVar /*!*/ var in TermDomain) - { + foreach (VCExprVar /*!*/ var in TermDomain) { coll.Collect(cce.NonNull(this)[var]); } - foreach (TypeVariable /*!*/ var in TypeDomain) - { + foreach (TypeVariable /*!*/ var in TypeDomain) { coll.Collect(cce.NonNull(this)[var]); } @@ -1082,18 +919,15 @@ public FreeVariableCollector /*!*/ Codomains } } - public VCExprSubstitution Clone() - { + public VCExprSubstitution Clone() { Contract.Ensures(Contract.Result() != null); VCExprSubstitution /*!*/ res = new VCExprSubstitution(); - foreach (IDictionary /*!*/ dict in TermSubsts) - { + foreach (IDictionary /*!*/ dict in TermSubsts) { res.TermSubsts.Add(HelperFuns.Clone(dict)); } - foreach (IDictionary /*!*/ dict in TypeSubsts) - { + foreach (IDictionary /*!*/ dict in TypeSubsts) { res.TypeSubsts.Add(HelperFuns.Clone(dict)); } @@ -1104,11 +938,9 @@ public VCExprSubstitution Clone() ///////////////////////////////////////////////////////////////////////////////// public class SubstitutingVCExprVisitor - : MutatingVCExprVisitor - { + : MutatingVCExprVisitor { public SubstitutingVCExprVisitor(VCExpressionGenerator gen) - : base(gen) - { + : base(gen) { Contract.Requires(gen != null); } @@ -1116,15 +948,13 @@ public SubstitutingVCExprVisitor(VCExpressionGenerator gen) // or variable capture can occur. if this might happen, we replace the // term and type variables bound by the binder with fresh variables private bool CollisionPossible(IEnumerable /*!*/ typeParams, - IEnumerable /*!*/ boundVars, VCExprSubstitution /*!*/ substitution) - { + IEnumerable /*!*/ boundVars, VCExprSubstitution /*!*/ substitution) { Contract.Requires(cce.NonNullElements(typeParams)); Contract.Requires(cce.NonNullElements(boundVars)); Contract.Requires(substitution != null); // variables can be shadowed by a binder if (typeParams.Any(var => substitution.ContainsKey(var)) || - boundVars.Any(var => substitution.ContainsKey(var))) - { + boundVars.Any(var => substitution.ContainsKey(var))) { return true; } // compute the codomain of the substitution @@ -1136,8 +966,7 @@ private bool CollisionPossible(IEnumerable /*!*/ typeParams, } // can be overwritten if names of bound variables are to be changed - protected virtual string ChooseNewVariableName(string oldName) - { + protected virtual string ChooseNewVariableName(string oldName) { Contract.Requires(oldName != null); Contract.Ensures(Contract.Result() != null); return oldName; @@ -1145,8 +974,7 @@ protected virtual string ChooseNewVariableName(string oldName) // handle type parameters in VCExprNAry protected override VCExpr /*!*/ UpdateModifiedNode(VCExprNAry /*!*/ originalNode, - List /*!*/ newSubExprs, bool changed, VCExprSubstitution /*!*/ substitution) - { + List /*!*/ newSubExprs, bool changed, VCExprSubstitution /*!*/ substitution) { //Contract.Requires(originalNode != null); //Contract.Requires(cce.NonNullElements(newSubExprs)); //Contract.Requires(substitution != null); @@ -1154,32 +982,26 @@ protected virtual string ChooseNewVariableName(string oldName) List /*!*/ typeParams = new List(); - foreach (Type /*!*/ t in originalNode.TypeArguments) - { + foreach (Type /*!*/ t in originalNode.TypeArguments) { Contract.Assert(t != null); Type /*!*/ newType = t.Substitute(substitution.ToTypeSubst); Contract.Assert(newType != null); - if (!ReferenceEquals(t, newType)) - { + if (!ReferenceEquals(t, newType)) { changed = true; } typeParams.Add(newType); } - if (changed) - { + if (changed) { return Gen.Function(originalNode.Op, newSubExprs, typeParams); - } - else - { + } else { return originalNode; } } - public override VCExpr /*!*/ Visit(VCExprQuantifier /*!*/ node, VCExprSubstitution /*!*/ substitution) - { + public override DynamicStack /*!*/ Visit(VCExprQuantifier node /*!*/, VCExprSubstitution substitution /*!*/) { Contract.Requires(node != null); Contract.Requires(substitution != null); Contract.Ensures(Contract.Result() != null); @@ -1189,27 +1011,23 @@ protected virtual string ChooseNewVariableName(string oldName) return Visit(node, substitution, false); } - public VCExpr /*!*/ Visit(VCExprQuantifier /*!*/ node, VCExprSubstitution /*!*/ substitution, - bool refreshBoundVariables) - { + public async DynamicStack /*!*/ Visit(VCExprQuantifier /*!*/ node, VCExprSubstitution /*!*/ substitution, + bool refreshBoundVariables) { Contract.Requires(node != null); Contract.Requires(substitution != null); Contract.Ensures(Contract.Result() != null); substitution.PushScope(); - try - { + try { List /*!*/ typeParams = node.TypeParameters; Contract.Assert(cce.NonNullElements(typeParams)); bool refreshAllVariables = refreshBoundVariables || CollisionPossible(node.TypeParameters, node.BoundVars, substitution); - if (refreshAllVariables) - { + if (refreshAllVariables) { // we introduce fresh type variables to ensure that none gets captured typeParams = new List(); - foreach (TypeVariable /*!*/ var in node.TypeParameters) - { + foreach (TypeVariable /*!*/ var in node.TypeParameters) { Contract.Assert(var != null); TypeVariable /*!*/ freshVar = @@ -1224,8 +1042,7 @@ protected virtual string ChooseNewVariableName(string oldName) List /*!*/ boundVars = node.BoundVars; Contract.Assert(cce.NonNullElements(boundVars)); - if (refreshAllVariables || !substitution.TypeSubstIsEmpty) - { + if (refreshAllVariables || !substitution.TypeSubstIsEmpty) { // collisions are possible, or we also substitute type variables. in this case // the bound term variables have to be replaced with fresh variables with the // right types @@ -1233,8 +1050,7 @@ protected virtual string ChooseNewVariableName(string oldName) IDictionary /*!*/ typeSubst = substitution.ToTypeSubst; Contract.Assert(cce.NonNullDictionaryAndValues(typeSubst)); - foreach (VCExprVar /*!*/ var in node.BoundVars) - { + foreach (VCExprVar /*!*/ var in node.BoundVars) { Contract.Assert(var != null); VCExprVar /*!*/ freshVar = @@ -1249,10 +1065,9 @@ protected virtual string ChooseNewVariableName(string oldName) List /*!*/ newTriggers = new List(); - foreach (VCTrigger /*!*/ trigger in node.Triggers) - { + foreach (VCTrigger /*!*/ trigger in node.Triggers) { Contract.Assert(trigger != null); - newTriggers.Add(Gen.Trigger(trigger.Pos, MutateSeq(trigger.Exprs, substitution))); + newTriggers.Add(Gen.Trigger(trigger.Pos, await MutateSeq(trigger.Exprs, substitution))); } VCExpr /*!*/ @@ -1262,45 +1077,39 @@ protected virtual string ChooseNewVariableName(string oldName) return Gen.Quantify(node.Quan, typeParams, boundVars, newTriggers, node.Info, newBody); } - finally - { + finally { substitution.PopScope(); } } - public override VCExpr Visit(VCExprVar node, VCExprSubstitution substitution) - { + public override VCExpr Visit(VCExprVar node, VCExprSubstitution substitution) { Contract.Requires(substitution != null); Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); VCExpr res = substitution[node]; - if (res != null) - { + if (res != null) { return res; } return node; } - public override VCExpr Visit(VCExprLet node, VCExprSubstitution substitution) - { + public override DynamicStack Visit(VCExprLet node, VCExprSubstitution substitution) { Contract.Requires(substitution != null); Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); // the default is to refresh bound variables only if necessary // because of collisions - return Visit(node, substitution, false); + return DynamicStack.FromResult(Visit(node, substitution, false)); } - public VCExpr Visit(VCExprLet node, VCExprSubstitution substitution, bool refreshBoundVariables) - { + public VCExpr Visit(VCExprLet node, VCExprSubstitution substitution, bool refreshBoundVariables) { Contract.Requires(substitution != null); Contract.Requires(node != null); Contract.Ensures(Contract.Result() != null); // let-expressions do not have type parameters (fortunately ...) substitution.PushScope(); - try - { + try { bool refreshAllVariables = refreshBoundVariables || !substitution.TypeSubstIsEmpty || @@ -1309,8 +1118,7 @@ public VCExpr Visit(VCExprLet node, VCExprSubstitution substitution, bool refres List /*!*/ newBoundVars = node.BoundVars; Contract.Assert(cce.NonNullElements(newBoundVars)); - if (refreshAllVariables) - { + if (refreshAllVariables) { // collisions are possible, or we also substitute type variables. in this case // the bound term variables have to be replaced with fresh variables with the // right types @@ -1318,8 +1126,7 @@ public VCExpr Visit(VCExprLet node, VCExprSubstitution substitution, bool refres IDictionary /*!*/ typeSubst = substitution.ToTypeSubst; Contract.Assert(cce.NonNullDictionaryAndValues(typeSubst)); - foreach (VCExprVar /*!*/ var in node.BoundVars) - { + foreach (VCExprVar /*!*/ var in node.BoundVars) { Contract.Assert(var != null); VCExprVar /*!*/ freshVar = @@ -1334,8 +1141,7 @@ public VCExpr Visit(VCExprLet node, VCExprSubstitution substitution, bool refres List /*!*/ newbindings = new List(); - for (int i = 0; i < node.Length; ++i) - { + for (int i = 0; i < node.Length; ++i) { VCExprLetBinding /*!*/ binding = node[i]; Contract.Assert(binding != null); @@ -1347,8 +1153,7 @@ public VCExpr Visit(VCExprLet node, VCExprSubstitution substitution, bool refres Contract.Assert(newBody != null); return Gen.Let(newbindings, newBody); } - finally - { + finally { substitution.PopScope(); } } @@ -1356,10 +1161,8 @@ public VCExpr Visit(VCExprLet node, VCExprSubstitution substitution, bool refres //////////////////////////////////////////////////////////////////////////// [ContractClassFor(typeof(StandardVCExprOpVisitor<,>))] - public abstract class StandardVCExprOpVisitorContracts : StandardVCExprOpVisitor - { - protected override Result StandardResult(VCExprNAry node, Arg arg) - { + public abstract class StandardVCExprOpVisitorContracts : StandardVCExprOpVisitor { + protected override DynamicStack StandardResult(VCExprNAry node, Arg arg) { Contract.Requires(node != null); throw new NotImplementedException(); } @@ -1368,264 +1171,220 @@ protected override Result StandardResult(VCExprNAry node, Arg arg) [ContractClass(typeof(StandardVCExprOpVisitorContracts<,>))] public abstract class StandardVCExprOpVisitor - : IVCExprOpVisitor - { - protected abstract Result StandardResult(VCExprNAry /*!*/ node, Arg arg); + : IVCExprOpVisitor { + protected abstract DynamicStack StandardResult(VCExprNAry node /*!*/, Arg arg); - public virtual Result VisitNotOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitNotOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitEqOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitEqOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitNeqOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitNeqOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitAndOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitAndOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitOrOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitOrOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitImpliesOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitImpliesOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitDistinctOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitDistinctOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitFieldAccessOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitFieldAccessOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - - public virtual Result VisitIsConstructorOp(VCExprNAry node, Arg arg) - { + + public virtual DynamicStack VisitIsConstructorOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - - public virtual Result VisitSelectOp(VCExprNAry node, Arg arg) - { + + public virtual DynamicStack VisitSelectOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitStoreOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitStoreOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitFloatAddOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitFloatAddOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitFloatSubOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitFloatSubOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitFloatMulOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitFloatMulOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitFloatDivOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitFloatDivOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitFloatLeqOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitFloatLeqOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitFloatLtOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitFloatLtOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitFloatGeqOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitFloatGeqOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitFloatGtOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitFloatGtOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitFloatEqOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitFloatEqOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitFloatNeqOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitFloatNeqOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitBvOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitBvOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitBvExtractOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitBvExtractOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitBvConcatOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitBvConcatOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitIfThenElseOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitIfThenElseOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitCustomOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitCustomOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitAddOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitAddOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitSubOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitSubOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitMulOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitMulOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitDivOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitDivOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitModOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitModOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitRealDivOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitRealDivOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitPowOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitPowOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitLtOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitLtOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitLeOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitLeOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitGtOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitGtOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitGeOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitGeOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitSubtypeOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitSubtypeOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitSubtype3Op(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitSubtype3Op(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitToIntOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitToIntOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitToRealOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitToRealOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitToFloatOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitToFloatOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } - public virtual Result VisitBoogieFunctionOp(VCExprNAry node, Arg arg) - { + public virtual DynamicStack VisitBoogieFunctionOp(VCExprNAry node, Arg arg) { //Contract.Requires(node != null); return StandardResult(node, arg); } diff --git a/Source/VCExpr/VCExpressionGenerator.cs b/Source/VCExpr/VCExpressionGenerator.cs index 6cc61ce05..7cbece8a5 100644 --- a/Source/VCExpr/VCExpressionGenerator.cs +++ b/Source/VCExpr/VCExpressionGenerator.cs @@ -5,24 +5,20 @@ using Microsoft.BaseTypes; using Microsoft.Boogie.VCExprAST; -namespace Microsoft.Boogie -{ - public class VCExpressionGenerator - { +namespace Microsoft.Boogie { + public class VCExpressionGenerator { public static readonly VCExpr False = new VCExprLiteral(Type.Bool); public static readonly VCExpr True = new VCExprLiteral(Type.Bool); public const string ControlFlowName = "ControlFlow"; private Function ControlFlowFunction = null; - public VCExpr ControlFlowFunctionApplication(VCExpr e1, VCExpr e2) - { + public VCExpr ControlFlowFunctionApplication(VCExpr e1, VCExpr e2) { Contract.Requires(e1 != null); Contract.Requires(e2 != null); Contract.Ensures(Contract.Result() != null); - if (ControlFlowFunction == null) - { + if (ControlFlowFunction == null) { Formal /*!*/ first = new Formal(Token.NoToken, new TypedIdent(Token.NoToken, "", Microsoft.Boogie.Type.Int), true); Formal /*!*/ @@ -41,36 +37,31 @@ public VCExpr ControlFlowFunctionApplication(VCExpr e1, VCExpr e2) return Function(BoogieFunctionOp(ControlFlowFunction), args); } - public VCExpr /*!*/ Integer(BigNum x) - { + public VCExpr /*!*/ Integer(BigNum x) { Contract.Ensures(Contract.Result() != null); return new VCExprIntLit(x); } - public VCExpr /*!*/ Real(BigDec x) - { + public VCExpr /*!*/ Real(BigDec x) { Contract.Ensures(Contract.Result() != null); return new VCExprRealLit(x); } - public VCExpr /*!*/ Float(BigFloat x) - { + public VCExpr /*!*/ Float(BigFloat x) { Contract.Ensures(Contract.Result() != null); return new VCExprFloatLit(x); } - public VCExpr /*!*/ RMode(RoundingMode x) - { + public VCExpr /*!*/ RMode(RoundingMode x) { Contract.Ensures(Contract.Result() != null); return new VCExprRModeLit(x); } - public VCExpr /*!*/ String(String x) - { + public VCExpr /*!*/ String(String x) { Contract.Ensures(Contract.Result() != null); return new VCExprStringLit(x); @@ -78,18 +69,15 @@ public VCExpr ControlFlowFunctionApplication(VCExpr e1, VCExpr e2) public VCExpr /*!*/ Function(VCExprOp /*!*/ op, List /*!*/ arguments, - List /*!*/ typeArguments) - { + List /*!*/ typeArguments) { Contract.Requires(op != null); Contract.Requires(cce.NonNullElements(arguments)); Contract.Requires(cce.NonNullElements(typeArguments)); - if (typeArguments.Count > 0) - { + if (typeArguments.Count > 0) { return new VCExprMultiAry(op, arguments, typeArguments); } - switch (arguments.Count) - { + switch (arguments.Count) { case 0: return new VCExprNullary(op); case 1: @@ -101,8 +89,7 @@ public VCExpr ControlFlowFunctionApplication(VCExpr e1, VCExpr e2) } } - public VCExpr /*!*/ Function(VCExprOp /*!*/ op, List /*!*/ arguments) - { + public VCExpr /*!*/ Function(VCExprOp /*!*/ op, List /*!*/ arguments) { Contract.Requires(op != null); Contract.Requires(cce.NonNullElements(arguments)); Contract.Ensures(Contract.Result() != null); @@ -110,8 +97,7 @@ public VCExpr ControlFlowFunctionApplication(VCExpr e1, VCExpr e2) return Function(op, arguments, VCExprNAry.EMPTY_TYPE_LIST); } - public VCExpr /*!*/ Function(VCExprOp /*!*/ op, params VCExpr[] /*!*/ arguments) - { + public VCExpr /*!*/ Function(VCExprOp /*!*/ op, params VCExpr[] /*!*/ arguments) { Contract.Requires(op != null); Contract.Requires(cce.NonNullElements(arguments)); @@ -120,8 +106,7 @@ public VCExpr ControlFlowFunctionApplication(VCExpr e1, VCExpr e2) VCExprNAry.EMPTY_TYPE_LIST); } - public VCExpr /*!*/ Function(VCExprOp /*!*/ op, VCExpr[] /*!*/ arguments, Type[] /*!*/ typeArguments) - { + public VCExpr /*!*/ Function(VCExprOp /*!*/ op, VCExpr[] /*!*/ arguments, Type[] /*!*/ typeArguments) { Contract.Requires(op != null); Contract.Requires(cce.NonNullElements(arguments)); Contract.Requires(cce.NonNullElements(typeArguments)); @@ -133,8 +118,7 @@ public VCExpr ControlFlowFunctionApplication(VCExpr e1, VCExpr e2) HelperFuns.ToNonNullList(typeArguments)); } - public VCExpr /*!*/ Function(Function /*!*/ op, List /*!*/ arguments) - { + public VCExpr /*!*/ Function(Function /*!*/ op, List /*!*/ arguments) { Contract.Requires(op != null); Contract.Requires(cce.NonNullElements(arguments)); Contract.Ensures(Contract.Result() != null); @@ -142,8 +126,7 @@ public VCExpr ControlFlowFunctionApplication(VCExpr e1, VCExpr e2) return Function(BoogieFunctionOp(op), arguments, VCExprNAry.EMPTY_TYPE_LIST); } - public VCExpr /*!*/ Function(Function /*!*/ op, params VCExpr[] /*!*/ arguments) - { + public VCExpr /*!*/ Function(Function /*!*/ op, params VCExpr[] /*!*/ arguments) { Contract.Requires(cce.NonNullElements(arguments)); Contract.Requires(op != null); Contract.Ensures(Contract.Result() != null); @@ -154,8 +137,7 @@ public VCExpr ControlFlowFunctionApplication(VCExpr e1, VCExpr e2) // The following method should really be called "ReduceLeft". It must // only be used for the binary operators "and" and "or" - public VCExpr /*!*/ NAry(VCExprOp /*!*/ op, List /*!*/ args) - { + public VCExpr /*!*/ NAry(VCExprOp /*!*/ op, List /*!*/ args) { Contract.Requires(op != null); Contract.Requires(cce.NonNullElements(args)); Contract.Ensures(Contract.Result() != null); @@ -163,8 +145,7 @@ public VCExpr ControlFlowFunctionApplication(VCExpr e1, VCExpr e2) return NAry(op, args.ToArray()); } - public VCExpr /*!*/ NAry(VCExprOp /*!*/ op, params VCExpr[] /*!*/ args) - { + public VCExpr /*!*/ NAry(VCExprOp /*!*/ op, params VCExpr[] /*!*/ args) { Contract.Requires(op != null); Contract.Requires(cce.NonNullElements(args)); Contract.Requires(op == AndOp || op == OrOp); @@ -174,8 +155,7 @@ public VCExpr ControlFlowFunctionApplication(VCExpr e1, VCExpr e2) VCExpr /*!*/ e = and ? True : False; - foreach (VCExpr a in args) - { + foreach (VCExpr a in args) { e = and ? AndSimp(e, cce.NonNull(a)) : OrSimp(e, cce.NonNull(a)); } @@ -191,36 +171,31 @@ public VCExpr ControlFlowFunctionApplication(VCExpr e1, VCExpr e2) public static readonly VCExprOp OrOp = new VCExprNAryOp(2, Type.Bool); public static readonly VCExprOp ImpliesOp = new VCExprNAryOp(2, Type.Bool); - public VCExprDistinctOp DistinctOp(int arity) - { + public VCExprDistinctOp DistinctOp(int arity) { Contract.Ensures(Contract.Result() != null); return new VCExprDistinctOp(arity); } - public VCExpr /*!*/ Not(List /*!*/ args) - { + public VCExpr /*!*/ Not(List /*!*/ args) { Contract.Requires(args != null); Contract.Requires(args.Count == 1); Contract.Requires(args[0] != null); return Function(NotOp, args); } - public VCExpr /*!*/ Not(VCExpr /*!*/ e0) - { + public VCExpr /*!*/ Not(VCExpr /*!*/ e0) { Contract.Requires(e0 != null); Contract.Ensures(Contract.Result() != null); return Function(NotOp, e0); } - public VCExpr /*!*/ Eq(VCExpr /*!*/ e0, VCExpr /*!*/ e1) - { + public VCExpr /*!*/ Eq(VCExpr /*!*/ e0, VCExpr /*!*/ e1) { return Function(EqOp, e0, e1); } - public VCExpr /*!*/ Neq(VCExpr /*!*/ e0, VCExpr /*!*/ e1) - { + public VCExpr /*!*/ Neq(VCExpr /*!*/ e0, VCExpr /*!*/ e1) { Contract.Requires(e0 != null); Contract.Requires(e1 != null); Contract.Ensures(Contract.Result() != null); @@ -228,16 +203,14 @@ public VCExprDistinctOp DistinctOp(int arity) return Function(NeqOp, e0, e1); } - public VCExpr /*!*/ And(VCExpr /*!*/ e0, VCExpr /*!*/ e1) - { + public VCExpr /*!*/ And(VCExpr /*!*/ e0, VCExpr /*!*/ e1) { Contract.Requires(e0 != null); Contract.Requires(e1 != null); Contract.Ensures(Contract.Result() != null); return Function(AndOp, e0, e1); } - public VCExpr /*!*/ Gt(VCExpr /*!*/ e0, VCExpr /*!*/ e1) - { + public VCExpr /*!*/ Gt(VCExpr /*!*/ e0, VCExpr /*!*/ e1) { Contract.Requires(e0 != null); Contract.Requires(e1 != null); Contract.Ensures(Contract.Result() != null); @@ -245,8 +218,7 @@ public VCExprDistinctOp DistinctOp(int arity) return Function(GtOp, e0, e1); } - public VCExpr /*!*/ Add(VCExpr /*!*/ e0, VCExpr /*!*/ e1) - { + public VCExpr /*!*/ Add(VCExpr /*!*/ e0, VCExpr /*!*/ e1) { Contract.Requires(e0 != null); Contract.Requires(e1 != null); Contract.Ensures(Contract.Result() != null); @@ -255,29 +227,25 @@ public VCExprDistinctOp DistinctOp(int arity) return Function(op, e0, e1); } - public VCExpr /*!*/ Or(VCExpr /*!*/ e0, VCExpr /*!*/ e1) - { + public VCExpr /*!*/ Or(VCExpr /*!*/ e0, VCExpr /*!*/ e1) { Contract.Requires(e0 != null); Contract.Requires(e1 != null); Contract.Ensures(Contract.Result() != null); return Function(OrOp, e0, e1); } - public VCExpr /*!*/ Implies(VCExpr /*!*/ e0, VCExpr /*!*/ e1) - { + public VCExpr /*!*/ Implies(VCExpr /*!*/ e0, VCExpr /*!*/ e1) { Contract.Requires(e0 != null); Contract.Requires(e1 != null); Contract.Ensures(Contract.Result() != null); return Function(ImpliesOp, e0, e1); } - public VCExpr /*!*/ Distinct(List /*!*/ args) - { + public VCExpr /*!*/ Distinct(List /*!*/ args) { Contract.Requires(cce.NonNullElements(args)); Contract.Ensures(Contract.Result() != null); - if (args.Count <= 1) - { + if (args.Count <= 1) { // trivial case return True; } @@ -289,96 +257,78 @@ public VCExprDistinctOp DistinctOp(int arity) // Versions of the propositional operators that automatically simplify in // certain cases (for example, if one of the operators is True or False) - public VCExpr NotSimp(VCExpr e0) - { + public VCExpr NotSimp(VCExpr e0) { Contract.Requires(e0 != null); Contract.Ensures(Contract.Result() != null); - if (e0.Equals(True)) - { + if (e0.Equals(True)) { return False; } - if (e0.Equals(False)) - { + if (e0.Equals(False)) { return True; } return Not(e0); } - public VCExpr AndSimp(VCExpr e0, VCExpr e1) - { + public VCExpr AndSimp(VCExpr e0, VCExpr e1) { Contract.Requires(e1 != null); Contract.Requires(e0 != null); Contract.Ensures(Contract.Result() != null); - if (e0.Equals(True)) - { + if (e0.Equals(True)) { return e1; } - if (e1.Equals(True)) - { + if (e1.Equals(True)) { return e0; } - if (e0.Equals(False) || e1.Equals(False)) - { + if (e0.Equals(False) || e1.Equals(False)) { return False; } return And(e0, e1); } - public VCExpr OrSimp(VCExpr e0, VCExpr e1) - { + public VCExpr OrSimp(VCExpr e0, VCExpr e1) { Contract.Requires(e1 != null); Contract.Requires(e0 != null); Contract.Ensures(Contract.Result() != null); - if (e0.Equals(False)) - { + if (e0.Equals(False)) { return e1; } - if (e1.Equals(False)) - { + if (e1.Equals(False)) { return e0; } - if (e0.Equals(True) || e1.Equals(True)) - { + if (e0.Equals(True) || e1.Equals(True)) { return True; } return Or(e0, e1); } - public VCExpr ImpliesSimp(VCExpr e0, VCExpr e1, bool aggressive = true) - { + public VCExpr ImpliesSimp(VCExpr e0, VCExpr e1, bool aggressive = true) { Contract.Requires(e1 != null); Contract.Requires(e0 != null); Contract.Ensures(Contract.Result() != null); - if (e0.Equals(True)) - { + if (e0.Equals(True)) { return e1; } - if (e1.Equals(False)) - { + if (e1.Equals(False)) { return NotSimp(e0); } - if (e0.Equals(False) || e1.Equals(True)) - { + if (e0.Equals(False) || e1.Equals(True)) { return True; } // attempt to save on the depth of expressions (to reduce chances of stack overflows) - while (aggressive && e1 is VCExprBinary) - { - VCExprBinary n = (VCExprBinary) e1; - if (n.Op == ImpliesOp) - { - if (AndSize(n[0]) <= AndSize(e0)) - { + while (aggressive && e1 is VCExprBinary) { + VCExprBinary n = (VCExprBinary)e1; + if (n.Op == ImpliesOp) { + if (AndSize(n[0]) <= AndSize(e0)) { // combine the antecedents e0 = And(e0, n[0]); e1 = n[1]; @@ -397,20 +347,15 @@ public VCExpr ImpliesSimp(VCExpr e0, VCExpr e1, bool aggressive = true) /// top-most layers of the expression, or it can simply be the length of the left-prong of this and-tree. The /// important thing is that: AndSize(e0) >= AndSize(31) ==> AndSize(And(e0,e1)) > AndSize(e0). /// - int AndSize(VCExpr e) - { + int AndSize(VCExpr e) { Contract.Requires(e != null); int n = 1; - while (true) - { + while (true) { VCExprNAry nary = e as VCExprNAry; - if (nary != null && nary.Op == AndOp && 2 <= nary.Arity) - { + if (nary != null && nary.Op == AndOp && 2 <= nary.Arity) { e = nary[0]; n++; - } - else - { + } else { return n; } } @@ -433,7 +378,7 @@ int AndSize(VCExpr e) public static readonly VCExprOp LeOp = new VCExprNAryOp(2, Type.Bool); public static readonly VCExprOp GtOp = new VCExprNAryOp(2, Type.Bool); public static readonly VCExprOp GeOp = new VCExprNAryOp(2, Type.Bool); - + public static readonly VCExprOp IfThenElseOp = new VCExprIfThenElseOp(); public static readonly VCExprOp ToIntOp = new VCExprNAryOp(1, Type.Int); public static readonly VCExprOp ToRealOp = new VCExprNAryOp(1, Type.Real); @@ -449,8 +394,7 @@ int AndSize(VCExpr e) public static readonly VCExprOp NamedAssumeOp = new VCExprCustomOp("named_assume##dummy", 2, Type.Bool); public static readonly VCExprOp NamedAssertOp = new VCExprCustomOp("named_assert##dummy", 2, Type.Bool); - public VCExprOp BoogieFunctionOp(Function func) - { + public VCExprOp BoogieFunctionOp(Function func) { Contract.Requires(func != null); Contract.Ensures(Contract.Result() != null); return new VCExprBoogieFunctionOp(func); @@ -458,8 +402,7 @@ public VCExprOp BoogieFunctionOp(Function func) // Float nodes - public VCExprOp BinaryFloatOp(int sig, int exp, string op) - { + public VCExprOp BinaryFloatOp(int sig, int exp, string op) { Contract.Requires(exp > 0); Contract.Requires(sig > 0); Contract.Requires(op != null); @@ -469,22 +412,19 @@ public VCExprOp BinaryFloatOp(int sig, int exp, string op) // Bitvector nodes - public VCExpr Bitvector(BvConst bv) - { + public VCExpr Bitvector(BvConst bv) { Contract.Requires(bv != null); Contract.Ensures(Contract.Result() != null); return Function(new VCExprBvOp(bv.Bits), Integer(bv.Value)); } - public VCExpr BvExtract(VCExpr bv, int bits, int start, int end) - { + public VCExpr BvExtract(VCExpr bv, int bits, int start, int end) { Contract.Requires(bv != null); Contract.Ensures(Contract.Result() != null); return Function(new VCExprBvExtractOp(start, end, bits), bv); } - public VCExpr BvConcat(VCExpr bv1, VCExpr bv2) - { + public VCExpr BvConcat(VCExpr bv1, VCExpr bv2) { Contract.Requires(bv2 != null); Contract.Requires(bv1 != null); Contract.Ensures(Contract.Result() != null); @@ -495,8 +435,7 @@ public VCExpr BvConcat(VCExpr bv1, VCExpr bv2) // Dispatcher for the visitor // the declared singleton operators - internal enum SingletonOp - { + internal enum SingletonOp { NotOp, EqOp, NeqOp, @@ -526,14 +465,12 @@ internal enum SingletonOp SingletonOpDict; [ContractInvariantMethod] - void MiscInvariant() - { + void MiscInvariant() { Contract.Invariant(SingletonOpDict != null); } - static VCExpressionGenerator() - { + static VCExpressionGenerator() { ScopedNamer.AddBoogieDeterminedName(ControlFlowName); SingletonOpDict = new Dictionary(); @@ -566,8 +503,7 @@ static VCExpressionGenerator() // Let-bindings - public VCExprLetBinding LetBinding(VCExprVar v, VCExpr e) - { + public VCExprLetBinding LetBinding(VCExprVar v, VCExpr e) { Contract.Requires(e != null); Contract.Requires(v != null); Contract.Ensures(Contract.Result() != null); @@ -579,13 +515,11 @@ public VCExprLetBinding LetBinding(VCExprVar v, VCExpr e) // create expressions like "let x = y, y = 5 in ...". All bound variables are // bound in all bound terms/formulas and can occur there, but the dependencies // have to be acyclic - public VCExpr Let(List bindings, VCExpr body) - { + public VCExpr Let(List bindings, VCExpr body) { Contract.Requires(body != null); Contract.Requires(cce.NonNullElements(bindings)); Contract.Ensures(Contract.Result() != null); - if (bindings.Count == 0) - { + if (bindings.Count == 0) { // no empty let-bindings return body; } @@ -593,8 +527,7 @@ public VCExpr Let(List bindings, VCExpr body) return new VCExprLet(bindings, body); } - public VCExpr Let(VCExpr body, params VCExprLetBinding[] bindings) - { + public VCExpr Let(VCExpr body, params VCExprLetBinding[] bindings) { Contract.Requires(body != null); Contract.Requires((cce.NonNullElements(bindings))); Contract.Ensures(Contract.Result() != null); @@ -614,14 +547,12 @@ public VCExpr Let(VCExpr body, params VCExprLetBinding[] bindings) /// // Turn let-bindings let v = E in ... into implications E ==> v - public VCExpr AsImplications(List bindings) - { + public VCExpr AsImplications(List bindings) { Contract.Requires(cce.NonNullElements(bindings)); Contract.Ensures(Contract.Result() != null); VCExpr /*!*/ antecedents = True; - foreach (VCExprLetBinding b in bindings) - { + foreach (VCExprLetBinding b in bindings) { // turn "LET_binding v = E" into "v <== E" antecedents = AndSimp(antecedents, Implies(b.E, b.V)); } @@ -630,14 +561,12 @@ public VCExpr AsImplications(List bindings) } // Turn let-bindings let v = E in ... into equations v == E - public VCExpr AsEquations(List bindings) - { + public VCExpr AsEquations(List bindings) { Contract.Requires(cce.NonNullElements(bindings)); Contract.Ensures(Contract.Result() != null); VCExpr /*!*/ antecedents = True; - foreach (VCExprLetBinding b in bindings) - { + foreach (VCExprLetBinding b in bindings) { // turn "LET_binding v = E" into "v <== E" antecedents = AndSimp(antecedents, Eq(b.E, b.V)); } @@ -681,8 +610,7 @@ public VCExpr Store(List allArgs, List typeArgs) // Quantifiers public VCExpr Quantify(Quantifier quan, List /*!*/ typeParams, List /*!*/ vars, - List /*!*/ triggers, VCQuantifierInfo info, VCExpr body) - { + List /*!*/ triggers, VCQuantifierInfo info, VCExpr body) { Contract.Requires(body != null); Contract.Requires(info != null); Contract.Requires(cce.NonNullElements(triggers)); @@ -693,8 +621,7 @@ public VCExpr Quantify(Quantifier quan, List /*!*/ typeParam } public VCExpr Forall(List /*!*/ typeParams, List /*!*/ vars, - List /*!*/ triggers, VCQuantifierInfo info, VCExpr body) - { + List /*!*/ triggers, VCQuantifierInfo info, VCExpr body) { Contract.Requires(body != null); Contract.Requires(info != null); Contract.Requires(cce.NonNullElements(triggers)); @@ -705,8 +632,7 @@ public VCExpr Forall(List /*!*/ typeParams, List /*!*/ vars, List /*!*/ triggers, string qid, int weight, - VCExpr body) - { + VCExpr body) { Contract.Requires(body != null); Contract.Requires(qid != null); Contract.Requires(cce.NonNullElements(triggers)); @@ -716,8 +642,7 @@ public VCExpr Forall(List /*!*/ vars, List /*! triggers, new VCQuantifierInfo(qid, -1, weight), body); } - public VCExpr Forall(List /*!*/ vars, List /*!*/ triggers, VCExpr body) - { + public VCExpr Forall(List /*!*/ vars, List /*!*/ triggers, VCExpr body) { Contract.Requires(body != null); Contract.Requires(cce.NonNullElements(triggers)); Contract.Requires(cce.NonNullElements(vars)); @@ -726,8 +651,7 @@ public VCExpr Forall(List /*!*/ vars, List /*! triggers, new VCQuantifierInfo(null, -1), body); } - public VCExpr Forall(VCExprVar var, VCTrigger trigger, VCExpr body) - { + public VCExpr Forall(VCExprVar var, VCTrigger trigger, VCExpr body) { Contract.Requires(body != null); Contract.Requires(trigger != null); Contract.Requires(var != null); @@ -736,8 +660,7 @@ public VCExpr Forall(VCExprVar var, VCTrigger trigger, VCExpr body) } public VCExpr Exists(List /*!*/ typeParams, List /*!*/ vars, - List /*!*/ triggers, VCQuantifierInfo info, VCExpr body) - { + List /*!*/ triggers, VCQuantifierInfo info, VCExpr body) { Contract.Requires(body != null); Contract.Requires(info != null); Contract.Requires(cce.NonNullElements(triggers)); @@ -747,8 +670,7 @@ public VCExpr Exists(List /*!*/ typeParams, List /*!*/ vars, List /*!*/ triggers, VCExpr body) - { + public VCExpr Exists(List /*!*/ vars, List /*!*/ triggers, VCExpr body) { Contract.Requires(body != null); Contract.Requires(cce.NonNullElements(triggers)); Contract.Requires(cce.NonNullElements(vars)); @@ -757,8 +679,7 @@ public VCExpr Exists(List /*!*/ vars, List /*! triggers, new VCQuantifierInfo(null, -1), body); } - public VCExpr Exists(VCExprVar var, VCTrigger trigger, VCExpr body) - { + public VCExpr Exists(VCExprVar var, VCTrigger trigger, VCExpr body) { Contract.Requires(body != null); Contract.Requires(trigger != null); Contract.Requires(var != null); @@ -766,15 +687,13 @@ public VCExpr Exists(VCExprVar var, VCTrigger trigger, VCExpr body) return Exists(HelperFuns.ToNonNullList(var), HelperFuns.ToNonNullList(trigger), body); } - public VCTrigger Trigger(bool pos, List exprs) - { + public VCTrigger Trigger(bool pos, List exprs) { Contract.Requires(cce.NonNullElements(exprs)); Contract.Ensures(Contract.Result() != null); return new VCTrigger(pos, exprs); } - public VCTrigger Trigger(bool pos, params VCExpr[] exprs) - { + public VCTrigger Trigger(bool pos, params VCExpr[] exprs) { Contract.Requires(exprs != null); Contract.Requires((Contract.ForAll(0, exprs.Length, i => exprs[i] != null))); Contract.Ensures(Contract.Result() != null);