summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGravatar tabarbe <unknown>2010-08-03 23:57:53 +0000
committerGravatar tabarbe <unknown>2010-08-03 23:57:53 +0000
commitf0c044ebd634cfc48f8f0f4903fcafdec597e3bd (patch)
treee46c1e9c25313631903a82f5a1c789325a366aee
parent6aa09a12ee9d3722446390d1332f83402ca0bbdb (diff)
Dafny: Port commit part 1/2: Committing changed files.
Do not attempt to regenerate the Parser and Scanner files before the port of Boogie/Core is done, as these have undergone changes, but will not be committed until after the Core port.
-rw-r--r--Source/Dafny/Compiler.cs177
-rw-r--r--Source/Dafny/Dafny.atg511
-rw-r--r--Source/Dafny/DafnyAst.cs2153
-rw-r--r--Source/Dafny/DafnyMain.cs15
-rw-r--r--Source/Dafny/DafnyPipeline.csproj273
-rw-r--r--Source/Dafny/Parser.cs515
-rw-r--r--Source/Dafny/Printer.cs150
-rw-r--r--Source/Dafny/Resolver.cs570
-rw-r--r--Source/Dafny/Scanner.cs84
-rw-r--r--Source/Dafny/SccGraph.cs134
-rw-r--r--Source/Dafny/Translator.cs1552
11 files changed, 3883 insertions, 2251 deletions
diff --git a/Source/Dafny/Compiler.cs b/Source/Dafny/Compiler.cs
index 03a83862..1726baf5 100644
--- a/Source/Dafny/Compiler.cs
+++ b/Source/Dafny/Compiler.cs
@@ -7,20 +7,27 @@ using System;
using System.Collections.Generic;
using System.Numerics;
using System.IO;
-using Microsoft.Contracts;
+using System.Diagnostics.Contracts;
using Bpl = Microsoft.Boogie;
using System.Text;
namespace Microsoft.Dafny {
public class Compiler {
- public Compiler(TextWriter! wr) {
+ public Compiler(TextWriter wr) {
+ Contract.Requires(wr != null);
this.wr = wr;
}
- TextWriter! wr;
+ [ContractInvariantMethod]
+void ObjectInvariant()
+{
+ Contract.Invariant(wr!=null);
+}
+
+ TextWriter wr;
public int ErrorCount;
- void Error(string! msg, params object[] args) {
+ void Error(string msg, params object[] args) {Contract.Requires(msg != null);
string s = string.Format("Compilation error: " + msg, args);
Console.WriteLine(s);
wr.WriteLine("/* {0} */", s);
@@ -28,8 +35,8 @@ namespace Microsoft.Dafny {
}
void ReadRuntimeSystem() {
- string! codebase = (!) System.IO.Path.GetDirectoryName((!)System.Reflection.Assembly.GetExecutingAssembly().Location);
- string! path = System.IO.Path.Combine(codebase, "DafnyRuntime.cs");
+ string codebase = cce.NonNull( System.IO.Path.GetDirectoryName(cce.NonNull(System.Reflection.Assembly.GetExecutingAssembly().Location)));
+ string path = System.IO.Path.Combine(codebase, "DafnyRuntime.cs");
using (TextReader rd = new StreamReader(new FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read)))
{
while (true) {
@@ -50,7 +57,7 @@ namespace Microsoft.Dafny {
wr.Write(spaces.Substring(0, ind));
}
- public void Compile(Program! program) {
+ public void Compile(Program program) {Contract.Requires(program != null);
wr.WriteLine("// Dafny program {0} compiled into C#", program.Name);
wr.WriteLine();
ReadRuntimeSystem();
@@ -91,8 +98,8 @@ namespace Microsoft.Dafny {
}
}
- void CompileDatatypeConstructors(DatatypeDecl! dt, int indent)
- {
+ void CompileDatatypeConstructors(DatatypeDecl dt, int indent)
+ {Contract.Requires(dt != null);
foreach (DatatypeCtor ctor in dt.Ctors) {
// class Dt_Ctor<T,U> : Base_Dt<T> {
// Fields;
@@ -148,7 +155,7 @@ namespace Microsoft.Dafny {
}
}
- void CompileDatatypeStruct(DatatypeDecl! dt, int indent) {
+ void CompileDatatypeStruct(DatatypeDecl dt, int indent) {Contract.Requires(dt != null);
// public struct Dt<T> {
// Base_Dt<T> d;
// public Base_Dt<T> D {
@@ -188,7 +195,7 @@ namespace Microsoft.Dafny {
wr.WriteLine("public static Base_{0} Default {{", DtT);
Indent(ind + IndentAmount);
wr.Write("get { return ");
- wr.Write("new {0}", DtCtorName((!)dt.DefaultCtor));
+ wr.Write("new {0}", DtCtorName(cce.NonNull(dt.DefaultCtor)));
// todo: type parameters
wr.Write("(");
string sep = "";
@@ -214,8 +221,9 @@ namespace Microsoft.Dafny {
wr.WriteLine("}");
}
- void WriteFormals(List<Formal!>! formals)
+ void WriteFormals(List<Formal/*!*/>/*!*/ formals)
{
+ Contract.Requires(cce.NonNullElements(formals));
int i = 0;
string sep = "";
foreach (Formal arg in formals) {
@@ -228,16 +236,19 @@ namespace Microsoft.Dafny {
}
}
- string! FormalName(Formal! formal, int i) {
+ string FormalName(Formal formal, int i) {Contract.Requires(formal != null);Contract.Ensures(Contract.Result<string>() != null);
+
return formal.Name.StartsWith("#") ? "a" + i : formal.Name;
}
- string! DtCtorName(DatatypeCtor! ctor) {
- return ((!)ctor.EnclosingDatatype).Name + "_" + ctor.Name;
+ string DtCtorName(DatatypeCtor ctor) {Contract.Requires(ctor != null);Contract.Ensures(Contract.Result<string>() != null);
+
+ return cce.NonNull(ctor.EnclosingDatatype).Name + "_" + ctor.Name;
}
- void CompileClassMembers(ClassDecl! c, int indent)
+ void CompileClassMembers(ClassDecl c, int indent)
{
+ Contract.Requires(c != null);
foreach (MemberDecl member in c.Members) {
if (member is Field) {
Field f = (Field)member;
@@ -277,13 +288,13 @@ namespace Microsoft.Dafny {
string source = "_source" + tmpVarCount;
tmpVarCount++;
Indent(indent);
- wr.Write("{0} {1} = ", TypeName((!)me.Source.Type), source);
+ wr.Write("{0} {1} = ", TypeName(cce.NonNull(me.Source.Type)), source);
TrExpr(me.Source);
wr.WriteLine(";");
int i = 0;
foreach (MatchCaseExpr mc in me.Cases) {
- MatchCasePrelude(source, (!)mc.Ctor, mc.Arguments, i, me.Cases.Count, indent + IndentAmount);
+ MatchCasePrelude(source, cce.NonNull(mc.Ctor), mc.Arguments, i, me.Cases.Count, indent + IndentAmount);
Indent(indent + 2*IndentAmount);
wr.Write("return ");
@@ -336,7 +347,7 @@ namespace Microsoft.Dafny {
if (m.Name == "Main" && m.Ins.Count == 0 && m.Outs.Count == 0) {
Indent(indent);
wr.WriteLine("public static void Main(string[] args) {");
- ClassDecl cl = (!)m.EnclosingClass;
+ ClassDecl cl = cce.NonNull(m.EnclosingClass);
Indent(indent + IndentAmount);
wr.Write("{0} b = new {0}", cl.Name);
if (cl.TypeArgs.Count != 0) {
@@ -356,18 +367,21 @@ namespace Microsoft.Dafny {
}
} else {
- assert false; // unexpected member
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected member
}
}
}
// ----- Type ---------------------------------------------------------------------------------
- readonly string! DafnySetClass = "Dafny.Set";
- readonly string! DafnySeqClass = "Dafny.Sequence";
+ readonly string DafnySetClass = "Dafny.Set";
+ readonly string DafnySeqClass = "Dafny.Sequence";
- string! TypeName(Type! type)
+ string TypeName(Type type)
{
+ Contract.Requires(type != null);
+ Contract.Ensures(Contract.Result<string>() != null);
+
while (true) {
TypeProxy tp = type as TypeProxy;
if (tp == null) {
@@ -393,7 +407,7 @@ namespace Microsoft.Dafny {
UserDefinedType udt = (UserDefinedType)type;
string s = udt.Name;
if (udt.TypeArgs.Count != 0) {
- if (exists{Type argType in udt.TypeArgs; argType is ObjectType}) {
+ if (Contract.Exists(udt.TypeArgs, argType =>argType is ObjectType)) {
Error("compilation does not support type 'object' as a type parameter; consider introducing a ghost");
}
s += "<" + TypeNames(udt.TypeArgs) + ">";
@@ -412,11 +426,14 @@ namespace Microsoft.Dafny {
}
return DafnySeqClass + "<" + TypeName(argType) + ">";
} else {
- assert false; // unexpected type
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected type
}
}
- string! TypeNames(List<Type!>! types) {
+ string/*!*/ TypeNames(List<Type/*!*/>/*!*/ types) {
+ Contract.Requires(cce.NonNullElements(types));
+ Contract.Ensures(Contract.Result<string>() != null);
+
string s = "";
string sep = "";
foreach (Type t in types) {
@@ -426,7 +443,10 @@ namespace Microsoft.Dafny {
return s;
}
- string! TypeParameters(List<TypeParameter!>! targs) {
+ string/*!*/ TypeParameters(List<TypeParameter/*!*/>/*!*/ targs) {
+ Contract.Requires(cce.NonNullElements(targs));
+ Contract.Ensures(Contract.Result<string>() != null);
+
string s = "";
string sep = "";
foreach (TypeParameter tp in targs) {
@@ -436,8 +456,11 @@ namespace Microsoft.Dafny {
return s;
}
- string! DefaultValue(Type! type)
+ string DefaultValue(Type type)
{
+ Contract.Requires(type != null);
+ Contract.Ensures(Contract.Result<string>() != null);
+
while (true) {
TypeProxy tp = type as TypeProxy;
if (tp == null) {
@@ -471,14 +494,15 @@ namespace Microsoft.Dafny {
} else if (type is SeqType) {
return DafnySeqClass + "<" + TypeName(((SeqType)type).Arg) + ">.Empty";
} else {
- assert false; // unexpected type
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected type
}
}
// ----- Stmt ---------------------------------------------------------------------------------
- void TrStmt(Statement! stmt, int indent)
+ void TrStmt(Statement stmt, int indent)
{
+ Contract.Requires(stmt != null);
if (stmt.IsGhost) {
return;
}
@@ -491,7 +515,7 @@ namespace Microsoft.Dafny {
if (arg.S != null) {
wr.Write("\"{0}\"", arg.S);
} else {
- assert arg.E != null;
+ Contract.Assert( arg.E != null);
TrExpr(arg.E);
}
wr.WriteLine(");");
@@ -526,7 +550,7 @@ namespace Microsoft.Dafny {
string rhs = "_rhs" + tmpVarCount;
string i = "_i" + tmpVarCount;
tmpVarCount++;
- Indent(indent); wr.Write("{0} {1} = ", TypeName((!)sel.Seq.Type), arr); TrExpr(sel.Seq); wr.WriteLine(";");
+ Indent(indent); wr.Write("{0} {1} = ", TypeName(cce.NonNull(sel.Seq.Type)), arr); TrExpr(sel.Seq); wr.WriteLine(";");
Indent(indent); wr.Write("int {0} = ", low);
if (sel.E0 == null) {
wr.Write("0");
@@ -541,7 +565,7 @@ namespace Microsoft.Dafny {
TrExpr(sel.E1);
}
wr.WriteLine(";");
- Indent(indent); wr.Write("{0} {1} = ", TypeName((!)sel.Type), rhs); TrAssignmentRhs(s.Rhs); wr.WriteLine(";");
+ Indent(indent); wr.Write("{0} {1} = ", TypeName(cce.NonNull(sel.Type)), rhs); TrAssignmentRhs(s.Rhs); wr.WriteLine(";");
Indent(indent);
wr.WriteLine("for (BigInteger {0} = {1}; {0} < {2}; {0}++) {{", i, low, high);
Indent(indent + IndentAmount);
@@ -569,10 +593,10 @@ namespace Microsoft.Dafny {
TrVarDecl(local, false, indent);
}
- assert s.Method != null; // follows from the fact that stmt has been successfully resolved
+ Contract.Assert( s.Method != null); // follows from the fact that stmt has been successfully resolved
Indent(indent);
if (s.Method.IsStatic) {
- wr.Write(TypeName((!)s.Receiver.Type));
+ wr.Write(TypeName(cce.NonNull(s.Receiver.Type)));
} else {
TrParenExpr(s.Receiver);
}
@@ -649,7 +673,7 @@ namespace Microsoft.Dafny {
string pr = "_pair" + tmpVarCount;
tmpVarCount++;
string TType = TypeName(s.BoundVar.Type);
- string RhsType = TypeName((!)s.BodyAssign.Lhs.Type);
+ string RhsType = TypeName(cce.NonNull(s.BodyAssign.Lhs.Type));
Indent(indent);
wr.WriteLine("List<Pair<{0},{1}>> {2} = new List<Pair<{0},{1}>>();", TType, RhsType, pu);
@@ -702,28 +726,27 @@ namespace Microsoft.Dafny {
string source = "_source" + tmpVarCount;
tmpVarCount++;
Indent(indent);
- wr.Write("{0} {1} = ", TypeName((!)s.Source.Type), source);
+ wr.Write("{0} {1} = ", TypeName(cce.NonNull(s.Source.Type)), source);
TrExpr(s.Source);
wr.WriteLine(";");
int i = 0;
foreach (MatchCaseStmt mc in s.Cases) {
- MatchCasePrelude(source, (!)mc.Ctor, mc.Arguments, i, s.Cases.Count, indent);
+ MatchCasePrelude(source, cce.NonNull(mc.Ctor), mc.Arguments, i, s.Cases.Count, indent);
TrStmtList(mc.Body, indent);
i++;
}
Indent(indent); wr.WriteLine("}");
} else {
- assert false; // unexpected statement
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected statement
}
}
int tmpVarCount = 0;
- void TrAssignmentRhs(AssignmentRhs! rhs)
- requires !(rhs is HavocRhs);
- {
+ void TrAssignmentRhs(AssignmentRhs rhs){Contract.Requires(rhs != null);
+ Contract.Requires( !(rhs is HavocRhs));
if (rhs is ExprRhs) {
ExprRhs e = (ExprRhs)rhs;
TrExpr(e.Expr);
@@ -748,13 +771,13 @@ namespace Microsoft.Dafny {
}
}
- void TrStmtList(List<Statement!>! stmts, int indent) {
- List<string!> currentLabels = null;
+ void TrStmtList(List<Statement/*!*/>/*!*/ stmts, int indent) {Contract.Requires(cce.NonNullElements(stmts));
+ List<string/*!*/> currentLabels = null;
foreach (Statement ss in stmts) {
if (ss is LabelStmt) {
LabelStmt s = (LabelStmt)ss;
if (currentLabels == null) {
- currentLabels = new List<string!>();
+ currentLabels = new List<string>();
}
currentLabels.Add(s.Label);
} else {
@@ -766,7 +789,8 @@ namespace Microsoft.Dafny {
SpillLabels(currentLabels, indent);
}
- void SpillLabels(List<string!> labels, int indent) {
+ void SpillLabels(List<string> labels, int indent) {
+ Contract.Requires(cce.NonNullElements(labels));
if (labels != null) {
foreach (string label in labels) {
Indent(indent);
@@ -775,7 +799,8 @@ namespace Microsoft.Dafny {
}
}
- void TrVarDecl(VarDecl! s, bool alwaysInitialize, int indent) {
+ void TrVarDecl(VarDecl s, bool alwaysInitialize, int indent) {
+ Contract.Requires(s != null);
Indent(indent);
wr.Write("{0} {1}", TypeName(s.Type), s.Name);
if (s.Rhs != null) {
@@ -788,7 +813,10 @@ namespace Microsoft.Dafny {
wr.WriteLine(";");
}
- void MatchCasePrelude(string! source, DatatypeCtor! ctor, List<BoundVar!>! arguments, int caseIndex, int caseCount, int indent) {
+ void MatchCasePrelude(string source, DatatypeCtor ctor, List<BoundVar/*!*/>/*!*/ arguments, int caseIndex, int caseCount, int indent) {
+ Contract.Requires(source != null);
+ Contract.Requires(ctor != null);
+ Contract.Requires(cce.NonNullElements(arguments));
// if (source.D is Dt_Ctor0) {
// FormalType f0 = ((Dt_Ctor0)source.D).a0;
// ...
@@ -817,18 +845,22 @@ namespace Microsoft.Dafny {
// ----- Expression ---------------------------------------------------------------------------
- void TrParenExpr(string! prefix, Expression! expr) {
+ void TrParenExpr(string prefix, Expression expr) {
+ Contract.Requires(prefix != null);
+ Contract.Requires(expr != null);
wr.Write(prefix);
TrParenExpr(expr);
}
- void TrParenExpr(Expression! expr) {
+ void TrParenExpr(Expression expr) {
+ Contract.Requires(expr != null);
wr.Write("(");
TrExpr(expr);
wr.Write(")");
}
- void TrExprList(List<Expression!>! exprs) {
+ void TrExprList(List<Expression/*!*/>/*!*/ exprs) {
+ Contract.Requires(cce.NonNullElements(exprs));
wr.Write("(");
string sep = "";
foreach (Expression e in exprs) {
@@ -839,8 +871,9 @@ namespace Microsoft.Dafny {
wr.Write(")");
}
- void TrExpr(Expression! expr)
+ void TrExpr(Expression expr)
{
+ Contract.Requires(expr != null);
if (expr is LiteralExpr) {
LiteralExpr e = (LiteralExpr)expr;
if (e.Value == null) {
@@ -855,7 +888,7 @@ namespace Microsoft.Dafny {
wr.Write("BigInteger.Parse(\"{0}\")", i);
}
} else {
- assert false; // unexpected literal
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected literal
}
} else if (expr is ThisExpr) {
@@ -863,17 +896,17 @@ namespace Microsoft.Dafny {
} else if (expr is IdentifierExpr) {
IdentifierExpr e = (IdentifierExpr)expr;
- wr.Write(((!)e.Var).Name);
+ wr.Write(cce.NonNull(e.Var).Name);
} else if (expr is SetDisplayExpr) {
SetDisplayExpr e = (SetDisplayExpr)expr;
- Type elType = ((SetType!)e.Type).Arg;
+ Type elType = cce.NonNull((SetType)e.Type).Arg;
wr.Write("{0}<{1}>.FromElements", DafnySetClass, TypeName(elType));
TrExprList(e.Elements);
} else if (expr is SeqDisplayExpr) {
SeqDisplayExpr e = (SeqDisplayExpr)expr;
- Type elType = ((SeqType!)e.Type).Arg;
+ Type elType = cce.NonNull((SeqType)e.Type).Arg;
wr.Write("{0}<{1}>.FromElements", DafnySeqClass, TypeName(elType));
TrExprList(e.Elements);
@@ -885,15 +918,15 @@ namespace Microsoft.Dafny {
} else if (expr is SeqSelectExpr) {
SeqSelectExpr e = (SeqSelectExpr)expr;
TrParenExpr(e.Seq);
- assert e.Seq.Type != null;
+ Contract.Assert( e.Seq.Type != null);
if (e.Seq.Type.IsArrayType) {
- assert e.SelectOne;
- assert e.E0 != null && e.E1 == null;
+ Contract.Assert( e.SelectOne);
+ Contract.Assert( e.E0 != null && e.E1 == null);
wr.Write("[(int)");
TrParenExpr(e.E0);
wr.Write("]");
} else if (e.SelectOne) {
- assert e.E0 != null && e.E1 == null;
+ Contract.Assert( e.E0 != null && e.E1 == null);
TrParenExpr(".Select", e.E0);
} else {
if (e.E1 != null) {
@@ -915,9 +948,9 @@ namespace Microsoft.Dafny {
} else if (expr is FunctionCallExpr) {
FunctionCallExpr e = (FunctionCallExpr)expr;
- Function f = (!)e.Function;
+ Function f = cce.NonNull(e.Function);
if (f.IsStatic) {
- wr.Write(TypeName((!)e.Receiver.Type));
+ wr.Write(TypeName(cce.NonNull(e.Receiver.Type)));
} else {
TrParenExpr(e.Receiver);
}
@@ -935,7 +968,7 @@ namespace Microsoft.Dafny {
} else if (expr is DatatypeValue) {
DatatypeValue dtv = (DatatypeValue)expr;
- assert dtv.Ctor != null; // since dtv has been successfully resolved
+ Contract.Assert( dtv.Ctor != null); // since dtv has been successfully resolved
wr.Write("new {0}(new {0}", dtv.DatatypeName, DtCtorName(dtv.Ctor));
if (dtv.InferredTypeArgs.Count != 0) {
wr.Write("<{0}>", TypeNames(dtv.InferredTypeArgs));
@@ -953,10 +986,10 @@ namespace Microsoft.Dafny {
wr.Write("))");
} else if (expr is OldExpr) {
- assert false; // 'old' is always a ghost (right?)
+ Contract.Assert(false); throw new cce.UnreachableException(); // 'old' is always a ghost (right?)
} else if (expr is FreshExpr) {
- assert false; // 'fresh' is always a ghost
+ Contract.Assert(false); throw new cce.UnreachableException(); // 'fresh' is always a ghost
} else if (expr is UnaryExpr) {
UnaryExpr e = (UnaryExpr)expr;
@@ -966,7 +999,7 @@ namespace Microsoft.Dafny {
TrParenExpr(e.E);
break;
case UnaryExpr.Opcode.SeqLength:
- if (((!)e.E.Type).IsArrayType) {
+ if (cce.NonNull(e.E.Type).IsArrayType) {
wr.Write("new BigInteger(");
TrParenExpr(e.E);
wr.Write(".Length)");
@@ -976,7 +1009,7 @@ namespace Microsoft.Dafny {
}
break;
default:
- assert false; // unexpected unary expression
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected unary expression
}
} else if (expr is BinaryExpr) {
@@ -996,7 +1029,7 @@ namespace Microsoft.Dafny {
opString = "&&"; break;
case BinaryExpr.ResolvedOpcode.EqCommon: {
- Type t = (!)e.E0.Type;
+ Type t = cce.NonNull(e.E0.Type);
if (t.IsDatatype || t.IsTypeParameter) {
callString = "Equals";
} else {
@@ -1005,7 +1038,7 @@ namespace Microsoft.Dafny {
break;
}
case BinaryExpr.ResolvedOpcode.NeqCommon: {
- Type t = (!)e.E0.Type;
+ Type t = cce.NonNull(e.E0.Type);
if (t.IsDatatype || t.IsTypeParameter) {
preOpString = "!";
callString = "Equals";
@@ -1092,7 +1125,7 @@ namespace Microsoft.Dafny {
break;
default:
- assert false; // unexpected binary expression
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected binary expression
}
if (opString != null) {
wr.Write(preOpString);
@@ -1108,7 +1141,7 @@ namespace Microsoft.Dafny {
}
} else if (expr is QuantifierExpr) {
- assert false; // a quantifier is always a ghost
+ Contract.Assert(false); throw new cce.UnreachableException(); // a quantifier is always a ghost
} else if (expr is ITEExpr) {
ITEExpr e = (ITEExpr)expr;
@@ -1121,7 +1154,7 @@ namespace Microsoft.Dafny {
wr.Write(")");
} else {
- assert false; // unexpected expression
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected expression
}
}
}
diff --git a/Source/Dafny/Dafny.atg b/Source/Dafny/Dafny.atg
index 6ae97b5c..6b6749da 100644
--- a/Source/Dafny/Dafny.atg
+++ b/Source/Dafny/Dafny.atg
@@ -10,6 +10,7 @@
//--------------------------------------------------------------------------*/
using System.Collections.Generic;
+using System.Diagnostics.Contracts;
using System.Numerics;
using Microsoft.Boogie;
using System.IO;
@@ -20,14 +21,14 @@ COMPILER Dafny
/*--------------------------------------------------------------------------*/
-static List<ModuleDecl!>! theModules = new List<ModuleDecl!>();
+static List<ModuleDecl/*!*/>/*!*/ theModules = new List<ModuleDecl/*!*/>();
-static Expression! dummyExpr = new LiteralExpr(Token.NoToken);
-static FrameExpression! dummyFrameExpr = new FrameExpression(dummyExpr, null);
-static Statement! dummyStmt = new ReturnStmt(Token.NoToken);
-static Attributes.Argument! dummyAttrArg = new Attributes.Argument("dummyAttrArg");
-static Scope<string>! parseVarScope = new Scope<string>();
+static Expression/*!*/ dummyExpr = new LiteralExpr(Token.NoToken);
+static FrameExpression/*!*/ dummyFrameExpr = new FrameExpression(dummyExpr, null);
+static Statement/*!*/ dummyStmt = new ReturnStmt(Token.NoToken);
+static Attributes.Argument/*!*/ dummyAttrArg = new Attributes.Argument("dummyAttrArg");
+static Scope<string>/*!*/ parseVarScope = new Scope<string>();
static int anonymousIds = 0;
struct MemberModifiers {
@@ -37,9 +38,12 @@ struct MemberModifiers {
}
// helper routine for parsing call statements
-private static void RecordCallLhs(IdentifierExpr! e,
- List<IdentifierExpr!>! lhs,
- List<AutoVarDecl!>! newVars) {
+private static void RecordCallLhs(IdentifierExpr/*!*/ e,
+ List<IdentifierExpr/*!*/>/*!*/ lhs,
+ List<AutoVarDecl/*!*/>/*!*/ newVars) {
+ Contract.Requires(e != null);
+ Contract.Requires(cce.NonNullElements(lhs));
+ Contract.Requires(cce.NonNullElements(newVars));
int index = lhs.Count;
lhs.Add(e);
if (parseVarScope.Find(e.Name) == null) {
@@ -50,8 +54,10 @@ private static void RecordCallLhs(IdentifierExpr! e,
}
// helper routine for parsing call statements
-private static Expression! ConvertToLocal(Expression! e)
+private static Expression/*!*/ ConvertToLocal(Expression/*!*/ e)
{
+Contract.Requires(e != null);
+Contract.Ensures(Contract.Result<Expression>() != null);
FieldSelectExpr fse = e as FieldSelectExpr;
if (fse != null && fse.Obj is ImplicitThisExpr) {
return new IdentifierExpr(fse.tok, fse.FieldName);
@@ -65,14 +71,16 @@ private static Expression! ConvertToLocal(Expression! e)
/// Returns the number of parsing errors encountered.
/// Note: first initialize the Scanner.
///</summary>
-public static int Parse (string! filename, List<ModuleDecl!>! modules) /* throws System.IO.IOException */ {
+public static int Parse (string/*!*/ filename, List<ModuleDecl/*!*/>/*!*/ modules) /* throws System.IO.IOException */ {
+ Contract.Requires(filename != null);
+ Contract.Requires(cce.NonNullElements(modules));
string s;
if (filename == "stdin.dfy") {
- s = Microsoft.Boogie.ParserHelper.Fill(System.Console.In, new List<string!>());
+ s = Microsoft.Boogie.ParserHelper.Fill(System.Console.In, new List<string>());
return Parse(s, filename, modules);
} else {
using (System.IO.StreamReader reader = new System.IO.StreamReader(filename)) {
- s = Microsoft.Boogie.ParserHelper.Fill(reader, new List<string!>());
+ s = Microsoft.Boogie.ParserHelper.Fill(reader, new List<string>());
return Parse(s, filename, modules);
}
}
@@ -84,10 +92,13 @@ public static int Parse (string! filename, List<ModuleDecl!>! modules) /* throws
/// Returns the number of parsing errors encountered.
/// Note: first initialize the Scanner.
///</summary>
-public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules) {
- List<ModuleDecl!> oldModules = theModules;
+public static int Parse (string/*!*/ s, string/*!*/ filename, List<ModuleDecl/*!*/>/*!*/ modules) {
+ Contract.Requires(s != null);
+ Contract.Requires(filename != null);
+ Contract.Requires(cce.NonNullElements(modules));
+ List<ModuleDecl/*!*/> oldModules = theModules;
theModules = modules;
- byte[]! buffer = (!) UTF8Encoding.Default.GetBytes(s);
+ byte[]/*!*/ buffer = cce.NonNull( UTF8Encoding.Default.GetBytes(s));
MemoryStream ms = new MemoryStream(buffer,false);
Errors errors = new Errors();
Scanner scanner = new Scanner(ms, errors, filename);
@@ -131,10 +142,10 @@ IGNORE cr + lf + tab
PRODUCTIONS
Dafny
-= (. ClassDecl! c; DatatypeDecl! dt;
- Attributes attrs; IToken! id; List<string!> theImports;
+= (. ClassDecl/*!*/ c; DatatypeDecl/*!*/ dt;
+ Attributes attrs; IToken/*!*/ id; List<string/*!*/> theImports;
- List<MemberDecl!> membersDefaultClass = new List<MemberDecl!>();
+ List<MemberDecl/*!*/> membersDefaultClass = new List<MemberDecl/*!*/>();
ModuleDecl module;
// to support multiple files, create a default module only if theModules doesn't already contain one
@@ -149,7 +160,7 @@ Dafny
defaultModule = new DefaultModuleDecl();
}
.)
- { "module" (. attrs = null; theImports = new List<string!>(); .)
+ { "module" (. attrs = null; theImports = new List<string/*!*/>(); .)
{ Attribute<ref attrs> }
Ident<out id>
[ "imports" Idents<theImports> ] (. module = new ModuleDecl(id, id.val, theImports, attrs); .)
@@ -179,13 +190,15 @@ Dafny
EOF
.
-ClassDecl<ModuleDecl! module, out ClassDecl! c>
-= (. IToken! id;
+ClassDecl<ModuleDecl/*!*/ module, out ClassDecl/*!*/ c>
+= (. Contract.Requires(module != null);
+ Contract.Ensures(Contract.ValueAtReturn(out c) != null);
+ IToken/*!*/ id;
Attributes attrs = null;
- List<TypeParameter!> typeArgs = new List<TypeParameter!>();
- IToken! idRefined;
- IToken optionalId = null;
- List<MemberDecl!> members = new List<MemberDecl!>();
+ List<TypeParameter/*!*/> typeArgs = new List<TypeParameter/*!*/>();
+ IToken/*!*/ idRefined;
+ IToken optionalId = null;
+ List<MemberDecl/*!*/> members = new List<MemberDecl/*!*/>();
.)
"class"
{ Attribute<ref attrs> }
@@ -204,9 +217,10 @@ ClassDecl<ModuleDecl! module, out ClassDecl! c>
.)
.
-ClassMemberDecl<.List<MemberDecl!>! mm.>
-= (. Method! m;
- Function! f;
+ClassMemberDecl<.List<MemberDecl/*!*/>/*!*/ mm.>
+= (. Contract.Requires(cce.NonNullElements(mm));
+ Method/*!*/ m;
+ Function/*!*/ f;
MemberModifiers mmod = new MemberModifiers();
.)
{ "ghost" (. mmod.IsGhost = true; .)
@@ -220,11 +234,13 @@ ClassMemberDecl<.List<MemberDecl!>! mm.>
)
.
-DatatypeDecl<ModuleDecl! module, out DatatypeDecl! dt>
-= (. IToken! id;
+DatatypeDecl<ModuleDecl/*!*/ module, out DatatypeDecl/*!*/ dt>
+= (. Contract.Requires(module != null);
+ Contract.Ensures(Contract.ValueAtReturn(out dt)!=null);
+ IToken/*!*/ id;
Attributes attrs = null;
- List<TypeParameter!> typeArgs = new List<TypeParameter!>();
- List<DatatypeCtor!> ctors = new List<DatatypeCtor!>();
+ List<TypeParameter/*!*/> typeArgs = new List<TypeParameter/*!*/>();
+ List<DatatypeCtor/*!*/> ctors = new List<DatatypeCtor/*!*/>();
.)
"datatype"
{ Attribute<ref attrs> }
@@ -236,11 +252,12 @@ DatatypeDecl<ModuleDecl! module, out DatatypeDecl! dt>
"}" (. dt = new DatatypeDecl(id, id.val, module, typeArgs, ctors, attrs); .)
.
-DatatypeMemberDecl<.List<DatatypeCtor!>! ctors.>
-= (. Attributes attrs = null;
- IToken! id;
- List<TypeParameter!> typeArgs = new List<TypeParameter!>();
- List<Formal!> formals = new List<Formal!>();
+DatatypeMemberDecl<.List<DatatypeCtor/*!*/>/*!*/ ctors.>
+= (. Contract.Requires(cce.NonNullElements(ctors));
+ Attributes attrs = null;
+ IToken/*!*/ id;
+ List<TypeParameter/*!*/> typeArgs = new List<TypeParameter/*!*/>();
+ List<Formal/*!*/> formals = new List<Formal/*!*/>();
.)
{ Attribute<ref attrs> }
Ident<out id>
@@ -253,9 +270,10 @@ DatatypeMemberDecl<.List<DatatypeCtor!>! ctors.>
";"
.
-FieldDecl<.MemberModifiers mmod, List<MemberDecl!>! mm.>
-= (. Attributes attrs = null;
- IToken! id; Type! ty;
+FieldDecl<.MemberModifiers mmod, List<MemberDecl/*!*/>/*!*/ mm.>
+= (. Contract.Requires(cce.NonNullElements(mm));
+ Attributes attrs = null;
+ IToken/*!*/ id; Type/*!*/ ty;
.)
"var"
(. if (mmod.IsUnlimited) { SemErr(t, "fields cannot be declared 'unlimited'"); }
@@ -268,11 +286,12 @@ FieldDecl<.MemberModifiers mmod, List<MemberDecl!>! mm.>
";"
.
-CouplingInvDecl<.MemberModifiers mmod, List<MemberDecl!>! mm.>
-= (. Attributes attrs = null;
- List<IToken!> ids = new List<IToken!>();;
- IToken! id;
- Expression! e;
+CouplingInvDecl<.MemberModifiers mmod, List<MemberDecl/*!*/>/*!*/ mm.>
+= (. Contract.Requires(cce.NonNullElements(mm));
+ Attributes attrs = null;
+ List<IToken/*!*/> ids = new List<IToken/*!*/>();;
+ IToken/*!*/ id;
+ Expression/*!*/ e;
parseVarScope.PushMarker();
.)
"replaces"
@@ -293,22 +312,25 @@ CouplingInvDecl<.MemberModifiers mmod, List<MemberDecl!>! mm.>
.
-GIdentType<bool allowGhost, out IToken! id, out Type! ty, out bool isGhost>
+GIdentType<bool allowGhost, out IToken/*!*/ id, out Type/*!*/ ty, out bool isGhost>
/* isGhost always returns as false if allowGhost is false */
-= (. isGhost = false; .)
+= (. Contract.Ensures(Contract.ValueAtReturn(out id)!=null);
+ Contract.Ensures(Contract.ValueAtReturn(out ty)!=null);
+ isGhost = false; .)
[ "ghost" (. if (allowGhost) { isGhost = true; } else { SemErr(t, "formal cannot be declared 'ghost' in this context"); } .)
]
IdentType<out id, out ty>
.
-IdentType<out IToken! id, out Type! ty>
-= Ident<out id>
+IdentType<out IToken/*!*/ id, out Type/*!*/ ty>
+= (.Contract.Ensures(Contract.ValueAtReturn(out id) != null); Contract.Ensures(Contract.ValueAtReturn(out ty) != null);.)
+ Ident<out id>
":"
Type<out ty>
.
-IdentTypeOptional<out BoundVar! var>
-= (. IToken! id; Type! ty; Type optType = null;
+IdentTypeOptional<out BoundVar/*!*/ var>
+= (. Contract.Ensures(Contract.ValueAtReturn(out var)!=null); IToken/*!*/ id; Type/*!*/ ty; Type optType = null;
.)
Ident<out id>
[ ":" Type<out ty> (. optType = ty; .)
@@ -316,8 +338,11 @@ IdentTypeOptional<out BoundVar! var>
(. var = new BoundVar(id, id.val, optType == null ? new InferredTypeProxy() : optType); .)
.
-TypeIdentOptional<out IToken! id, out string! identName, out Type! ty, out bool isGhost>
-= (. string name = null; isGhost = false; .)
+TypeIdentOptional<out IToken/*!*/ id, out string/*!*/ identName, out Type/*!*/ ty, out bool isGhost>
+= (.Contract.Ensures(Contract.ValueAtReturn(out id)!=null);
+ Contract.Ensures(Contract.ValueAtReturn(out ty)!=null);
+ Contract.Ensures(Contract.ValueAtReturn(out identName)!=null);
+ string name = null; isGhost = false; .)
[ "ghost" (. isGhost = true; .)
]
TypeAndToken<out id, out ty>
@@ -342,8 +367,9 @@ TypeIdentOptional<out IToken! id, out string! identName, out Type! ty, out bool
/*------------------------------------------------------------------------*/
-GenericParameters<.List<TypeParameter!>! typeArgs.>
-= (. IToken! id; .)
+GenericParameters<.List<TypeParameter/*!*/>/*!*/ typeArgs.>
+= (. Contract.Requires(cce.NonNullElements(typeArgs));
+ IToken/*!*/ id; .)
"<"
Ident<out id> (. typeArgs.Add(new TypeParameter(id, id.val)); .)
{ "," Ident<out id> (. typeArgs.Add(new TypeParameter(id, id.val)); .)
@@ -353,17 +379,18 @@ GenericParameters<.List<TypeParameter!>! typeArgs.>
/*------------------------------------------------------------------------*/
-MethodDecl<MemberModifiers mmod, out Method! m>
-= (. IToken! id;
+MethodDecl<MemberModifiers mmod, out Method/*!*/ m>
+= (. Contract.Ensures(Contract.ValueAtReturn(out m) !=null);
+ IToken/*!*/ id;
Attributes attrs = null;
- List<TypeParameter!>! typeArgs = new List<TypeParameter!>();
- List<Formal!> ins = new List<Formal!>();
- List<Formal!> outs = new List<Formal!>();
- List<MaybeFreeExpression!> req = new List<MaybeFreeExpression!>();
- List<FrameExpression!> mod = new List<FrameExpression!>();
- List<MaybeFreeExpression!> ens = new List<MaybeFreeExpression!>();
- List<Expression!> dec = new List<Expression!>();
- Statement! bb; BlockStmt body = null;
+ List<TypeParameter/*!*/>/*!*/ typeArgs = new List<TypeParameter/*!*/>();
+ List<Formal/*!*/> ins = new List<Formal/*!*/>();
+ List<Formal/*!*/> outs = new List<Formal/*!*/>();
+ List<MaybeFreeExpression/*!*/> req = new List<MaybeFreeExpression/*!*/>();
+ List<FrameExpression/*!*/> mod = new List<FrameExpression/*!*/>();
+ List<MaybeFreeExpression/*!*/> ens = new List<MaybeFreeExpression/*!*/>();
+ List<Expression/*!*/> dec = new List<Expression/*!*/>();
+ Statement/*!*/ bb; BlockStmt body = null;
bool isRefinement = false;
.)
( "method"
@@ -392,9 +419,10 @@ MethodDecl<MemberModifiers mmod, out Method! m>
.)
.
-MethodSpec<.List<MaybeFreeExpression!>! req, List<FrameExpression!>! mod, List<MaybeFreeExpression!>! ens,
- List<Expression!>! decreases.>
-= (. Expression! e; FrameExpression! fe; bool isFree = false;
+MethodSpec<.List<MaybeFreeExpression/*!*/>/*!*/ req, List<FrameExpression/*!*/>/*!*/ mod, List<MaybeFreeExpression/*!*/>/*!*/ ens,
+ List<Expression/*!*/>/*!*/ decreases.>
+= (. Contract.Requires(cce.NonNullElements(req)); Contract.Requires(cce.NonNullElements(mod)); Contract.Requires(cce.NonNullElements(ens)); Contract.Requires(cce.NonNullElements(decreases));
+ Expression/*!*/ e; FrameExpression/*!*/ fe; bool isFree = false;
.)
( "modifies" [ FrameExpression<out fe> (. mod.Add(fe); .)
{ "," FrameExpression<out fe> (. mod.Add(fe); .)
@@ -409,8 +437,8 @@ MethodSpec<.List<MaybeFreeExpression!>! req, List<FrameExpression!>! mod, List<M
)
.
-Formals<.bool incoming, bool allowGhosts, List<Formal!>! formals.>
-= (. IToken! id; Type! ty; bool isGhost; .)
+Formals<.bool incoming, bool allowGhosts, List<Formal/*!*/>/*!*/ formals.>
+= (. Contract.Requires(cce.NonNullElements(formals)); IToken/*!*/ id; Type/*!*/ ty; bool isGhost; .)
"("
[
GIdentType<allowGhosts, out id, out ty, out isGhost> (. formals.Add(new Formal(id, id.val, ty, incoming, isGhost)); parseVarScope.Push(id.val, id.val); .)
@@ -420,8 +448,8 @@ Formals<.bool incoming, bool allowGhosts, List<Formal!>! formals.>
")"
.
-FormalsOptionalIds<.List<Formal!>! formals.>
-= (. IToken! id; Type! ty; string! name; bool isGhost; .)
+FormalsOptionalIds<.List<Formal/*!*/>/*!*/ formals.>
+= (. Contract.Requires(cce.NonNullElements(formals)); IToken/*!*/ id; Type/*!*/ ty; string/*!*/ name; bool isGhost; .)
"("
[
TypeIdentOptional<out id, out name, out ty, out isGhost> (. formals.Add(new Formal(id, name, ty, true, isGhost)); parseVarScope.Push(name, name); .)
@@ -433,25 +461,25 @@ FormalsOptionalIds<.List<Formal!>! formals.>
/*------------------------------------------------------------------------*/
-Type<out Type! ty>
-= (. IToken! tok; .)
+Type<out Type/*!*/ ty>
+= (. Contract.Ensures(Contract.ValueAtReturn(out ty) != null); IToken/*!*/ tok; .)
TypeAndToken<out tok, out ty>
.
-TypeAndToken<out IToken! tok, out Type! ty>
-= (. tok = Token.NoToken; ty = new BoolType(); /*keep compiler happy*/
- List<Type!>! gt;
+TypeAndToken<out IToken/*!*/ tok, out Type/*!*/ ty>
+= (. Contract.Ensures(Contract.ValueAtReturn(out tok)!=null); Contract.Ensures(Contract.ValueAtReturn(out ty) != null); tok = Token.NoToken; ty = new BoolType(); /*keep compiler happy*/
+ List<Type/*!*/>/*!*/ gt;
.)
( "bool" (. tok = t; .)
| "int" (. tok = t; ty = new IntType(); .)
- | "set" (. tok = t; gt = new List<Type!>(); .)
+ | "set" (. tok = t; gt = new List<Type/*!*/>(); .)
GenericInstantiation<gt> (. if (gt.Count != 1) {
SemErr("set type expects exactly one type argument");
}
ty = new SetType(gt[0]);
.)
- | "seq" (. tok = t; gt = new List<Type!>(); .)
+ | "seq" (. tok = t; gt = new List<Type/*!*/>(); .)
GenericInstantiation<gt> (. if (gt.Count != 1) {
SemErr("seq type expects exactly one type argument");
}
@@ -461,24 +489,25 @@ TypeAndToken<out IToken! tok, out Type! ty>
)
.
-ReferenceType<out IToken! tok, out Type! ty>
-= (. tok = Token.NoToken; ty = new BoolType(); /*keep compiler happy*/
- List<Type!>! gt;
+ReferenceType<out IToken/*!*/ tok, out Type/*!*/ ty>
+= (. Contract.Ensures(Contract.ValueAtReturn(out tok) != null); Contract.Ensures(Contract.ValueAtReturn(out ty) != null);
+ tok = Token.NoToken; ty = new BoolType(); /*keep compiler happy*/
+ List<Type/*!*/>/*!*/ gt;
.)
( "object" (. tok = t; ty = new ObjectType(); .)
- | "array" (. tok = t; gt = new List<Type!>(); .)
+ | "array" (. tok = t; gt = new List<Type/*!*/>(); .)
GenericInstantiation<gt> (. if (gt.Count != 1) {
SemErr("array type expects exactly one type argument");
}
ty = UserDefinedType.ArrayType(tok, gt[0]);
.)
- | Ident<out tok> (. gt = new List<Type!>(); .)
+ | Ident<out tok> (. gt = new List<Type/*!*/>(); .)
[ GenericInstantiation<gt> ] (. ty = new UserDefinedType(tok, tok.val, gt); .)
)
.
-GenericInstantiation<.List<Type!>! gt.>
-= (. Type! ty; .)
+GenericInstantiation<.List<Type/*!*/>/*!*/ gt.>
+= (. Contract.Requires(cce.NonNullElements(gt)); Type/*!*/ ty; .)
"<"
Type<out ty> (. gt.Add(ty); .)
{ "," Type<out ty> (. gt.Add(ty); .)
@@ -488,16 +517,17 @@ GenericInstantiation<.List<Type!>! gt.>
/*------------------------------------------------------------------------*/
-FunctionDecl<MemberModifiers mmod, out Function! f>
-= (. Attributes attrs = null;
- IToken! id;
- List<TypeParameter!> typeArgs = new List<TypeParameter!>();
- List<Formal!> formals = new List<Formal!>();
- Type! returnType;
- List<Expression!> reqs = new List<Expression!>();
- List<FrameExpression!> reads = new List<FrameExpression!>();
- List<Expression!> decreases = new List<Expression!>();
- Expression! bb; Expression body = null;
+FunctionDecl<MemberModifiers mmod, out Function/*!*/ f>
+= (. Contract.Ensures(Contract.ValueAtReturn(out f)!=null);
+ Attributes attrs = null;
+ IToken/*!*/ id;
+ List<TypeParameter/*!*/> typeArgs = new List<TypeParameter/*!*/>();
+ List<Formal/*!*/> formals = new List<Formal/*!*/>();
+ Type/*!*/ returnType;
+ List<Expression/*!*/> reqs = new List<Expression/*!*/>();
+ List<FrameExpression/*!*/> reads = new List<FrameExpression/*!*/>();
+ List<Expression/*!*/> decreases = new List<Expression/*!*/>();
+ Expression/*!*/ bb; Expression body = null;
bool isFunctionMethod = false;
.)
"function"
@@ -522,8 +552,9 @@ FunctionDecl<MemberModifiers mmod, out Function! f>
.)
.
-FunctionSpec<.List<Expression!>! reqs, List<FrameExpression!>! reads, List<Expression!>! decreases.>
-= (. Expression! e; FrameExpression! fe; .)
+FunctionSpec<.List<Expression/*!*/>/*!*/ reqs, List<FrameExpression/*!*/>/*!*/ reads, List<Expression/*!*/>/*!*/ decreases.>
+= (. Contract.Requires(cce.NonNullElements(reqs)); Contract.Requires(cce.NonNullElements(reads)); Contract.Requires(cce.NonNullElements(decreases));
+ Expression/*!*/ e; FrameExpression/*!*/ fe; .)
( "requires" Expression<out e> ";" (. reqs.Add(e); .)
| "reads" [ PossiblyWildFrameExpression<out fe> (. reads.Add(fe); .)
{ "," PossiblyWildFrameExpression<out fe> (. reads.Add(fe); .)
@@ -533,8 +564,9 @@ FunctionSpec<.List<Expression!>! reqs, List<FrameExpression!>! reads, List<Expre
)
.
-PossiblyWildExpression<out Expression! e>
-= (. e = dummyExpr; .)
+PossiblyWildExpression<out Expression/*!*/ e>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e)!=null);
+ e = dummyExpr; .)
/* A decreases clause on a loop asks that no termination check be performed.
* Use of this feature is sound only with respect to partial correctness.
*/
@@ -543,8 +575,8 @@ PossiblyWildExpression<out Expression! e>
)
.
-PossiblyWildFrameExpression<out FrameExpression! fe>
-= (. fe = dummyFrameExpr; .)
+PossiblyWildFrameExpression<out FrameExpression/*!*/ fe>
+= (. Contract.Ensures(Contract.ValueAtReturn(out fe) != null); fe = dummyFrameExpr; .)
/* A reads clause can list a wildcard, which allows the enclosing function to
* read anything. In many cases, and in particular in all cases where
* the function is defined recursively, this makes it next to impossible to make
@@ -556,16 +588,16 @@ PossiblyWildFrameExpression<out FrameExpression! fe>
)
.
-FrameExpression<out FrameExpression! fe>
-= (. Expression! e; IToken! id; string fieldName = null; .)
+FrameExpression<out FrameExpression/*!*/ fe>
+= (. Contract.Ensures(Contract.ValueAtReturn(out fe) != null); Expression/*!*/ e; IToken/*!*/ id; string fieldName = null; .)
Expression<out e>
[ "`" Ident<out id> (. fieldName = id.val; .)
]
(. fe = new FrameExpression(e, fieldName); .)
.
-FunctionBody<out Expression! e>
-= (. e = dummyExpr; .)
+FunctionBody<out Expression/*!*/ e>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e) != null); e = dummyExpr; .)
"{"
( MatchExpression<out e>
| Expression<out e>
@@ -573,9 +605,9 @@ FunctionBody<out Expression! e>
"}"
.
-MatchExpression<out Expression! e>
-= (. IToken! x; MatchCaseExpr! c;
- List<MatchCaseExpr!> cases = new List<MatchCaseExpr!>();
+MatchExpression<out Expression/*!*/ e>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x; MatchCaseExpr/*!*/ c;
+ List<MatchCaseExpr/*!*/> cases = new List<MatchCaseExpr/*!*/>();
.)
"match" (. x = t; .)
Expression<out e>
@@ -584,10 +616,10 @@ MatchExpression<out Expression! e>
(. e = new MatchExpr(x, e, cases); .)
.
-CaseExpression<out MatchCaseExpr! c>
-= (. IToken! x, id, arg;
- List<BoundVar!> arguments = new List<BoundVar!>();
- Expression! body;
+CaseExpression<out MatchCaseExpr/*!*/ c>
+= (. Contract.Ensures(Contract.ValueAtReturn(out c) != null); IToken/*!*/ x, id, arg;
+ List<BoundVar/*!*/> arguments = new List<BoundVar/*!*/>();
+ Expression/*!*/ body;
.)
"case" (. x = t; parseVarScope.PushMarker(); .)
Ident<out id>
@@ -605,10 +637,10 @@ CaseExpression<out MatchCaseExpr! c>
/*------------------------------------------------------------------------*/
-BlockStmt<out Statement! block>
-= (. IToken! x;
- List<Statement!> body = new List<Statement!>();
- Statement! s;
+BlockStmt<out Statement/*!*/ block>
+= (. Contract.Ensures(Contract.ValueAtReturn(out block) != null); IToken/*!*/ x;
+ List<Statement/*!*/> body = new List<Statement/*!*/>();
+ Statement/*!*/ s;
.)
(. parseVarScope.PushMarker(); .)
"{" (. x = t; .)
@@ -618,8 +650,8 @@ BlockStmt<out Statement! block>
(. parseVarScope.PopMarker(); .)
.
-Stmt<.List<Statement!>! ss.>
-= (. Statement! s; .)
+Stmt<.List<Statement/*!*/>/*!*/ ss.>
+= (. Contract.Requires(cce.NonNullElements(ss)); Statement/*!*/ s; .)
/* By first reading a sequence of block statements, we avoid problems in the generated parser, despite
the ambiguity in the grammar. See Note in ConstAtomExpression production.
*/
@@ -630,8 +662,8 @@ Stmt<.List<Statement!>! ss.>
)
.
-OneStmt<out Statement! s>
-= (. IToken! x; IToken! id; string label = null;
+OneStmt<out Statement/*!*/ s>
+= (. Contract.Ensures(Contract.ValueAtReturn(out s) != null); IToken/*!*/ x; IToken/*!*/ id; string label = null;
s = dummyStmt; /* to please the compiler */
.)
/* This list does not contain BlockStmt, see comment above in Stmt production. */
@@ -656,9 +688,9 @@ OneStmt<out Statement! s>
)
.
-AssignStmt<out Statement! s>
-= (. IToken! x;
- Expression! lhs;
+AssignStmt<out Statement/*!*/ s>
+= (. Contract.Ensures(Contract.ValueAtReturn(out s) != null); IToken/*!*/ x;
+ Expression/*!*/ lhs;
Expression rhs;
Type ty;
s = dummyStmt;
@@ -666,7 +698,7 @@ AssignStmt<out Statement! s>
LhsExpr<out lhs>
":=" (. x = t; .)
AssignRhs<out rhs, out ty> (. if (ty == null) {
- assert rhs != null;
+ Contract.Assert(rhs != null);
s = new AssignStmt(x, lhs, rhs);
} else if (rhs == null) {
s = new AssignStmt(x, lhs, ty);
@@ -679,7 +711,7 @@ AssignStmt<out Statement! s>
AssignRhs<out Expression e, out Type ty>
/* ensures e != null || ty != null; */
-= (. IToken! x; Expression! ee; Type! tt;
+= (. IToken/*!*/ x; Expression/*!*/ ee; Type/*!*/ tt;
e = null; ty = null;
.)
( "new" TypeAndToken<out x, out tt> (. ty = tt; .)
@@ -689,18 +721,19 @@ AssignRhs<out Expression e, out Type ty>
) (. if (e == null && ty == null) { e = dummyExpr; } .)
.
-HavocStmt<out Statement! s>
-= (. IToken! x; Expression! lhs; .)
+HavocStmt<out Statement/*!*/ s>
+= (. Contract.Ensures(Contract.ValueAtReturn(out s) != null); IToken/*!*/ x; Expression/*!*/ lhs; .)
"havoc" (. x = t; .)
LhsExpr<out lhs> ";" (. s = new AssignStmt(x, lhs); .)
.
-LhsExpr<out Expression! e>
-= SelectExpression<out e>
+LhsExpr<out Expression/*!*/ e>
+= (.Contract.Ensures(Contract.ValueAtReturn(out e)!=null);.)
+ SelectExpression<out e>
.
-VarDeclStmts<.List<Statement!>! ss.>
-= (. VarDecl! d; bool isGhost = false; .)
+VarDeclStmts<.List<Statement/*!*/>/*!*/ ss.>
+= (. Contract.Requires(cce.NonNullElements(ss)); VarDecl/*!*/ d; bool isGhost = false; .)
[ "ghost" (. isGhost = true; .)
]
"var"
@@ -710,8 +743,8 @@ VarDeclStmts<.List<Statement!>! ss.>
";"
.
-IdentTypeRhs<out VarDecl! d, bool isGhost>
-= (. IToken! id; Type! ty; Expression! e;
+IdentTypeRhs<out VarDecl/*!*/ d, bool isGhost>
+= (. Contract.Ensures(Contract.ValueAtReturn(out d) != null); IToken/*!*/ id; Type/*!*/ ty; Expression/*!*/ e;
Expression rhs = null; Type newType = null;
Type optionalType = null; DeterminedAssignmentRhs optionalRhs = null;
.)
@@ -736,11 +769,11 @@ IdentTypeRhs<out VarDecl! d, bool isGhost>
.)
.
-IfStmt<out Statement! ifStmt>
-= (. IToken! x;
+IfStmt<out Statement/*!*/ ifStmt>
+= (. Contract.Ensures(Contract.ValueAtReturn(out ifStmt) != null); IToken/*!*/ x;
Expression guard;
- Statement! thn;
- Statement! s;
+ Statement/*!*/ thn;
+ Statement/*!*/ s;
Statement els = null;
.)
"if" (. x = t; .)
@@ -754,16 +787,16 @@ IfStmt<out Statement! ifStmt>
(. ifStmt = new IfStmt(x, guard, thn, els); .)
.
-WhileStmt<out Statement! stmt>
-= (. IToken! x;
+WhileStmt<out Statement/*!*/ stmt>
+= (. Contract.Ensures(Contract.ValueAtReturn(out stmt) != null); IToken/*!*/ x;
Expression guard;
- bool isFree; Expression! e;
- List<MaybeFreeExpression!> invariants = new List<MaybeFreeExpression!>();
- List<Expression!> decreases = new List<Expression!>();
- Statement! body;
+ bool isFree; Expression/*!*/ e;
+ List<MaybeFreeExpression/*!*/> invariants = new List<MaybeFreeExpression/*!*/>();
+ List<Expression/*!*/> decreases = new List<Expression/*!*/>();
+ Statement/*!*/ body;
.)
"while" (. x = t; .)
- Guard<out guard> (. assume guard == null || Owner.None(guard); .)
+ Guard<out guard> (. Contract.Assume(guard == null || cce.Owner.None(guard)); .)
{ (. isFree = false; .)
[ "free" (. isFree = true; .)
]
@@ -780,7 +813,7 @@ WhileStmt<out Statement! stmt>
.
Guard<out Expression e> /* null represents demonic-choice */
-= (. Expression! ee; e = null; .)
+= (. Expression/*!*/ ee; e = null; .)
"("
( "*" (. e = null; .)
| Expression<out ee> (. e = ee; .)
@@ -788,9 +821,10 @@ Guard<out Expression e> /* null represents demonic-choice */
")"
.
-MatchStmt<out Statement! s>
-= (. Token x; Expression! e; MatchCaseStmt! c;
- List<MatchCaseStmt!> cases = new List<MatchCaseStmt!>(); .)
+MatchStmt<out Statement/*!*/ s>
+= (. Contract.Ensures(Contract.ValueAtReturn(out s) != null);
+ Token x; Expression/*!*/ e; MatchCaseStmt/*!*/ c;
+ List<MatchCaseStmt/*!*/> cases = new List<MatchCaseStmt/*!*/>(); .)
"match" (. x = t; .)
Expression<out e>
"{"
@@ -800,10 +834,11 @@ MatchStmt<out Statement! s>
(. s = new MatchStmt(x, e, cases); .)
.
-CaseStatement<out MatchCaseStmt! c>
-= (. IToken! x, id, arg;
- List<BoundVar!> arguments = new List<BoundVar!>();
- List<Statement!> body = new List<Statement!>();
+CaseStatement<out MatchCaseStmt/*!*/ c>
+= (. Contract.Ensures(Contract.ValueAtReturn(out c) != null);
+ IToken/*!*/ x, id, arg;
+ List<BoundVar/*!*/> arguments = new List<BoundVar/*!*/>();
+ List<Statement/*!*/> body = new List<Statement/*!*/>();
.)
"case" (. x = t; parseVarScope.PushMarker(); .)
Ident<out id>
@@ -822,11 +857,11 @@ CaseStatement<out MatchCaseStmt! c>
(. parseVarScope.PopMarker(); .)
.
-CallStmt<out Statement! s>
-= (. IToken! x, id;
- Expression! e;
- List<IdentifierExpr!> lhs = new List<IdentifierExpr!>();
- List<AutoVarDecl!> newVars = new List<AutoVarDecl!>();
+CallStmt<out Statement/*!*/ s>
+= (. Contract.Ensures(Contract.ValueAtReturn(out s) != null); IToken/*!*/ x, id;
+ Expression/*!*/ e;
+ List<IdentifierExpr/*!*/> lhs = new List<IdentifierExpr/*!*/>();
+ List<AutoVarDecl/*!*/> newVars = new List<AutoVarDecl/*!*/>();
.)
"call" (. x = t; .)
CallStmtSubExpr<out e>
@@ -868,19 +903,19 @@ CallStmt<out Statement! s>
s = new CallStmt(x, newVars, lhs, fce.Receiver, fce.Name, fce.Args); // this actually does an ownership transfer of fce.Args
} else {
SemErr("RHS of call statement must denote a method invocation");
- s = new CallStmt(x, newVars, lhs, dummyExpr, "dummyMethodName", new List<Expression!>());
+ s = new CallStmt(x, newVars, lhs, dummyExpr, "dummyMethodName", new List<Expression/*!*/>());
}
.)
.
/*------------------------------------------------------------------------*/
-ForeachStmt<out Statement! s>
-= (. IToken! x, boundVar;
- Type! ty;
- Expression! collection;
- Expression! range;
- List<PredicateStmt!> bodyPrefix = new List<PredicateStmt!>();
+ForeachStmt<out Statement/*!*/ s>
+= (. Contract.Ensures(Contract.ValueAtReturn(out s) != null); IToken/*!*/ x, boundVar;
+ Type/*!*/ ty;
+ Expression/*!*/ collection;
+ Expression/*!*/ range;
+ List<PredicateStmt/*!*/> bodyPrefix = new List<PredicateStmt/*!*/>();
AssignStmt bodyAssign = null;
.)
(. parseVarScope.PushMarker(); .)
@@ -911,27 +946,27 @@ ForeachStmt<out Statement! s>
(. parseVarScope.PopMarker(); .)
.
-AssertStmt<out Statement! s>
-= (. IToken! x; Expression! e; .)
+AssertStmt<out Statement/*!*/ s>
+= (. Contract.Ensures(Contract.ValueAtReturn(out s) != null); IToken/*!*/ x; Expression/*!*/ e; .)
"assert" (. x = t; .)
Expression<out e> ";" (. s = new AssertStmt(x, e); .)
.
-AssumeStmt<out Statement! s>
-= (. IToken! x; Expression! e; .)
+AssumeStmt<out Statement/*!*/ s>
+= (. Contract.Ensures(Contract.ValueAtReturn(out s) != null); IToken/*!*/ x; Expression/*!*/ e; .)
"assume" (. x = t; .)
Expression<out e> ";" (. s = new AssumeStmt(x, e); .)
.
-UseStmt<out Statement! s>
-= (. IToken! x; Expression! e; .)
+UseStmt<out Statement/*!*/ s>
+= (. Contract.Ensures(Contract.ValueAtReturn(out s) != null); IToken/*!*/ x; Expression/*!*/ e; .)
"use" (. x = t; .)
Expression<out e> ";" (. s = new UseStmt(x, e); .)
.
-PrintStmt<out Statement! s>
-= (. IToken! x; Attributes.Argument! arg;
- List<Attributes.Argument!> args = new List<Attributes.Argument!>();
+PrintStmt<out Statement/*!*/ s>
+= (. Contract.Ensures(Contract.ValueAtReturn(out s) != null); IToken/*!*/ x; Attributes.Argument/*!*/ arg;
+ List<Attributes.Argument/*!*/> args = new List<Attributes.Argument/*!*/>();
.)
"print" (. x = t; .)
AttributeArg<out arg> (. args.Add(arg); .)
@@ -941,8 +976,8 @@ PrintStmt<out Statement! s>
.
/*------------------------------------------------------------------------*/
-Expression<out Expression! e>
-= (. IToken! x; Expression! e0; Expression! e1 = dummyExpr;
+Expression<out Expression/*!*/ e>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x; Expression/*!*/ e0; Expression/*!*/ e1 = dummyExpr;
e = dummyExpr;
.)
( "if" (. x = t; .)
@@ -954,8 +989,8 @@ Expression<out Expression! e>
.
/*------------------------------------------------------------------------*/
-EquivExpression<out Expression! e0>
-= (. IToken! x; Expression! e1; .)
+EquivExpression<out Expression/*!*/ e0>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expression/*!*/ e1; .)
ImpliesExpression<out e0>
{ EquivOp (. x = t; .)
ImpliesExpression<out e1> (. e0 = new BinaryExpr(x, BinaryExpr.Opcode.Iff, e0, e1); .)
@@ -965,8 +1000,8 @@ EquivExpression<out Expression! e0>
EquivOp = "<==>" | '\u21d4'.
/*------------------------------------------------------------------------*/
-ImpliesExpression<out Expression! e0>
-= (. IToken! x; Expression! e1; .)
+ImpliesExpression<out Expression/*!*/ e0>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expression/*!*/ e1; .)
LogicalExpression<out e0>
[ ImpliesOp (. x = t; .)
ImpliesExpression<out e1> (. e0 = new BinaryExpr(x, BinaryExpr.Opcode.Imp, e0, e1); .)
@@ -976,8 +1011,8 @@ ImpliesExpression<out Expression! e0>
ImpliesOp = "==>" | '\u21d2'.
/*------------------------------------------------------------------------*/
-LogicalExpression<out Expression! e0>
-= (. IToken! x; Expression! e1; .)
+LogicalExpression<out Expression/*!*/ e0>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expression/*!*/ e1; .)
RelationalExpression<out e0>
[ AndOp (. x = t; .)
RelationalExpression<out e1> (. e0 = new BinaryExpr(x, BinaryExpr.Opcode.And, e0, e1); .)
@@ -996,16 +1031,16 @@ AndOp = "&&" | '\u2227'.
OrOp = "||" | '\u2228'.
/*------------------------------------------------------------------------*/
-RelationalExpression<out Expression! e0>
-= (. IToken! x; Expression! e1; BinaryExpr.Opcode op; .)
+RelationalExpression<out Expression/*!*/ e0>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expression/*!*/ e1; BinaryExpr.Opcode op; .)
Term<out e0>
[ RelOp<out x, out op>
Term<out e1> (. e0 = new BinaryExpr(x, op, e0, e1); .)
]
.
-RelOp<out IToken! x, out BinaryExpr.Opcode op>
-= (. x = Token.NoToken; op = BinaryExpr.Opcode.Add/*(dummy)*/; .)
+RelOp<out IToken/*!*/ x, out BinaryExpr.Opcode op>
+= (. Contract.Ensures(Contract.ValueAtReturn(out x) != null); x = Token.NoToken; op = BinaryExpr.Opcode.Add/*(dummy)*/; .)
( "==" (. x = t; op = BinaryExpr.Opcode.Eq; .)
| "<" (. x = t; op = BinaryExpr.Opcode.Lt; .)
| ">" (. x = t; op = BinaryExpr.Opcode.Gt; .)
@@ -1022,32 +1057,32 @@ RelOp<out IToken! x, out BinaryExpr.Opcode op>
.
/*------------------------------------------------------------------------*/
-Term<out Expression! e0>
-= (. IToken! x; Expression! e1; BinaryExpr.Opcode op; .)
+Term<out Expression/*!*/ e0>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expression/*!*/ e1; BinaryExpr.Opcode op; .)
Factor<out e0>
{ AddOp<out x, out op>
Factor<out e1> (. e0 = new BinaryExpr(x, op, e0, e1); .)
}
.
-AddOp<out IToken! x, out BinaryExpr.Opcode op>
-= (. x = Token.NoToken; op=BinaryExpr.Opcode.Add/*(dummy)*/; .)
+AddOp<out IToken/*!*/ x, out BinaryExpr.Opcode op>
+= (. Contract.Ensures(Contract.ValueAtReturn(out x) != null); x = Token.NoToken; op=BinaryExpr.Opcode.Add/*(dummy)*/; .)
( "+" (. x = t; op = BinaryExpr.Opcode.Add; .)
| "-" (. x = t; op = BinaryExpr.Opcode.Sub; .)
)
.
/*------------------------------------------------------------------------*/
-Factor<out Expression! e0>
-= (. IToken! x; Expression! e1; BinaryExpr.Opcode op; .)
+Factor<out Expression/*!*/ e0>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expression/*!*/ e1; BinaryExpr.Opcode op; .)
UnaryExpression<out e0>
{ MulOp<out x, out op>
UnaryExpression<out e1> (. e0 = new BinaryExpr(x, op, e0, e1); .)
}
.
-MulOp<out IToken! x, out BinaryExpr.Opcode op>
-= (. x = Token.NoToken; op = BinaryExpr.Opcode.Add/*(dummy)*/; .)
+MulOp<out IToken/*!*/ x, out BinaryExpr.Opcode op>
+= (. Contract.Ensures(Contract.ValueAtReturn(out x) != null); x = Token.NoToken; op = BinaryExpr.Opcode.Add/*(dummy)*/; .)
( "*" (. x = t; op = BinaryExpr.Opcode.Mul; .)
| "/" (. x = t; op = BinaryExpr.Opcode.Div; .)
| "%" (. x = t; op = BinaryExpr.Opcode.Mod; .)
@@ -1055,8 +1090,8 @@ MulOp<out IToken! x, out BinaryExpr.Opcode op>
.
/*------------------------------------------------------------------------*/
-UnaryExpression<out Expression! e>
-= (. IToken! x; e = dummyExpr; .)
+UnaryExpression<out Expression/*!*/ e>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x; e = dummyExpr; .)
( "-" (. x = t; .)
UnaryExpression<out e> (. e = new BinaryExpr(x, BinaryExpr.Opcode.Sub, new LiteralExpr(x, 0), e); .)
| NegOp (. x = t; .)
@@ -1068,8 +1103,8 @@ UnaryExpression<out Expression! e>
NegOp = "!" | '\u00ac'.
-ConstAtomExpression<out Expression! e>
-= (. IToken! x, dtName, id; BigInteger n; List<Expression!>! elements;
+ConstAtomExpression<out Expression/*!*/ e>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x, dtName, id; BigInteger n; List<Expression/*!*/>/*!*/ elements;
e = dummyExpr;
.)
( "false" (. e = new LiteralExpr(t, false); .)
@@ -1079,7 +1114,7 @@ ConstAtomExpression<out Expression! e>
| "#" (. x = t; .)
Ident<out dtName>
"."
- Ident<out id> (. elements = new List<Expression!>(); .)
+ Ident<out id> (. elements = new List<Expression/*!*/>(); .)
[ "("
[ Expressions<elements> ]
")" ] (. e = new DatatypeValue(t, dtName.val, id.val, elements); .)
@@ -1088,10 +1123,10 @@ ConstAtomExpression<out Expression! e>
| "|" (. x = t; .)
Expression<out e> (. e = new UnaryExpr(x, UnaryExpr.Opcode.SeqLength, e); .)
"|"
- | "{" (. x = t; elements = new List<Expression!>(); .)
+ | "{" (. x = t; elements = new List<Expression/*!*/>(); .)
[ Expressions<elements> ] (. e = new SetDisplayExpr(x, elements); .)
"}"
- | "[" (. x = t; elements = new List<Expression!>(); .)
+ | "[" (. x = t; elements = new List<Expression/*!*/>(); .)
[ Expressions<elements> ] (. e = new SeqDisplayExpr(x, elements); .)
"]"
)
@@ -1104,8 +1139,8 @@ ConstAtomExpression<out Expression! e>
-- FunctionCallExpr
-- FieldSelectExpr
*/
-CallStmtSubExpr<out Expression! e>
-= (. e = dummyExpr; .)
+CallStmtSubExpr<out Expression/*!*/ e>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e) != null); e = dummyExpr; .)
( IdentOrFuncExpression<out e>
| ObjectExpression<out e>
SelectOrCallSuffix<ref e>
@@ -1113,18 +1148,18 @@ CallStmtSubExpr<out Expression! e>
{ SelectOrCallSuffix<ref e> }
.
-SelectExpression<out Expression! e>
-= (. IToken! id; e = dummyExpr; .)
+SelectExpression<out Expression/*!*/ e>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ id; e = dummyExpr; .)
( IdentOrFuncExpression<out e>
| ObjectExpression<out e>
)
{ SelectOrCallSuffix<ref e> }
.
-IdentOrFuncExpression<out Expression! e>
-= (. IToken! id; e = dummyExpr; List<Expression!>! args; .)
+IdentOrFuncExpression<out Expression/*!*/ e>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ id; e = dummyExpr; List<Expression/*!*/>/*!*/ args; .)
Ident<out id>
- [ "(" (. args = new List<Expression!>(); .)
+ [ "(" (. args = new List<Expression/*!*/>(); .)
[ Expressions<args> ]
")" (. e = new FunctionCallExpr(id, id.val, new ImplicitThisExpr(id), args); .)
] (. if (e == dummyExpr) {
@@ -1137,14 +1172,14 @@ IdentOrFuncExpression<out Expression! e>
.)
.
-SelectOrCallSuffix<ref Expression! e>
-= (. IToken! id, x; List<Expression!>! args;
- Expression e0 = null; Expression e1 = null; Expression! ee; bool anyDots = false;
+SelectOrCallSuffix<ref Expression/*!*/ e>
+= (. Contract.Requires(e != null); Contract.Ensures(e!=null); IToken/*!*/ id, x; List<Expression/*!*/>/*!*/ args;
+ Expression e0 = null; Expression e1 = null; Expression/*!*/ ee; bool anyDots = false;
bool func = false;
.)
( "."
Ident<out id>
- [ "(" (. args = new List<Expression!>(); func = true; .)
+ [ "(" (. args = new List<Expression/*!*/>(); func = true; .)
[ Expressions<args> ]
")" (. e = new FunctionCallExpr(id, id.val, e, args); .)
] (. if (!func) { e = new FieldSelectExpr(id, e, id.val); } .)
@@ -1162,15 +1197,15 @@ SelectOrCallSuffix<ref Expression! e>
/* a parsing error occurred */
e0 = dummyExpr;
}
- assert !anyDots ==> e0 != null;
+ Contract.Assert(anyDots || e0 != null);
if (anyDots) {
- assert e0 != null || e1 != null;
+ Contract.Assert(e0 != null || e1 != null);
e = new SeqSelectExpr(x, false, e, e0, e1);
} else if (e1 == null) {
- assert e0 != null;
+ Contract.Assert(e0 != null);
e = new SeqSelectExpr(x, true, e, e0, null);
} else {
- assert e0 != null;
+ Contract.Assert(e0 != null);
e = new SeqUpdateExpr(x, e, e0, e1);
}
.)
@@ -1182,8 +1217,8 @@ SelectOrCallSuffix<ref Expression! e>
or E(...), except Ident. Since the lookahead is just 1, quantifier expressions are also
parsed here. The expression returned is never an lvalue.
*/
-ObjectExpression<out Expression! e>
-= (. IToken! x; e = dummyExpr; .)
+ObjectExpression<out Expression/*!*/ e>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x; e = dummyExpr; .)
( "this" (. e = new ThisExpr(t); .)
| "old" (. x = t; .)
"("
@@ -1198,15 +1233,15 @@ ObjectExpression<out Expression! e>
/*------------------------------------------------------------------------*/
-QuantifierGuts<out Expression! q>
-= (. IToken! x = Token.NoToken;
+QuantifierGuts<out Expression/*!*/ q>
+= (. Contract.Ensures(Contract.ValueAtReturn(out q) != null); IToken/*!*/ x = Token.NoToken;
bool univ = false;
- BoundVar! bv;
- List<BoundVar!> bvars = new List<BoundVar!>();
- IToken! tok; Expr! e; ExprSeq! es;
+ BoundVar/*!*/ bv;
+ List<BoundVar/*!*/> bvars = new List<BoundVar/*!*/>();
+ IToken/*!*/ tok; Expr/*!*/ e; ExprSeq/*!*/ es;
Attributes attrs = null;
Triggers trigs = null;
- Expression! body;
+ Expression/*!*/ body;
.)
( Forall (. x = t; univ = true; .)
| Exists (. x = t; .)
@@ -1232,8 +1267,8 @@ Forall = "forall" | '\u2200'.
Exists = "exists" | '\u2203'.
QSep = "::" | '\u2022'.
-Expressions<.List<Expression!>! args.>
-= (. Expression! e; .)
+Expressions<.List<Expression/*!*/>/*!*/ args.>
+= (. Contract.Requires(cce.NonNullElements(args)); Expression/*!*/ e; .)
Expression<out e> (. args.Add(e); .)
{ "," Expression<out e> (. args.Add(e); .)
}
@@ -1249,8 +1284,8 @@ Attribute<ref Attributes attrs>
AttributeBody<ref Attributes attrs>
= (. string aName;
- List<Attributes.Argument!> aArgs = new List<Attributes.Argument!>();
- Attributes.Argument! aArg;
+ List<Attributes.Argument/*!*/> aArgs = new List<Attributes.Argument/*!*/>();
+ Attributes.Argument/*!*/ aArg;
.)
":" ident (. aName = t.val; .)
[ AttributeArg<out aArg> (. aArgs.Add(aArg); .)
@@ -1259,19 +1294,19 @@ AttributeBody<ref Attributes attrs>
] (. attrs = new Attributes(aName, aArgs, attrs); .)
.
-AttributeArg<out Attributes.Argument! arg>
-= (. Expression! e; arg = dummyAttrArg; .)
+AttributeArg<out Attributes.Argument/*!*/ arg>
+= (. Contract.Ensures(Contract.ValueAtReturn(out arg) != null); Expression/*!*/ e; arg = dummyAttrArg; .)
( string (. arg = new Attributes.Argument(t.val.Substring(1, t.val.Length-2)); .)
| Expression<out e> (. arg = new Attributes.Argument(e); .)
)
.
AttributeOrTrigger<ref Attributes attrs, ref Triggers trigs>
-= (. List<Expression!> es = new List<Expression!>();
+= (. List<Expression/*!*/> es = new List<Expression/*!*/>();
.)
"{"
( AttributeBody<ref attrs>
- | (. es = new List<Expression!>(); .)
+ | (. es = new List<Expression/*!*/>(); .)
Expressions<es> (. trigs = new Triggers(es, trigs); .)
)
"}"
@@ -1279,15 +1314,15 @@ AttributeOrTrigger<ref Attributes attrs, ref Triggers trigs>
/*------------------------------------------------------------------------*/
-Idents<.List<string!>! ids.>
-= (. IToken! id; .)
+Idents<.List<string/*!*/>/*!*/ ids.>
+= (. IToken/*!*/ id; .)
Ident<out id> (. ids.Add(id.val); .)
{ "," Ident<out id> (. ids.Add(id.val); .)
}
.
-Ident<out IToken! x>
-=
+Ident<out IToken/*!*/ x>
+= (. Contract.Ensures(Contract.ValueAtReturn(out x) != null); .)
ident (. x = t; .)
.
@@ -1303,4 +1338,4 @@ Nat<out BigInteger n>
.)
.
-END Dafny.
+END Dafny. \ No newline at end of file
diff --git a/Source/Dafny/DafnyAst.cs b/Source/Dafny/DafnyAst.cs
index b5f21655..6f607d83 100644
--- a/Source/Dafny/DafnyAst.cs
+++ b/Source/Dafny/DafnyAst.cs
@@ -6,60 +6,83 @@
using System;
using System.Text;
using System.Collections.Generic;
-using Microsoft.Contracts;
+using System.Diagnostics.Contracts;
using System.Numerics;
using Microsoft.Boogie;
-namespace Microsoft.Dafny
-{
+namespace Microsoft.Dafny {
public class Program {
- public readonly string! Name;
- public readonly List<ModuleDecl!>! Modules;
- public Program(string! name, [Captured] List<ModuleDecl!>! modules) {
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Name != null);
+ Contract.Invariant(cce.NonNullElements(Modules));
+ }
+
+ public readonly string Name;
+ public readonly List<ModuleDecl/*!*/>/*!*/ Modules;
+ public Program(string name, [Captured] List<ModuleDecl/*!*/>/*!*/ modules) {
+ Contract.Requires(name != null);
+ Contract.Requires(cce.NonNullElements(modules));
Name = name;
Modules = modules;
}
}
-
+
public class Attributes {
- public readonly string! Name;
- /*Frozen*/ public readonly List<Argument!>! Args;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Name != null);
+ Contract.Invariant(cce.NonNullElements(Args));
+ }
+
+ public readonly string Name;
+ /*Frozen*/
+ public readonly List<Argument/*!*/>/*!*/ Args;
public readonly Attributes Prev;
-
- public Attributes(string! name, [Captured] List<Argument!>! args, Attributes prev)
- {
+
+ public Attributes(string name, [Captured] List<Argument/*!*/>/*!*/ args, Attributes prev) {
+ Contract.Requires(name != null);
+ Contract.Requires(cce.NonNullElements(args));
Name = name;
Args = args;
Prev = prev;
}
-
+
public class Argument {
public readonly string S;
public readonly Expression E;
- invariant (S == null) != (E == null);
-
- public Argument(string! s) {
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant((S == null) != (E == null));
+ }
+
+ public Argument(string s) {
+ Contract.Requires(s != null);
S = s;
}
- public Argument(Expression! e) {
+ public Argument(Expression e) {
+ Contract.Requires(e != null);
E = e;
}
}
}
-
+
// ------------------------------------------------------------------------------------------------------
-
+
public abstract class Type {
- public static readonly BoolType! Bool = new BoolType();
- public static readonly IntType! Int = new IntType();
+ public static readonly BoolType Bool = new BoolType();
+ public static readonly IntType Int = new IntType();
/// <summary>
/// Used in error situations in order to reduce further error messages.
/// </summary>
- [Pure(false)]
- public static Type! Flexible {
- get { return new InferredTypeProxy(); }
+ //[Pure(false)]
+ public static Type Flexible {
+ get {
+ Contract.Ensures(Contract.Result<Type>() != null);
+ return new InferredTypeProxy();
+ }
}
-
+
public bool IsRefType {
get {
if (this is ObjectType) {
@@ -73,7 +96,7 @@ namespace Microsoft.Dafny
public bool IsArrayType {
get {
UserDefinedType udt = UserDefinedType.DenotesClass(this);
- return udt != null && ((ClassDecl!)udt.ResolvedClass).Name == "array"; // the cast to non-null is guaranteed by postcondition of DenotesClass
+ return udt != null && cce.NonNull((ClassDecl)udt.ResolvedClass).Name == "array"; // the cast to non-null is guaranteed by postcondition of DenotesClass
}
}
public bool IsDatatype {
@@ -92,127 +115,163 @@ namespace Microsoft.Dafny
}
}
public bool IsTypeParameter {
- get
- ensures result ==> this is UserDefinedType && ((UserDefinedType)this).ResolvedParam != null;
- {
+ get {
+ Contract.Ensures(!Contract.Result<bool>() || this is UserDefinedType && ((UserDefinedType)this).ResolvedParam != null);
UserDefinedType ct = this as UserDefinedType;
return ct != null && ct.ResolvedParam != null;
}
}
}
-
+
public abstract class BasicType : Type {
}
-
+
public class BoolType : BasicType {
- [Pure] public override string! ToString() {
+ [Pure]
+ public override string ToString() {
return "bool";
}
}
-
+
public class IntType : BasicType {
- [Pure] public override string! ToString() {
+ [Pure]
+ public override string ToString() {
return "int";
}
}
-
+
public class ObjectType : BasicType {
- [Pure] public override string! ToString() {
+ [Pure]
+ public override string ToString() {
return "object";
}
}
-
+
public abstract class CollectionType : Type {
- public readonly Type! Arg;
- public CollectionType(Type! arg) {
+ public readonly Type Arg;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Arg != null);
+ }
+
+ public CollectionType(Type arg) {
+ Contract.Requires(arg != null);
this.Arg = arg;
}
}
-
+
public class SetType : CollectionType {
- public SetType(Type! arg) {
- base(arg);
+ public SetType(Type arg) :base(arg){
+ Contract.Requires(arg != null);
+
}
- [Pure] public override string! ToString() {
- assume Arg.IsPeerConsistent;
- return "set<" + Arg + ">";
+ [Pure]
+ public override string ToString() {
+ Contract.Ensures(Contract.Result<string>() != null);
+ Contract.Assume(cce.IsPeerConsistent(Arg));
+ return "set<" + base.Arg + ">";
}
}
-
+
public class SeqType : CollectionType {
- public SeqType(Type! arg) {
- base(arg);
+ public SeqType(Type arg):base(arg) {
+ Contract.Requires(arg != null);
+
}
- [Pure] public override string! ToString() {
- assume Arg.IsPeerConsistent;
- return "seq<" + Arg + ">";
+ [Pure]
+ public override string ToString() {
+ Contract.Ensures(Contract.Result<string>() != null);
+ Contract.Assume(cce.IsPeerConsistent(Arg));
+ return "seq<" + base.Arg + ">";
}
}
-
+
public class UserDefinedType : Type {
- public readonly IToken! tok;
- public readonly string! Name;
- [Rep] public readonly List<Type!>! TypeArgs;
-
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(tok != null);
+ Contract.Invariant(cce.NonNullElements(Name));
+ Contract.Invariant(cce.NonNullElements(TypeArgs));
+ Contract.Invariant(arrayTypeDecl != null);
+ }
+
+ public readonly IToken tok;
+ public readonly string Name;
+ [Rep]
+ public readonly List<Type/*!*/>/*!*/ TypeArgs;
+
public TopLevelDecl ResolvedClass; // filled in by resolution, if Name denotes a class/datatype and TypeArgs match the type parameters of that class/datatype
public TypeParameter ResolvedParam; // filled in by resolution, if Name denotes an enclosing type parameter and TypeArgs is the empty list
- public static UserDefinedType! ArrayType(IToken! tok, Type! arg) {
- List<Type!> typeArgs = new List<Type!>();
+ public static UserDefinedType ArrayType(IToken tok, Type arg) {
+ Contract.Requires(tok != null);
+ Contract.Requires(arg != null);
+ Contract.Ensures(Contract.Result<UserDefinedType>() != null);
+
+ List<Type/*!*/> typeArgs = new List<Type/*!*/>();
typeArgs.Add(arg);
UserDefinedType udt = new UserDefinedType(tok, "array", typeArgs);
udt.ResolvedClass = arrayTypeDecl;
return udt;
}
- static TopLevelDecl! arrayTypeDecl;
+ static TopLevelDecl/*!*/ arrayTypeDecl;
static UserDefinedType() {
- List<TypeParameter!> typeArgs = new List<TypeParameter!>();
+ List<TypeParameter> typeArgs = new List<TypeParameter>();
typeArgs.Add(new TypeParameter(Token.NoToken, "arg"));
- ModuleDecl systemModule = new ModuleDecl(Token.NoToken, "_System", new List<string!>(), null);
- arrayTypeDecl = new ClassDecl(Token.NoToken, "array", systemModule, typeArgs, new List<MemberDecl!>(), null);
+ ModuleDecl systemModule = new ModuleDecl(Token.NoToken, "_System", new List<string>(), null);
+ arrayTypeDecl = new ClassDecl(Token.NoToken, "array", systemModule, typeArgs, new List<MemberDecl>(), null);
}
-
- public UserDefinedType(IToken! tok, string! name, [Captured] List<Type!>! typeArgs) {
+
+ public UserDefinedType(IToken/*!*/ tok, string/*!*/ name, [Captured] List<Type/*!*/>/*!*/ typeArgs) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(typeArgs != null);
this.tok = tok;
this.Name = name;
this.TypeArgs = typeArgs;
}
-
+
/// <summary>
/// This constructor constructs a resolved class type
/// </summary>
- public UserDefinedType(IToken! tok, string! name, TopLevelDecl! cd, [Captured] List<Type!>! typeArgs) {
+ public UserDefinedType(IToken/*!*/ tok, string/*!*/ name, TopLevelDecl/*!*/ cd, [Captured] List<Type/*!*/>/*!*/ typeArgs) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(cd != null);
+ Contract.Requires(cce.NonNullElements(typeArgs));
this.tok = tok;
this.Name = name;
this.TypeArgs = typeArgs;
this.ResolvedClass = cd;
}
-
+
/// <summary>
/// This constructor constructs a resolved type parameter
/// </summary>
- public UserDefinedType(IToken! tok, string! name, TypeParameter! tp) {
+ public UserDefinedType(IToken/*!*/ tok, string/*!*/ name, TypeParameter/*!*/ tp) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(tp != null);
this.tok = tok;
this.Name = name;
- this.TypeArgs = new List<Type!>();
+ this.TypeArgs = new List<Type/*!*/>();
this.ResolvedParam = tp;
}
-
+
/// <summary>
/// If type denotes a resolved class type, then return that class type.
/// Otherwise, return null.
/// </summary>
- public static UserDefinedType DenotesClass(Type! type)
- ensures result != null ==> result.ResolvedClass is ClassDecl;
- {
- while (true)
- invariant type.IsPeerConsistent;
- {
+ public static UserDefinedType DenotesClass(Type/*!*/ type) {
+ Contract.Requires(type != null);
+ Contract.Ensures(Contract.Result<UserDefinedType>() == null || Contract.Result<UserDefinedType>().ResolvedClass is ClassDecl);
+ while (true) {
+ cce.LoopInvariant(cce.IsPeerConsistent(type));
TypeProxy pt = type as TypeProxy;
if (pt != null && pt.T != null) {
type = pt.T;
- assume type.IsPeerConsistent;
+ Contract.Assume(cce.IsPeerConsistent(type));
} else {
break;
}
@@ -224,26 +283,32 @@ namespace Microsoft.Dafny
return null;
}
}
-
+
/// <summary>
/// If type denotes a resolved class type, then return that class type.
/// Otherwise, return null.
/// </summary>
- public static Type! ArrayElementType(Type! type)
- requires type.IsArrayType;
- {
+ public static Type ArrayElementType(Type type) {
+ Contract.Requires(type.IsArrayType);
+
+ Contract.Requires(type != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
+
UserDefinedType udt = DenotesClass(type);
- assert udt != null;
- assert udt.TypeArgs.Count == 1; // holds true of all array types
+ Contract.Assert(udt != null);
+ Contract.Assert(udt.TypeArgs.Count == 1); // holds true of all array types
return udt.TypeArgs[0];
}
-
- [Pure] public override string! ToString() {
+
+ [Pure]
+ public override string ToString() {
+ Contract.Ensures(Contract.Result<string>() != null);
+
string s = Name;
if (TypeArgs.Count != 0) {
string sep = "<";
foreach (Type t in TypeArgs) {
- assume t.IsPeerConsistent;
+ Contract.Assume(cce.IsPeerConsistent(t));
s += sep + t;
sep = ",";
}
@@ -252,74 +317,109 @@ namespace Microsoft.Dafny
return s;
}
}
-
+
public abstract class TypeProxy : Type {
public Type T; // filled in during resolution
- internal TypeProxy() { }
-
- [Pure] public override string! ToString() {
- assume T == null || T.IsPeerConsistent;
+ internal TypeProxy() {
+ }
+
+ [Pure]
+ public override string ToString() {
+ Contract.Ensures(Contract.Result<string>() != null);
+
+ Contract.Assume(T == null || cce.IsPeerConsistent(T));
return T == null ? "?" : T.ToString();
}
}
-
- public abstract class UnrestrictedTypeProxy : TypeProxy { }
-
+
+ public abstract class UnrestrictedTypeProxy : TypeProxy {
+ }
+
/// <summary>
/// This proxy stands for any type.
/// </summary>
public class InferredTypeProxy : UnrestrictedTypeProxy {
}
-
+
/// <summary>
/// This proxy stands for any type, but it originates from an instantiated type parameter.
/// </summary>
public class ParamTypeProxy : UnrestrictedTypeProxy {
- TypeParameter! orig;
- public ParamTypeProxy(TypeParameter! orig) {
+ TypeParameter orig;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(orig != null);
+ }
+
+ public ParamTypeProxy(TypeParameter orig) {
+ Contract.Requires(orig != null);
this.orig = orig;
}
}
-
+
public abstract class RestrictedTypeProxy : TypeProxy {
/// <summary>
/// The OrderID is used to simplify the unification code. Each restricted type proxy should use its
/// own OrderID.
/// </summary>
- public abstract int OrderID { get; }
+ public abstract int OrderID {
+ get;
+ }
}
-
+
/// <summary>
/// This proxy stands for any datatype.
/// </summary>
public class DatatypeProxy : RestrictedTypeProxy {
- public override int OrderID { get { return 0; } }
+ public override int OrderID {
+ get {
+ return 0;
+ }
+ }
}
-
+
/// <summary>
/// This proxy stands for object or any class/array type.
/// </summary>
public class ObjectTypeProxy : RestrictedTypeProxy {
- public override int OrderID { get { return 1; } }
+ public override int OrderID {
+ get {
+ return 1;
+ }
+ }
}
-
+
/// <summary>
/// This proxy stands for object or any class/array type or a set/sequence of object or a class/array type.
/// </summary>
public class ObjectsTypeProxy : RestrictedTypeProxy {
- public override int OrderID { get { return 2; } }
+ public override int OrderID {
+ get {
+ return 2;
+ }
+ }
}
-
+
/// <summary>
/// This proxy stands for:
/// set(Arg) or seq(Arg)
/// </summary>
public class CollectionTypeProxy : RestrictedTypeProxy {
- public readonly Type! Arg;
- public CollectionTypeProxy(Type! arg) {
+ public readonly Type Arg;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Arg != null);
+ }
+
+ public CollectionTypeProxy(Type arg) {
+ Contract.Requires(arg != null);
Arg = arg;
}
- public override int OrderID { get { return 3; } }
+ public override int OrderID {
+ get {
+ return 3;
+ }
+ }
}
/// <summary>
@@ -334,296 +434,550 @@ namespace Microsoft.Dafny
public OperationTypeProxy(bool allowSeq) {
AllowSeq = allowSeq;
}
- public override int OrderID { get { return 4; } }
+ public override int OrderID {
+ get {
+ return 4;
+ }
+ }
}
-
+
/// <summary>
/// This proxy stands for:
/// seq(Arg) or array(Arg)
/// </summary>
public class IndexableTypeProxy : RestrictedTypeProxy {
- public readonly Type! Arg;
- public IndexableTypeProxy(Type! arg) {
+ public readonly Type Arg;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Arg != null);
+ }
+
+ public IndexableTypeProxy(Type arg) {
+ Contract.Requires(arg != null);
Arg = arg;
}
- public override int OrderID { get { return 5; } }
+ public override int OrderID {
+ get {
+ return 5;
+ }
+ }
}
// ------------------------------------------------------------------------------------------------------
-
+
public abstract class Declaration {
- public IToken! tok;
- public readonly string! Name;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(tok != null);
+ Contract.Invariant(Name != null);
+ }
+
+ public IToken/*!*/ tok;
+ public readonly string/*!*/ Name;
public readonly Attributes Attributes;
-
- public Declaration(IToken! tok, string! name, Attributes attributes) {
+
+ public Declaration(IToken tok, string name, Attributes attributes) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
this.tok = tok;
this.Name = name;
this.Attributes = attributes;
}
-
+
[Pure]
- public override string! ToString() {
+ public override string ToString() {
+ Contract.Ensures(Contract.Result<string>() != null);
+
return Name;
}
}
-
+
public class TypeParameter : Declaration {
- public interface ParentType { }
- [Peer] ParentType parent;
+ public interface ParentType {
+ }
+ [Peer]
+ ParentType parent;
public ParentType Parent {
get {
return parent;
}
[param: Captured]
- set
- requires Parent == null; // set it only once
- requires value != null;
+ set {
+ Contract.Requires(Parent == null); // set it only once
+ Contract.Requires(value != null);
// BUGBUG: The following line is a workaround to tell the verifier that 'value' is not of an Immutable type.
// A proper solution would be to be able to express that in the program (in a specification or attribute) or
// to be able to declare 'parent' as [PeerOrImmutable].
- requires value is TopLevelDecl || value is Function || value is Method || value is DatatypeCtor;
- modifies parent;
- {
+ Contract.Requires(value is TopLevelDecl || value is Function || value is Method || value is DatatypeCtor);
+ //modifies parent;
parent = value;
}
}
- public TypeParameter(IToken! tok, string! name) {
- base(tok, name, null);
+ public TypeParameter(IToken tok, string name)
+ : base(tok, name, null) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+
}
}
-
+
public class ModuleDecl : Declaration {
- public readonly List<string!>! Imports;
- public readonly List<TopLevelDecl!>! TopLevelDecls = new List<TopLevelDecl!>(); // filled in by the parser; readonly after that
- public readonly Graph<MemberDecl!>! CallGraph = new Graph<MemberDecl!>(); // filled in during resolution
+ public readonly List<string/*!*/>/*!*/ Imports;
+ public readonly List<TopLevelDecl/*!*/> TopLevelDecls = new List<TopLevelDecl/*!*/>(); // filled in by the parser; readonly after that
+ public readonly Graph<MemberDecl/*!*/> CallGraph = new Graph<MemberDecl/*!*/>(); // filled in during resolution
public int Height; // height in the topological sorting of modules; filled in during resolution
- public ModuleDecl(IToken! tok, string! name, [Captured] List<string!>! imports, Attributes attributes) {
+
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(cce.NonNullElements(Imports));
+ Contract.Invariant(cce.NonNullElements(TopLevelDecls));
+ Contract.Invariant(CallGraph != null);
+ }
+
+
+ public ModuleDecl(IToken tok, string name, [Captured] List<string/*!*/>/*!*/ imports, Attributes attributes)
+ : base(tok, name, attributes) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(cce.NonNullElements(imports));
Imports = imports;
- base(tok, name, attributes);
+
}
public virtual bool IsDefaultModule {
- get { return false; }
+ get {
+ return false;
+ }
}
}
-
+
public class DefaultModuleDecl : ModuleDecl {
- public DefaultModuleDecl() {
- base(Token.NoToken, "_default", new List<string!>(), null);
+ public DefaultModuleDecl() : base(Token.NoToken, "_default", new List<string/*!*/>(), null) {
}
public override bool IsDefaultModule {
- get { return true; }
+ get {
+ return true;
+ }
}
}
-
+
public abstract class TopLevelDecl : Declaration, TypeParameter.ParentType {
- public readonly ModuleDecl! Module;
- public readonly List<TypeParameter!>! TypeArgs;
-
- public TopLevelDecl(IToken! tok, string! name, ModuleDecl! module, List<TypeParameter!>! typeArgs, Attributes attributes) {
+ public readonly ModuleDecl Module;
+ public readonly List<TypeParameter/*!*/>/*!*/ TypeArgs;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Module != null);
+ Contract.Invariant(cce.NonNullElements(TypeArgs));
+ }
+
+
+ public TopLevelDecl(IToken/*!*/ tok, string/*!*/ name, ModuleDecl/*!*/ module, List<TypeParameter/*!*/>/*!*/ typeArgs, Attributes attributes)
+ : base(tok, name, attributes) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(module != null);
+ Contract.Requires(cce.NonNullElements(typeArgs));
Module = module;
TypeArgs = typeArgs;
- base(tok, name, attributes);
}
}
public class ClassDecl : TopLevelDecl {
- public readonly List<MemberDecl!>! Members;
+ public readonly List<MemberDecl/*!*/>/*!*/ Members;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(cce.NonNullElements(Members));
+ }
+
+
+ public ClassDecl(IToken/*!*/ tok, string/*!*/ name, ModuleDecl/*!*/ module,
+ List<TypeParameter/*!*/>/*!*/ typeArgs, [Captured] List<MemberDecl/*!*/>/*!*/ members, Attributes attributes)
+ : base(tok, name, module, typeArgs, attributes) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(module != null);
+ Contract.Requires(cce.NonNullElements(typeArgs));
+ Contract.Requires(cce.NonNullElements(members));
+
- public ClassDecl(IToken! tok, string! name, ModuleDecl! module, List<TypeParameter!>! typeArgs, [Captured] List<MemberDecl!>! members, Attributes attributes) {
Members = members;
- base(tok, name, module, typeArgs, attributes);
}
public virtual bool IsDefaultClass {
- get { return false; }
+ get {
+ return false;
+ }
}
}
-
+
public class ClassRefinementDecl : ClassDecl {
- public readonly IToken! RefinedClass;
+ public readonly IToken/*!*/ RefinedClass;
public ClassDecl Refined; // filled in during resolution
- public ClassRefinementDecl(IToken! tok, string! name, ModuleDecl! module, List<TypeParameter!>! typeArgs, [Captured] List<MemberDecl!>! members, Attributes attributes, IToken! refinedClass) {
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(RefinedClass != null);
+ }
+
+ public ClassRefinementDecl(IToken tok, string name, ModuleDecl module, List<TypeParameter/*!*/>/*!*/ typeArgs,
+ [Captured] List<MemberDecl/*!*/>/*!*/ members, Attributes attributes, IToken/*!*/ refinedClass)
+ : base(tok, name, module, typeArgs, members, attributes) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(module != null);
+ Contract.Requires(cce.NonNullElements(typeArgs));
+ Contract.Requires(cce.NonNullElements(members));
+ Contract.Requires(refinedClass != null);
RefinedClass = refinedClass;
- base(tok, name, module, typeArgs, members, attributes);
}
}
-
+
public class DefaultClassDecl : ClassDecl {
- public DefaultClassDecl(DefaultModuleDecl! module, [Captured] List<MemberDecl!>! members) {
- base(Token.NoToken, "_default", module, new List<TypeParameter!>(), members, null);
+ public DefaultClassDecl(DefaultModuleDecl/*!*/ module, [Captured] List<MemberDecl/*!*/>/*!*/ members)
+ : base(Token.NoToken, "_default", module, new List<TypeParameter/*!*/>(), members, null) {
+ Contract.Requires(module != null);
+ Contract.Requires(cce.NonNullElements(members));
}
public override bool IsDefaultClass {
- get { return true; }
+ get {
+ return true;
+ }
}
}
-
+
public class DatatypeDecl : TopLevelDecl {
- public readonly List<DatatypeCtor!>! Ctors;
+ public readonly List<DatatypeCtor/*!*/>/*!*/ Ctors;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(cce.NonNullElements(Ctors));
+ }
+
public DatatypeCtor DefaultCtor; // set during resolution
-
- public DatatypeDecl(IToken! tok, string! name, ModuleDecl! module, List<TypeParameter!>! typeArgs, [Captured] List<DatatypeCtor!>! ctors, Attributes attributes) {
+
+ public DatatypeDecl(IToken/*!*/ tok, string/*!*/ name, ModuleDecl/*!*/ module, List<TypeParameter/*!*/>/*!*/ typeArgs,
+ [Captured] List<DatatypeCtor/*!*/>/*!*/ ctors, Attributes attributes)
+ : base(tok, name, module, typeArgs, attributes) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(module != null);
+ Contract.Requires(cce.NonNullElements(typeArgs));
+ Contract.Requires(cce.NonNullElements(ctors));
Ctors = ctors;
- base(tok, name, module, typeArgs, attributes);
+
}
}
-
+
public class DatatypeCtor : Declaration, TypeParameter.ParentType {
- public readonly List<TypeParameter!>! TypeArgs;
- public readonly List<Formal!>! Formals;
- // Todo: One could imagine having a precondition on datatype constructors
+ public readonly List<TypeParameter/*!*/>/*!*/ TypeArgs;
+ public readonly List<Formal/*!*/>/*!*/ Formals;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(cce.NonNullElements(TypeArgs));
+ Contract.Invariant(cce.NonNullElements(Formals));
+ }
+
+ // TODO: One could imagine having a precondition on datatype constructors
public DatatypeDecl EnclosingDatatype; // filled in during resolution
-
- public DatatypeCtor(IToken! tok, string! name, [Captured] List<TypeParameter!>! typeArgs, [Captured] List<Formal!>! formals,
- Attributes attributes) {
+
+ public DatatypeCtor(IToken/*!*/ tok, string/*!*/ name, [Captured] List<TypeParameter/*!*/>/*!*/ typeArgs,
+ [Captured] List<Formal/*!*/>/*!*/ formals,
+ Attributes attributes)
+ : base(tok, name, attributes) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(cce.NonNullElements(typeArgs));
+ Contract.Requires(cce.NonNullElements(formals));
this.TypeArgs = typeArgs;
this.Formals = formals;
- base(tok, name, attributes);
+
}
-
- public string! FullName {
- get
- requires EnclosingDatatype != null;
- {
+
+ public string FullName {
+ get {
+ Contract.Requires(EnclosingDatatype != null);
+ Contract.Ensures(Contract.Result<string>() != null);
+
return "#" + EnclosingDatatype.Name + "." + Name;
}
}
}
-
+
public abstract class MemberDecl : Declaration {
public ClassDecl EnclosingClass; // filled in during resolution
-
- public MemberDecl(IToken! tok, string! name, Attributes attributes) {
- base(tok, name, attributes);
+
+ public MemberDecl(IToken tok, string name, Attributes attributes)
+ : base(tok, name, attributes) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
}
/// <summary>
/// Returns className+"."+memberName. Available only after resolution.
/// </summary>
- public string! FullName {
- get
- requires EnclosingClass != null;
- {
+ public string FullName {
+ get {
+ Contract.Requires(EnclosingClass != null);
+ Contract.Ensures(Contract.Result<string>() != null);
+
+
return EnclosingClass.Name + "." + Name;
}
}
}
-
+
public class Field : MemberDecl {
public readonly bool IsGhost;
- public readonly Type! Type;
-
- public Field(IToken! tok, string! name, bool isGhost, Type! type, Attributes attributes) {
+ public readonly Type Type;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Type != null);
+ }
+
+
+ public Field(IToken tok, string name, bool isGhost, Type type, Attributes attributes)
+ : base(tok, name, attributes) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(type != null);
IsGhost = isGhost;
Type = type;
- base(tok, name, attributes);
+
}
}
-
+
public class CouplingInvariant : MemberDecl {
- public readonly Expression! Expr;
- public readonly List<IToken!>! Toks;
- public List<Formal!> Formals; // filled in during resolution
- public List<Field!> Refined; // filled in during resolution
-
- public CouplingInvariant(List<IToken!>! toks, Expression! expr, Attributes attributes)
- requires toks.Count > 0;
- {
- Expr = expr;
+ public readonly Expression Expr;
+ public readonly List<IToken/*!*/>/*!*/ Toks;
+ public List<Formal/*!*/> Formals; // filled in during resolution
+ public List<Field/*!*/> Refined; // filled in during resolution
+
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Expr != null);
+ Contract.Invariant(cce.NonNullElements(Toks));
+ Contract.Invariant(cce.NonNullElements(Formals));
+ Contract.Invariant(cce.NonNullElements(Refined));
+ }
+
+
+ public CouplingInvariant(List<IToken/*!*/>/*!*/ toks, Expression/*!*/ expr, Attributes attributes)
+ : base(toks[0], "_coupling_invariant" + getNames(toks), attributes) {
+ Contract.Requires(toks.Count > 0);
+ Expr = expr;
Toks = toks;
+
+
+
+ }
+
+ private static string getNames(List<IToken> toks) {
+ Contract.Requires(toks != null);
+ Contract.Ensures(Contract.Result<string>() != null);
+
StringBuilder sb = new StringBuilder();
- foreach (IToken tok in toks)
+ foreach (IToken tok in toks) {
+ Contract.Assert(tok != null);
sb.Append("_").Append(tok.val);
-
- base(toks[0], "_coupling_invariant" + sb.ToString(), attributes);
+ }
+ return sb.ToString();
}
-
+
public string[] Tokens() {
string[] result = new string[Toks.Count];
for (int i = 0; i < Toks.Count; i++)
result[i] = Toks[i].val;
return result;
- }
+ }
}
-
+
+ [ContractClass(typeof(IVariableContracts))]
public interface IVariable {
- string! Name { get; }
- string! UniqueName { get; }
- Type! Type { get; }
- bool IsMutable { get; }
- bool IsGhost { get; }
+ string/*!*/ Name {
+ get;
+ }
+ string/*!*/ UniqueName {
+ get;
+ }
+ Type/*!*/ Type {
+ get;
+ }
+ bool IsMutable {
+ get;
+ }
+ bool IsGhost {
+ get;
+ }
+ }
+ [ContractClassFor(typeof(IVariable))]
+ public abstract class IVariableContracts : IVariable {
+ public string Name {
+ get {
+ Contract.Ensures(Contract.Result<string>() != null);
+ throw new NotImplementedException();
+ }
+ }
+ public string UniqueName {
+ get {
+ Contract.Ensures(Contract.Result<string>() != null);
+ throw new NotImplementedException();
+ }
+ }
+ public Type Type {
+ get {
+ Contract.Ensures(Contract.Result<Type>() != null);
+ throw new NotImplementedException();
+ }
+ }
+ public bool IsMutable {
+ get {
+ throw new NotImplementedException();
+ }
+ }
+ public bool IsGhost {
+ get {
+ throw new NotImplementedException();
+ }
+ }
+
+
+
}
-
+
public abstract class NonglobalVariable : IVariable {
- public readonly IToken! tok;
- readonly string! name;
- public string! Name { get { return name; } }
+ public readonly IToken tok;
+ readonly string name;
+
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(tok != null);
+ Contract.Invariant(name != null);
+ Contract.Invariant(type != null);
+ }
+
+ public string Name {
+ get {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return name;
+ }
+ }
readonly int varId = varIdCount++;
- public string! UniqueName { get { return name + "#" + varId; } }
- Type! type;
- [Pure(false)] // TODO: if Type gets the status of [Frozen], then this attribute is not needed
- public Type! Type { get {
- assume type.IsPeerConsistent;
- while (true)
- invariant type.IsPeerConsistent;
- {
- TypeProxy t = type as TypeProxy;
- if (t != null && t.T != null) {
- type = t.T;
- assume type.IsPeerConsistent;
- } else {
- return type;
+ public string UniqueName {
+ get {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return name + "#" + varId;
+ }
+ }
+ Type type;
+ //[Pure(false)] // TODO: if Type gets the status of [Frozen], then this attribute is not needed
+ public Type/*!*/ Type {
+ get {
+ Contract.Ensures(Contract.Result<Type>() != null);
+
+ Contract.Assume(cce.IsPeerConsistent(type));
+ while (true) {
+ cce.LoopInvariant(cce.IsPeerConsistent(type));
+
+ TypeProxy t = type as TypeProxy;
+ if (t != null && t.T != null) {
+ type = t.T;
+ Contract.Assume(cce.IsPeerConsistent(type));
+ } else {
+ return type;
+ }
}
}
- } }
- public abstract bool IsMutable { get; }
+ }
+ public abstract bool IsMutable {
+ get;
+ }
bool isGhost; // readonly, except for BoundVar's of match expressions/statements during resolution
public bool IsGhost {
- get { return isGhost; }
- set { isGhost = value; }
+ get {
+ return isGhost;
+ }
+ set {
+ isGhost = value;
+ }
}
-
- public NonglobalVariable(IToken! tok, string! name, Type! type, bool isGhost) {
+
+ public NonglobalVariable(IToken tok, string name, Type type, bool isGhost) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(type != null);
this.tok = tok;
this.name = name;
this.type = type;
this.isGhost = isGhost;
}
-
+
internal static int varIdCount; // this varIdCount is used for both NonglobalVariable's and VarDecl's.
}
-
+
public class Formal : NonglobalVariable {
public readonly bool InParam; // true to in-parameter, false for out-parameter
- public override bool IsMutable { get { return !InParam; } }
-
- public Formal(IToken! tok, string! name, Type! type, bool inParam, bool isGhost) {
+ public override bool IsMutable {
+ get {
+ return !InParam;
+ }
+ }
+
+ public Formal(IToken/*!*/ tok, string/*!*/ name, Type/*!*/ type, bool inParam, bool isGhost)
+ : base(tok, name, type, isGhost) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(type != null);
InParam = inParam;
- base(tok, name, type, isGhost);
+
}
}
-
+
public class BoundVar : NonglobalVariable {
- public override bool IsMutable { get { return false; } }
-
- public BoundVar(IToken! tok, string! name, Type! type) {
- base(tok, name, type, false);
+ public override bool IsMutable {
+ get {
+ return false;
+ }
+ }
+
+ public BoundVar(IToken/*!*/ tok, string/*!*/ name, Type/*!*/ type)
+ : base(tok, name, type, false) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(type != null);
}
}
-
+
public class Function : MemberDecl, TypeParameter.ParentType {
public readonly bool IsStatic;
public readonly bool IsGhost; // functions are "ghost" by default; a non-ghost function is called a "function method"
public readonly bool IsUnlimited;
public bool IsRecursive; // filled in during resolution
- public readonly List<TypeParameter!>! TypeArgs;
- public readonly List<Formal!>! Formals;
- public readonly Type! ResultType;
- public readonly List<Expression!>! Req;
- public readonly List<FrameExpression!>! Reads;
- public readonly List<Expression!>! Decreases;
+ public readonly List<TypeParameter/*!*/>/*!*/ TypeArgs;
+ public readonly List<Formal/*!*/>/*!*/ Formals;
+ public readonly Type/*!*/ ResultType;
+ public readonly List<Expression/*!*/>/*!*/ Req;
+ public readonly List<FrameExpression/*!*/>/*!*/ Reads;
+ public readonly List<Expression/*!*/>/*!*/ Decreases;
public readonly Expression Body; // an extended expression
-
- public Function(IToken! tok, string! name, bool isStatic, bool isGhost, bool isUnlimited, [Captured] List<TypeParameter!>! typeArgs, [Captured] List<Formal!>! formals, Type! resultType,
- List<Expression!>! req, List<FrameExpression!>! reads, List<Expression!>! decreases, Expression body, Attributes attributes) {
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(cce.NonNullElements(TypeArgs));
+ Contract.Invariant(cce.NonNullElements(Formals));
+ Contract.Invariant(ResultType != null);
+ Contract.Invariant(cce.NonNullElements(Req));
+ Contract.Invariant(cce.NonNullElements(Reads));
+ Contract.Invariant(cce.NonNullElements(Decreases));
+ }
+
+
+ public Function(IToken tok, string name, bool isStatic, bool isGhost, bool isUnlimited, [Captured] List<TypeParameter/*!*/>/*!*/ typeArgs,
+ [Captured] List<Formal/*!*/>/*!*/ formals, Type/*!*/ resultType, List<Expression/*!*/>/*!*/ req, List<FrameExpression/*!*/>/*!*/ reads,
+ List<Expression/*!*/>/*!*/ decreases, Expression body, Attributes attributes)
+ : base(tok, name, attributes) {
+
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(cce.NonNullElements(typeArgs));
+ Contract.Requires(cce.NonNullElements(formals));
+ Contract.Requires(resultType != null);
+ Contract.Requires(cce.NonNullElements(req));
+ Contract.Requires(cce.NonNullElements(reads));
+ Contract.Requires(cce.NonNullElements(decreases));
this.IsStatic = isStatic;
this.IsGhost = isGhost;
this.IsUnlimited = isUnlimited;
@@ -634,30 +988,52 @@ namespace Microsoft.Dafny
this.Reads = reads;
this.Decreases = decreases;
this.Body = body;
- base(tok, name, attributes);
+
}
}
-
+
public class Method : MemberDecl, TypeParameter.ParentType {
public readonly bool IsStatic;
public readonly bool IsGhost;
- public readonly List<TypeParameter!>! TypeArgs;
- public readonly List<Formal!>! Ins;
- public readonly List<Formal!>! Outs;
- public readonly List<MaybeFreeExpression!>! Req;
- public readonly List<FrameExpression!>! Mod;
- public readonly List<MaybeFreeExpression!>! Ens;
- public readonly List<Expression!>! Decreases;
+ public readonly List<TypeParameter/*!*/>/*!*/ TypeArgs;
+ public readonly List<Formal/*!*/>/*!*/ Ins;
+ public readonly List<Formal/*!*/>/*!*/ Outs;
+ public readonly List<MaybeFreeExpression/*!*/>/*!*/ Req;
+ public readonly List<FrameExpression/*!*/>/*!*/ Mod;
+ public readonly List<MaybeFreeExpression/*!*/>/*!*/ Ens;
+ public readonly List<Expression/*!*/>/*!*/ Decreases;
public readonly BlockStmt Body;
-
- public Method(IToken! tok, string! name,
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(cce.NonNullElements(TypeArgs));
+ Contract.Invariant(cce.NonNullElements(Ins));
+ Contract.Invariant(cce.NonNullElements(Outs));
+ Contract.Invariant(cce.NonNullElements(Req));
+ Contract.Invariant(cce.NonNullElements(Mod));
+ Contract.Invariant(cce.NonNullElements(Ens));
+ Contract.Invariant(cce.NonNullElements(Decreases));
+ }
+
+
+ public Method(IToken tok, string name,
bool isStatic, bool isGhost,
- [Captured] List<TypeParameter!>! typeArgs,
- [Captured] List<Formal!>! ins, [Captured] List<Formal!>! outs,
- [Captured] List<MaybeFreeExpression!>! req, [Captured] List<FrameExpression!>! mod, [Captured] List<MaybeFreeExpression!>! ens,
- [Captured] List<Expression!>! decreases,
+ [Captured] List<TypeParameter/*!*/>/*!*/ typeArgs,
+ [Captured] List<Formal/*!*/>/*!*/ ins, [Captured] List<Formal/*!*/>/*!*/ outs,
+ [Captured] List<MaybeFreeExpression/*!*/>/*!*/ req, [Captured] List<FrameExpression/*!*/>/*!*/ mod,
+ [Captured] List<MaybeFreeExpression/*!*/>/*!*/ ens,
+ [Captured] List<Expression/*!*/>/*!*/ decreases,
[Captured] BlockStmt body,
- Attributes attributes) {
+ Attributes attributes)
+ : base(tok, name, attributes) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(cce.NonNullElements(typeArgs));
+ Contract.Requires(cce.NonNullElements(ins));
+ Contract.Requires(cce.NonNullElements(outs));
+ Contract.Requires(cce.NonNullElements(req));
+ Contract.Requires(cce.NonNullElements(mod));
+ Contract.Requires(cce.NonNullElements(ens));
+ Contract.Requires(cce.NonNullElements(decreases));
this.IsStatic = isStatic;
this.IsGhost = isGhost;
this.TypeArgs = typeArgs;
@@ -668,90 +1044,123 @@ namespace Microsoft.Dafny
this.Ens = ens;
this.Decreases = decreases;
this.Body = body;
- base(tok, name, attributes);
+
}
}
- public class MethodRefinement : Method {
+ public class MethodRefinement : Method {
public Method Refined; // filled in during resolution
- public MethodRefinement(IToken! tok, string! name,
+ public MethodRefinement(IToken/*!*/ tok, string/*!*/ name,
bool isStatic, bool isGhost,
- [Captured] List<TypeParameter!>! typeArgs,
- [Captured] List<Formal!>! ins, [Captured] List<Formal!>! outs,
- [Captured] List<MaybeFreeExpression!>! req, [Captured] List<FrameExpression!>! mod, [Captured] List<MaybeFreeExpression!>! ens,
- [Captured] List<Expression!>! decreases,
+ [Captured] List<TypeParameter/*!*/>/*!*/ typeArgs,
+ [Captured] List<Formal/*!*/>/*!*/ ins, [Captured] List<Formal/*!*/>/*!*/ outs,
+ [Captured] List<MaybeFreeExpression/*!*/>/*!*/ req, [Captured] List<FrameExpression/*!*/>/*!*/ mod,
+ [Captured] List<MaybeFreeExpression/*!*/>/*!*/ ens,
+ [Captured] List<Expression/*!*/>/*!*/ decreases,
[Captured] BlockStmt body,
- Attributes attributes) {
- base(tok, name, isStatic, isGhost, typeArgs, ins, outs, req, mod, ens, decreases, body, attributes);
+ Attributes attributes)
+ : base(tok, name, isStatic, isGhost, typeArgs, ins, outs, req, mod, ens, decreases, body, attributes) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(cce.NonNullElements(typeArgs));
+ Contract.Requires(cce.NonNullElements(ins));
+ Contract.Requires(cce.NonNullElements(outs));
+ Contract.Requires(cce.NonNullElements(req));
+ Contract.Requires(cce.NonNullElements(mod));
+ Contract.Requires(cce.NonNullElements(ens));
+ Contract.Requires(cce.NonNullElements(decreases));
+
}
}
-
+
// ------------------------------------------------------------------------------------------------------
-
+
public abstract class Statement {
- public readonly IToken! Tok;
+ public readonly IToken Tok;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Tok != null);
+ }
+
public bool IsGhost; // filled in by resolution
- public Statement(IToken! tok) {
+ public Statement(IToken tok) {
+ Contract.Requires(tok != null);
this.Tok = tok;
}
}
-
+
public abstract class PredicateStmt : Statement {
- [Peer] public readonly Expression! Expr;
+ [Peer]
+ public readonly Expression Expr;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Expr != null);
+ }
+
[Captured]
- public PredicateStmt(IToken! tok, Expression! expr)
- ensures Owner.Same(this, expr);
- {
- base(tok);
- Owner.AssignSame(this, expr);
+ public PredicateStmt(IToken tok, Expression expr)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(expr != null);
+ Contract.Ensures(cce.Owner.Same(this, expr));
+ cce.Owner.AssignSame(this, expr);
this.Expr = expr;
}
}
-
+
public class AssertStmt : PredicateStmt {
[Captured]
- public AssertStmt(IToken! tok, Expression! expr)
- ensures Owner.Same(this, expr);
- {
- base(tok, expr);
+ public AssertStmt(IToken/*!*/ tok, Expression/*!*/ expr)
+ : base(tok, expr) {
+ Contract.Requires(tok != null);
+ Contract.Requires(expr != null);
+ Contract.Ensures(cce.Owner.Same(this, expr));
+
}
}
-
+
public class AssumeStmt : PredicateStmt {
[Captured]
- public AssumeStmt(IToken! tok, Expression! expr)
- ensures Owner.Same(this, expr);
- {
- base(tok, expr);
+ public AssumeStmt(IToken/*!*/ tok, Expression/*!*/ expr)
+ : base(tok, expr) {
+ Contract.Requires(tok != null);
+ Contract.Requires(expr != null);
+ Contract.Ensures(cce.Owner.Same(this, expr));
+
}
}
-
+
public class UseStmt : PredicateStmt {
[Captured]
- public UseStmt(IToken! tok, Expression! expr)
- ensures Owner.Same(this, expr);
- {
- base(tok, expr);
+ public UseStmt(IToken/*!*/ tok, Expression/*!*/ expr)
+ : base(tok, expr) {
+ Contract.Requires(tok != null);
+ Contract.Requires(expr != null);
+ Contract.Ensures(cce.Owner.Same(this, expr));
+
}
- [Peer] private FunctionCallExpr fce;
+ [Peer]
+ private FunctionCallExpr fce;
/// <summary>
/// This method assumes the statement has been successfully resolved.
/// </summary>
- [Pure(false)]
- public FunctionCallExpr! FunctionCallExpr {
+ //[Pure(false)]
+ public FunctionCallExpr FunctionCallExpr {
get {
+ Contract.Ensures(Contract.Result<FunctionCallExpr>() != null);
+
if (fce == null) {
Expression expr = Expr;
- while (true)
- invariant Owner.Same(this, expr);
- {
+ while (true) {
+ cce.LoopInvariant(cce.Owner.Same(this, expr));
+
if (expr is OldExpr) {
expr = ((OldExpr)expr).E;
} else {
break;
}
}
- assume expr is FunctionCallExpr;
+ Contract.Assume(expr is FunctionCallExpr);
fce = (FunctionCallExpr)expr;
}
return fce;
@@ -763,141 +1172,228 @@ namespace Microsoft.Dafny
}
}
}
-
+
public class PrintStmt : Statement {
- public readonly List<Attributes.Argument!>! Args;
- public PrintStmt(IToken! tok, List<Attributes.Argument!>! args)
- {
- base(tok);
+ public readonly List<Attributes.Argument/*!*/>/*!*/ Args;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(cce.NonNullElements(Args));
+ }
+
+ public PrintStmt(IToken tok, List<Attributes.Argument/*!*/>/*!*/ args)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(cce.NonNullElements(args));
+
Args = args;
}
}
-
+
public class LabelStmt : Statement {
- public readonly string! Label;
- public LabelStmt(IToken! tok, string! label) {
+ public readonly string Label;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Label != null);
+ }
+
+ public LabelStmt(IToken/*!*/ tok, string/*!*/ label)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(label != null);
this.Label = label;
- base(tok);
+
}
}
-
+
public class BreakStmt : Statement {
public readonly string TargetLabel;
public Statement TargetStmt; // filled in during resolution
-
- public BreakStmt(IToken! tok, string targetLabel) {
+
+ public BreakStmt(IToken tok, string targetLabel)
+ : base(tok) {
+ Contract.Requires(tok != null);
this.TargetLabel = targetLabel;
- base(tok);
+
}
}
-
+
public class ReturnStmt : Statement {
- public ReturnStmt(IToken! tok) {
- base(tok);
+ public ReturnStmt(IToken tok)
+ : base(tok) {
+ Contract.Requires(tok != null);
+
}
}
-
+
public abstract class AssignmentRhs {
- internal AssignmentRhs() { }
+ internal AssignmentRhs() {
+ }
}
-
+
public abstract class DeterminedAssignmentRhs : AssignmentRhs {
- internal DeterminedAssignmentRhs() { }
+ internal DeterminedAssignmentRhs() {
+ }
}
-
+
public class ExprRhs : DeterminedAssignmentRhs {
- public readonly Expression! Expr;
- public ExprRhs(Expression! expr) {
+ public readonly Expression Expr;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Expr != null);
+ }
+
+ public ExprRhs(Expression expr) {
+ Contract.Requires(expr != null);
Expr = expr;
}
}
-
+
public class TypeRhs : DeterminedAssignmentRhs {
- public readonly Type! EType;
+ public readonly Type EType;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(EType != null);
+ }
+
public readonly Expression ArraySize;
- public TypeRhs(Type! type) {
+ public TypeRhs(Type type) {
+ Contract.Requires(type != null);
EType = type;
}
- public TypeRhs(Type! type, Expression! arraySize) {
+ public TypeRhs(Type type, Expression arraySize) {
+ Contract.Requires(type != null);
+ Contract.Requires(arraySize != null);
EType = type;
ArraySize = arraySize;
}
}
-
+
public class HavocRhs : AssignmentRhs {
}
public class AssignStmt : Statement {
- public readonly Expression! Lhs;
- public readonly AssignmentRhs! Rhs;
- public AssignStmt(IToken! tok, Expression! lhs, Expression! rhs) { // ordinary assignment statement
+ public readonly Expression/*!*/ Lhs;
+ public readonly AssignmentRhs/*!*/ Rhs;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Lhs != null);
+ Contract.Invariant(Rhs != null);
+
+ }
+
+ public AssignStmt(IToken tok, Expression lhs, Expression rhs)
+ : base(tok) { // ordinary assignment statement
+ Contract.Requires(tok != null);
+ Contract.Requires(lhs != null);
+ Contract.Requires(rhs != null);
this.Lhs = lhs;
this.Rhs = new ExprRhs(rhs);
- base(tok);
+
}
- public AssignStmt(IToken! tok, Expression! lhs, Type! type) { // alloc statement
+ public AssignStmt(IToken tok, Expression lhs, Type type)
+ : base(tok) { // alloc statement
+ Contract.Requires(tok != null);
+ Contract.Requires(lhs != null);
+ Contract.Requires(type != null);
this.Lhs = lhs;
this.Rhs = new TypeRhs(type);
- base(tok);
+
}
- public AssignStmt(IToken! tok, Expression! lhs, Type! type, Expression! arraySize) { // array alloc statement
+ public AssignStmt(IToken tok, Expression lhs, Type type, Expression arraySize)
+ : base(tok) { // array alloc statement
+ Contract.Requires(tok != null);
+ Contract.Requires(lhs != null);
+ Contract.Requires(type != null);
+ Contract.Requires(arraySize != null);
this.Lhs = lhs;
this.Rhs = new TypeRhs(type, arraySize);
- base(tok);
}
- public AssignStmt(IToken! tok, Expression! lhs) { // havoc
+ public AssignStmt(IToken tok, Expression lhs)
+ : base(tok) { // havoc
+ Contract.Requires(tok != null);
+ Contract.Requires(lhs != null);
this.Lhs = lhs;
this.Rhs = new HavocRhs();
- base(tok);
}
}
-
+
public class VarDecl : Statement, IVariable {
- readonly string! name;
- public string! Name { get { return name; } }
+ readonly string/*!*/ name;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(name != null);
+ Contract.Invariant(OptionalType != null || Rhs != null);
+ }
+
+ public string/*!*/ Name {
+ get {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return name;
+ }
+ }
readonly int varId = NonglobalVariable.varIdCount++;
- public string! UniqueName { get { return name + "#" + varId; } }
+ public string/*!*/ UniqueName {
+ get {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return name + "#" + varId;
+ }
+ }
public readonly Type OptionalType; // this is the type mentioned in the declaration, if any
internal Type type; // this is the declared or inferred type of the variable; it is non-null after resolution (even if resolution fails)
- [Pure(false)]
- public Type! Type { get {
- assume type != null; /* we assume object has been resolved */
- assume type.IsPeerConsistent;
- while (true)
- invariant type != null && type.IsPeerConsistent;
- {
- TypeProxy t = type as TypeProxy;
- if (t != null && t.T != null) {
- type = t.T;
- assume type.IsPeerConsistent;
- } else {
- return type;
+ //[Pure(false)]
+ public Type Type {
+ get {
+ Contract.Ensures(Contract.Result<Type>() != null);
+
+ Contract.Assume(type != null); /* we assume object has been resolved */
+ Contract.Assume(cce.IsPeerConsistent(type));
+ while (true) {
+ cce.LoopInvariant(type != null && cce.IsPeerConsistent(type));
+ TypeProxy t = type as TypeProxy;
+ if (t != null && t.T != null) {
+ type = t.T;
+ Contract.Assume(cce.IsPeerConsistent(type));
+ } else {
+ return type;
+ }
}
}
- } }
- public bool IsMutable { get { return true; } }
- bool IVariable.IsGhost { get { return base.IsGhost; } }
+ }
+ public bool IsMutable {
+ get {
+ return true;
+ }
+ }
+ bool IVariable.IsGhost {
+ get {
+ return base.IsGhost;
+ }
+ }
public readonly DeterminedAssignmentRhs Rhs;
- invariant OptionalType != null || Rhs != null;
-
- public VarDecl(IToken! tok, string! name, Type type, bool isGhost, DeterminedAssignmentRhs rhs)
- requires type != null || rhs != null;
- {
+
+ public VarDecl(IToken tok, string name, Type type, bool isGhost, DeterminedAssignmentRhs rhs)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(type != null || rhs != null);
+
this.name = name;
this.OptionalType = type;
this.IsGhost = isGhost;
this.Rhs = rhs;
- base(tok);
+
}
}
-
+
public class AutoVarDecl : VarDecl {
public readonly int Index;
- public AutoVarDecl(IToken! tok, string! name, Type! type, int index)
- {
+ public AutoVarDecl(IToken tok, string name, Type type, int index)
+ : base(tok, name, type, false, null) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
Index = index;
- base(tok, name, type, false, null);
+
}
/// <summary>
/// This method retrospectively makes the VarDecl a ghost. It is to be used only during resolution.
@@ -906,137 +1402,221 @@ namespace Microsoft.Dafny
base.IsGhost = true;
}
}
-
+
public class CallStmt : Statement {
- public readonly List<AutoVarDecl!>! NewVars;
- public readonly List<IdentifierExpr!>! Lhs;
- public readonly Expression! Receiver;
- public readonly string! MethodName;
- public readonly List<Expression!>! Args;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Receiver != null);
+ Contract.Invariant(MethodName != null);
+ Contract.Invariant(cce.NonNullElements(NewVars));
+ Contract.Invariant(cce.NonNullElements(Lhs));
+ Contract.Invariant(cce.NonNullElements(Args));
+ }
+
+ public readonly List<AutoVarDecl/*!*/>/*!*/ NewVars;
+ public readonly List<IdentifierExpr/*!*/>/*!*/ Lhs;
+ public readonly Expression/*!*/ Receiver;
+ public readonly string/*!*/ MethodName;
+ public readonly List<Expression/*!*/>/*!*/ Args;
public Method Method; // filled in by resolution
-
- public CallStmt(IToken! tok, List<AutoVarDecl!>! newVars, List<IdentifierExpr!>! lhs, Expression! receiver, string! methodName, List<Expression!>! args) {
+
+ public CallStmt(IToken tok, List<AutoVarDecl/*!*/>/*!*/ newVars, List<IdentifierExpr/*!*/>/*!*/ lhs, Expression/*!*/ receiver,
+ string/*!*/ methodName, List<Expression/*!*/>/*!*/ args)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(cce.NonNullElements(newVars));
+ Contract.Requires(cce.NonNullElements(lhs));
+ Contract.Requires(receiver != null);
+ Contract.Requires(methodName != null);
+ Contract.Requires(cce.NonNullElements(args));
+
this.NewVars = newVars;
this.Lhs = lhs;
this.Receiver = receiver;
this.MethodName = methodName;
this.Args = args;
- base(tok);
+
}
}
-
+
public class BlockStmt : Statement {
- public readonly List<Statement!>! Body;
- public BlockStmt(IToken! tok, [Captured] List<Statement!>! body) {
+ public readonly List<Statement/*!*/>/*!*/ Body;
+ public BlockStmt(IToken/*!*/ tok, [Captured] List<Statement/*!*/>/*!*/ body)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(cce.NonNullElements(body));
this.Body = body;
- base(tok);
+
}
}
-
+
public class IfStmt : Statement {
public readonly Expression Guard;
- public readonly Statement! Thn;
+ public readonly Statement Thn;
public readonly Statement Els;
- invariant Els == null || Els is BlockStmt || Els is IfStmt;
-
- public IfStmt(IToken! tok, Expression guard, Statement! thn, Statement els)
- requires els == null || els is BlockStmt || els is IfStmt;
- {
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Thn != null);
+
+
+ Contract.Invariant(Els == null || Els is BlockStmt || Els is IfStmt);
+ }
+ public IfStmt(IToken tok, Expression guard, Statement thn, Statement els)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(guard != null);
+ Contract.Requires(thn != null);
+ Contract.Requires(els == null || els is BlockStmt || els is IfStmt);
this.Guard = guard;
this.Thn = thn;
this.Els = els;
- base(tok);
+
}
}
public class WhileStmt : Statement {
public readonly Expression Guard;
- public readonly List<MaybeFreeExpression!>! Invariants;
- public readonly List<Expression!>! Decreases;
- public readonly Statement! Body;
-
- public WhileStmt(IToken! tok, Expression guard,
- List<MaybeFreeExpression!>! invariants, List<Expression!>! decreases,
- Statement! body) {
+ public readonly List<MaybeFreeExpression/*!*/>/*!*/ Invariants;
+ public readonly List<Expression/*!*/>/*!*/ Decreases;
+ public readonly Statement/*!*/ Body;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Body != null);
+ Contract.Invariant(cce.NonNullElements(Invariants));
+ Contract.Invariant(cce.NonNullElements(Decreases));
+ }
+
+
+ public WhileStmt(IToken tok, Expression guard,
+ List<MaybeFreeExpression/*!*/>/*!*/ invariants, List<Expression/*!*/>/*!*/ decreases,
+ Statement/*!*/ body)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(body != null);
+ Contract.Requires(cce.NonNullElements(invariants));
+ Contract.Requires(cce.NonNullElements(decreases));
this.Guard = guard;
this.Invariants = invariants;
this.Decreases = decreases;
this.Body = body;
- base(tok);
+
}
}
-
+
public class ForeachStmt : Statement {
- public readonly BoundVar! BoundVar;
- public readonly Expression! Collection;
- public readonly Expression! Range;
- public readonly List<PredicateStmt!>! BodyPrefix;
- public readonly AssignStmt! BodyAssign;
-
- public ForeachStmt(IToken! tok, BoundVar! boundVar, Expression! collection, Expression! range, List<PredicateStmt!>! bodyPrefix, AssignStmt! bodyAssign) {
+ public readonly BoundVar/*!*/ BoundVar;
+ public readonly Expression/*!*/ Collection;
+ public readonly Expression/*!*/ Range;
+ public readonly List<PredicateStmt/*!*/>/*!*/ BodyPrefix;
+ public readonly AssignStmt/*!*/ BodyAssign;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(BoundVar != null);
+ Contract.Invariant(Collection != null);
+ Contract.Invariant(Range != null);
+ Contract.Invariant(cce.NonNullElements(BodyPrefix));
+ Contract.Invariant(BodyAssign != null);
+ }
+
+
+ public ForeachStmt(IToken tok, BoundVar boundVar, Expression collection, Expression range,
+ List<PredicateStmt/*!*/>/*!*/ bodyPrefix, AssignStmt bodyAssign)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(boundVar != null);
+ Contract.Requires(collection != null);
+ Contract.Requires(range != null);
+ Contract.Requires(cce.NonNullElements(bodyPrefix));
+ Contract.Requires(bodyAssign != null);
this.BoundVar = boundVar;
this.Collection = collection;
this.Range = range;
this.BodyPrefix = bodyPrefix;
this.BodyAssign = bodyAssign;
- base(tok);
+
}
}
-
+
class MatchStmt : Statement {
- public readonly Expression! Source;
- public readonly List<MatchCaseStmt!>! Cases;
-
- public MatchStmt(IToken! tok, Expression! source, [Captured] List<MatchCaseStmt!>! cases) {
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Source != null);
+ Contract.Invariant(cce.NonNullElements(Cases));
+ }
+
+ public readonly Expression Source;
+ public readonly List<MatchCaseStmt/*!*/>/*!*/ Cases;
+
+ public MatchStmt(IToken tok, Expression source, [Captured] List<MatchCaseStmt/*!*/>/*!*/ cases)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(source != null);
+ Contract.Requires(cce.NonNullElements(cases));
this.Source = source;
this.Cases = cases;
- base(tok);
+
}
}
-
+
public class MatchCaseStmt {
- public readonly IToken! tok;
- public readonly string! Id;
+ public readonly IToken tok;
+ public readonly string Id;
public DatatypeCtor Ctor; // filled in by resolution
- public readonly List<BoundVar!>! Arguments;
- public readonly List<Statement!>! Body;
-
- public MatchCaseStmt(IToken! tok, string! id, [Captured] List<BoundVar!>! arguments, [Captured] List<Statement!>! body) {
+ public readonly List<BoundVar/*!*/>/*!*/ Arguments;
+ public readonly List<Statement/*!*/>/*!*/ Body;
+
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(tok != null);
+ Contract.Invariant(Id != null);
+ Contract.Invariant(cce.NonNullElements(Arguments));
+ Contract.Invariant(cce.NonNullElements(Body));
+ }
+
+
+ public MatchCaseStmt(IToken tok, string id, [Captured] List<BoundVar/*!*/>/*!*/ arguments, [Captured] List<Statement/*!*/>/*!*/ body) {
+ Contract.Requires(tok != null);
+ Contract.Requires(id != null);
+ Contract.Requires(cce.NonNullElements(arguments));
+ Contract.Requires(cce.NonNullElements(body));
this.tok = tok;
this.Id = id;
this.Arguments = arguments;
this.Body = body;
}
}
-
+
// ------------------------------------------------------------------------------------------------------
-
+
public abstract class Expression {
- public readonly IToken! tok;
+ public readonly IToken tok;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(tok != null);
+ }
+
protected Type type;
public Type Type { // filled in during resolution
[Verify(false)] // TODO: how do we allow Type.get to modify type and still be [Pure]?
[Additive] // validity of proper subclasses is not required
- get
- ensures type == null ==> result == null; // useful in conjunction with postcondition of constructor
- {
+ get {
+ Contract.Ensures(type != null || Contract.Result<Type>() == null); // useful in conjunction with postcondition of constructor
while (true) {
TypeProxy t = type as TypeProxy;
if (t != null && t.T != null) {
type = t.T;
} else {
- assume type == null || type.IsPeerConsistent;
+ Contract.Assume(type == null || cce.IsPeerConsistent(type));
return type;
}
}
}
[NoDefaultContract] // no particular validity of 'this' is required, except that it not be committed
- set
- requires this.IsValid;
- requires Type == null; // set it only once
- requires value != null && value.IsPeerConsistent;
- modifies type;
- {
+ set {
+ Contract.Requires(cce.IsValid(this));
+ Contract.Requires(Type == null); // set it only once
+ Contract.Requires(value != null && cce.IsPeerConsistent(value));
+ //modifies type;
type = value;
while (true) {
TypeProxy t = type as TypeProxy;
@@ -1048,18 +1628,20 @@ namespace Microsoft.Dafny
}
}
}
-
- public Expression(IToken! tok)
- ensures type == null; // we would have liked to have written Type==null, but that's not admissible or provable
- {
+
+ public Expression(IToken tok) {
+ Contract.Requires(tok != null);
+ Contract.Ensures(type == null); // we would have liked to have written Type==null, but that's not admissible or provable
+
this.tok = tok;
}
}
-
+
public class LiteralExpr : Expression {
public readonly object Value;
-
- public static bool IsTrue(Expression! e) {
+
+ public static bool IsTrue(Expression e) {
+ Contract.Requires(e != null);
if (e is LiteralExpr) {
LiteralExpr le = (LiteralExpr)e;
return le.Value is bool && (bool)le.Value;
@@ -1067,369 +1649,648 @@ namespace Microsoft.Dafny
return false;
}
}
-
- public LiteralExpr(IToken! tok) { // represents the Dafny literal "null"
+
+ public LiteralExpr(IToken tok)
+ : base(tok) { // represents the Dafny literal "null"
+ Contract.Requires(tok != null);
this.Value = null;
- base(tok);
+
}
-
- public LiteralExpr(IToken! tok, BigInteger n)
- requires 0 <= n.Sign;
- {
+
+ public LiteralExpr(IToken tok, BigInteger n)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(0 <= n.Sign);
+
this.Value = n;
- base(tok);
+
}
-
- public LiteralExpr(IToken! tok, int n)
- requires 0 <= n;
- {
- this(tok, new BigInteger(n));
+
+ public LiteralExpr(IToken tok, int n) :base(tok){
+ Contract.Requires(tok != null);
+ Contract.Requires(0 <= n);
+
+ this.Value = new BigInteger(n);
}
-
- public LiteralExpr(IToken! tok, bool b) {
+
+ public LiteralExpr(IToken tok, bool b)
+ : base(tok) {
+ Contract.Requires(tok != null);
this.Value = b;
- base(tok);
+
}
}
-
+
public class DatatypeValue : Expression {
- public readonly string! DatatypeName;
- public readonly string! MemberName;
- public readonly List<Expression!>! Arguments;
+ public readonly string DatatypeName;
+ public readonly string MemberName;
+ public readonly List<Expression/*!*/>/*!*/ Arguments;
public DatatypeCtor Ctor; // filled in by resolution
- public List<Type!>! InferredTypeArgs = new List<Type!>(); // filled in by resolution
-
- public DatatypeValue(IToken! tok, string! datatypeName, string! memberName, [Captured] List<Expression!>! arguments) {
+ public List<Type/*!*/> InferredTypeArgs = new List<Type>(); // filled in by resolution
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(DatatypeName != null);
+ Contract.Invariant(MemberName != null);
+ Contract.Invariant(cce.NonNullElements(Arguments));
+ Contract.Invariant(cce.NonNullElements(InferredTypeArgs));
+ }
+
+
+ public DatatypeValue(IToken tok, string datatypeName, string memberName, [Captured] List<Expression/*!*/>/*!*/ arguments)
+ : base(tok) {
+ Contract.Requires(cce.NonNullElements(arguments));
+ Contract.Requires(tok != null);
+ Contract.Requires(datatypeName != null);
+ Contract.Requires(memberName != null);
this.DatatypeName = datatypeName;
this.MemberName = memberName;
this.Arguments = arguments;
- base(tok);
+
}
}
-
+
public class ThisExpr : Expression {
- public ThisExpr(IToken! tok) {
- base(tok);
+ public ThisExpr(IToken tok)
+ : base(tok) {
+ Contract.Requires(tok != null);
}
}
-
+
public class ImplicitThisExpr : ThisExpr {
- public ImplicitThisExpr(IToken! tok) {
- base(tok);
+ public ImplicitThisExpr(IToken tok)
+ : base(tok) {
+ Contract.Requires(tok != null);
}
}
-
+
public class IdentifierExpr : Expression {
- public readonly string! Name;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Name != null);
+ }
+
+ public readonly string Name;
public IVariable Var; // filled in by resolution
- public IdentifierExpr(IToken! tok, string! name) {
+ public IdentifierExpr(IToken tok, string name)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
Name = name;
- base(tok);
+
+
}
}
public abstract class DisplayExpression : Expression {
- public readonly List<Expression!>! Elements;
- public DisplayExpression(IToken! tok, List<Expression!>! elements) {
+ public readonly List<Expression/*!*/>/*!*/ Elements;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(cce.NonNullElements(Elements));
+ }
+
+ public DisplayExpression(IToken tok, List<Expression/*!*/>/*!*/ elements)
+ : base(tok) {
+ Contract.Requires(cce.NonNullElements(elements));
Elements = elements;
- base(tok);
+
}
}
-
+
public class SetDisplayExpr : DisplayExpression {
- public SetDisplayExpr(IToken! tok, List<Expression!>! elements) {
- base(tok, elements);
+ public SetDisplayExpr(IToken tok, List<Expression/*!*/>/*!*/ elements)
+ : base(tok, elements) {
+ Contract.Requires(tok != null);
+ Contract.Requires(cce.NonNullElements(elements));
}
}
-
+
public class SeqDisplayExpr : DisplayExpression {
- public SeqDisplayExpr(IToken! tok, List<Expression!>! elements) {
- base(tok, elements);
+ public SeqDisplayExpr(IToken tok, List<Expression/*!*/>/*!*/ elements)
+ : base(tok, elements) {
+ Contract.Requires(cce.NonNullElements(elements));
+ Contract.Requires(tok != null);
}
}
-
+
public class FieldSelectExpr : Expression {
- public readonly Expression! Obj;
- public readonly string! FieldName;
+ public readonly Expression Obj;
+ public readonly string FieldName;
public Field Field; // filled in by resolution
-
- public FieldSelectExpr(IToken! tok, Expression! obj, string! fieldName) {
+
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Obj != null);
+ Contract.Invariant(FieldName != null);
+ }
+
+
+ public FieldSelectExpr(IToken tok, Expression obj, string fieldName)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(obj != null);
+ Contract.Requires(fieldName != null);
this.Obj = obj;
this.FieldName = fieldName;
- base(tok);
+
}
}
-
+
public class SeqSelectExpr : Expression {
public readonly bool SelectOne; // false means select a range
- public readonly Expression! Seq;
+ public readonly Expression Seq;
public readonly Expression E0;
public readonly Expression E1;
- invariant SelectOne ==> E1 == null;
- invariant E0 != null || E1 != null;
-
- public SeqSelectExpr(IToken! tok, bool selectOne, Expression! seq, Expression e0, Expression e1)
- requires selectOne ==> e1 == null;
- requires e0 != null || e1 != null;
- {
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Seq != null);
+ Contract.Invariant(!SelectOne || E1 == null);
+ Contract.Invariant(E0 != null || E1 != null);
+ }
+
+
+
+ public SeqSelectExpr(IToken tok, bool selectOne, Expression seq, Expression e0, Expression e1)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(seq != null);
+ Contract.Requires(!selectOne || e1 == null);
+ Contract.Requires(e0 != null || e1 != null);
+
SelectOne = selectOne;
Seq = seq;
E0 = e0;
E1 = e1;
- base(tok);
+
}
}
public class SeqUpdateExpr : Expression {
- public readonly Expression! Seq;
- public readonly Expression! Index;
- public readonly Expression! Value;
-
- public SeqUpdateExpr(IToken! tok, Expression! seq, Expression! index, Expression! val)
- {
+ public readonly Expression Seq;
+ public readonly Expression Index;
+ public readonly Expression Value;
+
+ public SeqUpdateExpr(IToken tok, Expression seq, Expression index, Expression val)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(seq != null);
+ Contract.Requires(index != null);
+ Contract.Requires(val != null);
Seq = seq;
Index = index;
Value = val;
- base(tok);
+
}
}
public class FunctionCallExpr : Expression {
- public readonly string! Name;
- [Peer] public readonly Expression! Receiver;
- [Peer] public readonly List<Expression!>! Args;
+ public readonly string/*!*/ Name;
+ [Peer]
+ public readonly Expression/*!*/ Receiver;
+ [Peer]
+ public readonly List<Expression/*!*/>/*!*/ Args;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Name != null);
+ Contract.Invariant(Receiver != null);
+ Contract.Invariant(cce.NonNullElements(Args));
+ }
+
public Function Function; // filled in by resolution
-
+
[Captured]
- public FunctionCallExpr(IToken! tok, string! fn, Expression! receiver, [Captured] List<Expression!>! args)
- ensures type == null;
- ensures Owner.Same(this, receiver);
- {
- base(tok);
+ public FunctionCallExpr(IToken tok, string fn, Expression receiver, [Captured] List<Expression/*!*/>/*!*/ args)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(fn != null);
+ Contract.Requires(receiver != null);
+ Contract.Requires(cce.NonNullElements(args));
+ Contract.Ensures(type == null);
+ Contract.Ensures(cce.Owner.Same(this, receiver));
+
+
this.Name = fn;
- Owner.AssignSame(this, receiver);
+ cce.Owner.AssignSame(this, receiver);
this.Receiver = receiver;
this.Args = args;
}
}
-
+
public class OldExpr : Expression {
- [Peer] public readonly Expression! E;
+ [Peer]
+ public readonly Expression E;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(E != null);
+ }
+
[Captured]
- public OldExpr(IToken! tok, Expression! expr) {
- base(tok);
- Owner.AssignSame(this, expr);
+ public OldExpr(IToken tok, Expression expr)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(expr != null);
+ cce.Owner.AssignSame(this, expr);
E = expr;
}
}
public class FreshExpr : Expression {
- public readonly Expression! E;
- public FreshExpr(IToken! tok, Expression! expr) {
+ public readonly Expression E;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(E != null);
+ }
+
+ public FreshExpr(IToken tok, Expression expr)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(expr != null);
E = expr;
- base(tok);
+
}
}
-
+
public class UnaryExpr : Expression {
- public enum Opcode { Not, SeqLength }
+ public enum Opcode {
+ Not,
+ SeqLength
+ }
public readonly Opcode Op;
- public readonly Expression! E;
-
- public UnaryExpr(IToken! tok, Opcode op, Expression! e) {
+ public readonly Expression E;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(E != null);
+ }
+
+
+ public UnaryExpr(IToken tok, Opcode op, Expression e)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(e != null);
this.Op = op;
this.E = e;
- base(tok);
+
}
}
-
+
public class BinaryExpr : Expression {
- public enum Opcode { Iff, Imp, And, Or,
- Eq, Neq, Lt, Le, Ge, Gt,
- Disjoint, In, NotIn,
- Add, Sub, Mul, Div, Mod }
+ public enum Opcode {
+ Iff,
+ Imp,
+ And,
+ Or,
+ Eq,
+ Neq,
+ Lt,
+ Le,
+ Ge,
+ Gt,
+ Disjoint,
+ In,
+ NotIn,
+ Add,
+ Sub,
+ Mul,
+ Div,
+ Mod
+ }
public readonly Opcode Op;
public enum ResolvedOpcode {
// logical operators
- Iff, Imp, And, Or,
+ Iff,
+ Imp,
+ And,
+ Or,
// non-collection types
- EqCommon, NeqCommon,
+ EqCommon,
+ NeqCommon,
// integers
- Lt, Le, Ge, Gt, Add, Sub, Mul, Div, Mod,
+ Lt,
+ Le,
+ Ge,
+ Gt,
+ Add,
+ Sub,
+ Mul,
+ Div,
+ Mod,
// sets
- SetEq, SetNeq, ProperSubset, Subset, Superset, ProperSuperset, Disjoint, InSet, NotInSet,
- Union, Intersection, SetDifference,
+ SetEq,
+ SetNeq,
+ ProperSubset,
+ Subset,
+ Superset,
+ ProperSuperset,
+ Disjoint,
+ InSet,
+ NotInSet,
+ Union,
+ Intersection,
+ SetDifference,
// sequences
- SeqEq, SeqNeq, ProperPrefix, Prefix, Concat, InSeq, NotInSeq,
+ SeqEq,
+ SeqNeq,
+ ProperPrefix,
+ Prefix,
+ Concat,
+ InSeq,
+ NotInSeq,
// datatypes
- RankLt, RankGt
+ RankLt,
+ RankGt
}
public ResolvedOpcode ResolvedOp; // filled in by resolution
-
- public static string! OpcodeString(Opcode op) {
+
+ public static string OpcodeString(Opcode op) {
+ Contract.Ensures(Contract.Result<string>() != null);
+
switch (op) {
- case Opcode.Iff: return "<==>";
- case Opcode.Imp: return "==>";
- case Opcode.And: return "&&";
- case Opcode.Or: return "||";
- case Opcode.Eq: return "==";
- case Opcode.Lt: return "<";
- case Opcode.Gt: return ">";
- case Opcode.Le: return "<=";
- case Opcode.Ge: return ">=";
- case Opcode.Neq: return "!=";
- case Opcode.Disjoint: return "!!";
- case Opcode.In: return "in";
- case Opcode.NotIn: return "!in";
- case Opcode.Add: return "+";
- case Opcode.Sub: return "-";
- case Opcode.Mul: return "*";
- case Opcode.Div: return "/";
- case Opcode.Mod: return "%";
+ case Opcode.Iff:
+ return "==";
+ case Opcode.Imp:
+ return "==>";
+ case Opcode.And:
+ return "&&";
+ case Opcode.Or:
+ return "||";
+ case Opcode.Eq:
+ return "==";
+ case Opcode.Lt:
+ return "<";
+ case Opcode.Gt:
+ return ">";
+ case Opcode.Le:
+ return "<=";
+ case Opcode.Ge:
+ return ">=";
+ case Opcode.Neq:
+ return "!=";
+ case Opcode.Disjoint:
+ return "!!";
+ case Opcode.In:
+ return "in";
+ case Opcode.NotIn:
+ return "!in";
+ case Opcode.Add:
+ return "+";
+ case Opcode.Sub:
+ return "-";
+ case Opcode.Mul:
+ return "*";
+ case Opcode.Div:
+ return "/";
+ case Opcode.Mod:
+ return "%";
default:
- assert false; // unexpected operator
+ Contract.Assert(false);
+ throw new cce.UnreachableException(); // unexpected operator
}
}
- public readonly Expression! E0;
- public readonly Expression! E1;
-
- public BinaryExpr(IToken! tok, Opcode op, Expression! e0, Expression! e1) {
+ public readonly Expression E0;
+ public readonly Expression E1;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(E0 != null);
+ Contract.Invariant(E1 != null);
+ }
+
+
+ public BinaryExpr(IToken tok, Opcode op, Expression e0, Expression e1)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(e0 != null);
+ Contract.Requires(e1 != null);
this.Op = op;
this.E0 = e0;
this.E1 = e1;
- base(tok);
+
}
}
-
+
public abstract class QuantifierExpr : Expression {
- public readonly List<BoundVar!>! BoundVars;
- public readonly Expression! Body;
+ public readonly List<BoundVar/*!*/>/*!*/ BoundVars;
+ public readonly Expression/*!*/ Body;
+
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(BoundVars != null);
+ Contract.Invariant(Body != null);
+ }
+
+
public readonly Triggers Trigs;
public readonly Attributes Attributes;
-
- public QuantifierExpr(IToken! tok, List<BoundVar!>! bvars, Expression! body, Triggers trigs, Attributes attrs) {
+
+ public QuantifierExpr(IToken/*!*/ tok, List<BoundVar/*!*/>/*!*/ bvars, Expression/*!*/ body, Triggers trigs, Attributes attrs)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(cce.NonNullElements(bvars));
+ Contract.Requires(body != null);
+
this.BoundVars = bvars;
this.Body = body;
this.Trigs = trigs;
this.Attributes = attrs;
- base(tok);
+
}
}
-
+
public class Triggers {
- public readonly List<Expression!>! Terms;
+ public readonly List<Expression/*!*/>/*!*/ Terms;
public readonly Triggers Prev;
-
- public Triggers(List<Expression!>! terms, Triggers prev) {
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(cce.NonNullElements(Terms));
+ }
+
+ public Triggers(List<Expression/*!*/>/*!*/ terms, Triggers prev) {
+ Contract.Requires(cce.NonNullElements(terms));
this.Terms = terms;
this.Prev = prev;
}
}
-
+
public class ForallExpr : QuantifierExpr {
- public ForallExpr(IToken! tok, List<BoundVar!>! bvars, Expression! body, Triggers trig, Attributes attrs) {
- base(tok, bvars, body, trig, attrs);
+ public ForallExpr(IToken tok, List<BoundVar/*!*/>/*!*/ bvars, Expression body, Triggers trig, Attributes attrs)
+ : base(tok, bvars, body, trig, attrs) {
+ Contract.Requires(cce.NonNullElements(bvars));
+ Contract.Requires(tok != null);
+ Contract.Requires(body != null);
}
}
-
+
public class ExistsExpr : QuantifierExpr {
- public ExistsExpr(IToken! tok, List<BoundVar!>! bvars, Expression! body, Triggers trig, Attributes attrs) {
- base(tok, bvars, body, trig, attrs);
+ public ExistsExpr(IToken tok, List<BoundVar/*!*/>/*!*/ bvars, Expression body, Triggers trig, Attributes attrs)
+ : base(tok, bvars, body, trig, attrs) {
+ Contract.Requires(cce.NonNullElements(bvars));
+ Contract.Requires(tok != null);
+ Contract.Requires(body != null);
}
}
-
+
public class WildcardExpr : Expression { // a WildcardExpr can occur only in reads clauses and a loop's decreases clauses (with different meanings)
- public WildcardExpr(IToken! tok) {
- base(tok);
+ public WildcardExpr(IToken tok)
+ : base(tok) {
+ Contract.Requires(tok != null);
+
}
}
-
+
public class ITEExpr : Expression {
- public readonly Expression! Test;
- public readonly Expression! Thn;
- public readonly Expression! Els;
-
- public ITEExpr(IToken! tok, Expression! test, Expression! thn, Expression! els) {
+ public readonly Expression Test;
+ public readonly Expression Thn;
+ public readonly Expression Els;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Test != null);
+ Contract.Invariant(Thn != null);
+ Contract.Invariant(Els != null);
+ }
+
+
+ public ITEExpr(IToken tok, Expression test, Expression thn, Expression els)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(test != null);
+ Contract.Requires(thn != null);
+ Contract.Requires(els != null);
this.Test = test;
this.Thn = thn;
this.Els = els;
- base(tok);
+
}
}
-
+
public class MatchExpr : Expression { // a MatchExpr is an "extended expression" and is only allowed in certain places
- public readonly Expression! Source;
- public readonly List<MatchCaseExpr!>! Cases;
-
- public MatchExpr(IToken! tok, Expression! source, [Captured] List<MatchCaseExpr!>! cases) {
+ public readonly Expression Source;
+ public readonly List<MatchCaseExpr/*!*/>/*!*/ Cases;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Source != null);
+ Contract.Invariant(cce.NonNullElements(Cases));
+ }
+
+
+ public MatchExpr(IToken tok, Expression source, [Captured] List<MatchCaseExpr/*!*/>/*!*/ cases)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(source != null);
+ Contract.Requires(cce.NonNullElements(cases));
this.Source = source;
this.Cases = cases;
- base(tok);
+
+
}
}
-
+
public class MatchCaseExpr {
- public readonly IToken! tok;
- public readonly string! Id;
+ public readonly IToken tok;
+ public readonly string Id;
public DatatypeCtor Ctor; // filled in by resolution
- public readonly List<BoundVar!>! Arguments;
- public readonly Expression! Body;
-
- public MatchCaseExpr(IToken! tok, string! id, [Captured] List<BoundVar!>! arguments, Expression! body) {
+ public readonly List<BoundVar/*!*/>/*!*/ Arguments;
+ public readonly Expression/*!*/ Body;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(tok != null);
+ Contract.Invariant(Id != null);
+ Contract.Invariant(Body != null);
+ Contract.Invariant(cce.NonNullElements(Arguments));
+ }
+
+
+ public MatchCaseExpr(IToken tok, string id, [Captured] List<BoundVar/*!*/>/*!*/ arguments, Expression body) {
+ Contract.Requires(tok != null);
+ Contract.Requires(id != null);
+ Contract.Requires(cce.NonNullElements(arguments));
+ Contract.Requires(body != null);
this.tok = tok;
this.Id = id;
this.Arguments = arguments;
this.Body = body;
}
}
-
+
public class BoxingCastExpr : Expression { // a BoxingCastExpr is used only as a temporary placeholding during translation
- public readonly Expression! E;
- public readonly Type! FromType;
- public readonly Type! ToType;
-
- public BoxingCastExpr(Expression! e, Type! fromType, Type! toType) {
- base(e.tok);
+ public readonly Expression E;
+ public readonly Type FromType;
+ public readonly Type ToType;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(E != null);
+ Contract.Invariant(FromType != null);
+ Contract.Invariant(ToType != null);
+ }
+
+
+ public BoxingCastExpr(Expression e, Type fromType, Type toType)
+ : base(e.tok) {
+ Contract.Requires(e != null);
+ Contract.Requires(fromType != null);
+ Contract.Requires(toType != null);
+
E = e;
FromType = fromType;
ToType = toType;
}
}
-
+
public class UnboxingCastExpr : Expression { // an UnboxingCastExpr is used only as a temporary placeholding during translation
- public readonly Expression! E;
- public readonly Type! FromType;
- public readonly Type! ToType;
-
- public UnboxingCastExpr(Expression! e, Type! fromType, Type! toType) {
- base(e.tok);
+ public readonly Expression E;
+ public readonly Type FromType;
+ public readonly Type ToType;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(E != null);
+ Contract.Invariant(FromType != null);
+ Contract.Invariant(ToType != null);
+ }
+
+
+ public UnboxingCastExpr(Expression e, Type fromType, Type toType)
+ : base(e.tok) {
+ Contract.Requires(e != null);
+ Contract.Requires(fromType != null);
+ Contract.Requires(toType != null);
+
E = e;
FromType = fromType;
ToType = toType;
}
}
-
+
public class MaybeFreeExpression {
- public readonly Expression! E;
+ public readonly Expression E;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(E != null);
+ }
+
public readonly bool IsFree;
- public MaybeFreeExpression(Expression! e, bool isFree) {
+ public MaybeFreeExpression(Expression e, bool isFree) {
+ Contract.Requires(e != null);
E = e;
IsFree = isFree;
}
}
-
+
public class FrameExpression {
- public readonly Expression! E; // may be a WildcardExpr
+ public readonly Expression E; // may be a WildcardExpr
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(E != null);
+ Contract.Invariant(!(E is WildcardExpr) || FieldName == null && Field == null);
+ }
+
public readonly string FieldName;
public Field Field; // filled in during resolution (but is null if FieldName is)
- invariant E is WildcardExpr ==> FieldName == null && Field == null;
- public FrameExpression(Expression! e, string fieldName)
- requires e is WildcardExpr ==> fieldName == null;
- {
+
+ public FrameExpression(Expression e, string fieldName) {
+ Contract.Requires(e != null);
+ Contract.Requires(!(e is WildcardExpr) || fieldName == null);
+
E = e;
FieldName = fieldName;
}
}
-}
+} \ No newline at end of file
diff --git a/Source/Dafny/DafnyMain.cs b/Source/Dafny/DafnyMain.cs
index 21375145..893d3b90 100644
--- a/Source/Dafny/DafnyMain.cs
+++ b/Source/Dafny/DafnyMain.cs
@@ -6,7 +6,7 @@
using System;
using System.IO;
using System.Collections.Generic;
-using Microsoft.Contracts;
+using System.Diagnostics.Contracts;
using Bpl = Microsoft.Boogie;
namespace Microsoft.Dafny {
@@ -14,12 +14,15 @@ namespace Microsoft.Dafny {
/// <summary>
/// Returns null on success, or an error string otherwise.
/// </summary>
- public static string ParseCheck(List<string!>! fileNames, string! programName, out Program program)
- modifies Bpl.CommandLineOptions.Clo.XmlSink.*;
+ public static string ParseCheck(List<string/*!*/>/*!*/ fileNames, string/*!*/ programName, out Program program)
+ //modifies Bpl.CommandLineOptions.Clo.XmlSink.*;
{
+ Contract.Requires(programName != null);
+ Contract.Requires(fileNames != null);
program = null;
- List<ModuleDecl!> modules = new List<ModuleDecl!>();
- foreach (string! dafnyFileName in fileNames){
+ List<ModuleDecl> modules = new List<ModuleDecl>();
+ foreach (string dafnyFileName in fileNames){
+ Contract.Assert(dafnyFileName != null);
if (Bpl.CommandLineOptions.Clo.XmlSink != null && Bpl.CommandLineOptions.Clo.XmlSink.IsOpen) {
Bpl.CommandLineOptions.Clo.XmlSink.WriteFileFragment(dafnyFileName);
}
@@ -69,4 +72,4 @@ namespace Microsoft.Dafny {
return null; // success
}
}
-}
+} \ No newline at end of file
diff --git a/Source/Dafny/DafnyPipeline.csproj b/Source/Dafny/DafnyPipeline.csproj
index ba644870..1179fe04 100644
--- a/Source/Dafny/DafnyPipeline.csproj
+++ b/Source/Dafny/DafnyPipeline.csproj
@@ -1,145 +1,128 @@
-<?xml version="1.0" encoding="utf-8"?>
-<VisualStudioProject>
- <XEN ProjectType="Local"
- SchemaVersion="1.0"
- Name="Dafny"
- ProjectGuid="dead83c6-1510-4af9-8f7d-c837ddbb2632"
- >
- <Build>
- <Settings ApplicationIcon=""
- AssemblyName="DafnyPipeline"
- OutputType="Library"
- RootNamespace="DafnyPipeline"
- StartupObject=""
- StandardLibraryLocation=""
- TargetPlatform="v2"
- TargetPlatformLocation=""
- >
- <Config Name="Debug"
- AllowUnsafeBlocks="False"
- BaseAddress="285212672"
- CheckForOverflowUnderflow="False"
- ConfigurationOverrideFile=""
- DefineConstants="DEBUG;TRACE"
- DocumentationFile=""
- DebugSymbols="True"
- FileAlignment="4096"
- IncrementalBuild="True"
- Optimize="False"
- OutputPath="bin\debug"
- RegisterForComInterop="False"
- RemoveIntegerChecks="false"
- TreatWarningsAsErrors="False"
- WarningLevel="4"
- CheckContractAdmissibility="True"
- CheckPurity="False"
- />
- <Config Name="Release"
- AllowUnsafeBlocks="false"
- BaseAddress="285212672"
- CheckForOverflowUnderflow="false"
- ConfigurationOverrideFile=""
- DefineConstants="TRACE"
- DocumentationFile=""
- DebugSymbols="false"
- FileAlignment="4096"
- IncrementalBuild="false"
- Optimize="true"
- OutputPath="bin\release"
- RegisterForComInterop="false"
- RemoveIntegerChecks="false"
- TreatWarningsAsErrors="false"
- WarningLevel="4"
- CheckContractAdmissibility="True"
- CheckPurity="False"
- />
- </Settings>
- <References>
- <Reference Name="System"
- AssemblyName="System"
- Private="false"
- />
- <Reference Name="System.Data"
- AssemblyName="System.Data"
- Private="false"
- />
- <Reference Name="System.Xml"
- AssemblyName="System.Xml"
- Private="false"
- />
- <Reference Name="Core"
- AssemblyName="Core"
- Private="false"
- HintPath="../Core/bin/Debug/Core.dll"
- />
- <Reference Name="FSharp.Core"
- AssemblyName="FSharp.Core"
- Private="true"
- HintPath="../../Binaries/FSharp.Core.dll"
- />
- <Reference Name="FSharp.PowerPack"
- AssemblyName="FSharp.PowerPack"
- Private="true"
- HintPath="../../Binaries/FSharp.PowerPack.dll"
- />
- <Reference Name="Basetypes"
- AssemblyName="Basetypes"
- Private="true"
- HintPath="../Basetypes/bin/debug/Basetypes.dll"
- />
- </References>
- </Build>
- <Files>
- <Include>
- <File RelPath="DafnyAst.ssc"
- SubType="Code"
- BuildAction="Compile"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="Scanner.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="Parser.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="DafnyMain.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="Printer.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="Resolver.ssc"
- />
- <File BuildAction="None"
- SubType="Content"
- RelPath="Dafny.atg"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="Translator.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="..\version.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="SccGraph.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="Compiler.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="AssemblyInfo.ssc"
- />
- </Include>
- </Files>
- </XEN>
-</VisualStudioProject> \ No newline at end of file
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ <ProductVersion>9.0.30729</ProductVersion>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{FE44674A-1633-4917-99F4-57635E6FA740}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>DafnyPipeline</RootNamespace>
+ <AssemblyName>DafnyPipeline</AssemblyName>
+ <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
+ <FileAlignment>512</FileAlignment>
+ <CodeContractsAssemblyMode>0</CodeContractsAssemblyMode>
+ <SignAssembly>true</SignAssembly>
+ <AssemblyOriginatorKeyFile>InterimKey.snk</AssemblyOriginatorKeyFile>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ <DebugSymbols>true</DebugSymbols>
+ <DebugType>full</DebugType>
+ <Optimize>false</Optimize>
+ <OutputPath>bin\Debug\</OutputPath>
+ <DefineConstants>DEBUG;TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ <CodeContractsEnableRuntimeChecking>False</CodeContractsEnableRuntimeChecking>
+ <CodeContractsRuntimeOnlyPublicSurface>False</CodeContractsRuntimeOnlyPublicSurface>
+ <CodeContractsRuntimeThrowOnFailure>True</CodeContractsRuntimeThrowOnFailure>
+ <CodeContractsRuntimeCallSiteRequires>False</CodeContractsRuntimeCallSiteRequires>
+ <CodeContractsRunCodeAnalysis>False</CodeContractsRunCodeAnalysis>
+ <CodeContractsNonNullObligations>False</CodeContractsNonNullObligations>
+ <CodeContractsBoundsObligations>False</CodeContractsBoundsObligations>
+ <CodeContractsArithmeticObligations>False</CodeContractsArithmeticObligations>
+ <CodeContractsPointerObligations>False</CodeContractsPointerObligations>
+ <CodeContractsContainerAnalysis>False</CodeContractsContainerAnalysis>
+ <CodeContractsRedundantAssumptions>False</CodeContractsRedundantAssumptions>
+ <CodeContractsRunInBackground>True</CodeContractsRunInBackground>
+ <CodeContractsShowSquigglies>False</CodeContractsShowSquigglies>
+ <CodeContractsUseBaseLine>False</CodeContractsUseBaseLine>
+ <CodeContractsEmitXMLDocs>False</CodeContractsEmitXMLDocs>
+ <CodeContractsCustomRewriterAssembly>
+ </CodeContractsCustomRewriterAssembly>
+ <CodeContractsCustomRewriterClass>
+ </CodeContractsCustomRewriterClass>
+ <CodeContractsLibPaths>
+ </CodeContractsLibPaths>
+ <CodeContractsExtraRewriteOptions>
+ </CodeContractsExtraRewriteOptions>
+ <CodeContractsExtraAnalysisOptions>
+ </CodeContractsExtraAnalysisOptions>
+ <CodeContractsBaseLineFile>
+ </CodeContractsBaseLineFile>
+ <CodeContractsRuntimeCheckingLevel>Full</CodeContractsRuntimeCheckingLevel>
+ <CodeContractsReferenceAssembly>Build</CodeContractsReferenceAssembly>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ <DebugType>pdbonly</DebugType>
+ <Optimize>true</Optimize>
+ <OutputPath>bin\Release\</OutputPath>
+ <DefineConstants>TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <ItemGroup>
+ <Reference Include="AIFramework, Version=2.0.0.0, Culture=neutral, PublicKeyToken=736440c9b414ea16, processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+ <HintPath>..\..\Binaries\AIFramework.dll</HintPath>
+ </Reference>
+ <Reference Include="Basetypes, Version=2.0.0.0, Culture=neutral, PublicKeyToken=736440c9b414ea16, processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+ <HintPath>..\..\Binaries\Basetypes.dll</HintPath>
+ </Reference>
+ <Reference Include="Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=736440c9b414ea16, processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+ <HintPath>..\..\Binaries\Core.dll</HintPath>
+ </Reference>
+ <Reference Include="FSharp.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+ <HintPath>..\..\Binaries\FSharp.Core.dll</HintPath>
+ </Reference>
+ <Reference Include="FSharp.PowerPack, Version=1.9.9.9, Culture=neutral, PublicKeyToken=a19089b1c74d0809, processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+ <HintPath>..\..\Binaries\FSharp.PowerPack.dll</HintPath>
+ </Reference>
+ <Reference Include="Microsoft.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=736440c9b414ea16, processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+ <HintPath>..\..\Binaries\Microsoft.Contracts.dll</HintPath>
+ </Reference>
+ <Reference Include="System" />
+ <Reference Include="System.Core">
+ <RequiredTargetFramework>3.5</RequiredTargetFramework>
+ </Reference>
+ <Reference Include="System.Data" />
+ <Reference Include="System.Xml" />
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="Compiler.cs" />
+ <Compile Include="DafnyAst.cs" />
+ <Compile Include="DafnyMain.cs" />
+ <Compile Include="Printer.cs" />
+ <Compile Include="Resolver.cs" />
+ <Compile Include="SccGraph.cs" />
+ <Compile Include="Translator.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="cce.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="Dafny.atg" />
+ <None Include="InterimKey.snk" />
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="Parser.cs" />
+ <Compile Include="Scanner.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <Folder Include="Properties\" />
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
+ Other similar extension points exist, see Microsoft.Common.targets.
+ <Target Name="BeforeBuild">
+ </Target>
+ <Target Name="AfterBuild">
+ </Target>
+ -->
+</Project> \ No newline at end of file
diff --git a/Source/Dafny/Parser.cs b/Source/Dafny/Parser.cs
index d35fb5d3..dd4c7478 100644
--- a/Source/Dafny/Parser.cs
+++ b/Source/Dafny/Parser.cs
@@ -1,4 +1,5 @@
using System.Collections.Generic;
+using System.Diagnostics.Contracts;
using System.Numerics;
using Microsoft.Boogie;
using System.IO;
@@ -32,14 +33,14 @@ public class Parser {
public Token/*!*/ la; // lookahead token
int errDist = minErrDist;
-static List<ModuleDecl!>! theModules = new List<ModuleDecl!>();
+static List<ModuleDecl/*!*/>/*!*/ theModules = new List<ModuleDecl/*!*/>();
-static Expression! dummyExpr = new LiteralExpr(Token.NoToken);
-static FrameExpression! dummyFrameExpr = new FrameExpression(dummyExpr, null);
-static Statement! dummyStmt = new ReturnStmt(Token.NoToken);
-static Attributes.Argument! dummyAttrArg = new Attributes.Argument("dummyAttrArg");
-static Scope<string>! parseVarScope = new Scope<string>();
+static Expression/*!*/ dummyExpr = new LiteralExpr(Token.NoToken);
+static FrameExpression/*!*/ dummyFrameExpr = new FrameExpression(dummyExpr, null);
+static Statement/*!*/ dummyStmt = new ReturnStmt(Token.NoToken);
+static Attributes.Argument/*!*/ dummyAttrArg = new Attributes.Argument("dummyAttrArg");
+static Scope<string>/*!*/ parseVarScope = new Scope<string>();
static int anonymousIds = 0;
struct MemberModifiers {
@@ -49,9 +50,12 @@ struct MemberModifiers {
}
// helper routine for parsing call statements
-private static void RecordCallLhs(IdentifierExpr! e,
- List<IdentifierExpr!>! lhs,
- List<AutoVarDecl!>! newVars) {
+private static void RecordCallLhs(IdentifierExpr/*!*/ e,
+ List<IdentifierExpr/*!*/>/*!*/ lhs,
+ List<AutoVarDecl/*!*/>/*!*/ newVars) {
+ Contract.Requires(e != null);
+ Contract.Requires(cce.NonNullElements(lhs));
+ Contract.Requires(cce.NonNullElements(newVars));
int index = lhs.Count;
lhs.Add(e);
if (parseVarScope.Find(e.Name) == null) {
@@ -62,8 +66,10 @@ private static void RecordCallLhs(IdentifierExpr! e,
}
// helper routine for parsing call statements
-private static Expression! ConvertToLocal(Expression! e)
+private static Expression/*!*/ ConvertToLocal(Expression/*!*/ e)
{
+Contract.Requires(e != null);
+Contract.Ensures(Contract.Result<Expression>() != null);
FieldSelectExpr fse = e as FieldSelectExpr;
if (fse != null && fse.Obj is ImplicitThisExpr) {
return new IdentifierExpr(fse.tok, fse.FieldName);
@@ -77,14 +83,16 @@ private static Expression! ConvertToLocal(Expression! e)
/// Returns the number of parsing errors encountered.
/// Note: first initialize the Scanner.
///</summary>
-public static int Parse (string! filename, List<ModuleDecl!>! modules) /* throws System.IO.IOException */ {
+public static int Parse (string/*!*/ filename, List<ModuleDecl/*!*/>/*!*/ modules) /* throws System.IO.IOException */ {
+ Contract.Requires(filename != null);
+ Contract.Requires(cce.NonNullElements(modules));
string s;
if (filename == "stdin.dfy") {
- s = Microsoft.Boogie.ParserHelper.Fill(System.Console.In, new List<string!>());
+ s = Microsoft.Boogie.ParserHelper.Fill(System.Console.In, new List<string>());
return Parse(s, filename, modules);
} else {
using (System.IO.StreamReader reader = new System.IO.StreamReader(filename)) {
- s = Microsoft.Boogie.ParserHelper.Fill(reader, new List<string!>());
+ s = Microsoft.Boogie.ParserHelper.Fill(reader, new List<string>());
return Parse(s, filename, modules);
}
}
@@ -96,10 +104,13 @@ public static int Parse (string! filename, List<ModuleDecl!>! modules) /* throws
/// Returns the number of parsing errors encountered.
/// Note: first initialize the Scanner.
///</summary>
-public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules) {
- List<ModuleDecl!> oldModules = theModules;
+public static int Parse (string/*!*/ s, string/*!*/ filename, List<ModuleDecl/*!*/>/*!*/ modules) {
+ Contract.Requires(s != null);
+ Contract.Requires(filename != null);
+ Contract.Requires(cce.NonNullElements(modules));
+ List<ModuleDecl/*!*/> oldModules = theModules;
theModules = modules;
- byte[]! buffer = (!) UTF8Encoding.Default.GetBytes(s);
+ byte[]/*!*/ buffer = cce.NonNull( UTF8Encoding.Default.GetBytes(s));
MemoryStream ms = new MemoryStream(buffer,false);
Errors errors = new Errors();
Scanner scanner = new Scanner(ms, errors, filename);
@@ -115,7 +126,7 @@ public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules
public Parser(Scanner/*!*/ scanner, Errors/*!*/ errors) {
this.scanner = scanner;
this.errors = errors;
- Token! tok = new Token();
+ Token/*!*/ tok = new Token();
tok.val = "";
this.la = tok;
this.t = new Token(); // just to satisfy its non-null constraint
@@ -126,12 +137,15 @@ public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules
errDist = 0;
}
- public void SemErr (string! msg) {
+ public void SemErr (string/*!*/ msg) {
+ Contract.Requires(msg != null);
if (errDist >= minErrDist) errors.SemErr(t, msg);
errDist = 0;
}
- public void SemErr(IToken! tok, string! msg) {
+ public void SemErr(IToken/*!*/ tok, string/*!*/ msg) {
+ Contract.Requires(tok != null);
+ Contract.Requires(msg != null);
errors.SemErr(tok, msg);
}
@@ -178,10 +192,10 @@ public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules
void Dafny() {
- ClassDecl! c; DatatypeDecl! dt;
- Attributes attrs; IToken! id; List<string!> theImports;
+ ClassDecl/*!*/ c; DatatypeDecl/*!*/ dt;
+ Attributes attrs; IToken/*!*/ id; List<string/*!*/> theImports;
- List<MemberDecl!> membersDefaultClass = new List<MemberDecl!>();
+ List<MemberDecl/*!*/> membersDefaultClass = new List<MemberDecl/*!*/>();
ModuleDecl module;
// to support multiple files, create a default module only if theModules doesn't already contain one
@@ -199,7 +213,7 @@ public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules
while (StartOf(1)) {
if (la.kind == 4) {
Get();
- attrs = null; theImports = new List<string!>();
+ attrs = null; theImports = new List<string/*!*/>();
while (la.kind == 6) {
Attribute(ref attrs);
}
@@ -254,13 +268,14 @@ public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules
Expect(7);
}
- void Ident(out IToken! x) {
+ void Ident(out IToken/*!*/ x) {
+ Contract.Ensures(Contract.ValueAtReturn(out x) != null);
Expect(1);
x = t;
}
- void Idents(List<string!>! ids) {
- IToken! id;
+ void Idents(List<string/*!*/>/*!*/ ids) {
+ IToken/*!*/ id;
Ident(out id);
ids.Add(id.val);
while (la.kind == 16) {
@@ -270,13 +285,15 @@ public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules
}
}
- void ClassDecl(ModuleDecl! module, out ClassDecl! c) {
- IToken! id;
+ void ClassDecl(ModuleDecl/*!*/ module, out ClassDecl/*!*/ c) {
+ Contract.Requires(module != null);
+ Contract.Ensures(Contract.ValueAtReturn(out c) != null);
+ IToken/*!*/ id;
Attributes attrs = null;
- List<TypeParameter!> typeArgs = new List<TypeParameter!>();
- IToken! idRefined;
- IToken optionalId = null;
- List<MemberDecl!> members = new List<MemberDecl!>();
+ List<TypeParameter/*!*/> typeArgs = new List<TypeParameter/*!*/>();
+ IToken/*!*/ idRefined;
+ IToken optionalId = null;
+ List<MemberDecl/*!*/> members = new List<MemberDecl/*!*/>();
Expect(8);
while (la.kind == 6) {
@@ -303,11 +320,13 @@ public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules
}
- void DatatypeDecl(ModuleDecl! module, out DatatypeDecl! dt) {
- IToken! id;
+ void DatatypeDecl(ModuleDecl/*!*/ module, out DatatypeDecl/*!*/ dt) {
+ Contract.Requires(module != null);
+ Contract.Ensures(Contract.ValueAtReturn(out dt)!=null);
+ IToken/*!*/ id;
Attributes attrs = null;
- List<TypeParameter!> typeArgs = new List<TypeParameter!>();
- List<DatatypeCtor!> ctors = new List<DatatypeCtor!>();
+ List<TypeParameter/*!*/> typeArgs = new List<TypeParameter/*!*/>();
+ List<DatatypeCtor/*!*/> ctors = new List<DatatypeCtor/*!*/>();
Expect(13);
while (la.kind == 6) {
@@ -325,9 +344,10 @@ public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules
dt = new DatatypeDecl(id, id.val, module, typeArgs, ctors, attrs);
}
- void ClassMemberDecl(List<MemberDecl!>! mm) {
- Method! m;
- Function! f;
+ void ClassMemberDecl(List<MemberDecl/*!*/>/*!*/ mm) {
+ Contract.Requires(cce.NonNullElements(mm));
+ Method/*!*/ m;
+ Function/*!*/ f;
MemberModifiers mmod = new MemberModifiers();
while (la.kind == 10 || la.kind == 11 || la.kind == 12) {
@@ -355,8 +375,9 @@ public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules
} else SynErr(104);
}
- void GenericParameters(List<TypeParameter!>! typeArgs) {
- IToken! id;
+ void GenericParameters(List<TypeParameter/*!*/>/*!*/ typeArgs) {
+ Contract.Requires(cce.NonNullElements(typeArgs));
+ IToken/*!*/ id;
Expect(20);
Ident(out id);
typeArgs.Add(new TypeParameter(id, id.val));
@@ -368,9 +389,10 @@ public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules
Expect(21);
}
- void FieldDecl(MemberModifiers mmod, List<MemberDecl!>! mm) {
+ void FieldDecl(MemberModifiers mmod, List<MemberDecl/*!*/>/*!*/ mm) {
+ Contract.Requires(cce.NonNullElements(mm));
Attributes attrs = null;
- IToken! id; Type! ty;
+ IToken/*!*/ id; Type/*!*/ ty;
Expect(15);
if (mmod.IsUnlimited) { SemErr(t, "fields cannot be declared 'unlimited'"); }
@@ -389,16 +411,17 @@ public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules
Expect(14);
}
- void FunctionDecl(MemberModifiers mmod, out Function! f) {
+ void FunctionDecl(MemberModifiers mmod, out Function/*!*/ f) {
+ Contract.Ensures(Contract.ValueAtReturn(out f)!=null);
Attributes attrs = null;
- IToken! id;
- List<TypeParameter!> typeArgs = new List<TypeParameter!>();
- List<Formal!> formals = new List<Formal!>();
- Type! returnType;
- List<Expression!> reqs = new List<Expression!>();
- List<FrameExpression!> reads = new List<FrameExpression!>();
- List<Expression!> decreases = new List<Expression!>();
- Expression! bb; Expression body = null;
+ IToken/*!*/ id;
+ List<TypeParameter/*!*/> typeArgs = new List<TypeParameter/*!*/>();
+ List<Formal/*!*/> formals = new List<Formal/*!*/>();
+ Type/*!*/ returnType;
+ List<Expression/*!*/> reqs = new List<Expression/*!*/>();
+ List<FrameExpression/*!*/> reads = new List<FrameExpression/*!*/>();
+ List<Expression/*!*/> decreases = new List<Expression/*!*/>();
+ Expression/*!*/ bb; Expression body = null;
bool isFunctionMethod = false;
Expect(37);
@@ -436,17 +459,18 @@ public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules
}
- void MethodDecl(MemberModifiers mmod, out Method! m) {
- IToken! id;
+ void MethodDecl(MemberModifiers mmod, out Method/*!*/ m) {
+ Contract.Ensures(Contract.ValueAtReturn(out m) !=null);
+ IToken/*!*/ id;
Attributes attrs = null;
- List<TypeParameter!>! typeArgs = new List<TypeParameter!>();
- List<Formal!> ins = new List<Formal!>();
- List<Formal!> outs = new List<Formal!>();
- List<MaybeFreeExpression!> req = new List<MaybeFreeExpression!>();
- List<FrameExpression!> mod = new List<FrameExpression!>();
- List<MaybeFreeExpression!> ens = new List<MaybeFreeExpression!>();
- List<Expression!> dec = new List<Expression!>();
- Statement! bb; BlockStmt body = null;
+ List<TypeParameter/*!*/>/*!*/ typeArgs = new List<TypeParameter/*!*/>();
+ List<Formal/*!*/> ins = new List<Formal/*!*/>();
+ List<Formal/*!*/> outs = new List<Formal/*!*/>();
+ List<MaybeFreeExpression/*!*/> req = new List<MaybeFreeExpression/*!*/>();
+ List<FrameExpression/*!*/> mod = new List<FrameExpression/*!*/>();
+ List<MaybeFreeExpression/*!*/> ens = new List<MaybeFreeExpression/*!*/>();
+ List<Expression/*!*/> dec = new List<Expression/*!*/>();
+ Statement/*!*/ bb; BlockStmt body = null;
bool isRefinement = false;
if (la.kind == 22) {
@@ -490,11 +514,12 @@ public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules
}
- void CouplingInvDecl(MemberModifiers mmod, List<MemberDecl!>! mm) {
+ void CouplingInvDecl(MemberModifiers mmod, List<MemberDecl/*!*/>/*!*/ mm) {
+ Contract.Requires(cce.NonNullElements(mm));
Attributes attrs = null;
- List<IToken!> ids = new List<IToken!>();;
- IToken! id;
- Expression! e;
+ List<IToken/*!*/> ids = new List<IToken/*!*/>();;
+ IToken/*!*/ id;
+ Expression/*!*/ e;
parseVarScope.PushMarker();
Expect(17);
@@ -520,11 +545,12 @@ public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules
}
- void DatatypeMemberDecl(List<DatatypeCtor!>! ctors) {
+ void DatatypeMemberDecl(List<DatatypeCtor/*!*/>/*!*/ ctors) {
+ Contract.Requires(cce.NonNullElements(ctors));
Attributes attrs = null;
- IToken! id;
- List<TypeParameter!> typeArgs = new List<TypeParameter!>();
- List<Formal!> formals = new List<Formal!>();
+ IToken/*!*/ id;
+ List<TypeParameter/*!*/> typeArgs = new List<TypeParameter/*!*/>();
+ List<Formal/*!*/> formals = new List<Formal/*!*/>();
while (la.kind == 6) {
Attribute(ref attrs);
@@ -543,8 +569,8 @@ public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules
Expect(14);
}
- void FormalsOptionalIds(List<Formal!>! formals) {
- IToken! id; Type! ty; string! name; bool isGhost;
+ void FormalsOptionalIds(List<Formal/*!*/>/*!*/ formals) {
+ Contract.Requires(cce.NonNullElements(formals)); IToken/*!*/ id; Type/*!*/ ty; string/*!*/ name; bool isGhost;
Expect(29);
if (StartOf(6)) {
TypeIdentOptional(out id, out name, out ty, out isGhost);
@@ -558,14 +584,15 @@ public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules
Expect(30);
}
- void IdentType(out IToken! id, out Type! ty) {
+ void IdentType(out IToken/*!*/ id, out Type/*!*/ ty) {
+ Contract.Ensures(Contract.ValueAtReturn(out id) != null); Contract.Ensures(Contract.ValueAtReturn(out ty) != null);
Ident(out id);
Expect(19);
Type(out ty);
}
- void Expression(out Expression! e) {
- IToken! x; Expression! e0; Expression! e1 = dummyExpr;
+ void Expression(out Expression/*!*/ e) {
+ Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x; Expression/*!*/ e0; Expression/*!*/ e1 = dummyExpr;
e = dummyExpr;
if (la.kind == 52) {
@@ -582,7 +609,9 @@ public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules
} else SynErr(108);
}
- void GIdentType(bool allowGhost, out IToken! id, out Type! ty, out bool isGhost) {
+ void GIdentType(bool allowGhost, out IToken/*!*/ id, out Type/*!*/ ty, out bool isGhost) {
+ Contract.Ensures(Contract.ValueAtReturn(out id)!=null);
+ Contract.Ensures(Contract.ValueAtReturn(out ty)!=null);
isGhost = false;
if (la.kind == 10) {
Get();
@@ -591,13 +620,13 @@ public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules
IdentType(out id, out ty);
}
- void Type(out Type! ty) {
- IToken! tok;
+ void Type(out Type/*!*/ ty) {
+ Contract.Ensures(Contract.ValueAtReturn(out ty) != null); IToken/*!*/ tok;
TypeAndToken(out tok, out ty);
}
- void IdentTypeOptional(out BoundVar! var) {
- IToken! id; Type! ty; Type optType = null;
+ void IdentTypeOptional(out BoundVar/*!*/ var) {
+ Contract.Ensures(Contract.ValueAtReturn(out var)!=null); IToken/*!*/ id; Type/*!*/ ty; Type optType = null;
Ident(out id);
if (la.kind == 19) {
@@ -608,7 +637,10 @@ public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules
var = new BoundVar(id, id.val, optType == null ? new InferredTypeProxy() : optType);
}
- void TypeIdentOptional(out IToken! id, out string! identName, out Type! ty, out bool isGhost) {
+ void TypeIdentOptional(out IToken/*!*/ id, out string/*!*/ identName, out Type/*!*/ ty, out bool isGhost) {
+ Contract.Ensures(Contract.ValueAtReturn(out id)!=null);
+ Contract.Ensures(Contract.ValueAtReturn(out ty)!=null);
+ Contract.Ensures(Contract.ValueAtReturn(out identName)!=null);
string name = null; isGhost = false;
if (la.kind == 10) {
Get();
@@ -634,9 +666,9 @@ public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules
}
- void TypeAndToken(out IToken! tok, out Type! ty) {
- tok = Token.NoToken; ty = new BoolType(); /*keep compiler happy*/
- List<Type!>! gt;
+ void TypeAndToken(out IToken/*!*/ tok, out Type/*!*/ ty) {
+ Contract.Ensures(Contract.ValueAtReturn(out tok)!=null); Contract.Ensures(Contract.ValueAtReturn(out ty) != null); tok = Token.NoToken; ty = new BoolType(); /*keep compiler happy*/
+ List<Type/*!*/>/*!*/ gt;
if (la.kind == 31) {
Get();
@@ -646,7 +678,7 @@ public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules
tok = t; ty = new IntType();
} else if (la.kind == 33) {
Get();
- tok = t; gt = new List<Type!>();
+ tok = t; gt = new List<Type/*!*/>();
GenericInstantiation(gt);
if (gt.Count != 1) {
SemErr("set type expects exactly one type argument");
@@ -655,7 +687,7 @@ public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules
} else if (la.kind == 34) {
Get();
- tok = t; gt = new List<Type!>();
+ tok = t; gt = new List<Type/*!*/>();
GenericInstantiation(gt);
if (gt.Count != 1) {
SemErr("seq type expects exactly one type argument");
@@ -667,8 +699,8 @@ public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules
} else SynErr(109);
}
- void Formals(bool incoming, bool allowGhosts, List<Formal!>! formals) {
- IToken! id; Type! ty; bool isGhost;
+ void Formals(bool incoming, bool allowGhosts, List<Formal/*!*/>/*!*/ formals) {
+ Contract.Requires(cce.NonNullElements(formals)); IToken/*!*/ id; Type/*!*/ ty; bool isGhost;
Expect(29);
if (la.kind == 1 || la.kind == 10) {
GIdentType(allowGhosts, out id, out ty, out isGhost);
@@ -682,9 +714,10 @@ public static int Parse (string! s, string! filename, List<ModuleDecl!>! modules
Expect(30);
}
- void MethodSpec(List<MaybeFreeExpression!>! req, List<FrameExpression!>! mod, List<MaybeFreeExpression!>! ens,
-List<Expression!>! decreases) {
- Expression! e; FrameExpression! fe; bool isFree = false;
+ void MethodSpec(List<MaybeFreeExpression/*!*/>/*!*/ req, List<FrameExpression/*!*/>/*!*/ mod, List<MaybeFreeExpression/*!*/>/*!*/ ens,
+List<Expression/*!*/>/*!*/ decreases) {
+ Contract.Requires(cce.NonNullElements(req)); Contract.Requires(cce.NonNullElements(mod)); Contract.Requires(cce.NonNullElements(ens)); Contract.Requires(cce.NonNullElements(decreases));
+ Expression/*!*/ e; FrameExpression/*!*/ fe; bool isFree = false;
if (la.kind == 24) {
Get();
@@ -721,10 +754,10 @@ List<Expression!>! decreases) {
} else SynErr(111);
}
- void BlockStmt(out Statement! block) {
- IToken! x;
- List<Statement!> body = new List<Statement!>();
- Statement! s;
+ void BlockStmt(out Statement/*!*/ block) {
+ Contract.Ensures(Contract.ValueAtReturn(out block) != null); IToken/*!*/ x;
+ List<Statement/*!*/> body = new List<Statement/*!*/>();
+ Statement/*!*/ s;
parseVarScope.PushMarker();
Expect(6);
@@ -737,8 +770,8 @@ List<Expression!>! decreases) {
parseVarScope.PopMarker();
}
- void FrameExpression(out FrameExpression! fe) {
- Expression! e; IToken! id; string fieldName = null;
+ void FrameExpression(out FrameExpression/*!*/ fe) {
+ Contract.Ensures(Contract.ValueAtReturn(out fe) != null); Expression/*!*/ e; IToken/*!*/ id; string fieldName = null;
Expression(out e);
if (la.kind == 40) {
Get();
@@ -748,8 +781,8 @@ List<Expression!>! decreases) {
fe = new FrameExpression(e, fieldName);
}
- void Expressions(List<Expression!>! args) {
- Expression! e;
+ void Expressions(List<Expression/*!*/>/*!*/ args) {
+ Contract.Requires(cce.NonNullElements(args)); Expression/*!*/ e;
Expression(out e);
args.Add(e);
while (la.kind == 16) {
@@ -759,8 +792,8 @@ List<Expression!>! decreases) {
}
}
- void GenericInstantiation(List<Type!>! gt) {
- Type! ty;
+ void GenericInstantiation(List<Type/*!*/>/*!*/ gt) {
+ Contract.Requires(cce.NonNullElements(gt)); Type/*!*/ ty;
Expect(20);
Type(out ty);
gt.Add(ty);
@@ -772,16 +805,17 @@ List<Expression!>! decreases) {
Expect(21);
}
- void ReferenceType(out IToken! tok, out Type! ty) {
+ void ReferenceType(out IToken/*!*/ tok, out Type/*!*/ ty) {
+ Contract.Ensures(Contract.ValueAtReturn(out tok) != null); Contract.Ensures(Contract.ValueAtReturn(out ty) != null);
tok = Token.NoToken; ty = new BoolType(); /*keep compiler happy*/
- List<Type!>! gt;
+ List<Type/*!*/>/*!*/ gt;
if (la.kind == 35) {
Get();
tok = t; ty = new ObjectType();
} else if (la.kind == 36) {
Get();
- tok = t; gt = new List<Type!>();
+ tok = t; gt = new List<Type/*!*/>();
GenericInstantiation(gt);
if (gt.Count != 1) {
SemErr("array type expects exactly one type argument");
@@ -790,7 +824,7 @@ List<Expression!>! decreases) {
} else if (la.kind == 1) {
Ident(out tok);
- gt = new List<Type!>();
+ gt = new List<Type/*!*/>();
if (la.kind == 20) {
GenericInstantiation(gt);
}
@@ -798,8 +832,9 @@ List<Expression!>! decreases) {
} else SynErr(112);
}
- void FunctionSpec(List<Expression!>! reqs, List<FrameExpression!>! reads, List<Expression!>! decreases) {
- Expression! e; FrameExpression! fe;
+ void FunctionSpec(List<Expression/*!*/>/*!*/ reqs, List<FrameExpression/*!*/>/*!*/ reads, List<Expression/*!*/>/*!*/ decreases) {
+ Contract.Requires(cce.NonNullElements(reqs)); Contract.Requires(cce.NonNullElements(reads)); Contract.Requires(cce.NonNullElements(decreases));
+ Expression/*!*/ e; FrameExpression/*!*/ fe;
if (la.kind == 26) {
Get();
Expression(out e);
@@ -824,8 +859,8 @@ List<Expression!>! decreases) {
} else SynErr(113);
}
- void FunctionBody(out Expression! e) {
- e = dummyExpr;
+ void FunctionBody(out Expression/*!*/ e) {
+ Contract.Ensures(Contract.ValueAtReturn(out e) != null); e = dummyExpr;
Expect(6);
if (la.kind == 41) {
MatchExpression(out e);
@@ -835,8 +870,8 @@ List<Expression!>! decreases) {
Expect(7);
}
- void PossiblyWildFrameExpression(out FrameExpression! fe) {
- fe = dummyFrameExpr;
+ void PossiblyWildFrameExpression(out FrameExpression/*!*/ fe) {
+ Contract.Ensures(Contract.ValueAtReturn(out fe) != null); fe = dummyFrameExpr;
if (la.kind == 39) {
Get();
fe = new FrameExpression(new WildcardExpr(t), null);
@@ -845,7 +880,8 @@ List<Expression!>! decreases) {
} else SynErr(115);
}
- void PossiblyWildExpression(out Expression! e) {
+ void PossiblyWildExpression(out Expression/*!*/ e) {
+ Contract.Ensures(Contract.ValueAtReturn(out e)!=null);
e = dummyExpr;
if (la.kind == 39) {
Get();
@@ -855,9 +891,9 @@ List<Expression!>! decreases) {
} else SynErr(116);
}
- void MatchExpression(out Expression! e) {
- IToken! x; MatchCaseExpr! c;
- List<MatchCaseExpr!> cases = new List<MatchCaseExpr!>();
+ void MatchExpression(out Expression/*!*/ e) {
+ Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x; MatchCaseExpr/*!*/ c;
+ List<MatchCaseExpr/*!*/> cases = new List<MatchCaseExpr/*!*/>();
Expect(41);
x = t;
@@ -869,10 +905,10 @@ List<Expression!>! decreases) {
e = new MatchExpr(x, e, cases);
}
- void CaseExpression(out MatchCaseExpr! c) {
- IToken! x, id, arg;
- List<BoundVar!> arguments = new List<BoundVar!>();
- Expression! body;
+ void CaseExpression(out MatchCaseExpr/*!*/ c) {
+ Contract.Ensures(Contract.ValueAtReturn(out c) != null); IToken/*!*/ x, id, arg;
+ List<BoundVar/*!*/> arguments = new List<BoundVar/*!*/>();
+ Expression/*!*/ body;
Expect(42);
x = t; parseVarScope.PushMarker();
@@ -896,8 +932,8 @@ List<Expression!>! decreases) {
parseVarScope.PopMarker();
}
- void Stmt(List<Statement!>! ss) {
- Statement! s;
+ void Stmt(List<Statement/*!*/>/*!*/ ss) {
+ Contract.Requires(cce.NonNullElements(ss)); Statement/*!*/ s;
while (la.kind == 6) {
BlockStmt(out s);
ss.Add(s);
@@ -910,8 +946,8 @@ List<Expression!>! decreases) {
} else SynErr(117);
}
- void OneStmt(out Statement! s) {
- IToken! x; IToken! id; string label = null;
+ void OneStmt(out Statement/*!*/ s) {
+ Contract.Ensures(Contract.ValueAtReturn(out s) != null); IToken/*!*/ x; IToken/*!*/ id; string label = null;
s = dummyStmt; /* to please the compiler */
switch (la.kind) {
@@ -989,8 +1025,8 @@ List<Expression!>! decreases) {
}
}
- void VarDeclStmts(List<Statement!>! ss) {
- VarDecl! d; bool isGhost = false;
+ void VarDeclStmts(List<Statement/*!*/>/*!*/ ss) {
+ Contract.Requires(cce.NonNullElements(ss)); VarDecl/*!*/ d; bool isGhost = false;
if (la.kind == 10) {
Get();
isGhost = true;
@@ -1006,8 +1042,8 @@ List<Expression!>! decreases) {
Expect(14);
}
- void AssertStmt(out Statement! s) {
- IToken! x; Expression! e;
+ void AssertStmt(out Statement/*!*/ s) {
+ Contract.Ensures(Contract.ValueAtReturn(out s) != null); IToken/*!*/ x; Expression/*!*/ e;
Expect(60);
x = t;
Expression(out e);
@@ -1015,8 +1051,8 @@ List<Expression!>! decreases) {
s = new AssertStmt(x, e);
}
- void AssumeStmt(out Statement! s) {
- IToken! x; Expression! e;
+ void AssumeStmt(out Statement/*!*/ s) {
+ Contract.Ensures(Contract.ValueAtReturn(out s) != null); IToken/*!*/ x; Expression/*!*/ e;
Expect(61);
x = t;
Expression(out e);
@@ -1024,8 +1060,8 @@ List<Expression!>! decreases) {
s = new AssumeStmt(x, e);
}
- void UseStmt(out Statement! s) {
- IToken! x; Expression! e;
+ void UseStmt(out Statement/*!*/ s) {
+ Contract.Ensures(Contract.ValueAtReturn(out s) != null); IToken/*!*/ x; Expression/*!*/ e;
Expect(62);
x = t;
Expression(out e);
@@ -1033,9 +1069,9 @@ List<Expression!>! decreases) {
s = new UseStmt(x, e);
}
- void PrintStmt(out Statement! s) {
- IToken! x; Attributes.Argument! arg;
- List<Attributes.Argument!> args = new List<Attributes.Argument!>();
+ void PrintStmt(out Statement/*!*/ s) {
+ Contract.Ensures(Contract.ValueAtReturn(out s) != null); IToken/*!*/ x; Attributes.Argument/*!*/ arg;
+ List<Attributes.Argument/*!*/> args = new List<Attributes.Argument/*!*/>();
Expect(63);
x = t;
@@ -1050,9 +1086,9 @@ List<Expression!>! decreases) {
s = new PrintStmt(x, args);
}
- void AssignStmt(out Statement! s) {
- IToken! x;
- Expression! lhs;
+ void AssignStmt(out Statement/*!*/ s) {
+ Contract.Ensures(Contract.ValueAtReturn(out s) != null); IToken/*!*/ x;
+ Expression/*!*/ lhs;
Expression rhs;
Type ty;
s = dummyStmt;
@@ -1062,7 +1098,7 @@ List<Expression!>! decreases) {
x = t;
AssignRhs(out rhs, out ty);
if (ty == null) {
- assert rhs != null;
+ Contract.Assert(rhs != null);
s = new AssignStmt(x, lhs, rhs);
} else if (rhs == null) {
s = new AssignStmt(x, lhs, ty);
@@ -1073,8 +1109,8 @@ List<Expression!>! decreases) {
Expect(14);
}
- void HavocStmt(out Statement! s) {
- IToken! x; Expression! lhs;
+ void HavocStmt(out Statement/*!*/ s) {
+ Contract.Ensures(Contract.ValueAtReturn(out s) != null); IToken/*!*/ x; Expression/*!*/ lhs;
Expect(51);
x = t;
LhsExpr(out lhs);
@@ -1082,11 +1118,11 @@ List<Expression!>! decreases) {
s = new AssignStmt(x, lhs);
}
- void CallStmt(out Statement! s) {
- IToken! x, id;
- Expression! e;
- List<IdentifierExpr!> lhs = new List<IdentifierExpr!>();
- List<AutoVarDecl!> newVars = new List<AutoVarDecl!>();
+ void CallStmt(out Statement/*!*/ s) {
+ Contract.Ensures(Contract.ValueAtReturn(out s) != null); IToken/*!*/ x, id;
+ Expression/*!*/ e;
+ List<IdentifierExpr/*!*/> lhs = new List<IdentifierExpr/*!*/>();
+ List<AutoVarDecl/*!*/> newVars = new List<AutoVarDecl/*!*/>();
Expect(56);
x = t;
@@ -1132,16 +1168,16 @@ List<Expression!>! decreases) {
s = new CallStmt(x, newVars, lhs, fce.Receiver, fce.Name, fce.Args); // this actually does an ownership transfer of fce.Args
} else {
SemErr("RHS of call statement must denote a method invocation");
- s = new CallStmt(x, newVars, lhs, dummyExpr, "dummyMethodName", new List<Expression!>());
+ s = new CallStmt(x, newVars, lhs, dummyExpr, "dummyMethodName", new List<Expression/*!*/>());
}
}
- void IfStmt(out Statement! ifStmt) {
- IToken! x;
+ void IfStmt(out Statement/*!*/ ifStmt) {
+ Contract.Ensures(Contract.ValueAtReturn(out ifStmt) != null); IToken/*!*/ x;
Expression guard;
- Statement! thn;
- Statement! s;
+ Statement/*!*/ thn;
+ Statement/*!*/ s;
Statement els = null;
Expect(52);
@@ -1161,18 +1197,18 @@ List<Expression!>! decreases) {
ifStmt = new IfStmt(x, guard, thn, els);
}
- void WhileStmt(out Statement! stmt) {
- IToken! x;
+ void WhileStmt(out Statement/*!*/ stmt) {
+ Contract.Ensures(Contract.ValueAtReturn(out stmt) != null); IToken/*!*/ x;
Expression guard;
- bool isFree; Expression! e;
- List<MaybeFreeExpression!> invariants = new List<MaybeFreeExpression!>();
- List<Expression!> decreases = new List<Expression!>();
- Statement! body;
+ bool isFree; Expression/*!*/ e;
+ List<MaybeFreeExpression/*!*/> invariants = new List<MaybeFreeExpression/*!*/>();
+ List<Expression/*!*/> decreases = new List<Expression/*!*/>();
+ Statement/*!*/ body;
Expect(54);
x = t;
Guard(out guard);
- assume guard == null || Owner.None(guard);
+ Contract.Assume(guard == null || cce.Owner.None(guard));
while (la.kind == 25 || la.kind == 28 || la.kind == 55) {
if (la.kind == 25 || la.kind == 55) {
isFree = false;
@@ -1200,9 +1236,10 @@ List<Expression!>! decreases) {
stmt = new WhileStmt(x, guard, invariants, decreases, body);
}
- void MatchStmt(out Statement! s) {
- Token x; Expression! e; MatchCaseStmt! c;
- List<MatchCaseStmt!> cases = new List<MatchCaseStmt!>();
+ void MatchStmt(out Statement/*!*/ s) {
+ Contract.Ensures(Contract.ValueAtReturn(out s) != null);
+ Token x; Expression/*!*/ e; MatchCaseStmt/*!*/ c;
+ List<MatchCaseStmt/*!*/> cases = new List<MatchCaseStmt/*!*/>();
Expect(41);
x = t;
Expression(out e);
@@ -1215,12 +1252,12 @@ List<Expression!>! decreases) {
s = new MatchStmt(x, e, cases);
}
- void ForeachStmt(out Statement! s) {
- IToken! x, boundVar;
- Type! ty;
- Expression! collection;
- Expression! range;
- List<PredicateStmt!> bodyPrefix = new List<PredicateStmt!>();
+ void ForeachStmt(out Statement/*!*/ s) {
+ Contract.Ensures(Contract.ValueAtReturn(out s) != null); IToken/*!*/ x, boundVar;
+ Type/*!*/ ty;
+ Expression/*!*/ collection;
+ Expression/*!*/ range;
+ List<PredicateStmt/*!*/> bodyPrefix = new List<PredicateStmt/*!*/>();
AssignStmt bodyAssign = null;
parseVarScope.PushMarker();
@@ -1273,12 +1310,13 @@ List<Expression!>! decreases) {
parseVarScope.PopMarker();
}
- void LhsExpr(out Expression! e) {
+ void LhsExpr(out Expression/*!*/ e) {
+ Contract.Ensures(Contract.ValueAtReturn(out e)!=null);
SelectExpression(out e);
}
void AssignRhs(out Expression e, out Type ty) {
- IToken! x; Expression! ee; Type! tt;
+ IToken/*!*/ x; Expression/*!*/ ee; Type/*!*/ tt;
e = null; ty = null;
if (la.kind == 48) {
@@ -1298,8 +1336,8 @@ List<Expression!>! decreases) {
if (e == null && ty == null) { e = dummyExpr; }
}
- void SelectExpression(out Expression! e) {
- IToken! id; e = dummyExpr;
+ void SelectExpression(out Expression/*!*/ e) {
+ Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ id; e = dummyExpr;
if (la.kind == 1) {
IdentOrFuncExpression(out e);
} else if (la.kind == 29 || la.kind == 95 || la.kind == 96) {
@@ -1310,8 +1348,8 @@ List<Expression!>! decreases) {
}
}
- void IdentTypeRhs(out VarDecl! d, bool isGhost) {
- IToken! id; Type! ty; Expression! e;
+ void IdentTypeRhs(out VarDecl/*!*/ d, bool isGhost) {
+ Contract.Ensures(Contract.ValueAtReturn(out d) != null); IToken/*!*/ id; Type/*!*/ ty; Expression/*!*/ e;
Expression rhs = null; Type newType = null;
Type optionalType = null; DeterminedAssignmentRhs optionalRhs = null;
@@ -1341,7 +1379,7 @@ List<Expression!>! decreases) {
}
void Guard(out Expression e) {
- Expression! ee; e = null;
+ Expression/*!*/ ee; e = null;
Expect(29);
if (la.kind == 39) {
Get();
@@ -1353,10 +1391,11 @@ List<Expression!>! decreases) {
Expect(30);
}
- void CaseStatement(out MatchCaseStmt! c) {
- IToken! x, id, arg;
- List<BoundVar!> arguments = new List<BoundVar!>();
- List<Statement!> body = new List<Statement!>();
+ void CaseStatement(out MatchCaseStmt/*!*/ c) {
+ Contract.Ensures(Contract.ValueAtReturn(out c) != null);
+ IToken/*!*/ x, id, arg;
+ List<BoundVar/*!*/> arguments = new List<BoundVar/*!*/>();
+ List<Statement/*!*/> body = new List<Statement/*!*/>();
Expect(42);
x = t; parseVarScope.PushMarker();
@@ -1384,8 +1423,8 @@ List<Expression!>! decreases) {
parseVarScope.PopMarker();
}
- void CallStmtSubExpr(out Expression! e) {
- e = dummyExpr;
+ void CallStmtSubExpr(out Expression/*!*/ e) {
+ Contract.Ensures(Contract.ValueAtReturn(out e) != null); e = dummyExpr;
if (la.kind == 1) {
IdentOrFuncExpression(out e);
} else if (la.kind == 29 || la.kind == 95 || la.kind == 96) {
@@ -1397,8 +1436,8 @@ List<Expression!>! decreases) {
}
}
- void AttributeArg(out Attributes.Argument! arg) {
- Expression! e; arg = dummyAttrArg;
+ void AttributeArg(out Attributes.Argument/*!*/ arg) {
+ Contract.Ensures(Contract.ValueAtReturn(out arg) != null); Expression/*!*/ e; arg = dummyAttrArg;
if (la.kind == 3) {
Get();
arg = new Attributes.Argument(t.val.Substring(1, t.val.Length-2));
@@ -1408,8 +1447,8 @@ List<Expression!>! decreases) {
} else SynErr(125);
}
- void EquivExpression(out Expression! e0) {
- IToken! x; Expression! e1;
+ void EquivExpression(out Expression/*!*/ e0) {
+ Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expression/*!*/ e1;
ImpliesExpression(out e0);
while (la.kind == 65 || la.kind == 66) {
EquivOp();
@@ -1419,8 +1458,8 @@ List<Expression!>! decreases) {
}
}
- void ImpliesExpression(out Expression! e0) {
- IToken! x; Expression! e1;
+ void ImpliesExpression(out Expression/*!*/ e0) {
+ Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expression/*!*/ e1;
LogicalExpression(out e0);
if (la.kind == 67 || la.kind == 68) {
ImpliesOp();
@@ -1438,8 +1477,8 @@ List<Expression!>! decreases) {
} else SynErr(126);
}
- void LogicalExpression(out Expression! e0) {
- IToken! x; Expression! e1;
+ void LogicalExpression(out Expression/*!*/ e0) {
+ Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expression/*!*/ e1;
RelationalExpression(out e0);
if (StartOf(13)) {
if (la.kind == 69 || la.kind == 70) {
@@ -1476,8 +1515,8 @@ List<Expression!>! decreases) {
} else SynErr(127);
}
- void RelationalExpression(out Expression! e0) {
- IToken! x; Expression! e1; BinaryExpr.Opcode op;
+ void RelationalExpression(out Expression/*!*/ e0) {
+ Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expression/*!*/ e1; BinaryExpr.Opcode op;
Term(out e0);
if (StartOf(14)) {
RelOp(out x, out op);
@@ -1502,8 +1541,8 @@ List<Expression!>! decreases) {
} else SynErr(129);
}
- void Term(out Expression! e0) {
- IToken! x; Expression! e1; BinaryExpr.Opcode op;
+ void Term(out Expression/*!*/ e0) {
+ Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expression/*!*/ e1; BinaryExpr.Opcode op;
Factor(out e0);
while (la.kind == 82 || la.kind == 83) {
AddOp(out x, out op);
@@ -1512,8 +1551,8 @@ List<Expression!>! decreases) {
}
}
- void RelOp(out IToken! x, out BinaryExpr.Opcode op) {
- x = Token.NoToken; op = BinaryExpr.Opcode.Add/*(dummy)*/;
+ void RelOp(out IToken/*!*/ x, out BinaryExpr.Opcode op) {
+ Contract.Ensures(Contract.ValueAtReturn(out x) != null); x = Token.NoToken; op = BinaryExpr.Opcode.Add/*(dummy)*/;
switch (la.kind) {
case 73: {
Get();
@@ -1579,8 +1618,8 @@ List<Expression!>! decreases) {
}
}
- void Factor(out Expression! e0) {
- IToken! x; Expression! e1; BinaryExpr.Opcode op;
+ void Factor(out Expression/*!*/ e0) {
+ Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expression/*!*/ e1; BinaryExpr.Opcode op;
UnaryExpression(out e0);
while (la.kind == 39 || la.kind == 84 || la.kind == 85) {
MulOp(out x, out op);
@@ -1589,8 +1628,8 @@ List<Expression!>! decreases) {
}
}
- void AddOp(out IToken! x, out BinaryExpr.Opcode op) {
- x = Token.NoToken; op=BinaryExpr.Opcode.Add/*(dummy)*/;
+ void AddOp(out IToken/*!*/ x, out BinaryExpr.Opcode op) {
+ Contract.Ensures(Contract.ValueAtReturn(out x) != null); x = Token.NoToken; op=BinaryExpr.Opcode.Add/*(dummy)*/;
if (la.kind == 82) {
Get();
x = t; op = BinaryExpr.Opcode.Add;
@@ -1600,8 +1639,8 @@ List<Expression!>! decreases) {
} else SynErr(131);
}
- void UnaryExpression(out Expression! e) {
- IToken! x; e = dummyExpr;
+ void UnaryExpression(out Expression/*!*/ e) {
+ Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x; e = dummyExpr;
if (la.kind == 83) {
Get();
x = t;
@@ -1619,8 +1658,8 @@ List<Expression!>! decreases) {
} else SynErr(132);
}
- void MulOp(out IToken! x, out BinaryExpr.Opcode op) {
- x = Token.NoToken; op = BinaryExpr.Opcode.Add/*(dummy)*/;
+ void MulOp(out IToken/*!*/ x, out BinaryExpr.Opcode op) {
+ Contract.Ensures(Contract.ValueAtReturn(out x) != null); x = Token.NoToken; op = BinaryExpr.Opcode.Add/*(dummy)*/;
if (la.kind == 39) {
Get();
x = t; op = BinaryExpr.Opcode.Mul;
@@ -1641,8 +1680,8 @@ List<Expression!>! decreases) {
} else SynErr(134);
}
- void ConstAtomExpression(out Expression! e) {
- IToken! x, dtName, id; BigInteger n; List<Expression!>! elements;
+ void ConstAtomExpression(out Expression/*!*/ e) {
+ Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x, dtName, id; BigInteger n; List<Expression/*!*/>/*!*/ elements;
e = dummyExpr;
switch (la.kind) {
@@ -1672,7 +1711,7 @@ List<Expression!>! decreases) {
Ident(out dtName);
Expect(92);
Ident(out id);
- elements = new List<Expression!>();
+ elements = new List<Expression/*!*/>();
if (la.kind == 29) {
Get();
if (StartOf(8)) {
@@ -1702,7 +1741,7 @@ List<Expression!>! decreases) {
}
case 6: {
Get();
- x = t; elements = new List<Expression!>();
+ x = t; elements = new List<Expression/*!*/>();
if (StartOf(8)) {
Expressions(elements);
}
@@ -1712,7 +1751,7 @@ List<Expression!>! decreases) {
}
case 49: {
Get();
- x = t; elements = new List<Expression!>();
+ x = t; elements = new List<Expression/*!*/>();
if (StartOf(8)) {
Expressions(elements);
}
@@ -1735,12 +1774,12 @@ List<Expression!>! decreases) {
}
- void IdentOrFuncExpression(out Expression! e) {
- IToken! id; e = dummyExpr; List<Expression!>! args;
+ void IdentOrFuncExpression(out Expression/*!*/ e) {
+ Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ id; e = dummyExpr; List<Expression/*!*/>/*!*/ args;
Ident(out id);
if (la.kind == 29) {
Get();
- args = new List<Expression!>();
+ args = new List<Expression/*!*/>();
if (StartOf(8)) {
Expressions(args);
}
@@ -1757,8 +1796,8 @@ List<Expression!>! decreases) {
}
- void ObjectExpression(out Expression! e) {
- IToken! x; e = dummyExpr;
+ void ObjectExpression(out Expression/*!*/ e) {
+ Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x; e = dummyExpr;
if (la.kind == 95) {
Get();
e = new ThisExpr(t);
@@ -1780,9 +1819,9 @@ List<Expression!>! decreases) {
} else SynErr(137);
}
- void SelectOrCallSuffix(ref Expression! e) {
- IToken! id, x; List<Expression!>! args;
- Expression e0 = null; Expression e1 = null; Expression! ee; bool anyDots = false;
+ void SelectOrCallSuffix(ref Expression/*!*/ e) {
+ Contract.Requires(e != null); Contract.Ensures(e!=null); IToken/*!*/ id, x; List<Expression/*!*/>/*!*/ args;
+ Expression e0 = null; Expression e1 = null; Expression/*!*/ ee; bool anyDots = false;
bool func = false;
if (la.kind == 92) {
@@ -1790,7 +1829,7 @@ List<Expression!>! decreases) {
Ident(out id);
if (la.kind == 29) {
Get();
- args = new List<Expression!>(); func = true;
+ args = new List<Expression/*!*/>(); func = true;
if (StartOf(8)) {
Expressions(args);
}
@@ -1827,15 +1866,15 @@ List<Expression!>! decreases) {
/* a parsing error occurred */
e0 = dummyExpr;
}
- assert !anyDots ==> e0 != null;
+ Contract.Assert(anyDots || e0 != null);
if (anyDots) {
- assert e0 != null || e1 != null;
+ Contract.Assert(e0 != null || e1 != null);
e = new SeqSelectExpr(x, false, e, e0, e1);
} else if (e1 == null) {
- assert e0 != null;
+ Contract.Assert(e0 != null);
e = new SeqSelectExpr(x, true, e, e0, null);
} else {
- assert e0 != null;
+ Contract.Assert(e0 != null);
e = new SeqUpdateExpr(x, e, e0, e1);
}
@@ -1843,15 +1882,15 @@ List<Expression!>! decreases) {
} else SynErr(139);
}
- void QuantifierGuts(out Expression! q) {
- IToken! x = Token.NoToken;
+ void QuantifierGuts(out Expression/*!*/ q) {
+ Contract.Ensures(Contract.ValueAtReturn(out q) != null); IToken/*!*/ x = Token.NoToken;
bool univ = false;
- BoundVar! bv;
- List<BoundVar!> bvars = new List<BoundVar!>();
- IToken! tok; Expr! e; ExprSeq! es;
+ BoundVar/*!*/ bv;
+ List<BoundVar/*!*/> bvars = new List<BoundVar/*!*/>();
+ IToken/*!*/ tok; Expr/*!*/ e; ExprSeq/*!*/ es;
Attributes attrs = null;
Triggers trigs = null;
- Expression! body;
+ Expression/*!*/ body;
if (la.kind == 97 || la.kind == 98) {
Forall();
@@ -1899,13 +1938,13 @@ List<Expression!>! decreases) {
}
void AttributeOrTrigger(ref Attributes attrs, ref Triggers trigs) {
- List<Expression!> es = new List<Expression!>();
+ List<Expression/*!*/> es = new List<Expression/*!*/>();
Expect(6);
if (la.kind == 19) {
AttributeBody(ref attrs);
} else if (StartOf(8)) {
- es = new List<Expression!>();
+ es = new List<Expression/*!*/>();
Expressions(es);
trigs = new Triggers(es, trigs);
} else SynErr(143);
@@ -1922,8 +1961,8 @@ List<Expression!>! decreases) {
void AttributeBody(ref Attributes attrs) {
string aName;
- List<Attributes.Argument!> aArgs = new List<Attributes.Argument!>();
- Attributes.Argument! aArg;
+ List<Attributes.Argument/*!*/> aArgs = new List<Attributes.Argument/*!*/>();
+ Attributes.Argument/*!*/ aArg;
Expect(19);
Expect(1);
@@ -1951,7 +1990,7 @@ List<Expression!>! decreases) {
Expect(0);
}
- static readonly bool[,]! set = {
+ static readonly bool[,]/*!*/ set = {
{T,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x},
{x,x,x,x, T,x,x,x, T,T,T,T, T,T,x,T, x,T,x,x, x,x,T,x, x,x,x,x, x,x,x,x, x,x,x,x, x,T,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x},
{x,x,x,x, x,x,x,x, x,T,T,T, T,x,x,T, x,T,x,x, x,x,T,x, x,x,x,x, x,x,x,x, x,x,x,x, x,T,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x},
@@ -1977,10 +2016,10 @@ List<Expression!>! decreases) {
public class Errors {
public int count = 0; // number of errors detected
- public System.IO.TextWriter! errorStream = Console.Out; // error messages go to this stream
+ public System.IO.TextWriter/*!*/ errorStream = Console.Out; // error messages go to this stream
// public string errMsgFormat = "-- line {0} col {1}: {2}"; // 0=line, 1=column, 2=text
- public string! errMsgFormat4 = "{0}({1},{2}): Error: {3}"; // 0=line, 1=column, 2=text
- public string! errMsgFormat = "-- line {0} col {1}: {2}"; // 0=line, 1=column, 2=text
+ public string/*!*/ errMsgFormat4 = "{0}({1},{2}): Error: {3}"; // 0=line, 1=column, 2=text
+ public string/*!*/ errMsgFormat = "-- line {0} col {1}: {2}"; // 0=line, 1=column, 2=text
public void SynErr (string filename, int line, int col, int n) {
string s;
@@ -2139,12 +2178,14 @@ public class Errors {
count++;
}
- public void SemErr (int line, int col, string! s) {
+ public void SemErr (int line, int col, string/*!*/ s) {
+ Contract.Requires(s != null);
errorStream.WriteLine(errMsgFormat, line, col, s);
count++;
}
- public void SemErr (string filename, int line, int col, string! s) {
+ public void SemErr (string filename, int line, int col, string/*!*/ s) {
+ Contract.Requires(s != null);
errorStream.WriteLine(errMsgFormat4, filename, line, col, s);
count++;
}
@@ -2154,7 +2195,9 @@ public class Errors {
count++;
}
- public void SemErr(IToken! tok, string! msg) { // semantic errors
+ public void SemErr(IToken/*!*/ tok, string/*!*/ msg) { // semantic errors
+ Contract.Requires(tok != null);
+ Contract.Requires(msg != null);
SemErr(tok.filename, tok.line, tok.col, msg);
}
diff --git a/Source/Dafny/Printer.cs b/Source/Dafny/Printer.cs
index c269e621..cd026393 100644
--- a/Source/Dafny/Printer.cs
+++ b/Source/Dafny/Printer.cs
@@ -6,18 +6,26 @@
using System;
using System.IO;
using System.Collections.Generic;
-using Microsoft.Contracts;
+using System.Diagnostics.Contracts;
using System.Numerics;
using Bpl = Microsoft.Boogie;
namespace Microsoft.Dafny {
class Printer {
- TextWriter! wr;
- public Printer(TextWriter! wr) {
+ TextWriter wr;
+ [ContractInvariantMethod]
+void ObjectInvariant()
+{
+ Contract.Invariant(wr!=null);
+}
+
+ public Printer(TextWriter wr) {
+ Contract.Requires(wr != null);
this.wr = wr;
}
- public void PrintProgram(Program! prog) {
+ public void PrintProgram(Program prog) {
+ Contract.Requires(prog != null);
if (Bpl.CommandLineOptions.Clo.ShowEnv != Bpl.CommandLineOptions.ShowEnvironment.Never) {
wr.WriteLine("// " + Bpl.CommandLineOptions.Clo.Version);
wr.WriteLine("// " + Bpl.CommandLineOptions.Clo.Environment);
@@ -49,9 +57,11 @@ namespace Microsoft.Dafny {
}
}
- public void PrintTopLevelDecls(List<TopLevelDecl!>! classes, int indent) {
+ public void PrintTopLevelDecls(List<TopLevelDecl> classes, int indent) {
+ Contract.Requires(classes!= null);
int i = 0;
foreach (TopLevelDecl d in classes) {
+ Contract.Assert(d != null);
if (d is DatatypeDecl) {
if (i++ != 0) { wr.WriteLine(); }
PrintDatatype((DatatypeDecl)d, indent);
@@ -70,7 +80,8 @@ namespace Microsoft.Dafny {
}
}
- public void PrintClass(ClassDecl! c, int indent) {
+ public void PrintClass(ClassDecl c, int indent) {
+ Contract.Requires(c != null);
Indent(indent);
PrintClassMethodHelper("class", c.Attributes, c.Name, c.TypeArgs);
if (c is ClassRefinementDecl) {
@@ -87,9 +98,11 @@ namespace Microsoft.Dafny {
}
}
- public void PrintClass_Members(ClassDecl! c, int indent)
- requires c.Members.Count != 0;
+ public void PrintClass_Members(ClassDecl c, int indent)
{
+ Contract.Requires(c != null);
+ Contract.Requires( c.Members.Count != 0);
+
int state = 0; // 0 - no members yet; 1 - previous member was a field; 2 - previous member was non-field
foreach (MemberDecl m in c.Members) {
if (m is Method) {
@@ -107,14 +120,17 @@ namespace Microsoft.Dafny {
} else if (m is CouplingInvariant) {
wr.WriteLine();
PrintCouplingInvariant((CouplingInvariant)m, indent);
- state = 2;
+ state = 2;
} else {
- assert false; // unexpected member
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected member
}
}
}
- void PrintClassMethodHelper(string! kind, Attributes attrs, string! name, List<TypeParameter!>! typeArgs) {
+ void PrintClassMethodHelper(string kind, Attributes attrs, string name, List<TypeParameter> typeArgs) {
+ Contract.Requires(kind != null);
+ Contract.Requires(name != null);
+ Contract.Requires(typeArgs != null);
if (kind.Length != 0) {
wr.Write("{0} ", kind);
}
@@ -124,6 +140,7 @@ namespace Microsoft.Dafny {
wr.Write("<");
string sep = "";
foreach (TypeParameter tp in typeArgs) {
+ Contract.Assert(tp != null);
wr.Write("{0}{1}", sep, tp.Name);
sep = ", ";
}
@@ -131,7 +148,8 @@ namespace Microsoft.Dafny {
}
}
- public void PrintDatatype(DatatypeDecl! dt, int indent) {
+ public void PrintDatatype(DatatypeDecl dt, int indent) {
+ Contract.Requires(dt != null);
Indent(indent);
PrintClassMethodHelper("datatype", dt.Attributes, dt.Name, dt.TypeArgs);
if (dt.Ctors.Count == 0) {
@@ -156,21 +174,24 @@ namespace Microsoft.Dafny {
}
}
- public void PrintAttributeArgs(List<Attributes.Argument!>! args) {
+ public void PrintAttributeArgs(List<Attributes.Argument> args) {
+ Contract.Requires(args != null);
string prefix = " ";
foreach (Attributes.Argument arg in args) {
+ Contract.Assert(arg != null);
wr.Write(prefix);
prefix = ", ";
if (arg.S != null) {
wr.Write("\"{0}\"", arg.S);
} else {
- assert arg.E != null;
+ Contract.Assert( arg.E != null);
PrintExpression(arg.E);
}
}
}
- public void PrintField(Field! field, int indent) {
+ public void PrintField(Field field, int indent) {
+ Contract.Requires(field != null);
Indent(indent);
if (field.IsGhost) {
wr.Write("ghost ");
@@ -182,7 +203,8 @@ namespace Microsoft.Dafny {
wr.WriteLine(";");
}
- public void PrintCouplingInvariant(CouplingInvariant! inv, int indent) {
+ public void PrintCouplingInvariant(CouplingInvariant inv, int indent) {
+ Contract.Requires(inv != null);
Indent(indent);
wr.Write("replaces");
string sep = " ";
@@ -193,10 +215,11 @@ namespace Microsoft.Dafny {
}
wr.Write(" by ");
PrintExpression(inv.Expr);
- wr.WriteLine(";");
+ wr.WriteLine(";");
}
- public void PrintFunction(Function! f, int indent) {
+ public void PrintFunction(Function f, int indent) {
+ Contract.Requires(f != null);
Indent(indent);
string k = "function";
if (f.IsUnlimited) { k = "unlimited " + k; }
@@ -221,7 +244,8 @@ namespace Microsoft.Dafny {
}
}
- public void PrintCtor(DatatypeCtor! ctor, int indent) {
+ public void PrintCtor(DatatypeCtor ctor, int indent) {
+ Contract.Requires(ctor != null);
Indent(indent);
PrintClassMethodHelper("", ctor.Attributes, ctor.Name, ctor.TypeArgs);
if (ctor.Formals.Count != 0) {
@@ -233,17 +257,18 @@ namespace Microsoft.Dafny {
// ----------------------------- PrintMethod -----------------------------
const int IndentAmount = 2;
- const string! BunchaSpaces = " ";
+ const string BunchaSpaces = " ";
void Indent(int amount)
- requires 0 <= amount;
- {
+ { Contract.Requires( 0 <= amount);
+
while (0 < amount) {
wr.Write(BunchaSpaces.Substring(0, amount));
amount -= BunchaSpaces.Length;
}
}
- public void PrintMethod(Method! method, int indent) {
+ public void PrintMethod(Method method, int indent) {
+ Contract.Requires(method != null);
Indent(indent);
string k = method is MethodRefinement ? "refines" : "method";
if (method.IsStatic) { k = "static " + k; }
@@ -262,7 +287,7 @@ namespace Microsoft.Dafny {
}
wr.WriteLine(method.Body == null ? ";" : "");
- int ind = indent + IndentAmount;
+ int ind = indent + IndentAmount;
PrintSpec("requires", method.Req, ind);
PrintFrameSpecLine("modifies", method.Mod, ind);
PrintSpec("ensures", method.Ens, ind);
@@ -275,10 +300,12 @@ namespace Microsoft.Dafny {
}
}
- void PrintFormals(List<Formal!>! ff) {
+ void PrintFormals(List<Formal> ff) {
+ Contract.Requires(ff!=null);
wr.Write("(");
string sep = "";
foreach (Formal f in ff) {
+ Contract.Assert(f != null);
wr.Write(sep);
sep = ", ";
PrintFormal(f);
@@ -286,7 +313,8 @@ namespace Microsoft.Dafny {
wr.Write(")");
}
- void PrintFormal(Formal! f) {
+ void PrintFormal(Formal f) {
+ Contract.Requires(f != null);
if (f.IsGhost) {
wr.Write("ghost ");
}
@@ -296,8 +324,11 @@ namespace Microsoft.Dafny {
PrintType(f.Type);
}
- void PrintSpec(string! kind, List<Expression!>! ee, int indent) {
+ void PrintSpec(string kind, List<Expression> ee, int indent) {
+ Contract.Requires(kind != null);
+ Contract.Requires(ee != null);
foreach (Expression e in ee) {
+ Contract.Assert(e != null);
Indent(indent);
wr.Write("{0} ", kind);
PrintExpression(e);
@@ -305,7 +336,9 @@ namespace Microsoft.Dafny {
}
}
- void PrintSpecLine(string! kind, List<Expression!>! ee, int indent) {
+ void PrintSpecLine(string kind, List<Expression/*!*/>/*!*/ ee, int indent) {
+ Contract.Requires(ee != null);
+ Contract.Requires(kind!=null);
if (ee.Count != 0) {
Indent(indent);
wr.Write("{0} ", kind);
@@ -314,7 +347,9 @@ namespace Microsoft.Dafny {
}
}
- void PrintFrameSpecLine(string! kind, List<FrameExpression!>! ee, int indent) {
+ void PrintFrameSpecLine(string kind, List<FrameExpression/*!*/>/*!*/ ee, int indent) {
+ Contract.Requires(kind != null);
+ Contract.Requires(cce.NonNullElements(ee));
if (ee.Count != 0) {
Indent(indent);
wr.Write("{0} ", kind);
@@ -323,8 +358,11 @@ namespace Microsoft.Dafny {
}
}
- void PrintSpec(string! kind, List<MaybeFreeExpression!>! ee, int indent) {
+ void PrintSpec(string kind, List<MaybeFreeExpression> ee, int indent) {
+ Contract.Requires(kind != null);
+ Contract.Requires(ee != null);
foreach (MaybeFreeExpression e in ee) {
+ Contract.Assert(e != null);
Indent(indent);
wr.Write("{0}{1} ", e.IsFree ? "free " : "", kind);
PrintExpression(e.E);
@@ -334,11 +372,14 @@ namespace Microsoft.Dafny {
// ----------------------------- PrintType -----------------------------
- public void PrintType(Type! ty) {
+ public void PrintType(Type ty) {
+ Contract.Requires(ty != null);
wr.Write(ty.ToString());
}
- public void PrintType(string! prefix, Type! ty) {
+ public void PrintType(string prefix, Type ty) {
+ Contract.Requires(prefix != null);
+ Contract.Requires(ty != null);
string s = ty.ToString();
if (s != "?") {
wr.Write("{0}{1}", prefix, s);
@@ -352,7 +393,8 @@ namespace Microsoft.Dafny {
/// If the statement requires several lines, subsequent lines are indented at "indent".
/// No newline is printed after the statement.
/// </summary>
- public void PrintStatement(Statement! stmt, int indent) {
+ public void PrintStatement(Statement stmt, int indent) {
+ Contract.Requires(stmt != null);
if (stmt is AssertStmt) {
wr.Write("assert ");
PrintExpression(((AssertStmt)stmt).Expr);
@@ -524,11 +566,12 @@ namespace Microsoft.Dafny {
wr.WriteLine("}");
} else {
- assert false; // unexpected statement
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected statement
}
}
- void PrintDeterminedRhs(DeterminedAssignmentRhs! rhs) {
+ void PrintDeterminedRhs(DeterminedAssignmentRhs rhs) {
+ Contract.Requires(rhs != null);
if (rhs is ExprRhs) {
PrintExpression(((ExprRhs)rhs).Expr);
} else if (rhs is TypeRhs) {
@@ -541,7 +584,7 @@ namespace Microsoft.Dafny {
wr.Write("]");
}
} else {
- assert false; // unexpected RHS
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected RHS
}
}
@@ -555,7 +598,8 @@ namespace Microsoft.Dafny {
// ----------------------------- PrintExpression -----------------------------
- public void PrintExtendedExpr(Expression! expr, int indent) {
+ public void PrintExtendedExpr(Expression expr, int indent) {
+ Contract.Requires(expr != null);
Indent(indent);
if (expr is ITEExpr) {
while (true) {
@@ -599,23 +643,27 @@ namespace Microsoft.Dafny {
}
}
- public void PrintExpression(Expression! expr) {
+ public void PrintExpression(Expression expr) {
+ Contract.Requires(expr != null);
PrintExpr(expr, 0, false, -1);
}
/// <summary>
/// An indent of -1 means print the entire expression on one line.
/// </summary>
- public void PrintExpression(Expression! expr, int indent) {
+ public void PrintExpression(Expression expr, int indent) {
+ Contract.Requires(expr != null);
PrintExpr(expr, 0, false, indent);
}
/// <summary>
/// An indent of -1 means print the entire expression on one line.
/// </summary>
- void PrintExpr(Expression! expr, int contextBindingStrength, bool fragileContext, int indent)
- requires -1 <= indent;
+ void PrintExpr(Expression expr, int contextBindingStrength, bool fragileContext, int indent)
{
+ Contract.Requires( -1 <= indent);
+
+ Contract.Requires(expr != null);
if (expr is LiteralExpr) {
LiteralExpr e = (LiteralExpr)expr;
if (e.Value == null) {
@@ -674,7 +722,7 @@ namespace Microsoft.Dafny {
PrintExpr(e.Seq, 0x00, false, indent); // BOGUS: fix me
wr.Write("[");
if (e.SelectOne) {
- assert e.E0 != null;
+ Contract.Assert( e.E0 != null);
PrintExpression(e.E0);
} else {
if (e.E0 != null) {
@@ -748,7 +796,7 @@ namespace Microsoft.Dafny {
case UnaryExpr.Opcode.Not:
op = "!"; opBindingStrength = 0x60; break;
default:
- assert false; // unexpected unary opcode
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected unary opcode
}
bool parensNeeded = opBindingStrength < contextBindingStrength ||
(fragileContext && opBindingStrength == contextBindingStrength);
@@ -795,7 +843,7 @@ namespace Microsoft.Dafny {
case BinaryExpr.Opcode.Iff:
opBindingStrength = 0x08; break;
default:
- assert false; // unexpected binary operator
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected binary operator
}
int opBS = opBindingStrength & 0xF8;
int ctxtBS = contextBindingStrength & 0xF8;
@@ -864,9 +912,9 @@ namespace Microsoft.Dafny {
if (parensNeeded) { wr.Write(")"); }
} else if (expr is MatchExpr) {
- assert false; // MatchExpr is an extended expression and should be printed only using PrintExtendedExpr
+ Contract.Assert(false); throw new cce.UnreachableException(); // MatchExpr is an extended expression and should be printed only using PrintExtendedExpr
} else {
- assert false; // unexpected expression
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected expression
}
}
@@ -880,18 +928,22 @@ namespace Microsoft.Dafny {
}
}
- void PrintExpressionList(List<Expression!>! exprs) {
+ void PrintExpressionList(List<Expression> exprs) {
+ Contract.Requires(exprs != null);
string sep = "";
foreach (Expression e in exprs) {
+ Contract.Assert(e != null);
wr.Write(sep);
sep = ", ";
PrintExpression(e);
}
}
-
- void PrintFrameExpressionList(List<FrameExpression!>! fexprs) {
+
+ void PrintFrameExpressionList(List<FrameExpression/*!*/>/*!*/ fexprs) {
+ Contract.Requires(fexprs != null);
string sep = "";
foreach (FrameExpression fe in fexprs) {
+ Contract.Assert(fe != null);
wr.Write(sep);
sep = ", ";
PrintExpression(fe.E);
diff --git a/Source/Dafny/Resolver.cs b/Source/Dafny/Resolver.cs
index a216682c..64a23393 100644
--- a/Source/Dafny/Resolver.cs
+++ b/Source/Dafny/Resolver.cs
@@ -6,13 +6,15 @@
using System;
using System.Collections.Generic;
using System.Numerics;
-using Microsoft.Contracts;
+using System.Diagnostics.Contracts;
using Microsoft.Boogie;
namespace Microsoft.Dafny {
public class Resolver {
public int ErrorCount = 0;
- void Error(IToken! tok, string! msg, params object[] args) {
+ void Error(IToken tok, string msg, params object[] args) {
+ Contract.Requires(tok != null);
+ Contract.Requires(msg != null);
ConsoleColor col = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("{0}({1},{2}): Error: {3}",
@@ -21,29 +23,48 @@ namespace Microsoft.Dafny {
Console.ForegroundColor = col;
ErrorCount++;
}
- void Error(Declaration! d, string! msg, params object[] args) {
+ void Error(Declaration d, string msg, params object[] args) {
+ Contract.Requires(d != null);
+ Contract.Requires(msg != null);
Error(d.tok, msg, args);
}
- void Error(Statement! s, string! msg, params object[] args) {
+ void Error(Statement s, string msg, params object[] args) {
+ Contract.Requires(s != null);
+ Contract.Requires(msg != null);
Error(s.Tok, msg, args);
}
- void Error(NonglobalVariable! v, string! msg, params object[] args) {
+ void Error(NonglobalVariable v, string msg, params object[] args) {
+ Contract.Requires(v != null);
+ Contract.Requires(msg != null);
Error(v.tok, msg, args);
}
- void Error(Expression! e, string! msg, params object[] args) {
+ void Error(Expression e, string msg, params object[] args) {
+ Contract.Requires(e != null);
+ Contract.Requires(msg != null);
Error(e.tok, msg, args);
}
- readonly Dictionary<string!,TopLevelDecl!>! classes = new Dictionary<string!,TopLevelDecl!>();
- readonly Dictionary<ClassDecl!,Dictionary<string!,MemberDecl!>!>! classMembers = new Dictionary<ClassDecl!,Dictionary<string!,MemberDecl!>!>();
- readonly Dictionary<DatatypeDecl!,Dictionary<string!,DatatypeCtor!>!>! datatypeCtors = new Dictionary<DatatypeDecl!,Dictionary<string!,DatatypeCtor!>!>();
- readonly Graph<ModuleDecl!>! importGraph = new Graph<ModuleDecl!>();
+ readonly Dictionary<string/*!*/,TopLevelDecl/*!*/>/*!*/ classes = new Dictionary<string/*!*/,TopLevelDecl/*!*/>();
+ readonly Dictionary<ClassDecl/*!*/,Dictionary<string/*!*/,MemberDecl/*!*/>/*!*/>/*!*/ classMembers = new Dictionary<ClassDecl/*!*/,Dictionary<string/*!*/,MemberDecl/*!*/>/*!*/>();
+ readonly Dictionary<DatatypeDecl/*!*/,Dictionary<string/*!*/,DatatypeCtor/*!*/>/*!*/>/*!*/ datatypeCtors = new Dictionary<DatatypeDecl/*!*/,Dictionary<string/*!*/,DatatypeCtor/*!*/>/*!*/>();
+ readonly Graph<ModuleDecl/*!*/>/*!*/ importGraph = new Graph<ModuleDecl/*!*/>();
+ [ContractInvariantMethod]
+void ObjectInvariant()
+{
+ Contract.Invariant(cce.NonNullElements(classes));
+ Contract.Invariant(cce.NonNullElements(importGraph));
+ Contract.Invariant(cce.NonNullElements(classMembers) && Contract.ForAll(classMembers.Values, v=> cce.NonNullElements(v)));
+ Contract.Invariant(cce.NonNullElements(datatypeCtors)&&Contract.ForAll(datatypeCtors.Values, v=> cce.NonNullElements(v)));
+
+}
+
bool checkRefinements = true; // used to indicate a cycle in refinements
- public void ResolveProgram(Program! prog) {
+ public void ResolveProgram(Program prog) {
+ Contract.Requires(prog != null);
// register modules
- Dictionary<string,ModuleDecl!> modules = new Dictionary<string,ModuleDecl!>();
+ Dictionary<string,ModuleDecl> modules = new Dictionary<string,ModuleDecl>();
foreach (ModuleDecl m in prog.Modules) {
if (modules.ContainsKey(m.Name)) {
Error(m, "Duplicate module name: {0}", m.Name);
@@ -52,7 +73,7 @@ namespace Microsoft.Dafny {
}
}
// resolve imports and register top-level declarations
- Graph<TopLevelDecl!>! refines = new Graph<TopLevelDecl!>();
+ Graph<TopLevelDecl> refines = new Graph<TopLevelDecl>();
foreach (ModuleDecl m in prog.Modules) {
importGraph.AddVertex(m);
foreach (string imp in m.Imports) {
@@ -62,15 +83,15 @@ namespace Microsoft.Dafny {
} else if (other == m) {
Error(m, "module must not import itself: {0}", imp);
} else {
- assert other != null; // follows from postcondition of TryGetValue
+ Contract.Assert( other != null); // follows from postcondition of TryGetValue
importGraph.AddEdge(m, other);
}
}
RegisterTopLevelDecls(m.TopLevelDecls);
- foreach (TopLevelDecl! decl in m.TopLevelDecls) refines.AddVertex(decl);
+ foreach (TopLevelDecl decl in m.TopLevelDecls) {Contract.Assert(decl != null); refines.AddVertex(decl);}
}
// check for cycles in the import graph
- List<ModuleDecl!> cycle = importGraph.TryFindCycle();
+ List<ModuleDecl> cycle = importGraph.TryFindCycle();
if (cycle != null) {
string cy = "";
string sep = "";
@@ -81,8 +102,8 @@ namespace Microsoft.Dafny {
Error(cycle[0], "import graph contains a cycle: {0}", cy);
} else {
// fill in module heights
- List<ModuleDecl!> mm = importGraph.TopologicallySortedComponents();
- assert mm.Count == prog.Modules.Count; // follows from the fact that there are no cycles
+ List<ModuleDecl> mm = importGraph.TopologicallySortedComponents();
+ Contract.Assert( mm.Count == prog.Modules.Count); // follows from the fact that there are no cycles
int h = 0;
foreach (ModuleDecl m in mm) {
m.Height = h;
@@ -94,13 +115,13 @@ namespace Microsoft.Dafny {
foreach (ModuleDecl m in prog.Modules)
foreach (TopLevelDecl decl in m.TopLevelDecls)
if (decl is ClassRefinementDecl) {
- ClassRefinementDecl! rdecl = (ClassRefinementDecl) decl;
- ResolveTopLevelRefinement(rdecl);
+ ClassRefinementDecl rdecl = (ClassRefinementDecl) decl;
+ ResolveTopLevelRefinement(rdecl);
if (rdecl.Refined != null) refines.AddEdge(rdecl, rdecl.Refined);
}
// attempt finding refinement cycles
- List<TopLevelDecl!> refinesCycle = refines.TryFindCycle();
+ List<TopLevelDecl> refinesCycle = refines.TryFindCycle();
if (refinesCycle != null) {
string cy = "";
string sep = "";
@@ -113,7 +134,7 @@ namespace Microsoft.Dafny {
}
// resolve top-level declarations
- Graph<DatatypeDecl!> datatypeDependencies = new Graph<DatatypeDecl!>();
+ Graph<DatatypeDecl> datatypeDependencies = new Graph<DatatypeDecl>();
foreach (ModuleDecl m in prog.Modules) {
ResolveTopLevelDecls_Signatures(m.TopLevelDecls, datatypeDependencies);
}
@@ -140,8 +161,10 @@ namespace Microsoft.Dafny {
}
}
- public void RegisterTopLevelDecls(List<TopLevelDecl!>! declarations) {
+ public void RegisterTopLevelDecls(List<TopLevelDecl> declarations) {
+ Contract.Requires(declarations != null);
foreach (TopLevelDecl d in declarations) {
+ Contract.Assert(d != null);
// register the class/datatype name
if (classes.ContainsKey(d.Name)) {
Error(d, "Duplicate name of top-level declaration: {0}", d.Name);
@@ -153,7 +176,7 @@ namespace Microsoft.Dafny {
ClassDecl cl = (ClassDecl)d;
// register the names of the class members
- Dictionary<string!,MemberDecl!> members = new Dictionary<string!,MemberDecl!>();
+ Dictionary<string,MemberDecl> members = new Dictionary<string,MemberDecl>();
classMembers.Add(cl, members);
foreach (MemberDecl m in cl.Members) {
@@ -167,7 +190,7 @@ namespace Microsoft.Dafny {
DatatypeDecl dt = (DatatypeDecl)d;
// register the names of the constructors
- Dictionary<string!,DatatypeCtor!> ctors = new Dictionary<string!,DatatypeCtor!>();
+ Dictionary<string,DatatypeCtor> ctors = new Dictionary<string,DatatypeCtor>();
datatypeCtors.Add(dt, ctors);
foreach (DatatypeCtor ctor in dt.Ctors) {
@@ -181,22 +204,26 @@ namespace Microsoft.Dafny {
}
}
- public void ResolveTopLevelRefinement(ClassRefinementDecl! decl) {
+ public void ResolveTopLevelRefinement(ClassRefinementDecl decl) {
+ Contract.Requires(decl != null);
if (!classes.ContainsKey(decl.RefinedClass.val)) {
Error(decl.RefinedClass, "Refined class declaration is missing: {0}", decl.RefinedClass.val);
} else {
- TopLevelDecl! a = classes[decl.RefinedClass.val];
+ TopLevelDecl a = classes[decl.RefinedClass.val];
if (!(a is ClassDecl)) {
Error(a, "Refined declaration is not a class declaration: {0}", a.Name);
return;
}
- decl.Refined = (ClassDecl!) a;
+ decl.Refined = cce.NonNull((ClassDecl) a);
// TODO: copy over remaining members of a
}
}
- public void ResolveTopLevelDecls_Signatures(List<TopLevelDecl!>! declarations, Graph<DatatypeDecl!>! datatypeDependencies) {
+ public void ResolveTopLevelDecls_Signatures(List<TopLevelDecl/*!*/>/*!*/ declarations, Graph<DatatypeDecl/*!*/>/*!*/ datatypeDependencies) {
+ Contract.Requires(declarations != null);
+ Contract.Requires(cce.NonNullElements(datatypeDependencies));
foreach (TopLevelDecl d in declarations) {
+ Contract.Assert(d != null);
allTypeParameters.PushMarker();
ResolveTypeParameters(d.TypeArgs, true, d);
if (d is ClassDecl) {
@@ -208,8 +235,11 @@ namespace Microsoft.Dafny {
}
}
- public void ResolveTopLevelDecls_Meat(List<TopLevelDecl!>! declarations, Graph<DatatypeDecl!>! datatypeDependencies) {
+ public void ResolveTopLevelDecls_Meat(List<TopLevelDecl/*!*/>/*!*/ declarations, Graph<DatatypeDecl/*!*/>/*!*/ datatypeDependencies) {
+ Contract.Requires(declarations != null);
+ Contract.Requires(cce.NonNullElements(datatypeDependencies));
foreach (TopLevelDecl d in declarations) {
+ Contract.Assert(d != null);
allTypeParameters.PushMarker();
ResolveTypeParameters(d.TypeArgs, false, d);
if (d is ClassDecl) {
@@ -227,17 +257,19 @@ namespace Microsoft.Dafny {
ClassDecl currentClass;
Function currentFunction;
- readonly Scope<TypeParameter>! allTypeParameters = new Scope<TypeParameter>();
- readonly Scope<IVariable>! scope = new Scope<IVariable>();
- readonly Scope<Statement>! labeledStatements = new Scope<Statement>();
+ readonly Scope<TypeParameter>/*!*/ allTypeParameters = new Scope<TypeParameter>();
+ readonly Scope<IVariable>/*!*/ scope = new Scope<IVariable>();
+ readonly Scope<Statement>/*!*/ labeledStatements = new Scope<Statement>();
/// <summary>
/// Assumes type parameters have already been pushed
/// </summary>
- void ResolveClassMemberTypes(ClassDecl! cl)
- requires currentClass == null;
- ensures currentClass == null;
+ void ResolveClassMemberTypes(ClassDecl/*!*/ cl)
{
+ Contract.Requires(cl != null);
+ Contract.Requires( currentClass == null);
+ Contract.Ensures( currentClass == null);
+
currentClass = cl;
foreach (MemberDecl member in cl.Members) {
member.EnclosingClass = cl;
@@ -261,24 +293,24 @@ namespace Microsoft.Dafny {
} else if (member is CouplingInvariant) {
CouplingInvariant inv = (CouplingInvariant)member;
if (currentClass is ClassRefinementDecl) {
- ClassDecl refined = ((ClassRefinementDecl)currentClass).Refined;
+ ClassDecl refined = ((ClassRefinementDecl)currentClass).Refined;
if (refined != null) {
- assert classMembers.ContainsKey(refined);
- Dictionary<string!,MemberDecl!> members = classMembers[refined];
+ Contract.Assert( classMembers.ContainsKey(refined));
+ Dictionary<string,MemberDecl> members = classMembers[refined];
// resolve abstracted fields in the refined class
- List<Field!> fields = new List<Field!>();
+ List<Field> fields = new List<Field>();
foreach (IToken tok in inv.Toks) {
if (!members.ContainsKey(tok.val))
- Error(tok, "Refined class does not declare a field: {0}", tok.val);
+ Error(tok, "Refined class does not declare a field: {0}", tok.val);
else {
- MemberDecl! field = members[tok.val];
+ MemberDecl field = members[tok.val];
if (!(field is Field))
Error(tok, "Coupling invariant refers to a non-field member: {0}", tok.val);
- else if (fields.Contains((Field!)field))
- Error(tok, "Duplicate reference to a field in the refined class: {0}", tok.val);
+ else if (fields.Contains(cce.NonNull((Field)field)))
+ Error(tok, "Duplicate reference to a field in the refined class: {0}", tok.val);
else
- fields.Add((Field!)field);
+ fields.Add(cce.NonNull((Field)field));
}
}
inv.Refined = fields;
@@ -288,13 +320,13 @@ namespace Microsoft.Dafny {
Error(member, "Coupling invariants can only be declared in refinement classes");
}
} else {
- assert false; // unexpected member type
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected member type
}
if (currentClass is ClassRefinementDecl) {
- ClassDecl refined = ((ClassRefinementDecl)currentClass).Refined;
+ ClassDecl refined = ((ClassRefinementDecl)currentClass).Refined;
if (refined != null) {
- assert classMembers.ContainsKey(refined);
+ Contract.Assert( classMembers.ContainsKey(refined));
// there is a member with the same name in refined class if and only if the member is a refined method
if ((member is MethodRefinement) != (classMembers[refined].ContainsKey(member.Name)))
@@ -308,10 +340,12 @@ namespace Microsoft.Dafny {
/// <summary>
/// Assumes type parameters have already been pushed, and that all types in class members have been resolved
/// </summary>
- void ResolveClassMemberBodies(ClassDecl! cl)
- requires currentClass == null;
- ensures currentClass == null;
+ void ResolveClassMemberBodies(ClassDecl cl)
{
+ Contract.Requires(cl != null);
+ Contract.Requires( currentClass == null);
+ Contract.Ensures( currentClass == null);
+
ResolveAttributes(cl.Attributes, false);
currentClass = cl;
foreach (MemberDecl member in cl.Members) {
@@ -345,7 +379,7 @@ namespace Microsoft.Dafny {
if (mf.Ins.Count != mf.Refined.Ins.Count)
Error(mf, "Different number of input variables");
if (mf.Outs.Count != mf.Refined.Outs.Count)
- Error(mf, "Different number of output variables");
+ Error(mf, "Different number of output variables");
if (mf.IsStatic || mf.Refined.IsStatic)
Error(mf, "Refined methods cannot be static");
} else {
@@ -353,18 +387,20 @@ namespace Microsoft.Dafny {
}
}
} else {
- Error(member, "Refinement methods can only be declared in refinement classes: {0}", member.Name);
+ Error(member, "Refinement methods can only be declared in refinement classes: {0}", member.Name);
}
}
} else if (member is CouplingInvariant) {
CouplingInvariant inv = (CouplingInvariant)member;
if (inv.Refined != null) {
- inv.Formals = new List<Formal!>();
+ inv.Formals = new List<Formal>();
scope.PushMarker();
for (int i = 0; i < inv.Refined.Count; i++) {
- Field! field = inv.Refined[i];
- Formal! formal = new Formal(inv.Toks[i], field.Name, field.Type, true, field.IsGhost);
+ Field field = inv.Refined[i];
+ Contract.Assert(field != null);
+ Formal formal = new Formal(inv.Toks[i], field.Name, field.Type, true, field.IsGhost);
+ Contract.Assert(formal != null);
inv.Formals.Add(formal);
scope.Push(inv.Toks[i].val, formal);
}
@@ -372,7 +408,7 @@ namespace Microsoft.Dafny {
scope.PopMarker();
}
} else {
- assert false; // unexpected member type
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected member type
}
}
currentClass = null;
@@ -381,9 +417,12 @@ namespace Microsoft.Dafny {
/// <summary>
/// Assumes type parameters have already been pushed
/// </summary>
- void ResolveCtorTypes(DatatypeDecl! dt, Graph<DatatypeDecl!>! dependencies)
+ void ResolveCtorTypes(DatatypeDecl/*!*/ dt, Graph<DatatypeDecl/*!*/>/*!*/ dependencies)
{
+ Contract.Requires(dt != null);
+ Contract.Requires(cce.NonNullElements(dependencies));
foreach (DatatypeCtor ctor in dt.Ctors) {
+
ctor.EnclosingDatatype = dt;
allTypeParameters.PushMarker();
@@ -406,10 +445,12 @@ namespace Microsoft.Dafny {
/// The algorithm used here is quadratic in the number of datatypes in the SCC. Since that number is
/// deemed to be rather small, this seems okay.
/// </summary>
- void SccStratosphereCheck(DatatypeDecl! startingPoint, Graph<DatatypeDecl!>! dependencies)
+ void SccStratosphereCheck(DatatypeDecl startingPoint, Graph<DatatypeDecl/*!*/>/*!*/ dependencies)
{
- List<DatatypeDecl!> scc = dependencies.GetSCC(startingPoint);
- List<DatatypeDecl!>! cleared = new List<DatatypeDecl!>(); // this is really a set
+ Contract.Requires(startingPoint != null);
+ Contract.Requires(cce.NonNullElements(dependencies));
+ List<DatatypeDecl> scc = dependencies.GetSCC(startingPoint);
+ List<DatatypeDecl> cleared = new List<DatatypeDecl>(); // this is really a set
while (true) {
int clearedThisRound = 0;
foreach (DatatypeDecl dt in scc) {
@@ -443,7 +484,10 @@ namespace Microsoft.Dafny {
/// go to a different SCC or to a type in 'goodOnes'.
/// Returns 'true' and sets dt.DefaultCtor if that is the case.
/// </summary>
- bool StratosphereCheck(DatatypeDecl! dt, Graph<DatatypeDecl!>! dependencies, List<DatatypeDecl!>! goodOnes) {
+ bool StratosphereCheck(DatatypeDecl dt, Graph<DatatypeDecl/*!*/>/*!*/ dependencies, List<DatatypeDecl/*!*/>/*!*/ goodOnes) {
+ Contract.Requires(dt != null);
+ Contract.Requires(cce.NonNullElements(dependencies));
+ Contract.Requires(cce.NonNullElements(goodOnes));
// Stated differently, check that there is some constuctor where no argument type goes to the same stratum.
DatatypeDecl stratumRepresentative = dependencies.GetSCCRepresentative(dt);
foreach (DatatypeCtor ctor in dt.Ctors) {
@@ -477,8 +521,10 @@ namespace Microsoft.Dafny {
}
}
- void ResolveAttributeArgs(List<Attributes.Argument!>! args, bool twoState, bool specContext) {
+ void ResolveAttributeArgs(List<Attributes.Argument/*!*/>/*!*/ args, bool twoState, bool specContext) {
+ Contract.Requires(args != null);
foreach (Attributes.Argument aa in args) {
+ Contract.Assert(aa != null);
if (aa.E != null) {
ResolveExpression(aa.E, twoState, specContext);
}
@@ -494,7 +540,10 @@ namespace Microsoft.Dafny {
}
}
- void ResolveTypeParameters(List<TypeParameter!>! tparams, bool emitErrors, TypeParameter.ParentType! parent) {
+ void ResolveTypeParameters(List<TypeParameter/*!*/>/*!*/ tparams, bool emitErrors, TypeParameter.ParentType/*!*/ parent) {
+
+ Contract.Requires(tparams != null);
+ Contract.Requires(parent != null);
// push type arguments of the refined class
if (checkRefinements && parent is ClassRefinementDecl) {
ClassDecl refined = ((ClassRefinementDecl)parent).Refined;
@@ -504,6 +553,7 @@ namespace Microsoft.Dafny {
// push non-duplicated type parameter names
foreach (TypeParameter tp in tparams) {
+ Contract.Assert(tp != null);
if (emitErrors) {
// we're seeing this TypeParameter for the first time
tp.Parent = parent;
@@ -517,7 +567,8 @@ namespace Microsoft.Dafny {
/// <summary>
/// Assumes type parameters have already been pushed
/// </summary>
- void ResolveFunctionSignature(Function! f) {
+ void ResolveFunctionSignature(Function f) {
+ Contract.Requires(f != null);
scope.PushMarker();
foreach (Formal p in f.Formals) {
if (!scope.Push(p.Name, p)) {
@@ -532,10 +583,10 @@ namespace Microsoft.Dafny {
/// <summary>
/// Assumes type parameters have already been pushed
/// </summary>
- void ResolveFunction(Function! f)
- requires currentFunction == null;
- ensures currentFunction == null;
- {
+ void ResolveFunction(Function f){
+ Contract.Requires(f != null);
+ Contract.Requires( currentFunction == null);
+ Contract.Ensures( currentFunction == null);
scope.PushMarker();
currentFunction = f;
if (f.IsStatic) {
@@ -546,7 +597,7 @@ namespace Microsoft.Dafny {
}
foreach (Expression r in f.Req) {
ResolveExpression(r, false, true);
- assert r.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( r.Type != null); // follows from postcondition of ResolveExpression
if (!UnifyTypes(r.Type, Type.Bool)) {
Error(r, "Precondition must be a boolean (got {0})", r.Type);
}
@@ -560,7 +611,7 @@ namespace Microsoft.Dafny {
}
if (f.Body != null) {
ResolveExpression(f.Body, false, f.IsGhost);
- assert f.Body.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( f.Body.Type != null); // follows from postcondition of ResolveExpression
if (!UnifyTypes(f.Body.Type, f.ResultType)) {
Error(f, "Function body type mismatch (expected {0}, got {1})", f.ResultType, f.Body.Type);
}
@@ -569,10 +620,12 @@ namespace Microsoft.Dafny {
scope.PopMarker();
}
- void ResolveFrameExpression(FrameExpression! fe, string! kind) {
+ void ResolveFrameExpression(FrameExpression fe, string kind) {
+ Contract.Requires(fe != null);
+ Contract.Requires(kind != null);
ResolveExpression(fe.E, false, true);
Type t = fe.E.Type;
- assert t != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( t != null); // follows from postcondition of ResolveExpression
if (t is CollectionType) {
t = ((CollectionType)t).Arg;
}
@@ -589,9 +642,9 @@ namespace Microsoft.Dafny {
if (member == null) {
// error has already been reported by ResolveMember
} else if (!(member is Field)) {
- Error(fe.E, "member {0} in class {1} does not refer to a field", fe.FieldName, ((!)ctype).Name);
+ Error(fe.E, "member {0} in class {1} does not refer to a field", fe.FieldName, cce.NonNull(ctype).Name);
} else {
- assert ctype != null && ctype.ResolvedClass != null; // follows from postcondition of ResolveMember
+ Contract.Assert( ctype != null && ctype.ResolvedClass != null); // follows from postcondition of ResolveMember
fe.Field = (Field)member;
}
}
@@ -603,7 +656,8 @@ namespace Microsoft.Dafny {
/// <summary>
/// Assumes type parameters have already been pushed
/// </summary>
- void ResolveMethodSignature(Method! m) {
+ void ResolveMethodSignature(Method m) {
+ Contract.Requires(m != null);
scope.PushMarker();
// resolve in-parameters
foreach (Formal p in m.Ins) {
@@ -625,7 +679,8 @@ namespace Microsoft.Dafny {
/// <summary>
/// Assumes type parameters have already been pushed
/// </summary>
- void ResolveMethod(Method! m) {
+ void ResolveMethod(Method m) {
+ Contract.Requires(m != null);
// Add in-parameters to the scope, but don't care about any duplication errors, since they have already been reported
scope.PushMarker();
if (m.IsStatic) {
@@ -638,7 +693,7 @@ namespace Microsoft.Dafny {
// Start resolving specification...
foreach (MaybeFreeExpression e in m.Req) {
ResolveExpression(e.E, false, true);
- assert e.E.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( e.E.Type != null); // follows from postcondition of ResolveExpression
if (!UnifyTypes(e.E.Type, Type.Bool)) {
Error(e.E, "Precondition must be a boolean (got {0})", e.E.Type);
}
@@ -661,7 +716,7 @@ namespace Microsoft.Dafny {
// ... continue resolving specification
foreach (MaybeFreeExpression e in m.Ens) {
ResolveExpression(e.E, true, true);
- assert e.E.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( e.E.Type != null); // follows from postcondition of ResolveExpression
if (!UnifyTypes(e.E.Type, Type.Bool)) {
Error(e.E, "Postcondition must be a boolean (got {0})", e.E.Type);
}
@@ -679,7 +734,8 @@ namespace Microsoft.Dafny {
/// <summary>
/// Assumes type parameters have already been pushed
/// </summary>
- void ResolveCtorSignature(DatatypeCtor! ctor) {
+ void ResolveCtorSignature(DatatypeCtor ctor) {
+ Contract.Requires(ctor != null);
scope.PushMarker();
foreach (Formal p in ctor.Formals) {
if (!scope.Push(p.Name, p)) {
@@ -690,7 +746,8 @@ namespace Microsoft.Dafny {
scope.PopMarker();
}
- public void ResolveType(Type! type) {
+ public void ResolveType(Type type) {
+ Contract.Requires(type != null);
if (type is BasicType) {
// nothing to resolve
} else if (type is CollectionType) {
@@ -711,7 +768,7 @@ namespace Microsoft.Dafny {
TopLevelDecl d;
if (!classes.TryGetValue(t.Name, out d)) {
Error(t.tok, "Undeclared top-level type or type parameter: {0}", t.Name);
- } else if (((!)d).TypeArgs.Count == t.TypeArgs.Count) {
+ } else if (cce.NonNull(d).TypeArgs.Count == t.TypeArgs.Count) {
t.ResolvedClass = d;
} else {
Error(t.tok, "Wrong number of type arguments ({0} instead of {1}) passed to class/datatype: {2}", t.TypeArgs.Count, d.TypeArgs.Count, t.Name);
@@ -725,11 +782,13 @@ namespace Microsoft.Dafny {
}
} else {
- assert false; // unexpected type
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected type
}
}
- public bool UnifyTypes(Type! a, Type! b) {
+ public bool UnifyTypes(Type a, Type b) {
+ Contract.Requires(a != null);
+ Contract.Requires(b != null);
while (a is TypeProxy) {
TypeProxy proxy = (TypeProxy)a;
if (proxy.T == null) {
@@ -779,7 +838,7 @@ namespace Microsoft.Dafny {
UserDefinedType bb = (UserDefinedType)b;
if (aa.ResolvedClass != null && aa.ResolvedClass == bb.ResolvedClass) {
// these are both resolved class/datatype types
- assert aa.TypeArgs.Count == bb.TypeArgs.Count;
+ Contract.Assert( aa.TypeArgs.Count == bb.TypeArgs.Count);
bool successSoFar = true;
for (int i = 0; i < aa.TypeArgs.Count; i++) {
if (!UnifyTypes(aa.TypeArgs[i], bb.TypeArgs[i])) {
@@ -789,7 +848,7 @@ namespace Microsoft.Dafny {
return successSoFar;
} else if (aa.ResolvedParam != null && aa.ResolvedParam == bb.ResolvedParam) {
// these are both resolved type parameters
- assert aa.TypeArgs.Count == 0 && bb.TypeArgs.Count == 0;
+ Contract.Assert( aa.TypeArgs.Count == 0 && bb.TypeArgs.Count == 0);
return true;
} else {
// something is wrong; either aa or bb wasn't properly resolved, or they don't unify
@@ -797,16 +856,17 @@ namespace Microsoft.Dafny {
}
} else {
- assert false; // unexpected type
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected type
}
}
- bool AssignProxy(TypeProxy! proxy, Type! t)
- requires proxy.T == null;
- requires t is TypeProxy ==> ((TypeProxy)t).T == null;
- modifies proxy.T, ((TypeProxy)t).T; // might also change t.T if t is a proxy
- ensures result ==> proxy == t || proxy.T != null || (t is TypeProxy && ((TypeProxy)t).T != null);
- {
+ bool AssignProxy(TypeProxy proxy, Type t){
+ Contract.Requires(proxy != null);
+ Contract.Requires(t != null);
+ Contract.Requires( proxy.T == null);
+ Contract.Requires( (t is TypeProxy)|| ((TypeProxy)t).T == null);
+ //modifies proxy.T, ((TypeProxy)t).T; // might also change t.T if t is a proxy
+ Contract.Ensures( Contract.Result<bool>() || proxy == t || proxy.T != null || (t is TypeProxy && ((TypeProxy)t).T != null));
if (proxy == t) {
// they are already in the same equivalence class
return true;
@@ -887,7 +947,7 @@ namespace Microsoft.Dafny {
}
} else {
- assert false; // unexpected proxy type
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected proxy type
}
// do the merge
@@ -895,13 +955,15 @@ namespace Microsoft.Dafny {
return true;
}
- bool AssignRestrictedProxies(RestrictedTypeProxy! a, RestrictedTypeProxy! b)
- requires a != b;
- requires a.T == null && b.T == null;
- requires a.OrderID <= b.OrderID;
- modifies a.T, b.T;
- ensures result ==> a.T != null || b.T != null;
- {
+ bool AssignRestrictedProxies(RestrictedTypeProxy a, RestrictedTypeProxy b)
+ { Contract.Requires(a != null);
+ Contract.Requires(b != null);
+ Contract.Requires( a != b);
+ Contract.Requires( a.T == null && b.T == null);
+ Contract.Requires( a.OrderID <= b.OrderID);
+ //modifies a.T, b.T;
+ Contract.Ensures(Contract.Result<bool>() || a.T != null || b.T != null);
+
if (a is DatatypeProxy) {
if (b is DatatypeProxy) {
// all is fine
@@ -956,7 +1018,7 @@ namespace Microsoft.Dafny {
a.T = b.T;
return UnifyTypes(pb.Arg, new ObjectTypeProxy());
} else {
- assert false; // unexpected restricted-proxy type
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected restricted-proxy type
}
} else if (a is CollectionTypeProxy) {
@@ -980,13 +1042,13 @@ namespace Microsoft.Dafny {
b.T = new SeqType(pb.Arg);
return UnifyTypes(pa.Arg, pb.Arg);
} else {
- assert false; // unexpected restricted-proxy type
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected restricted-proxy type
}
} else if (a is OperationTypeProxy) {
OperationTypeProxy pa = (OperationTypeProxy)a;
if (b is OperationTypeProxy) {
- if (pa.AllowSeq ==> ((OperationTypeProxy)b).AllowSeq) {
+ if (!pa.AllowSeq || ((OperationTypeProxy)b).AllowSeq) {
b.T = a;
} else {
a.T = b; // b has the stronger requirement
@@ -1005,23 +1067,22 @@ namespace Microsoft.Dafny {
}
} else if (a is IndexableTypeProxy) {
- assert b is IndexableTypeProxy; // else we have unexpected restricted-proxy type
+ Contract.Assert( b is IndexableTypeProxy); // else we have unexpected restricted-proxy type
a.T = b;
return UnifyTypes(((IndexableTypeProxy)a).Arg, ((IndexableTypeProxy)b).Arg);
} else {
- assert false; // unexpected restricted-proxy type
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected restricted-proxy type
}
}
- public void ResolveStatement(Statement! stmt, bool specContextOnly, Method! method)
- requires !(stmt is LabelStmt); // these should be handled inside lists of statements
- {
+ public void ResolveStatement(Statement stmt, bool specContextOnly, Method method){Contract.Requires(stmt != null);Contract.Requires(method != null);
+ Contract.Requires( !(stmt is LabelStmt)); // these should be handled inside lists of statements
if (stmt is UseStmt) {
UseStmt s = (UseStmt)stmt;
s.IsGhost = true;
ResolveExpression(s.Expr, true, true);
- assert s.Expr.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( s.Expr.Type != null); // follows from postcondition of ResolveExpression
Expression expr = s.Expr;
while (true) {
if (expr is OldExpr) {
@@ -1034,7 +1095,7 @@ namespace Microsoft.Dafny {
PredicateStmt s = (PredicateStmt)stmt;
s.IsGhost = true;
ResolveExpression(s.Expr, true, true);
- assert s.Expr.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( s.Expr.Type != null); // follows from postcondition of ResolveExpression
if (!UnifyTypes(s.Expr.Type, Type.Bool)) {
Error(s.Expr, "condition is expected to be of type {0}, but is {1}", Type.Bool, s.Expr.Type);
}
@@ -1066,7 +1127,7 @@ namespace Microsoft.Dafny {
ResolveExpression(s.Lhs, true, true); // allow ghosts for now, but see FieldSelectExpr LHS case below
}
bool lhsResolvedSuccessfully = ErrorCount == prevErrorCount;
- assert s.Lhs.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( s.Lhs.Type != null); // follows from postcondition of ResolveExpression
// check that LHS denotes a mutable variable or a field
bool lvalueIsGhost = false;
if (s.Lhs is IdentifierExpr) {
@@ -1104,7 +1165,7 @@ namespace Microsoft.Dafny {
SeqSelectExpr lhs = (SeqSelectExpr)s.Lhs;
// LHS is fine, provided the "sequence" is really an array
if (lhsResolvedSuccessfully) {
- assert lhs.Seq.Type != null;
+ Contract.Assert( lhs.Seq.Type != null);
Type elementType = new InferredTypeProxy();
if (!UnifyTypes(lhs.Seq.Type, UserDefinedType.ArrayType(Token.NoToken, elementType))) {
Error(lhs.Seq, "LHS of array assignment must denote an array element (found {0})", lhs.Seq.Type);
@@ -1125,10 +1186,10 @@ namespace Microsoft.Dafny {
if (s.Rhs is ExprRhs) {
ExprRhs rr = (ExprRhs)s.Rhs;
ResolveExpression(rr.Expr, true, lvalueIsGhost);
- assert rr.Expr.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( rr.Expr.Type != null); // follows from postcondition of ResolveExpression
Type lhsType = s.Lhs.Type;
if (s.Lhs is SeqSelectExpr && !((SeqSelectExpr)s.Lhs).SelectOne) {
- assert lhsType.IsArrayType;
+ Contract.Assert( lhsType.IsArrayType);
lhsType = UserDefinedType.ArrayElementType(lhsType);
}
if (!UnifyTypes(lhsType, rr.Expr.Type)) {
@@ -1143,7 +1204,7 @@ namespace Microsoft.Dafny {
} else if (s.Rhs is HavocRhs) {
// nothing else to do
} else {
- assert false; // unexpected RHS
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected RHS
}
} else if (stmt is VarDecl) {
@@ -1153,17 +1214,17 @@ namespace Microsoft.Dafny {
s.type = s.OptionalType;
}
if (s.Rhs != null) {
- Type! rhsType;
+ Type rhsType;
if (s.Rhs is ExprRhs) {
ExprRhs rr = (ExprRhs)s.Rhs;
ResolveExpression(rr.Expr, true, s.IsGhost);
- assert rr.Expr.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( rr.Expr.Type != null); // follows from postcondition of ResolveExpression
rhsType = rr.Expr.Type;
} else if (s.Rhs is TypeRhs) {
TypeRhs rr = (TypeRhs)s.Rhs;
rhsType = ResolveTypeRhs(rr, stmt, s.IsGhost);
} else {
- assert false; // unexpected RHS
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected RHS
}
if (s.OptionalType == null) {
s.type = rhsType;
@@ -1181,7 +1242,7 @@ namespace Microsoft.Dafny {
// resolve receiver
ResolveReceiver(s.Receiver, true, false);
- assert s.Receiver.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( s.Receiver.Type != null); // follows from postcondition of ResolveExpression
// resolve the method name
UserDefinedType ctype;
MemberDecl member = ResolveMember(s.Tok, s.Receiver.Type, s.MethodName, out ctype);
@@ -1189,7 +1250,7 @@ namespace Microsoft.Dafny {
if (member == null) {
// error has already been reported by ResolveMember
} else if (!(member is Method)) {
- Error(s, "member {0} in class {1} does not refer to a method", s.MethodName, ((!)ctype).Name);
+ Error(s, "member {0} in class {1} does not refer to a method", s.MethodName, cce.NonNull(ctype).Name);
} else {
callee = (Method)member;
s.Method = callee;
@@ -1209,7 +1270,7 @@ namespace Microsoft.Dafny {
}
// resolve left-hand side
- Dictionary<string!,object> lhsNameSet = new Dictionary<string!,object>();
+ Dictionary<string,object> lhsNameSet = new Dictionary<string,object>();
foreach (IdentifierExpr lhs in s.Lhs) {
ResolveExpression(lhs, true, true);
if (lhsNameSet.ContainsKey(lhs.Name)) {
@@ -1233,7 +1294,7 @@ namespace Microsoft.Dafny {
} else if (callee.Outs.Count != s.Lhs.Count) {
Error(s, "wrong number of method result arguments (got {0}, expected {1})", s.Lhs.Count, callee.Outs.Count);
} else {
- assert ctype != null; // follows from postcondition of ResolveMember above
+ Contract.Assert( ctype != null); // follows from postcondition of ResolveMember above
if (!scope.AllowInstance && !callee.IsStatic && s.Receiver is ThisExpr) {
// The call really needs an instance, but that instance is given as 'this', which is not
// available in this context. For more details, see comment in the resolution of a
@@ -1241,9 +1302,9 @@ namespace Microsoft.Dafny {
Error(s.Receiver, "'this' is not allowed in a 'static' context");
}
// build the type substitution map
- Dictionary<TypeParameter!,Type!> subst = new Dictionary<TypeParameter!,Type!>();
+ Dictionary<TypeParameter,Type> subst = new Dictionary<TypeParameter,Type>();
for (int i = 0; i < ctype.TypeArgs.Count; i++) {
- subst.Add(((!)ctype.ResolvedClass).TypeArgs[i], ctype.TypeArgs[i]);
+ subst.Add(cce.NonNull(ctype.ResolvedClass).TypeArgs[i], ctype.TypeArgs[i]);
}
foreach (TypeParameter p in callee.TypeArgs) {
subst.Add(p, new ParamTypeProxy(p));
@@ -1251,16 +1312,16 @@ namespace Microsoft.Dafny {
// type check the arguments
for (int i = 0; i < callee.Ins.Count; i++) {
Type st = SubstType(callee.Ins[i].Type, subst);
- if (!UnifyTypes((!)s.Args[i].Type, st)) {
+ if (!UnifyTypes(cce.NonNull(s.Args[i].Type), st)) {
Error(s, "incorrect type of method in-parameter {0} (expected {1}, got {2})", i, st, s.Args[i].Type);
}
}
for (int i = 0; i < callee.Outs.Count; i++) {
Type st = SubstType(callee.Outs[i].Type, subst);
IdentifierExpr lhs = s.Lhs[i];
- if (!UnifyTypes((!)lhs.Type, st)) {
+ if (!UnifyTypes(cce.NonNull(lhs.Type), st)) {
Error(s, "incorrect type of method out-parameter {0} (expected {1}, got {2})", i, st, lhs.Type);
- } else if (!specContextOnly && !((!)lhs.Var).IsGhost && (s.IsGhost || callee.Outs[i].IsGhost)) {
+ } else if (!specContextOnly && !cce.NonNull(lhs.Var).IsGhost && (s.IsGhost || callee.Outs[i].IsGhost)) {
Error(s, "actual out-parameter {0} is required to be a ghost variable", i);
}
}
@@ -1293,7 +1354,7 @@ namespace Microsoft.Dafny {
if (s.Guard != null) {
int prevErrorCount = ErrorCount;
ResolveExpression(s.Guard, true, true);
- assert s.Guard.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( s.Guard.Type != null); // follows from postcondition of ResolveExpression
bool successfullyResolved = ErrorCount == prevErrorCount;
if (!UnifyTypes(s.Guard.Type, Type.Bool)) {
Error(s.Guard, "condition is expected to be of type {0}, but is {1}", Type.Bool, s.Guard.Type);
@@ -1314,7 +1375,7 @@ namespace Microsoft.Dafny {
if (s.Guard != null) {
int prevErrorCount = ErrorCount;
ResolveExpression(s.Guard, true, true);
- assert s.Guard.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( s.Guard.Type != null); // follows from postcondition of ResolveExpression
bool successfullyResolved = ErrorCount == prevErrorCount;
if (!UnifyTypes(s.Guard.Type, Type.Bool)) {
Error(s.Guard, "condition is expected to be of type {0}, but is {1}", Type.Bool, s.Guard.Type);
@@ -1325,7 +1386,7 @@ namespace Microsoft.Dafny {
}
foreach (MaybeFreeExpression inv in s.Invariants) {
ResolveExpression(inv.E, true, true);
- assert inv.E.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( inv.E.Type != null); // follows from postcondition of ResolveExpression
if (!UnifyTypes(inv.E.Type, Type.Bool)) {
Error(inv.E, "invariant is expected to be of type {0}, but is {1}", Type.Bool, inv.E.Type);
}
@@ -1341,19 +1402,19 @@ namespace Microsoft.Dafny {
ForeachStmt s = (ForeachStmt)stmt;
ResolveExpression(s.Collection, true, true);
- assert s.Collection.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( s.Collection.Type != null); // follows from postcondition of ResolveExpression
if (!UnifyTypes(s.Collection.Type, new CollectionTypeProxy(s.BoundVar.Type))) {
Error(s.Collection, "The type is expected to be a collection of {0} (instead got {1})", s.BoundVar.Type, s.Collection.Type);
}
scope.PushMarker();
bool b = scope.Push(s.BoundVar.Name, s.BoundVar);
- assert b; // since we just pushed a marker, we expect the Push to succeed
+ Contract.Assert( b); // since we just pushed a marker, we expect the Push to succeed
ResolveType(s.BoundVar.Type);
int prevErrorCount = ErrorCount;
ResolveExpression(s.Range, true, true);
- assert s.Range.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( s.Range.Type != null); // follows from postcondition of ResolveExpression
if (!UnifyTypes(s.Range.Type, Type.Bool)) {
Error(s.Range, "range condition is expected to be of type {0}, but is {1}", Type.Bool, s.Range.Type);
}
@@ -1383,26 +1444,26 @@ namespace Microsoft.Dafny {
bool bodyIsSpecOnly = specContextOnly;
int prevErrorCount = ErrorCount;
ResolveExpression(s.Source, true, true);
- assert s.Source.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( s.Source.Type != null); // follows from postcondition of ResolveExpression
bool successfullyResolved = ErrorCount == prevErrorCount;
if (!specContextOnly && successfullyResolved) {
bodyIsSpecOnly = UsesSpecFeatures(s.Source);
}
UserDefinedType sourceType = null;
DatatypeDecl dtd = null;
- Dictionary<TypeParameter!,Type!> subst = new Dictionary<TypeParameter!,Type!>();
+ Dictionary<TypeParameter,Type> subst = new Dictionary<TypeParameter,Type>();
if (s.Source.Type.IsDatatype) {
sourceType = (UserDefinedType)s.Source.Type;
- dtd = (DatatypeDecl!)sourceType.ResolvedClass;
+ dtd = cce.NonNull((DatatypeDecl)sourceType.ResolvedClass);
}
- Dictionary<string!,DatatypeCtor!> ctors;
+ Dictionary<string,DatatypeCtor> ctors;
if (dtd == null) {
Error(s.Source, "the type of the match source expression must be a datatype");
ctors = null;
} else {
- assert sourceType != null; // dtd and sourceType are set together above
+ Contract.Assert( sourceType != null); // dtd and sourceType are set together above
ctors = datatypeCtors[dtd];
- assert ctors != null; // dtd should have been inserted into datatypeCtors during a previous resolution stage
+ Contract.Assert( ctors != null); // dtd should have been inserted into datatypeCtors during a previous resolution stage
// build the type-parameter substitution map for this use of the datatype
for (int i = 0; i < dtd.TypeArgs.Count; i++) {
@@ -1411,15 +1472,15 @@ namespace Microsoft.Dafny {
}
s.IsGhost = bodyIsSpecOnly;
- Dictionary<string!,object> memberNamesUsed = new Dictionary<string!,object>(); // this is really a set
+ Dictionary<string,object> memberNamesUsed = new Dictionary<string,object>(); // this is really a set
foreach (MatchCaseStmt mc in s.Cases) {
DatatypeCtor ctor = null;
if (ctors != null) {
- assert dtd != null;
+ Contract.Assert( dtd != null);
if (!ctors.TryGetValue(mc.Id, out ctor)) {
Error(mc.tok, "member {0} does not exist in datatype {1}", mc.Id, dtd.Name);
} else {
- assert ctor != null; // follows from postcondition of TryGetValue
+ Contract.Assert( ctor != null); // follows from postcondition of TryGetValue
mc.Ctor = ctor;
if (ctor.Formals.Count != mc.Arguments.Count) {
Error(mc.tok, "member {0} has wrong number of formals (found {1}, expected {2})", mc.Arguments.Count, ctor.Formals.Count);
@@ -1465,19 +1526,21 @@ namespace Microsoft.Dafny {
} else {
- assert false;
+ Contract.Assert(false); throw new cce.UnreachableException();
}
}
- void ResolveBlockStatement(BlockStmt! blockStmt, bool specContextOnly, Method! method)
+ void ResolveBlockStatement(BlockStmt blockStmt, bool specContextOnly, Method method)
{
+ Contract.Requires(blockStmt != null);
+ Contract.Requires(method != null);
int labelsToPop = 0;
foreach (Statement ss in blockStmt.Body) {
if (ss is LabelStmt) {
LabelStmt ls = (LabelStmt)ss;
labeledStatements.PushMarker();
bool b = labeledStatements.Push(ls.Label, ls);
- assert b; // since we just pushed a marker, we expect the Push to succeed
+ Contract.Assert( b); // since we just pushed a marker, we expect the Push to succeed
labelsToPop++;
} else {
ResolveStatement(ss, specContextOnly, method);
@@ -1487,7 +1550,11 @@ namespace Microsoft.Dafny {
for (; 0 < labelsToPop; labelsToPop--) { labeledStatements.PopMarker(); }
}
- Type! ResolveTypeRhs(TypeRhs! rr, Statement! stmt, bool specContext) {
+ Type ResolveTypeRhs(TypeRhs rr, Statement stmt, bool specContext) {
+ Contract.Requires(rr != null);
+ Contract.Requires(stmt != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
+
ResolveType(rr.EType);
if (rr.ArraySize == null) {
if (!rr.EType.IsRefType) {
@@ -1505,27 +1572,35 @@ namespace Microsoft.Dafny {
return rr.EType;
}
- MemberDecl ResolveMember(IToken! tok, Type! receiverType, string! memberName, out UserDefinedType ctype)
- ensures result != null ==> ctype != null && ctype.ResolvedClass != null;
+ MemberDecl ResolveMember(IToken tok, Type receiverType, string memberName, out UserDefinedType ctype)
{
+ Contract.Requires(tok != null);
+ Contract.Requires(receiverType != null);
+ Contract.Requires(memberName != null);
+ Contract.Ensures( Contract.Result<MemberDecl>() == null || Contract.ValueAtReturn(out ctype) != null && ctype.ResolvedClass != null);
+
ctype = UserDefinedType.DenotesClass(receiverType);
if (ctype == null) {
Error(tok, "receiver (of type {0}) must be of a class type", receiverType);
} else {
- assert ctype.ResolvedClass is ClassDecl; // follows from postcondition of DenotesClass
- assert ctype.TypeArgs.Count == ctype.ResolvedClass.TypeArgs.Count; // follows from the fact that ctype was resolved
+ Contract.Assert( ctype.ResolvedClass is ClassDecl); // follows from postcondition of DenotesClass
+ Contract.Assert( ctype.TypeArgs.Count == ctype.ResolvedClass.TypeArgs.Count); // follows from the fact that ctype was resolved
MemberDecl member;
if (!classMembers[(ClassDecl)ctype.ResolvedClass].TryGetValue(memberName, out member)) {
Error(tok, "member {0} does not exist in class {1}", memberName, ctype.Name);
} else {
- return (!)member;
+ return cce.NonNull(member);
}
}
ctype = null;
return null;
}
- Type! SubstType(Type! type, Dictionary<TypeParameter!,Type!>! subst) {
+ Type SubstType(Type type, Dictionary<TypeParameter/*!*/,Type/*!*/>/*!*/ subst) {
+ Contract.Requires(type != null);
+ Contract.Requires(cce.NonNullElements(subst));
+ Contract.Ensures(Contract.Result<Type>() != null);
+
if (type is BasicType) {
return type;
} else if (type is CollectionType) {
@@ -1538,26 +1613,26 @@ namespace Microsoft.Dafny {
} else if (type is SeqType) {
return new SeqType(arg);
} else {
- assert false; // unexpected collection type
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected collection type
}
} else if (type is UserDefinedType) {
UserDefinedType t = (UserDefinedType)type;
if (t.ResolvedParam != null) {
- assert t.TypeArgs.Count == 0;
+ Contract.Assert( t.TypeArgs.Count == 0);
Type s;
if (subst.TryGetValue(t.ResolvedParam, out s)) {
- return (!)s;
+ return cce.NonNull(s);
} else {
return type;
}
} else if (t.ResolvedClass != null) {
- List<Type!> newArgs = null; // allocate it lazily
+ List<Type> newArgs = null; // allocate it lazily
for (int i = 0; i < t.TypeArgs.Count; i++) {
Type p = t.TypeArgs[i];
Type s = SubstType(p, subst);
if (s != p && newArgs == null) {
// lazily construct newArgs
- newArgs = new List<Type!>();
+ newArgs = new List<Type>();
for (int j = 0; j < i; j++) {
newArgs.Add(t.TypeArgs[j]);
}
@@ -1586,12 +1661,16 @@ namespace Microsoft.Dafny {
return SubstType(t.T, subst);
}
} else {
- assert false; // unexpected type
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected type
}
}
- public static UserDefinedType! GetThisType(IToken! tok, ClassDecl! cl) {
- List<Type!> args = new List<Type!>();
+ public static UserDefinedType GetThisType(IToken tok, ClassDecl cl) {
+ Contract.Requires(tok != null);
+ Contract.Requires(cl != null);
+ Contract.Ensures(Contract.Result<UserDefinedType>() != null);
+
+ List<Type> args = new List<Type>();
foreach (TypeParameter tp in cl.TypeArgs) {
args.Add(new UserDefinedType(tok, tp.Name, tp));
}
@@ -1601,10 +1680,10 @@ namespace Microsoft.Dafny {
/// <summary>
/// "twoState" implies that "old" and "fresh" expressions are allowed
/// </summary>
- void ResolveExpression(Expression! expr, bool twoState, bool specContext)
- requires currentClass != null;
- ensures expr.Type != null;
- {
+ void ResolveExpression(Expression expr, bool twoState, bool specContext){
+ Contract.Requires(expr != null);
+ Contract.Requires( currentClass != null);
+ Contract.Ensures( expr.Type != null);
if (expr.Type != null) {
// expression has already been resovled
return;
@@ -1624,7 +1703,7 @@ namespace Microsoft.Dafny {
} else if (e.Value is bool) {
e.Type = Type.Bool;
} else {
- assert false; // unexpected literal type
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected literal type
}
} else if (expr is ThisExpr) {
@@ -1655,8 +1734,8 @@ namespace Microsoft.Dafny {
} else {
// this resolution is a little special, in that the syntax shows only the base name, not its instantiation (which is inferred)
DatatypeDecl dt = (DatatypeDecl)d;
- List<Type!> gt = new List<Type!>(dt.TypeArgs.Count);
- Dictionary<TypeParameter!,Type!> subst = new Dictionary<TypeParameter!,Type!>();
+ List<Type> gt = new List<Type>(dt.TypeArgs.Count);
+ Dictionary<TypeParameter,Type> subst = new Dictionary<TypeParameter,Type>();
for (int i = 0; i < dt.TypeArgs.Count; i++) {
Type t = new InferredTypeProxy();
gt.Add(t);
@@ -1670,7 +1749,7 @@ namespace Microsoft.Dafny {
if (!datatypeCtors[dt].TryGetValue(dtv.MemberName, out ctor)) {
Error(expr.tok, "undeclared constructor {0} in datatype {1}", dtv.MemberName, dtv.DatatypeName);
} else {
- assert ctor != null; // follows from postcondition of TryGetValue
+ Contract.Assert( ctor != null); // follows from postcondition of TryGetValue
dtv.Ctor = ctor;
if (ctor.Formals.Count != dtv.Arguments.Count) {
Error(expr.tok, "wrong number of arguments to datatype constructor {0} (found {1}, expected {2})", dtv.DatatypeName, dtv.Arguments.Count, ctor.Formals.Count);
@@ -1686,7 +1765,7 @@ namespace Microsoft.Dafny {
foreach (Expression arg in dtv.Arguments) {
Formal formal = ctor != null && j < ctor.Formals.Count ? ctor.Formals[j] : null;
ResolveExpression(arg, twoState, specContext || (formal != null && formal.IsGhost));
- assert arg.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( arg.Type != null); // follows from postcondition of ResolveExpression
if (formal != null) {
Type st = SubstType(formal.Type, subst);
if (!UnifyTypes(arg.Type, st)) {
@@ -1702,9 +1781,9 @@ namespace Microsoft.Dafny {
Type elementType = new InferredTypeProxy();
foreach (Expression ee in e.Elements) {
ResolveExpression(ee, twoState, specContext);
- assert ee.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( ee.Type != null); // follows from postcondition of ResolveExpression
if (!UnifyTypes(elementType, ee.Type)) {
- Error(ee, "All elements of display must be of the same type (got {0}, but type of previous elements is {1})", ee.Type, elementType);
+ Error(ee, "All elements of display must be of the same type (got {0}, but type of previous elements is {1})", ee.Type, elementType);
}
}
if (expr is SetDisplayExpr) {
@@ -1716,18 +1795,18 @@ namespace Microsoft.Dafny {
} else if (expr is FieldSelectExpr) {
FieldSelectExpr e = (FieldSelectExpr)expr;
ResolveExpression(e.Obj, twoState, specContext);
- assert e.Obj.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( e.Obj.Type != null); // follows from postcondition of ResolveExpression
UserDefinedType ctype;
MemberDecl member = ResolveMember(expr.tok, e.Obj.Type, e.FieldName, out ctype);
if (member == null) {
// error has already been reported by ResolveMember
} else if (!(member is Field)) {
- Error(expr, "member {0} in class {1} does not refer to a field", e.FieldName, ((!)ctype).Name);
+ Error(expr, "member {0} in class {1} does not refer to a field", e.FieldName, cce.NonNull(ctype).Name);
} else {
- assert ctype != null && ctype.ResolvedClass != null; // follows from postcondition of ResolveMember
+ Contract.Assert( ctype != null && ctype.ResolvedClass != null); // follows from postcondition of ResolveMember
e.Field = (Field)member;
// build the type substitution map
- Dictionary<TypeParameter!,Type!> subst = new Dictionary<TypeParameter!,Type!>();
+ Dictionary<TypeParameter,Type> subst = new Dictionary<TypeParameter,Type>();
for (int i = 0; i < ctype.TypeArgs.Count; i++) {
subst.Add(ctype.ResolvedClass.TypeArgs[i], ctype.TypeArgs[i]);
}
@@ -1745,19 +1824,19 @@ namespace Microsoft.Dafny {
SeqUpdateExpr e = (SeqUpdateExpr)expr;
bool seqErr = false;
ResolveExpression(e.Seq, twoState, specContext);
- assert e.Seq.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( e.Seq.Type != null); // follows from postcondition of ResolveExpression
Type elementType = new InferredTypeProxy();
if (!UnifyTypes(e.Seq.Type, new SeqType(elementType))) {
Error(expr, "sequence update requires a sequence (got {0})", e.Seq.Type);
seqErr = true;
}
ResolveExpression(e.Index, twoState, specContext);
- assert e.Index.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( e.Index.Type != null); // follows from postcondition of ResolveExpression
if (!UnifyTypes(e.Index.Type, Type.Int)) {
Error(e.Index, "sequence update requires integer index (got {0})", e.Index.Type);
}
ResolveExpression(e.Value, twoState, specContext);
- assert e.Value.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( e.Value.Type != null); // follows from postcondition of ResolveExpression
if (!UnifyTypes(e.Value.Type, elementType)) {
Error(e.Value, "sequence update requires the value to have the element type of the sequence (got {0})", e.Value.Type);
}
@@ -1768,13 +1847,13 @@ namespace Microsoft.Dafny {
} else if (expr is FunctionCallExpr) {
FunctionCallExpr e = (FunctionCallExpr)expr;
ResolveReceiver(e.Receiver, twoState, specContext);
- assert e.Receiver.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( e.Receiver.Type != null); // follows from postcondition of ResolveExpression
UserDefinedType ctype;
MemberDecl member = ResolveMember(expr.tok, e.Receiver.Type, e.Name, out ctype);
if (member == null) {
// error has already been reported by ResolveMember
} else if (!(member is Function)) {
- Error(expr, "member {0} in class {1} does not refer to a function", e.Name, ((!)ctype).Name);
+ Error(expr, "member {0} in class {1} does not refer to a function", e.Name, cce.NonNull(ctype).Name);
} else {
Function function = (Function)member;
e.Function = function;
@@ -1784,7 +1863,7 @@ namespace Microsoft.Dafny {
if (function.Formals.Count != e.Args.Count) {
Error(expr, "wrong number of function arguments (got {0}, expected {1})", e.Args.Count, function.Formals.Count);
} else {
- assert ctype != null; // follows from postcondition of ResolveMember
+ Contract.Assert( ctype != null); // follows from postcondition of ResolveMember
if (!scope.AllowInstance && !function.IsStatic && e.Receiver is ThisExpr) {
// The call really needs an instance, but that instance is given as 'this', which is not
// available in this context. In most cases, occurrences of 'this' inside e.Receiver would
@@ -1796,9 +1875,9 @@ namespace Microsoft.Dafny {
Error(e.Receiver, "'this' is not allowed in a 'static' context");
}
// build the type substitution map
- Dictionary<TypeParameter!,Type!> subst = new Dictionary<TypeParameter!,Type!>();
+ Dictionary<TypeParameter,Type> subst = new Dictionary<TypeParameter,Type>();
for (int i = 0; i < ctype.TypeArgs.Count; i++) {
- subst.Add(((!)ctype.ResolvedClass).TypeArgs[i], ctype.TypeArgs[i]);
+ subst.Add(cce.NonNull(ctype.ResolvedClass).TypeArgs[i], ctype.TypeArgs[i]);
}
foreach (TypeParameter p in function.TypeArgs) {
subst.Add(p, new ParamTypeProxy(p));
@@ -1807,7 +1886,7 @@ namespace Microsoft.Dafny {
for (int i = 0; i < function.Formals.Count; i++) {
Expression farg = e.Args[i];
ResolveExpression(farg, twoState, specContext);
- assert farg.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( farg.Type != null); // follows from postcondition of ResolveExpression
Type s = SubstType(function.Formals[i].Type, subst);
if (!UnifyTypes(farg.Type, s)) {
Error(expr, "incorrect type of function argument {0} (expected {1}, got {2})", i, s, farg.Type);
@@ -1852,7 +1931,7 @@ namespace Microsoft.Dafny {
ResolveExpression(e.E, twoState, specContext);
// the type of e.E must be either an object or a collection of objects
Type t = e.E.Type;
- assert t != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( t != null); // follows from postcondition of ResolveExpression
if (t is CollectionType) {
t = ((CollectionType)t).Arg;
}
@@ -1868,7 +1947,7 @@ namespace Microsoft.Dafny {
} else if (expr is UnaryExpr) {
UnaryExpr e = (UnaryExpr)expr;
ResolveExpression(e.E, twoState, specContext);
- assert e.E.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( e.E.Type != null); // follows from postcondition of ResolveExpression
switch (e.Op) {
case UnaryExpr.Opcode.Not:
if (!UnifyTypes(e.E.Type, Type.Bool)) {
@@ -1883,15 +1962,15 @@ namespace Microsoft.Dafny {
expr.Type = Type.Int;
break;
default:
- assert false; // unexpected unary operator
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected unary operator
}
} else if (expr is BinaryExpr) {
BinaryExpr e = (BinaryExpr)expr;
ResolveExpression(e.E0, twoState, specContext);
- assert e.E0.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( e.E0.Type != null); // follows from postcondition of ResolveExpression
ResolveExpression(e.E1, twoState, specContext);
- assert e.E1.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( e.E1.Type != null); // follows from postcondition of ResolveExpression
switch (e.Op) {
case BinaryExpr.Opcode.Iff:
case BinaryExpr.Opcode.Imp:
@@ -2007,7 +2086,7 @@ namespace Microsoft.Dafny {
break;
default:
- assert false; // unexpected operator
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected operator
}
e.ResolvedOp = ResolveOp(e.Op, e.E1.Type);
@@ -2024,7 +2103,7 @@ namespace Microsoft.Dafny {
ResolveType(v.Type);
}
ResolveExpression(e.Body, twoState, specContext);
- assert e.Body.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( e.Body.Type != null); // follows from postcondition of ResolveExpression
if (!UnifyTypes(e.Body.Type, Type.Bool)) {
Error(expr, "body of quantifier must be of type bool (instead got {0})", e.Body.Type);
}
@@ -2041,11 +2120,11 @@ namespace Microsoft.Dafny {
} else if (expr is ITEExpr) {
ITEExpr e = (ITEExpr)expr;
ResolveExpression(e.Test, twoState, specContext);
- assert e.Test.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( e.Test.Type != null); // follows from postcondition of ResolveExpression
ResolveExpression(e.Thn, twoState, specContext);
- assert e.Thn.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( e.Thn.Type != null); // follows from postcondition of ResolveExpression
ResolveExpression(e.Els, twoState, specContext);
- assert e.Els.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( e.Els.Type != null); // follows from postcondition of ResolveExpression
if (!UnifyTypes(e.Test.Type, Type.Bool)) {
Error(expr, "guard condition in if-then-else expression must be a boolean (instead got {0})", e.Test.Type);
}
@@ -2057,24 +2136,24 @@ namespace Microsoft.Dafny {
} else if (expr is MatchExpr) {
MatchExpr me = (MatchExpr)expr;
- assert !twoState; // currently, match expressions are allowed only at the outermost level of function bodies
+ Contract.Assert( !twoState); // currently, match expressions are allowed only at the outermost level of function bodies
ResolveExpression(me.Source, twoState, specContext);
- assert me.Source.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( me.Source.Type != null); // follows from postcondition of ResolveExpression
UserDefinedType sourceType = null;
DatatypeDecl dtd = null;
- Dictionary<TypeParameter!,Type!> subst = new Dictionary<TypeParameter!,Type!>();
+ Dictionary<TypeParameter,Type> subst = new Dictionary<TypeParameter,Type>();
if (me.Source.Type.IsDatatype) {
sourceType = (UserDefinedType)me.Source.Type;
- dtd = (DatatypeDecl!)sourceType.ResolvedClass;
+ dtd = cce.NonNull((DatatypeDecl)sourceType.ResolvedClass);
}
- Dictionary<string!,DatatypeCtor!> ctors;
+ Dictionary<string,DatatypeCtor> ctors;
if (dtd == null) {
Error(me.Source, "the type of the match source expression must be a datatype");
ctors = null;
} else {
- assert sourceType != null; // dtd and sourceType are set together above
+ Contract.Assert( sourceType != null); // dtd and sourceType are set together above
ctors = datatypeCtors[dtd];
- assert ctors != null; // dtd should have been inserted into datatypeCtors during a previous resolution stage
+ Contract.Assert( ctors != null); // dtd should have been inserted into datatypeCtors during a previous resolution stage
IdentifierExpr ie = me.Source as IdentifierExpr;
if (ie == null || !(ie.Var is Formal)) {
@@ -2087,16 +2166,16 @@ namespace Microsoft.Dafny {
}
}
- Dictionary<string!,object> memberNamesUsed = new Dictionary<string!,object>(); // this is really a set
+ Dictionary<string,object> memberNamesUsed = new Dictionary<string,object>(); // this is really a set
expr.Type = new InferredTypeProxy();
foreach (MatchCaseExpr mc in me.Cases) {
DatatypeCtor ctor = null;
if (ctors != null) {
- assert dtd != null;
+ Contract.Assert( dtd != null);
if (!ctors.TryGetValue(mc.Id, out ctor)) {
Error(mc.tok, "member {0} does not exist in datatype {1}", mc.Id, dtd.Name);
} else {
- assert ctor != null; // follows from postcondition of TryGetValue
+ Contract.Assert( ctor != null); // follows from postcondition of TryGetValue
mc.Ctor = ctor;
if (ctor.Formals.Count != mc.Arguments.Count) {
Error(mc.tok, "member {0} has wrong number of formals (found {1}, expected {2})", mc.Arguments.Count, ctor.Formals.Count);
@@ -2132,7 +2211,7 @@ namespace Microsoft.Dafny {
i++;
}
ResolveExpression(mc.Body, twoState, specContext);
- assert mc.Body.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( mc.Body.Type != null); // follows from postcondition of ResolveExpression
if (!UnifyTypes(expr.Type, mc.Body.Type)) {
Error(mc.Body.tok, "type of case bodies do not agree (found {0}, previous types {1})", mc.Body.Type, expr.Type);
}
@@ -2143,7 +2222,7 @@ namespace Microsoft.Dafny {
}
} else {
- assert false; // unexpected expression
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected expression
}
if (expr.Type == null) {
@@ -2152,10 +2231,12 @@ namespace Microsoft.Dafny {
}
}
- void ResolveReceiver(Expression! expr, bool twoState, bool specContext)
- requires currentClass != null;
- ensures expr.Type != null;
+ void ResolveReceiver(Expression expr, bool twoState, bool specContext)
{
+ Contract.Requires(expr != null);
+ Contract.Requires( currentClass != null);
+ Contract.Ensures( expr.Type != null);
+
if (expr is ThisExpr) {
// Allow 'this' here, regardless of scope.AllowInstance. The caller is responsible for
// making sure 'this' does not really get used when it's not available.
@@ -2165,10 +2246,11 @@ namespace Microsoft.Dafny {
}
}
- void ResolveSeqSelectExpr(SeqSelectExpr! e, bool twoState, bool specContext, bool allowNonUnitArraySelection) {
+ void ResolveSeqSelectExpr(SeqSelectExpr e, bool twoState, bool specContext, bool allowNonUnitArraySelection) {
+ Contract.Requires(e != null);
bool seqErr = false;
ResolveExpression(e.Seq, twoState, specContext);
- assert e.Seq.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( e.Seq.Type != null); // follows from postcondition of ResolveExpression
Type elementType = new InferredTypeProxy();
Type expectedType;
if (e.SelectOne || allowNonUnitArraySelection) {
@@ -2182,14 +2264,14 @@ namespace Microsoft.Dafny {
}
if (e.E0 != null) {
ResolveExpression(e.E0, twoState, specContext);
- assert e.E0.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( e.E0.Type != null); // follows from postcondition of ResolveExpression
if (!UnifyTypes(e.E0.Type, Type.Int)) {
Error(e.E0, "sequence/array selection requires integer indices (got {0})", e.E0.Type);
}
}
if (e.E1 != null) {
ResolveExpression(e.E1, twoState, specContext);
- assert e.E1.Type != null; // follows from postcondition of ResolveExpression
+ Contract.Assert( e.E1.Type != null); // follows from postcondition of ResolveExpression
if (!UnifyTypes(e.E1.Type, Type.Int)) {
Error(e.E1, "sequence/array selection requires integer indices (got {0})", e.E1.Type);
}
@@ -2207,7 +2289,8 @@ namespace Microsoft.Dafny {
/// Note: this method is allowed to be called even if "type" does not make sense for "op", as might be the case if
/// resolution of the binary expression failed. If so, an arbitrary resolved opcode is returned.
/// </summary>
- BinaryExpr.ResolvedOpcode ResolveOp(BinaryExpr.Opcode op, Type! operandType) {
+ BinaryExpr.ResolvedOpcode ResolveOp(BinaryExpr.Opcode op, Type operandType) {
+ Contract.Requires(operandType != null);
switch (op) {
case BinaryExpr.Opcode.Iff: return BinaryExpr.ResolvedOpcode.Iff;
case BinaryExpr.Opcode.Imp: return BinaryExpr.ResolvedOpcode.Imp;
@@ -2297,7 +2380,7 @@ namespace Microsoft.Dafny {
case BinaryExpr.Opcode.Div: return BinaryExpr.ResolvedOpcode.Div;
case BinaryExpr.Opcode.Mod: return BinaryExpr.ResolvedOpcode.Mod;
default:
- assert false; // unexpected operator
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected operator
}
}
@@ -2306,25 +2389,27 @@ namespace Microsoft.Dafny {
/// that is allowed only in specification contexts.
/// Requires 'expr' to be a successfully resolved expression.
/// </summary>
- bool UsesSpecFeatures(Expression! expr)
- requires currentClass != null;
+ bool UsesSpecFeatures(Expression expr)
{
+ Contract.Requires(expr != null);
+ Contract.Requires( currentClass != null);
+
if (expr is LiteralExpr) {
return false;
} else if (expr is ThisExpr) {
return false;
} else if (expr is IdentifierExpr) {
IdentifierExpr e = (IdentifierExpr)expr;
- return ((!)e.Var).IsGhost;
+ return cce.NonNull(e.Var).IsGhost;
} else if (expr is DatatypeValue) {
DatatypeValue dtv = (DatatypeValue)expr;
- return exists{Expression arg in dtv.Arguments; UsesSpecFeatures(arg)};
+ return Contract.Exists(dtv.Arguments, arg=> UsesSpecFeatures(arg));
} else if (expr is DisplayExpression) {
DisplayExpression e = (DisplayExpression)expr;
- return exists{Expression ee in e.Elements; UsesSpecFeatures(ee)};
+ return Contract.Exists( e.Elements,ee=> UsesSpecFeatures(ee));
} else if (expr is FieldSelectExpr) {
FieldSelectExpr e = (FieldSelectExpr)expr;
- return ((!)e.Field).IsGhost || UsesSpecFeatures(e.Obj);
+ return cce.NonNull(e.Field).IsGhost || UsesSpecFeatures(e.Obj);
} else if (expr is SeqSelectExpr) {
SeqSelectExpr e = (SeqSelectExpr)expr;
return UsesSpecFeatures(e.Seq) ||
@@ -2337,10 +2422,10 @@ namespace Microsoft.Dafny {
(e.Value != null && UsesSpecFeatures(e.Value));
} else if (expr is FunctionCallExpr) {
FunctionCallExpr e = (FunctionCallExpr)expr;
- if (((!)e.Function).IsGhost) {
+ if (cce.NonNull(e.Function).IsGhost) {
return true;
}
- return exists{Expression arg in e.Args; UsesSpecFeatures(arg)};
+ return Contract.Exists( e.Args,arg=> UsesSpecFeatures(arg));
} else if (expr is OldExpr) {
OldExpr e = (OldExpr)expr;
return UsesSpecFeatures(e.E);
@@ -2368,28 +2453,31 @@ namespace Microsoft.Dafny {
if (UsesSpecFeatures(me.Source)) {
return true;
}
- return exists{MatchCaseExpr mc in me.Cases; UsesSpecFeatures(mc.Body)};
+ return Contract.Exists( me.Cases,mc=> UsesSpecFeatures(mc.Body));
} else {
- assert false; // unexpected expression
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected expression
}
}
}
class Scope<Thing> where Thing : class {
- [Rep] readonly List<string>! names = new List<string>(); // a null means a marker
- [Rep] readonly List<Thing?>! things = new List<Thing?>();
+ [Rep] readonly List<string> names = new List<string>(); // a null means a marker
+ [Rep] readonly List<Thing> things = new List<Thing>();
+ [ContractInvariantMethod]
+ void ObjectInvariant()
+ {
+ Contract.Invariant(names != null);
+ Contract.Invariant(things != null);
+ Contract.Invariant(names.Count == things.Count);
+ Contract.Invariant(-1 <= scopeSizeWhereInstancesWereDisallowed && scopeSizeWhereInstancesWereDisallowed <= names.Count);
+ }
+
int scopeSizeWhereInstancesWereDisallowed = -1;
- #region SpecSharp compiler annoyance
- invariant names.Count == things.Count;
- invariant -1 <= scopeSizeWhereInstancesWereDisallowed && scopeSizeWhereInstancesWereDisallowed <= names.Count;
- #endregion
-
public bool AllowInstance {
get { return scopeSizeWhereInstancesWereDisallowed == -1; }
set
- requires AllowInstance && !value; // only allowed to change from true to false (that's all that's currently needed in Dafny); Pop is what can make the change in the other direction
- {
+ {Contract.Requires( AllowInstance && !value); // only allowed to change from true to false (that's all that's currently needed in Dafny); Pop is what can make the change in the other direction
scopeSizeWhereInstancesWereDisallowed = names.Count;
}
}
@@ -2416,7 +2504,9 @@ namespace Microsoft.Dafny {
// Pushes name-->var association and returns "true", if name has not already been pushed since the last marker.
// If name already has been pushed since the last marker, does nothing and returns "false".
- public bool Push(string! name, Thing! thing) {
+ public bool Push(string name, Thing thing) {
+ Contract.Requires(name != null);
+ Contract.Requires(thing != null);
if (Find(name, true) != null) {
return false;
} else {
@@ -2426,7 +2516,8 @@ namespace Microsoft.Dafny {
}
}
- Thing? Find(string! name, bool topScopeOnly) {
+ Thing Find(string name, bool topScopeOnly) {
+ Contract.Requires(name != null);
for (int n = names.Count; 0 <= --n; ) {
if (names[n] == null) {
if (topScopeOnly) {
@@ -2434,14 +2525,15 @@ namespace Microsoft.Dafny {
}
} else if (names[n] == name) {
Thing t = things[n];
- assert t != null;
+ Contract.Assert( t != null);
return t;
}
}
return null; // not present
}
- public Thing? Find(string! name) {
+ public Thing Find(string name) {
+ Contract.Requires(name != null);
return Find(name, false);
}
}
diff --git a/Source/Dafny/Scanner.cs b/Source/Dafny/Scanner.cs
index dbff78e7..d3c761c1 100644
--- a/Source/Dafny/Scanner.cs
+++ b/Source/Dafny/Scanner.cs
@@ -4,9 +4,8 @@ using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;
-using Microsoft.Contracts;
+using System.Diagnostics.Contracts;
using Microsoft.Boogie;
-using BoogiePL;
namespace Microsoft.Dafny {
@@ -24,16 +23,21 @@ public class Buffer {
public const int EOF = 65535 + 1; // char.MaxValue + 1;
const int MIN_BUFFER_LENGTH = 1024; // 1KB
const int MAX_BUFFER_LENGTH = MIN_BUFFER_LENGTH * 64; // 64KB
- byte[]! buf; // input buffer
+ byte[]/*!*/ buf; // input buffer
int bufStart; // position of first byte in buffer relative to input stream
int bufLen; // length of buffer
int fileLen; // length of input stream (may change if the stream is no file)
int bufPos; // current position in buffer
- Stream! stream; // input stream (seekable)
+ Stream/*!*/ stream; // input stream (seekable)
bool isUserStream; // was the stream opened by the user?
+[ContractInvariantMethod]
+void ObjectInvariant(){
+ Contract.Invariant(buf != null);
+ Contract.Invariant(stream != null);}
[NotDelayed]
- public Buffer (Stream! s, bool isUserStream) {
+ public Buffer (Stream/*!*/ s, bool isUserStream) :base() {
+ Contract.Requires(s != null);
stream = s; this.isUserStream = isUserStream;
int fl, bl;
@@ -47,13 +51,14 @@ public class Buffer {
buf = new byte[(bl>0) ? bl : MIN_BUFFER_LENGTH];
fileLen = fl; bufLen = bl;
- base();
+
if (fileLen > 0) Pos = 0; // setup buffer to position 0 (start)
else bufPos = 0; // index 0 is already after the file, thus Pos = 0 is invalid
if (bufLen == fileLen && s.CanSeek) Close();
}
- protected Buffer(Buffer! b) { // called in UTF8Buffer constructor
+ protected Buffer(Buffer/*!*/ b) { // called in UTF8Buffer constructor
+ Contract.Requires(b != null);
buf = b.buf;
bufStart = b.bufStart;
bufLen = b.bufLen;
@@ -96,7 +101,8 @@ public class Buffer {
return ch;
}
- public string! GetString (int beg, int end) {
+ public string/*!*/ GetString (int beg, int end) {
+ Contract.Ensures(Contract.Result<string>() != null);
int len = 0;
char[] buf = new char[end - beg];
int oldPos = Pos;
@@ -163,7 +169,7 @@ public class Buffer {
// UTF8Buffer
//-----------------------------------------------------------------------------------
public class UTF8Buffer: Buffer {
- public UTF8Buffer(Buffer! b): base(b) {}
+ public UTF8Buffer(Buffer/*!*/ b): base(b) {Contract.Requires(b != null);}
public override int Read() {
int ch;
@@ -207,24 +213,35 @@ public class Scanner {
const int noSym = 103;
- public Buffer! buffer; // scanner buffer
+[ContractInvariantMethod]
+void objectInvariant(){
+ Contract.Invariant(buffer!=null);
+ Contract.Invariant(t != null);
+ Contract.Invariant(start != null);
+ Contract.Invariant(tokens != null);
+ Contract.Invariant(pt != null);
+ Contract.Invariant(tval != null);
+ Contract.Invariant(Filename != null);
+ Contract.Invariant(errorHandler != null);
+}
+ public Buffer/*!*/ buffer; // scanner buffer
- Token! t; // current token
+ Token/*!*/ t; // current token
int ch; // current input character
int pos; // byte position of current character
int col; // column number of current character
int line; // line number of current character
int oldEols; // EOLs that appeared in a comment;
- static readonly Hashtable! start; // maps first token character to start state
+ static readonly Hashtable/*!*/ start; // maps first token character to start state
- Token! tokens; // list of tokens already peeked (first token is a dummy)
- Token! pt; // current peek token
+ Token/*!*/ tokens; // list of tokens already peeked (first token is a dummy)
+ Token/*!*/ pt; // current peek token
- char[]! tval = new char[128]; // text of current token
+ char[]/*!*/ tval = new char[128]; // text of current token
int tlen; // length of current token
- private string! Filename;
- private Errors! errorHandler;
+ private string/*!*/ Filename;
+ private Errors/*!*/ errorHandler;
static Scanner() {
start = new Hashtable(128);
@@ -275,7 +292,9 @@ public class Scanner {
}
[NotDelayed]
- public Scanner (string! fileName, Errors! errorHandler) {
+ public Scanner (string/*!*/ fileName, Errors/*!*/ errorHandler) :base(){
+ Contract.Requires(fileName != null);
+ Contract.Requires(errorHandler != null);
this.errorHandler = errorHandler;
pt = tokens = new Token(); // first token is a dummy
t = new Token(); // dummy because t is a non-null field
@@ -283,7 +302,7 @@ public class Scanner {
Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
buffer = new Buffer(stream, false);
Filename = fileName;
- base();
+
Init();
} catch (IOException) {
throw new FatalError("Cannot open file " + fileName);
@@ -291,13 +310,16 @@ public class Scanner {
}
[NotDelayed]
- public Scanner (Stream! s, Errors! errorHandler, string! fileName) {
+ public Scanner (Stream/*!*/ s, Errors/*!*/ errorHandler, string/*!*/ fileName) :base(){
+ Contract.Requires(s != null);
+ Contract.Requires(errorHandler != null);
+ Contract.Requires(fileName != null);
pt = tokens = new Token(); // first token is a dummy
t = new Token(); // dummy because t is a non-null field
buffer = new Buffer(s, true);
this.errorHandler = errorHandler;
this.Filename = fileName;
- base();
+
Init();
}
@@ -317,7 +339,8 @@ public class Scanner {
pt = tokens = new Token(); // first token is a dummy
}
- string! ReadToEOL(){
+ string/*!*/ ReadToEOL(){
+ Contract.Ensures(Contract.Result<string>() != null);
int p = buffer.Pos;
int ch = buffer.Read();
// replace isolated '\r' by '\n' in order to make
@@ -329,7 +352,8 @@ public class Scanner {
// eol handling uniform across Windows, Unix and Mac
if (ch == '\r' && buffer.Peek() != '\n') ch = EOL;
}
- string! s = buffer.GetString(p, buffer.Pos);
+ string/*!*/ s = buffer.GetString(p, buffer.Pos);
+ Contract.Assert(s!=null);
return s;
}
@@ -355,7 +379,8 @@ public class Scanner {
int prLine = line;
int prColumn = 0;
- string! hashLine = ReadToEOL();
+ string/*!*/ hashLine = ReadToEOL();
+ Contract.Assert(hashLine!=null);
col = 0;
line++;
@@ -518,7 +543,8 @@ public class Scanner {
}
}
- Token! NextToken() {
+ Token/*!*/ NextToken() {
+ Contract.Ensures(Contract.Result<Token>() != null);
while (ch == ' ' ||
ch >= 9 && ch <= 10 || ch == 13
) NextCh();
@@ -529,7 +555,7 @@ public class Scanner {
t.pos = pos; t.col = col; t.line = line;
t.filename = this.Filename;
int state;
- if (start.ContainsKey(ch)) { state = (int) (!) start[ch]; }
+ if (start.ContainsKey(ch)) { state = (int) cce.NonNull( start[ch]); }
else { state = 0; }
tlen = 0; AddCh();
@@ -694,7 +720,8 @@ public class Scanner {
}
// get the next token (possibly a token already seen during peeking)
- public Token! Scan () {
+ public Token/*!*/ Scan () {
+ Contract.Ensures(Contract.Result<Token>() != null);
if (tokens.next == null) {
return NextToken();
} else {
@@ -704,7 +731,8 @@ public class Scanner {
}
// peek for the next token, ignore pragmas
- public Token! Peek () {
+ public Token/*!*/ Peek () {
+ Contract.Ensures(Contract.Result<Token>() != null);
do {
if (pt.next == null) {
pt.next = NextToken();
diff --git a/Source/Dafny/SccGraph.cs b/Source/Dafny/SccGraph.cs
index 0498f55d..c7be5420 100644
--- a/Source/Dafny/SccGraph.cs
+++ b/Source/Dafny/SccGraph.cs
@@ -1,4 +1,6 @@
+using System;
using System.Collections.Generic;
+using System.Diagnostics.Contracts;
namespace Microsoft.Dafny {
@@ -7,9 +9,18 @@ namespace Microsoft.Dafny {
enum VisitedStatus { Unvisited, OnStack, Visited }
class Vertex {
public readonly Node N;
- public readonly List<Vertex!>! Successors = new List<Vertex!>();
+ public readonly List<Vertex/*!*/>/*!*/ Successors = new List<Vertex/*!*/>();
+ public List<Vertex/*!*/> SccMembers; // non-null only for the representative of the SCC
+ [ContractInvariantMethod]
+void ObjectInvariant()
+{
+ Contract.Invariant(cce.NonNullElements(Successors));
+ if(SccMembers!=null)
+ Contract.Invariant(cce.NonNullElements(SccMembers));
+}
+
public Vertex SccRepresentative; // null if not computed
- public List<Vertex!> SccMembers; // non-null only for the representative of the SCC
+
public int SccId; // valid only for SCC representatives; indicates position of this representative vertex in the graph's topological sort
// the following field is used during the computation of SCCs and of reachability
public VisitedStatus Visited;
@@ -22,18 +33,31 @@ namespace Microsoft.Dafny {
public Vertex(Node n) {
N = n;
}
- public void AddSuccessor(Vertex! v) {
- Successors.Add(v);
+ public void AddSuccessor(Vertex v) {
+ Contract.Requires(v != null);
+ Successors.Add(v);
}
}
- Dictionary<Node, Vertex!>! vertices = new Dictionary<Node, Vertex!>();
+
+
+[ContractInvariantMethod]
+void ObjectInvariant()
+{
+ Contract.Invariant(vertices!=null);
+ Contract.Invariant(cce.NonNullElements(vertices.Values));
+ if(topologicallySortedRepresentatives!=null)
+ Contract.Invariant(cce.NonNullElements(topologicallySortedRepresentatives));
+ Contract.Invariant(!sccComputed || topologicallySortedRepresentatives != null);
+}
+
+ Dictionary<Node, Vertex/*!*/>/*!*/ vertices = new Dictionary<Node, Vertex/*!*/>();
bool sccComputed = false;
- List<Vertex!> topologicallySortedRepresentatives; // computed by the SCC computation
- invariant sccComputed ==> topologicallySortedRepresentatives != null;
+ List<Vertex/*!*/> topologicallySortedRepresentatives; // computed by the SCC computation
+
public int SccCount {
get {
ComputeSCCs();
- assert topologicallySortedRepresentatives != null; // follows from postcondition of ComputeSCCs and the object invariant
+ Contract.Assert( topologicallySortedRepresentatives != null); // follows from postcondition of ComputeSCCs and the object invariant
return topologicallySortedRepresentatives.Count;
}
}
@@ -53,15 +77,17 @@ namespace Microsoft.Dafny {
/// <summary>
/// Idempotently adds a vertex 'n' to the graph and then returns the Vertex for it.
/// </summary>
- Vertex! GetVertex(Node n) {
+ Vertex GetVertex(Node n) {
+ Contract.Ensures(Contract.Result<Vertex>() != null);
+
Vertex v = FindVertex(n);
if (v == null) {
v = new Vertex(n);
vertices.Add(n, v);
if (sccComputed) {
- assert topologicallySortedRepresentatives != null; // follows from object invariant
+ Contract.Assert( topologicallySortedRepresentatives != null); // follows from object invariant
v.SccRepresentative = v;
- v.SccMembers = new List<Vertex!>();
+ v.SccMembers = new List<Vertex>();
v.SccMembers.Add(v);
v.SccId = topologicallySortedRepresentatives.Count;
topologicallySortedRepresentatives.Add(v);
@@ -76,7 +102,7 @@ namespace Microsoft.Dafny {
Vertex FindVertex(Node n) {
Vertex v;
if (vertices.TryGetValue(n, out v)) {
- assert v != null; // follows from postcondition of TryGetValue (since 'vertices' maps to the type Vertex!)
+ Contract.Assert( v != null); // follows from postcondition of TryGetValue (since 'vertices' maps to the type Vertex!)
return v;
} else {
return null;
@@ -110,19 +136,22 @@ namespace Microsoft.Dafny {
return GetSCCRepr(n).SccId;
}
- Vertex! GetSCCRepr(Node n) {
+ Vertex GetSCCRepr(Node n) {
+ Contract.Ensures(Contract.Result<Vertex>() != null);
+
Vertex v = GetVertex(n);
ComputeSCCs();
- assert v.SccRepresentative != null; // follows from what ComputeSCCs does
+ Contract.Assert( v.SccRepresentative != null); // follows from what ComputeSCCs does
return v.SccRepresentative;
}
/// <summary>
/// Returns a list of the topologically sorted SCCs, each represented in the list by its representative node.
/// </summary>
- public List<Node>! TopologicallySortedComponents() {
+ public List<Node> TopologicallySortedComponents() {
+ Contract.Ensures(cce.NonNullElements(Contract.Result<List<Node>>()));
ComputeSCCs();
- assert topologicallySortedRepresentatives != null; // follows from object invariant
+ Contract.Assert( topologicallySortedRepresentatives != null); // follows from object invariant
List<Node> nn = new List<Node>();
foreach (Vertex v in topologicallySortedRepresentatives) {
nn.Add(v.N);
@@ -134,11 +163,11 @@ namespace Microsoft.Dafny {
/// Idempotently adds 'n' as a vertex and then returns the set of Node's in the strongly connected component
/// that contains 'n'.
/// </summary>
- public List<Node>! GetSCC(Node n) {
+ public List<Node> GetSCC(Node n) {Contract.Ensures(cce.NonNullElements(Contract.Result<List<Node>>()));
Vertex v = GetVertex(n);
ComputeSCCs();
Vertex repr = v.SccRepresentative;
- assert repr != null && repr.SccMembers != null; // follows from postcondition of ComputeSCCs
+ Contract.Assert( repr != null && repr.SccMembers != null); // follows from postcondition of ComputeSCCs
List<Node> nn = new List<Node>();
foreach (Vertex w in repr.SccMembers) {
nn.Add(w.N);
@@ -150,13 +179,13 @@ namespace Microsoft.Dafny {
/// Idempotently adds 'n' as a vertex and then returns the size of the set of Node's in the strongly connected component
/// that contains 'n'.
/// </summary>
- public int GetSCCSize(Node n)
- ensures 1 <= result;
- {
+ public int GetSCCSize(Node n){
+ Contract.Ensures( 1 <= Contract.Result<int>());
+
Vertex v = GetVertex(n);
ComputeSCCs();
Vertex repr = v.SccRepresentative;
- assert repr != null && repr.SccMembers != null; // follows from postcondition of ComputeSCCs
+ Contract.Assert( repr != null && repr.SccMembers != null); // follows from postcondition of ComputeSCCs
return repr.SccMembers.Count;
}
@@ -168,24 +197,25 @@ namespace Microsoft.Dafny {
/// of the vertices.
/// </summary>
void ComputeSCCs()
- ensures sccComputed;
{
+ Contract.Ensures( sccComputed);
+
if (sccComputed) { return; } // check if already computed
// reset all SCC information
- topologicallySortedRepresentatives = new List<Vertex!>();
+ topologicallySortedRepresentatives = new List<Vertex>();
foreach (Vertex v in vertices.Values) {
v.Visited = VisitedStatus.Unvisited;
v.SccMembers = null;
}
- Stack<Vertex!> stack = new Stack<Vertex!>();
+ Stack<Vertex> stack = new Stack<Vertex>();
int cnt = 0;
foreach (Vertex v in vertices.Values) {
if (v.Visited == VisitedStatus.Unvisited) {
SearchC(v, stack, ref cnt);
}
}
- assert cnt == vertices.Count; // sanity check that everything has been visited
+ Contract.Assert( cnt == vertices.Count); // sanity check that everything has been visited
sccComputed = true;
}
@@ -193,11 +223,13 @@ namespace Microsoft.Dafny {
/// <summary>
/// This is the 'SearchC' procedure from the Aho, Hopcroft, and Ullman book 'The Design and Analysis of Computer Algorithms'.
/// </summary>
- void SearchC(Vertex! v, Stack<Vertex!>! stack, ref int cnt)
- requires v.Visited == VisitedStatus.Unvisited;
- requires topologicallySortedRepresentatives != null;
- ensures v.Visited != VisitedStatus.Unvisited;
- {
+ void SearchC(Vertex/*!*/ v, Stack<Vertex/*!*/>/*!*/ stack, ref int cnt){
+ Contract.Requires(v != null);
+ Contract.Requires(cce.NonNullElements(stack));
+ Contract.Requires( v.Visited == VisitedStatus.Unvisited);
+ Contract.Requires( topologicallySortedRepresentatives != null);
+ Contract.Ensures( v.Visited != VisitedStatus.Unvisited);
+
v.DfNumber = cnt;
cnt++;
v.LowLink = v.DfNumber;
@@ -207,10 +239,10 @@ namespace Microsoft.Dafny {
foreach (Vertex w in v.Successors) {
if (w.Visited == VisitedStatus.Unvisited) {
SearchC(w, stack, ref cnt);
- v.LowLink = min{v.LowLink, w.LowLink};
+ v.LowLink = Math.Min(v.LowLink, w.LowLink);
} else if (w.Visited == VisitedStatus.OnStack) {
- assert w.DfNumber < v.DfNumber || v.LowLink <= w.DfNumber; // the book also has the guard 'w.DfNumber < v.DfNumber', but that seems unnecessary to me, so this assert is checking my understanding
- v.LowLink = min{v.LowLink, w.DfNumber};
+ Contract.Assert( w.DfNumber < v.DfNumber || v.LowLink <= w.DfNumber); // the book also has the guard 'w.DfNumber < v.DfNumber', but that seems unnecessary to me, so this assert is checking my understanding
+ v.LowLink = Math.Min(v.LowLink, w.DfNumber);
}
}
@@ -218,7 +250,7 @@ namespace Microsoft.Dafny {
// The SCC containing 'v' has now been computed.
v.SccId = topologicallySortedRepresentatives.Count;
topologicallySortedRepresentatives.Add(v);
- v.SccMembers = new List<Vertex!>();
+ v.SccMembers = new List<Vertex>();
while (true) {
Vertex x = stack.Pop();
x.Visited = VisitedStatus.Visited;
@@ -240,13 +272,13 @@ namespace Microsoft.Dafny {
}
foreach (Vertex v in vertices.Values) {
- assert v.Visited != VisitedStatus.OnStack;
+ Contract.Assert( v.Visited != VisitedStatus.OnStack);
if (v.Visited == VisitedStatus.Unvisited) {
- List<Vertex!> cycle = CycleSearch(v);
+ List<Vertex> cycle = CycleSearch(v);
if (cycle != null) {
List<Node> nodes = new List<Node>();
- foreach (Vertex v in cycle) {
- nodes.Add(v.N);
+ foreach (Vertex v_ in cycle) {
+ nodes.Add(v_.N);
}
return nodes; // a cycle is found
}
@@ -263,12 +295,14 @@ namespace Microsoft.Dafny {
/// w on the stack followed by the vertices (in reverse order) in the returned list, where
/// w is the first vertex in the list returned.
/// </summary>
- List<Vertex!> CycleSearch(Vertex! v)
- requires v.Visited == VisitedStatus.Unvisited;
- ensures v.Visited != VisitedStatus.Unvisited;
- ensures result == null ==> v.Visited == VisitedStatus.Visited;
- ensures result != null ==> result.Count != 0;
+ List<Vertex/*!*/> CycleSearch(Vertex v)
{
+ Contract.Requires(v != null);
+ Contract.Requires( v.Visited == VisitedStatus.Unvisited);
+ Contract.Ensures( v.Visited != VisitedStatus.Unvisited);
+ Contract.Ensures( Contract.Result<List<Vertex>>() != null || v.Visited == VisitedStatus.Visited);
+ Contract.Ensures( Contract.Result<List<Vertex>>() == null || Contract.Result<List<Vertex>>().Count != 0);
+
v.Visited = VisitedStatus.OnStack;
foreach (Vertex succ in v.Successors) {
// todo: I would use a 'switch' statement, but there seems to be a bug in the Spec# compiler's type checking.
@@ -276,7 +310,7 @@ namespace Microsoft.Dafny {
// there is no cycle in the subtree rooted at succ, hence this path does not give rise to any cycles
} else if (succ.Visited == VisitedStatus.OnStack) {
// we found a cycle!
- List<Vertex!> cycle = new List<Vertex!>();
+ List<Vertex> cycle = new List<Vertex>();
cycle.Add(succ);
if (v == succ) {
// entire cycle has been found
@@ -284,8 +318,8 @@ namespace Microsoft.Dafny {
}
return cycle;
} else {
- assert succ.Visited == VisitedStatus.Unvisited;
- List<Vertex!> cycle = CycleSearch(succ);
+ Contract.Assert( succ.Visited == VisitedStatus.Unvisited);
+ List<Vertex> cycle = CycleSearch(succ);
if (cycle != null) {
if (succ.Visited == VisitedStatus.Visited) {
// the entire cycle has been collected
@@ -321,7 +355,9 @@ namespace Microsoft.Dafny {
return ReachSearch(a, b);
}
- bool ReachSearch(Vertex! source, Vertex! sink) {
+ bool ReachSearch(Vertex source, Vertex sink) {
+ Contract.Requires(source != null);
+ Contract.Requires(sink != null);
if (source == sink) {
return true;
} else if (source.Gen == generation) {
@@ -329,7 +365,7 @@ namespace Microsoft.Dafny {
return false;
} else {
source.Gen = generation;
- return exists{Vertex succ in source.Successors; ReachSearch(succ, sink)};
+ return Contract.Exists(source.Successors,succ=> ReachSearch(succ, sink));
}
}
}
diff --git a/Source/Dafny/Translator.cs b/Source/Dafny/Translator.cs
index e80f546b..df597dad 100644
--- a/Source/Dafny/Translator.cs
+++ b/Source/Dafny/Translator.cs
@@ -6,7 +6,7 @@
using System;
using System.Collections.Generic;
using System.Numerics;
-using Microsoft.Contracts;
+using System.Diagnostics.Contracts;
using Bpl = Microsoft.Boogie;
using System.Text;
using Microsoft.Boogie;
@@ -20,26 +20,42 @@ namespace Microsoft.Dafny {
sink = boogieProgram;
predef = FindPredefinedDecls(boogieProgram);
}
- base();
+ //base();
if (predef != null) {
cevVariables.Add(predef.HeapVarName, predef.CevHeapName);
}
}
// translation state
- readonly Dictionary<TopLevelDecl!,Bpl.Constant!>! classes = new Dictionary<TopLevelDecl!,Bpl.Constant!>();
- readonly Dictionary<Field!,Bpl.Constant!>! fields = new Dictionary<Field!,Bpl.Constant!>();
+ readonly Dictionary<TopLevelDecl/*!*/,Bpl.Constant/*!*/>/*!*/ classes = new Dictionary<TopLevelDecl/*!*/,Bpl.Constant/*!*/>();
+ readonly Dictionary<Field/*!*/,Bpl.Constant/*!*/>/*!*/ fields = new Dictionary<Field/*!*/,Bpl.Constant/*!*/>();
// Machinery for providing information to the Counterexample Visualizer
- readonly Dictionary<string!,int>! cevFilenames = new Dictionary<string!,int>();
- readonly Dictionary<IToken!,Bpl.Constant!>! cevLocations = new Dictionary<IToken!,Bpl.Constant!>();
- readonly Dictionary<string!,Bpl.Constant!>! cevVariables = new Dictionary<string!,Bpl.Constant!>();
- Bpl.Expr! CevLocation(IToken! tok)
- requires predef != null && sink != null;
- {
+ readonly Dictionary<string/*!*/,int>/*!*/ cevFilenames = new Dictionary<string/*!*/,int>();
+ readonly Dictionary<IToken/*!*/,Bpl.Constant/*!*/>/*!*/ cevLocations = new Dictionary<IToken/*!*/,Bpl.Constant/*!*/>();
+ readonly Dictionary<string/*!*/,Bpl.Constant/*!*/>/*!*/ cevVariables = new Dictionary<string/*!*/,Bpl.Constant/*!*/>();
+
+ [ContractInvariantMethod]
+void ObjectInvariant()
+{
+ Contract.Invariant(cce.NonNullElements(classes));
+ Contract.Invariant(cce.NonNullElements(fields));
+ Contract.Invariant(cce.NonNullElements(cevFilenames));
+ Contract.Invariant(cce.NonNullElements(cevLocations));
+ Contract.Invariant(cce.NonNullElements(cevVariables));
+}
+
+
+ Bpl.Expr CevLocation(IToken tok)
+ {
+ Contract.Requires(tok != null);
+ Contract.Requires( predef != null && sink != null);
+ Contract.Ensures(Contract.Result<Bpl.Expr>() != null);
+
+
Bpl.Constant c;
if (cevLocations.TryGetValue(tok, out c)) {
- assert c != null;
+ Contract.Assert( c != null);
} else {
int fileId;
string filename = "#file^" + (tok.filename == null ? ".dfy" : tok.filename);
@@ -56,7 +72,10 @@ namespace Microsoft.Dafny {
}
return new Bpl.IdentifierExpr(tok, c);
}
- static string! Sanitize(string! s) {
+ static string Sanitize(string s) {
+ Contract.Requires(s != null);
+ Contract.Ensures(Contract.Result<string>() != null);
+
StringBuilder sb = new StringBuilder();
foreach (char ch in s) {
if (char.IsLetterOrDigit(ch) || ch == '#' || ch == '^' || ch == '$' || ch == '.' || ch == '@') {
@@ -67,12 +86,17 @@ namespace Microsoft.Dafny {
}
return sb.ToString();
}
- Bpl.Expr! CevVariable(Bpl.IToken! tok, string! name)
- requires predef != null && sink != null;
+ Bpl.Expr CevVariable(Bpl.IToken tok, string name)
{
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires( predef != null && sink != null);
+ Contract.Ensures(Contract.Result<Bpl.Expr>() != null);
+
+
Bpl.Constant c;
if (cevVariables.TryGetValue(name, out c)) {
- assert c != null;
+ Contract.Assert( c != null);
} else {
c = new Bpl.Constant(tok, new Bpl.TypedIdent(tok, string.Format("#loc.{0}", name), predef.CevTokenType), true);
cevVariables.Add(name, c);
@@ -83,42 +107,102 @@ namespace Microsoft.Dafny {
readonly Bpl.Program sink;
readonly PredefinedDecls predef;
+
internal class PredefinedDecls {
- public readonly Bpl.Type! RefType;
- public readonly Bpl.Type! BoxType;
- public readonly Bpl.Type! CevTokenType;
- public readonly Bpl.Type! CevVariableKind;
- public readonly Bpl.Type! CevEventType;
- private readonly Bpl.TypeSynonymDecl! setTypeCtor;
- public Bpl.Type! SetType(IToken! tok, Bpl.Type! ty) {
+ public readonly Bpl.Type RefType;
+ public readonly Bpl.Type BoxType;
+ public readonly Bpl.Type CevTokenType;
+ public readonly Bpl.Type CevVariableKind;
+ public readonly Bpl.Type CevEventType;
+ private readonly Bpl.TypeSynonymDecl setTypeCtor;
+ private readonly Bpl.TypeCtorDecl seqTypeCtor;
+ readonly Bpl.TypeCtorDecl fieldName;
+ public readonly Bpl.Type HeapType;
+ public readonly string HeapVarName;
+ public readonly Bpl.Constant CevHeapName;
+ public readonly Bpl.Type ClassNameType;
+ public readonly Bpl.Type FieldCategoryType;
+ public readonly Bpl.Type DatatypeType;
+ public readonly Bpl.Type DtCtorId;
+ public readonly Bpl.Expr Null;
+ private readonly Bpl.Constant allocField;
+ [ContractInvariantMethod]
+ void ObjectInvariant()
+{
+ Contract.Invariant(RefType!=null);
+ Contract.Invariant(BoxType != null);
+ Contract.Invariant(CevTokenType != null);
+ Contract.Invariant(CevVariableKind != null);
+ Contract.Invariant(CevEventType != null);
+ Contract.Invariant(setTypeCtor != null);
+ Contract.Invariant(seqTypeCtor != null);
+ Contract.Invariant(fieldName != null);
+ Contract.Invariant(HeapType != null);
+ Contract.Invariant(HeapVarName != null);
+ Contract.Invariant(CevEventType != null);
+ Contract.Invariant(ClassNameType != null);
+ Contract.Invariant(FieldCategoryType != null);
+ Contract.Invariant(DatatypeType != null);
+ Contract.Invariant(DtCtorId != null);
+ Contract.Invariant(Null != null);
+ Contract.Invariant(allocField != null);
+}
+
+
+ public Bpl.Type SetType(IToken tok, Bpl.Type ty) {
+ Contract.Requires(tok != null);
+ Contract.Requires(ty != null);
+ Contract.Ensures(Contract.Result<Bpl.Type>() != null);
+
return new Bpl.TypeSynonymAnnotation(Token.NoToken, setTypeCtor, new Bpl.TypeSeq(ty));
}
- private readonly Bpl.TypeCtorDecl! seqTypeCtor;
- public Bpl.Type! SeqType(IToken! tok, Bpl.Type! ty) {
+
+ public Bpl.Type SeqType(IToken tok, Bpl.Type ty) {
+ Contract.Requires(tok != null);
+ Contract.Requires(ty != null);
+ Contract.Ensures(Contract.Result<Bpl.Type>() != null);
return new Bpl.CtorType(Token.NoToken, seqTypeCtor, new Bpl.TypeSeq(ty));
}
- readonly Bpl.TypeCtorDecl! fieldName;
- public Bpl.Type! FieldName(IToken! tok, Bpl.Type! ty) {
+
+ public Bpl.Type FieldName(IToken tok, Bpl.Type ty) {
+ Contract.Requires(tok != null);
+ Contract.Requires(ty != null);
+ Contract.Ensures(Contract.Result<Bpl.Type>() != null);
+
return new Bpl.CtorType(tok, fieldName, new Bpl.TypeSeq(ty));
}
- public readonly Bpl.Type! HeapType;
- public readonly string! HeapVarName;
- public readonly Bpl.Constant! CevHeapName;
- public readonly Bpl.Type! ClassNameType;
- public readonly Bpl.Type! FieldCategoryType;
- public readonly Bpl.Type! DatatypeType;
- public readonly Bpl.Type! DtCtorId;
- public readonly Bpl.Expr! Null;
- private readonly Bpl.Constant! allocField;
- public Bpl.IdentifierExpr! Alloc(IToken! tok) {
+
+ public Bpl.IdentifierExpr Alloc(IToken tok) {
+ Contract.Requires(tok != null);
+ Contract.Ensures(Contract.Result<Bpl.IdentifierExpr>() != null);
+
return new Bpl.IdentifierExpr(tok, allocField);
}
- public PredefinedDecls(Bpl.TypeCtorDecl! refType, Bpl.TypeCtorDecl! boxType, Bpl.TypeCtorDecl! cevTokenType, Bpl.TypeCtorDecl! cevVariableKind, Bpl.TypeCtorDecl! cevEventType,
- Bpl.TypeSynonymDecl! setTypeCtor, Bpl.TypeCtorDecl! seqTypeCtor, Bpl.TypeCtorDecl! fieldNameType,
- Bpl.GlobalVariable! heap, Bpl.TypeCtorDecl! classNameType, Bpl.TypeCtorDecl! fieldCategoryType,
- Bpl.TypeCtorDecl! datatypeType, Bpl.TypeCtorDecl! dtCtorId,
- Bpl.Constant! allocField, Bpl.Constant! cevHeapNameConst) {
+ public PredefinedDecls(Bpl.TypeCtorDecl refType, Bpl.TypeCtorDecl boxType, Bpl.TypeCtorDecl cevTokenType,
+ Bpl.TypeCtorDecl cevVariableKind, Bpl.TypeCtorDecl cevEventType,
+ Bpl.TypeSynonymDecl setTypeCtor, Bpl.TypeCtorDecl seqTypeCtor, Bpl.TypeCtorDecl fieldNameType,
+ Bpl.GlobalVariable heap, Bpl.TypeCtorDecl classNameType, Bpl.TypeCtorDecl fieldCategoryType,
+ Bpl.TypeCtorDecl datatypeType, Bpl.TypeCtorDecl dtCtorId,
+ Bpl.Constant allocField, Bpl.Constant cevHeapNameConst) {
+ #region Non-null preconditions on parameters
+ Contract.Requires(refType != null);
+ Contract.Requires(boxType != null);
+ Contract.Requires(cevTokenType != null);
+ Contract.Requires(cevVariableKind != null);
+ Contract.Requires(cevEventType != null);
+ Contract.Requires(setTypeCtor != null);
+ Contract.Requires(seqTypeCtor != null);
+ Contract.Requires(fieldNameType != null);
+ Contract.Requires(heap != null);
+ Contract.Requires(classNameType != null);
+ Contract.Requires(fieldCategoryType != null);
+ Contract.Requires(datatypeType != null);
+ Contract.Requires(dtCtorId != null);
+ Contract.Requires(allocField != null);
+ Contract.Requires(cevHeapNameConst != null);
+ #endregion
+
Bpl.CtorType refT = new Bpl.CtorType(Token.NoToken, refType, new Bpl.TypeSeq());
this.RefType = refT;
this.BoxType = new Bpl.CtorType(Token.NoToken, boxType, new Bpl.TypeSeq());
@@ -140,7 +224,8 @@ namespace Microsoft.Dafny {
}
}
- static PredefinedDecls FindPredefinedDecls(Bpl.Program! prog) {
+ static PredefinedDecls FindPredefinedDecls(Bpl.Program prog) {
+ Contract.Requires(prog != null);
if (prog.Resolve() != 0) {
Console.WriteLine("Error: resolution errors encountered in Dafny prelude");
return null;
@@ -245,9 +330,9 @@ namespace Microsoft.Dafny {
}
static Bpl.Program ReadPrelude() {
- //using (System.IO.Stream stream = (!) System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("DafnyPrelude.bpl")) // Use this once Spec#/VSIP supports designating a non-.resx project item as an embedded resource
- string! codebase = (!) System.IO.Path.GetDirectoryName((!)System.Reflection.Assembly.GetExecutingAssembly().Location);
- string! preludePath = System.IO.Path.Combine(codebase, "DafnyPrelude.bpl");
+ //using (System.IO.Stream stream = cce.NonNull( System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("DafnyPrelude.bpl")) // Use this once Spec#/VSIP supports designating a non-.resx project item as an embedded resource
+ string codebase = cce.NonNull( System.IO.Path.GetDirectoryName(cce.NonNull(System.Reflection.Assembly.GetExecutingAssembly().Location)));
+ string preludePath = System.IO.Path.Combine(codebase, "DafnyPrelude.bpl");
Bpl.Program prelude;
int errorCount = Bpl.Parser.Parse(preludePath, null, out prelude);
@@ -273,7 +358,10 @@ namespace Microsoft.Dafny {
*/
}
- public Bpl.Program! Translate(Program! program) {
+ public Bpl.Program Translate(Program program) {
+ Contract.Requires(program != null);
+ Contract.Ensures(Contract.Result<Bpl.Program>() != null);
+
if (sink == null || predef == null) {
// something went wrong during construction, which reads the prelude; an error has
// already been printed, so just return an empty program here (which is non-null)
@@ -291,9 +379,11 @@ namespace Microsoft.Dafny {
return sink;
}
- void AddDatatype(DatatypeDecl! dt)
- requires sink != null && predef != null;
+ void AddDatatype(DatatypeDecl dt)
{
+ Contract.Requires(dt != null);
+ Contract.Requires( sink != null && predef != null);
+
foreach (DatatypeCtor ctor in dt.Ctors) {
// Add: function #dt.ctor(paramTypes) returns (DatatypeType);
Bpl.VariableSeq argTypes = new Bpl.VariableSeq();
@@ -308,8 +398,8 @@ namespace Microsoft.Dafny {
Bpl.Constant cid = new Bpl.Constant(ctor.tok, new Bpl.TypedIdent(ctor.tok, "#" + ctor.FullName, predef.DtCtorId), true);
sink.TopLevelDeclarations.Add(cid);
// Add: axiom (forall params :: DatatypeCtorId(#dt.ctor(params)) == ##dt.ctor);
- Bpl.VariableSeq! bvs;
- List<Bpl.Expr!>! args;
+ Bpl.VariableSeq bvs;
+ List<Bpl.Expr> args;
CreateBoundVariables(ctor.Formals, out bvs, out args);
Bpl.Expr lhs = FunctionCall(ctor.tok, ctor.FullName, predef.DatatypeType, args);
lhs = FunctionCall(ctor.tok, BuiltinFunction.DatatypeCtorId, null, lhs);
@@ -381,21 +471,31 @@ namespace Microsoft.Dafny {
}
}
- void CreateBoundVariables(List<Formal!>! formals, out Bpl.VariableSeq! bvs, out List<Bpl.Expr!>! args)
- ensures bvs.Length == args.Count;
+ void CreateBoundVariables(List<Formal/*!*/>/*!*/ formals, out Bpl.VariableSeq/*!*/ bvs, out List<Bpl.Expr/*!*/>/*!*/ args)
{
+ Contract.Requires(formals != null);
+
+
+ Contract.Ensures( Contract.ValueAtReturn(out bvs).Length == Contract.ValueAtReturn(out args).Count);
+ Contract.Ensures(Contract.ValueAtReturn(out bvs) != null);
+ Contract.Ensures(cce.NonNullElements(Contract.ValueAtReturn(out args)));
+
+
bvs = new Bpl.VariableSeq();
- args = new List<Bpl.Expr!>();
+ args = new List<Bpl.Expr>();
foreach (Formal arg in formals) {
+ Contract.Assert(arg != null);
Bpl.Variable bv = new Bpl.BoundVariable(arg.tok, new Bpl.TypedIdent(arg.tok, "a" + bvs.Length, TrType(arg.Type)));
bvs.Add(bv);
args.Add(new Bpl.IdentifierExpr(arg.tok, bv));
}
}
- void AddClassMembers(ClassDecl! c)
- requires sink != null && predef != null;
+ void AddClassMembers(ClassDecl c)
{
+ Contract.Requires( sink != null && predef != null);
+
+ Contract.Requires(c != null);
sink.TopLevelDeclarations.Add(GetClass(c));
foreach (MemberDecl member in c.Members) {
@@ -414,7 +514,7 @@ namespace Microsoft.Dafny {
MatchExpr me = (MatchExpr)f.Body;
Formal formal = (Formal)((IdentifierExpr)me.Source).Var; // correctness of casts follows from what resolution checks
foreach (MatchCaseExpr mc in me.Cases) {
- assert mc.Ctor != null; // the field is filled in by resolution
+ Contract.Assert( mc.Ctor != null); // the field is filled in by resolution
Bpl.Axiom ax = FunctionAxiom(f, mc.Body, formal, mc.Ctor, mc.Arguments);
sink.TopLevelDeclarations.Add(ax);
}
@@ -452,18 +552,21 @@ namespace Microsoft.Dafny {
// TODO: define a well-foundedness condition to check
} else {
- assert false; // unexpected member
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected member
}
}
}
- Bpl.Axiom! FunctionAxiom(Function! f, Expression! body, Formal specializationFormal,
- DatatypeCtor ctor, List<BoundVar!> specializationReplacementFormals)
- requires predef != null;
- requires specializationFormal == null <==> ctor == null;
- requires specializationFormal == null <==> specializationReplacementFormals == null;
- requires f.EnclosingClass != null;
- {
+ Bpl.Axiom/*!*/ FunctionAxiom(Function/*!*/ f, Expression/*!*/ body, Formal specializationFormal,
+ DatatypeCtor ctor, List<BoundVar/*!*/> specializationReplacementFormals){
+ Contract.Requires(f != null);
+ Contract.Requires(body != null);
+ Contract.Requires(cce.NonNullElements(specializationReplacementFormals));
+ Contract.Requires( predef != null);
+ Contract.Requires( specializationFormal == null && ctor == null);
+ Contract.Requires( specializationFormal == null && specializationReplacementFormals == null);
+ Contract.Requires( f.EnclosingClass != null);
+
ExpressionTranslator etran = new ExpressionTranslator(this, predef, f.tok);
// axiom
@@ -504,8 +607,8 @@ namespace Microsoft.Dafny {
}
DatatypeValue r = null;
if (specializationReplacementFormals != null) {
- assert ctor != null; // follows from if guard and the precondition
- List<Expression!> rArgs = new List<Expression!>();
+ Contract.Assert( ctor != null); // follows from if guard and the precondition
+ List<Expression> rArgs = new List<Expression>();
foreach (BoundVar p in specializationReplacementFormals) {
bv = new Bpl.BoundVariable(p.tok, new Bpl.TypedIdent(p.tok, p.UniqueName, TrType(p.Type)));
formals.Add(bv);
@@ -513,8 +616,8 @@ namespace Microsoft.Dafny {
ie.Var = p; ie.Type = ie.Var.Type; // resolve it here
rArgs.Add(ie);
}
- r = new DatatypeValue(f.tok, ((!)ctor.EnclosingDatatype).Name, ctor.Name, rArgs);
- r.Ctor = ctor; r.Type = new UserDefinedType(f.tok, ctor.EnclosingDatatype.Name, new List<Type!>()/*this is not right, but it seems like it won't matter here*/); // resolve it here
+ r = new DatatypeValue(f.tok, cce.NonNull(ctor.EnclosingDatatype).Name, ctor.Name, rArgs);
+ r.Ctor = ctor; r.Type = new UserDefinedType(f.tok, ctor.EnclosingDatatype.Name, new List<Type>()/*this is not right, but it seems like it won't matter here*/); // resolve it here
}
foreach (Formal p in f.Formals) {
if (p != specializationFormal) {
@@ -522,7 +625,7 @@ namespace Microsoft.Dafny {
formals.Add(bv);
args.Add(new Bpl.IdentifierExpr(p.tok, bv));
} else {
- assert r != null; // it is set above
+ Contract.Assert( r != null); // it is set above
args.Add(etran.TrExpr(r));
}
}
@@ -539,7 +642,7 @@ namespace Microsoft.Dafny {
Bpl.Expr ante = FunctionCall(f.tok, BuiltinFunction.IsGoodHeap, null, etran.HeapExpr);
if (!f.IsStatic) {
- assert bvThisIdExpr != null; // set to non-null value above when !f.IsStatic
+ Contract.Assert( bvThisIdExpr != null); // set to non-null value above when !f.IsStatic
ante = Bpl.Expr.And(ante, Bpl.Expr.Neq(bvThisIdExpr, predef.Null));
}
foreach (Expression req in f.Req) {
@@ -550,8 +653,8 @@ namespace Microsoft.Dafny {
Bpl.Trigger tr = new Bpl.Trigger(f.tok, true, new Bpl.ExprSeq(funcAppl));
Bpl.TypeVariableSeq typeParams = TrTypeParamDecls(f.TypeArgs);
if (specializationFormal != null) {
- assert r != null;
- Dictionary<IVariable,Expression!> substMap = new Dictionary<IVariable,Expression!>();
+ Contract.Assert( r != null);
+ Dictionary<IVariable,Expression> substMap = new Dictionary<IVariable,Expression>();
substMap.Add(specializationFormal, r);
body = Substitute(body, null, substMap);
}
@@ -559,10 +662,10 @@ namespace Microsoft.Dafny {
return new Bpl.Axiom(f.tok, Bpl.Expr.Imp(activate, ax));
}
- void AddLimitedAxioms(Function! f)
- requires f.IsRecursive && !f.IsUnlimited;
- requires sink != null && predef != null;
- {
+ void AddLimitedAxioms(Function f){
+ Contract.Requires(f != null);
+ Contract.Requires( f.IsRecursive && !f.IsUnlimited);
+ Contract.Requires( sink != null && predef != null);
// axiom (forall formals :: { f(args) } f(args) == f#limited(args))
Bpl.VariableSeq formals = new Bpl.VariableSeq();
@@ -599,9 +702,11 @@ namespace Microsoft.Dafny {
sink.TopLevelDeclarations.Add(new Bpl.Axiom(f.tok, ax));
}
- void AddAllocationAxiom(Field! f)
- requires sink != null && predef != null;
+ void AddAllocationAxiom(Field f)
{
+ Contract.Requires(f != null);
+ Contract.Requires( sink != null && predef != null);
+
if (f.Type is BoolType || f.Type is IntType || f.Type.IsTypeParameter) {
return;
}
@@ -681,7 +786,12 @@ namespace Microsoft.Dafny {
}
}
- Bpl.Expr! InSeqRange(IToken! tok, Bpl.Expr! index, Bpl.Expr! seq, bool isSequence, Bpl.Expr lowerBound, bool includeUpperBound) {
+ Bpl.Expr InSeqRange(IToken tok, Bpl.Expr index, Bpl.Expr seq, bool isSequence, Bpl.Expr lowerBound, bool includeUpperBound) {
+ Contract.Requires(tok != null);
+ Contract.Requires(index != null);
+ Contract.Requires(seq != null);
+ Contract.Ensures(Contract.Result<Bpl.Expr>() != null);
+
if (lowerBound == null) {
lowerBound = Bpl.Expr.Literal(0);
}
@@ -700,9 +810,13 @@ namespace Microsoft.Dafny {
int loopHeapVarCount = 0;
int otherTmpVarCount = 0;
Bpl.IdentifierExpr _phvie = null;
- Bpl.IdentifierExpr! GetPrevHeapVar_IdExpr(IToken! tok, Bpl.VariableSeq! locals) // local variable that's shared between statements that need it
- requires predef != null;
- {
+ Bpl.IdentifierExpr GetPrevHeapVar_IdExpr(IToken tok, Bpl.VariableSeq locals){ // local variable that's shared between statements that need it
+ Contract.Requires(tok != null);
+ Contract.Requires(locals != null); Contract.Requires( predef != null);
+ Contract.Ensures(Contract.Result<Bpl.IdentifierExpr>() != null);
+
+
+
if (_phvie == null) {
// the "tok" of the first request for this variable is the one we use
Bpl.LocalVariable prevHeapVar = new Bpl.LocalVariable(tok, new Bpl.TypedIdent(tok, "$prevHeap", predef.HeapType));
@@ -712,9 +826,14 @@ namespace Microsoft.Dafny {
return _phvie;
}
Bpl.IdentifierExpr _nwie = null;
- Bpl.IdentifierExpr! GetNewVar_IdExpr(IToken! tok, Bpl.VariableSeq! locals) // local variable that's shared between statements that need it
- requires predef != null;
- {
+ Bpl.IdentifierExpr GetNewVar_IdExpr(IToken tok, Bpl.VariableSeq locals) // local variable that's shared between statements that need it
+ { Contract.Requires(tok != null);
+ Contract.Requires(locals != null);
+ Contract.Requires( predef != null);
+
+ Contract.Ensures(Contract.Result<Bpl.IdentifierExpr>() != null);
+
+
if (_nwie == null) {
// the "tok" of the first request for this variable is the one we use
Bpl.LocalVariable nwVar = new Bpl.LocalVariable(tok, new Bpl.TypedIdent(tok, "$nw", predef.RefType)); // important: no where clause (that's why we're going through the trouble of setting of this variable in the first place)
@@ -724,12 +843,15 @@ namespace Microsoft.Dafny {
return _nwie;
}
- void AddMethodImpl(Method! m, Bpl.Procedure! proc, bool wellformednessProc)
- requires sink != null && predef != null;
- requires wellformednessProc || m.Body != null;
- requires currentMethod == null && loopHeapVarCount == 0 && _phvie == null && _nwie == null;
- ensures currentMethod == null && loopHeapVarCount == 0 && _phvie == null && _nwie == null;
+ void AddMethodImpl(Method m, Bpl.Procedure proc, bool wellformednessProc)
{
+ Contract.Requires(m != null);
+ Contract.Requires(proc != null);
+ Contract.Requires( sink != null && predef != null);
+ Contract.Requires( wellformednessProc || m.Body != null);
+ Contract.Requires( currentMethod == null && loopHeapVarCount == 0 && _phvie == null && _nwie == null);
+ Contract.Ensures( currentMethod == null && loopHeapVarCount == 0 && _phvie == null && _nwie == null);
+
currentMethod = m;
Bpl.TypeVariableSeq typeParams = TrTypeParamDecls(m.TypeArgs);
@@ -743,7 +865,7 @@ namespace Microsoft.Dafny {
Bpl.StmtList stmts;
if (!wellformednessProc) {
// translate the body of the method
- assert m.Body != null; // follows from method precondition and the if guard
+ Contract.Assert( m.Body != null); // follows from method precondition and the if guard
stmts = TrStmt2StmtList(builder, m.Body, localVariables, etran);
} else {
// check well-formedness of the preconditions, and then assume each one of them
@@ -779,8 +901,9 @@ namespace Microsoft.Dafny {
// also play havoc with the out parameters
if (outParams.Length != 0) { // don't create an empty havoc statement
Bpl.IdentifierExprSeq outH = new Bpl.IdentifierExprSeq();
- foreach (Bpl.Variable! f in outParams) {
- outH.Add(new Bpl.IdentifierExpr(f.tok, f));
+ foreach (Bpl.Variable b in outParams) {
+ Contract.Assert(b != null);
+ outH.Add(new Bpl.IdentifierExpr(b.tok, b));
}
builder.Add(new Bpl.HavocCmd(m.tok, outH));
}
@@ -806,10 +929,15 @@ namespace Microsoft.Dafny {
_nwie = null;
}
- void GenerateImplPrelude(Method! m, Bpl.VariableSeq! inParams, Bpl.VariableSeq! outParams,
- Bpl.StmtListBuilder! builder, Bpl.VariableSeq! localVariables)
- requires predef != null;
- {
+ void GenerateImplPrelude(Method m, Bpl.VariableSeq inParams, Bpl.VariableSeq outParams,
+ Bpl.StmtListBuilder builder, Bpl.VariableSeq localVariables){
+ Contract.Requires(m != null);
+ Contract.Requires(inParams != null);
+ Contract.Requires(outParams != null);
+ Contract.Requires(builder != null);
+ Contract.Requires(localVariables != null);
+ Contract.Requires( predef != null);
+
// Add CEV prelude
CEVPrelude(m, inParams, outParams, builder);
@@ -817,12 +945,17 @@ namespace Microsoft.Dafny {
DefineFrame(m.tok, m.Mod, builder, localVariables);
}
- void CEVPrelude(Method! m, Bpl.VariableSeq! inParams, Bpl.VariableSeq! outParams, Bpl.StmtListBuilder! builder)
- requires predef != null;
+ void CEVPrelude(Method m, Bpl.VariableSeq inParams, Bpl.VariableSeq outParams, Bpl.StmtListBuilder builder)
{
+ Contract.Requires(m != null);
+ Contract.Requires(inParams != null);
+ Contract.Requires(outParams != null);
+ Contract.Requires(builder != null);
+ Contract.Requires( predef != null);
+
builder.Add(Bpl.Cmd.SimpleAssign(m.tok, Bpl.Expr.Ident("#cev_pc", Bpl.Type.Int), Bpl.Expr.Add(Bpl.Expr.Ident("#cev_pc", Bpl.Type.Int), Bpl.Expr.Literal(1))));
foreach (Bpl.Variable p in inParams) {
- assert p != null;
+ Contract.Assert( p != null);
builder.Add(new Bpl.CallCmd(p.tok, "CevVarIntro",
new Bpl.ExprSeq(
CevLocation(p.tok),
@@ -832,7 +965,7 @@ namespace Microsoft.Dafny {
new Bpl.IdentifierExprSeq()));
}
foreach (Bpl.Variable p in outParams) {
- assert p != null;
+ Contract.Assert( p != null);
builder.Add(new Bpl.CallCmd(p.tok, "CevVarIntro",
new Bpl.ExprSeq(
CevLocation(p.tok),
@@ -843,13 +976,18 @@ namespace Microsoft.Dafny {
}
}
- void DefineFrame(IToken! tok, List<FrameExpression!>! frameClause, Bpl.StmtListBuilder! builder, Bpl.VariableSeq! localVariables)
- requires predef != null;
- {
+ void DefineFrame(IToken/*!*/ tok, List<FrameExpression/*!*/>/*!*/ frameClause, Bpl.StmtListBuilder/*!*/ builder, Bpl.VariableSeq/*!*/ localVariables){
+ Contract.Requires(tok != null);
+ Contract.Requires(cce.NonNullElements(frameClause));
+ Contract.Requires(builder != null);
+ Contract.Requires(cce.NonNullElements(localVariables));
+
+ Contract.Requires( predef != null);
+
ExpressionTranslator etran = new ExpressionTranslator(this, predef, tok);
// Declare a local variable $_Frame: <alpha>[ref, Field alpha]bool
Bpl.IdentifierExpr theFrame = etran.TheFrame(tok); // this is a throw-away expression, used only to extract the name and type of the $_Frame variable
- assert theFrame.Type != null; // follows from the postcondition of TheFrame
+ Contract.Assert( theFrame.Type != null); // follows from the postcondition of TheFrame
Bpl.LocalVariable frame = new Bpl.LocalVariable(tok, new Bpl.TypedIdent(tok, theFrame.Name, theFrame.Type));
localVariables.Add(frame);
// $_Frame := (lambda<alpha> $o: ref, $f: Field alpha :: $o != null && $Heap[$o,alloc] ==> ($o,$f) in Modifies/Reads-Clause);
@@ -866,11 +1004,19 @@ namespace Microsoft.Dafny {
builder.Add(Bpl.Cmd.SimpleAssign(tok, new Bpl.IdentifierExpr(tok, frame), lambda));
}
- void CheckFrameSubset(IToken! tok, List<FrameExpression!>! calleeFrame,
- Expression receiverReplacement, Dictionary<IVariable,Expression!> substMap,
- ExpressionTranslator! etran, Bpl.StmtListBuilder! builder, string! errorMessage)
- requires predef != null;
+ void CheckFrameSubset(IToken tok, List<FrameExpression/*!*/>/*!*/ calleeFrame,
+ Expression receiverReplacement, Dictionary<IVariable,Expression/*!*/> substMap,
+ ExpressionTranslator/*!*/ etran, Bpl.StmtListBuilder/*!*/ builder, string errorMessage)
+
{
+ Contract.Requires(tok != null);
+ Contract.Requires(cce.NonNullElements(calleeFrame));
+ Contract.Requires(receiverReplacement != null);
+ Contract.Requires(cce.NonNullElements(substMap));
+ Contract.Requires(etran != null);
+ Contract.Requires(builder != null);
+ Contract.Requires(errorMessage != null);
+ Contract.Requires( predef != null);
// emit: assert (forall<alpha> o: ref, f: Field alpha :: o != null && $Heap[o,alloc] && (o,f) in calleeFrame ==> $_Frame[o,f]);
Bpl.TypeVariable alpha = new Bpl.TypeVariable(tok, "alpha");
Bpl.BoundVariable oVar = new Bpl.BoundVariable(tok, new Bpl.TypedIdent(tok, "$o", predef.RefType));
@@ -902,9 +1048,11 @@ namespace Microsoft.Dafny {
///
/// If the function is a recursive, non-unlimited function, then the same axiom is also produced for "F#limited" instead of "F".
/// </summary>
- void AddFrameAxiom(Function! f)
- requires sink != null && predef != null;
+ void AddFrameAxiom(Function f)
{
+ Contract.Requires(f != null);
+ Contract.Requires( sink != null && predef != null);
+
Bpl.BoundVariable h0Var = new Bpl.BoundVariable(f.tok, new Bpl.TypedIdent(f.tok, "$h0", predef.HeapType));
Bpl.BoundVariable h1Var = new Bpl.BoundVariable(f.tok, new Bpl.TypedIdent(f.tok, "$h1", predef.HeapType));
Bpl.Expr h0 = new Bpl.IdentifierExpr(f.tok, h0Var);
@@ -946,7 +1094,7 @@ namespace Microsoft.Dafny {
f0args.Add(th);
f1args.Add(th);
- Type thisType = Resolver.GetThisType(f.tok, (!)f.EnclosingClass);
+ Type thisType = Resolver.GetThisType(f.tok, cce.NonNull(f.EnclosingClass));
Bpl.Expr wh = Bpl.Expr.And(Bpl.Expr.Neq(th, predef.Null),
Bpl.Expr.And(etran0.GoodRef(f.tok, th, thisType), etran1.GoodRef(f.tok, th, thisType)));
wellFormed = Bpl.Expr.And(wellFormed, wh);
@@ -986,18 +1134,26 @@ namespace Microsoft.Dafny {
}
}
- Bpl.Expr! InRWClause(IToken! tok, Bpl.Expr! o, Bpl.Expr! f, List<FrameExpression!>! rw, ExpressionTranslator! etran,
- Expression receiverReplacement, Dictionary<IVariable,Expression!> substMap)
- requires predef != null;
+ Bpl.Expr/*!*/ InRWClause(IToken/*!*/ tok, Bpl.Expr/*!*/ o, Bpl.Expr/*!*/ f, List<FrameExpression/*!*/>/*!*/ rw, ExpressionTranslator/*!*/ etran,
+ Expression receiverReplacement, Dictionary<IVariable,Expression/*!*/> substMap){
+ Contract.Requires(tok != null);
+ Contract.Requires(o != null);
+ Contract.Requires(f != null);
+ Contract.Requires(etran != null);
+ Contract.Requires(cce.NonNullElements(rw));
+ Contract.Requires(cce.NonNullElements(substMap));
+ Contract.Requires( predef != null);Contract.Requires( receiverReplacement == null && substMap == null);
+ Contract.Ensures(Contract.Result<Bpl.Expr>() != null);
+
// requires o to denote an expression of type RefType
// "rw" is is allowed to contain a WildcardExpr
- requires receiverReplacement == null <==> substMap == null;
- {
+
+
Bpl.Expr disjunction = null;
foreach (FrameExpression rwComponent in rw) {
Expression e = rwComponent.E;
if (substMap != null) {
- assert receiverReplacement != null;
+ Contract.Assert( receiverReplacement != null);
e = Substitute(e, receiverReplacement, substMap);
}
Bpl.Expr disjunct;
@@ -1036,10 +1192,11 @@ namespace Microsoft.Dafny {
}
}
- void AddWellformednessCheck(Function! f)
- requires sink != null && predef != null;
- requires f.EnclosingClass != null;
- {
+ void AddWellformednessCheck(Function f){
+ Contract.Requires(f != null);
+ Contract.Requires( sink != null && predef != null);
+ Contract.Requires( f.EnclosingClass != null);
+
ExpressionTranslator etran = new ExpressionTranslator(this, predef, f.tok);
// parameters of the procedure
Bpl.VariableSeq inParams = new Bpl.VariableSeq();
@@ -1102,9 +1259,11 @@ namespace Microsoft.Dafny {
sink.TopLevelDeclarations.Add(impl);
}
- Bpl.Expr! IsTotal(Expression! expr, ExpressionTranslator! etran)
- requires predef != null;
- {
+ Bpl.Expr IsTotal(Expression expr, ExpressionTranslator etran){
+ Contract.Requires(expr != null);Contract.Requires(etran != null);
+ Contract.Requires( predef != null);
+ Contract.Ensures(Contract.Result<Bpl.Expr>() != null);
+
if (expr is LiteralExpr || expr is ThisExpr || expr is IdentifierExpr || expr is WildcardExpr) {
return Bpl.Expr.True;
} else if (expr is DisplayExpression) {
@@ -1144,7 +1303,7 @@ namespace Microsoft.Dafny {
return total;
} else if (expr is FunctionCallExpr) {
FunctionCallExpr e = (FunctionCallExpr)expr;
- assert e.Function != null; // follows from the fact that expr has been successfully resolved
+ Contract.Assert( e.Function != null); // follows from the fact that expr has been successfully resolved
// check well-formedness of receiver
Bpl.Expr r = IsTotal(e.Receiver, etran);
if (!e.Function.IsStatic && !(e.Receiver is ThisExpr)) {
@@ -1153,7 +1312,7 @@ namespace Microsoft.Dafny {
// check well-formedness of the other parameters
r = BplAnd(r, IsTotal(e.Args, etran));
// create a substitution map from each formal parameter to the corresponding actual parameter
- Dictionary<IVariable,Expression!> substMap = new Dictionary<IVariable,Expression!>();
+ Dictionary<IVariable,Expression> substMap = new Dictionary<IVariable,Expression>();
for (int i = 0; i < e.Function.Formals.Count; i++) {
substMap.Add(e.Function.Formals[i], e.Args[i]);
}
@@ -1220,19 +1379,28 @@ namespace Microsoft.Dafny {
total = BplAnd(total, Bpl.Expr.Imp(Bpl.Expr.Not(test), IsTotal(e.Els, etran)));
return total;
} else {
- assert false; // unexpected expression
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected expression
}
}
- Bpl.Expr! IsTotal(List<Expression!>! exprs, ExpressionTranslator! etran) {
+ Bpl.Expr/*!*/ IsTotal(List<Expression/*!*/>/*!*/ exprs, ExpressionTranslator/*!*/ etran) {
+ Contract.Requires(etran != null);
+ Contract.Requires(exprs != null);
+ Contract.Ensures(Contract.Result<Bpl.Expr>() != null);
+
Bpl.Expr total = Bpl.Expr.True;
foreach (Expression e in exprs) {
+ Contract.Assert(e != null);
total = BplAnd(total, IsTotal(e, etran));
}
return total;
}
- Bpl.Expr! BplAnd(Bpl.Expr! a, Bpl.Expr! b) {
+ Bpl.Expr BplAnd(Bpl.Expr a, Bpl.Expr b) {
+ Contract.Requires(a != null);
+ Contract.Requires(b != null);
+ Contract.Ensures(Contract.Result<Bpl.Expr>() != null);
+
if (a == Bpl.Expr.True) {
return b;
} else if (b == Bpl.Expr.True) {
@@ -1248,13 +1416,17 @@ namespace Microsoft.Dafny {
case Position.Positive: return Position.Negative;
case Position.Negative: return Position.Positive;
case Position.Neither: return Position.Neither;
- default: assert false; // unexpected Position
+ default: Contract.Assert(false); throw new cce.UnreachableException(); // unexpected Position
}
}
- void CheckNonNull(IToken! tok, Expression! e, Bpl.StmtListBuilder! builder, ExpressionTranslator! etran)
- requires predef != null;
- {
+ void CheckNonNull(IToken tok, Expression e, Bpl.StmtListBuilder builder, ExpressionTranslator etran){
+ Contract.Requires(tok != null);
+ Contract.Requires(e != null);
+ Contract.Requires(builder != null);
+ Contract.Requires(etran != null);
+ Contract.Requires( predef != null);
+
if (e is ThisExpr) {
// already known to be non-null
} else {
@@ -1262,9 +1434,13 @@ namespace Microsoft.Dafny {
}
}
- void CheckWellformed(Expression! expr, Function func, Position pos, Bpl.VariableSeq! locals, Bpl.StmtListBuilder! builder, ExpressionTranslator! etran)
- requires predef != null;
- {
+ void CheckWellformed(Expression expr, Function func, Position pos, Bpl.VariableSeq locals, Bpl.StmtListBuilder builder, ExpressionTranslator etran){
+ Contract.Requires(expr != null);
+ Contract.Requires(locals != null);
+ Contract.Requires(builder != null);
+ Contract.Requires(etran != null);
+ Contract.Requires( predef != null);
+
if (expr is LiteralExpr || expr is ThisExpr || expr is IdentifierExpr || expr is WildcardExpr) {
// always allowed
} else if (expr is DisplayExpression) {
@@ -1294,8 +1470,8 @@ namespace Microsoft.Dafny {
CheckWellformed(e.E1, func, Position.Neither, locals, builder, etran);
builder.Add(Assert(expr.tok, InSeqRange(expr.tok, etran.TrExpr(e.E1), seq, isSequence, e0, true), "end-of-range beyond length of " + (isSequence ? "sequence" : "array")));
}
- if (func != null && ((!)e.Seq.Type).IsArrayType) {
- assert e.E0 != null;
+ if (func != null && cce.NonNull(e.Seq.Type).IsArrayType) {
+ Contract.Assert( e.E0 != null);
Bpl.Expr fieldName = FunctionCall(expr.tok, BuiltinFunction.IndexField, null, etran.TrExpr(e.E0));
builder.Add(Assert(expr.tok, Bpl.Expr.SelectTok(expr.tok, etran.TheFrame(expr.tok), seq, fieldName), "insufficient reads clause to read array element"));
}
@@ -1309,7 +1485,7 @@ namespace Microsoft.Dafny {
CheckWellformed(e.Value, func, Position.Neither, locals, builder, etran);
} else if (expr is FunctionCallExpr) {
FunctionCallExpr e = (FunctionCallExpr)expr;
- assert e.Function != null; // follows from the fact that expr has been successfully resolved
+ Contract.Assert( e.Function != null); // follows from the fact that expr has been successfully resolved
// check well-formedness of receiver
CheckWellformed(e.Receiver, func, Position.Neither, locals, builder, etran);
if (!e.Function.IsStatic && !(e.Receiver is ThisExpr)) {
@@ -1320,7 +1496,7 @@ namespace Microsoft.Dafny {
CheckWellformed(arg, func, Position.Neither, locals, builder, etran);
}
// create a local variable for each formal parameter, and assign each actual parameter to the corresponding local
- Dictionary<IVariable,Expression!> substMap = new Dictionary<IVariable,Expression!>();
+ Dictionary<IVariable,Expression> substMap = new Dictionary<IVariable,Expression>();
for (int i = 0; i < e.Function.Formals.Count; i++) {
Formal p = e.Function.Formals[i];
VarDecl local = new VarDecl(p.tok, p.Name, p.Type, p.IsGhost, null);
@@ -1331,7 +1507,7 @@ namespace Microsoft.Dafny {
locals.Add(new Bpl.LocalVariable(local.Tok, new Bpl.TypedIdent(local.Tok, local.UniqueName, TrType(local.Type))));
Bpl.IdentifierExpr lhs = (Bpl.IdentifierExpr)etran.TrExpr(ie); // TODO: is this cast always justified?
Expression ee = e.Args[i];
- Bpl.Cmd cmd = Bpl.Cmd.SimpleAssign(p.tok, lhs, etran.CondApplyBox(p.tok, etran.TrExpr(ee), (!)ee.Type, p.Type));
+ Bpl.Cmd cmd = Bpl.Cmd.SimpleAssign(p.tok, lhs, etran.CondApplyBox(p.tok, etran.TrExpr(ee), cce.NonNull(ee.Type), p.Type));
builder.Add(cmd);
}
// check that the preconditions for the call hold
@@ -1344,17 +1520,17 @@ namespace Microsoft.Dafny {
CheckFrameSubset(expr.tok, e.Function.Reads, e.Receiver, substMap, etran, builder, "insufficient reads clause to invoke function");
// finally, check that the decreases measure goes down
- ModuleDecl module = ((!)e.Function.EnclosingClass).Module;
- if (module == ((!)func.EnclosingClass).Module) {
+ ModuleDecl module = cce.NonNull(e.Function.EnclosingClass).Module;
+ if (module == cce.NonNull(func.EnclosingClass).Module) {
if (module.CallGraph.GetSCCRepresentative(e.Function) == module.CallGraph.GetSCCRepresentative(func)) {
- List<Expression!> contextDecreases = func.Decreases;
+ List<Expression> contextDecreases = func.Decreases;
if (contextDecreases.Count == 0) {
- contextDecreases = new List<Expression!>();
+ contextDecreases = new List<Expression>();
contextDecreases.Add(FrameToObjectSet(func.Reads)); // use its reads clause instead
}
- List<Expression!> calleeDecreases = e.Function.Decreases;
+ List<Expression> calleeDecreases = e.Function.Decreases;
if (calleeDecreases.Count == 0) {
- calleeDecreases = new List<Expression!>();
+ calleeDecreases = new List<Expression>();
calleeDecreases.Add(FrameToObjectSet(e.Function.Reads)); // use its reads clause instead
}
CheckCallTermination(expr.tok, contextDecreases, calleeDecreases, e.Receiver, substMap, etran, builder);
@@ -1409,7 +1585,7 @@ namespace Microsoft.Dafny {
} else if (expr is QuantifierExpr) {
QuantifierExpr e = (QuantifierExpr)expr;
- Dictionary<IVariable,Expression!> substMap = new Dictionary<IVariable,Expression!>();
+ Dictionary<IVariable,Expression> substMap = new Dictionary<IVariable,Expression>();
foreach (BoundVar bv in e.BoundVars) {
VarDecl local = new VarDecl(bv.tok, bv.Name, bv.Type, bv.IsGhost, null);
local.type = local.OptionalType; // resolve local here
@@ -1435,7 +1611,7 @@ namespace Microsoft.Dafny {
CheckWellformed(me.Source, func, pos, locals, builder, etran);
Bpl.Expr src = etran.TrExpr(me.Source);
foreach (MatchCaseExpr mc in me.Cases) {
- assert mc.Ctor != null; // follows from the fact that mc has been successfully resolved
+ Contract.Assert( mc.Ctor != null); // follows from the fact that mc has been successfully resolved
Bpl.ExprSeq args = new Bpl.ExprSeq();
for (int i = 0; i < mc.Arguments.Count; i++) {
BoundVar p = mc.Arguments[i];
@@ -1445,7 +1621,7 @@ namespace Microsoft.Dafny {
ie.Var = p; ie.Type = ie.Var.Type; // resolve it here
Type t = mc.Ctor.Formals[i].Type;
- args.Add(etran.CondApplyBox(expr.tok, new Bpl.IdentifierExpr(p.tok, local), (!)p.Type, t));
+ args.Add(etran.CondApplyBox(expr.tok, new Bpl.IdentifierExpr(p.tok, local), cce.NonNull(p.Type), t));
}
Bpl.IdentifierExpr id = new Bpl.IdentifierExpr(mc.tok, mc.Ctor.FullName, predef.DatatypeType);
Bpl.Expr ct = new Bpl.NAryExpr(mc.tok, new Bpl.FunctionCall(id), args);
@@ -1457,28 +1633,32 @@ namespace Microsoft.Dafny {
}
} else {
- assert false; // unexpected expression
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected expression
}
}
- Expression! FrameToObjectSet(List<FrameExpression!>! fexprs) {
- List<Expression!> sets = new List<Expression!>();
- List<Expression!> singletons = null;
+ Expression FrameToObjectSet(List<FrameExpression> fexprs) {
+ Contract.Requires(fexprs != null);
+ Contract.Ensures(Contract.Result<Expression>() != null);
+
+ List<Expression> sets = new List<Expression>();
+ List<Expression> singletons = null;
foreach (FrameExpression fe in fexprs) {
+ Contract.Assert(fe != null);
if (fe.E is WildcardExpr) {
// drop wildcards altogether
} else {
Expression e = fe.E; // keep only fe.E, drop any fe.Field designation
- assert e.Type != null; // should have been resolved already
+ Contract.Assert( e.Type != null); // should have been resolved already
if (e.Type.IsRefType) {
// e represents a singleton set
if (singletons == null) {
- singletons = new List<Expression!>();
+ singletons = new List<Expression>();
}
singletons.Add(e);
} else {
// e is already a set
- assert e.Type is SetType;
+ Contract.Assert( e.Type is SetType);
sets.Add(e);
}
}
@@ -1489,7 +1669,7 @@ namespace Microsoft.Dafny {
sets.Add(display);
}
if (sets.Count == 0) {
- Expression emptyset = new SetDisplayExpr(Token.NoToken, new List<Expression!>());
+ Expression emptyset = new SetDisplayExpr(Token.NoToken, new List<Expression>());
emptyset.Type = new SetType(new ObjectType()); // resolve here
return emptyset;
} else {
@@ -1504,12 +1684,15 @@ namespace Microsoft.Dafny {
}
}
- Bpl.Constant! GetClass(TopLevelDecl! cl)
- requires predef != null;
- {
+ Bpl.Constant GetClass(TopLevelDecl cl)
+ {
+ Contract.Requires(cl != null);
+ Contract.Requires( predef != null);
+ Contract.Ensures(Contract.Result<Bpl.Constant>() != null);
+
Bpl.Constant cc;
if (classes.TryGetValue(cl, out cc)) {
- assert cc != null;
+ Contract.Assert( cc != null);
} else {
cc = new Bpl.Constant(cl.tok, new Bpl.TypedIdent(cl.tok, "class." + cl.Name, predef.ClassNameType), true);
classes.Add(cl, cc);
@@ -1517,9 +1700,11 @@ namespace Microsoft.Dafny {
return cc;
}
- Bpl.Expr GetTypeExpr(IToken! tok, Type! type)
- requires predef != null;
- {
+ Bpl.Expr GetTypeExpr(IToken tok, Type type)
+ {
+ Contract.Requires(tok != null);
+ Contract.Requires(type != null);
+ Contract.Requires( predef != null);
while (true) {
TypeProxy tp = type as TypeProxy;
if (tp == null) {
@@ -1564,12 +1749,15 @@ namespace Microsoft.Dafny {
}
}
- Bpl.Constant! GetField(Field! f)
- requires sink != null && predef != null;
- {
+ Bpl.Constant GetField(Field f)
+ {
+ Contract.Requires(f != null);Contract.Requires( sink != null && predef != null);
+ Contract.Ensures(Contract.Result<Bpl.Constant>() != null);
+
+
Bpl.Constant fc;
if (fields.TryGetValue(f, out fc)) {
- assert fc != null;
+ Contract.Assert( fc != null);
} else {
// const unique f: Field ty;
Bpl.Type ty = predef.FieldName(f.tok, TrType(f.Type));
@@ -1577,25 +1765,29 @@ namespace Microsoft.Dafny {
fields.Add(f, fc);
// axiom FCat(f) == $NamedField && DeclType(f) == C;
Bpl.Expr fcat = Bpl.Expr.Eq(FunctionCall(f.tok, BuiltinFunction.FCat, ty, Bpl.Expr.Ident(fc)), new Bpl.IdentifierExpr(f.tok, "$NamedField", predef.FieldCategoryType));
- Bpl.Expr declType = Bpl.Expr.Eq(FunctionCall(f.tok, BuiltinFunction.DeclType, ty, Bpl.Expr.Ident(fc)), new Bpl.IdentifierExpr(f.tok, GetClass((!)f.EnclosingClass)));
+ Bpl.Expr declType = Bpl.Expr.Eq(FunctionCall(f.tok, BuiltinFunction.DeclType, ty, Bpl.Expr.Ident(fc)), new Bpl.IdentifierExpr(f.tok, GetClass(cce.NonNull(f.EnclosingClass))));
Bpl.Axiom ax = new Bpl.Axiom(f.tok, Bpl.Expr.And(fcat, declType));
sink.TopLevelDeclarations.Add(ax);
}
return fc;
}
- Bpl.Expr! GetField(FieldSelectExpr! fse)
- requires fse.Field != null;
- {
+ Bpl.Expr GetField(FieldSelectExpr fse)
+ {
+ Contract.Requires(fse != null);Contract.Requires( fse.Field != null);
+ Contract.Ensures(Contract.Result<Bpl.Expr>() != null);
+
+
return new Bpl.IdentifierExpr(fse.tok, GetField(fse.Field));
}
/// <summary>
/// This method is expected to be called just once for each function in the program.
/// </summary>
- void AddFunction(Function! f)
- requires predef != null && sink != null;
- {
+ void AddFunction(Function f)
+ {
+ Contract.Requires(f != null);
+ Contract.Requires( predef != null && sink != null);
Bpl.TypeVariableSeq typeParams = TrTypeParamDecls(f.TypeArgs);
Bpl.VariableSeq args = new Bpl.VariableSeq();
args.Add(new Bpl.Formal(f.tok, new Bpl.TypedIdent(f.tok, "$heap", predef.HeapType), true));
@@ -1620,11 +1812,15 @@ namespace Microsoft.Dafny {
/// wellformednessProc set to true, once with wellformednessProc set to false).
/// In addition, it is used once to generate refinement conditions.
/// </summary>
- Bpl.Procedure! AddMethod(Method! m, bool wellformednessProc, bool skipEnsures)
- requires predef != null;
- requires m.EnclosingClass != null;
- requires skipEnsures ==> !wellformednessProc;
- {
+ Bpl.Procedure AddMethod(Method m, bool wellformednessProc, bool skipEnsures)
+ {
+ Contract.Requires(m != null);
+ Contract.Requires( predef != null);
+ Contract.Requires( m.EnclosingClass != null);
+ Contract.Requires( !skipEnsures || !wellformednessProc);
+ Contract.Ensures(Contract.Result<Bpl.Procedure>() != null);
+
+
ExpressionTranslator etran = new ExpressionTranslator(this, predef, m.tok);
Bpl.VariableSeq inParams = new Bpl.VariableSeq();
@@ -1664,7 +1860,7 @@ namespace Microsoft.Dafny {
if (p.IsFree) {
req.Add(Requires(p.E.tok, true, etran.TrExpr(p.E), null, comment));
} else {
- List<Expression!>! definitions, pieces;
+ List<Expression> definitions, pieces;
if (!SplitExpr(p.E, out definitions, out pieces)) {
req.Add(Requires(p.E.tok, false, etran.TrExpr(p.E), null, comment));
} else {
@@ -1687,7 +1883,7 @@ namespace Microsoft.Dafny {
if (p.IsFree) {
ens.Add(Ensures(p.E.tok, true, etran.TrExpr(p.E), null, comment));
} else {
- List<Expression!>! definitions, pieces;
+ List<Expression> definitions, pieces;
if (!SplitExpr(p.E, out definitions, out pieces)) {
ens.Add(Ensures(p.E.tok, false, etran.TrExpr(p.E), null, comment));
} else {
@@ -1735,24 +1931,25 @@ namespace Microsoft.Dafny {
#region Refinement extension
- void AddMethodRefinement(MethodRefinement! m)
- requires sink != null && predef != null;
- {
+ void AddMethodRefinement(MethodRefinement m)
+ {
+ Contract.Requires(m != null);
+ Contract.Requires( sink != null && predef != null);
// r is abstract, m is concrete
Method r = m.Refined;
- assert r != null;
- assert m.EnclosingClass != null;
- string! name = "Refinement$$" + m.FullName;
- string! that = "that";
+ Contract.Assert( r != null);
+ Contract.Assert( m.EnclosingClass != null);
+ string name = "Refinement$$" + m.FullName;
+ string that = "that";
Bpl.IdentifierExpr heap = new Bpl.IdentifierExpr(m.tok, predef.HeapVarName, predef.HeapType);
- ExpressionTranslator etran = new ExpressionTranslator(this, predef, heap, that);
+ ExpressionTranslator etran = new ExpressionTranslator(this, predef, heap, that);
// TODO: this straight inlining does not handle recursive calls
// TODO: we assume frame allows anything to be changed -- we don't include post-conditions in the refinement procedure, or check refinement of frames
// generate procedure declaration with pre-condition wp(r, true)
- Bpl.Procedure! proc = AddMethod(r, false, true);
+ Bpl.Procedure proc = AddMethod(r, false, true);
proc.Name = name;
// create "that" for m
@@ -1760,7 +1957,7 @@ namespace Microsoft.Dafny {
Bpl.Expr.Neq(new Bpl.IdentifierExpr(m.tok, that, predef.RefType), predef.Null),
etran.GoodRef(m.tok, new Bpl.IdentifierExpr(m.tok, that, predef.RefType), Resolver.GetThisType(m.tok, m.EnclosingClass)));
Bpl.Formal thatVar = new Bpl.Formal(m.tok, new Bpl.TypedIdent(m.tok, that, predef.RefType, wh), true);
- proc.InParams.Add(thatVar);
+ proc.InParams.Add(thatVar);
// add outs of m to the outs of the refinement procedure
foreach (Formal p in m.Outs) {
@@ -1774,34 +1971,34 @@ namespace Microsoft.Dafny {
Bpl.TypeVariableSeq typeParams = TrTypeParamDecls(m.TypeArgs);
Bpl.VariableSeq inParams = Bpl.Formal.StripWhereClauses(proc.InParams);
Bpl.VariableSeq outParams = Bpl.Formal.StripWhereClauses(proc.OutParams);
- Bpl.StmtListBuilder builder = new Bpl.StmtListBuilder();
- Bpl.VariableSeq localVariables = new Bpl.VariableSeq();
+ Bpl.StmtListBuilder builder = new Bpl.StmtListBuilder();
+ Bpl.VariableSeq localVariables = new Bpl.VariableSeq();
- assert m.Body != null;
- assert r.Body != null;
+ Contract.Assert( m.Body != null);
+ Contract.Assert( r.Body != null);
// declare a frame variable that allows anything to be changed (not checking modifies clauses)
CEVPrelude(m, inParams, outParams, builder);
- Bpl.IdentifierExpr theFrame = etran.TheFrame(m.tok);
- assert theFrame.Type != null;
+ Bpl.IdentifierExpr theFrame = etran.TheFrame(m.tok);
+ Contract.Assert( theFrame.Type != null);
Bpl.LocalVariable frame = new Bpl.LocalVariable(m.tok, new Bpl.TypedIdent(m.tok, theFrame.Name, theFrame.Type));
localVariables.Add(frame);
// $_Frame := (lambda<alpha> $o: ref, $f: Field alpha :: true);
Bpl.TypeVariable alpha = new Bpl.TypeVariable(m.tok, "alpha");
Bpl.BoundVariable oVar = new Bpl.BoundVariable(m.tok, new Bpl.TypedIdent(m.tok, "$o", predef.RefType));
Bpl.BoundVariable fVar = new Bpl.BoundVariable(m.tok, new Bpl.TypedIdent(m.tok, "$f", predef.FieldName(m.tok, alpha)));
- Bpl.Expr lambda = new Bpl.LambdaExpr(m.tok, new Bpl.TypeVariableSeq(alpha), new Bpl.VariableSeq(oVar, fVar), null, Bpl.Expr.True);
+ Bpl.Expr lambda = new Bpl.LambdaExpr(m.tok, new Bpl.TypeVariableSeq(alpha), new Bpl.VariableSeq(oVar, fVar), null, Bpl.Expr.True);
builder.Add(Bpl.Cmd.SimpleAssign(m.tok, new Bpl.IdentifierExpr(m.tok, frame), lambda));
// assume I($Heap, $Heap)
- builder.Add(new Bpl.AssumeCmd(m.tok, TrCouplingInvariant(m, heap, "this", heap, that)));
+ builder.Add(new Bpl.AssumeCmd(m.tok, TrCouplingInvariant(m, heap, "this", heap, that)));
// assign input formals of m (except "this")
for (int i = 0; i < m.Ins.Count; i++) {
Bpl.LocalVariable arg = new Bpl.LocalVariable(m.tok, new Bpl.TypedIdent(m.tok, m.Ins[i].UniqueName, TrType(m.Ins[i].Type)));
localVariables.Add(arg);
Bpl.Variable var = inParams[i+1];
- assert var != null;
+ Contract.Assert( var != null);
builder.Add(Bpl.Cmd.SimpleAssign(m.tok, new Bpl.IdentifierExpr(m.tok, arg), new Bpl.IdentifierExpr(m.tok, var)));
}
@@ -1812,7 +2009,7 @@ namespace Microsoft.Dafny {
_phvie = null;
_nwie = null;
- // call inlined m;
+ // call inlined m;
TrStmt(m.Body, builder, localVariables, etran);
// $Heap1 := $Heap;
@@ -1820,7 +2017,7 @@ namespace Microsoft.Dafny {
localVariables.Add(heap2);
builder.Add(Bpl.Cmd.SimpleAssign(m.tok, new Bpl.IdentifierExpr(m.tok, heap2), etran.HeapExpr));
- // $Heap := old($Heap);
+ // $Heap := old($Heap);
builder.Add(Bpl.Cmd.SimpleAssign(m.tok, heap, new Bpl.OldExpr(m.tok, heap)));
// call inlined r;
@@ -1835,22 +2032,22 @@ namespace Microsoft.Dafny {
_phvie = null;
_nwie = null;
- // assert output variables of r and m are pairwise equal
- assert outParams.Length % 2 == 0;
+ // Contract.Assert( output variables of r and m are pairwise equal
+ Contract.Assert( outParams.Length % 2 == 0);
int k = outParams.Length / 2;
for (int i = 0; i < k; i++) {
Bpl.Variable rOut = outParams[i];
Bpl.Variable mOut = outParams[i+k];
- assert rOut != null && mOut != null;
+ Contract.Assert( rOut != null && mOut != null);
builder.Add(Assert(m.tok, Bpl.Expr.Eq(new Bpl.IdentifierExpr(m.tok, mOut), new Bpl.IdentifierExpr(m.tok, rOut)),
"Refinement method may not produce the same value for output variable " + m.Outs[i].Name));
}
- // assert I($Heap1, $Heap)
+ // Contract.Assert( I($Heap1, $Heap)
builder.Add(Assert(m.tok, TrCouplingInvariant(m, heap, "this", new Bpl.IdentifierExpr(m.tok, heap2), that),
"Refinement method may not preserve the coupling invariant"));
- Bpl.StmtList stmts = builder.Collect(m.tok);
+ Bpl.StmtList stmts = builder.Collect(m.tok);
Bpl.Implementation impl = new Bpl.Implementation(m.tok, proc.Name,
typeParams, inParams, outParams,
localVariables, stmts);
@@ -1859,11 +2056,24 @@ namespace Microsoft.Dafny {
private sealed class NominalSubstituter : Duplicator
{
- private readonly Dictionary<string!,Bpl.Expr!>! subst;
- public NominalSubstituter(Dictionary<string!,Bpl.Expr!>! subst) { this.subst = subst; base(); }
+ private readonly Dictionary<string,Bpl.Expr> subst;
+ public NominalSubstituter(Dictionary<string,Bpl.Expr> subst) :base(){
+ Contract.Requires(cce.NonNullElements(subst));
+ this.subst = subst;
+ }
- public override Expr! VisitIdentifierExpr(Bpl.IdentifierExpr! node)
+ [ContractInvariantMethod]
+void ObjectInvariant()
+{
+ Contract.Invariant(cce.NonNullElements(subst));
+}
+
+
+ public override Expr VisitIdentifierExpr(Bpl.IdentifierExpr node)
{
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
+
if (subst.ContainsKey(node.Name))
return subst[node.Name];
else
@@ -1871,31 +2081,36 @@ namespace Microsoft.Dafny {
}
}
- Bpl.Expr! TrCouplingInvariant(MethodRefinement! m, Bpl.Expr! absHeap, string! absThis, Bpl.Expr! conHeap, string! conThis)
- requires predef != null;
- {
- Bpl.Expr! cond = Bpl.Expr.True;
+ Bpl.Expr TrCouplingInvariant(MethodRefinement m, Bpl.Expr absHeap, string absThis, Bpl.Expr conHeap, string conThis)
+ {
+ Contract.Requires(m != null);
+ Contract.Requires(absHeap != null);
+ Contract.Requires(absThis != null);
+ Contract.Requires(conHeap != null);
+ Contract.Requires(conThis != null);
+ Contract.Requires(predef != null);
+ Bpl.Expr cond = Bpl.Expr.True;
ClassRefinementDecl c = m.EnclosingClass as ClassRefinementDecl;
- assert c != null;
+ Contract.Assert( c != null);
ExpressionTranslator etran = new ExpressionTranslator(this, predef, conHeap, conThis);
foreach (MemberDecl d in c.Members)
if (d is CouplingInvariant) {
CouplingInvariant inv = (CouplingInvariant)d;
- assert inv.Refined != null;
- assert inv.Formals != null;
+ Contract.Assert( inv.Refined != null);
+ Contract.Assert( inv.Formals != null);
// replace formals with field dereferences
- Dictionary<string!,Bpl.Expr!>! map = new Dictionary<string!,Bpl.Expr!>();
- Bpl.Expr! absVar = new Bpl.IdentifierExpr(d.tok, absThis, predef.RefType);
+ Dictionary<string,Bpl.Expr> map = new Dictionary<string,Bpl.Expr>();
+ Bpl.Expr absVar = new Bpl.IdentifierExpr(d.tok, absThis, predef.RefType);
for (int i = 0; i < inv.Refined.Count; i++) {
// TODO: boxing/unboxing?
- Bpl.Expr! result = Bpl.Expr.SelectTok(inv.Toks[i], absHeap, absVar, new Bpl.IdentifierExpr(inv.Toks[i], GetField((!)inv.Refined[i])));
+ Bpl.Expr result = Bpl.Expr.SelectTok(inv.Toks[i], absHeap, absVar, new Bpl.IdentifierExpr(inv.Toks[i], GetField(cce.NonNull(inv.Refined[i]))));
map.Add(inv.Formals[i].UniqueName, result);
}
- Bpl.Expr! e = new NominalSubstituter(map).VisitExpr(etran.TrExpr(inv.Expr));
+ Bpl.Expr e = new NominalSubstituter(map).VisitExpr(etran.TrExpr(inv.Expr));
cond = Bpl.Expr.And(cond, e);
}
@@ -1905,15 +2120,26 @@ namespace Microsoft.Dafny {
#endregion
class BoilerplateTriple { // a triple that is now a quintuple
- public readonly IToken! tok;
+ [ContractInvariantMethod]
+void ObjectInvariant()
+{
+ Contract.Invariant(tok!=null);
+ Contract.Invariant(Expr != null);
+ Contract.Invariant(IsFree || ErrorMessage != null);
+}
+
+ public readonly IToken tok;
public readonly bool IsFree;
- public readonly Bpl.Expr! Expr;
+ public readonly Bpl.Expr Expr;
public readonly string ErrorMessage;
- invariant IsFree || ErrorMessage != null;
public readonly string Comment;
- public BoilerplateTriple(IToken! tok, bool isFree, Bpl.Expr! expr, string errorMessage, string comment)
- requires isFree || errorMessage != null;
- {
+
+
+ public BoilerplateTriple(IToken tok, bool isFree, Bpl.Expr expr, string errorMessage, string comment)
+ {
+ Contract.Requires(tok != null);
+ Contract.Requires(expr != null);
+ Contract.Requires( isFree || errorMessage != null);
this.tok = tok;
IsFree = isFree;
Expr = expr;
@@ -1929,9 +2155,15 @@ namespace Microsoft.Dafny {
/// S2. the post-state of the two-state interval
/// This method assumes that etranPre denotes S1, etran denotes S2, and that etran.Old denotes S0.
/// </summary>
- List<BoilerplateTriple!>! GetTwoStateBoilerplate(IToken! tok, Method! method, ExpressionTranslator! etranPre, ExpressionTranslator! etran)
+ List<BoilerplateTriple/*!*/>/*!*/ GetTwoStateBoilerplate(IToken/*!*/ tok, Method/*!*/ method, ExpressionTranslator/*!*/ etranPre, ExpressionTranslator/*!*/ etran)
{
- List<BoilerplateTriple!> boilerplate = new List<BoilerplateTriple!>();
+ Contract.Requires(tok != null);
+ Contract.Requires(method != null);
+ Contract.Requires(etranPre != null);
+ Contract.Requires(etran != null);
+ Contract.Ensures(cce.NonNullElements(Contract.Result<List<BoilerplateTriple>>()));
+
+ List<BoilerplateTriple> boilerplate = new List<BoilerplateTriple>();
// the frame condition, which is free since it is checked with every heap update and call
boilerplate.Add(new BoilerplateTriple(tok, true, FrameCondition(tok, method.Mod, etranPre, etran), null, "frame condition"));
@@ -1950,9 +2182,15 @@ namespace Microsoft.Dafny {
/// S2. the post-state of the two-state interval
/// This method assumes that etranPre denotes S1, etran denotes S2, and that etran.Old denotes S0.
/// </summary>
- Bpl.Expr! FrameCondition(IToken! tok, List<FrameExpression!>! modifiesClause, ExpressionTranslator! etranPre, ExpressionTranslator! etran)
- requires predef != null;
- {
+ Bpl.Expr/*!*/ FrameCondition(IToken/*!*/ tok, List<FrameExpression/*!*/>/*!*/ modifiesClause, ExpressionTranslator/*!*/ etranPre, ExpressionTranslator/*!*/ etran)
+ {
+ Contract.Requires(tok != null);
+ Contract.Requires(etran != null);
+ Contract.Requires(etranPre != null);
+ Contract.Requires(cce.NonNullElements(modifiesClause));
+ Contract.Requires( predef != null);
+ Contract.Ensures(Contract.Result<Bpl.Expr>() != null);
+
// generate:
// (forall<alpha> o: ref, f: Field alpha :: { $Heap[o,f] }
// o != null && old($Heap)[o,alloc] ==>
@@ -1977,9 +2215,12 @@ namespace Microsoft.Dafny {
// ----- Type ---------------------------------------------------------------------------------
- Bpl.Type! TrType(Type! type)
- requires predef != null;
- {
+ Bpl.Type TrType(Type type)
+ {
+ Contract.Requires(type != null);Contract.Requires( predef != null);
+ Contract.Ensures(Contract.Result<Bpl.Type>() != null);
+
+
while (true) {
TypeProxy tp = type as TypeProxy;
if (tp == null) {
@@ -2008,28 +2249,38 @@ namespace Microsoft.Dafny {
} else if (type is SeqType) {
return predef.SeqType(Token.NoToken, predef.BoxType);
} else {
- assert false; // unexpected type
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected type
}
}
- Bpl.TypeVariableSeq! TrTypeParamDecls(List<TypeParameter!>! tps)
+ Bpl.TypeVariableSeq TrTypeParamDecls(List<TypeParameter/*!*/>/*!*/ tps)
{
+ Contract.Requires(cce.NonNullElements(tps));
+ Contract.Ensures(Contract.Result<Bpl.TypeVariableSeq>() != null);
+
Bpl.TypeVariableSeq typeParams = new Bpl.TypeVariableSeq();
return typeParams;
}
// ----- Statement ----------------------------------------------------------------------------
- Bpl.AssertCmd! Assert(Bpl.IToken! tok, Bpl.Expr! condition, string! errorMessage)
+ Bpl.AssertCmd Assert(Bpl.IToken tok, Bpl.Expr condition, string errorMessage)
{
+ Contract.Requires(tok != null);
+ Contract.Requires(condition != null);
+ Contract.Requires(errorMessage != null);
+ Contract.Ensures(Contract.Result<Bpl.AssertCmd>() != null);
+
Bpl.AssertCmd cmd = new Bpl.AssertCmd(tok, condition);
cmd.ErrorData = "Error: " + errorMessage;
return cmd;
}
- Bpl.AssertCmd! AssertNS(Bpl.IToken! tok, Bpl.Expr! condition, string! errorMessage)
+ Bpl.AssertCmd AssertNS(Bpl.IToken tok, Bpl.Expr condition, string errorMessage)
{
- List<object!> args = new List<object!>();
+ Contract.Requires(tok != null);Contract.Requires(errorMessage != null);Contract.Requires(condition != null);Contract.Ensures(Contract.Result<Bpl.AssertCmd>() != null);
+
+ List<object> args = new List<object>();
args.Add(Bpl.Expr.Literal(0));
Bpl.QKeyValue kv = new Bpl.QKeyValue(tok, "subsumption", args, null);
Bpl.AssertCmd cmd = new Bpl.AssertCmd(tok, condition, kv);
@@ -2037,8 +2288,12 @@ namespace Microsoft.Dafny {
return cmd;
}
- Bpl.Ensures! Ensures(IToken! tok, bool free, Bpl.Expr! condition, string errorMessage, string comment)
+ Bpl.Ensures Ensures(IToken tok, bool free, Bpl.Expr condition, string errorMessage, string comment)
{
+ Contract.Requires(tok != null);
+ Contract.Requires(condition != null);
+ Contract.Ensures(Contract.Result<Bpl.Ensures>() != null);
+
Bpl.Ensures ens = new Bpl.Ensures(tok, free, condition, comment);
if (errorMessage != null) {
ens.ErrorData = errorMessage;
@@ -2046,8 +2301,10 @@ namespace Microsoft.Dafny {
return ens;
}
- Bpl.Requires! Requires(IToken! tok, bool free, Bpl.Expr! condition, string errorMessage, string comment)
+ Bpl.Requires Requires(IToken tok, bool free, Bpl.Expr condition, string errorMessage, string comment)
{
+ Contract.Requires(tok != null);
+ Contract.Requires(condition != null);
Bpl.Requires req = new Bpl.Requires(tok, free, condition, comment);
if (errorMessage != null) {
req.ErrorData = errorMessage;
@@ -2055,27 +2312,43 @@ namespace Microsoft.Dafny {
return req;
}
- Bpl.StmtList! TrStmt2StmtList(Statement! block, Bpl.VariableSeq! locals, ExpressionTranslator! etran)
- requires currentMethod != null && predef != null;
- {
+ Bpl.StmtList TrStmt2StmtList(Statement block, Bpl.VariableSeq locals, ExpressionTranslator etran)
+ {
+ Contract.Requires(block != null);
+ Contract.Requires(locals != null);
+ Contract.Requires(etran != null);Contract.Requires( currentMethod != null && predef != null);
+ Contract.Ensures(Contract.Result<Bpl.StmtList>() != null);
+
+
return TrStmt2StmtList(new Bpl.StmtListBuilder(), block, locals, etran);
}
- Bpl.StmtList! TrStmt2StmtList(Bpl.StmtListBuilder! builder, Statement! block, Bpl.VariableSeq! locals, ExpressionTranslator! etran)
- requires currentMethod != null && predef != null;
- {
+ Bpl.StmtList TrStmt2StmtList(Bpl.StmtListBuilder builder, Statement block, Bpl.VariableSeq locals, ExpressionTranslator etran)
+ {
+ Contract.Requires(builder != null);
+ Contract.Requires(block != null);
+ Contract.Requires(locals != null);
+ Contract.Requires(etran != null);
+ Contract.Requires( currentMethod != null && predef != null);
+ Contract.Ensures(Contract.Result<Bpl.StmtList>() != null);
+
+
TrStmt(block, builder, locals, etran);
return builder.Collect(block.Tok); // TODO: would be nice to have an end-curly location for "block"
}
- void TrStmt(Statement! stmt, Bpl.StmtListBuilder! builder, Bpl.VariableSeq! locals, ExpressionTranslator! etran)
- requires currentMethod != null && predef != null;
+ void TrStmt(Statement stmt, Bpl.StmtListBuilder builder, Bpl.VariableSeq locals, ExpressionTranslator etran)
{
+ Contract.Requires(stmt != null);
+ Contract.Requires(builder != null);
+ Contract.Requires(locals != null);
+ Contract.Requires(etran != null);
+ Contract.Requires( currentMethod != null && predef != null);
if (stmt is AssertStmt) {
AddComment(builder, stmt, "assert statement");
AssertStmt s = (AssertStmt)stmt;
builder.Add(AssertNS(s.Expr.tok, IsTotal(s.Expr, etran), "assert condition must be well defined")); // totality check
- List<Expression!>! definitions, pieces;
+ List<Expression> definitions, pieces;
if (!SplitExpr(s.Expr, out definitions, out pieces)) {
builder.Add(Assert(s.Expr.tok, etran.TrExpr(s.Expr), "assertion violation"));
} else {
@@ -2121,7 +2394,7 @@ namespace Microsoft.Dafny {
AssignStmt s = (AssignStmt)stmt;
TrAssignment(stmt.Tok, s.Lhs, s.Rhs, builder, locals, etran);
if (s.Lhs is IdentifierExpr) {
- Bpl.IdentifierExpr v = etran.TrVar(stmt.Tok, (!)((IdentifierExpr)s.Lhs).Var);
+ Bpl.IdentifierExpr v = etran.TrVar(stmt.Tok, cce.NonNull((IdentifierExpr)s.Lhs).Var);
builder.Add(new Bpl.CallCmd(stmt.Tok, "CevUpdate",
new Bpl.ExprSeq(CevLocation(stmt.Tok), CevVariable(stmt.Tok, v.Name), v),
new Bpl.IdentifierExprSeq()));
@@ -2165,7 +2438,7 @@ namespace Microsoft.Dafny {
}
AddComment(builder, stmt, "call statement");
Bpl.ExprSeq ins = new Bpl.ExprSeq();
- assert s.Method != null; // follows from the fact that stmt has been successfully resolved
+ Contract.Assert( s.Method != null); // follows from the fact that stmt has been successfully resolved
if (!s.Method.IsStatic) {
ins.Add(etran.TrExpr(s.Receiver));
}
@@ -2174,7 +2447,7 @@ namespace Microsoft.Dafny {
// but Boogie doesn't give us a hook for that. So, we set up our own local variables here to
// store the actual parameters.
// Create a local variable for each formal parameter, and assign each actual parameter to the corresponding local
- Dictionary<IVariable,Expression!> substMap = new Dictionary<IVariable,Expression!>();
+ Dictionary<IVariable,Expression> substMap = new Dictionary<IVariable,Expression>();
for (int i = 0; i < s.Method.Ins.Count; i++) {
Formal p = s.Method.Ins[i];
VarDecl local = new VarDecl(p.tok, p.Name, p.Type, p.IsGhost, null);
@@ -2187,7 +2460,7 @@ namespace Microsoft.Dafny {
Bpl.IdentifierExpr lhs = (Bpl.IdentifierExpr)etran.TrExpr(ie); // TODO: is this cast always justified?
Expression actual = s.Args[i];
builder.Add(Assert(actual.tok, IsTotal(actual, etran), "argument must be well defined")); // totality check
- Bpl.Cmd cmd = Bpl.Cmd.SimpleAssign(p.tok, lhs, etran.CondApplyBox(stmt.Tok, etran.TrExpr(actual), (!)actual.Type, s.Method.Ins[i].Type));
+ Bpl.Cmd cmd = Bpl.Cmd.SimpleAssign(p.tok, lhs, etran.CondApplyBox(stmt.Tok, etran.TrExpr(actual), cce.NonNull(actual.Type), s.Method.Ins[i].Type));
builder.Add(cmd);
ins.Add(lhs);
}
@@ -2196,7 +2469,7 @@ namespace Microsoft.Dafny {
List<Bpl.IdentifierExpr> tmpOuts = new List<Bpl.IdentifierExpr>(s.Lhs.Count);
for (int i = 0; i < s.Lhs.Count; i++) {
Expression e = s.Lhs[i];
- if (ExpressionTranslator.ModeledAsBoxType(s.Method.Outs[i].Type) && !ExpressionTranslator.ModeledAsBoxType((!)e.Type)) {
+ if (ExpressionTranslator.ModeledAsBoxType(s.Method.Outs[i].Type) && !ExpressionTranslator.ModeledAsBoxType(cce.NonNull(e.Type))) {
// we need an Unbox
Bpl.LocalVariable var = new Bpl.LocalVariable(stmt.Tok, new Bpl.TypedIdent(stmt.Tok, "$tmp#" + otherTmpVarCount, predef.BoxType));
otherTmpVarCount++;
@@ -2214,8 +2487,8 @@ namespace Microsoft.Dafny {
CheckFrameSubset(stmt.Tok, s.Method.Mod, s.Receiver, substMap, etran, builder, "call may violate caller's modifies clause");
// Check termination
- ModuleDecl module = ((!)s.Method.EnclosingClass).Module;
- if (module == ((!)currentMethod.EnclosingClass).Module) {
+ ModuleDecl module = cce.NonNull(s.Method.EnclosingClass).Module;
+ if (module == cce.NonNull(currentMethod.EnclosingClass).Module) {
if (module.CallGraph.GetSCCRepresentative(s.Method) == module.CallGraph.GetSCCRepresentative(currentMethod)) {
CheckCallTermination(stmt.Tok, currentMethod.Decreases, s.Method.Decreases, s.Receiver, substMap, etran, builder);
}
@@ -2230,7 +2503,7 @@ namespace Microsoft.Dafny {
Bpl.IdentifierExpr lhs = (Bpl.IdentifierExpr)etran.TrExpr(e); // TODO: is this cast always justified?
if (tmpVarIdE != null) {
// e := UnBox(tmpVar);
- Bpl.Cmd cmd = Bpl.Cmd.SimpleAssign(stmt.Tok, lhs, FunctionCall(stmt.Tok, BuiltinFunction.Unbox, TrType((!)e.Type), tmpVarIdE));
+ Bpl.Cmd cmd = Bpl.Cmd.SimpleAssign(stmt.Tok, lhs, FunctionCall(stmt.Tok, BuiltinFunction.Unbox, TrType(cce.NonNull(e.Type)), tmpVarIdE));
builder.Add(cmd);
}
builder.Add(new Bpl.CallCmd(stmt.Tok, "CevUpdateHere",
@@ -2292,7 +2565,7 @@ namespace Microsoft.Dafny {
loopHeapVarCount++;
// use simple heuristics to create a default decreases clause, if none is given
- List<Expression!> theDecreases = s.Decreases;
+ List<Expression> theDecreases = s.Decreases;
bool inferredDecreases = false;
if (theDecreases.Count == 0 && s.Guard != null) {
Expression prefix = null;
@@ -2354,8 +2627,8 @@ namespace Microsoft.Dafny {
ExpressionTranslator etranPreLoop = new ExpressionTranslator(this, predef, preLoopHeap);
builder.Add(Bpl.Cmd.SimpleAssign(stmt.Tok, preLoopHeap, etran.HeapExpr)); // TODO: does this screw up labeled breaks for this loop?
- List<Bpl.Expr!> initDecr = null;
- if (!exists{Expression e in theDecreases; e is WildcardExpr}) {
+ List<Bpl.Expr> initDecr = null;
+ if (!Contract.Exists(theDecreases,e=> e is WildcardExpr)) {
initDecr = RecordDecreasesValue(theDecreases, builder, locals, etran, "$decr" + loopId + "$init$");
}
@@ -2375,7 +2648,7 @@ namespace Microsoft.Dafny {
new Bpl.ExprSeq(CevLocation(stmt.Tok)),
new Bpl.IdentifierExprSeq(preLoopCevPC))); // TODO: does this screw up labeled breaks for this loop?
- List<Bpl.PredicateCmd!> invariants = new List<Bpl.PredicateCmd!>();
+ List<Bpl.PredicateCmd> invariants = new List<Bpl.PredicateCmd>();
Bpl.StmtListBuilder invDefinednessBuilder = new Bpl.StmtListBuilder();
foreach (MaybeFreeExpression loopInv in s.Invariants) {
invDefinednessBuilder.Add(AssertNS(loopInv.E.tok, IsTotal(loopInv.E, etran), (loopInv.IsFree ? "free " : "") + "loop invariant must be well defined")); // totality check
@@ -2383,7 +2656,7 @@ namespace Microsoft.Dafny {
if (loopInv.IsFree) {
invariants.Add(new Bpl.AssumeCmd(loopInv.E.tok, Bpl.Expr.Imp(w, etran.TrExpr(loopInv.E))));
} else {
- List<Expression!>! definitions, pieces;
+ List<Expression> definitions, pieces;
if (!SplitExpr(loopInv.E, out definitions, out pieces)) {
invariants.Add(Assert(loopInv.E.tok, Bpl.Expr.Imp(w, etran.TrExpr(loopInv.E)), "loop invariant violation"));
} else {
@@ -2409,18 +2682,18 @@ namespace Microsoft.Dafny {
if (tri.IsFree) {
invariants.Add(new Bpl.AssumeCmd(stmt.Tok, tri.Expr));
} else {
- assert tri.ErrorMessage != null; // follows from BoilerplateTriple invariant
+ Contract.Assert( tri.ErrorMessage != null); // follows from BoilerplateTriple invariant
invariants.Add(Assert(stmt.Tok, tri.Expr, tri.ErrorMessage));
}
}
// include a free invariant that says that all completed iterations so far have only decreased the termination metric
if (initDecr != null) {
- List<IToken!> toks = new List<IToken!>();
- List<Type!> types = new List<Type!>();
- List<Bpl.Expr!> decrs = new List<Bpl.Expr!>();
+ List<IToken> toks = new List<IToken>();
+ List<Type> types = new List<Type>();
+ List<Bpl.Expr> decrs = new List<Bpl.Expr>();
foreach (Expression e in theDecreases) {
toks.Add(e.tok);
- types.Add((!)e.Type);
+ types.Add(cce.NonNull(e.Type));
decrs.Add(etran.TrExpr(e));
}
Bpl.Expr decrCheck = DecreasesCheck(toks, types, decrs, initDecr, etran, null, null, true);
@@ -2447,7 +2720,7 @@ namespace Microsoft.Dafny {
// as the first thing inside the loop, generate: if (!w) { assert IsTotal(inv); assume false; }
invDefinednessBuilder.Add(new Bpl.AssumeCmd(stmt.Tok, Bpl.Expr.False));
loopBodyBuilder.Add(new Bpl.IfCmd(stmt.Tok, Bpl.Expr.Not(w), invDefinednessBuilder.Collect(stmt.Tok), null, null));
- // generate: assert IsTotal(guard); if (!guard) { break; }
+ // generate: Contract.Assert( IsTotal(guard); if (!guard) { break); }
Bpl.Expr guard;
if (s.Guard == null) {
guard = null;
@@ -2463,20 +2736,20 @@ namespace Microsoft.Dafny {
new Bpl.ExprSeq(CevLocation(stmt.Tok), new Bpl.IdentifierExpr(stmt.Tok, "loop_entered", predef.CevEventType)),
new Bpl.IdentifierExprSeq()));
// termination checking
- if (exists{Expression e in theDecreases; e is WildcardExpr}) {
+ if (Contract.Exists(theDecreases,e=> e is WildcardExpr)) {
// omit termination checking for this loop
TrStmt(s.Body, loopBodyBuilder, locals, etran);
} else {
- List<Bpl.Expr!> oldBfs = RecordDecreasesValue(theDecreases, loopBodyBuilder, locals, etran, "$decr" + loopId + "$");
+ List<Bpl.Expr> oldBfs = RecordDecreasesValue(theDecreases, loopBodyBuilder, locals, etran, "$decr" + loopId + "$");
// time for the actual loop body
TrStmt(s.Body, loopBodyBuilder, locals, etran);
// check definedness of decreases expressions
- List<IToken!> toks = new List<IToken!>();
- List<Type!> types = new List<Type!>();
- List<Bpl.Expr!> decrs = new List<Bpl.Expr!>();
+ List<IToken> toks = new List<IToken>();
+ List<Type> types = new List<Type>();
+ List<Bpl.Expr> decrs = new List<Bpl.Expr>();
foreach (Expression e in theDecreases) {
toks.Add(e.tok);
- types.Add((!)e.Type);
+ types.Add(cce.NonNull(e.Type));
decrs.Add(etran.TrExpr(e));
}
Bpl.Expr decrCheck = DecreasesCheck(toks, types, decrs, oldBfs, etran, loopBodyBuilder, " at end of loop iteration", false);
@@ -2536,7 +2809,7 @@ namespace Microsoft.Dafny {
if (ps is AssertStmt) {
Bpl.Expr q = new Bpl.ForallExpr(ps.Expr.tok, new Bpl.VariableSeq(oVar), Bpl.Expr.Imp(oInS, IsTotal(ps.Expr, etran)));
builder.Add(AssertNS(ps.Expr.tok, q, "assert condition must be well defined")); // totality check
- List<Expression!>! definitions, pieces;
+ List<Expression> definitions, pieces;
SplitExpr(ps.Expr, out definitions, out pieces);
foreach (Expression d in definitions) {
Bpl.Expr e = etran.TrExpr(d);
@@ -2553,7 +2826,7 @@ namespace Microsoft.Dafny {
Bpl.Expr q = new Bpl.ForallExpr(ps.Expr.tok, new Bpl.VariableSeq(oVar), Bpl.Expr.Imp(oInS, eIsTotal));
builder.Add(AssertNS(ps.Expr.tok, q, "assume condition must be well defined")); // totality check
} else {
- assert ps is UseStmt;
+ Contract.Assert( ps is UseStmt);
// no totality check (see UseStmt case above)
}
Bpl.Expr enchilada; // the whole enchilada
@@ -2576,7 +2849,7 @@ namespace Microsoft.Dafny {
builder.Add(AssertNS(rhsExpr.Expr.tok, qqq, "RHS of assignment must be well defined")); // totality check
}
- // Here comes: assert (forall o: ref :: o != null && o in S && Range(o) ==> $_Frame[o,F]);
+ // Here comes: Contract.Assert( (forall o: ref :: o != null && o in S && Range(o) ==> $_Frame[o,F]);
Bpl.Expr body = Bpl.Expr.Imp(oInS, Bpl.Expr.Select(etran.TheFrame(stmt.Tok), o, GetField((FieldSelectExpr)s.BodyAssign.Lhs)));
Bpl.Expr qq = new Bpl.ForallExpr(stmt.Tok, new Bpl.VariableSeq(oVar), body);
builder.Add(Assert(s.BodyAssign.Tok, qq, "foreach assignment may update an object not in the enclosing method's modifies clause"));
@@ -2627,7 +2900,7 @@ namespace Microsoft.Dafny {
for (int i = s.Cases.Count; 0 <= --i; ) {
MatchCaseStmt mc = (MatchCaseStmt)s.Cases[i];
// havoc all bound variables
- List<Expression!> rArgs = new List<Expression!>();
+ List<Expression> rArgs = new List<Expression>();
Bpl.IdentifierExprSeq havocIds = new Bpl.IdentifierExprSeq();
foreach (BoundVar arg in mc.Arguments) {
Bpl.LocalVariable v = new Bpl.LocalVariable(arg.tok, new Bpl.TypedIdent(arg.tok, arg.UniqueName, TrType(arg.Type)));
@@ -2640,9 +2913,9 @@ namespace Microsoft.Dafny {
if (havocIds.Length != 0) {
builder.Add(new Bpl.HavocCmd(mc.tok, havocIds));
}
- assert mc.Ctor != null && mc.Ctor.EnclosingDatatype != null; // everything has been successfully resolved
+ Contract.Assert( mc.Ctor != null && mc.Ctor.EnclosingDatatype != null); // everything has been successfully resolved
DatatypeValue r = new DatatypeValue(mc.tok, mc.Ctor.EnclosingDatatype.Name, mc.Ctor.Name, rArgs);
- r.Ctor = mc.Ctor; r.Type = new UserDefinedType(mc.tok, mc.Ctor.EnclosingDatatype.Name, new List<Type!>()/*this is not right, but it seems like it won't matter here*/); // resolve it here
+ r.Ctor = mc.Ctor; r.Type = new UserDefinedType(mc.tok, mc.Ctor.EnclosingDatatype.Name, new List<Type>()/*this is not right, but it seems like it won't matter here*/); // resolve it here
// translate the body into b
b = new Bpl.StmtListBuilder();
@@ -2654,16 +2927,19 @@ namespace Microsoft.Dafny {
ifCmd = new Bpl.IfCmd(mc.tok, guard, b.Collect(mc.tok), ifCmd, els);
els = null;
}
- assert ifCmd != null; // follows from the fact that s.Cases.Count != 0.
+ Contract.Assert( ifCmd != null); // follows from the fact that s.Cases.Count != 0.
builder.Add(ifCmd);
} else {
- assert false; // unexpected statement
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected statement
}
}
- static Expression! CreateIntLiteral(IToken! tok, int n)
+ static Expression CreateIntLiteral(IToken tok, int n)
{
+ Contract.Requires(tok != null);
+ Contract.Ensures(Contract.Result<Expression>() != null);
+
if (0 <= n) {
Expression lit = new LiteralExpr(tok, n);
lit.Type = Type.Int; // resolve here
@@ -2673,33 +2949,48 @@ namespace Microsoft.Dafny {
}
}
- static Expression! CreateIntSub(IToken! tok, Expression! e0, Expression! e1)
- requires e0.Type is IntType && e1.Type is IntType;
- {
+ static Expression CreateIntSub(IToken tok, Expression e0, Expression e1)
+ {
+ Contract.Requires(tok != null);
+ Contract.Requires(e0 != null);
+ Contract.Requires(e1 != null);
+
+
+ Contract.Requires( e0.Type is IntType && e1.Type is IntType);
+ Contract.Ensures(Contract.Result<Expression>() != null);
BinaryExpr s = new BinaryExpr(tok, BinaryExpr.Opcode.Sub, e0, e1);
s.ResolvedOp = BinaryExpr.ResolvedOpcode.Sub; // resolve here
s.Type = Type.Int; // resolve here
return s;
}
- static Expression! CreateIntITE(IToken! tok, Expression! test, Expression! e0, Expression! e1)
- requires test.Type is BoolType && e0.Type is IntType && e1.Type is IntType;
- {
+ static Expression CreateIntITE(IToken tok, Expression test, Expression e0, Expression e1)
+ {
+ Contract.Requires(tok != null);
+ Contract.Requires(test != null);
+ Contract.Requires(e0 != null);
+ Contract.Requires(e1 != null);
+ Contract.Requires( test.Type is BoolType && e0.Type is IntType && e1.Type is IntType);
+ Contract.Ensures(Contract.Result<Expression>() != null);
+
ITEExpr ite = new ITEExpr(tok, test, e0, e1);
ite.Type = Type.Int; // resolve here
return ite;
}
- public IEnumerable<Expression!>! Conjuncts(Expression! expr)
- requires expr.Type is BoolType;
- {
+ public IEnumerable<Expression> Conjuncts(Expression expr)
+ {
+ Contract.Requires(expr != null);
+ Contract.Requires( expr.Type is BoolType);
+ Contract.Ensures(cce.NonNullElements(Contract.Result<IEnumerable<Expression>>()));
+
if (expr is BinaryExpr) {
BinaryExpr bin = (BinaryExpr)expr;
if (bin.ResolvedOp == BinaryExpr.ResolvedOpcode.And) {
foreach (Expression e in Conjuncts(bin.E0)) {
yield return e;
}
- assert bin != null; // the necessity of this cast is a compiler bug, but perhaps an irrepairable one
+ Contract.Assert( bin != null); // the necessity of this cast is a compiler bug, but perhaps an irrepairable one
foreach (Expression e in Conjuncts(bin.E1)) {
yield return e;
}
@@ -2709,12 +3000,18 @@ namespace Microsoft.Dafny {
yield return expr;
}
- List<Bpl.Expr!>! RecordDecreasesValue(List<Expression!>! decreases, Bpl.StmtListBuilder! builder, Bpl.VariableSeq! locals, ExpressionTranslator! etran, string! varPrefix)
+ List<Bpl.Expr> RecordDecreasesValue(List<Expression> decreases, Bpl.StmtListBuilder builder, Bpl.VariableSeq locals, ExpressionTranslator etran, string varPrefix)
{
- List<Bpl.Expr!> oldBfs = new List<Bpl.Expr!>();
+ Contract.Requires(locals != null);
+ Contract.Requires(etran != null);
+ Contract.Requires(varPrefix != null);
+ Contract.Requires(builder != null);
+ Contract.Requires(decreases != null);
+ List<Bpl.Expr> oldBfs = new List<Bpl.Expr>();
int c = 0;
foreach (Expression e in decreases) {
- Bpl.LocalVariable bfVar = new Bpl.LocalVariable(e.tok, new Bpl.TypedIdent(e.tok, varPrefix + c, TrType((!)e.Type)));
+ Contract.Assert(e != null);
+ Bpl.LocalVariable bfVar = new Bpl.LocalVariable(e.tok, new Bpl.TypedIdent(e.tok, varPrefix + c, TrType(cce.NonNull(e.Type))));
locals.Add(bfVar);
Bpl.IdentifierExpr bf = new Bpl.IdentifierExpr(e.tok, bfVar);
oldBfs.Add(bf);
@@ -2727,19 +3024,25 @@ namespace Microsoft.Dafny {
return oldBfs;
}
- void CheckCallTermination(IToken! tok, List<Expression!>! contextDecreases, List<Expression!>! calleeDecreases,
- Expression receiverReplacement, Dictionary<IVariable,Expression!>! substMap,
- ExpressionTranslator! etran, Bpl.StmtListBuilder! builder)
- {
- int N = min{contextDecreases.Count, calleeDecreases.Count};
- List<IToken!> toks = new List<IToken!>();
- List<Type!> types = new List<Type!>();
- List<Bpl.Expr!> callee = new List<Bpl.Expr!>();
- List<Bpl.Expr!> caller = new List<Bpl.Expr!>();
+ void CheckCallTermination(IToken/*!*/ tok, List<Expression/*!*/>/*!*/ contextDecreases, List<Expression/*!*/>/*!*/ calleeDecreases,
+ Expression receiverReplacement, Dictionary<IVariable,Expression/*!*/>/*!*/ substMap,
+ ExpressionTranslator/*!*/ etran, Bpl.StmtListBuilder/*!*/ builder){
+ Contract.Requires(tok != null);
+ Contract.Requires(cce.NonNullElements(contextDecreases));
+ Contract.Requires(cce.NonNullElements(calleeDecreases));
+ Contract.Requires(cce.NonNullElements(substMap));
+ Contract.Requires(etran != null);
+ Contract.Requires(builder != null);
+
+ int N = Math.Min(contextDecreases.Count, calleeDecreases.Count);
+ List<IToken> toks = new List<IToken>();
+ List<Type> types = new List<Type>();
+ List<Bpl.Expr> callee = new List<Bpl.Expr>();
+ List<Bpl.Expr> caller = new List<Bpl.Expr>();
for (int i = 0; i < N; i++) {
Expression e0 = Substitute(calleeDecreases[i], receiverReplacement, substMap);
Expression e1 = contextDecreases[i];
- if (!CompatibleDecreasesTypes((!)e0.Type, (!)e1.Type)) {
+ if (!CompatibleDecreasesTypes(cce.NonNull(e0.Type), cce.NonNull(e1.Type))) {
break;
}
toks.Add(tok);
@@ -2757,20 +3060,26 @@ namespace Microsoft.Dafny {
/// ee0 represents the new values and ee1 represents old values.
/// If builder is non-null, then the check '0 ATMOST decr' is generated to builder.
/// </summary>
- Bpl.Expr! DecreasesCheck(List<IToken!>! toks, List<Type!>! types, List<Bpl.Expr!>! ee0, List<Bpl.Expr!>! ee1,
- ExpressionTranslator! etran,
- Bpl.StmtListBuilder builder, string suffixMsg, bool allowNoChange)
- requires predef != null;
- requires types.Count == ee0.Count && ee0.Count == ee1.Count;
- requires builder != null <==> suffixMsg != null;
- {
+ Bpl.Expr DecreasesCheck(List<IToken/*!*/>/*!*/ toks, List<Type/*!*/>/*!*/ types, List<Bpl.Expr/*!*/>/*!*/ ee0, List<Bpl.Expr/*!*/>/*!*/ ee1,
+ ExpressionTranslator/*!*/ etran, Bpl.StmtListBuilder builder, string suffixMsg, bool allowNoChange)
+ {
+ Contract.Requires(cce.NonNullElements(toks));
+ Contract.Requires(cce.NonNullElements(types));
+ Contract.Requires(cce.NonNullElements(ee0));
+ Contract.Requires(cce.NonNullElements(ee1));
+ Contract.Requires(etran != null);
+ Contract.Requires( predef != null);
+ Contract.Requires( types.Count == ee0.Count && ee0.Count == ee1.Count);
+ Contract.Requires( builder != null && suffixMsg != null);
+ Contract.Ensures(Contract.Result<Bpl.Expr>() != null);
+
int N = types.Count;
// compute eq and less for each component of the lexicographic pair
- List<Bpl.Expr!> Eq = new List<Bpl.Expr!>(N);
- List<Bpl.Expr!> Less = new List<Bpl.Expr!>(N);
+ List<Bpl.Expr> Eq = new List<Bpl.Expr>(N);
+ List<Bpl.Expr> Less = new List<Bpl.Expr>(N);
for (int i = 0; i < N; i++) {
- Bpl.Expr! less, atmost, eq;
+ Bpl.Expr less, atmost, eq;
ComputeLessEq(toks[i], types[i], ee0[i], ee1[i], out less, out atmost, out eq, etran);
Eq.Add(eq);
Less.Add(allowNoChange ? atmost : less);
@@ -2812,7 +3121,9 @@ namespace Microsoft.Dafny {
return decrCheck;
}
- bool CompatibleDecreasesTypes(Type! t, Type! u) {
+ bool CompatibleDecreasesTypes(Type t, Type u) {
+ Contract.Requires(t != null);
+ Contract.Requires(u != null);
if (t is BoolType) {
return u is BoolType;
} else if (t is IntType) {
@@ -2824,14 +3135,23 @@ namespace Microsoft.Dafny {
} else if (t.IsDatatype) {
return u.IsDatatype;
} else {
- assert t.IsRefType;
+ Contract.Assert( t.IsRefType);
return u.IsRefType;
}
}
- void ComputeLessEq(IToken! tok, Type! ty, Bpl.Expr! e0, Bpl.Expr! e1, out Bpl.Expr! less, out Bpl.Expr! atmost, out Bpl.Expr! eq, ExpressionTranslator! etran)
- requires predef != null;
- {
+ void ComputeLessEq(IToken/*!*/ tok, Type/*!*/ ty, Bpl.Expr/*!*/ e0, Bpl.Expr/*!*/ e1, out Bpl.Expr/*!*/ less, out Bpl.Expr/*!*/ atmost, out Bpl.Expr/*!*/ eq, ExpressionTranslator/*!*/ etran)
+ {
+ Contract.Requires(tok != null);
+ Contract.Requires(ty != null);
+ Contract.Requires(e0 != null);
+ Contract.Requires(e1 != null);
+ Contract.Requires(etran != null);
+ Contract.Requires( predef != null);
+ Contract.Ensures(Contract.ValueAtReturn(out less)!=null);
+ Contract.Ensures(Contract.ValueAtReturn(out atmost)!=null);
+ Contract.Ensures(Contract.ValueAtReturn(out eq)!=null);
+
if (ty is BoolType) {
eq = Bpl.Expr.Iff(e0, e1);
less = Bpl.Expr.And(Bpl.Expr.Not(e0), e1);
@@ -2867,16 +3187,23 @@ namespace Microsoft.Dafny {
}
}
- void AddComment(Bpl.StmtListBuilder! builder, Statement! stmt, string! comment) {
+ void AddComment(Bpl.StmtListBuilder builder, Statement stmt, string comment) {
+ Contract.Requires(builder != null);
+ Contract.Requires(stmt != null);
+ Contract.Requires(comment != null);
builder.Add(new Bpl.CommentCmd(string.Format("----- {0} ----- {1}({2},{3})", comment, stmt.Tok.filename, stmt.Tok.line, stmt.Tok.col)));
}
- Bpl.Expr GetWhereClause(IToken! tok, Bpl.Expr! x, Type! type, ExpressionTranslator! etran)
- requires predef != null;
- {
+ Bpl.Expr GetWhereClause(IToken tok, Bpl.Expr x, Type type, ExpressionTranslator etran)
+ {
+ Contract.Requires(tok != null);
+ Contract.Requires(x != null);
+ Contract.Requires(type != null);
+ Contract.Requires(etran != null);
+ Contract.Requires( predef != null);
if (type is TypeProxy) {
// unresolved proxy
- assert ((TypeProxy)type).T == null;
+ Contract.Assert( ((TypeProxy)type).T == null);
// omit where clause (in other places, unresolved proxies are treated as a reference type; we could do that here too, but
// we might as well leave out the where clause altogether)
return null;
@@ -2933,10 +3260,16 @@ namespace Microsoft.Dafny {
}
}
- void TrAssignment(IToken! tok, Expression! lhs, AssignmentRhs! rhs, Bpl.StmtListBuilder! builder, Bpl.VariableSeq! locals,
- ExpressionTranslator! etran)
- requires predef != null;
+ void TrAssignment(IToken tok, Expression lhs, AssignmentRhs rhs, Bpl.StmtListBuilder builder, Bpl.VariableSeq locals,
+ ExpressionTranslator etran)
{
+ Contract.Requires(tok != null);
+ Contract.Requires(lhs != null);
+ Contract.Requires(rhs != null);
+ Contract.Requires(builder != null);
+ Contract.Requires(cce.NonNullElements(locals));
+ Contract.Requires(etran != null);
+ Contract.Requires( predef != null);
if (rhs is ExprRhs) {
builder.Add(Assert(tok, IsTotal(lhs, etran), "LHS expression must be well defined")); // totality check
builder.Add(Assert(tok, IsTotal(((ExprRhs)rhs).Expr, etran), "RHS expression must be well defined")); // totality check
@@ -2947,27 +3280,27 @@ namespace Microsoft.Dafny {
builder.Add(cmd);
} else if (lhs is FieldSelectExpr) {
FieldSelectExpr fse = (FieldSelectExpr)lhs;
- assert fse.Field != null;
- // check that the enclosing modifies clause allows this object to be written: assert $_Frame[obj];
+ Contract.Assert( fse.Field != null);
+ // check that the enclosing modifies clause allows this object to be written: Contract.Assert( $_Frame[obj]);
builder.Add(Assert(tok, Bpl.Expr.SelectTok(tok, etran.TheFrame(tok), etran.TrExpr(fse.Obj), GetField(fse)), "assignment may update an object not in the enclosing method's modifies clause"));
- Bpl.IdentifierExpr h = (Bpl.IdentifierExpr!)etran.HeapExpr; // TODO: is this cast always justified?
- bRhs = etran.CondApplyBox(tok, bRhs, (!)((ExprRhs)rhs).Expr.Type, fse.Field.Type);
+ Bpl.IdentifierExpr h = cce.NonNull((Bpl.IdentifierExpr)etran.HeapExpr); // TODO: is this cast always justified?
+ bRhs = etran.CondApplyBox(tok, bRhs, cce.NonNull((ExprRhs)rhs).Expr.Type, fse.Field.Type);
Bpl.Cmd cmd = Bpl.Cmd.MapAssign(tok, h, etran.TrExpr(fse.Obj), new Bpl.IdentifierExpr(tok, GetField(fse.Field)), bRhs);
builder.Add(cmd);
// assume $IsGoodHeap($Heap);
builder.Add(AssumeGoodHeap(tok, etran));
} else {
SeqSelectExpr sel = (SeqSelectExpr)lhs;
- assert sel.Seq.Type != null && sel.Seq.Type.IsArrayType;
+ Contract.Assert( sel.Seq.Type != null && sel.Seq.Type.IsArrayType);
bRhs = etran.BoxIfNecessary(tok, bRhs, UserDefinedType.ArrayElementType(sel.Seq.Type));
if (sel.SelectOne) {
- assert sel.E0 != null;
+ Contract.Assert( sel.E0 != null);
Bpl.Expr fieldName = FunctionCall(tok, BuiltinFunction.IndexField, null, etran.TrExpr(sel.E0));
- // check that the enclosing modifies clause allows this object to be written: assert $_Frame[obj,index];
+ // check that the enclosing modifies clause allows this object to be written: Contract.Assert( $_Frame[obj,index]);
builder.Add(Assert(tok, Bpl.Expr.SelectTok(tok, etran.TheFrame(tok), etran.TrExpr(sel.Seq), fieldName), "assignment may update an array not in the enclosing method's modifies clause"));
- Bpl.IdentifierExpr h = (Bpl.IdentifierExpr!)etran.HeapExpr; // TODO: is this cast always justified?
+ Bpl.IdentifierExpr h = cce.NonNull((Bpl.IdentifierExpr)etran.HeapExpr); // TODO: is this cast always justified?
Bpl.Cmd cmd = Bpl.Cmd.MapAssign(tok, h, etran.TrExpr(sel.Seq), fieldName, bRhs);
builder.Add(cmd);
// assume $IsGoodHeap($Heap);
@@ -2992,14 +3325,14 @@ namespace Microsoft.Dafny {
}
} else if (rhs is HavocRhs) {
- assert lhs is IdentifierExpr; // for this kind of RHS, the LHS is restricted to be a simple variable
+ Contract.Assert( lhs is IdentifierExpr); // for this kind of RHS, the LHS is restricted to be a simple variable
Bpl.IdentifierExpr x = (Bpl.IdentifierExpr)etran.TrExpr(lhs); // TODO: is this cast always justified?
builder.Add(new Bpl.HavocCmd(tok, new Bpl.IdentifierExprSeq(x)));
} else {
- assert rhs is TypeRhs; // otherwise, an unexpected AssignmentRhs
+ Contract.Assert( rhs is TypeRhs); // otherwise, an unexpected AssignmentRhs
TypeRhs tRhs = (TypeRhs)rhs;
- assert lhs is IdentifierExpr; // for this kind of RHS, the LHS is restricted to be a simple variable
+ Contract.Assert( lhs is IdentifierExpr); // for this kind of RHS, the LHS is restricted to be a simple variable
if (tRhs.ArraySize != null) {
CheckWellformed(tRhs.ArraySize, null, Position.Positive, locals, builder, etran);
@@ -3013,11 +3346,11 @@ namespace Microsoft.Dafny {
Bpl.Expr rightType;
if (tRhs.ArraySize != null) {
// array allocation
- List<Type!> typeArgs = new List<Type!>();
+ List<Type> typeArgs = new List<Type>();
typeArgs.Add(tRhs.EType);
rightType = etran.GoodRef_Ref(tok, nw, new Bpl.IdentifierExpr(tok, "class.array", predef.ClassNameType), typeArgs, true);
} else if (tRhs.EType is ObjectType) {
- rightType = etran.GoodRef_Ref(tok, nw, new Bpl.IdentifierExpr(tok, "class.object", predef.ClassNameType), new List<Type!>(), true);
+ rightType = etran.GoodRef_Ref(tok, nw, new Bpl.IdentifierExpr(tok, "class.object", predef.ClassNameType), new List<Type>(), true);
} else {
rightType = etran.GoodRef_Class(tok, nw, (UserDefinedType)tRhs.EType, true);
}
@@ -3039,41 +3372,68 @@ namespace Microsoft.Dafny {
}
}
- Bpl.AssumeCmd! AssumeGoodHeap(IToken! tok, ExpressionTranslator! etran) {
+ Bpl.AssumeCmd AssumeGoodHeap(IToken tok, ExpressionTranslator etran) {
+ Contract.Requires(tok != null);
+ Contract.Requires(etran != null);
+ Contract.Ensures(Contract.Result<AssumeCmd>() != null);
+
return new Bpl.AssumeCmd(tok, FunctionCall(tok, BuiltinFunction.IsGoodHeap, null, etran.HeapExpr));
}
// ----- Expression ---------------------------------------------------------------------------
internal class ExpressionTranslator {
- public readonly Bpl.Expr! HeapExpr;
- public readonly PredefinedDecls! predef;
- public readonly Translator! translator;
- public readonly string! This;
+ public readonly Bpl.Expr HeapExpr;
+ public readonly PredefinedDecls predef;
+ public readonly Translator translator;
+ public readonly string This;
readonly Function applyLimited_CurrentFunction;
+ [ContractInvariantMethod]
+void ObjectInvariant()
+{
+ Contract.Invariant(HeapExpr!=null);
+ Contract.Invariant(predef != null);
+ Contract.Invariant(translator != null);
+ Contract.Invariant(This != null);
+}
+
- public ExpressionTranslator(Translator! translator, PredefinedDecls! predef, IToken! heapToken) {
+ public ExpressionTranslator(Translator translator, PredefinedDecls predef, IToken heapToken) {
+ Contract.Requires(translator != null);
+ Contract.Requires(predef != null);
+ Contract.Requires(heapToken != null);
this.translator = translator;
this.predef = predef;
this.HeapExpr = new Bpl.IdentifierExpr(heapToken, predef.HeapVarName, predef.HeapType);
this.This = "this";
}
- public ExpressionTranslator(Translator! translator, PredefinedDecls! predef, Bpl.Expr! heap) {
+ public ExpressionTranslator(Translator translator, PredefinedDecls predef, Bpl.Expr heap) {
+ Contract.Requires(translator != null);
+ Contract.Requires(predef != null);
+ Contract.Requires(heap != null);
this.translator = translator;
this.predef = predef;
this.HeapExpr = heap;
this.This = "this";
}
- public ExpressionTranslator(Translator! translator, PredefinedDecls! predef, Bpl.Expr! heap, string! thisVar) {
+ public ExpressionTranslator(Translator translator, PredefinedDecls predef, Bpl.Expr heap, string thisVar) {
+ Contract.Requires(translator != null);
+ Contract.Requires(predef != null);
+ Contract.Requires(heap != null);
+ Contract.Requires(thisVar != null);
this.translator = translator;
this.predef = predef;
this.HeapExpr = heap;
this.This = thisVar;
}
- ExpressionTranslator(Translator! translator, PredefinedDecls! predef, Bpl.Expr! heap, Function applyLimited_CurrentFunction) {
+ ExpressionTranslator(Translator translator, PredefinedDecls predef, Bpl.Expr heap, Function applyLimited_CurrentFunction) {
+ Contract.Requires(translator != null);
+ Contract.Requires(predef != null);
+ Contract.Requires(heap != null);
+ Contract.Requires(applyLimited_CurrentFunction != null);
this.translator = translator;
this.predef = predef;
this.HeapExpr = heap;
@@ -3082,8 +3442,10 @@ namespace Microsoft.Dafny {
}
ExpressionTranslator oldEtran;
- public ExpressionTranslator! Old {
+ public ExpressionTranslator Old {
get {
+ Contract.Ensures(Contract.Result<ExpressionTranslator>() != null);
+
if (oldEtran == null) {
oldEtran = new ExpressionTranslator(translator, predef, new Bpl.OldExpr(HeapExpr.tok, HeapExpr), applyLimited_CurrentFunction);
}
@@ -3091,40 +3453,47 @@ namespace Microsoft.Dafny {
}
}
- public ExpressionTranslator! LimitedFunctions(Function! applyLimited_CurrentFunction) {
+ public ExpressionTranslator LimitedFunctions(Function applyLimited_CurrentFunction) {
+ Contract.Requires(applyLimited_CurrentFunction != null);
+ Contract.Ensures(Contract.Result<ExpressionTranslator>() != null);
+
return new ExpressionTranslator(translator, predef, HeapExpr, applyLimited_CurrentFunction);
}
- public Bpl.IdentifierExpr! TheFrame(IToken! tok)
- ensures result.Type != null;
+ public Bpl.IdentifierExpr TheFrame(IToken tok)
{
+ Contract.Requires(tok != null);
+ Contract.Ensures(Contract.Result<Bpl.IdentifierExpr>() != null);
+ Contract.Ensures( Contract.Result<Bpl.IdentifierExpr>().Type != null);
+
Bpl.TypeVariable alpha = new Bpl.TypeVariable(tok, "beta");
Bpl.Type fieldAlpha = predef.FieldName(tok, alpha);
Bpl.Type ty = new Bpl.MapType(tok, new Bpl.TypeVariableSeq(alpha), new Bpl.TypeSeq(predef.RefType, fieldAlpha), Bpl.Type.Bool);
return new Bpl.IdentifierExpr(tok, "$_Frame", ty);
}
- public Bpl.IdentifierExpr! ModuleContextHeight()
- ensures result.Type != null;
- {
+ public Bpl.IdentifierExpr ModuleContextHeight()
+ {
+ Contract.Ensures( Contract.Result<Bpl.IdentifierExpr>().Type != null);
return new Bpl.IdentifierExpr(Token.NoToken, "$ModuleContextHeight", Bpl.Type.Int);
}
- public Bpl.IdentifierExpr! FunctionContextHeight()
- ensures result.Type != null;
- {
+ public Bpl.IdentifierExpr FunctionContextHeight()
+ {
+ Contract.Ensures( Contract.Result<Bpl.IdentifierExpr>().Type != null);
return new Bpl.IdentifierExpr(Token.NoToken, "$FunctionContextHeight", Bpl.Type.Int);
}
- public Bpl.IdentifierExpr! InMethodContext()
- ensures result.Type != null;
- {
+ public Bpl.IdentifierExpr InMethodContext()
+ {
+ Contract.Ensures( Contract.Result<Bpl.IdentifierExpr>().Type != null);
return new Bpl.IdentifierExpr(Token.NoToken, "$InMethodContext", Bpl.Type.Bool);
}
- public Bpl.Expr! TrExpr(Expression! expr)
- requires predef != null;
- {
+ public Bpl.Expr TrExpr(Expression expr)
+ {
+ Contract.Requires(expr != null);
+ Contract.Requires( predef != null);
if (expr is LiteralExpr) {
LiteralExpr e = (LiteralExpr)expr;
if (e.Value == null) {
@@ -3134,7 +3503,7 @@ namespace Microsoft.Dafny {
} else if (e.Value is BigInteger) {
return Bpl.Expr.Literal(Microsoft.Basetypes.BigNum.FromBigInt((BigInteger)e.Value));
} else {
- assert false; // unexpected literal
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected literal
}
} else if (expr is ThisExpr) {
@@ -3142,13 +3511,13 @@ namespace Microsoft.Dafny {
} else if (expr is IdentifierExpr) {
IdentifierExpr e = (IdentifierExpr)expr;
- return TrVar(expr.tok, (!)e.Var);
+ return TrVar(expr.tok, cce.NonNull(e.Var));
} else if (expr is SetDisplayExpr) {
SetDisplayExpr e = (SetDisplayExpr)expr;
Bpl.Expr s = translator.FunctionCall(expr.tok, BuiltinFunction.SetEmpty, predef.BoxType);
foreach (Expression ee in e.Elements) {
- Bpl.Expr ss = BoxIfNecessary(expr.tok, TrExpr(ee), (!)ee.Type);
+ Bpl.Expr ss = BoxIfNecessary(expr.tok, TrExpr(ee), cce.NonNull(ee.Type));
s = translator.FunctionCall(expr.tok, BuiltinFunction.SetUnionOne, predef.BoxType, s, ss);
}
return s;
@@ -3158,7 +3527,7 @@ namespace Microsoft.Dafny {
Bpl.Expr s = translator.FunctionCall(expr.tok, BuiltinFunction.SeqEmpty, predef.BoxType);
int i = 0;
foreach (Expression ee in e.Elements) {
- Bpl.Expr ss = BoxIfNecessary(expr.tok, TrExpr(ee), (!)ee.Type);
+ Bpl.Expr ss = BoxIfNecessary(expr.tok, TrExpr(ee), cce.NonNull(ee.Type));
s = translator.FunctionCall(expr.tok, BuiltinFunction.SeqBuild, predef.BoxType, s, Bpl.Expr.Literal(i), ss, Bpl.Expr.Literal(i+1));
i++;
}
@@ -3166,16 +3535,16 @@ namespace Microsoft.Dafny {
} else if (expr is FieldSelectExpr) {
FieldSelectExpr e = (FieldSelectExpr)expr;
- Bpl.Expr result = Bpl.Expr.SelectTok(expr.tok, HeapExpr, TrExpr(e.Obj), new Bpl.IdentifierExpr(expr.tok, translator.GetField((!)e.Field)));
- return CondApplyUnbox(expr.tok, result, e.Field.Type, (!)expr.Type);
+ Bpl.Expr result = Bpl.Expr.SelectTok(expr.tok, HeapExpr, TrExpr(e.Obj), new Bpl.IdentifierExpr(expr.tok, translator.GetField(cce.NonNull(e.Field))));
+ return CondApplyUnbox(expr.tok, result, e.Field.Type, cce.NonNull(expr.Type));
} else if (expr is SeqSelectExpr) {
SeqSelectExpr e = (SeqSelectExpr)expr;
Bpl.Expr seq = TrExpr(e.Seq);
Type elmtType;
- assert e.Seq.Type != null; // the expression has been successfully resolved
+ Contract.Assert( e.Seq.Type != null); // the expression has been successfully resolved
if (e.Seq.Type.IsArrayType) {
- assert e.SelectOne; // resolution enforces that a non-unit array selections is allowed only as an assignment LHS
+ Contract.Assert( e.SelectOne); // resolution enforces that a non-unit array selections is allowed only as an assignment LHS
elmtType = UserDefinedType.ArrayElementType(e.Seq.Type);
} else {
elmtType = ((SeqType)e.Seq.Type).Arg;
@@ -3184,7 +3553,7 @@ namespace Microsoft.Dafny {
Bpl.Expr e0 = e.E0 == null ? null : TrExpr(e.E0);
Bpl.Expr e1 = e.E1 == null ? null : TrExpr(e.E1);
if (e.SelectOne) {
- assert e1 == null;
+ Contract.Assert( e1 == null);
Bpl.Expr x;
if (e.Seq.Type.IsArrayType) {
Bpl.Expr fieldName = translator.FunctionCall(expr.tok, BuiltinFunction.IndexField, null, e0);
@@ -3209,23 +3578,23 @@ namespace Microsoft.Dafny {
} else if (expr is SeqUpdateExpr) {
SeqUpdateExpr e = (SeqUpdateExpr)expr;
Bpl.Expr seq = TrExpr(e.Seq);
- Type elmtType = ((SeqType!)e.Seq.Type).Arg;
+ Type elmtType = cce.NonNull((SeqType)e.Seq.Type).Arg;
Bpl.Expr index = TrExpr(e.Index);
Bpl.Expr val = BoxIfNecessary(expr.tok, TrExpr(e.Value), elmtType);
return translator.FunctionCall(expr.tok, BuiltinFunction.SeqUpdate, predef.BoxType, seq, index, val);
} else if (expr is FunctionCallExpr) {
FunctionCallExpr e = (FunctionCallExpr)expr;
- string nm = ((!)e.Function).FullName;
+ string nm = cce.NonNull(e.Function).FullName;
if (this.applyLimited_CurrentFunction != null && e.Function.IsRecursive && !e.Function.IsUnlimited) {
- ModuleDecl module = ((!)e.Function.EnclosingClass).Module;
- if (module == ((!)applyLimited_CurrentFunction.EnclosingClass).Module) {
+ ModuleDecl module = cce.NonNull(e.Function.EnclosingClass).Module;
+ if (module == cce.NonNull(applyLimited_CurrentFunction.EnclosingClass).Module) {
if (module.CallGraph.GetSCCRepresentative(e.Function) == module.CallGraph.GetSCCRepresentative(applyLimited_CurrentFunction)) {
nm += "#limited";
}
}
}
- Bpl.IdentifierExpr id = new Bpl.IdentifierExpr(expr.tok, nm, translator.TrType((!)e.Type));
+ Bpl.IdentifierExpr id = new Bpl.IdentifierExpr(expr.tok, nm, translator.TrType(cce.NonNull(e.Type)));
Bpl.ExprSeq args = new Bpl.ExprSeq();
args.Add(HeapExpr);
if (!e.Function.IsStatic) {
@@ -3234,19 +3603,19 @@ namespace Microsoft.Dafny {
for (int i = 0; i < e.Args.Count; i++) {
Expression ee = e.Args[i];
Type t = e.Function.Formals[i].Type;
- args.Add(CondApplyBox(expr.tok, TrExpr(ee), (!)ee.Type, t));
+ args.Add(CondApplyBox(expr.tok, TrExpr(ee), cce.NonNull(ee.Type), t));
}
Bpl.Expr result = new Bpl.NAryExpr(expr.tok, new Bpl.FunctionCall(id), args);
return CondApplyUnbox(expr.tok, result, e.Function.ResultType, expr.Type);
} else if (expr is DatatypeValue) {
DatatypeValue dtv = (DatatypeValue)expr;
- assert dtv.Ctor != null; // since dtv has been successfully resolved
+ Contract.Assert( dtv.Ctor != null); // since dtv has been successfully resolved
Bpl.ExprSeq args = new Bpl.ExprSeq();
for (int i = 0; i < dtv.Arguments.Count; i++) {
Expression arg = dtv.Arguments[i];
Type t = dtv.Ctor.Formals[i].Type;
- args.Add(CondApplyBox(expr.tok, TrExpr(arg), (!)arg.Type, t));
+ args.Add(CondApplyBox(expr.tok, TrExpr(arg), cce.NonNull(arg.Type), t));
}
Bpl.IdentifierExpr id = new Bpl.IdentifierExpr(dtv.tok, dtv.Ctor.FullName, predef.DatatypeType);
return new Bpl.NAryExpr(dtv.tok, new Bpl.FunctionCall(id), args);
@@ -3299,16 +3668,16 @@ namespace Microsoft.Dafny {
return translator.FunctionCall(expr.tok, BuiltinFunction.ArrayLength, null, arg);
}
default:
- assert false; // unexpected unary expression
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected unary expression
}
} else if (expr is BinaryExpr) {
BinaryExpr e = (BinaryExpr)expr;
Bpl.Expr e0 = TrExpr(e.E0);
if (e.ResolvedOp == BinaryExpr.ResolvedOpcode.InSet) {
- return TrInSet(expr.tok, e0, e.E1, (!)e.E0.Type); // let TrInSet translate e.E1
+ return TrInSet(expr.tok, e0, e.E1, cce.NonNull(e.E0.Type)); // let TrInSet translate e.E1
} else if (e.ResolvedOp == BinaryExpr.ResolvedOpcode.NotInSet) {
- Bpl.Expr arg = TrInSet(expr.tok, e0, e.E1, (!)e.E0.Type); // let TrInSet translate e.E1
+ Bpl.Expr arg = TrInSet(expr.tok, e0, e.E1, cce.NonNull(e.E0.Type)); // let TrInSet translate e.E1
return Bpl.Expr.Not(arg);
}
Bpl.Expr e1 = TrExpr(e.E1);
@@ -3363,13 +3732,13 @@ namespace Microsoft.Dafny {
case BinaryExpr.ResolvedOpcode.Disjoint:
return translator.FunctionCall(expr.tok, BuiltinFunction.SetDisjoint, null, e0, e1);
case BinaryExpr.ResolvedOpcode.InSet:
- assert false; // this case handled above
+ Contract.Assert(false); throw new cce.UnreachableException(); // this case handled above
case BinaryExpr.ResolvedOpcode.Union:
- return translator.FunctionCall(expr.tok, BuiltinFunction.SetUnion, translator.TrType(((SetType!)expr.Type).Arg), e0, e1);
+ return translator.FunctionCall(expr.tok, BuiltinFunction.SetUnion, translator.TrType(cce.NonNull((SetType)expr.Type).Arg), e0, e1);
case BinaryExpr.ResolvedOpcode.Intersection:
- return translator.FunctionCall(expr.tok, BuiltinFunction.SetIntersection, translator.TrType(((SetType!)expr.Type).Arg), e0, e1);
+ return translator.FunctionCall(expr.tok, BuiltinFunction.SetIntersection, translator.TrType(cce.NonNull((SetType)expr.Type).Arg), e0, e1);
case BinaryExpr.ResolvedOpcode.SetDifference:
- return translator.FunctionCall(expr.tok, BuiltinFunction.SetDifference, translator.TrType(((SetType!)expr.Type).Arg), e0, e1);
+ return translator.FunctionCall(expr.tok, BuiltinFunction.SetDifference, translator.TrType(cce.NonNull((SetType)expr.Type).Arg), e0, e1);
case BinaryExpr.ResolvedOpcode.SeqEq:
return translator.FunctionCall(expr.tok, BuiltinFunction.SeqEqual, null, e0, e1);
@@ -3386,13 +3755,13 @@ namespace Microsoft.Dafny {
translator.FunctionCall(expr.tok, BuiltinFunction.SeqSameUntil, null, e0, e1, len0));
}
case BinaryExpr.ResolvedOpcode.Concat:
- return translator.FunctionCall(expr.tok, BuiltinFunction.SeqAppend, translator.TrType(((SeqType!)expr.Type).Arg), e0, e1);
+ return translator.FunctionCall(expr.tok, BuiltinFunction.SeqAppend, translator.TrType(cce.NonNull((SeqType)expr.Type).Arg), e0, e1);
case BinaryExpr.ResolvedOpcode.InSeq:
return translator.FunctionCall(expr.tok, BuiltinFunction.SeqContains, null, e1,
- BoxIfNecessary(expr.tok, e0, (!)e.E0.Type));
+ BoxIfNecessary(expr.tok, e0, cce.NonNull(e.E0.Type)));
case BinaryExpr.ResolvedOpcode.NotInSeq:
Bpl.Expr arg = translator.FunctionCall(expr.tok, BuiltinFunction.SeqContains, null, e1,
- BoxIfNecessary(expr.tok, e0, (!)e.E0.Type));
+ BoxIfNecessary(expr.tok, e0, cce.NonNull(e.E0.Type)));
return Bpl.Expr.Not(arg);
case BinaryExpr.ResolvedOpcode.RankLt:
@@ -3405,7 +3774,7 @@ namespace Microsoft.Dafny {
translator.FunctionCall(expr.tok, BuiltinFunction.DtRank, null, e1));
default:
- assert false; // unexpected binary expression
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected binary expression
}
} else if (expr is QuantifierExpr) {
@@ -3428,7 +3797,7 @@ namespace Microsoft.Dafny {
if (e is ForallExpr) {
return new Bpl.ForallExpr(expr.tok, new Bpl.TypeVariableSeq(), bvars, kv, tr, body);
} else {
- assert e is ExistsExpr;
+ Contract.Assert( e is ExistsExpr);
return new Bpl.ExistsExpr(expr.tok, new Bpl.TypeVariableSeq(), bvars, kv, tr, body);
}
@@ -3437,7 +3806,7 @@ namespace Microsoft.Dafny {
Bpl.Expr g = TrExpr(e.Test);
Bpl.Expr thn = TrExpr(e.Thn);
Bpl.Expr els = TrExpr(e.Els);
- return translator.FunctionCall(expr.tok, BuiltinFunction.IfThenElse, translator.TrType((!)expr.Type), g, thn, els);
+ return translator.FunctionCall(expr.tok, BuiltinFunction.IfThenElse, translator.TrType(cce.NonNull(expr.Type)), g, thn, els);
} else if (expr is BoxingCastExpr) {
BoxingCastExpr e = (BoxingCastExpr)expr;
@@ -3448,16 +3817,25 @@ namespace Microsoft.Dafny {
return CondApplyUnbox(e.tok, TrExpr(e.E), e.FromType, e.ToType);
} else {
- assert false; // unexpected expression
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected expression
}
}
- public Bpl.Expr! ProperSubset(IToken! tok, Bpl.Expr! e0, Bpl.Expr! e1) {
+ public Bpl.Expr ProperSubset(IToken tok, Bpl.Expr e0, Bpl.Expr e1) {
+ Contract.Requires(tok != null);
+ Contract.Requires(e0 != null);
+ Contract.Requires(e1 != null);
+ Contract.Ensures(Contract.Result<Bpl.Expr>() != null);
+
return Bpl.Expr.And(
translator.FunctionCall(tok, BuiltinFunction.SetSubset, null, e0, e1),
Bpl.Expr.Not(translator.FunctionCall(tok, BuiltinFunction.SetSubset, null, e1, e0)));
}
- public Bpl.Expr! ProperPrefix(IToken! tok, Bpl.Expr! e0, Bpl.Expr! e1) {
+ public Bpl.Expr ProperPrefix(IToken tok, Bpl.Expr e0, Bpl.Expr e1) {
+ Contract.Requires(tok != null);
+ Contract.Requires(e0 != null);
+ Contract.Requires(e1 != null);
+ Contract.Ensures(Contract.Result<Bpl.Expr>() != null);
Bpl.Expr len0 = translator.FunctionCall(tok, BuiltinFunction.SeqLength, null, e0);
Bpl.Expr len1 = translator.FunctionCall(tok, BuiltinFunction.SeqLength, null, e1);
return Bpl.Expr.And(
@@ -3465,9 +3843,12 @@ namespace Microsoft.Dafny {
translator.FunctionCall(tok, BuiltinFunction.SeqSameUntil, null, e0, e1, len0));
}
- public Bpl.Expr! TrUseExpr(FunctionCallExpr! e)
- requires e.Function != null && e.Type != null;
- {
+ public Bpl.Expr TrUseExpr(FunctionCallExpr e)
+ {
+ Contract.Requires(e != null); Contract.Requires( e.Function != null && e.Type != null);
+ Contract.Ensures(Contract.Result<Bpl.Expr>() != null);
+
+
Function fn = e.Function;
Bpl.ExprSeq args = new Bpl.ExprSeq();
args.Add(HeapExpr);
@@ -3487,7 +3868,13 @@ namespace Microsoft.Dafny {
return Bpl.Expr.Eq(f0, f1);
}
- public Bpl.Expr! CondApplyBox(IToken! tok, Bpl.Expr! e, Type! fromType, Type! toType) {
+ public Bpl.Expr CondApplyBox(IToken tok, Bpl.Expr e, Type fromType, Type toType) {
+ Contract.Requires(tok != null);
+ Contract.Requires(e != null);
+ Contract.Requires(fromType != null);
+ Contract.Requires(toType != null);
+ Contract.Ensures(Contract.Result<Bpl.Expr>() != null);
+
if (!ModeledAsBoxType(fromType) && ModeledAsBoxType(toType)) {
return translator.FunctionCall(tok, BuiltinFunction.Box, null, e);
} else {
@@ -3495,7 +3882,12 @@ namespace Microsoft.Dafny {
}
}
- public Bpl.Expr! BoxIfNecessary(IToken! tok, Bpl.Expr! e, Type! fromType) {
+ public Bpl.Expr BoxIfNecessary(IToken tok, Bpl.Expr e, Type fromType) {
+ Contract.Requires(tok != null);
+ Contract.Requires(e != null);
+ Contract.Requires(fromType != null);
+ Contract.Ensures(Contract.Result<Bpl.Expr>() != null);
+
if (!ModeledAsBoxType(fromType)) {
return translator.FunctionCall(tok, BuiltinFunction.Box, null, e);
} else {
@@ -3503,15 +3895,22 @@ namespace Microsoft.Dafny {
}
}
- public Bpl.Expr! CondApplyUnbox(IToken! tok, Bpl.Expr! e, Type! fromType, Type! toType) {
+ public Bpl.Expr CondApplyUnbox(IToken tok, Bpl.Expr e, Type fromType, Type toType) {
+Contract.Requires(tok != null);
+ Contract.Requires(e != null);
+ Contract.Requires(fromType != null);
+ Contract.Requires(toType != null);
+ Contract.Ensures(Contract.Result<Bpl.Expr>() != null);
if (ModeledAsBoxType(fromType) && !ModeledAsBoxType(toType)) {
return translator.FunctionCall(tok, BuiltinFunction.Unbox, translator.TrType(toType), e);
} else {
return e;
}
+
}
- public static bool ModeledAsBoxType(Type! t) {
+ public static bool ModeledAsBoxType(Type t) {
+ Contract.Requires(t != null);
while (true) {
TypeProxy tp = t as TypeProxy;
if (tp == null) {
@@ -3526,7 +3925,11 @@ namespace Microsoft.Dafny {
return t.IsTypeParameter;
}
- public Bpl.IdentifierExpr! TrVar(IToken! tok, IVariable! var) {
+ public Bpl.IdentifierExpr TrVar(IToken tok, IVariable var) {
+ Contract.Requires(var != null);
+ Contract.Requires(tok != null);
+ Contract.Ensures(Contract.Result<Bpl.IdentifierExpr>() != null);
+
return new Bpl.IdentifierExpr(tok, var.UniqueName, translator.TrType(var.Type));
}
@@ -3534,7 +3937,14 @@ namespace Microsoft.Dafny {
/// Translate like s[Box(elmt)], but try to avoid as many set functions as possible in the
/// translation, because such functions can mess up triggering.
/// </summary>
- public Bpl.Expr! TrInSet(IToken! tok, Bpl.Expr! elmt, Expression! s, Type! elmtType) {
+ public Bpl.Expr TrInSet(IToken tok, Bpl.Expr elmt, Expression s, Type elmtType) {
+ Contract.Requires(tok != null);
+ Contract.Requires(elmt != null);
+ Contract.Requires(s != null);
+ Contract.Requires(elmtType != null);
+
+ Contract.Ensures(Contract.Result<Bpl.Expr>() != null);
+
if (s is BinaryExpr) {
BinaryExpr bin = (BinaryExpr)s;
switch (bin.ResolvedOp) {
@@ -3570,12 +3980,12 @@ namespace Microsoft.Dafny {
Bpl.QKeyValue TrAttributes(Attributes attrs) {
Bpl.QKeyValue kv = null;
while (attrs != null) {
- List<object!> parms = new List<object!>();
+ List<object> parms = new List<object>();
foreach (Attributes.Argument arg in attrs.Args) {
if (arg.E != null) {
parms.Add(TrExpr(arg.E));
} else {
- parms.Add((!)arg.S);
+ parms.Add(cce.NonNull(arg.S));
}
}
kv = new Bpl.QKeyValue(Token.NoToken, attrs.Name, parms, kv);
@@ -3586,16 +3996,29 @@ namespace Microsoft.Dafny {
// --------------- help routines ---------------
- public Bpl.Expr! IsAlloced(IToken! tok, Bpl.Expr! e) {
+ public Bpl.Expr IsAlloced(IToken tok, Bpl.Expr e) {
+ Contract.Requires(tok != null);
+ Contract.Requires(e != null);
+ Contract.Ensures(Contract.Result<Bpl.Expr>() != null);
+
return IsAlloced(tok, e, HeapExpr);
}
- Bpl.Expr! IsAlloced(IToken! tok, Bpl.Expr! e, Bpl.Expr! heap) {
+ Bpl.Expr IsAlloced(IToken tok, Bpl.Expr e, Bpl.Expr heap) {
+ Contract.Requires(tok != null);
+ Contract.Requires(e != null);
+ Contract.Requires(heap != null);
+ Contract.Ensures(Contract.Result<Bpl.Expr>() != null);
+
return Bpl.Expr.SelectTok(tok, heap, e, predef.Alloc(tok));
}
- public Bpl.Expr! GoodRef(IToken! tok, Bpl.Expr! e, Type! type) {
- Bpl.Expr goodRef;
+ public Bpl.Expr GoodRef(IToken tok, Bpl.Expr e, Type type) {
+ Contract.Requires(tok != null);
+ Contract.Requires(e != null);
+ Contract.Requires(type != null);
+ Contract.Ensures(Contract.Result<Bpl.Expr>() != null);
+
if (type is UserDefinedType && ((UserDefinedType)type).ResolvedClass != null) {
// Heap[e, alloc] && dtype(e) == T
return GoodRef_Class(tok, e, (UserDefinedType)type, false);
@@ -3605,13 +4028,21 @@ namespace Microsoft.Dafny {
}
}
- public Bpl.Expr! GoodRef_Class(IToken! tok, Bpl.Expr! e, UserDefinedType! type, bool isNew)
- requires type.ResolvedClass is ClassDecl;
- {
+ public Bpl.Expr GoodRef_Class(IToken tok, Bpl.Expr e, UserDefinedType type, bool isNew)
+ {
+ Contract.Requires(tok != null);
+ Contract.Requires(e != null);
+ Contract.Requires(type != null);
+ Contract.Requires( type.ResolvedClass is ClassDecl);
+ Contract.Ensures(Contract.Result<Bpl.Expr>() != null);
return GoodRef_Ref(tok, e, new Bpl.IdentifierExpr(tok, translator.GetClass(type.ResolvedClass)), type.TypeArgs, isNew);
}
- public Bpl.Expr! GoodRef_Ref(IToken! tok, Bpl.Expr! e, Bpl.Expr! type, List<Type!>! typeArgs, bool isNew) {
+ public Bpl.Expr GoodRef_Ref(IToken tok, Bpl.Expr e, Bpl.Expr type, List<Type/*!*/>/*!*/ typeArgs, bool isNew) {
+ Contract.Requires(tok != null);
+ Contract.Requires(e != null);
+ Contract.Requires(type != null);
+ Contract.Requires(cce.NonNullElements(typeArgs));
// Heap[e, alloc]
Bpl.Expr r = IsAlloced(tok, e);
if (isNew) {
@@ -3637,7 +4068,10 @@ namespace Microsoft.Dafny {
return r;
}
- public Bpl.Expr TypeAlloced(IToken! tok, Bpl.Expr! e, Type! type) {
+ public Bpl.Expr TypeAlloced(IToken tok, Bpl.Expr e, Type type) {
+ Contract.Requires(tok != null);
+ Contract.Requires(e!= null);
+ Contract.Requires(type != null);
while (true) {
TypeProxy proxy = type as TypeProxy;
if (proxy == null) {
@@ -3734,187 +4168,204 @@ namespace Microsoft.Dafny {
}
// The "typeInstantiation" argument is passed in to help construct the result type of the function.
- Bpl.NAryExpr! FunctionCall(IToken! tok, BuiltinFunction f, Bpl.Type typeInstantiation, params Bpl.Expr[]! args)
- requires predef != null;
- {
+ Bpl.NAryExpr FunctionCall(IToken tok, BuiltinFunction f, Bpl.Type typeInstantiation, params Bpl.Expr[] args)
+ {
+ Contract.Requires(tok != null);
+ Contract.Requires(args != null);
+ Contract.Requires( predef != null);
+ Contract.Ensures(Contract.Result<Bpl.NAryExpr>() != null);
+
switch (f) {
case BuiltinFunction.SetEmpty: {
- assert args.Length == 0;
- assert typeInstantiation != null;
+ Contract.Assert( args.Length == 0);
+ Contract.Assert( typeInstantiation != null);
Bpl.Type resultType = predef.SetType(tok, typeInstantiation);
return Bpl.Expr.CoerceType(tok, FunctionCall(tok, "Set#Empty", resultType, args), resultType);
}
case BuiltinFunction.SetUnionOne:
- assert args.Length == 2;
- assert typeInstantiation != null;
+ Contract.Assert( args.Length == 2);
+ Contract.Assert( typeInstantiation != null);
return FunctionCall(tok, "Set#UnionOne", predef.SetType(tok, typeInstantiation), args);
case BuiltinFunction.SetUnion:
- assert args.Length == 2;
- assert typeInstantiation != null;
+ Contract.Assert( args.Length == 2);
+ Contract.Assert( typeInstantiation != null);
return FunctionCall(tok, "Set#Union", predef.SetType(tok, typeInstantiation), args);
case BuiltinFunction.SetIntersection:
- assert args.Length == 2;
- assert typeInstantiation != null;
+ Contract.Assert( args.Length == 2);
+ Contract.Assert( typeInstantiation != null);
return FunctionCall(tok, "Set#Intersection", predef.SetType(tok, typeInstantiation), args);
case BuiltinFunction.SetDifference:
- assert args.Length == 2;
- assert typeInstantiation != null;
+ Contract.Assert( args.Length == 2);
+ Contract.Assert( typeInstantiation != null);
return FunctionCall(tok, "Set#Difference", predef.SetType(tok, typeInstantiation), args);
case BuiltinFunction.SetEqual:
- assert args.Length == 2;
- assert typeInstantiation == null;
+ Contract.Assert( args.Length == 2);
+ Contract.Assert( typeInstantiation == null);
return FunctionCall(tok, "Set#Equal", Bpl.Type.Bool, args);
case BuiltinFunction.SetSubset:
- assert args.Length == 2;
- assert typeInstantiation == null;
+ Contract.Assert( args.Length == 2);
+ Contract.Assert( typeInstantiation == null);
return FunctionCall(tok, "Set#Subset", Bpl.Type.Bool, args);
case BuiltinFunction.SetDisjoint:
- assert args.Length == 2;
- assert typeInstantiation == null;
+ Contract.Assert( args.Length == 2);
+ Contract.Assert( typeInstantiation == null);
return FunctionCall(tok, "Set#Disjoint", Bpl.Type.Bool, args);
case BuiltinFunction.SeqLength:
- assert args.Length == 1;
- assert typeInstantiation == null;
+ Contract.Assert( args.Length == 1);
+ Contract.Assert( typeInstantiation == null);
return FunctionCall(tok, "Seq#Length", Bpl.Type.Int, args);
case BuiltinFunction.SeqEmpty: {
- assert args.Length == 0;
- assert typeInstantiation != null;
+ Contract.Assert( args.Length == 0);
+ Contract.Assert( typeInstantiation != null);
Bpl.Type resultType = predef.SeqType(tok, typeInstantiation);
return Bpl.Expr.CoerceType(tok, FunctionCall(tok, "Seq#Empty", resultType, args), resultType);
}
case BuiltinFunction.SeqBuild:
- assert args.Length == 4;
- assert typeInstantiation != null;
+ Contract.Assert( args.Length == 4);
+ Contract.Assert( typeInstantiation != null);
return FunctionCall(tok, "Seq#Build", predef.SeqType(tok, typeInstantiation), args);
case BuiltinFunction.SeqAppend:
- assert args.Length == 2;
- assert typeInstantiation != null;
+ Contract.Assert( args.Length == 2);
+ Contract.Assert( typeInstantiation != null);
return FunctionCall(tok, "Seq#Append", predef.SeqType(tok, typeInstantiation), args);
case BuiltinFunction.SeqIndex:
- assert args.Length == 2;
- assert typeInstantiation != null;
+ Contract.Assert( args.Length == 2);
+ Contract.Assert( typeInstantiation != null);
return FunctionCall(tok, "Seq#Index", typeInstantiation, args);
case BuiltinFunction.SeqUpdate:
- assert args.Length == 3;
- assert typeInstantiation != null;
+ Contract.Assert( args.Length == 3);
+ Contract.Assert( typeInstantiation != null);
return FunctionCall(tok, "Seq#Update", predef.SeqType(tok, typeInstantiation), args);
case BuiltinFunction.SeqContains:
- assert args.Length == 2;
- assert typeInstantiation == null;
+ Contract.Assert( args.Length == 2);
+ Contract.Assert( typeInstantiation == null);
return FunctionCall(tok, "Seq#Contains", Bpl.Type.Bool, args);
case BuiltinFunction.SeqDrop:
- assert args.Length == 2;
- assert typeInstantiation != null;
+ Contract.Assert( args.Length == 2);
+ Contract.Assert( typeInstantiation != null);
return FunctionCall(tok, "Seq#Drop", predef.SeqType(tok, typeInstantiation), args);
case BuiltinFunction.SeqTake:
- assert args.Length == 2;
- assert typeInstantiation != null;
+ Contract.Assert( args.Length == 2);
+ Contract.Assert( typeInstantiation != null);
return FunctionCall(tok, "Seq#Take", predef.SeqType(tok, typeInstantiation), args);
case BuiltinFunction.SeqEqual:
- assert args.Length == 2;
- assert typeInstantiation == null;
+ Contract.Assert( args.Length == 2);
+ Contract.Assert( typeInstantiation == null);
return FunctionCall(tok, "Seq#Equal", Bpl.Type.Bool, args);
case BuiltinFunction.SeqSameUntil:
- assert args.Length == 3;
- assert typeInstantiation == null;
+ Contract.Assert( args.Length == 3);
+ Contract.Assert( typeInstantiation == null);
return FunctionCall(tok, "Seq#SameUntil", Bpl.Type.Bool, args);
case BuiltinFunction.ArrayLength:
- assert args.Length == 1;
- assert typeInstantiation == null;
+ Contract.Assert( args.Length == 1);
+ Contract.Assert( typeInstantiation == null);
return FunctionCall(tok, "Array#Length", Bpl.Type.Int, args);
case BuiltinFunction.IndexField:
- assert args.Length == 1;
- assert typeInstantiation == null;
+ Contract.Assert( args.Length == 1);
+ Contract.Assert( typeInstantiation == null);
return FunctionCall(tok, "IndexField", predef.FieldName(tok, predef.BoxType), args);
case BuiltinFunction.IfThenElse:
- assert args.Length == 3;
- assert typeInstantiation != null;
+ Contract.Assert( args.Length == 3);
+ Contract.Assert( typeInstantiation != null);
return FunctionCall(tok, "$ite", typeInstantiation, args);
case BuiltinFunction.Box:
- assert args.Length == 1;
- assert typeInstantiation == null;
+ Contract.Assert( args.Length == 1);
+ Contract.Assert( typeInstantiation == null);
return FunctionCall(tok, "$Box", predef.BoxType, args);
case BuiltinFunction.Unbox:
- assert args.Length == 1;
- assert typeInstantiation != null;
+ Contract.Assert( args.Length == 1);
+ Contract.Assert( typeInstantiation != null);
return Bpl.Expr.CoerceType(tok, FunctionCall(tok, "$Unbox", typeInstantiation, args), typeInstantiation);
case BuiltinFunction.IsGoodHeap:
- assert args.Length == 1;
- assert typeInstantiation == null;
+ Contract.Assert( args.Length == 1);
+ Contract.Assert( typeInstantiation == null);
return FunctionCall(tok, "$IsGoodHeap", Bpl.Type.Bool, args);
case BuiltinFunction.HeapSucc:
- assert args.Length == 2;
- assert typeInstantiation == null;
+ Contract.Assert( args.Length == 2);
+ Contract.Assert( typeInstantiation == null);
return FunctionCall(tok, "$HeapSucc", Bpl.Type.Bool, args);
case BuiltinFunction.DynamicType:
- assert args.Length == 1;
- assert typeInstantiation == null;
+ Contract.Assert( args.Length == 1);
+ Contract.Assert( typeInstantiation == null);
return FunctionCall(tok, "dtype", predef.ClassNameType, args);
case BuiltinFunction.TypeParams:
- assert args.Length == 2;
- assert typeInstantiation == null;
+ Contract.Assert( args.Length == 2);
+ Contract.Assert( typeInstantiation == null);
return FunctionCall(tok, "TypeParams", predef.ClassNameType, args);
case BuiltinFunction.TypeTuple:
- assert args.Length == 2;
- assert typeInstantiation == null;
+ Contract.Assert( args.Length == 2);
+ Contract.Assert( typeInstantiation == null);
return FunctionCall(tok, "TypeTuple", predef.ClassNameType, args);
case BuiltinFunction.DeclType:
- assert args.Length == 1;
- assert typeInstantiation != null;
+ Contract.Assert( args.Length == 1);
+ Contract.Assert( typeInstantiation != null);
return FunctionCall(tok, "DeclType", predef.ClassNameType, args);
case BuiltinFunction.FCat:
- assert args.Length == 1;
- assert typeInstantiation != null;
+ Contract.Assert( args.Length == 1);
+ Contract.Assert( typeInstantiation != null);
return FunctionCall(tok, "FCat", predef.FieldCategoryType, args);
case BuiltinFunction.DatatypeCtorId:
- assert args.Length == 1;
- assert typeInstantiation == null;
+ Contract.Assert( args.Length == 1);
+ Contract.Assert( typeInstantiation == null);
return FunctionCall(tok, "DatatypeCtorId", predef.DtCtorId, args);
case BuiltinFunction.DtRank:
- assert args.Length == 1;
- assert typeInstantiation == null;
+ Contract.Assert( args.Length == 1);
+ Contract.Assert( typeInstantiation == null);
return FunctionCall(tok, "DtRank", Bpl.Type.Int, args);
case BuiltinFunction.CevInit:
- assert args.Length == 1;
- assert typeInstantiation == null;
+ Contract.Assert( args.Length == 1);
+ Contract.Assert( typeInstantiation == null);
return FunctionCall(tok, "#cev_init", Bpl.Type.Bool, args);
case BuiltinFunction.CevVarIntro:
- assert args.Length == 5;
- assert typeInstantiation == null;
+ Contract.Assert( args.Length == 5);
+ Contract.Assert( typeInstantiation == null);
return FunctionCall(tok, "#cev_var_intro", Bpl.Type.Bool, args);
case BuiltinFunction.CevVarUpdate:
- assert args.Length == 4;
- assert typeInstantiation == null;
+ Contract.Assert( args.Length == 4);
+ Contract.Assert( typeInstantiation == null);
return FunctionCall(tok, "#cev_var_update", Bpl.Type.Bool, args);
case BuiltinFunction.CevControlFlowEvent:
- assert args.Length == 2;
- assert typeInstantiation == null;
+ Contract.Assert( args.Length == 2);
+ Contract.Assert( typeInstantiation == null);
return FunctionCall(tok, "#cev_control_flow_event", Bpl.Type.Bool, args);
case BuiltinFunction.CevProgramLocation:
- assert args.Length == 1;
- assert typeInstantiation == null;
+ Contract.Assert( args.Length == 1);
+ Contract.Assert( typeInstantiation == null);
return FunctionCall(tok, "#cev_save_position", predef.CevTokenType, args);
default:
- assert false; // unexpected built-in function
+ Contract.Assert(false); throw new cce.UnreachableException(); // unexpected built-in function
}
}
- Bpl.NAryExpr! FunctionCall(IToken! tok, string! function, Bpl.Type! returnType, params Bpl.Expr[]! args)
+ Bpl.NAryExpr FunctionCall(IToken tok, string function, Bpl.Type returnType, params Bpl.Expr[] args)
{
+ Contract.Requires(tok != null);
+ Contract.Requires(function != null);
+ Contract.Requires(args != null);
+ Contract.Ensures(Contract.Result<Bpl.NAryExpr>() != null);
+
return new Bpl.NAryExpr(tok, new Bpl.FunctionCall(new Bpl.IdentifierExpr(tok, function, returnType)), new Bpl.ExprSeq(args));
}
- Bpl.NAryExpr! FunctionCall(IToken! tok, string! function, Bpl.Type! returnType, List<Bpl.Expr!>! args)
+ Bpl.NAryExpr FunctionCall(IToken tok, string function, Bpl.Type returnType, List<Bpl.Expr> args)
{
+ Contract.Requires(tok != null);
+ Contract.Requires(function != null);
+ Contract.Requires(returnType != null);
+ Contract.Requires(cce.NonNullElements(args));
+
+
+ Contract.Ensures(Contract.Result<Bpl.NAryExpr>() != null);
+
Bpl.ExprSeq aa = new Bpl.ExprSeq();
foreach (Bpl.Expr arg in args) {
aa.Add(arg);
@@ -3922,21 +4373,27 @@ namespace Microsoft.Dafny {
return new Bpl.NAryExpr(tok, new Bpl.FunctionCall(new Bpl.IdentifierExpr(tok, function, returnType)), aa);
}
- public bool SplitExpr(Expression! expr, out List<Expression!>! definitions, out List<Expression!>! pieces) {
- definitions = new List<Expression!>();
- pieces = new List<Expression!>();
+ public bool SplitExpr(Expression expr, out List<Expression/*!*/>/*!*/ definitions, out List<Expression/*!*/>/*!*/ pieces) {
+ Contract.Requires(expr != null);
+ Contract.Ensures(cce.NonNullElements(Contract.ValueAtReturn(out definitions)));
+ Contract.Ensures(cce.NonNullElements(Contract.ValueAtReturn(out pieces)));
+ definitions = new List<Expression>();
+ pieces = new List<Expression>();
return SplitExpr(expr, true, definitions, pieces);
}
///<summary>
/// Returns false if no split occurred (in that case, nothing was added to definitions, and (exactly) expr itself was added to pieces.
///</summary>
- public bool SplitExpr(Expression! expr, bool expandFunctions, List<Expression!>! definitions, List<Expression!>! pieces)
- requires expr.Type is BoolType || (expr is BoxingCastExpr && ((BoxingCastExpr)expr).E.Type is BoolType);
- {
+ public bool SplitExpr(Expression expr, bool expandFunctions, List<Expression/*!*/>/*!*/ definitions, List<Expression/*!*/>/*!*/ pieces)
+ {
+ Contract.Requires(expr != null);
+ Contract.Requires(cce.NonNullElements(definitions));
+ Contract.Requires(cce.NonNullElements(pieces));
+ Contract.Requires( expr.Type is BoolType || (expr is BoxingCastExpr && ((BoxingCastExpr)expr).E.Type is BoolType));
if (expr is BoxingCastExpr) {
BoxingCastExpr bce = (BoxingCastExpr)expr;
- List<Expression!> pp = new List<Expression!>();
+ List<Expression> pp = new List<Expression>();
if (SplitExpr(bce.E, expandFunctions, definitions, pp)) {
foreach (Expression e in pp) {
Expression r = new BoxingCastExpr(e, bce.FromType, bce.ToType);
@@ -3954,7 +4411,7 @@ namespace Microsoft.Dafny {
return true;
} else if (bin.ResolvedOp == BinaryExpr.ResolvedOpcode.Imp) {
- List<Expression!> pp = new List<Expression!>();
+ List<Expression> pp = new List<Expression>();
if (SplitExpr(bin.E1, expandFunctions, definitions, pp)) {
foreach (Expression e in pp) {
BinaryExpr r = new BinaryExpr(e.tok, bin.Op, bin.E0, e);
@@ -3968,7 +4425,7 @@ namespace Microsoft.Dafny {
} else if (expr is ITEExpr) {
ITEExpr ite = (ITEExpr)expr;
- List<Expression!> pp = new List<Expression!>();
+ List<Expression> pp = new List<Expression>();
SplitExpr(ite.Thn, expandFunctions, definitions, pp);
foreach (Expression e in pp) {
BinaryExpr r = new BinaryExpr(e.tok, BinaryExpr.Opcode.Imp, ite.Test, e);
@@ -3978,7 +4435,7 @@ namespace Microsoft.Dafny {
Expression negatedGuard = new UnaryExpr(ite.Test.tok, UnaryExpr.Opcode.Not, ite.Test);
negatedGuard.Type = ite.Test.Type; // resolve on the fly
- pp = new List<Expression!>();
+ pp = new List<Expression>();
SplitExpr(ite.Els, expandFunctions, definitions, pp);
foreach (Expression e in pp) {
BinaryExpr r = new BinaryExpr(e.tok, BinaryExpr.Opcode.Imp, negatedGuard, e);
@@ -3988,7 +4445,8 @@ namespace Microsoft.Dafny {
return true;
} else if (expr is OldExpr) {
- List<Expression!> dd = new List<Expression!>(), pp = new List<Expression!>();
+ List<Expression> dd = new List<Expression>();
+ List<Expression> pp = new List<Expression>();
if (SplitExpr(((OldExpr)expr).E, expandFunctions, dd, pp)) {
foreach (Expression e in dd) {
Expression r = new OldExpr(expr.tok, e);
@@ -4005,29 +4463,29 @@ namespace Microsoft.Dafny {
} else if (expandFunctions && expr is FunctionCallExpr) {
FunctionCallExpr fexp = (FunctionCallExpr)expr;
- assert fexp.Function != null; // filled in during resolution
+ Contract.Assert( fexp.Function != null); // filled in during resolution
if (fexp.Function.Body != null && !(fexp.Function.Body is MatchExpr)) {
// inline this body
- Dictionary<IVariable,Expression!> substMap = new Dictionary<IVariable,Expression!>();
- assert fexp.Args.Count == fexp.Function.Formals.Count;
+ Dictionary<IVariable,Expression> substMap = new Dictionary<IVariable,Expression>();
+ Contract.Assert( fexp.Args.Count == fexp.Function.Formals.Count);
for (int i = 0; i < fexp.Function.Formals.Count; i++) {
Formal p = fexp.Function.Formals[i];
Expression arg = fexp.Args[i];
- arg = new BoxingCastExpr(arg, (!)arg.Type, p.Type);
+ arg = new BoxingCastExpr(arg, cce.NonNull(arg.Type), p.Type);
arg.Type = p.Type; // resolve here
substMap.Add(p, arg);
}
Expression body = Substitute(fexp.Function.Body, fexp.Receiver, substMap);
// add definition: fn(args) ==> body
- Expression bodyx = new UnboxingCastExpr(body, fexp.Function.ResultType, (!)expr.Type);
+ Expression bodyx = new UnboxingCastExpr(body, fexp.Function.ResultType, cce.NonNull(expr.Type));
bodyx.Type = expr.Type; // resolve here
BinaryExpr def = new BinaryExpr(expr.tok, BinaryExpr.Opcode.Imp, fexp, bodyx);
def.ResolvedOp = BinaryExpr.ResolvedOpcode.Imp; def.Type = Type.Bool; // resolve on the fly
definitions.Add(def);
// recurse on body
- List<Expression!> pp = new List<Expression!>();
+ List<Expression> pp = new List<Expression>();
SplitExpr(body, false, definitions, pp);
foreach (Expression e in pp) {
Expression r = new UnboxingCastExpr(e, fexp.Function.ResultType, expr.Type);
@@ -4038,11 +4496,15 @@ namespace Microsoft.Dafny {
}
}
- pieces.Add(expr);
+ pieces.Add(expr);
return false;
}
- static Expression! Substitute(Expression! expr, Expression receiverReplacement, Dictionary<IVariable,Expression!>! substMap) {
+ static Expression Substitute(Expression expr, Expression receiverReplacement, Dictionary<IVariable,Expression/*!*/>/*!*/ substMap) {
+ Contract.Requires(expr != null);
+ Contract.Requires(cce.NonNullElements(substMap));
+ Contract.Ensures(Contract.Result<Expression>() != null);
+
Expression newExpr = null; // set to non-null value only if substitution has any effect; if non-null, newExpr will be resolved at end
if (expr is LiteralExpr || expr is WildcardExpr) {
@@ -4053,12 +4515,11 @@ namespace Microsoft.Dafny {
IdentifierExpr e = (IdentifierExpr)expr;
Expression substExpr;
if (substMap.TryGetValue(e.Var, out substExpr)) {
- return (!)substExpr;
+ return cce.NonNull(substExpr);
}
} else if (expr is DisplayExpression) {
DisplayExpression e = (DisplayExpression)expr;
- List<Expression!> newElements = SubstituteExprList(e.Elements, receiverReplacement, substMap);
- DisplayExpression newDisplayExpr;
+ List<Expression> newElements = SubstituteExprList(e.Elements, receiverReplacement, substMap);
if (newElements != e.Elements) {
if (expr is SetDisplayExpr) {
newExpr = new SetDisplayExpr(expr.tok, newElements);
@@ -4097,7 +4558,7 @@ namespace Microsoft.Dafny {
} else if (expr is FunctionCallExpr) {
FunctionCallExpr e = (FunctionCallExpr)expr;
Expression receiver = Substitute(e.Receiver, receiverReplacement, substMap);
- List<Expression!> newArgs = SubstituteExprList(e.Args, receiverReplacement, substMap);
+ List<Expression> newArgs = SubstituteExprList(e.Args, receiverReplacement, substMap);
if (receiver != e.Receiver || newArgs != e.Args) {
FunctionCallExpr newFce = new FunctionCallExpr(expr.tok, e.Name, receiver, newArgs);
newFce.Function = e.Function; // resolve on the fly (and set newFce.Type below, at end)
@@ -4106,7 +4567,7 @@ namespace Microsoft.Dafny {
} else if (expr is DatatypeValue) {
DatatypeValue dtv = (DatatypeValue)expr;
- List<Expression!> newArgs = SubstituteExprList(dtv.Arguments, receiverReplacement, substMap);
+ List<Expression> newArgs = SubstituteExprList(dtv.Arguments, receiverReplacement, substMap);
if (newArgs != dtv.Arguments) {
DatatypeValue newDtv = new DatatypeValue(dtv.tok, dtv.DatatypeName, dtv.MemberName, newArgs);
newDtv.Ctor = dtv.Ctor; // resolve on the fly (and set newDtv.Type below, at end)
@@ -4172,15 +4633,18 @@ namespace Microsoft.Dafny {
}
}
- static List<Expression!>! SubstituteExprList(List<Expression!>! elist,
- Expression receiverReplacement, Dictionary<IVariable,Expression!>! substMap) {
- List<Expression!> newElist = null; // initialized lazily
+ static List<Expression/*!*/>/*!*/ SubstituteExprList(List<Expression/*!*/>/*!*/ elist,
+ Expression receiverReplacement, Dictionary<IVariable,Expression/*!*/>/*!*/ substMap) {
+ Contract.Requires(cce.NonNullElements(elist));
+ Contract.Requires(cce.NonNullElements(substMap));
+ Contract.Ensures(cce.NonNullElements(Contract.Result<List<Expression>>()));
+ List<Expression> newElist = null; // initialized lazily
for (int i = 0; i < elist.Count; i++)
- invariant newElist == null || newElist.Count == i;
- {
+ {cce.LoopInvariant( newElist == null || newElist.Count == i);
+
Expression substE = Substitute(elist[i], receiverReplacement, substMap);
if (substE != elist[i] && newElist == null) {
- newElist = new List<Expression!>();
+ newElist = new List<Expression>();
for (int j = 0; j < i; j++) {
newElist.Add(elist[j]);
}
@@ -4196,9 +4660,10 @@ namespace Microsoft.Dafny {
}
}
- static Triggers SubstTriggers(Triggers trigs, Expression receiverReplacement, Dictionary<IVariable,Expression!>! substMap) {
+ static Triggers SubstTriggers(Triggers trigs, Expression receiverReplacement, Dictionary<IVariable,Expression/*!*/>/*!*/ substMap) {
+ Contract.Requires(cce.NonNullElements(substMap));
if (trigs != null) {
- List<Expression!> terms = SubstituteExprList(trigs.Terms, receiverReplacement, substMap);
+ List<Expression> terms = SubstituteExprList(trigs.Terms, receiverReplacement, substMap);
Triggers prev = SubstTriggers(trigs.Prev, receiverReplacement, substMap);
if (terms != trigs.Terms || prev != trigs.Prev) {
return new Triggers(terms, prev);
@@ -4206,10 +4671,11 @@ namespace Microsoft.Dafny {
}
return trigs;
}
-
- static Attributes SubstAttributes(Attributes attrs, Expression receiverReplacement, Dictionary<IVariable,Expression!>! substMap) {
+
+ static Attributes SubstAttributes(Attributes attrs, Expression receiverReplacement, Dictionary<IVariable, Expression/*!*/>/*!*/ substMap) {
+ Contract.Requires(cce.NonNullElements(substMap));
if (attrs != null) {
- List<Attributes.Argument!> newArgs = new List<Attributes.Argument!>(); // allocate it eagerly, what the heck, it doesn't seem worth the extra complexity in the code to do it lazily for the infrequently occurring attributes
+ List<Attributes.Argument> newArgs = new List<Attributes.Argument>(); // allocate it eagerly, what the heck, it doesn't seem worth the extra complexity in the code to do it lazily for the infrequently occurring attributes
bool anyArgSubst = false;
foreach (Attributes.Argument arg in attrs.Args) {
Attributes.Argument newArg = arg;
@@ -4235,4 +4701,4 @@ namespace Microsoft.Dafny {
}
}
-}
+} \ No newline at end of file